Completed
Push — feature/EVO-5751-text-index-mo... ( 0ab3ac...8fecb1 )
by
unknown
62:16 queued 57:01
created

ChoiceConstraintBuilder::supportsConstraint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
ccs 0
cts 2
cp 0
cc 1
eloc 2
nc 1
nop 2
crap 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
    /**
22
     * if this builder supports a given constraint
23
     *
24
     * @param string $type    Field type
25
     * @param array  $options Options
26
     *
27
     * @return bool
28
     */
29
    public function supportsConstraint($type, array $options = [])
30
    {
31
        return ($type === 'Choice');
32
    }
33
34
    /**
35
     * Adds constraints to the property
36
     *
37
     * @param string        $fieldName field name
38
     * @param Schema        $property  property
39
     * @param DocumentModel $model     parent model
40
     * @param array         $options   the constraint options
41
     *
42
     * @return Schema the modified property
43
     */
44
    public function buildConstraint($fieldName, Schema $property, DocumentModel $model, array $options)
45
    {
46
        $enumValue = array_reduce(
47
            $options,
48
            function ($carry, $option) {
49
                if ($option->name == 'choices') {
50
                    return explode('|', $option->value);
51
                }
52
            }
53
        );
54
55
        // is this a numeric field? convert values
56
        if (in_array('integer', $property->getType()->getTypes())) {
57
            $enumValue = array_map('intval', $enumValue);
58
        }
59
60
        if (is_array($enumValue)) {
61
            $property->setEnum($enumValue);
62
        }
63
64
        return $property;
65
    }
66
}
67