Test Failed
Push — develop ( bcf63f...70e2cc )
by Andrew
09:44
created

Helper::getSingleTypeMenu()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * SEOmatic plugin for Craft CMS 3.x
4
 *
5
 * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful,
6
 * and flexible
7
 *
8
 * @link      https://nystudio107.com
9
 * @copyright Copyright (c) 2017 nystudio107
10
 */
11
12
namespace nystudio107\seomatic\services;
13
14
use nystudio107\seomatic\helpers\UrlHelper;
15
use nystudio107\seomatic\Seomatic;
16
use nystudio107\seomatic\helpers\DynamicMeta as DynamicMetaHelper;
17
use nystudio107\seomatic\helpers\ImageTransform as ImageTransformHelper;
18
use nystudio107\seomatic\helpers\Schema as SchemaHelper;
19
use nystudio107\seomatic\helpers\Text as TextHelper;
20
21
use Craft;
22
use craft\base\Component;
23
use craft\elements\Asset;
24
use craft\elements\db\MatrixBlockQuery;
25
use craft\elements\db\TagQuery;
26
use craft\helpers\Template;
27
use craft\web\twig\variables\Paginate;
28
29
use yii\base\Exception;
30
use yii\base\InvalidConfigException;
31
32
/**
33
 * @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...
34
 * @package   Seomatic
35
 * @since     3.0.0
36
 */
