Passed
Push — release-11.1.x ( 058dc3...7cde52 )
by Rafael
21:11
created

RoutingService::getUrlFacetPathService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
ccs 0
cts 3
cp 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
declare(strict_types=1);
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
namespace ApacheSolrForTypo3\Solr\Routing;
18
19
use ApacheSolrForTypo3\Solr\Routing\Enhancer\SolrRouteEnhancerInterface;
20
use Psr\Http\Message\ServerRequestInterface;
21
use Psr\Http\Message\UriInterface;
22
use Psr\Log\LoggerAwareInterface;
23
use Psr\Log\LoggerAwareTrait;
24
use TYPO3\CMS\Core\Context\Context;
25
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
26
use TYPO3\CMS\Core\Http\Uri;
27
use TYPO3\CMS\Core\Routing\PageSlugCandidateProvider;
28
use TYPO3\CMS\Core\Routing\SiteMatcher;
29
use TYPO3\CMS\Core\Site\Entity\NullSite;
30
use TYPO3\CMS\Core\Site\Entity\Site;
31
use TYPO3\CMS\Core\Site\Entity\SiteInterface;
32
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
33
use TYPO3\CMS\Core\Site\SiteFinder;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
36
/**
37
 * This service class bundles method required to process and manipulate routes.
38
 *
39
 * @author Lars Tode <[email protected]>
40
 */
41
class RoutingService implements LoggerAwareInterface
42
{
43
    use LoggerAwareTrait;
44
45
    /**
46
     * Default plugin namespace
47
     */
48
    const PLUGIN_NAMESPACE = 'tx_solr';
49
50
    /**
51
     * Settings from routing configuration
52
     *
53
     * @var array
54
     */
55
    protected $settings = [];
56
57
    /**
58
     * List of filter that are placed as path arguments
59
     *
60
     * @var array
61
     */
62
    protected $pathArguments = [];
63
64
    /**
65
     * Plugin/extension namespace
66
     *
67
     * @var string
68
     */
69
    protected $pluginNamespace = 'tx_solr';
70
71
    /**
72
     * List of TYPO3 core parameters, that we should ignore
73
     *
74
     * @see \TYPO3\CMS\Frontend\Page\CacheHashCalculator::isCoreParameter
75
     * @var string[]
76
     */
77
    protected $coreParameters = ['no_cache', 'cHash', 'id', 'MP', 'type'];
78
79
    /**
80
     * @var UrlFacetService
81
     */
82
    protected $urlFacetPathService;
83
84
    /**
85
     * @var UrlFacetService
86
     */
87
    protected $urlFacetQueryService;
88
89
    /**
90
     * RoutingService constructor.
91
     *
92
     * @param array $settings
93
     * @param string $pluginNamespace
94
     */
95
    public function __construct(array $settings = [], string $pluginNamespace = self::PLUGIN_NAMESPACE)
96
    {
97
        $this->settings = $settings;
98
        $this->pluginNamespace = $pluginNamespace;
99
        if (empty($this->pluginNamespace)) {
100
            $this->pluginNamespace = self::PLUGIN_NAMESPACE;
101
        }
102
        $this->initUrlFacetService();
103
    }
104
105
    /**
106
     * Creates a clone of the current service and replace the settings inside
107
     *
108
     * @param array $settings
109
     * @return RoutingService
110
     */
111
    public function withSettings(array $settings): RoutingService
112
    {
113
        $service = clone $this;
114
        $service->settings = $settings;
115
        $service->initUrlFacetService();
116
        return $service;
117
    }
118
119
    /**
120
     * Creates a clone of the current service and replace the settings inside
121
     *
122
     * @param array $pathArguments
123
     * @return RoutingService
124
     */
125
    public function withPathArguments(array $pathArguments): RoutingService
126
    {
127
        $service = clone $this;
128
        $service->pathArguments = $pathArguments;
129
        $service->initUrlFacetService();
130
        return $service;
131
    }
132
133
    /**
134
     * Load configuration from routing configuration
135
     *
136
     * @param array $routingConfiguration
137
     * @return $this
138
     */
139
    public function fromRoutingConfiguration(array $routingConfiguration): RoutingService
140
    {
141
        if (empty($routingConfiguration) ||
142
            empty($routingConfiguration['type']) ||
143
            !$this->isRouteEnhancerForSolr((string)$routingConfiguration['type'])) {
144
            return $this;
145
        }
146
147
        if (isset($routingConfiguration['solr'])) {
148
            $this->settings = $routingConfiguration['solr'];
149
            $this->initUrlFacetService();
150
        }
151
152
        if (isset($routingConfiguration['_arguments'])) {
153
            $this->pathArguments = $routingConfiguration['_arguments'];
154
        }
155
156
        return $this;
157
    }
158
159
    /**
160
     * Reset the routing service
161
     *
162
     * @return $this
163
     */
164
    public function reset(): RoutingService
165
    {
166
        $this->settings = [];
167
        $this->pathArguments = [];
168
        $this->pluginNamespace = self::PLUGIN_NAMESPACE;
169
        return $this;
170
    }
171
172
    /**
173
     * Initialize url facet services for different types
174
     *
175
     * @return $this
176
     */
177
    protected function initUrlFacetService(): RoutingService
178
    {
179
        $this->urlFacetPathService = new UrlFacetService('path', $this->settings);
180
        $this->urlFacetQueryService = new UrlFacetService('query', $this->settings);
181
182
        return $this;
183
    }
184
185
    /**
186
     * @return UrlFacetService
187
     */
188
    public function getUrlFacetPathService(): UrlFacetService
189
    {
190
        return $this->urlFacetPathService;
191
    }
192
193
    /**
194
     * @return UrlFacetService
195
     */
196
    public function getUrlFacetQueryService(): UrlFacetService
197
    {
198
        return $this->urlFacetQueryService;
199
    }
200
201
    /**
202
     * Test if the given parameter is a Core parameter
203
     *
204
     * @see \TYPO3\CMS\Frontend\Page\CacheHashCalculator::isCoreParameter
205
     * @param string $parameterName
206
     * @return bool
207
     */
208
    public function isCoreParameter(string $parameterName): bool
209
    {
210
        return in_array($parameterName, $this->coreParameters);
211
    }
212
213
    /**
214
     * This returns the plugin namespace
215
     * @see https://docs.typo3.org/p/apache-solr-for-typo3/solr/master/en-us/Configuration/Reference/TxSolrView.html#pluginnamespace
216
     *
217
     * @return string
218
     */
219
    public function getPluginNamespace(): string
220
    {
221
        return $this->pluginNamespace;
222
    }
223
224
    /**
225
     * Determine if an enhancer is in use for Solr
226
     *
227
     * @param string $enhancerName
228
     * @return bool
229
     */
230
    public function isRouteEnhancerForSolr(string $enhancerName): bool
231
    {
232
        if (empty($enhancerName)) {
233
            return false;
234
        }
235
236
        if (!isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['routing']['enhancers'][$enhancerName])) {
237
            return false;
238
        }
239
        $className = $GLOBALS['TYPO3_CONF_VARS']['SYS']['routing']['enhancers'][$enhancerName];
240
241
        if (!class_exists($className)) {
242
            return false;
243
        }
244
245
        $interfaces = class_implements($className);
246
247
        return in_array(SolrRouteEnhancerInterface::class, $interfaces);
248
    }
