Skip to content

Instantly share code, notes, and snippets.

@ThePooN
Forked from celianvdb/Enum.class.php
Created July 8, 2016 23:15
Show Gist options
  • Save ThePooN/0936613dd40bdee999046290c631ff8b to your computer and use it in GitHub Desktop.
Save ThePooN/0936613dd40bdee999046290c631ff8b to your computer and use it in GitHub Desktop.
Simple Enum class
<?php
class Enum
{
private $enumsList = array();
private $reverseList = array();
public function __construct(array $enums)
{
$this->addEnums($enums);
}
public function reverse($value)
{
unset($this->reverseList);
$this->reverseList = array();
if($value != 0){
while($value > 0)
{
$lastNearestLowerEntry = $this->nearestLowerEntry($value);
$this->reverseList[] = $lastNearestLowerEntry['name'];
$value -= $lastNearestLowerEntry['value'];
}
return $this->reverseList;
}
else
{
return null;
}
}
private function nearestLowerEntry($value)
{
$lastEntry = $this->enumsList[0];
foreach($this->enumsList as $key=>$data)
{
if($data['value'] > $value && $lastEntry['value'] < $value)
{
return $lastEntry;
}
else if($value > $data['value'] && !isset($this->enumsList[$key + 1]) OR $data['value'] == $value)
{
return $data;
}
$lastEntry = $data;
}
}
private function addEnums(array $enums)
{
$biggestPowOf2Value = -1;
foreach($enums as $data)
{
$this->enumsList[] = array(
'name' => $data,
'value' => pow(2, $biggestPowOf2Value + 1),
);
$biggestPowOf2Value ++;
}
}
private function getPowOf2($entry)
{
if(is_int($entry)){
$number = 0;
$powOf2 = -1;
while($number < $entry)
{
$powOf2 ++;
$number = pow(2, $powOf2);
}
return $powOf2;
}
}
}
<?php
require_once('Enum.class.php');
// example with a colors of object
$characteristics = new Enum(array('blue', 'red', 'green'));
// Value of blue = 2^0 = 1
// Value of red = 2^1 = 2
// Value of green = 2^2 = 4
// If my object is blue and red his value is 3
$characteristicsOfMyObject = $characteristics->reverse(3); // return array
echo 'Colors of a object with a value equal to 3 : ';
foreach($characteristicsOfMyObject as $data) // writte red, blue
{
echo '<br/>- '.$data;
}
// If my object is blue and red his value is 7
$characteristicsOfMyObject = $characteristics->reverse(7); // return array
echo '<br/> <br/>Colors of a object with a value equal to 7 : ';
foreach($characteristicsOfMyObject as $data) // writte green, red, blue
{
echo '<br/>- '.$data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment