1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ducatel\PHPCollection; |
4
|
|
|
|
5
|
|
|
use Ducatel\PHPCollection\Exception\NoDuplicateAllowedException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* This class represent a set which contains only one type of object. |
9
|
|
|
* |
10
|
|
|
* Characteristics: |
11
|
|
|
* |
12
|
|
|
* - Values: Typed value, duplicates not allowed |
13
|
|
|
* - Ordering: No specific order |
14
|
|
|
* |
15
|
|
|
* @package Ducatel\PHPCollection |
16
|
|
|
* @author D.Ducatel |
17
|
|
|
*/ |
18
|
|
|
class TypedSet extends TypedArray |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Add an object to this collection |
22
|
|
|
* |
23
|
|
|
* @param object $object The object you want to add |
24
|
|
|
* |
25
|
|
|
* @param null|object $key The key where object will be stored. Null if you won't to use this as associative array |
26
|
|
|
* |
27
|
|
|
* @return True when added with success. False if you try to add a duplicate or if the type is not valid |
28
|
|
|
*/ |
29
|
|
|
public function add($object, $key = null) |
30
|
|
|
{ |
31
|
|
|
try { |
32
|
|
|
if ($this->contains($object)) { |
33
|
|
|
return false; |
34
|
|
|
} |
35
|
|
|
} catch (\TypeError $e) { |
36
|
|
|
return false; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
|
40
|
|
|
return parent::add($object, $key); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Offset to set |
45
|
|
|
* |
46
|
|
|
* @link http://php.net/manual/en/arrayaccess.offsetset.php |
47
|
|
|
* |
48
|
|
|
* @param mixed $offset The offset to assign the value to. |
49
|
|
|
* @param mixed $value The value to set. |
50
|
|
|
* |
51
|
|
|
* @throws NoDuplicateAllowedException When try to add an object already added |
52
|
|
|
* @throws \TypeError When try to add type not managed by this collection |
53
|
|
|
* @thows |
54
|
|
|
* @since 5.0.0 |
55
|
|
|
*/ |
56
|
|
|
public function offsetSet($offset, $value) |
57
|
|
|
{ |
58
|
|
|
if ($this->contains($value)) { |
59
|
|
|
throw new NoDuplicateAllowedException("Object already inserted"); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
parent::offsetSet($offset, $value); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|