Completed
Push — master ( c75f75...29f450 )
by Sam
08:47
created

DataList::removeByID()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
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
     * The DataModel from which this DataList comes.
54
     *
55
     * @var DataModel
56
     */
57
    protected $model;
58
59
    /**
60
     * Create a new DataList.
61
     * No querying is done on construction, but the initial query schema is set up.
62
     *
63
     * @param string $dataClass - The DataObject class to query.
64
     */
65
    public function __construct($dataClass)
66
    {
67
        $this->dataClass = $dataClass;
68
        $this->dataQuery = new DataQuery($this->dataClass);
69
70
        parent::__construct();
71
    }
72
73
    /**
74
     * Set the DataModel
75
     *
76
     * @param DataModel $model
77
     */
78
    public function setDataModel(DataModel $model)
79
    {
80
        $this->model = $model;
81
    }
82
83
    /**
84
     * Get the dataClass name for this DataList, ie the DataObject ClassName
85
     *
86
     * @return string
87
     */
88
    public function dataClass()
89
    {
90
        return $this->dataClass;
91
    }
92
93
    /**
94
     * When cloning this object, clone the dataQuery object as well
95
     */
96
    public function __clone()
97
    {
98
        $this->dataQuery = clone $this->dataQuery;
99
    }
100
101
    /**
102
     * Return a copy of the internal {@link DataQuery} object
103
     *
104
     * Because the returned value is a copy, modifying it won't affect this list's contents. If
105
     * you want to alter the data query directly, use the alterDataQuery method
106
     *
107
     * @return DataQuery
108
     */
109
    public function dataQuery()
110
    {
111
        return clone $this->dataQuery;
112
    }
113
114
    /**
115
     * @var bool - Indicates if we are in an alterDataQueryCall already, so alterDataQuery can be re-entrant
116
     */
117
    protected $inAlterDataQueryCall = false;
118
119
    /**
120
     * Return a new DataList instance with the underlying {@link DataQuery} object altered
121
     *
122
     * If you want to alter the underlying dataQuery for this list, this wrapper method
123
     * will ensure that you can do so without mutating the existing List object.
124
     *
125
     * It clones this list, calls the passed callback function with the dataQuery of the new
126
     * list as it's first parameter (and the list as it's second), then returns the list
127
     *
128
     * Note that this function is re-entrant - it's safe to call this inside a callback passed to
129
     * alterDataQuery
130
     *
131
     * @param callable $callback
132
     * @return static
133
     * @throws Exception
134
     */
135
    public function alterDataQuery($callback)
136
    {
137
        if ($this->inAlterDataQueryCall) {
138
            $list = $this;
139
140
            $res = call_user_func($callback, $list->dataQuery, $list);
141
            if ($res) {
142
                $list->dataQuery = $res;
143
            }
144
145
            return $list;
146
        } else {
147
            $list = clone $this;
148
            $list->inAlterDataQueryCall = true;
149
150
            try {
151
                $res = call_user_func($callback, $list->dataQuery, $list);
152
                if ($res) {
153
                    $list->dataQuery = $res;
154
                }
155
            } catch (Exception $e) {
156
                $list->inAlterDataQueryCall = false;
157
                throw $e;
158
            }
159
160
            $list->inAlterDataQueryCall = false;
161
            return $list;
162
        }
163
    }
164
165
    /**
166
     * Return a new DataList instance with the underlying {@link DataQuery} object changed
167
     *
168
     * @param DataQuery $dataQuery
169
     * @return static
170
     */
171
    public function setDataQuery(DataQuery $dataQuery)
172
    {
173
        $clone = clone $this;
174
        $clone->dataQuery = $dataQuery;
175
        return $clone;
176
    }
177
178
    /**
179
     * Returns a new DataList instance with the specified query parameter assigned
180
     *
181
     * @param string|array $keyOrArray Either the single key to set, or an array of key value pairs to set
182
     * @param mixed $val If $keyOrArray is not an array, this is the value to set
183
     * @return static
184
     */
185
    public function setDataQueryParam($keyOrArray, $val = null)
186
    {
187
        $clone = clone $this;
188
189
        if (is_array($keyOrArray)) {
190
            foreach ($keyOrArray as $key => $val) {
191
                $clone->dataQuery->setQueryParam($key, $val);
192
            }
193
        } else {
194
            $clone->dataQuery->setQueryParam($keyOrArray, $val);
195
        }
196
197
        return $clone;
198
    }
199
200
    /**
201
     * Returns the SQL query that will be used to get this DataList's records.  Good for debugging. :-)
202
     *
203
     * @param array $parameters Out variable for parameters required for this query
204
     * @return string The resulting SQL query (may be paramaterised)
205
     */
