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

ExtReferenceHandler::validateExtRef()   C

Complexity

Conditions 10
Paths 8

Size

Total Lines 50
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 76.992

Importance

Changes 3
Bugs 1 Features 0
Metric Value
dl 0
loc 50
ccs 4
cts 32
cp 0.125
rs 5.7647
c 3
b 1
f 0
cc 10
eloc 29
nc 8
nop 1
crap 76.992

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * ExtReferenceHandler class file
4
 */
5
6
namespace Graviton\DocumentBundle\Serializer\Handler;
7
8
use Graviton\DocumentBundle\Entity\ExtReference;
9
use Graviton\DocumentBundle\Service\ExtReferenceConverterInterface;
10
use Graviton\JsonSchemaBundle\Validator\Constraint\Event\ConstraintEventFormat;
11
use Graviton\RestBundle\Routing\Loader\ActionUtils;
12
use JMS\Serializer\Context;
13
use JMS\Serializer\JsonDeserializationVisitor;
14
use JMS\Serializer\JsonSerializationVisitor;
15
16
/**
17
 * JMS serializer handler for ExtReference
18
 *
19
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
20
 * @license  http://opensource.org/licenses/GPL GPL
21
 * @link     http://swisscom.ch
22
 */
23
class ExtReferenceHandler
24
{
25
    /**
26
     * @var ExtReferenceConverterInterface
27
     */
28
    private $converter;
29
30
    /**
31
     * @var array
32
     */
33
    private $extRefPatternCache = [];
34
35
    /**
36
     * Constructor
37
     *
38
     * @param ExtReferenceConverterInterface $converter Converter
39
     */
40 12
    public function __construct(ExtReferenceConverterInterface $converter)
41
    {
42 12
        $this->converter = $converter;
43 12
    }
44
45
    /**
46
     * Serialize extref to JSON
47
     *
48
     * @param JsonSerializationVisitor $visitor      Visitor
49
     * @param ExtReference             $extReference Extref
50
     * @param array                    $type         Type
51
     * @param Context                  $context      Context
52
     * @return string|null
53
     */
54 4
    public function serializeExtReferenceToJson(
55
        JsonSerializationVisitor $visitor,
56
        ExtReference $extReference,
57
        array $type,
58
        Context $context
59
    ) {
60
        try {
61 4
            return $visitor->visitString($this->converter->getUrl($extReference), $type, $context);
62 2
        } catch (\InvalidArgumentException $e) {
63 2
            return $visitor->visitNull(null, $type, $context);
64
        }
65
    }
66
67
    /**
68
     * Serialize extref to JSON
69
     *
70
     * @param JsonDeserializationVisitor $visitor Visitor
71
     * @param string                     $url     Extref URL
72
     * @param array                      $type    Type
73
     * @param Context                    $context Context
74
     * @return ExtReference|null
75
     */
76 4
    public function deserializeExtReferenceFromJson(
77
        JsonDeserializationVisitor $visitor,
78
        $url,
79
        array $type,
80
        Context $context
81
    ) {
82
        try {
83 4
            return $this->converter->getExtReference(
84 4
                $visitor->visitString($url, $type, $context)
85 2
            );
86 2
        } catch (\InvalidArgumentException $e) {
87 2
            return null;
88
        }
89
    }
90
91
    /**
92
     * Schema validation function for extref values. Will be executed when a user submits an extref
93
     *
94
     * @param ConstraintEventFormat $event event
95
     *
96
     * @return void
97
     */
98 4
    public function validateExtRef(ConstraintEventFormat $event)
99
    {
100 4
        $schema = $event->getSchema();
101
102 4
        if (!isset($schema->format) || (isset($schema->format) && $schema->format != 'extref')) {
103 4
            return;
104
        }
105
106
        $value = $event->getElement();
107
108
        // 1st) can it be converted to extref?
109
        try {
110
            $this->converter->getExtReference(
111
                $value
112
            );
113
        } catch (\InvalidArgumentException $e) {
114
            $event->addError(sprintf('Value "%s" is not a valid extref.', $value));
115
            return;
116
        }
117
118
        // 2nd) if yes, correct collection(s)?
119
        if (!isset($schema->{'x-collection'})) {
120
            return;
121
        }
122
123
        $collections = $schema->{'x-collection'};
124
125
        if (in_array('*', $collections)) {
126
            return;
127
        }
128
129
        $allValues = implode('-', $collections);
130
        if (!isset($this->extRefPatternCache[$allValues])) {
131
            $paths = [];
132
            foreach ($collections as $url) {
133
                $urlParts = parse_url($url);
134
                $paths[] = str_replace('/', '\\/', $urlParts['path']);
135
            }
136
            $this->extRefPatternCache[$allValues] = '(' . implode('|', $paths) . ')(' . ActionUtils::ID_PATTERN . ')$';
137
        }
138
139
        $stringConstraint = $event->getFactory()->createInstanceFor('string');
140
        $schema->format = null;
141
        $schema->pattern = $this->extRefPatternCache[$allValues];
142
        $stringConstraint->check($value, $schema, $event->getPath());
143
144
        if (!empty($stringConstraint->getErrors())) {
145
            $event->addError(sprintf('Value "%s" does not refer to a correct collection for this extref.', $value));
146
        }
147
    }
148
}
149