Skip to content

Commit cdf589a

Browse files
committed
initial commit
0 parents  commit cdf589a

24 files changed

+1747
-0
lines changed

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
.idea
2+
.phpunit.result.cache
3+
coverage
4+
coverage.xml
5+
composer.lock
6+
vendor

.travis.yml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
language: php
2+
3+
php:
4+
- 7.1
5+
- 7.2
6+
- 7.3
7+
- hhvm
8+
- nightly
9+
10+
sudo: false
11+
12+
before_script:
13+
- COMPOSER_ROOT_VERSION=dev-master composer install
14+
15+
script:
16+
- vendor/bin/phpunit --coverage-text
17+
18+
matrix:
19+
allow_failures:
20+
- php: hhvm
21+
- php: nightly

LICENSE

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Copyright (c) 2019 Tomasz Kowalczyk
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is furnished
8+
to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in all
11+
copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19+
THE SOFTWARE.

Makefile

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
test: test-phpunit
2+
test-phpunit:
3+
PHP_VERSION=7.3 docker-compose run --rm php php -v && php vendor/bin/phpunit --coverage-text
4+
test-phpunit-local:
5+
php -v
6+
php vendor/bin/phpunit --coverage-text
7+
8+
travis:
9+
PHP_VERSION=7.1 make travis-job
10+
PHP_VERSION=7.2 make travis-job
11+
PHP_VERSION=7.3 make travis-job
12+
PHP_VERSION=7.3 docker-compose run --rm composer composer config --unset platform
13+
travis-job:
14+
docker-compose run --rm composer composer config platform.php ${PHP_VERSION}
15+
docker-compose run --rm composer composer update -q
16+
PHP_VERSION=${PHP_VERSION} docker-compose run --rm php php -v
17+
PHP_VERSION=${PHP_VERSION} docker-compose run --rm php php vendor/bin/phpunit