206
    public function sql(&$parameters = array())
207
    {
208
        return $this->dataQuery->query()->sql($parameters);
209
    }
210
211
    /**
212
     * Return a new DataList instance with a WHERE clause added to this list's query.
213
     *
214
     * Supports parameterised queries.
215
     * See SQLSelect::addWhere() for syntax examples, although DataList
216
     * won't expand multiple method arguments as SQLSelect does.
217
     *
218
     * @param string|array|SQLConditionGroup $filter Predicate(s) to set, as escaped SQL statements or
219
     * paramaterised queries
220
     * @return static
221
     */
222
    public function where($filter)
223
    {
224
        return $this->alterDataQuery(function (DataQuery $query) use ($filter) {
225
            $query->where($filter);
226
        });
227
    }
228
229
    /**
230
     * Return a new DataList instance with a WHERE clause added to this list's query.
231
     * All conditions provided in the filter will be joined with an OR
232
     *
233
     * Supports parameterised queries.
234
     * See SQLSelect::addWhere() for syntax examples, although DataList
235
     * won't expand multiple method arguments as SQLSelect does.
236
     *
237
     * @param string|array|SQLConditionGroup $filter Predicate(s) to set, as escaped SQL statements or
238
     * paramaterised queries
239
     * @return static
240
     */
241
    public function whereAny($filter)
242
    {
243
        return $this->alterDataQuery(function (DataQuery $query) use ($filter) {
244
            $query->whereAny($filter);
245
        });
246
    }
247
248
249
250
    /**
251
     * Returns true if this DataList can be sorted by the given field.
252
     *
253
     * @param string $fieldName
254
     * @return boolean
255
     */
256
    public function canSortBy($fieldName)
257
    {
258
        return $this->dataQuery()->query()->canSortBy($fieldName);
259
    }
260
261
    /**
262
     * Returns true if this DataList can be filtered by the given field.
263
     *
264
     * @param string $fieldName (May be a related field in dot notation like Member.FirstName)
265
     * @return boolean
266
     */
267
    public function canFilterBy($fieldName)
268
    {
269
        $model = singleton($this->dataClass);
270
        $relations = explode(".", $fieldName);
271
        // First validate the relationships
272
        $fieldName = array_pop($relations);
273
        foreach ($relations as $r) {
274
            $relationClass = $model->getRelationClass($r);
275
            if (!$relationClass) {
276
                return false;
277
            }
278
            $model = singleton($relationClass);
279
            if (!$model) {
280
                return false;
281
            }
282
        }
283
        // Then check field
284
        if ($model->hasDatabaseField($fieldName)) {
285
            return true;
286
        }
287
        return false;
288
    }
289
290
    /**
291
     * Return a new DataList instance with the records returned in this query
292
     * restricted by a limit clause.
293
     *
294
     * @param int $limit
295
     * @param int $offset
296
     * @return static
297
     */
298
    public function limit($limit, $offset = 0)
299
    {
300
        return $this->alterDataQuery(function (DataQuery $query) use ($limit, $offset) {
301
            $query->limit($limit, $offset);
302
        });
303
    }
304
305
    /**
306
     * Return a new DataList instance with distinct records or not
307
     *
308
     * @param bool $value
309
     * @return static
310
     */
311
    public function distinct($value)
312
    {
313
        return $this->alterDataQuery(function (DataQuery $query) use ($value) {
314
            $query->distinct($value);
315
        });
316
    }
317
318
    /**
319
     * Return a new DataList instance as a copy of this data list with the sort
320
     * order set.
321
     *
322
     * @see SS_List::sort()
323
     * @see SQLSelect::orderby
324
     * @example $list = $list->sort('Name'); // default ASC sorting
325
     * @example $list = $list->sort('Name DESC'); // DESC sorting
326
     * @example $list = $list->sort('Name', 'ASC');
327
     * @example $list = $list->sort(array('Name'=>'ASC', 'Age'=>'DESC'));
328
     *
329
     * @param String|array Escaped SQL statement. If passed as array, all keys and values are assumed to be escaped.
330
     * @return static
331
     */
332
    public function sort()
333
    {
334
        $count = func_num_args();
335
336
        if ($count == 0) {
337
            return $this;
338
        }
339
340
        if ($count > 2) {
341
            throw new InvalidArgumentException('This method takes zero, one or two arguments');
342
        }
343
344
        if ($count == 2) {
345
            $col = null;
346
            $dir = null;
347
            list($col, $dir) = func_get_args();
348
349
            // Validate direction
350
            if (!in_array(strtolower($dir), array('desc','asc'))) {
351
                user_error('Second argument to sort must be either ASC or DESC');
352
            }
353
354
            $sort = array($col => $dir);
355
        } else {
356
            $sort = func_get_arg(0);
357
        }
358
359
        return $this->alterDataQuery(function (DataQuery $query, DataList $list) use ($sort) {
360
361
            if (is_string($sort) && $sort) {
362
                if (stristr($sort, ' asc') || stristr($sort, ' desc')) {
363
                    $query->sort($sort);
364
                } else {
365
                    $list->applyRelation($sort, $column, true);
366
                    $query->sort($column, 'ASC');
367
                }
368
            } elseif (is_array($sort)) {
369
                // 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...
370
                $query->sort(null, null); // wipe the sort
371
372
                foreach ($sort as $column => $direction) {
373
                    // Convert column expressions to SQL fragment, while still allowing the passing of raw SQL
374
                    // fragments.
375
                    $list->applyRelation($column, $relationColumn, true);
376
                    $query->sort($relationColumn, $direction, false);
377
                }
378
            }
379
        });
380
    }
381
382
    /**
383
     * Return a copy of this list which only includes items with these charactaristics
384
     *
385
     * @see SS_List::filter()
386
     *
387
     * @example $list = $list->filter('Name', 'bob'); // only bob in the list
388
     * @example $list = $list->filter('Name', array('aziz', 'bob'); // aziz and bob in list
389
     * @example $list = $list->filter(array('Name'=>'bob', 'Age'=>21)); // bob with the age 21
390
     * @example $list = $list->filter(array('Name'=>'bob', 'Age'=>array(21, 43))); // bob with the Age 21 or 43
391
     * @example $list = $list->filter(array('Name'=>array('aziz','bob'), 'Age'=>array(21, 43)));
392
     *          // aziz with the age 21 or 43 and bob with the Age 21 or 43
393
     *
394
     * Note: When filtering on nullable columns, null checks will be automatically added.
395
     * E.g. ->filter('Field:not', 'value) will generate '... OR "Field" IS NULL', and
396
     * ->filter('Field:not', null) will generate '"Field" IS NOT NULL'
397
     *
398
     * @todo extract the sql from $customQuery into a SQLGenerator class
399
     *
400
     * @param string|array Escaped SQL statement. If passed as array, all keys and values will be escaped internally
401
     * @return $this
402
     */
403
    public function filter()
404
    {
405
        // Validate and process arguments
406
        $arguments = func_get_args();
407
        switch (sizeof($arguments)) {
408
            case 1:
409
                $filters = $arguments[0];
410
411
                break;
412
            case 2:
413
                $filters = array($arguments[0] => $arguments[1]);
414
415
                break;
416
            default:
417
                throw new InvalidArgumentException('Incorrect number of arguments passed to filter()');
418
        }
419
420
        return $this->addFilter($filters);
421
    }
422
423
    /**
424
     * Return a new instance of the list with an added filter
425
     *
426
     * @param array $filterArray
427
     * @return $this
428
     */
429
    public function addFilter($filterArray)
430
    {
431
        $list = $this;
432
433
        foreach ($filterArray as $expression => $value) {
434
            $filter = $this->createSearchFilter($expression, $value);
435
            $list = $list->alterDataQuery(array($filter, 'apply'));
436
        }
437
438
        return $list;
439
    }
440
441
    /**
442
     * Return a copy of this list which contains items matching any of these charactaristics.
443
     *
444
     * @example // only bob in the list
445
     *          $list = $list->filterAny('Name', 'bob');
446
     *          // SQL: WHERE "Name" = 'bob'
447
     * @example // azis or bob in the list
448
     *          $list = $list->filterAny('Name', array('aziz', 'bob');
449
     *          // SQL: WHERE ("Name" IN ('aziz','bob'))
450
     * @example // bob or anyone aged 21 in the list
451
     *          $list = $list->filterAny(array('Name'=>'bob, 'Age'=>21));
452
     *          // SQL: WHERE ("Name" = 'bob' OR "Age" = '21')
453
     * @example // bob or anyone aged 21 or 43 in the list
454
     *          $list = $list->filterAny(array('Name'=>'bob, 'Age'=>array(21, 43)));
455
     *          // SQL: WHERE ("Name" = 'bob' OR ("Age" IN ('21', '43'))
456
     * @example // all bobs, phils or anyone aged 21 or 43 in the list
457
     *          $list = $list->filterAny(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43)));
458
     *          // SQL: WHERE (("Name" IN ('bob', 'phil')) OR ("Age" IN ('21', '43'))
459
     *
460
     * @todo extract the sql from this method into a SQLGenerator class
461
     *
462
     * @param string|array See {@link filter()}
463
     * @return static
464
     */
465
    public function filterAny()
466
    {
467
        $numberFuncArgs = count(func_get_args());
468
        $whereArguments = array();
469
470
        if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
471
            $whereArguments = func_get_arg(0);
472
        } elseif ($numberFuncArgs == 2) {
473
            $whereArguments[func_get_arg(0)] = func_get_arg(1);
474
        } else {
475
            throw new InvalidArgumentException('Incorrect number of arguments passed to filterAny()');
476
        }
477
478
        return $this->alterDataQuery(function (DataQuery $query) use ($whereArguments) {
479
            $subquery = $query->disjunctiveGroup();
480
481
            foreach ($whereArguments as $field => $value) {
482
                $filter = $this->createSearchFilter($field, $value);
483
                $filter->apply($subquery);
484
            }
485
        });
486
    }
487
488
    /**
489
     * Note that, in the current implementation, the filtered list will be an ArrayList, but this may change in a
490
     * future implementation.
491
     * @see Filterable::filterByCallback()
492
     *
493
     * @example $list = $list->filterByCallback(function($item, $list) { return $item->Age == 9; })
494
     * @param callable $callback
495
     * @return ArrayList (this may change in future implementations)
496
     */
497
    public function filterByCallback($callback)
498
    {
499
        if (!is_callable($callback)) {
500
            throw new LogicException(sprintf(
501
                "SS_Filterable::filterByCallback() passed callback must be callable, '%s' given",
502
                gettype($callback)
503
            ));
504
        }
505
        /** @var ArrayList $output */
506
        $output = ArrayList::create();
507
        foreach ($this as $item) {
508
            if (call_user_func($callback, $item, $this)) {
509
                $output->push($item);
510
            }
511
        }
512
        return $output;
513
    }
514
515
    /**
516
     * Given a field or relation name, apply it safely to this datalist.
517
     *
518
     * Unlike getRelationName, this is immutable and will fallback to the quoted field
519
     * name if not a relation.
520
     *
521
     * @param string $field Name of field or relation to apply
522
     * @param string &$columnName Quoted column name
523
     * @param bool $linearOnly Set to true to restrict to linear relations only. Set this
524
     * if this relation will be used for sorting, and should not include duplicate rows.
525
     * @return $this DataList with this relation applied
526
     */
527
    public function applyRelation($field, &$columnName = null, $linearOnly = false)
528
    {
529
        // If field is invalid, return it without modification
530
        if (!$this->isValidRelationName($field)) {
531
            $columnName = $field;
532
            return $this;
533
        }
534
535
        // Simple fields without relations are mapped directly
536
        if (strpos($field, '.') === false) {
537
            $columnName = '"'.$field.'"';
538
            return $this;
539
        }
540
541
        return $this->alterDataQuery(
542
            function (DataQuery $query) use ($field, &$columnName, $linearOnly) {
543
                $relations = explode('.', $field);
544
                $fieldName = array_pop($relations);
545
546
                // Apply
547
                $relationModelName = $query->applyRelation($relations, $linearOnly);
548
549
                // Find the db field the relation belongs to
550
                $columnName = DataObject::getSchema()->sqlColumnForField($relationModelName, $fieldName);
551
            }
552
        );
553
    }
554
555
    /**
556
     * Check if the given field specification could be interpreted as an unquoted relation name
557
     *
558
     * @param string $field
559
     * @return bool
560
     */
561
    protected function isValidRelationName($field)
562
    {
563
        return preg_match('/^[A-Z0-9._]+$/i', $field);
564
    }
565
566
    /**
567
     * Given a filter expression and value construct a {@see SearchFilter} instance
568
     *
569
     * @param string $filter E.g. `Name:ExactMatch:not`, `Name:ExactMatch`, `Name:not`, `Name`
570
     * @param mixed $value Value of the filter
571
     * @return SearchFilter
572
     */
573
    protected function createSearchFilter($filter, $value)
574
    {
575
        // Field name is always the first component
576
        $fieldArgs = explode(':', $filter);
577
        $fieldName = array_shift($fieldArgs);
578
579
        // Inspect type of second argument to determine context
580
        $secondArg = array_shift($fieldArgs);
581
        $modifiers = $fieldArgs;
582
        if (!$secondArg) {
583
            // Use default filter if none specified. E.g. `->filter(['Name' => $myname])`
584
            $filterServiceName = 'DataListFilter.default';
585
        } else {
586
            // The presence of a second argument is by default ambiguous; We need to query
587
            // Whether this is a valid modifier on the default filter, or a filter itself.
588
            /** @var SearchFilter $defaultFilterInstance */
589
            $defaultFilterInstance = Injector::inst()->get('DataListFilter.default');
590
            if (in_array(strtolower($secondArg), $defaultFilterInstance->getSupportedModifiers())) {
591
                // Treat second (and any subsequent) argument as modifiers, using default filter
592
                $filterServiceName = 'DataListFilter.default';
593
                array_unshift($modifiers, $secondArg);
594
            } else {
595
                // Second argument isn't a valid modifier, so assume is filter identifier
596
                $filterServiceName = "DataListFilter.{$secondArg}";
597
            }
598
        }
599
600
        // Build instance
601
        return Injector::inst()->create($filterServiceName, $fieldName, $value, $modifiers);
602
    }
