1818
1919namespace ZfcRbac \Role ;
2020
21+ use Rbac \Role \RoleInterface ;
2122use Rbac \Role \HierarchicalRole ;
2223use Rbac \Role \Role ;
2324
4243class InMemoryRoleProvider implements RoleProviderInterface
4344{
4445 /**
46+ * Role storage
47+ *
48+ * @var array
49+ */
50+ private $ roles = [];
51+
52+ /**
53+ * Roles config
54+ *
4555 * @var array
4656 */
4757 private $ rolesConfig = [];
@@ -62,34 +72,50 @@ public function getRoles(array $roleNames)
6272 $ roles = [];
6373
6474 foreach ($ roleNames as $ roleName ) {
65- // If no config, we create a simple role with no permission
66- if (!isset ($ this ->rolesConfig [$ roleName ])) {
67- $ roles [] = new Role ($ roleName );
68- continue ;
69- }
70-
71- $ roleConfig = $ this ->rolesConfig [$ roleName ];
75+ $ roles [] = $ this ->getRole ($ roleName );
76+ }
77+ return $ roles ;
78+ }
7279
73- if (isset ($ roleConfig ['children ' ])) {
74- $ role = new HierarchicalRole ($ roleName );
75- $ childRoles = (array ) $ roleConfig ['children ' ];
80+ /**
81+ * Get role by role name
82+ *
83+ * @param $roleName
84+ * @return RoleInterface
85+ */
86+ protected function getRole ($ roleName )
87+ {
88+ if (isset ($ this ->roles [$ roleName ])) {
89+ return $ this ->roles [$ roleName ];
90+ }
7691
77- foreach ( $ this -> getRoles ( $ childRoles ) as $ childRole ) {
78- $ role -> addChild ( $ childRole );
79- }
80- } else {
81- $ role = new Role ( $ roleName ) ;
82- }
92+ // If no config, we create a simple role with no permission
93+ if (! isset ( $ this -> rolesConfig [ $ roleName ])) {
94+ $ role = new Role ( $ roleName );
95+ $ this -> roles [ $ roleName ] = $ role ;
96+ return $ role ;
97+ }
8398
84- $ permissions = isset ( $ roleConfig [ ' permissions ' ]) ? $ roleConfig [ ' permissions ' ] : [ ];
99+ $ roleConfig = $ this -> rolesConfig [ $ roleName ];
85100
86- foreach ($ permissions as $ permission ) {
87- $ role ->addPermission ($ permission );
101+ if (isset ($ roleConfig ['children ' ])) {
102+ $ role = new HierarchicalRole ($ roleName );
103+ $ childRoles = (array )$ roleConfig ['children ' ];
104+ foreach ($ childRoles as $ childRole ) {
105+ $ childRole = $ this ->getRole ($ childRole );
106+ $ role ->addChild ($ childRole );
88107 }
108+ } else {
109+ $ role = new Role ($ roleName );
110+ }
89111
90- $ roles [] = $ role ;
112+ $ permissions = isset ($ roleConfig ['permissions ' ]) ? $ roleConfig ['permissions ' ] : [];
113+ foreach ($ permissions as $ permission ) {
114+ $ role ->addPermission ($ permission );
91115 }
92116
93- return $ roles ;
117+ $ this ->roles [$ roleName ] = $ role ;
118+
119+ return $ role ;
94120 }
95121}
0 commit comments