Completed
Push — master ( 04d975...930ba5 )
by
unknown
97:51 queued 93:08
created

ConstraintBuilder::addConstraints()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 28
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.1979

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 28
ccs 14
cts 17
cp 0.8235
rs 8.439
cc 6
eloc 13
nc 8
nop 3
crap 6.1979
1
<?php
2
/**
3
 * ConstraintBuilder class file
4
 */
5
6
namespace Graviton\SchemaBundle\Constraint;
7
8
use Graviton\RestBundle\Model\DocumentModel;
9
use Graviton\SchemaBundle\Constraint\Builder\ConstraintBuilderInterface;
10
use Graviton\SchemaBundle\Document\Schema;
11
12
/**
13
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
14
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
15
 * @link     http://swisscom.ch
16
 */
17
class ConstraintBuilder
18
{
19
    /**
20
     * @var ConstraintBuilderInterface[]
21
     */
22
    private $builders = [];
23
24
    /**
25
     * Add constraint builder
26
     *
27
     * @param ConstraintBuilderInterface $builder Constraint builder
28
     *
29
     * @return void
30
     */
31 6
    public function addConstraintBuilder(ConstraintBuilderInterface $builder)
32
    {
33 6
        $this->builders[] = $builder;
34 6
    }
35
36
    /**
37
     * Go through the constraints and call the builders to do their job
38
     *
39
     * @param string        $fieldName field name
40
     * @param Schema        $property  the property
41
     * @param DocumentModel $model     the parent model
42
     *
43
     * @return Schema
44
     */
45 2
    public function addConstraints($fieldName, Schema $property, DocumentModel $model)
46
    {
47 2
        $constraints = $model->getConstraints($fieldName);
48
49 2
        if (!is_array($constraints)) {
50
            return $property;
51
        }
52
53 2
        foreach ($constraints as $constraint) {
54 2
            $isSupported = false;
55 2
            foreach ($this->builders as $builder) {
56 2
                if ($builder->supportsConstraint($constraint->name, $constraint->options)) {
57 2
                    $property = $builder->buildConstraint($fieldName, $property, $model, $constraint->options);
58 2
                    $isSupported = true;
59 2
                }
60 2
            }
61
62 2
            if (!$isSupported) {
63
                /**
64
                 * unknown/not supported constraints will be added to the 'x-constraints' schema property.
65
                 * this allows others (possibly schema constraints) to pick it up and implement more advanced logic.
66
                 */
67
                 $property->addConstraint($constraint->name);
68
            }
69 2
        }
70
71 2
        return $property;
72
    }
73
}
74