Completed
Push — master ( 0b2e6b...2c86a7 )
by Paul
49:42 queued 39:17
created

RolesDataSource::getAllAvailableRoles()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 2
Metric Value
dl 0
loc 17
rs 8.8571
c 5
b 1
f 2
cc 5
eloc 10
nc 9
nop 1
1
<?php
2
3
namespace Victoire\Bundle\CriteriaBundle\DataSource;
4
5
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
6
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
7
use Symfony\Component\Security\Core\Role\RoleHierarchy;
8
9
class RolesDataSource
10
{
11
    /**
12
     * @var TokenStorage
13
     */
14
    private $tokenStorage;
15
16
    /*
17
     * @var array
18
     */
19
    private $roleHierarchy;
20
21
    /**
22
     * RolesDataSource constructor.
23
     *
24
     * @param TokenStorage $tokenStorage
25
     * @param array        $roleHierarchy
26
     */
27
    public function __construct(TokenStorage $tokenStorage, $roleHierarchy)
28
    {
29
        $this->tokenStorage = $tokenStorage;
30
        $this->roleHierarchy = $roleHierarchy;
31
    }
32
33
    /**
34
     * @return mixed
35
     */
36
    public function getRoles()
37
    {
38
        $user = $this->tokenStorage->getToken()->getUser();
39
40
        return $user;
41
    }
42
43
    /**
44
     * @return array
45
     */
46
    public function getRolesFormParams()
47
    {
48
        return [
49
            'type'    => ChoiceType::class,
50
            'options' => [
51
                'choices'           => $this->getAllAvailableRoles($this->roleHierarchy),
52
                'choices_as_values' => true,
53
                'choice_label'      => function ($value) {
54
                    return $value;
55
                },
56
            ],
57
        ];
58
    }
59
60
    /**
61
     * flatten the array of all roles defined in role_hierarchy.
62
     *
63
     * @param array $roleHierarchy
64
     *
65
     * @return array
66
     */
67
    public function getAllAvailableRoles($roleHierarchy)
68
    {
69
        $roles = [];
70
        foreach ($roleHierarchy as $key => $value) {
71
            if (is_array($value)) {
72
                $roles = array_merge($roles, $this->getAllAvailableRoles($value));
73
            }
74
            if (is_string($key)) {
75
                $roles[] = $key;
76
            }
77
            if (is_string($value)) {
78
                $roles[] = $value;
79
            }
80
        }
81
82
        return $roles;
83
    }
84
}
85