Vector.php 10.3 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7 8 9 10 11 12 13
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

/**
 * Vector implements an integer-indexed collection class.
 *
 * You can access, append, insert, remove an item from the vector
Qiang Xue committed
14 15
 * by calling methods such as [[itemAt()]], [[add()]], [[insertAt()]],
 * [[remove()]] and [[removeAt()]].
Qiang Xue committed
16
 *
Qiang Xue committed
17
 * To get the number of the items in the vector, use [[getCount()]].
Qiang Xue committed
18 19 20 21
 *
 * Because Vector implements a set of SPL interfaces, it can be used
 * like a regular PHP array as follows,
 *
w  
Qiang Xue committed
22
 * ~~~
Qiang Xue committed
23 24 25 26
 * $vector[] = $item;				// append new item at the end
 * $vector[$index] = $item;			// set new item at $index
 * unset($vector[$index]);			// remove the item at $index
 * if (isset($vector[$index]))		// if the vector has an item at $index
resurtm committed
27
 * foreach ($vector as $index => $item) // traverse each item in the vector
Qiang Xue committed
28
 * $n = count($vector);				// count the number of items
Qiang Xue committed
29 30 31 32
 * ~~~
 *
 * Note that if you plan to extend Vector by performing additional operations
 * with each addition or removal of an item (e.g. performing type check),
Qiang Xue committed
33 34 35
 * please make sure you override [[insertAt()]] and [[removeAt()]].
 *
 * @property integer $count the number of items in the vector
Qiang Xue committed
36 37 38 39
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
40
class Vector extends Object implements \IteratorAggregate, \ArrayAccess, \Countable
Qiang Xue committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54
{
	/**
	 * @var array internal data storage
	 */
	private $_d = array();
	/**
	 * @var integer number of items
	 */
	private $_c = 0;

	/**
	 * Constructor.
	 * Initializes the vector with an array or an iterable object.
	 * @param mixed $data the initial data to be populated into the vector.
Qiang Xue committed
55
	 * This can be an array or an iterable object.
Qiang Xue committed
56
	 * @param array $config name-value pairs that will be used to initialize the object properties
Qiang Xue committed
57 58
	 * @throws Exception if data is not well formed (neither an array nor an iterable object)
	 */
Qiang Xue committed
59
	public function __construct($data = array(), $config = array())
