Completed
Pull Request — develop (#284)
by
unknown
09:13
created

Facets::assertValidName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 * @author Miroslav Fedeleš <[email protected]>
9
 * @since 0.27
10
 */
11
12
namespace Solr;
13
14
use IteratorAggregate;
15
use Countable;
16
use ArrayIterator;
17
use ArrayAccess;
18
use InvalidArgumentException;
19
use SolrDisMaxQuery;
20
use SolrUtils;
21
22
class Facets implements IteratorAggregate, Countable
23
{
24
    
25
    const TYPE_FIELD = 'facet_fields';
26
    
27
    /**
28
     * @var ArrayAccess
29
     */
30
    protected $facetResult;
31
    
32
    /**
33
     * @var array
34
     */
35
    protected $params = [];
36
    
37
    /**
38
     * @var array
39
     */
40
    protected $definitions = [];
41
    
42
    /**
43
     * @var array
44
     */
45
    protected $queryMethodMap = [
46
        'facet_fields' => 'addFacetField'
47
    ];
48
    
49
    /**
50
     * @var array
51
     */
52
    protected $cache;
53
54
    /**
55
     * @param string $name
56
     * @param string $title
57
     * @param string $type
58
     * @return Facets
59
     */
60
    public function addDefinition($name, $title, $type = self::TYPE_FIELD)
61
    {
62
        if (!isset($this->queryMethodMap[$type])) {
63
            throw new InvalidArgumentException(sprintf('invalid type "%s"', $type));
64
        }
65
        
66
        $this->definitions[$name] = [
67
            'type' => $type,
68
            'title' => $title
69
        ];
70
        
71
        return $this;
72
    }
73
74
    /**
75
	 * @see IteratorAggregate::getIterator()
76
	 */
77
	public function getIterator()
78
	{
79
		return new ArrayIterator($this->toArray());
80
		
81
	}
82
83
    /**
84
	 * @see Countable::count()
85
	 */
86
	public function count()
87
	{
88
		return count($this->toArray());
89
	}
90
91
    /**
92
     * @return array
93
     */
94
    public function toArray()
95
    {
96
        if (!isset($this->cache)) {
97
            $this->cache = [];
98
            
99
            foreach ($this->definitions as $name => $definition) {
100
                // check if the facet definition exists in the facet result
101
                if (!isset($this->facetResult[$definition['type']])
102
                    || !isset($this->facetResult[$definition['type']][$name])
103
                ) {
104
                    continue;
105
                }
106
                
107
                // cast to array to workaround the 'Notice: Illegal member variable name' for PHP <= 5.6.20
108
                $result = (array)$this->facetResult[$definition['type']][$name];
109
                // remove empty value
110
                unset($result['']);
111
                
112
                $this->cache[$name] = $result;
113
            }
114
        }
115
        
116
        return $this->cache;
117
    }
118
    
119
    /**
120
     * @param ArrayAccess $facetResult
121
     * @return Facets
122
     */
123
    public function setFacetResult(ArrayAccess $facetResult)
124
    {
125
        $this->facetResult = $facetResult;
126
        $this->cache = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $cache.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
127
        
128
        return $this;
129
    }
130
    /**
131
	 * @param array $params
132
	 * @return Facets
133
	 */
134
	public function setParams(array $params)
135
	{
136
		$this->params = $params;
137
		
138
		return $this;
139
	}
140
141
    /**
142
     * @param SolrDisMaxQuery $query
143
     * @return Facets
144
     */
145
    public function setupQuery(SolrDisMaxQuery $query)
146
    {
147
        $query->setFacet(true);
148
        
149
        foreach ($this->definitions as $name => $definition) {
150
            $tag = sprintf('tag-%s', $name);
151
            $method = $this->queryMethodMap[$definition['type']];
152
            $query->$method(sprintf('{!ex=%s}%s', $tag, $name));
153
            
154
            if (isset($this->params[$name]) && is_array($this->params[$name])) {
155
                $valueList = array_filter(array_map(function ($value) {
156
                    return trim(SolrUtils::escapeQueryChars($value));
157
                }, array_keys($this->params[$name])));
158
                
159
                if ($valueList) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $valueList of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
160
                    $query->addFilterQuery(sprintf('{!tag=%s}%s:(%s)', $tag, $name, implode(' OR ', $valueList)));
161
                }
162
            }
163
        }
164
        
165
        return $this;
166
    }
167
    
168
    /**
169
     * @param string $name
170
     * @param string $value
171
     * @return boolean
172
     * @throws InvalidArgumentException
173
     */
174
    public function isValueActive($name, $value)
175
    {
176
        $this->assertValidName($name);
177
        
178
        return isset($this->params[$name])
179
            && is_array($this->params[$name])
180
            && isset($this->params[$name][$value]);
181
    }
182
    
183
    /**
184
     * @return array
185
     */
186
    public function getActiveValues()
187
    {
188
        $return = [];
189
        
190
        foreach ($this->toArray() as $name => $values) {
191
            if (isset($this->params[$name])
192
                && is_array($this->params[$name])
193
                && $this->params[$name]
194
            ) {
195
                $activeValues = [];
196
                
197
                foreach ($values as $value => $count) {
198
                    if (isset($this->params[$name][$value])) {
199
                        $activeValues[] = $value;
200
                    }
201
                }
202
                
203
                if ($activeValues) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $activeValues of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
204
                    $return[$name] = $activeValues;
205
                }
206
            }
207
        }
208
        
209
        return $return;
210
    }
211
    
212
    /**
213
     * @param string $name
214
     * @return string Non-translated title
215
     * @throws InvalidArgumentException
216
     */
217
    public function getTitle($name)
218
    {
219
        $this->assertValidName($name);
220
        
221
        return $this->definitions[$name]['title'];
222
    }
223
    
224
    /**
225
     * @param string $name
226
     * @throws InvalidArgumentException
227
     */
228
    protected function assertValidName($name)
229
    {
230
        if (! isset($this->definitions[$name])) {
231
            throw new InvalidArgumentException();
232
        }
233
    }
234
}