Test Failed
Push — v5 ( 567dd3...527085 )
by Andrew
46:05 queued 21:29
created

Sitemap::resolveNestedField()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
eloc 4
c 2
b 2
f 0
dl 0
loc 7
rs 10
cc 2
nc 1
nop 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\Entry;
0 ignored issues
show
Bug introduced by
The type craft\elements\Entry 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...
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\events\ModifySitemapQueryEvent;
19
use nystudio107\seomatic\fields\SeoSettings;
20
use nystudio107\seomatic\helpers\EagerLoad as EagerLoadHelper;
21
use nystudio107\seomatic\helpers\Field as FieldHelper;
22
use nystudio107\seomatic\models\MetaBundle;
23
use nystudio107\seomatic\models\SitemapTemplate;
24
use nystudio107\seomatic\Seomatic;
25
use Throwable;
26
use yii\base\Exception;
27
use yii\helpers\Html;
28
use function array_intersect_key;
29
use function count;
30
use function in_array;
31
32
/**
33
 * @author    nystudio107
34
 * @package   Seomatic
35
 * @since     3.4.18
36
 */
37
class Sitemap
38
{
39
    /**
40
     * @event IncludeSitemapEntryEvent The event that is triggered when an entry is
41
     * about to be included in a sitemap
42
     *
43
     * ---
44
     * ```php
45
     * use nystudio107\seomatic\events\IncludeSitemapEntryEvent;
46
     * use nystudio107\seomatic\helpers\Sitemap;
47
     * use yii\base\Event;
48
     * Event::on(Sitemap::class, Sitemap::EVENT_INCLUDE_SITEMAP_ENTRY, function(IncludeSitemapEntryEvent $e) {
49
     *     $e->include = false;
50
     * });
51
     * ```
52
     */
53
    public const EVENT_INCLUDE_SITEMAP_ENTRY = 'includeSitemapEntry';
54
55
    /**
56
     * @event ModifySitemapQueryEvent Allows the modification of the element query used to generate a sitemap
57
     *
58
     * ---
59
     * ```php
60
     * use nystudio107\seomatic\events\ModifySitemapQueryEvent;
61
     * use nystudio107\seomatic\helpers\Sitemap;
62
     * use yii\base\Event;
63
     * Event::on(Sitemap::class, Sitemap::EVENT_MODIFY_SITEMAP_QUERY, function(ModifySitemapQueryEvent $e) {
64
     *     $e->query->limit(10);
65
     * });
66
     * ```
67
     */
68
    public const EVENT_MODIFY_SITEMAP_QUERY = 'modifySitemapQuery';
69
70
    /**
71
     * @const The number of assets to return in a single paginated query
72
     */
73
    public const SITEMAP_QUERY_PAGE_SIZE = 100;
74
75
    /**
76
     * Generate a sitemap with the passed in $params
77
     *
78
     * @param array $params
79
     * @return string
80
     * @throws SiteNotFoundException
81
     */
82
    public static function generateSitemap(array $params): ?string
83
    {
84
        $groupId = $params['groupId'];
85
        $type = $params['type'];
86
        $handle = $params['handle'];
87
        $siteId = $params['siteId'];
88
        $page = $params['page'];
89
90
        // Get an array of site ids for this site group
91
        $groupSiteIds = [];
92
93
        if (Seomatic::$settings->siteGroupsSeparate) {
94
            if (empty($groupId)) {
95
                try {
96
                    $thisSite = Craft::$app->getSites()->getSiteById($siteId);
97
                    if ($thisSite !== null) {
98
                        $group = $thisSite->getGroup();
99
                        $groupId = $group->id;
100
                    }
101
                } catch (Throwable $e) {
102
                    Craft::error($e->getMessage(), __METHOD__);
103
                }
104
            }
105
            $siteGroup = Craft::$app->getSites()->getGroupById($groupId);
106
            if ($siteGroup !== null) {
107
                $groupSiteIds = $siteGroup->getSiteIds();
108
            }
109
        }
110
111
        if (empty($groupSiteIds)) {
112
            $groupSiteIds = Craft::$app->getSites()->allSiteIds;
113
        }
114
115
        $lines = [];
116
        // Sitemap index XML header and opening tag
117
        $lines[] = '<?xml version="1.0" encoding="UTF-8"?>';
118
        $lines[] = '<?xml-stylesheet type="text/xsl" href="sitemap.xsl"?>';
119
        // One sitemap entry for each element
120
        $metaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceHandle(
121
            $type,
122
            $handle,
123
            $siteId
124
        );
125
        // If it doesn't exist, exit
126
        if ($metaBundle === null) {
127
            return null;
128
        }
129
        $multiSite = count($metaBundle->sourceAltSiteSettings) > 1;
130
        $totalElements = null;
131
        $urlsetLine = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"';
132
        if ($metaBundle->metaSitemapVars->sitemapAssets) {
133
            $urlsetLine .= ' xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"';
134
            $urlsetLine .= ' xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"';
135
        }
136
        if ($multiSite) {
137
            $urlsetLine .= ' xmlns:xhtml="http://www.w3.org/1999/xhtml"';
138
        }
139
        if ((bool)$metaBundle->metaSitemapVars->newsSitemap) {
140
            $urlsetLine .= ' xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"';
141
        }
142
        $urlsetLine .= '>';
143
        $lines[] = $urlsetLine;
144
145
        // Get all of the elements for this meta bundle type
146
        $seoElement = Seomatic::$plugin->seoElements->getSeoElementByMetaBundleType($metaBundle->sourceBundleType);
147
148
        if ($seoElement !== null) {
149
            // Ensure `null` so that the resulting element query is correct
150
            if (empty($metaBundle->metaSitemapVars->sitemapLimit)) {
151
                $metaBundle->metaSitemapVars->sitemapLimit = null;
152
            }
153
            $totalElements = self::getTotalElementsInSitemap($seoElement, $metaBundle);
154
        }
155
156
        // If no elements exist, just exit
157
        if (!$totalElements) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $totalElements of type integer|null is loosely compared to false; 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...
158
            return null;
159
        }
160
161
        // Stash the sitemap attributes so they can be modified on a per-entry basis
162
        $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

162
        /** @scrutinizer ignore-call */ 
163
        $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...
163
        $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

163
        /** @scrutinizer ignore-call */ 
164
        $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...
164
        // Use craft\db\Paginator to paginate the results so we don't exceed any memory limits
165
        // See batch() and each() discussion here: https://github.com/yiisoft/yii2/issues/8420
166
        // and here: https://github.com/craftcms/cms/issues/7338
167
168
        // Allow listeners to modify the query before we use it
169
        $elementQuery = $seoElement::sitemapElementsQuery($metaBundle);
170
        $event = new ModifySitemapQueryEvent([
171
            'query' => $elementQuery,
172
            'metaBundle' => $metaBundle,
173
        ]);
174
        Event::trigger(self::class, self::EVENT_MODIFY_SITEMAP_QUERY, $event);
175
176
        $sitemapPageSize = $metaBundle->metaSitemapVars->sitemapPageSize;
177
        $elementQuery->limit($metaBundle->metaSitemapVars->sitemapLimit ?? null);
178
179
        // Eager load assets & relations
180
        if ($metaBundle->metaSitemapVars->sitemapAssets || $metaBundle->metaSitemapVars->sitemapFiles) {
181
            $woof = EagerLoadHelper::sitemapEagerLoadMap($metaBundle);
0 ignored issues
show
Unused Code introduced by
The assignment to $woof is dead and can be removed.
Loading history...
182
            //$elementQuery->with(EagerLoadHelper::sitemapEagerLoadMap($metaBundle));
183
        }
184
185
        // If this is not a paged sitemap, go through full results
186
        if (empty($sitemapPageSize)) {
187
            $pagedSitemap = false;
188
            $paginator = new Paginator($elementQuery, [
189
                'pageSize' => self::SITEMAP_QUERY_PAGE_SIZE,
190
            ]);
191
            $elements = $paginator->getPageResults();
192
        } else {
193
            $sitemapPage = empty($page) ? 1 : $page;
194
            $pagedSitemap = true;
195
            $elementQuery->limit($sitemapPageSize);
196
            $elementQuery->offset(($sitemapPage - 1) * $sitemapPageSize);
197
            $elements = $elementQuery->all();
198
            $totalElements = $sitemapPageSize;
199
            $paginator = new Paginator($elementQuery, [
200
                'pageSize' => $sitemapPageSize,
201
            ]);
202
        }
203
204
        $currentElement = 1;
205
206
        do {
207
            if (Craft::$app instanceof ConsoleApplication) {
208
                if ($pagedSitemap) {
209
                    $message = sprintf('Query %d elements', $sitemapPageSize);
210
                } else {
211
                    $message = sprintf('Query %d / %d - elements: %d',
212
                        $paginator->getCurrentPage(),
213
                        $paginator->getTotalPages(),
214
                        $paginator->getTotalResults());
215
                }
216
                echo $message . PHP_EOL;
217
            }
218
            /** @var Element $element */
219
            foreach ($elements as $element) {
220
                // Output some info if this is a console app
221
                if (Craft::$app instanceof ConsoleApplication) {
222
                    echo "Processing element {$currentElement}/{$totalElements} - {$element->title}" . PHP_EOL;
223
                }
224
225
                $metaBundle->metaSitemapVars->setAttributes($stashedSitemapAttrs, false);
226
                $metaBundle->metaGlobalVars->setAttributes($stashedGlobalVarsAttrs, false);
227
                // Combine in any per-entry type settings
228
                self::combineEntryTypeSettings($seoElement, $element, $metaBundle);
229
                // Make sure this entry isn't disabled
230
                self::combineFieldSettings($element, $metaBundle);
231
                // Special case for the __home__ URI
232
                $path = ($element->uri === '__home__') ? '' : $element->uri;
233
                // Check to see if robots is `none` or `no index`
234
                $robotsEnabled = true;
235
                if (!empty($metaBundle->metaGlobalVars->robots)) {
236
                    $robotsEnabled = $metaBundle->metaGlobalVars->robots !== 'none' &&
237
                        $metaBundle->metaGlobalVars->robots !== 'noindex';
238
                }
239
                $enabled = $element->getEnabledForSite($metaBundle->sourceSiteId);
240
                $enabled = $enabled && $path !== null && $metaBundle->metaSitemapVars->sitemapUrls && $robotsEnabled;
241
                $event = new IncludeSitemapEntryEvent([
242
                    'include' => $enabled,
243
                    'element' => $element,
244
                    'metaBundle' => $metaBundle,
245
                ]);
246
                Event::trigger(self::class, self::EVENT_INCLUDE_SITEMAP_ENTRY, $event);
247
                // Only add in a sitemap entry if it meets our criteria
248
                if ($event->include) {
249
                    // Get the url and canonicalUrl
250
                    try {
251
                        $url = UrlHelper::siteUrl($path, null, null, $metaBundle->sourceSiteId);
252
                    } catch (Exception $e) {
253
                        $url = '';
254
                    }
255
                    $url = UrlHelper::absoluteUrlWithProtocol($url);
256
                    if (Seomatic::$settings->excludeNonCanonicalUrls) {
257
                        Seomatic::$matchedElement = $element;
258
                        MetaValue::cache();
259
                        $path = $metaBundle->metaGlobalVars->parsedValue('canonicalUrl');
260
                        try {
261
                            $canonicalUrl = UrlHelper::siteUrl($path, null, null, $metaBundle->sourceSiteId);
262
                        } catch (Exception $e) {
263
                            $canonicalUrl = '';
264
                        }
265
                        $canonicalUrl = UrlHelper::absoluteUrlWithProtocol($canonicalUrl);
266
                        if ($url !== $canonicalUrl) {
267
                            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

267
                            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...
268
                            continue;
269
                        }
270
                    }
271
                    $dateUpdated = $element->dateUpdated ?? $element->dateCreated ?? new DateTime();
272
                    $lines[] = '<url>';
273
                    // Standard sitemap key/values
274
                    $lines[] = '<loc>';
275
                    $lines[] = self::encodeSitemapEntity($url);
276
                    $lines[] = '</loc>';
277
                    $lines[] = '<lastmod>';
278
                    $lines[] = $dateUpdated->format(DateTime::W3C);
279
                    $lines[] = '</lastmod>';
280
                    $lines[] = '<changefreq>';
281
                    $lines[] = $metaBundle->metaSitemapVars->sitemapChangeFreq;
282
                    $lines[] = '</changefreq>';
283
                    $lines[] = '<priority>';
284
                    $lines[] = $metaBundle->metaSitemapVars->sitemapPriority;
285
                    $lines[] = '</priority>';
286
                    // Handle alternate URLs if this is multi-site
287
                    if ($multiSite && $metaBundle->metaSitemapVars->sitemapAltLinks) {
288
                        $primarySiteId = Craft::$app->getSites()->getPrimarySite()->id;
289
                        foreach ($metaBundle->sourceAltSiteSettings as $altSiteSettings) {
290
                            if (in_array($altSiteSettings['siteId'], $groupSiteIds, false) && SiteHelper::siteEnabledWithUrls($altSiteSettings['siteId'])) {
291
                                $altElement = null;
292
                                if ($seoElement !== null) {
293
                                    /** @var Element $altElement */
294
                                    $altElement = $seoElement::sitemapAltElement(
295
                                        $metaBundle,
296
                                        $element->id,
297
                                        $altSiteSettings['siteId']
298
                                    );
299
                                }
300
                                // Make sure to only include the `hreflang` if the element exists,
301
                                // and sitemaps are on for it
302
                                if (Seomatic::$settings->addHrefLang && $altElement && $altElement->url) {
303
                                    list($altSourceId, $altSourceBundleType, $altSourceHandle, $altSourceSiteId, $altTypeId)
304
                                        = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($altElement);
305
                                    $altMetaBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
306
                                        $altSourceBundleType,
307
                                        $altSourceId,
308
                                        $altSourceSiteId
309
                                    );
310
                                    if ($altMetaBundle) {
311
                                        $altEnabled = $altElement->getEnabledForSite($altMetaBundle->sourceSiteId);
312
                                        // Make sure this entry isn't disabled
313
                                        self::combineFieldSettings($altElement, $altMetaBundle);
314
                                        if ($altEnabled && $altMetaBundle->metaSitemapVars->sitemapUrls) {
315
                                            try {
316
                                                $altUrl = UrlHelper::siteUrl($altElement->url, null, null, $altSourceId);
317
                                            } catch (Exception $e) {
318
                                                $altUrl = $altElement->url;
319
                                            }
320
                                            $altUrl = UrlHelper::absoluteUrlWithProtocol($altUrl);
321
                                            // If this is the primary site, add it as x-default, too
322
                                            if ($primarySiteId === $altSourceSiteId && Seomatic::$settings->addXDefaultHrefLang) {
323
                                                $lines[] = '<xhtml:link rel="alternate"'
324
                                                    . ' hreflang="x-default"'
325
                                                    . ' href="' . self::encodeSitemapEntity($altUrl) . '"'
326
                                                    . ' />';
327
                                            }
328
                                            $lines[] = '<xhtml:link rel="alternate"'
329
                                                . ' hreflang="' . $altSiteSettings['language'] . '"'
330
                                                . ' href="' . self::encodeSitemapEntity($altUrl) . '"'
331
                                                . ' />';
332
                                        }
333
                                    }
334
                                }
335
                            }
336
                        }
337
                    }
338
                    // Handle news sitemaps https://developers.google.com/search/docs/crawling-indexing/sitemaps/news-sitemap
339
                    if ((bool)$metaBundle->metaSitemapVars->newsSitemap) {
340
                        $now = new DateTime();
341
                        $interval = $now->diff($dateUpdated);
342
                        if ($interval->days <= 2) {
343
                            $language = strtolower($element->getLanguage());
344
                            if (!str_starts_with($language, 'zh')) {
345
                                $language = substr($language, 0, 2);
346
                            }
347
                            $lines[] = '<news:news>';
348
                            $lines[] = '<news:publication>';
349
                            $lines[] = '<news:name>' . self::encodeSitemapEntity($metaBundle->metaSitemapVars->newsPublicationName) . '</news:name>';
350
                            $lines[] = '<news:language>' . $language . '</news:language>';
351
                            $lines[] = '</news:publication>';
352
                            $lines[] = '<news:publication_date>' . $dateUpdated->format(DateTime::W3C) . '</news:publication_date>';
353
                            $lines[] = '<news:title>' . self::encodeSitemapEntity($element->title) . '</news:title>';
354
                            $lines[] = '</news:news>';
355
                        }
356
                    }
357
                    // Handle any Assets
358
                    if ($metaBundle->metaSitemapVars->sitemapAssets) {
359
                        // Regular Assets fields
360
                        $assetFields = FieldHelper::fieldsOfTypeFromElement(
361
                            $element,
362
                            FieldHelper::ASSET_FIELD_CLASS_KEY,
363
                            true
364
                        );
365
                        foreach ($assetFields as $assetField) {
366
                            $resolvedField = self::resolveNestedField($element, $assetField);
367
                            if ($resolvedField !== null) {
368
                                $assets = $resolvedField->all();
369
                                /** @var Asset[] $assets */
370
                                foreach ($assets as $asset) {
371
                                    self::assetSitemapItem($asset, $metaBundle, $lines);
372
                                }
373
                            }
374
                        }
375
                        // Assets embeded in Block fields
376
                        $blockFields = FieldHelper::fieldsOfTypeFromElement(
377
                            $element,
378
                            FieldHelper::BLOCK_FIELD_CLASS_KEY,
379
                            true
380
                        );
381
                        foreach ($blockFields as $blockField) {
382
                            $resolvedField = self::resolveNestedField($element, $blockField);
383
                            if ($resolvedField !== null) {
384
                                $blocks = $resolvedField->all();
385
                                /** @var Entry[]|NeoBlock[]|object[] $blocks */
386
                                foreach ($blocks as $block) {
387
                                    $assetFields = [];
388
                                    if ($block instanceof Entry) {
389
                                        $assetFields = FieldHelper::matrixFieldsOfType($block, AssetsField::class);
390
                                    }
391
                                    if ($block instanceof NeoBlock) {
392
                                        $assetFields = FieldHelper::neoFieldsOfType($block, AssetsField::class);
393
                                    }
394
                                    foreach ($assetFields as $assetField) {
395
                                        foreach ($block[$assetField]->all() as $asset) {
396
                                            self::assetSitemapItem($asset, $metaBundle, $lines);
397
                                        }
398
                                    }
399
                                }
400
                            }
401
                        }
402
                    }
403
                    $lines[] = '</url>';
404
                }
405
                // Include links to any known file types in the assets fields
406
                if ($metaBundle->metaSitemapVars->sitemapFiles) {
407
                    // Regular Assets fields
408
                    $assetFields = FieldHelper::fieldsOfTypeFromElement(
409
                        $element,
410
                        FieldHelper::ASSET_FIELD_CLASS_KEY,
411
                        true
412
                    );
413
                    foreach ($assetFields as $assetField) {
414
                        $resolvedField = self::resolveNestedField($element, $assetField);
415
                        if ($resolvedField !== null) {
416
                            $assets = $resolvedField->all();
417
                            foreach ($assets as $asset) {
418
                                self::assetFilesSitemapLink($asset, $metaBundle, $lines);
419
                            }
420
                        }
421
                    }
422
                    // Assets embeded in Block fields
423
                    $blockFields = FieldHelper::fieldsOfTypeFromElement(
424
                        $element,
425
                        FieldHelper::BLOCK_FIELD_CLASS_KEY,
426
                        true
427
                    );
428
                    foreach ($blockFields as $blockField) {
429
                        $resolvedField = self::resolveNestedField($element, $blockField);
430
                        if ($resolvedField !== null) {
431
                            $blocks = $resolvedField->all();
432
                            /** @var Entry[]|NeoBlock[]|object[] $blocks */
433
                            foreach ($blocks as $block) {
434
                                $assetFields = [];
435
                                if ($block instanceof Entry) {
436
                                    $assetFields = FieldHelper::matrixFieldsOfType($block, AssetsField::class);
437
                                }
438
                                if ($block instanceof NeoBlock) {
439
                                    $assetFields = FieldHelper::neoFieldsOfType($block, AssetsField::class);
440
                                }
441
                                foreach ($assetFields as $assetField) {
442
                                    foreach ($block[$assetField]->all() as $asset) {
443
                                        self::assetFilesSitemapLink($asset, $metaBundle, $lines);
444
                                    }
445
                                }
446
                            }
447
                        }
448
                    }
449
                }
450
                $currentElement++;
451
            }
452
453
            if ($pagedSitemap) {
454
                break;
455
            }
456
457
            if ($paginator->getCurrentPage() == $paginator->getTotalPages()) {
458
                break;
459
            }
460
461
            $paginator->currentPage++;
462
            $elements = $paginator->getPageResults();
463
        } while (!empty($elements));
