VoterProviderWithContainer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie\MessageBus\PSR;
13
14
use ICanBoogie\MessageBus\Voter;
15
use ICanBoogie\MessageBus\VoterNotFound;
16
use ICanBoogie\MessageBus\VoterProvider;
17
use Psr\Container\ContainerInterface;
18
use Throwable;
19
20
/**
21
 * Provides permission voters from a service container.
22
 */
23
final class VoterProviderWithContainer implements VoterProvider
24
{
25
    /**
26
     * @param array<string, string> $permissionToVoter
27
     *     Where _key_ is a permission and _value_ a voter service identifier.
28
     */
29
    public function __construct(
30
        private ContainerInterface $container,
31
        private array $permissionToVoter,
32
    ) {
33
    }
34
35
    public function getVoterForPermission(string $permission): ?Voter
36
    {
37
        $id = $this->permissionToVoter[$permission]
38
            ?? throw new VoterNotFound($permission);
39
40
        try {
41
            return $this->container->get($id); // @phpstan-ignore-line
42
        } catch (Throwable $e) {
43
            throw new VoterNotFound($permission, $e);
44
        }
45
    }
46
}
47