Completed
Push — master ( d06511...3d3ec0 )
by Christopher
02:49
created

Query::orHaving()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 9
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 9
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
/**
3
 * @link      https://github.com/chrmorandi/yii2-ldap for the canonical source repository
4
 * @package   yii2-ldap
5
 * @author    Christopher Mota <[email protected]>
6
 * @license   Mit License - view the LICENSE file that was distributed with this source code.
7
 */
8
9
namespace chrmorandi\ldap;
10
11
use Yii;
12
use yii\base\Component;
13
use chrmorandi\ldap\Connection;
14
use yii\db\Expression;
15
use yii\db\QueryInterface;
16
use yii\db\QueryTrait;
17
18
/**
19
 * Query represents a SEARCH in LDAP database directory.
20
 *
21
 * Query provides a set of methods to facilitate the specification of different clauses
22
 * in a SEARCH statement. These methods can be chained together.
23
 *
24
 * For example,
25
 *
26
 * ```php
27
 * $query = new Query;
28
 * // compose the query
29
 * $query->select('id, name')
30
 *     ->from('user')
31
 *     ->limit(10);
32
 * // build and execute the query
33
 * $rows = $query->all();
34
 * ```
35
 *
36
 * Query internally uses the [[FilterBuilder]] class to generate the LDAP filters.
37
 *
38
 * @author Christopher Mota <[email protected]>
39
 * @since 1.0.0
40
 */
