RuleSetContainer::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace League\JsonGuard\RuleSet;
4
5
use League\JsonGuard\Exception\ConstraintNotFoundException;
6
use Psr\Container\ContainerInterface;
7
8
/**
9
 * A lightweight container for building rule sets.
10
 */
11
class RuleSetContainer implements ContainerInterface
12
{
13
    /**
14
     * @var \Closure[]
15
     */
16
    private $rules = [];
17
18
    /**
19
     * @param array $rules
20
     */
21 242
    public function __construct(array $rules = [])
22
    {
23 242
        foreach ($rules as $keyword => $rule) {
24 242
            $this->set($keyword, $rule);
25
        }
26 242
    }
27
28 152
    public function get($keyword)
29
    {
30 152
        if (!$this->has($keyword)) {
31 2
            throw ConstraintNotFoundException::forRule($keyword);
32
        }
33
34 150
        return $this->rules[$keyword]($this);
35
    }
36
37 154
    public function has($keyword)
38
    {
39 154
        return isset($this->rules[$keyword]);
40
    }
41
42
    /**
43
     * Adds a rule to the container.
44
     *
45
     * @param string          $keyword Identifier of the entry.
46
     * @param \Closure|string $factory The closure to invoke when this entry is resolved or the FQCN.
47
     *                                 The closure will be given this container as the only
48
     *                                 argument when invoked.
49
     */
50 242
    public function set($keyword, $factory)
51
    {
52 242
        if (!(is_string($factory) || $factory instanceof \Closure)) {
53
            throw new \InvalidArgumentException(
54
                sprintf('Expected a string or Closure, got %s', gettype($keyword))
55
            );
56
        }
57
58 150
        $this->rules[$keyword] = function ($container) use ($factory) {
59 150
            static $object;
60
61 150
            if (is_null($object)) {
62 150
                $object = is_string($factory) ? new $factory() : $factory($container);
63
            }
64
65 150
            return $object;
66
        };
67 242
    }
68
}
69