Completed
Push — master ( d1c976...1cf840 )
by Hannes
02:12
created

Validator::onException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4286
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace hanneskod\clean;
4
5
/**
6
 * Base validator including exception handling using a callback
7
 */
8
abstract class Validator
9
{
10
    /**
11
     * @var callable Callback on exception
12
     */
13
    private $onExceptionCallback = [__CLASS__, 'defaultOnExceptionCallback'];
14
15
    /**
16
     * Validate tainted data
17
     *
18
     * @param  mixed $tainted
19
     * @return mixed The cleaned data
20
     * @throws ValidationException If validation fails
21
     */
22
    abstract public function validate($tainted);
23
24
    /**
25
     * Register on-exception callback
26
     *
27
     * The callback should take an \Exception object and proccess it as
28
     * appropriate. This generally means throwing an exception of some kind
29
     * or returning a replacement value.
30
     *
31
     * @param  callable $callback
32
     * @return self Instance for chaining
33
     */
34
    public function onException(callable $callback)
35
    {
36
        $this->onExceptionCallback = $callback;
37
        return $this;
38
    }
39
40
    /**
41
     * Call the on-exception callback
42
     *
43
     * @param  \Exception $exception
44
     * @return mixed Whatever the callback returns
45
     */
46
    protected function fireException(\Exception $exception)
47
    {
48
        return call_user_func($this->onExceptionCallback, $exception);
49
    }
50
51
    /**
52
     * Simple callback that throws exceptions
53
     *
54
     * @param  \Exception $exception
55
     * @return void Never returns
56
     * @throws \Exception throws supplied exception
57
     */
58
    protected static function defaultOnExceptionCallback(\Exception $exception)
59
    {
60
        throw $exception;
61
    }
62
}
63