Completed
Push — master ( c22208...64acfb )
by Igor
04:17
created

BaseController::response()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace app\components;
4
5
use Yii;
6
use yii\web\Controller;
7
use yii\helpers\ArrayHelper;
8
use app\helpers\Http;
9
10
/**
11
 * Global base controller
12
 */
13
class BaseController extends Controller
14
{
15
    /**
16
     * @var string Path to js bundle
17
     */
18
    public $jsBundle = 'front.js';
19
    /**
20
     * @var string Path to css bundle
21
     */
22
    public $cssBundle = 'front.css';
23
24
    /**
25
     * @return string Return CSS bundle
26
     */
27
    public function getCssBundle()
28
    {
29
        return '/assets/' . ArrayHelper::getValue(Yii::$app->params['assets'], $this->cssBundle);
30
    }
31
32
    /**
33
     * @return string Return JS bundle
34
     */
35
    public function getJsBundle()
36
    {
37
        return '/assets/' . ArrayHelper::getValue(Yii::$app->params['assets'], $this->jsBundle);
38
    }
39
40
    /**
41
     * Load the model based on its primary key value or WHERE condition.
42
     * If the model is not found or access denied, a 404 HTTP exception will be thrown.
43
     *
44
     * @param ActiveRecord $model
45
     * @param int|array $id primary key or WHERE condition
46
     * @param callable $checkAccess
47
     * @return ActiveRecord
48
     * @throws NotFoundHttpException
49
     */
50
    public function loadModel($model, $id, $checkAccess = null)
51
    {
52
        $model = $model::findOne($id);
53
54
        if ($model === null || ($checkAccess !== null && !$model->$checkAccess())) {
55
            Http::exception(404);
56
        } // @codeCoverageIgnore
57
58
        return $model;
59
    }
60
61
    /**
62
     * Show alert message
63
     *
64
     * @param string $type success|error
65
     * @param string $message
66
     * @param string $url If null go Home
67
     */
68
    public function alert($type, $message, $url = null)
69
    {
70
        Yii::$app->getSession()->setFlash($type, $message);
71
        return $url ? $this->redirect($url) : $this->goHome();
72
    }
73
74
    /**
75
     * HTTP Response
76
     *
77
     * @param mixed $data
78
     * @param string $format The response format
79
     * @see http://www.yiiframework.com/doc-2.0/yii-web-response.html
80
     */
81
    public function response($data, $format = \yii\web\Response::FORMAT_JSON)
82
    {
83
        \Yii::$app->response->format = $format;
84
        return $data;
85
    }
86
}
87