Passed
Push — v4 ( abac4f...4f4e34 )
by Andrew
44:17 queued 19:59
created

Sitemap::getElementListSitemap()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 0
c 0
b 0
f 0
dl 0
loc 2
ccs 0
cts 1
cp 0
rs 10
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace nystudio107\seomatic\helpers;
4
5
use benf\neo\elements\Block as NeoBlock;
6
use Craft;
7
use craft\base\Element;
8
use craft\base\Event;
9
use craft\console\Application as ConsoleApplication;
10
use craft\db\Paginator;
11
use craft\elements\Asset;
12
use craft\elements\MatrixBlock;
13
use craft\errors\SiteNotFoundException;
14
use craft\fields\Assets as AssetsField;
15
use DateTime;
16
use nystudio107\seomatic\base\SeoElementInterface;
17
use nystudio107\seomatic\events\IncludeSitemapEntryEvent;
18
use nystudio107\seomatic\fields\SeoSettings;
19
use nystudio107\seomatic\helpers\Field as FieldHelper;
20
use nystudio107\seomatic\models\MetaBundle;
21
use nystudio107\seomatic\models\SitemapTemplate;
22
use nystudio107\seomatic\Seomatic;
23
use Throwable;
24
use verbb\supertable\elements\SuperTableBlockElement as SuperTableBlock;
25
use yii\base\Exception;
26
use yii\helpers\Html;
27
use function array_intersect_key;
28
use function count;
29
use function in_array;
30
31
/**
32
 * @author    nystudio107
33
 * @package   Seomatic
34
 * @since     3.4.18
35
 */
36
class Sitemap
37
{
38
    /**
39
     * @event IncludeSitemapEntryEvent The event that is triggered when an entry is
40
     * about to be included in a sitemap
41
     *
42
     * ---
43
     * ```php
44
     * use nystudio107\seomatic\events\IncludeSitemapEntryEvent;
45
     * use nystudio107\seomatic\helpers\Sitemap;
46
     * use yii\base\Event;
47
     * Event::on(Sitemap::class, Sitemap::EVENT_INCLUDE_SITEMAP_ENTRY, function(IncludeSitemapEntryEvent $e) {
48
     *     $e->include = false;
49
     * });
50
     * ```
51
     */
52
    public const EVENT_INCLUDE_SITEMAP_ENTRY = 'includeSitemapEntry';
53
54
    /**
55
     * @const The number of assets to return in a single paginated query
56
     */
57
    public const SITEMAP_QUERY_PAGE_SIZE = 100;
58
59
    /**
60
     * Generate a sitemap with the passed in $params
61
     *
62
     * @param array $params
63
     * @return string
64
     * @throws SiteNotFoundException
65
     */
66
    public static function generateSitemap(array $params): ?string
67
    {
68
        $groupId = $params['groupId'];
69
        $type = $params['type'];
70
        $handle = $params['handle'];
71
        $siteId = $params['siteId'];
72
        $page = $params['page'];
73
74
        // Get an array of site ids for this site group
75
        $groupSiteIds = [];
76
77
        if (Seomatic::$settings->siteGroupsSeparate) {
78
            if (empty($groupId)) {
79
                try {
80
                    $thisSite = Craft::$app->getSites()->getSiteById($siteId);
81
                    if ($thisSite !== null) {
82
                        $group = $thisSite->getGroup();
83
                        $groupId = $group->id;
84
                    }
85
                } catch (Throwable $e) {
86
                    Craft::error($e->getMessage(), __METHOD__);
87
                }
88
            }
89
            $siteGroup = Craft::$app->getSites()->getGroupById($groupId);
90
            if ($siteGroup !== null) {
91
                $groupSiteIds = $siteGroup->getSiteIds();
92
            }
93
        }
94
95
        if (empty($groupSiteIds)) {
96
            $groupSiteIds = Craft::$app->getSites()->allSiteIds;
97
        }
98
99
        $lines = [];
100
        // Sitemap index XML header and opening tag
101
        $lines[] = '<?xml version="1.0" encoding="UTF-8"?>';
102
        $lines[] = '<?xml-stylesheet type="text/xsl" href="sitemap.xsl"?>';
103
        // One sitemap entry for each element
104
        $metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceHandle(
105
            $type,
106
            $handle,
107
            $siteId
108
        );
109
        // If it doesn't exist, exit
110
        if ($metaBundle === null) {
111
            return null;
112
        }
113
        $multiSite = count($metaBundle->sourceAltSiteSettings) > 1;
114
        $totalElements = null;
115
        $urlsetLine = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
116
        if ($metaBundle->metaSitemapVars->sitemapAssets) {
117
            $urlsetLine .= ' xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"';
118
            $urlsetLine .= ' xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"';
119
        }
120
        if ($multiSite) {
121
            $urlsetLine .= ' xmlns:xhtml="http://www.w3.org/1999/xhtml"';
122
        }
123
        if ((bool)$metaBundle->metaSitemapVars->newsSitemap) {
124
            $urlsetLine .= ' xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"';
125
        }
126
        $urlsetLine .= '>';
127
        $lines[] = $urlsetLine;
128
129
        // Get all of the elements for this meta bundle type
130
        $seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType($metaBundle->sourceBundleType);
131
132
        if ($seoElement !== null) {
133
            // Ensure `null` so that the resulting element query is correct
134
            if (empty($metaBundle->metaSitemapVars->sitemapLimit)) {
135
                $metaBundle->metaSitemapVars->sitemapLimit = null;
136
            }
137
138
            $totalElements = $seoElement::sitemapElementsQuery($metaBundle)->count();
139
            if ($metaBundle->metaSitemapVars->sitemapLimit && ($totalElements > $metaBundle->metaSitemapVars->sitemapLimit)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $metaBundle->metaSitemapVars->sitemapLimit of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
140
                $totalElements = $metaBundle->metaSitemapVars->sitemapLimit;
141
            }
142
        }
143
144
        // If no elements exist, just exit
145
        if (!$totalElements) {
146
            return null;
147
        }
148
149
        // Stash the sitemap attributes so they can be modified on a per-entry basis
150
        $stashedSitemapAttrs = $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

150
        /** @scrutinizer ignore-call */ 
151
        $stashedSitemapAttrs = $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...
151
        $stashedGlobalVarsAttrs = $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

151
        /** @scrutinizer ignore-call */ 
152
        $stashedGlobalVarsAttrs = $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...
152
        // Use craft\db\Paginator to paginate the results so we don't exceed any memory limits
153
        // See batch() and each() discussion here: https://github.com/yiisoft/yii2/issues/8420
154
        // and here: https://github.com/craftcms/cms/issues/7338
155
156
        $elementQuery = $seoElement::sitemapElementsQuery($metaBundle);
157
        $sitemapPageSize = $metaBundle->metaSitemapVars->sitemapPageSize;
158
        $elementQuery->limit($metaBundle->metaSitemapVars->sitemapLimit ?? null);
159
160
        // If this is not a paged sitemap, go through full resultss
161
        if (is_null($sitemapPageSize)) {
162
            $pagedSitemap = false;
163
            $paginator = new Paginator($elementQuery, [
164
                'pageSize' => self::SITEMAP_QUERY_PAGE_SIZE,
165
            ]);
166
            $elements = $paginator->getPageResults();
167
        } else {
168
            $sitemapPage = empty($page) ? 1 : $page;
169
            $pagedSitemap = true;
170
            $elementQuery->limit($sitemapPageSize);
171
            $elementQuery->offset(($sitemapPage - 1) * $sitemapPageSize);
172
            $elements = $elementQuery->all();
173
            $totalElements = $sitemapPageSize;
174
            $paginator = new Paginator($elementQuery, [
175
                'pageSize' => $sitemapPageSize,
176
            ]);
177
        }
178
179
        $currentElement = 1;
180
181
        do {
182
            if (Craft::$app instanceof ConsoleApplication) {
183
                if ($pagedSitemap) {
184
                    $message = sprintf('Query %d elements', $sitemapPageSize);
185
                } else {
186
                    $message = sprintf('Query %d / %d - elements: %d',
187
                        $paginator->getCurrentPage(),
188
                        $paginator->getTotalPages(),
189
                        $paginator->getTotalResults());
190
                }
191
                echo $message . PHP_EOL;
192
            }
193
            /** @var Element $element */
194
            foreach ($elements as $element) {
195
                // Output some info if this is a console app
196
                if (Craft::$app instanceof ConsoleApplication) {
197
                    echo "Processing element {$currentElement}/{$totalElements} - {$element->title}" . PHP_EOL;
198
                }
199
200
                $metaBundle->metaSitemapVars->setAttributes($stashedSitemapAttrs, false);
201
                $metaBundle->metaGlobalVars->setAttributes($stashedGlobalVarsAttrs, false);
202
                // Combine in any per-entry type settings
203
                self::combineEntryTypeSettings($seoElement, $element, $metaBundle);
204
                // Make sure this entry isn't disabled
205
                self::combineFieldSettings($element, $metaBundle);
206
                // Special case for the __home__ URI
207
                $path = ($element->uri === '__home__') ? '' : $element->uri;
208
                // Check to see if robots is `none` or `no index`
209
                $robotsEnabled = true;
210
                if (!empty($metaBundle->metaGlobalVars->robots)) {
211
                    $robotsEnabled = $metaBundle->metaGlobalVars->robots !== 'none' &&
212
                        $metaBundle->metaGlobalVars->robots !== 'noindex';
213
                }
214
                $enabled = $element->getEnabledForSite($metaBundle->sourceSiteId);
215
                $enabled = $enabled && $path !== null && $metaBundle->metaSitemapVars->sitemapUrls && $robotsEnabled;
216
                $event = new IncludeSitemapEntryEvent([
217
                    'include' => $enabled,
218
                    'element' => $element,
219
                    'metaBundle' => $metaBundle,
220
                ]);
221
                Event::trigger(self::class, self::EVENT_INCLUDE_SITEMAP_ENTRY, $event);
222
                // Only add in a sitemap entry if it meets our criteria
223
                if ($event->include) {
224
                    // Get the url and canonicalUrl
225
                    try {
226
                        $url = UrlHelper::siteUrl($path, null, null, $metaBundle->sourceSiteId);
227
                    } catch (Exception $e) {
228
                        $url = '';
229
                    }
230
                    $url = UrlHelper::absoluteUrlWithProtocol($url);
231
                    if (Seomatic::$settings->excludeNonCanonicalUrls) {
232
                        Seomatic::$matchedElement = $element;
233
                        MetaValue::cache();
234
                        $path = $metaBundle->metaGlobalVars->parsedValue('canonicalUrl');
235
                        try {
236
                            $canonicalUrl = UrlHelper::siteUrl($path, null, null, $metaBundle->sourceSiteId);
237
                        } catch (Exception $e) {
238
                            $canonicalUrl = '';
239
                        }
240
                        $canonicalUrl = UrlHelper::absoluteUrlWithProtocol($canonicalUrl);
241
                        if ($url !== $canonicalUrl) {
242
                            Craft::info("Excluding URL: {$url} from the sitemap because it does not match the Canonical URL: {$canonicalUrl} - " . $metaBundle->metaGlobalVars->canonicalUrl . " - " . $element->uri);
0 ignored issues
show
Bug introduced by
Are you sure $metaBundle->metaGlobalVars->canonicalUrl of type object|string can be used in concatenation? ( Ignorable by Annotation )

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

242
                            Craft::info("Excluding URL: {$url} from the sitemap because it does not match the Canonical URL: {$canonicalUrl} - " . /** @scrutinizer ignore-type */ $metaBundle->metaGlobalVars->canonicalUrl . " - " . $element->uri);
Loading history...
243
                            continue;
244
                        }
245
                    }
246
                    $dateUpdated = $element->dateUpdated ?? $element->dateCreated ?? new DateTime();
247
                    $lines[] = '<url>';
248
                    // Standard sitemap key/values
249
                    $lines[] = '<loc>';
250
                    $lines[] = Html::encode($url);
251
                    $lines[] = '</loc>';
252
                    $lines[] = '<lastmod>';
253
                    $lines[] = $dateUpdated->format(DateTime::W3C);
254
                    $lines[] = '</lastmod>';
255
                    $lines[] = '<changefreq>';
256
                    $lines[] = $metaBundle->metaSitemapVars->sitemapChangeFreq;
257
                    $lines[] = '</changefreq>';
258
                    $lines[] = '<priority>';
259
                    $lines[] = $metaBundle->metaSitemapVars->sitemapPriority;
260
                    $lines[] = '</priority>';
261
                    // Handle alternate URLs if this is multi-site
262
                    if ($multiSite && $metaBundle->metaSitemapVars->sitemapAltLinks) {
263
                        $primarySiteId = Craft::$app->getSites()->getPrimarySite()->id;
264
                        foreach ($metaBundle->sourceAltSiteSettings as $altSiteSettings) {
265
                            if (in_array($altSiteSettings['siteId'], $groupSiteIds, false) && SiteHelper::siteEnabledWithUrls($altSiteSettings['siteId'])) {
266
                                $altElement = null;
267
                                if ($seoElement !== null) {
268
                                    /** @var Element $altElement */
269
                                    $altElement = $seoElement::sitemapAltElement(
270
                                        $metaBundle,
271
                                        $element->id,
272
                                        $altSiteSettings['siteId']
273
                                    );
274
                                }
275
                                // Make sure to only include the `hreflang` if the element exists,
276
                                // and sitemaps are on for it
277
                                if (Seomatic::$settings->addHrefLang && $altElement && $altElement->url) {
278
                                    list($altSourceId, $altSourceBundleType, $altSourceHandle, $altSourceSiteId, $altTypeId)
279
                                        = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($altElement);
280
                                    $altMetaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
281
                                        $altSourceBundleType,
282
                                        $altSourceId,
283
                                        $altSourceSiteId
284
                                    );
285
                                    if ($altMetaBundle) {
286
                                        $altEnabled = $altElement->getEnabledForSite($altMetaBundle->sourceSiteId);
287
                                        // Make sure this entry isn't disabled
288
                                        self::combineFieldSettings($altElement, $altMetaBundle);
289
                                        if ($altEnabled && $altMetaBundle->metaSitemapVars->sitemapUrls) {
290
                                            try {
291
                                                $altUrl = UrlHelper::siteUrl($altElement->url, null, null, $altSourceId);
292
                                            } catch (Exception $e) {
293
                                                $altUrl = $altElement->url;
294
                                            }
295
                                            $altUrl = UrlHelper::absoluteUrlWithProtocol($altUrl);
296
                                            // If this is the primary site, add it as x-default, too
297
                                            if ($primarySiteId === $altSourceSiteId && Seomatic::$settings->addXDefaultHrefLang) {
298
                                                $lines[] = '<xhtml:link rel="alternate"'
299
                                                    . ' hreflang="x-default"'
300
                                                    . ' href="' . Html::encode($altUrl) . '"'
301
                                                    . ' />';
302
                                            }
303
                                            $lines[] = '<xhtml:link rel="alternate"'
304
                                                . ' hreflang="' . $altSiteSettings['language'] . '"'
305
                                                . ' href="' . Html::encode($altUrl) . '"'
306
                                                . ' />';
307
                                        }
308
                                    }
309
                                }
310
                            }
311
                        }
312
                    }
313
                    // Handle news sitemaps https://developers.google.com/search/docs/crawling-indexing/sitemaps/news-sitemap
314
                    if ((bool)$metaBundle->metaSitemapVars->newsSitemap) {
315
                        $now = new DateTime();
316
                        $interval = $now->diff($dateUpdated);
317
                        if ($interval->days <= 2) {
318
                            $language = strtolower($element->getLanguage());
319
                            if (!str_starts_with($language, 'zh')) {
320
                                $language = substr($language, 0, 2);
321
                            }
322
                            $lines[] = '<news:news>';
323
                            $lines[] = '<news:publication>';
324
                            $lines[] = '<news:name>' . $metaBundle->metaSitemapVars->newsPublicationName . '</news:name>';
325
                            $lines[] = '<news:language>' . $language . '</news:language>';
326
                            $lines[] = '</news:publication>';
327
                            $lines[] = '<news:publication_date>' . $dateUpdated->format(DateTime::W3C) . '</news:publication_date>';
328
                            $lines[] = '<news:title>' . $element->title . '</news:title>';
329
                            $lines[] = '</news:news>';
330
                        }
331
                    }
332
                    // Handle any Assets
333
                    if ($metaBundle->metaSitemapVars->sitemapAssets) {
334
                        // Regular Assets fields
335
                        $assetFields = FieldHelper::fieldsOfTypeFromElement(
336
                            $element,
337
                            FieldHelper::ASSET_FIELD_CLASS_KEY,
338
                            true
339
                        );
340
                        foreach ($assetFields as $assetField) {
341
                            $assets = $element[$assetField]->all();
342
                            /** @var Asset[] $assets */
343
                            foreach ($assets as $asset) {
344
                                self::assetSitemapItem($asset, $metaBundle, $lines);
345
                            }
346
                        }
347
                        // Assets embeded in Block fields
348
                        $blockFields = FieldHelper::fieldsOfTypeFromElement(
349
                            $element,
350
                            FieldHelper::BLOCK_FIELD_CLASS_KEY,
351
                            true
352
                        );
353
                        foreach ($blockFields as $blockField) {
354
                            $blocks = $element[$blockField]->all();
355
                            /** @var MatrixBlock[]|NeoBlock[]|SuperTableBlock[]|object[] $blocks */
356
                            foreach ($blocks as $block) {
357
                                $assetFields = [];
358
                                if ($block instanceof MatrixBlock) {
359
                                    $assetFields = FieldHelper::matrixFieldsOfType($block, AssetsField::class);
360
                                }
361
                                if ($block instanceof NeoBlock) {
362
                                    $assetFields = FieldHelper::neoFieldsOfType($block, AssetsField::class);
363
                                }
364
                                if ($block instanceof SuperTableBlock) {
365
                                    $assetFields = FieldHelper::superTableFieldsOfType($block, AssetsField::class);
366
                                }
367
                                foreach ($assetFields as $assetField) {
368
                                    foreach ($block[$assetField]->all() as $asset) {
369
                                        self::assetSitemapItem($asset, $metaBundle, $lines);
370
                                    }
371
                                }
372
                            }
373
                        }
374
                    }
375
                    $lines[] = '</url>';
376
                }
377
                // Include links to any known file types in the assets fields
378
                if ($metaBundle->metaSitemapVars->sitemapFiles) {
379
                    // Regular Assets fields
380
                    $assetFields = FieldHelper::fieldsOfTypeFromElement(
381
                        $element,
382
                        FieldHelper::ASSET_FIELD_CLASS_KEY,
383
                        true
384
                    );
385
                    foreach ($assetFields as $assetField) {
386
                        $assets = $element[$assetField]->all();
387
                        foreach ($assets as $asset) {
388
                            self::assetFilesSitemapLink($asset, $metaBundle, $lines);
389
                        }
390
                    }
391
                    // Assets embeded in Block fields
392
                    $blockFields = FieldHelper::fieldsOfTypeFromElement(
393
                        $element,
394
                        FieldHelper::BLOCK_FIELD_CLASS_KEY,
395
                        true
396
                    );
397
                    foreach ($blockFields as $blockField) {
398
                        $blocks = $element[$blockField]->all();
399
                        /** @var MatrixBlock[]|NeoBlock[]|SuperTableBlock[]|object[] $blocks */
400
                        foreach ($blocks as $block) {
401
                            $assetFields = [];
402
                            if ($block instanceof MatrixBlock) {
403
                                $assetFields = FieldHelper::matrixFieldsOfType($block, AssetsField::class);
404
                            }
405
                            if ($block instanceof SuperTableBlock) {
406
                                $assetFields = FieldHelper::superTableFieldsOfType($block, AssetsField::class);
407
                            }
408
                            if ($block instanceof NeoBlock) {
409
                                $assetFields = FieldHelper::neoFieldsOfType($block, AssetsField::class);
410
                            }
411
                            foreach ($assetFields as $assetField) {
412
                                foreach ($block[$assetField]->all() as $asset) {
413
                                    self::assetFilesSitemapLink($asset, $metaBundle, $lines);
414
                                }
415
                            }
416
                        }
417
                    }
418
                }
419
                $currentElement++;
420
            }
421
422
            if ($pagedSitemap) {
423
                break;
424
            }
425
426
            if ($paginator->getCurrentPage() == $paginator->getTotalPages()) {
427
                break;
428
            }
429
430
            $paginator->currentPage++;
431
            $elements = $paginator->getPageResults();
432
        } while (!empty($elements));
433
434
        // Sitemap closing tag
435
        $lines[] = '</urlset>';
436
437
        return implode('', $lines);
438
    }
