Passed
Push — main ( b7a629...b09cce )
by Rafael
34:19
created

RoutingService::removeHeadingSlash()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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