Completed
Push — master ( c17796...052b15 )
by Damian
01:29
created

DataList::each()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 9.4285
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
        } else {
130
            $list = clone $this;
131
            $list->inAlterDataQueryCall = true;
132
133
            try {
134
                $res = call_user_func($callback, $list->dataQuery, $list);
135
                if ($res) {
136
                    $list->dataQuery = $res;
137
                }
138
            } catch (Exception $e) {
139
                $list->inAlterDataQueryCall = false;
140
                throw $e;
141
            }
142
143
            $list->inAlterDataQueryCall = false;
144
            return $list;
145
        }
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 => $val) {
174
                $clone->dataQuery->setQueryParam($key, $val);
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 paramaterised)
188
     */
189
    public function sql(&$parameters = array())
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), array('desc','asc'))) {
334
                user_error('Second argument to sort must be either ASC or DESC');
0 ignored issues
show
Bug introduced by
The call to user_error() has too few arguments starting with error_type. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

334
                /** @scrutinizer ignore-call */ 
335
                user_error('Second argument to sort must be either ASC or DESC');

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
335
            }
336
337
            $sort = array($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 (stristr($sort, ' asc') || stristr($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'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
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 charactaristics
367
     *
368
     * @see SS_List::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)) {
0 ignored issues
show
Bug introduced by
The call to sizeof() has too few arguments starting with mode. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

390
        switch (/** @scrutinizer ignore-call */ sizeof($arguments)) {

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
391
            case 1:
392
                $filters = $arguments[0];
393
394
                break;
395
            case 2:
396
                $filters = array($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(array($filter, 'apply'));
419
        }
420
421
        return $list;
422
    }
423
424
    /**
425
     * Return a copy of this list which contains items matching any of these charactaristics.
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 = array();
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
     * @param string $field Name of field or relation to apply
505
     * @param string &$columnName Quoted column name
506
     * @param bool $linearOnly Set to true to restrict to linear relations only. Set this
507
     * if this relation will be used for sorting, and should not include duplicate rows.
508
     * @return $this DataList with this relation applied
509
     */
510
    public function applyRelation($field, &$columnName = null, $linearOnly = false)
511
    {
512
        // If field is invalid, return it without modification
513
        if (!$this->isValidRelationName($field)) {
514
            $columnName = $field;
515
            return $this;
516
        }
517
518
        // Simple fields without relations are mapped directly
519
        if (strpos($field, '.') === false) {
520
            $columnName = '"'.$field.'"';
521
            return $this;
522
        }
523
524
        return $this->alterDataQuery(
525
            function (DataQuery $query) use ($field, &$columnName, $linearOnly) {
526
                $relations = explode('.', $field);
527
                $fieldName = array_pop($relations);
528
529
                // Apply relation
530
                $relationModelName = $query->applyRelation($relations, $linearOnly);
531
                $relationPrefix = $query->applyRelationPrefix($relations);
532
533
                // Find the db field the relation belongs to
534
                $columnName = DataObject::getSchema()
535
                    ->sqlColumnForField($relationModelName, $fieldName, $relationPrefix);
536
            }
537
        );
538
    }
539
540
    /**
541
     * Check if the given field specification could be interpreted as an unquoted relation name
542
     *
543
     * @param string $field
544
     * @return bool
545
     */
546
    protected function isValidRelationName($field)
547
    {
548
        return preg_match('/^[A-Z0-9._]+$/i', $field);
549
    }
550
551
    /**
552
     * Given a filter expression and value construct a {@see SearchFilter} instance
553
     *
554
     * @param string $filter E.g. `Name:ExactMatch:not`, `Name:ExactMatch`, `Name:not`, `Name`
555
     * @param mixed $value Value of the filter
556
     * @return SearchFilter
557
     */
558
    protected function createSearchFilter($filter, $value)
559
    {
560
        // Field name is always the first component
561
        $fieldArgs = explode(':', $filter);
562
        $fieldName = array_shift($fieldArgs);
563
564
        // Inspect type of second argument to determine context
565
        $secondArg = array_shift($fieldArgs);
566
        $modifiers = $fieldArgs;
567
        if (!$secondArg) {
568
            // Use default filter if none specified. E.g. `->filter(['Name' => $myname])`
569
            $filterServiceName = 'DataListFilter.default';
570
        } else {
571
            // The presence of a second argument is by default ambiguous; We need to query
572
            // Whether this is a valid modifier on the default filter, or a filter itself.
573
            /** @var SearchFilter $defaultFilterInstance */
574
            $defaultFilterInstance = Injector::inst()->get('DataListFilter.default');
575
            if (in_array(strtolower($secondArg), $defaultFilterInstance->getSupportedModifiers())) {
576
                // Treat second (and any subsequent) argument as modifiers, using default filter
577
                $filterServiceName = 'DataListFilter.default';
578
                array_unshift($modifiers, $secondArg);
579
            } else {
580
                // Second argument isn't a valid modifier, so assume is filter identifier
581
                $filterServiceName = "DataListFilter.{$secondArg}";
582
            }
583
        }
584
585
        // Build instance
586
        return Injector::inst()->create($filterServiceName, $fieldName, $value, $modifiers);
587
    }
588
589
    /**
590
     * Return a copy of this list which does not contain any items with these charactaristics
591
     *
592
     * @see SS_List::exclude()
593
     * @example $list = $list->exclude('Name', 'bob'); // exclude bob from list
594
     * @example $list = $list->exclude('Name', array('aziz', 'bob'); // exclude aziz and bob from list
595
     * @example $list = $list->exclude(array('Name'=>'bob, 'Age'=>21)); // exclude bob that has Age 21
596
     * @example $list = $list->exclude(array('Name'=>'bob, 'Age'=>array(21, 43))); // exclude bob with Age 21 or 43
597
     * @example $list = $list->exclude(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43)));
598
     *          // bob age 21 or 43, phil age 21 or 43 would be excluded
599
     *
600
     * @todo extract the sql from this method into a SQLGenerator class
601
     *
602
     * @param string|array Escaped SQL statement. If passed as array, all keys and values will be escaped internally
603
     * @return $this
604
     */
605
    public function exclude()
606
    {
607
        $numberFuncArgs = count(func_get_args());
608
        $whereArguments = array();
609
610
        if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
611
            $whereArguments = func_get_arg(0);
612
        } elseif ($numberFuncArgs == 2) {
613
            $whereArguments[func_get_arg(0)] = func_get_arg(1);
614
        } else {
615
            throw new InvalidArgumentException('Incorrect number of arguments passed to exclude()');
616
        }
617
618
        return $this->alterDataQuery(function (DataQuery $query) use ($whereArguments) {
619
            $subquery = $query->disjunctiveGroup();
620
621
            foreach ($whereArguments as $field => $value) {
622
                $filter = $this->createSearchFilter($field, $value);
623
                $filter->exclude($subquery);
624
            }
625
        });
626
    }
627
628
    /**
629
     * This method returns a copy of this list that does not contain any DataObjects that exists in $list
630
     *
631
     * The $list passed needs to contain the same dataclass as $this
632
     *
633
     * @param DataList $list
634
     * @return static
635
     * @throws InvalidArgumentException
636
     */
637
    public function subtract(DataList $list)
638
    {
639
        if ($this->dataClass() != $list->dataClass()) {
640
            throw new InvalidArgumentException('The list passed must have the same dataclass as this class');
641
        }
642
643
        return $this->alterDataQuery(function (DataQuery $query) use ($list) {
644
            $query->subtract($list->dataQuery());
645
        });
646
    }
647
648
    /**
649
     * Return a new DataList instance with an inner join clause added to this list's query.
650
     *
651
     * @param string $table Table name (unquoted and as escaped SQL)
652
     * @param string $onClause Escaped SQL statement, e.g. '"Table1"."ID" = "Table2"."ID"'
653
     * @param string $alias - if you want this table to be aliased under another name
654
     * @param int $order A numerical index to control the order that joins are added to the query; lower order values
655
     * will cause the query to appear first. The default is 20, and joins created automatically by the
656
     * ORM have a value of 10.
657
     * @param array $parameters Any additional parameters if the join is a parameterised subquery
658
     * @return static
659
     */
660
    public function innerJoin($table, $onClause, $alias = null, $order = 20, $parameters = array())
661
    {
662
        return $this->alterDataQuery(function (DataQuery $query) use ($table, $onClause, $alias, $order, $parameters) {
663
            $query->innerJoin($table, $onClause, $alias, $order, $parameters);
664
        });
665
    }
666
667
    /**
668
     * Return a new DataList instance with a left join clause added to this list's query.
669
     *
670
     * @param string $table Table name (unquoted and as escaped SQL)
671
     * @param string $onClause Escaped SQL statement, e.g. '"Table1"."ID" = "Table2"."ID"'
672
     * @param string $alias - if you want this table to be aliased under another name
673
     * @param int $order A numerical index to control the order that joins are added to the query; lower order values
674
     * will cause the query to appear first. The default is 20, and joins created automatically by the
675
     * ORM have a value of 10.
676
     * @param array $parameters Any additional parameters if the join is a parameterised subquery
677
     * @return static
678
     */
679
    public function leftJoin($table, $onClause, $alias = null, $order = 20, $parameters = array())
680
    {
681
        return $this->alterDataQuery(function (DataQuery $query) use ($table, $onClause, $alias, $order, $parameters) {
682
            $query->leftJoin($table, $onClause, $alias, $order, $parameters);
683
        });
684
    }
685
686
    /**
687
     * Return an array of the actual items that this DataList contains at this stage.
688
     * This is when the query is actually executed.
689
     *
690
     * @return array
691
     */
692
    public function toArray()
693
    {
694
        $query = $this->dataQuery->query();
695
        $rows = $query->execute();
696
        $results = array();
697
698
        foreach ($rows as $row) {
699
            $results[] = $this->createDataObject($row);
700
        }
701
702
        return $results;
703
    }
704
705
    /**
706
     * Return this list as an array and every object it as an sub array as well
707
     *
708
     * @return array
709
     */
710
    public function toNestedArray()
711
    {
712
        $result = array();
713
714
        foreach ($this as $item) {
715
            $result[] = $item->toMap();
716
        }
717
718
        return $result;
719
    }
720
721
    /**
722
     * Walks the list using the specified callback
723
     *
724
     * @param callable $callback
725
     * @return $this
726
     */
727
    public function each($callback)
728
    {
729
        foreach ($this as $row) {
730
            $callback($row);
731
        }
732
733
        return $this;
734
    }
735
736
    public function debug()
737
    {
738
        $val = "<h2>" . static::class . "</h2><ul>";
739
        foreach ($this->toNestedArray() as $item) {
740
            $val .= "<li style=\"list-style-type: disc; margin-left: 20px\">" . Debug::text($item) . "</li>";
741
        }
742
        $val .= "</ul>";
743
        return $val;
744
    }
745
746
    /**
747
     * Returns a map of this list
748
     *
749
     * @param string $keyField - the 'key' field of the result array
750
     * @param string $titleField - the value field of the result array
751
     * @return Map
752
     */
753
    public function map($keyField = 'ID', $titleField = 'Title')
754
    {
755
        return new Map($this, $keyField, $titleField);
756
    }
757
758
    /**
759
     * Create a DataObject from the given SQL row
760
     *
761
     * @param array $row
762
     * @return DataObject
763
     */
764
    public function createDataObject($row)
765
    {
766
        $class = $this->dataClass;
767
768
        if (empty($row['ClassName'])) {
769
            $row['ClassName'] = $class;
770
        }
771
772
        // Failover from RecordClassName to ClassName
773
        if (empty($row['RecordClassName'])) {
774
            $row['RecordClassName'] = $row['ClassName'];
775
        }
776
777
        // Instantiate the class mentioned in RecordClassName only if it exists, otherwise default to $this->dataClass
778
        if (class_exists($row['RecordClassName'])) {
779
            $class = $row['RecordClassName'];
780
        }
781
782
        $item = Injector::inst()->create($class, $row, false, $this->getQueryParams());
783
784
        return $item;
785
    }
786
787
    /**
788
     * Get query parameters for this list.
789
     * These values will be assigned as query parameters to newly created objects from this list.
790
     *
791
     * @return array
792
     */
793
    public function getQueryParams()
794
    {
795
        return $this->dataQuery()->getQueryParams();
796
    }
797
798
    /**
799
     * Returns an Iterator for this DataList.
800
     * This function allows you to use DataLists in foreach loops
801
     *
802
     * @return ArrayIterator
803
     */
804
    public function getIterator()
805
    {
806
        return new ArrayIterator($this->toArray());
807
    }
808
809
    /**
810
     * Return the number of items in this DataList
811
     *
812
     * @return int
813
     */
814
    public function count()
815
    {
816
        return $this->dataQuery->count();
817
    }
818
819
    /**
820
     * Return the maximum value of the given field in this DataList
821
     *
822
     * @param string $fieldName
823
     * @return mixed
824
     */
825
    public function max($fieldName)
826
    {
827
        return $this->dataQuery->max($fieldName);
828
    }
829
830
    /**
831
     * Return the minimum value of the given field in this DataList
832
     *
833
     * @param string $fieldName
834
     * @return mixed
835
     */
836
    public function min($fieldName)
837
    {
838
        return $this->dataQuery->min($fieldName);
839
    }
840
841
    /**
842
     * Return the average value of the given field in this DataList
843
     *
844
     * @param string $fieldName
845
     * @return mixed
846
     */
847
    public function avg($fieldName)
848
    {
849
        return $this->dataQuery->avg($fieldName);
850
    }
851
852
    /**
853
     * Return the sum of the values of the given field in this DataList
854
     *
855
     * @param string $fieldName
856
     * @return mixed
857
     */
858
    public function sum($fieldName)
859
    {
860
        return $this->dataQuery->sum($fieldName);
861
    }
862
863
864
    /**
865
     * Returns the first item in this DataList
866
     *
867
     * @return DataObject
868
     */
869
    public function first()
870
    {
871
        foreach ($this->dataQuery->firstRow()->execute() as $row) {
872
            return $this->createDataObject($row);
873
        }
874
        return null;
875
    }
876
877
    /**
878
     * Returns the last item in this DataList
879
     *
880
     *  @return DataObject
881
     */
882
    public function last()
883
    {
884
        foreach ($this->dataQuery->lastRow()->execute() as $row) {
885
            return $this->createDataObject($row);
886
        }
887
        return null;
888
    }
889
890
    /**
891
     * Returns true if this DataList has items
892
     *
893
     * @return bool
894
     */
895
    public function exists()
896
    {
897
        return $this->count() > 0;
898
    }
899
900
    /**
901
     * Find the first DataObject of this DataList where the given key = value
902
     *
903
     * @param string $key
904
     * @param string $value
905
     * @return DataObject|null
906
     */
907
    public function find($key, $value)
908
    {
909
        return $this->filter($key, $value)->first();
910
    }
911
912
    /**
913
     * Restrict the columns to fetch into this DataList
914
     *
915
     * @param array $queriedColumns
916
     * @return static
917
     */
918
    public function setQueriedColumns($queriedColumns)
919
    {
920
        return $this->alterDataQuery(function (DataQuery $query) use ($queriedColumns) {
921
            $query->setQueriedColumns($queriedColumns);
922
        });
923
    }
924
925
    /**
926
     * Filter this list to only contain the given Primary IDs
927
     *
928
     * @param array $ids Array of integers
929
     * @throws InvalidArgumentException
930
     * @return $this
931
     */
932
    public function byIDs($ids)
933
    {
934
        $intIDs = array();
935
        foreach ($ids as $id) {
936
            if (!is_numeric($id)) {
937
                throw new InvalidArgumentException(
938
                    'Invalid value passed to byIDs() in param array. All params have to be numeric or of type Integer.'
939
                );
940
            }
941
            $intIDs[] = intval($id, 10);
942
        }
943
944
        return $this->filter('ID', $intIDs);
945
    }
946
947
    /**
948
     * Return the first DataObject with the given ID
949
     *
950
     * @param int $id
951
     * @return DataObject
952
     * @throws InvalidArgumentException
953
     */
954
    public function byID($id)
955
    {
956
        if (!is_numeric($id)) {
957
            throw new InvalidArgumentException(
958
                'Incorrect param type for $id passed to byID(). Numeric value is expected.'
959
            );
960
        }
961
        return $this->filter('ID', intval($id, 10))->first();
962
    }
963
964
    /**
965
     * Returns an array of a single field value for all items in the list.
966
     *
967
     * @param string $colName
968
     * @return array
969
     */
970
    public function column($colName = "ID")
971
    {
972
        return $this->dataQuery->column($colName);
973
    }
974
975
    // Member altering methods
976
977
    /**
978
     * Sets the ComponentSet to be the given ID list.
979
     * Records will be added and deleted as appropriate.
980
     *
981
     * @param array $idList List of IDs.
982
     */
983
    public function setByIDList($idList)
984
    {
985
        $has = array();
986
987
        // Index current data
988
        foreach ($this->column() as $id) {
989
            $has[$id] = true;
990
        }
991
992
        // Keep track of items to delete
993
        $itemsToDelete = $has;
994
995
        // add items in the list
996
        // $id is the database ID of the record
997
        if ($idList) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $idList of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
998
            foreach ($idList as $id) {
999
                unset($itemsToDelete[$id]);
1000
                if ($id && !isset($has[$id])) {
1001
                    $this->add($id);
1002
                }
1003
            }
1004
        }
1005
1006
        // Remove any items that haven't been mentioned
1007
        $this->removeMany(array_keys($itemsToDelete));
1008
    }
