GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — filters-dev ( c59b06...8ccd21 )
by Ivan
14:40 queued 04:15
created

Page::afterSave()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
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 7
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace app\modules\page\models;
4
5
use app\behaviors\CleanRelations;
6
use app\behaviors\Tree;
7
use app\modules\image\models\Image;
8
use app\properties\HasProperties;
9
use app\traits\GetImages;
10
use devgroup\TagDependencyHelper\ActiveRecordHelper;
11
use Yii;
12
use yii\behaviors\TimestampBehavior;
13
use yii\caching\TagDependency;
14
use yii\data\ActiveDataProvider;
15
use yii\db\ActiveRecord;
16
use yii\db\Expression;
17
18
/**
19
 * This is the model class for table "page".
20
 * @property integer $id
21
 * @property integer $parent_id
22
 * @property string $slug
23
 * @property string $slug_compiled
24
 * @property boolean $slug_absolute
25
 * @property boolean $published
26
 * @property boolean $searchable
27
 * @property integer $robots
28
 * @property string $title
29
 * @property string $h1
30
 * @property string $meta_description
31
 * @property string $breadcrumbs_label
32
 * @property string $content
33
 * @property string $announce
34
 * @property integer $sort_order
35
 * @property string $date_added
36
 * @property string $date_modified
37
 * @property string $show_type
38
 * @property string $name
39
 * @property Page[] $children children of current page
40
 * @property Page $parent parent of current page
41
 * @property string|false $subdomain subdomain's name or false if it's not set
42
 * @property Image $images
43
 */
44
class Page extends ActiveRecord implements \JsonSerializable
45
{
46
    use GetImages;
47
    private static $identity_map = [];
48
49
    /**
50
     * @inheritdoc
51
     */
52
    public static function tableName()
53
    {
54
        return '{{%page}}';
55
    }
56
57
    /**
58
     * @inheritdoc
59
     */
60 View Code Duplication
    public function rules()
61
    {
62
        return [
63
            [['slug', 'title'], 'required'],
64
            [['robots', 'parent_id', 'sort_order'], 'integer'],
65
            [['slug_absolute', 'published', 'searchable'], 'boolean'],
66
            [
67
                [
68
                    'content',
69
                    'title',
70
                    'h1',
71
                    'meta_description',
72
                    'breadcrumbs_label',
73
                    'announce',
74
                    'slug_compiled',
75
                    'name'
76
                ],
77
                'string'
78
            ],
79
            [['date_added', 'date_modified'], 'safe'],
80
            [['slug'], 'string', 'max' => 80],
81
            [['slug_compiled'], 'string', 'max' => 180],
82
            [['show_type', 'subdomain'], 'string'],
83
            ['sort_order', 'default', 'value' => 0],
84
        ];
85
    }
86
87
    /**
88
     * @inheritdoc
89
     */
90
    public function attributeLabels()
91
    {
92
        return [
93
            'id' => Yii::t('app', 'ID'),
94
            'slug' => Yii::t('app', 'Slug'),
95
            'slug_compiled' => Yii::t('app', 'Slug Compiled'),
96
            'slug_absolute' => Yii::t('app', 'Slug Absolute'),
97
            'content' => Yii::t('app', 'Content'),
98
            'published' => Yii::t('app', 'Published'),
99
            'searchable' => Yii::t('app', 'Searchable'),
100
            'show_type' => Yii::t('app', 'Show Type'),
101
            'robots' => Yii::t('app', 'Robots'),
102
            'title' => Yii::t('app', 'Title'),
103
            'h1' => Yii::t('app', 'H1'),
104
            'meta_description' => Yii::t('app', 'Meta Description'),
105
            'breadcrumbs_label' => Yii::t('app', 'Breadcrumbs Label'),
106
            'announce' => Yii::t('app', 'Announce'),
107
            'sort_order' => Yii::t('app', 'Sort Order'),
108
            'date_added' => Yii::t('app', 'Date Added'),
109
            'date_modified' => Yii::t('app', 'Date Modified'),
110
            'subdomain' => Yii::t('app', 'Subdomain'),
111
            'name' => Yii::t('app', 'Name'),
112
        ];
113
    }
114
115
    /**
116
     * @inheritdoc
117
     */
118 View Code Duplication
    public function behaviors()
119
    {
120
        return [
121
            [
122
                'class' => HasProperties::className(),
123
            ],
124
            [
125
                'class' => ActiveRecordHelper::className(),
126
            ],
127
            [
128
                'class' => CleanRelations::className(),
129
            ],
130
            [
131
                'class' => Tree::className(),
132
                'activeAttribute' => 'published',
133
                'sortOrder' => [
134
                    'sort_order' => SORT_ASC,
135
                    'id' => SORT_ASC
136
                ],
137
            ],
138
            [
139
                'class' => TimestampBehavior::className(),
140
                'createdAtAttribute' => 'date_added',
141
                'updatedAtAttribute' => 'date_modified',
142
                'value' => new Expression('NOW()'),
143
                'attributes' => [
144
                    ActiveRecord::EVENT_BEFORE_INSERT => ['date_added'],
145
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['date_modified'],
146
                ],
147
            ],
148
        ];
149
    }
150
151
152
    /**
153
     * Search tasks
154
     * @param $params
155
     * @return ActiveDataProvider
156
     */
157
    public function search($params)
158
    {
159
        /** @var $query \yii\db\ActiveQuery */
160
        $query = self::find()->with('images');
161
        if (null != $this->parent_id) {
162
            $query->andWhere(['parent_id' => $this->parent_id]);
163
        }
164
        $dataProvider = new ActiveDataProvider([
165
            'query' => $query,
166
            'pagination' => [
167
                'pageSize' => 10,
168
            ],
169
        ]);
170
        if (!($this->load($params))) {
171
            return $dataProvider;
172
        }
173
        $query->andFilterWhere(['id' => $this->id]);
174
        $query->andFilterWhere(['like', 'slug', $this->slug]);
175
        $query->andFilterWhere(['like', 'slug_compiled', $this->slug_compiled]);
176
        $query->andFilterWhere(['like', 'slug_absolute', $this->slug_absolute]);
177
        $query->andFilterWhere(['published' => $this->published]);
178
        $query->andFilterWhere(['like', 'title', $this->title]);
179
        $query->andFilterWhere(['like', 'h1', $this->h1]);
180
        $query->andFilterWhere(['like', 'meta_description', $this->meta_description]);
181
        $query->andFilterWhere(['like', 'breadcrumbs_label', $this->breadcrumbs_label]);
182
        return $dataProvider;
183
    }
184
185
    /**
186
     * @param int $id
187
     * @param int $is_published
188
     * @return mixed
189
     */
190
    public static function findById($id, $is_published = 1)
191
    {
192
        if (!is_numeric($id)) {
193
            return null;
194
        }
195
        if (!isset(static::$identity_map[$id])) {
196
197
            $cacheKey = "Page:$id:$is_published";
198
            static::$identity_map[$id] = Yii::$app->cache->get($cacheKey);
199
            if (!is_object(static::$identity_map[$id])) {
200
                static::$identity_map[$id] = Page::find()->where(['id' => $id, 'published' => $is_published])->with('images')->one();
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
201
202
                if (is_object(static::$identity_map[$id])) {
203
                    Yii::$app->cache->set(
204
                        $cacheKey,
205
                        static::$identity_map[$id],
206
                        86400,
207
                        new TagDependency([
208
                            'tags' => [
209
                                ActiveRecordHelper::getCommonTag(static::className())
210
                            ]
211
                        ])
212
                    );
213
                }
214
            }
215
        }
216
        return static::$identity_map[$id];
217
    }
218
219
    /**
220
     * @inheritdoc
221
     */
222
    public function beforeSave($insert)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
223
    {
224
        if (!$insert) {
225
            // reset a cache tag to get a new parent model below
226
            TagDependency::invalidate(Yii::$app->cache, [ActiveRecordHelper::getCommonTag(self::className())]);
227
        }
228
        $this->slug_compiled = $this->compileSlug();
229
        TagDependency::invalidate(
230
            Yii::$app->cache,
231
            [
232
                ActiveRecordHelper::getCommonTag($this->className()),
233
                'Page:' . $this->slug_compiled
234
            ]
235
        );
236
        TagDependency::invalidate(
237
            Yii::$app->cache,
238
            [
239
                ActiveRecordHelper::getCommonTag($this->className()),
240
                'Page:' . $this->id . ':0'
241
            ]
242
        );
243
        TagDependency::invalidate(
244
            Yii::$app->cache,
245
            [
246
                ActiveRecordHelper::getCommonTag($this->className()),
247
                'Page:' . $this->id . ':1'
248
            ]
249
        );
250
        if (empty($this->breadcrumbs_label)) {
251
            $this->breadcrumbs_label = $this->title;
252
        }
253
        if (empty($this->h1)) {
254
            $this->h1 = $this->title;
255
        }
256
        return parent::beforeSave($insert);
257
    }
258
259
    /**
260
     * @inheritdoc
261
     */
262
    public function afterSave($insert, $changedAttributes)
263
    {
264
        parent::afterSave($insert, $changedAttributes);
265
266
        static::$identity_map[$this->id] = $this;
267
268
    }
269
270
    /**
271
     * Compiles url for subdomain's links like http://subdomain.example.com
272
     *
273
     * Respects schema, relies on Yii::$app->getModule("core")->serverName as main domain name
274
     * and Yii::$app->getModule("core")->serverPort
275
     *
276
     * @param string $sub_domain
277
     * @param string $slug
278
     * @return string compiled url
279
     */
280
    private function compileUrl($sub_domain, $slug = "")
281
    {
282
        $schema = Yii::$app->request->isSecureConnection ? "https://" : "http://";
283
        $main_domain = Yii::$app->getModule("core")->getBaseUrl();
284
285
        return "{$schema}{$sub_domain}.{$main_domain}/{$slug}";
286
    }
287
288
    /**
289
     * Compiles slug based on parent compiled slug, slug absoluteness and subdomain property
290
     * @return string
291
     */
292
    public function compileSlug()
293
    {
294
        // accessing parent's model via Tree behaviour
295
        $parent_model = $this->parent;
296
297
        if (intval($this->slug_absolute) === 1) {
298
            $slug = $this->slug === ":mainpage:" ? "" : $this->slug;
299
            $subdomain = null;
300
            if (empty($this->subdomain) === false) {
301
                $subdomain = $this->subdomain;
302
            } elseif ($parent_model !== null) {
303
                if (empty($parent_model->subdomain) === false) {
304
                    // subdomain in parent is set - here is not
305
                    $subdomain = $parent_model->subdomain;
306
                }
307
            }
308
309
            if ($subdomain === null) {
310
                // subdomain is empty
311
                // no root
312
                return $this->slug;
313
            } else {
314
                return $this->compileUrl($subdomain, $slug);
315
            }
316
        } else {
317
            // not-absolute slug
318
            if ($parent_model !== null) {
319
                // should prepend parent's slug
320
                // can't be another domain then parent
321
                if ($parent_model->slug === ':mainpage:') {
322
                    return $this->slug;
323
                } else {
324
                    return $parent_model->slug_compiled . '/' . $this->slug;
325
                }
326
            } else {
327
                return ':mainpage:'; // it's main page
328
            }
329
        }
330
    }
331
332
    /**
333
     * @param string $path PATH из запроса ( $request->getPathInfo() )
0 ignored issues
show
Documentation introduced by
Should the type for parameter $path not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
334
     * @return mixed|null
335
     */
336
    public static function getByUrlPath($path = null)
337
    {
338
        if ((null === $path) || !is_string($path)) {
339
            return null;
340
        }
341
        $cacheKey = "Page:$path";
342
        $page = Yii::$app->cache->get($cacheKey);
343
        if ($page === false) {
344
            $page = static::find()->where(['slug_compiled' => $path, 'published' => 1])->asArray()->one();
345
            $duration = 86400;
346
            if (!is_array($page)) {
347
                $duration = 3600;
348
            }
349
            Yii::$app->cache->set(
350
                $cacheKey,
351
                $page,
352
                $duration,
353
                new TagDependency([
354
                    'tags' => [
355
                        ActiveRecordHelper::getCommonTag(static::className())
356
                    ]
357
                ])
358
            );
359
        }
360
        return $page;
361
    }
362
363
    /**
364
     * Preparation to delete page.
365
     * Deleting all inserted pages.
366
     * @return bool
367
     */
368 View Code Duplication
    public function beforeDelete()
369
    {
370
        if (!parent::beforeDelete()) {
371
            return false;
372
        }
373
        foreach ($this->children as $child) {
374
            /** @var Page $child */
375
            $child->delete();
376
        }
377
        return true;
378
    }
379
380
    public function getChildren()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
381
    {
382
        return $this->hasMany(Page::className(), ['parent_id' => 'id'])->orderBy(['sort_order'=>SORT_ASC]);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
383
    }
384
385
    /**
386
     * @return string
387
     */
388
    public function __toString()
389
    {
390
        return ($this->className() . ':' . $this->id);
391
    }
392
393
    /**
394
     * @return string
395
     */
396
    public function jsonSerialize()
397
    {
398
        return ($this->className() . ':' . $this->id);
399
    }
400
}