DynamicMeta::includeHttpHeaders()   F
last analyzed

Complexity

Conditions 21
Paths 259

Size

Total Lines 75
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 50
dl 0
loc 75
rs 2.5958
c 0
b 0
f 0
cc 21
nc 259
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
 * SEOmatic plugin for Craft CMS
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\helpers;
13
14
use Craft;
15
use craft\base\Element;
16
use craft\errors\SiteNotFoundException;
17
use craft\helpers\DateTimeHelper;
18
use craft\web\twig\variables\Paginate;
19
use DateTime;
20
use nystudio107\seomatic\events\AddDynamicMetaEvent;
21
use nystudio107\seomatic\fields\SeoSettings;
22
use nystudio107\seomatic\helpers\Field as FieldHelper;
23
use nystudio107\seomatic\helpers\Localization as LocalizationHelper;
24
use nystudio107\seomatic\helpers\Text as TextHelper;
25
use nystudio107\seomatic\models\Entity;
26
use nystudio107\seomatic\models\jsonld\BreadcrumbList;
27
use nystudio107\seomatic\models\jsonld\ContactPoint;
28
use nystudio107\seomatic\models\jsonld\LocalBusiness;
29
use nystudio107\seomatic\models\jsonld\OpeningHoursSpecification;
30
use nystudio107\seomatic\models\jsonld\Organization;
31
use nystudio107\seomatic\models\jsonld\Thing;
32
use nystudio107\seomatic\models\MetaBundle;
33
use nystudio107\seomatic\models\MetaJsonLd;
34
use nystudio107\seomatic\models\MetaLink;
35
use nystudio107\seomatic\Seomatic;
36
use nystudio107\seomatic\services\Helper as SeomaticHelper;
37
use RecursiveArrayIterator;
38
use RecursiveIteratorIterator;
39
use Throwable;
40
use yii\base\Event;
41
use yii\base\Exception;
42
use yii\base\InvalidConfigException;
43
use function count;
44
use function in_array;
45
use function is_array;
46
use function is_string;
47
48
/**
49
 * @author    nystudio107
50
 * @package   Seomatic
51
 * @since     3.0.0
52
 */
