PermissionsAcl::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 2
nc 1
nop 4
ccs 10
cts 10
cp 1
crap 2
1
<?php
2
namespace Germania\Permissions;
3
4
use Psr\Log\LoggerInterface;
5
use Psr\Log\LoggerAwareTrait;
6
use Psr\Log\NullLogger;
7
8
class PermissionsAcl
9
{
10
11
    use LoggerAwareTrait;
12
13
    /**
14
     * @var \PDOStatement
15
     */
16
    public $stmt;
17
18
    /**
19
     * @var string
20
     */
21
    public $permissions_table = "permissions";
22
23
    /**
24
     * @var string
25
     */
26
    public $permissions_roles_table = "permissions_roles";
27
28
    /**
29
     * @var Seperator string for roles in SELECT statement
30
     */
31
    protected $separator = ",";
32
33
34
    /**
35
     * @param \PDO                 $pdo                      PDO instance
36
     * @param string               $permissions_table        Permissions table name
37
     * @param string               $permissions_roles_table  Permissions and roles assignments table
38
     * @param LoggerInterface|null $logger                   Optional: PSR-3 Logger
39
     */
40 5
    public function __construct( \PDO $pdo, $permissions_table, $permissions_roles_table, LoggerInterface $logger = null )
41
    {
42 5
        $this->setLogger( $logger ?: new NullLogger );
43
44
        // Prerequisites
45 5
        $this->permissions_table       = $permissions_table;
46 5
        $this->permissions_roles_table = $permissions_roles_table;
47
48
        // Read pages and allowed roles
49
        $sql =  "SELECT
50
        P.permission_name AS task,
51 5
        GROUP_CONCAT(Pmm.role_id SEPARATOR '{$this->separator}') AS roles
52
53 5
        FROM {$this->permissions_table} P
54 5
        LEFT JOIN {$this->permissions_roles_table} Pmm
55
        ON P.id = Pmm.permission_id
56
57 1
        GROUP BY task";
58
59
        // Prepare business
60 5
        $this->stmt = $pdo->prepare( $sql );
61 5
    }
62
63
64
    /**
65
     * @return array
66
     */
67 5
    public function __invoke(  )
68
    {
69 5
        $this->stmt->execute();
70
71
        // Fetch results; explode arrays
72 5
        $acl = array_map(function( $roles ) {
73
            return array_filter(explode($this->separator, $roles));
74 5
        }, $this->stmt->fetchAll( \PDO::FETCH_UNIQUE | \PDO::FETCH_OBJ | \PDO::FETCH_COLUMN));
75
76 5
        return $acl;
77
    }
78
}
79