summaryrefslogtreecommitdiff
path: root/vendor/doctrine/persistence/src/Persistence/Reflection/RuntimeReflectionProperty.php
blob: 5f5205642dd7180c0ee448d670314422020585fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php

declare(strict_types=1);

namespace Doctrine\Persistence\Reflection;

use Doctrine\Common\Proxy\Proxy as CommonProxy;
use Doctrine\Persistence\Proxy;
use ReflectionProperty;
use ReturnTypeWillChange;

use function ltrim;
use function method_exists;

/**
 * PHP Runtime Reflection Property.
 *
 * Avoids triggering lazy loading if the provided object
 * is a {@see \Doctrine\Persistence\Proxy}.
 */
class RuntimeReflectionProperty extends ReflectionProperty
{
    /** @var string */
    private $key;

    /** @param class-string $class */
    public function __construct(string $class, string $name)
    {
        parent::__construct($class, $name);

        $this->key = $this->isPrivate() ? "\0" . ltrim($class, '\\') . "\0" . $name : ($this->isProtected() ? "\0*\0" . $name : $name);
    }

    /**
     * {@inheritDoc}
     *
     * @return mixed
     */
    #[ReturnTypeWillChange]
    public function getValue($object = null)
    {
        if ($object === null) {
            return parent::getValue($object);
        }

        return ((array) $object)[$this->key] ?? null;
    }

    /**
     * {@inheritDoc}
     *
     * @param object|null $object
     * @param mixed       $value
     *
     * @return void
     */
    #[ReturnTypeWillChange]
    public function setValue($object, $value = null)
    {
        if (! ($object instanceof Proxy && ! $object->__isInitialized())) {
            parent::setValue($object, $value);

            return;
        }

        if ($object instanceof CommonProxy) {
            $originalInitializer = $object->__getInitializer();
            $object->__setInitializer(null);

            parent::setValue($object, $value);

            $object->__setInitializer($originalInitializer);

            return;
        }

        if (! method_exists($object, '__setInitialized')) {
            return;
        }

        $object->__setInitialized(true);

        parent::setValue($object, $value);

        $object->__setInitialized(false);
    }
}