1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sofa\Eloquence\Validable; |
4
|
|
|
|
5
|
|
|
use Sofa\Eloquence\Contracts\Validable; |
6
|
|
|
|
7
|
|
|
class Observer |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Validation skipping flag. |
11
|
|
|
* |
12
|
|
|
* @var integer |
13
|
|
|
*/ |
14
|
|
|
const SKIP_ONCE = 1; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Validation skipping flag. |
18
|
|
|
* |
19
|
|
|
* @var integer |
20
|
|
|
*/ |
21
|
|
|
const SKIP_ALWAYS = 2; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Halt creating if model doesn't pass validation. |
25
|
|
|
* |
26
|
|
|
* @param \Sofa\Eloquence\Contracts\Validable $model |
27
|
|
|
* @return void|false |
28
|
|
|
*/ |
29
|
|
|
public function creating(Validable $model) |
30
|
|
|
{ |
31
|
|
|
if ($model->validationEnabled() && !$model->isValid()) { |
32
|
|
|
return false; |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Updating event handler. |
38
|
|
|
* |
39
|
|
|
* @param \Sofa\Eloquence\Contracts\Validable $model |
40
|
|
|
* @return void|false |
41
|
|
|
*/ |
42
|
|
|
public function updating(Validable $model) |
43
|
|
|
{ |
44
|
|
|
if ($model->validationEnabled()) { |
45
|
|
|
return $this->validateUpdate($model); |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Halt updating if model doesn't pass validation. |
51
|
|
|
* |
52
|
|
|
* @param \Sofa\Eloquence\Contracts\Validable $model |
53
|
|
|
* @return void|false |
54
|
|
|
*/ |
55
|
|
|
protected function validateUpdate(Validable $model) |
56
|
|
|
{ |
57
|
|
|
// When we are trying to update this model we need to set the update rules |
58
|
|
|
// on the validator first, next we can determine if the model is valid, |
59
|
|
|
// finally we restore original rules and notify in case of failure. |
60
|
|
|
$model->getValidator()->setRules($model->getUpdateRules()); |
61
|
|
|
|
62
|
|
|
$valid = $model->isValid(); |
63
|
|
|
|
64
|
|
|
$model->getValidator()->setRules($model->getCreateRules()); |
65
|
|
|
|
66
|
|
|
if (!$valid) { |
67
|
|
|
return false; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Enable validation for the model if skipped only once. |
73
|
|
|
* |
74
|
|
|
* @param \Sofa\Eloquence\Contracts\Validable $model |
75
|
|
|
* @return void |
76
|
|
|
*/ |
77
|
|
|
public function saved(Validable $model) |
78
|
|
|
{ |
79
|
|
|
if ($model->skipsValidation() === static::SKIP_ONCE) { |
80
|
|
|
$model->enableValidation(); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|