Passed
Push — task/2976_TYPO3.11_compatibili... ( 803400...b598e4 )
by Rafael
33:58 queued 15:41
created

EscapeService::escapePhrase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
namespace ApacheSolrForTypo3\Solr\Domain\Search\Query\Helper;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2017 Timo Hund <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
/**
28
 * The EscpaeService is responsible to escape the querystring as expected for Apache Solr.
29
 *
30
 * This class should have no dependencies since it only contains static functions
31
 *
32
 * @author Timo Hund <[email protected]>
33
 */
34
class EscapeService {
35
36
    /**
37
     * Quote and escape search strings
38
     *
39
     * @param string|int|double $string String to escape
40
     * @return string|int|double The escaped/quoted string
41
     */
42 19
    public static function escape($string)
43
    {
44
        // when we have a numeric string only, nothing needs to be done
45 19
        if (is_numeric($string)) {
46 1
            return $string;
47
        }
48
49
        // when no whitespaces are in the query we can also just escape the special characters
50 18
        if (preg_match('/\W/', $string) != 1) {
51 2
            return static::escapeSpecialCharacters($string);
52
        }
53
54
        // when there are no quotes inside the query string we can also just escape the whole string
55 16
        $hasQuotes = strrpos($string, '"') !== false;
56 16
        if (!$hasQuotes) {
57 9
            return static::escapeSpecialCharacters($string);
58
        }
59
60 7
        $result = static::tokenizeByQuotesAndEscapeDependingOnContext($string);
61
62 7
        return $result;
63
    }
64
65
    /**
66
     * Applies trim and htmlspecialchars on the querystring to use it as output.
67
     *
68
     * @param mixed $string
69
     * @return string
70
     */
71
    public static function clean($string): string
72
    {
73
        $string = trim($string);
74
        $string = htmlspecialchars($string);
75
        return $string;
76
    }
77
78
    /**
79
     * This method is used to escape the content in the query string surrounded by quotes
80
     * different then when it is not in a quoted context.
81
     *
82
     * @param string $string
83
     * @return string
84
     */
85 7
    protected static function tokenizeByQuotesAndEscapeDependingOnContext($string)
86
    {
87 7
        $result = '';
88 7
        $quotesCount = substr_count($string, '"');
89 7
        $isEvenAmountOfQuotes = $quotesCount % 2 === 0;
90
91
        // go over all quote segments and apply escapePhrase inside a quoted
92
        // context and escapeSpecialCharacters outside the quoted context.
93 7
        $segments = explode('"', $string);
94 7
        $segmentsIndex = 0;
95 7
        foreach ($segments as $segment) {
96 7
            $isInQuote = $segmentsIndex % 2 !== 0;
97 7
            $isLastQuote = $segmentsIndex === $quotesCount;
98
99 7
            if ($isLastQuote && !$isEvenAmountOfQuotes) {
100 1
                $result .= '\"';
101
            }
102
103 7
            if ($isInQuote && !$isLastQuote) {
104 6
                $result .= static::escapePhrase($segment);
105
            } else {
106 7
                $result .= static::escapeSpecialCharacters($segment);
107
            }
108
109 7
            $segmentsIndex++;
110
        }
111
112 7
        return $result;
113
    }
114
115
    /**
116
     * Escapes a value meant to be contained in a phrase with characters with
117
     * special meanings in Lucene query syntax.
118
     *
119
     * @param string $value Unescaped - "dirty" - string
120
     * @return string Escaped - "clean" - string
121
     */
122 6
    protected static function escapePhrase($value)
123
    {
124 6
        $pattern = '/("|\\\)/';
125 6
        $replace = '\\\$1';
126
127 6
        return '"' . preg_replace($pattern, $replace, $value) . '"';
128
    }
129
130
    /**
131
     * Escapes characters with special meanings in Lucene query syntax.
132
     *
133
     * @param string $value Unescaped - "dirty" - string
134
     * @return string Escaped - "clean" - string
135
     */
136 18
    protected static function escapeSpecialCharacters($value)
137
    {
138
        // list taken from http://lucene.apache.org/core/4_4_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package_description
139
        // which mentions: + - && || ! ( ) { } [ ] ^ " ~ * ? : \ /
140
        // of which we escape: ( ) { } [ ] ^ " ~ : \ /
141
        // and explicitly don't escape: + - && || ! * ?
142 18
        $pattern = '/(\\(|\\)|\\{|\\}|\\[|\\]|\\^|"|~|\:|\\\\|\\/)/';
143 18
        $replace = '\\\$1';
144
145 18
        return preg_replace($pattern, $replace, $value);
146
    }
147
}