Passed
Push — v4 ( 0283c4...b00655 )
by Andrew
49:59 queued 22:19
created

Sitemap::getTotalElementsInSitemap()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 5
cp 0
rs 10
cc 3
nc 2
nop 2
crap 12
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
     * Return the total number of elements in a sitemap, respecting metabundle settings.
442
     *
443
     * @param class-string<SeoElementInterface> $seoElementClass
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<SeoElementInterface> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<SeoElementInterface>.
Loading history...
444
     * @param MetaBundle $metaBundle
445
     * @return int|null
446
     */
447
    public static function getTotalElementsInSitemap(string $seoElementClass, MetaBundle $metaBundle): ?int
448
    {
449
        $totalElements = $seoElementClass::sitemapElementsQuery($metaBundle)->count();
450
451
        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...
452
            $totalElements = $metaBundle->metaSitemapVars->sitemapLimit;
453
        }
454
455
        return $totalElements;
456
    }
457
458
    /**
459
     * Combine any per-entry type field settings from $element with the passed in
460
     * $metaBundle
461
     *
462
     * @param SeoElementInterface|string $seoElement
463
     * @param Element $element
464
     * @param MetaBundle $metaBundle
465
     */
466
    protected static function combineEntryTypeSettings($seoElement, Element $element, MetaBundle $metaBundle)
467
    {
468
        if (!empty($seoElement::typeMenuFromHandle($metaBundle->sourceHandle))) {
469
            list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId)
470
                = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element);
471
            $entryTypeBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
472
                $sourceBundleType,
473
                $sourceId,
474
                $sourceSiteId,
475
                $typeId
476
            );
477
            // Combine in any settings for this entry type
478
            if ($entryTypeBundle) {
479
                // Combine the meta sitemap vars
480
                $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

480
                /** @scrutinizer ignore-call */ 
481
                $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...
481
                $attributes = array_filter(
482
                    $attributes,
483
                    [ArrayHelper::class, 'preserveBools']
484
                );
485
                $metaBundle->metaSitemapVars->setAttributes($attributes, false);
486
487
                // Combine the meta global vars
488
                $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

488
                /** @scrutinizer ignore-call */ 
489
                $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...
489
                $attributes = array_filter(
490
                    $attributes,
491
                    [ArrayHelper::class, 'preserveBools']
492
                );
493
                $metaBundle->metaGlobalVars->setAttributes($attributes, false);
494
            }
495
        }
496
    }
497
498
    /**
499
     * Combine any SEO Settings field settings from $element with the passed in
500
     * $metaBundle
501
     *
502
     * @param Element $element
503
     * @param MetaBundle $metaBundle
504
     */
505
    protected static function combineFieldSettings(Element $element, MetaBundle $metaBundle)
506
    {
507
        $fieldHandles = FieldHelper::fieldsOfTypeFromElement(
508
            $element,
509
            FieldHelper::SEO_SETTINGS_CLASS_KEY,
510
            true
511
        );
512
        foreach ($fieldHandles as $fieldHandle) {
513
            if (!empty($element->$fieldHandle)) {
514
                /** @var SeoSettings $seoSettingsField */
515
                $seoSettingsField = Craft::$app->getFields()->getFieldByHandle($fieldHandle);
516
                /** @var MetaBundle $metaBundle */
517
                $fieldMetaBundle = $element->$fieldHandle;
518
                if ($seoSettingsField !== null) {
519
                    if ($seoSettingsField->sitemapTabEnabled) {
520
                        Seomatic::$plugin->metaBundles->pruneFieldMetaBundleSettings($fieldMetaBundle, $fieldHandle);
521
                        // Combine the meta sitemap vars
522
                        $attributes = $fieldMetaBundle->metaSitemapVars->getAttributes();
523
524
                        // Get the explicitly inherited attributes
525
                        $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

525
                        $inherited = array_keys(/** @scrutinizer ignore-type */ ArrayHelper::remove($attributes, 'inherited', []));
Loading history...
526
527
                        $attributes = array_intersect_key(
528
                            $attributes,
529
                            array_flip((array)$seoSettingsField->sitemapEnabledFields)
530
                        );
531
                        $attributes = array_filter(
532
                            $attributes,
533
                            [ArrayHelper::class, 'preserveBools']
534
                        );
535
536
                        foreach ($inherited as $inheritedAttribute) {
537
                            unset($attributes[$inheritedAttribute]);
538
                        }
539
540
                        $metaBundle->metaSitemapVars->setAttributes($attributes, false);
541
                    }
542
                    // Combine the meta global vars
543
                    $attributes = $fieldMetaBundle->metaGlobalVars->getAttributes();
544
                    $attributes = array_filter(
545
                        $attributes,
546
                        [ArrayHelper::class, 'preserveBools']
547
                    );
548
                    $metaBundle->metaGlobalVars->setAttributes($attributes, false);
549
                }
550
            }
551
        }
552
    }
