PostController::actionView()   D
last analyzed

Complexity

Conditions 10
Paths 31

Size

Total Lines 35
Code Lines 21

Duplication

Lines 11
Ratio 31.43 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 11
loc 35
rs 4.8196
cc 10
eloc 21
nc 31
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://www.writesdown.com/
4
 * @copyright Copyright (c) 2015 WritesDown
5
 * @license http://www.writesdown.com/license/
6
 */
7
8
namespace frontend\controllers;
9
10
use common\models\Option;
11
use common\models\Post;
12
use common\models\PostComment as Comment;
13
use common\models\PostType;
14
use Yii;
15
use yii\data\Pagination;
16
use yii\web\Controller;
17
use yii\web\NotFoundHttpException;
18
19
/**
20
 * Class PostController
21
 *
22
 * @author Agiel K. Saputra <[email protected]>
23
 * @since 0.1.0
24
 */
25
class PostController extends Controller
26
{
27
    /**
28
     * @param int|null $id Post type ID
29
     * @param string|null $slug Post type slug.
30
     * @return string
31
     * @throws \yii\web\NotFoundHttpException
32
     */
33 View Code Duplication
    public function actionIndex($id = null, $slug = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
34
    {
35
        $render = 'index';
36
37
        if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
38
            $postType = $this->findPostType($id);
39
        } elseif ($slug) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $slug of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
40
            $postType = $this->findPostTypeBySlug($slug);
41
        } else {
42
            throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
43
        }
44
45
        $query = $postType->getPosts()
0 ignored issues
show
Bug introduced by
The method getPosts cannot be called on $postType (of type array|boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
46
            ->andWhere(['status' => 'publish'])
47
            ->andWhere(['<=', 'date', date('Y-m-d H:i:s')])
48
            ->orderBy(['id' => SORT_DESC]);
49
        $countQuery = clone $query;
50
        $pages = new Pagination([
51
            'totalCount' => $countQuery->count(),
52
            'pageSize' => Option::get('posts_per_page'),
53
        ]);
54
        $query->offset($pages->offset)->limit($pages->limit);
55
        $posts = $query->all();
56
57
        if ($posts) {
58
            if (is_file($this->view->theme->basePath . '/post/index-' . $postType->name . '.php')) {
59
                $render = 'index-' . $postType->name . '.php';
60
            }
61
62
            return $this->render($render, [
63
                'postType' => $postType,
64
                'posts' => $posts,
65
                'pages' => $pages,
66
            ]);
67
        }
68
69
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
70
    }
71
72
    /**
73
     * Displays a single Post model.
74
     *
75
     * @param null $slug Post slug
76
     * @param integer $id Post ID
77
     * @throws \yii\web\NotFoundHttpException
78
     * @return mixed
79
     */
80
    public function actionView($id = null, $slug = null)
81
    {
82
        $render = 'view';
83
        $comment = new Comment();
84
85
        if ($id) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
86
            $model = $this->findModel($id);
87
        } elseif ($slug) {
88
            $model = $this->findModelBySlug($slug);
89
        } else {
90
            throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
91
        }
92
93 View Code Duplication
        if ($comment->load(Yii::$app->request->post()) && $comment->save()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
            if (!$comment->parent) {
95
                $model->comment_count++;
96
            }
97
            if ($model->save()) {
98
                $this->refresh();
99
            }
100
        }
101
102 View Code Duplication
        if ($model->password && $model->password !== Yii::$app->request->post('password')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
103
            return $this->render('protected', ['post' => $model]);
104
        }
105
106
        if (is_file($this->view->theme->basePath . '/post/view-' . $model->postType->name . '.php')) {
107
            $render = 'view-' . $model->postType->name . '.php';
108
        }
109
110
        return $this->render($render, [
111
            'post' => $model,
112
            'comment' => $comment,
113
        ]);
114
    }
115
116
    /**
117
     * Finds the Post model based on its primary key value.
118
     * If the model is not found, a 404 HTTP exception will be thrown.
119
     *
120
     * @param integer $id
121
     * @return Post the loaded model
122
     * @throws NotFoundHttpException if the model cannot be found
123
     */
124 View Code Duplication
    protected function findModel($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
125
    {
126
        $model = Post::find()
0 ignored issues
show
Bug Compatibility introduced by
The expression \common\models\Post::fin...Y-m-d H:i:s')))->one(); of type yii\db\ActiveRecord|array|null adds the type array to the return on line 132 which is incompatible with the return type documented by frontend\controllers\PostController::findModel of type common\models\Post.
Loading history...
127
            ->andWhere(['id' => $id, 'status' => 'publish'])
128
            ->andWhere(['<=', 'date', date('Y-m-d H:i:s')])
129
            ->one();
130
131
        if ($model) {
132
            return $model;
133
        }
134
135
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
136
    }
137
138
139
    /**
140
     * Finds the Post model based on its primary key value.
141
     * If the model is not found, a 404 HTTP exception will be thrown.
142
     *
143
     * @param string $slug
144
     * @return Post the loaded model
145
     * @throws NotFoundHttpException if the model cannot be found
146
     */
147 View Code Duplication
    protected function findModelBySlug($slug)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
    {
149
        $model = Post::find()
0 ignored issues
show
Bug Compatibility introduced by
The expression \common\models\Post::fin...Y-m-d H:i:s')))->one(); of type yii\db\ActiveRecord|array|null adds the type array to the return on line 155 which is incompatible with the return type documented by frontend\controllers\Pos...roller::findModelBySlug of type common\models\Post.
Loading history...
150
            ->andWhere(['slug' => $slug, 'status' => 'publish'])
151
            ->andWhere(['<=', 'date', date('Y-m-d H:i:s')])
152
            ->one();
153
154
        if ($model) {
155
            return $model;
156
        }
157
158
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
159
    }
160
161
    /**
162
     * Finds the Post model based on its primary key value.
163
     * If the model is not found, a 404 HTTP exception will be thrown.
164
     *
165
     * @param $id
166
     * @throws \yii\web\NotFoundHttpException
167
     * @return PostType the loaded model
168
     */
169
    protected function findPostType($id)
170
    {
171
        $model = PostType::findOne($id);
172
173
        if ($model) {
174
            return $model;
175
        }
176
177
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
178
    }
179
180
    /**
181
     * Finds the Post model based on its primary key value.
182
     * If the model is not found, a 404 HTTP exception will be thrown.
183
     *
184
     * @param string $slug Post type slug
185
     * @throws \yii\web\NotFoundHttpException
186
     * @return PostType the loaded model
187
     */
188
    protected function findPostTypeBySlug($slug)
189
    {
190
        $model = PostType::findOne(['slug' => $slug]);
191
192
        if ($model) {
193
            return $model;
194
        }
195
196
        throw new NotFoundHttpException(Yii::t('writesdown', 'The requested page does not exist.'));
197
    }
198
}
199