Completed
Push — master ( e32eeb...714cda )
by
unknown
89:50 queued 46:29
created

ConstraintFactory::parse()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 25
Code Lines 17

Duplication

Lines 11
Ratio 44 %
Metric Value
dl 11
loc 25
rs 8.439
cc 6
eloc 17
nc 4
nop 1
1
<?php
2
3
namespace Oro\Bundle\FormBundle\Validator;
4
5
use Symfony\Component\Validator\Constraint;
6
7
class ConstraintFactory
8
{
9
    /**
10
     * Creates a validation constraint.
11
     *
12
     * @param string $name    The name of standard constraint or FQCN of a custom constraint
13
     * @param mixed  $options The constraint options (as associative array)
14
     *                        or the value for the default option (any other type)
15
     *
16
     * @return Constraint
17
     *
18
     * @throws \InvalidArgumentException if unknown constraint detected
19
     */
20
    public function create($name, $options = null)
21
    {
22
        if (strpos($name, '\\') !== false && class_exists($name)) {
23
            $className = (string)$name;
24
        } else {
25
            $className = 'Symfony\\Component\\Validator\\Constraints\\' . $name;
26
        }
27
28
        if (!class_exists($className)) {
29
            throw new \InvalidArgumentException(
30
                sprintf('The "%s" class does not exist.', $className)
31
            );
32
        }
33
34
        /**
35
         * Fixed issue with array pointer on php7
36
         */
37
        if (is_array($options)) {
38
            reset($options);
39
        }
40
41
        return new $className($options);
42
    }
43
44
    /**
45
     * Creates validation constraints by a given definition.
46
     *
47
     * @param array $constraints The definition of constraints
48
     *
49
     * @return Constraint[]
50
     *
51
     * @throws \InvalidArgumentException if invalid definition detected
52
     */
53
    public function parse(array $constraints)
54
    {
55
        $result = [];
56
        foreach ($constraints as $key => $value) {
57
            if (is_array($value)) {
58
                foreach ($value as $name => $options) {
59
                    $result[] = $this->create($name, $options);
60
                }
61
            } elseif ($value instanceof Constraint) {
62
                $result[] = $value;
63 View Code Duplication
            } else {
64
                throw new \InvalidArgumentException(
65
                    sprintf(
66
                        'Expected that each element in the constraints array must be either'
67
                        . ' instance of "Symfony\Component\Validator\Constraint"'
68
                        . ' or "array(constraint name => constraint options)".'
69
                        . ' Found "%s" element.',
70
                        is_object($value) ? get_class($value) : gettype($value)
71
                    )
72
                );
73
            }
74
        }
75
76
        return $result;
77
    }
78
}
79