Completed
Push — master ( caa721...fceab7 )
by Fabian
14s queued 10s
created

Target::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace IntegerNet\CallbackProxy;
5
6
use Psr\Http\Message\RequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Slim\Http\Uri;
9
10
class Target
11
{
12
    /**
13
     * @var \Psr\Http\Message\UriInterface
14
     */
15
    private $uri;
16
17
    /**
18
     * @var string[]
19
     */
20
    private $additionalHeaders;
21
22 48
    public function __construct(\Psr\Http\Message\UriInterface $uri, array $additionalHeaders = [])
23
    {
24 48
        $this->uri = $uri;
25 48
        $this->additionalHeaders = $additionalHeaders;
26 48
    }
27
28 12
    public static function fromConfig($config): self
29
    {
30 12
        if (is_string($config)) {
31 6
            return new self(Uri::createFromString($config));
32
        }
33 9
        if (!isset($config['uri'])) {
34 3
            throw new \InvalidArgumentException(
35 3
                '$config argument must be a string or an array containing an "uri" element'
36
            );
37
        }
38 6
        $additionalHeaders = [];
39 6
        if (isset($config['basic-auth'])) {
40 6
            $additionalHeaders['Authorization'] = 'Basic ' . \base64_encode($config['basic-auth']);
41
        }
42 6
        return new self(Uri::createFromString($config['uri']), $additionalHeaders);
43
    }
44
45 42
    public function applyToRequest(RequestInterface $request, string $action): RequestInterface
46
    {
47 42
        $request = $request->withUri($this->uri->withPath($this->uri->getPath() . $action));
48 42
        foreach ($this->additionalHeaders as $name => $value) {
49 3
            $request = $request->withHeader($name, $value);
50
        }
51 42
        return $request;
52
    }
53
54 42
    public function applyToResponse(ResponseInterface $response, string $action): ResponseInterface
55
    {
56 42
        return $response->withHeader(
57 42
            'X-Response-From',
58 42
            $this->uri->withPath($this->uri->getPath() . $action)->__toString()
59
        );
60
    }
61
}
62