CookiePlugin   A
last analyzed

Complexity

Total Complexity 25

Size/Duplication

Total Lines 160
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 96.05%

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 6
dl 0
loc 160
ccs 73
cts 76
cp 0.9605
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B handleRequest() 0 46 11
C createCookie() 0 66 11
A createValueKey() 0 8 2
1
<?php
2
3
namespace Http\Client\Plugin;
4
5 1
@trigger_error('The '.__NAMESPACE__.'\CookiePlugin class is deprecated since version 1.1 and will be removed in 2.0. Use Http\Client\Common\Plugin\CookiePlugin instead.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
6
7
use Http\Client\Exception\TransferException;
8
use Http\Message\Cookie;
9
use Http\Message\CookieJar;
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\ResponseInterface;
12
13
/**
14
 * Handle request cookies.
15
 *
16
 * @author Joel Wurtz <[email protected]>
17
 *
18
 * @deprecated since since version 1.1, and will be removed in 2.0. Use {@link \Http\Client\Common\Plugin\CookiePlugin} instead.
19
 */
20
class CookiePlugin implements Plugin
0 ignored issues
show
Deprecated Code introduced by
The interface Http\Client\Plugin\Plugin has been deprecated with message: since since version 1.1, and will be removed in 2.0. Use {@link \Http\Client\Common\Plugin} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
21
{
22
    /**
23
     * Cookie storage.
24
     *
25
     * @var CookieJar
26
     */
27
    private $cookieJar;
28
29
    /**
30
     * @param CookieJar $cookieJar
31
     */
32 10
    public function __construct(CookieJar $cookieJar)
33
    {
34 10
        $this->cookieJar = $cookieJar;
35 10
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 8
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
41
    {
42 8
        foreach ($this->cookieJar->getCookies() as $cookie) {
43 6
            if ($cookie->isExpired()) {
44 1
                continue;
45
            }
46
47 5
            if (!$cookie->matchDomain($request->getUri()->getHost())) {
48 1
                continue;
49
            }
50
51 4
            if (!$cookie->matchPath($request->getUri()->getPath())) {
52 1
                continue;
53
            }
54
55 3
            if ($cookie->isSecure() && ('https' !== $request->getUri()->getScheme())) {
56 1
                continue;
57
            }
58
59 2
            $request = $request->withAddedHeader('Cookie', sprintf('%s=%s', $cookie->getName(), $cookie->getValue()));
60 8
        }
61
62 8
        return $next($request)->then(function (ResponseInterface $response) use ($request) {
63 2
            if ($response->hasHeader('Set-Cookie')) {
64 2
                $setCookies = $response->getHeader('Set-Cookie');
65
66 2
                foreach ($setCookies as $setCookie) {
67 2
                    $cookie = $this->createCookie($request, $setCookie);
68
69
                    // Cookie invalid do not use it
70 1
                    if (null === $cookie) {
71
                        continue;
72
                    }
73
74
                    // Restrict setting cookie from another domain
75 1
                    if (false === strpos($cookie->getDomain(), $request->getUri()->getHost())) {
76
                        continue;
77
                    }
78
79 1
                    $this->cookieJar->addCookie($cookie);
80 1
                }
81 1
            }
82
83 1
            return $response;
84 8
        });
85
    }
86
87
    /**
88
     * Creates a cookie from a string.
89
     *
90
     * @param RequestInterface $request
91
     * @param $setCookie
92
     *
93
     * @return Cookie|null
94
     *
95
     * @throws \Http\Client\Exception\TransferException
96
     */
97 2
    private function createCookie(RequestInterface $request, $setCookie)
98
    {
99 2
        $parts = array_map('trim', explode(';', $setCookie));
100
101 2
        if (empty($parts) || !strpos($parts[0], '=')) {
102
            return;
103
        }
104
105 2
        list($name, $cookieValue) = $this->createValueKey(array_shift($parts));
106
107 2
        $maxAge = null;
108 2
        $expires = null;
109 2
        $domain = $request->getUri()->getHost();
110 2
        $path = $request->getUri()->getPath();
111 2
        $secure = false;
112 2
        $httpOnly = false;
113
114
        // Add the cookie pieces into the parsed data array
115 2
        foreach ($parts as $part) {
116 2
            list($key, $value) = $this->createValueKey($part);
117
118 2
            switch (strtolower($key)) {
119 2
                case 'expires':
120 2
                    $expires = \DateTime::createFromFormat(\DateTime::COOKIE, $value);
121
122 2
                    if (true !== ($expires instanceof \DateTime)) {
123 1
                        throw new TransferException(
124 1
                            sprintf(
125 1
                                'Cookie header `%s` expires value `%s` could not be converted to date',
126 1
                                $name,
127
                                $value
128 1
                            )
129 1
                        );
130
                    }
131
132 1
                    break;
133
134 1
                case 'max-age':
135 1
                    $maxAge = (int) $value;
136
137 1
                    break;
138
139 1
                case 'domain':
140 1
                    $domain = $value;
141
142 1
                    break;
143
144 1
                case 'path':
145 1
                    $path = $value;
146
147 1
                    break;
148
149 1
                case 'secure':
150 1
                    $secure = true;
151
152 1
                    break;
153
154 1
                case 'httponly':
155 1
                    $httpOnly = true;
156
157 1
                    break;
158 1
            }
159 1
        }
160
161 1
        return new Cookie($name, $cookieValue, $maxAge, $domain, $path, $secure, $httpOnly, $expires);
0 ignored issues
show
Bug introduced by
It seems like $cookieValue defined by $this->createValueKey(array_shift($parts)) on line 105 can also be of type boolean; however, Http\Message\Cookie::__construct() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $domain defined by $value on line 140 can also be of type boolean; however, Http\Message\Cookie::__construct() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Bug introduced by
It seems like $path defined by $value on line 145 can also be of type boolean; however, Http\Message\Cookie::__construct() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Security Bug introduced by
It seems like $expires defined by \DateTime::createFromFor...teTime::COOKIE, $value) on line 120 can also be of type false; however, Http\Message\Cookie::__construct() does only seem to accept null|object<DateTime>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
162
    }
163
164
    /**
165
     * Separates key/value pair from cookie.
166
     *
167
     * @param $part
168
     *
169
     * @return array
170
     */
171 2
    private function createValueKey($part)
172
    {
173 2
        $parts = explode('=', $part, 2);
174 2
        $key = trim($parts[0]);
175 2
        $value = isset($parts[1]) ? trim($parts[1]) : true;
176
177 2
        return [$key, $value];
178
    }
179
}
180