53
class DynamicMeta
54
{
55
    // Constants
56
    // =========================================================================
57
58
    /**
59
     * @event AddDynamicMetaEvent The event that is triggered when SEOmatic has
60
     *        included the standard meta containers, and gives your plugin/module
61
     *        the chance to add whatever custom dynamic meta items you like
62
     *
63
     * ---
64
     * ```php
65
     * use nystudio107\seomatic\events\AddDynamicMetaEvent;
66
     * use nystudio107\seomatic\helpers\DynamicMeta;
67
     * use yii\base\Event;
68
     * Event::on(DynamicMeta::class, DynamicMeta::EVENT_ADD_DYNAMIC_META, function(AddDynamicMetaEvent $e) {
69
     *     // Add whatever dynamic meta items to the containers as you like
70
     * });
71
     * ```
72
     */
73
    public const EVENT_ADD_DYNAMIC_META = 'addDynamicMeta';
74
75
    // Static Methods
76
    // =========================================================================
77
78
    /**
79
     * Paginate based on the passed in Paginate variable as returned from the
80
     * Twig {% paginate %} tag:
81
     * https://docs.craftcms.com/v3/templating/tags/paginate.html#the-pageInfo-variable
82
     *
83
     * @param ?Paginate $pageInfo
84
     */
85
    public static function paginate(?Paginate $pageInfo)
86
    {
87
        if ($pageInfo !== null && $pageInfo->currentPage !== null) {
88
            // Let the meta containers know that this page is paginated
89
            Seomatic::$plugin->metaContainers->paginationPage = (string)$pageInfo->currentPage;
90
            // See if we should strip the query params
91
            $stripQueryParams = true;
92
            $pageTrigger = Craft::$app->getConfig()->getGeneral()->pageTrigger;
93
            // Is this query string-based pagination?
94
            if ($pageTrigger[0] === '?') {
95
                $stripQueryParams = false;
96
            }
97
            // Set the canonical URL to be the paginated URL
98
            // see: https://github.com/nystudio107/craft-seomatic/issues/375#issuecomment-488369209
99
            $url = $pageInfo->getPageUrl($pageInfo->currentPage);
100
            if ($stripQueryParams) {
101
                $url = preg_replace('/\?.*/', '', $url);
102
            }
103
            if (!empty($url)) {
104
                $url = UrlHelper::absoluteUrlWithProtocol($url);
105
                Seomatic::$seomaticVariable->meta->canonicalUrl = $url;
106
                $canonical = Seomatic::$seomaticVariable->link->get('canonical');
107
                if ($canonical !== null) {
108
                    $canonical->href = $url;
109
                }
110
            }
111
            // Set the previous URL
112
            $url = $pageInfo->getPrevUrl();
113
            if ($stripQueryParams) {
114
                $url = preg_replace('/\?.*/', '', $url);
115
            }
116
            if (!empty($url)) {
117
                $url = UrlHelper::absoluteUrlWithProtocol($url);
118
                $metaTag = Seomatic::$plugin->link->create([
0 ignored issues
show
Unused Code introduced by
The assignment to $metaTag is dead and can be removed.
Loading history...
119
                    'rel' => 'prev',
120
                    'href' => $url,
121
                ]);
122
            }
123
            // Set the next URL
124
            $url = $pageInfo->getNextUrl();
125
            if ($stripQueryParams) {
126
                $url = preg_replace('/\?.*/', '', $url);
127
            }
128
            if (!empty($url)) {
129
                $url = UrlHelper::absoluteUrlWithProtocol($url);
130
                $metaTag = Seomatic::$plugin->link->create([
131
                    'rel' => 'next',
132
                    'href' => $url,
133
                ]);
134
            }
135
        }
136
    }
137
138
    /**
139
     * Include any headers for this request
140
     */
141
    public static function includeHttpHeaders()
142
    {
143
        self::addCspHeaders();
144
        // Don't include headers for any response code >= 400
145
        $request = Craft::$app->getRequest();
146
        if (!$request->isConsoleRequest) {
147
            $response = Craft::$app->getResponse();
148
            if ($response->statusCode >= 400 || SeomaticHelper::isPreview()) {
149
                return;
150
            }
151
        }
152
        // Assuming they have headersEnabled, add the response code to the headers
153
        if (Seomatic::$settings->headersEnabled) {
154
            $response = Craft::$app->getResponse();
155
            // X-Robots-Tag header
156
            $robots = Seomatic::$seomaticVariable->tag->get('robots');
157
            if ($robots !== null && $robots->include) {
158
                $robotsArray = $robots->renderAttributes();
159
                $content = $robotsArray['content'] ?? '';
160
                if (!empty($content)) {
161
                    // The content property can be a string or an array
162
                    if (is_array($content)) {
163
                        $headerValue = '';
164
                        foreach ($content as $contentVal) {
165
                            $headerValue .= ($contentVal . ',');
166
                        }
167
                        $headerValue = rtrim($headerValue, ',');
168
                    } else {
169
                        $headerValue = $content;
170
                    }
171
                    $response->headers->set('X-Robots-Tag', $headerValue);
172
                }
173
            }
174
            // Link canonical header
175
            $canonical = Seomatic::$seomaticVariable->link->get('canonical');
176
            if ($canonical !== null && $canonical->include) {
177
                $canonicalArray = $canonical->renderAttributes();
178
                $href = $canonicalArray['href'] ?? '';
179
                if (!empty($href)) {
180
                    // The href property can be a string or an array
181
                    if (is_array($href)) {
182
                        $headerValue = '';
183
                        foreach ($href as $hrefVal) {
184
                            $headerValue .= ('<' . $hrefVal . '>' . ',');
185
                        }
186
                        $headerValue = rtrim($headerValue, ',');
187
                    } else {
188
                        $headerValue = '<' . $href . '>';
189
                    }
190
                    $headerValue .= "; rel='canonical'";
191
                    $response->headers->add('Link', $headerValue);
192
                }
193
            }
194
            // Referrer-Policy header
195
            $referrer = Seomatic::$seomaticVariable->tag->get('referrer');
196
            if ($referrer !== null && $referrer->include) {
197
                $referrerArray = $referrer->renderAttributes();
198
                $content = $referrerArray['content'] ?? '';
199
                if (!empty($content)) {
200
                    // The content property can be a string or an array
201
                    if (is_array($content)) {
202
                        $headerValue = '';
203
                        foreach ($content as $contentVal) {
204
                            $headerValue .= ($contentVal . ',');
205
                        }
206
                        $headerValue = rtrim($headerValue, ',');
207
                    } else {
208
                        $headerValue = $content;
209
                    }
210
                    $response->headers->add('Referrer-Policy', $headerValue);
211
                }
212
            }
213
            // The X-Powered-By tag
214
            if (Seomatic::$settings->generatorEnabled) {
215
                $response->headers->add('X-Powered-By', 'SEOmatic');
216
            }
217
        }
218
    }
219
220
    /**
221
     * Add the Content-Security-Policy script-src headers
222
     */
223
    public static function addCspHeaders()
224
    {
225
        $cspNonces = self::getCspNonces();
226
        $container = Seomatic::$plugin->script->container();
227
        if ($container !== null) {
228
            $container->addNonceHeaders($cspNonces);
229
        }
230
    }
231
232
    /**
233
     * Get all of the CSP Nonces from containers that can have them
234
     *
235
     * @return array
236
     */
237
    public static function getCspNonces(): array
238
    {
239
        $cspNonces = [];
240
        // Add in any fixed policies from Settings
241
        if (!empty(Seomatic::$settings->cspScriptSrcPolicies)) {
242
            $fixedCsps = Seomatic::$settings->cspScriptSrcPolicies;
243
            $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($fixedCsps));
244
            foreach ($iterator as $value) {
245
                $cspNonces[] = $value;
246
            }
247
        }
248
        // Add in any CSP nonce headers
249
        $container = Seomatic::$plugin->jsonLd->container();
250
        if ($container !== null) {
251
            $cspNonces = array_merge($cspNonces, $container->getCspNonces());
252
        }
253
        $container = Seomatic::$plugin->script->container();
254
        if ($container !== null) {
255
            $cspNonces = array_merge($cspNonces, $container->getCspNonces());
256
        }
257
258
        return $cspNonces;
259
    }
