Custom annotation in symfony 3 controller

Viewed 6916

So the question is pretty straightforward. I have a code in my controller that has became redundant, and i've decided to make the 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 do i make custom annotation @CheckRequest in which I can use the $request object as a parameter?

2 Answers

For 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 **/
}
Related