464
465
        // Sitemap closing tag
466
        $lines[] = '</urlset>';
467
468
        return implode('', $lines);
469
    }
470
471
    /**
472
     * Fields coming back from FieldHelper:: are delimited by a . if they are nested fields like
473
     * ContentBlock or Matrix fields, so we need to drill down to find the actual field in question
474
     *
475
     * @param Element $element
476
     * @param $name
477
     * @return Element|mixed
478
     */
479
    public static function resolveNestedField(Element $element, $name)
480
    {
481
        $result = array_reduce(explode('.', $name), function($o, $p) {
482
            return $o === null ? $o : $o->$p;
483
        }, $element);
484
485
        return $result;
486
    }
487
488
    /**
489
     * Encode sitemap entities to make sure they follow the RFC-3986 standard for URIs, the RFC-3987 standard for IRIs
490
     * and the XML standard.
491
     * ref: https://sitemaps.org/protocol.html#escaping
492
     *
493
     * @param string $text
494
     * @return string
495
     */
496
    public static function encodeSitemapEntity(string $text): string
497
    {
498
        return Html::encode(UrlHelper::encodeUrl($text));
499
    }
500
501
    /**
502
     * Return the total number of elements in a sitemap, respecting metabundle settings.
503
     *
504
     * @param class-string<SeoElementInterface> $seoElement
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...
505
     * @param MetaBundle $metaBundle
506
     * @return int|null
507
     */
