Passed
Push — v3 ( d49e4d...c31cc7 )
by Andrew
17:27 queued 08:45
created

ContentSeoController::actionMetaBundles()   F

Complexity

Conditions 20
Paths 324

Size

Total Lines 124
Code Lines 86

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 20
eloc 86
c 4
b 0
f 0
nc 324
nop 5
dl 0
loc 124
rs 1.7833

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
 * SEOmatic plugin for Craft CMS 3.x
4
 *
5
 * @link      https://nystudio107.com/
6
 * @copyright Copyright (c) 2019 nystudio107
7
 * @license   https://nystudio107.com/license
0 ignored issues
show
Coding Style introduced by
@license tag must contain a URL and a license name
Loading history...
8
 */
9
10
namespace nystudio107\seomatic\controllers;
11
12
use nystudio107\seomatic\base\SeoElementInterface;
13
use nystudio107\seomatic\models\MetaBundle;
14
use nystudio107\seomatic\Seomatic;
15
use nystudio107\seomatic\services\SeoElements;
16
17
use Craft;
18
use craft\db\Query;
19
use craft\helpers\UrlHelper;
20
use craft\web\Controller;
21
22
use yii\web\Response;
23
24
/**
25
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
26
 * @package   Seomatic
27
 * @since     3.2.18
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
28
 */
29
class ContentSeoController extends Controller
30
{
31
    // Constants
32
    // =========================================================================
33
34
    // Protected Properties
35
    // =========================================================================
36
37
    /**
38
     * @var    bool|array
39
     */
40
    protected $allowAnonymous = [
41
    ];
42
43
    // Public Methods
44
    // =========================================================================
45
46
    /**
47
     * Handle requests for the dashboard statistics table
48
     *
49
     * @param string   $sort
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
50
     * @param int      $page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
51
     * @param int      $per_page
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
52
     * @param string   $filter
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
53
     * @param null|int $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
54
     *
55
     * @return Response
56
     */
57
    public function actionMetaBundles(
58
        string $sort = 'sourceName|asc',
59
        int $page = 1,
60
        int $per_page = 20,
61
        $filter = '',
62
        $siteId = 0
63
    ): Response {
64
        $data = [];
65
        $sortField = 'sourceName';
66
        $sortType = 'ASC';
67
        $additionalSort = '';
68
        // Figure out the sorting type
69
        if ($sort !== '') {
70
            if (strpos($sort, '|') === false) {
71
                $sortField = $sort;
72
            } else {
73
                list($sortField, $sortType) = explode('|', $sort);
74
            }
75
        }
76
        if ($sortField !== 'sourceName') {
77
            $additionalSort = ', sourceName ASC';
78
        }
79
        // Query the db table
80
        $offset = ($page - 1) * $per_page;
81
82
        $query = (new Query())
83
            ->from(['{{%seomatic_metabundles}}'])
84
            ->offset($offset)
85
            ->limit($per_page)
86
            ->orderBy("{$sortField} {$sortType}".$additionalSort)
87
            ->where(['!=', 'sourceBundleType', Seomatic::$plugin->metaBundles::GLOBAL_META_BUNDLE])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
88
            ;
89
        $currentSiteHandle = '';
90
        if ((int)$siteId !== 0) {
91
            $query->andWhere(['sourceSiteId' => $siteId]);
92
            $site = Craft::$app->getSites()->getSiteById($siteId);
0 ignored issues
show
Bug introduced by
It seems like $siteId can also be of type null; however, parameter $siteId of craft\services\Sites::getSiteById() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

92
            $site = Craft::$app->getSites()->getSiteById(/** @scrutinizer ignore-type */ $siteId);
Loading history...
93
            if ($site !== null) {
94
                $currentSiteHandle = $site->handle;
95
            }
96
        }
97
        if ($filter !== '') {
98
            $query->andWhere(['like', 'sourceName', $filter]);
99
        }
100
        $bundles = $query->all();
101
        if ($bundles) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $bundles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
102
            $dataArray = [];
103
            // Add in the `addLink` field
104
            foreach ($bundles as $bundle) {
105
                $dataItem = [];
106
                $metaBundle = MetaBundle::create($bundle);
107
                if ($metaBundle !== null) {
108
                    $sourceBundleType = $metaBundle->sourceBundleType;
109
                    $sourceHandle = $metaBundle->sourceHandle;
110
                    $dataItem['sourceName'] = $metaBundle->sourceName;
111
                    $dataItem['sourceType'] = $metaBundle->sourceType;
112
                    $dataItem['contentSeoUrl'] = UrlHelper::cpUrl(
113
                        "seomatic/edit-content/general/{$sourceBundleType}/{$sourceHandle}/{$currentSiteHandle}"
114
                    );
115
                    // Fill in the number of entries
116
                    $entries = 0;
117
                    $seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType(
118
                        $metaBundle->sourceBundleType
119
                    );
120
                    /** @var SeoElementInterface $seoElement */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
121
                    if ($seoElement !== null) {
122
                        $query = $seoElement::sitemapElementsQuery($metaBundle);
123
                        $entries = $query->count();
124
                        Craft::error('shit: ' . print_r($entries, true), __METHOD__);
125
                    }
126
                    $dataItem['entries'] = $entries;
127
                    // Basic configuration setup
128
                    $dataItem['title'] = $metaBundle->metaGlobalVars->seoTitle !== '' ? 'enabled' : 'disabled';
129
                    $dataItem['description'] = $metaBundle->metaGlobalVars->seoDescription !== '' ? 'enabled' : 'disabled';
130
                    $dataItem['image'] = $metaBundle->metaGlobalVars->seoImage !== '' ? 'enabled' : 'disabled';
131
                    $dataItem['sitemap'] = $metaBundle->metaSitemapVars->sitemapUrls ? 'enabled' : 'disabled';
132
                    $dataItem['robots'] = $metaBundle->metaGlobalVars->robots;
133
                    // Calculate the setup stat
134
                    $stat = 0;
135
                    $numGrades = \count(SettingsController::SETUP_GRADES);
136
                    $numFields = \count(SettingsController::SEO_SETUP_FIELDS);
137
                    foreach (SettingsController::SEO_SETUP_FIELDS as $setupField => $setupLabel) {
138
                        $stat += (int)!empty($metaBundle->metaGlobalVars[$setupField]);
139
                        $value = $variables['contentSetupChecklist'][$setupField]['value'] ?? 0;
140
                        $variables['contentSetupChecklist'][$setupField] = [
141
                            'label' => $setupLabel,
142
                            'value' => $value + (int)!empty($metaBundle->metaGlobalVars[$setupField]),
143
                        ];
144
                    }
145
                    $stat = round($numGrades - (($stat * $numGrades) / $numFields));
146
                    if ($stat >= $numGrades) {
147
                        $stat = $numGrades - 1;
148
                    }
149
                    $dataItem['setup'] = SettingsController::SETUP_GRADES[$stat];
150
151
                    $dataArray[] = $dataItem;
152
                }
153
            }
154
            // Format the data for the API
155
            $data['data'] = $dataArray;
156
            $query = (new Query())
157
                ->from(['{{%seomatic_metabundles}}'])
158
                ->orderBy("{$sortField} {$sortType}")
159
                ->where(['!=', 'sourceBundleType', Seomatic::$plugin->metaBundles::GLOBAL_META_BUNDLE])
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
160
            ;
161
            if ((int)$siteId !== 0) {
162
                $query->andWhere(['sourceSiteId' => $siteId]);
163
            }
164
            if ($filter !== '') {
165
                $query->andWhere(['like', 'sourceName', $filter]);
166
            }
167
            $count = $query->count();
168
            $data['links']['pagination'] = [
169
                'total' => $count,
170
                'per_page' => $per_page,
171
                'current_page' => $page,
172
                'last_page' => ceil($count / $per_page),
173
                'next_page_url' => null,
174
                'prev_page_url' => null,
175
                'from' => $offset + 1,
176
                'to' => $offset + ($count > $per_page ? $per_page : $count),
177
            ];
178
        }
179
180
        return $this->asJson($data);
181
    }
182
183
    // Protected Methods
184
    // =========================================================================
185
}
186