ShopSearchSimple   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 8

Test Coverage

Coverage 84%

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 17
c 4
b 0
f 1
lcom 0
cbo 8
dl 0
loc 94
ccs 42
cts 50
cp 0.84
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B searchFromVars() 0 35 6
C scaffoldSearchFields() 0 38 11
1
<?php
2
/**
3
 * VERY simple adapter to use DataList and :PartialMatch searches. Bare mininum
4
 * that will probably get terrible results but doesn't require any
5
 * additional setup.
6
 *
7
 * @author Mark Guinn <[email protected]>
8
 * @date 09.03.2013
9
 * @package shop_search
10
 */
11
class ShopSearchSimple extends Object implements ShopSearchAdapter
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
12
{
13
    /**
14
     * @param string $keywords
15
     * @param array $filters [optional]
16
     * @param array $facetSpec [optional]
17
     * @param int $start [optional]
18
     * @param int $limit [optional]
19
     * @param string $sort [optional]
20
     * @return ArrayData
21
     */
22 5
    public function searchFromVars($keywords, array $filters=array(), array $facetSpec=array(), $start=-1, $limit=-1, $sort='')
23
    {
24 5
        $searchable = ShopSearch::get_searchable_classes();
25 5
        $matches = new ArrayList;
26
27 5
        foreach ($searchable as $className) {
28 5
            $list = DataObject::get($className);
29
30
            // get searchable fields
31 5
            $keywordFields = $this->scaffoldSearchFields($className);
32
33
            // convert that list into something we can pass to Datalist::filter
34 5
            $keywordFilter = array();
35 5
            if (!empty($keywords)) {
36 4
                foreach ($keywordFields as $searchField) {
0 ignored issues
show
Bug introduced by
The expression $keywordFields of type array<integer,string,{"0":"string"}>|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...
37 4
                    $name = (strpos($searchField, ':') !== false) ? $searchField : "$searchField:PartialMatch";
38 4
                    $keywordFilter[$name] = $keywords;
39 4
                }
40 4
            }
41 5
            if (count($keywordFilter) > 0) {
42 4
                $list = $list->filterAny($keywordFilter);
43 4
            }
44
45
            // add in any other filters
46 5
            $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
47
48
            // add any matches to the big list
49 5
            $matches->merge($list);
50 5
        }
51
52 5
        return new ArrayData(array(
53 5
            'Matches'   => $matches,
54 5
            'Facets'    => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool)Config::inst()->get('ShopSearch', 'auto_facet_attributes')),
55 5
        ));
56
    }
57
58
59
    /**
60
     * This is verbatim copied from GridFieldAddExistingAutocompleter, with the exception
61
     * that the default is 'PartialMatch' instead of 'StartsWith'
62
     *
63
     * @param String $dataClass - the class name
64
     * @return Array|null - names of the searchable fields, with filters if appropriate
65
     */
66 5
    protected function scaffoldSearchFields($dataClass)
67
    {
68 5
        $obj = singleton($dataClass);
69 5
        $fields = null;
70 5
        if ($fieldSpecs = $obj->searchableFields()) {
71 5
            $customSearchableFields = $obj->stat('searchable_fields');
72 5
            foreach ($fieldSpecs as $name => $spec) {
73 5
                if (is_array($spec) && array_key_exists('filter', $spec)) {
74
                    // The searchableFields() spec defaults to PartialMatch,
75
                    // so we need to check the original setting.
76
                    // If the field is defined $searchable_fields = array('MyField'),
77
                    // then default to StartsWith filter, which makes more sense in this context.
78 5
                    if (!$customSearchableFields || array_search($name, $customSearchableFields)) {
79 5
                        $filter = 'PartialMatch';
80 5
                    } else {
81 5
                        $filter = preg_replace('/Filter$/', '', $spec['filter']);
82
                    }
83
84 5
                    if (class_exists($filter . 'Filter')) {
85 5
                        $fields[] = "{$name}:{$filter}";
86 5
                    } else {
87
                        $fields[] = $name;
88
                    }
89 5
                } else {
90
                    $fields[] = $name;
91
                }
92 5
            }
93 5
        }
94 5
        if (is_null($fields)) {
95
            if ($obj->hasDatabaseField('Title')) {
96
                $fields = array('Title');
97
            } elseif ($obj->hasDatabaseField('Name')) {
98
                $fields = array('Name');
99
            }
100
        }
101
102 5
        return $fields;
103
    }
104
}
105