summaryrefslogtreecommitdiff
path: root/vendor/ruflin/elastica/lib/Elastica/Util.php
blob: a49f2d781c1f9abda1fb04129492d1cf6e92d6e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
<?php
namespace Elastica;

/**
 * Elastica tools.
 *
 * @author Nicolas Ruflin <spam@ruflin.com>
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Oleg Zinchenko <olegz@default-value.com>
 * @author Roberto Nygaard <roberto@nygaard.es>
 */
class Util
{
    /**
     * Replace the following reserved words: AND OR NOT
     * and
     * escapes the following terms: + - && || ! ( ) { } [ ] ^ " ~ * ? : \.
     *
     * @link http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Boolean%20operators
     * @link http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Escaping%20Special%20Characters
     *
     * @param string $term Query term to replace and escape
     *
     * @return string Replaced and escaped query term
     */
    public static function replaceBooleanWordsAndEscapeTerm($term)
    {
        $result = $term;
        $result = self::replaceBooleanWords($result);
        $result = self::escapeTerm($result);

        return $result;
    }

    /**
     * Escapes the following terms (because part of the query language)
     * + - && || ! ( ) { } [ ] ^ " ~ * ? : \ < >.
     *
     * @link http://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#_reserved_characters
     *
     * @param string $term Query term to escape
     *
     * @return string Escaped query term
     */
    public static function escapeTerm($term)
    {
        $result = $term;
        // \ escaping has to be first, otherwise escaped later once again
        $chars = array('\\', '+', '-', '&&', '||', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '/', '<', '>');

        foreach ($chars as $char) {
            $result = str_replace($char, '\\'.$char, $result);
        }

        return $result;
    }

    /**
     * Replace the following reserved words (because part of the query language)
     * AND OR NOT.
     *
     * @link http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Boolean%20operators
     *
     * @param string $term Query term to replace
     *
     * @return string Replaced query term
     */
    public static function replaceBooleanWords($term)
    {
        $replacementMap = array(' AND ' => ' && ', ' OR ' => ' || ', ' NOT ' => ' !');
        $result = strtr($term, $replacementMap);

        return $result;
    }

    /**
     * Converts a snake_case string to CamelCase.
     *
     * For example: hello_world to HelloWorld
     *
     * @param string $string snake_case string
     *
     * @return string CamelCase string
     */
    public static function toCamelCase($string)
    {
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
    }

    /**
     * Converts a CamelCase string to snake_case.
     *
     * For Example HelloWorld to hello_world
     *
     * @param string $string CamelCase String to Convert
     *
     * @return string SnakeCase string
     */
    public static function toSnakeCase($string)
    {
        $string = preg_replace('/([A-Z])/', '_$1', $string);

        return strtolower(substr($string, 1));
    }

    /**
     * Converts given time to format: 1995-12-31T23:59:59Z.
     *
     * This is the lucene date format
     *
     * @param int $date Date input (could be string etc.) -> must be supported by strtotime
     *
     * @return string Converted date string
     */
    public static function convertDate($date)
    {
        if (is_int($date)) {
            $timestamp = $date;
        } else {
            $timestamp = strtotime($date);
        }
        $string = date('Y-m-d\TH:i:s\Z', $timestamp);

        return $string;
    }

    /**
     * Convert a \DateTime object to format: 1995-12-31T23:59:59Z+02:00.
     *
     * Converts it to the lucene format, including the appropriate TimeZone
     *
     * @param \DateTime $dateTime
     * @param bool      $includeTimezone
     *
     * @return string
     */
    public static function convertDateTimeObject(\DateTime $dateTime, $includeTimezone = true)
    {
        $formatString = 'Y-m-d\TH:i:s'.($includeTimezone === true ? 'P' : '\Z');
        $string = $dateTime->format($formatString);

        return $string;
    }

    /**
     * Tries to guess the name of the param, based on its class
     * Example: \Elastica\Filter\HasChildFilter => has_child.
     *
     * @param string|object Class or Class name
     *
     * @return string parameter name
     */
    public static function getParamName($class)
    {
        if (is_object($class)) {
            $class = get_class($class);
        }

        $parts = explode('\\', $class);
        $last = array_pop($parts);
        $last = preg_replace('/(Facet|Query|Filter)$/', '', $last);
        $name = self::toSnakeCase($last);

        return $name;
    }

    /**
     * Converts Request to Curl console command.
     *
     * @param Request $request
     *
     * @return string
     */
    public static function convertRequestToCurlCommand(Request $request)
    {
        $message = 'curl -X'.strtoupper($request->getMethod()).' ';
        $message .= '\'http://'.$request->getConnection()->getHost().':'.$request->getConnection()->getPort().'/';
        $message .= $request->getPath();

        $query = $request->getQuery();
        if (!empty($query)) {
            $message .= '?'.http_build_query($query);
        }

        $message .= '\'';

        $data = $request->getData();
        if (!empty($data)) {
            $message .= ' -d \''.JSON::stringify($data).'\'';
        }

        return $message;
    }
}