439
440
441
    /**
442
     * Combine any per-entry type field settings from $element with the passed in
443
     * $metaBundle
444
     *
445
     * @param SeoElementInterface|string $seoElement
446
     * @param Element $element
447
     * @param MetaBundle $metaBundle
448
     */
449
    protected static function combineEntryTypeSettings($seoElement, Element $element, MetaBundle $metaBundle)
450
    {
451
        if (!empty($seoElement::typeMenuFromHandle($metaBundle->sourceHandle))) {
452
            list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId)
453
                = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element);
454
            $entryTypeBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
455
                $sourceBundleType,
456
                $sourceId,
457
                $sourceSiteId,
458
                $typeId
459
            );
460
            // Combine in any settings for this entry type
461
            if ($entryTypeBundle) {
462
                // Combine the meta sitemap vars
463
                $attributes = $entryTypeBundle->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

463
                /** @scrutinizer ignore-call */ 
464
                $attributes = $entryTypeBundle->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...
464
                $attributes = array_filter(
465
                    $attributes,
466
                    [ArrayHelper::class, 'preserveBools']
467
                );
468
                $metaBundle->metaSitemapVars->setAttributes($attributes, false);
469
470
                // Combine the meta global vars
471
                $attributes = $entryTypeBundle->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

471
                /** @scrutinizer ignore-call */ 
472
                $attributes = $entryTypeBundle->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...
472
                $attributes = array_filter(
473
                    $attributes,
474
                    [ArrayHelper::class, 'preserveBools']
475
                );
476
                $metaBundle->metaGlobalVars->setAttributes($attributes, false);
477
            }
478
        }
479
    }
480
481
    /**
482
     * Combine any SEO Settings field settings from $element with the passed in
483
     * $metaBundle
484
     *
485
     * @param Element $element
486
     * @param MetaBundle $metaBundle
487
     */
488
    protected static function combineFieldSettings(Element $element, MetaBundle $metaBundle)
489
    {
490
        $fieldHandles = FieldHelper::fieldsOfTypeFromElement(
491
            $element,
492
            FieldHelper::SEO_SETTINGS_CLASS_KEY,
493
            true
494
        );
495
        foreach ($fieldHandles as $fieldHandle) {
496
            if (!empty($element->$fieldHandle)) {
497
                /** @var SeoSettings $seoSettingsField */
498
                $seoSettingsField = Craft::$app->getFields()->getFieldByHandle($fieldHandle);
499
                /** @var MetaBundle $metaBundle */
500
                $fieldMetaBundle = $element->$fieldHandle;
501
                if ($seoSettingsField !== null) {
502
                    if ($seoSettingsField->sitemapTabEnabled) {
503
                        Seomatic::$plugin->metaBundles->pruneFieldMetaBundleSettings($fieldMetaBundle, $fieldHandle);
504
                        // Combine the meta sitemap vars
505
                        $attributes = $fieldMetaBundle->metaSitemapVars->getAttributes();
506
507
                        // Get the explicitly inherited attributes
508
                        $inherited = array_keys(ArrayHelper::remove($attributes, 'inherited', []));
0 ignored issues
show
Bug introduced by
It seems like nystudio107\seomatic\hel..., 'inherited', array()) can also be of type null; however, parameter $array of array_keys() does only seem to accept array, 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

508
                        $inherited = array_keys(/** @scrutinizer ignore-type */ ArrayHelper::remove($attributes, 'inherited', []));
Loading history...
509
510
                        $attributes = array_intersect_key(
511
                            $attributes,
512
                            array_flip((array)$seoSettingsField->sitemapEnabledFields)
513
                        );
514
                        $attributes = array_filter(
515
                            $attributes,
516
                            [ArrayHelper::class, 'preserveBools']
517
                        );
518
519
                        foreach ($inherited as $inheritedAttribute) {
520
                            unset($attributes[$inheritedAttribute]);
521
                        }
522
523
                        $metaBundle->metaSitemapVars->setAttributes($attributes, false);
524
                    }
525
                    // Combine the meta global vars
526
                    $attributes = $fieldMetaBundle->metaGlobalVars->getAttributes();
527
                    $attributes = array_filter(
528
                        $attributes,
529
                        [ArrayHelper::class, 'preserveBools']
530
                    );
531
                    $metaBundle->metaGlobalVars->setAttributes($attributes, false);
532
                }
533
            }
534
        }
535
    }
536
537
    /**
538
     * @param Asset $asset
539
     * @param MetaBundle $metaBundle
540
     * @param array $lines
541
     */
542
    protected static function assetSitemapItem(Asset $asset, MetaBundle $metaBundle, array &$lines)
543
    {
544
        if ((bool)$asset->enabledForSite && $asset->getUrl() !== null) {
545
            switch ($asset->kind) {
546
                case 'image':
547
                    $transform = Craft::$app->getImageTransforms()->getTransformByHandle($metaBundle->metaSitemapVars->sitemapAssetTransform ?? '');
548
                    $lines[] = '<image:image>';
549
                    $lines[] = '<image:loc>';
550
                    $lines[] = Html::encode(UrlHelper::absoluteUrlWithProtocol($asset->getUrl($transform, true)));
551
                    $lines[] = '</image:loc>';
552
                    // Handle the dynamic field => property mappings
553
                    foreach ($metaBundle->metaSitemapVars->sitemapImageFieldMap as $row) {
554
                        $fieldName = $row['field'] ?? '';
555
                        $propName = $row['property'] ?? '';
556
                        if (!empty($fieldName) && !empty($asset[$fieldName]) && !empty($propName)) {
557
                            $lines[] = '<image:' . $propName . '>';
558
                            $lines[] = Html::encode($asset[$fieldName]);
559
                            $lines[] = '</image:' . $propName . '>';
560
                        }
561
                    }
562
                    $lines[] = '</image:image>';
563
                    break;
564
565
                case 'video':
566
                    $lines[] = '<video:video>';
567
                    $lines[] = '<video:content_loc>';
568
                    $lines[] = Html::encode(UrlHelper::absoluteUrlWithProtocol($asset->getUrl()));
569
                    $lines[] = '</video:content_loc>';
570
                    // Handle the dynamic field => property mappings
571
                    foreach ($metaBundle->metaSitemapVars->sitemapVideoFieldMap as $row) {
572
                        $fieldName = $row['field'] ?? '';
573
                        $propName = $row['property'] ?? '';
574
                        if (!empty($fieldName) && !empty($asset[$fieldName]) && !empty($propName)) {
575
                            $lines[] = '<video:' . $propName . '>';
576
                            $lines[] = Html::encode($asset[$fieldName]);
577
                            $lines[] = '</video:' . $propName . '>';
578
                        }
579
                    }
580
                    $lines[] = '</video:video>';
581
                    break;
582
            }
583
        }
584
    }
