MetaContainers::getMatchedMetaBundle()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 21
ccs 0
cts 15
cp 0
rs 9.7998
cc 3
nc 3
nop 0
crap 12
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\services;
13
14
use Craft;
15
use craft\base\Component;
16
use craft\base\Element;
17
use craft\base\ElementInterface;
0 ignored issues
show
Bug introduced by
The type craft\base\ElementInterface 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 craft\commerce\Plugin as CommercePlugin;
19
use craft\console\Application as ConsoleApplication;
20
use craft\elements\GlobalSet;
21
use craft\helpers\ElementHelper;
22
use craft\web\UrlManager;
23
use nystudio107\seomatic\base\MetaContainer;
24
use nystudio107\seomatic\base\MetaItem;
25
use nystudio107\seomatic\events\InvalidateContainerCachesEvent;
26
use nystudio107\seomatic\events\MetaBundleDebugDataEvent;
27
use nystudio107\seomatic\helpers\ArrayHelper;
28
use nystudio107\seomatic\helpers\DynamicMeta as DynamicMetaHelper;
29
use nystudio107\seomatic\helpers\Field as FieldHelper;
30
use nystudio107\seomatic\helpers\Json;
31
use nystudio107\seomatic\helpers\Localization as LocalizationHelper;
32
use nystudio107\seomatic\helpers\MetaValue as MetaValueHelper;
33
use nystudio107\seomatic\helpers\UrlHelper;
34
use nystudio107\seomatic\models\FrontendTemplateContainer;
35
use nystudio107\seomatic\models\MetaBundle;
36
use nystudio107\seomatic\models\MetaGlobalVars;
37
use nystudio107\seomatic\models\MetaJsonLd;
38
use nystudio107\seomatic\models\MetaJsonLdContainer;
39
use nystudio107\seomatic\models\MetaLinkContainer;
40
use nystudio107\seomatic\models\MetaScript;
41
use nystudio107\seomatic\models\MetaScriptContainer;
42
use nystudio107\seomatic\models\MetaSitemapVars;
43
use nystudio107\seomatic\models\MetaSiteVars;
44
use nystudio107\seomatic\models\MetaTagContainer;
45
use nystudio107\seomatic\models\MetaTitleContainer;
46
use nystudio107\seomatic\seoelements\SeoProduct;
47
use nystudio107\seomatic\Seomatic;
48
use nystudio107\seomatic\services\JsonLd as JsonLdService;
49
use nystudio107\seomatic\variables\SeomaticVariable;
50
use Throwable;
51
use yii\base\Exception;
52
use yii\base\InvalidConfigException;
53
use yii\caching\TagDependency;
54
use yii\web\BadRequestHttpException;
55
use function is_array;
56
use function is_object;
57
58
/**
59
 * Meta container functions for SEOmatic
60
 * An instance of the service is available via [[`Seomatic::$plugin->metaContainers`|`seomatic.containers`]]
61
 *
62
 * @author    nystudio107
63
 * @package   Seomatic
64
 * @since     3.0.0
65
 */
66
class MetaContainers extends Component
67
{
68
    // Constants
69
    // =========================================================================
70
71
    public const GLOBAL_METACONTAINER_CACHE_TAG = 'seomatic_metacontainer';
72
    public const METACONTAINER_CACHE_TAG = 'seomatic_metacontainer_';
73
74
    public const CACHE_KEY = 'seomatic_metacontainer_';
75
    public const INVALID_RESPONSE_CACHE_KEY = 'seomatic_invalid_response';
76
    public const GLOBALS_CACHE_KEY = 'parsed_globals_';
77
    public const SCRIPTS_CACHE_KEY = 'body_scripts_';
78
79
    /** @var array Rules for replacement values on arbitrary empty values */
80
    public const COMPOSITE_SETTING_LOOKUP = [
81
        'ogImage' => [
82
            'metaBundleSettings.ogImageSource' => 'sameAsSeo.seoImage',
83
        ],
84
        'twitterImage' => [
85
            'metaBundleSettings.twitterImageSource' => 'sameAsSeo.seoImage',
86
        ],
87
    ];
88
89
    /**
90
     * @event InvalidateContainerCachesEvent The event that is triggered when SEOmatic
91
     *        is about to clear its meta container caches
92
     *
93
     * ---
94
     * ```php
95
     * use nystudio107\seomatic\events\InvalidateContainerCachesEvent;
96
     * use nystudio107\seomatic\services\MetaContainers;
97
     * use yii\base\Event;
98
     * Event::on(MetaContainers::class, MetaContainers::EVENT_INVALIDATE_CONTAINER_CACHES, function(InvalidateContainerCachesEvent $e) {
99
     *     // Container caches are about to be cleared
100
     * });
101
     * ```
102
     */
103
    public const EVENT_INVALIDATE_CONTAINER_CACHES = 'invalidateContainerCaches';
104
105
    /**
106
     * @event MetaBundleDebugDataEvent The event that is triggered to record MetaBundle
107
     * debug data
108
     *
109
     * ---
110
     * ```php
111
     * use nystudio107\seomatic\events\MetaBundleDebugDataEvent;
112
     * use nystudio107\seomatic\services\MetaContainers;
113
     * use yii\base\Event;
114
     * Event::on(MetaContainers::class, MetaContainers::EVENT_METABUNDLE_DEBUG_DATA, function(MetaBundleDebugDataEvent $e) {
115
     *     // Do something with the MetaBundle debug data
116
     * });
117
     * ```
118
     */
119
    public const EVENT_METABUNDLE_DEBUG_DATA = 'metaBundleDebugData';
120
121
    // Public Properties
122
    // =========================================================================
123
124
    /**
125
     * @var MetaGlobalVars|null
126
     */
127
    public $metaGlobalVars;
128
129
    /**
130
     * @var MetaSiteVars|null
131
     */
132
    public $metaSiteVars;
133
134
    /**
135
     * @var MetaSitemapVars|null
136
     */
137
    public $metaSitemapVars;
138
139
    /**
140
     * @var string The current page number of paginated pages
141
     */
142
    public $paginationPage = '1';
143
144
    /**
145
     * @var null|string Cached nonce to be shared by all JSON-LD entities
146
     */
147
    public $cachedJsonLdNonce;
148
149
    /**
150
     * @var MetaContainer[]|array|null
151
     */
152
    public $metaContainers = [];
153
154
    // Protected Properties
155
    // =========================================================================
156
157
    /**
158
     * @var null|MetaBundle
159
     */
160
    protected $matchedMetaBundle;
161
162
    /**
163
     * @var null|TagDependency
164
     */
165
    protected $containerDependency;
166
167
    /**
168
     * @var bool Whether or not the matched element should be included in the
169
     *      meta containers
170
     */
171
    protected $includeMatchedElement = true;
172
173
    // Public Methods
174
    // =========================================================================
175
176
    /**
177
     * @inheritdoc
178
     */
179 1
    public function init(): void
180
    {
181 1
        parent::init();
182
        // Get the page number of this request
183 1
        $request = Craft::$app->getRequest();
184 1
        if (!$request->isConsoleRequest) {
185
            $this->paginationPage = (string)$request->pageNum;
186
        }
187
    }
188
189
    /**
190
     * Return the containers of a specific type
191
     *
192
     * @param string $type
193
     *
194
     * @return array
195
     */
196
    public function getContainersOfType(string $type): array
197
    {
198
        $containers = [];
199
        /** @var MetaContainer $metaContainer */
200
        foreach ($this->metaContainers as $metaContainer) {
201
            if ($metaContainer::CONTAINER_TYPE === $type) {
202
                $containers[] = $metaContainer;
203
            }
204
        }
205
206
        return $containers;
207
    }
208
209
    /**
210
     * Include the meta containers
211
     */
212
    public function includeMetaContainers()
213
    {
214
        Craft::beginProfile('MetaContainers::includeMetaContainers', __METHOD__);
215
        // Fire an 'metaBundleDebugData' event
216
        if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
217
            $metaBundle = new MetaBundle([
218
                'metaGlobalVars' => clone $this->metaGlobalVars,
219
                'metaSiteVars' => clone $this->metaSiteVars,
220
                'metaSitemapVars' => clone $this->metaSitemapVars,
221
                'metaContainers' => $this->metaContainers,
222
            ]);
223
            $event = new MetaBundleDebugDataEvent([
224
                'metaBundleCategory' => MetaBundleDebugDataEvent::COMBINED_META_BUNDLE,
225
                'metaBundle' => $metaBundle,
226
            ]);
227
            $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
228
        }
229
        // Add in our http headers
230
        DynamicMetaHelper::includeHttpHeaders();
231
        DynamicMetaHelper::addCspTags();
232
        $this->parseGlobalVars();
233
        foreach ($this->metaContainers as $metaContainer) {
234
            /** @var $metaContainer MetaContainer */
235
            if ($metaContainer->include) {
236
                // Don't cache the rendered result if we're previewing meta containers
237
                if (Seomatic::$previewingMetaContainers) {
238
                    $metaContainer->clearCache = true;
239
                }
240
                $metaContainer->includeMetaData($this->containerDependency);
241
            }
242
        }
243
        Craft::endProfile('MetaContainers::includeMetaContainers', __METHOD__);
244
    }
245
246
    /**
247
     * Parse the global variables
248
     */
249
    public function parseGlobalVars()
250
    {
251
        $dependency = $this->containerDependency;
252
        $uniqueKey = $dependency->tags[3] ?? self::GLOBALS_CACHE_KEY;
253
        list($this->metaGlobalVars, $this->metaSiteVars) = Craft::$app->getCache()->getOrSet(
254
            self::GLOBALS_CACHE_KEY . $uniqueKey,
255
            function() use ($uniqueKey) {
256
                Craft::info(
257
                    self::GLOBALS_CACHE_KEY . ' cache miss: ' . $uniqueKey,
258
                    __METHOD__
259
                );
260
261
                if ($this->metaGlobalVars) {
262
                    $this->metaGlobalVars->parseProperties();
263
                }
264
                if ($this->metaSiteVars) {
265
                    $this->metaSiteVars->parseProperties();
266
                }
267
268
                return [$this->metaGlobalVars, $this->metaSiteVars];
269
            },
270
            Seomatic::$cacheDuration,
271
            $dependency
272
        );
273
    }
274
275
    /**
276
     * Prep all of the meta for preview purposes
277
     *
278
     * @param string $uri
279
     * @param int|null $siteId
280
     * @param bool $parseVariables Whether or not the variables should be
281
     *                                 parsed as Twig
282
     * @param bool $includeElement Whether or not the matched element
283
     *                                 should be factored into the preview
284
     */
285
    public function previewMetaContainers(
286
        string            $uri = '',
287
        int               $siteId = null,
288
        bool              $parseVariables = false,
289
        bool              $includeElement = true,
290
        ?ElementInterface $element = null,
291
    ) {
292
        // If we've already previewed the containers for this request, there's no need to do it again
293
        if (Seomatic::$previewingMetaContainers && !Seomatic::$headlessRequest) {
294
            return;
295
        }
296
        // It's possible this won't exist at this point
297
        if (!Seomatic::$seomaticVariable) {
298
            // Create our variable and stash it in the plugin for global access
299
            Seomatic::$seomaticVariable = new SeomaticVariable();
300
        }
301
        Seomatic::$previewingMetaContainers = true;
302
        $this->includeMatchedElement = $includeElement;
303
        $this->loadMetaContainers($uri, $siteId, $element);
304
        // Load in the right globals
305
        $twig = Craft::$app->getView()->getTwig();
0 ignored issues
show
Unused Code introduced by
The assignment to $twig is dead and can be removed.
Loading history...
306
        $globalSets = GlobalSet::findAll([
307
            'siteId' => $siteId,
308
        ]);
309
        foreach ($globalSets as $globalSet) {
310
            MetaValueHelper::$templatePreviewVars[$globalSet->handle] = $globalSet;
311
        }
312
        // Parse the global vars
313
        if ($parseVariables) {
314
            $this->parseGlobalVars();
315
        }
316
        // Get the homeUrl and canonicalUrl
317
        $homeUrl = '/';
318
        $canonicalUrl = $this->metaGlobalVars->parsedValue('canonicalUrl');
0 ignored issues
show
Bug introduced by
The method parsedValue() does not exist on null. ( Ignorable by Annotation )

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

318
        /** @scrutinizer ignore-call */ 
319
        $canonicalUrl = $this->metaGlobalVars->parsedValue('canonicalUrl');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
319
        $canonicalUrl = DynamicMetaHelper::sanitizeUrl($canonicalUrl, false);
320
        // Special-case the global bundle
321
        if ($uri === MetaBundles::GLOBAL_META_BUNDLE || $uri === '__home__') {
322
            $canonicalUrl = '/';
323
        }
324
        try {
325
            $homeUrl = UrlHelper::siteUrl($homeUrl, null, null, $siteId);
326
            $canonicalUrl = UrlHelper::siteUrl($canonicalUrl, null, null, $siteId);
327
        } catch (Exception $e) {
328
            Craft::error($e->getMessage(), __METHOD__);
329
        }
330
        $canonical = Seomatic::$seomaticVariable->link->get('canonical');
331
        if ($canonical !== null) {
332
            $canonical->href = $canonicalUrl;
333
        }
334
        $home = Seomatic::$seomaticVariable->link->get('home');
335
        if ($home !== null) {
336
            $home->href = $homeUrl;
337
        }
338
        // The current language may _not_ match the current site, if we're headless
339
        $ogLocale = Seomatic::$seomaticVariable->tag->get('og:locale');
340
        if ($ogLocale !== null && $siteId !== null) {
341
            $site = Craft::$app->getSites()->getSiteById($siteId);
342
            if ($site !== null) {
343
                $ogLocale->content = LocalizationHelper::normalizeOgLocaleLanguage($site->language);
344
            }
345
        }
346
        // Update seomatic.meta.canonicalUrl when previewing meta containers
347
        $this->metaGlobalVars->canonicalUrl = $canonicalUrl;
348
    }
349
350
    /**
351
     * Load the meta containers
352
     *
353
     * @param string|null $uri
354
     * @param int|null $siteId
355
     * @param ElementInterface|null $element
356
     */
357
    public function loadMetaContainers(?string $uri = '', int $siteId = null, ?ElementInterface $element = null)
358
    {
359
        Craft::beginProfile('MetaContainers::loadMetaContainers', __METHOD__);
360
        // Avoid recursion
361
        if (!Seomatic::$loadingMetaContainers) {
362
            Seomatic::$loadingMetaContainers = true;
363
            $this->setMatchedElement($uri, $siteId);
0 ignored issues
show
Bug introduced by
It seems like $uri can also be of type null; however, parameter $uri of nystudio107\seomatic\ser...rs::setMatchedElement() does only seem to accept string, 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

363
            $this->setMatchedElement(/** @scrutinizer ignore-type */ $uri, $siteId);
Loading history...
364
            // If this is a draft or revision we're previewing, swap it in so they see the draft preview image & data
365
            if ($element && ElementHelper::isDraftOrRevision($element)) {
366
                Seomatic::setMatchedElement($element);
367
            }
368
            // Get the cache tag for the matched meta bundle
369
            $metaBundle = $this->getMatchedMetaBundle();
370
            $metaBundleSourceId = '';
371
            $metaBundleSourceType = '';
372
            if ($metaBundle) {
373
                $metaBundleSourceId = $metaBundle->sourceId;
374
                $metaBundleSourceType = $metaBundle->sourceBundleType;
375
            }
376
            // We need an actual $siteId here for the cache key
377
            if ($siteId === null) {
378
                $siteId = Craft::$app->getSites()->currentSite->id
379
                    ?? Craft::$app->getSites()->primarySite->id
380
                    ?? 1;
381
            }
382
            // Handle pagination
383
            $paginationPage = 'page' . $this->paginationPage;
384
            // Get the path for the current request
385
            $request = Craft::$app->getRequest();
386
            $requestPath = '/';
387
            if (!$request->getIsConsoleRequest()) {
388
                try {
389
                    $requestPath = $request->getPathInfo();
390
                } catch (InvalidConfigException $e) {
391
                    Craft::error($e->getMessage(), __METHOD__);
392
                }
393
                // If this is any type of a preview, ensure that it's not cached
394
                if (Seomatic::$plugin->helper::isPreview()) {
395
                    Seomatic::$previewingMetaContainers = true;
396
                }
397
            }
398
            // Cache requests that have a token associated with them separately
399
            $token = '';
400
            $request = Craft::$app->getRequest();
401
            if (!$request->isConsoleRequest) {
402
                try {
403
                    $token = $request->getToken() ?? '';
404
                } catch (BadRequestHttpException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
405
                }
406
            }
407
            // Get our cache key
408
            $cacheKey = $uri . $siteId . $paginationPage . $requestPath . $this->getAllowedUrlParams() . $token;
409
            // For requests with a status code of >= 400, use one cache key
410
            if (!$request->isConsoleRequest) {
411
                $response = Craft::$app->getResponse();
412
                if ($response->statusCode >= 400) {
413
                    $cacheKey = $siteId . self::INVALID_RESPONSE_CACHE_KEY . $response->statusCode;
414
                }
415
            }
416
            // Load the meta containers
417
            $dependency = new TagDependency([
418
                'tags' => [
419
                    self::GLOBAL_METACONTAINER_CACHE_TAG,
420
                    self::METACONTAINER_CACHE_TAG . $metaBundleSourceId . $metaBundleSourceType . $siteId,
421
                    self::METACONTAINER_CACHE_TAG . $uri . $siteId,
422
                    self::METACONTAINER_CACHE_TAG . $cacheKey,
423
                    self::METACONTAINER_CACHE_TAG . $metaBundleSourceId . $metaBundleSourceType,
424
                ],
425
            ]);
426
            $this->containerDependency = $dependency;
427
            $debugModule = Seomatic::$settings->enableDebugToolbarPanel ? Craft::$app->getModule('debug') : null;
428
            if (Seomatic::$previewingMetaContainers || $debugModule) {
429
                Seomatic::$plugin->frontendTemplates->loadFrontendTemplateContainers($siteId);
430
                $this->loadGlobalMetaContainers($siteId);
431
                $this->loadContentMetaContainers();
432
                $this->loadFieldMetaContainers();
433
                // We only need the dynamic data for headless requests
434
                if (Seomatic::$headlessRequest || Seomatic::$plugin->helper::isPreview() || $debugModule) {
435
                    DynamicMetaHelper::addDynamicMetaToContainers($uri, $siteId);
436
                }
437
            } else {
438
                $cache = Craft::$app->getCache();
439
                list($this->metaGlobalVars, $this->metaSiteVars, $this->metaSitemapVars, $this->metaContainers) = $cache->getOrSet(
440
                    self::CACHE_KEY . $cacheKey,
441
                    function() use ($uri, $siteId) {
442
                        Craft::info(
443
                            'Meta container cache miss: ' . $uri . '/' . $siteId,
444
                            __METHOD__
445
                        );
446
                        $this->loadGlobalMetaContainers($siteId);
447
                        $this->loadContentMetaContainers();
448
                        $this->loadFieldMetaContainers();
449
                        DynamicMetaHelper::addDynamicMetaToContainers($uri, $siteId);
450
451
                        return [$this->metaGlobalVars, $this->metaSiteVars, $this->metaSitemapVars, $this->metaContainers];
452
                    },
453
                    Seomatic::$cacheDuration,
454
                    $dependency
455
                );
456
            }
457
            Seomatic::$seomaticVariable->init();
0 ignored issues
show
Bug introduced by
The method init() does not exist on null. ( Ignorable by Annotation )

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

457
            Seomatic::$seomaticVariable->/** @scrutinizer ignore-call */ 
458
                                         init();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
458
            MetaValueHelper::cache();
459
            Seomatic::$loadingMetaContainers = false;
460
        }
461
        Craft::endProfile('MetaContainers::loadMetaContainers', __METHOD__);
462
    }
463
464
    /**
465
     * Return the MetaBundle that corresponds with the Seomatic::$matchedElement
466
     *
467
     * @return null|MetaBundle
468
     */
469
    public function getMatchedMetaBundle()
470
    {
471
        $metaBundle = null;
472
        /** @var Element|null $element */
473
        $element = Seomatic::$matchedElement;
474
        if ($element) {
475
            $sourceType = Seomatic::$plugin->seoElements->getMetaBundleTypeFromElement($element);
476
            if ($sourceType) {
477
                list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId)
478
                    = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element);
479
                $metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
480
                    $sourceType,
481
                    $sourceId,
482
                    $sourceSiteId,
483
                    $typeId
484
                );
485
            }
486
        }
487
        $this->matchedMetaBundle = $metaBundle;
488
489
        return $metaBundle;
490
    }
491
492
    /**
493
     * Load the global site meta containers
494
     *
495
     * @param int|null $siteId
496
     */
497
    public function loadGlobalMetaContainers(int $siteId = null)
498
    {
499
        Craft::beginProfile('MetaContainers::loadGlobalMetaContainers', __METHOD__);
500
        if ($siteId === null) {
501
            $siteId = Craft::$app->getSites()->currentSite->id ?? 1;
502
        }
503
        $metaBundle = Seomatic::$plugin->metaBundles->getGlobalMetaBundle($siteId);
504
        if ($metaBundle) {
505
            // Fire an 'metaBundleDebugData' event
506
            if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
507
                $event = new MetaBundleDebugDataEvent([
508
                    'metaBundleCategory' => MetaBundleDebugDataEvent::GLOBAL_META_BUNDLE,
509
                    'metaBundle' => $metaBundle,
510
                ]);
511
                $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
512
            }
513
            // Meta global vars
514
            $this->metaGlobalVars = clone $metaBundle->metaGlobalVars;
515
            // Meta site vars
516
            $this->metaSiteVars = clone $metaBundle->metaSiteVars;
517
            // Meta sitemap vars
518
            $this->metaSitemapVars = clone $metaBundle->metaSitemapVars;
519
            // Language
520
            $this->metaGlobalVars->language = Seomatic::$language;
521
            // Meta containers
522
            foreach ($metaBundle->metaContainers as $key => $metaContainer) {
523
                $this->metaContainers[$key] = clone $metaContainer;
524
            }
525
        }
526
        Craft::endProfile('MetaContainers::loadGlobalMetaContainers', __METHOD__);
527
    }
528
529
    /**
530
     * Add the meta bundle to our existing meta containers, overwriting meta
531
     * items with the same key
532
     *
533
     * @param MetaBundle $metaBundle
534
     */
535
    public function addMetaBundleToContainers(MetaBundle $metaBundle)
536
    {
537
        // Ensure the variable is synced properly first
538
        Seomatic::$seomaticVariable->init();
539
        // Meta global vars
540
        $attributes = $metaBundle->metaGlobalVars->getAttributes();
0 ignored issues
show
Bug introduced by
The method getAttributes() does not exist on null. ( Ignorable by Annotation )

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

540
        /** @scrutinizer ignore-call */ 
541
        $attributes = $metaBundle->metaGlobalVars->getAttributes();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
541
        // Parse the meta values so we can filter out any blank or empty attributes
542
        // So that they can fall back on the parent container
543
        $parsedAttributes = $attributes;
544
        MetaValueHelper::parseArray($parsedAttributes);
545
        $parsedAttributes = array_filter(
546
            $parsedAttributes,
547
            [ArrayHelper::class, 'preserveBools']
548
        );
549
        $attributes = array_intersect_key($attributes, $parsedAttributes);
550
        // Add the attributes in
551
        $attributes = array_filter(
552
            $attributes,
553
            [ArrayHelper::class, 'preserveBools']
554
        );
555
        $this->metaGlobalVars->setAttributes($attributes, false);
556
        // Meta site vars
557
        /*
558
         * Don't merge in the Site vars, since they are only editable on
559
         * a global basis. Otherwise stale data will be unable to be edited
560
        $attributes = $metaBundle->metaSiteVars->getAttributes();
561
        $attributes = array_filter($attributes);
562
        $this->metaSiteVars->setAttributes($attributes, false);
563
        */
564
        // Meta sitemap vars
565
        $attributes = $metaBundle->metaSitemapVars->getAttributes();
0 ignored issues
show
Bug introduced by
The method getAttributes() does not exist on null. ( Ignorable by Annotation )

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

565
        /** @scrutinizer ignore-call */ 
566
        $attributes = $metaBundle->metaSitemapVars->getAttributes();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
566
        $attributes = array_filter(
567
            $attributes,
568
            [ArrayHelper::class, 'preserveBools']
569
        );
570
        $this->metaSitemapVars->setAttributes($attributes, false);
0 ignored issues
show
Bug introduced by
The method setAttributes() does not exist on null. ( Ignorable by Annotation )

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

570
        $this->metaSitemapVars->/** @scrutinizer ignore-call */ 
571
                                setAttributes($attributes, false);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
571
        // Language
572
        $this->metaGlobalVars->language = Seomatic::$language;
573
        // Meta containers
574
        foreach ($metaBundle->metaContainers as $key => $metaContainer) {
575
            foreach ($metaContainer->data as $metaTag) {
576
                $this->addToMetaContainer($metaTag, $key);
577
            }
578
        }
579
    }
580
581
    /**
582
     * Add the passed in MetaItem to the MetaContainer indexed as $key
583
     *
584
     * @param $data MetaItem The MetaItem to add to the container
585
     * @param $key  string   The key to the container to add the data to
586 1
     */
587
    public function addToMetaContainer(MetaItem $data, string $key)
588
    {
589 1
        /** @var MetaContainer $container */
590
        $container = $this->getMetaContainer($key);
591 1
592
        if ($container !== null) {
593
            $container->addData($data, $data->key);
594
        }
595
    }
596
597
    /**
598
     * @param string $key
599
     *
600
     * @return mixed|null
601 1
     */
602
    public function getMetaContainer(string $key)
603 1
    {
604 1
        if (!$key || empty($this->metaContainers[$key])) {
605 1
            $error = Craft::t(
606 1
                'seomatic',
607 1
                'Meta container with key `{key}` does not exist.',
608 1
                ['key' => $key]
609 1
            );
610
            Craft::error($error, __METHOD__);
611 1
612
            return null;
613
        }
614
615
        return $this->metaContainers[$key];
616
    }
617
618
    /**
619
     * Create a MetaContainer of the given $type with the $key
620
     *
621
     * @param string $type
622
     * @param string $key
623
     *
624
     * @return null|MetaContainer
625
     */
626
    public function createMetaContainer(string $type, string $key): ?MetaContainer
627
    {
628
        /** @var MetaContainer $container */
629
        $container = null;
630
        if (empty($this->metaContainers[$key])) {
631
            /** @var string|null $className */
632
            $className = null;
633
            // Create a new container based on the type passed in
634
            switch ($type) {
635
                case MetaTagContainer::CONTAINER_TYPE:
636
                    $className = MetaTagContainer::class;
637
                    break;
638
                case MetaLinkContainer::CONTAINER_TYPE:
639
                    $className = MetaLinkContainer::class;
640
                    break;
641
                case MetaScriptContainer::CONTAINER_TYPE:
642
                    $className = MetaScriptContainer::class;
643
                    break;
644
                case MetaJsonLdContainer::CONTAINER_TYPE:
645
                    $className = MetaJsonLdContainer::class;
646
                    break;
647
                case MetaTitleContainer::CONTAINER_TYPE:
648
                    $className = MetaTitleContainer::class;
649
                    break;
650
            }
651
            if ($className) {
652
                $container = $className::create();
653
                $this->metaContainers[$key] = $container;
654
            }
655
        }
656
657
        /** @var MetaContainer $className */
658
        return $container;
659
    }
660
661
    // Protected Methods
662
    // =========================================================================
663
664
    /**
665
     * Render the HTML of all MetaContainers of a specific $type
666
     *
667
     * @param string $type
668
     *
669
     * @return string
670
     */
671
    public function renderContainersByType(string $type): string
672
    {
673
        $html = '';
674
        // Special-case for requests for the FrontendTemplateContainer "container"
675
        if ($type === FrontendTemplateContainer::CONTAINER_TYPE) {
676
            $renderedTemplates = [];
677
            if (Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'] ?? false) {
678
                $frontendTemplateContainers = Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'];
679
                foreach ($frontendTemplateContainers as $name => $frontendTemplateContainer) {
680
                    if ($frontendTemplateContainer->include) {
681
                        $result = $frontendTemplateContainer->render([
682
                        ]);
683
                        $renderedTemplates[] = [$name => $result];
684
                    }
685
                }
686
            }
687
            $html .= Json::encode($renderedTemplates);
688
689
            return $html;
690
        }
691
        /** @var MetaContainer $metaContainer */
692
        foreach ($this->metaContainers as $metaContainer) {
693
            if ($metaContainer::CONTAINER_TYPE === $type && $metaContainer->include) {
694
                $result = $metaContainer->render([
695
                    'renderRaw' => true,
696
                    'renderScriptTags' => true,
697
                    'array' => true,
698
                ]);
699
                // Special case for script containers, because they can have body scripts too
700
                if ($metaContainer::CONTAINER_TYPE === MetaScriptContainer::CONTAINER_TYPE) {
701
                    $bodyScript = '';
702
                    /** @var MetaScriptContainer $metaContainer */
703
                    if ($metaContainer->prepForInclusion()) {
704
                        foreach ($metaContainer->data as $metaScript) {
705
                            /** @var MetaScript $metaScript */
706
                            if (!empty($metaScript->bodyTemplatePath)) {
707
                                $bodyScript .= $metaScript->renderBodyHtml();
708
                            }
709
                        }
710
                    }
711
712
                    $result = Json::encode([
713
                        'script' => $result,
714
                        'bodyScript' => $bodyScript,
715
                    ]);
716
                }
717
718
                $html .= $result;
719
            }
720
        }
721
        // Special-case for requests for the MetaSiteVars "container"
722
        if ($type === MetaSiteVars::CONTAINER_TYPE) {
723
            $result = Json::encode($this->metaSiteVars->toArray());
0 ignored issues
show
Bug introduced by
The method toArray() does not exist on null. ( Ignorable by Annotation )

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

723
            $result = Json::encode($this->metaSiteVars->/** @scrutinizer ignore-call */ toArray());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
724
            $html .= $result;
725
        }
726
727
        return $html;
728
    }
729
730
    /**
731
     * Render the HTML of all MetaContainers of a specific $type as an array
732
     *
733
     * @param string $type
734
     *
735
     * @return array
736
     */
737
    public function renderContainersArrayByType(string $type): array
738
    {
739
        $htmlArray = [];
740
        // Special-case for requests for the FrontendTemplateContainer "container"
741
        if ($type === FrontendTemplateContainer::CONTAINER_TYPE) {
742
            $renderedTemplates = [];
743
            if (Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'] ?? false) {
744
                $frontendTemplateContainers = Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'];
745
                foreach ($frontendTemplateContainers as $name => $frontendTemplateContainer) {
746
                    if ($frontendTemplateContainer->include) {
747
                        $result = $frontendTemplateContainer->render([
748
                        ]);
749
                        $renderedTemplates[] = [$name => $result];
750
                    }
751
                }
752
            }
753
754
            return $renderedTemplates;
755
        }
756
        /** @var MetaContainer $metaContainer */
757
        foreach ($this->metaContainers as $metaContainer) {
758
            if ($metaContainer::CONTAINER_TYPE === $type && $metaContainer->include) {
759
                /** @noinspection SlowArrayOperationsInLoopInspection */
760
                $htmlArray = array_merge($htmlArray, $metaContainer->renderArray());
761
            }
762
        }
763
        // Special-case for requests for the MetaSiteVars "container"
764
        if ($type === MetaSiteVars::CONTAINER_TYPE) {
765
            $result = Json::encode($this->metaSiteVars->toArray());
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
766
            $htmlArray = array_merge($htmlArray, $this->metaSiteVars->toArray());
767
        }
768
769
        return $htmlArray;
770
    }
771
772
    /**
773
     * Return a MetaItem object by $key from container $type
774
     *
775
     * @param string $key
776
     * @param string $type
777
     *
778
     * @return null|MetaItem
779
     */
780
    public function getMetaItemByKey(string $key, string $type = '')
781
    {
782
        $metaItem = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $metaItem is dead and can be removed.
Loading history...
783
        /** @var MetaContainer $metaContainer */
784
        foreach ($this->metaContainers as $metaContainer) {
785
            if (($metaContainer::CONTAINER_TYPE === $type) || empty($type)) {
786
                foreach ($metaContainer->data as $metaItem) {
787
                    if ($key === $metaItem->key) {
788
                        return $metaItem;
789
                    }
790
                }
791
            }
792
        }
793
794
        return null;
795
    }
796
797
    /**
798
     * Invalidate all of the meta container caches
799
     */
800
    public function invalidateCaches()
801
    {
802
        $cache = Craft::$app->getCache();
803
        TagDependency::invalidate($cache, self::GLOBAL_METACONTAINER_CACHE_TAG);
804
        Craft::info(
805
            'All meta container caches cleared',
806
            __METHOD__
807
        );
808
        // Trigger an event to let other plugins/modules know we've cleared our caches
809
        $event = new InvalidateContainerCachesEvent([
810
            'uri' => null,
811
            'siteId' => null,
812
            'sourceId' => null,
813
            'sourceType' => null,
814
        ]);
815
        if (!Craft::$app instanceof ConsoleApplication) {
816
            $this->trigger(self::EVENT_INVALIDATE_CONTAINER_CACHES, $event);
817
        }
818
    }
819
820
    /**
821
     * Invalidate a meta bundle cache
822
     *
823
     * @param int $sourceId
824
     * @param null|string $sourceType
825
     * @param null|int $siteId
826
     */
827
    public function invalidateContainerCacheById(int $sourceId, $sourceType = null, $siteId = null)
828
    {
829
        $metaBundleSourceId = '';
830
        if ($sourceId) {
831
            $metaBundleSourceId = $sourceId;
832
        }
833
        $metaBundleSourceType = '';
834
        if ($sourceType) {
835
            $metaBundleSourceType = $sourceType;
836
        }
837
        $cache = Craft::$app->getCache();
838
        TagDependency::invalidate(
839
            $cache,
840
            self::METACONTAINER_CACHE_TAG . $metaBundleSourceId . $metaBundleSourceType . $siteId
841
        );
842
        Craft::info(
843
            'Meta bundle cache cleared: ' . $metaBundleSourceId . ' / ' . $metaBundleSourceType . ' / ' . $siteId,
844
            __METHOD__
845
        );
846
        // Trigger an event to let other plugins/modules know we've cleared our caches
847
        $event = new InvalidateContainerCachesEvent([
848
            'uri' => null,
849
            'siteId' => $siteId,
850
            'sourceId' => $sourceId,
851
            'sourceType' => $metaBundleSourceType,
852
        ]);
853
        if (!Craft::$app instanceof ConsoleApplication) {
854
            $this->trigger(self::EVENT_INVALIDATE_CONTAINER_CACHES, $event);
855
        }
856
    }
857
858
    /**
859
     * Invalidate a meta bundle cache
860
     *
861
     * @param string $uri
862
     * @param null|int $siteId
863
     */
864
    public function invalidateContainerCacheByPath(string $uri, $siteId = null)
865
    {
866
        $cache = Craft::$app->getCache();
867
        if ($siteId === null) {
868
            $siteId = Craft::$app->getSites()->currentSite->id ?? 1;
869
        }
870
        TagDependency::invalidate($cache, self::METACONTAINER_CACHE_TAG . $uri . $siteId);
871
        Craft::info(
872
            'Meta container cache cleared: ' . $uri . ' / ' . $siteId,
873
            __METHOD__
874
        );
875
        // Trigger an event to let other plugins/modules know we've cleared our caches
876
        $event = new InvalidateContainerCachesEvent([
877
            'uri' => $uri,
878
            'siteId' => $siteId,
879
            'sourceId' => null,
880
            'sourceType' => null,
881
        ]);
882
        if (!Craft::$app instanceof ConsoleApplication) {
883
            $this->trigger(self::EVENT_INVALIDATE_CONTAINER_CACHES, $event);
884
        }
885
    }
886
887
    // Protected Methods
888
    // =========================================================================
889
890
    /**
891
     * Set the element that matches the $uri
892
     *
893
     * @param string $uri
894
     * @param int|null $siteId
895
     */
896
    protected function setMatchedElement(string $uri, int $siteId = null)
897
    {
898
        if ($siteId === null) {
899
            $siteId = Craft::$app->getSites()->currentSite->id
900
                ?? Craft::$app->getSites()->primarySite->id
901
                ?? 1;
902
        }
903
        $element = null;
904
        $uri = trim($uri, '/');
905
        /** @var Element $element */
906
        $enabledOnly = !Seomatic::$previewingMetaContainers;
907
        // Try to use Craft's matched element if looking for an enabled element, the current `siteId` is being used and
908
        // the current `uri` matches what was in the request
909
        $request = Craft::$app->getRequest();
910
        if ($enabledOnly && !$request->getIsConsoleRequest()) {
911
            /** @var UrlManager $urlManager */
912
            $urlManager = Craft::$app->getUrlManager();
913
            try {
914
                if ($siteId === Craft::$app->getSites()->currentSite->id
915
                    && $request->getPathInfo() === $uri) {
916
                    $element = $urlManager->getMatchedElement();
917
                }
918
            } catch (Throwable $e) {
919
                Craft::error($e->getMessage(), __METHOD__);
920
            }
921
        }
922
        if (!$element) {
923
            $element = Craft::$app->getElements()->getElementByUri($uri, $siteId, $enabledOnly);
924
        }
925
        if ($element && ($element->uri !== null)) {
926
            Seomatic::setMatchedElement($element);
927
        }
928
    }
929
930
    /**
931
     * Return as key/value pairs any allowed parameters in the request
932
     *
933
     * @return string
934
     */
935
    protected function getAllowedUrlParams(): string
936
    {
937
        $result = '';
938
        $allowedParams = Seomatic::$settings->allowedUrlParams;
939
        if (Craft::$app->getPlugins()->getPlugin(SeoProduct::REQUIRED_PLUGIN_HANDLE)) {
940
            $commerce = CommercePlugin::getInstance();
941
            if ($commerce !== null) {
942
                $allowedParams[] = 'variant';
943
            }
944
        }
945
        // Iterate through the allowed parameters, adding the key/value pair to the $result string as found
946
        $request = Craft::$app->getRequest();
947
        if (!$request->isConsoleRequest) {
948
            foreach ($allowedParams as $allowedParam) {
949
                $value = $request->getParam($allowedParam);
950
                if ($value !== null) {
951
                    $result .= "{$allowedParam}={$value}";
952
                }
953
            }
954
        }
955
956
        return $result;
957
    }
958
959
    /**
960
     * Load the meta containers specific to the matched meta bundle
961
     */
962
    protected function loadContentMetaContainers()
963
    {
964
        Craft::beginProfile('MetaContainers::loadContentMetaContainers', __METHOD__);
965
        $metaBundle = $this->getMatchedMetaBundle();
966
        if ($metaBundle) {
967
            // Fire an 'metaBundleDebugData' event
968
            if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
969
                $event = new MetaBundleDebugDataEvent([
970
                    'metaBundleCategory' => MetaBundleDebugDataEvent::CONTENT_META_BUNDLE,
971
                    'metaBundle' => $metaBundle,
972
                ]);
973
                $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
974
            }
975
            $this->addMetaBundleToContainers($metaBundle);
976
        }
977
        Craft::endProfile('MetaContainers::loadContentMetaContainers', __METHOD__);
978
    }
979
980
    /**
981
     * Load any meta containers in the current element
982
     */
983
    protected function loadFieldMetaContainers()
984
    {
985
        Craft::beginProfile('MetaContainers::loadFieldMetaContainers', __METHOD__);
986
        $element = Seomatic::$matchedElement;
987
        if ($element && $this->includeMatchedElement) {
988
            /** @var Element $element */
989
            $fieldHandles = FieldHelper::fieldsOfTypeFromElement($element, FieldHelper::SEO_SETTINGS_CLASS_KEY, true);
990
            foreach ($fieldHandles as $fieldHandle) {
991
                if (!empty($element->$fieldHandle)) {
992
                    /** @var MetaBundle $metaBundle */
993
                    $metaBundle = $element->$fieldHandle;
994
                    Seomatic::$plugin->metaBundles->pruneFieldMetaBundleSettings($metaBundle, $fieldHandle);
995
996
                    // See which properties have to be overridden, because the parent bundle says so.
997
                    foreach (self::COMPOSITE_SETTING_LOOKUP as $settingName => $rules) {
998
                        if (empty($metaBundle->metaGlobalVars->{$settingName})) {
999
                            $parentBundle = Seomatic::$plugin->metaBundles->getContentMetaBundleForElement($element);
1000
1001
                            foreach ($rules as $settingPath => $action) {
1002
                                list($container, $property) = explode('.', $settingPath);
1003
                                list($testValue, $sourceSetting) = explode('.', $action);
1004
1005
                                $bundleProp = $parentBundle->{$container}->{$property} ?? null;
1006
                                if ($bundleProp == $testValue) {
1007
                                    $metaBundle->metaGlobalVars->{$settingName} = $metaBundle->metaGlobalVars->{$sourceSetting};
1008
                                }
1009
                            }
1010
                        }
1011
                    }
1012
1013
                    // Handle re-creating the `mainEntityOfPage` so that the model injected into the
1014
                    // templates has the appropriate attributes
1015
                    $generalContainerKey = MetaJsonLdContainer::CONTAINER_TYPE . JsonLdService::GENERAL_HANDLE;
1016
                    $generalContainer = $this->metaContainers[$generalContainerKey];
1017
                    if (($generalContainer !== null) && !empty($generalContainer->data['mainEntityOfPage'])) {
1018
                        /** @var MetaJsonLd $jsonLdModel */
1019
                        $jsonLdModel = $generalContainer->data['mainEntityOfPage'];
1020
                        $config = $jsonLdModel->getAttributes();
1021
                        $schemaType = $metaBundle->metaGlobalVars->mainEntityOfPage ?? $config['type'] ?? null;
1022
                        // If the schemaType is '' we should fall back on whatever the mainEntityOfPage already is
1023
                        if (empty($schemaType)) {
1024
                            $schemaType = null;
1025
                        }
1026
                        if ($schemaType !== null) {
1027
                            $config['key'] = 'mainEntityOfPage';
1028
                            $schemaType = MetaValueHelper::parseString($schemaType);
1029
                            $generalContainer->data['mainEntityOfPage'] = MetaJsonLd::create($schemaType, $config);
1030
                        }
1031
                    }
1032
                    // Fire an 'metaBundleDebugData' event
1033
                    if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
1034
                        $event = new MetaBundleDebugDataEvent([
1035
                            'metaBundleCategory' => MetaBundleDebugDataEvent::FIELD_META_BUNDLE,
1036
                            'metaBundle' => $metaBundle,
1037
                        ]);
1038
                        $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
1039
                    }
1040
                    $this->addMetaBundleToContainers($metaBundle);
1041
                }
1042
            }
1043
        }
1044
        Craft::endProfile('MetaContainers::loadFieldMetaContainers', __METHOD__);
1045
    }
1046
1047
    /**
1048
     * Generate an md5 hash from an object or array
1049
     *
1050
     * @param string|array|MetaItem $data
1051
     *
1052
     * @return string
1053
     */
1054
    protected function getHash($data): string
1055
    {
1056
        if (is_object($data)) {
1057
            $data = $data->toArray();
1058
        }
1059
        if (is_array($data)) {
1060
            $data = serialize($data);
1061
        }
1062
1063
        return md5($data);
1064
    }
1065
1066
    // Private Methods
1067
    // =========================================================================
1068
}
1069