EnumMap.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. /**
  81. * Checks whether the map types match the supplied ones.
  82. *
  83. * You should call this method when an EnumMap is passed to you and you want to ensure that it's made up of the
  84. * correct types.
  85. *
  86. * @throws ExpectationException when supplied key type mismatches local key type
  87. * @throws ExpectationException when supplied value type mismatches local value type
  88. * @throws ExpectationException when the supplied map allows null values, abut should not
  89. */
  90. public function expect(string $keyType, string $valueType, bool $allowNullValues) : void
  91. {
  92. if ($keyType !== $this->keyType) {
  93. throw new ExpectationException(sprintf(
  94. 'Callee expected an EnumMap with key type %s, but got %s',
  95. $keyType,
  96. $this->keyType
  97. ));
  98. }
  99. if ($valueType !== $this->valueType) {
  100. throw new ExpectationException(sprintf(
  101. 'Callee expected an EnumMap with value type %s, but got %s',
  102. $keyType,
  103. $this->keyType
  104. ));
  105. }
  106. if ($allowNullValues !== $this->allowNullValues) {
  107. throw new ExpectationException(sprintf(
  108. 'Callee expected an EnumMap with nullable flag %s, but got %s',
  109. ($allowNullValues ? 'true' : 'false'),
  110. ($this->allowNullValues ? 'true' : 'false')
  111. ));
  112. }
  113. }
  114. /**
  115. * Returns the number of key-value mappings in this map.
  116. */
  117. public function size() : int
  118. {
  119. return $this->size;
  120. }
  121. /**
  122. * Returns true if this map maps one or more keys to the specified value.
  123. */
  124. public function containsValue($value) : bool
  125. {
  126. return in_array($this->maskNull($value), $this->values, true);
  127. }
  128. /**
  129. * Returns true if this map contains a mapping for the specified key.
  130. */
  131. public function containsKey(AbstractEnum $key) : bool
  132. {
  133. $this->checkKeyType($key);
  134. return null !== $this->values[$key->ordinal()];
  135. }
  136. /**
  137. * Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  138. *
  139. * More formally, if this map contains a mapping from a key to a value, then this method returns the value;
  140. * otherwise it returns null (there can be at most one such mapping).
  141. *
  142. * A return value of null does not necessarily indicate that the map contains no mapping for the key; it's also
  143. * possible that hte map explicitly maps the key to null. The {@see self::containsKey()} operation may be used to
  144. * distinguish these two cases.
  145. *
  146. * @return mixed
  147. */
  148. public function get(AbstractEnum $key)
  149. {
  150. $this->checkKeyType($key);
  151. return $this->unmaskNull($this->values[$key->ordinal()]);
  152. }
  153. /**
  154. * Associates the specified value with the specified key in this map.
  155. *
  156. * If the map previously contained a mapping for this key, the old value is replaced.
  157. *
  158. * @return mixed the previous value associated with the specified key, or null if there was no mapping for the key.
  159. * (a null return can also indicate that the map previously associated null with the specified key.)
  160. * @throws IllegalArgumentException when the passed values does not match the internal value type
  161. */
  162. public function put(AbstractEnum $key, $value)
  163. {
  164. $this->checkKeyType($key);
  165. if (! $this->isValidValue($value)) {
  166. throw new IllegalArgumentException(sprintf('Value is not of type %s', $this->valueType));
  167. }
  168. $index = $key->ordinal();
  169. $oldValue = $this->values[$index];
  170. $this->values[$index] = $this->maskNull($value);
  171. if (null === $oldValue) {
  172. ++$this->size;
  173. }
  174. return $this->unmaskNull($oldValue);
  175. }
  176. /**
  177. * Removes the mapping for this key frm this map if present.
  178. *
  179. * @return mixed the previous value associated with the specified key, or null if there was no mapping for the key.
  180. * (a null return can also indicate that the map previously associated null with the specified key.)
  181. */
  182. public function remove(AbstractEnum $key)
  183. {
  184. $this->checkKeyType($key);
  185. $index = $key->ordinal();
  186. $oldValue = $this->values[$index];
  187. $this->values[$index] = null;
  188. if (null !== $oldValue) {
  189. --$this->size;
  190. }
  191. return $this->unmaskNull($oldValue);
  192. }
  193. /**
  194. * Removes all mappings from this map.
  195. */
  196. public function clear() : void
  197. {
  198. $this->values = array_fill(0, count($this->keyUniverse), null);
  199. $this->size = 0;
  200. }
  201. /**
  202. * Compares the specified map with this map for quality.
  203. *
  204. * Returns true if the two maps represent the same mappings.
  205. */
  206. public function equals(self $other) : bool
  207. {
  208. if ($this === $other) {
  209. return true;
  210. }
  211. if ($this->size !== $other->size) {
  212. return false;
  213. }
  214. return $this->values === $other->values;
  215. }
  216. /**
  217. * Returns the values contained in this map.
  218. *
  219. * The array will contain the values in the order their corresponding keys appear in the map, which is their natural
  220. * order (the order in which the num constants are declared).
  221. */
  222. public function values() : array
  223. {
  224. return array_values(array_map(function ($value) {
  225. return $this->unmaskNull($value);
  226. }, array_filter($this->values, function ($value) : bool {
  227. return null !== $value;
  228. })));
  229. }
  230. public function serialize() : string
  231. {
  232. $values = [];
  233. foreach ($this->values as $ordinal => $value) {
  234. if (null === $value) {
  235. continue;
  236. }
  237. $values[$ordinal] = $this->unmaskNull($value);
  238. }
  239. return serialize([
  240. 'keyType' => $this->keyType,
  241. 'valueType' => $this->valueType,
  242. 'allowNullValues' => $this->allowNullValues,
  243. 'values' => $values,
  244. ]);
  245. }
  246. public function unserialize($serialized) : void
  247. {
  248. $data = unserialize($serialized);
  249. $this->__construct($data['keyType'], $data['valueType'], $data['allowNullValues']);
  250. foreach ($this->keyUniverse as $key) {
  251. if (array_key_exists($key->ordinal(), $data['values'])) {
  252. $this->put($key, $data['values'][$key->ordinal()]);
  253. }
  254. }
  255. }
  256. public function getIterator() : Traversable
  257. {
  258. foreach ($this->keyUniverse as $key) {
  259. if (null === $this->values[$key->ordinal()]) {
  260. continue;
  261. }
  262. yield $key => $this->unmaskNull($this->values[$key->ordinal()]);
  263. }
  264. }
  265. private function maskNull($value)
  266. {
  267. if (null === $value) {
  268. return NullValue::instance();
  269. }
  270. return $value;
  271. }
  272. private function unmaskNull($value)
  273. {
  274. if ($value instanceof NullValue) {
  275. return null;
  276. }
  277. return $value;
  278. }
  279. /**
  280. * @throws IllegalArgumentException when the passed key does not match the internal key type
  281. */
  282. private function checkKeyType(AbstractEnum $key) : void
  283. {
  284. if (get_class($key) !== $this->keyType) {
  285. throw new IllegalArgumentException(sprintf(
  286. 'Object of type %s is not the same type as %s',
  287. get_class($key),
  288. $this->keyType
  289. ));
  290. }
  291. }
  292. private function isValidValue($value) : bool
  293. {
  294. if (null === $value) {
  295. if ($this->allowNullValues) {
  296. return true;
  297. }
  298. return false;
  299. }
  300. switch ($this->valueType) {
  301. case 'mixed':
  302. return true;
  303. case 'bool':
  304. case 'boolean':
  305. return is_bool($value);
  306. case 'int':
  307. case 'integer':
  308. return is_int($value);
  309. case 'float':
  310. case 'double':
  311. return is_float($value);
  312. case 'string':
  313. return is_string($value);
  314. case 'object':
  315. return is_object($value);
  316. case 'array':
  317. return is_array($value);
  318. }
  319. return $value instanceof $this->valueType;
  320. }
  321. }