Qiang Xue committed
60
	{
61
		if (!empty($data)) {
Qiang Xue committed
62 63
			$this->copyFrom($data);
		}
Qiang Xue committed
64
		parent::__construct($config);
Qiang Xue committed
65 66 67 68 69 70
	}

	/**
	 * Returns an iterator for traversing the items in the vector.
	 * This method is required by the SPL interface `IteratorAggregate`.
	 * It will be implicitly called when you use `foreach` to traverse the vector.
Qiang Xue committed
71
	 * @return VectorIterator an iterator for traversing the items in the vector.
Qiang Xue committed
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
	 */
	public function getIterator()
	{
		return new VectorIterator($this->_d);
	}

	/**
	 * Returns the number of items in the vector.
	 * This method is required by the SPL `Countable` interface.
	 * It will be implicitly called when you use `count($vector)`.
	 * @return integer number of items in the vector.
	 */
	public function count()
	{
		return $this->getCount();
	}

	/**
	 * Returns the number of items in the vector.
	 * @return integer the number of items in the vector
	 */
	public function getCount()
	{
		return $this->_c;
	}

	/**
	 * Returns the item at the specified index.
	 * @param integer $index the index of the item
	 * @return mixed the item at the index
Qiang Xue committed
102
	 * @throws InvalidParamException if the index is out of range
Qiang Xue committed
103 104 105 106 107
	 */
	public function itemAt($index)
	{
		if (isset($this->_d[$index])) {
			return $this->_d[$index];
Qiang Xue committed
108
		} elseif ($index >= 0 && $index < $this->_c) { // in case the value is null
Qiang Xue committed
109
			return $this->_d[$index];
Qiang Xue committed
110
		} else {
Qiang Xue committed
111
			throw new InvalidParamException('Index out of range: ' . $index);
Qiang Xue committed
112
		}
Qiang Xue committed
113 114 115 116 117 118 119 120 121 122 123
	}

	/**
	 * Appends an item at the end of the vector.
	 * @param mixed $item new item
	 * @return integer the zero-based index at which the item is added
	 * @throws Exception if the vector is read-only.
	 */
	public function add($item)
	{
		$this->insertAt($this->_c, $item);
Qiang Xue committed
124
		return $this->_c - 1;
Qiang Xue committed
125 126 127 128 129 130 131 132
	}

	/**
	 * Inserts an item at the specified position.
	 * Original item at the position and the following items will be moved
	 * one step towards the end.
	 * @param integer $index the specified position.
	 * @param mixed $item new item to be inserted into the vector
Qiang Xue committed
133
	 * @throws InvalidParamException if the index specified is out of range, or the vector is read-only.
Qiang Xue committed
134 135 136
	 */
	public function insertAt($index, $item)
	{
w  
Qiang Xue committed
137 138
		if ($index === $this->_c) {
			$this->_d[$this->_c++] = $item;
Qiang Xue committed
139
		} elseif ($index >= 0 && $index < $this->_c) {
w  
Qiang Xue committed
140 141
			array_splice($this->_d, $index, 0, array($item));
			$this->_c++;
Qiang Xue committed
142
		} else {
Qiang Xue committed
143
			throw new InvalidParamException('Index out of range: ' . $index);
Qiang Xue committed
144 145 146 147 148 149 150 151 152 153 154 155 156 157
		}
	}

	/**
	 * Removes an item from the vector.
	 * The vector will search for the item, and the first item found
	 * will be removed from the vector.
	 * @param mixed $item the item to be removed.
	 * @return mixed the index at which the item is being removed, or false
	 * if the item cannot be found in the vector.
	 * @throws Exception if the vector is read only.
	 */
	public function remove($item)
	{
Qiang Xue committed
158
		if (($index = $this->indexOf($item)) >= 0) {
Qiang Xue committed
159 160
			$this->removeAt($index);
			return $index;
Qiang Xue committed
161
		} else {
Qiang Xue committed
162
			return false;
Qiang Xue committed
163
		}
Qiang Xue committed
164 165 166 167 168 169
	}

	/**
	 * Removes an item at the specified position.
	 * @param integer $index the index of the item to be removed.
	 * @return mixed the removed item.
Qiang Xue committed
170
	 * @throws InvalidParamException if the index is out of range, or the vector is read only.
Qiang Xue committed
171 172 173
	 */
	public function removeAt($index)
	{
w  
Qiang Xue committed
174 175 176 177
		if ($index >= 0 && $index < $this->_c) {
			$this->_c--;
			if ($index === $this->_c) {
				return array_pop($this->_d);
Qiang Xue committed
178
			} else {
w  
Qiang Xue committed
179 180 181
				$item = $this->_d[$index];
				array_splice($this->_d, $index, 1);
				return $item;
Qiang Xue committed
182
			}
Qiang Xue committed
183
		} else {
Qiang Xue committed
184
			throw new InvalidParamException('Index out of range: ' . $index);
Qiang Xue committed
185 186 187 188 189
		}
	}

	/**
	 * Removes all items from the vector.
190 191 192
	 * @param boolean $safeClear whether to clear every item by calling [[removeAt]].
	 * Defaults to false, meaning all items in the vector will be cleared directly
	 * without calling [[removeAt]].
Qiang Xue committed
193
	 */
Qiang Xue committed
194
	public function removeAll($safeClear = false)
Qiang Xue committed
195
	{
196
		if ($safeClear) {
Qiang Xue committed
197
			for ($i = $this->_c - 1; $i >= 0; --$i) {
198 199
				$this->removeAt($i);
			}
Qiang Xue committed
200
		} else {
201 202
			$this->_d = array();
			$this->_c = 0;
Qiang Xue committed
203 204 205 206 207 208 209 210 211
		}
	}

	/**
	 * Returns a value indicating whether the vector contains the specified item.
	 * Note that the search is based on strict PHP comparison.
	 * @param mixed $item the item
	 * @return boolean whether the vector contains the item
	 */
Qiang Xue committed
212
	public function has($item)
Qiang Xue committed
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
	{
		return $this->indexOf($item) >= 0;
	}

	/**
	 * Returns the index of the specified item in the vector.
	 * The index is zero-based. If the item is not found in the vector, -1 will be returned.
	 * Note that the search is based on strict PHP comparison.
	 * @param mixed $item the item
	 * @return integer the index of the item in the vector (0 based), -1 if not found.
	 */
	public function indexOf($item)
	{
		$index = array_search($item, $this->_d, true);
		return $index === false ? -1 : $index;
	}

	/**
	 * Returns the vector as a PHP array.
	 * @return array the items in the vector.
	 */
	public function toArray()
	{
		return $this->_d;
	}

	/**
	 * Copies iterable data into the vector.
	 * Note, existing data in the vector will be cleared first.
	 * @param mixed $data the data to be copied from, must be an array or an object implementing `Traversable`
Qiang Xue committed
243
	 * @throws InvalidParamException if data is neither an array nor an object implementing `Traversable`.
Qiang Xue committed
244
	 */
