phpro / zf-doctrine-hydration-module

Configurable Doctrine hydrators for ZF2
18 stars 33 forks source link

Embed Field Extraction Fails When Not Set #29

Closed matwright closed 8 years ago

matwright commented 8 years ago

I have encountered a bug when an object is extracted that has at least one embed field that is either null or does not exist in the database (mongo).

The problem arises because the extract() method within the EmbeddedField Strategy class accepts a value of mixed type, however the Doctrine Hydrator extract() method that is subsequently called requires an object. Unfortunately the type is never tested and ends up in a get_class function call, as the value is NULL when not set in the DB, the get_class function call returns the name of the current class and exceptions are eventually thrown much further down the line.

EmbeddedField :

/**
     * @param mixed $value
     *
     * @return mixed
     */
    public function extract($value)
    {
        $hydrator = $this->getDoctrineHydrator();
        return $hydrator->extract($value);
    } 

https://github.com/phpro/zf-doctrine-hydration-module/blob/master/src/Hydrator/ODM/MongoDB/Strategy/EmbeddedField.php#L12

Note that the param annotation is mixed however the DoctrineHydrator class requires an object to its extract() method :

 /**
     * Extract values from an object
     *
     * @param  object $object
     * @return array
     */
    public function extract($object)
    {
        $this->prepare($object);

        if ($this->byValue) {
            return $this->extractByValue($object);
        }

        return $this->extractByReference($object);
    }

https://github.com/phpro/zf-doctrine-hydration-module/blob/master/src/Hydrator/DoctrineHydrator.php#L50

I have added a test case below, where the embed one is never set. This test fails because of an exception due to the non object value.

https://github.com/matwright/zf-doctrine-hydration-module/blob/hotfix/test-case-to-demonstrate-embed-field-break-when-not-set/test/src/Tests/Hydrator/ODM/MongoDB/Strategy/EmbeddedFieldTest.php#L26

I think the extract in the embed field strategy should either throw an exception or handle non objects by returning the same given value.

veewee commented 8 years ago

Fixed in #30 and #31.