Passed
Push — pulls/manymanylist-add-callbac... ( 7684da...77b6c5 )
by Sam
09:25
created

DataList::offsetExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\ORM;
4
5
use SilverStripe\Core\Injector\Injector;
6
use SilverStripe\Dev\Debug;
7
use SilverStripe\ORM\Filters\SearchFilter;
8
use SilverStripe\ORM\Queries\SQLConditionGroup;
9
use SilverStripe\View\ViewableData;
10
use ArrayIterator;
11
use Exception;
12
use InvalidArgumentException;
13
use LogicException;
14
15
/**
16
 * Implements a "lazy loading" DataObjectSet.
17
 * Uses {@link DataQuery} to do the actual query generation.
18
 *
19
 * DataLists are _immutable_ as far as the query they represent is concerned. When you call a method that
20
 * alters the query, a new DataList instance is returned, rather than modifying the existing instance
21
 *
22
 * When you add or remove an element to the list the query remains the same, but because you have modified
23
 * the underlying data the contents of the list changes. These are some of those methods:
24
 *
25
 *   - add
26
 *   - addMany
27
 *   - remove
28
 *   - removeMany
29
 *   - removeByID
30
 *   - removeByFilter
31
 *   - removeAll
32
 *
33
 * Subclasses of DataList may add other methods that have the same effect.
34
 */
35
class DataList extends ViewableData implements SS_List, Filterable, Sortable, Limitable
36
{
37
38
    /**
39
     * The DataObject class name that this data list is querying
40
     *
41
     * @var string
42
     */
43
    protected $dataClass;
44
45
    /**
46
     * The {@link DataQuery} object responsible for getting this DataList's records
47
     *
48
     * @var DataQuery
49
     */
50
    protected $dataQuery;
51
52
    /**
53
     * Create a new DataList.
54
     * No querying is done on construction, but the initial query schema is set up.
55
     *
56
     * @param string $dataClass - The DataObject class to query.
57
     */
58
    public function __construct($dataClass)
59
    {
60
        $this->dataClass = $dataClass;
61
        $this->dataQuery = new DataQuery($this->dataClass);
62
63
        parent::__construct();
64
    }
65
66
    /**
67
     * Get the dataClass name for this DataList, ie the DataObject ClassName
68
     *
69
     * @return string
70
     */
71
    public function dataClass()
72
    {
73
        return $this->dataClass;
74
    }
75
76
    /**
77
     * When cloning this object, clone the dataQuery object as well
78
     */
79
    public function __clone()
80
    {
81
        $this->dataQuery = clone $this->dataQuery;
82
    }
83
84
    /**
85
     * Return a copy of the internal {@link DataQuery} object
86
     *
87
     * Because the returned value is a copy, modifying it won't affect this list's contents. If
88
     * you want to alter the data query directly, use the alterDataQuery method
89
     *
90
     * @return DataQuery
91
     */
92
    public function dataQuery()
93
    {
94
        return clone $this->dataQuery;
95
    }
96
97
    /**
98
     * @var bool - Indicates if we are in an alterDataQueryCall already, so alterDataQuery can be re-entrant
99
     */
100
    protected $inAlterDataQueryCall = false;
101
102
    /**
103
     * Return a new DataList instance with the underlying {@link DataQuery} object altered
104
     *
105
     * If you want to alter the underlying dataQuery for this list, this wrapper method
106
     * will ensure that you can do so without mutating the existing List object.
107
     *
108
     * It clones this list, calls the passed callback function with the dataQuery of the new
109
     * list as it's first parameter (and the list as it's second), then returns the list
110
     *
111
     * Note that this function is re-entrant - it's safe to call this inside a callback passed to
112
     * alterDataQuery
113
     *
114
     * @param callable $callback
115
     * @return static
116
     * @throws Exception
117
     */
118
    public function alterDataQuery($callback)
119
    {
120
        if ($this->inAlterDataQueryCall) {
121
            $list = $this;
122
123
            $res = call_user_func($callback, $list->dataQuery, $list);
124
            if ($res) {
125
                $list->dataQuery = $res;
126
            }
127
128
            return $list;
129
        }
130
131
        $list = clone $this;
132
        $list->inAlterDataQueryCall = true;
133
134
        try {
135
            $res = $callback($list->dataQuery, $list);
136
            if ($res) {
137
                $list->dataQuery = $res;
138
            }
139
        } catch (Exception $e) {
140
            $list->inAlterDataQueryCall = false;
141
            throw $e;
142
        }
143
144
        $list->inAlterDataQueryCall = false;
145
        return $list;
146
    }
147
148
    /**
149
     * Return a new DataList instance with the underlying {@link DataQuery} object changed
150
     *
151
     * @param DataQuery $dataQuery
152
     * @return static
153
     */
154
    public function setDataQuery(DataQuery $dataQuery)
155
    {
156
        $clone = clone $this;
157
        $clone->dataQuery = $dataQuery;
158
        return $clone;
159
    }
160
161
    /**
162
     * Returns a new DataList instance with the specified query parameter assigned
163
     *
164
     * @param string|array $keyOrArray Either the single key to set, or an array of key value pairs to set
165
     * @param mixed $val If $keyOrArray is not an array, this is the value to set
166
     * @return static
167
     */
168
    public function setDataQueryParam($keyOrArray, $val = null)
169
    {
170
        $clone = clone $this;
171
172
        if (is_array($keyOrArray)) {
173
            foreach ($keyOrArray as $key => $value) {
174
                $clone->dataQuery->setQueryParam($key, $value);
175
            }
176
        } else {
177
            $clone->dataQuery->setQueryParam($keyOrArray, $val);
178
        }
179
180
        return $clone;
181
    }
182
183
    /**
184
     * Returns the SQL query that will be used to get this DataList's records.  Good for debugging. :-)
185
     *
186
     * @param array $parameters Out variable for parameters required for this query
187
     * @return string The resulting SQL query (may be parameterised)
188
     */
189
    public function sql(&$parameters = [])
190
    {
191
        return $this->dataQuery->query()->sql($parameters);
192
    }
193
194
    /**
195
     * Return a new DataList instance with a WHERE clause added to this list's query.
196
     *
197
     * Supports parameterised queries.
198
     * See SQLSelect::addWhere() for syntax examples, although DataList
199
     * won't expand multiple method arguments as SQLSelect does.
200
     *
201
     * @param string|array|SQLConditionGroup $filter Predicate(s) to set, as escaped SQL statements or
202
     * paramaterised queries
203
     * @return static
204
     */
205
    public function where($filter)
206
    {
207
        return $this->alterDataQuery(function (DataQuery $query) use ($filter) {
208
            $query->where($filter);
209
        });
210
    }
211
212
    /**
213
     * Return a new DataList instance with a WHERE clause added to this list's query.
214
     * All conditions provided in the filter will be joined with an OR
215
     *
216
     * Supports parameterised queries.
217
     * See SQLSelect::addWhere() for syntax examples, although DataList
218
     * won't expand multiple method arguments as SQLSelect does.
219
     *
220
     * @param string|array|SQLConditionGroup $filter Predicate(s) to set, as escaped SQL statements or
221
     * paramaterised queries
222
     * @return static
223
     */
224
    public function whereAny($filter)
225
    {
226
        return $this->alterDataQuery(function (DataQuery $query) use ($filter) {
227
            $query->whereAny($filter);
228
        });
229
    }
230
231
232
233
    /**
234
     * Returns true if this DataList can be sorted by the given field.
235
     *
236
     * @param string $fieldName
237
     * @return boolean
238
     */
239
    public function canSortBy($fieldName)
240
    {
241
        return $this->dataQuery()->query()->canSortBy($fieldName);
242
    }
243
244
    /**
245
     * Returns true if this DataList can be filtered by the given field.
246
     *
247
     * @param string $fieldName (May be a related field in dot notation like Member.FirstName)
248
     * @return boolean
249
     */
250
    public function canFilterBy($fieldName)
251
    {
252
        $model = singleton($this->dataClass);
253
        $relations = explode(".", $fieldName);
254
        // First validate the relationships
255
        $fieldName = array_pop($relations);
256
        foreach ($relations as $r) {
257
            $relationClass = $model->getRelationClass($r);
258
            if (!$relationClass) {
259
                return false;
260
            }
261
            $model = singleton($relationClass);
262
            if (!$model) {
263
                return false;
264
            }
265
        }
266
        // Then check field
267
        if ($model->hasDatabaseField($fieldName)) {
268
            return true;
269
        }
270
        return false;
271
    }
272
273
    /**
274
     * Return a new DataList instance with the records returned in this query
275
     * restricted by a limit clause.
276
     *
277
     * @param int $limit
278
     * @param int $offset
279
     * @return static
280
     */
281
    public function limit($limit, $offset = 0)
282
    {
283
        return $this->alterDataQuery(function (DataQuery $query) use ($limit, $offset) {
284
            $query->limit($limit, $offset);
285
        });
286
    }
287
288
    /**
289
     * Return a new DataList instance with distinct records or not
290
     *
291
     * @param bool $value
292
     * @return static
293
     */
294
    public function distinct($value)
295
    {
296
        return $this->alterDataQuery(function (DataQuery $query) use ($value) {
297
            $query->distinct($value);
298
        });
299
    }
300
301
    /**
302
     * Return a new DataList instance as a copy of this data list with the sort
303
     * order set.
304
     *
305
     * @see SS_List::sort()
306
     * @see SQLSelect::orderby
307
     * @example $list = $list->sort('Name'); // default ASC sorting
308
     * @example $list = $list->sort('Name DESC'); // DESC sorting
309
     * @example $list = $list->sort('Name', 'ASC');
310
     * @example $list = $list->sort(array('Name'=>'ASC', 'Age'=>'DESC'));
311
     *
312
     * @param String|array Escaped SQL statement. If passed as array, all keys and values are assumed to be escaped.
0 ignored issues
show
Bug introduced by
The type SilverStripe\ORM\Escaped was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
313
     * @return static
314
     */
315
    public function sort()
316
    {
317
        $count = func_num_args();
318
319
        if ($count == 0) {
320
            return $this;
321
        }
322
323
        if ($count > 2) {
324
            throw new InvalidArgumentException('This method takes zero, one or two arguments');
325
        }
326
327
        if ($count == 2) {
328
            $col = null;
329
            $dir = null;
330
            list($col, $dir) = func_get_args();
331
332
            // Validate direction
333
            if (!in_array(strtolower($dir), ['desc', 'asc'])) {
334
                user_error('Second argument to sort must be either ASC or DESC');
335
            }
336
337
            $sort = [$col => $dir];
338
        } else {
339
            $sort = func_get_arg(0);
340
        }
341
342
        return $this->alterDataQuery(function (DataQuery $query, DataList $list) use ($sort) {
343
344
            if (is_string($sort) && $sort) {
345
                if (false !== stripos($sort, ' asc') || false !== stripos($sort, ' desc')) {
346
                    $query->sort($sort);
347
                } else {
348
                    $list->applyRelation($sort, $column, true);
349
                    $query->sort($column, 'ASC');
350
                }
351
            } elseif (is_array($sort)) {
352
                // sort(array('Name'=>'desc'));
353
                $query->sort(null, null); // wipe the sort
354
355
                foreach ($sort as $column => $direction) {
356
                    // Convert column expressions to SQL fragment, while still allowing the passing of raw SQL
357
                    // fragments.
358
                    $list->applyRelation($column, $relationColumn, true);
359
                    $query->sort($relationColumn, $direction, false);
360
                }
361
            }
362
        });
363
    }
364
365
    /**
366
     * Return a copy of this list which only includes items with these characteristics
367
     *
368
     * @see Filterable::filter()
369
     *
370
     * @example $list = $list->filter('Name', 'bob'); // only bob in the list
371
     * @example $list = $list->filter('Name', array('aziz', 'bob'); // aziz and bob in list
372
     * @example $list = $list->filter(array('Name'=>'bob', 'Age'=>21)); // bob with the age 21
373
     * @example $list = $list->filter(array('Name'=>'bob', 'Age'=>array(21, 43))); // bob with the Age 21 or 43
374
     * @example $list = $list->filter(array('Name'=>array('aziz','bob'), 'Age'=>array(21, 43)));
375
     *          // aziz with the age 21 or 43 and bob with the Age 21 or 43
376
     *
377
     * Note: When filtering on nullable columns, null checks will be automatically added.
378
     * E.g. ->filter('Field:not', 'value) will generate '... OR "Field" IS NULL', and
379
     * ->filter('Field:not', null) will generate '"Field" IS NOT NULL'
380
     *
381
     * @todo extract the sql from $customQuery into a SQLGenerator class
382
     *
383
     * @param string|array Escaped SQL statement. If passed as array, all keys and values will be escaped internally
384
     * @return $this
385
     */
386
    public function filter()
387
    {
388
        // Validate and process arguments
389
        $arguments = func_get_args();
390
        switch (sizeof($arguments)) {
391
            case 1:
392
                $filters = $arguments[0];
393
394
                break;
395
            case 2:
396
                $filters = [$arguments[0] => $arguments[1]];
397
398
                break;
399
            default:
400
                throw new InvalidArgumentException('Incorrect number of arguments passed to filter()');
401
        }
402
403
        return $this->addFilter($filters);
404
    }
405
406
    /**
407
     * Return a new instance of the list with an added filter
408
     *
409
     * @param array $filterArray
410
     * @return $this
411
     */
412
    public function addFilter($filterArray)
413
    {
414
        $list = $this;
415
416
        foreach ($filterArray as $expression => $value) {
417
            $filter = $this->createSearchFilter($expression, $value);
418
            $list = $list->alterDataQuery([$filter, 'apply']);
419
        }
420
421
        return $list;
422
    }
423
424
    /**
425
     * Return a copy of this list which contains items matching any of these characteristics.
426
     *
427
     * @example // only bob in the list
428
     *          $list = $list->filterAny('Name', 'bob');
429
     *          // SQL: WHERE "Name" = 'bob'
430
     * @example // azis or bob in the list
431
     *          $list = $list->filterAny('Name', array('aziz', 'bob');
432
     *          // SQL: WHERE ("Name" IN ('aziz','bob'))
433
     * @example // bob or anyone aged 21 in the list
434
     *          $list = $list->filterAny(array('Name'=>'bob, 'Age'=>21));
435
     *          // SQL: WHERE ("Name" = 'bob' OR "Age" = '21')
436
     * @example // bob or anyone aged 21 or 43 in the list
437
     *          $list = $list->filterAny(array('Name'=>'bob, 'Age'=>array(21, 43)));
438
     *          // SQL: WHERE ("Name" = 'bob' OR ("Age" IN ('21', '43'))
439
     * @example // all bobs, phils or anyone aged 21 or 43 in the list
440
     *          $list = $list->filterAny(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43)));
441
     *          // SQL: WHERE (("Name" IN ('bob', 'phil')) OR ("Age" IN ('21', '43'))
442
     *
443
     * @todo extract the sql from this method into a SQLGenerator class
444
     *
445
     * @param string|array See {@link filter()}
0 ignored issues
show
Bug introduced by
The type SilverStripe\ORM\See was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
446
     * @return static
447
     */
448
    public function filterAny()
449
    {
450
        $numberFuncArgs = count(func_get_args());
451
        $whereArguments = [];
452
453
        if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
454
            $whereArguments = func_get_arg(0);
455
        } elseif ($numberFuncArgs == 2) {
456
            $whereArguments[func_get_arg(0)] = func_get_arg(1);
457
        } else {
458
            throw new InvalidArgumentException('Incorrect number of arguments passed to filterAny()');
459
        }
460
461
        return $this->alterDataQuery(function (DataQuery $query) use ($whereArguments) {
462
            $subquery = $query->disjunctiveGroup();
463
464
            foreach ($whereArguments as $field => $value) {
465
                $filter = $this->createSearchFilter($field, $value);
466
                $filter->apply($subquery);
467
            }
468
        });
469
    }