508
    public static function getTotalElementsInSitemap(string $seoElement, MetaBundle $metaBundle): ?int
509
    {
510
        // Allow listeners to modify the query before we use it
511
        $query = $seoElement::sitemapElementsQuery($metaBundle);
512
        $event = new ModifySitemapQueryEvent([
513
            'query' => $query,
514
            'metaBundle' => $metaBundle,
515
        ]);
516
        Event::trigger(self::class, self::EVENT_MODIFY_SITEMAP_QUERY, $event);
517
        $totalElements = $query->count();
518
519
        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...
520
            $totalElements = $metaBundle->metaSitemapVars->sitemapLimit;
521
        }
522
523
        return $totalElements;
524
    }
525
526
    /**
527
     * Combine any per-entry type field settings from $element with the passed in
528
     * $metaBundle
529
     *
530
     * @param SeoElementInterface|string $seoElement
531
     * @param Element $element
532
     * @param MetaBundle $metaBundle
533
     */
534
    protected static function combineEntryTypeSettings($seoElement, Element $element, MetaBundle $metaBundle)
535
    {
536
        if (!empty($seoElement::typeMenuFromHandle($metaBundle->sourceHandle))) {
537
            list($sourceId, $sourceBundleType, $sourceHandle, $sourceSiteId, $typeId)
538
                = Seomatic::$plugin->metaBundles->getMetaSourceFromElement($element);
539
            $entryTypeBundle = Seomatic::$plugin->metaBundles->getMetaBundleBySourceId(
540
                $sourceBundleType,
541
                $sourceId,
542
                $sourceSiteId,
543
                $typeId
544
            );
545
            // Combine in any settings for this entry type
546
            if ($entryTypeBundle) {
547
                // Combine the meta sitemap vars
548
                $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

548
                /** @scrutinizer ignore-call */ 
549
                $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...
549
                $attributes = array_filter(
550
                    $attributes,
551
                    [ArrayHelper::class, 'preserveBools']
552
                );
553
                $metaBundle->metaSitemapVars->setAttributes($attributes, false);
554
555
                // Combine the meta global vars
556
                $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

556
                /** @scrutinizer ignore-call */ 
557
                $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...
557
                $attributes = array_filter(
558
                    $attributes,
559
                    [ArrayHelper::class, 'preserveBools']
560
                );
561
                $metaBundle->metaGlobalVars->setAttributes($attributes, false);
562
            }
563
        }
564
    }
