Completed
Push — master ( 2bc4b1...eec5d7 )
by Timo
40s
created

SearchRequest::getContextSystemLanguageUid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace ApacheSolrForTypo3\Solr\Domain\Search;
4
5
/***************************************************************
6
 *  Copyright notice
7
 *
8
 *  (c) 2015-2016 Timo Schmidt <[email protected]>
9
 *  All rights reserved
10
 *
11
 *  This script is part of the TYPO3 project. The TYPO3 project is
12
 *  free software; you can redistribute it and/or modify
13
 *  it under the terms of the GNU General Public License as published by
14
 *  the Free Software Foundation; either version 2 of the License, or
15
 *  (at your option) any later version.
16
 *
17
 *  The GNU General Public License can be found at
18
 *  http://www.gnu.org/copyleft/gpl.html.
19
 *
20
 *  This script is distributed in the hope that it will be useful,
21
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 *  GNU General Public License for more details.
24
 *
25
 *  This copyright notice MUST APPEAR in all copies of the script!
26
 ***************************************************************/
27
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
28
use ApacheSolrForTypo3\Solr\System\Util\ArrayAccessor;
29
use TYPO3\CMS\Core\Utility\ArrayUtility;
30
31
/**
32
 * The searchRequest is used to act as an api to the arguments that have been passed
33
 * with GET and POST.
34
 *
35
 * @author Timo Schmidt <[email protected]>
36
 */
