EnumMap.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. declare(strict_types = 1);
  3. namespace DASPRiD\Enum;
  4. use DASPRiD\Enum\Exception\ExpectationException;
  5. use DASPRiD\Enum\Exception\IllegalArgumentException;
  6. use IteratorAggregate;
  7. use Serializable;
  8. use Traversable;
  9. /**
  10. * A specialized map implementation for use with enum type keys.
  11. *
  12. * All of the keys in an enum map must come from a single enum type that is specified, when the map is created. Enum
  13. * maps are represented internally as arrays. This representation is extremely compact and efficient.
  14. *
  15. * Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared).
  16. * This is reflected in the iterators returned by the collection views {@see self::getIterator()} and
  17. * {@see self::values()}.
  18. *
  19. * Iterators returned by the collection views are not consistent: They may or may not show the effects of modifications
  20. * to the map that occur while the iteration is in progress.
  21. */
  22. final class EnumMap implements Serializable, IteratorAggregate
  23. {
  24. /**
  25. * The class name of the key.
  26. *
  27. * @var string
  28. */
  29. private $keyType;
  30. /**
  31. * The type of the value.
  32. *
  33. * @var string
  34. */
  35. private $valueType;
  36. /**
  37. * @var bool
  38. */
  39. private $allowNullValues;
  40. /**
  41. * All of the constants comprising the enum, cached for performance.
  42. *
  43. * @var array<int, AbstractEnum>
  44. */
  45. private $keyUniverse;
  46. /**
  47. * Array representation of this map. The ith element is the value to which universe[i] is currently mapped, or null
  48. * if it isn't mapped to anything, or NullValue if it's mapped to null.
  49. *
  50. * @var array<int, mixed>
  51. */
  52. private $values;
  53. /**
  54. * @var int
  55. */
  56. private $size = 0;
  57. /**
  58. * Creates a new enum map.
  59. *
  60. * @param string $keyType the type of the keys, must extend AbstractEnum
  61. * @param string $valueType the type of the values
  62. * @param bool $allowNullValues whether to allow null values
  63. * @throws IllegalArgumentException when key type does not extend AbstractEnum
  64. */
  65. public function __construct(string $keyType, string $valueType, bool $allowNullValues)
  66. {
  67. if (! is_subclass_of($keyType, AbstractEnum::class)) {
  68. throw new IllegalArgumentException(sprintf(
  69. 'Class %s does not extend %s',
  70. $keyType,
  71. AbstractEnum::class
  72. ));
  73. }
  74. $this->keyType = $keyType;
  75. $this->valueType = $valueType;
  76. $this->allowNullValues = $allowNullValues;
  77. $this->keyUniverse = $keyType::values();
  78. $this->values = array_fill(0, count($this->keyUniverse), null);
  79. }
  80. public function __serialize(): array
  81. {
  82. $values = [];
  83. foreach ($this->values as $ordinal => $value) {
  84. if (null === $value) {
  85. continue;
  86. }
  87. $values[$ordinal] = $this->unmaskNull($value);
  88. }
  89. return [
  90. 'keyType' => $this->keyType,
  91. 'valueType' => $this->valueType,
  92. 'allowNullValues' => $this->allowNullValues,
  93. 'values' => $values,
  94. ];
  95. }
  96. public function __unserialize(array $data): void
  97. {
  98. $this->unserialize(serialize($data));
  99. }
  100. /**
  101. * Checks whether the map types match the supplied ones.
  102. *
  103. * You should call this method when an EnumMap is passed to you and you want to ensure that it's made up of the
  104. * correct types.
  105. *
  106. * @throws ExpectationException when supplied key type mismatches local key type
  107. * @throws ExpectationException when supplied value type mismatches local value type
  108. * @throws ExpectationException when the supplied map allows null values, abut should not
  109. */
  110. public function expect(string $keyType, string $valueType, bool $allowNullValues) : void
  111. {
  112. if ($keyType !== $this->keyType) {
  113. throw new ExpectationException(sprintf(
  114. 'Callee expected an EnumMap with key type %s, but got %s',
  115. $keyType,
  116. $this->keyType
  117. ));
  118. }
  119. if ($valueType !== $this->valueType) {
  120. throw new ExpectationException(sprintf(
  121. 'Callee expected an EnumMap with value type %s, but got %s',
  122. $keyType,
  123. $this->keyType
  124. ));
  125. }
  126. if ($allowNullValues !== $this->allowNullValues) {
  127. throw new ExpectationException(sprintf(
  128. 'Callee expected an EnumMap with nullable flag %s, but got %s',
  129. ($allowNullValues ? 'true' : 'false'),
  130. ($this->allowNullValues ? 'true' : 'false')
  131. ));
  132. }
  133. }
  134. /**
  135. * Returns the number of key-value mappings in this map.
  136. */
  137. public function size() : int
  138. {
  139. return $this->size;
  140. }
  141. /**
  142. * Returns true if this map maps one or more keys to the specified value.
  143. */
  144. public function containsValue($value) : bool
  145. {
  146. return in_array($this->maskNull($value), $this->values, true);
  147. }
  148. /**
  149. * Returns true if this map contains a mapping for the specified key.
  150. */
  151. public function containsKey(AbstractEnum $key) : bool
  152. {
  153. $this->checkKeyType($key);
  154. return null !== $this->values[$key->ordinal()];
  155. }
  156. /**
  157. * Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  158. *
  159. * More formally, if this map contains a mapping from a key to a value, then this method returns the value;
  160. * otherwise it returns null (there can be at most one such mapping).
  161. *
  162. * A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also
  163. * possible that hte map explicitly maps the key to null. The {@see self::containsKey()} operation may be used to
  164. * distinguish these two cases.
  165. *
  166. * @return mixed
  167. */
  168. public function get(AbstractEnum $key)
  169. {
  170. $this->checkKeyType($key);
  171. return $this->unmaskNull($this->values[$key->ordinal()]);
  172. }
  173. /**
  174. * Associates the specified value with the specified key in this map.
  175. *
  176. * If the map previously contained a mapping for this key, the old value is replaced.
  177. *
  178. * @return mixed the previous value associated with the specified key, or null if there was no mapping for the key.
  179. * (a null return can also indicate that the map previously associated null with the specified key.)
  180. * @throws IllegalArgumentException when the passed values does not match the internal value type
  181. */
  182. public function put(AbstractEnum $key, $value)
  183. {
  184. $this->checkKeyType($key);
  185. if (! $this->isValidValue($value)) {
  186. throw new IllegalArgumentException(sprintf('Value is not of type %s', $this->valueType));
  187. }
  188. $index = $key->ordinal();
  189. $oldValue = $this->values[$index];
  190. $this->values[$index] = $this->maskNull($value);
  191. if (null === $oldValue) {
  192. ++$this->size;
  193. }
  194. return $this->unmaskNull($oldValue);
  195. }
  196. /**
  197. * Removes the mapping for this key frm this map if present.
  198. *
  199. * @return mixed the previous value associated with the specified key, or null if there was no mapping for the key.
  200. * (a null return can also indicate that the map previously associated null with the specified key.)
  201. */
  202. public function remove(AbstractEnum $key)
  203. {
  204. $this->checkKeyType($key);
  205. $index = $key->ordinal();
  206. $oldValue = $this->values[$index];
  207. $this->values[$index] = null;
  208. if (null !== $oldValue) {
  209. --$this->size;
  210. }
  211. return $this->unmaskNull($oldValue);
  212. }
  213. /**
  214. * Removes all mappings from this map.
  215. */
  216. public function clear() : void
  217. {
  218. $this->values = array_fill(0, count($this->keyUniverse), null);
  219. $this->size = 0;
  220. }
  221. /**
  222. * Compares the specified map with this map for quality.
  223. *
  224. * Returns true if the two maps represent the same mappings.
  225. */
  226. public function equals(self $other) : bool
  227. {
  228. if ($this === $other) {
  229. return true;
  230. }
  231. if ($this->size !== $other->size) {
  232. return false;
  233. }
  234. return $this->values === $other->values;
  235. }
  236. /**
  237. * Returns the values contained in this map.
  238. *
  239. * The array will contain the values in the order their corresponding keys appear in the map, which is their natural
  240. * order (the order in which the num constants are declared).
  241. */
  242. public function values() : array
  243. {
  244. return array_values(array_map(function ($value) {
  245. return $this->unmaskNull($value);
  246. }, array_filter($this->values, function ($value) : bool {
  247. return null !== $value;
  248. })));
  249. }
  250. public function serialize() : string
  251. {
  252. return serialize($this->__serialize());
  253. }
  254. public function unserialize($serialized) : void
  255. {
  256. $data = unserialize($serialized);
  257. $this->__construct($data['keyType'], $data['valueType'], $data['allowNullValues']);
  258. foreach ($this->keyUniverse as $key) {
  259. if (array_key_exists($key->ordinal(), $data['values'])) {
  260. $this->put($key, $data['values'][$key->ordinal()]);
  261. }
  262. }
  263. }
  264. public function getIterator() : Traversable
  265. {
  266. foreach ($this->keyUniverse as $key) {
  267. if (null === $this->values[$key->ordinal()]) {
  268. continue;
  269. }
  270. yield $key => $this->unmaskNull($this->values[$key->ordinal()]);
  271. }
  272. }
  273. private function maskNull($value)
  274. {
  275. if (null === $value) {
  276. return NullValue::instance();
  277. }
  278. return $value;
  279. }
  280. private function unmaskNull($value)
  281. {
  282. if ($value instanceof NullValue) {
  283. return null;
  284. }
  285. return $value;
  286. }
  287. /**
  288. * @throws IllegalArgumentException when the passed key does not match the internal key type
  289. */
  290. private function checkKeyType(AbstractEnum $key) : void
  291. {
  292. if (get_class($key) !== $this->keyType) {
  293. throw new IllegalArgumentException(sprintf(
  294. 'Object of type %s is not the same type as %s',
  295. get_class($key),
  296. $this->keyType
  297. ));
  298. }
  299. }
  300. private function isValidValue($value) : bool
  301. {
  302. if (null === $value) {
  303. if ($this->allowNullValues) {
  304. return true;
  305. }
  306. return false;
  307. }
  308. switch ($this->valueType) {
  309. case 'mixed':
  310. return true;
  311. case 'bool':
  312. case 'boolean':
  313. return is_bool($value);
  314. case 'int':
  315. case 'integer':
  316. return is_int($value);
  317. case 'float':
  318. case 'double':
  319. return is_float($value);
  320. case 'string':
  321. return is_string($value);
  322. case 'object':
  323. return is_object($value);
  324. case 'array':
  325. return is_array($value);
  326. }
  327. return $value instanceof $this->valueType;
  328. }
  329. }