4 * This file is part of the Behat.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace Behat\Behat\Output\Node\EventListener\Statistics;
13 use Behat\Behat\Output\Statistics\HookStat;
14 use Behat\Behat\Output\Statistics\Statistics;
15 use Behat\Testwork\Call\CallResult;
16 use Behat\Testwork\EventDispatcher\Event\AfterSetup;
17 use Behat\Testwork\EventDispatcher\Event\AfterTested;
18 use Behat\Testwork\Exception\ExceptionPresenter;
19 use Behat\Testwork\Hook\Tester\Setup\HookedSetup;
20 use Behat\Testwork\Hook\Tester\Setup\HookedTeardown;
21 use Behat\Testwork\Output\Formatter;
22 use Behat\Testwork\Output\Node\EventListener\EventListener;
23 use Symfony\Component\EventDispatcher\Event;
26 * Listens and records hook stats.
28 * @author Konstantin Kudryashov <ever.zet@gmail.com>
30 final class HookStatsListener implements EventListener
37 * @var ExceptionPresenter
39 private $exceptionPresenter;
42 * Initializes listener.
44 * @param Statistics $statistics
45 * @param ExceptionPresenter $exceptionPresenter
47 public function __construct(Statistics $statistics, ExceptionPresenter $exceptionPresenter)
49 $this->statistics = $statistics;
50 $this->exceptionPresenter = $exceptionPresenter;
56 public function listenEvent(Formatter $formatter, Event $event, $eventName)
58 $this->captureHookStatsOnEvent($event);
62 * Captures hook stats on hooked event.
66 private function captureHookStatsOnEvent(Event $event)
68 if ($event instanceof AfterSetup && $event->getSetup() instanceof HookedSetup) {
69 $this->captureBeforeHookStats($event->getSetup());
72 if ($event instanceof AfterTested && $event->getTeardown() instanceof HookedTeardown) {
73 $this->captureAfterHookStats($event->getTeardown());
78 * Captures before hook stats.
80 * @param HookedSetup $setup
82 private function captureBeforeHookStats(HookedSetup $setup)
84 $hookCallResults = $setup->getHookCallResults();
86 foreach ($hookCallResults as $hookCallResult) {
87 $this->captureHookStat($hookCallResult);
92 * Captures before hook stats.
94 * @param HookedTeardown $teardown
96 private function captureAfterHookStats(HookedTeardown $teardown)
98 $hookCallResults = $teardown->getHookCallResults();
100 foreach ($hookCallResults as $hookCallResult) {
101 $this->captureHookStat($hookCallResult);
106 * Captures hook call result.
108 * @param CallResult $hookCallResult
110 private function captureHookStat(CallResult $hookCallResult)
112 $callee = $hookCallResult->getCall()->getCallee();
113 $hook = (string) $callee;
114 $path = $callee->getPath();
115 $stdOut = $hookCallResult->getStdOut();
116 $error = $hookCallResult->getException()
117 ? $this->exceptionPresenter->presentException($hookCallResult->getException())
120 $stat = new HookStat($hook, $path, $error, $stdOut);
121 $this->statistics->registerHookStat($stat);