Skip to content

Version 2.0 #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 18 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,6 @@ class Action extends Enum
## Usage

```php
$action = new Action(Action::VIEW);

// or
$action = Action::VIEW();
```

Expand All @@ -58,9 +55,22 @@ function setAction(Action $action) {
}
```

Each Enum instance for a given key is a singleton, so you can use:

```php
function setAction(Action $action) {
if ($action === Action::VIEW()) {
//
}
}
```

**Note** that this is not true, if you `unserialize()` Enums.
In case another Enum instance already exists,
an `E_USER_NOTICE` is triggered.

## Documentation

- `__construct()` The constructor checks that the value exist in the enum
- `__toString()` You can `echo $myValue`, it will display the enum value (value of the constant)
- `getValue()` Returns the current value of the enum
- `getKey()` Returns the key of the current value on Enum
Expand All @@ -74,6 +84,8 @@ Static methods:
- `isValid()` Check if tested value is valid on enum set
- `isValidKey()` Check if tested key is valid on enum set
- `search()` Return key for searched value
- `fromKey()` Return Enum instance for the given key
- `fromValue()` Return Enum instance for the given value

### Static methods

Expand All @@ -91,23 +103,8 @@ $action = Action::EDIT();

Static method helpers are implemented using [`__callStatic()`](http://www.php.net/manual/en/language.oop5.overloading.php#object.callstatic).

If you care about IDE autocompletion, you can either implement the static methods yourself:

```php
class Action extends Enum
{
const VIEW = 'view';

/**
* @return Action
*/
public static function VIEW() {
return new Action(self::VIEW);
}
}
```

or you can use phpdoc (this is supported in PhpStorm for example):
If you care about IDE autocompletion,
you can use phpdoc (this is supported in PhpStorm for example):

```php
/**
Expand Down
92 changes: 57 additions & 35 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

namespace MyCLabs\Enum;

use BadMethodCallException;

/**
* Base Enum class
*
Expand All @@ -18,32 +20,27 @@
abstract class Enum
{
/**
* Enum value
* Enum name
*
* @var mixed
* @var string
*/
protected $value;
private $name;

/**
* Store existing constants in a static cache per object.
* Enum value
*
* @var array
* @var mixed
*/
protected static $cache = array();
private $value;

/**
* Creates a new value of some type
*
* @param mixed $value
*
* @throws \UnexpectedValueException if incompatible type is given.
*/
public function __construct($value)
final private function __construct($name, $value)
{
if (!$this->isValid($value)) {
throw new \UnexpectedValueException("Value '$value' is not part of the enum " . get_called_class());
}

$this->name = $name;
$this->value = $value;
}

Expand All @@ -62,7 +59,7 @@ public function getValue()
*/
public function getKey()
{
return static::search($this->value);
return $this->name;
}

/**
Expand All @@ -74,15 +71,14 @@ public function __toString()
}

/**
* Compares one Enum with another.
*
* This method is final, for more information read https://github.com/myclabs/php-enum/issues/4
*
* @return bool True if Enums are equal, false if not equal
* Register object in cache and trigger a notice if it already exists.
*/
final public function equals(Enum $enum)
public function __wakeup()
{
return $this->getValue() === $enum->getValue() && get_called_class() == get_class($enum);
$enum = EnumManager::get($this);
if ($enum !== $this) {
trigger_error("Enum is already initialized", E_USER_NOTICE);
}
}

/**
Expand All @@ -104,8 +100,8 @@ public static function values()
{
$values = array();

foreach (static::toArray() as $key => $value) {
$values[$key] = new static($value);
foreach (static::toArray() as $name => $value) {
$values[$name] = EnumManager::get(new static($name, $value));
}

return $values;
Expand All @@ -118,13 +114,7 @@ public static function values()
*/
public static function toArray()
{
$class = get_called_class();
if (!array_key_exists($class, static::$cache)) {
$reflection = new \ReflectionClass($class);
static::$cache[$class] = $reflection->getConstants();
}

return static::$cache[$class];
return EnumManager::constants(new static(null, null));
}

/**
Expand Down Expand Up @@ -165,22 +155,54 @@ public static function search($value)
return array_search($value, static::toArray(), true);
}

/**
* Returns Enum by value
*
* @return static
*/
public static function fromValue($value)
{
$name = static::search($value);
if ($name === false) {
return null;
}

return EnumManager::get(new static($name, $value));
}

/**
* Returns Enum by key
*
* @return static
*/
public static function fromKey($name)
{
$array = static::toArray();
if (isset($array[$name]) || array_key_exists($name, $array)) {
return EnumManager::get(new static($name, $array[$name]));
}

return null;
}

/**
* Returns a value when called statically like so: MyEnum::SOME_VALUE() given SOME_VALUE is a class constant
*
* @param string $name
* @param array $arguments
*
* @return static
* @throws \BadMethodCallException
* @throws BadMethodCallException
*/
public static function __callStatic($name, $arguments)
{
$array = static::toArray();
if (isset($array[$name])) {
return new static($array[$name]);
$result = static::fromKey($name);

if ($result === null) {
$msg = "No static method or enum constant '$name' in class " . get_called_class();
throw new BadMethodCallException($msg);
}

throw new \BadMethodCallException("No static method or enum constant '$name' in class " . get_called_class());
return $result;
}
}
55 changes: 55 additions & 0 deletions src/EnumManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not seeing test for this new functionality

/**
* @link http://github.com/myclabs/php-enum
* @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
*/

namespace MyCLabs\Enum;

use ReflectionObject;

/**
* Enum instance manager
*
* @internal
*/
abstract class EnumManager
Copy link

@chippyash chippyash Jan 30, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't this be better called Enum\Factory

Actually, I see more clearly what it is doing. Enum\Store would be a better name

{
/**
* Store existing Enum instances.
*
* @var array
*/
private static $instances = array();

/**
* Returns the Enum instance for the given prototype
*
* @return Enum
*/
public static function get(Enum $enum)
{
$reflection = new ReflectionObject($enum);
$class = $reflection->getName();
$name = $enum->getKey();

if (isset(self::$instances[$class][$name])) {
return self::$instances[$class][$name];
}

self::$instances[$class][$name] = $enum;
return $enum;
}

/**
* Returns all possible values as an array
*
* @return array Constant name in key, constant value in value
*/
public static function constants(Enum $enum)
{
$reflection = new ReflectionObject($enum);
$result = $reflection->getConstants();
return $result;
}
}
Loading