Passed
Push — v3 ( afe9d2...5d62d2 )
by Andrew
37:44 queued 22:13
created

MetaContainers::getMetaContainer()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3.0123

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 2
nop 1
dl 0
loc 14
ccs 8
cts 9
cp 0.8889
crap 3.0123
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * SEOmatic plugin for Craft CMS 3.x
4
 *
5
 * A turnkey SEO implementation for Craft CMS that is comprehensive, powerful,
6
 * and flexible
7
 *
8
 * @link      https://nystudio107.com
9
 * @copyright Copyright (c) 2017 nystudio107
10
 */
11
12
namespace nystudio107\seomatic\services;
13
14
use Craft;
15
use craft\base\Component;
16
use craft\base\Element;
17
use craft\commerce\Plugin as CommercePlugin;
0 ignored issues
show
Bug introduced by
The type craft\commerce\Plugin 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\console\Application as ConsoleApplication;
19
use craft\elements\GlobalSet;
20
use nystudio107\seomatic\base\MetaContainer;
21
use nystudio107\seomatic\base\MetaItem;
22
use nystudio107\seomatic\events\InvalidateContainerCachesEvent;
23
use nystudio107\seomatic\events\MetaBundleDebugDataEvent;
24
use nystudio107\seomatic\helpers\ArrayHelper;
25
use nystudio107\seomatic\helpers\DynamicMeta as DynamicMetaHelper;
26
use nystudio107\seomatic\helpers\Field as FieldHelper;
27
use nystudio107\seomatic\helpers\Json;
28
use nystudio107\seomatic\helpers\Localization as LocalizationHelper;
29
use nystudio107\seomatic\helpers\MetaValue as MetaValueHelper;
30
use nystudio107\seomatic\helpers\UrlHelper;
31
use nystudio107\seomatic\models\FrontendTemplateContainer;
32
use nystudio107\seomatic\models\MetaBundle;
33
use nystudio107\seomatic\models\MetaGlobalVars;
34
use nystudio107\seomatic\models\MetaJsonLd;
35
use nystudio107\seomatic\models\MetaJsonLdContainer;
36
use nystudio107\seomatic\models\MetaLinkContainer;
37
use nystudio107\seomatic\models\MetaScript;
38
use nystudio107\seomatic\models\MetaScriptContainer;
39
use nystudio107\seomatic\models\MetaSitemapVars;
40
use nystudio107\seomatic\models\MetaSiteVars;
41
use nystudio107\seomatic\models\MetaTagContainer;
42
use nystudio107\seomatic\models\MetaTitleContainer;
43
use nystudio107\seomatic\seoelements\SeoProduct;
44
use nystudio107\seomatic\Seomatic;
45
use nystudio107\seomatic\services\JsonLd as JsonLdService;
46
use nystudio107\seomatic\variables\SeomaticVariable;
47
use yii\base\Exception;
48
use yii\base\InvalidConfigException;
49
use yii\caching\TagDependency;
50
use function is_array;
51
use function is_object;
52
53
/**
54
 * Meta container functions for SEOmatic
55
 * An instance of the service is available via [[`Seomatic::$plugin->metaContainers`|`seomatic.containers`]]
56
 *
57
 * @author    nystudio107
58
 * @package   Seomatic
59
 * @since     3.0.0
60
 */
