Passed
Push — master ( 5d30f6...461084 )
by Alexey
02:28
created

AbstractValidation::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 10
ccs 8
cts 8
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
4
namespace Lexuss1979\Validol\Validations;
5
6
7
use Lexuss1979\Validol\ValueObject;
8
9
abstract class AbstractValidation
10
{
11
    const REQUIREMENTS_GROUP = 'requirements';
12
    const TYPE_GROUP = 'type';
13
    const COMMON_GROUP = 'common';
14
    protected $error;
15
    protected $data;
16
    protected $options;
17
    protected $group = self::COMMON_GROUP;
18
    protected $errorMessage = null;
19
20 150
    public function __construct($options = null)
21
    {
22 150
        $this->options = $options;
23 150
    }
24
25 88
    public function error()
26
    {
27 88
        return $this->error;
28
    }
29
30 147
    public function validate(ValueObject $data)
31
    {
32 147
        $this->data = $data;
33 147
        if (!$this->isValid($data)) {
34 88
            $this->error = $this->getErrorMessage();
35 88
            $this->afterFailedValidation();
36 88
            return false;
37
        }
38 127
        $this->afterSuccessValidation();
39 127
        return true;
40
    }
41
42
    abstract public function isValid(ValueObject $data);
43
44 88
    public function getErrorMessage()
45
    {
46 88
        if (!is_null($this->errorMessage)) return str_replace("{name}", $this->data->name(), $this->errorMessage);
47
48 45
        return $this->errorMessage();
49
    }
50
51 2
    public function setErrorMessage($message)
52
    {
53 2
        $this->errorMessage = $message;
54 2
    }
55
56
    protected function errorMessage()
57
    {
58
        return "{$this->data->name()} is not valid";
59
    }
60
61 88
    protected function afterFailedValidation()
62
    {
63
64 88
    }
65
66 127
    protected function afterSuccessValidation()
67
    {
68
69 127
    }
70
71 144
    public function group()
72
    {
73 144
        return $this->group;
74
    }
75
}