Passed
Pull Request — develop ( #58 )
by
unknown
32:22 queued 14:42
created

ApiController::rules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
ccs 0
cts 6
cp 0
crap 2
1
<?php
2
3
namespace neon\core\web;
4
5
use neon\user\services\apiTokenManager\NullAuth;
6
use yii\web\Controller;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, neon\core\web\Controller. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use yii\filters\VerbFilter;
8
use yii\filters\ContentNegotiator;
9
use yii\filters\auth\CompositeAuth;
10
use yii\filters\auth\QueryParamAuth;
11
use yii\filters\auth\HttpBearerAuth;
12
use yii\filters\AccessControl;
13
use neon\user\services\apiTokenManager\JwtTokenAuth;
14
15
/**
16
 * Useful controller for serving REST style API's
17
 *
18
 * The Controller implements the following steps in a RESTful API request handling cycle:
19
 * The steps are managed by specific behavior objects @see $this->behaviors() which act as middleware
20
 *
21
 * 1. Resolving response format (see [[ContentNegotiator]]);
22
 * 2. Validating request method (see [[verbs()]]).
23
 * 3. Authenticating user (see [[\yii\filters\auth\AuthInterface]]);
24
 * 4. Rate limiting (see [[RateLimiter]]);
25
 * 5. Formatting response data (see [[serializeData()]]).
26
 *
27
 * Output using json should loosely be based on
28
 * http://jsonapi.org/format/1.1/
29
 */
30
class ApiController extends Controller
31
{
32
	/**
33
	 * Whether or not the api requires a user to be logged in
34
	 * This is not used
35
	 * @deprecated
36
	 * @var boolean
37
	 */
38
	protected $_login_required = false;
39
40
	/**
41
	 * What role(s) must the user have?
42
	 * This will apply to all controller actions in sub classes
43
	 * for finer grained control you can override the rules function
44
	 * @see $this->rules()
45
	 * @var array
46
	 */
47
	protected $_login_roles = ['neon-administrator'];
48
49
	/**
50
	 * @inheritdoc
51
	 */
52
	public $enableCsrfValidation = false;
53
54
	/**
55
	 * @var int record the action start time
56
	 */
57
	public $actionStartTime = 0;
58
59
	/**
60
	 * @inheritdoc
61
	 */
62
	public function init()
63
	{
64
		parent::init();
65
		// before doing anything we must turn off the session
66
		// this controller is for stateless non session APIs
67
		neon()->user->enableSession = false;
68
		neon()->user->loginUrl = null;
69
		neon()->getRequest()->enableCsrfValidation = false;
70
	}
71
72
	/**
73
	 * Set up our default authentication methods for REST style API methods
74
	 * @return array
75
	 */
76
	public function behaviors()
77
	{
78
		$behaviours = [
79
			'contentNegotiator' => [
80
				'class' => ContentNegotiator::class,
81
				'formats' => [
82
					'application/json' => Response::FORMAT_JSON,
83
					'text/html' => Response::FORMAT_HTML,
84
					'application/xml' => Response::FORMAT_XML,
85
					'application/php' => 'php',
86
				],
87
			],
88
			'verbFilter' => [
89
				'class' => VerbFilter::class,
90
				'actions' => $this->verbs()
91
			],
92
			'compositeAuth' => [
93
				'class' => CompositeAuth::class,
94
				'authMethods' => [
95
					['class' => QueryParamAuth::class, 'tokenParam' => 'api_token'],
96
					// Note for the TokenAuth to authenticate a user the user must have been logged in
97
					// then TokenAuth::generateJwtToken() must be called on that page.
98
					// If this has been previously called then the cookie will exist and therefore this method should authenticate.
99
					['class' => JwtTokenAuth::class],
100
					// validate a token presented in the http authorization bearer auth header
101
					['class' => HttpBearerAuth::class],
102
					// This validates the request against a query token parameter - see UserApiToken
103
				],
104
			],
105
			'access' => [
106
				'class' => AccessControl::class,
107
				'rules' => $this->rules()
108
			]
109
		];
110
		return $behaviours;
111
	}
112
113
	/**
114
	 * @inheritdoc
115
	 */
116
	public function beforeAction($action)
117
	{
118
		$this->actionStartTime = microtime(true);
0 ignored issues
show
Documentation Bug introduced by
It seems like microtime(true) can also be of type string. However, the property $actionStartTime is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
119
		// call the auth methods
120
		return parent::beforeAction($action);
121
	}
122
123
	/**
124
	 * @inheritdoc
125
	 */
126
	public function afterAction($action, $result)
127
	{
128
		$return = parent::afterAction($action, $result);
129
		if (is_array($return) && isset($return['data'])) {
130
			$return['meta'] = [
131
				'time' => [
132
					'total' => neon()->getExecutionTime(),
133
					'action' => microtime(true) - $this->actionStartTime
134
				]
135
			];
136
		}
137
		return $return;
138
	}
139
140
	/**
141
	 * The allowed http request verbs for an action
142
	 * For example:
143
	 *
144
	 * ```php
145
	 * [
146
	 *   'create' => ['get', 'post'],
147
	 *   'update' => ['get', 'put', 'post'],
148
	 *   'delete' => ['post', 'delete'],
149
	 *   '*' => ['get'],
150
	 * ]
151
	 * ```
152
	 */
153
	public function verbs()
154
	{
155
		return [
156
			'*' => ['post']
157
		];
158
	}
159
160
	/**
161
	 * A definition for an array of AccessRule objects:
162
	 * @see \yii\filters\AccessRule
163
	 *
164
	 * For example:
165
	 *
166
	 * ```php
167
	 * [
168
	 *     [
169
	 *         'allow' => true,
170
	 *         'actions' => ['update'], // if not specified will apply to all actions in the controller
171
	 *         'roles' => ['updatePost'], // the roles a user must have
172
	 *     ],
173
	 * ],
174
	 * ```
175
	 */
176
	public function rules()
177
	{
178
		return [
179
			[
180
				'allow' => true,
181
				'roles' => $this->_login_roles
182
			]
183
		];
184
	}
185
}
186