CallbackValidator::parseCallback()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
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