1009
1010
    /**
1011
     * Returns an array with both the keys and values set to the IDs of the records in this list.
1012
     * Does not respect sort order. Use ->column("ID") to get an ID list with the current sort.
1013
     *
1014
     * @return array
1015
     */
1016
    public function getIDList()
1017
    {
1018
        $ids = $this->column("ID");
1019
        return $ids ? array_combine($ids, $ids) : array();
1020
    }
1021
1022
    /**
1023
     * Returns a HasManyList or ManyMany list representing the querying of a relation across all
1024
     * objects in this data list.  For it to work, the relation must be defined on the data class
1025
     * that you used to create this DataList.
1026
     *
1027
     * Example: Get members from all Groups:
1028
     *
1029
     *     DataList::Create("Group")->relation("Members")
1030
     *
1031
     * @param string $relationName
1032
     * @return HasManyList|ManyManyList
1033
     */
1034
    public function relation($relationName)
1035
    {
1036
        $ids = $this->column('ID');
1037
        $singleton = DataObject::singleton($this->dataClass);
1038
        /** @var HasManyList|ManyManyList $relation */
1039
        $relation = $singleton->$relationName($ids);
1040
        return $relation;
1041
    }
1042
1043
    public function dbObject($fieldName)
1044
    {
1045
        return singleton($this->dataClass)->dbObject($fieldName);
1046
    }