585
586
    /**
587
     * @param Asset $asset
588
     * @param MetaBundle $metaBundle
589
     * @param array $lines
590
     */
591
    protected static function assetFilesSitemapLink(Asset $asset, MetaBundle $metaBundle, array &$lines)
592
    {
593
        if ((bool)$asset->enabledForSite && $asset->getUrl() !== null) {
594
            if (in_array($asset->kind, SitemapTemplate::FILE_TYPES, false)) {
595
                $dateUpdated = $asset->dateUpdated ?? $asset->dateCreated ?? new DateTime();
596
                $lines[] = '<url>';
597
                $lines[] = '<loc>';
598
                $lines[] = Html::encode(UrlHelper::absoluteUrlWithProtocol($asset->getUrl()));
599
                $lines[] = '</loc>';
600
                $lines[] = '<lastmod>';
601
                $lines[] = $dateUpdated->format(DateTime::W3C);
602
                $lines[] = '</lastmod>';
603
                $lines[] = '<changefreq>';
604
                $lines[] = $metaBundle->metaSitemapVars->sitemapChangeFreq;
605
                $lines[] = '</changefreq>';
606
                $lines[] = '<priority>';
607
                $lines[] = $metaBundle->metaSitemapVars->sitemapPriority;
608
                $lines[] = '</priority>';
609
                $lines[] = '</url>';
610
            }
611
        }
612
    }
613
614
    protected static function getElementListSitemap(array $elements)
0 ignored issues
show
Unused Code introduced by
The parameter $elements is not used and could be removed. ( Ignorable by Annotation )

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

614
    protected static function getElementListSitemap(/** @scrutinizer ignore-unused */ array $elements)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
615
    {
616
    }
617
}
618