37
class Helper extends Component
38
{
39
    // Constants
40
    // =========================================================================
41
42
    const TWITTER_TRANSFORM_MAP = [
43
            'summary' => 'twitter-summary',
44
            'summary_large_image' => 'twitter-large',
45
            'app' => 'twitter-large',
46
            'player' => 'twitter-large',
47
        ];
48
49
    // Public Methods
50
    // =========================================================================
51
52
    /**
53
     * Sanitize user input by decoding any HTML Entities, URL decoding the text,
54
     * then removing any newlines, stripping tags, stripping Twig tags, and changing
55
     * single {}'s into ()'s
56
     *
57
     * @param $str
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
58
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
59
     */
60
    public static function sanitizeUserInput($str): string
61
    {
62
        return TextHelper::sanitizeUserInput($str);
63
    }
64
65
    /**
66
     * Return the appropriate Twitter Transform based on the current $metaGlobalVars->twitterCard
67
     *
68
     * @return string
69
     */
70
    public static function twitterTransform(): string
71
    {
72
        $transform = 'twitter-summary';
73
        $metaGlobalVars = Seomatic::$plugin->metaContainers->metaGlobalVars;
74
        if ($metaGlobalVars) {
0 ignored issues
show
introduced by
$metaGlobalVars is of type nystudio107\seomatic\models\MetaGlobalVars, thus it always evaluated to true.
Loading history...
75
            $transform = self::TWITTER_TRANSFORM_MAP[$metaGlobalVars->twitterCard] ?? $transform;
76
        }
77
78
        return $transform;
79
    }
80
81
    /**
82
     * Return the proper content for the `query-input` JSON-LD property
83
     *
84
     * @return string
85
     */
86
    public static function siteLinksQueryInput(): string
87
    {
88
        $result = '';
89
90
        $metaSiteVars = Seomatic::$plugin->metaContainers->metaSiteVars;
91
        if ($metaSiteVars && !empty($metaSiteVars->siteLinksQueryInput)) {
92
            $result = 'required name='.$metaSiteVars->siteLinksQueryInput;
93
        }
94
95
        return $result;
96
    }
97
98
    /**
99
     * Return whether this is a preview request of any kind
100
     *
101
     * @return bool
102
     */
103
    public static function isPreview(): bool
104
    {
105
        $isPreview = false;
106
        $request = Craft::$app->getRequest();
107
        if (Seomatic::$craft32) {
108
            $isPreview = $request->getIsPreview();
109
        }
110
        $isLivePreview = $request->getIsLivePreview();
111
112
        return ($isPreview || $isLivePreview);
113
    }
114
115
    /**
116
     * Return the Same As Links info as an array or null
117
     *
118
     * @param string $handle
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
119
     * @return array|null
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
120
     */
121
    public static function sameAsByHandle(string $handle) {
0 ignored issues
show
Coding Style introduced by
Opening brace should be on a new line
Loading history...
122
        $result = null;
123
124
        $sameAs = Seomatic::$plugin->metaContainers->metaSiteVars->sameAsLinks;
125
        if (!empty($sameAs) && !empty($handle)) {
126
            foreach ($sameAs as $sameAsInfo) {
127
                if (!empty($sameAsInfo) && is_array($sameAsInfo) && !empty($sameAsInfo['handle'])) {
128
                    if ($sameAsInfo['handle'] === $handle) {
129
                        return $sameAsInfo;
130
                    }
131
                }
132
            }
133
        }
134
135
        return $result;
136
    }
137
138
    /**
139
     * Return the canonical URL for the request, with the query string stripped
140
     *
141
     * @return string
142
     */
143
    public static function safeCanonicalUrl(): string
144
    {
145
        $url = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $url is dead and can be removed.
Loading history...
146
        try {
147
            $url = Craft::$app->getRequest()->getPathInfo();
148
        } catch (InvalidConfigException $e) {
149
            Craft::error($e->getMessage(), __METHOD__);
150
        }
151
        $url = DynamicMetaHelper::sanitizeUrl($url);
152
153
        return UrlHelper::absoluteUrlWithProtocol($url);
154
    }
155
156
    /**
157
     * Return the site URL for a given URL. This gives SEOmatic a chance to override it
158
     *
159
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
160
     * @param array|string|null $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
161
     * @param string|null $scheme
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 7 spaces after parameter type; 1 found
Loading history...
162
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 10 spaces after parameter type; 1 found
Loading history...
163
     * @return string
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
164
     * @throws Exception if|null $siteId is invalid
0 ignored issues
show
Coding Style introduced by
Tag @throws cannot be grouped with parameter tags in a doc comment
Loading history...
165
     */
166
    public static function siteUrl(string $path = '', $params = null, string $scheme = null, int $siteId = null): string
0 ignored issues
show
Unused Code introduced by
The parameter $siteId is not used and could be removed. ( Ignorable by Annotation )

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

166
    public static function siteUrl(string $path = '', $params = null, string $scheme = null, /** @scrutinizer ignore-unused */ int $siteId = null): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $scheme is not used and could be removed. ( Ignorable by Annotation )

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

166
    public static function siteUrl(string $path = '', $params = null, /** @scrutinizer ignore-unused */ string $scheme = null, int $siteId = null): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $params is not used and could be removed. ( Ignorable by Annotation )

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

166
    public static function siteUrl(string $path = '', /** @scrutinizer ignore-unused */ $params = null, string $scheme = null, int $siteId = null): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
167
    {
168
        return UrlHelper::siteUrl($path);
169
    }
170
171
    /**
172
     * Paginate based on the passed in Paginate variable as returned from the
173
     * Twig {% paginate %} tag:
174
     * https://docs.craftcms.com/v3/templating/tags/paginate.html#the-pageInfo-variable
175
     *
176
     * @param Paginate $pageInfo
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
177
     */
178
    public static function paginate(Paginate $pageInfo)
179
    {
180
        DynamicMetaHelper::paginate($pageInfo);
181
    }
182
183
    /**
184
     * Truncates the string to a given length. If $substring is provided, and
185
     * truncating occurs, the string is further truncated so that the substring
186
     * may be appended without exceeding the desired length.
187
     *
188
     * @param  string $string    The string to truncate
189
     * @param  int    $length    Desired length of the truncated string
190
     * @param  string $substring The substring to append if it can fit
191
     *
192
     * @return string with the resulting $str after truncating
193
     */
194
    public static function truncate($string, $length, $substring = '…'): string
195
    {
196
        return TextHelper::truncate($string, $length, $substring);
197
    }
198
199
    /**
200
     * Truncates the string to a given length, while ensuring that it does not
201
     * split words. If $substring is provided, and truncating occurs, the
202
     * string is further truncated so that the substring may be appended without
203
     * exceeding the desired length.
204
     *
205
     * @param  string $string    The string to truncate
206
     * @param  int    $length    Desired length of the truncated string
207
     * @param  string $substring The substring to append if it can fit
208
     *
209
     * @return string with the resulting $str after truncating
210
     */
211
    public static function truncateOnWord($string, $length, $substring = '…'): string
212
    {
213
        return TextHelper::truncateOnWord($string, $length, $substring);
214
    }
215
216
    /**
217
     * Return a list of localized URLs that are in the current site's group
218
     * The current URI is used if $uri is null. Similarly, the current site is
219
     * used if $siteId is null.
220
     * The resulting array of arrays has `id`, `language`, `ogLanguage`,
221
     * `hreflangLanguage`, and `url` as keys.
222
     *
223
     * @param string|null $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
224
     * @param int|null    $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
225
     *
226
     * @return array
227
     */
228
    public static function getLocalizedUrls(string $uri = null, int $siteId = null): array
229
    {
230
        return DynamicMetaHelper::getLocalizedUrls($uri, $siteId);
231
    }
232
233
    /**
234
     * Allow setting the X-Robots-Tag and Link headers on static files as per:
235
     * https://moz.com/blog/how-to-advanced-relcanonical-http-headers
236
     *
237
     * @param        $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
238
     * @param string $robots
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
239
     * @param string $canonical
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
240
     * @param bool   $inline
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
241
     *
242
     * @return \Twig\Markup
243
     * @throws \yii\base\Exception
244
     */
245
    public static function seoFileLink($url, $robots = '', $canonical = '', $inline = true): \Twig\Markup
246
    {
247
        // Get the file name
248
        $path = parse_url($url, PHP_URL_PATH);
249
        $fileName = pathinfo($path, PATHINFO_BASENAME);
250
        // Set some defaults
251
        $robots = empty($robots) ? 'all' : $robots;
252
        $canonical = empty($canonical) ? $url : $canonical;
253
        $inlineStr = $inline === true ? '1' : '0';
254
        // Compose the base64 encoded URL
255
        $seoFileLink = 'seomatic/seo-file-link/'
256
            .base64_encode($url)
257
            .'/'
258
            .base64_encode($robots)
259
            .'/'
260
            .base64_encode($canonical)
261
            .'/'
262
            .$inlineStr
263
            .'/'
264
            .$fileName;
0 ignored issues
show
Bug introduced by
Are you sure $fileName of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

264
            ./** @scrutinizer ignore-type */ $fileName;
Loading history...
265
266
        return Template::raw(UrlHelper::siteUrl($seoFileLink));
267
    }
268
269
    /**
270
     * Load the appropriate meta containers for the given $uri and optional
271
     * $siteId
272
     *
273
     * @param string   $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
274
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
275
     */
276
    public static function loadMetadataForUri(string $uri = '', int $siteId = null)
277
    {
278
        Seomatic::$plugin->metaContainers->loadMetaContainers($uri, $siteId);
279
    }
280
281
    /**
282
     * Get the URL to the $siteId's sitemap index
283
     *
284
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
285
     *
286
     * @return string
287
     */
288
    public static function sitemapIndexForSiteId(int $siteId = null): string
289
    {
290
        return Seomatic::$plugin->sitemaps->sitemapIndexUrlForSiteId($siteId);
291
    }
292
293
    /**
294
     * Return a sitemap for each site in the same site group
295
     *
296
     * @return string
297
     */
298
    public static function siteGroupSitemaps(): string
299
    {
300
        return Seomatic::$plugin->sitemaps->siteGroupSitemaps();
301
    }
302
303
    /**
304
     * @param string   $sourceType
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
305
     * @param string   $sourceHandle
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
306
     * @param int|null $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
307
     *
308
     * @return string
309
     */
310
    public static function sitemapUrlForBundle(string $sourceType, string $sourceHandle, int $siteId = null): string
311
    {
312
        return Seomatic::$plugin->sitemaps->sitemapUrlForBundle($sourceType, $sourceHandle, $siteId);
313
    }
314
315
    /**
316
     * Extract plain old text from a field
317
     *
318
     * @param $field
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
319
     *
320
     * @return string
321
     */
322
    public static function extractTextFromField($field = null): string
323
    {
324
        return TextHelper::extractTextFromField($field);
325
    }
326
327
    /**
328
     * Extract concatenated text from all of the tags in the $tagElement and
329
     * return as a comma-delimited string
330
     *
331
     * @param TagQuery $tagQuery
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
332
     *
333
     * @return string
334
     */
335
    public static function extractTextFromTags($tagQuery = null): string
336
    {
337
        return TextHelper::extractTextFromTags($tagQuery);
338
    }
339
340
    /**
341
     * Extract text from all of the blocks in a matrix field, concatenating it
342
     * together.
343
     *
344
     * @param MatrixBlockQuery $matrixQuery
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
345
     * @param string           $fieldHandle
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
346
     *
347
     * @return string
348
     */
349
    public static function extractTextFromMatrix($matrixQuery = null, $fieldHandle = ''): string
350
    {
351
        return TextHelper::extractTextFromMatrix($matrixQuery, $fieldHandle);
352
    }
353
354
    /**
355
     * Return the most important keywords extracted from the text as a comma-
356
     * delimited string
357
     *
358
     * @param string $text
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
359
     * @param int    $limit
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
360
     * @param bool   $useStopWords
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
361
     *
362
     * @return string
363
     */
364
    public static function extractKeywords($text = '', $limit = 15, $useStopWords = true): string
365
    {
366
        return TextHelper::extractKeywords($text, $limit, $useStopWords);
367
    }
368
369
    /**
370
     * Extract a summary consisting of the 3 most important sentences from the
371
     * text
372
     *
373
     * @param string $text
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
374
     * @param bool   $useStopWords
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
375
     *
376
     * @return string
377
     */
378
    public static function extractSummary($text = '', $useStopWords = true): string
379
    {
380
        return TextHelper::extractSummary($text, $useStopWords);
381
    }
382
383
    /**
384
     * Return a period-delimited schema.org path from the $settings
385
     *
386
     * @param $settings
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
387
     *
388
     * @return string
389
     */
390
    public static function getEntityPath($settings): string
391
    {
392
        return SchemaHelper::getEntityPath($settings);
393
    }
394
395
    /**
396
     * Return a flattened, indented menu of the given $path
397
     *
398
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
399
     *
400
     * @return array
401
     */
402
    public static function getTypeMenu($path): array
403
    {
404
        return SchemaHelper::getTypeMenu($path);
405
    }
406
407
    /**
408
     * Return a single menu of schemas starting at $path
409
     *
410
     * @param string $path
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
411
     *
412
     * @return array
413
     */
414
    public static function getSingleTypeMenu($path): array
415
    {
416
        return SchemaHelper::getSingleTypeMenu($path);
417
    }
418
419
    /**
420
     * Transform the $asset for social media sites in $transformName and
421
     * optional $siteId
422
     *
423
     * @param int|Asset $asset         the Asset or Asset ID
424
     * @param string    $transformName the name of the transform to apply
425
     * @param int|null  $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
426
     * @param string    $transformMode
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
427
     *
428
     * @return string URL to the transformed image
429
     */
430
    public function socialTransform($asset, $transformName = '', $siteId = null, $transformMode = null): string
431
    {
432
        return ImageTransformHelper::socialTransform($asset, $transformName, $siteId, $transformMode);
433
    }
434
435
    /**
436
     * Get the width of the transformed social image for $transformName and
437
     * optional $siteId
438
     *
439
     * @param int|Asset $asset         the Asset or Asset ID
440
     * @param string    $transformName the name of the transform to apply
441
     * @param int|null  $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
442
     * @param string    $transformMode
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
443
     *
444
     * @return string URL to the transformed image
445
     */
446
    public function socialTransformWidth(
447
        $asset,
448
        $transformName = '',
449
        $siteId = null,
450
        $transformMode = null
451
    ): string {
452
        return ImageTransformHelper::socialTransformWidth($asset, $transformName, $siteId, $transformMode);
453
    }
454
455
    /**
456
     * Get the height of the transformed social image for $transformName and
457
     * optional $siteId
458
     *
459
     * @param int|Asset $asset         the Asset or Asset ID
460
     * @param string    $transformName the name of the transform to apply
461
     * @param int|null  $siteId
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
462
     * @param string    $transformMode
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
463
     *
464
     * @return string URL to the transformed image
465
     */
466
    public function socialTransformHeight(
467
        $asset,
468
        $transformName = '',
469
        $siteId = null,
470
        $transformMode = null
471
    ): string {
472
        return ImageTransformHelper::socialTransformHeight($asset, $transformName, $siteId, $transformMode);
473
    }
474
475
    /**
476
     * Return whether we are running Craft 3.1 or later
477
     *
478
     * @return bool
479
     */
480
    public function craft31(): bool
481
    {
482
        return Seomatic::$craft31;
483
    }
484
485
    /**
486
     * Return whether we are running Craft 3.2 or later
487
     *
488
     * @return bool
489
     */
490
    public function craft32(): bool
491
    {
492
        return Seomatic::$craft32;
493
    }
494
495
    /**
496
     * Return whether we are running Craft 3.3 or later
497
     *
498
     * @return bool
499
     */
500
    public function craft33(): bool
501
    {
502
        return Seomatic::$craft33;
503
    }
504
}
505