1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace KunicMarko\SonataAnnotationBundle\DependencyInjection\Compiler; |
6
|
|
|
|
7
|
|
|
use Doctrine\Common\Annotations\Reader; |
8
|
|
|
use KunicMarko\SonataAnnotationBundle\Annotation\Access; |
9
|
|
|
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
10
|
|
|
use Symfony\Component\DependencyInjection\ContainerBuilder; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @author Marko Kunic <[email protected]> |
14
|
|
|
*/ |
15
|
|
|
final class AccessCompilerPass implements CompilerPassInterface |
16
|
|
|
{ |
17
|
|
|
use FindClassTrait; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var Reader |
21
|
|
|
*/ |
22
|
|
|
private $annotationReader; |
23
|
|
|
|
24
|
|
|
public function process(ContainerBuilder $container): void |
25
|
|
|
{ |
26
|
|
|
$this->annotationReader = $container->get('annotation_reader'); |
27
|
|
|
$roles = $container->getParameter('security.role_hierarchy.roles'); |
28
|
|
|
|
29
|
|
|
foreach ($container->findTaggedServiceIds('sonata.admin') as $id => $tag) { |
30
|
|
|
if (!($class = $this->getClass($container, $id))) { |
31
|
|
|
continue; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
if ($permissions = $this->getRoles(new \ReflectionClass($class), $this->getRolePrefix($id))) { |
35
|
|
|
$roles = array_merge_recursive($roles, $permissions); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$container->setParameter('security.role_hierarchy.roles', $roles); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
private function getRolePrefix(string $serviceId): string |
43
|
|
|
{ |
44
|
|
|
return 'ROLE_' . str_replace('.', '_', strtoupper($serviceId)) . '_'; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
private function getRoles(\ReflectionClass $class, string $prefix): array |
48
|
|
|
{ |
49
|
|
|
$roles = []; |
50
|
|
|
|
51
|
|
|
foreach ($this->annotationReader->getClassAnnotations($class) as $annotation) { |
52
|
|
|
if (!$annotation instanceof Access) { |
53
|
|
|
continue; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$roles[$annotation->getRole()] = array_map( |
57
|
|
|
function (string $permission) use ($prefix) { |
58
|
|
|
return $prefix . strtoupper($permission); |
59
|
|
|
}, |
60
|
|
|
$annotation->permissions |
61
|
|
|
); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $roles; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|