Controller::findModels()   B
last analyzed

Complexity

Conditions 7
Paths 16

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
ccs 0
cts 11
cp 0
rs 8.6346
cc 7
nc 16
nop 2
crap 56
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-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\base;
12
13
use hipanel\actions\ExportAction;
14
use hipanel\behaviors\UiOptionsBehavior;
15
use hipanel\components\Cache;
16
use hipanel\components\Response;
17
use hipanel\models\IndexPageUiOptions;
18
use hiqdev\hiart\ActiveRecord;
19
use Yii;
20
use yii\di\Instance;
21
use yii\helpers\Inflector;
22
use yii\web\NotFoundHttpException;
23
24
/**
25
 * Site controller.
26
 */
27
class Controller extends \yii\web\Controller
28
{
29
    /**
30
     * @var Cache|array|string the cache object or the application component ID of the cache object
31
     */
32
    protected $_cache = 'cache';
33
34
    /**
35
     * @var IndexPageUiOptions
36
     */
37
    public $indexPageUiOptionsModel;
38
39
    public function init()
40
    {
41
        parent::init();
42
43
        $this->indexPageUiOptionsModel = Yii::createObject(['class' => IndexPageUiOptions::class]);
44
        $this->indexPageUiOptionsModel->validate(); // In order to get default settings form Model rules()
45
    }
46
47
    public function behaviors()
48
    {
49
        return [
50
            [
51
                'class' => UiOptionsBehavior::class,
52
            ],
53
        ];
54
    }
55
56
    public function actions()
57
    {
58
        return [
59
            'export' => [
60
                'class' => ExportAction::class,
61
            ],
62
        ];
63
    }
64
65
    public function setCache($cache)
66
    {
67
        $this->_cache = $cache;
68
    }
69
70
    public function getCache()
71
    {
72
        if (!is_object($this->_cache)) {
73
            $this->_cache = Instance::ensure($this->_cache, Cache::class);
74
        }
75
76
        return $this->_cache;
77
    }
78
79
    /**
80
     * @var array internal actions
81
     */
82
    protected $_internalActions;
83
84
    /**
85
     * @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...
86
     * @return string Main Model class name
87
     */
88
    public static function modelClassName()
89
    {
90
        $parts = explode('\\', static::class);
91
        $last = array_pop($parts);
92
        array_pop($parts);
93
        $parts[] = 'models';
94
        $parts[] = substr($last, 0, -10);
95
96
        return implode('\\', $parts);
97
    }
98
99
    /**
100
     * @param array $config config to be used to create the [[Model]]
101
     * @return ActiveRecord
102
     */
103
    public static function newModel($config = [], $submodel = '')
104
    {
105
        $config['class'] = static::modelClassName() . $submodel;
106
107
        return Yii::createObject($config);
108
    }
109
110
    /**
111
     * @param array $config config to be used to create the [[Model]]
112
     * @return ActiveRecord|SearchModelTrait Search Model object
113
     */
114
    public static function searchModel($config = [])
115
    {
116
        return static::newModel($config, 'Search');
117
    }
118
119
    /**
120
     * @return string main model's formName()
121
     */
122
    public static function formName()
123
    {
124
        return static::newModel()->formName();
125
    }
126
127
    /**
128
     * @return string search model's formName()
129
     */
130
    public static function searchFormName()
131
    {
132
        return static::newModel()->formName() . 'Search';
133
    }
134
135
    /**
136
     * @param string $separator
137
     * @return string Main model's camel2id'ed formName()
138
     */
139
    public static function modelId($separator = '-')
140
    {
141
        return Inflector::camel2id(static::formName(), $separator);
142
    }
143
144
    /**
145
     * Returns the module ID based on the namespace of the controller.
146
     * @return mixed
147
     */
148
    public static function moduleId()
149
    {
150
        return array_values(array_slice(explode('\\', get_called_class()), -3, 1, true))[0]; // todo: remove
151
    }
152
153
    public static function controllerId()
154
    {
155
        return Inflector::camel2id(substr(end(explode('\\', get_called_class())), 0, -10)); // todo: remove
0 ignored issues
show
Bug introduced by
explode('\\', get_called_class()) cannot be passed to end() as the parameter $array expects a reference.
Loading history...
156
    }
157
158
    /**
159
     * @param int|array $condition scalar ID or array to be used for searching
160
     * @param array $config config to be used to create the [[Model]]
161
     * @throws NotFoundHttpException
162
     * @return array|ActiveRecord|static|null
163
     */
164
    public static function findModel($condition, $config = [])
165
    {
166
        /* @noinspection PhpVoidFunctionResultUsedInspection */
167
        $model = static::newModel($config)->findOne(is_array($condition) ? $condition : ['id' => $condition]);
168
        if ($model === null) {
169
            throw new NotFoundHttpException('The requested object not found.');
170
        }
171
172
        return $model;
173
    }
174
175
    public static function findModels($condition, $config = [])
176
    {
177
        $containsIntKeys = 0;
178
        if (is_array($condition)) {
179
            foreach (array_keys($condition) as $item) {
180
                if (is_numeric($item)) {
181
                    $containsIntKeys = true;
182
                    break;
183
                }
184
            }
185
        }
186
187
        if (!is_array($condition) || $containsIntKeys) {
188
            $condition = ['id' => $condition];
189
        }
190
        $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...
191
        if ($models === null) {
192
            throw new NotFoundHttpException('The requested object not found.');
193
        }
194
195
        return $models;
196
    }
197
198
    public static function renderJson($data)
199
    {
200
        Yii::$app->response->format = Response::FORMAT_JSON;
201
202
        return $data;
203
    }
204
205
    public static function renderJsonp($data)
206
    {
207
        Yii::$app->response->format = Response::FORMAT_JSONP;
208
209
        return $data;
210
    }
211
212
    public function actionIndex()
213
    {
214
        return $this->render('index');
215
    }
216
217
    public function setInternalAction($id, $action)
218
    {
219
        $this->_internalActions[$id] = $action;
220
    }
221
222
    public function hasInternalAction($id)
223
    {
224
        return array_key_exists($id, $this->_internalActions);
225
    }
226
227
    public function createAction($id)
228
    {
229
        $config = $this->_internalActions[$id];
230
231
        return $config ? Yii::createObject($config, [$id, $this]) : parent::createAction($id);
232
    }
233
234
    /**
235
     * Prepares array for building url to action based on given action id and parameters.
236
     *
237
     * @param string $action action id
238
     * @param string|int|array $params ID of object to be action'ed or array of parameters
239
     * @return array array suitable for Url::to
240
     */
241
    public static function getActionUrl($action = 'index', $params = [])
242
    {
243
        $params = is_array($params) ? $params : ['id' => $params];
244
245
        return array_merge([implode('/', ['', static::moduleId(), static::controllerId(), $action])], $params);
246
    }
247
248
    /**
249
     * Prepares array for building url to search with given filters.
250
     */
251
    public static function getSearchUrl(array $params = [])
252
    {
253
        return static::getActionUrl('index', [static::searchFormName() => $params]);
254
    }
255
}
256