PdoUserUuidRolesContainer   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 1
dl 0
loc 81
c 0
b 0
f 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 1
A __invoke() 0 8 1
A get() 0 11 2
A has() 0 6 1
1
<?php
2
namespace Germania\UserRoles;
3
4
use Psr\Container\ContainerInterface;
5
use Psr\Container\NotFoundExceptionInterface;
6
7
8
/**
9
 * This PSR Container gets the user role names for a given user.
10
 */
11
class PdoUserUuidRolesContainer implements ContainerInterface
12
{
13
14
	/**
15
	 * @var \PDOStatement
16
	 */
17
	public $stmt;
18
19
20
	/**
21
	 * @param \PDO   $pdo               PDO handler
22
	 * @param string $users_table       Table name for users
23
	 * @param string $users_roles_table Table name for users-roles mapping
24
	 */
25
	public function __construct( \PDO $pdo, string $users_table, string $users_roles_table, string $roles_table )
26
	{
27
		$sql = "SELECT
28
        R.usergroup_short_name,
29
30
        LOWER(HEX(U.uuid)) as uuid
31
        FROM `{$users_table}` U
32
33
        LEFT JOIN `{$users_roles_table}` UR
34
        ON U.id = UR.client_id
35
36
        LEFT JOIN `{$roles_table}` R
37
        ON UR.role_id = R.id
38
39
        HAVING uuid=:uuid";
40
41
        $this->stmt = $pdo->prepare( $sql );
42
	}
43
44
45
	/**
46
	 * Returns the user role names for a given user UUID.
47
	 *
48
	 * @param  string $user_id User ID or UUID
49
	 * @return array          
50
	 */
51
	public function __invoke( string $user_id )
52
	{
53
		$this->stmt->execute([
54
			'uuid' => str_replace("-", "", $user_id)
55
		]);
56
57
		return $this->stmt->fetchAll( \PDO::FETCH_COLUMN );
58
	}
59
60
61
62
	/**
63
	 * Alias for `get( $user_id )`, but throws NoUserRolesFoundException
64
	 * when no roles can be found.
65
	 * 
66
	 * @inheritDoc
67
	 * @throws NoUserGroupsFoundException
68
	 */
69
	public function get( $user_id )
70
	{	
71
		$user_id_str = "" . $user_id;
72
		$groups = $this->__invoke( $user_id_str );
73
74
		if (empty($groups)):
75
			throw new NoUserRolesFoundException;
76
		endif;
77
78
		return $groups;
79
	}
80
81
82
	/**
83
	 * @inheritDoc
84
	 */
85
	public function has( $user_id )
86
	{
87
		$user_id_str = "" . $user_id;
88
		$groups = $this->__invoke( $user_id_str );
89
		return !empty( $groups );
90
	}
91
}
92
93