This repository has been archived by the owner on Dec 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathSearchableBehavior.php
executable file
·591 lines (548 loc) · 18.4 KB
/
SearchableBehavior.php
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
<?php
/**
* Copyright 2009-2013, Cake Development Corporation (http://cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2009 - 2014, Cake Development Corporation (http://cakedc.com)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ModelBehavior', 'Model');
/**
* Searchable behavior
*
*/
class SearchableBehavior extends ModelBehavior {
/**
* Default settings
* - wildcardAny: the character used instead of % (% is a normal character then)
* - wildcardOne: the character used instead of _ (_ is a normal character then)
* - like: auto add % wildcard to beginning, end or both (both false => user can enter wildcards himself)
* - ilike: auto add % wildcard to beginning, end or both (both false => user can enter wildcards himself)
* - connectorAnd: the character between search terms to specify an "and" relationship (binds stronger than or, similar to * and + in math)
* - connectorOr: the character between search terms to specify an "or" relationship
*
* @var array
*/
protected $_defaults = array(
'wildcardAny' => '*', //on windows/unix/mac/google/... thats the default one
'wildcardOne' => '?', //on windows/unix/mac thats the default one
'like' => array('before' => true, 'after' => true),
'ilike' => array('before' => true, 'after' => true),
'connectorAnd' => null,
'connectorOr' => null,
);
/**
* Configuration of model
*
* @param Model $Model
* @param array $config
* @return void
*/
public function setup(Model $Model, $config = array()) {
$this->_defaults = (array)Configure::read('Search.Searchable') + $this->_defaults;
$this->settings[$Model->alias] = $config + $this->_defaults;
}
/**
* Prepares the filter args based on the model information and calls
* Model::getFilterArgs if present to set up the filterArgs with proper model
* aliases.
*
* @param Model $Model
* @return boolean|array
*/
public function setupFilterArgs(Model $Model) {
if (method_exists($Model, 'getFilterArgs')) {
$Model->getFilterArgs();
}
if (empty($Model->filterArgs)) {
return false;
}
foreach ($Model->filterArgs as $key => $val) {
if (!isset($val['name'])) {
$Model->filterArgs[$key]['name'] = $key;
}
if (!isset($val['field'])) {
$Model->filterArgs[$key]['field'] = $Model->filterArgs[$key]['name'];
}
if (!isset($val['type'])) {
$Model->filterArgs[$key]['type'] = 'value';
}
}
return $Model->filterArgs;
}
/**
* parseCriteria
* parses the GET data and returns the conditions for the find('all')/paginate
* we are just going to test if the params are legit
*
* @param Model $Model
* @param array $data Criteria of key->value pairs from post/named parameters
* @return array Array of conditions that express the conditions needed for the search
*/
public function parseCriteria(Model $Model, $data) {
$this->setupFilterArgs($Model);
$conditions = array();
foreach ($Model->filterArgs as $field) {
// If this field was not passed and a default value exists, use that instead.
if (!array_key_exists($field['name'], $data) && array_key_exists('defaultValue', $field)) {
$data[$field['name']] = $field['defaultValue'];
}
if (in_array($field['type'], array('like'))) {
$this->_addCondLike($Model, $conditions, $data, $field, 'LIKE');
} elseif (in_array($field['type'], array('ilike'))) {
$this->_addCondLike($Model, $conditions, $data, $field, 'ILIKE');
} elseif (in_array($field['type'], array('value', 'lookup'))) {
$this->_addCondValue($Model, $conditions, $data, $field);
} elseif ($field['type'] === 'expression') {
$this->_addCondExpression($Model, $conditions, $data, $field);
} elseif ($field['type'] === 'query') {
$this->_addCondQuery($Model, $conditions, $data, $field);
} elseif ($field['type'] === 'subquery') {
$this->_addCondSubquery($Model, $conditions, $data, $field);
}
}
return $conditions;
}
/**
* Validate search
*
* @param Model $Model
* @param null $data
* @return boolean always true
*/
public function validateSearch(Model $Model, $data = null) {
if (!empty($data)) {
$Model->set($data);
}
$keys = array_keys($Model->data[$Model->alias]);
foreach ($keys as $key) {
if (empty($Model->data[$Model->alias][$key])) {
unset($Model->data[$Model->alias][$key]);
}
}
return true;
}
/**
* filter retrieving variables only that present in Model::filterArgs
*
* @param Model $Model
* @param array $vars
* @return array, filtered args
*/
public function passedArgs(Model $Model, $vars) {
$this->setupFilterArgs($Model);
$result = array();
foreach ($vars as $var => $val) {
if (in_array($var, Hash::extract($Model->filterArgs, '{n}.name'))) {
$result[$var] = $val;
}
}
return $result;
}
/**
* Generates a query string using the same API Model::find() uses, calling the beforeFind process for the model
*
* @param Model $Model
* @param string $type Type of find operation (all / first / count / neighbors / list / threaded)
* @param array $query Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
* @return array Array of records
* @link http://book.cakephp.org/view/1018/find
*/
public function getQuery(Model $Model, $type = 'first', $query = array()) {
$Model->findQueryType = $type;
$Model->id = $Model->getID();
$query = $Model->buildQuery($type, $query);
$this->findQueryType = null;
return $this->_queryGet($Model, $query);
}
/**
* Clear all associations
*
* @param Model $Model
* @param boolean $reset
* @return void
*/
public function unbindAllModels(Model $Model, $reset = false) {
$assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
$unbind = array();
foreach ($assocs as $assoc) {
$unbind[$assoc] = array_keys($Model->{$assoc});
}
$Model->unbindModel($unbind, $reset);
}
/**
* For custom queries inside the model
* example "makePhoneCondition": $cond = array('OR' => array_merge($this->condIlike('cell_number', $filter), $this->condIlike('landline_number', $filter, array('before' => false))));
*
* @param Model $Model
* @param $name
* @param $data
* @param array $field
* @return array of conditions
*/
public function condIlike(Model $Model, $name, $data, $field = array()) {
$conditions = array();
$field['name'] = $name;
if (!is_array($data)) {
$data = array($name => $data);
}
if (!isset($field['field'])) {
$field['field'] = $field['name'];
}
return $this->_addCondLike($Model, $conditions, $data, $field, 'ILIKE');
}
/**
* For custom queries inside the model
* example "makePhoneCondition": $cond = array('OR' => array_merge($this->condLike('cell_number', $filter), $this->condLike('landline_number', $filter, array('before' => false))));
*
* @param Model $Model
* @param $name
* @param $data
* @param array $field
* @return array of conditions
*/
public function condLike(Model $Model, $name, $data, $field = array()) {
$conditions = array();
$field['name'] = $name;
if (!is_array($data)) {
$data = array($name => $data);
}
if (!isset($field['field'])) {
$field['field'] = $field['name'];
}
return $this->_addCondLike($Model, $conditions, $data, $field, 'LIKE');
}
/**
* Replace substitutions with original wildcards
* but first, escape the original wildcards in the text to use them as normal search text
*
* @param Model $Model
* @param $data
* @param array $options
* @return string queryLikeString
*/
public function formatLike(Model $Model, $data, $options = array()) {
$options = array_merge($this->settings[$Model->alias], $options);
$from = $to = $substFrom = $substTo = array();
if ($options['wildcardAny'] !== '%') {
$from[] = '%';
$to[] = '\%';
$substFrom[] = $options['wildcardAny'];
$substTo[] = '%';
}
if ($options['wildcardOne'] !== '_') {
$from[] = '_';
$to[] = '\_';
$substFrom[] = $options['wildcardOne'];
$substTo[] = '_';
}
if (!empty($from)) {
// escape first
$data = str_replace($from, $to, $data);
// replace wildcards
$data = str_replace($substFrom, $substTo, $data);
}
return $data;
}
/**
* Return the current chars for querying LIKE/ILIKE statements on this model
*
* @param Model $Model Reference to the model
* @param array $options
* @return array, [one=>..., any=>...]
*/
public function getWildcards(Model $Model, $options = array()) {
$options = array_merge($this->settings[$Model->alias], $options);
return array('any' => $options['wildcardAny'], 'one' => $options['wildcardOne']);
}
/**
* Add Conditions based on fuzzy comparison
*
* @param Model $Model Reference to the model
* @param array $conditions existing Conditions collected for the model
* @param array $data Array of data used in search query
* @param array $field Field definition information
* @return array Conditions
*/
protected function _addCondLike(Model $Model, &$conditions, $data, $field, $likeMethod = 'LIKE') {
$settingName = strtolower($likeMethod);
if (!is_array($this->settings[$Model->alias][$settingName])) {
$this->settings[$Model->alias][$settingName] = array('before' => $this->settings[$Model->alias][$settingName], 'after' => $this->settings[$Model->alias][$settingName]);
}
$field = array_merge($this->settings[$Model->alias][$settingName], $field);
if (empty($data[$field['name']])) {
return $conditions;
}
$fieldNames = (array)$field['field'];
$cond = array();
foreach ($fieldNames as $fieldName) {
if (strpos($fieldName, '.') === false) {
$fieldName = $Model->alias . '.' . $fieldName;
}
if ($field['before'] === true) {
$field['before'] = '%';
}
if ($field['after'] === true) {
$field['after'] = '%';
}
$options = $this->settings[$Model->alias];
$from = $to = $substFrom = $substTo = array();
if ($options['wildcardAny'] !== '%') {
$from[] = '%';
$to[] = '\%';
$from[] = $options['wildcardAny'];
$to[] = '%';
}
if ($options['wildcardOne'] !== '_') {
$from[] = '_';
$to[] = '\_';
$from[] = $options['wildcardOne'];
$to[] = '_';
}
$value = $data[$field['name']];
if (!empty($from)) {
$value = str_replace($from, $to, $value);
}
if (!empty($field['connectorAnd']) || !empty($field['connectorOr'])) {
$cond[] = $this->_connectedLike($value, $field, $fieldName, $likeMethod);
} else {
$cond[$fieldName . " " . $likeMethod] = $field['before'] . $value . $field['after'];
}
}
if (count($cond) > 1) {
if (isset($conditions['OR'])) {
$conditions[]['OR'] = $cond;
} else {
$conditions['OR'] = $cond;
}
} else {
$conditions = array_merge($conditions, $cond);
}
return $conditions;
}
/**
* Form AND/OR query array using CakeText::tokenize to separate
* search terms by or/and connectors.
*
* @param mixed $value
* @param array $field
* @param string $fieldName
* @return array Conditions
*/
protected function _connectedLike($value, $field, $fieldName, $likeMethod = 'LIKE') {
$or = array();
if (Configure::version() < '2.7') {
$orValues = String::tokenize($value, $field['connectorOr']);
} else {
$orValues = CakeText::tokenize($value, $field['connectorOr']);
}
foreach ($orValues as $orValue) {
if (Configure::version() < '2.7') {
$andValues = String::tokenize($orValue, $field['connectorAnd']);
} else {
$andValues = CakeText::tokenize($orValue, $field['connectorAnd']);
}
$and = array();
foreach ($andValues as $andValue) {
$and[] = array($fieldName . " " . $likeMethod => $field['before'] . $andValue . $field['after']);
}
$or[] = array('AND' => $and);
}
return array('OR' => $or);
}
/**
* Add Conditions based on exact comparison
*
* @param Model $Model Reference to the model
* @param array $conditions existing Conditions collected for the model
* @param array $data Array of data used in search query
* @param array $field Field definition information
* @return array of conditions
*/
protected function _addCondValue(Model $Model, &$conditions, $data, $field) {
$fieldNames = (array)$field['field'];
$fieldValue = isset($data[$field['name']]) ? $data[$field['name']] : null;
$cond = array();
foreach ($fieldNames as $fieldName) {
if (strpos($fieldName, '.') === false) {
$fieldName = $Model->alias . '.' . $fieldName;
}
if (is_array($fieldValue) && empty($fieldValue)) {
continue;
}
if (!is_array($fieldValue) && ($fieldValue === null || $fieldValue === '' && empty($field['allowEmpty']))) {
continue;
}
if (is_array($fieldValue) || !is_array($fieldValue) && (string)$fieldValue !== '') {
$cond[$fieldName] = $fieldValue;
} elseif (isset($data[$field['name']]) && !empty($field['allowEmpty'])) {
$schema = $Model->schema($field['name']);
if (isset($schema) && ($schema['default'] !== null || !empty($schema['null']))) {
$cond[$fieldName] = $schema['default'];
} elseif (!empty($fieldValue)) {
$cond[$fieldName] = $fieldValue;
} else {
$cond[$fieldName] = $fieldValue;
}
}
}
if (count($cond) > 1) {
if (isset($conditions['OR'])) {
$conditions[]['OR'] = $cond;
} else {
$conditions['OR'] = $cond;
}
} else {
$conditions = array_merge($conditions, $cond);
}
return $conditions;
}
/**
* Add Conditions based expressions to search conditions.
*
* @param Model $Model Instance of AppModel
* @param array $conditions Existing conditions.
* @param array $data Data for a field.
* @param array $field Info for field.
* @return array of conditions modified by this method
*/
protected function _addCondExpression(Model $Model, &$conditions, $data, $field) {
$fieldName = $field['field'];
if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
$fieldValues = $Model->{$field['method']}($data, $field);
if (!empty($conditions[$fieldName]) && is_array($conditions[$fieldName])) {
$conditions[$fieldName] = array_unique(array_merge(array($conditions[$fieldName]), array($fieldValues)));
} else {
$conditions[$fieldName] = $fieldValues;
}
}
return $conditions;
}
/**
* Add Conditions based query to search conditions.
*
* @param Model $Model Instance of AppModel
* @param array $conditions Existing conditions.
* @param array $data Data for a field.
* @param array $field Info for field.
* @return array of conditions modified by this method
*/
protected function _addCondQuery(Model $Model, &$conditions, $data, $field) {
if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
$conditionsAdd = $Model->{$field['method']}($data, $field);
// if our conditions function returns something empty, nothing to merge in
if (!empty($conditionsAdd)) {
$conditions = Hash::merge($conditions, (array)$conditionsAdd);
}
}
return $conditions;
}
/**
* Add Conditions based subquery to search conditions.
*
* @param Model $Model Instance of AppModel
* @param array $conditions Existing conditions.
* @param array $data Data for a field.
* @param array $field Info for field.
* @return array of conditions modified by this method
*/
protected function _addCondSubquery(Model $Model, &$conditions, $data, $field) {
$fieldName = $field['field'];
if ((method_exists($Model, $field['method']) || $this->_checkBehaviorMethods($Model, $field['method'])) && (!empty($field['allowEmpty']) || !empty($data[$field['name']]) || (isset($data[$field['name']]) && (string)$data[$field['name']] !== ''))) {
$subquery = $Model->{$field['method']}($data, $field);
// if our subquery function returns something empty, nothing to merge in
if (!empty($subquery)) {
$conditions[] = $Model->getDataSource()->expression("$fieldName in ($subquery)");
}
}
return $conditions;
}
/**
* Helper method for getQuery.
* extension of dbo source method. Create association query.
*
* @param Model $Model
* @param array $queryData
* @return string
*/
protected function _queryGet(Model $Model, $queryData = array()) {
/** @var DboSource $db */
$db = $Model->getDataSource();
$queryData = $this->_scrubQueryData($queryData);
$recursive = null;
$byPass = false;
$null = null;
$linkedModels = array();
if (isset($queryData['recursive'])) {
$recursive = $queryData['recursive'];
}
if ($recursive !== null) {
$Model->recursive = $recursive;
}
if (!empty($queryData['fields'])) {
$byPass = true;
$queryData['fields'] = $db->fields($Model, null, $queryData['fields']);
} else {
$queryData['fields'] = $db->fields($Model);
}
$_associations = $Model->associations();
if ($Model->recursive == -1) {
$_associations = array();
} elseif ($Model->recursive == 0) {
unset($_associations[2], $_associations[3]);
}
foreach ($_associations as $type) {
foreach ($Model->{$type} as $assoc => $assocData) {
$linkModel = $Model->{$assoc};
$external = isset($assocData['external']);
$linkModel->getDataSource();
if ($Model->useDbConfig === $linkModel->useDbConfig) {
if ($byPass) {
$assocData['fields'] = false;
}
if ($db->generateAssociationQuery($Model, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null) === true) {
$linkedModels[$type . '/' . $assoc] = true;
}
}
}
}
return trim($db->generateAssociationQuery($Model, null, null, null, null, $queryData, false, $null));
}
/**
* Private helper method to remove query metadata in given data array.
*
* @param array $data
* @return array
*/
protected function _scrubQueryData($data) {
static $base = null;
if ($base === null) {
$base = array_fill_keys(array('conditions', 'fields', 'joins', 'order', 'limit', 'offset', 'group'), array());
}
return (array)$data + $base;
}
/**
* Check if model have some method in attached behaviors
*
* @param Model $Model
* @param string $method
* @return boolean, true if method exists in attached and enabled behaviors
*/
protected function _checkBehaviorMethods(Model $Model, $method) {
$behaviors = $Model->Behaviors->enabled();
$count = count($behaviors);
$found = false;
for ($i = 0; $i < $count; $i++) {
$name = $behaviors[$i];
$methods = get_class_methods($Model->Behaviors->{$name});
$check = array_flip($methods);
$found = isset($check[$method]);
if ($found) {
return true;
}
}
return $found;
}
}