Custom annotation in symfony 3 controller

So the question is pretty simple. I have code in my controller that has become redundant, and I decided to make an annotation for it.

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));
    }

How to create a custom @CheckRequest annotation in which I can use the $ request object as a parameter?

+4
source share
1 answer

You need to create a custom annotation, and then a listener that enters the annotation reader and handles the kernel.controller event :

annotation

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

Service Definition

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

LISTENER:

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)
    {
        // ...
    }
}
+5

Source: https://habr.com/ru/post/1683444/


All Articles