1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
// Copyright (c) Lellys Informática. All rights reserved. See License.txt in the project root for license information. |
4
|
|
|
namespace Collections; |
5
|
|
|
|
6
|
|
|
use Collections\Iterator\VectorIterator; |
7
|
|
|
use Collections\Traits\VectorLikeTrait; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Vector is a stack-like collection. |
11
|
|
|
* |
12
|
|
|
* Like all objects in PHP, Vectors have reference-like semantics. When a |
13
|
|
|
* caller passes a Vector to a callee, the callee can modify the Vector and the |
14
|
|
|
* caller will see the changes. Vectors do not have "copy-on-write" semantics. |
15
|
|
|
* |
16
|
|
|
* Vectors only support integer keys. If a non-integer key is used, an |
17
|
|
|
* exception will be thrown. |
18
|
|
|
* |
19
|
|
|
* Vectors suoport "$m[$k]" style syntax for getting and setting values by |
20
|
|
|
* key. Vectors also support "isset($m[$k])" and "empty($m[$k])" syntax, and |
21
|
|
|
* they provide similar semantics as arrays. Elements can be added to a Vector |
22
|
|
|
* using "$m[] = .." syntax. |
23
|
|
|
* |
24
|
|
|
* Vectors do not support iterating while new elements are being added or |
25
|
|
|
* elements are being removed. When a new element is added or removed, all |
26
|
|
|
* iterators that point to the Vector shall be considered invalid. |
27
|
|
|
* |
28
|
|
|
* Vectors do not support taking elements by reference. If binding assignment |
29
|
|
|
* (=&) is used with an element of a Vector, or if an element of a Vector is |
30
|
|
|
* passed by reference, of if a Vector is used with foreach by reference, an |
31
|
|
|
* exception will be thrown. |
32
|
|
|
*/ |
33
|
|
|
class Vector implements VectorInterface, \ArrayAccess |
34
|
|
|
{ |
35
|
|
|
use VectorLikeTrait, SortTrait; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* {@inheritdoc} |
39
|
|
|
*/ |
40
|
|
|
public function __construct($array = null) |
41
|
|
|
{ |
42
|
|
|
$this->init($array); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public static function fromItems($items) |
46
|
|
|
{ |
47
|
|
|
return new self($items); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritdoc} |
52
|
|
|
*/ |
53
|
|
|
public function indexOf($item) |
54
|
|
|
{ |
55
|
|
|
return array_search($item, $this->container, true); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* {@inheritdoc} |
60
|
|
|
*/ |
61
|
|
|
public function reverse() |
62
|
|
|
{ |
63
|
|
|
return static::fromArray(array_reverse($this->container)); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Gets the collection's iterator |
68
|
|
|
* @return VectorIterator |
69
|
|
|
*/ |
70
|
|
|
public function getIterator() |
71
|
|
|
{ |
72
|
|
|
return new VectorIterator($this->container); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|