symfony 3控制器中的自定义注释

问题描述 投票:9回答:2

所以问题非常简单。我的控制器中的代码已经变得冗余,我决定为它做一个注释。

if (!$request->getContentType() === 'json' ) {
        return new JsonResponse(array('success' => false));
    }
    $content = $request->getContent();

    if(empty($content)){
        throw new BadRequestHttpException("Content is empty");
    }
    $data = json_decode($content, true);
    if(empty($data) || !array_key_exists('type', $data)) {
        return new JsonResponse(array('success' => false));
    }

如何制作自定义注释@CheckRequest,我可以使用$ request对象作为参数?

php symfony annotations doctrine
2个回答
9
投票

您需要创建一个自定义注释,然后是一个注入注释阅读器并处理kernel.controller事件的侦听器:

注解

/**
 * @Annotation
 */
class CheckRequest
{
}

服务定义

services:
    controller_check_request:
        class: AppBundle\EventListener\ControllerCheckRequestListener
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController}
        arguments:
            - "@annotation_reader"

监听器:

namespace AppBundle\EventListener;

use AppBundle\Annotation\CheckRequest;
use Doctrine\Common\Annotations\Reader;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

class ControllerCheckRequestListener
{
    /** @var Reader */
    private $reader;

    /**
     * @param Reader $reader
     */
    public function __construct(Reader $reader)
    {
        $this->reader = $reader;
    }

    /**
     * {@inheritdoc}
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        if (!is_array($controllers = $event->getController())) {
            return;
        }

        $request = $event->getRequest();
        $content = $request->getContent();

        list($controller, $methodName) = $controllers;

        $reflectionClass = new \ReflectionClass($controller);
        $classAnnotation = $this->reader
            ->getClassAnnotation($reflectionClass, CheckRequest::class);

        $reflectionObject = new \ReflectionObject($controller);
        $reflectionMethod = $reflectionObject->getMethod($methodName);
        $methodAnnotation = $this->reader
            ->getMethodAnnotation($reflectionMethod, CheckRequest::class);

        if (!($classAnnotation || $methodAnnotation)) {
            return;
        }

        if ($request->getContentType() !== 'json' ) {
            return $event->setController(
                function() {
                    return new JsonResponse(['success' => false]);
                }
            );
        }

        if (empty($content)) {
            throw new BadRequestHttpException('Content is empty');
        }

        $data = json_decode($content, true);

        if ($request->getContentType() !== 'json' ) {
            return $event->setController(
                function() {
                    return new JsonResponse(['success' => false]);
                }
            );
        }
    }
}

请注意,不是返回响应,而是使用$event->setController();设置整个控制器,并且在进行该调用时也必须使用return

然后在您的控制器中,您可以在整个类中设置它:

use AppBundle\Annotation\CheckRequest;

/**
 * @CheckRequest
 */
class YourController extends Controller
{
}

或个别方法/行动:

use AppBundle\Annotation\CheckRequest;

class TestController extends Controller
{
    /**
     * @Route("/", name="index")
     * @CheckRequest
     */
    public function indexAction(Request $request)
    {
        // ...
    }
}

0
投票

对于Symfony 3.4。*

public function onKernelController(FilterControllerEvent $event){

    if (!is_array($controllers = $event->getController())) {
        return;
    }

    list($controller, $methodName) = $controllers;

    $reflectionClass = new \ReflectionClass($controller);

    // Controller
    $reader = new \Doctrine\Common\Annotations\AnnotationReader();
    $classAnnotation = $reader->getClassAnnotation($reflectionClass, AnnotationClass::class);

    // Method
    $reflectionMethod = $reflectionClass->getMethod($methodName);
    $methodAnnotation = $reader->getMethodAnnotation($reflectionMethod, AnnotationClass::class);

    if(!($classAnnotation || $methodAnnotation)){
        return;
    }

    /** TODO CODE HERE **/
}
© www.soinside.com 2019 - 2024. All rights reserved.