Passed
Push — v3 ( 432ffb...f9ff88 )
by Andrew
40:19 queued 27:54
created

MetaContainers::includeScriptBodyHtml()   B

Complexity

Conditions 10
Paths 3

Size

Total Lines 42
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 10
eloc 26
c 1
b 1
f 0
nc 3
nop 1
dl 0
loc 42
ccs 0
cts 26
cp 0
crap 110
rs 7.6666

1 Method

Rating   Name   Duplication   Size   Complexity  
A MetaContainers::getContainersOfType() 0 11 3

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