Completed
Push — master ( 575d8d...afd64c )
by Steevan
04:50
created

UniqueObjectValidator::compare()   C

Complexity

Conditions 11
Paths 11

Size

Total Lines 43
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 43
rs 5.2653
cc 11
eloc 29
nc 11
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace steevanb\SymfonyValidatorConstraints\Constraints;
4
5
use Symfony\Component\Validator\Constraint;
6
use Symfony\Component\Validator\ConstraintValidator;
7
8
class UniqueObjectValidator extends ConstraintValidator
9
{
10
    /** @var array */
11
    protected $traversablesValues = [];
12
13
    /**
14
     * @param mixed $traversable
15
     * @param UniqueObject $constraint
16
     */
17
    public function validate($traversable, Constraint $constraint)
18
    {
19
        $this
20
            ->assertIsTraversable($traversable)
21
            ->defineTraversablesValues($traversable, $constraint);
1 ignored issue
show
Compatibility introduced by
$constraint of type object<Symfony\Component\Validator\Constraint> is not a sub-type of object<steevanb\SymfonyV...nstraints\UniqueObject>. It seems like you assume a child class of the class Symfony\Component\Validator\Constraint to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
22
23
        foreach ($traversable as $data) {
24
            $this->compare($data, $constraint);
1 ignored issue
show
Compatibility introduced by
$constraint of type object<Symfony\Component\Validator\Constraint> is not a sub-type of object<steevanb\SymfonyV...nstraints\UniqueObject>. It seems like you assume a child class of the class Symfony\Component\Validator\Constraint to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
25
        }
26
    }
27
28
    /**
29
     * @param mixed $data
30
     * @throws \Exception
31
     * @return $this
32
     */
33
    protected function assertIsTraversable($data)
34
    {
35
        if (is_array($data) === false && $data instanceof \Traversable === false) {
36
            throw new \Exception(gettype($data) . ' is not iterable.');
37
        }
38
39
        return $this;
40
    }
41
42
    /**
43
     * @param array|\Traversable $traversable
44
     * @param UniqueObject $uniqueObject
45
     * @return $this
46
     */
47
    protected function defineTraversablesValues($traversable, UniqueObject $uniqueObject)
48
    {
49
        foreach ($traversable as $data) {
50
            $traversableHash = spl_object_hash($data);
51
            $this->traversablesValues[$traversableHash] = ['properties' => [], 'getters' => []];
52
53
            foreach ($uniqueObject->getProperties() as $property) {
54
                $this->traversablesValues[$traversableHash]['properties'][$property] =
55
                    $this->getTraversableValue($data->$property);
56
            }
57
58
            foreach ($uniqueObject->getGetters() as $getter) {
59
                $this->traversablesValues[$traversableHash]['getters'][$getter] =
60
                    $this->getTraversableValue($data->$getter());
61
            }
62
        }
63
64
        return $this;
65
    }
66
67
    /**
68
     * @param mixed $value
69
     * @return string
70
     */
71
    protected function getTraversableValue($value)
72
    {
73
        return (is_object($value)) ? spl_object_hash($value) : $value;
74
    }
75
76
    /**
77
     * @param mixed $data
78
     * @param UniqueObject $uniqueObject
79
     */
80
    protected function compare($data, UniqueObject $uniqueObject)
81
    {
82
        static $alreadyTested = [];
83
        if (in_array($uniqueObject->getUniqid(), $alreadyTested)) {
84
            return;
85
        }
86
87
        $dataHash = spl_object_hash($data);
88
        $dataValues = $this->traversablesValues[$dataHash];
89
        foreach ($this->traversablesValues as $objectHash => $values) {
90
            if (
91
                $objectHash === $dataHash
92
                || (
93
                    count($values['properties']) !== count($dataValues['properties'])
94
                    || count($values['getters']) !== count($dataValues['getters'])
95
                )
96
            ) {
97
                continue;
98
            }
99
100
            $compare = true;
101
            foreach (['properties', 'getters'] as $type) {
102
                foreach ($dataValues[$type] as $name => $value) {
103
                    if (
104
                        array_key_exists($name, $dataValues[$type])
105
                        && $this->compareValues($dataValues[$type][$name], $value, $uniqueObject->getStrict()) === false
106
                    ) {
107
                        $compare = false;
108
                        break 2;
109
                    }
110
                }
111
            }
112
            if ($compare) {
113
                $this
114
                    ->context
115
                    ->buildViolation($uniqueObject->getMessage())
116
                    ->atPath($this->context->getPropertyName())
117
                    ->addViolation();
118
                $alreadyTested[] = $uniqueObject->getUniqid();
119
                break;
120
            }
121
        }
122
    }
123
124
    /**
125
     * @param mixed $value1
126
     * @param mixed $value2
127
     * @param bool $strict
128
     * @return bool
129
     */
130
    protected function compareValues($value1, $value2, $strict)
131
    {
132
        return ($strict) ? $value1 === $value2 : $value1 == $value2;
133
    }
134
}
135