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