1047
1048
    /**
1049
     * Add a number of items to the component set.
1050
     *
1051
     * @param array $items Items to add, as either DataObjects or IDs.
1052
     * @return $this
1053
     */
1054
    public function addMany($items)
1055
    {
1056
        foreach ($items as $item) {
1057
            $this->add($item);
1058
        }
1059
        return $this;
1060
    }
1061
1062
    /**
1063
     * Remove the items from this list with the given IDs
1064
     *
1065
     * @param array $idList
1066
     * @return $this
1067
     */
1068
    public function removeMany($idList)
1069
    {
1070
        foreach ($idList as $id) {
1071
            $this->removeByID($id);
1072
        }
1073
        return $this;
1074
    }
1075
1076
    /**
1077
     * Remove every element in this DataList matching the given $filter.
1078
     *
1079
     * @param string|array $filter - a sql type where filter
1080
     * @return $this
1081
     */
1082
    public function removeByFilter($filter)
1083
    {
1084
        foreach ($this->where($filter) as $item) {
1085
            $this->remove($item);
1086
        }
1087
        return $this;
1088
    }
1089
1090
    /**
1091
     * Remove every element in this DataList.
1092
     *
1093
     * @return $this
1094
     */
1095
    public function removeAll()
1096
    {
1097
        foreach ($this as $item) {
1098
            $this->remove($item);
1099
        }
1100
        return $this;
1101
    }
