ArrayList.php
16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
<?php
/**
* A list object that wraps around an array of objects or arrays.
*
* Note that (like DataLists), the implementations of the methods from SS_Filterable, SS_Sortable and
* SS_Limitable return a new instance of ArrayList, rather than modifying the existing instance.
*
* For easy reference, methods that operate in this way are:
*
* - limit
* - reverse
* - sort
* - filter
* - exclude
*
* @package framework
* @subpackage model
*/
class ArrayList extends ViewableData implements SS_List, SS_Filterable, SS_Sortable, SS_Limitable {
/**
* Holds the items in the list
*
* @var array
*/
protected $items = array();
/**
*
* @param array $items - an initial array to fill this object with
*/
public function __construct(array $items = array()) {
$this->items = array_values($items);
parent::__construct();
}
/**
* Return the class of items in this list, by looking at the first item inside it.
*/
public function dataClass() {
if(count($this->items) > 0) return get_class($this->items[0]);
}
/**
* Return the number of items in this list
*
* @return int
*/
public function count() {
return count($this->items);
}
/**
* Returns true if this list has items
*
* @return bool
*/
public function exists() {
return (bool) count($this);
}
/**
* Returns an Iterator for this ArrayList.
* This function allows you to use ArrayList in foreach loops
*
* @return ArrayIterator
*/
public function getIterator() {
foreach($this->items as $i => $item) {
if(is_array($item)) $this->items[$i] = new ArrayData($item);
}
return new ArrayIterator($this->items);
}
/**
* Return an array of the actual items that this ArrayList contains.
*
* @return array
*/
public function toArray() {
return $this->items;
}
/**
* Walks the list using the specified callback
*
* @param callable $callback
* @return DataList
*/
public function each($callback) {
foreach($this as $item) {
$callback($item);
}
}
public function debug() {
$val = "<h2>" . $this->class . "</h2><ul>";
foreach($this->toNestedArray() as $item) {
$val .= "<li style=\"list-style-type: disc; margin-left: 20px\">" . Debug::text($item) . "</li>";
}
$val .= "</ul>";
return $val;
}
/**
* Return this list as an array and every object it as an sub array as well
*
* @return array
*/
public function toNestedArray() {
$result = array();
foreach ($this->items as $item) {
if (is_object($item)) {
if (method_exists($item, 'toMap')) {
$result[] = $item->toMap();
} else {
$result[] = (array) $item;
}
} else {
$result[] = $item;
}
}
return $result;
}
/**
* Get a sub-range of this dataobjectset as an array
*
* @param int $offset
* @param int $length
* @return ArrayList
*/
public function limit($length, $offset = 0) {
if(!$length) {
$length = count($this->items);
}
$list = clone $this;
$list->items = array_slice($this->items, $offset, $length);
return $list;
}
/**
* Add this $item into this list
*
* @param mixed $item
*/
public function add($item) {
$this->push($item);
}
/**
* Remove this item from this list
*
* @param mixed $item
*/
public function remove($item) {
$renumberKeys = false;
foreach ($this->items as $key => $value) {
if ($item === $value) {
$renumberKeys = true;
unset($this->items[$key]);
}
}
if($renumberKeys) $this->items = array_values($this->items);
}
/**
* Replaces an item in this list with another item.
*
* @param array|object $item
* @param array|object $with
* @return void;
*/
public function replace($item, $with) {
foreach ($this->items as $key => $candidate) {
if ($candidate === $item) {
$this->items[$key] = $with;
return;
}
}
}
/**
* Merges with another array or list by pushing all the items in it onto the
* end of this list.
*
* @param array|object $with
*/
public function merge($with) {
foreach ($with as $item) $this->push($item);
}
/**
* Removes items from this list which have a duplicate value for a certain
* field. This is especially useful when combining lists.
*
* @param string $field
*/
public function removeDuplicates($field = 'ID') {
$seen = array();
$renumberKeys = false;
foreach ($this->items as $key => $item) {
$value = $this->extractValue($item, $field);
if (array_key_exists($value, $seen)) {
$renumberKeys = true;
unset($this->items[$key]);
}
$seen[$value] = true;
}
if($renumberKeys) $this->items = array_values($this->items);
}
/**
* Pushes an item onto the end of this list.
*
* @param array|object $item
*/
public function push($item) {
$this->items[] = $item;
}
/**
* Pops the last element off the end of the list and returns it.
*
* @return array|object
*/
public function pop() {
return array_pop($this->items);
}
/**
* Add an item onto the beginning of the list.
*
* @param array|object $item
*/
public function unshift($item) {
array_unshift($this->items, $item);
}
/**
* Shifts the item off the beginning of the list and returns it.
*
* @return array|object
*/
public function shift() {
return array_shift($this->items);
}
/**
* Returns the first item in the list
*
* @return mixed
*/
public function first() {
return reset($this->items);
}
/**
* Returns the last item in the list
*
* @return mixed
*/
public function last() {
return end($this->items);
}
/**
* Returns a map of this list
*
* @param type $keyfield - the 'key' field of the result array
* @param type $titlefield - the value field of the result array
* @return array
*/
public function map($keyfield = 'ID', $titlefield = 'Title') {
$map = array();
foreach ($this->items as $item) {
$map[$this->extractValue($item, $keyfield)] = $this->extractValue(
$item,
$titlefield
);
}
return $map;
}
/**
* Find the first item of this list where the given key = value
*
* @param type $key
* @param type $value
* @return type
*/
public function find($key, $value) {
foreach ($this->items as $item) {
if ($this->extractValue($item, $key) == $value) {
return $item;
}
}
}
/**
* Returns an array of a single field value for all items in the list.
*
* @param string $colName
* @return array
*/
public function column($colName = 'ID') {
$result = array();
foreach ($this->items as $item) {
$result[] = $this->extractValue($item, $colName);
}
return $result;
}
/**
* You can always sort a ArrayList
*
* @param string $by
* @return bool
*/
public function canSortBy($by) {
return true;
}
/**
* Reverses an {@link ArrayList}
*
* @return ArrayList
*/
public function reverse() {
$list = clone $this;
$list->items = array_reverse($this->items);
return $list;
}
/**
* Parses a specified column into a sort field and direction
*
* @param type $column String to parse containing the column name
* @param type $direction Optional Additional argument which may contain the direction
* @return array Sort specification in the form array("Column", SORT_ASC).
*/
protected function parseSortColumn($column, $direction = null) {
// Substitute the direction for the column if column is a numeric index
if($direction && (empty($column) || is_numeric($column))) {
$column = $direction;
$direction = null;
}
// Parse column specification, considering possible ansi sql quoting
if(preg_match('/^"?(?<column>[^"\s]+)"?(\s+(?<direction>((asc)|(desc))(ending)?))?$/i', $column, $match)) {
$column = $match['column'];
if(empty($direction) && !empty($match['direction'])) {
$direction = $match['direction'];
}
} else {
throw new InvalidArgumentException("Invalid sort() column");
}
// Parse sort direction specification
if(empty($direction) || preg_match('/^asc(ending)?$/i', $direction)) {
$direction = SORT_ASC;
} elseif(preg_match('/^desc(ending)?$/i', $direction)) {
$direction = SORT_DESC;
} else {
throw new InvalidArgumentException("Invalid sort() direction");
}
return array($column, $direction);
}
/**
* Sorts this list by one or more fields. You can either pass in a single
* field name and direction, or a map of field names to sort directions.
*
* Note that columns may be double quoted as per ANSI sql standard
*
* @return DataList
* @see SS_List::sort()
* @example $list->sort('Name'); // default ASC sorting
* @example $list->sort('Name DESC'); // DESC sorting
* @example $list->sort('Name', 'ASC');
* @example $list->sort(array('Name'=>'ASC,'Age'=>'DESC'));
*/
public function sort() {
$args = func_get_args();
if(count($args)==0){
return $this;
}
if(count($args)>2){
throw new InvalidArgumentException('This method takes zero, one or two arguments');
}
// One argument and it's a string
if(count($args)==1 && is_string($args[0])){
list($column, $direction) = $this->parseSortColumn($args[0]);
$columnsToSort[$column] = $direction;
} else if(count($args)==2) {
list($column, $direction) = $this->parseSortColumn($args[0], $args[1]);
$columnsToSort[$column] = $direction;
} else if(is_array($args[0])) {
foreach($args[0] as $key => $value) {
list($column, $direction) = $this->parseSortColumn($key, $value);
$columnsToSort[$column] = $direction;
}
} else {
throw new InvalidArgumentException("Bad arguments passed to sort()");
}
// This the main sorting algorithm that supports infinite sorting params
$multisortArgs = array();
$values = array();
foreach($columnsToSort as $column => $direction ) {
// The reason these are added to columns is of the references, otherwise when the foreach
// is done, all $values and $direction look the same
$values[$column] = array();
$sortDirection[$column] = $direction;
// We need to subtract every value into a temporary array for sorting
foreach($this->items as $index => $item) {
$values[$column][] = $this->extractValue($item, $column);
}
// PHP 5.3 requires below arguments to be reference when using array_multisort together
// with call_user_func_array
// First argument is the 'value' array to be sorted
$multisortArgs[] = &$values[$column];
// First argument is the direction to be sorted,
$multisortArgs[] = &$sortDirection[$column];
}
$list = clone $this;
// As the last argument we pass in a reference to the items that all the sorting will be applied upon
$multisortArgs[] = &$list->items;
call_user_func_array('array_multisort', $multisortArgs);
return $list;
}
/**
* Returns true if the given column can be used to filter the records.
*
* It works by checking the fields available in the first record of the list.
*/
public function canFilterBy($by) {
$firstRecord = $this->first();
if ($firstRecord === false) {
return false;
}
return array_key_exists($by, $firstRecord);
}
/**
* Filter the list to include items with these charactaristics
*
* @return ArrayList
* @see SS_List::filter()
* @example $list->filter('Name', 'bob'); // only bob in the list
* @example $list->filter('Name', array('aziz', 'bob'); // aziz and bob in list
* @example $list->filter(array('Name'=>'bob, 'Age'=>21)); // bob with the Age 21 in list
* @example $list->filter(array('Name'=>'bob, 'Age'=>array(21, 43))); // bob with the Age 21 or 43
* @example $list->filter(array('Name'=>array('aziz','bob'), 'Age'=>array(21, 43)));
* // aziz with the age 21 or 43 and bob with the Age 21 or 43
*/
public function filter() {
if(count(func_get_args())>2){
throw new InvalidArgumentException('filter takes one array or two arguments');
}
if(count(func_get_args()) == 1 && !is_array(func_get_arg(0))){
throw new InvalidArgumentException('filter takes one array or two arguments');
}
$keepUs = array();
if(count(func_get_args())==2){
$keepUs[func_get_arg(0)] = func_get_arg(1);
}
if(count(func_get_args())==1 && is_array(func_get_arg(0))){
foreach(func_get_arg(0) as $column => $value) {
$keepUs[$column] = $value;
}
}
$itemsToKeep = array();
foreach($this->items as $item){
$keepItem = true;
foreach($keepUs as $column => $value ) {
if(is_array($value) && !in_array($this->extractValue($item, $column), $value)) {
$keepItem = false;
} elseif(!is_array($value) && $this->extractValue($item, $column) != $value) {
$keepItem = false;
}
}
if($keepItem) {
$itemsToKeep[] = $item;
}
}
$list = clone $this;
$list->items = $itemsToKeep;
return $list;
}
public function byID($id) {
$firstElement = $this->filter("ID", $id)->first();
if ($firstElement === false) {
return null;
}
return $firstElement;
}
/**
* @see SS_Filterable::filterByCallback()
*
* @example $list = $list->filterByCallback(function($item, $list) { return $item->Age == 9; })
* @param callable $callback
* @return ArrayList
*/
public function filterByCallback($callback) {
if(!is_callable($callback)) {
throw new LogicException(sprintf(
"SS_Filterable::filterByCallback() passed callback must be callable, '%s' given",
gettype($callback)
));
}
$output = ArrayList::create();
foreach($this as $item) {
if(call_user_func($callback, $item, $this)) $output->push($item);
}
return $output;
}
/**
* Exclude the list to not contain items with these charactaristics
*
* @return ArrayList
* @see SS_List::exclude()
* @example $list->exclude('Name', 'bob'); // exclude bob from list
* @example $list->exclude('Name', array('aziz', 'bob'); // exclude aziz and bob from list
* @example $list->exclude(array('Name'=>'bob, 'Age'=>21)); // exclude bob that has Age 21
* @example $list->exclude(array('Name'=>'bob, 'Age'=>array(21, 43))); // exclude bob with Age 21 or 43
* @example $list->exclude(array('Name'=>array('bob','phil'), 'Age'=>array(21, 43)));
* // bob age 21 or 43, phil age 21 or 43 would be excluded
*/
public function exclude() {
if(count(func_get_args())>2){
throw new InvalidArgumentException('exclude() takes one array or two arguments');
}
if(count(func_get_args()) == 1 && !is_array(func_get_arg(0))){
throw new InvalidArgumentException('exclude() takes one array or two arguments');
}
$removeUs = array();
if(count(func_get_args())==2){
$removeUs[func_get_arg(0)] = func_get_arg(1);
}
if(count(func_get_args())==1 && is_array(func_get_arg(0))){
foreach(func_get_arg(0) as $column => $excludeValue) {
$removeUs[$column] = $excludeValue;
}
}
$hitsRequiredToRemove = count($removeUs);
$matches = array();
foreach($removeUs as $column => $excludeValue) {
foreach($this->items as $key => $item){
if(!is_array($excludeValue) && $this->extractValue($item, $column) == $excludeValue) {
$matches[$key]=isset($matches[$key])?$matches[$key]+1:1;
} elseif(is_array($excludeValue) && in_array($this->extractValue($item, $column), $excludeValue)) {
$matches[$key]=isset($matches[$key])?$matches[$key]+1:1;
}
}
}
$keysToRemove = array_keys($matches,$hitsRequiredToRemove);
$itemsToKeep = array();
foreach($this->items as $key => $value) {
if(!in_array($key, $keysToRemove)) {
$itemsToKeep[] = $value;
}
}
$list = clone $this;
$list->items = $itemsToKeep;
return $list;
}
protected function shouldExclude($item, $args) {
}
/**
* Returns whether an item with $key exists
*
* @param mixed $key
* @return bool
*/
public function offsetExists($offset) {
return array_key_exists($offset, $this->items);
}
/**
* Returns item stored in list with index $key
*
* @param mixed $key
* @return DataObject
*/
public function offsetGet($offset) {
if ($this->offsetExists($offset)) return $this->items[$offset];
}
/**
* Set an item with the key in $key
*
* @param mixed $key
* @param mixed $value
*/
public function offsetSet($offset, $value) {
if($offset == null) {
$this->items[] = $value;
} else {
$this->items[$offset] = $value;
}
}
/**
* Unset an item with the key in $key
*
* @param mixed $key
*/
public function offsetUnset($offset) {
unset($this->items[$offset]);
}
/**
* Extracts a value from an item in the list, where the item is either an
* object or array.
*
* @param array|object $item
* @param string $key
* @return mixed
*/
protected function extractValue($item, $key) {
if (is_object($item)) {
return $item->$key;
} else {
if (array_key_exists($key, $item)) return $item[$key];
}
}
}