Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Role.php
Go to the documentation of this file.
1 <?php
7 
12 
13 class Role implements \Magento\Framework\Acl\LoaderInterface
14 {
18  const ACL_ROLES_CACHE_KEY = 'authorization_role_cached_data';
19 
23  protected $_resource;
24 
28  protected $_groupFactory;
29 
33  protected $_roleFactory;
34 
38  private $aclDataCache;
39 
43  private $serializer;
44 
48  private $cacheKey;
49 
58  public function __construct(
59  \Magento\Authorization\Model\Acl\Role\GroupFactory $groupFactory,
60  \Magento\Authorization\Model\Acl\Role\UserFactory $roleFactory,
61  \Magento\Framework\App\ResourceConnection $resource,
62  \Magento\Framework\Acl\Data\CacheInterface $aclDataCache = null,
63  Json $serializer = null,
64  $cacheKey = self::ACL_ROLES_CACHE_KEY
65  ) {
66  $this->_resource = $resource;
67  $this->_groupFactory = $groupFactory;
68  $this->_roleFactory = $roleFactory;
69  $this->aclDataCache = $aclDataCache ?: ObjectManager::getInstance()->get(
70  \Magento\Framework\Acl\Data\CacheInterface::class
71  );
72  $this->serializer = $serializer ?: ObjectManager::getInstance()->get(Json::class);
73  $this->cacheKey = $cacheKey;
74  }
75 
82  public function populateAcl(\Magento\Framework\Acl $acl)
83  {
84  foreach ($this->getRolesArray() as $role) {
85  $parent = $role['parent_id'] > 0 ? $role['parent_id'] : null;
86  switch ($role['role_type']) {
87  case RoleGroup::ROLE_TYPE:
88  $acl->addRole($this->_groupFactory->create(['roleId' => $role['role_id']]), $parent);
89  break;
90 
91  case RoleUser::ROLE_TYPE:
92  if (!$acl->hasRole($role['role_id'])) {
93  $acl->addRole($this->_roleFactory->create(['roleId' => $role['role_id']]), $parent);
94  } else {
95  $acl->addRoleParent($role['role_id'], $parent);
96  }
97  break;
98  }
99  }
100  }
101 
107  private function getRolesArray()
108  {
109  $rolesCachedData = $this->aclDataCache->load($this->cacheKey);
110  if ($rolesCachedData) {
111  return $this->serializer->unserialize($rolesCachedData);
112  }
113 
114  $roleTableName = $this->_resource->getTableName('authorization_role');
115  $connection = $this->_resource->getConnection();
116 
117  $select = $connection->select()
118  ->from($roleTableName)
119  ->order('tree_level');
120 
121  $rolesArray = $connection->fetchAll($select);
122  $this->aclDataCache->save($this->serializer->serialize($rolesArray), $this->cacheKey);
123  return $rolesArray;
124  }
125 }
$resource
Definition: bulk.php:12
$groupFactory
populateAcl(\Magento\Framework\Acl $acl)
Definition: Role.php:82
__construct(\Magento\Authorization\Model\Acl\Role\GroupFactory $groupFactory, \Magento\Authorization\Model\Acl\Role\UserFactory $roleFactory, \Magento\Framework\App\ResourceConnection $resource, \Magento\Framework\Acl\Data\CacheInterface $aclDataCache=null, Json $serializer=null, $cacheKey=self::ACL_ROLES_CACHE_KEY)
Definition: Role.php:58
$connection
Definition: bulk.php:13