Passed
Push — develop ( 8c641f...efd4ff )
by Andrew
02:59
created

MultiSite::setMultiSiteVariables()   B

Complexity

Conditions 11
Paths 120

Size

Total Lines 53
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 53
rs 7.15
c 0
b 0
f 0
cc 11
nc 120
nop 3

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
 * Webperf plugin for Craft CMS 3.x
4
 *
5
 * Monitor the performance of your webpages through real-world user timing data
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2018 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\webperf\helpers;
12
13
use Craft;
0 ignored issues
show
Bug introduced by
The type Craft was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
use craft\helpers\ArrayHelper;
0 ignored issues
show
Bug introduced by
The type craft\helpers\ArrayHelper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use craft\models\Site;
0 ignored issues
show
Bug introduced by
The type craft\models\Site was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
17
use yii\web\ForbiddenHttpException;
0 ignored issues
show
Bug introduced by
The type yii\web\ForbiddenHttpException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use yii\web\NotFoundHttpException;
0 ignored issues
show
Bug introduced by
The type yii\web\NotFoundHttpException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
20
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
21
 * @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...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 4
Loading history...
22
 * @package   Webperf
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
23
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 3 spaces but found 5
Loading history...
24
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
25
class MultiSite
26
{
27
    // Constants
28
    // =========================================================================
29
30
    // Public Static Methods
31
    // =========================================================================
32
33
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
34
     * @param array $variables
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
35
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
36
    public static function setSitesMenuVariables(array &$variables)
37
    {
38
        // Set defaults based on the section settings
39
        $variables['sitesMenu'] = [
40
            0 => Craft::t(
41
                'webperf',
42
                'All Sites'
43
            ),
44
        ];
45
        // Enabled sites
46
        $sites = Craft::$app->getSites();
47
        if (Craft::$app->getIsMultiSite()) {
48
49
            /** @var Site $site */
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
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
50
            foreach ($sites->getAllGroups() as $group) {
51
                $groupSites = $sites->getSitesByGroupId($group->id);
52
                $variables['sitesMenu'][$group->name]
53
                    = ['optgroup' => $group->name];
54
                foreach ($groupSites as $groupSite) {
55
                    $variables['sitesMenu'][$groupSite->id] = $groupSite->name;
56
                }
57
            }
58
        }
59
    }
60
61
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $siteId should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $variables should have a doc-comment as per coding-style.
Loading history...
62
     * @param string $siteHandle
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
63
     * @param        $siteId
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 8
Loading history...
64
     * @param        $variables
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 8
Loading history...
65
     *
66
     * @throws \yii\web\ForbiddenHttpException
67
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
68
    public static function setMultiSiteVariables($siteHandle, &$siteId, array &$variables)
69
    {
70
        // Enabled sites
71
        $sites = Craft::$app->getSites();
72
        if (Craft::$app->getIsMultiSite()) {
73
            // Set defaults based on the section settings
74
            $variables['enabledSiteIds'] = [];
75
            $variables['siteIds'] = [];
76
77
            /** @var Site $site */
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
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
78
            foreach ($sites->getEditableSiteIds() as $editableSiteId) {
79
                $variables['enabledSiteIds'][] = $editableSiteId;
80
                $variables['siteIds'][] = $editableSiteId;
81
            }
82
83
            // Make sure the $siteId they are trying to edit is in our array of editable sites
84
            if (!\in_array($siteId, $variables['enabledSiteIds'], false)) {
85
                if (!empty($variables['enabledSiteIds'])) {
86
                    if ($siteId !== 0) {
87
                        $siteId = reset($variables['enabledSiteIds']);
88
                    }
89
                } else {
90
                    self::requirePermission('editSite:'.$siteId);
91
                }
92
            }
93
        }
94
        // Set the currentSiteId and currentSiteHandle
95
        $variables['currentSiteId'] = empty($siteId) ? 0 : $siteId;
96
        $variables['currentSiteHandle'] = empty($siteHandle)
97
            ? Craft::$app->getSites()->currentSite->handle
98
            : $siteHandle;
99
100
        // Page title
101
        $variables['showSites'] = (
102
            Craft::$app->getIsMultiSite() &&
103
            \count($variables['enabledSiteIds'])
104
        );
105
106
        if ($variables['showSites']) {
107
            if ($variables['currentSiteId'] === 0) {
108
                $variables['sitesMenuLabel'] = Craft::t(
109
                    'webperf',
110
                    'All Sites'
111
                );
112
            } else {
113
                $variables['sitesMenuLabel'] = Craft::t(
114
                    'site',
115
                    $sites->getSiteById((int)$variables['currentSiteId'])->name
116
                );
117
            }
118
        } else {
119
            $variables['currentSiteId'] = 0;
120
            $variables['sitesMenuLabel'] = '';
121
        }
122
    }
123
124
    /**
125
     * Return a siteId from a siteHandle
126
     *
127
     * @param string $siteHandle
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
128
     *
129
     * @return int|null
130
     * @throws NotFoundHttpException
131
     */
132
    public static function getSiteIdFromHandle($siteHandle)
133
    {
134
        // Get the site to edit
135
        if ($siteHandle !== null) {
0 ignored issues
show
introduced by
The condition $siteHandle !== null is always true.
Loading history...
136
            $site = Craft::$app->getSites()->getSiteByHandle($siteHandle);
137
            if (!$site) {
138
                throw new NotFoundHttpException('Invalid site handle: '.$siteHandle);
139
            }
140
            $siteId = $site->id;
141
        } else {
142
            $siteId = 0;
143
        }
144
145
        return $siteId;
146
    }
147
148
    /**
149
     * Returns the site that most closely matches the requested URL.
150
     * Adapted from craft\web\Request.php
151
     *
152
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
153
     *
154
     * @return Site
155
     * @throws \craft\errors\SiteNotFoundException
156
     */
157
    public static function getSiteFromUrl(string $url): Site
158
    {
159
        $sites = Craft::$app->getSites()->getAllSites();
160
        $request = Craft::$app->getRequest();
161
162
        $hostName = parse_url($url, PHP_URL_HOST);
163
        $fullUri = trim(parse_url($url, PHP_URL_PATH), '/');
164
        $secure = parse_url($url, PHP_URL_SCHEME) === 'https';
165
        $scheme = $secure ? 'https' : 'http';
166
        $port = $secure ? $request->getSecurePort() : $request->getPort();
167
168
        $scores = [];
169
        foreach ($sites as $i => $site) {
170
            if (!$site->baseUrl) {
171
                continue;
172
            }
173
174
            if (($parsed = parse_url(self::getBaseUrl($site))) === false) {
175
                Craft::warning('Unable to parse the site base URL: ' . $site->baseUrl);
176
                continue;
177
            }
178
179
            // Does the site URL specify a host name?
180
            if (!empty($parsed['host']) && $hostName && $parsed['host'] !== $hostName) {
181
                continue;
182
            }
183
184
            // Does the site URL specify a base path?
185
            $parsedPath = !empty($parsed['path']) ? self::normalizePath($parsed['path']) : '';
186
            if ($parsedPath && strpos($fullUri . '/', $parsedPath . '/') !== 0) {
187
                continue;
188
            }
189
190
            // It's a possible match!
191
            $scores[$i] = 8 + strlen($parsedPath);
192
193
            $parsedScheme = !empty($parsed['scheme']) ? strtolower($parsed['scheme']) : $scheme;
194
            $parsedPort = $parsed['port'] ?? ($parsedScheme === 'https' ? 443 : 80);
195
196
            // Do the ports match?
197
            if ($parsedPort == $port) {
198
                $scores[$i] += 4;
199
            }
200
201
            // Do the schemes match?
202
            if ($parsedScheme === $scheme) {
203
                $scores[$i] += 2;
204
            }
205
206
            // One Pence point if it's the primary site in case we need a tiebreaker
207
            if ($site->primary) {
208
                $scores[$i]++;
209
            }
210
        }
211
212
        if (empty($scores)) {
213
            // Default to the primary site
214
            return Craft::$app->getSites()->getPrimarySite();
215
        }
216
217
        // Sort by scores descending
218
        arsort($scores, SORT_NUMERIC);
219
        $first = ArrayHelper::firstKey($scores);
220
221
        return $sites[$first];
222
    }
223
224
    // Protected Static Methods
225
    // =========================================================================
226
227
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
228
     * @param string $permissionName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
229
     *
230
     * @throws ForbiddenHttpException
231
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
232
    protected static function requirePermission(string $permissionName)
233
    {
234
        if (!Craft::$app->getUser()->checkPermission($permissionName)) {
235
            throw new ForbiddenHttpException('User is not permitted to perform this action');
236
        }
237
    }
238
239
    /**
240
     * Normalizes a URI path by trimming leading/trailing slashes and removing double slashes.
241
     *
242
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
243
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag cannot be grouped with parameter tags in a doc comment
Loading history...
244
     */
245
    protected static function normalizePath(string $path): string
246
    {
247
        return preg_replace('/\/\/+/', '/', trim($path, '/'));
248
    }
249
250
    /**
251
     * Returns the site’s base URL.
252
     *
253
     * @param Site $site
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
254
     *
255
     * @return string|null
256
     */
257
    protected static function getBaseUrl(Site $site): string
258
    {
259
        if ($site->baseUrl) {
260
            return rtrim(self::parseEnv($site->baseUrl), '/') . '/';
261
        }
262
263
        return null;
0 ignored issues
show
Bug Best Practice introduced by
The expression return null returns the type null which is incompatible with the type-hinted return string.
Loading history...
264
    }
265
266
    /**
267
     * Checks if a string references an environment variable (`$VARIABLE_NAME`)
268
     * and/or an alias (`@aliasName`), and returns the referenced value.
269
     *
270
     * ---
271
     *
272
     * ```php
273
     * $value1 = Craft::parseEnv('$SMPT_PASSWORD');
274
     * $value2 = Craft::parseEnv('@webroot');
275
     * ```
276
     *
277
     * @param string|null $str
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 1
Loading history...
278
     * @return string|null The parsed value, or the original value if it didn’t
0 ignored issues
show
Coding Style introduced by
Tag cannot be grouped with parameter tags in a doc comment
Loading history...
279
     * reference an environment variable and/or alias.
280
     */
281
    protected static function parseEnv(string $str = null)
282
    {
283
        if ($str === null) {
284
            return null;
285
        }
286
287
        if (preg_match('/^\$(\w+)$/', $str, $matches)) {
288
            $str = getenv($matches[1]) ?: $str;
289
        }
290
291
        return Craft::getAlias($str);
292
    }
293
}
294