Skip to content

Instantly share code, notes, and snippets.

@lashae
Created August 28, 2015 08:36
Show Gist options
  • Save lashae/d65cae0e61a51c0b9baa to your computer and use it in GitHub Desktop.
Save lashae/d65cae0e61a51c0b9baa to your computer and use it in GitHub Desktop.
Sf2 custom annotation
<?php
namespace AppBundle\Annotations;
/**
* @Annotation
*/
class AllowedUser
{
public $group;
}
<?php
namespace AppBundle\Annotations\Driver;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class AnnotationDriver
{
/**
* @var \Doctrine\Common\Annotations\Reader
*/
private $reader;
public function __construct($reader)
{
$this->reader = $reader;
}
public function onKernelController(FilterControllerEvent $event)
{
//Skip controllers of anonymous function (closure) type.
if (!is_array($currentController = $event->getController())) {
return;
}
$customAnnotationClass = 'AppBundle\Annotations\AllowedUser';
list($currentControllerInstance, $currentMethodName) = $currentController;
$object = new \ReflectionObject($currentControllerInstance);
$method = $object->getMethod($currentMethodName);
$annotation = $this->reader->getMethodAnnotation($method, $customAnnotationClass);
if(!is_null($annotation)) {
$group = $annotation->group;
/*
* $group = ['group' => 'managers']
*/
}
}
}
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AppBundle\Annotations\AllowedUser;
class MyController extends Controller
{
/**
* @AllowedUser(group="managers")
*/
public function promoteStaffAction()
{
//...
}
services:
app_bundle_annotation_driver:
class: AppBundle\Annotations\Driver\AnnotationDriver
tags:
- {name: kernel.event_listener, event: kernel.controller, method: onKernelController}
arguments: [@annotation_reader]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment