如何禁用param转换器中的doctrine过滤器

时间:2015-07-31 18:34:17

标签: symfony doctrine-orm doctrine-extensions

我在项目中使用doctrine softdeleteable扩展,并将控制器操作设置为这样。

/**
 * @Route("address/{id}/")
 * @Method("GET")
 * @ParamConverter("address", class="MyBundle:Address")
 * @Security("is_granted('view', address)")
 */
public function getAddressAction(Address $address)
{

如果删除了对象,它返回NotFound时效果很好,但是我想授予具有ROLE_ADMIN的用户访问权限,以便能够看到软删除的内容。

是否已经有办法让param转换器禁用过滤器,或者我是否必须创建自己的自定义参数转换器?

1 个答案:

答案 0 :(得分:1)

没有现成的方法,但我通过创建自己的注释解决了这个问题,在my $updateQuery - //UPDATE query if(//updateQuery has effected rows){ //send mail }else //do nothing 完成工作之前禁用了softdeleteable过滤器。

AcmeBundle /注释/ IgnoreSoftDelete.php:

ParamConverter

AcmeBundle /事件监听/ AnnotationListener.php:

namespace AcmeBundle\Annotation;

use Doctrine\Common\Annotations\Annotation;

/**
 * @Annotation
 * @Target({"CLASS", "METHOD"})
 */
class IgnoreSoftDelete extends Annotation { }

AcmeBundle /资源/配置/ services.yml:

namespace AcmeBundle\EventListener;

use Doctrine\Common\Util\ClassUtils;
use Doctrine\Common\Annotations\Reader;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class AnnotationListener {

    protected $reader;

    public function __construct(Reader $reader) {
        $this->reader = $reader;
    }

    public function onKernelController(FilterControllerEvent $event) {
        if (!is_array($controller = $event->getController())) {
            return;
        }

        list($controller, $method, ) = $controller;

        $this->ignoreSoftDeleteAnnotation($controller, $method);
    }

    private function readAnnotation($controller, $method, $annotation) {
        $classReflection = new \ReflectionClass(ClassUtils::getClass($controller));
        $classAnnotation = $this->reader->getClassAnnotation($classReflection, $annotation);

        $objectReflection = new \ReflectionObject($controller);
        $methodReflection = $objectReflection->getMethod($method);
        $methodAnnotation = $this->reader->getMethodAnnotation($methodReflection, $annotation);

        if (!$classAnnotation && !$methodAnnotation) {
            return false;
        }

        return [$classAnnotation, $classReflection, $methodAnnotation, $methodReflection];
    }

    private function ignoreSoftDeleteAnnotation($controller, $method) {
        static $class = 'AcmeBundle\Annotation\IgnoreSoftDelete';

        if ($this->readAnnotation($controller, $method, $class)) {
            $em = $controller->get('doctrine.orm.entity_manager');
            $em->getFilters()->disable('softdeleteable');
        }
    }

}

AcmeBundle /控制器/ DefaultController.php:

services:
    acme.annotation_listener:
        class: AcmeBundle\EventListener\AnnotationListener
        arguments: [@annotation_reader]
        tags:
            - { name: kernel.event_listener, event: kernel.controller }

注释可以应用于单个操作方法和整个控制器类。