1102
1103
    /**
1104
     * This method are overloaded by HasManyList and ManyMany list to perform more sophisticated
1105
     * list manipulation
1106
     *
1107
     * @param mixed $item
1108
     */
1109
    public function add($item)
1110
    {
1111
        // Nothing needs to happen by default
1112
        // TO DO: If a filter is given to this data list then
1113
    }
1114
1115
    /**
1116
     * Return a new item to add to this DataList.
1117
     *
1118
     * @todo This doesn't factor in filters.
1119
     * @param array $initialFields
1120
     * @return DataObject
1121
     */
1122
    public function newObject($initialFields = null)
1123
    {
1124
        $class = $this->dataClass;
1125
        return Injector::inst()->create($class, $initialFields, false);
1126
    }
1127
1128
    /**
1129
     * Remove this item by deleting it
1130
     *
1131
     * @param DataObject $item
1132
     * @todo Allow for amendment of this behaviour - for example, we can remove an item from
1133
     * an "ActiveItems" DataList by chaning the status to inactive.
1134
     */
1135
    public function remove($item)
1136
    {
1137
        // By default, we remove an item from a DataList by deleting it.
1138
        $this->removeByID($item->ID);
1139
    }
1140
1141
    /**
1142
     * Remove an item from this DataList by ID
1143
     *
1144
     * @param int $itemID The primary ID
1145
     */
1146
    public function removeByID($itemID)
1147
    {
1148
        $item = $this->byID($itemID);
1149
1150
        if ($item) {
1151
            $item->delete();
1152
        }
1153
    }
1154
1155
    /**
1156
     * Reverses a list of items.
1157
     *
1158
     * @return static
1159
     */
1160
    public function reverse()
1161
    {
1162
        return $this->alterDataQuery(function (DataQuery $query) {
1163
            $query->reverseSort();
1164
        });
1165
    }
1166
1167
    /**
1168
     * Returns whether an item with $key exists
1169
     *
1170
     * @param mixed $key
1171
     * @return bool
1172
     */
1173
    public function offsetExists($key)
1174
    {
1175
        return ($this->limit(1, $key)->first() != null);
1176
    }
1177
1178
    /**
1179
     * Returns item stored in list with index $key
1180
     *
1181
     * @param mixed $key
1182
     * @return DataObject
1183
     */
1184
    public function offsetGet($key)
1185
    {
1186
        return $this->limit(1, $key)->first();
1187
    }
1188
1189
    /**
1190
     * Set an item with the key in $key
1191
     *
1192
     * @param mixed $key
1193
     * @param mixed $value
1194
     */
1195
    public function offsetSet($key, $value)
1196
    {
1197
        user_error("Can't alter items in a DataList using array-access", E_USER_ERROR);
1198
    }
1199
1200
    /**
1201
     * Unset an item with the key in $key
1202
     *
1203
     * @param mixed $key
1204
     */
1205
    public function offsetUnset($key)
1206
    {
1207
        user_error("Can't alter items in a DataList using array-access", E_USER_ERROR);
1208
    }
1209
}
1210