565
566
    /**
567
     * Combine any SEO Settings field settings from $element with the passed in
568
     * $metaBundle
569
     *
570
     * @param Element $element
571
     * @param MetaBundle $metaBundle
572
     */
573
    protected static function combineFieldSettings(Element $element, MetaBundle $metaBundle)
574
    {
575
        $fieldHandles = FieldHelper::fieldsOfTypeFromElement(
576
            $element,
577
            FieldHelper::SEO_SETTINGS_CLASS_KEY,
578
            true
579
        );
580
        foreach ($fieldHandles as $fieldHandle) {
581
            if (!empty($element->$fieldHandle)) {
582
                /** @var SeoSettings $seoSettingsField */
583
                $seoSettingsField = Craft::$app->getFields()->getFieldByHandle($fieldHandle);
584
                /** @var MetaBundle $metaBundle */
585
                $fieldMetaBundle = $element->$fieldHandle;
586
                if ($seoSettingsField !== null) {
587
                    if ($seoSettingsField->sitemapTabEnabled) {
588
                        Seomatic::$plugin->metaBundles->pruneFieldMetaBundleSettings($fieldMetaBundle, $fieldHandle);
589
                        // Combine the meta sitemap vars
590
                        $attributes = $fieldMetaBundle->metaSitemapVars->getAttributes();
591
592
                        // Get the explicitly inherited attributes
593
                        $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

593
                        $inherited = array_keys(/** @scrutinizer ignore-type */ ArrayHelper::remove($attributes, 'inherited', []));
Loading history...
594
595
                        $attributes = array_intersect_key(
596
                            $attributes,
597
                            array_flip((array)$seoSettingsField->sitemapEnabledFields)
598
                        );
599
                        $attributes = array_filter(
600
                            $attributes,
601
                            [ArrayHelper::class, 'preserveBools']
602
                        );
603
604
                        foreach ($inherited as $inheritedAttribute) {
605
                            unset($attributes[$inheritedAttribute]);
606
                        }
607
608
                        $metaBundle->metaSitemapVars->setAttributes($attributes, false);
609
                    }
610
                    // Combine the meta global vars
611
                    $attributes = $fieldMetaBundle->metaGlobalVars->getAttributes();
612
                    $attributes = array_filter(
613
                        $attributes,
614
                        [ArrayHelper::class, 'preserveBools']
615
                    );
616
                    $metaBundle->metaGlobalVars->setAttributes($attributes, false);
617
                }
618
            }
619
        }
620
    }
621
622
    /**
623
     * @param Asset $asset
624
     * @param MetaBundle $metaBundle
625
     * @param array $lines
626
     */
627
    protected static function assetSitemapItem(Asset $asset, MetaBundle $metaBundle, array &$lines)
628
    {
629
        if ((bool)$asset->enabledForSite && $asset->getUrl() !== null) {
630
            switch ($asset->kind) {
631
                case 'image':
632
                    $transform = Craft::$app->getImageTransforms()->getTransformByHandle($metaBundle->metaSitemapVars->sitemapAssetTransform ?? '');
633
                    $lines[] = '<image:image>';
634
                    $lines[] = '<image:loc>';
635
                    $lines[] = self::encodeSitemapEntity(UrlHelper::absoluteUrlWithProtocol($asset->getUrl($transform, true)));
636
                    $lines[] = '</image:loc>';
637
                    // Handle the dynamic field => property mappings
638
                    foreach ($metaBundle->metaSitemapVars->sitemapImageFieldMap as $row) {
639
                        $fieldName = $row['field'] ?? '';
640
                        $propName = $row['property'] ?? '';
641
                        if (!empty($fieldName) && !empty($asset[$fieldName]) && !empty($propName)) {
642
                            $lines[] = '<image:' . $propName . '>';
643
                            $lines[] = self::encodeSitemapEntity($asset[$fieldName]);
644
                            $lines[] = '</image:' . $propName . '>';
645
                        }
646
                    }
647
                    $lines[] = '</image:image>';
648
                    break;
649
650
                case 'video':
651
                    $lines[] = '<video:video>';
652
                    $lines[] = '<video:content_loc>';
653
                    $lines[] = self::encodeSitemapEntity(UrlHelper::absoluteUrlWithProtocol($asset->getUrl()));
654
                    $lines[] = '</video:content_loc>';
655
                    // Handle the dynamic field => property mappings
656
                    foreach ($metaBundle->metaSitemapVars->sitemapVideoFieldMap as $row) {
657
                        $fieldName = $row['field'] ?? '';
658
                        $propName = $row['property'] ?? '';
659
                        if (!empty($fieldName) && !empty($asset[$fieldName]) && !empty($propName)) {
660
                            $lines[] = '<video:' . $propName . '>';
661
                            $lines[] = self::encodeSitemapEntity($asset[$fieldName]);
662
                            $lines[] = '</video:' . $propName . '>';
663
                        }
664
                    }
665
                    $lines[] = '</video:video>';
666
                    break;
667
            }
668
        }
669
    }
