1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @copyright Copyright (c) Flipbox Digital Limited |
5
|
|
|
* @license https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE |
6
|
|
|
* @link https://github.com/flipboxfactory/craft-ember |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace flipbox\ember\validators; |
10
|
|
|
|
11
|
|
|
use yii\base\Model; |
12
|
|
|
use yii\db\Query; |
13
|
|
|
use yii\validators\Validator; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @author Flipbox Factory <[email protected]> |
17
|
|
|
* @since 1.0.0 |
18
|
|
|
*/ |
19
|
|
|
class LimitValidator extends Validator |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var callable This can be a global function name, anonymous function, etc. |
23
|
|
|
* The function signature must be as follows, |
24
|
|
|
* |
25
|
|
|
* ```php |
26
|
|
|
* function foo(\yii\db\Query $query) { |
27
|
|
|
* // modify $query here |
28
|
|
|
* return $query; |
29
|
|
|
* } |
30
|
|
|
* ``` |
31
|
|
|
*/ |
32
|
|
|
public $query; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @var callable This can be a global function name, anonymous function, etc. |
36
|
|
|
* The function signature must be as follows, |
37
|
|
|
* |
38
|
|
|
* ```php |
39
|
|
|
* function foo(\yii\base\Model $model) { |
40
|
|
|
* // compute $limit here |
41
|
|
|
* return (int) $limit; |
42
|
|
|
* } |
43
|
|
|
* ``` |
44
|
|
|
*/ |
45
|
|
|
public $limit; |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @inheritdoc |
49
|
|
|
* @param \yii\base\Model $model the data model to be validated |
50
|
|
|
* @param string $attribute the name of the attribute to be validated. |
51
|
|
|
*/ |
52
|
|
|
public function validateAttribute($model, $attribute) |
53
|
|
|
{ |
54
|
|
|
if (0 === ($limit = $this->getLimit($model))) { |
55
|
|
|
return; // no limit |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$count = (int)$this->getQuery($model)->count(); |
59
|
|
|
|
60
|
|
|
if ($count >= $limit) { |
61
|
|
|
$this->addError($model, $attribute, $this->message); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param Model $model |
67
|
|
|
* @return int |
68
|
|
|
*/ |
69
|
|
|
protected function getLimit(Model $model): int |
70
|
|
|
{ |
71
|
|
|
return (int)call_user_func($this->limit, $model); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @param Model $model |
76
|
|
|
* @return Query |
77
|
|
|
*/ |
78
|
|
|
protected function getQuery(Model $model): Query |
79
|
|
|
{ |
80
|
|
|
return call_user_func($this->query, $model); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|