Skip to content

Instantly share code, notes, and snippets.

@dahse89
Created March 14, 2017 12:58
Show Gist options
  • Save dahse89/a6f7d038949ee71beaa22a73d1bc6bba to your computer and use it in GitHub Desktop.
Save dahse89/a6f7d038949ee71beaa22a73d1bc6bba to your computer and use it in GitHub Desktop.
<?php
/**
* Trait EnumTrait
* @author Philipp Dahse <ph.dahse@gmail.com>
*/
trait EnumTrait
{
/**
* @return array
*/
public static function toArray()
{
return (new \ReflectionClass(self::class))->getConstants();
}
/**
* @param $const
*
* @return null|mixed
*/
public static function get($const)
{
return defined($constant = self::class . "::$const") ? constant($constant) : null;
}
/**
* @param $const
* @return bool
*/
public static function has($const)
{
return self::get($const) !== null;
}
/**
* Get enum as fliped array
* @notice maybe you will lose entries if values are not unique
*/
public static function reverseArray()
{
return array_flip(self::toArray()));
}
/**
* Find key by value
*
* @notice not consistent for ambiguous values
* @param $value
*
* @return null
*/
public static function reverseLookup($value)
{
return array_key_exists($value,$reverse = self::reverseArray()) ? $reverse[$value] : null;
}
}
// EXAMPLE USAGE
/**
* Class BillingStateEnum
*/
abstract class BillingStateEnum
{
use EnumTrait;
const BILLED = 'billed';
const CANCELED = 'canceled';
const FAILED = 'failed';
const PAID = 'paid';
}
BillingStateEnum::toArray(); // ['BILLED' => 'billed', 'CANCELED' => 'canceled', 'FAILED' => 'failed', 'PAID' => 'paid']
BillingStateEnum::get('BILLED'); // billed
BillingStateEnum::has('TEST'); // false
BillingStateEnum::reverseArray(); // ['billed' => 'BILLED', 'canceled' => 'CANCELED', 'failed' => 'FAILED', 'paid' => 'PAID']
BillingStateEnum::reverseLookup('failed'); //FAILED
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment