PrivilegeController.php 2.11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
<?php

namespace UnicaenAuth\Guard;

use BjyAuthorize\Guard\Controller;
use Zend\ServiceManager\ServiceLocatorInterface;
use UnicaenAuth\Provider\Privilege\PrivilegeProviderAwareTrait;
use UnicaenApp\Traits\SessionContainerTrait;


/**
12
 * Description of PrivilegeController
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
 *
 * @author Laurent LECLUSE <laurent.lecluse at unicaen.fr>
 */
class PrivilegeController extends Controller
{
    use PrivilegeProviderAwareTrait;
    use SessionContainerTrait;



    public function __construct(array $rules, ServiceLocatorInterface $serviceLocator)
    {
        $this->serviceLocator = $serviceLocator;
        parent::__construct($this->privilegesToRoles($rules), $serviceLocator);
    }



    protected function privilegesToRoles(array $rules)
    {
        $pr = $this->getPrivilegeProvider()->getPrivilegesRoles();

        foreach ($rules as $index => $rule) {
            if (isset($rule['privileges'])) {
                $rolesCount    = 0;
                $privileges    = (array)$rule['privileges'];
                $rule['roles'] = isset($rule['roles']) ? (array)$rule['roles'] : [];
                foreach ($pr as $privilege => $roles) {
                    if (in_array($privilege, $privileges)) {
                        $rolesCount += count($roles);
                        $rule['roles'] = array_unique(array_merge($rule['roles'], $roles));
                    }
                }
                unset($rule['privileges']);
                if (0 < count($rule['roles'])) {
                    $rules[$index] = $rule;
                }else{
                    unset($rules[$index]);
                }
            }
        }

        return $rules;
    }



    /**
     * Pour récupérer le serviceLocator depuis les traits de service
     *
     * @return ServiceLocatorInterface
     */
    protected function getServiceLocator()
    {
        return $this->serviceLocator;
    }



    public static function getResourceId($controller, $action = null)
    {
        if (isset($action)) {
            return sprintf('controller/%s:%s', $controller, strtolower($action));
        }

        return sprintf('controller/%s', $controller);
    }

}