Subversion Repositories oidplus

Rev

Go to most recent revision | Blame | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. namespace phpseclib3\Common;
  4.  
  5. /**
  6.  * @internal
  7.  */
  8. trait ConstantUtilityTrait
  9. {
  10.     /** @var string[]|null */
  11.     private static $valueToConstantNameMap = null;
  12.  
  13.     /**
  14.      * @param string|int $value
  15.      * @return string|null
  16.      */
  17.     public static function findConstantNameByValue($value)
  18.     {
  19.         if (!self::$valueToConstantNameMap) {
  20.             $reflectionClass = new \ReflectionClass(static::class);
  21.             $constantNameToValueMap = $reflectionClass->getConstants();
  22.             self::$valueToConstantNameMap = array_flip($constantNameToValueMap);
  23.         }
  24.         if (isset(self::$valueToConstantNameMap[$value])) {
  25.             return self::$valueToConstantNameMap[$value];
  26.         }
  27.         return null;
  28.     }
  29.  
  30.     /**
  31.      * @param string|int $value
  32.      * @return string
  33.      */
  34.     public static function getConstantNameByValue($value)
  35.     {
  36.         $constantName = static::findConstantNameByValue($value);
  37.         if ($constantName === null) {
  38.             throw new \InvalidArgumentException(sprintf('"%s" does not have constant with value "%s".', static::class, $value));
  39.         }
  40.         return $constantName;
  41.     }
  42. }
  43.