Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace User\Acl;
- use Zend\Cache\Storage\Adapter\Filesystem;
- use Zend\Permissions\Acl\Acl;
- class Service
- {
- protected $role = 'guest';
- protected $config = array();
- protected $cache = null;
- protected $acl = null;
- protected $cacheKey = 'application_acl';
- public function __construct($role = 'guest', array $config, Filesystem $cache)
- {
- $this->setRole($role);
- $this->setConfig($config);
- $this->setCache($cache);
- $this->acl = $this->factory();
- }
- public function getRole()
- {
- return $this->role;
- }
- public function setRole($role)
- {
- $this->role = $role;
- return $this;
- }
- public function getConfig()
- {
- return $this->config;
- }
- public function setConfig(array $config)
- {
- $this->config = $config;
- return $this;
- }
- public function getCache()
- {
- return $this->cache;
- }
- public function setCache(Filesystem $cache)
- {
- $this->cache = $cache;
- return $this;
- }
- public function getAcl()
- {
- return $this->acl;
- }
- public function setAcl(Acl $acl)
- {
- $this->acl = $acl;
- return $this;
- }
- public function factory()
- {
- // try to read acl from cache
- $acl = $this->getCache()->getItem($this->cacheKey);
- // check cache
- if (!$acl) {
- // create acl
- $acl = new Acl();
- // loop through role data
- foreach ($this->config as $role => $resources) {
- // check for role
- if (!$acl->hasRole($role)) {
- $acl->addRole($role);
- }
- // loop through resource data
- foreach ($resources as $resource => $rules) {
- // check for resource
- if (!$acl->hasResource($resource)) {
- $acl->addResource($resource);
- }
- // loop trough rules
- foreach ($rules as $rule => $privileges)
- {
- // add rule with privileges
- $acl->$rule($role, $resource, $privileges);
- }
- }
- }
- // store in cache
- $this->getCache()->setItem($this->cacheKey, $acl);
- }
- // pass acl
- return $acl;
- }
- public function isAllowed($resource, $privilege)
- {
- // check resource
- if (empty($resource) || !$this->getAcl()->hasResource($resource)) {
- return false;
- }
- // check privilege
- if (empty($privilege)) {
- return false;
- }
- // check acl
- return $this->getAcl()->isAllowed($this->getRole(), $resource, $privilege);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement