3 * TPriorityList, TPriorityListIterator classes
5 * @author Brad Anderson <javalizard@gmail.com>
6 * @link http://www.pradosoft.com/
7 * @copyright Copyright © 2005-2014 PradoSoft
8 * @license http://www.pradosoft.com/license/
9 * @package System.Collections
15 * TPriorityList implements a priority ordered list collection class. It allows you to specify
16 * any numeric for priorities down to a specific precision. The lower the numeric, the high the priority of the item in the
17 * list. Thus -10 has a higher priority than -5, 0, 10 (the default), 18, 10005, etc. Per {@link round}, precision may be negative and
18 * thus rounding can go by 10, 100, 1000, etc, instead of just .1, .01, .001, etc. The default precision allows for 8 decimal
19 * places. There is also a default priority of 10, if no different default priority is specified or no item specific priority is indicated.
20 * If you replace TList with this class it will work exactly the same with items inserted set to the default priority, until you start
21 * using different priorities than the default priority.
23 * As you access the PHP array features of this class, it flattens and caches the results. If at all possible, this
24 * will keep the cache fresh even when manipulated. If this is not possible the cache is cleared.
25 * When an array of items are needed and the cache is outdated, the cache is recreated from the items and their priorities
27 * You can access, append, insert, remove an item by using
28 * {@link itemAt}, {@link add}, {@link insertAt}, and {@link remove}.
29 * To get the number of the items in the list, use {@link getCount}.
30 * TPriorityList can also be used like a regular array as follows,
32 * $list[]=$item; // append with the default priority. It may not be the last item if other items in the list are prioritized after the default priority
33 * $list[$index]=$item; // $index must be between 0 and $list->Count-1. This sets the element regardless of priority. Priority stays the same.
34 * $list[$index]=$item; // $index is $list->Count. This appends the item to the end of the list with the same priority as the last item in the list.
35 * unset($list[$index]); // remove the item at $index
36 * if(isset($list[$index])) // if the list has an item at $index
37 * foreach($list as $index=>$item) // traverse each item in the list in proper priority order and add/insert order
38 * $n=count($list); // returns the number of items in the list
41 * To extend TPriorityList for doing your own operations with each addition or removal,
42 * override {@link insertAtIndexInPriority()} and {@link removeAtIndexInPriority()} and then call the parent.
44 * @author Brad Anderson <javalizard@gmail.com>
45 * @package System.Collections
48 class TPriorityList extends TList
51 * @var array internal data storage
55 * @var boolean indicates if the _d is currently ordered.
59 * @var array cached flattened internal data storage
63 * @var integer number of items contain within the list
67 * @var numeric the default priority of items without specified priorities
71 * @var integer the precision of the numeric priorities within this priority list.
77 * Initializes the list with an array or an iterable object.
78 * @param array|Iterator the intial data. Default is null, meaning no initial data.
79 * @param boolean whether the list is read-only
80 * @param numeric the default priority of items without specified priorities.
81 * @param integer the precision of the numeric priorities
82 * @throws TInvalidDataTypeException If data is not null and is neither an array nor an iterator.
84 public function __construct($data=null,$readOnly=false,$defaultPriority=10,$precision=8)
86 parent::__construct();
88 $this->copyFrom($data);
89 $this->setReadOnly($readOnly);
90 $this->setPrecision($precision);
91 $this->setDefaultPriority($defaultPriority);
95 * Returns the number of items in the list.
96 * This method is required by Countable interface.
97 * @return integer number of items in the list.
99 public function count()
101 return $this->getCount();
105 * Returns the total number of items in the list
106 * @return integer the number of items in the list
108 public function getCount()
114 * Gets the number of items at a priority within the list
115 * @param numeric optional priority at which to count items. if no parameter, it will be set to the default {@link getDefaultPriority}
116 * @return integer the number of items in the list at the specified priority
118 public function getPriorityCount($priority=null)
121 $priority=$this->getDefaultPriority();
122 $priority=(string)round(TPropertyValue::ensureFloat($priority),$this->_p);
124 if(!isset($this->_d[$priority]) || !is_array($this->_d[$priority]))
126 return count($this->_d[$priority]);
130 * @return numeric gets the default priority of inserted items without a specified priority
132 public function getDefaultPriority()
138 * This must be called internally or when instantiated.
139 * @param numeric sets the default priority of inserted items without a specified priority
141 protected function setDefaultPriority($value)
143 $this->_dp=(string)round(TPropertyValue::ensureFloat($value),$this->_p);
147 * @return integer The precision of numeric priorities, defaults to 8
149 public function getPrecision()
155 * This must be called internally or when instantiated.
156 * @param integer The precision of numeric priorities.
158 protected function setPrecision($value)
160 $this->_p=TPropertyValue::ensureInteger($value);
164 * Returns an iterator for traversing the items in the list.
165 * This method is required by the interface IteratorAggregate.
166 * @return Iterator an iterator for traversing the items in the list.
168 public function getIterator()
170 return new ArrayIterator($this->flattenPriorities());
174 * This returns a list of the priorities within this list, ordered lowest to highest.
175 * @return array the array of priority numerics in decreasing priority order
177 public function getPriorities()
179 $this->sortPriorities();
180 return array_keys($this->_d);
185 * This orders the priority list internally.
187 protected function sortPriorities() {
189 ksort($this->_d,SORT_NUMERIC);
195 * This flattens the priority list into a flat array [0,...,n-1]
196 * @return array array of items in the list in priority and index order
198 protected function flattenPriorities() {
199 if(is_array($this->_fd))
202 $this->sortPriorities();
204 foreach($this->_d as $priority => $itemsatpriority)
205 $this->_fd=array_merge($this->_fd,$itemsatpriority);
211 * Returns the item at the index of a flattened priority list.
212 * {@link offsetGet} calls this method.
213 * @param integer the index of the item to get
214 * @return mixed the element at the offset
215 * @throws TInvalidDataValueException Issued when the index is invalid
217 public function itemAt($index)
219 if($index>=0&&$index<$this->getCount()) {
220 $arr=$this->flattenPriorities();
223 throw new TInvalidDataValueException('list_index_invalid',$index);
227 * Gets all the items at a specific priority.
228 * @param numeric priority of the items to get. Defaults to null, filled in with the default priority, if left blank.
229 * @return array all items at priority in index order, null if there are no items at that priority
231 public function itemsAtPriority($priority=null)
234 $priority=$this->getDefaultPriority();
235 $priority=(string)round(TPropertyValue::ensureFloat($priority),$this->_p);
237 return isset($this->_d[$priority])?$this->_d[$priority]:null;
241 * Returns the item at an index within a priority
242 * @param integer the index into the list of items at priority
243 * @param numeric the priority which to index. no parameter or null will result in the default priority
244 * @return mixed the element at the offset, false if no element is found at the offset
246 public function itemAtIndexInPriority($index,$priority=null)
249 $priority=$this->getDefaultPriority();
250 $priority=(string)round(TPropertyValue::ensureFloat($priority), $this->_p);
252 return !isset($this->_d[$priority])?false:(
253 isset($this->_d[$priority][$index])?$this->_d[$priority][$index]:false
258 * Appends an item into the list at the end of the specified priority. The position of the added item may
259 * not be at the end of the list.
260 * @param mixed item to add into the list at priority
261 * @param numeric priority blank or null for the default priority
262 * @return int the index within the flattened array
263 * @throws TInvalidOperationException if the map is read-only
265 public function add($item,$priority=null)
267 if($this->getReadOnly())
268 throw new TInvalidOperationException('list_readonly',get_class($this));
270 return $this->insertAtIndexInPriority($item,false,$priority,true);
274 * Inserts an item at an index. It reads the priority of the item at index within the flattened list
275 * and then inserts the item at that priority-index.
276 * @param integer the specified position in the flattened list.
277 * @param mixed new item to add
278 * @throws TInvalidDataValueException If the index specified exceeds the bound
279 * @throws TInvalidOperationException if the list is read-only
281 public function insertAt($index,$item)
283 if($this->getReadOnly())
284 throw new TInvalidOperationException('list_readonly',get_class($this));
286 if(($priority=$this->priorityAt($index,true))!==false)
287 $this->insertAtIndexInPriority($item,$priority[1],$priority[0]);
289 throw new TInvalidDataValueException('list_index_invalid',$index);
293 * Inserts an item at the specified index within a priority. Override and call this method to
294 * insert your own functionality.
295 * @param mixed item to add within the list.
296 * @param integer index within the priority to add the item, defaults to false which appends the item at the priority
297 * @param numeric priority priority of the item. defaults to null, which sets it to the default priority
298 * @param boolean preserveCache specifies if this is a special quick function or not. This defaults to false.
299 * @throws TInvalidDataValueException If the index specified exceeds the bound
300 * @throws TInvalidOperationException if the list is read-only
302 public function insertAtIndexInPriority($item,$index=false,$priority=null,$preserveCache=false)
304 if($this->getReadOnly())
305 throw new TInvalidOperationException('list_readonly',get_class($this));
308 $priority=$this->getDefaultPriority();
309 $priority=(string)round(TPropertyValue::ensureFloat($priority), $this->_p);
312 $this->sortPriorities();
314 foreach($this->_d as $prioritykey=>$items)
315 if($prioritykey>=$priority)
320 if($index===false&&isset($this->_d[$priority])) {
321 $c=count($this->_d[$priority]);
323 $this->_d[$priority][]=$item;
324 } else if(isset($this->_d[$priority])) {
326 array_splice($this->_d[$priority],$index,0,array($item));
330 $this->_d[$priority]=array($item);
333 if($this->_fd&&is_array($this->_fd)) // if there is a flattened array cache
334 array_splice($this->_fd,$c,0,array($item));
337 if($index===false&&isset($this->_d[$priority])) {
338 $cc=count($this->_d[$priority]);
339 $this->_d[$priority][]=$item;
340 } else if(isset($this->_d[$priority])) {
342 array_splice($this->_d[$priority],$index,0,array($item));
346 $this->_d[$priority]=array($item);
348 if($this->_fd&&is_array($this->_fd)&&count($this->_d)==1)
349 array_splice($this->_fd,$cc,0,array($item));
362 * Removes an item from the priority list.
363 * The list will search for the item. The first matching item found will be removed from the list.
364 * @param mixed item the item to be removed.
365 * @param numeric priority of item to remove. without this parameter it defaults to false.
366 * A value of false means any priority. null will be filled in with the default priority.
367 * @return integer index within the flattened list at which the item is being removed
368 * @throws TInvalidDataValueException If the item does not exist
370 public function remove($item,$priority=false)
372 if($this->getReadOnly())
373 throw new TInvalidOperationException('list_readonly',get_class($this));
375 if(($p=$this->priorityOf($item,true))!==false)
377 if($priority!==false) {
379 $priority=$this->getDefaultPriority();
380 $priority=(string)round(TPropertyValue::ensureFloat($priority),$this->_p);
383 throw new TInvalidDataValueException('list_item_inexistent');
385 $this->removeAtIndexInPriority($p[1],$p[0]);
389 throw new TInvalidDataValueException('list_item_inexistent');
393 * Removes an item at the specified index in the flattened list.
394 * @param integer index of the item to be removed.
395 * @return mixed the removed item.
396 * @throws TInvalidDataValueException If the index specified exceeds the bound
397 * @throws TInvalidOperationException if the list is read-only
399 public function removeAt($index)
401 if($this->getReadOnly())
402 throw new TInvalidOperationException('list_readonly',get_class($this));
404 if(($priority=$this->priorityAt($index, true))!==false)
405 return $this->removeAtIndexInPriority($priority[1],$priority[0]);
406 throw new TInvalidDataValueException('list_index_invalid',$index);
410 * Removes the item at a specific index within a priority. Override
411 * and call this method to insert your own functionality.
412 * @param integer index of item to remove within the priority.
413 * @param numeric priority of the item to remove, defaults to null, or left blank, it is then set to the default priority
414 * @return mixed the removed item.
415 * @throws TInvalidDataValueException If the item does not exist
417 public function removeAtIndexInPriority($index, $priority=null)
419 if($this->getReadOnly())
420 throw new TInvalidOperationException('list_readonly',get_class($this));
423 $priority=$this->getDefaultPriority();
424 $priority=(string)round(TPropertyValue::ensureFloat($priority),$this->_p);
426 if(!isset($this->_d[$priority])||$index<0||$index>=count($this->_d[$priority]))
427 throw new TInvalidDataValueException('list_item_inexistent');
429 // $value is an array of elements removed, only one
430 $value=array_splice($this->_d[$priority],$index,1);
433 if(!count($this->_d[$priority]))
434 unset($this->_d[$priority]);
442 * Removes all items in the priority list by calling removeAtIndexInPriority from the last item to the first.
444 public function clear()
446 if($this->getReadOnly())
447 throw new TInvalidOperationException('list_readonly',get_class($this));
449 $d=array_reverse($this->_d,true);
450 foreach($this->_d as $priority=>$items) {
451 for($index=count($items)-1;$index>=0;$index--)
452 $this->removeAtIndexInPriority($index,$priority);
453 unset($this->_d[$priority]);
459 * @return boolean whether the list contains the item
461 public function contains($item)
463 return $this->indexOf($item)>=0;
468 * @return integer the index of the item in the flattened list (0 based), -1 if not found.
470 public function indexOf($item)
472 if(($index=array_search($item,$this->flattenPriorities(),true))===false)
479 * Returns the priority of a particular item
480 * @param mixed the item to look for within the list
481 * @param boolean withindex this specifies if the full positional data of the item within the list is returned.
482 * This defaults to false, if no parameter is provided, so only provides the priority number of the item by default.
483 * @return numeric|array the priority of the item in the list, false if not found.
484 * if withindex is true, an array is returned of [0 => $priority, 1 => $priorityIndex, 2 => flattenedIndex,
485 * 'priority' => $priority, 'index' => $priorityIndex, 'absindex' => flattenedIndex]
487 public function priorityOf($item,$withindex = false)
489 $this->sortPriorities();
492 foreach($this->_d as $priority=>$items) {
493 if(($index=array_search($item,$items,true))!==false) {
495 return $withindex?array($priority,$index,$absindex,
496 'priority'=>$priority,'index'=>$index,'absindex'=>$absindex):$priority;
498 $absindex+=count($items);
505 * Retutrns the priority of an item at a particular flattened index.
506 * @param integer index of the item within the list
507 * @param boolean withindex this specifies if the full positional data of the item within the list is returned.
508 * This defaults to false, if no parameter is provided, so only provides the priority number of the item by default.
509 * @return numeric|array the priority of the item in the list, false if not found.
510 * if withindex is true, an array is returned of [0 => $priority, 1 => $priorityIndex, 2 => flattenedIndex,
511 * 'priority' => $priority, 'index' => $priorityIndex, 'absindex' => flattenedIndex]
513 public function priorityAt($index,$withindex = false)
515 if($index<0||$index>=$this->getCount())
516 throw new TInvalidDataValueException('list_index_invalid',$index);
519 $this->sortPriorities();
520 foreach($this->_d as $priority=>$items) {
521 if($index>=($c=count($items)))
524 return $withindex?array($priority,$index,$absindex,
525 'priority'=>$priority,'index'=>$index,'absindex'=>$absindex):$priority;
531 * This inserts an item before another item within the list. It uses the same priority as the
532 * found index item and places the new item before it.
533 * @param mixed indexitem the item to index
534 * @param mixed the item to add before indexitem
535 * @return integer where the item has been inserted in the flattened list
536 * @throws TInvalidDataValueException If the item does not exist
538 public function insertBefore($indexitem, $item)
540 if($this->getReadOnly())
541 throw new TInvalidOperationException('list_readonly',get_class($this));
543 if(($priority=$this->priorityOf($indexitem,true))===false)
544 throw new TInvalidDataValueException('list_item_inexistent');
546 $this->insertAtIndexInPriority($item,$priority[1],$priority[0]);
552 * This inserts an item after another item within the list. It uses the same priority as the
553 * found index item and places the new item after it.
554 * @param mixed indexitem the item to index
555 * @param mixed the item to add after indexitem
556 * @return integer where the item has been inserted in the flattened list
557 * @throws TInvalidDataValueException If the item does not exist
559 public function insertAfter($indexitem, $item)
561 if($this->getReadOnly())
562 throw new TInvalidOperationException('list_readonly',get_class($this));
564 if(($priority=$this->priorityOf($indexitem,true))===false)
565 throw new TInvalidDataValueException('list_item_inexistent');
567 $this->insertAtIndexInPriority($item,$priority[1]+1,$priority[0]);
569 return $priority[2]+1;
573 * @return array the priority list of items in array
575 public function toArray()
577 return $this->flattenPriorities();
581 * @return array the array of priorities keys with values of arrays of items. The priorities are sorted so important priorities, lower numerics, are first.
583 public function toPriorityArray()
585 $this->sortPriorities();
590 * Combines the map elements which have a priority below the parameter value
591 * @param numeric the cut-off priority. All items of priority less than this are returned.
592 * @param boolean whether or not the input cut-off priority is inclusive. Default: false, not inclusive.
593 * @return array the array of priorities keys with values of arrays of items that are below a specified priority.
594 * The priorities are sorted so important priorities, lower numerics, are first.
596 public function toArrayBelowPriority($priority,$inclusive=false)
598 $this->sortPriorities();
600 foreach($this->_d as $itemspriority=>$itemsatpriority)
602 if((!$inclusive&&$itemspriority>=$priority)||$itemspriority>$priority)
604 $items=array_merge($items,$itemsatpriority);
610 * Combines the map elements which have a priority above the parameter value
611 * @param numeric the cut-off priority. All items of priority greater than this are returned.
612 * @param boolean whether or not the input cut-off priority is inclusive. Default: true, inclusive.
613 * @return array the array of priorities keys with values of arrays of items that are above a specified priority.
614 * The priorities are sorted so important priorities, lower numerics, are first.
616 public function toArrayAbovePriority($priority,$inclusive=true)
618 $this->sortPriorities();
620 foreach($this->_d as $itemspriority=>$itemsatpriority)
622 if((!$inclusive&&$itemspriority<=$priority)||$itemspriority<$priority)
624 $items=array_merge($items,$itemsatpriority);
631 * Copies iterable data into the priority list.
632 * Note, existing data in the map will be cleared first.
633 * @param mixed the data to be copied from, must be an array or object implementing Traversable
634 * @throws TInvalidDataTypeException If data is neither an array nor an iterator.
636 public function copyFrom($data)
638 if($data instanceof TPriorityList)
640 if($this->getCount()>0)
642 foreach($data->getPriorities() as $priority)
644 foreach($data->itemsAtPriority($priority) as $index=>$item)
645 $this->insertAtIndexInPriority($item,$index,$priority);
647 } else if(is_array($data)||$data instanceof Traversable) {
648 if($this->getCount()>0)
650 foreach($data as $key=>$item)
652 } else if($data!==null)
653 throw new TInvalidDataTypeException('map_data_not_iterable');
657 * Merges iterable data into the priority list.
658 * New data will be appended to the end of the existing data. If another TPriorityList is merged,
659 * the incoming parameter items will be appended at the priorities they are present. These items will be added
660 * to the end of the existing items with equal priorities, if there are any.
661 * @param mixed the data to be merged with, must be an array or object implementing Traversable
662 * @throws TInvalidDataTypeException If data is neither an array nor an iterator.
664 public function mergeWith($data)
666 if($data instanceof TPriorityList)
668 foreach($data->getPriorities() as $priority)
670 foreach($data->itemsAtPriority($priority) as $index=>$item)
671 $this->insertAtIndexInPriority($item,false,$priority);
674 else if(is_array($data)||$data instanceof Traversable)
676 foreach($data as $priority=>$item)
680 else if($data!==null)
681 throw new TInvalidDataTypeException('map_data_not_iterable');
685 * Returns whether there is an element at the specified offset.
686 * This method is required by the interface ArrayAccess.
687 * @param mixed the offset to check on
690 public function offsetExists($offset)
692 return ($offset>=0&&$offset<$this->getCount());
696 * Returns the element at the specified offset.
697 * This method is required by the interface ArrayAccess.
698 * @param integer the offset to retrieve element.
699 * @return mixed the element at the offset, null if no element is found at the offset
701 public function offsetGet($offset)
703 return $this->itemAt($offset);
707 * Sets the element at the specified offset. This method is required by the interface ArrayAccess.
708 * Setting elements in a priority list is not straight forword when appending and setting at the
709 * end boundary. When appending without an offset (a null offset), the item will be added at
710 * the default priority. The item may not be the last item in the list. When appending with an
711 * offset equal to the count of the list, the item will get be appended with the last items priority.
713 * All together, when setting the location of an item, the item stays in that location, but appending
714 * an item into a priority list doesn't mean the item is at the end of the list.
715 * @param integer the offset to set element
716 * @param mixed the element value
718 public function offsetSet($offset,$item)
721 return $this->add($item);
722 if($offset===$this->getCount()) {
723 $priority=$this->priorityAt($offset-1,true);
726 $priority=$this->priorityAt($offset,true);
727 $this->removeAtIndexInPriority($priority[1],$priority[0]);
729 $this->insertAtIndexInPriority($item,$priority[1],$priority[0]);
733 * Unsets the element at the specified offset.
734 * This method is required by the interface ArrayAccess.
735 * @param mixed the offset to unset element
737 public function offsetUnset($offset)
739 $this->removeAt($offset);