Skip to content

"Object could not be converted to string" in UniqueEntityValidator with foreign primary keys #21274

Closed
@marcverney

Description

@marcverney
Q A
Bug report? yes
Feature request? no
BC Break report? no
RFC? no
Symfony version 3.1.2

tl;dr

The UniqueEntityValidator makes the wrong assumption that Doctrine's ClassMetaData::getIdentifierValues() can only return scalars:

implode(', ', $class->getIdentifierValues($entity))

Therefore, it crashes when the returned identifiers are objects (associated entities).

Details

When the DoctrineBridge UniqueEntityValidator encounters a non unique value, it builds a constraint violation with it. In case this value is not castable to a string it tries to build one itself:

if (is_object($invalidValue) && !method_exists($invalidValue, '__toString')) {
    $invalidValue = sprintf('Object of class "%s" identified by "%s"', get_class($entity), implode(', ', $class->getIdentifierValues($entity)));
}

If the entity's identifiers are associations (for example a Friendship entity with the two users as composite PK), $class->getIdentifierValues($entity) returns those entities. If they don't have any __toString() method either, the implode() function can't execute and it errors out with the following message:

Error: Object of class [...] could not be converted to string

Not sure what the complete value should be anyway. Recursing one level would produce a rather convoluted string...:

Object of class Acme\AppBundle\Entity\Friendship identified by object of class Acme\AppBundle\Entity\User identified by 123, object of class Acme\AppBundle\Entity\User identified by 456

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions