Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
13 / 13 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| Collection | |
100.00% |
13 / 13 |
|
100.00% |
3 / 3 |
6 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| add | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| remove | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * @license MIT |
| 5 | * @author hazuki3417<hazuki3417@gmail.com> |
| 6 | * @copyright 2021 hazuki3417 all rights reserved. |
| 7 | */ |
| 8 | |
| 9 | namespace Selen\Data\Structure; |
| 10 | |
| 11 | use Selen\Data\Type; |
| 12 | |
| 13 | final class Collection extends AbstractCollection |
| 14 | { |
| 15 | /** @var string 型名またはクラス名 */ |
| 16 | private string $typeName; |
| 17 | |
| 18 | public function __construct(string $typeName) |
| 19 | { |
| 20 | $this->typeName = $typeName; |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * オブジェクトを追加します |
| 25 | * |
| 26 | * @param mixed $object 追加するオブジェクトを渡します |
| 27 | * |
| 28 | * @return bool 成功した場合はtrueを返します |
| 29 | * |
| 30 | * @throws \InvalidArgumentException 型が一致しない場合にスローします |
| 31 | */ |
| 32 | public function add($object): bool |
| 33 | { |
| 34 | $isExpectedType = Type::validate($object, $this->typeName); |
| 35 | |
| 36 | if (!$isExpectedType) { |
| 37 | throw new \InvalidArgumentException('Invalid argument type.'); |
| 38 | } |
| 39 | $this->objects[] = $object; |
| 40 | |
| 41 | return true; |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * オブジェクトを削除します |
| 46 | * |
| 47 | * @param mixed $object 削除するオブジェクトを渡します |
| 48 | * |
| 49 | * @return bool オブジェクトを削除できた場合はtrueを返します |
| 50 | * |
| 51 | * @throws \InvalidArgumentException 型が一致しない場合にスローします |
| 52 | */ |
| 53 | public function remove($object): bool |
| 54 | { |
| 55 | $isExpectedType = Type::validate($object, $this->typeName); |
| 56 | |
| 57 | if (!$isExpectedType) { |
| 58 | throw new \InvalidArgumentException('Invalid argument type.'); |
| 59 | } |
| 60 | |
| 61 | $index = \array_search($object, $this->objects, true); |
| 62 | |
| 63 | if ($index !== false) { |
| 64 | unset($this->objects[$index]); |
| 65 | } |
| 66 | |
| 67 | return true; |
| 68 | } |
| 69 | } |