ModelAbstract   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 213
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Importance

Changes 0
Metric Value
wmc 24
lcom 2
cbo 1
dl 0
loc 213
rs 10
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A queryPostSlug() 0 11 2
A queryLimit() 0 6 2
A setUrl() 0 6 1
getModelUrlParams() 0 1 ?
A scopeListFrontend() 0 19 1
A scopeWhereTranslatable() 0 4 1
A whereTranslatableProperty() 0 6 2
A queryDisplayEmpty() 0 7 2
A queryOrderBy() 0 16 4
A withRelation() 0 24 2
A queryGroupBy() 0 10 3
A handleExceptions() 0 14 4
1
<?php declare(strict_types=1);
2
3
namespace GinoPane\BlogTaxonomy\Models;
4
5
use Db;
6
use Model;
7
use Cms\Classes\Controller;
8
use October\Rain\Database\Builder;
9
use October\Rain\Database\Relations\HasMany;
10
use GinoPane\BlogTaxonomy\Classes\PostListFiltersTrait;
11
12
/**
13
 * Class ModelAbstract
14
 *
15
 * @property string $url
16
 *
17
 * @package GinoPane\BlogTaxonomy\Models
18
 */
19
abstract class ModelAbstract extends Model
0 ignored issues
show
Coding Style introduced by
ModelAbstract does not seem to conform to the naming convention (^Abstract|Factory$).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
20
{
21
    /**
22
     * @var array
23
     */
24
    public static $sortingOptions = [];
25
26
    /**
27
     * Sets the URL attribute with a URL to this object
28
     *
29
     * @param string $pageName
30
     * @param Controller $controller
31
     * @param array $params
32
     *
33
     * @return void
34
     */
35
    public function setUrl($pageName, Controller $controller, array $params = array())
36
    {
37
        $params = $this->getModelUrlParams($params);
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $params. This often makes code more readable.
Loading history...
38
39
        $this->url = $controller->pageUrl($pageName, $params, false);
40
    }
41
42
    /**
43
     * @param array $params
44
     *
45
     * @return array
46
     */
47
    abstract protected function getModelUrlParams(array $params): array;
48
49
    /**
50
     * Gets a list of items related to Posts for frontend use
51
     *
52
     * @param       $query
53
     * @param array $options Available options are "sort", "displayEmpty", "limit", "post"
54
     *
55
     * @return mixed
56
     */
57
    public function scopeListFrontend(Builder $query, array $options = [])
58
    {
59
        $this->withRelation($query, $options);
60
61
        $sortField = $this->queryOrderBy($query, $options);
62
63
        $this->queryDisplayEmpty($query, $options);
64
65
        $this->queryPostSlug($query, $options);
66
67
        $this->queryLimit($query, $options);
68
69
        // GROUP BY is required for SQLite to deal with HAVING
70
        // We use it for all connections just to keep implementation
71
        // independent from the connection being used
72
        $this->queryGroupBy($query, $sortField);
73
74
        return $query->get();
75
    }
76
77
    /**
78
     * @param Builder   $query
79
     * @param string    $property
80
     * @param mixed     $value
81
     */
82
    public function scopeWhereTranslatable(Builder $query, string $property, $value)
83
    {
84
        self::whereTranslatableProperty($query, $property, $value);
85
    }
86
87
    /**
88
     * @param Builder $query
89
     * @param string $property
90
     * @param $value
91
     */
92
    public static function whereTranslatableProperty(Builder $query, string $property, $value)
93
    {
94
        $query->getModel()->isClassExtendedWith('RainLab.Translate.Behaviors.TranslatableModel')
95
            ? $query->transWhere($property, $value)
96
            : $query->where($property, $value);
97
    }
98
99
    /**
100
     * @param Builder $query
101
     * @param array   $options
102
     *
103
     * @return void
104
     */
105
    protected function queryDisplayEmpty(Builder $query, array $options)
106
    {
107
        if (empty($options['displayEmpty'])) {
108
            $query
109
                ->having('posts_count', '>', 0);
110
        }
111
    }
112
113
    /**
114
     * @param Builder $query
115
     * @param array   $options
116
     *
117
     * @return void
118
     */
119
    protected function queryPostSlug(Builder $query, array $options)
120
    {
121
        if (!empty($options['post'])) {
122
            $query->whereHas(
123
                'posts',
124
                static function ($query) use ($options) {
125
                    ModelAbstract::whereTranslatableProperty($query, 'slug', $options['post']);
126
                }
127
            );
128
        }
129
    }
130
131
    /**
132
     * @param Builder $query
133
     * @param array   $options
134
     *
135
     * @return void
136
     */
137
    private function queryLimit(Builder $query, array $options)
138
    {
139
        if (!empty($options['limit'])) {
140
            $query->take($options['limit']);
141
        }
142
    }
143
144
    /**
145
     * @param Builder $query
146
     * @param array   $options
147
     *
148
     * @return string|null
149
     */
150
    private function queryOrderBy(Builder $query, array $options): ?string
151
    {
152
        if (!empty($options['sort']) && \array_key_exists($options['sort'], static::$sortingOptions)) {
153
            if ($options['sort'] === 'random') {
154
                $query->inRandomOrder();
155
            } else {
156
                list($sortField, $sortDirection) = explode(' ', $options['sort']);
157
158
                $query->orderBy($sortField, $sortDirection);
159
160
                return $sortField;
161
            }
162
        }
163
164
        return null;
165
    }
166
167
    /**
168
     * @param Builder $query
169
     * @param array   $options
170
     *
171
     * @return void
172
     */
173
    protected function withRelation(Builder $query, array $options)
174
    {
175
        if (!empty($options['fetchPosts'])) {
176
            $query->with(
177
                [
178
                    'posts' => static function (HasMany $query) use ($options) {
179
                        $query->isPublished();
180
181
                        self::handleExceptions($query->getQuery(), $options);
182
                    }
183
                ]
184
            );
185
        }
186
187
        $query->withCount(
188
            [
189
                'posts' => static function ($query) use ($options) {
190
                    $query->isPublished();
191
192
                    self::handleExceptions($query, $options);
193
                }
194
            ]
195
        );
196
    }
197
198
    /**
199
     * @param Builder     $query
200
     * @param string|null $sortField
201
     */
202
    private function queryGroupBy(Builder $query, ?string $sortField = null)
203
    {
204
        if (Db::getDriverName() === 'sqlite') {
205
            if ($sortField !== null) {
206
                $query->groupBy('id', $sortField);
207
            } else {
208
                $query->groupBy('id');
209
            }
210
        }
211
    }
212
213
    /**
214
     * @param Builder   $query
215
     * @param array     $options
216
     */
217
    protected static function handleExceptions(Builder $query, array $options)
218
    {
219
        if (!empty($options['includeCategories'])) {
220
            PostListFiltersTrait::handleInclusionsByCategory($query, $options['includeCategories']);
221
        }
222
223
        if (!empty($options['exceptPosts'])) {
224
            PostListFiltersTrait::handleExceptionsByPost($query, $options['exceptPosts']);
225
        }
226
227
        if (!empty($options['exceptCategories'])) {
228
            PostListFiltersTrait::handleExceptionsByCategory($query, $options['exceptCategories']);
229
        }
230
    }
231
}
232