laminas/laminas-hydrator

ReflectionHydrator is hard to extend due to the use of self::.

ianef opened this issue · 0 comments

ianef commented

Bug Report

I have written a hydrator that hydrates Doctrine entities from arrays and the Request object. It also handles associations within the entity, and nested associations within that. It uses Reflection to determine the target type from property types, type hints, and @var annotations.

When hydrating associations, Doctrine returns a Proxy class which inherits from the entity class we are working with. The problem is that the ReflectionHydrator uses ReflectionClass to obtain the properties of the object, but this does not return the properties of the base entity class which are marked as private, just the immediate properties of the Proxy class.

I have tried to extend ReflectionHydrator and override getReflProperties() so that I can use the parent class reflection for proxy entities, but that does not work as calls to getReflProperties are made using the self operator.

I am proposing replacing the use of self:: with static:: in method calls so that extended methods will use the overridden getReflProperties method I need to customise.

Q A
Version(s) 4.5.0 - 4.14.0

Summary

Extending ReflectionHydrator to override getReflProperties for custom ReflectionClass handling does not work as expected because calls to this method within ReflectionHydrator are made using self::.

Current behavior

Code in the extended ReflectionHydrator ::getReflProperties method is not called from the hydrate() or extract() methods.

Expected behavior

Code in the extended ReflectionHydrator ::getReflProperties method should be called from the hydrate() and extract() methods.

Suggested fix

    /**
     * Extract values from an object
     *
     * {@inheritDoc}
     */
    public function extract(object $object): array
    {
        $result = [];
        foreach (static::getReflProperties($object) as $property) {
            $propertyName = $this->extractName($property->getName(), $object);
            if (! $this->getCompositeFilter()->filter($propertyName)) {
                continue;
            }

            $value                 = $property->getValue($object);
            $result[$propertyName] = $this->extractValue($propertyName, $value, $object);
        }

        return $result;
    }

    /**
     * Hydrate $object with the provided $data.
     *
     * {@inheritDoc}
     */
    public function hydrate(array $data, object $object)
    {
        $reflProperties = static::getReflProperties($object);
        foreach ($data as $key => $value) {
            $name = $this->hydrateName($key, $data);
            if (isset($reflProperties[$name])) {
                $reflProperties[$name]->setValue($object, $this->hydrateValue($name, $value, $data));
            }
        }
        return $object;
    }