603
604
    /**
605
     * Return a copy of this list which does not contain any items with these charactaristics
606
     *
607
     * @see SS_List::exclude()
608
     * @example $list = $list->exclude('Name', 'bob'); // exclude bob from list
609
     * @example $list = $list->exclude('Name', array('aziz', 'bob'); // exclude aziz and bob from list
610
     * @example $list = $list->exclude(array('Name'=>'bob, 'Age'=>21)); // exclude bob that has Age 21
611
     * @example $list = $list->exclude(array('Name'=>'bob, 'Age'=>array(21, 43))); // exclude bob with Age 21 or 43
612
     * @example $list = $list->exclude(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43)));
613
     *          // bob age 21 or 43, phil age 21 or 43 would be excluded
614
     *
615
     * @todo extract the sql from this method into a SQLGenerator class
616
     *
617
     * @param string|array Escaped SQL statement. If passed as array, all keys and values will be escaped internally
618
     * @return $this
619
     */
620
    public function exclude()
621
    {
622
        $numberFuncArgs = count(func_get_args());
623
        $whereArguments = array();
624
625
        if ($numberFuncArgs == 1 && is_array(func_get_arg(0))) {
626
            $whereArguments = func_get_arg(0);
627
        } elseif ($numberFuncArgs == 2) {
628
            $whereArguments[func_get_arg(0)] = func_get_arg(1);
629
        } else {
630
            throw new InvalidArgumentException('Incorrect number of arguments passed to exclude()');
631
        }
632
633
        return $this->alterDataQuery(function (DataQuery $query) use ($whereArguments) {
634
            $subquery = $query->disjunctiveGroup();
635
636
            foreach ($whereArguments as $field => $value) {
637
                $filter = $this->createSearchFilter($field, $value);
638
                $filter->exclude($subquery);
639
            }
640
        });
641
    }
642
643
    /**
644
     * This method returns a copy of this list that does not contain any DataObjects that exists in $list
645
     *
646
     * The $list passed needs to contain the same dataclass as $this
647
     *
648
     * @param DataList $list
649
     * @return static
650
     * @throws InvalidArgumentException
651
     */
652
    public function subtract(DataList $list)
653
    {
654
        if ($this->dataClass() != $list->dataClass()) {
655
            throw new InvalidArgumentException('The list passed must have the same dataclass as this class');
656
        }
657
658
        return $this->alterDataQuery(function (DataQuery $query) use ($list) {
659
            $query->subtract($list->dataQuery());
660
        });
661
    }
662
663
    /**
664
     * Return a new DataList instance with an inner join clause added to this list's query.
665
     *
666
     * @param string $table Table name (unquoted and as escaped SQL)
667
     * @param string $onClause Escaped SQL statement, e.g. '"Table1"."ID" = "Table2"."ID"'
668
     * @param string $alias - if you want this table to be aliased under another name
669
     * @param int $order A numerical index to control the order that joins are added to the query; lower order values
670
     * will cause the query to appear first. The default is 20, and joins created automatically by the
671
     * ORM have a value of 10.
672
     * @param array $parameters Any additional parameters if the join is a parameterised subquery
673
     * @return static
674
     */
675
    public function innerJoin($table, $onClause, $alias = null, $order = 20, $parameters = array())
676
    {
677
        return $this->alterDataQuery(function (DataQuery $query) use ($table, $onClause, $alias, $order, $parameters) {
678
            $query->innerJoin($table, $onClause, $alias, $order, $parameters);
679
        });
680
    }
681
682
    /**
683
     * Return a new DataList instance with a left join clause added to this list's query.
684
     *
685
     * @param string $table Table name (unquoted and as escaped SQL)
686
     * @param string $onClause Escaped SQL statement, e.g. '"Table1"."ID" = "Table2"."ID"'
687
     * @param string $alias - if you want this table to be aliased under another name
688
     * @param int $order A numerical index to control the order that joins are added to the query; lower order values
689
     * will cause the query to appear first. The default is 20, and joins created automatically by the
690
     * ORM have a value of 10.
691
     * @param array $parameters Any additional parameters if the join is a parameterised subquery
692
     * @return static
693
     */
