Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
75.00% covered (warning)
75.00%
87 / 116
68.75% covered (warning)
68.75%
11 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
SideFacets
75.00% covered (warning)
75.00%
87 / 116
68.75% covered (warning)
68.75%
11 / 16
110.56
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 setConfig
91.11% covered (success)
91.11%
41 / 45
0.00% covered (danger)
0.00%
0 / 1
18.23
 init
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
5.07
 getCheckboxFacetSet
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getFacetSet
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 getDateFacets
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFullDateFacets
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getGenericRangeFacets
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getNumericRangeFacets
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getAllRangeFacets
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
3
 getCollapsedFacets
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 getShowMoreSetting
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
30
 getShowInLightboxSetting
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 getRangeFacets
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
9
 getHierarchicalFacets
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getHierarchicalFacetSortOptions
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3/**
4 * SideFacets Recommendations Module
5 *
6 * PHP version 8
7 *
8 * Copyright (C) Villanova University 2010.
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2,
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
22 *
23 * @category VuFind
24 * @package  Recommendations
25 * @author   Demian Katz <demian.katz@villanova.edu>
26 * @author   Juha Luoma <juha.luoma@helsinki.fi>
27 * @license  http://opensource.org/licenses/gpl-2.0.php GNU General Public License
28 * @link     https://vufind.org/wiki/development:plugins:recommendation_modules Wiki
29 */
30
31namespace VuFind\Recommend;
32
33use VuFind\Search\Solr\HierarchicalFacetHelper;
34use VuFind\Solr\Utils as SolrUtils;
35
36use function get_class;
37use function in_array;
38use function intval;
39use function is_array;
40
41/**
42 * SideFacets Recommendations Module
43 *
44 * This class provides recommendations displaying facets beside search results
45 *
46 * @category VuFind
47 * @package  Recommendations
48 * @author   Demian Katz <demian.katz@villanova.edu>
49 * @author   Juha Luoma <juha.luoma@helsinki.fi>
50 * @license  http://opensource.org/licenses/gpl-2.0.php GNU General Public License
51 * @link     https://vufind.org/wiki/development:plugins:recommendation_modules Wiki
52 */
53class SideFacets extends AbstractFacets
54{
55    /**
56     * Year-only date facet configuration
57     *
58     * @var array
59     */
60    protected $dateFacets = [];
61
62    /**
63     * Day/month/year date facet configuration
64     *
65     * @var array
66     */
67    protected $fullDateFacets = [];
68
69    /**
70     * Generic range facet configuration
71     *
72     * @var array
73     */
74    protected $genericRangeFacets = [];
75
76    /**
77     * Numeric range facet configuration
78     *
79     * @var array
80     */
81    protected $numericRangeFacets = [];
82
83    /**
84     * Main facet configuration
85     *
86     * @var array
87     */
88    protected $mainFacets = [];
89
90    /**
91     * Checkbox facet configuration
92     *
93     * @var array
94     */
95    protected $checkboxFacets = [];
96
97    /**
98     * Should we display dynamically-generated checkbox facets that are not
99     * explicitly configured in $checkboxFacets?
100     *
101     * @var bool
102     */
103    protected $showDynamicCheckboxFacets = true;
104
105    /**
106     * Settings controlling how lightbox is used for facet display.
107     *
108     * @var bool|string
109     */
110    protected $showInLightboxSettings = [];
111
112    /**
113     * Settings controlling how many values to display before "show more."
114     *
115     * @var array
116     */
117    protected $showMoreSettings = [];
118
119    /**
120     * Collapsed facet setting
121     *
122     * @var bool|string
123     */
124    protected $collapsedFacets = false;
125
126    /**
127     * Hierarchical facet setting
128     *
129     * @var array
130     */
131    protected $hierarchicalFacets = [];
132
133    /**
134     * Hierarchical facet sort options
135     *
136     * @var array
137     */
138    protected $hierarchicalFacetSortOptions = [];
139
140    /**
141     * Hierarchical facet helper
142     *
143     * @var HierarchicalFacetHelper
144     */
145    protected $hierarchicalFacetHelper;
146
147    /**
148     * Constructor
149     *
150     * @param \VuFind\Config\PluginManager $configLoader Configuration loader
151     * @param HierarchicalFacetHelper      $facetHelper  Helper for handling
152     * hierarchical facets
153     */
154    public function __construct(
155        \VuFind\Config\PluginManager $configLoader,
156        HierarchicalFacetHelper $facetHelper = null
157    ) {
158        parent::__construct($configLoader);
159        $this->hierarchicalFacetHelper = $facetHelper;
160    }
161
162    /**
163     * Store the configuration of the recommendation module.
164     *
165     * @param string $settings Settings from searches.ini.
166     *
167     * @return void
168     */
169    public function setConfig($settings)
170    {
171        // Parse the additional settings:
172        $settings = explode(':', $settings);
173        $mainSection = empty($settings[0]) ? 'Results' : $settings[0];
174        $checkboxSection = $settings[1] ?? false;
175        $iniName = $settings[2] ?? 'facets';
176        $showDynamicCheckboxFacets = $settings[3] ?? true;
177
178        // Load the desired facet information...
179        $config = $this->configLoader->get($iniName);
180
181        // All standard facets to display:
182        $this->mainFacets = isset($config->$mainSection) ?
183            $config->$mainSection->toArray() : [];
184
185        // Load boolean configurations:
186        $this->loadBooleanConfigs($config, array_keys($this->mainFacets));
187
188        // Get a list of fields that should be displayed as ranges rather than
189        // standard facet lists.
190        if (isset($config->SpecialFacets->dateRange)) {
191            $this->dateFacets = $config->SpecialFacets->dateRange->toArray();
192        }
193        if (isset($config->SpecialFacets->fullDateRange)) {
194            $this->fullDateFacets = $config->SpecialFacets->fullDateRange->toArray();
195        }
196        if (isset($config->SpecialFacets->genericRange)) {
197            $this->genericRangeFacets
198                = $config->SpecialFacets->genericRange->toArray();
199        }
200        if (isset($config->SpecialFacets->numericRange)) {
201            $this->numericRangeFacets
202                = $config->SpecialFacets->numericRange->toArray();
203        }
204
205        // Checkbox facets:
206        $flipCheckboxes = false;
207        if (str_starts_with($checkboxSection, '~')) {
208            $checkboxSection = substr($checkboxSection, 1);
209            $flipCheckboxes = true;
210        }
211        $this->checkboxFacets
212            = ($checkboxSection && isset($config->$checkboxSection))
213            ? $config->$checkboxSection->toArray() : [];
214        if ($flipCheckboxes) {
215            $this->checkboxFacets = array_flip($this->checkboxFacets);
216        }
217        if (
218            !$showDynamicCheckboxFacets
219            || strtolower(trim($showDynamicCheckboxFacets)) === 'false'
220        ) {
221            $this->showDynamicCheckboxFacets = false;
222        }
223
224        // Show more settings:
225        if (isset($config->Results_Settings->showMore)) {
226            $this->showMoreSettings
227                = $config->Results_Settings->showMore->toArray();
228        }
229        if (isset($config->Results_Settings->showMoreInLightbox)) {
230            $this->showInLightboxSettings
231                = $config->Results_Settings->showMoreInLightbox->toArray();
232        }
233
234        // Collapsed facets:
235        if (isset($config->Results_Settings->collapsedFacets)) {
236            $this->collapsedFacets = $config->Results_Settings->collapsedFacets;
237        }
238
239        // Hierarchical facets:
240        if (isset($config->SpecialFacets->hierarchical)) {
241            $this->hierarchicalFacets
242                = $config->SpecialFacets->hierarchical->toArray();
243        }
244
245        // Hierarchical facet sort options:
246        if (isset($config->SpecialFacets->hierarchicalFacetSortOptions)) {
247            $this->hierarchicalFacetSortOptions
248                = $config->SpecialFacets->hierarchicalFacetSortOptions->toArray();
249        }
250    }
251
252    /**
253     * Called before the Search Results object performs its main search
254     * (specifically, in response to \VuFind\Search\SearchRunner::EVENT_CONFIGURED).
255     * This method is responsible for setting search parameters needed by the
256     * recommendation module and for reading any existing search parameters that may
257     * be needed.
258     *
259     * @param \VuFind\Search\Base\Params $params  Search parameter object
260     * @param \Laminas\Stdlib\Parameters $request Parameter object representing user
261     * request.
262     *
263     * @return void
264     */
265    public function init($params, $request)
266    {
267        $mainFacets = $this->mainFacets;
268        if ($request != null && ($enabledFacets = $request->get('enabledFacets', null)) !== null) {
269            $mainFacets = array_intersect_key($mainFacets, array_flip($enabledFacets));
270        }
271        // Turn on side facets in the search results:
272        foreach ($mainFacets as $name => $desc) {
273            $params->addFacet($name, $desc, in_array($name, $this->orFacets));
274        }
275        foreach ($this->checkboxFacets as $name => $desc) {
276            $params->addCheckboxFacet($name, $desc);
277        }
278    }
279
280    /**
281     * Get checkbox facet information from the search results.
282     *
283     * @return array
284     */
285    public function getCheckboxFacetSet()
286    {
287        return $this->results->getParams()->getCheckboxFacets(
288            array_keys($this->checkboxFacets),
289            $this->showDynamicCheckboxFacets
290        );
291    }
292
293    /**
294     * Get facet information from the search results.
295     *
296     * @return array
297     * @throws \Exception
298     */
299    public function getFacetSet()
300    {
301        $facetSet = $this->results->getFacetList($this->mainFacets);
302
303        foreach ($this->hierarchicalFacets as $hierarchicalFacet) {
304            if (isset($facetSet[$hierarchicalFacet])) {
305                if (!$this->hierarchicalFacetHelper) {
306                    throw new \Exception(
307                        get_class($this) . ': hierarchical facet helper unavailable'
308                    );
309                }
310
311                $facetSet[$hierarchicalFacet]['list'] = $this->hierarchicalFacetHelper->filterFacets(
312                    $hierarchicalFacet,
313                    $facetSet[$hierarchicalFacet]['list'],
314                    $this->results->getOptions()
315                );
316            }
317        }
318
319        return $facetSet;
320    }
321
322    /**
323     * Return year-based date facet information in a format processed for use in the
324     * view.
325     *
326     * @return array Array of from/to value arrays keyed by field.
327     */
328    public function getDateFacets()
329    {
330        return $this->getRangeFacets('dateFacets');
331    }
332
333    /**
334     * Return year/month/day-based date facet information in a format processed for
335     * use in the view.
336     *
337     * @return array Array of from/to value arrays keyed by field.
338     */
339    public function getFullDateFacets()
340    {
341        return $this->getRangeFacets('fullDateFacets');
342    }
343
344    /**
345     * Return generic range facet information in a format processed for use in the
346     * view.
347     *
348     * @return array Array of from/to value arrays keyed by field.
349     */
350    public function getGenericRangeFacets()
351    {
352        return $this->getRangeFacets('genericRangeFacets');
353    }
354
355    /**
356     * Return numeric range facet information in a format processed for use in the
357     * view.
358     *
359     * @return array Array of from/to value arrays keyed by field.
360     */
361    public function getNumericRangeFacets()
362    {
363        return $this->getRangeFacets('numericRangeFacets');
364    }
365
366    /**
367     * Get combined range details.
368     *
369     * @return array
370     */
371    public function getAllRangeFacets()
372    {
373        $raw = [
374            'date' => $this->getDateFacets(),
375            'fulldate' => $this->getFullDateFacets(),
376            'generic' => $this->getGenericRangeFacets(),
377            'numeric' => $this->getNumericRangeFacets(),
378        ];
379        $processed = [];
380        foreach ($raw as $type => $values) {
381            foreach ($values as $field => $range) {
382                $processed[$field] = ['type' => $type, 'values' => $range];
383            }
384        }
385        return $processed;
386    }
387
388    /**
389     * Return the list of facets configured to be collapsed
390     *
391     * @return array
392     */
393    public function getCollapsedFacets()
394    {
395        if (empty($this->collapsedFacets)) {
396            return [];
397        } elseif ($this->collapsedFacets == '*') {
398            return array_keys($this->mainFacets);
399        }
400        return array_map('trim', explode(',', $this->collapsedFacets));
401    }
402
403    /**
404     * Return the list of facets configured to be collapsed
405     * defaults to 6
406     *
407     * @param string $facetName Name of the facet to get
408     * @param int    $default   Value to use if configuration is absent/invalid
409     *
410     * @return int
411     */
412    public function getShowMoreSetting($facetName, $default = 6)
413    {
414        // Look for either facet-specific configuration or else a configured
415        // default. If neither is found, initialize return value to null.
416        $val = null;
417        if (isset($this->showMoreSettings[$facetName])) {
418            $val = intval($this->showMoreSettings[$facetName]);
419        } elseif (isset($this->showMoreSettings['*'])) {
420            $val = intval($this->showMoreSettings['*']);
421        }
422
423        // Validate the return value, using default if missing/invalid
424        return (isset($val) && $val > 0) ? $val : $default;
425    }
426
427    /**
428     * Return settings for showing more results in the lightbox
429     *
430     * @param string $facetName Name of the facet to get
431     *
432     * @return int
433     */
434    public function getShowInLightboxSetting($facetName)
435    {
436        // Look for either facet-specific configuration or else a configured
437        // default.
438        if (isset($this->showInLightboxSettings[$facetName])) {
439            return $this->showInLightboxSettings[$facetName];
440        } elseif (isset($this->showInLightboxSettings['*'])) {
441            return $this->showInLightboxSettings['*'];
442        }
443
444        // No config found; use default behavior:
445        return 'more';
446    }
447
448    /**
449     * Return range facet information in a format processed for use in the view.
450     *
451     * @param string $property Name of property containing active range facets
452     *
453     * @return array Array of from/to value arrays keyed by field.
454     */
455    protected function getRangeFacets($property)
456    {
457        $filters = $this->results->getParams()->getRawFilters();
458        $result = [];
459        if (isset($this->$property) && is_array($this->$property)) {
460            foreach ($this->$property as $current) {
461                $from = $to = '';
462                if (isset($filters[$current])) {
463                    foreach ($filters[$current] as $filter) {
464                        if ($range = SolrUtils::parseRange($filter)) {
465                            $from = $range['from'] == '*' ? '' : $range['from'];
466                            $to = $range['to'] == '*' ? '' : $range['to'];
467                            break;
468                        }
469                    }
470                }
471                $result[$current] = [$from, $to];
472            }
473        }
474        return $result;
475    }
476
477    /**
478     * Return the list of facets configured to be hierarchical
479     *
480     * @return array
481     */
482    public function getHierarchicalFacets()
483    {
484        return $this->hierarchicalFacets;
485    }
486
487    /**
488     * Return the list of configured hierarchical facet sort options
489     *
490     * @return array
491     */
492    public function getHierarchicalFacetSortOptions()
493    {
494        return $this->hierarchicalFacetSortOptions;
495    }
496}