Completed
Push — master ( 578b2c...e2ba94 )
by Alexander
12:27
created

AjaxFilter::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 0
crap 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\filters;
9
10
use Yii;
11
use yii\base\ActionFilter;
12
use yii\web\BadRequestHttpException;
13
use yii\web\Request;
14
15
/**
16
 * AjaxFilter allow to limit access only for ajax requests.
17
 *
18
 * ```php
19
 * public function behaviors()
20
 * {
21
 *     return [
22
 *         [
23
 *             'class' => 'yii\filters\AjaxFilter',
24
 *             'only' => ['index']
25
 *         ],
26
 *     ];
27
 * }
28
 * ```
29
 *
30
 * @author Dmitry Dorogin <[email protected]>
31
 * @since 2.0.13
32
 */
33
class AjaxFilter extends ActionFilter
34
{
35
    /**
36
     * @var string the message to be displayed when request isn't ajax
37
     */
38
    public $errorMessage = 'Request must be XMLHttpRequest.';
39
    /**
40
     * @var Request the current request. If not set, the `request` application component will be used.
41
     */
42
    public $request;
43
44
    /**
45
     * @inheritdoc
46
     */
47 1
    public function init()
48
    {
49 1
        if ($this->request === null) {
50 1
            $this->request = Yii::$app->getRequest();
51
        }
52 1
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57 1
    public function beforeAction($action)
58
    {
59 1
        if ($this->request->getIsAjax()) {
60 1
            return true;
61
        }
62
63 1
        throw new BadRequestHttpException($this->errorMessage);
64
    }
65
}