Failed Conditions
Push — release-11.5.x ( 71e6eb...3bfdb1 )
by Markus
27:37
created

OptionCollection::getByLowercaseLabelPrefix()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 8
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the TYPO3 CMS project.
7
 *
8
 * It is free software; you can redistribute it and/or modify it under
9
 * the terms of the GNU General Public License, either version 2
10
 * of the License, or any later version.
11
 *
12
 * For the full copyright and license information, please read the
13
 * LICENSE.txt file that was distributed with this source code.
14
 *
15
 * The TYPO3 project - inspiring people to share!
16
 */
17
18
namespace ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Facets\OptionBased;
19
20
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Facets\AbstractFacetItemCollection;
21
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Facets\OptionBased\Options\Option;
22
23
/**
24
 * Collection for facet options.
25
 *
26
 * @author Frans Saris <[email protected]>
27
 * @author Timo Hund <[email protected]>
28
 */
29
class OptionCollection extends AbstractFacetItemCollection
30
{
31
    /**
32
     * Returns an array of prefixes from the option labels.
33
     *
34
     * Red, Blue, Green => r, g, b
35
     *
36
     * Can be used in combination with getByPrefix() to group facet options by prefix (e.g. alphabetical).
37
     *
38
     * @param int $length
39
     * @return array
40
     */
41
    public function getLowercaseLabelPrefixes(int $length = 1): array
42
    {
43
        $prefixes = $this->getLabelPrefixes($length);
44
        return array_map('mb_strtolower', $prefixes);
45
    }
46
47
    /**
48
     * @param string $filteredPrefix
49
     * @return AbstractFacetItemCollection|OptionCollection
50
     */
51
    public function getByLowercaseLabelPrefix(string $filteredPrefix): OptionCollection
52
    {
53
        /** @noinspection PhpIncompatibleReturnTypeInspection */
54
        return $this->getFilteredCopy(function (Option $option) use ($filteredPrefix) {
55
            $filteredPrefixLength = mb_strlen($filteredPrefix);
56
            $currentPrefix = mb_substr(mb_strtolower($option->getLabel()), 0, $filteredPrefixLength);
57
58
            return $currentPrefix === $filteredPrefix;
59
        });
60
    }
61
62
    /**
63
     * @param int $length
64
     * @return array
65
     */
66
    protected function getLabelPrefixes(int $length = 1): array
67
    {
68
        $prefixes = [];
69
        foreach ($this->data as $option) {
70
            /** @var $option Option */
71
            $prefix = mb_substr($option->getLabel(), 0, $length);
72
            $prefixes[$prefix] = $prefix;
73
        }
74
75
        return array_values($prefixes);
76
    }
77
}
78