Completed
Pull Request — master (#150)
by
unknown
03:45
created

SolrSearchQueryWriterIn::generateQueryString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\FullTextSearch\Solr\Writers;
4
5
use SilverStripe\FullTextSearch\Search\Criteria\SearchCriterion;
6
use SilverStripe\FullTextSearch\Search\Queries\AbstractSearchQueryWriter;
7
8
/**
9
 * Class SolrSearchQueryWriter_In
10
 * @package SilverStripe\FullTextSearch\Solr\Writers
11
 */
12
class SolrSearchQueryWriterIn extends AbstractSearchQueryWriter
13
{
14
    /**
15
     * @param SearchCriterion $searchCriterion
16
     * @return string
17
     */
18
    public function generateQueryString(SearchCriterion $searchCriterion)
19
    {
20
        $qs = $this->getComparisonPolarity($searchCriterion->getComparison());
21
        $qs .= $this->getInComparisonString($searchCriterion);
22
23
        return $qs;
24
    }
25
26
    /**
27
     * Is this a positive (+) or negative (-) Solr comparison.
28
     *
29
     * @param string $comparison
30
     * @return string
31
     */
32
    protected function getComparisonPolarity($comparison)
33
    {
34
        switch ($comparison) {
35
            case SearchCriterion::NOT_IN:
36
                return '-';
37
            default:
38
                return '';
39
        }
40
    }
41
42
    /**
43
     * @param SearchCriterion $searchCriterion
44
     * @return string
45
     */
46
    protected function getInComparisonString(SearchCriterion $searchCriterion)
47
    {
48
        $conditions = array();
49
50
        if (!is_array($searchCriterion->getValue())) {
51
            throw new \InvalidArgumentException('Invalid value type for Criterion IN');
52
        }
53
54
        foreach ($searchCriterion->getValue() as $value) {
55
            $condition = addslashes($searchCriterion->getTarget());
56
            $condition .= $this->getComparisonConjunction();
57
58
            if (is_string($value)) {
59
                // String values need to be wrapped in quotes and escaped.
60
                $condition .= $searchCriterion->getQuoteValue($value);
61
            } else {
62
                $condition .= $value;
63
            }
64
65
            $conditions[] = $condition;
66
        }
67
68
        return '(' . implode(' ', $conditions) . ')';
69
    }
70
71
    /**
72
     * Decide how we are comparing our left and right values.
73
     *
74
     * @return string
75
     */
76
    protected function getComparisonConjunction()
77
    {
78
        return ':';
79
    }
80
}
81