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

MinMaxValidator   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 2
dl 0
loc 60
ccs 0
cts 38
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A validateAttribute() 0 10 2
B validateValue() 0 20 8
B validateQueryAttribute() 0 14 7
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