Passed
Push — master ( e78d75...1f156d )
by Robbie
04:13 queued 11s
created

SolrSearchQueryWriterIn::getInComparisonString()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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