RestRequestParser::isUpdateableByReference()   B
last analyzed

Complexity

Conditions 7
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

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