61
class MetaContainers extends Component
62
{
63
    // Constants
64
    // =========================================================================
65
66
    const GLOBAL_METACONTAINER_CACHE_TAG = 'seomatic_metacontainer';
67
    const METACONTAINER_CACHE_TAG = 'seomatic_metacontainer_';
68
69
    const CACHE_KEY = 'seomatic_metacontainer_';
70
    const INVALID_RESPONSE_CACHE_KEY = 'seomatic_invalid_response';
71
    const GLOBALS_CACHE_KEY = 'parsed_globals_';
72
    const SCRIPTS_CACHE_KEY = 'body_scripts_';
73
74
    /** @var array Rules for replacement values on arbitrary empty values */
75
    const COMPOSITE_SETTING_LOOKUP = [
76
        'ogImage' => [
77
            'metaBundleSettings.ogImageSource' => 'sameAsSeo.seoImage',
78
        ],
79
        'twitterImage' => [
80
            'metaBundleSettings.twitterImageSource' => 'sameAsSeo.seoImage',
81
        ],
82
    ];
83
84
    /**
85
     * @event InvalidateContainerCachesEvent The event that is triggered when SEOmatic
86
     *        is about to clear its meta container caches
87
     *
88
     * ---
89
     * ```php
90
     * use nystudio107\seomatic\events\InvalidateContainerCachesEvent;
91
     * use nystudio107\seomatic\services\MetaContainers;
92
     * use yii\base\Event;
93
     * Event::on(MetaContainers::class, MetaContainers::EVENT_INVALIDATE_CONTAINER_CACHES, function(InvalidateContainerCachesEvent $e) {
94
     *     // Container caches are about to be cleared
95
     * });
96
     * ```
97
     */
98
    const EVENT_INVALIDATE_CONTAINER_CACHES = 'invalidateContainerCaches';
99
100
    /**
101
     * @event MetaBundleDebugDataEvent The event that is triggered to record MetaBundle
102
     * debug data
103
     *
104
     * ---
105
     * ```php
106
     * use nystudio107\seomatic\events\MetaBundleDebugDataEvent;
107
     * use nystudio107\seomatic\services\MetaContainers;
108
     * use yii\base\Event;
109
     * Event::on(MetaContainers::class, MetaContainers::EVENT_METABUNDLE_DEBUG_DATA, function(MetaBundleDebugDataEvent $e) {
110
     *     // Do something with the MetaBundle debug data
111
     * });
112
     * ```
113
     */
114
    const EVENT_METABUNDLE_DEBUG_DATA = 'metaBundleDebugData';
115
116
    // Public Properties
117
    // =========================================================================
118
119
    /**
120
     * @var MetaGlobalVars
121
     */
122
    public $metaGlobalVars;
123
124
    /**
125
     * @var MetaSiteVars
126
     */
127
    public $metaSiteVars;
128
129
    /**
130
     * @var MetaSitemapVars
131
     */
132
    public $metaSitemapVars;
133
134
    /**
135
     * @var string The current page number of paginated pages
136
     */
137
    public $paginationPage = '1';
138
139
    /**
140
     * @var null|string Cached nonce to be shared by all JSON-LD entities
141
     */
142
    public $cachedJsonLdNonce;
143
144
    /**
145
     * @var MetaContainer
146
     */
147
    public $metaContainers = [];
148
149
    // Protected Properties
150
    // =========================================================================
151
152
    /**
153
     * @var null|MetaBundle
154
     */
155
    protected $matchedMetaBundle;
156
157
    /**
158
     * @var null|TagDependency
159
     */
160
    protected $containerDependency;
161
162
    /**
163
     * @var bool Whether or not the matched element should be included in the
164
     *      meta containers
165
     */
166
    protected $includeMatchedElement = true;
167
168
    // Public Methods
169
    // =========================================================================
170
171
    /**
172
     * @inheritdoc
173
     */
174 1
    public function init()
175
    {
176 1
        parent::init();
177
        // Get the page number of this request
178 1
        $request = Craft::$app->getRequest();
179 1
        if (!$request->isConsoleRequest) {
180
            $this->paginationPage = (string)$request->pageNum;
181
        }
182 1
    }
183
184
    /**
185
     * Return the containers of a specific type
186
     *
187
     * @param string $type
188
     *
189
     * @return array
190
     */
191
    public function getContainersOfType(string $type): array
192
    {
193
        $containers = [];
194
        /** @var  $metaContainer MetaContainer */
195
        foreach ($this->metaContainers as $metaContainer) {
196
            if ($metaContainer::CONTAINER_TYPE === $type) {
197
                $containers[] = $metaContainer;
198
            }
199
        }
200
201
        return $containers;
202
    }
203
204
    /**
205
     * Include the meta containers
206
     */
207
    public function includeMetaContainers()
208
    {
209
        Craft::beginProfile('MetaContainers::includeMetaContainers', __METHOD__);
210
        // If this page is paginated, we need to factor that into the cache key
211
        // We also need to re-add the hreflangs
212
        if ($this->paginationPage !== '1') {
213
            if (Seomatic::$settings->addHrefLang && Seomatic::$settings->addPaginatedHreflang) {
214
                DynamicMetaHelper::addMetaLinkHrefLang();
215
            }
216
        }
217
        // Fire an 'metaBundleDebugData' event
218
        if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
219
            $metaBundle = new MetaBundle([
220
                'metaGlobalVars' => clone $this->metaGlobalVars,
221
                'metaSiteVars' => clone $this->metaSiteVars,
222
                'metaSitemapVars' => clone $this->metaSitemapVars,
223
                'metaContainers' => $this->metaContainers,
224
            ]);
225
            $event = new MetaBundleDebugDataEvent([
226
                'metaBundleCategory' => MetaBundleDebugDataEvent::COMBINED_META_BUNDLE,
227
                'metaBundle' => $metaBundle,
228
            ]);
229
            $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
230
        }
231
        // Add in our http headers
232
        DynamicMetaHelper::includeHttpHeaders();
233
        DynamicMetaHelper::addCspTags();
234
        $this->parseGlobalVars();
235
        foreach ($this->metaContainers as $metaContainer) {
236
            /** @var $metaContainer MetaContainer */
237
            if ($metaContainer->include) {
238
                // Don't cache the rendered result if we're previewing meta containers
239
                if (Seomatic::$previewingMetaContainers) {
240
                    $metaContainer->clearCache = true;
241
                }
242
                $metaContainer->includeMetaData($this->containerDependency);
243
            }
244
        }
245
        Craft::endProfile('MetaContainers::includeMetaContainers', __METHOD__);
246
    }
247
248
    /**
249
     * Parse the global variables
250
     */
251
    public function parseGlobalVars()
252
    {
253
        $dependency = $this->containerDependency;
254
        $uniqueKey = $dependency->tags[3] ?? self::GLOBALS_CACHE_KEY;
255
        list($this->metaGlobalVars, $this->metaSiteVars) = Craft::$app->getCache()->getOrSet(
256
            self::GLOBALS_CACHE_KEY . $uniqueKey,
257
            function () use ($uniqueKey) {
258
                Craft::info(
259
                    self::GLOBALS_CACHE_KEY . ' cache miss: ' . $uniqueKey,
260
                    __METHOD__
261
                );
262
263
                if ($this->metaGlobalVars) {
264
                    $this->metaGlobalVars->parseProperties();
265
                }
266
                if ($this->metaSiteVars) {
267
                    $this->metaSiteVars->parseProperties();
268
                }
269
270
                return [$this->metaGlobalVars, $this->metaSiteVars];
271
            },
272
            Seomatic::$cacheDuration,
273
            $dependency
274
        );
275
    }
