Completed
Push — master ( f57266...a0db3b )
by Kamil
08:26 queued 50s
created

CookieSetter::shouldMinkSessionBePrepared()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 9
nc 4
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Sylius\Behat\Service\Setter;
15
16
use Behat\Mink\Driver\Selenium2Driver;
17
use Behat\Mink\Session;
18
use FriendsOfBehat\SymfonyExtension\Driver\SymfonyDriver;
19
use Symfony\Component\BrowserKit\Cookie;
20
21
final class CookieSetter implements CookieSetterInterface
22
{
23
    /**
24
     * @var Session
25
     */
26
    private $minkSession;
27
28
    /**
29
     * @var array
30
     */
31
    private $minkParameters;
32
33
    /**
34
     * @param Session $minkSession
35
     * @param array $minkParameters
36
     */
37
    public function __construct(Session $minkSession, array $minkParameters)
38
    {
39
        $this->minkSession = $minkSession;
40
        $this->minkParameters = $minkParameters;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function setCookie($name, $value)
47
    {
48
        $this->prepareMinkSessionIfNeeded($this->minkSession);
49
50
        $driver = $this->minkSession->getDriver();
51
52
        if ($driver instanceof SymfonyDriver) {
53
            $driver->getClient()->getCookieJar()->set(
54
                new Cookie($name, $value, null, null, parse_url($this->minkParameters['base_url'], PHP_URL_HOST))
55
            );
56
57
            return;
58
        }
59
60
        $this->minkSession->setCookie($name, $value);
61
    }
62
63
    private function prepareMinkSessionIfNeeded(Session $session): void
64
    {
65
        if ($this->shouldMinkSessionBePrepared($session)) {
66
            $session->visit(rtrim($this->minkParameters['base_url'], '/') . '/');
67
        }
68
    }
69
70
    private function shouldMinkSessionBePrepared(Session $session): bool
71
    {
72
        $driver = $session->getDriver();
73
74
        if ($driver instanceof SymfonyDriver) {
75
            return false;
76
        }
77
78
        if ($driver instanceof Selenium2Driver && $driver->getWebDriverSession() === null) {
79
            return true;
80
        }
81
82
        if (false !== strpos($session->getCurrentUrl(), $this->minkParameters['base_url'])) {
83
            return false;
84
        }
85
86
        return true;
87
    }
88
}
89