Passed
Pull Request — master (#407)
by Kirill
07:03
created

Manager::add()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 3
nc 2
nop 3
dl 0
loc 7
rs 10
c 1
b 0
f 1
1
<?php
2
3
/**
4
 * This file is part of Spiral Framework package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Distribution;
13
14
final class Manager implements MutableDistributionInterface
15
{
16
    /**
17
     * @var string
18
     */
19
    public const DEFAULT_RESOLVER = 'default';
20
21
    /**
22
     * @var string
23
     */
24
    private const ERROR_REDEFINITION = 'Can not redefine already defined distribution resolver `%s`';
25
26
    /**
27
     * @var string
28
     */
29
    private const ERROR_NOT_FOUND = 'Distribution resolver `%s` has not been defined';
30
31
    /**
32
     * @var array<string, UriResolverInterface>
33
     */
34
    private $resolvers = [];
35
36
    /**
37
     * @var string
38
     */
39
    private $default;
40
41
    /**
42
     * @param string $name
43
     */
44
    public function __construct(string $name = self::DEFAULT_RESOLVER)
45
    {
46
        $this->default = $name;
47
    }
48
49
    /**
50
     * @param string $name
51
     * @return $this
52
     */
53
    public function withDefault(string $name): DistributionInterface
54
    {
55
        $self = clone $this;
56
        $self->default = $name;
57
58
        return $self;
59
    }
60
61
    /**
62
     * {@inheritDoc}
63
     */
64
    public function resolver(string $name = null): UriResolverInterface
65
    {
66
        $name = $name ?? $this->default;
67
68
        if (!isset($this->resolvers[$name])) {
69
            throw new \InvalidArgumentException(\sprintf(self::ERROR_NOT_FOUND, $name));
70
        }
71
72
        return $this->resolvers[$name];
73
    }
74
75
    /**
76
     * {@inheritDoc}
77
     */
78
    public function add(string $name, UriResolverInterface $resolver, bool $overwrite = false): void
79
    {
80
        if ($overwrite === false && isset($this->resolvers[$name])) {
81
            throw new \InvalidArgumentException(\sprintf(self::ERROR_REDEFINITION, $name));
82
        }
83
84
        $this->resolvers[$name] = $resolver;
85
    }
86
87
    /**
88
     * {@inheritDoc}
89
     */
90
    public function getIterator(): \Traversable
91
    {
92
        return new \ArrayIterator($this->resolvers);
93
    }
94
95
    /**
96
     * {@inheritDoc}
97
     */
98
    public function count(): int
99
    {
100
        return \count($this->resolvers);
101
    }
102
}
103