Test Failed
Pull Request — main (#30)
by Stéphane
11:42
created

Uri::__construct()   B

Complexity

Conditions 8
Paths 7

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 38
ccs 13
cts 13
cp 1
rs 8.4444
cc 8
nc 7
nop 1
crap 8
1
<?php
2
3
namespace CHStudio\Raven\Http\Factory;
4
5
use InvalidArgumentException;
6
use Stringable;
7
8
class Uri implements Stringable
9
{
10
    private readonly string $uri;
11
12 15
    public function __construct(mixed $value)
13
    {
14 15
        if (\is_array($value)) {
15 4
            if (!\is_string($value['base'])) {
16 1
                throw new InvalidArgumentException(
17 1
                    'If you want to build an URI from an array, use the schema: [ base => string, ?parameters => [string => mixed]'
18 1
                );
19
            }
20
21 3
            // Check if parameters is a valid string[]
22 3
            $parameters = $value['parameters'] ?? [];
23 11
            if (!\is_array($parameters)) {
24 4
                throw new InvalidArgumentException('value parameters must be an array.');
25
            }
26 10
27
            $search = [];
28
            $replace = [];
29 10
            foreach ($parameters as $name => $parameter) {
30
                if (!\is_string($name) || !\is_string($parameter)) {
31 10
                    throw new InvalidArgumentException(\sprintf(
32
                        'Invalid parameter given {name: %s, parameter: %s}',
33
                        var_export($name, true),
34
                        var_export($parameter, true)
35
                    ));
36
                }
37
                $search[] = $name;
38
                $replace[] = $parameter;
39
            }
40
41
            $this->uri = str_replace(
0 ignored issues
show
Bug introduced by
The property uri is declared read-only in CHStudio\Raven\Http\Factory\Uri.
Loading history...
42
                $search,
43
                $replace,
44
                (string) $value['base']
45
            );
46
        } elseif (\is_string($value)) {
47
            $this->uri = $value;
48
        } else {
49
            throw new InvalidArgumentException('$value must be a string or an array.');
50
        }
51
    }
52
53
    public function __toString(): string
54
    {
55
        return $this->uri;
56
    }
57
}
58