CallbackValidator   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 86
rs 10
c 0
b 0
f 0
wmc 13
lcom 1
cbo 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 5 1
A validateCallback() 0 8 2
A parseCallback() 0 6 2
A callbackIsInvalid() 0 4 1
A callbackIsValid() 0 4 2
A getInvalidCallbackMessage() 0 6 2
A callbackIsAccessible() 0 6 2
1
<?php
2
3
4
namespace SmartWeb\ModuleTesting\ExpressionLanguage;
5
6
use Closure;
7
use InvalidArgumentException;
8
use ReflectionMethod;
9
use SmartWeb\ModuleTesting\Contracts\ExpressionLanguage\Validator;
10
11
12
/**
13
 * Class CallbackValidator
14
 *
15
 * @package SmartWeb\ModuleTesting\ExpressionLanguage
16
 */
17
class CallbackValidator implements Validator
18
{
19
    
20
    /**
21
     * @var callable|Closure
22
     */
23
    private $callback;
24
    
25
    /**
26
     * @var string
27
     */
28
    private $expectation;
29
    
30
    /**
31
     * @inheritDoc
32
     */
33
    public function __construct(string $expectation)
34
    {
35
        $this->expectation = $expectation;
36
    }
37
    
38
    /**
39
     * @inheritDoc
40
     */
41
    public function validate($callback)
42
    {
43
        $this->callback = $callback;
44
        $this->validateCallback();
45
    }
46
    
47
    protected function validateCallback()
48
    {
49
        $this->callback = $this->parseCallback();
50
        
51
        if ($this->callbackIsInvalid()) {
52
            throw new InvalidArgumentException($this->expectation . $this->getInvalidCallbackMessage());
53
        }
54
    }
55
    
56
    /**
57
     * @return callable|Closure
58
     */
59
    protected function parseCallback()
60
    {
61
        return is_array($this->callback)
62
            ? get_class($this->callback[0]) . '::' . $this->callback[1]
63
            : $this->callback;
64
    }
65
    
66
    /**
67
     * @return bool
68
     */
69
    protected function callbackIsInvalid()
70
    {
71
        return !$this->callbackIsValid();
72
    }
73
    
74
    /**
75
     * @return bool
76
     */
77
    protected function callbackIsValid()
78
    {
79
        return is_callable($this->callback) || ($this->callback instanceof Closure);
80
    }
81
    
82
    /**
83
     * @return string
84
     */
85
    protected function getInvalidCallbackMessage() : string
86
    {
87
        return $this->callbackIsAccessible()
88
            ? "; was: '{$this->callback}'"
89
            : ", cannot access private method {$this->callback}()";
90
    }
91
    
92
    /**
93
     * @return bool
94
     */
95
    protected function callbackIsAccessible() : bool
96
    {
97
        $method = new ReflectionMethod($this->callback);
98
        
99
        return $method->isPublic() && !$method->isAbstract();
100
    }
101
    
102
}
103