Completed
Push — master ( c925cd...a7a479 )
by Philip
02:31
created

UniqueValidator::isValid()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 24
rs 8.6845
cc 4
eloc 16
nc 4
nop 2
1
<?php
2
3
/*
4
 * This file is part of the CRUDlex package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CRUDlex;
13
14
use \Valdi\Validator\ValidatorInterface;
15
16
/**
17
 * A validator to check for an unique field.
18
 */
19
class UniqueValidator implements ValidatorInterface {
20
21
    protected function isValidUniqueMany($value, $data, $entity, $field) {
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $entity is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $field is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
22
        return true;
23
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function isValid($value, array $parameters) {
29
30
        if (in_array($value, [null, ''])) {
31
            return true;
32
        }
33
34
        $data   = $parameters[0];
35
        $entity = $parameters[1];
36
        $field  = $parameters[2];
37
        $type   = $data->getDefinition()->getType($field);
38
39
        if ($type === 'many') {
40
            return $this->isValidUniqueMany($value, $data, $entity, $field);
41
        }
42
43
        $params          = [$field => $value];
44
        $paramsOperators = [$field => '='];
45
        if ($entity->get('id') !== null) {
46
            $params['id']          = $entity->get('id');
47
            $paramsOperators['id'] = '!=';
48
        }
49
        $amount = intval($data->countBy($data->getDefinition()->getTable(), $params, $paramsOperators, true));
50
        return $amount == 0;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function getInvalidDetails() {
57
        return 'unique';
58
    }
59
60
}
61