Completed
Push — feature/other-validation ( 1442c4...18a759 )
by Narcotic
64:54
created

ChoiceConstraintBuilder::supportsConstraint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
/**
3
 * ChoiceConstraintBuilder class file
4
 *
5
 * a constraint builder that renders an enum for the schema
6
 */
7
8
namespace Graviton\SchemaBundle\Constraint\Builder;
9
10
use Graviton\RestBundle\Model\DocumentModel;
11
use Graviton\SchemaBundle\Document\Schema;
12
13
/**
14
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
15
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
16
 * @link     http://swisscom.ch
17
 */
18
class ChoiceConstraintBuilder implements ConstraintBuilderInterface
19
{
20
    /**
21
     * if this builder supports a given constraint
22
     *
23
     * @param string $type    Field type
24
     * @param array  $options Options
25
     *
26
     * @return bool
27
     */
28
    public function supportsConstraint($type, array $options = [])
29
    {
30
        return ($type === 'Choice');
31
    }
32
33
    /**
34
     * Adds constraints to the property
35
     *
36
     * @param string        $fieldName field name
37
     * @param Schema        $property  property
38
     * @param DocumentModel $model     parent model
39
     * @param array         $options   the constraint options
40
     *
41
     * @return Schema the modified property
42
     */
43
    public function buildConstraint($fieldName, Schema $property, DocumentModel $model, array $options)
44
    {
45
        $enumValue = array_reduce(
46
            $options,
47
            function ($carry, $option) {
48
                if ($option->name == 'choices') {
49
                    return explode('|', $option->value);
50
                }
51
            }
52
        );
53
54
        if (is_array($enumValue)) {
55
            $property->setEnum($enumValue);
56
        }
57
58
        return $property;
59
    }
60
}
61