Completed
Pull Request — master (#108)
by Matt
11:28
created

RuleSetTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 10
c 0
b 0
f 0
wmc 8
lcom 0
cbo 2

5 Methods

Rating   Name   Duplication   Size   Complexity  
rules() 0 1 ?
setRule() 0 1 ?
A set() 0 7 3
A has() 0 4 1
A get() 0 14 4
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
    public function set($id, $constraint)
28
    {
29
        if (!is_string($constraint) && !$constraint instanceof \Closure) {
30
            throw new \InvalidArgumentException(sprintf('Expected a string or Closure, got %s', gettype($constraint)));
31
        }
32
        $this->setRule($id, $constraint);
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function has($id)
39
    {
40
        return array_key_exists($id, $this->rules());
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function get($id)
47
    {
48
        if (!$this->has($id)) {
49
            throw ConstraintNotFoundException::forRule($id);
50
        }
51
52
        $concrete = $this->rules()[$id];
53
54
        try {
55
            return is_string($concrete) ? new $concrete() : $concrete();
56
        } catch (\Exception $e) {
57
            throw ConstraintException::forRule($id, $e);
58
        }
59
    }
60
}
61