470
471
    /**
472
     * Note that, in the current implementation, the filtered list will be an ArrayList, but this may change in a
473
     * future implementation.
474
     * @see Filterable::filterByCallback()
475
     *
476
     * @example $list = $list->filterByCallback(function($item, $list) { return $item->Age == 9; })
477
     * @param callable $callback
478
     * @return ArrayList (this may change in future implementations)
479
     */
480
    public function filterByCallback($callback)
481
    {
482
        if (!is_callable($callback)) {
483
            throw new LogicException(sprintf(
484
                "SS_Filterable::filterByCallback() passed callback must be callable, '%s' given",
485
                gettype($callback)
486
            ));
487
        }
488
        /** @var ArrayList $output */
489
        $output = ArrayList::create();
490
        foreach ($this as $item) {
491
            if (call_user_func($callback, $item, $this)) {
492
                $output->push($item);
493
            }
494
        }
495
        return $output;
496
    }
497
498
    /**
499
     * Given a field or relation name, apply it safely to this datalist.
500
     *
501
     * Unlike getRelationName, this is immutable and will fallback to the quoted field
502
     * name if not a relation.
503
     *
504
     * Example use (simple WHERE condition on data sitting in a related table):
505
     *
506
     * <code>
507
     *  $columnName = null;
508
     *  $list = Page::get()
509
     *    ->applyRelation('TaxonomyTerms.ID', $columnName)
510
     *    ->where([$columnName => 'my value']);
511
     * </code>
512
     *
513
     *
514
     * @param string $field Name of field or relation to apply
515
     * @param string &$columnName Quoted column name
516
     * @param bool $linearOnly Set to true to restrict to linear relations only. Set this
517
     * if this relation will be used for sorting, and should not include duplicate rows.
518
     * @return $this DataList with this relation applied
519
     */