260
261
    /**
262
     * Add the Content-Security-Policy script-src tags
263
     */
264
    public static function addCspTags()
265
    {
266
        $cspNonces = self::getCspNonces();
267
        $container = Seomatic::$plugin->script->container();
268
        if ($container !== null) {
269
            $container->addNonceTags($cspNonces);
270
        }
271
    }
272
273
    /**
274
     * Add any custom/dynamic meta to the containers
275
     *
276
     * @param string|null $uri The URI of the route to add dynamic metadata for
277
     * @param int|null $siteId The siteId of the current site
278
     */
279
    public static function addDynamicMetaToContainers(string $uri = null, int $siteId = null)
280
    {
281
        Craft::beginProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__);
282
        $request = Craft::$app->getRequest();
283
        // Don't add dynamic meta to console requests, they have no concept of a URI or segments
284
        if (!$request->getIsConsoleRequest()) {
285
            $response = Craft::$app->getResponse();
286
            if ($response->statusCode < 400) {
287
                self::addMetaJsonLdBreadCrumbs($siteId);
288
                if (Seomatic::$settings->addHrefLang) {
289
                    self::addMetaLinkHrefLang($uri, $siteId);
290
                }
291
                self::addSameAsMeta();
292
                $metaSiteVars = Seomatic::$plugin->metaContainers->metaSiteVars;
293
                $jsonLd = Seomatic::$plugin->jsonLd->get('identity');
294
                if ($jsonLd !== null) {
295
                    self::addOpeningHours($jsonLd, $metaSiteVars->identity);
0 ignored issues
show
Bug introduced by
It seems like $metaSiteVars->identity can also be of type array; however, parameter $entity of nystudio107\seomatic\hel...Meta::addOpeningHours() does only seem to accept null|nystudio107\seomatic\models\Entity, 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

295
                    self::addOpeningHours($jsonLd, /** @scrutinizer ignore-type */ $metaSiteVars->identity);
Loading history...
296
                    self::addContactPoints($jsonLd, $metaSiteVars->identity);
0 ignored issues
show
Bug introduced by
It seems like $metaSiteVars->identity can also be of type array; however, parameter $entity of nystudio107\seomatic\hel...eta::addContactPoints() does only seem to accept null|nystudio107\seomatic\models\Entity, 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

296
                    self::addContactPoints($jsonLd, /** @scrutinizer ignore-type */ $metaSiteVars->identity);
Loading history...
297
                }
298
                $jsonLd = Seomatic::$plugin->jsonLd->get('creator');
299
                if ($jsonLd !== null) {
300
                    self::addOpeningHours($jsonLd, $metaSiteVars->creator);
301
                    self::addContactPoints($jsonLd, $metaSiteVars->creator);
302
                }
303
                // Allow modules/plugins a chance to add dynamic meta
304
                $event = new AddDynamicMetaEvent([
305
                    'uri' => $uri,
306
                    'siteId' => $siteId,
307
                ]);
308
                Event::trigger(static::class, self::EVENT_ADD_DYNAMIC_META, $event);
309
            }
310
        }
311
        Craft::endProfile('DynamicMeta::addDynamicMetaToContainers', __METHOD__);
