Created
June 24, 2022 09:39
-
-
Save Jamiewarb/379c181427322f7a556845ebde56752e to your computer and use it in GitHub Desktop.
Abstract Constant for PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Constants; | |
use ReflectionClass; | |
abstract class AbstractConstant | |
{ | |
/** | |
* Get a constant value by name | |
* | |
* @param string $name The name of the constant | |
* @throws \InvalidArgumentException | |
* @return mixed The value of the constant | |
*/ | |
public static function getByName(string $name): mixed | |
{ | |
$constants = self::getConstants(); | |
if (!isset($constants[$name])) { | |
throw new \InvalidArgumentException( | |
'Wrong ' . self::getReflection()->getShortName() . ' name: ' . $name | |
); | |
} | |
return $constants[$name]; | |
} | |
/** | |
* Get a constant name by value | |
* | |
* @param mixed $value | |
* @throws \InvalidArgumentException | |
* @return int|string | |
*/ | |
public static function getByValue(mixed $value): int|string | |
{ | |
$constants = self::getConstants(); | |
foreach ($constants as $constantName => $constantValue) { | |
if ($constantValue === $value) { | |
return $constantName; | |
} | |
} | |
throw new \InvalidArgumentException( | |
'Wrong ' . self::getReflection()->getShortName() . ' value: ' . $value | |
); | |
} | |
/** | |
* Get an array of all constants defined and their values | |
* | |
* @return array | |
*/ | |
public static function getConstants(): array | |
{ | |
return self::getReflection()->getConstants(); | |
} | |
/** | |
* Get an array of all constant names | |
* | |
* @return array | |
*/ | |
public static function getConstantNames(): array | |
{ | |
return array_keys(self::getConstants()); | |
} | |
/** | |
* Get an array of all constant values | |
* | |
* @return array | |
*/ | |
public static function getConstantValues(): array | |
{ | |
return array_values(self::getConstants()); | |
} | |
/** | |
* | |
* @return ReflectionClass | |
*/ | |
protected static function getReflection(): ReflectionClass | |
{ | |
return new ReflectionClass(get_called_class()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Constants; | |
class AppEnvironment extends AbstractConstant | |
{ | |
const PRODUCTION = 'production'; | |
const STAGING = 'staging'; | |
const LOCAL = 'local'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment