Completed
Push — master ( f57266...a0db3b )
by Kamil
77:12 queued 77:00
created

CookieSetter   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 0
dl 0
loc 68
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setCookie() 0 16 2
A prepareMinkSessionIfNeeded() 0 6 2
B shouldMinkSessionBePrepared() 0 18 5
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