Passed
Branch 3.0.0 (3c68a7)
by Pieter
04:04
created

setAttributeValue()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
c 0
b 0
f 0
nc 5
nop 5
dl 0
loc 10
rs 10
1
<?php
2
namespace W2w\Lib\Apie\Plugins\Core\Normalizers;
3
4
use Exception;
5
use ReflectionException;
6
use ReflectionProperty;
7
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
8
9
/**
10
 * Variation of ObjectNormalizer to be able to set the property even if there is no setter. This can be used by classes
11
 * implementing ApiResourceRetrieverInterface to set values that have no setter but only have a getter, for example a
12
 * created_at field in a database table.
13
 */
14
class EvilReflectionPropertyNormalizer extends ObjectNormalizer
15
{
16
    /**
17
     * {@inheritdoc}
18
     */
19
    public function hasCacheableSupportsMethod(): bool
20
    {
21
        return true;
22
    }
23
24
    /**
25
     * {@inheritdoc}
26
     */
27
    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = [])
28
    {
29
        try {
30
            $this->propertyAccessor->setValue($object, $attribute, $value);
31
        } catch (Exception $exception) {
32
            try {
33
                $refl = new ReflectionProperty($object, $attribute);
34
                $refl->setAccessible(true);
35
                $refl->setValue($object, $value);
36
            } catch (ReflectionException $reflException) {
37
                // ignored
38
            }
39
        }
40
    }
41
}
42