Test Failed
Pull Request — master (#6)
by
unknown
01:49
created

UserPermissionsComponent::checkForHandler()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 0
cts 12
cp 0
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 12
nc 3
nop 2
crap 30
1
<?php
2
namespace UserPermissions\Controller\Component;
3
4
use Cake\Controller\Component;
5
use Cake\Controller\ComponentRegistry;
6
use Cake\Controller\Component\FlashComponent;
7
use Cake\Datasource\ConnectionManager;
8
use Cake\Log\Log;
9
use Cake\ORM\TableRegistry;
10
use UserPermissions\Exception\MissingHandlerException;
11
12
class UserPermissionsComponent extends Component {
13
14
    /**
15
     * Controller name
16
     *
17
     * @var string
18
     */
19
	public $controller = null;
20
21
    /**
22
     * Session
23
     *
24
     * @var string
25
     */
26
	public $session = null;
27
28
    /**
29
     * Components array
30
     *
31
     * @var array
32
     */
33
   	public $components = ['Flash'];
34
35
    private $actions;
36
37
    private $allow;
38
39
    private $redirect;
40
41
    private $params;
42
43
    private $message;
44
45
    private $userType;
46
47
    private $action;
48
	
49
	/**
50
	 * Boolean value which holds the configuration for the behavior in case of
51
	 * missing handlers.
52
	 */
53
	private $throwEx;
54
55
    /**
56
    * Initialization to get controller variable
57
    *
58
	* For this component available settings:
59
	* 	bool throwEx - default false - if set to true, an exception will be
60
	*		thrown, if a handler is about to be called but does not exist.
61
	*
62
    * @param array $config Configuration array for the component.
63
    */
64 1
    public function initialize(array $config)
65
    {
66 1
        parent::initialize($config);
67
        
68 1
        $this->controller = $this->_registry->getController();
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->_registry->getController() of type object<Cake\Controller\Controller> is incompatible with the declared type string of property $controller.

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...
69 1
        $this->session = $this->controller->request->session();
70
71 1
        $this->actions 		= array();
72 1
		$this->allow 		= true;
73 1
		$this->redirect 	= '';
74 1
		$this->params 		= '';
75 1
		$this->message 		= '';
76 1
		$this->userType 	= '';
77 1
		$this->action   	= null;
78 1
		$this->throwEx      = isset($config["throwEx"]) && $config["throwEx"];
79 1
    }
80
81
    /**
82
    * Initialization to get controller variable
83
    *
84
    * @param array $rules Array of rules for permissions.
85
    * @return bool false if user / group doesn't have permission, true if has permission
86
    */
87 1
    public function allow ($rules) {
88 1
    	$this->setUserValues();
89 1
    	$this->bindConfiguration($rules);
90
91
		if (!$this->applyGroupsRules($rules)) {
92
			$this->applyViewsRules($rules);
93
		}
94
95
		return $this->allow;
96
    }
97
98 1
    private function setUserValues()
99
    {
100 1
    	$userId = $this->session->read('Auth.User.id');
0 ignored issues
show
Bug introduced by
The method read cannot be called on $this->session (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
101
102 1
    	if (!isset($userId)) {
103 1
			$this->userType = 'guest';
104
		}
105 1
    }
106
107 1
    private function bindConfiguration(array $rules) 
108
    {	
109 1
		foreach(array("user_type", "redirect", "action", "controller", "message") as $key) {
110 1
			if(isset($rules[$key])) {
111 1
				$this->$key = $value;
0 ignored issues
show
Bug introduced by
The variable $value seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
112
			}
113
		}
114
		if(!is_object($value)) {
0 ignored issues
show
Bug introduced by
The variable $value seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
115
			Log::write("warning", sprintf("controller is not an object (%s)", gettype($value)));
0 ignored issues
show
Bug introduced by
The variable $value seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
116
		}
117
118
		foreach($rules['groups']  as $key => $value){
119
			if($key == $this->userType){
120
				foreach($value as $v){
121
					array_push($this->actions, $v);
122
				}
123
			}
124
		}
125
    }
126
127
    private function applyGroupsRules(array $rules)
128
    {
129
    	$existRulesForGroups = false;
130
131
    	if(isset($rules['groups'])){
132
			foreach($rules['groups'] as $key => $value){
133
				$this->searchForApplyGroupRules($key, $value);
0 ignored issues
show
Unused Code introduced by
The call to UserPermissionsComponent...rchForApplyGroupRules() has too many arguments starting with $value.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
134
			}
135
		}
136
137
		return $existRulesForGroups;
138
    }
139
140
    private function searchForApplyGroupRules($key)
141
    {
142
    	if($key == $this->userType){
143
    		if ($this->notInArrayAction()) {
144
				$this->redirectIfIsSet();
145
				
146
				$this->allow = false;
147
			}
148
		}
149
    }
150
151
    private function notInArrayAction()
152
    {
153
    	return ((!in_array('*', $this->actions)) && (!in_array($this->action, $this->actions)));
154
    }
155
156
    private function applyViewsRules(array $rules)
157
    {
158
    	if(isset($rules['views'])){
159
			foreach($rules['views'] as $key => $value){
160
				$this->searchForApplyViewRules($key, $value);
161
			}
162
		}
163
    }
164
165
    private function searchForApplyViewRules($key, $value)
166
    {
167
    	if($key == $this->action) {
168
			if(!$this->checkForHandler($this->controller, $value) || !$this->controller->$value()){
0 ignored issues
show
Bug introduced by
The method $value cannot be called on $this->controller (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
169
				$this->redirectIfIsSet();
170
				
171
				$this->allow = false;
172
			}
173
		}
174
    }
175
	
176
	private function checkForHandler($controller, $handler)
177
	{
178
		if(!method_exists($controller, $handler)) {
179
			$msg = sprintf(
180
				"Controller %s=%s has no method called '%s'",
181
				is_object($controller) ? "class" : "type",
182
				is_object($controller) ? get_class($controller) : gettype($controller),
183
				$handler
184
			);
185
			Log::write("debug", $msg);
186
			if($this->throwEx) {
187
				throw new MissingHandlerException($msg);
188
			}
189
			return false;
190
		}
191
		
192
		return true;
193
	}
194
195
    private function redirectIfIsSet()
196
    {
197
    	if($this->redirect != ''){
198
			if($this->message != ''){
199
				$this->Flash->set($this->message);
0 ignored issues
show
Documentation introduced by
The property Flash does not exist on object<UserPermissions\C...erPermissionsComponent>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
200
			}
201
			
202
			header("Location: " . $this->redirect);
203
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method redirectIfIsSet() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
204
		}
205
	}
206
}