1 | <?php |
||
28 | class RoleLabelTwigExtension extends AbstractUtilityTwigExtension { |
||
29 | |||
30 | use LabelTwigExtensionTrait; |
||
31 | |||
32 | /** |
||
33 | * Service name. |
||
34 | * |
||
35 | * @var string |
||
36 | */ |
||
37 | const SERVICE_NAME = "wbw.bootstrap.twig.extension.utility.role_label"; |
||
38 | |||
39 | /** |
||
40 | * Constructor. |
||
41 | * |
||
42 | * @param Environment $twigEnvironment The Twig environment. |
||
43 | * @param BaseTranslatorInterface $translator The translator. |
||
44 | * @param LabelTwigExtension $extension The label component Twig extension. |
||
45 | */ |
||
46 | public function __construct(Environment $twigEnvironment, $translator, LabelTwigExtension $extension) { |
||
47 | parent::__construct($twigEnvironment, $translator); |
||
48 | $this->setLabelTwigExtension($extension); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * Apply the color. |
||
53 | * |
||
54 | * @param string $label The label. |
||
55 | * @param string $content The content. |
||
56 | * @param string $color The color. |
||
57 | * @return string Returns the label with applied color. |
||
58 | */ |
||
59 | private function applyColor(string $label, string $content, string $color): string { |
||
60 | $searches = ">" . $content; |
||
61 | $replaces = ' style="background-color:' . $color . ';"' . $searches; |
||
62 | return str_replace([$searches], [$replaces], $label); |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * Display a Bootstrap role label. |
||
67 | * |
||
68 | * @param UserInterface|null $user The user. |
||
69 | * @param array $roleColors The role colors. |
||
70 | * @param array $roleTrans The role translations. |
||
71 | * @return string Returns the Bootstrap role label. |
||
72 | */ |
||
73 | public function bootstrapRoleLabelFunction(?UserInterface $user, array $roleColors = [], array $roleTrans = []): string { |
||
74 | |||
75 | if (null === $user) { |
||
76 | return ""; |
||
77 | } |
||
78 | |||
79 | $output = []; |
||
80 | |||
81 | /** @var Role|string $current */ |
||
82 | foreach ($user->getRoles() as $current) { |
||
83 | |||
84 | $role = true === $current instanceof Role ? $current->getRole() : $current; |
||
85 | |||
86 | $trans = $role; |
||
87 | if (true === array_key_exists($role, $roleTrans)) { |
||
88 | $trans = $this->getTranslator()->trans($roleTrans[$role]); |
||
89 | } |
||
90 | |||
91 | $label = $this->getLabelTwigExtension()->bootstrapLabelDefaultFunction(["content" => $trans]); |
||
92 | if (true === array_key_exists($role, $roleColors)) { |
||
93 | $label = $this->applyColor($label, $trans, $roleColors[$role]); |
||
94 | } |
||
95 | |||
96 | $output[] = $label; |
||
97 | } |
||
98 | |||
99 | return implode(" ", $output); |
||
100 | } |
||
101 | |||
102 | /** |
||
103 | * Get the Twig functions. |
||
104 | * |
||
105 | * @return TwigFunction[] Returns the Twig functions. |
||
106 | */ |
||
107 | public function getFunctions(): array { |
||
112 | } |
||
113 |