Completed
Push — master ( 9395b4...e05577 )
by David
16s queued 11s
created

CookiePlugin::handleRequest()   C

Complexity

Conditions 11
Paths 6

Size

Total Lines 46
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 11.055

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 46
ccs 24
cts 26
cp 0.9231
rs 5.2653
cc 11
eloc 22
nc 6
nop 3
crap 11.055

How to fix   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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 20 and the first side effect is on line 5.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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() && ($request->getUri()->getScheme() !== 'https')) {
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 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 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 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 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...
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