Created
August 21, 2012 04:04
-
-
Save lavoiesl/3411401 to your computer and use it in GitHub Desktop.
Workaround for circular dependency in Symfony2 services
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Acme\SiteBundle\Listener; | |
use Doctrine\ORM\Event\LifecycleEventArgs; | |
use Acme\SiteBundle\Entity\Comment; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
use Symfony\Component\Security\Acl\Domain\ObjectIdentity; | |
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity; | |
use Symfony\Component\Security\Acl\Permission\MaskBuilder; | |
use Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException; | |
class CommentsAcl | |
{ | |
private $container; | |
/** | |
* Inject the whole container because otherwise we would have a circular dependency | |
* DBAL -> ORM -> EventManager -> ACL Provider | |
* @link https://groups.google.com/d/topic/symfony2/MreLJgfnn_U/discussion | |
*/ | |
public function __construct(ContainerInterface $container) | |
{ | |
$this->container = $container; | |
} | |
public function postPersist(LifecycleEventArgs $args) | |
{ | |
$entity = $args->getEntity(); | |
$aclProvider = $this->container->get('security.acl.provider'); | |
if ($entity instanceof Comment) { | |
// Add operator rights to target so it can manage the comments on his person | |
if (($person = $entity->getTarget()) && ($user = $person->getUser())) { | |
$securityIdentity = UserSecurityIdentity::fromAccount($user); | |
$objectIdentity = ObjectIdentity::fromDomainObject($entity); | |
try { | |
$acl = $aclProvider->createAcl($objectIdentity); | |
} catch (AclAlreadyExistsException $e) { | |
$acl = $aclProvider->findAcl($objectIdentity); | |
} | |
$acl->insertObjectAce($securityIdentity, MaskBuilder::MASK_OPERATOR); | |
} | |
$aclProvider->updateAcl($acl); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
acme.listener.acl.comments: | |
class: Acme\SiteBundle\Listener\CommentsAcl | |
arguments: [ @service_container ] | |
tags: | |
- { name: doctrine.event_listener, event: postPersist } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment