AbstractEnum.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * This file is part of PHPWord - A pure PHP library for reading and writing
  4. * word processing documents.
  5. *
  6. * PHPWord is free software distributed under the terms of the GNU Lesser
  7. * General Public License version 3 as published by the Free Software Foundation.
  8. *
  9. * For the full copyright and license information, please read the LICENSE
  10. * file that was distributed with this source code. For the full list of
  11. * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
  12. *
  13. * @see https://github.com/PHPOffice/PHPWord
  14. * @copyright 2010-2018 PHPWord contributors
  15. * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
  16. */
  17. namespace PhpOffice\PhpWord\Shared;
  18. abstract class AbstractEnum
  19. {
  20. private static $constCacheArray = null;
  21. private static function getConstants()
  22. {
  23. if (self::$constCacheArray == null) {
  24. self::$constCacheArray = array();
  25. }
  26. $calledClass = get_called_class();
  27. if (!array_key_exists($calledClass, self::$constCacheArray)) {
  28. $reflect = new \ReflectionClass($calledClass);
  29. self::$constCacheArray[$calledClass] = $reflect->getConstants();
  30. }
  31. return self::$constCacheArray[$calledClass];
  32. }
  33. /**
  34. * Returns all values for this enum
  35. *
  36. * @return array
  37. */
  38. public static function values()
  39. {
  40. return array_values(self::getConstants());
  41. }
  42. /**
  43. * Returns true the value is valid for this enum
  44. *
  45. * @param string $value
  46. * @return bool true if value is valid
  47. */
  48. public static function isValid($value)
  49. {
  50. $values = array_values(self::getConstants());
  51. return in_array($value, $values, true);
  52. }
  53. /**
  54. * Validates that the value passed is a valid value
  55. *
  56. * @param string $value
  57. * @throws \InvalidArgumentException if the value passed is not valid for this enum
  58. */
  59. public static function validate($value)
  60. {
  61. if (!self::isValid($value)) {
  62. $calledClass = get_called_class();
  63. $values = array_values(self::getConstants());
  64. throw new \InvalidArgumentException("$value is not a valid value for $calledClass, possible values are " . implode(', ', $values));
  65. }
  66. }
  67. }