276
277
    /**
278
     * Prep all of the meta for preview purposes
279
     *
280
     * @param string $uri
281
     * @param int|null $siteId
282
     * @param bool $parseVariables Whether or not the variables should be
283
     *                                 parsed as Twig
284
     * @param bool $includeElement Whether or not the matched element
285
     *                                 should be factored into the preview
286
     */
287
    public function previewMetaContainers(
288
        string $uri = '',
289
        int    $siteId = null,
290
        bool   $parseVariables = false,
291
        bool   $includeElement = true
292
    )
293
    {
294
        // If we've already previewed the containers for this request, there's no need to do it again
295
        if (Seomatic::$previewingMetaContainers && !Seomatic::$headlessRequest) {
296
            return;
297
        }
298
        // It's possible this won't exist at this point
299
        if (!Seomatic::$seomaticVariable) {
300
            // Create our variable and stash it in the plugin for global access
301
            Seomatic::$seomaticVariable = new SeomaticVariable();
302
        }
303
        Seomatic::$previewingMetaContainers = true;
304
        $this->includeMatchedElement = $includeElement;
305
        $this->loadMetaContainers($uri, $siteId);
306
        // Load in the right globals
307
        $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...
308
        $globalSets = GlobalSet::findAll([
309
            'siteId' => $siteId,
310
        ]);
311
        foreach ($globalSets as $globalSet) {
312
            MetaValueHelper::$templatePreviewVars[$globalSet->handle] = $globalSet;
313
        }
314
        // Parse the global vars
315
        if ($parseVariables) {
316
            $this->parseGlobalVars();
317
        }
318
        // Get the homeUrl and canonicalUrl
319
        $homeUrl = '/';
320
        $canonicalUrl = $this->metaGlobalVars->parsedValue('canonicalUrl');
321
        $canonicalUrl = DynamicMetaHelper::sanitizeUrl($canonicalUrl, false);
322
        // Special-case the global bundle
323
        if ($uri === MetaBundles::GLOBAL_META_BUNDLE || $uri === '__home__') {
324
            $canonicalUrl = '/';
325
        }
326
        try {
327
            $homeUrl = UrlHelper::siteUrl($homeUrl, null, null, $siteId);
328
            $canonicalUrl = UrlHelper::siteUrl($canonicalUrl, null, null, $siteId);
329
        } catch (Exception $e) {
330
            Craft::error($e->getMessage(), __METHOD__);
331
        }
332
        $canonical = Seomatic::$seomaticVariable->link->get('canonical');
333
        if ($canonical !== null) {
334
            $canonical->href = $canonicalUrl;
335
        }
336
        $home = Seomatic::$seomaticVariable->link->get('home');
337
        if ($home !== null) {
338
            $home->href = $homeUrl;
339
        }
340
        // The current language may _not_ match the current site, if we're headless
341
        $ogLocale = Seomatic::$seomaticVariable->tag->get('og:locale');
342
        if ($ogLocale !== null && $siteId !== null) {
343
            $site = Craft::$app->getSites()->getSiteById($siteId);
344
            if ($site !== null) {
345
                $ogLocale->content = LocalizationHelper::normalizeOgLocaleLanguage($site->language);
346
            }
347
        }
348
        // Update seomatic.meta.canonicalUrl when previewing meta containers
349
        $this->metaGlobalVars->canonicalUrl = $canonicalUrl;
350
    }
351
352
    /**
353
     * Load the meta containers
354
     *
355
     * @param string|null $uri
356
     * @param int|null $siteId
357
     */
358
    public function loadMetaContainers(string $uri = '', int $siteId = null)