312
    }
313
314
    /**
315
     * Add breadcrumbs to the MetaJsonLdContainer
316
     *
317
     * @param int|null $siteId
318
     */
319
    public static function addMetaJsonLdBreadCrumbs(int $siteId = null)
320
    {
321
        Craft::beginProfile('DynamicMeta::addMetaJsonLdBreadCrumbs', __METHOD__);
322
        $position = 0;
323
        if ($siteId === null) {
324
            $siteId = Craft::$app->getSites()->currentSite->id
325
                ?? Craft::$app->getSites()->primarySite->id
326
                ?? 1;
327
        }
328
        $site = Craft::$app->getSites()->getSiteById($siteId);
329
        if ($site === null) {
330
            return;
331
        }
332
        $siteUrl = '/';
0 ignored issues
show
Unused Code introduced by
The assignment to $siteUrl is dead and can be removed.
Loading history...
333
        try {
334
            $siteUrl = SiteHelper::siteEnabledWithUrls($siteId) ? $site->baseUrl : Craft::$app->getSites()->getPrimarySite()->baseUrl;
335
        } catch (SiteNotFoundException $e) {
336
            Craft::error($e->getMessage(), __METHOD__);
337
        }
338
        if (!empty(Seomatic::$settings->siteUrlOverride)) {
339
            try {
340
                $siteUrl = UrlHelper::getSiteUrlOverrideSetting($siteId);
341
            } catch (Throwable $e) {
342
                // That's okay
343
            }
344
        }
345
        /** @var BreadcrumbList $crumbs */
346
        $crumbs = Seomatic::$plugin->jsonLd->create([
347
            'type' => 'BreadcrumbList',
348
            'name' => 'Breadcrumbs',
349
            'description' => 'Breadcrumbs list',
350
        ], false);
351
        // Include the Homepage in the breadcrumbs, if includeHomepageInBreadcrumbs is true
352
        $element = null;
353
        if (Seomatic::$settings->includeHomepageInBreadcrumbs) {
354
            /** @var Element $element */
355
            $position++;
356
            $element = Craft::$app->getElements()->getElementByUri('__home__', $siteId, true);
357
            if ($element) {
358
                $uri = $element->uri === '__home__' ? '' : ($element->uri ?? '');
359
                try {
360
                    $id = UrlHelper::siteUrl($uri, null, null, $siteId);
361
                } catch (Exception $e) {
362
                    $id = $siteUrl;
363
                    Craft::error($e->getMessage(), __METHOD__);
364
                }
365
                $item = UrlHelper::stripQueryString($id);
366
                $item = UrlHelper::absoluteUrlWithProtocol($item);
367
                $listItem = MetaJsonLd::create('ListItem', [
368
                    'position' => $position,
369
                    'name' => $element->title,
370
                    'item' => $item,
371
                    '@id' => $id,
372
                ]);
373
                $crumbs->itemListElement[] = $listItem;
374
            } else {
375
                $item = UrlHelper::stripQueryString($siteUrl ?? '/');
376
                $item = UrlHelper::absoluteUrlWithProtocol($item);
377
                $crumbs->itemListElement[] = MetaJsonLd::create('ListItem', [
378
                    'position' => $position,
379
                    'name' => 'Homepage',
380
                    'item' => $item,
381
                    '@id' => $siteUrl,
382
                ]);
383
            }
384
        }
385
        // Build up the segments, and look for elements that match
386
        $uri = '';
387
        $segments = Craft::$app->getRequest()->getSegments();
388
        /** @var Element|null $lastElement */
389
        $lastElement = Seomatic::$matchedElement;
390
        if ($lastElement && $element) {
391
            if ($lastElement->uri !== '__home__' && $element->uri) {
392
                $path = $lastElement->uri;
393
                $segments = array_values(array_filter(explode('/', $path), function($segment) {
394
                    return $segment !== '';
395
                }));
396
            }
397
        }
398
        // Parse through the segments looking for elements that match
399
        foreach ($segments as $segment) {
400
            $uri .= $segment;
401
            /** @var Element|null $element */
402
            $element = Craft::$app->getElements()->getElementByUri($uri, $siteId, true);
403
            if ($element && $element->uri) {
404
                $position++;
405
                $uri = $element->uri === '__home__' ? '' : $element->uri;
406
                try {
407
                    $id = UrlHelper::siteUrl($uri, null, null, $siteId);
408
                } catch (Exception $e) {
409
                    $id = $siteUrl;
410
                    Craft::error($e->getMessage(), __METHOD__);
411
                }
412
                $item = UrlHelper::stripQueryString($id);
413
                $item = UrlHelper::absoluteUrlWithProtocol($item);
414
                $crumbs->itemListElement[] = MetaJsonLd::create('ListItem', [
415
                    'position' => $position,
416
                    'name' => $element->title,
417
                    'item' => $item,
418
                    '@id' => $id,
419
                ]);
420
            }
421
            $uri .= '/';
422
        }
423
        if (!empty($crumbs->itemListElement)) {
424
            Seomatic::$plugin->jsonLd->add($crumbs);
425
        }
426
        Craft::endProfile('DynamicMeta::addMetaJsonLdBreadCrumbs', __METHOD__);
427
    }
