MetaContainers::setMatchedElement()   B
last analyzed

Complexity

Conditions 10
Paths 48

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 3
Bugs 2 Features 0
Metric Value
eloc 20
dl 0
loc 31
ccs 0
cts 20
cp 0
rs 7.6666
c 3
b 2
f 0
cc 10
nc 48
nop 2
crap 110

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * SEOmatic plugin for Craft CMS 3.x
4
 *
5
 * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful,
6
 * and flexible
7
 *
8
 * @link      https://nystudio107.com
9
 * @copyright Copyright (c) 2017 nystudio107
10
 */
11
12
namespace nystudio107\seomatic\services;
13
14
use Craft;
15
use craft\base\Component;
16
use craft\base\Element;
17
use craft\base\ElementInterface;
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
    const GLOBAL_METACONTAINER_CACHE_TAG = 'seomatic_metacontainer';
72
    const METACONTAINER_CACHE_TAG = 'seomatic_metacontainer_';
73
74
    const CACHE_KEY = 'seomatic_metacontainer_';
75
    const INVALID_RESPONSE_CACHE_KEY = 'seomatic_invalid_response';
76
    const GLOBALS_CACHE_KEY = 'parsed_globals_';
77
    const SCRIPTS_CACHE_KEY = 'body_scripts_';
78
79
    /** @var array Rules for replacement values on arbitrary empty values */
80
    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
    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
    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()
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 1
    }
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) {
0 ignored issues
show
introduced by
$element is of type craft\base\Element, thus it always evaluated to true.
Loading history...
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
     */
587 1
    public function addToMetaContainer(MetaItem $data, string $key)
588
    {
589
        /** @var MetaContainer $container */
590 1
        $container = $this->getMetaContainer($key);
591
592 1
        if ($container !== null) {
593
            $container->addData($data, $data->key);
594
        }
595 1
    }
596
597
    /**
598
     * @param string $key
599
     *
600
     * @return mixed|null
601
     */
602 1
    public function getMetaContainer(string $key)
603
    {
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
            );
610 1
            Craft::error($error, __METHOD__);
611
612 1
            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
                default:
651
                    break;
652
            }
653
            if ($className) {
654
                $container = $className::create();
655
                if ($container) {
656
                    $this->metaContainers[$key] = $container;
657
                }
658
            }
659
        }
660
661
        /** @var MetaContainer|null $container */
662
        return $container;
663
    }
664
665
    // Protected Methods
666
    // =========================================================================
667
668
    /**
669
     * Render the HTML of all MetaContainers of a specific $type
670
     *
671
     * @param string $type
672
     *
673
     * @return string
674
     */
675
    public function renderContainersByType(string $type): string
676
    {
677
        $html = '';
678
        // Special-case for requests for the FrontendTemplateContainer "container"
679
        if ($type === FrontendTemplateContainer::CONTAINER_TYPE) {
680
            $renderedTemplates = [];
681
            if (Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'] ?? false) {
682
                $frontendTemplateContainers = Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'];
683
                foreach ($frontendTemplateContainers as $name => $frontendTemplateContainer) {
684
                    if ($frontendTemplateContainer->include) {
685
                        $result = $frontendTemplateContainer->render([
686
                        ]);
687
                        $renderedTemplates[] = [$name => $result];
688
                    }
689
                }
690
            }
691
            $html .= Json::encode($renderedTemplates);
692
693
            return $html;
694
        }
695
        /** @var MetaContainer $metaContainer */
696
        foreach ($this->metaContainers as $metaContainer) {
697
            if ($metaContainer::CONTAINER_TYPE === $type && $metaContainer->include) {
698
                $result = $metaContainer->render([
699
                    'renderRaw' => true,
700
                    'renderScriptTags' => true,
701
                    'array' => true,
702
                ]);
703
                // Special case for script containers, because they can have body scripts too
704
                if ($metaContainer::CONTAINER_TYPE === MetaScriptContainer::CONTAINER_TYPE) {
705
                    $bodyScript = '';
706
                    /** @var MetaScriptContainer $metaContainer */
707
                    if ($metaContainer->prepForInclusion()) {
708
                        foreach ($metaContainer->data as $metaScript) {
709
                            /** @var MetaScript $metaScript */
710
                            if (!empty($metaScript->bodyTemplatePath)) {
711
                                $bodyScript .= $metaScript->renderBodyHtml();
712
                            }
713
                        }
714
                    }
715
716
                    $result = Json::encode([
717
                        'script' => $result,
718
                        'bodyScript' => $bodyScript,
719
                    ]);
720
                }
721
722
                $html .= $result;
723
            }
724
        }
725
        // Special-case for requests for the MetaSiteVars "container"
726
        if ($type === MetaSiteVars::CONTAINER_TYPE) {
727
            $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

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