-
Notifications
You must be signed in to change notification settings - Fork 201
/
WireArray.php
1491 lines (1314 loc) · 39.9 KB
/
WireArray.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* ProcessWire WireArray
*
* WireArray is the base array access object used in the ProcessWire framework.
*
* Several methods are duplicated here for syntactical convenience and jQuery-like usability.
* Many methods act upon the array and return $this, which enables WireArrays to be used for fluent interfaces.
* WireArray is the base of the PageArray (subclass) which is the most used instance.
*
* TODO narrow down to one method of addition and removal, especially for removal, i.e. make shift() run through remove()
*
* ProcessWire 2.x
* Copyright (C) 2013 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://processwire.com
*
*/
class WireArray extends Wire implements IteratorAggregate, ArrayAccess, Countable {
/**
* Basic type managed by the WireArray for data storage
*
*/
protected $data = array();
/**
* Any extra user defined data to accompany the WireArray
*
* See the data() method. Note these are not under change tracking.
*
*/
protected $extraData = array();
/**
* Array containing the items that have been removed from this WireArray while trackChanges is on
*
* @see getRemovedKeys()
*
*/
protected $itemsRemoved = array();
/**
* Array containing the items that have been added to this WireArray while trackChanges is on
*
* @see getRemovedKeys()
*
*/
protected $itemsAdded = array();
/**
* Template mehod that descendant classes may use to validate items added to this WireArray
*
* @param mixed $item Item to add
* @return bool True if item is valid and may be added, false if not
*
*/
public function isValidItem($item) {
return $item instanceof Wire;
}
/**
* Template method that descendant classes may use to validate the key of items added to this WireArray
*
* @param string|int $key
* @return bool True if key is valid and may be used, false if not
*
*/
public function isValidKey($key) {
return true;
}
/**
* Template method that descendant classes may use to find a key from the item itself, or null if disabled.
*
* Used by add() and prepend()
*
* @param object $item
* @return string|int|null
*
*/
public function getItemKey($item) {
// in this base class, we don't make assumptions how the key is determined
// so we just search the array to see if the item is already here and
// return it's key if it is here
$key = array_search($item, $this->data, true);
return $key === false ? null : $key;
}
/**
* Get a blank copy of an item of the type that this WireArray holds
*
* @throws WireException
* @return mixed
*
*/
public function makeBlankItem() {
$class = get_class($this);
if($class != 'WireArray') throw new WireException("Class '$class' doesn't yet implement method 'makeBlankItem()' and it needs to.");
return null;
}
/**
* Creates a new blank instance of itself, for internal use.
*
* @return WireArray
*
*/
public function makeNew() {
$class = get_class($this);
$newArray = new $class();
return $newArray;
}
/**
* Creates a new populated (copy/cloen) instance of itself, for internal use.
*
* Same as a clone, except that descending classes may wish to replace the
* clone call a manually created WireArray to prevent deep cloning.
*
* @return WireArray
*
*/
public function makeCopy() {
return clone $this;
}
/**
* Import items into this WireArray.
*
* @throws WireException
* @param array|WireArray $items Items to import.
* @return WireArray This instance.
*
*/
public function import($items) {
if(!is_array($items) && !self::iterable($items))
throw new WireException('WireArray cannot import non arrays or non-iterable objects');
foreach($items as $key => $value) {
if(($k = $this->getItemKey($value)) !== null) $key = $k;
if(isset($this->data[$key])) continue; // won't overwrite existing keys
$this->set($key, $value);
}
return $this;
}
/**
* Add an item to the end of the WireArray.
*
* @throws WireException
* @param int|string|array|object $item Item to add.
* @return WireArray This instance.
*/
public function add($item) {
if(!$this->isValidItem($item)) {
if($item instanceof WireArray) {
foreach($item as $i) $this->prepend($i);
return $this;
} else {
throw new WireException("Item added to " . get_class($this) . " is not an allowed type");
}
}
$key = null;
if(($key = $this->getItemKey($item)) !== null) {
if(isset($this->data[$key])) unset($this->data[$key]); // avoid two copies of the same item, re-add it to the end
$this->data[$key] = $item;
} else {
$this->data[] = $item;
}
$this->trackChange("add");
$this->trackAdd($item);
return $this;
}
/**
* Insert an item either before or after another
*
* Provides the implementation for the insertBefore and insertAfter functions
*
*/
protected function _insert($item, $existingItem, $insertBefore = true) {
if(!$this->isValidItem($item)) throw new WireException("You may not insert this item type");
$data = array();
$this->add($item); // first add the item, then we'll move it
$itemKey = $this->getItemKey($item);
foreach($this->data as $key => $value) {
if($value === $existingItem) {
// found $existingItem, so insert $item and then insert $existingItem
if($insertBefore) {
$data[$itemKey] = $item;
$data[$key] = $value;
} else {
$data[$key] = $value;
$data[$itemKey] = $item;
}
} else if($value === $item) {
// skip over it since the above is doing the insert
continue;
} else {
// continue populating existing data
$data[$key] = $value;
}
}
$this->data = $data;
return $this;
}
/**
* Insert an item before an existing item
*
* @param int|string|array|object $item Item you want to insert
* @param int|string|array|object $existingItem Item already present that you want to insert before
* @return \WireArray
*
*/
public function insertBefore($item, $existingItem) {
return $this->_insert($item, $existingItem, true);
}
/**
* Insert an item after an existing item
*
* @param int|string|array|object $item Item you want to insert
* @param int|string|array|object $existingItem Item already present that you want to insert after
* @return \WireArray
*
*/
public function insertAfter($item, $existingItem) {
return $this->_insert($item, $existingItem, false);
}
/**
* Replace one item with the other
*
* If both items are already present, they will change places.
* If one item is not already present, it will replace the one that is.
* If neither item is present, both will be added at the end.
*
* @param Wire|string|int $itemA
* @param Wire|string|int $itemB
* @return \WireArray
*
*/
public function replace($itemA, $itemB) {
$a = $this->get($itemA);
$b = $this->get($itemB);
if($a && $b) {
// swap a and b
$data = $this->data;
foreach($data as $key => $value) {
if($value === $a) {
$key = $b->getItemKey();
$value = $b;
} else if($value === $b) {
$key = $a->getItemKey();
$value = $a;
}
$data[$key] = $value;
}
$this->data = $data;
} else if($a) {
// b not already in array, so replace a with b
$this->_insert($itemB, $a);
$this->remove($a);
} else if($b) {
// a not already in array, so replace b with a
$this->_insert($itemA, $b);
$this->remove($b);
}
return $this;
}
/**
* Sets an index in the WireArray.
*
* @param int|string $key Key of item to set.
* @param int|string|array|object $value Value of item.
* @throws WireException
* @return \WireArray
*
*/
public function set($key, $value) {
if(!$this->isValidItem($value)) throw new WireException("Item '$key' set to " . get_class($this) . " is not an allowed type");
if(!$this->isValidKey($key)) throw new WireException("Key '$key' is not an allowed key for " . get_class($this));
$this->data[$key] = $value;
$this->trackChange("set");
$this->trackAdd($value);
return $this;
}
/**
* Enables setting of WireArray elements in object notation.
*
* Example: $myArray->myElement = 10;
* Not applicable to numerically indexed arrays.
*
* @param int|string $property Key of item to set.
* @param int|string|array|object Value of item to set.
* @throws WireException
*
*/
public function __set($property, $value) {
if($this->getProperty($property)) throw new WireException("Property '$property' is a reserved word and may not be set by direct reference.");
$this->set($property, $value);
}
/**
* Ensures that isset() and empty() work for this classes properties.
*
*/
public function __isset($key) {
return isset($this->data[$key]);
}
/**
* Ensures that unset() works for this classes data.
*
*/
public function __unset($key) {
$this->remove($key);
}
/**
* Like set() but accepts an array or WireArray to set multiple values at once
*
* @param array|WireArray $data
* @return $this
*
*/
public function setArray($data) {
if(self::iterable($data)) {
foreach($data as $key => $value) $this->set($key, $value);
}
return $this;
}
/**
* Returns the value of the item at the given index, or false if not set.
*
* You may also specify a selector, in which case this method will return the same result as the findOne() method.
*
* @throws WireException
* @param int|string $key Key of item to retrieve. If not specified, 0 is assumed (for first item).
* @return int|string|array|object Value of item requested, or null if it doesn't exist.
*
*/
public function get($key) {
// if an object was provided, get it's key
if(is_object($key)) $key = $this->getItemKey($key);
// don't allow arrays as keys
if(is_array($key)) throw new WireException("WireArray::get cannot accept an array as a key");
// check if the index is set and return it if so
if(isset($this->data[$key])) return $this->data[$key];
// check if key contains a selector
if(Selectors::stringHasOperator($key)) return $this->findOne($key);
// if the WireArray uses numeric keys, then it's okay to
// match a 'name' field if the provided key is a string
$match = null;
if(is_string($key) && $this->usesNumericKeys()) $match = $this->getItemThatMatches('name', $key);
return $match;
}
/**
* Enables derefencing of WireArray elements in object notation.
*
* Example: $myArray->myElement
* Not applicable to numerically indexed arrays.
* Fuel properties and hooked properties have precedence with this type of call.
*
* @param int|string $property
* @return mixed Value of requested index, or false if it doesn't exist.
*
*/
public function __get($property) {
$value = parent::__get($property);
if(is_null($value)) $value = $this->getProperty($property);
if(is_null($value)) $value = $this->get($property);
return $value;
}
/**
* Get a predefined property of the array or extra data that has been set.
*
* These map to functions form the array and are here for convenience.
* Properties include count, last, first, keys, values.
* These can also be accessed by direct reference.
*
* @param string $property
* @return mixed
*
*/
public function getProperty($property) {
static $properties = array(
// property => method to map to
'count' => 'count',
'last' => 'last',
'first' => 'first',
'keys' => 'getKeys',
'values' => 'getValues',
);
if(!in_array($property, $properties)) return $this->data($property);
$func = $properties[$property];
return $this->$func();
}
/**
* Return the first item in this WireArray having a property called $key with the value of $value or NULL if not matched.
*
* Used internally by get() and has().
*
* @param string $key Property to match.
* @param string|int|object $value $value to match.
* @return Wire|null
*
*/
protected function getItemThatMatches($key, $value) {
if(ctype_digit("$key")) return null;
$item = null;
foreach($this->data as $wire) {
if($wire->$key === $value) {
$item = $wire;
break;
}
}
return $item;
}
/**
* Does this WireArray have the given index or match the given selector?
*
* If the WireArray uses numeric keys, then this will also match a wire's "name" field.
*
* @param int|string $key Key of item to check or selector.
* @return bool True if the item exists, false if not.
*/
public function has($key) {
if(is_object($key)) $key = $this->getItemKey($key);
if(array_key_exists($key, $this->data)) return true;
$match = null;
if(is_string($key)) {
if(Selectors::stringHasOperator($key)) {
$match = $this->findOne($key);
} else if($this->usesNumericKeys()) {
$match = $this->getItemThatMatches('name', $key);
}
}
return $match ? true : false;
}
/**
* Get a regular PHP array of all the items in this WireArray.
*
* @return array Copy of the array that WireArray uses internally.
*/
public function getArray() {
return $this->data;
}
/**
* Returns all items in the WireArray.
*
* This is for syntax convenience, as it simply eturns this instance of the WireArray.
*
* @return WireArray
*/
public function getAll() {
return $this;
}
/**
* Returns an array of all keys used in this WireArray.
*
* @return array Keys used in the WireArray.
*/
public function getKeys() {
return array_keys($this->data);
}
/**
* Returns an array of all values used in this WireArray.
*
* @return array Values used in the WireArray.
*/
public function getValues() {
return array_values($this->data);
}
/**
* Get one or more random elements from this WireArray.
*
* If one item is requested, the item is returned (unless $alwaysArray is true).
* If multiple items are requested, a new WireArray of those items is returned.
*
* @param int $num Number of items to return. Optional and defaults to 1.
* @param bool $alwaysArray If true, then method will always return a container of items, even if it only contains 1.
* @return int|string|array|object|WireArray|null Returns value of item, or new WireArray of items if more than one requested.
*/
public function getRandom($num = 1, $alwaysArray = false) {
$items = $this->makeNew();
$count = $this->count();
if(!$count) {
if($num == 1 && !$alwaysArray) return null;
return $items;
}
$keys = array_rand($this->data, ($num > $count ? $count : $num));
if($num == 1 && !$alwaysArray) return $this->data[$keys];
if(!is_array($keys)) $keys = array($keys);
foreach($keys as $key) $items->add($this->data[$key]);
$items->setTrackChanges(true);
return $items;
}
/**
* Get a quantity of random elements from this WireArray.
*
* Unlike getRandom() this one always returns a WireArray (or derived type).
*
* @param int $num Number of items to return
* @return WireArray
*
*/
public function findRandom($num) {
return $this->getRandom((int) $num, true);
}
/**
* Get a quantity of random elements from this WireArray based on a timed interval (or user provided seed).
*
* If no $seed is provided, today's date is used to seed the random number
* generator, so you can use this function to rotate items on a daily basis.
*
* Idea and implementation provided by @mindplay.dk
*
* @param int $num the amount of items to extract from the given list
* @param int|string $seed a number used to see the random number generator; or a string compatible with date()
* @return \WireArray
*
*/
public function findRandomTimed($num, $seed = 'Ymd') {
if(is_string($seed)) $seed = crc32(date($seed));
srand($seed);
$keys = $this->getKeys();
$items = $this->makeNew();
while(count($keys) > 0 && count($items) < $num) {
$index = rand(0, count($keys)-1);
$key = $keys[$index];
$items->add($this->get($key));
array_splice($keys, $index, 1);
}
return $items;
}
/**
* Get a slice of the WireArray.
*
* Given a starting point and a number of items, returns a new WireArray of those items.
* If $limit is omitted, then it includes everything beyond the starting point.
*
* @param int $start Starting index.
* @param int $limit Number of items to include. If omitted, includes the rest of the array.
* @return WireArray Returns a new WireArray.
*
*/
public function slice($start, $limit = 0) {
if($limit) $slice = array_slice($this->data, $start, $limit);
else $slice = array_slice($this->data, $start);
$items = $this->makeNew();
$items->import($slice);
$items->setTrackChanges(true);
return $items;
}
/**
* Prepend an element to the beginning of the WireArray.
*
* @param int|string|array|object $item Item to prepend.
* @return \WireArray This instance.
* @throws WireException
*
*/
public function prepend($item) {
if(!$this->isValidItem($item)) {
if($item instanceof WireArray) {
foreach($item as $i) $this->prepend($i);
return $this;
} else {
throw new WireException("Item prepend to " . get_class($this) . " is not an allowed type");
}
}
if(($key = $this->getItemKey($item)) !== null) {
$a = array($key => $item);
$this->data = $a + $this->data; // UNION operator for arrays
// $this->data = array_merge($a, $this->data);
} else {
array_unshift($this->data, $item);
}
//if($item instanceof Wire) $item->setTrackChanges();
$this->trackChange('prepend');
$this->trackAdd($item);
return $this;
}
/**
* Append an item to the end of the WireArray.
*
* @param int|string|array|object Item to append.
* @return WireArray This instance.
*
*/
public function append($item) {
$this->add($item);
return $this;
}
/**
* Unshift an element to the beginning of the WireArray.
*
* Alias for prepend()
*
* @param int|string|array|object Item to prepend.
* @return WireArray This instance.
*
*/
public function unshift($item) {
return $this->prepend($item);
}
/**
* Shift an element off the beginning of the WireArray.
*
* @return int|string|array|object Item shifted off the beginning.
*
*/
public function shift() {
$item = array_shift($this->data);
$this->trackChange('shift');
$this->trackRemove($item);
return $item;
}
/**
* Push an item at the end of the WireArray.
*
* Same as add() and append(), but here for syntax convenience.
*
* @param int|string|array|object Item to push.
* @return WireArray This instance.
*
*/
public function push($item) {
$this->add($item);
return $this;
}
/**
* Pop an element off the end of the WireArray.
*
* @return int|string|array|object Item popped off the end.
*
*/
public function pop() {
$item = array_pop($this->data);
$this->trackChange('pop');
$this->trackRemove($item);
return $item;
}
/**
* Shuffle/randomize the WireArray.
*
* @return WireArray This instance.
*
*/
public function shuffle() {
$keys = $this->getKeys();
$data = array();
// shuffle the keys rather than the original array in case it's associative
// because PHP's shuffle reindexes the array
shuffle($keys);
foreach($keys as $key) {
$data[$key] = $this->data[$key];
}
$this->data = $data;
$this->trackChange('shuffle');
return $this;
}
/**
* Returns a WireArray of the item at the given index.
*
* Unlike get() this returns a new WireArray with a single item, or a blank WireArray if item doesn't exist.
* Applicable to numerically indexed ProcesArray's only.
*
* @param int $num
* @return WireArray
*
*/
public function index($num) {
return $this->slice($num, 1);
}
/**
* Returns the item at the given index starting from 0, or NULL if it doesn't exist.
*
* Unlike the index() method, this returns an actual item and not another WireArray.
*
* @param int $num Return the nth item in this WireArray. Specify a negative number to count from the end rather than the start.
* @return Wire|null
*
*/
public function eq($num) {
$num = (int) $num;
$item = array_slice($this->data, $num, 1);
$item = count($item) ? reset($item) : null;
return $item;
}
/**
* Returns the first item in the WireArray or boolean FALSE if empty.
*
* Note that this resets the internal WireArray pointer, which would affect other active iterations.
*
* @return int|string|array|object
*
*/
public function first() {
return reset($this->data);
}
/**
* Returns the last item in the WireArray or boolean FALSE if empty.
*
* Note that this resets the internal WireArray pointer, which would affect other active iterations.
*
* @return int|string|array|object
*
*/
public function last() {
return end($this->data);
}
/**
* Removes the item at the given index from the WireArray (if it exists).
*
* @param int|string|Wire $key Index of item or object instance.
* @return WireArray This instance.
*
*/
public function remove($key) {
if(is_object($key)) {
$key = $this->getItemKey($key);
}
if($this->has($key)) {
$item = $this->data[$key];
unset($this->data[$key]);
$this->trackChange("remove");
$this->trackRemove($item);
}
return $this;
}
/**
* Removes all items from the WireArray
*
*/
public function removeAll() {
foreach($this as $key => $value) {
$this->remove($key);
}
return $this;
}
/**
* Sort this WireArray by the given properties.
*
* $properties can be given as a sortByField string, i.e. "name, datestamp" OR as an array of strings, i.e. array("name", "datestamp")
* You may also specify the properties as "property.subproperty", where property resolves to a Wire derived object,
* and subproperty resolves to a property within that object.
*
* @param string|array $properties Field names to sort by (comma separated string or an array). Prepend or append a minus "-" to reverse the sort (per field).
* @return WireArray reference to current instance.
*/
public function sort($properties) {
return $this->_sort($properties);
}
/**
* Sort this WireArray by the given properties (internal use)
*
* This function contains additions and modifications by @niklaka.
*
* $properties can be given as a sortByField string, i.e. "name, datestamp" OR as an array of strings, i.e. array("name", "datestamp")
* You may also specify the properties as "property.subproperty", where property resolves to a Wire derived object,
* and subproperty resolves to a property within that object.
*
* @param string|array $properties Field names to sort by (comma separated string or an array). Prepend or append a minus "-" to reverse the sort (per field).
* @param int $numNeeded *Internal* amount of rows that need to be sorted (optimization used by filterData)
* @return WireArray reference to current instance.
*/
protected function _sort($properties, $numNeeded = null) {
// string version is used for change tracking
$propertiesStr = is_array($properties) ? implode(',', $properties) : $properties;
if(!is_array($properties)) $properties = preg_split('/\s*,\s*/', $properties);
// shortcut for random (only allowed as the sole sort property)
// no warning/error for issuing more properties though
// TODO: warning for random+more properties (and trackChange() too)
if($properties[0] == 'random') return $this->shuffle();
$this->data = $this->stableSort($this, $properties, $numNeeded);
$this->trackChange("sort:$propertiesStr");
return $this;
}
/**
* Sort given array by first given property.
*
* This function contains additions and modifications by @niklaka.
*
* @param array &$data Reference to an array to sort.
* @param array $properties Array of properties: first property is used now and others in recursion, if needed.
* @param int $numNeeded *Internal* amount of rows that need to be sorted (optimization used by filterData)
* @return array Sorted array (at least $numNeeded items, if $numNeeded is given)
*/
protected function stableSort(&$data, $properties, $numNeeded = null) {
$property = array_shift($properties);
$unidentified = array();
$sortable = array();
$reverse = false;
$subProperty = '';
if(substr($property, 0, 1) == '-' || substr($property, -1) == '-') {
$reverse = true;
$property = trim($property, '-');
}
if($pos = strpos($property, ".")) {
$subProperty = substr($property, $pos+1);
$property = substr($property, 0, $pos);
}
foreach($data as $item) {
$key = $this->getItemPropertyValue($item, $property);
// if item->property resolves to another Wire, then try to get the subProperty from that Wire (if it exists)
if($key instanceof Wire && $subProperty) {
$key = $this->getItemPropertyValue($key, $subProperty);
}
// check for items that resolve to blank
if(is_null($key) || (is_string($key) && !strlen(trim($key)))) {
$unidentified[] = $item;
continue;
}
$key = (string) $key;
// ensure numeric sorting if the key is a number
if(ctype_digit("$key")) $key = (int) $key;
if(isset($sortable[$key])) {
// key resolved to the same value that another did, so keep them together by converting this index to an array
// this makes the algorithm stable (for equal keys the order would be undefined)
if(is_array($sortable[$key])) $sortable[$key][] = $item;
else $sortable[$key] = array($sortable[$key], $item);
} else {
$sortable[$key] = $item;
}
}
// sort the items by the keys we collected
if($reverse) krsort($sortable);
else ksort($sortable);
// add the items that resolved to no key to the end, as an array
$sortable[] = $unidentified;
// restore sorted array to lose sortable keys and restore proper keys
$a = array();
foreach($sortable as $key => $value) {
if(is_array($value)) {
// if more properties to sort by exist, use them for this sub-array
$n = null;
if($numNeeded) $n = $numNeeded - count($a);
if(count($properties)) $value = $this->stableSort($value, $properties, $n);
foreach($value as $k => $v) {
$newKey = $this->getItemKey($v);
$a[$newKey] = $v;
// are we done yet?
if($numNeeded && count($a) > $numNeeded) break;
}
} else {
$newKey = $this->getItemKey($value);
$a[$newKey] = $value;
}
// are we done yet?
if($numNeeded && count($a) > $numNeeded) break;
}
return $a;
}
/**
* Get the value of $property from $item
*
* Used by the WireArray::sort method to retrieve a value from a Wire object.
* Primarily here as a template method so that it can be overridden.
* Lets it prepare the Wire for any states needed for sorting.
*
* @param Wire $item
* @param string $property
* @return mixed
*
*/
protected function getItemPropertyValue(Wire $item, $property) {
if(strpos($property, '.') !== false) return WireData::_getDot($property, $item);
return $item->$property;
}
/**
* Filter out Wires that don't match the selector.
*
* This is applicable to and destructive to the WireArray.
* This function contains additions and modifications by @niklaka.
*
* @param string|Selectors $selectors AttributeSelector string to use as the filter.
* @param bool $not Make this a "not" filter? (default is false)
* @return WireArray reference to current [filtered] instance
*
*/
protected function filterData($selectors, $not = false) {
if(is_object($selectors) && $selectors instanceof Selectors) {
// fantastic
} else {
if(ctype_digit("$selectors")) $selectors = "id=$selectors";
$selectors = new Selectors($selectors);
}
$sort = array();
$start = 0;
$limit = null;
// leave sort, limit and start away from filtering selectors
foreach($selectors as $selector) {