Completed
Push — standalone ( 1b0272...9e8eb1 )
by Philip
04:15
created

RestRequestParser::isUpdateableByReference()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 7

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 8
cts 8
cp 1
rs 8.2222
c 0
b 0
f 0
cc 7
eloc 10
nc 3
nop 2
crap 7
1
<?php
2
3
namespace Dontdrinkandroot\RestBundle\Service;
4
5
use Doctrine\Common\Util\ClassUtils;
6
use Doctrine\DBAL\Types\Type;
7
use Doctrine\ORM\EntityManagerInterface;
8
use Dontdrinkandroot\RestBundle\Metadata\Annotation\Method;
9
use Dontdrinkandroot\RestBundle\Metadata\Annotation\Right;
10
use Dontdrinkandroot\RestBundle\Metadata\PropertyMetadata;
11
use Metadata\MetadataFactory;
12
use Symfony\Component\HttpFoundation\Request;
13
use Symfony\Component\PropertyAccess\PropertyAccessor;
14
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
15
16
class RestRequestParser
17
{
18
    /**
19
     * @var MetadataFactory
20
     */
21
    private $metadataFactory;
22
23
    /**
24
     * @var PropertyAccessor
25
     */
26
    private $propertyAccessor;
27
28
    /**
29
     * @var AuthorizationCheckerInterface
30
     */
31
    private $authorizationChecker;
32
33
    /**
34
     * @var EntityManagerInterface
35
     */
36
    private $entityManager;
37
38 24
    public function __construct(
39
        MetadataFactory $metadataFactory,
40
        PropertyAccessor $propertyAccessor,
41
        AuthorizationCheckerInterface $authorizationChecker,
42
        EntityManagerInterface $entityManager
43
    ) {
44 24
        $this->metadataFactory = $metadataFactory;
45 24
        $this->propertyAccessor = $propertyAccessor;
46 24
        $this->authorizationChecker = $authorizationChecker;
47 24
        $this->entityManager = $entityManager;
48 24
    }
49
50
    /**
51
     * @param Request     $request
52
     * @param string      $entityClass
53
     * @param object|null $entity
54
     *
55
     * @return object
56
     */
57 24
    public function parseEntity(
58
        Request $request,
59
        $entityClass,
60
        $entity = null
61
    ) {
62 24
        $method = $request->getMethod();
63 24
        $format = $request->getRequestFormat();
64
65 24
        if ('json' !== $format) {
66
            throw new \RuntimeException(sprintf('Unsupported format "%s"', $format));
67
        }
68
69 24
        $data = $this->getRequestContent($request);
70
71 24
        if (null === $entity) {
72 14
            $entity = new $entityClass;
73
        }
74
75 24
        $this->updateObject($entity, $method, $data);
76
77 24
        return $entity;
78
    }
79
80
    /**
81
     * @param Request $request
82
     *
83
     * @return array
84
     */
85 24
    protected function getRequestContent(Request $request)
86
    {
87 24
        $content = $request->getContent();
88 24
        if ('' !== $content) {
89 24
            return json_decode($content, true);
90
        }
91
92
        return $request->request->all();
93
    }
94
95
    /**
96
     * @param object $object Access by reference.
97
     * @param string $method
98
     * @param array  $data
99
     */
100 24
    protected function updateObject(
101
        &$object,
102
        $method,
103
        $data
104
    ) {
105 24
        $classMetadata = $this->metadataFactory->getMetadataForClass(ClassUtils::getClass($object));
106
107 24
        foreach ($data as $key => $value) {
108 22
            if (array_key_exists($key, $classMetadata->propertyMetadata)) {
109
                /** @var PropertyMetadata $propertyMetadata */
110 22
                $propertyMetadata = $classMetadata->propertyMetadata[$key];
111 22
                if ($this->isUpdateable($object, $method, $propertyMetadata)) {
112 22
                    $this->updateProperty($object, $method, $propertyMetadata, $value);
113
                }
114
            }
115
        }
116 24
    }
117
118
    /**
119
     * @param object           $object Access by reference.
120
     * @param string           $method
121
     * @param PropertyMetadata $propertyMetadata
122
     * @param mixed            $value
123
     */
124 22
    protected function updateProperty(
125
        &$object,
126
        string $method,
127
        PropertyMetadata $propertyMetadata,
128
        $value
129
    ) {
130 22
        $byReference = $this->isUpdateableByReference($propertyMetadata, $method);
131 22
        if ($byReference) {
132 4
            $this->updateByReference($object, $propertyMetadata, $value);
133 18
        } elseif (array_key_exists($propertyMetadata->getType(), Type::getTypesMap())) {
134 18
            $convertedValue = $this->convert($propertyMetadata->getType(), $value);
135 18
            $this->propertyAccessor->setValue($object, $propertyMetadata->name, $convertedValue);
136
        } else {
137 2
            $this->updatePropertyObject($object, $method, $propertyMetadata, $value);
138
        }
139 22
    }
140
141 4
    private function updateByReference(&$object, PropertyMetadata $propertyMetadata, $value)
142
    {
143 4
        $type = $propertyMetadata->getType();
144 4
        $classMetadata = $this->entityManager->getClassMetadata($type);
145 4
        $identifiers = $classMetadata->getIdentifier();
146 4
        $id = [];
147 4
        foreach ($identifiers as $idName) {
148 4
            $id[$idName] = $value[$idName];
149
        }
150 4
        $reference = $this->entityManager->getReference($type, $id);
151 4
        $this->propertyAccessor->setValue($object, $propertyMetadata->name, $reference);
152 4
    }
153
154 2
    protected function updatePropertyObject(
155
        &$object,
156
        string $method,
157
        PropertyMetadata $propertyMetadata,
158
        $value
159
    ) {
160 2
        $propertyObject = $this->propertyAccessor->getValue($object, $propertyMetadata->name);
161 2
        if (null === $propertyObject) {
162
            $type = $propertyMetadata->getType();
163
            $propertyObject = new $type;
164
        }
165
166 2
        $this->updateObject($propertyObject, $method, $value);
167 2
        $this->propertyAccessor->setValue($object, $propertyMetadata->name, $propertyObject);
168 2
    }
169
170
    /**
171
     * @param string           $method
172
     * @param object           $object
173
     * @param PropertyMetadata $propertyMetadata
174
     *
175
     * @return bool
176
     */
177 22
    protected function isUpdateable(
178
        $object,
179
        string $method,
180
        PropertyMetadata $propertyMetadata
181
    ): bool {
182 22
        if ((Request::METHOD_PUT === $method || Request::METHOD_PATCH === $method) && $propertyMetadata->isPuttable()) {
183 10
            return $this->isGranted($object, $propertyMetadata->getPuttable()->right);
184
        }
185
186 18
        if (Request:: METHOD_POST === $method && $propertyMetadata->isPostable()) {
187 12
            return $this->isGranted($object, $propertyMetadata->getPostable()->right);
188
        }
189
190 12
        return false;
191
    }
192
193 22
    private function isGranted($object, ?Right $right): BOOL
194
    {
195 22
        if (null === $right) {
196 22
            return true;
197
        }
198
199 12
        $propertyPath = $right->propertyPath;
200 12
        if (null === $propertyPath) {
201 12
            return $this->authorizationChecker->isGranted($right->attributes);
202
        } else {
203
            $subject = $this->resolveSubject($object, $propertyPath);
204
205
            return $this->authorizationChecker->isGranted($right->attributes, $subject);
206
        }
207
    }
208
209
    private function resolveSubject($entity, $propertyPath)
210
    {
211
        if ('this' === $propertyPath) {
212
            return $entity;
213
        }
214
215
        return $this->propertyAccessor->getValue($entity, $propertyPath);
216
    }
217
218 18
    private function convert(?string $type, $value)
219
    {
220 18
        if (null === $value) {
221
            return $value;
222
        }
223
224
        switch ($type) {
225 18
            case 'datetime':
226 18
            case 'date':
227 18
            case 'time':
228 2
                return new \DateTime($value);
229
            default:
230 18
                return $value;
231
        }
232
    }
233
234 22
    private function isUpdateableByReference(PropertyMetadata $propertyMetadata, string $method)
235
    {
236
        if (
237 22
            Method::PUT === $method
238 22
            && null !== $propertyMetadata->getPuttable() && true === $propertyMetadata->getPuttable()->byReference
239
        ) {
240 2
            return true;
241
        }
242
243
        if (
244 20
            Method::POST === $method
245 20
            && null !== $propertyMetadata->getPostable() && true === $propertyMetadata->getPostable()->byReference
246
        ) {
247 2
            return true;
248
        }
249
250 18
        return false;
251
    }
252
}
253