37
class SearchRequest
38
{
39
    /**
40
     * @var string
41
     */
42
    protected $id;
43
44
    /**
45
     * @var string
46
     */
47
    protected $argumentNameSpace = 'tx_solr';
48
49
    /**
50
     * Arguments that should be kept for sub requests.
51
     *
52
     * @var array
53
     */
54
    protected $persistentArgumentsPaths = array('q', 'tx_solr:filter', 'tx_solr:sort');
55
56
    /**
57
     * @var bool
58
     */
59
    protected $stateChanged = false;
60
61
    /**
62
     * @var ArrayAccessor
63
     */
64
    protected $argumentsAccessor;
65
66
    /**
67
     * The sys_language_uid that was used in the context where the request was build.
68
     * This could be different from the "L" parameter and and not relevant for urls,
69
     * because typolink itself will handle it.
70
     *
71
     * @var int
72
     */
73
    protected $contextSystemLanguageUid;
74
75
    /**
76
     * The page_uid that was used in the context where the request was build.
77
     *
78
     * The pageUid is not relevant for the typolink additionalArguments and therefore
79
     * a separate property.
80
     *
81
     * @var int
82
     */
83
    protected $contextPageUid;
84
85
    /**
86
     * @var TypoScriptConfiguration
87
     */
88
    protected $contextTypoScriptConfiguration;
89
90
    /**
91
     * @param array $argumentsArray
92
     * @param int $pageUid
93
     * @param int $sysLanguageUid
94
     * @param TypoScriptConfiguration $typoScriptConfiguration
95
     */
96 56
    public function __construct(array $argumentsArray = array(), $pageUid = 0, $sysLanguageUid = 0, TypoScriptConfiguration $typoScriptConfiguration = null)
97
    {
98 56
        $this->stateChanged = true;
99 56
        $this->persistedArguments = $argumentsArray;
0 ignored issues
show
Bug introduced by
The property persistedArguments does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
100 56
        $this->contextPageUid = $pageUid;
101 56
        $this->contextSystemLanguageUid = $sysLanguageUid;
102 56
        $this->contextTypoScriptConfiguration = $typoScriptConfiguration;
103 56
        $this->id = spl_object_hash($this);
104 56
        $this->reset();
105 56
    }
106
107
    /**
108
     * @return string
109
     */
110 1
    public function getId()
111
    {
112 1
        return $this->id;
113
    }
114
115
    /**
116
     * Can be used do merge arguments into the request arguments
117
     *
118
     * @param array $argumentsToMerge
119
     * @return SearchRequest
120
     */
121 24
    public function mergeArguments(array $argumentsToMerge)
122
    {
123 24
        ArrayUtility::mergeRecursiveWithOverrule(
124 24
            $this->persistedArguments,
125
            $argumentsToMerge
126 24
        );
127
128 24
        $this->reset();
129
130 24
        return $this;
131
    }
132
133
    /**
134
     * Helper method to prefix an accessor with the arguments namespace.
135
     *
136
     * @param $path
137
     * @return string
138
     */
139 47
    protected function prefixWithNamespace($path)
140
    {
141 47
        return $this->argumentNameSpace . ':' . $path;
142
    }
143
144
    /**
145
     * @return array
146
     */
147 1
    public function getActiveFacetNames()
148
    {
149 1
        $activeFacets = $this->getActiveFacets();
150 1
        $facetNames = array();
151 1
        foreach ($activeFacets as $activeFacet) {
0 ignored issues
show
Bug introduced by
The expression $activeFacets of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
152 1
            $facetName = explode(':', $activeFacet, 2);
153 1
            $facetNames[] = $facetName[0];
154 1
        }
155
156 1
        return $facetNames;
157
    }
158
159
    /**
160
     * Returns all facet values for a certain facetName
161
     * @param string $facetName
162
     * @return array
163
     */
164 1
    public function getActiveFacetValuesByName($facetName)
165
    {
166 1
        $values = [];
167 1
        $activeFacets = $this->getActiveFacets();
168 1
        foreach ($activeFacets as $activeFacet) {
0 ignored issues
show
Bug introduced by
The expression $activeFacets of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
169 1
            $parts = explode(':', $activeFacet, 2);
170 1
            if ($parts[0] !== $facetName) {
171
                continue;
172
            }
173 1
            $values[] = $parts[1];
174 1
        }
175
176 1
        return $values;
177
    }
178
179
    /**
180
     * @return array|null
181
     */
182 11
    protected function getActiveFacets()
183
    {
184 11
        $path = $this->prefixWithNamespace('filter');
185 11
        return $this->argumentsAccessor->get($path, array());
186
    }
187
188
    /**
189
     * @return int
190
     */
191 2
    public function getActiveFacetCount()
192
    {
193 2
        return count($this->getActiveFacets());
194
    }
195
196
    /**
197
     * @param $activeFacets
198
     * @return array|null
199
     *
200
     * @return SearchRequest
201
     */
202 8
    protected function setActiveFacets($activeFacets = array())
203
    {
204 8
        $path = $this->prefixWithNamespace('filter');
205 8
        $this->argumentsAccessor->set($path, $activeFacets);
206
207 8
        return $this;
208
    }
209
210
    /**
211
     * Adds a facet value to the request.
212
     *
213
     * @param string $facetName
214
     * @param mixed $facetValue
215
     *
216
     * @return SearchRequest
217
     */
218 6
    public function addFacetValue($facetName, $facetValue)
219
    {
220 6
        if ($this->getHasFacetValue($facetName, $facetValue)) {
221
            return $this;
222
        }
223
224 6
        $facetValues = $this->getActiveFacets();
225 6
        $facetValues[] = $facetName . ':' . $facetValue;
226 6
        $this->setActiveFacets($facetValues);
227
228 6
        $this->stateChanged = true;
229 6
        return $this;
230
    }
231
232
    /**
233
     * Removes a facet value from the request.
234
     *
235
     * @param string $facetName
236
     * @param mixed $facetValue
237
     *
238
     * @return SearchRequest
239
     */
240 1
    public function removeFacetValue($facetName, $facetValue)
241
    {
242 1
        if (!$this->getHasFacetValue($facetName, $facetValue)) {
243
            return $this;
244
        }
245 1
        $facetValues = $this->getActiveFacets();
246 1
        $facetValueToLookFor = $facetName . ':' . $facetValue;
247
248 1
        foreach ($facetValues as $index => $facetValue) {
0 ignored issues
show
Bug introduced by
The expression $facetValues of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
249 1
            if ($facetValue === $facetValueToLookFor) {
250 1
                unset($facetValues[$index]);
251 1
                break;
252
            }
253 1
        }
254
255 1
        $this->setActiveFacets($facetValues);
0 ignored issues
show
Bug introduced by
It seems like $facetValues defined by $this->getActiveFacets() on line 245 can also be of type null; however, ApacheSolrForTypo3\Solr\...uest::setActiveFacets() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
256 1
        $this->stateChanged = true;
257 1
        return $this;
258
    }
259
260
    /**
261
     * Removes all facet values from the request by a certain facet name
262
     *
263
     * @param string $facetName
264
     *
265
     * @return SearchRequest
266
     */
267 1
    public function removeAllFacetValuesByName($facetName)
268
    {
269 1
        $facetValues = $this->getActiveFacets();
270
271 1
        foreach ($facetValues as $index => $facetValue) {
0 ignored issues
show
Bug introduced by
The expression $facetValues of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
272 1
            $parts = explode(':', $facetValue, 2);
273 1
            if ($parts[0] === $facetName) {
274
                // a facet for the request facet name was found, so we unset it.
275 1
                unset($facetValues[$index]);
276 1
            }
277 1
        }
278
279 1
        $this->setActiveFacets($facetValues);
0 ignored issues
show
Bug introduced by
It seems like $facetValues defined by $this->getActiveFacets() on line 269 can also be of type null; however, ApacheSolrForTypo3\Solr\...uest::setActiveFacets() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
280 1
        $this->stateChanged = true;
281 1
        return $this;
282
    }
283
284
    /**
285
     * Removes all active facets from the request.
286
     *
287
     * @return SearchRequest
288
     */
289 1
    public function removeAllFacets()
290
    {
291 1
        $path = $this->prefixWithNamespace('filter');
292 1
        $this->argumentsAccessor->reset($path);
293 1
        $this->stateChanged = true;
294 1
        return $this;
295
    }
296
297
    /**
298
     * @param string $facetName
299
     * @param mixed $facetValue
300
     * @return bool
301
     */
302 7
    public function getHasFacetValue($facetName, $facetValue)
303
    {
304 7
        $facetNameAndValueToCheck = $facetName . ':' . $facetValue;
305 7
        foreach ($this->getActiveFacets() as $activeFacet) {
0 ignored issues
show
Bug introduced by
The expression $this->getActiveFacets() of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
306 2
            if ($activeFacet == $facetNameAndValueToCheck) {
307 1
                return true;
308
            }
309 7
        }
310
311 7
        return false;
312
    }
313
314
    /**
315
     * @return bool
316
     */
317 3
    public function getHasSorting()
318
    {
319 3
        $path = $this->prefixWithNamespace('sort');
320 3
        return $this->argumentsAccessor->has($path);
321
    }
322
323
    /**
324
     * Returns the sorting string in the url e.g. title asc.
325
     *
326
     * @return string|null
327
     */
328 2
    protected function getSorting()
329
    {
330 2
        $path = $this->prefixWithNamespace('sort');
331 2
        return $this->argumentsAccessor->get($path);
332
    }
333
334
    /**
335
     * Helper function to get the sorting configuration name or direction.
336
     *
337
     * @param $index
338
     * @return null
339
     */
340 2
    protected function getSortingPart($index)
341
    {
342 2
        $sorting = $this->getSorting();
343 2
        if ($sorting === null) {
344
            return null;
345
        }
346
347 2
        $parts = explode(' ', $sorting);
348 2
        return isset($parts[$index]) ? $parts[$index] : null;
349
    }
350
351
    /**
352
     * Returns the sorting configuration name that is currently used.
353
     *
354
     * @return string
355
     */
356 2
    public function getSortingName()
357
    {
358 2
        return $this->getSortingPart(0);
359
    }
360
361
    /**
362
     * Returns the sorting direction that is currently used.
363
     *
364
     * @return string
365
     */
366 1
    public function getSortingDirection()
367
    {
368 1
        return strtolower($this->getSortingPart(1));
369
    }
370
371
    /**
372
     * @return SearchRequest
373
     */
374 1
    public function removeSorting()
375
    {
376 1
        $path = $this->prefixWithNamespace('sort');
377 1
        $this->argumentsAccessor->reset($path, null);
0 ignored issues
show
Unused Code introduced by
The call to ArrayAccessor::reset() has too many arguments starting with null.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
378 1
        $this->stateChanged = true;
379 1
        return $this;
380
    }
381
382
    /**
383
     * @param string $sortingName
384
     * @param string $direction (asc or desc)
385
     *
386
     * @return SearchRequest
387
     */
388 1
    public function setSorting($sortingName, $direction = 'asc')
389
    {
390 1
        $value = $sortingName . ' ' . $direction;
391 1
        $path = $this->prefixWithNamespace('sort');
392 1
        $this->argumentsAccessor->set($path, $value);
393 1
        $this->stateChanged = true;
394 1
        return $this;
395
    }
396
397
    /**
398
     * Method to set the paginated page of the search
399
     *
400
     * @param int $page
401
     * @return SearchRequest
402
     */
403 1
    public function setPage($page)
404
    {
405 1
        $this->stateChanged = true;
406 1
        $path = $this->prefixWithNamespace('page');
407 1
        $this->argumentsAccessor->set($path, $page);
408 1
        return $this;
409
    }
410
411
    /**
412
     * Returns the passed page.
413
     *
414
     * @return int|null
415
     */
416 32
    public function getPage()
417
    {
418 32
        $path = $this->prefixWithNamespace('page');
419 32
        return $this->argumentsAccessor->get($path);
420
    }
421
422
    /**
423
     * Method to overwrite the query string.
424
     *
425
     * @param string $rawQueryString
426
     * @return SearchRequest
427
     */
428 9
    public function setRawQueryString($rawQueryString)
429
    {
430 9
        $this->stateChanged = true;
431 9
        $this->argumentsAccessor->set('q', $rawQueryString);
432 9
        return $this;
433
    }
434
435
    /**
436
     * Returns the passed rawQueryString.
437
     *
438
     * @return int|string
439
     */
440 31
    public function getRawUserQuery()
441
    {
442 31
        return $this->argumentsAccessor->get('q');
443
    }
444
445
    /**
446
     * Method to check if the query string is an empty string
447
     * (also empty string or whitespaces only are handled as empty).
448
     *
449
     * When no query string is set (null) the method returns false.
450
     * @return bool
451
     */
452 33
    public function getRawUserQueryIsEmptyString()
453
    {
454 33
        $query = $this->argumentsAccessor->get('q', null);
455
456 33
        if ($query === null) {
457 2
            return false;
458
        }
459
460 31
        if (trim($query) === '') {
461 4
            return true;
462
        }
463
464 27
        return false;
465
    }
466
467
    /**
468
     * This method returns true when no querystring is present at all.
469
     * Which means no search by the user was triggered
470
     *
471
     * @return bool
472
     */
473 33
    public function getRawUserQueryIsNull()
474
    {
475 33
        $query = $this->argumentsAccessor->get('q', null);
476 33
        return $query === null;
477
    }
478
479
    /**
480
     * Sets the results per page that are used during search.
481
     *
482
     * @param int $resultsPerPage
483
     * @return SearchRequest
484
     */
485 1
    public function setResultsPerPage($resultsPerPage)
486
    {
487 1
        $path = $this->prefixWithNamespace('resultsPerPage');
488 1
        $this->argumentsAccessor->set($path, $resultsPerPage);
489 1
        $this->stateChanged = true;
490
491 1
        return $this;
492
    }
493
494
    /**
495
     * @return bool
496
     */
497 1
    public function getStateChanged()
498
    {
499 1
        return $this->stateChanged;
500
    }
501
502
    /**
503
     * Returns the passed resultsPerPage value
504
     * @return int|null
505
     */
506 30
    public function getResultsPerPage()
507
    {
508 30
        $path = $this->prefixWithNamespace('resultsPerPage');
509 30
        return $this->argumentsAccessor->get($path);
510
    }
511
512
    /**
513
     * @return int
514
     */
515 1
    public function getContextSystemLanguageUid()
516
    {
517 1
        return $this->contextSystemLanguageUid;
518
    }
519
520
    /**
521
     * @return int
522
     */
523 2
    public function getContextPageUid()
524
    {
525 2
        return $this->contextPageUid;
526
    }
527
528
    /**
529
     * Get contextTypoScriptConfiguration
530
     *
531
     * @return TypoScriptConfiguration
532
     */
533 2
    public function getContextTypoScriptConfiguration()
534
    {
535 2
        return $this->contextTypoScriptConfiguration;
536
    }
537
538
    /**
539
     * Assigns the last known persistedArguments and restores their state.
540
     *
541
     * @return SearchRequest
542
     */
543 56
    public function reset()
544
    {
545 56
        $this->argumentsAccessor = new ArrayAccessor($this->persistedArguments);
546 56
        $this->stateChanged = false;
547 56
        return $this;
548
    }
549
550
    /**
551
     * This can be used to start a new sub request, e.g. for a faceted search.
552
     *
553
     * @param bool $onlyPersistentArguments
554
     * @return SearchRequest
555
     */
556 2
    public function getCopyForSubRequest($onlyPersistentArguments = true)
557
    {
558 2
        $argumentsArray = $this->argumentsAccessor->getData();
559 2
        if ($onlyPersistentArguments) {
560 2
            $arguments = new ArrayAccessor();
561 2
            foreach ($this->persistentArgumentsPaths as $persistentArgumentPath) {
562 2
                if ($this->argumentsAccessor->has($persistentArgumentPath)) {
563 2
                    $arguments->set($persistentArgumentPath, $this->argumentsAccessor->get($persistentArgumentPath));
564 2
                }
565 2
            }
566
567 2
            $argumentsArray = $arguments->getData();
568 2
        }
569
570 2
        return new SearchRequest($argumentsArray);
571
    }
572
573
    /**
574
     * @return array
575
     */
576 8
    public function getAsArray()
577
    {
578 8
        return $this->argumentsAccessor->getData();
579
    }
580
}
581