670
671
    /**
672
     * @param Asset $asset
673
     * @param MetaBundle $metaBundle
674
     * @param array $lines
675
     */
676
    protected static function assetFilesSitemapLink(Asset $asset, MetaBundle $metaBundle, array &$lines)
677
    {
678
        if ((bool)$asset->enabledForSite && $asset->getUrl() !== null) {
679
            if (in_array($asset->kind, SitemapTemplate::FILE_TYPES, false)) {
680
                $dateUpdated = $asset->dateUpdated ?? $asset->dateCreated ?? new DateTime();
681
                $lines[] = '<url>';
682
                $lines[] = '<loc>';
683
                $lines[] = self::encodeSitemapEntity(UrlHelper::absoluteUrlWithProtocol($asset->getUrl()));
684
                $lines[] = '</loc>';
685
                $lines[] = '<lastmod>';
686
                $lines[] = $dateUpdated->format(DateTime::W3C);
687
                $lines[] = '</lastmod>';
688
                $lines[] = '<changefreq>';
689
                $lines[] = $metaBundle->metaSitemapVars->sitemapChangeFreq;
690
                $lines[] = '</changefreq>';
691
                $lines[] = '<priority>';
692
                $lines[] = $metaBundle->metaSitemapVars->sitemapPriority;
693
                $lines[] = '</priority>';
694
                $lines[] = '</url>';
695
            }
696
        }
697
    }
698
}
699