By dawehner on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Issue links:
Description:
Some access checkers does not really make sense to be reused outside of a single route.
One good example is some really specific access checker of the toolbar module:
/**
* @file
* Contains \Drupal\toolbar\Access\SubtreeAccess.
*/
namespace Drupal\toolbar\Access;
use Drupal\Core\Access\StaticAccessCheckInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;
use Drupal\Core\Session\AccountInterface;
/**
* Defines a special access checker for the toolbar subtree route.
*/
class SubtreeAccess implements StaticAccessCheckInterface {
/**
* {@inheritdoc}
*/
public function appliesTo() {
return array('_access_toolbar_subtree');
}
/**
* {@inheritdoc}
*/
public function access(Route $route, Request $request, AccountInterface $account) {
$hash = $request->get('hash');
return ($account->hasPermission('access toolbar') && ($hash == _toolbar_get_subtrees_hash())) ? static::ALLOW : static::DENY;
}
}
For these cases you can specify a controller like method on the routing definition:
toolbar.subtrees:
path: '/toolbar/subtrees/{hash}'
defaults:
_controller: '\Drupal\toolbar\Routing\ToolbarController::subtreesJsonp'
requirements:
_custom_access: '\Drupal\toolbar\Routing\ToolbarController::checkSubTreeAccess'
and add the method directly on the other controller:
class ToolbarController extends ControllerBase {
/**
* Checks access for the subtree controller.
*/
public function checkSubTreeAccess(Request $request) {
$hash = $request->get('hash');
return ($this->currentUser()->hasPermission('access toolbar') && ($hash == _toolbar_get_subtrees_hash())) ? AccessInterface::ALLOW : AccessInterface::DENY;
}
}
Impacts:
Module developers