Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
da26127
Change identifier to name
jodiedunlop Sep 14, 2018
6745120
Change static method valueFor() to valueForKey()
jodiedunlop Sep 14, 2018
df27a89
Add static method nameForKey()
jodiedunlop Sep 14, 2018
6400bb8
Change exists() and checkExists() to isValidKey() and requireValidKey…
jodiedunlop Sep 14, 2018
ce9166e
Improve keyForName()
jodiedunlop Sep 14, 2018
078f0a7
Fix error in key() when the key is not a string (eg. int)
jodiedunlop Sep 14, 2018
1f024a9
Fix is() instance method to handle non-string keys
jodiedunlop Sep 14, 2018
ad4f245
Fix late-static binding: change self references
jodiedunlop Sep 18, 2018
d159b97
Add Enum::instanceFromName() method
jodiedunlop Sep 19, 2018
10162b7
Change implementation of instanceFromKey() to use array_search
jodiedunlop Sep 19, 2018
c865499
Rename some internal variables
jodiedunlop Sep 19, 2018
434d78b
Removed flip() and renamed fromValue() to keyForValue()
jodiedunlop Sep 19, 2018
b1e9572
Change nameForKey implementation and throw on duplicate keys
jodiedunlop Sep 19, 2018
257ab25
Add uncommitted duplicate key classes
jodiedunlop Sep 19, 2018
549f8d3
Rename Enum::constantMap() method to namesAndKeys()
jodiedunlop Sep 21, 2018
f1e6c52
Update README to document API changes
jodiedunlop Sep 21, 2018
2031ec1
Add Enum::valueForName() method
jodiedunlop Sep 23, 2018
c616f17
Rename Bevs stub to Beverages
jodiedunlop Sep 23, 2018
903e409
Fix isValidName() to handle null keys
jodiedunlop Sep 23, 2018
32e71ee
Update CHANGELOG for 2.0.0 release
jodiedunlop Sep 23, 2018
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
22 changes: 22 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,30 @@
# [Unreleased]

- Add Enum::instanceFromKey($key)
- **Breaking** Change `$instance->identifier` to `$instance->name()`
- **Breaking** Change `Enum::identifiers()` to `Enum::names()`
- **Breaking** Change `Enum::getKeyForIdentfier()` to `Enum::keyForName()`
- **Breaking** Change `Enum::valueFor()` to `Enum::valueForKey()`
Copy link
Contributor

Choose a reason for hiding this comment

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

Enum::valueForName() for completeness?

- Add `Enum::nameForKey()` to get the constant name for a given key
- **Breaking** Change `Enum::exists()` to `Enum::isValidKey()`
- **Breaking** Change `Enum::checkExists()` to `Enum::requireValidKey()`
- Fix `$instance->key()` to handle non-string keys
- Fix `$instance->is()` to handle non-string keys
- Fix late-static binding in some methods which referred to `self::`
- Add `Enum::instanceFromName($name)` to get an instance via name (alternative to Enum::NAME())
- Change implementation of `Enum::instanceFromKey($key)` to use array_search
- **Breaking** Change: the default provided static `map()` method will return an array of constant keys mapped to `null`.
Previously it returned an empty array `[]` when not overridden. In practice, this may not effect userland code.
- **Breaking** Change: you can no longer provide a non-keyed array in an `map()` method implemented
in your sub-class. This method should be used to map keys to values (if necessary). A default map() method is provided
which maps keys to `null` values.
- **Breaking** Change `Enum::fromValue($val)` has been renamed to `Enum::keyForValue()`
- **Breaking** Change: removed `Enum::flip()`
- **Breaking** Change `Enum::constantMap()` to `Enum::namesAndKeys()`
- Updated README to reflect API changes

# 1.1.0
- **Breaki

- Add flip() and fromValue()

Expand Down
172 changes: 81 additions & 91 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,72 +13,67 @@ This library provides an Enum / Enumeration implementation for PHP.
## Why use this library

