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

ChoiceConstraintBuilder   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 5
lcom 0
cbo 2
dl 0
loc 49
ccs 0
cts 17
cp 0
rs 10
c 3
b 0
f 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A supportsConstraint() 0 4 1
B buildConstraint() 0 22 4
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