Completed
Push — develop ( b3a70f...be3b18 )
by Nate
02:28
created

MinMaxValidator::validateValue()   B

Complexity

Conditions 8
Paths 5

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 17
cp 0
rs 7.7777
c 0
b 0
f 0
cc 8
eloc 11
nc 5
nop 1
crap 72
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/domains/license
6
 * @link       https://www.flipboxfactory.com/software/domains/
7
 */
8
9
namespace flipbox\domains\validators;
10
11
use craft\validators\ArrayValidator;
12
use yii\db\QueryInterface;
13
14
/**
15
 * @author Flipbox Factory <[email protected]>
16
 * @since 1.0.0
17
 */
18
class MinMaxValidator extends ArrayValidator
19
{
20
    /**
21
     * @inheritdoc
22
     */
23
    public function validateAttribute($model, $attribute)
24
    {
25
        $value = $model->$attribute;
26
27
        if($value instanceof QueryInterface) {
28
            return $this->validateQueryAttribute($model, $attribute, $value);
29
        }
30
31
        return parent::validateAttribute($model, $attribute);
32
    }
33
34
    /**
35
     * @inheritdoc
36
     */
37
    protected function validateValue($value)
38
    {
39
        if(!$value instanceof QueryInterface) {
40
            return parent::validateValue($value);
41
        }
42
43
        $count = $value->count();
44
45
        if ($this->min !== null && $count < $this->min) {
46
            return [$this->tooFew, ['min' => $this->min]];
47
        }
48
        if ($this->max !== null && $count > $this->max) {
49
            return [$this->tooMany, ['max' => $this->max]];
50
        }
51
        if ($this->count !== null && $count !== $this->count) {
52
            return [$this->notEqual, ['count' => $this->count]];
53
        }
54
55
        return null;
56
    }
57
58
    /**
59
     * @param $model
60
     * @param $attribute
61
     * @param QueryInterface $query
62
     */
63
    protected function validateQueryAttribute($model, $attribute, QueryInterface $query)
64
    {
65
        $count = $query->count();
66
67
        if ($this->min !== null && $count < $this->min) {
68
            $this->addError($model, $attribute, $this->tooFew, ['min' => $this->min]);
69
        }
70
        if ($this->max !== null && $count > $this->max) {
71
            $this->addError($model, $attribute, $this->tooMany, ['max' => $this->max]);
72
        }
73
        if ($this->count !== null && $count !== $this->count) {
74
            $this->addError($model, $attribute, $this->notEqual, ['count' => $this->count]);
75
        }
76
    }
77
}
78