Completed
Pull Request — master (#2)
by Fabian
16:22
created

Target::applyToResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
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
    public function __construct(\Psr\Http\Message\UriInterface $uri, array $additionalHeaders = [])
23
    {
24
        $this->uri = $uri;
25
        $this->additionalHeaders = $additionalHeaders;
26
    }
27
28
    public static function fromConfig($config): self
29
    {
30
        if (is_string($config)) {
31
            return new self(Uri::createFromString($config));
32
        }
33
        if (!isset($config['uri'])) {
34
            throw new \InvalidArgumentException(
35
                '$config argument must be a string or an array containing an "uri" element'
36
            );
37
        }
38
        $additionalHeaders = [];
39
        if (isset($config['basic-auth'])) {
40
            $additionalHeaders['Authorization'] = 'Basic ' . \base64_encode($config['basic-auth']);
41
        }
42
        return new self(Uri::createFromString($config['uri']), $additionalHeaders);
43
    }
44
45
    public function applyToRequest(RequestInterface $request, string $action): RequestInterface
46
    {
47
        $request = $request->withUri($this->uri->withPath($this->uri->getPath() . $action));
48
        foreach ($this->additionalHeaders as $name => $value) {
49
            $request = $request->withHeader($name, $value);
50
        }
51
        return $request;
52
    }
53
54
    public function applyToResponse(ResponseInterface $response, string $action): ResponseInterface
55
    {
56
        return $response->withHeader(
57
            'X-Response-From',
58
            $this->uri->withPath($this->uri->getPath() . $action)->__toString()
59
        );
60
    }
61
}
62