Completed
Push — master ( 89011d...ce8f51 )
by Klochok
03:44
created

Controller::behaviors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 0
cts 2
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * HiPanel core package.
4
 *
5
 * @link      https://hipanel.com/
6
 * @package   hipanel-core
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2014-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\base;
12
13
use hipanel\behaviors\UiOptionsBehavior;
14
use hipanel\components\Cache;
15
use hipanel\components\Response;
16
use hipanel\models\IndexPageUiOptions;
17
use hiqdev\hiart\ActiveRecord;
18
use Yii;
19
use yii\di\Instance;
20
use yii\helpers\Inflector;
21
use yii\web\NotFoundHttpException;
22
23
/**
24
 * Site controller.
25
 */
26
class Controller extends \yii\web\Controller
27
{
28
    /**
29
     * @var Cache|array|string the cache object or the application component ID of the cache object
30
     */
31
    protected $_cache = 'cache';
32
33
    /**
34
     * @var IndexPageUiOptions
35
     */
36
    public $indexPageUiOptionsModel;
37
38
    public function init()
39
    {
40
        parent::init();
41
42
        $this->indexPageUiOptionsModel = Yii::createObject(['class' => IndexPageUiOptions::class]);
43
        $this->indexPageUiOptionsModel->validate(); // In order to get default settings form Model rules()
44
    }
45
46
    public function behaviors()
47
    {
48
        return [
49
            [
50
                'class' => UiOptionsBehavior::class,
51
            ],
52
        ];
53
    }
54
55
    public function setCache($cache)
56
    {
57
        $this->_cache = $cache;
58
    }
59
60
    public function getCache()
61
    {
62
        if (!is_object($this->_cache)) {
63
            $this->_cache = Instance::ensure($this->_cache, Cache::class);
64
        }
65
66
        return $this->_cache;
67
    }
68
69
    /**
70
     * @var array internal actions
71
     */
72
    protected $_internalActions;
73
74
    /**
75
     * @param string $submodel the submodel that will be added to the ClassName
0 ignored issues
show
Bug introduced by
There is no parameter named $submodel. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
76
     * @return string Main Model class name
77
     */
78
    public static function modelClassName()
79
    {
80
        $parts = explode('\\', static::class);
81
        $last = array_pop($parts);
82
        array_pop($parts);
83
        $parts[] = 'models';
84
        $parts[] = substr($last, 0, -10);
85
86
        return implode('\\', $parts);
87
    }
88
89
    /**
90
     * @param array $config config to be used to create the [[Model]]
91
     * @return ActiveRecord
92
     */
93
    public static function newModel($config = [], $submodel = '')
94
    {
95
        $config['class'] = static::modelClassName() . $submodel;
96
        return Yii::createObject($config);
97
    }
98
99
    /**
100
     * @param array $config config to be used to create the [[Model]]
101
     * @return ActiveRecord|SearchModelTrait Search Model object
102
     */
103
    public static function searchModel($config = [])
104
    {
105
        return static::newModel($config, 'Search');
106
    }
107
108
    /**
109
     * @return string main model's formName()
110
     */
111
    public static function formName()
112
    {
113
        return static::newModel()->formName();
114
    }
115
116
    /**
117
     * @return string search model's formName()
118
     */
119
    public static function searchFormName()
120
    {
121
        return static::newModel()->formName() . 'Search';
122
    }
123
124
    /**
125
     * @param string $separator
126
     * @return string Main model's camel2id'ed formName()
127
     */
128
    public static function modelId($separator = '-')
129
    {
130
        return Inflector::camel2id(static::formName(), $separator);
131
    }
132
133
    /**
134
     * Returns the module ID based on the namespace of the controller.
135
     * @return mixed
136
     */
137
    public static function moduleId()
138
    {
139
        return explode('\\', get_called_class())[2];
140
    }
141
142
    public static function controllerId()
143
    {
144
        return strtolower(substr(explode('\\', get_called_class())[4], 0, -10));
145
    }
146
147
    /**
148
     * @param int|array $condition scalar ID or array to be used for searching
149
     * @param array $config config to be used to create the [[Model]]
150
     * @throws NotFoundHttpException
151
     * @return array|ActiveRecord|null|static
152
     */
153
    public static function findModel($condition, $config = [])
154
    {
155
        /* @noinspection PhpVoidFunctionResultUsedInspection */
156
        $model = static::newModel($config)->findOne(is_array($condition) ? $condition : ['id' => $condition]);
157
        if ($model === null) {
158
            throw new NotFoundHttpException('The requested object not found.');
159
        }
160
161
        return $model;
162
    }
163
164
    public static function findModels($condition, $config = [])
165
    {
166
        $containsIntKeys = 0;
167
        if (is_array($condition)) {
168
            foreach (array_keys($condition) as $item) {
169
                if (is_numeric($item)) {
170
                    $containsIntKeys = true;
171
                    break;
172
                }
173
            }
174
        }
175
176
        if (!is_array($condition) || $containsIntKeys) {
177
            $condition = ['id' => $condition];
178
        }
179
        $models = static::searchModel($config)->search([static::searchFormName() => $condition], ['pagination' => false])->getModels();
0 ignored issues
show
Bug introduced by
The method search does only exist in hipanel\base\SearchModelTrait, but not in hiqdev\hiart\ActiveRecord.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
180
        if ($models === null) {
181
            throw new NotFoundHttpException('The requested object not found.');
182
        }
183
184
        return $models;
185
    }
186
187
    public static function renderJson($data)
188
    {
189
        Yii::$app->response->format = Response::FORMAT_JSON;
190
191
        return $data;
192
    }
193
194
    public static function renderJsonp($data)
195
    {
196
        Yii::$app->response->format = Response::FORMAT_JSONP;
197
198
        return $data;
199
    }
200
201
    public function actionIndex()
202
    {
203
        return $this->render('index');
204
    }
205
206
    public function setInternalAction($id, $action)
207
    {
208
        $this->_internalActions[$id] = $action;
209
    }
210
211
    public function hasInternalAction($id)
212
    {
213
        return array_key_exists($id, $this->_internalActions);
214
    }
215
216
    public function createAction($id)
217
    {
218
        $config = $this->_internalActions[$id];
219
        return $config ? Yii::createObject($config, [$id, $this]) : parent::createAction($id);
220
    }
221
222
    /**
223
     * Prepares array for building url to action based on given action id and parameters.
224
     *
225
     * @param string $action action id
226
     * @param string|int|array $params ID of object to be action'ed or array of parameters
227
     * @return array array suitable for Url::to
228
     */
229
    public static function getActionUrl($action = 'index', $params = [])
230
    {
231
        $params = is_array($params) ? $params : ['id' => $params];
232
        return array_merge([implode('/', ['', static::moduleId(), static::controllerId(), $action])], $params);
233
    }
234
235
    /**
236
     * Prepares array for building url to search with given filters.
237
     */
238
    public static function getSearchUrl(array $params = [])
239
    {
240
        return static::getActionUrl('index', [static::searchFormName() => $params]);
241
    }
242
}
243