Completed
Push — master ( 71371d...9699e3 )
by Nazar
04:12
created

Permission::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 2
eloc 5
nc 2
nop 3
1
<?php
2
/**
3
 * @package   CleverStyle CMS
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2013-2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs;
9
use
10
	cs\Cache\Prefix;
11
12
/**
13
 * Class for permissions manipulating
14
 *
15
 * @method static $this instance($check = false)
16
 */
17
class Permission {
18
	use
19
		CRUD_helpers,
20
		Singleton;
21
22
	protected $data_model = [
23
		'id'    => 'int:0',
24
		'group' => 'text',
25
		'label' => 'text'
26
	];
27
	protected $table      = '[prefix]permissions';
28
	/**
29
	 * Array of all permissions for quick selecting
30
	 * @var array
31
	 */
32
	protected $permissions_table = [];
33
	/**
34
	 * @var Prefix
35
	 */
36
	protected $cache;
37
	/**
38
	 * Returns database index
39
	 *
40
	 * @return int
41
	 */
42
	protected function cdb () {
43
		return Config::instance()->module('System')->db('users');
44
	}
45
	protected function construct () {
46
		$this->cache = new Prefix('permissions');
47
	}
48
	/**
49
	 * Get permission data<br>
50
	 * If <b>$group</b> or/and <b>$label</b> parameter is specified, <b>$id</b> is ignored.
51
	 *
52
	 * @param int|null    $id
53
	 * @param null|string $group
54
	 * @param null|string $label
55
	 *
56
	 * @return array|false If only <b>$id</b> specified - result is array of permission data, in other cases result will be array of arrays of corresponding
1 ignored issue
show
Documentation introduced by
Should the return type not be array|false|integer|string? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
57
	 *                     permissions data
58
	 */
59
	function get ($id = null, $group = null, $label = null) {
60
		if ($group !== null || $label !== null) {
61
			return $this->read(
62
				$this->search(
1 ignored issue
show
Bug introduced by
It seems like $this->search(array('gro... 'id', true) ?: array() can also be of type array; however, cs\CRUD::read() does only seem to accept integer|array<integer,in...g|array<integer,string>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
63
					[
64
						'group' => $group,
65
						'label' => $label
66
					],
67
					1,
68
					PHP_INT_MAX,
69
					'id',
70
					true
71
				) ?: []
72
			);
73
		} else {
74
			return $this->read($id);
75
		}
76
	}
77
	/**
78
	 * Add permission
79
	 *
80
	 * @param string $group
81
	 * @param string $label
82
	 *
83
	 * @return false|int Group id or <b>false</b> on failure
1 ignored issue
show
Documentation introduced by
Should the return type not be integer|string|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
84
	 */
85
	function add ($group, $label) {
86
		$id = $this->create([$group, $label]);
87
		if ($id) {
88
			$this->del_all_cache();
89
		}
90
		return $id;
91
	}
92
	/**
93
	 * Set permission
94
	 *
95
	 * @param int    $id
96
	 * @param string $group
97
	 * @param string $label
98
	 *
99
	 * @return bool
100
	 */
101
	function set ($id, $group, $label) {
102
		$result = $this->update([$id, $group, $label]);
103
		if ($result) {
104
			$this->del_all_cache();
105
		}
106
		return $result;
107
	}
108
	/**
109
	 * Deletion of permission or array of permissions
110
	 *
111
	 * @param int|int[] $id
112
	 *
113
	 * @return bool
114
	 */
115
	function del ($id) {
116
		if (!$id) {
117
			return false;
118
		}
119
		$id = implode(',', (array)_int($id));
120
		if ($this->db_prime()->q(
121
			[
122
				"DELETE FROM `[prefix]permissions`
123
				WHERE `id` IN ($id)",
124
				"DELETE FROM `[prefix]users_permissions`
125
				WHERE `permission` IN ($id)",
126
				"DELETE FROM `[prefix]groups_permissions`
127
				WHERE `permission` IN ($id)"
128
			]
129
		)
130
		) {
131
			$Cache = $this->cache;
132
			unset(
133
				$Cache->users,
134
				$Cache->groups
135
			);
136
			$this->del_all_cache();
137
			return true;
138
		} else {
139
			return false;
140
		}
141
	}
142
	/**
143
	 * Returns array of all permissions grouped by permissions groups
144
	 *
145
	 * @return array Format of array: ['group']['label'] = <i>permission_id</i>
146
	 */
147
	function get_all () {
148
		if (empty($this->permissions_table)) {
149
			$this->permissions_table = $this->cache->get(
1 ignored issue
show
Documentation Bug introduced by
It seems like $this->cache->get('all',...rn $all_permissions; }) of type * is incompatible with the declared type array of property $permissions_table.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
150
				'all',
151
				function () {
152
					$data            = $this->read(
153
						$this->search([], 1, PHP_INT_MAX, 'id', true) ?: []
1 ignored issue
show
Bug introduced by
It seems like $this->search(array(), 1... 'id', true) ?: array() can also be of type array; however, cs\CRUD::read() does only seem to accept integer|array<integer,in...g|array<integer,string>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
154
					);
155
					$all_permissions = [];
156
					foreach ($data as $item) {
1 ignored issue
show
Bug introduced by
The expression $data of type array|false|integer|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
157
						$all_permissions[$item['group']][$item['label']] = $item['id'];
158
					}
159
					return $all_permissions;
160
				}
161
			);
162
		}
163
		return $this->permissions_table;
164
	}
165
	/**
166
	 * Deletion of permission table (is used after adding, setting or deletion of permission)
167
	 */
168
	protected function del_all_cache () {
169
		$this->permissions_table = [];
170
		unset($this->cache->all);
171
	}
172
}
173