<?php
namespace Jbi\CoreBundle\Security\Acl\Domain;
use Symfony\Component\Security\Acl\Exception\InvalidDomainObjectException;
use Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Doctrine\ORM\EntityManager;
/**
* Strategy to be used for retrieving object identities from domain objects
* where the domain object may be a Doctrine proxy.
*/
class ObjectIdentityRetrievalStrategy implements ObjectIdentityRetrievalStrategyInterface
{
/**
* @var \Doctrine\ORM\EntityManager $em
*/
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
/**
* {@inheritDoc}
*/
public function getObjectIdentity($domainObject)
{
try {
if ($domainObject instanceof \Doctrine\ORM\Proxy\Proxy) {
return $this->fromDomainObject($domainObject);
}
return ObjectIdentity::fromDomainObject($domainObject);
} catch (InvalidDomainObjectException $failed) {
return null;
}
}
private function fromDomainObject($domainObject)
{
if (!is_object($domainObject)) {
throw new InvalidDomainObjectException('$domainObject must be an object.');
}
try {
if ($domainObject instanceof DomainObjectInterface) {
return new ObjectIdentity($domainObject->getObjectIdentifier(), $this->em->getClassMetadata(get_class($domainObject))->getName());
} elseif (method_exists($domainObject, 'getId')) {
return new ObjectIdentity($domainObject->getId(), $this->em->getClassMetadata(get_class($domainObject))->getName());
}
} catch (\InvalidArgumentException $invalid) {
throw new InvalidDomainObjectException($invalid->getMessage(), 0, $invalid);
}
throw new InvalidDomainObjectException('$domainObject must either implement the DomainObjectInterface, or have a method named "getId".');
}
}
Thank you. I mentioned your post here: http://stackoverflow.com/questions/7476552/doctrine-2-proxy-classes-breaking-symfony2-acl
Nice catch! We’ll use it in production soon :p.
Thank you very much for sharing this!
I just wonder why is this not part of Symfony’s core already?
I really like Symfony, but more I get deep in it more I find odd things, like not being able to handle form errors in a controller if you don’t set the option ‘error_bubbling’ to true to every field of the form type.
Some things are expected and are really annoying when you find yourself stucked for this kind of nonsense.