* Very simple to implement and use.
* Flexible values can be assigned.
* Complex can optionally be mapped by providing a `map()` method.
* Allows type-hinting when passing enumerated values between methods and classes.

## Usage

### Extend the Enum class

Extending the `Enum` class is simple;
First create a new class that extends `\Rexlabs\Enum\Enum` and do the following;

1. Simply declare any constants
1. Declare your constants
2. *Optional*: provide a `map()` method:

## Example

```php
<?php
namespace MyProject\Enum;

use Rexlabs\Enum\Enum;

class Animal extends Enum
Copy link
Contributor

Choose a reason for hiding this comment

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

Changing from animals to cities is anthropocentric

Copy link
Contributor Author

Choose a reason for hiding this comment

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

TIL

class City extends \Rexlabs\Enum\Enum
{
// Declare any constants and their 'key'
const CAT = 'kitty';
const DOG = 'dog';
const HORSE = 'horse';
const PIGEON = 'skyrat';

// Optional: Provide a map() method to assign values to your keys.
// Your map method should return an array key => optional value
public static function map(): array
const BRISBANE = 'Brisbane';
const MELBOURNE = 'Melbourne';
const SYDNEY = 'Sydney';

// OPTIONAL - Provide a map() method if you would like to
// map additional data, which will be available from the ->value() method
public static function map(): array
{
return [
self::CAT => 'Kitty-cat',
self::DOG => null,
self::HORSE => null,
self::PIGEON => ['you','filthy','animal'],
static::BRISBANE => ["state"=>"QLD", "population"=>""],
static::MELBOURNE => ["state"=>"VIC", "population"=>"5m"],
static::SYDNEY => ["state"=>"NSW", "population"=>"5m"],
];
}

}
```

### Use your extended class

```php
<?php
use MyProject\Enum\Animal;

// Via class constant
echo Animal::CAT; // "kitty"

// Get an Animal instance for 'CAT'
$cat = Animal::CAT(); // (object)Animal
$cat->identifier(); // "CAT"
$cat->key(); // "kitty"
$cat->value(); // "Kitty-cat"
$cat->is(Animal::CAT); // (boolean)true
$cat->is(Animal::CAT()); // (boolean)true
$cat->is(Animal::PIGEON()); // (boolean)false

Animal::DOG()->value(); // (null) - No value was assigned in map()

Animal::PIGEON()->key(); // "skyrat"
Animal::PIGEON()->value(); // (array)['you', 'filthy', 'animal']

// Get a new Enum instance from a given key
$kitty = 'kitty';
$cat = Animal::instanceFromKey($kitty);
// Static access
echo City::BRISBANE; // "Brisbane"
echo City::MELBOURNE; // "Melbourne"
City::names(); // (array)["BRISBANE", "BRISBANE", "SYDNEY"]
City::keys(); // (array)["Brisbane", "Melbourne", "Sydney"]
City::keyForName('BRISBANE'); // "Brisbane"
City::nameForKey('Melbourne'); // "MELBOURNE"
City::isValidKey('Sydney'); // (boolean)true
City::isValidKey('Paris'); // (boolean)false

// Getting an instance - all return a City instance.
$city = City::BRISBANE();
$city = City::instanceFromName('BRISBANE');
$city = City::instanceFromKey('Brisbane');

// Working with an instance
$city->name(); // "BRISBANE"
$city->key(); // "Brisbane"
$city->value()['population']; // null - no value mapped
$city->is(City::BRISBANE); // (boolean)true
$city->is(City::BRISBANE()); // (boolean)true
$city->is(City::SYDNEY()); // (boolean)false

// Or ...
City::SYDNEY()->key(); // "Sydney"
City::SYDNEY()->value(); // (array)["state"=>"NSW", "population"=>"5m"]
```

## Dependencies
Expand All @@ -93,43 +88,31 @@ To install in your project:
composer require rexlabs/enum
```

## More Examples



### Type-hinting

Now you can type-hint your `Enum` object as a dependency:

```php
<?php
function sayHelloTo(Animal $animal) {
$name = $animal->value() ?? $animal->key();
if (is_array($name)) {
$name = implode(' ', $name);
}

echo "Greeting for {$animal->identifier()}: Hello $name\n";

function announceCity(City $city) {
echo "{$city->key()} is located in {$city->value()["state"]}, population: {$city->value()["population"]}\n";
}

// Get a new instance
sayHelloTo(Animal::CAT()); // "Greeting for CAT: Hello Kitty-cat"
sayHelloTo(Animal::DOG()); // "Greeting for DOG: Hello dog"
sayHelloTo(Animal::PIGEON()); // "Greeting for PIGEON: Hello you filthy animal"
announceCity(City::SYDNEY()); // "Sydney is located in NSW, population: 5m"
```


## Instance Methods

Each instance of `Enum` provides the following methods:

### identifier()
### name()

Returns the constant identifier.
Returns the constant name.

```php
$enum->identifier();
$enum->name();
```

### key()
Expand All @@ -151,31 +134,29 @@ $enum->value();

### is(Enum|string $compare)

Returns true if this instance is the same as the given constant string or enumeration instance.
Returns true if this instance is the same as the given constant key or enumeration instance.

```php
$enum->is(Animal::CAT); // Compare to constant key
$enum->is(Animal::CAT()); // Compare to instance
$enum->is(City::SYDNEY); // Compare to constant key
$enum->is(City::SYDNEY()); // Compare to instance
```

### __toString()

The `__toString()` method is defined to return the instance identifier (constant name).
The `__toString()` method is defined to return the constant name.

```php
(string)Animal::CAT(); // "CAT"
(string)City::SYDNEY(); // "SYDNEY"
```


## Static Methods

### map()

Returns an array which maps the constants, and any values. This method is implemented in a sub-class.

### flip()

If a map exists, this returns an array with a flipped mapping - value => constant
Returns an array which maps the constant keys to a value.
This method can be optionally implemented in a sub-class.
The default implementation returns an array of keys mapped to `null`.

### keys()

Expand All @@ -186,42 +167,51 @@ Returns an array of constant keys.
Returns an array of values defined in `map()`. If `map()` is not implemented then an array of null values will
be returned.

### identifiers()
### names()

Returns an array of all the constant identifiers declared with `const MY_CONST = 'key'`
Returns an array of all the constant names declared with the class.

### constantMap()
### namesAndKeys()

Returns an array of CONST => key, for all of the constant identifiers declared with `const MY_CONST = 'key'`.
Returns an associative array of CONSTANT_NAME => key, for all of the constant names declared within the class.

### getKeyForIdentifier(string $identifier)
### keyForName(string $name)

Returns the key for the given constant identifier.
Returns the key for the given constant name.

### identifierExists(string $identifier)
### nameForKey(string $key)

Returns true if the given identifier is declared as a `const` within the class.
Returns the constant name for the given key (the inverse of `keyForName`).

### valueFor(string $key)
### valueForKey(string $key)

Returns the value (or null if not mapped) for the given key (as declared in the `map()` method).

### fromValue(string $value)
### keyForValue(mixed $value)

Returns the key for the given value (as declared in the `map()` method).

> Note: If duplicate values are contained within the `map()` method then only the first key will be returned.

Returns the constant for the given value (as declared in the `map()` method).
> Caveats: Only works with single dimension arrays and it will only return the last key if multiple keys have the same value.
### instanceFromName($name)

Create instance of this Enum from the given constant name.

### instanceFromKey($key)

Create instance of this Enum from the given key.

### exists(string $key)
### isValidKey(string $key)

Returns true if the given key exists.

### checkExists(string $key)
### isValidName(string $name)

Returns true if the given constant name (case-sensitive) has been declared in the class.

### requireValidKey(string $key)

Throws a `InvalidArgumentException` if the given key does NOT exist.
Throws a `\Rexlabs\Enum\Exceptions\InvalidKeyException` if the given key does NOT exist.

## Tests

Expand Down
Loading