Skip to content

Instantly share code, notes, and snippets.

@oziks
Created December 30, 2013 10:30
Show Gist options
  • Save oziks/8180382 to your computer and use it in GitHub Desktop.
Save oziks/8180382 to your computer and use it in GitHub Desktop.
<?php
namespace M6\Helpers\Bundle\ORMBundle\Repository;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
/**
* Repository class
*/
class Repository extends EntityRepository
{
/**
* Gets the name of the primary table.
*
* @return string
*/
protected function getTableName()
{
return $this
->getClassMetadata()
->getTableName();
}
/**
* Create and contextualized a query builder.
*
* @param SecurityContextInterface $context
*
* @return QueryBuilder
*/
protected function contextualizedQuery(SecurityContextInterface $context)
{
$queryBuilder = $this->createQueryBuilder('Query');
$config = $context->getToken()->getUser()->getConfigEntities();
// validate the active field
if (!empty($config[$this->getTableName()]['active'])) {
$queryBuilder
->andWhere('Query.active = :active')
->setParameter('active', true);
}
// validate the publications fields
if (!empty($config[$this->getTableName()]['publication'])) {
$queryBuilder
->andWhere('Query.publishedAt <= :published_at')
->andWhere('Query.unpublishedAt > :unpublished_at')
->setParameter('published_at', new \DateTime())
->setParameter('unpublished_at', new \DateTime());
}
return $queryBuilder;
}
/**
* Finds an entities with security context.
*
* @param SecurityContextInterface $context
* @param integer $id
*
* @return object|array The entity instance or the entities collection
*/
public function findWithContext(SecurityContextInterface $context, array $criteria = [], array $orderBy = null, $limit = null, $offset = 0)
{
$queryBuilder = $this->contextualizedQuery($context);
if ($criteria) {
foreach ($criteria as $field => $value) {
$queryBuilder
->andWhere(sprintf('Query.%s = :%s', $field, $field))
->setParameter($field, $value);
}
}
if ($orderBy) {
foreach ($orderBy as $field => $order) {
$queryBuilder
->orderBy(sprintf('Query.%s', $field), $order);
}
}
if ($limit > 0) {
$queryBuilder->setMaxResults($limit);
}
$queryBuilder->setFirstResult($offset);
if (array_key_exists('id', $criteria)) {
return $queryBuilder
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
}
return $queryBuilder
->getQuery()
->getResult();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment