Security.php in Bamboo Twig 8
File
bamboo_twig_security/src/TwigExtension/Security.php
View source
<?php
namespace Drupal\bamboo_twig_security\TwigExtension;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class Security extends \Twig_Extension {
protected $currentUser;
protected $userStorage;
public function __construct(AccountInterface $currentUser, EntityTypeManagerInterface $entity) {
$this->currentUser = $currentUser;
$this->userStorage = $entity
->getStorage('user');
}
public function getFunctions() {
return [
new \Twig_SimpleFunction('get_current_user', [
$this,
'getCurrentUser',
]),
new \Twig_SimpleFunction('has_permission', [
$this,
'hasPermission',
]),
new \Twig_SimpleFunction('has_role', [
$this,
'hasRole',
]),
];
}
public function getName() {
return 'bamboo_twig.twig.security';
}
public function getCurrentUser($user = NULL) {
if ($this->currentUser
->isAnonymous()) {
return NULL;
}
return $this->userStorage
->load($this->currentUser
->id());
}
public function hasPermission($permission, $user = NULL) {
if (is_null($user) && $this->currentUser
->isAnonymous()) {
return NULL;
}
$user_id = $this->currentUser
->id();
if (!is_null($user) && is_int($user)) {
$user_id = $user;
}
$account = $this->userStorage
->load($user_id);
if (!$account) {
return NULL;
}
return $account
->hasPermission($permission);
}
public function hasRole($role, $user = NULL) {
if (is_null($user) && $this->currentUser
->isAnonymous()) {
return NULL;
}
$user_id = $this->currentUser
->id();
if (!is_null($user) && is_int($user)) {
$user_id = $user;
}
$account = $this->userStorage
->load($user_id);
if (!$account) {
return NULL;
}
return $account
->hasRole($role);
}
}
Classes
Name |
Description |
Security |
Provides a 'Security' Twig Extensions. |