359
    {
360
        Craft::beginProfile('MetaContainers::loadMetaContainers', __METHOD__);
361
        // Avoid recursion
362
        if (!Seomatic::$loadingMetaContainers) {
363
            Seomatic::$loadingMetaContainers = true;
364
            $this->setMatchedElement($uri, $siteId);
365
            // Get the cache tag for the matched meta bundle
366
            $metaBundle = $this->getMatchedMetaBundle();
367
            $metaBundleSourceId = '';
368
            $metaBundleSourceType = '';
369
            if ($metaBundle) {
370
                $metaBundleSourceId = $metaBundle->sourceId;
371
                $metaBundleSourceType = $metaBundle->sourceBundleType;
372
            }
373
            // We need an actual $siteId here for the cache key
374
            if ($siteId === null) {
375
                $siteId = Craft::$app->getSites()->currentSite->id
376
                    ?? Craft::$app->getSites()->primarySite->id
377
                    ?? 1;
378
            }
379
            // Handle pagination
380
            $paginationPage = 'page' . $this->paginationPage;
381
            // Get the path for the current request
382
            $request = Craft::$app->getRequest();
383
            $requestPath = '/';
384
            if (!$request->getIsConsoleRequest()) {
385
                try {
386
                    $requestPath = $request->getPathInfo();
387
                } catch (InvalidConfigException $e) {
388
                    Craft::error($e->getMessage(), __METHOD__);
389
                }
390
                // If this is any type of a preview, ensure that it's not cached
391
                if (Seomatic::$plugin->helper::isPreview()) {
392
                    Seomatic::$previewingMetaContainers = true;
393
                }
394
            }
395
            // Get our cache key
396
            $cacheKey = $uri . $siteId . $paginationPage . $requestPath . $this->getAllowedUrlParams();
397
            // For requests with a status code of >= 400, use one cache key
398
            if (!$request->isConsoleRequest) {
399
                $response = Craft::$app->getResponse();
400
                if ($response->statusCode >= 400) {
401
                    $cacheKey = $siteId . self::INVALID_RESPONSE_CACHE_KEY . $response->statusCode;
402
                }
403
            }
404
            // Load the meta containers
405
            $dependency = new TagDependency([
406
                'tags' => [
407
                    self::GLOBAL_METACONTAINER_CACHE_TAG,
408
                    self::METACONTAINER_CACHE_TAG . $metaBundleSourceId . $metaBundleSourceType . $siteId,
409
                    self::METACONTAINER_CACHE_TAG . $uri . $siteId,
410
                    self::METACONTAINER_CACHE_TAG . $cacheKey,
411
                ],
412
            ]);
413
            $this->containerDependency = $dependency;
414
            $debugModule = Craft::$app->getModule('debug');
415
            if (Seomatic::$previewingMetaContainers || $debugModule) {
416
                Seomatic::$plugin->frontendTemplates->loadFrontendTemplateContainers($siteId);
417
                $this->loadGlobalMetaContainers($siteId);
418
                $this->loadContentMetaContainers();
419
                $this->loadFieldMetaContainers();
420
                // We only need the dynamic data for headless requests
421
                if (Seomatic::$headlessRequest || Seomatic::$plugin->helper::isPreview() || $debugModule) {
422
                    DynamicMetaHelper::addDynamicMetaToContainers($uri, $siteId);
423
                }
424
            } else {
425
                $cache = Craft::$app->getCache();
426
                list($this->metaGlobalVars, $this->metaSiteVars, $this->metaSitemapVars, $this->metaContainers) = $cache->getOrSet(
427
                    self::CACHE_KEY . $cacheKey,
428
                    function () use ($uri, $siteId) {
429
                        Craft::info(
430
                            'Meta container cache miss: ' . $uri . '/' . $siteId,
431
                            __METHOD__
432
                        );
433
                        $this->loadGlobalMetaContainers($siteId);
434
                        $this->loadContentMetaContainers();
435
                        $this->loadFieldMetaContainers();
436
                        DynamicMetaHelper::addDynamicMetaToContainers($uri, $siteId);
437
438
                        return [$this->metaGlobalVars, $this->metaSiteVars, $this->metaSitemapVars, $this->metaContainers];
439
                    },
440
                    Seomatic::$cacheDuration,
441
                    $dependency
442
                );
443
            }
444
            Seomatic::$seomaticVariable->init();
445
            MetaValueHelper::cache();
446
            Seomatic::$loadingMetaContainers = false;
447
        }
448
        Craft::endProfile('MetaContainers::loadMetaContainers', __METHOD__);
449
    }
450
451
    /**
452
     * Set the element that matches the $uri
453
     *
454
     * @param string $uri
455
     * @param int|null $siteId
456
     */
457
    protected function setMatchedElement(string $uri, int $siteId = null)
458
    {
459
        if ($siteId === null) {
460
            $siteId = Craft::$app->getSites()->currentSite->id
461
                ?? Craft::$app->getSites()->primarySite->id
462
                ?? 1;
463
        }
464
        $element = null;
465
        $uri = trim($uri, '/');
466
        /** @var Element $element */
467
        $enabledOnly = !Seomatic::$previewingMetaContainers;
468
        // Try to use Craft's matched element if looking for an enabled element, the current `siteId` is being used and
469
        // the current `uri` matches what was in the request
470
        if ($enabledOnly
471
            && $siteId === Craft::$app->getSites()->currentSite->id
472
            && Craft::$app->getRequest()->getPathInfo() === $uri) {
473
            $element = Craft::$app->getUrlManager()->getMatchedElement();
474
        }
475
        if (!$element) {
476
            $element = Craft::$app->getElements()->getElementByUri($uri, $siteId, $enabledOnly);
477
        }
478
        if ($element && ($element->uri !== null)) {
479
            Seomatic::setMatchedElement($element);
480
        }
481
    }
482
483
    /**
484
     * Return the MetaBundle that corresponds with the Seomatic::$matchedElement
485
     *
486
     * @return null|MetaBundle
487
     */
488
    public function getMatchedMetaBundle()
489
    {
490
        $metaBundle = null;
491
        /** @var Element $element */
492
        $element = Seomatic::$matchedElement;
493
        if ($element) {
0 ignored issues
show
introduced by
$element is of type craft\base\Element, thus it always evaluated to true.
Loading history...
494
            $sourceType = Seomatic::$plugin->seoElements->getMetaBundleTypeFromElement($element);
495
            if ($sourceType) {
496
                list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId)
497
                    = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element);
498
                $metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
499
                    $sourceType,
500
                    $sourceId,
501
                    $sourceSiteId,
502
                    $typeId
503
                );
504
            }
505
        }
506
        $this->matchedMetaBundle = $metaBundle;
507
508
        return $metaBundle;
509
    }
510
511
    /**
512
     * Return as key/value pairs any allowed parameters in the request
513
     *
514
     * @return string
515
     */
516
    protected function getAllowedUrlParams(): string
517
    {
518
        $result = '';
519
        $allowedParams = Seomatic::$settings->allowedUrlParams;
520
        if (Craft::$app->getPlugins()->getPlugin(SeoProduct::REQUIRED_PLUGIN_HANDLE)) {
521
            $commerce = CommercePlugin::getInstance();
522
            if ($commerce !== null) {
523
                $allowedParams[] = 'variant';
524
            }
525
        }
526
        // Iterate through the allowed parameters, adding the key/value pair to the $result string as found
527
        $request = Craft::$app->getRequest();
528
        if (!$request->isConsoleRequest) {
529
            foreach ($allowedParams as $allowedParam) {
530
                $value = $request->getParam($allowedParam);
531
                if ($value !== null) {
532
                    $result .= "{$allowedParam}={$value}";
533
                }
534
            }
535
        }
536
537
        return $result;
538
    }
539
540
    /**
541
     * Load the global site meta containers
542
     *
543
     * @param int|null $siteId
544
     */
545
    public function loadGlobalMetaContainers(int $siteId = null)
546
    {
547
        Craft::beginProfile('MetaContainers::loadGlobalMetaContainers', __METHOD__);
548
        if ($siteId === null) {
549
            $siteId = Craft::$app->getSites()->currentSite->id ?? 1;
550
        }
551
        $metaBundle = Seomatic::$plugin->metaBundles->getGlobalMetaBundle($siteId);
552
        if ($metaBundle) {
553
            // Fire an 'metaBundleDebugData' event
554
            if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
555
                $event = new MetaBundleDebugDataEvent([
556
                    'metaBundleCategory' => MetaBundleDebugDataEvent::GLOBAL_META_BUNDLE,
557
                    'metaBundle' => $metaBundle,
558
                ]);
559
                $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
560
            }
561
            // Meta global vars
562
            $this->metaGlobalVars = clone $metaBundle->metaGlobalVars;
563
            // Meta site vars
564
            $this->metaSiteVars = clone $metaBundle->metaSiteVars;
565
            // Meta sitemap vars
566
            $this->metaSitemapVars = clone $metaBundle->metaSitemapVars;
567
            // Language
568
            $this->metaGlobalVars->language = Seomatic::$language;
569
            // Meta containers
570
            foreach ($metaBundle->metaContainers as $key => $metaContainer) {
571
                $this->metaContainers[$key] = clone $metaContainer;
572
            }
573
        }
574
        Craft::endProfile('MetaContainers::loadGlobalMetaContainers', __METHOD__);
575
    }
576
577
    /**
578
     * Load the meta containers specific to the matched meta bundle
579
     */
580
    protected function loadContentMetaContainers()
581
    {
582
        Craft::beginProfile('MetaContainers::loadContentMetaContainers', __METHOD__);
583
        $metaBundle = $this->getMatchedMetaBundle();
584
        if ($metaBundle) {
585
            // Fire an 'metaBundleDebugData' event
586
            if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
587
                $event = new MetaBundleDebugDataEvent([
588
                    'metaBundleCategory' => MetaBundleDebugDataEvent::CONTENT_META_BUNDLE,
589
                    'metaBundle' => $metaBundle,
590
                ]);
591
                $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
592
            }
593
            $this->addMetaBundleToContainers($metaBundle);
594
        }
595
        Craft::endProfile('MetaContainers::loadContentMetaContainers', __METHOD__);
596
    }
597
598
    /**
599
     * Add the meta bundle to our existing meta containers, overwriting meta
600
     * items with the same key
601
     *
602
     * @param MetaBundle $metaBundle
603
     */
604
    public function addMetaBundleToContainers(MetaBundle $metaBundle)
605
    {
606
        // Ensure the variable is synced properly first
607
        Seomatic::$seomaticVariable->init();
608
        // Meta global vars
609
        $attributes = $metaBundle->metaGlobalVars->getAttributes();
610
        // Parse the meta values so we can filter out any blank or empty attributes
611
        // So that they can fall back on the parent container
612
        $parsedAttributes = $attributes;
613
        MetaValueHelper::parseArray($parsedAttributes);
614
        $parsedAttributes = array_filter(
615
            $parsedAttributes,
616
            [ArrayHelper::class, 'preserveBools']
617
        );
618
        $attributes = array_intersect_key($attributes, $parsedAttributes);
619
        // Add the attributes in
620
        $attributes = array_filter(
621
            $attributes,
622
            [ArrayHelper::class, 'preserveBools']
623
        );
624
        $this->metaGlobalVars->setAttributes($attributes, false);
625
        // Meta site vars
626
        /*
627
         * Don't merge in the Site vars, since they are only editable on
628
         * a global basis. Otherwise stale data will be unable to be edited
629
        $attributes = $metaBundle->metaSiteVars->getAttributes();
630
        $attributes = array_filter($attributes);
631
        $this->metaSiteVars->setAttributes($attributes, false);
632
        */
633
        // Meta sitemap vars
634
        $attributes = $metaBundle->metaSitemapVars->getAttributes();
635
        $attributes = array_filter(
636
            $attributes,
637
            [ArrayHelper::class, 'preserveBools']
638
        );
639
        $this->metaSitemapVars->setAttributes($attributes, false);
640
        // Language
641
        $this->metaGlobalVars->language = Seomatic::$language;
642
        // Meta containers
643
        foreach ($metaBundle->metaContainers as $key => $metaContainer) {
644
            foreach ($metaContainer->data as $metaTag) {
645
                $this->addToMetaContainer($metaTag, $key);
646
            }
647
        }
648
    }
