Completed
Push — master ( df3ea1...7d74eb )
by Hannes
01:56
created

AbstractValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 0
dl 0
loc 45
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A onException() 0 5 1
A fireException() 0 4 1
A defaultOnExceptionCallback() 0 4 1
A __invoke() 0 4 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace hanneskod\clean;
6
7
/**
8
 * Base validator including exception handling using a callback
9
 */
10
abstract class AbstractValidator implements ValidatorInterface
11
{
12
    /**
13
     * @var callable Callback on exception
14
     */
15
    private $onExceptionCallback = [__CLASS__, 'defaultOnExceptionCallback'];
16
17
    /**
18
     * Register on-exception callback
19
     *
20
     * The callback should take an \Exception object and proccess it as
21
     * appropriate. This generally means throwing an exception of some kind
22
     * or returning a replacement value.
23
     */
24
    public function onException(callable $callback): self
25
    {
26
        $this->onExceptionCallback = $callback;
27
        return $this;
28
    }
29
30
    /**
31
     * Call the on-exception callback
32
     *
33
     * @return mixed Whatever the callback returns
34
     */
35
    protected function fireException(\Exception $exception)
36
    {
37
        return call_user_func($this->onExceptionCallback, $exception);
38
    }
39
40
    /**
41
     * Simple callback that throws exceptions
42
     *
43
     * @throws \Exception throws supplied exception
44
     */
45
    protected static function defaultOnExceptionCallback(\Exception $exception): void
46
    {
47
        throw $exception;
48
    }
49
50
    public function __invoke($tainted)
51
    {
52
        return $this->validate($tainted);
53
    }
54
}
55