249
250
    /**
251
     * Masks Solr filter inside of the query parameters
252
     *
253
     * @param string $uriPath
254
     * @return string
255
     */
256
    public function finalizePathQuery(string $uriPath): string
257
    {
258
        $pathSegments = explode('/', $uriPath);
259
        $query = array_pop($pathSegments);
260
        $queryValues = explode($this->urlFacetPathService->getMultiValueSeparator(), $query);
261
        $queryValues = array_map([$this->urlFacetPathService, 'decodeSingleValue'], $queryValues);
262
        /*
263
         * In some constellations the path query contains the facet type in front.
264
         * This leads to the result, that the query values could contain the same facet value multiple times.
265
         *
266
         * In order to avoid this behaviour, the query values need to be checked and clean up.
267
         * 1. Remove possible prefix information
268
         * 2. Apply character replacements
269
         * 3. Filter duplicate values
270
         */
271
        $queryValuesCount = count($queryValues);
272
        for ($i = 0; $i < $queryValuesCount; $i++) {
273
            $queryValues[$i] = urldecode($queryValues[$i]);
274
            if ($this->containsFacetAndValueSeparator((string)$queryValues[$i])) {
275
                [$facetName, $facetValue] = explode(
276
                    $this->detectFacetAndValueSeparator((string)$queryValues[$i]),
277
                    (string)$queryValues[$i],
278
                    2
279
                );
280
281
                if ($this->isPathArgument((string)$facetName)) {
282
                    $queryValues[$i] = $facetValue;
283
                }
284
285
            }
286
            $queryValues[$i] = $this->urlFacetPathService->applyCharacterMap($queryValues[$i]);
287
        }
288
289
        $queryValues = array_unique($queryValues);
290
        $queryValues = array_map([$this->urlFacetPathService, 'encodeSingleValue'], $queryValues);
291
        sort($queryValues);
292
        $pathSegments[] = implode(
293
            $this->urlFacetPathService->getMultiValueSeparator(),
294
            $queryValues
295
        );
296
        return implode('/', $pathSegments);
297
    }
298
299
    /**
300
     * This method checks if the query parameter should be masked.
301
     *
302
     * @return bool
303
     */
304
    public function shouldMaskQueryParameter(): bool
305
    {
306
        if (!isset($this->settings['query']['mask']) ||
307
            !(bool)$this->settings['query']['mask']) {
308
            return false;
309
        }
310
311
        $targetFields = $this->getQueryParameterMap();
312
313
        return !empty($targetFields);
314
    }
315
316
    /**
317
     * Masks Solr filter inside of the query parameters
318
     *
319
     * @param array $queryParams
320
     * @return array
321
     */
322 1
    public function maskQueryParameters(array $queryParams): array
323
    {
324 1
        if (!$this->shouldMaskQueryParameter()) {
325
            return $queryParams;
326
        }
327
328 1
        if (!isset($queryParams[$this->getPluginNamespace()])) {
329
            $this->logger
330
                ->/** @scrutinizer ignore-call */
331
                error('Mask error: Query parameters has no entry for namespace ' . $this->getPluginNamespace());
332
            return $queryParams;
333
        }
334
335 1
        if (!isset($queryParams[$this->getPluginNamespace()]['filter']) ||
336 1
            empty($queryParams[$this->getPluginNamespace()]['filter'])) {
337
            $this->logger
338
                ->/** @scrutinizer ignore-call */
339
                info('Mask info: Query parameters has no filter in namespace ' . $this->getPluginNamespace());
340
            return $queryParams;
341
        }
342
343 1
        if (!is_array($queryParams[$this->getPluginNamespace()]['filter'])) {
344
            $this->logger
345
                ->/** @scrutinizer ignore-call */
346
                warning('Mask info: Filter within the Query parameters is not an array');
347
            return $queryParams;
348
        }
349
350 1
        $queryParameterMap = $this->getQueryParameterMap();
351 1
        $newQueryParams = $queryParams;
352
353 1
        $newFilterArray = [];
354 1
        foreach ($newQueryParams[$this->getPluginNamespace()]['filter'] as $queryParamName => $queryParamValue) {
355 1
            $defaultSeparator = $this->detectFacetAndValueSeparator((string)$queryParamValue);
356 1
            [$facetName, $facetValue] = explode($defaultSeparator, $queryParamValue, 2);
357 1
            $keep = false;
358 1
            if (isset($queryParameterMap[$facetName]) &&
359 1
                isset($newQueryParams[$queryParameterMap[$facetName]])) {
360
                $this->logger->/** @scrutinizer ignore-call */error(
361
                    'Mask error: Facet "' . $facetName . '" as "' . $queryParameterMap[$facetName] .
362
                    '" already in query!'
363
                );
364
                $keep = true;
365
            }
366 1
            if (!isset($queryParameterMap[$facetName]) || $keep) {
367
                $newFilterArray[] = $queryParamValue;
368
                continue;
369
            }
370
371 1
            $newQueryParams[$queryParameterMap[$facetName]] = $facetValue;
372
        }
373
374 1
        $newQueryParams[$this->getPluginNamespace()]['filter'] = $newFilterArray;
375
376 1
        return $this->cleanUpQueryParameters($newQueryParams);
377
    }
378
379
    /**
380
     * Unmask incoming parameters if needed
381
     *
382
     * @param array $queryParams
383
     * @return array
384
     */
385
    public function unmaskQueryParameters(array $queryParams): array
386
    {
387
        if (!$this->shouldMaskQueryParameter()) {
388
            return $queryParams;
389
        }
390
391
        /*
392
         * The array $queryParameterMap contains the mapping of
393
         * facet name to new url name. In order to unmask we need to switch key and values.
394
         */
395
        $queryParameterMap = $this->getQueryParameterMap();
396
        $queryParameterMapSwitched = [];
397
        foreach ($queryParameterMap as $value => $key) {
398
            $queryParameterMapSwitched[$key] = $value;
399
        }
400
401
        $newQueryParams = [];
402
        foreach ($queryParams as $queryParamName => $queryParamValue) {
403
            // A merge is needed!
404
            if (!isset($queryParameterMapSwitched[$queryParamName])) {
405
                if (isset($newQueryParams[$queryParamName])) {
406
                    $newQueryParams[$queryParamName] = array_merge_recursive(
407
                        $newQueryParams[$queryParamName],
408
                        $queryParamValue
409
                    );
410
                } else {
411
                    $newQueryParams[$queryParamName] = $queryParamValue;
412
                }
413
                continue;
414
            }
415
            if (!isset($newQueryParams[$this->getPluginNamespace()])) {
416
                $newQueryParams[$this->getPluginNamespace()] = [];
417
            }
418
            if (!isset($newQueryParams[$this->getPluginNamespace()]['filter'])) {
419
                $newQueryParams[$this->getPluginNamespace()]['filter'] = [];
420
            }
421
422
            $newQueryParams[$this->getPluginNamespace()]['filter'][] =
423
                $queryParameterMapSwitched[$queryParamName] . ':' . $queryParamValue;
424
        }
425
426
        return $this->cleanUpQueryParameters($newQueryParams);
427
    }
428
429
    /**
430
     * This method check if the query parameters should be touched or not.
431
     *
432
     * There are following requirements:
433
     * - Masking is activated and the mal is valid or
434
     * - Concat is activated
435
     *
436
     * @return bool
437
     */
438
    public function shouldConcatQueryParameters(): bool
439
    {
440
        /*
441
         * The concat will activate automatically if parameters should be masked.
442
         * This solution is less complex since not every mapping parameter needs to be tested
443
         */
444
        if ($this->shouldMaskQueryParameter()) {
445
            return true;
446
        }
447
448
        return isset($this->settings['query']['concat']) && (bool)$this->settings['query']['concat'];
449
    }
450
451
    /**
452
     * Returns the query parameter map
453
     *
454
     * Note TYPO3 core query arguments removed from the configured map!
455
     *
456
     * @return array
457
     */
458
    public function getQueryParameterMap(): array
459
    {
460
        if (!isset($this->settings['query']['map']) ||
461
            !is_array($this->settings['query']['map']) ||
462
            empty($this->settings['query']['map'])) {
463
            return [];
464
        }
465
        // TODO: Test if there is more than one value!
466
        $self = $this;
467
        return array_filter(
468
            $this->settings['query']['map'],
469
            function($value) use ($self) {
470
                return !$self->isCoreParameter($value);
471
            }
472
        );
473
    }
474
475
    /**
476
     * Group all filter values together and concat e
477
     * Note: this will just handle filter values
478
     *
479
     * IN:
480
     * tx_solr => [
481
     *   filter => [
482
     *      color:red
483
     *      product:candy
484
     *      color:blue
485
     *      taste:sour
486
     *   ]
487
     * ]
488
     *
489
     * OUT:
490
     * tx_solr => [
491
     *   filter => [
492
     *      color:blue,red
493
     *      product:candy
494
     *      taste:sour
495
     *   ]
496
     * ]
497
     * @param array $queryParams
498
     * @return array
499
     */
500 1
    public function concatQueryParameter(array $queryParams = []): array
501
    {
502 1
        if (!$this->shouldConcatQueryParameters()) {
503
            return $queryParams;
504
        }
505
506 1
        if (!isset($queryParams[$this->getPluginNamespace()])) {
507
            $this->logger
508
                ->error('Mask error: Query parameters has no entry for namespace ' . $this->getPluginNamespace());
0 ignored issues
show
Bug introduced by
The method error() 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

508
                ->/** @scrutinizer ignore-call */ 
509
                  error('Mask error: Query parameters has no entry for namespace ' . $this->getPluginNamespace());

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...
509
            return $queryParams;
510
        }
511
512 1
        if (!isset($queryParams[$this->getPluginNamespace()]['filter']) ||
513 1
            empty($queryParams[$this->getPluginNamespace()]['filter'])) {
514
            $this->logger
515
                ->info('Mask info: Query parameters has no filter in namespace ' . $this->getPluginNamespace());
516
            return $queryParams;
517
        }
518
519 1
        if (!is_array($queryParams[$this->getPluginNamespace()]['filter'])) {
520
            $this->logger
521
                ->/** @scrutinizer ignore-call */
522
                warning('Mask info: Filter within the Query parameters is not an array');
523
            return $queryParams;
524
        }
525
526 1
        $queryParams[$this->getPluginNamespace()]['filter'] =
527 1
            $this->concatFilterValues($queryParams[$this->getPluginNamespace()]['filter']);
528
529 1
        return $this->cleanUpQueryParameters($queryParams);
530
    }
531
532
    /**
533
     * This method expect a filter array that should be concat instead of the whole query
534
     *
535
     * @param array $filterArray
536
     * @return array
537
     */
538
    public function concatFilterValues(array $filterArray): array
539
    {
540
        if (empty($filterArray) || !$this->shouldConcatQueryParameters()) {
541
            return $filterArray;
542
        }
543
544
        $queryParameterMap = $this->getQueryParameterMap();
545
        $newFilterArray = [];
546
        $defaultSeparator = $this->detectFacetAndValueSeparator((string)$filterArray[0]);
547
        // Collect parameter names and rename parameter if required
548
        foreach ($filterArray as $set) {
549
            $separator = $this->detectFacetAndValueSeparator((string)$set);
550
            [$facetName, $facetValue] = explode($separator, $set, 2);
551
            if (isset($queryParameterMap[$facetName])) {
552
                $facetName = $queryParameterMap[$facetName];
553
            }
554
            if (!isset($newFilterArray[$facetName])) {
555
                $newFilterArray[$facetName] = [$facetValue];
556
            } else {
557
                $newFilterArray[$facetName][] = $facetValue;
558
            }
559
        }
560
561
        foreach ($newFilterArray as $facetName => $facetValues) {
562
            $newFilterArray[$facetName] = $facetName . $defaultSeparator . $this->queryParameterFacetsToString($facetValues);
563
        }
564
565
        return array_values($newFilterArray);
566
    }
567
568
    /**
569
     * Inflate given query parameters if configured
570
     * Note: this will just combine filter values
571
     *
572
     * IN:
573
     * tx_solr => [
574
     *   filter => [
575
     *      color:blue,red
576
     *      product:candy
577
     *      taste:sour
578
     *   ]
579
     * ]
580
     *
581
     * OUT:
582
     * tx_solr => [
583
     *   filter => [
584
     *      color:red
585
     *      product:candy
586
     *      color:blue
587
     *      taste:sour
588
     *   ]
589
     * ]
590
     *
591
     * @param array $queryParams
592
     * @return array
593
     */
594 1
    public function inflateQueryParameter(array $queryParams = []): array
595
    {
596 1
        if (!$this->shouldConcatQueryParameters()) {
597
            return $queryParams;
598
        }
599
600 1
        if (!isset($queryParams[$this->getPluginNamespace()])) {
601
            $queryParams[$this->getPluginNamespace()] = [];
602
        }
603
604 1
        if (!isset($queryParams[$this->getPluginNamespace()]['filter'])) {
605
            $queryParams[$this->getPluginNamespace()]['filter'] = [];
606
        }
607
608 1
        $newQueryParams = [];
609 1
        foreach ($queryParams[$this->getPluginNamespace()]['filter'] as $set) {
610 1
            $separator = $this->detectFacetAndValueSeparator((string)$set);
611 1
            [$facetName, $facetValuesString] = explode($separator, $set, 2);
612 1
            $facetValues = explode($this->urlFacetQueryService->getMultiValueSeparator(), $facetValuesString);
613
614
            /**
615
             * A facet value could contain the multi value separator. This value is masked in order to
616
             * avoid problems during separation of the values (line above).
617
             *
618
             * After splitting the values, the character inside the value need to be restored
619
             *
620
             * @see RoutingService::queryParameterFacetsToString
621
             */
622 1
            $facetValues = array_map([$this->urlFacetQueryService, 'decodeSingleValue'], $facetValues);
623
624 1
            foreach ($facetValues as $facetValue) {
625 1
                $newQueryParams[] = $facetName . $separator . $facetValue;
626
            }
627
        }
628 1
        $queryParams[$this->getPluginNamespace()]['filter'] = array_values($newQueryParams);
629
630 1
        return $this->cleanUpQueryParameters($queryParams);
631
    }
632
633
    /**
634
     * Cleanup the query parameters, to avoid empty solr arguments
635
     *
636
     * @param array $queryParams
637
     * @return array
638
     */
639
    public function cleanUpQueryParameters(array $queryParams): array
640
    {
641
        if (empty($queryParams[$this->getPluginNamespace()]['filter'])) {
642
            unset($queryParams[$this->getPluginNamespace()]['filter']);
643
        }
644
645
        if (empty($queryParams[$this->getPluginNamespace()])) {
646
            unset($queryParams[$this->getPluginNamespace()]);
647
        }
648
        return $queryParams;
649
    }
650
651
    /**
652
     * Builds a string out of multiple facet values
653
     *
654
     * A facet value could contain the multi value separator. This value have to masked in order to
655
     * avoid problems during separation of the values later.
656
     *
657
     * This mask have to apply before contact the values
658
     *
659
     * @param array $facets
660
     * @return string
661
     */
662
    public function queryParameterFacetsToString(array $facets): string
663
    {
664
        $facets = array_map([$this->urlFacetQueryService, 'encodeSingleValue'], $facets);
665
        sort($facets);
666
        return implode($this->urlFacetQueryService->getMultiValueSeparator(), $facets);
667
    }
668
669
    /**
670
     * Returns the string which separates the facet from the value
671
     *
672
     * @param string $facetWithValue
673
     * @return string
674
     */
675
    public function detectFacetAndValueSeparator(string $facetWithValue): string
676
    {
677
        $separator = ':';
678
        if (mb_strpos($facetWithValue, '%3A') !== false) {
679
            $separator = '%3A';
680
        }
681
682
        return $separator;
683
    }
684
685
    /**
686
     * Check if given facet value combination contains a separator
687
     *
688
     * @param string $facetWithValue
689
     * @return bool
690
     */
691
    public function containsFacetAndValueSeparator(string $facetWithValue): bool
692
    {
693
        if (mb_strpos($facetWithValue, ':') === false && mb_strpos($facetWithValue, '%3A') === false) {
694
            return false;
695
        }
696
697
        return true;
698
    }
699
700
    /**
701
     * Cleanup facet values (strip type if needed)
702
     *
703
     * @param array $facetValues
704
     * @return array
705
     */
706
    public function cleanupFacetValues(array $facetValues): array
707
    {
708
        $facetValuesCount = count($facetValues);
709
        for ($i = 0; $i < $facetValuesCount; $i++) {
710
            if (!$this->containsFacetAndValueSeparator((string)$facetValues[$i])) {
711
                continue;
712
            }
713
714
            $separator = $this->detectFacetAndValueSeparator((string)$facetValues[$i]);
715
            [$type, $value] = explode($separator, $facetValues[$i]);
716
717
            if ($this->isMappingArgument($type) || $this->isPathArgument($type)) {
718
                $facetValues[$i] = $value;
719
            }
720
        }
721
        return $facetValues;
722
    }
723
724
    /**
725
     * Builds a string out of multiple facet values
726
     *
727
     * @param array $facets
728
     * @return string
729
     */
730
    public function pathFacetsToString(array $facets): string
731
    {
732
        $facets = $this->cleanupFacetValues($facets);
733
        sort($facets);
734
        $facets = array_map([$this->urlFacetPathService, 'applyCharacterMap'], $facets);
735
        $facets = array_map([$this->urlFacetPathService, 'encodeSingleValue'], $facets);
736
        return implode($this->urlFacetPathService->getMultiValueSeparator(), $facets);
737
    }
738
739
    /**
740
     * Builds a string out of multiple facet values
741
     *
742
     * @param array $facets
743
     * @return string
744
     */
745 2
    public function facetsToString(array $facets): string
746
    {
747 2
        $facets = $this->cleanupFacetValues($facets);
748 2
        sort($facets);
749 2
        return implode($this->getDefaultMultiValueSeparator(), $facets);
750
    }
751
752
    /**
753
     * Builds a string out of multiple facet values
754
     *
755
     * This method is used in two different situation
756
     *  1. Middleware: Here the values should not be decoded
757
     *  2. Within the event listener CachedPathVariableModifier
758
     *
759
     * @param string $facets
760
     * @param bool $decode
761
     * @return array
762
     */
763
    public function pathFacetStringToArray(string $facets, bool $decode = true): array
764
    {
765
        $facetString = $this->urlFacetPathService->applyCharacterMap($facets);
766
        $facets = explode($this->urlFacetPathService->getMultiValueSeparator(), $facetString);
767
        if (!$decode) {
768
            return $facets;
769
        }
770
        return array_map([$this->urlFacetPathService, 'decodeSingleValue'], $facets);
771
    }
772
773
    /**
774
     * Returns the multi value separator
775
     * @return string
776
     */
777 2
    public function getDefaultMultiValueSeparator(): string
778
    {
779 2
        return $this->settings['multiValueSeparator'] ?? ',';
780
    }
781
782
    /**
783
     * Find a enhancer configuration by a given page id
784
     *
785
     * @param int $pageUid
786
     * @return array
787
     */
788
    public function fetchEnhancerByPageUid(int $pageUid): array
789
    {
790
        $site = $this->findSiteByUid($pageUid);
791
        if ($site instanceof NullSite) {
792
            return [];
793
        }
794
795
        return $this->fetchEnhancerInSiteConfigurationByPageUid(
796
            $site,
797
            $pageUid
798
        );
799
    }
800
801
    /**
802
     * Returns the route enhancer configuration by given site and page uid
803
     *
804
     * @param Site $site
805
     * @param int $pageUid
806
     * @return array
807
     */
808
    public function fetchEnhancerInSiteConfigurationByPageUid(Site $site, int $pageUid): array
809
    {
810
        $configuration = $site->getConfiguration();
811
        if (empty($configuration['routeEnhancers']) || !is_array($configuration['routeEnhancers'])) {
812
            return [];
813
        }
814
        $result = [];
815
        foreach ($configuration['routeEnhancers'] as $routing => $settings) {
816
            // Not the page we are looking for
817
            if (isset($settings['limitToPages']) &&
818
                is_array($settings['limitToPages']) &&
819
                !in_array($pageUid, $settings['limitToPages'])) {
820
                continue;
821
            }
822
823
            if (empty($settings) || !isset($settings['type']) ||
824
                !$this->isRouteEnhancerForSolr((string)$settings['type'])
825
            ) {
826
                continue;
827
            }
828
            $result[] = $settings;
829
        }
830
831
        return $result;
832
    }
833
834
    /**
835
     * Add heading slash to given slug
836
     *
837
     * @param string $slug
838
     * @return string
839
     */
840
    public function cleanupHeadingSlash(string $slug): string
841
    {
842
        if (mb_substr($slug, 0, 1) !== '/') {
843
            return '/' . $slug;
844
        } else if (mb_substr($slug, 0, 2) === '//') {
845
            return mb_substr($slug, 1, mb_strlen($slug) - 1);
846
        }
847
848
        return $slug;
849
    }
850
851
    /**
852
     * Add heading slash to given slug
853
     *
854
     * @param string $slug
855
     * @return string
856
     */
857
    public function addHeadingSlash(string $slug): string
858
    {
859
        if (mb_substr($slug, 0, 1) === '/') {
860
            return $slug;
861
        }
862
863
        return '/' . $slug;
864
    }
865
866
    /**
867
     * Remove heading slash from given slug
868
     *
869
     * @param string $slug
870
     * @return string
871
     */
872
    public function removeHeadingSlash(string $slug): string
873
    {
874
        if (mb_substr($slug, 0, 1) !== '/') {
875
            return $slug;
876
        }
877
878
        return mb_substr($slug, 1, mb_strlen($slug) - 1);
879
    }
880
881
    /**
882
     * Retrieve the site by given UID
883
     *
884
     * @param int $pageUid
885
     * @return SiteInterface
886
     */
887
    public function findSiteByUid(int $pageUid): SiteInterface
888
    {
889
        try {
890
            $site = $this->getSiteFinder()
891
                ->getSiteByPageId($pageUid);
892
            return $site;
893
        } catch (SiteNotFoundException $exception) {
894
            return new NullSite();
895
        }
896
    }
897
898
    /**
899
     * @param Site $site
900
     * @return PageSlugCandidateProvider
901
     */
902
    public function getSlugCandidateProvider(Site $site): PageSlugCandidateProvider
903
    {
904
        $context = GeneralUtility::makeInstance(Context::class);
905
        return GeneralUtility::makeInstance(
906
            PageSlugCandidateProvider::class,
907
            $context,
908
            $site,
909
            null
910
        );
911
    }
912
913
    /**
914
     * Convert the base string into a URI object
915
     *
916
     * @param string $base
917
     * @return UriInterface|null
918
     */
919 1
    public function convertStringIntoUri(string $base): ?UriInterface
920
    {
921
        try {
922
            /* @var Uri $uri */
923 1
            $uri = GeneralUtility::makeInstance(
924 1
                Uri::class,
925 1
                $base
926
            );
927
928 1
            return $uri;
929
        } catch (\InvalidArgumentException $argumentException) {
930
            return null;
931
        }
932
    }
933
934
    /**
935
     * In order to search for a path, a possible language prefix need to remove
936
     *
937
     * @param SiteLanguage $language
938
     * @param string $path
939
     * @return string
940
     */
941
    public function stripLanguagePrefixFromPath(SiteLanguage $language, string $path): string
942
    {
943
        if ($language->getBase()->getPath() === '/') {
944
            return $path;
945
        }
946
947
        $pathLength = mb_strlen($language->getBase()->getPath());
948
949
        $path = mb_substr($path, $pathLength, mb_strlen($path) - $pathLength);
950
        if (mb_substr($path, 0, 1) !== '/') {
951
            $path = '/' . $path;
952
        }
953
954
        return $path;
955
    }
956
957
    /**
958
     * Enrich the current query Params with data from path information
959
     *
960
     * @param ServerRequestInterface $request
961
     * @param array $arguments
962
     * @param array $parameters
963
     * @return ServerRequestInterface
964
     */
965 3
    public function addPathArgumentsToQuery(
966
        ServerRequestInterface $request,
967
        array $arguments,
968
        array $parameters
969
    ): ServerRequestInterface {
970 3
        $queryParams = $request->getQueryParams();
971 3
        foreach ($arguments as $fieldName => $queryPath) {
972
            // Skip if there is no parameter
973 3
            if (!isset($parameters[$fieldName])) {
974
                continue;
975
            }
976 3
            $pathElements = explode('/', $queryPath);
977
978 3
            if (!empty($this->pluginNamespace)) {
979 3
                array_unshift($pathElements, $this->pluginNamespace);
980
            }
981
982 3
            $queryParams = $this->processUriPathArgument(
983 3
                $queryParams,
984 3
                $fieldName,
985 3
                $parameters,
986 3
                $pathElements
987
            );
988
        }
989
990 3
        return $request->withQueryParams($queryParams);
991
    }
992
993
    /**
994
     * Check if given argument is a mapping argument
995
     *
996
     * @param string $facetName
997
     * @return bool
998
     */
999
    public function isMappingArgument(string $facetName): bool
1000
    {
1001
        $map = $this->getQueryParameterMap();
1002
        if (isset($map[$facetName]) && $this->shouldMaskQueryParameter()) {
1003
            return true;
1004
        }
1005
1006
        return false;
1007
    }
1008
1009
    /**
1010
     * Check if given facet type is an path argument
1011
     *
1012
     * @param string $facetName
1013
     * @return bool
1014
     */
1015
    public function isPathArgument(string $facetName): bool
1016
    {
1017
        return isset($this->pathArguments[$facetName]);
1018
    }
1019
1020
    /**
1021
     * @param string $variable
1022
     * @return string
1023
     */
1024
    public function reviewVariable(string $variable): string
1025
    {
1026
        if (!$this->containsFacetAndValueSeparator((string)$variable)) {
1027
            return $variable;
1028
        }
1029
1030
        $separator = $this->detectFacetAndValueSeparator((string)$variable);
1031
        [$type, $value] = explode($separator, $variable, 2);
1032
1033
        return $this->isMappingArgument($type) ? $value : $variable;
1034
    }
1035
1036
    /**
1037
     * Remove type prefix from filter
1038
     *
1039
     * @param array $variables
1040
     * @return array
1041
     */
1042
    public function reviseFilterVariables(array $variables): array
1043
    {
1044
        $newVariables = [];
1045
        foreach ($variables as $key => $value) {
1046
            $matches = [];
1047
            if (!preg_match('/###' . $this->getPluginNamespace() . ':filter:\d+:(.+?)###/', $key, $matches)) {
1048
                $newVariables[$key] = $value;
1049
                continue;
1050
            }
1051
            if (!$this->isMappingArgument($matches[1]) && !$this->isPathArgument($matches[1])) {
1052
                $newVariables[$key] = $value;
1053
                continue;
1054
            }
1055
            $separator = $this->detectFacetAndValueSeparator((string)$value);
1056
            $parts = explode($separator, $value);
1057
1058
            do {
1059
                if ($parts[0] === $matches[1]) {
1060
                    array_shift($parts);
1061
                }
1062
            } while ($parts[0] === $matches[1]);
1063
1064
            $newVariables[$key] = implode($separator, $parts);
1065
        }
1066
1067
        return $newVariables;
1068
    }
1069
1070
    /**
1071
     * Converts path segment information into query parameters
1072
     *
1073
     * Example:
1074
     * /products/household
1075
     *
1076
     * tx_solr:
1077
     *      filter:
1078
     *          - type:household
1079
     *
1080
     * @param array $queryParams
1081
     * @param string $fieldName
1082
     * @param array $parameters
1083
     * @param array $pathElements
1084
     * @return array
1085
     */
1086
    protected function processUriPathArgument(
1087
        array $queryParams,
1088
        string $fieldName,
1089
        array $parameters,
1090
        array $pathElements
1091
    ): array {
1092
        $queryKey = array_shift($pathElements);
1093
        $queryKey = (string)$queryKey;
1094
1095
        $tmpQueryKey = $queryKey;
1096
        if (strpos($queryKey, '-') !== false) {
1097
            [$tmpQueryKey, $filterName] = explode('-', $tmpQueryKey, 2);
1098
        }
1099
        if (!isset($queryParams[$tmpQueryKey]) || $queryParams[$tmpQueryKey] === null) {
1100
            $queryParams[$tmpQueryKey] = [];
1101
        }
1102
1103
        if (strpos($queryKey, '-') !== false) {
1104
            [$queryKey, $filterName] = explode('-', $queryKey, 2);
1105
            // explode multiple values
1106
            $values = $this->pathFacetStringToArray($parameters[$fieldName], false);
1107
            sort($values);
1108
1109
            // @TODO: Support URL data bag
1110
            foreach ($values as $value) {
1111
                $value = $this->urlFacetPathService->applyCharacterMap($value);
1112
                $queryParams[$queryKey][] = $filterName . ':' . $value;
1113
            }
1114
        } else {
1115
            $queryParams[$queryKey] = $this->processUriPathArgument(
1116
                $queryParams[$queryKey],
1117
                $fieldName,
1118
                $parameters,
1119
                $pathElements
1120
            );
1121
        }
1122
1123
        return $queryParams;
1124
    }
1125
1126
    /**
1127
     * Return site matcher
1128
     *
1129
     * @return SiteMatcher
1130
     */
1131
    public function getSiteMatcher(): SiteMatcher
1132
    {
1133
        return GeneralUtility::makeInstance(SiteMatcher::class, $this->getSiteFinder());
1134
    }
1135
1136
    /**
1137
     * Returns the site finder
1138
     *
1139
     * @return SiteFinder|null
1140
     */
1141
    protected function getSiteFinder(): ?SiteFinder
1142
    {
1143
        return GeneralUtility::makeInstance(SiteFinder::class);
1144
    }
1145
}
1146