649
650
    // Protected Methods
651
    // =========================================================================
652
653
    /**
654
     * Add the passed in MetaItem to the MetaContainer indexed as $key
655
     *
656
     * @param $data MetaItem The MetaItem to add to the container
657
     * @param $key  string   The key to the container to add the data to
658
     */
659 1
    public function addToMetaContainer(MetaItem $data, string $key)
660
    {
661
        /** @var  $container MetaContainer */
662 1
        $container = $this->getMetaContainer($key);
663
664 1
        if ($container !== null) {
665
            $container->addData($data, $data->key);
666
        }
667 1
    }
668
669
    /**
670
     * @param string $key
671
     *
672
     * @return mixed|null
673
     */
674 1
    public function getMetaContainer(string $key)
675
    {
676 1
        if (!$key || empty($this->metaContainers[$key])) {
677 1
            $error = Craft::t(
678 1
                'seomatic',
679 1
                'Meta container with key `{key}` does not exist.',
680 1
                ['key' => $key]
681
            );
682 1
            Craft::error($error, __METHOD__);
683
684 1
            return null;
685
        }
686
687
        return $this->metaContainers[$key];
688
    }
689
690
    /**
691
     * Load any meta containers in the current element
692
     */
693
    protected function loadFieldMetaContainers()
694
    {
695
        Craft::beginProfile('MetaContainers::loadFieldMetaContainers', __METHOD__);
696
        $element = Seomatic::$matchedElement;
697
        if ($element && $this->includeMatchedElement) {
698
            /** @var Element $element */
699
            $fieldHandles = FieldHelper::fieldsOfTypeFromElement($element, FieldHelper::SEO_SETTINGS_CLASS_KEY, true);
700
            foreach ($fieldHandles as $fieldHandle) {
701
                if (!empty($element->$fieldHandle)) {
702
                    /** @var MetaBundle $metaBundle */
703
                    $metaBundle = $element->$fieldHandle;
704
                    Seomatic::$plugin->metaBundles->pruneFieldMetaBundleSettings($metaBundle, $fieldHandle);
705
706
                    // See which properties have to be overridden, because the parent bundle says so.
707
                    foreach (self::COMPOSITE_SETTING_LOOKUP as $settingName => $rules) {
708
                        if (empty($metaBundle->metaGlobalVars->{$settingName})) {
709
                            $parentBundle = Seomatic::$plugin->metaBundles->getContentMetaBundleForElement($element);
710
711
                            foreach ($rules as $settingPath => $action) {
712
                                list ($container, $property) = explode('.', $settingPath);
713
                                list ($testValue, $sourceSetting) = explode('.', $action);
714
715
                                $bundleProp = $parentBundle->{$container}->{$property} ?? null;
716
                                if ($bundleProp == $testValue) {
717
                                    $metaBundle->metaGlobalVars->{$settingName} = $metaBundle->metaGlobalVars->{$sourceSetting};
718
                                }
719
                            }
720
                        }
721
                    }
722
723
                    // Handle re-creating the `mainEntityOfPage` so that the model injected into the
724
                    // templates has the appropriate attributes
725
                    $generalContainerKey = MetaJsonLdContainer::CONTAINER_TYPE . JsonLdService::GENERAL_HANDLE;
726
                    $generalContainer = $this->metaContainers[$generalContainerKey];
727
                    if (($generalContainer !== null) && !empty($generalContainer->data['mainEntityOfPage'])) {
728
                        /** @var MetaJsonLd $jsonLdModel */
729
                        $jsonLdModel = $generalContainer->data['mainEntityOfPage'];
730
                        $config = $jsonLdModel->getAttributes();
731
                        $schemaType = $metaBundle->metaGlobalVars->mainEntityOfPage ?? $config['type'] ?? null;
732
                        // If the schemaType is '' we should fall back on whatever the mainEntityOfPage already is
733
                        if (empty($schemaType)) {
734
                            $schemaType = null;
735
                        }
736
                        if ($schemaType !== null) {
737
                            $config['key'] = 'mainEntityOfPage';
738
                            $schemaType = MetaValueHelper::parseString($schemaType);
739
                            $generalContainer->data['mainEntityOfPage'] = MetaJsonLd::create($schemaType, $config);
740
                        }
741
                    }
742
                    // Fire an 'metaBundleDebugData' event
743
                    if ($this->hasEventHandlers(self::EVENT_METABUNDLE_DEBUG_DATA)) {
744
                        $event = new MetaBundleDebugDataEvent([
745
                            'metaBundleCategory' => MetaBundleDebugDataEvent::FIELD_META_BUNDLE,
746
                            'metaBundle' => $metaBundle,
747
                        ]);
748
                        $this->trigger(self::EVENT_METABUNDLE_DEBUG_DATA, $event);
749
                    }
750
                    $this->addMetaBundleToContainers($metaBundle);
751
                }
752
            }
753
        }
754
        Craft::endProfile('MetaContainers::loadFieldMetaContainers', __METHOD__);
755
    }
756
757
    /**
758
     * Create a MetaContainer of the given $type with the $key
759
     *
760
     * @param string $type
761
     * @param string $key
762
     *
763
     * @return null|MetaContainer
764
     */
765
    public function createMetaContainer(string $type, string $key): MetaContainer
