|
| 1 | +<?php |
| 2 | + |
| 3 | +class MabeEnum_EnumMap implements Iterator, Countable |
| 4 | +{ |
| 5 | + private $enums = array(); |
| 6 | + private $values = array(); |
| 7 | + |
| 8 | + private $enumClass; |
| 9 | + |
| 10 | + public function __construct($enumClass) |
| 11 | + { |
| 12 | + $reflectionClass = new ReflectionClass($enumClass); |
| 13 | + if (!reflectionClass->isInstanceOf('MabeEnum_Enum')) { |
| 14 | + throw new InvalidArgumentException("'{$enumClass}' have to be an instance of 'MabeEnum_Enum'"); |
| 15 | + } |
| 16 | + |
| 17 | + $this->enumClass = $enumClass; |
| 18 | + } |
| 19 | + |
| 20 | + public function attach($enum, $value) |
| 21 | + { |
| 22 | + if (!($enum instanceof $this->enumClass)) { |
| 23 | + $enum = new $this->enumClass($enum); |
| 24 | + } |
| 25 | + |
| 26 | + if ($this->contains($enum)) { |
| 27 | + throw new RuntimeException("'{$enum}' already attached to map"); |
| 28 | + } |
| 29 | + |
| 30 | + $ordinal = $enum->getOrdinal(); |
| 31 | + $this->values[$ordinal] = $value; |
| 32 | + $this->enums[$ordinal] = $enum; |
| 33 | + } |
| 34 | + |
| 35 | + public function get($enum) |
| 36 | + { |
| 37 | + if (!($enum instanceof $this->enumClass)) { |
| 38 | + $enum = new $this->enumClass($enum); |
| 39 | + } |
| 40 | + |
| 41 | + if (!$this->contains($enum)) { |
| 42 | + throw new RuntimeException("'{$enum}' not attached to map"); |
| 43 | + } |
| 44 | + |
| 45 | + return $this->values[$enum->getOrdinal()]; |
| 46 | + } |
| 47 | + |
| 48 | + public function contains($enum) |
| 49 | + { |
| 50 | + if (!($enum instanceof $this->enumClass)) { |
| 51 | + $enum = new $this->enumClass($enum); |
| 52 | + } |
| 53 | + |
| 54 | + return array_key_exists($enum->getOrdinal(), $this->values); |
| 55 | + } |
| 56 | + |
| 57 | + public function detach($enum) |
| 58 | + { |
| 59 | + if (!($enum instanceof $this->enumClass)) { |
| 60 | + $enum = new $this->enumClass($enum); |
| 61 | + } |
| 62 | + |
| 63 | + if (!$this->contains($enum)) { |
| 64 | + throw new RuntimeException("'{$enum}' not attached to map"); |
| 65 | + } |
| 66 | + |
| 67 | + $ordinal = $enum->getOrdinal(); |
| 68 | + unset($this->values[$ordinal], $this->enums[$ordinal]); |
| 69 | + } |
| 70 | + |
| 71 | + /* Iterator */ |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | + /* Countable */ |
| 76 | + |
| 77 | + public function count() |
| 78 | + { |
| 79 | + return count($this->map); |
| 80 | + } |
| 81 | +} |
0 commit comments