Skip to content

Instantly share code, notes, and snippets.

@lopsided
Created January 27, 2015 11:24
Show Gist options
  • Save lopsided/b32c819d7bf4edeea00a to your computer and use it in GitHub Desktop.
Save lopsided/b32c819d7bf4edeea00a to your computer and use it in GitHub Desktop.
Soft deleteable filter
# Doctrine Configuration
doctrine:
orm:
filters:
softdeleteable:
class: Acme\MyBundle\ORM\Filter\SoftDeleteableFilter
enabled: true
<?php
/**
* This is an adaptation of the same filter used in the Doctrine2 Behaviours package found here:
* https://github.com/Atlantic18/DoctrineExtensions
*
* It is a simplified filter made for use with the KnpLabs Doctrine Behaviours package found here:
* https://github.com/KnpLabs/DoctrineBehaviors
* (as this package doesn't include a filter)
*
* All credit for this goes to
*
* @author Gustavo Falco <[email protected]>
* @author Gediminas Morkevicius <[email protected]>
* @author Patrik Votoček <[email protected]>
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*
* Adaptation of this filter:
* https://github.com/Atlantic18/DoctrineExtensions/blob/master/lib/Gedmo/SoftDeleteable/Filter/SoftDeleteableFilter.php
*/
namespace Acme\MyBundle\ORM\Filter;
use Doctrine\ORM\Mapping\ClassMetaData;
use Doctrine\ORM\Query\Filter\SQLFilter;
class SoftDeleteableFilter extends SQLFilter
{
protected $entityManager;
protected $disabled = array();
/**
* Add the soft deletable filter
*
* @param ClassMetaData $targetEntity
* @param $targetTableAlias
* @return string
*/
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
$class = $targetEntity->getName();
if (array_key_exists($class, $this->disabled) && $this->disabled[$class] === true) {
return '';
} elseif (
array_key_exists($targetEntity->rootEntityName, $this->disabled)
&& $this->disabled[$targetEntity->rootEntityName] === true
) {
return '';
} elseif (!$targetEntity->hasField('deletedAt')) {
return '';
}
$conn = $this->getEntityManager()->getConnection();
$platform = $conn->getDatabasePlatform();
$column = $targetEntity->getQuotedColumnName('deletedAt', $platform);
$addCondSql = $platform->getIsNullExpression($targetTableAlias.'.'.$column);
return $addCondSql;
}
protected function getEntityManager()
{
if ($this->entityManager === null) {
$refl = new \ReflectionProperty('Doctrine\ORM\Query\Filter\SQLFilter', 'em');
$refl->setAccessible(true);
$this->entityManager = $refl->getValue($this);
}
return $this->entityManager;
}
public function disableForEntity($class)
{
$this->disabled[$class] = true;
}
public function enableForEntity($class)
{
$this->disabled[$class] = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment