Completed
Pull Request — master (#14)
by Márk
03:05
created

CookiePlugin::createCookie()   C

Complexity

Conditions 11
Paths 10

Size

Total Lines 60
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 11.0016

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 60
ccs 41
cts 42
cp 0.9762
rs 6.2926
cc 11
eloc 39
nc 10
nop 2
crap 11.0016

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 10
    public function __construct(CookieJar $cookieJar)
30
    {
31 10
        $this->cookieJar = $cookieJar;
32 10
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37 8
    public function handleRequest(RequestInterface $request, callable $next, callable $first)
38
    {
39 8
        foreach ($this->cookieJar->getCookies() as $cookie) {
40 6
            if ($cookie->isExpired()) {
41 1
                continue;
42
            }
43
44 5
            if (!$cookie->matchDomain($request->getUri()->getHost())) {
45 1
                continue;
46
            }
47
48 4
            if (!$cookie->matchPath($request->getUri()->getPath())) {
49 1
                continue;
50
            }
51
52 3
            if ($cookie->isSecure() && ($request->getUri()->getScheme() !== 'https')) {
53 1
                continue;
54
            }
55
56 2
            $request = $request->withAddedHeader('Cookie', sprintf('%s=%s', $cookie->getName(), $cookie->getValue()));
57 8
        }
58
59 8
        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($cookie->getDomain(), $request->getUri()->getHost())) {
73
                        continue;
74
                    }
75
76 1
                    $this->cookieJar->addCookie($cookie);
77 1
                }
78 1
            }
79
80 1
            return $response;
81 8
        });
82
    }
83
84
    /**
85
     * Creates a cookie from a string.
86
     *
87
     * @param RequestInterface $request
88
     * @param $setCookie
89
     *
90
     * @return Cookie|null
91
     *
92
     * @throws TransferException
93
     */
94 2
    private function createCookie(RequestInterface $request, $setCookie)
95
    {
96 2
        $parts = array_map('trim', explode(';', $setCookie));
97
98 2
        if (empty($parts) || !strpos($parts[0], '=')) {
99
            return;
100
        }
101
102 2
        list($name, $cookieValue) = $this->createValueKey(array_shift($parts));
103
104 2
        $maxAge = null;
105 2
        $expires = null;
106 2
        $domain = $request->getUri()->getHost();
107 2
        $path = $request->getUri()->getPath();
108 2
        $secure = false;
109 2
        $httpOnly = false;
110
111
        // Add the cookie pieces into the parsed data array
112 2
        foreach ($parts as $part) {
113 2
            list($key, $value) = $this->createValueKey($part);
114
115 2
            switch (strtolower($key)) {
116 2
                case 'expires':
117 2
                    $expires = \DateTime::createFromFormat(\DateTime::COOKIE, $value);
118
119 2
                    if (true !== ($expires instanceof \DateTime)) {
120 1
                        throw new TransferException(
121 1
                            sprintf(
122 1
                                'Cookie header `%s` expires value `%s` could not be converted to date',
123 1
                                $name,
124
                                $value
125 1
                            )
126 1
                        );
127
                    }
128 1
                    break;
129
130 1
                case 'max-age':
131 1
                    $maxAge = (int) $value;
132 1
                    break;
133
134 1
                case 'domain':
135 1
                    $domain = $value;
136 1
                    break;
137
138 1
                case 'path':
139 1
                    $path = $value;
140 1
                    break;
141
142 1
                case 'secure':
143 1
                    $secure = true;
144 1
                    break;
145
146 1
                case 'httponly':
147 1
                    $httpOnly = true;
148 1
                    break;
149 1
            }
150 1
        }
151
152 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 102 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 135 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 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...
Security Bug introduced by
It seems like $expires defined by \DateTime::createFromFor...teTime::COOKIE, $value) on line 117 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...
153
    }
154
155
    /**
156
     * Separates key/value pair from cookie.
157
     *
158
     * @param $part
159
     *
160
     * @return array
161
     */
162 2
    private function createValueKey($part)
163
    {
164 2
        $parts = explode('=', $part, 2);
165 2
        $key = trim($parts[0]);
166 2
        $value = isset($parts[1]) ? trim($parts[1]) : true;
167
168 2
        return [$key, $value];
169
    }
170
}
171