766
    {
767
        /** @var MetaContainer $container */
768
        $container = null;
769
        if (empty($this->metaContainers[$key])) {
770
            /** @var MetaContainer $className */
771
            $className = null;
772
            // Create a new container based on the type passed in
773
            switch ($type) {
774
                case MetaTagContainer::CONTAINER_TYPE:
775
                    $className = MetaTagContainer::class;
776
                    break;
777
                case MetaLinkContainer::CONTAINER_TYPE:
778
                    $className = MetaLinkContainer::class;
779
                    break;
780
                case MetaScriptContainer::CONTAINER_TYPE:
781
                    $className = MetaScriptContainer::class;
782
                    break;
783
                case MetaJsonLdContainer::CONTAINER_TYPE:
784
                    $className = MetaJsonLdContainer::class;
785
                    break;
786
                case MetaTitleContainer::CONTAINER_TYPE:
787
                    $className = MetaTitleContainer::class;
788
                    break;
789
            }
790
            if ($className) {
791
                $container = $className::create();
792
                if ($container) {
0 ignored issues
show
introduced by
$container is of type nystudio107\seomatic\base\Container, thus it always evaluated to true.
Loading history...
793
                    $this->metaContainers[$key] = $container;
794
                }
795
            }
796
        }
797
798
        /** @var MetaContainer $className */
799
        return $container;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $container could return the type nystudio107\seomatic\base\Container which includes types incompatible with the type-hinted return nystudio107\seomatic\base\MetaContainer. Consider adding an additional type-check to rule them out.
Loading history...
800
    }
801
802
    /**
803
     * Render the HTML of all MetaContainers of a specific $type
804
     *
805
     * @param string $type
806
     *
807
     * @return string
808
     */
809
    public function renderContainersByType(string $type): string
810
    {
811
        $html = '';
812
        // Special-case for requests for the FrontendTemplateContainer "container"
813
        if ($type === FrontendTemplateContainer::CONTAINER_TYPE) {
814
            $renderedTemplates = [];
815
            if (Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'] ?? false) {
816
                $frontendTemplateContainers = Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'];
817
                foreach ($frontendTemplateContainers as $name => $frontendTemplateContainer) {
818
                    if ($frontendTemplateContainer->include) {
819
                        $result = $frontendTemplateContainer->render([
820
                        ]);
821
                        $renderedTemplates[] = [$name => $result];
822
                    }
823
                }
824
            }
825
            $html .= Json::encode($renderedTemplates);
826
827
            return $html;
828
        }
829
        /** @var  $metaContainer MetaContainer */
830
        foreach ($this->metaContainers as $metaContainer) {
831
            if ($metaContainer::CONTAINER_TYPE === $type && $metaContainer->include) {
832
                $result = $metaContainer->render([
833
                    'renderRaw' => true,
834
                    'renderScriptTags' => true,
835
                    'array' => true,
836
                ]);
837
                // Special case for script containers, because they can have body scripts too
838
                if ($metaContainer::CONTAINER_TYPE === MetaScriptContainer::CONTAINER_TYPE) {
839
                    $bodyScript = '';
840
                    /** @var MetaScriptContainer $metaContainer */
841
                    if ($metaContainer->prepForInclusion()) {
842
                        foreach ($metaContainer->data as $metaScript) {
843
                            /** @var MetaScript $metaScript */
844
                            if (!empty($metaScript->bodyTemplatePath)) {
845
                                $bodyScript .= $metaScript->renderBodyHtml();
846
                            }
847
                        }
848
                    }
849
850
                    $result = Json::encode([
851
                        'script' => $result,
852
                        'bodyScript' => $bodyScript,
853
                    ]);
854
                }
855
856
                $html .= $result;
857
            }
858
        }
859
        // Special-case for requests for the MetaSiteVars "container"
860
        if ($type === MetaSiteVars::CONTAINER_TYPE) {
861
            $result = Json::encode($this->metaSiteVars->toArray());
862
            $html .= $result;
863
        }
864
865
        return $html;
866
    }
867
868
    /**
869
     * Render the HTML of all MetaContainers of a specific $type as an array
870
     *
871
     * @param string $type
872
     *
873
     * @return array
874
     */
875
    public function renderContainersArrayByType(string $type): array
876
    {
877
        $htmlArray = [];
878
        // Special-case for requests for the FrontendTemplateContainer "container"
879
        if ($type === FrontendTemplateContainer::CONTAINER_TYPE) {
880
            $renderedTemplates = [];
881
            if (Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'] ?? false) {
882
                $frontendTemplateContainers = Seomatic::$plugin->frontendTemplates->frontendTemplateContainer['data'];
883
                foreach ($frontendTemplateContainers as $name => $frontendTemplateContainer) {
884
                    if ($frontendTemplateContainer->include) {
885
                        $result = $frontendTemplateContainer->render([
886
                        ]);
887
                        $renderedTemplates[] = [$name => $result];
888
                    }
889
                }
890
            }
891
892
            return $renderedTemplates;
893
        }
894
        /** @var  $metaContainer MetaContainer */
895
        foreach ($this->metaContainers as $metaContainer) {
896
            if ($metaContainer::CONTAINER_TYPE === $type && $metaContainer->include) {
897
                /** @noinspection SlowArrayOperationsInLoopInspection */
898
                $htmlArray = array_merge($htmlArray, $metaContainer->renderArray());
899
            }
900
        }
901
        // Special-case for requests for the MetaSiteVars "container"
902
        if ($type === MetaSiteVars::CONTAINER_TYPE) {
903
            $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...
904
            $htmlArray = array_merge($htmlArray, $this->metaSiteVars->toArray());
905
        }
906
907
        return $htmlArray;
908
    }
