Completed
Pull Request — master (#108)
by Matt
04:36
created

RuleSetTrait::has()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace League\JsonGuard\RuleSets;
4
5
use League\JsonGuard\Exceptions\ConstraintException;
6
use League\JsonGuard\Exceptions\ConstraintNotFoundException;
7
8
trait RuleSetTrait
9
{
10
    /**
11
     * @return array
12
     */
13
    abstract protected function rules();
14
15
    /**
16
     * @param string          $id
17
     * @param string|\Closure $constraint
18
     *
19
     * @return void
20
     */
21
    abstract protected function setRule($id, $constraint);
22
23
    /**
24
     * @param string          $id
25
     * @param string|\Closure $constraint
26
     */
27 2
    public function set($id, $constraint)
28
    {
29 2
        if (!is_string($constraint) && !$constraint instanceof \Closure) {
30
            throw new \InvalidArgumentException(sprintf('Expected a string or Closure, got %s', gettype($constraint)));
31
        }
32 2
        $this->setRule($id, $constraint);
33 2
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 156
    public function has($id)
39
    {
40 156
        return array_key_exists($id, $this->rules());
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 152
    public function get($id)
47
    {
48 152
        if (!$this->has($id)) {
49 2
            throw ConstraintNotFoundException::forRule($id);
50
        }
51
52 150
        $concrete = $this->rules()[$id];
53
54
        try {
55 150
            return is_string($concrete) ? new $concrete() : $concrete();
56
        } catch (\Exception $e) {
57
            throw ConstraintException::forRule($id, $e);
58
        }
59
    }
60
}
61