Completed
Push — master ( 9b9020...8f5910 )
by Razon
02:07
created

ArticleController::applyFilter()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 10
rs 9.6111
c 0
b 0
f 0
cc 5
nc 9
nop 3
1
<?php
2
namespace App\Http\Api\Backend\Controller;
3
4
use App\Http\Api\Backend\Model\Article;
5
use yii\base\DynamicModel;
6
7
class ArticleController extends ActiveController
8
{
9
    public $modelClass = Article::class;
10
    
11
    public function getQuery($action)
12
    {
13
        return parent::getQuery($action)
14
            ->alias('a')
15
            ->orderBy([
16
                'a.id' => SORT_DESC
17
            ])
18
            ->andWhere([
19
                'a.is_deleted' => 0,
20
            ]);
21
    }
22
23
    public function searchModel()
24
    {
25
        return (new DynamicModel(['id' => '', 'title' => '', 'author' => '', 'summary' => '', 'status' => '']))
26
            ->addRule(['title', 'author', 'summary'], 'string')
27
            ->addRule(['id', 'status'], 'number');
28
    }
29
30
    protected function applyFilter($query, $model, $filter)
31
    {
32
        foreach (['title', 'author', 'summary'] as $name) {
33
            if (!empty($model->$name)) {
34
                $query->andWhere(['LIKE', 'a.' . $name, $model->$name]);
35
            }
36
        }
37
        foreach (['id', 'status'] as $name) {
38
            if (is_numeric($model->$name)) {
39
                $query->andWhere(['a.' . $name => $model->$name]);
40
            }
41
        }
42
    }
43
}
44