694
    public function leftJoin($table, $onClause, $alias = null, $order = 20, $parameters = array())
695
    {
696
        return $this->alterDataQuery(function (DataQuery $query) use ($table, $onClause, $alias, $order, $parameters) {
697
            $query->leftJoin($table, $onClause, $alias, $order, $parameters);
698
        });
699
    }
700
701
    /**
702
     * Return an array of the actual items that this DataList contains at this stage.
703
     * This is when the query is actually executed.
704
     *
705
     * @return array
706
     */
707
    public function toArray()
708
    {
709
        $query = $this->dataQuery->query();
710
        $rows = $query->execute();
711
        $results = array();
712
713
        foreach ($rows as $row) {
714
            $results[] = $this->createDataObject($row);
715
        }
716
717
        return $results;
718
    }
719
720
    /**
721
     * Return this list as an array and every object it as an sub array as well
722
     *
723
     * @return array
724
     */
725
    public function toNestedArray()
726
    {
727
        $result = array();
728
729
        foreach ($this as $item) {
730
            $result[] = $item->toMap();
731
        }
732
733
        return $result;
734
    }
735
736
    /**
737
     * Walks the list using the specified callback
738
     *
739
     * @param callable $callback
740
     * @return $this
741
     */
742
    public function each($callback)
743
    {
744
        foreach ($this as $row) {
745
            $callback($row);
746
        }
747
748
        return $this;
749
    }
750
751
    public function debug()
752
    {
753
        $val = "<h2>" . static::class . "</h2><ul>";
754
        foreach ($this->toNestedArray() as $item) {
755
            $val .= "<li style=\"list-style-type: disc; margin-left: 20px\">" . Debug::text($item) . "</li>";
756
        }
757
        $val .= "</ul>";
758
        return $val;
759
    }
760
761
    /**
762
     * Returns a map of this list
763
     *
764
     * @param string $keyField - the 'key' field of the result array
765
     * @param string $titleField - the value field of the result array
766
     * @return Map
767
     */
768
    public function map($keyField = 'ID', $titleField = 'Title')
769
    {
770
        return new Map($this, $keyField, $titleField);
771
    }
772
773
    /**
774
     * Create a DataObject from the given SQL row
775
     *
776
     * @param array $row
777
     * @return DataObject
778
     */
779
    public function createDataObject($row)
780
    {
781
        $class = $this->dataClass;
782
783
        if (empty($row['ClassName'])) {
784
            $row['ClassName'] = $class;
785
        }
786
787
        // Failover from RecordClassName to ClassName
788
        if (empty($row['RecordClassName'])) {
789
            $row['RecordClassName'] = $row['ClassName'];
790
        }
791
792
        // Instantiate the class mentioned in RecordClassName only if it exists, otherwise default to $this->dataClass
793
        if (class_exists($row['RecordClassName'])) {
794
            $class = $row['RecordClassName'];
795
        }
796
797
        $item = Injector::inst()->create($class, $row, false, $this->model, $this->getQueryParams());
798
799
        return $item;
800
    }
801
802
    /**
803
     * Get query parameters for this list.
804
     * These values will be assigned as query parameters to newly created objects from this list.
805
     *
806
     * @return array
807
     */
808
    public function getQueryParams()
809
    {
810
        return $this->dataQuery()->getQueryParams();
811
    }
812
813
    /**
814
     * Returns an Iterator for this DataList.
815
     * This function allows you to use DataLists in foreach loops
816
     *
817
     * @return ArrayIterator
818
     */
819
    public function getIterator()
820
    {
821
        return new ArrayIterator($this->toArray());
822
    }
823
824
    /**
825
     * Return the number of items in this DataList
826
     *
827
     * @return int
828
     */
829
    public function count()
830
    {
831
        return $this->dataQuery->count();
832
    }
833
834
    /**
835
     * Return the maximum value of the given field in this DataList
836
     *
837
     * @param string $fieldName
838
     * @return mixed
839
     */
840
    public function max($fieldName)
841
    {
842
        return $this->dataQuery->max($fieldName);
843
    }
844
845
    /**
846
     * Return the minimum value of the given field in this DataList
847
     *
848
     * @param string $fieldName
849
     * @return mixed
850
     */
851
    public function min($fieldName)
852
    {
853
        return $this->dataQuery->min($fieldName);
854
    }
855
856
    /**
857
     * Return the average value of the given field in this DataList
858
     *
859
     * @param string $fieldName
860
     * @return mixed
861
     */
862
    public function avg($fieldName)
863
    {
864
        return $this->dataQuery->avg($fieldName);
865
    }
866
867
    /**
868
     * Return the sum of the values of the given field in this DataList
869
     *
870
     * @param string $fieldName
871
     * @return mixed
872
     */
873
    public function sum($fieldName)
874
    {
875
        return $this->dataQuery->sum($fieldName);
876
    }
877
878
879
    /**
880
     * Returns the first item in this DataList
881
     *
882
     * @return DataObject
883
     */
884
    public function first()
885
    {
886
        foreach ($this->dataQuery->firstRow()->execute() as $row) {
887
            return $this->createDataObject($row);
888
        }
889
        return null;
890
    }
891
892
    /**
893
     * Returns the last item in this DataList
894
     *
895
     *  @return DataObject
896
     */
897
    public function last()
898
    {
899
        foreach ($this->dataQuery->lastRow()->execute() as $row) {
900
            return $this->createDataObject($row);
901
        }
902
        return null;
903
    }
904
905
    /**
906
     * Returns true if this DataList has items
907
     *
908
     * @return bool
909
     */
910
    public function exists()
911
    {
912
        return $this->count() > 0;
913
    }
914
915
    /**
916
     * Find the first DataObject of this DataList where the given key = value
917
     *
918
     * @param string $key
919
     * @param string $value
920
     * @return DataObject|null
921
     */
922
    public function find($key, $value)
923
    {
924
        return $this->filter($key, $value)->first();
925
    }
926
927
    /**
928
     * Restrict the columns to fetch into this DataList
929
     *
930
     * @param array $queriedColumns
931
     * @return static
932
     */
933
    public function setQueriedColumns($queriedColumns)
934
    {
935
        return $this->alterDataQuery(function (DataQuery $query) use ($queriedColumns) {
936
            $query->setQueriedColumns($queriedColumns);
937
        });
938
    }
939
940
    /**
941
     * Filter this list to only contain the given Primary IDs
942
     *
943
     * @param array $ids Array of integers
944
     * @return $this
945
     */
946
    public function byIDs($ids)
947
    {
948
        return $this->filter('ID', $ids);
949
    }
950
951
    /**
952
     * Return the first DataObject with the given ID
953
     *
954
     * @param int $id
955
     * @return DataObject
956
     */
957
    public function byID($id)
958
    {
959
        return $this->filter('ID', $id)->first();
960
    }
961
962
    /**
963
     * Returns an array of a single field value for all items in the list.
964
     *
965
     * @param string $colName
966
     * @return array
967
     */
968
    public function column($colName = "ID")
969
    {
970
        return $this->dataQuery->column($colName);
971
    }
972
973
    // Member altering methods
974
975
    /**
976
     * Sets the ComponentSet to be the given ID list.
977
     * Records will be added and deleted as appropriate.
978
     *
979
     * @param array $idList List of IDs.
980
     */
981
    public function setByIDList($idList)
982
    {
983
        $has = array();
984
985
        // Index current data
986
        foreach ($this->column() as $id) {
987
            $has[$id] = true;
988
        }
989
990
        // Keep track of items to delete
991
        $itemsToDelete = $has;
992
993
        // add items in the list
994
        // $id is the database ID of the record
995
        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...
996
            foreach ($idList as $id) {
997
                unset($itemsToDelete[$id]);
998
                if ($id && !isset($has[$id])) {
999
                    $this->add($id);
1000
                }
1001
            }
1002
        }
1003
1004
        // Remove any items that haven't been mentioned
1005
        $this->removeMany(array_keys($itemsToDelete));
1006
    }
1007
1008
    /**
1009
     * Returns an array with both the keys and values set to the IDs of the records in this list.
1010
     * Does not respect sort order. Use ->column("ID") to get an ID list with the current sort.
1011
     *
1012
     * @return array
1013
     */
1014
    public function getIDList()
1015
    {
1016
        $ids = $this->column("ID");
1017
        return $ids ? array_combine($ids, $ids) : array();
1018
    }
1019
1020
    /**
1021
     * Returns a HasManyList or ManyMany list representing the querying of a relation across all
1022
     * objects in this data list.  For it to work, the relation must be defined on the data class
1023
     * that you used to create this DataList.
1024
     *
1025
     * Example: Get members from all Groups:
1026
     *
1027
     *     DataList::Create("Group")->relation("Members")
1028
     *
1029
     * @param string $relationName
1030
     * @return HasManyList|ManyManyList
1031
     */
1032
    public function relation($relationName)
1033
    {
1034
        $ids = $this->column('ID');
1035
        return singleton($this->dataClass)->$relationName()->forForeignID($ids);
1036
    }