41
class Query extends Component implements QueryInterface
42
{
43
    use QueryTrait;
44
45
    const SEARCH_SCOPE_SUB  = 'ldap_search';
46
    const SEARCH_SCOPE_ONE  = 'ldap_list';
47
    const SEARCH_SCOPE_BASE = 'ldap_read';
48
    
49
    /**
50
     * @var string the scope of search
51
     * The search scope:
52
     * Query::SEARCH_SCOPE_SUB searches the complete subtree including the $baseDn node. This is the default value.
53
     * Query::SEARCH_SCOPE_ONE restricts search to one level below $baseDn.
54
     * Query::SEARCH_SCOPE_BASE restricts search to the $baseDn itself; this can be used to efficiently retrieve a single entry by its DN.
55
     */
56
    public $scope = self::SEARCH_SCOPE_SUB;
57
    
58
    /**
59
     * @var array the columns being selected. For example, `['id', 'name']`.
60
     * This is used to construct the SEARCH function in a LDAP statement. If not set, it means selecting all columns.
61
     * @see select()
62
     */
63
    public $select;
64
    
65
    /**
66
     * @var string The search filter. Format is described in the LDAP documentation.
67
     * @see http://www.faqs.org/rfcs/rfc4515.html
68
     */
69
    public $filter;
70
71
    /**
72
     * Creates a LDAP command that can be used to execute this query.
73
     * @param Connection $db the database connection.
74
     * If this parameter is not given, the `db` application component will be used.
75
     * @return DataReader
76
     */
77
    protected function execute($db = null)
78
    {
79
        if ($db === null) {
80
            $db = Yii::$app->get('ldap');
81
        }
82
        
83
        $this->filter = (new FilterBuilder)->build($this->where);
84
        $select = (is_array($this->select)) ? $this->select : [];
85
        $this->limit = empty($this->limit) ? 0 : $this->limit;
86
                
87
        $params = [
88
            $db->baseDn,
89
            $filter,
0 ignored issues
show
Bug introduced by
The variable $filter does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
90
            $select,
91
            0,
92
            $this->limit
93
        ];
94
95
        return $db->execute($this->scope, $params);
96
    }
97
98
    /**
99
     * Executes the query and returns all results as an array.
100
     * @param Connection $db the database connection.
101
     * If this parameter is not given, the `db` application component will be used.
102
     * @return array the query results. If the query results in nothing, an empty array will be returned.
103
     */
104 View Code Duplication
    public function all($db = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
    {
106
        if ($db === null) {
107
            $db = Yii::$app->get('ldap');
108
        }
109
        
110
        /** @var $result DataReader */
111
        $result = $this->execute($db);        
112
        return $this->populate($result->toArray());
113
    }
114
115
    /**
116
     * Converts the raw query results into the format as specified by this query.
117
     * This method is internally used to convert the data fetched from database
118
     * into the format as required by this query.
119
     * @param array $rows the raw query result from database
120
     * @return array the converted query result
121
     */
122
    public function populate($rows)
123
    {
124
        if ($this->indexBy === null) {
125
            return $rows;
126
        }
127
        $result = [];
128
        foreach ($rows as $row) {
129
            if (is_string($this->indexBy)) {
130
                $key = $row[$this->indexBy];
131
            } else {
132
                $key = call_user_func($this->indexBy, $row);
133
            }
134
            $result[$key] = $row;
135
        }
136
        return $result;
137
    }
138
139
    /**
140
     * Executes the query and returns a single row of result.
141
     * @param Connection $db the database connection.
142
     * If this parameter is not given, the `db` application component will be used.
143
     * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query
144
     * results in nothing.
145
     */
146 View Code Duplication
    public function one($db = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
147
    {
148
        if ($db === null) {
149
            $db = Yii::$app->get('ldap');
150
        }
151
152
        $this->limit = 1;
153
        $result = $this->execute($db);
154
        return $result->toArray();
155
    }
156
157
    /**
158
     * Returns the number of entries in a search.
159
     * @param Connection $db the database connection
160
     * If this parameter is not given (or null), the `db` application component will be used.
161
     * @return integer number of entries.
162
     */
163 View Code Duplication
    public function count($db = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
    {
165
        if ($db === null) {
166
            $db = Yii::$app->get('ldap');
167
        }
168
        
169
        $result = $this->execute($db);
170
        return $result->count();
171
    }
172
    
173
174
    /**
175
     * Returns a value indicating whether the query result contains any row of data.
176
     * @param Connection $db the database connection.
177
     * If this parameter is not given, the `db` application component will be used.
178
     * @return boolean whether the query result contains any row of entries.
179
     */
180 View Code Duplication
    public function exists($db = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
181
    {
182
        if ($db === null) {
183
            $db = Yii::$app->get('ldap');
184
        }
185
        
186
        $result = $this->execute($db);
187
        return (boolean)$result->count();
188
    }
189
190
    /**
191
     * Sets the SELECT part of the query.
192
     * @param string|array $columns the columns to be selected.
193
     * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
194
     *
195
     * ```php
196
     * $query->addSelect(['cn, mail'])->one();
197
     * ```
198
     *
199
     * @return $this the query object itself
200
     */
201
    public function select($columns)
202
    {
203
        if (!is_array($columns)) {
204
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
205
        }
206
        $this->select = $columns;
207
        return $this;
208
    }
209
210
    /**
211
     * Add more columns to the select part of the query.
212
     *
213
     * ```php
214
     * $query->addSelect(['cn, mail'])->one();
215
     * ```
216
     *
217
     * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
218
     * details about the format of this parameter.
219
     * @return $this the query object itself
220
     * @see select()
221
     */
222
    public function addSelect($columns)
223
    {
224
        if (!is_array($columns)) {
225
            $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
226
        }
227
        if ($this->select === null) {
228
            $this->select = $columns;
229
        } else {
230
            $this->select = array_merge($this->select, $columns);
231
        }
232
        return $this;
233
    }
234
235
    /**
236
     * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
237
     *
238
     * It adds an additional WHERE condition for the given field and determines the comparison operator
239
     * based on the first few characters of the given value.
240
     * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
241
     * The new condition and the existing one will be joined using the 'AND' operator.
242
     *
243
     * The comparison operator is intelligently determined based on the first few characters in the given value.
244
     * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
245
     *
246
     * - `<`: the column must be less than the given value.
247
     * - `>`: the column must be greater than the given value.
248
     * - `<=`: the column must be less than or equal to the given value.
249
     * - `>=`: the column must be greater than or equal to the given value.
250
     * - `~=`: the column must approximate the given value.
251
     * - `=`: the column must be equal to the given value.
252
     * - If none of the above operators is detected, the `$defaultOperator` will be used.
253
     *
254
     * @param string $name the column name.
255
     * @param string $value the column value optionally prepended with the comparison operator.
256
     * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
257
     * Defaults to `=`, performing an exact match.
258
     * @return $this The query object itself
259
     */
260
    public function andFilterCompare($name, $value, $defaultOperator = '=')
261
    {
262
        if (preg_match("/^(~=|>=|>|<=|<|=)/", $value, $matches)) {
263
            $operator = $matches[1];
264
            $value = substr($value, strlen($operator));
265
        } else {
266
            $operator = $defaultOperator;
267
        }
268
        return $this->andFilterWhere([$operator, $name, $value]);
269
    }
270
271
    /**
272
     * Creates a new Query object and copies its property values from an existing one.
273
     * The properties being copies are the ones to be used by query builders.
274
     * @param Query $from the source query object
275
     * @return Query the new Query object
276
     */
277
    public static function create(Query $from)
278
    {
279
        return new self([
280
            'where' => $from->where,
281
            'limit' => $from->limit,
282
            'offset' => $from->offset,
283
            'orderBy' => $from->orderBy,
284
            'indexBy' => $from->indexBy,
285
            'select' => $from->select,
286
        ]);
287
    }
288
}
289