RequestHeadersAlter   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 23
dl 0
loc 53
ccs 20
cts 20
cp 1
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A alter() 0 38 4
1
<?php
2
3
/**
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 *
7
 * @see https://github.com/ecphp
8
 */
9
10
declare(strict_types=1);
11
12
namespace EcPhp\ReverseProxyHelperBundle\Service;
13
14
use InvalidArgumentException;
15
use Symfony\Component\HttpFoundation\Request;
16
17
use function array_key_exists;
18
19
use const FILTER_VALIDATE_URL;
20
21
final class RequestHeadersAlter implements RequestAlterInterface
22
{
23
    /**
24
     * @var array<mixed>
25
     */
26
    private $parameters;
27
28
    /**
29
     * @param array<mixed> $parameters
30
     */
31 8
    public function __construct(array $parameters)
32
    {
33 8
        $this->parameters = $parameters;
34
    }
35
36 7
    public function alter(Request $request): Request
37
    {
38 7
        $parsed = parse_url($this->parameters['base_url']);
39
40 7
        if (false === $parsed) {
41 1
            throw new InvalidArgumentException('Unable to parse the provided URL.');
42
        }
43
44 6
        if (false === array_key_exists('host', $parsed)) {
45 2
            return $request;
46
        }
47
48 4
        if (false === filter_var($this->parameters['base_url'], FILTER_VALIDATE_URL)) {
49 1
            return $request;
50
        }
51
52
        $request
53 3
            ->headers
54 3
            ->add(
55 3
                array_map(
56 3
                    static function (string $key) use ($parsed): string {
57 3
                        return (string) $parsed[$key];
58
                    },
59 3
                    array_filter(
60
                        [
61 3
                            'X-Forwarded-Host' => 'host',
62
                            'X-Forwarded-Proto' => 'scheme',
63
                            'X-Forwarded-Port' => 'port',
64
                            'X-Forwarded-Prefix' => 'path',
65
                        ],
66 3
                        static function (string $key) use ($parsed): bool {
67 3
                            return array_key_exists($key, $parsed);
68
                        }
69
                    )
70
                )
71
            );
72
73 3
        return $request;
74
    }
75
}
76