Completed
Push — master ( f7d058...3104fd )
by Patrick
13:36
created

AddPathPlugin   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 12
c 1
b 1
f 0
dl 0
loc 38
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A handleRequest() 0 9 2
A __construct() 0 9 3
1
<?php declare(strict_types=1);
2
3
namespace Starweb\HttpClient\Plugin;
4
5
use Http\Client\Common\Plugin;
6
use Http\Promise\Promise;
7
use Psr\Http\Message\RequestInterface;
8
use Psr\Http\Message\UriInterface;
9
10
/**
11
 * Customized AddPathPlugin from php-http/client-common:2.x branch.
12
 *
13
 * @see https://github.com/php-http/client-common/blob/2.0.0/src/Plugin/AddPathPlugin.php
14
 * @see https://github.com/php-http/client-common/issues/171
15
 * @see https://github.com/php-http/client-common/issues/141
16
 */
17
final class AddPathPlugin implements Plugin
18
{
19
    /**
20
     * The URI.
21
     *
22
     * @var \Psr\Http\Message\UriInterface
23
     */
24
    private $uri;
25
26
    /**
27
     * AddPathPlugin constructor.
28
     *
29
     * @param \Psr\Http\Message\UriInterface $uri
30
     *   The URI.
31
     */
32
    public function __construct(UriInterface $uri)
33
    {
34
        if ('' === $uri->getPath()) {
35
            throw new \InvalidArgumentException('URI path cannot be empty');
36
        }
37
        if ('/' === substr($uri->getPath(), -1)) {
38
            $uri = $uri->withPath(rtrim($uri->getPath(), '/'));
39
        }
40
        $this->uri = $uri;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
47
    {
48
        $prepend = $this->uri->getPath();
49
        $path = $request->getUri()->getPath();
50
        if (0 !== strpos($path, $prepend)) {
51
            $request = $request->withUri($request->getUri()->withPath($prepend . $path));
52
        }
53
54
        return $next($request);
55
    }
56
}
57