428
429
    /**
430
     * Add meta hreflang tags if there is more than one site
431
     *
432
     * @param string|null $uri
433
     * @param int|null $siteId
434
     */
435
    public static function addMetaLinkHrefLang(string $uri = null, int $siteId = null)
436
    {
437
        Craft::beginProfile('DynamicMeta::addMetaLinkHrefLang', __METHOD__);
438
        $siteLocalizedUrls = self::getLocalizedUrls($uri, $siteId);
439
        $currentPaginationUrl = null;
440
        if (Seomatic::$plugin->metaContainers->paginationPage !== '1') {
441
            $currentPaginationUrl = Seomatic::$seomaticVariable->meta->canonicalUrl ?? null;
442
        }
443
        if (!empty($siteLocalizedUrls)) {
444
            // Add the rel=alternate tag
445
            /** @var MetaLink $metaTag */
446
            $metaTag = Seomatic::$plugin->link->create([
447
                'rel' => 'alternate',
448
                'hreflang' => [],
449
                'href' => [],
450
            ]);
451
            // Add the alternate language link rel's
452
            if (count($siteLocalizedUrls) > 1) {
453
                foreach ($siteLocalizedUrls as $siteLocalizedUrl) {
454
                    $url = $siteLocalizedUrl['url'];
455
                    if ($siteLocalizedUrl['current']) {
456
                        $url = $currentPaginationUrl ?? $siteLocalizedUrl['url'];
457
                    }
458
                    $metaTag->hreflang[] = $siteLocalizedUrl['hreflangLanguage'];
459
                    $metaTag->href[] = $url;
460
                    // Add the x-default hreflang
461
                    if ($siteLocalizedUrl['primary'] && Seomatic::$settings->addXDefaultHrefLang) {
462
                        $metaTag->hreflang[] = 'x-default';
463
                        $metaTag->href[] = $siteLocalizedUrl['url'];
464
                    }
465
                }
466
                Seomatic::$plugin->link->add($metaTag);
467
            }
468
            // Add in the og:locale:alternate tags
469
            $ogLocaleAlternate = Seomatic::$plugin->tag->get('og:locale:alternate');
470
            if (count($siteLocalizedUrls) > 1 && $ogLocaleAlternate) {
471
                $ogContentArray = [];
472
                foreach ($siteLocalizedUrls as $siteLocalizedUrl) {
473
                    if (!in_array($siteLocalizedUrl['ogLanguage'], $ogContentArray, true) &&
474
                        Craft::$app->language !== $siteLocalizedUrl['language']) {
475
                        $ogContentArray[] = $siteLocalizedUrl['ogLanguage'];
476
                    }
477
                }
478
                $ogLocaleAlternate->content = $ogContentArray;
479
            }
480
        }
481
        Craft::endProfile('DynamicMeta::addMetaLinkHrefLang', __METHOD__);
482
    }
483
484
    /**
485
     * Return a list of localized URLs that are in the current site's group
486
     * The current URI is used if $uri is null. Similarly, the current site is
487
     * used if $siteId is null.
488
     * The resulting array of arrays has `id`, `language`, `ogLanguage`,
489
     * `hreflangLanguage`, and `url` as keys.
490
     *
491
     * @param string|null $uri
492
     * @param int|null $siteId
493
     *
494
     * @return array
495
     */
496
    public static function getLocalizedUrls(string $uri = null, int $siteId = null): array
497
    {
498
        Craft::beginProfile('DynamicMeta::getLocalizedUrls', __METHOD__);
499
        $localizedUrls = [];
500
        // No pagination params for URLs
501
        $urlParams = null;
502
        // Get the request URI
503
        if ($uri === null) {
504
            $requestUri = Craft::$app->getRequest()->pathInfo;
505
        } else {
506
            $requestUri = $uri;
507
        }
508
        // Get the site to use
509
        if ($siteId === null) {
510
            try {
511
                $thisSite = Craft::$app->getSites()->getCurrentSite();
512
            } catch (SiteNotFoundException $e) {
513
                $thisSite = null;
514
                Craft::error($e->getMessage(), __METHOD__);
515
            }
516
        } else {
517
            $thisSite = Craft::$app->getSites()->getSiteById($siteId);
518
        }
519
        // Bail if we can't get a site
520
        if ($thisSite === null) {
521
            return $localizedUrls;
522
        }
523
        if (Seomatic::$settings->siteGroupsSeparate) {
524
            // Get only the sites that are in the current site's group
525
            try {
526
                $siteGroup = $thisSite->getGroup();
527
            } catch (InvalidConfigException $e) {
528
                $siteGroup = null;
529
                Craft::error($e->getMessage(), __METHOD__);
530
            }
531
            // Bail if we can't get a site group
532
            if ($siteGroup === null) {
533
                return $localizedUrls;
534
            }
535
            $sites = $siteGroup->getSites();
536
        } else {
537
            $sites = Craft::$app->getSites()->getAllSites();
538
        }
539
        $elements = Craft::$app->getElements();
540
        foreach ($sites as $site) {
541
            $includeUrl = true;
542
            $matchedElement = $elements->getElementByUri($requestUri, $thisSite->id, true);
543
            if ($matchedElement) {
544
                $url = $elements->getElementUriForSite($matchedElement->getId(), $site->id);
545
                // See if they have disabled sitemaps or robots for this entry,
546
                // and if so, don't include it in the hreflang
547
                $element = null;
548
                if ($url) {
549
                    /** @var Element $element */
550
                    $element = $elements->getElementByUri($url, $site->id, false);
551
                }
552
                if ($element !== null) {
553
                    /** @var MetaBundle $metaBundle */
554
                    list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId)
555
                        = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element);
556
                    $metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
557
                        $sourceBundleType,
558
                        $sourceId,
559
                        $sourceSiteId
560
                    );
561
                    if ($metaBundle !== null) {
562
                        // If robots contains 'none' or 'noindex' don't include the URL
563
                        $robotsArray = explode(',', $metaBundle->metaGlobalVars->robots);
564
                        if (in_array('noindex', $robotsArray, true) || in_array('none', $robotsArray, true)) {
565
                            $includeUrl = false;
566
                        }
567
                    }
568
                    $fieldHandles = FieldHelper::fieldsOfTypeFromElement(
569
                        $element,
570
                        FieldHelper::SEO_SETTINGS_CLASS_KEY,
571
                        true
572
                    );
573
                    foreach ($fieldHandles as $fieldHandle) {
574
                        if (!empty($element->$fieldHandle)) {
575
                            /** @var MetaBundle $fieldMetaBundle */
576
                            $fieldMetaBundle = $element->$fieldHandle;
577
                            /** @var SeoSettings $seoSettingsField */
578
                            $seoSettingsField = Craft::$app->getFields()->getFieldByHandle($fieldHandle);
579
                            if ($seoSettingsField !== null) {
580
                                // If robots is set to 'none' don't include the URL
581
                                if ($seoSettingsField->generalTabEnabled
582
                                    && in_array('robots', $seoSettingsField->generalEnabledFields, false)
583
                                    && !Seomatic::$plugin->helper->isInherited($fieldMetaBundle->metaGlobalVars, 'robots')
0 ignored issues
show
Bug introduced by
It seems like $fieldMetaBundle->metaGlobalVars can also be of type array and null; however, parameter $settingCollection of nystudio107\seomatic\ser...s\Helper::isInherited() does only seem to accept nystudio107\seomatic\base\InheritableSettingsModel, 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

583
                                    && !Seomatic::$plugin->helper->isInherited(/** @scrutinizer ignore-type */ $fieldMetaBundle->metaGlobalVars, 'robots')
Loading history...
584
                                ) {
585
                                    // If robots contains 'none' or 'noindex' don't include the URL
586
                                    $robotsArray = explode(',', $fieldMetaBundle->metaGlobalVars->robots);
587
                                    if (in_array('noindex', $robotsArray, true) || in_array('none', $robotsArray, true)) {
588
                                        $includeUrl = false;
589
                                    } else {
590
                                        // Otherwise, include the URL
591
                                        $includeUrl = true;
592
                                    }
593
                                }
594
                            }
595
                        }
596
                    }
597
                    // Never include the URL if the element isn't enabled for the site
598
                    if (isset($element->enabledForSite) && !(bool)$element->enabledForSite) {
599
                        $includeUrl = false;
600
                    }
601
                } else {
602
                    $includeUrl = false;
603
                }
604
                $url = ($url === '__home__') ? '' : $url;
605
            } else {
606
                try {
607
                    $url = SiteHelper::siteEnabledWithUrls($site->id) ? UrlHelper::siteUrl($requestUri, $urlParams, null, $site->id)
608
                        : Craft::$app->getSites()->getPrimarySite()->baseUrl;
609
                } catch (SiteNotFoundException $e) {
610
                    $url = '';
611
                    Craft::error($e->getMessage(), __METHOD__);
612
                } catch (Exception $e) {
613
                    $url = '';
614
                    Craft::error($e->getMessage(), __METHOD__);
615
                }
616
            }
617
            $url = $url ?? '';
618
            if (!UrlHelper::isAbsoluteUrl($url)) {
619
                try {
620
                    $url = UrlHelper::siteUrl($url, $urlParams, null, $site->id);
621
                } catch (Exception $e) {
622
                    $url = '';
623
                    Craft::error($e->getMessage(), __METHOD__);
624
                }
625
            }
626
            // Strip any query string params, and make sure we have an absolute URL with protocol
627
            if ($urlParams === null) {
628
                $url = UrlHelper::stripQueryString($url);
629
            }
630
            $url = UrlHelper::absoluteUrlWithProtocol($url);
631
632
            $url = self::sanitizeUrl($url);
633
            $language = $site->language;
634
            $ogLanguage = LocalizationHelper::normalizeOgLocaleLanguage($language);
635
            $hreflangLanguage = $language;
636
            $hreflangLanguage = strtolower($hreflangLanguage);
637
            $hreflangLanguage = str_replace('_', '-', $hreflangLanguage);
638
            if ($includeUrl) {
639
                $localizedUrls[] = [
640
                    'id' => $site->id,
641
                    'language' => $language,
642
                    'ogLanguage' => $ogLanguage,
643
                    'hreflangLanguage' => $hreflangLanguage,
644
                    'url' => $url,
645
                    'primary' => $site->primary,
646
                    'current' => $thisSite->id === $site->id,
647
                ];
648
            }
649
        }
650
        Craft::endProfile('DynamicMeta::getLocalizedUrls', __METHOD__);
651
652
        return $localizedUrls;
653
    }
654
655
    /**
656
     * Return a sanitized URL with the query string stripped
657
     *
658
     * @param string $url
659
     * @param bool $checkStatus
660
     *
661
     * @return string
662
     */
663
    public static function sanitizeUrl(string $url, bool $checkStatus = true, bool $stripQueryString = true): string
664
    {
665
        // Remove the query string
666
        if ($stripQueryString) {
667
            $url = UrlHelper::stripQueryString($url);
668
        }
669
        $url = UrlHelper::encodeUrlQueryParams(TextHelper::sanitizeUserInput($url));
670
671
        // If this is a >= 400 status code, set the canonical URL to nothing
672
        if ($checkStatus && !Craft::$app->getRequest()->getIsConsoleRequest() && Craft::$app->getResponse()->statusCode >= 400) {
673
            $url = '';
674
        }
675
676
        return $url;
677
    }
678
679
    /**
680
     * Add the Same As meta tags and JSON-LD
681
     */
682
    public static function addSameAsMeta()
683
    {
684
        Craft::beginProfile('DynamicMeta::addSameAsMeta', __METHOD__);
685
        $metaContainers = Seomatic::$plugin->metaContainers;
686
        $sameAsUrls = [];
687
        if (!empty($metaContainers->metaSiteVars->sameAsLinks)) {
688
            $sameAsUrls = ArrayHelper::getColumn($metaContainers->metaSiteVars->sameAsLinks, 'url', false);
689
            $sameAsUrls = array_values(array_filter($sameAsUrls));
690
        }
691
        // Facebook OpenGraph
692
        $ogSeeAlso = Seomatic::$plugin->tag->get('og:see_also');
693
        if ($ogSeeAlso) {
0 ignored issues
show
introduced by
$ogSeeAlso is of type nystudio107\seomatic\models\MetaTag, thus it always evaluated to true.
Loading history...
694
            $ogSeeAlso->content = $sameAsUrls;
695
        }
696
        // Site Identity JSON-LD
697
        $identity = Seomatic::$plugin->jsonLd->get('identity');
698
        /** @var Thing|null $identity */
699
        if ($identity !== null && property_exists($identity, 'sameAs')) {
700
            $identity->sameAs = $sameAsUrls;
701
        }
702
        Craft::endProfile('DynamicMeta::addSameAsMeta', __METHOD__);
703
    }
704
705
    /**
706
     * Add the OpeningHoursSpecific to the $jsonLd based on the Entity settings
707
     *
708
     * @param MetaJsonLd $jsonLd
709
     * @param ?Entity $entity
710
     */
711
    public static function addOpeningHours(MetaJsonLd $jsonLd, ?Entity $entity)
712
    {
713
        Craft::beginProfile('DynamicMeta::addOpeningHours', __METHOD__);
714
        if ($jsonLd instanceof LocalBusiness && $entity !== null) {
715
            /** @var LocalBusiness $jsonLd */
716
            $openingHours = [];
717
            $days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
718
            $times = $entity->localBusinessOpeningHours;
719
            $index = 0;
720
            foreach ($times as $hours) {
721
                $openTime = '';
722
                $closeTime = '';
723
                if (!empty($hours['open'])) {
724
                    /** @var DateTime $dateTime */
725
                    try {
726
                        $dateTime = DateTimeHelper::toDateTime($hours['open']['date'], false, false);
727
                    } catch (\Exception $e) {
728
                        $dateTime = false;
729
                    }
730
                    if ($dateTime !== false) {
731
                        $openTime = $dateTime->format('H:i:s');
732
                    }
733
                }
734
                if (!empty($hours['close'])) {
735
                    /** @var DateTime $dateTime */
736
                    try {
737
                        $dateTime = DateTimeHelper::toDateTime($hours['close']['date'], false, false);
738
                    } catch (\Exception $e) {
739
                        $dateTime = false;
740
                    }
741
                    if ($dateTime !== false) {
742
                        $closeTime = $dateTime->format('H:i:s');
743
                    }
744
                }
745
                if ($openTime && $closeTime) {
746
                    /** @var OpeningHoursSpecification $hours */
747
                    $hours = Seomatic::$plugin->jsonLd->create([
748
                        'type' => 'OpeningHoursSpecification',
749
                        'opens' => $openTime,
750
                        'closes' => $closeTime,
751
                        'dayOfWeek' => [$days[$index]],
752
                    ], false);
753
                    $openingHours[] = $hours;
754
                }
755
                $index++;
756
            }
757
            $jsonLd->openingHoursSpecification = $openingHours;
758
        }
759
        Craft::endProfile('DynamicMeta::addOpeningHours', __METHOD__);
760
    }
761
762
    /**
763
     * Add the ContactPoint to the $jsonLd based on the Entity settings
764
     *
765
     * @param MetaJsonLd $jsonLd
766
     * @param Entity|null $entity
767
     */
768
    public static function addContactPoints(MetaJsonLd $jsonLd, ?Entity $entity)
769
    {
770
        Craft::beginProfile('DynamicMeta::addContactPoints', __METHOD__);
771
        if ($jsonLd instanceof Organization && $entity !== null) {
772
            /** @var Organization $jsonLd */
773
            $contactPoints = [];
774
            if (is_array($entity->organizationContactPoints)) {
0 ignored issues
show
introduced by
The condition is_array($entity->organizationContactPoints) is always true.
Loading history...
775
                foreach ($entity->organizationContactPoints as $contacts) {
776
                    /** @var ContactPoint $contact */
777
                    $contact = Seomatic::$plugin->jsonLd->create([
778
                        'type' => 'ContactPoint',
779
                        'telephone' => $contacts['telephone'],
780
                        'contactType' => $contacts['contactType'],
781
                    ], false);
782
                    $contactPoints[] = $contact;
783
                }
784
            }
785
            $jsonLd->contactPoint = $contactPoints;
786
        }
787
        Craft::endProfile('DynamicMeta::addContactPoints', __METHOD__);
788
    }
789
790
    /**
791
     * Normalize the array of opening hours passed in
792
     *
793
     * @param $value
794
     */
795
    public static function normalizeTimes(&$value)
796
    {
797
        if (is_string($value)) {
798
            $value = Json::decode($value);
799
        }
800
        $normalized = [];
801
        $times = ['open', 'close'];
802
        for ($day = 0; $day <= 6; $day++) {
803
            foreach ($times as $time) {
804
                if (isset($value[$day][$time])
805
                    && ($date = DateTimeHelper::toDateTime($value[$day][$time])) !== false
806
                ) {
807
                    $normalized[$day][$time] = (array)($date);
808
                } else {
809
                    $normalized[$day][$time] = null;
810
                }
811
            }
812
        }
813
814
        $value = $normalized;
815
    }
816
}
817