DefaultController::actionIndex()   D
last analyzed

Complexity

Conditions 16
Paths 90

Size

Total Lines 107
Code Lines 68

Duplication

Lines 21
Ratio 19.63 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 21
loc 107
rs 4.8736
cc 16
eloc 68
nc 90
nop 0

How to fix   Long Method    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 modules\sitemap\frontend\controllers;
9
10
use common\models\Media;
11
use common\models\Option;
12
use common\models\Post;
13
use common\models\PostType;
14
use common\models\Taxonomy;
15
use common\models\Term;
16
use Yii;
17
use yii\data\Pagination;
18
use yii\filters\AccessControl;
19
use yii\helpers\ArrayHelper;
20
use yii\helpers\Url;
21
use yii\web\Controller;
22
23
/**
24
 * Class DefaultController
25
 *
26
 * @author  Agiel K. Saputra <[email protected]>
27
 * @since   0.2.0
28
 */
29
class DefaultController extends Controller
30
{
31
    /**
32
     * @var array option for sitemap
33
     */
34
    private $_option = [];
35
36
    /**
37
     * @inheritdoc
38
     */
39
    public function behaviors()
40
    {
41
        return [
42
            'access' => [
43
                'class' => AccessControl::className(),
44
                'rules' => [
45
                    [
46
                        'actions'       => ['index', 'style', 'view'],
47
                        'allow'         => true,
48
                        'matchCallback' => function () {
49
                            $option = Option::get('sitemap');
50
51
                            return $option['enable_sitemap'];
52
                        },
53
                    ],
54
                ],
55
            ],
56
        ];
57
    }
58
59
    /**
60
     * @return string
61
     */
62
    public function actionIndex()
63
    {
64
        /* @var $postType PostType */
65
        /* @var $post Post */
66
        /* @var $taxonomies Taxonomy[] */
67
        /* @var $taxonomy Taxonomy */
68
        /* @var $lastMedia Media */
69
70
        $response = Yii::$app->response;
71
        $response->headers->set('Content-Type', 'text/xml; charset=UTF-8');
72
        $response->format = $response::FORMAT_RAW;
73
        $postTypes = PostType::find()->select(['id', 'slug'])->all();
74
        $taxonomies = Taxonomy::find()->select(['id', 'slug'])->all();
75
        $items = [];
76
77
        foreach ($postTypes as $postType) {
78
            if (isset($this->_option['post_type'][$postType->id]['enable'])
79
                && $this->_option['post_type'][$postType->id]['enable']
80
            ) {
81
                if ($post = $postType->getPosts()
82
                    ->andWhere(['status' => Post::STATUS_PUBLISH])
83
                    ->andWhere(['<=', 'date', date('Y-m-d H:i:s')])
84
                    ->orderBy(['id' => SORT_DESC])
85
                    ->one()
86
                ) {
87
                    $lastmod = new \DateTime($post->modified, new \DateTimeZone(Option::get('time_zone')));
88
                    $query = $postType->getPosts()
89
                        ->andWhere(['status' => Post::STATUS_PUBLISH])
90
                        ->andWhere(['<=', 'date', date('Y-m-d H:i:s')]);
91
                    $countQuery = clone $query;
92
                    $pages = new Pagination([
93
                        'totalCount' => $countQuery->count(),
94
                        'pageSize'   => $this->_option['entries_per_page'],
95
                    ]);
96 View Code Duplication
                    for ($i = 1; $i <= $pages->pageCount; $i++) {
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...
97
                        $items[] = [
98
                            'loc'     => Yii::$app->urlManager->hostInfo
99
                                . Url::to(['view', 'type' => 'p', 'slug' => $postType->slug, 'page' => $i]),
100
                            'lastmod' => $lastmod->format('r'),
101
                        ];
102
                    }
103
                }
104
            }
105
        }
106
107
        foreach ($taxonomies as $taxonomy) {
108
            if (isset($this->_option['taxonomy'][$taxonomy->id]['enable'])
109
                && $this->_option['taxonomy'][$taxonomy->id]['enable']
110
            ) {
111
                if ($terms = $taxonomy->terms) {
112
                    $post = Post::find()
113
                        ->from(['post' => Post::tableName()])
114
                        ->innerJoinWith([
115
                            'terms' => function ($query) {
116
                                /* @var $query \yii\db\ActiveQuery */
117
                                $query->from(['term' => Term::tableName()]);
118
                            },
119
                        ])
120
                        ->where(['IN', 'term.id', ArrayHelper::getColumn($terms, 'id')])
121
                        ->andWhere(['post.status' => Post::STATUS_PUBLISH])
122
                        ->andWhere(['<=', 'date', date('Y-m-d H:i:s')])
123
                        ->orderBy(['post.id' => SORT_DESC])
124
                        ->one();
125
126
                    if ($post) {
127
                        $query = $taxonomy->getTerms();
128
                        $lastmod = new \DateTime($post->modified, new \DateTimeZone(Option::get('time_zone')));
129
                        $countQuery = clone $query;
130
                        $pages = new Pagination([
131
                            'totalCount' => $countQuery->count(),
132
                            'pageSize'   => $this->_option['entries_per_page'],
133
                        ]);
134
135 View Code Duplication
                        for ($i = 1; $i <= $pages->pageCount; $i++) {
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...
136
                            $items[] = [
137
                                'loc'     => Yii::$app->urlManager->hostInfo
138
                                    . Url::to(['view', 'type' => 'c', 'slug' => $taxonomy->slug, 'page' => $i]),
139
                                'lastmod' => $lastmod->format('r'),
140
                            ];
141
                        }
142
                    }
143
                }
144
            }
145
        }
146
147
        if (isset($this->_option['media']['enable']) && $this->_option['media']['enable']) {
148
            $query = Media::find();
149
            $countQuery = clone $query;
150
            $pages = new Pagination([
151
                'totalCount' => $countQuery->count(),
152
                'pageSize'   => $this->_option['entries_per_page'],
153
            ]);
154
155
            if ($lastMedia = $query->orderBy(['id' => SORT_DESC])->one()) {
156
                $lastmod = new \DateTime($lastMedia->modified, new \DateTimeZone(Option::get('time_zone')));
157 View Code Duplication
                for ($i = 1; $i <= $pages->pageCount; $i++) {
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...
158
                    $items[] = [
159
                        'loc'     => Yii::$app->urlManager->hostInfo
160
                            . Url::to(['view', 'type' => 'm', 'slug' => 'media', 'page' => $i]),
161
                        'lastmod' => $lastmod->format('r'),
162
                    ];
163
                }
164
            }
165
        }
166
167
        return $this->renderPartial('index', ['items' => $items]);
168
    }
169
170
    /**
171
     * @return string
172
     */
173
    public function actionStyle()
174
    {
175
        $response = Yii::$app->response;
176
        $response->headers->set('Content-Type', 'text/xml; charset=UTF-8');
177
        $response->format = $response::FORMAT_RAW;
178
179
        return $this->renderPartial('style');
180
    }
181
182
    /**
183
     * @param string $type
184
     * @param string $slug
185
     * @param int    $page
186
     *
187
     * @return string
188
     */
189
    public function actionView($type, $slug, $page = 1)
190
    {
191
        /* @var $taxonomy Taxonomy */
192
        /* @var $postType PostType */
193
        /* @var $posts Post[] */
194
        /* @var $images Media[] */
195
        /* @var $terms Term[] */
196
        /* @var $mediaSet Media[] */
197
        /* @var $post Post */
198
199
        $page--;
200
        $items = [];
201
        $response = Yii::$app->response;
202
        $response->headers->set('Content-Type', 'text/xml; charset=UTF-8');
203
        $response->format = $response::FORMAT_RAW;
204
        if ($type === 'h') {
205
            $item['loc'] = Yii::$app->urlManager->hostInfo . Yii::$app->urlManager->baseUrl . '/';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$item was never initialized. Although not strictly required by PHP, it is generally a good practice to add $item = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
206
            $item['changefreq'] = $this->_option['home']['changefreq'];
207
            $item['priority'] = $this->_option['home']['priority'];
208
209
            return $this->renderPartial('home', ['item' => $item]);
210
        } elseif ($type === 'p') {
211
            $postType = PostType::find()->where(['slug' => $slug])->one();
212
            $posts = $postType->getPosts()
213
                ->andWhere(['status' => 'publish'])
214
                ->andWhere(['<=', 'date', date('Y-m-d H:i:s')])
215
                ->offset($page * $this->_option['entries_per_page'])
216
                ->limit($this->_option['entries_per_page'])
217
                ->all();
218
219
            foreach ($posts as $post) {
220
                $lastmod = new \DateTime($post->modified, new \DateTimeZone(Option::get('time_zone')));
221
                $items[$post->id]['loc'] = $post->url;
222
                $items[$post->id]['lastmod'] = $lastmod->format('r');
223
                $items[$post->id]['changefreq'] = $this->_option['post_type'][$postType->id]['changefreq'];
224
                $items[$post->id]['priority'] = $this->_option['post_type'][$postType->id]['priority'];
225
226
                if ($images = $post->getMedia()->where(['LIKE', 'mime_type', 'image'])->all()) {
227
                    foreach ($images as $image) {
228
                        $metadata = $image->getMeta('metadata');
229
                        $items[$post->id]['image'][$image->id]['loc'] = $image->getUploadUrl()
230
                            . $metadata['versions']['full']['url'];
231
                        $items[$post->id]['image'][$image->id]['title'] = $image->title
232
                            ? $image->title
233
                            : null;
234
                        $items[$post->id]['image'][$image->id]['caption'] = $image->excerpt
235
                            ? $image->excerpt
236
                            : null;
237
                    }
238
                }
239
            }
240
241
            return $this->renderPartial('post-type', ['items' => $items]);
242
        } elseif ($type === 'c') {
243
            $taxonomy = Taxonomy::find()->where(['slug' => $slug])->one();
244
            $terms = $taxonomy->getTerms()
245
                ->offset($page * $this->_option['entries_per_page'])
246
                ->limit($this->_option['entries_per_page'])
247
                ->all();
248
249
            foreach ($terms as $term) {
250
                $post = $term->getPosts()
251
                    ->andWhere(['status' => Post::STATUS_PUBLISH])
252
                    ->andWhere(['<=', 'date', date('Y-m-d H:i:s')])
253
                    ->orderBy(['id' => SORT_DESC])
254
                    ->one();
255
256
                if ($post) {
257
                    $lastmod = new \DateTime($post->modified, new \DateTimeZone(Option::get('time_zone')));
258
                    $items[$term->id]['loc'] = $term->url;
259
                    $items[$term->id]['lastmod'] = $lastmod->format('r');
260
                    $items[$term->id]['changefreq'] = $this->_option['taxonomy'][$taxonomy->id]['changefreq'];
261
                    $items[$term->id]['priority'] = $this->_option['taxonomy'][$taxonomy->id]['priority'];
262
                }
263
            }
264
265
            return $this->renderPartial('taxonomy', ['items' => $items]);
266
        } elseif ($type === 'm') {
267
            $mediaSet = Media::find()
268
                ->offset($page * $this->_option['entries_per_page'])
269
                ->limit($this->_option['entries_per_page'])
270
                ->all();
271
            foreach ($mediaSet as $media) {
272
                $lastmod = new \DateTime($media->modified, new \DateTimeZone(Option::get('time_zone')));
273
                $items[$media->id]['loc'] = $media->getUrl();
274
                $items[$media->id]['lastmod'] = $lastmod->format('r');
275
                $items[$media->id]['changefreq'] = $this->_option['media']['changefreq'];
276
                $items[$media->id]['priority'] = $this->_option['media']['priority'];
277
            }
278
279
            return $this->renderPartial('media', ['items' => $items]);
280
        }
281
282
        return $this->redirect(['/site/not-found']);
283
    }
284
285
    /**
286
     * @inheritdoc
287
     */
288
    public function beforeAction($action)
289
    {
290
        /*  @var $postType \common\models\PostType */
291
        /*  @var $taxonomy \common\models\Taxonomy */
292
        if (parent::beforeAction($action)) {
293
            $this->_option = Option::get('sitemap');
0 ignored issues
show
Documentation Bug introduced by
It seems like \common\models\Option::get('sitemap') can also be of type string or boolean. However, the property $_option is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
294
295
            return true;
296
        }
297
298
        return false;
299
    }
300
}
301