README.md

Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
# Platenum
2+
3+
[![Build Status](https://travis-ci.org/thunderer/Platenum.png?branch=master)](https://travis-ci.org/thunderer/Platenum)
4+
[![License](https://poser.pugx.org/thunderer/platenum/license.svg)](https://packagist.org/packages/thunderer/platenum)
5+
[![Latest Stable Version](https://poser.pugx.org/thunderer/platenum/v/stable.svg)](https://packagist.org/packages/thunderer/platenum)
6+
7+
Platenum provides a flexible and feature-complete solution for [enumerations (enums)](https://en.wikipedia.org/wiki/Enumerated_type) in PHP with no external dependencies. The name comes from the Latin term for a [Platinum](https://en.wikipedia.org/wiki/Platinum) chemical element.
8+
9+
## Installation
10+
11+
This library is available on Packagist and can be installed with Composer in projects supporting PHP 7.1 and above:
12+
13+
```
14+
composer require thunderer/platenum
15+
```
16+
17+
## Usage
18+
19+
Create a new class with members definition:
20+
21+
```php
22+
<?php
23+
declare(strict_types=1);
24+
namespace X;
25+
26+
use Thunder\Platenum\Enum\ConstantsEnumTrait;
27+
28+
/**
29+
* @method static self ACTIVE()
30+
* @method static self INACTIVE()
31+
* @method static self SUSPENDED()
32+
* @method static self DISABLED()
33+
*/
34+
final class AccountStatusEnum
35+
{
36+
private const ACTIVE = 1;
37+
private const INACTIVE = 2;
38+
private const SUSPENDED = 3;
39+
private const DISABLED = 4;
40+
41+
use ConstantsEnumTrait;
42+
}
43+
```
44+
45+
> Tip: To enable autocomplete for the constant methods, include the [`@method` declarations](http://docs.phpdoc.org/references/phpdoc/tags/method.html) as shown in the listing above.
46+
47+
Members instances can be created using either constants methods, members names, or their values:
48+
49+
```php
50+
$active = AccountStatusEnum::ACTIVE();
51+
$alsoActive = AccountStatusEnum::fromMember('ACTIVE');
52+
$stillActive = AccountStatusEnum::fromValue(1);
53+
```
54+
55+
Enums can be compared using strict `===` operator or an `equals()` method:
56+
57+
```php
58+
assert($active === $alsoActive);
59+
assert(true === $active->equals($alsoActive));
60+
```
61+
62+
> Note: Strict comparison `===` should be always preferred. Loose `==` comparison will also work correctly, but it has [loads of quirks](http://php.net/manual/en/language.oop5.object-comparison.php).
63+
64+
The `getValue()` method returns the raw value of given instance:
65+
66+
```php
67+
assert(1 === $active->getValue());
68+
```
69+
70+
**enum generator**
71+
72+
Classes can be automatically generated using built-in `bin/generate` utility. It accepts three parameters:
73+
- location of its members (either `constants`, `docblock` or `static`),
74+
- (fully qualified) class name, Platenum matches the namespace to your autoloading configuration and puts the file in the proper directory,
75+
- members names with optional values where supported.
76+
77+
Example:
78+
79+
```
80+
bin/generate constants Thunder\\Platenum\\YourEnum FOO=1,BAR=3
81+
bin/generate docblock Thunder\\Platenum\\YourEnum FOO,BAR
82+
bin/generate static Thunder\\Platenum\\YourEnum FOO,BAR=3
83+
```
84+
85+
## Sources
86+
87+
There are multiple sources from which Platenum can read enumeration members. Base `EnumTrait` provides all enum functionality without any source, to be defined in a static `resolve()` method. Each source is available both as a `trait` which uses `EnumTrait` with concrete `resolve()` method implementation and an `abstract class` based on that trait. Usage of traits is recommended as target enum classes should not have any common type hint.
88+
89+
In this section the `BooleanEnum` class with two members (`TRUE=true` and `FALSE=false`) will be used as an example.
90+
91+
**class constants**
92+
93+
```php
94+
final class BooleanEnum
95+
{
96+
use ConstantsEnumTrait;
97+
98+
private const TRUE = true;
99+
private const FALSE = false;
100+
}
101+
```
102+
103+
```php
104+
final class BooleanEnum extends AbstractConstantsEnum
105+
{
106+
private const TRUE = true;
107+
private const FALSE = false;
108+
}
109+
```
110+
111+
**class docblock**
112+
113+
> Note: There is no way to specify members values inside docblock, therefore all members names are also their values - in this case `TRUE='TRUE'` and `FALSE='FALSE'`.
114+
115+
```php
116+
/**
117+
* @method static self TRUE()
118+
* @method static self FALSE()
119+
*/
120+
final class BooleanEnum
121+
{
122+
use DocblockEnumTrait;
123+
}
124+
```
125+
126+
```php
127+
/**
128+
* @method static self TRUE()
129+
* @method static self FALSE()
130+
*/
131+
final class BooleanEnum extends AbstractDocblockEnum {}
132+
```
133+
134+
**static property**
135+
136+
```php
137+
final class BooleanEnum
138+
{
139+
use StaticEnumTrait;
140+
141+
private static $mapping = [
142+
'TRUE' => true,
143+
'FALSE' => false,
144+
];
145+
}
146+
```
147+
148+
```php
149+
final class BooleanEnum extends AbstractStaticEnum
150+
{
151+
private static $mapping = [
152+
'TRUE' => true,
153+
'FALSE' => false,
154+
];
155+
}
156+
```
157+
158+
**custom source**
159+
160+
> Note: The `resolve` method will be called only once when the enumeration is used for the first time.
161+
162+
```php
163+
final class BooleanEnum
164+
{
165+
use EnumTrait;
166+
167+
private static function resolve(): array
168+
{
169+
return [
170+
'TRUE' => true,
171+
'FALSE' => false,
172+
];
173+
}
174+
}
175+
```
176+
177+
## Reasons
178+
179+
There are already a few `enum` libraries in the PHP ecosystem. Why another one? There are several reasons to do so:
180+
181+
**Sources** Platenum allows multiple sources for enumeration members. `EnumTrait` contains all enum functions - extend it with your custom `resolve()` method to create custom source. In fact, all enumeration sources in this repository are defined this way.
182+
183+
**Features** Platenum provides complete feature set for all kinds of operations on enumeration members, values, comparison, transformation, and more. Look at PhpEnumerations project to see the feature matrix created during development of this library.
184+
185+
**Inheritance** Existing solutions use inheritance for creating enum classes:
186+
187+
```php
188+
class YourEnum extends LibraryEnum
189+
{
190+
const ONE = 1;
191+
const TWO = 2;
192+
}
193+
```
194+
195+
Enumerations should be represented as different types without an ability to be used interchangeably. Platenum leverages traits to provide complete class body, therefore `instanceof` comparison will fail as it should and there is no possibility to typehint generic `LibraryEnum` class to allow any enum instance there.
196+
197+
**Comparison** Creating more than one instance of certain enum value should not prohibit you from strictly comparing them like any other variable. Other solutions encourage using loose comparison (`==`) as the instances with the same values are not the same instances of their classes. This library guarantees that the same enum value instance will always be the same instance which can be strictly compared:
198+
199+
```php
200+
final class YourEnum
201+
{
202+
private const ONE = 1;
203+
private const TWO = 2;
204+
205+
use EnumTrait;
206+
}
207+
208+
YourEnum::ONE() === YourEnum::ONE()
209+
YourEnum::fromValue(1) === YourEnum::ONE()
210+
YourEnum::fromValue(1) === YourEnum::fromValue(1)
211+
```
212+
213+
> Note: If you want to prove me wrong by using reflection or other opcode modifying extensions like `uopz`, then save yourself that effort, you're right and I surrender.
214+
215+
**Serialization**
216+
217+
Platenum provides correct (de)serialization solution which preserves its single member instance guarantees.
218+
219+
The only exception to that guarantee is when an enum instance is `unserialize()`d inside another class as PHP always creates a new object there. This can be easily mitigated by `fromInstance` replacement helper method inside `__wakeup()` method which accepts its argument by reference and automatically swaps it to a correct instance:
220+
221+
```php
222+
public function __wakeup()
223+
{
224+
$this->enum->fromInstance($this->enum);
225+
}
226+
```
227+
228+
Note that `equals()` method is not affected as it does not rely on the same object instance but its class and actual value inside.
229+
230+
# License
231+
232+
See LICENSE file in the main directory of this library.

bin/generate

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#!/usr/bin/env php
2+
<?php
3+
declare(strict_types=1);
4+
namespace X;
5+
6+
use Thunder\Platenum\Command\GenerateCommand;
7+
8+
$vendorLoaderPath = dirname(__DIR__, 3).'/vendor/autoload.php';
9+
$packageLoaderPath = dirname(__DIR__, 1).'/vendor/autoload.php';
10+
$loader = require file_exists($vendorLoaderPath) ? $vendorLoaderPath : $packageLoaderPath;
11+
12+
(new GenerateCommand($loader))->execute($argc, $argv);

composer.json

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
{
2+
"name": "thunderer/platenum",
3+
"description": "PHP enum library",
4+
"keywords": ["enum", "enumeration"],
5+
"type": "library",
6+
"license": "MIT",
7+
"authors": [
8+
{
9+
"name": "Tomasz Kowalczyk",
10+
"email": "[email protected]"
11+
}
12+
],
13+
"require": {
14+
"php": "^7.1"
15+
},
16+
"require-dev": {
17+
"ext-json": "*",
18+
"phpunit/phpunit": ">=6.0",
19+
"hirak/prestissimo": "^0.3.8"
20+
},
21+
"autoload": {
22+
"psr-4": {
23+
"Thunder\\Platenum\\": "src"
24+
}
25+
},
26+
"autoload-dev": {
27+
"psr-4": {
28+
"Thunder\\Platenum\\Tests\\": "tests"
29+
}
30+
},
31+
"suggest": {
32+
"ext-json": "Allow JSON serializable enumerations."
33+
},
34+
"config": {
35+
}
36+
}

docker-compose.yaml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
version: '3'
2+
3+
services:
4+
5+
composer:
6+
image: composer
7+
volumes:
8+
- .:/app
9+
working_dir: /app
10+
11+
php:
12+
image: php:${PHP_VERSION}
13+
volumes:
14+
- .:/app
15+
working_dir: /app

phpunit.xml.dist

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?xml version="1.0" encoding="UTF-8" ?>
2+
<phpunit
3+
backupGlobals = "false"
4+
backupStaticAttributes = "false"
5+
colors = "true"
6+
convertErrorsToExceptions = "true"
7+
convertNoticesToExceptions = "true"
8+
convertWarningsToExceptions = "true"
9+
processIsolation = "false"
10+
stopOnFailure = "false"
11+
bootstrap = "vendor/autoload.php"
12+
>
13+
14+
<testsuites>
15+
<testsuite name="Platenum">
16+
<directory>./tests/</directory>
17+
</testsuite>
18+
</testsuites>
19+
20+
<logging>
21+
<log type="coverage-html" target="coverage" lowUpperBound="50" highLowerBound="90"/>
22+
<log type="coverage-clover" target="coverage.xml"/>
23+
</logging>
24+
25+
<filter>
26+
<whitelist>
27+
<directory>./src</directory>
28+
</whitelist>
29+
</filter>
30+
</phpunit>

0 commit comments

Comments
 (0)