909
910
    // Protected Methods
911
    // =========================================================================
912
913
    /**
914
     * Return a MetaItem object by $key from container $type
915
     *
916
     * @param string $key
917
     * @param string $type
918
     *
919
     * @return null|MetaItem
920
     */
921
    public function getMetaItemByKey(string $key, string $type = '')
922
    {
923
        $metaItem = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $metaItem is dead and can be removed.
Loading history...
924
        /** @var  $metaContainer MetaContainer */
925
        foreach ($this->metaContainers as $metaContainer) {
926
            if (($metaContainer::CONTAINER_TYPE === $type) || empty($type)) {
927
                /** @var  $metaTag MetaItem */
928
                foreach ($metaContainer->data as $metaItem) {
929
                    if ($key === $metaItem->key) {
930
                        return $metaItem;
931
                    }
932
                }
933
            }
934
        }
935
936
        return null;
937
    }
938
939
    /**
940
     * Invalidate all of the meta container caches
941
     */
942
    public function invalidateCaches()
943
    {
944
        $cache = Craft::$app->getCache();
945
        TagDependency::invalidate($cache, self::GLOBAL_METACONTAINER_CACHE_TAG);
946
        Craft::info(
947
            'All meta container caches cleared',
948
            __METHOD__
949
        );
950
        // Trigger an event to let other plugins/modules know we've cleared our caches
951
        $event = new InvalidateContainerCachesEvent([
952
            'uri' => null,
953
            'siteId' => null,
954
            'sourceId' => null,
955
            'sourceType' => null,
956
        ]);
957
        if (!Craft::$app instanceof ConsoleApplication) {
958
            $this->trigger(self::EVENT_INVALIDATE_CONTAINER_CACHES, $event);
959
        }
960
    }
961
962
    /**
963
     * Invalidate a meta bundle cache
964
     *
965
     * @param int $sourceId
966
     * @param null|string $sourceType
967
     * @param null|int $siteId
968
     */
969
    public function invalidateContainerCacheById(int $sourceId, $sourceType = null, $siteId = null)
970
    {
971
        $metaBundleSourceId = '';
972
        if ($sourceId) {
973
            $metaBundleSourceId = $sourceId;
974
        }
975
        $metaBundleSourceType = '';
976
        if ($sourceType) {
977
            $metaBundleSourceType = $sourceType;
978
        }
979
        if ($siteId === null) {
980
            $siteId = Craft::$app->getSites()->currentSite->id ?? 1;
981
        }
982
        $cache = Craft::$app->getCache();
983
        TagDependency::invalidate(
984
            $cache,
985
            self::METACONTAINER_CACHE_TAG . $metaBundleSourceId . $metaBundleSourceType . $siteId
986
        );
987
        Craft::info(
988
            'Meta bundle cache cleared: ' . $metaBundleSourceId . ' / ' . $metaBundleSourceType . ' / ' . $siteId,
989
            __METHOD__
990
        );
991
        // Trigger an event to let other plugins/modules know we've cleared our caches
992
        $event = new InvalidateContainerCachesEvent([
993
            'uri' => null,
994
            'siteId' => $siteId,
995
            'sourceId' => $sourceId,
996
            'sourceType' => $metaBundleSourceType,
997
        ]);
998
        if (!Craft::$app instanceof ConsoleApplication) {
999
            $this->trigger(self::EVENT_INVALIDATE_CONTAINER_CACHES, $event);
1000
        }
1001
    }
1002
1003
    /**
1004
     * Invalidate a meta bundle cache
1005
     *
1006
     * @param string $uri
1007
     * @param null|int $siteId
1008
     */
1009
    public function invalidateContainerCacheByPath(string $uri, $siteId = null)
1010
    {
1011
        $cache = Craft::$app->getCache();
1012
        if ($siteId === null) {
1013
            $siteId = Craft::$app->getSites()->currentSite->id ?? 1;
1014
        }
1015
        TagDependency::invalidate($cache, self::METACONTAINER_CACHE_TAG . $uri . $siteId);
1016
        Craft::info(
1017
            'Meta container cache cleared: ' . $uri . ' / ' . $siteId,
1018
            __METHOD__
1019
        );
1020
        // Trigger an event to let other plugins/modules know we've cleared our caches
1021
        $event = new InvalidateContainerCachesEvent([
1022
            'uri' => $uri,
1023
            'siteId' => $siteId,
1024
            'sourceId' => null,
1025
            'sourceType' => null,
1026
        ]);
1027
        if (!Craft::$app instanceof ConsoleApplication) {
1028
            $this->trigger(self::EVENT_INVALIDATE_CONTAINER_CACHES, $event);
1029
        }
1030
    }
1031
1032
    /**
1033
     * Generate an md5 hash from an object or array
1034
     *
1035
     * @param string|array|MetaItem $data
1036
     *
1037
     * @return string
1038
     */
1039
    protected function getHash($data): string
1040
    {
1041
        if (is_object($data)) {
1042
            $data = $data->toArray();
1043
        }
1044
        if (is_array($data)) {
1045
            $data = serialize($data);
1046
        }
1047
1048
        return md5($data);
1049
    }
1050
1051
    // Private Methods
1052
    // =========================================================================
1053
}
1054