Qiang Xue committed
245
	public function copyFrom($data)
Qiang Xue committed
246
	{
247
		if (is_array($data) || $data instanceof \Traversable) {
Qiang Xue committed
248
			if ($this->_c > 0) {
Qiang Xue committed
249
				$this->removeAll();
Qiang Xue committed
250 251 252 253 254 255 256
			}
			if ($data instanceof self) {
				$data = $data->_d;
			}
			foreach ($data as $item) {
				$this->add($item);
			}
Qiang Xue committed
257
		} else {
Qiang Xue committed
258
			throw new InvalidParamException('Data must be either an array or an object implementing Traversable.');
Qiang Xue committed
259
		}
Qiang Xue committed
260 261 262 263 264
	}

	/**
	 * Merges iterable data into the vector.
	 * New items will be appended to the end of the existing items.
Qiang Xue committed
265
	 * @param array|\Traversable $data the data to be merged with. It must be an array or object implementing Traversable
Qiang Xue committed
266
	 * @throws InvalidParamException if data is neither an array nor an object implementing `Traversable`.
Qiang Xue committed
267 268 269
	 */
	public function mergeWith($data)
	{
270
		if (is_array($data) || ($data instanceof \Traversable)) {
Qiang Xue committed
271 272 273 274 275 276
			if ($data instanceof Vector) {
				$data = $data->_d;
			}
			foreach ($data as $item) {
				$this->add($item);
			}
Qiang Xue committed
277
		} else {
Qiang Xue committed
278
			throw new InvalidParamException('The data to be merged with must be an array or an object implementing Traversable.');
Qiang Xue committed
279
		}
Qiang Xue committed
280 281 282 283 284
	}

	/**
	 * Returns a value indicating whether there is an item at the specified offset.
	 * This method is required by the SPL interface `ArrayAccess`.
w  
Qiang Xue committed
285
	 * It is implicitly called when you use something like `isset($vector[$offset])`.
Qiang Xue committed
286 287 288 289 290 291 292 293 294 295 296
	 * @param integer $offset the offset to be checked
	 * @return boolean whether there is an item at the specified offset.
	 */
	public function offsetExists($offset)
	{
		return $offset >= 0 && $offset < $this->_c;
	}

	/**
	 * Returns the item at the specified offset.
	 * This method is required by the SPL interface `ArrayAccess`.
w  
Qiang Xue committed
297
	 * It is implicitly called when you use something like `$value = $vector[$offset];`.
Qiang Xue committed
298
	 * This is equivalent to [[itemAt]].
Qiang Xue committed
299 300 301 302 303 304 305 306 307 308 309 310
	 * @param integer $offset the offset to retrieve item.
	 * @return mixed the item at the offset
	 * @throws Exception if the offset is out of range
	 */
	public function offsetGet($offset)
	{
		return $this->itemAt($offset);
	}

	/**
	 * Sets the item at the specified offset.
	 * This method is required by the SPL interface `ArrayAccess`.
w  
Qiang Xue committed
311
	 * It is implicitly called when you use something like `$vector[$offset] = $item;`.
Qiang Xue committed
312 313 314 315 316 317 318 319 320 321 322
	 * If the offset is null or equal to the number of the existing items,
	 * the new item will be appended to the vector.
	 * Otherwise, the existing item at the offset will be replaced with the new item.
	 * @param integer $offset the offset to set item
	 * @param mixed $item the item value
	 * @throws Exception if the offset is out of range, or the vector is read only.
	 */
	public function offsetSet($offset, $item)
	{
		if ($offset === null || $offset === $this->_c) {
			$this->insertAt($this->_c, $item);
Qiang Xue committed
323
		} else {
Qiang Xue committed
324 325 326 327 328 329 330 331
			$this->removeAt($offset);
			$this->insertAt($offset, $item);
		}
	}

	/**
	 * Unsets the item at the specified offset.
	 * This method is required by the SPL interface `ArrayAccess`.
w  
Qiang Xue committed
332
	 * It is implicitly called when you use something like `unset($vector[$offset])`.
Qiang Xue committed
333 334 335 336 337 338 339 340 341
	 * This is equivalent to [[removeAt]].
	 * @param integer $offset the offset to unset item
	 * @throws Exception if the offset is out of range, or the vector is read only.
	 */
	public function offsetUnset($offset)
	{
		$this->removeAt($offset);
	}
}