1037
1038
    public function dbObject($fieldName)
1039
    {
1040
        return singleton($this->dataClass)->dbObject($fieldName);
1041
    }
1042
1043
    /**
1044
     * Add a number of items to the component set.
1045
     *
1046
     * @param array $items Items to add, as either DataObjects or IDs.
1047
     * @return $this
1048
     */
1049
    public function addMany($items)
1050
    {
1051
        foreach ($items as $item) {
1052
            $this->add($item);
1053
        }
1054
        return $this;
1055
    }
1056
1057
    /**
1058
     * Remove the items from this list with the given IDs
1059
     *
1060
     * @param array $idList
1061
     * @return $this
1062
     */
1063
    public function removeMany($idList)
1064
    {
1065
        foreach ($idList as $id) {
1066
            $this->removeByID($id);
1067
        }
1068
        return $this;
1069
    }
1070
1071
    /**
1072
     * Remove every element in this DataList matching the given $filter.
1073
     *
1074
     * @param string|array $filter - a sql type where filter
1075
     * @return $this
1076
     */
1077
    public function removeByFilter($filter)
1078
    {
1079
        foreach ($this->where($filter) as $item) {
1080
            $this->remove($item);
1081
        }
1082
        return $this;
1083
    }
1084
1085
    /**
1086
     * Remove every element in this DataList.
1087
     *
1088
     * @return $this
1089
     */
1090
    public function removeAll()
1091
    {
1092
        foreach ($this as $item) {
1093
            $this->remove($item);
1094
        }
1095
        return $this;
1096
    }
1097
1098
    /**
1099
     * This method are overloaded by HasManyList and ManyMany list to perform more sophisticated
1100
     * list manipulation
1101
     *
1102
     * @param mixed $item
1103
     */
1104
    public function add($item)
1105
    {
1106
        // Nothing needs to happen by default
1107
        // TO DO: If a filter is given to this data list then
1108
    }
1109
1110
    /**
1111
     * Return a new item to add to this DataList.
1112
     *
1113
     * @todo This doesn't factor in filters.
1114
     * @param array $initialFields
1115
     * @return DataObject
1116
     */
1117
    public function newObject($initialFields = null)
1118
    {
1119
        $class = $this->dataClass;
1120
        return Injector::inst()->create($class, $initialFields, false, $this->model);
1121
    }
1122
1123
    /**
1124
     * Remove this item by deleting it
1125
     *
1126
     * @param DataObject $item
1127
     * @todo Allow for amendment of this behaviour - for example, we can remove an item from
1128
     * an "ActiveItems" DataList by chaning the status to inactive.
1129
     */
1130
    public function remove($item)
1131
    {
1132
        // By default, we remove an item from a DataList by deleting it.
1133
        $this->removeByID($item->ID);
1134
    }
1135
1136
    /**
1137
     * Remove an item from this DataList by ID
1138
     *
1139
     * @param int $itemID The primary ID
1140
     */
1141
    public function removeByID($itemID)
1142
    {
1143
        $item = $this->byID($itemID);
1144
1145
        if ($item) {
1146
            $item->delete();
1147
        }
1148
    }
1149
1150
    /**
1151
     * Reverses a list of items.
1152
     *
1153
     * @return static
1154
     */
1155
    public function reverse()
1156
    {
1157
        return $this->alterDataQuery(function (DataQuery $query) {
1158
            $query->reverseSort();
1159
        });
1160
    }
1161
1162
    /**
1163
     * Returns whether an item with $key exists
1164
     *
1165
     * @param mixed $key
1166
     * @return bool
1167
     */
1168
    public function offsetExists($key)
1169
    {
1170
        return ($this->limit(1, $key)->first() != null);
1171
    }
1172
1173
    /**
1174
     * Returns item stored in list with index $key
1175
     *
1176
     * @param mixed $key
1177
     * @return DataObject
1178
     */
1179
    public function offsetGet($key)
1180
    {
1181
        return $this->limit(1, $key)->first();
1182
    }
1183
1184
    /**
1185
     * Set an item with the key in $key
1186
     *
1187
     * @param mixed $key
1188
     * @param mixed $value
1189
     */
1190
    public function offsetSet($key, $value)
1191
    {
1192
        user_error("Can't alter items in a DataList using array-access", E_USER_ERROR);
1193
    }
1194
1195
    /**
1196
     * Unset an item with the key in $key
1197
     *
1198
     * @param mixed $key
1199
     */
1200
    public function offsetUnset($key)
1201
    {
1202
        user_error("Can't alter items in a DataList using array-access", E_USER_ERROR);
1203
    }
1204
}
1205