Skip to content

Instantly share code, notes, and snippets.

@msonnabaum
Created March 20, 2013 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msonnabaum/5207807 to your computer and use it in GitHub Desktop.
Save msonnabaum/5207807 to your computer and use it in GitHub Desktop.
<?php
namespace Drupal\Core\Routing;
use Drupal\Core\Access\AccessCheckInterface;
use Drupal\Core\Entity\EntityInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Tests\UnitTestCase;
class EntityAccessCheck implements AccessCheckInterface {
/**
* Implements \Drupal\Core\Access\AccessCheckInterface::applies().
*/
public function applies(Route $route) {
return array_key_exists('_access_entity', $route->getRequirements());
}
/**
* Implements \Drupal\Core\Access\AccessCheckInterface::access().
*
* The value of the '_access_entity' key must be in the pattern
* 'slug.operation.' The slug corresponds to the named param {slug}.
* This will check a node for 'update' access:
* @code
* pattern: '/foo/{node}/bar'
* requirements:
* _access_entity: 'node.update'
* @endcode
*/
public function access(Route $route, Request $request) {
$requirements = $route->getRequirements();
// Split up the slug and the operation.
list($slug, $operation) = explode('.', $requirements['_access_entity']);
// If this slug is in the request, and it is an entity, check its access.
if ($request->attributes->has($slug)) {
$entity = $request->attributes->get($slug);
if ($entity instanceof EntityInterface) {
return $entity->access($operation);
}
}
}
}
class EntityAccessCheckTest extends UnitTestCase {
function testApplies() {
$e = new EntityAccessCheck();
$route = $this->getMockBuilder('Symfony\Component\Routing\Route')
->disableOriginalConstructor()
->getMock();
$route->expects($this->any())
->method('getRequirements')
->will($this->returnValue(array('_access_entity' => '')));
$res = $e->applies($route);
$this->assertEquals(TRUE, $res);
$route = $this->getMockBuilder('Symfony\Component\Routing\Route')
->disableOriginalConstructor()
->getMock();
$route->expects($this->any())
->method('getRequirements')
->will($this->returnValue(array()));
$res = $e->applies($route);
$this->assertEquals(FALSE, $res);
}
function testAccess() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment