MetaContainers::init()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
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
    public function init(): void
180
    {
181
        parent::init();
182
        // Get the page number of this request
183
        $request = Craft::$app->getRequest();
184
        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
                if ($sourceId !== null) {
480
                    $metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
481
                        $sourceType,
482
                        $sourceId,
483
                        $sourceSiteId,
484
                        $typeId
485
                    );
486
                }
487
            }
488
        }
489
        $this->matchedMetaBundle = $metaBundle;
490
491
        return $metaBundle;
492
    }
493
494
    /**
495
     * Load the global site meta containers
496
     *
497
     * @param int|null $siteId
498
     */
499
    public function loadGlobalMetaContainers(int $siteId = null)
500
    {
501
        Craft::beginProfile('MetaContainers::loadGlobalMetaContainers', __METHOD__);
502
        if ($siteId === null) {
503
            $siteId = Craft::$app->getSites()->currentSite->id ?? 1;
504
        }
505
        $metaBundle = Seomatic::$plugin->metaBundles->getGlobalMetaBundle($siteId);
506
        if ($metaBundle) {
507
            // Fire an 'metaBundleDebugData' event
508
            if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
509
                $event = new MetaBundleDebugDataEvent([
510
                    'metaBundleCategory' => MetaBundleDebugDataEvent::GLOBAL_META_BUNDLE,
511
                    'metaBundle' => $metaBundle,
512
                ]);
513
                $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
514
            }
515
            // Meta global vars
516
            $this->metaGlobalVars = clone $metaBundle->metaGlobalVars;
517
            // Meta site vars
518
            $this->metaSiteVars = clone $metaBundle->metaSiteVars;
519
            // Meta sitemap vars
520
            $this->metaSitemapVars = clone $metaBundle->metaSitemapVars;
521
            // Language
522
            $this->metaGlobalVars->language = Seomatic::$language;
523
            // Meta containers
524
            foreach ($metaBundle->metaContainers as $key => $metaContainer) {
525
                $this->metaContainers[$key] = clone $metaContainer;
526
            }
527
        }
528
        Craft::endProfile('MetaContainers::loadGlobalMetaContainers', __METHOD__);
529
    }
530
531
    /**
532
     * Add the meta bundle to our existing meta containers, overwriting meta
533
     * items with the same key
534
     *
535
     * @param MetaBundle $metaBundle
536
     */
537
    public function addMetaBundleToContainers(MetaBundle $metaBundle)
538
    {
539
        // Ensure the variable is synced properly first
540
        Seomatic::$seomaticVariable->init();
541
        // Meta global vars
542
        $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

542
        /** @scrutinizer ignore-call */ 
543
        $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...
543
        // Parse the meta values so we can filter out any blank or empty attributes
544
        // So that they can fall back on the parent container
545
        $parsedAttributes = $attributes;
546
        MetaValueHelper::parseArray($parsedAttributes);
547
        $parsedAttributes = array_filter(
548
            $parsedAttributes,
549
            [ArrayHelper::class, 'preserveBools']
550
        );
551
        $attributes = array_intersect_key($attributes, $parsedAttributes);
552
        // Add the attributes in
553
        $attributes = array_filter(
554
            $attributes,
555
            [ArrayHelper::class, 'preserveBools']
556
        );
557
        $this->metaGlobalVars->setAttributes($attributes, false);
558
        // Meta site vars
559
        /*
560
         * Don't merge in the Site vars, since they are only editable on
561
         * a global basis. Otherwise stale data will be unable to be edited
562
        $attributes = $metaBundle->metaSiteVars->getAttributes();
563
        $attributes = array_filter($attributes);
564
        $this->metaSiteVars->setAttributes($attributes, false);
565
        */
566
        // Meta sitemap vars
567
        $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

567
        /** @scrutinizer ignore-call */ 
568
        $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...
568
        $attributes = array_filter(
569
            $attributes,
570
            [ArrayHelper::class, 'preserveBools']
571
        );
572
        $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

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

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