Completed
Push — master ( 155019...7aca82 )
by Yo
02:17
created

Client::doRequest()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.9713
c 0
b 0
f 0
cc 2
eloc 15
nc 2
nop 1
1
<?php
2
namespace Yoanm\Behat3SymfonyExtension\Client;
3
4
use Psr\Log\LoggerInterface;
5
use Symfony\Bundle\FrameworkBundle\Client as BaseClient;
6
use Symfony\Component\BrowserKit\CookieJar;
7
use Symfony\Component\BrowserKit\History;
8
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
9
use Symfony\Component\HttpKernel\KernelInterface;
10
use Yoanm\Behat3SymfonyExtension\Event\AfterRequestEvent;
11
use Yoanm\Behat3SymfonyExtension\Event\BeforeRequestEvent;
12
use Yoanm\Behat3SymfonyExtension\Event\Events;
13
14
class Client extends BaseClient
15
{
16
    /** @var bool */
17
    private $requestPerformed = false;
18
    /** @var LoggerInterface */
19
    private $logger;
20
    /** @var EventDispatcherInterface */
21
    private $dispatcher;
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function __construct(
27
        KernelInterface $kernel,
28
        LoggerInterface $logger,
29
        EventDispatcherInterface $dispatcher,
30
        array $server,
31
        History $history,
32
        CookieJar $cookieJar
33
    ) {
34
        $this->logger = $logger;
35
        $this->dispatcher = $dispatcher;
36
        parent::__construct($kernel, $server, $history, $cookieJar);
37
        $this->disableReboot();
38
    }
39
40
    /**
41
     * @return boolean
42
     */
43
    public function hasPerformedRequest()
44
    {
45
        return $this->requestPerformed;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    protected function doRequest($request)
52
    {
53
        if ($this->requestPerformed) {
54
            $this->logger->debug('A request has already been performed => reboot kernel');
55
            // Reboot sfKernel to avoid parent::doRequest to shutdown it and from Kernel::handle to boot it
56
            // This behavior will allow mocking symfony app container service for instance
57
            $this->getKernel()->shutdown();
58
            $this->getKernel()->boot();
59
        } else {
60
            $this->requestPerformed = true;
61
        }
62
63
        $this->dispatcher->dispatch(
64
            Events::BEFORE_REQUEST,
65
            new BeforeRequestEvent($request)
66
        );
67
        $response = parent::doRequest($request);
68
        $this->dispatcher->dispatch(
69
            Events::AFTER_REQUEST,
70
            new AfterRequestEvent($response)
71
        );
72
73
        return $response;
74
    }
75
}
76