Skip to content

Instantly share code, notes, and snippets.

@Jamiewarb
Created June 24, 2022 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jamiewarb/379c181427322f7a556845ebde56752e to your computer and use it in GitHub Desktop.
Save Jamiewarb/379c181427322f7a556845ebde56752e to your computer and use it in GitHub Desktop.
Abstract Constant for PHP
<?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());
}
}
<?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