520
    public function applyRelation($field, &$columnName = null, $linearOnly = false)
521
    {
522
        // If field is invalid, return it without modification
523
        if (!$this->isValidRelationName($field)) {
524
            $columnName = $field;
525
            return $this;
526
        }
527
528
        // Simple fields without relations are mapped directly
529
        if (strpos($field, '.') === false) {
530
            $columnName = '"' . $field . '"';
531
            return $this;
532
        }
533
534
        return $this->alterDataQuery(
535
            function (DataQuery $query) use ($field, &$columnName, $linearOnly) {
536
                $relations = explode('.', $field);
537
                $fieldName = array_pop($relations);
538
539
                // Apply relation
540
                $relationModelName = $query->applyRelation($relations, $linearOnly);
541
                $relationPrefix = $query->applyRelationPrefix($relations);
542
543
                // Find the db field the relation belongs to
544
                $columnName = DataObject::getSchema()
545
                    ->sqlColumnForField($relationModelName, $fieldName, $relationPrefix);
546
            }
547
        );
548
    }
549
550
    /**
551
     * Check if the given field specification could be interpreted as an unquoted relation name
552
     *
553
     * @param string $field
554
     * @return bool
555
     */
556
    protected function isValidRelationName($field)
557
    {
558
        return preg_match('/^[A-Z0-9._]+$/i', $field);
0 ignored issues
show
Bug Best Practice introduced by
The expression return preg_match('/^[A-Z0-9._]+$/i', $field) returns the type integer which is incompatible with the documented return type boolean.
Loading history...
559
    }
560
561
    /**
562
     * Given a filter expression and value construct a {@see SearchFilter} instance
563
     *
564
     * @param string $filter E.g. `Name:ExactMatch:not`, `Name:ExactMatch`, `Name:not`, `Name`
565
     * @param mixed $value Value of the filter
566
     * @return SearchFilter
567
     */
568
    protected function createSearchFilter($filter, $value)
569
    {
570
        // Field name is always the first component
571
        $fieldArgs = explode(':', $filter);
572
        $fieldName = array_shift($fieldArgs);
573
574
        // Inspect type of second argument to determine context
575
        $secondArg = array_shift($fieldArgs);
576
        $modifiers = $fieldArgs;
577
        if (!$secondArg) {
578
            // Use default filter if none specified. E.g. `->filter(['Name' => $myname])`
579
            $filterServiceName = 'DataListFilter.default';
580
        } else {
581
            // The presence of a second argument is by default ambiguous; We need to query
582
            // Whether this is a valid modifier on the default filter, or a filter itself.
583
            /** @var SearchFilter $defaultFilterInstance */
584
            $defaultFilterInstance = Injector::inst()->get('DataListFilter.default');
585
            if (in_array(strtolower($secondArg), $defaultFilterInstance->getSupportedModifiers())) {
586
                // Treat second (and any subsequent) argument as modifiers, using default filter
587
                $filterServiceName = 'DataListFilter.default';
588
                array_unshift($modifiers, $secondArg);
589
            } else {
590
                // Second argument isn't a valid modifier, so assume is filter identifier
591
                $filterServiceName = "DataListFilter.{$secondArg}";
592
            }
593
        }
594
595
        // Build instance
596
        return Injector::inst()->create($filterServiceName, $fieldName, $value, $modifiers);
597
    }
598
599
    /**
600
     * Return a copy of this list which does not contain any items that match all params
601
     *
602
     * @example $list = $list->exclude('Name', 'bob'); // exclude bob from list
603
     * @example $list = $list->exclude('Name', array('aziz', 'bob'); // exclude aziz and bob from list
604
     * @example $list = $list->exclude(array('Name'=>'bob, 'Age'=>21)); // exclude bob that has Age 21
605
     * @example $list = $list->exclude(array('Name'=>'bob, 'Age'=>array(21, 43))); // exclude bob with Age 21 or 43
606
     * @example $list = $list->exclude(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43)));
607
     *          // bob age 21 or 43, phil age 21 or 43 would be excluded
608
     *
609
     * @todo extract the sql from this method into a SQLGenerator class
610
     *
611
     * @param string|array
612
     * @param string [optional]
613
     *
614
     * @return $this
615
     */
616
    public function exclude()
617
    {
618
        $numberFuncArgs = count(func_get_args());
619
        $whereArguments = [];
620
621
        if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
622
            $whereArguments = func_get_arg(0);
623
        } elseif ($numberFuncArgs == 2) {
624
            $whereArguments[func_get_arg(0)] = func_get_arg(1);
625
        } else {
626
            throw new InvalidArgumentException('Incorrect number of arguments passed to exclude()');
627
        }
628
629
        return $this->alterDataQuery(function (DataQuery $query) use ($whereArguments) {
630
            $subquery = $query->disjunctiveGroup();
631
632
            foreach ($whereArguments as $field => $value) {
633
                $filter = $this->createSearchFilter($field, $value);
634
                $filter->exclude($subquery);
635
            }
636
        });
637
    }
638
639
    /**
640
     * Return a copy of this list which does not contain any items with any of these params
641
     *
642
     * @example $list = $list->excludeAny('Name', 'bob'); // exclude bob from list
643
     * @example $list = $list->excludeAny('Name', array('aziz', 'bob'); // exclude aziz and bob from list
644
     * @example $list = $list->excludeAny(array('Name'=>'bob, 'Age'=>21)); // exclude bob or Age 21
645
     * @example $list = $list->excludeAny(array('Name'=>'bob, 'Age'=>array(21, 43))); // exclude bob or Age 21 or 43
646
     * @example $list = $list->excludeAny(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43)));
647
     *          // bob, phil, 21 or 43 would be excluded
648
     *
649
     * @param string|array
650
     * @param string [optional]
651
     *
652
     * @return $this
653
     */
654
    public function excludeAny()
655
    {
656
        $numberFuncArgs = count(func_get_args());
657
        $whereArguments = [];
658
659
        if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
660
            $whereArguments = func_get_arg(0);
661
        } elseif ($numberFuncArgs == 2) {
662
            $whereArguments[func_get_arg(0)] = func_get_arg(1);
663
        } else {
664
            throw new InvalidArgumentException('Incorrect number of arguments passed to excludeAny()');
665
        }
666
667
        return $this->alterDataQuery(function (DataQuery $dataQuery) use ($whereArguments) {
668
            foreach ($whereArguments as $field => $value) {
669
                $filter = $this->createSearchFilter($field, $value);
670
                $filter->exclude($dataQuery);
671
            }
672
            return $dataQuery;
673
        });
674
    }
675
676
    /**
677
     * This method returns a copy of this list that does not contain any DataObjects that exists in $list
678
     *
679
     * The $list passed needs to contain the same dataclass as $this
680
     *
681
     * @param DataList $list
682
     * @return static
683
     * @throws InvalidArgumentException
684
     */
685
    public function subtract(DataList $list)
686
    {
687
        if ($this->dataClass() != $list->dataClass()) {
688
            throw new InvalidArgumentException('The list passed must have the same dataclass as this class');
689
        }
690
691
        return $this->alterDataQuery(function (DataQuery $query) use ($list) {
692
            $query->subtract($list->dataQuery());
693
        });
694
    }
695
696
    /**
697
     * Return a new DataList instance with an inner join clause added to this list's query.
698
     *
699
     * @param string $table Table name (unquoted and as escaped SQL)
700
     * @param string $onClause Escaped SQL statement, e.g. '"Table1"."ID" = "Table2"."ID"'
701
     * @param string $alias - if you want this table to be aliased under another name
702
     * @param int $order A numerical index to control the order that joins are added to the query; lower order values
703
     * will cause the query to appear first. The default is 20, and joins created automatically by the
704
     * ORM have a value of 10.
705
     * @param array $parameters Any additional parameters if the join is a parameterised subquery
706
     * @return static
707
     */
708
    public function innerJoin($table, $onClause, $alias = null, $order = 20, $parameters = [])
709
    {
710
        return $this->alterDataQuery(function (DataQuery $query) use ($table, $onClause, $alias, $order, $parameters) {
711
            $query->innerJoin($table, $onClause, $alias, $order, $parameters);
712
        });
713
    }
714
715
    /**
716
     * Return a new DataList instance with a left join clause added to this list's query.
717
     *
718
     * @param string $table Table name (unquoted and as escaped SQL)
719
     * @param string $onClause Escaped SQL statement, e.g. '"Table1"."ID" = "Table2"."ID"'
720
     * @param string $alias - if you want this table to be aliased under another name
721
     * @param int $order A numerical index to control the order that joins are added to the query; lower order values
722
     * will cause the query to appear first. The default is 20, and joins created automatically by the
723
     * ORM have a value of 10.
724
     * @param array $parameters Any additional parameters if the join is a parameterised subquery
725
     * @return static
726
     */
727
    public function leftJoin($table, $onClause, $alias = null, $order = 20, $parameters = [])
728
    {
729
        return $this->alterDataQuery(function (DataQuery $query) use ($table, $onClause, $alias, $order, $parameters) {
730
            $query->leftJoin($table, $onClause, $alias, $order, $parameters);
731
        });
732
    }
733
734
    /**
735
     * Return an array of the actual items that this DataList contains at this stage.
736
     * This is when the query is actually executed.
737
     *
738
     * @return array
739
     */
740
    public function toArray()
741
    {
742
        $query = $this->dataQuery->query();
743
        $rows = $query->execute();
744
        $results = [];
745
746
        foreach ($rows as $row) {
747
            $results[] = $this->createDataObject($row);
748
        }
749
750
        return $results;
751
    }
752
753
    /**
754
     * Return this list as an array and every object it as an sub array as well
755
     *
756
     * @return array
757
     */
758
    public function toNestedArray()
759
    {
760
        $result = [];
761
762
        foreach ($this as $item) {
763
            $result[] = $item->toMap();
764
        }
765
766
        return $result;
767
    }
768
769
    /**
770
     * Walks the list using the specified callback
771
     *
772
     * @param callable $callback
773
     * @return $this
774
     */
775
    public function each($callback)
776
    {
777
        foreach ($this as $row) {
778
            $callback($row);
779
        }
780
781
        return $this;
782
    }
783
784
    /**
785
     * Returns a generator for this DataList
786
     *
787
     * @return \Generator&DataObject[]
788
     */
789
    public function getGenerator()
790
    {
791
        $query = $this->dataQuery->query()->execute();
792
793
        while ($row = $query->record()) {
794
            yield $this->createDataObject($row);
795
        }
796
    }
797
798
    public function debug()
799
    {
800
        $val = "<h2>" . static::class . "</h2><ul>";
801
        foreach ($this->toNestedArray() as $item) {
802
            $val .= "<li style=\"list-style-type: disc; margin-left: 20px\">" . Debug::text($item) . "</li>";
803
        }
804
        $val .= "</ul>";
805
        return $val;
806
    }
807
808
    /**
809
     * Returns a map of this list
810
     *
811
     * @param string $keyField - the 'key' field of the result array
812
     * @param string $titleField - the value field of the result array
813
     * @return Map
814
     */
815
    public function map($keyField = 'ID', $titleField = 'Title')
816
    {
817
        return new Map($this, $keyField, $titleField);
818
    }
819
820
    /**
821
     * Create a DataObject from the given SQL row
822
     *
823
     * @param array $row
824
     * @return DataObject
825
     */
826
    public function createDataObject($row)
827
    {
828
        $class = $this->dataClass;
829
830
        if (empty($row['ClassName'])) {
831
            $row['ClassName'] = $class;
832
        }
833
834
        // Failover from RecordClassName to ClassName
835
        if (empty($row['RecordClassName'])) {
836
            $row['RecordClassName'] = $row['ClassName'];
837
        }
838
839
        // Instantiate the class mentioned in RecordClassName only if it exists, otherwise default to $this->dataClass
840
        if (class_exists($row['RecordClassName'])) {
841
            $class = $row['RecordClassName'];
842
        }
843
844
        $item = Injector::inst()->create($class, $row, false, $this->getQueryParams());
845
846
        return $item;
847
    }
848
849
    /**
850
     * Get query parameters for this list.
851
     * These values will be assigned as query parameters to newly created objects from this list.
852
     *
853
     * @return array
854
     */
855
    public function getQueryParams()
856
    {
857
        return $this->dataQuery()->getQueryParams();
858
    }
859
860
    /**
861
     * Returns an Iterator for this DataList.
862
     * This function allows you to use DataLists in foreach loops
863
     *
864
     * @return ArrayIterator
865
     */
866
    public function getIterator()
867
    {
868
        return new ArrayIterator($this->toArray());
869
    }
870
871
    /**
872
     * Return the number of items in this DataList
873
     *
874
     * @return int
875
     */
876
    public function count()
877
    {
878
        return $this->dataQuery->count();
879
    }
880
881
    /**
882
     * Return the maximum value of the given field in this DataList
883
     *
884
     * @param string $fieldName
885
     * @return mixed
886
     */
887
    public function max($fieldName)
888
    {
889
        return $this->dataQuery->max($fieldName);
890
    }
891
892
    /**
893
     * Return the minimum value of the given field in this DataList
894
     *
895
     * @param string $fieldName
896
     * @return mixed
897
     */
898
    public function min($fieldName)
899
    {
900
        return $this->dataQuery->min($fieldName);
901
    }
902
903
    /**
904
     * Return the average value of the given field in this DataList
905
     *
906
     * @param string $fieldName
907
     * @return mixed
908
     */
909
    public function avg($fieldName)
910
    {
911
        return $this->dataQuery->avg($fieldName);
912
    }
913
914
    /**
915
     * Return the sum of the values of the given field in this DataList
916
     *
917
     * @param string $fieldName
918
     * @return mixed
919
     */
920
    public function sum($fieldName)
921
    {
922
        return $this->dataQuery->sum($fieldName);
923
    }
924
925
926
    /**
927
     * Returns the first item in this DataList
928
     *
929
     * The object returned is not cached, unlike {@link DataObject::get_one()}
930
     *
931
     * @return DataObject
932
     */
933
    public function first()
934
    {
935
        foreach ($this->dataQuery->firstRow()->execute() as $row) {
936
            return $this->createDataObject($row);
937
        }
938
        return null;
939
    }
940
941
    /**
942
     * Returns the last item in this DataList
943
     *
944
     * The object returned is not cached, unlike {@link DataObject::get_one()}
945
     *
946
     * @return DataObject
947
     */
948
    public function last()
949
    {
950
        foreach ($this->dataQuery->lastRow()->execute() as $row) {
951
            return $this->createDataObject($row);
952
        }
953
        return null;
954
    }
955
956
    /**
957
     * Returns true if this DataList has items
958
     *
959
     * @return bool
960
     */
961
    public function exists()
962
    {
963
        return $this->count() > 0;
964
    }
965
966
    /**
967
     * Find the first DataObject of this DataList where the given key = value
968
     *
969
     * The object returned is not cached, unlike {@link DataObject::get_one()}
970
     *
971
     * @param string $key
972
     * @param string $value
973
     * @return DataObject|null
974
     */
975
    public function find($key, $value)
976
    {
977
        return $this->filter($key, $value)->first();
978
    }
979
980
    /**
981
     * Restrict the columns to fetch into this DataList
982
     *
983
     * @param array $queriedColumns
984
     * @return static
985
     */
986
    public function setQueriedColumns($queriedColumns)
987
    {
988
        return $this->alterDataQuery(function (DataQuery $query) use ($queriedColumns) {
989
            $query->setQueriedColumns($queriedColumns);
990
        });
991
    }
992
993
    /**
994
     * Filter this list to only contain the given Primary IDs
995
     *
996
     * @param array $ids Array of integers
997
     * @return $this
998
     */
999
    public function byIDs($ids)
1000
    {
1001
        return $this->filter('ID', $ids);
1002
    }
1003
1004
    /**
1005
     * Return the first DataObject with the given ID
1006
     *
1007
     * The object returned is not cached, unlike {@link DataObject::get_by_id()}
1008
     *
1009
     * @param int $id
1010
     * @return DataObject
1011
     */
1012
    public function byID($id)
1013
    {
1014
        return $this->filter('ID', $id)->first();
1015
    }
1016
1017
    /**
1018
     * Returns an array of a single field value for all items in the list.
1019
     *
1020
     * @param string $colName
1021
     * @return array
1022
     */
1023
    public function column($colName = "ID")
1024
    {
1025
        return $this->dataQuery->distinct(false)->column($colName);
1026
    }
1027
1028
    /**
1029
     * Returns a unque array of a single field value for all items in the list.
1030
     *
1031
     * @param string $colName
1032
     * @return array
1033
     */
1034
    public function columnUnique($colName = "ID")
1035
    {
1036
        return $this->dataQuery->distinct(true)->column($colName);
1037
    }
1038
1039
    // Member altering methods
1040
1041
    /**
1042
     * Sets the ComponentSet to be the given ID list.
1043
     * Records will be added and deleted as appropriate.
1044
     *
1045
     * @param array $idList List of IDs.
1046
     */
1047
    public function setByIDList($idList)
1048
    {
1049
        $has = [];
1050
1051
        // Index current data
1052
        foreach ($this->column() as $id) {
1053
            $has[$id] = true;
1054
        }
1055
1056
        // Keep track of items to delete
1057
        $itemsToDelete = $has;
1058
1059
        // add items in the list
1060
        // $id is the database ID of the record
1061
        if ($idList) {
1062
            foreach ($idList as $id) {
1063
                unset($itemsToDelete[$id]);
1064
                if ($id && !isset($has[$id])) {
1065
                    $this->add($id);
1066
                }
1067
            }
1068
        }
1069
1070
        // Remove any items that haven't been mentioned
1071
        $this->removeMany(array_keys($itemsToDelete));
1072
    }
1073
1074
    /**
1075
     * Returns an array with both the keys and values set to the IDs of the records in this list.
1076
     * Does not respect sort order. Use ->column("ID") to get an ID list with the current sort.
1077
     *
1078
     * @return array
1079
     */
1080
    public function getIDList()
1081
    {
1082
        $ids = $this->column("ID");
1083
        return $ids ? array_combine($ids, $ids) : [];
0 ignored issues
show
Bug Best Practice introduced by
The expression return $ids ? array_combine($ids, $ids) : array() could also return false which is incompatible with the documented return type array. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
1084
    }
1085
1086
    /**
1087
     * Returns a HasManyList or ManyMany list representing the querying of a relation across all
1088
     * objects in this data list.  For it to work, the relation must be defined on the data class
1089
     * that you used to create this DataList.
1090
     *
1091
     * Example: Get members from all Groups:
1092
     *
1093
     *     DataList::Create(\SilverStripe\Security\Group::class)->relation("Members")
1094
     *
1095
     * @param string $relationName
1096
     * @return HasManyList|ManyManyList
1097
     */
1098
    public function relation($relationName)
1099
    {
1100
        $ids = $this->column('ID');
1101
        $singleton = DataObject::singleton($this->dataClass);
1102
        /** @var HasManyList|ManyManyList $relation */
1103
        $relation = $singleton->$relationName($ids);
1104
        return $relation;
1105
    }
1106
1107
    public function dbObject($fieldName)
1108
    {
1109
        return singleton($this->dataClass)->dbObject($fieldName);
1110
    }
1111
1112
    /**
1113
     * Add a number of items to the component set.
1114
     *
1115
     * @param array $items Items to add, as either DataObjects or IDs.
1116
     * @return $this
1117
     */
1118
    public function addMany($items)
1119
    {
1120
        foreach ($items as $item) {
1121
            $this->add($item);
1122
        }
1123
        return $this;
1124
    }
1125
1126
    /**
1127
     * Remove the items from this list with the given IDs
1128
     *
1129
     * @param array $idList
1130
     * @return $this
1131
     */
1132
    public function removeMany($idList)
1133
    {
1134
        foreach ($idList as $id) {
1135
            $this->removeByID($id);
1136
        }
1137
        return $this;
1138
    }
1139
1140
    /**
1141
     * Remove every element in this DataList matching the given $filter.
1142
     *
1143
     * @param string|array $filter - a sql type where filter
1144
     * @return $this
1145
     */
1146
    public function removeByFilter($filter)
1147
    {
1148
        foreach ($this->where($filter) as $item) {
1149
            $this->remove($item);
1150
        }
1151
        return $this;
1152
    }
1153
1154
    /**
1155
     * Shuffle the datalist using a random function provided by the SQL engine
1156
     *
1157
     * @return $this
1158
     */
1159
    public function shuffle()
1160
    {
1161
        return $this->sort(DB::get_conn()->random());
1162
    }
1163
1164
    /**
1165
     * Remove every element in this DataList.
1166
     *
1167
     * @return $this
1168
     */
1169
    public function removeAll()
1170
    {
1171
        foreach ($this as $item) {
1172
            $this->remove($item);
1173
        }
1174
        return $this;
1175
    }
1176
1177
    /**
1178
     * This method are overloaded by HasManyList and ManyMany list to perform more sophisticated
1179
     * list manipulation
1180
     *
1181
     * @param mixed $item
1182
     */
1183
    public function add($item)
1184
    {
1185
        // Nothing needs to happen by default
1186
        // TO DO: If a filter is given to this data list then
1187
    }
1188
1189
    /**
1190
     * Return a new item to add to this DataList.
1191
     *
1192
     * @todo This doesn't factor in filters.
1193
     * @param array $initialFields
1194
     * @return DataObject
1195
     */
1196
    public function newObject($initialFields = null)
1197
    {
1198
        $class = $this->dataClass;
1199
        return Injector::inst()->create($class, $initialFields, false);
1200
    }
1201
1202
    /**
1203
     * Remove this item by deleting it
1204
     *
1205
     * @param DataObject $item
1206
     * @todo Allow for amendment of this behaviour - for example, we can remove an item from
1207
     * an "ActiveItems" DataList by chaning the status to inactive.
1208
     */
1209
    public function remove($item)
1210
    {
1211
        // By default, we remove an item from a DataList by deleting it.
1212
        $this->removeByID($item->ID);
1213
    }
1214
1215
    /**
1216
     * Remove an item from this DataList by ID
1217
     *
1218
     * @param int $itemID The primary ID
1219
     */
1220
    public function removeByID($itemID)
1221
    {
1222
        $item = $this->byID($itemID);
1223
1224
        if ($item) {
0 ignored issues
show
introduced by
$item is of type SilverStripe\ORM\DataObject, thus it always evaluated to true.
Loading history...
1225
            $item->delete();
1226
        }
1227
    }
1228
1229
    /**
1230
     * Reverses a list of items.
1231
     *
1232
     * @return static
1233
     */
1234
    public function reverse()
1235
    {
1236
        return $this->alterDataQuery(function (DataQuery $query) {
1237
            $query->reverseSort();
1238
        });
1239
    }
1240
1241
    /**
1242
     * Returns whether an item with $key exists
1243
     *
1244
     * @param mixed $key
1245
     * @return bool
1246
     */
1247
    public function offsetExists($key)
1248
    {
1249
        return ($this->limit(1, $key)->first() != null);
1250
    }
1251
1252
    /**
1253
     * Returns item stored in list with index $key
1254
     *
1255
     * The object returned is not cached, unlike {@link DataObject::get_one()}
1256
     *
1257
     * @param mixed $key
1258
     * @return DataObject
1259
     */
1260
    public function offsetGet($key)
1261
    {
1262
        return $this->limit(1, $key)->first();
1263
    }
1264
1265
    /**
1266
     * Set an item with the key in $key
1267
     *
1268
     * @param mixed $key
1269
     * @param mixed $value
1270
     */
1271
    public function offsetSet($key, $value)
1272
    {
1273
        user_error("Can't alter items in a DataList using array-access", E_USER_ERROR);
1274
    }
1275
1276
    /**
1277
     * Unset an item with the key in $key
1278
     *
1279
     * @param mixed $key
1280
     */
1281
    public function offsetUnset($key)
1282
    {
1283
        user_error("Can't alter items in a DataList using array-access", E_USER_ERROR);
1284
    }
1285
}
1286