Skip to content

Instantly share code, notes, and snippets.

@coma
Created February 10, 2013 10:59
Show Gist options
  • Save coma/4749233 to your computer and use it in GitHub Desktop.
Save coma/4749233 to your computer and use it in GitHub Desktop.
service injection in repo
<?php
namespace Comakai\TicketsBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Comakai\TicketsBundle\Entity\User;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\Security\Core\SecurityContext;
class ProjectRepository extends EntityRepository
{
/** @var \Symfony\Component\Security\Core\SecurityContext */
private $securityContext;
/**
* @DI\InjectParams({
* "securityContext" = @DI\Inject("security.context"),
* })
*/
public function setSecurityContext(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
public function findAllForUser()
{
if ($this->securityContext->isGranted('ROLE_ADMIN')) {
return $this->findAll();
}
return $this
->createQueryBuilder('a')
->join('a.users', 'b')
->where('b = :user')
->setParameter('user', $this->securityContext->getToken()->getUser())
->getQuery()
->getResult();
}
public function findOneForUser()
{
$qb = $this->createQueryBuilder('a')->setMaxResults(1);
if ($this->securityContext->isGranted('ROLE_ADMIN')) {
return $qb->getQuery()->getOneOrNullResult();
}
return $qb
->join('a.users', 'b')
->where('b = :user')
->setParameter('user', $this->securityContext->getToken()->getUser())
->getQuery()
->getOneOrNullResult();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment