Completed
Pull Request — master (#68)
by
unknown
04:21
created

CookiePlugin   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 154
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 96.1%

Importance

Changes 6
Bugs 4 Features 1
Metric Value
wmc 25
c 6
b 4
f 1
lcom 1
cbo 6
dl 0
loc 154
ccs 74
cts 77
cp 0.961
rs 10

4 Methods

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