553
554
    /**
555
     * @param Asset $asset
556
     * @param MetaBundle $metaBundle
557
     * @param array $lines
558
     */
559
    protected static function assetSitemapItem(Asset $asset, MetaBundle $metaBundle, array &$lines)
560
    {
561
        if ((bool)$asset->enabledForSite && $asset->getUrl() !== null) {
562
            switch ($asset->kind) {
563
                case 'image':
564
                    $transform = Craft::$app->getImageTransforms()->getTransformByHandle($metaBundle->metaSitemapVars->sitemapAssetTransform ?? '');
565
                    $lines[] = '<image:image>';
566
                    $lines[] = '<image:loc>';
567
                    $lines[] = Html::encode(UrlHelper::absoluteUrlWithProtocol($asset->getUrl($transform, true)));
568
                    $lines[] = '</image:loc>';
569
                    // Handle the dynamic field => property mappings
570
                    foreach ($metaBundle->metaSitemapVars->sitemapImageFieldMap as $row) {
571
                        $fieldName = $row['field'] ?? '';
572
                        $propName = $row['property'] ?? '';
573
                        if (!empty($fieldName) && !empty($asset[$fieldName]) && !empty($propName)) {
574
                            $lines[] = '<image:' . $propName . '>';
575
                            $lines[] = Html::encode($asset[$fieldName]);
576
                            $lines[] = '</image:' . $propName . '>';
577
                        }
578
                    }
579
                    $lines[] = '</image:image>';
580
                    break;
581
582
                case 'video':
583
                    $lines[] = '<video:video>';
584
                    $lines[] = '<video:content_loc>';
585
                    $lines[] = Html::encode(UrlHelper::absoluteUrlWithProtocol($asset->getUrl()));
586
                    $lines[] = '</video:content_loc>';
587
                    // Handle the dynamic field => property mappings
588
                    foreach ($metaBundle->metaSitemapVars->sitemapVideoFieldMap as $row) {
589
                        $fieldName = $row['field'] ?? '';
590
                        $propName = $row['property'] ?? '';
591
                        if (!empty($fieldName) && !empty($asset[$fieldName]) && !empty($propName)) {
592
                            $lines[] = '<video:' . $propName . '>';
593
                            $lines[] = Html::encode($asset[$fieldName]);
594
                            $lines[] = '</video:' . $propName . '>';
595
                        }
596
                    }
597
                    $lines[] = '</video:video>';
598
                    break;
599
            }
600
        }
601
    }
602
603
    /**
604
     * @param Asset $asset
605
     * @param MetaBundle $metaBundle
606
     * @param array $lines
607
     */
608
    protected static function assetFilesSitemapLink(Asset $asset, MetaBundle $metaBundle, array &$lines)
609
    {
610
        if ((bool)$asset->enabledForSite && $asset->getUrl() !== null) {
611
            if (in_array($asset->kind, SitemapTemplate::FILE_TYPES, false)) {
612
                $dateUpdated = $asset->dateUpdated ?? $asset->dateCreated ?? new DateTime();
613
                $lines[] = '<url>';
614
                $lines[] = '<loc>';
615
                $lines[] = Html::encode(UrlHelper::absoluteUrlWithProtocol($asset->getUrl()));
616
                $lines[] = '</loc>';
617
                $lines[] = '<lastmod>';
618
                $lines[] = $dateUpdated->format(DateTime::W3C);
619
                $lines[] = '</lastmod>';
620
                $lines[] = '<changefreq>';
621
                $lines[] = $metaBundle->metaSitemapVars->sitemapChangeFreq;
622
                $lines[] = '</changefreq>';
623
                $lines[] = '<priority>';
624
                $lines[] = $metaBundle->metaSitemapVars->sitemapPriority;
625
                $lines[] = '</priority>';
626
                $lines[] = '</url>';
627
            }
628
        }
629
    }
630
}
631