Completed
Pull Request — master (#70)
by Márk
03:26
created

CookiePlugin::createValueKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Http\Client\Plugin;
4
5
use Http\Client\Exception\TransferException;
6
use Http\Message\Cookie;
7
use Http\Message\CookieJar;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
/**
12
 * Handle request cookies.
13
 *
14
 * @author Joel Wurtz <[email protected]>
15
 *
16
 * @deprecated since since version 1.1, and will be removed in 2.0. Use {@link \Http\Client\Common\Plugin\CookiePlugin} instead.
17
 */
18
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...
19
{
20
    /**
21
     * Cookie storage.
22
     *
23
     * @var CookieJar
24
     */
25
    private $cookieJar;
26
27
    /**
28
     * @param CookieJar $cookieJar
29
     */
30 10
    public function __construct(CookieJar $cookieJar)
31
    {
32 10
        $this->cookieJar = $cookieJar;
33 10
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 8
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
39
    {
40 8
        foreach ($this->cookieJar->getCookies() as $cookie) {
41 6
            if ($cookie->isExpired()) {
42 1
                continue;
43
            }
44
45 5
            if (!$cookie->matchDomain($request->getUri()->getHost())) {
46 1
                continue;
47
            }
48
49 4
            if (!$cookie->matchPath($request->getUri()->getPath())) {
50 1
                continue;
51
            }
52
53 3
            if ($cookie->isSecure() && ($request->getUri()->getScheme() !== 'https')) {
54 1
                continue;
55
            }
56
57 2
            $request = $request->withAddedHeader('Cookie', sprintf('%s=%s', $cookie->getName(), $cookie->getValue()));
58 8
        }
59
60 8
        return $next($request)->then(function (ResponseInterface $response) use ($request) {
61 2
            if ($response->hasHeader('Set-Cookie')) {
62 2
                $setCookies = $response->getHeader('Set-Cookie');
63
64 2
                foreach ($setCookies as $setCookie) {
65 2
                    $cookie = $this->createCookie($request, $setCookie);
66
67
                    // Cookie invalid do not use it
68 1
                    if (null === $cookie) {
69
                        continue;
70
                    }
71
72
                    // Restrict setting cookie from another domain
73 1
                    if (false === strpos($cookie->getDomain(), $request->getUri()->getHost())) {
74
                        continue;
75
                    }
76
77 1
                    $this->cookieJar->addCookie($cookie);
78 1
                }
79 1
            }
80
81 1
            return $response;
82 8
        });
83
    }
84
85
    /**
86
     * Creates a cookie from a string.
87
     *
88
     * @param RequestInterface $request
89
     * @param $setCookie
90
     *
91
     * @return Cookie|null
92
     *
93
     * @throws \Http\Client\Exception\TransferException
94
     */
95 2
    private function createCookie(RequestInterface $request, $setCookie)
96
    {
97 2
        $parts = array_map('trim', explode(';', $setCookie));
98
99 2
        if (empty($parts) || !strpos($parts[0], '=')) {
100
            return;
101
        }
102
103 2
        list($name, $cookieValue) = $this->createValueKey(array_shift($parts));
104
105 2
        $maxAge = null;
106 2
        $expires = null;
107 2
        $domain = $request->getUri()->getHost();
108 2
        $path = $request->getUri()->getPath();
109 2
        $secure = false;
110 2
        $httpOnly = false;
111
112
        // Add the cookie pieces into the parsed data array
113 2
        foreach ($parts as $part) {
114 2
            list($key, $value) = $this->createValueKey($part);
115
116 2
            switch (strtolower($key)) {
117 2
                case 'expires':
118 2
                    $expires = \DateTime::createFromFormat(\DateTime::COOKIE, $value);
119
120 2
                    if (true !== ($expires instanceof \DateTime)) {
121 1
                        throw new TransferException(
122 1
                            sprintf(
123 1
                                'Cookie header `%s` expires value `%s` could not be converted to date',
124 1
                                $name,
125
                                $value
126 1
                            )
127 1
                        );
128
                    }
129
130 1
                    break;
131
132 1
                case 'max-age':
133 1
                    $maxAge = (int) $value;
134 1
                    break;
135
136 1
                case 'domain':
137 1
                    $domain = $value;
138 1
                    break;
139
140 1
                case 'path':
141 1
                    $path = $value;
142 1
                    break;
143
144 1
                case 'secure':
145 1
                    $secure = true;
146 1
                    break;
147
148 1
                case 'httponly':
149 1
                    $httpOnly = true;
150 1
                    break;
151 1
            }
152 1
        }
153
154 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 103 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 137 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 141 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 118 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...
155
    }
156
157
    /**
158
     * Separates key/value pair from cookie.
159
     *
160
     * @param $part
161
     *
162
     * @return array
163
     */
164 2
    private function createValueKey($part)
165
    {
166 2
        $parts = explode('=', $part, 2);
167 2
        $key = trim($parts[0]);
168 2
        $value = isset($parts[1]) ? trim($parts[1]) : true;
169
170 2
        return [$key, $value];
171
    }
172
}
173