Passed
Push — main ( 9c59f2...5fac80 )
by Peter
02:52
created

EnforcerBootstrapper::createCombinedAdapter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
nc 1
nop 3
dl 0
loc 11
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Bootstrappers\Authorization;
6
7
use AbterPhp\Framework\Authorization\CombinedAdapter;
8
use AbterPhp\Framework\Authorization\Constant\Role;
9
use AbterPhp\Framework\Constant\Env;
10
use AbterPhp\Framework\Constant\Session;
11
use Casbin\Enforcer;
12
use Casbin\Exceptions\CasbinException;
13
use Opulence\Environments\Environment;
14
use Opulence\Ioc\Bootstrappers\Bootstrapper;
15
use Opulence\Ioc\Bootstrappers\ILazyBootstrapper;
16
use Opulence\Ioc\IContainer;
17
use Opulence\Ioc\IocException;
18
use Opulence\Sessions\ISession;
19
use Opulence\Views\Compilers\Fortune\ITranspiler;
20
21
class EnforcerBootstrapper extends Bootstrapper implements ILazyBootstrapper
22
{
23
    /**
24
     * @return array
25
     */
26
    public function getBindings(): array
27
    {
28
        return [
29
            Enforcer::class,
30
        ];
31
    }
32
33
    /**
34
     * @param IContainer $container
35
     *
36
     * @throws CasbinException
37
     * @throws IocException
38
     */
39
    public function registerBindings(IContainer $container)
40
    {
41
        /** @var CombinedAdapter $combinedAdapter */
42
        $combinedAdapter = $container->resolve(CombinedAdapter::class);
43
44
        $modelPath = sprintf("%s/model.conf", Environment::getVar(Env::DIR_AUTH_CONFIG));
45
        $enforcer  = new Enforcer($modelPath, $combinedAdapter);
46
47
        $enforcer->loadPolicy();
48
49
        $container->bindInstance(Enforcer::class, $enforcer);
50
51
        $this->registerViewFunction($container, $enforcer);
52
    }
53
54
    /**
55
     * @param IContainer $container
56
     * @param Enforcer   $enforcer
57
     *
58
     * @throws IocException
59
     */
60
    private function registerViewFunction(IContainer $container, Enforcer $enforcer)
61
    {
62
        if (!$container->hasBinding(ISession::class)) {
63
            return;
64
        }
65
66
        /** @var ISession $session */
67
        $session  = $container->resolve(ISession::class);
68
        $username = $session->get(Session::USERNAME);
69
70
        /** @var ITranspiler $transpiler */
71
        $transpiler = $container->resolve(ITranspiler::class);
72
        $transpiler->registerViewFunction(
73
            'canView',
74
            function (string $key) use ($username, $enforcer) {
75
                return $enforcer->enforce($username, 'admin_resource_' . $key, Role::READ);
76
            }
77
        );
78
    }
79
}
80