How to change role hierarchy storage in Symfony2?

前端 未结 6 1244
醉话见心
醉话见心 2020-12-22 21:32

In my project I need to store role hierarchy in database and create new roles dynamically. In Symfony2 role hierarchy is stored in security.yml by default. What

6条回答
  •  长情又很酷
    2020-12-22 22:07

    Since role hierarchy don't change often, this a quick class to cache to memcached.

    hierarchy = $hierarchy;
    
            $roleMap = $memcache->get('roleMap');
    
            if ($roleMap) {
                $this->map = unserialize($roleMap);
            } else {
                $this->buildRoleMap();
                // cache to memcache
                $memcache->set('roleMap', serialize($this->map));
            }
        }
    
        /**
         * {@inheritdoc}
         */
        public function getReachableRoles(array $roles)
        {
            $reachableRoles = $roles;
            foreach ($roles as $role) {
                if (!isset($this->map[$role->getRole()])) {
                    continue;
                }
    
                foreach ($this->map[$role->getRole()] as $r) {
                    $reachableRoles[] = new Role($r);
                }
            }
    
            return $reachableRoles;
        }
    
        protected function buildRoleMap()
        {
            $this->map = array();
            foreach ($this->hierarchy as $main => $roles) {
                $this->map[$main] = $roles;
                $visited = array();
                $additionalRoles = $roles;
                while ($role = array_shift($additionalRoles)) {
                    if (!isset($this->hierarchy[$role])) {
                        continue;
                    }
    
                    $visited[] = $role;
                    $this->map[$main] = array_unique(array_merge($this->map[$main], $this->hierarchy[$role]));
                    $additionalRoles = array_merge($additionalRoles, array_diff($this->hierarchy[$role], $visited));
                }
            }
        }
    }
    

提交回复
热议问题