Skip to content
This repository was archived by the owner on Dec 26, 2023. It is now read-only.

Commit 687392b

Browse files
author
Petr Knap
committed
Added ConstantsAsMembers trait
1 parent cfd0d76 commit 687392b

File tree

4 files changed

+66
-21
lines changed

4 files changed

+66
-21
lines changed

README.md

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,10 @@ And now the **same code with Enum** instead of Constants:
5151
```php
5252
<?php
5353

54-
class MyBoolean extends \PetrKnap\Php\Enum\Enum
54+
class MyBoolean extends \PetrKnap\Php\Enum\ConstEnum
5555
{
56-
protected function members()
57-
{
58-
return [
59-
"MY_TRUE" => 1,
60-
"MY_FALSE" => 2
61-
];
62-
}
56+
const MY_TRUE = 1;
57+
const MY_FALSE = 2;
6358
}
6459

6560
function isTrue(MyBoolean $myBoolean)
@@ -87,20 +82,15 @@ isTrue(false); // uncaught type error - OK
8782
```php
8883
<?php
8984

90-
class DayOfWeek extends \PetrKnap\Php\Enum\Enum
85+
class DayOfWeek extends \PetrKnap\Php\Enum\ConstEnum
9186
{
92-
protected function members()
93-
{
94-
return [
95-
"SUNDAY" => 0,
96-
"MONDAY" => 1,
97-
"TUESDAY" => 2,
98-
"WEDNESDAY" => 3,
99-
"THURSDAY" => 4,
100-
"FRIDAY" => 5,
101-
"SATURDAY" => 6
102-
];
103-
}
87+
const SUNDAY = 0;
88+
const MONDAY = 1;
89+
const TUESDAY = 2;
90+
const WEDNESDAY = 3;
91+
const THURSDAY = 4;
92+
const FRIDAY = 5;
93+
const SATURDAY = 6;
10494
}
10595
```
10696

src/ConstantsAsMembers.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace PetrKnap\Php\Enum;
4+
5+
use ReflectionClass;
6+
7+
trait ConstantsAsMembers
8+
{
9+
/**
10+
* @return array
11+
*/
12+
protected function members()
13+
{
14+
$classReflection = new ReflectionClass(get_called_class());
15+
16+
return $classReflection->getConstants();
17+
}
18+
}

tests/ConstantsAsMembersTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
namespace PetrKnap\Php\Enum\Test;
4+
5+
use PetrKnap\Php\Enum\Test\ConstantsAsMembersTest\MyBoolean;
6+
7+
class ConstantsAsMembersTest extends \PHPUnit_Framework_TestCase
8+
{
9+
public function testMembersWorks()
10+
{
11+
$this->assertEquals(
12+
[
13+
'MY_TRUE' => 1,
14+
'MY_FALSE' => 2,
15+
],
16+
MyBoolean::getMembers()
17+
);
18+
}
19+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace PetrKnap\Php\Enum\Test\ConstantsAsMembersTest;
4+
5+
use PetrKnap\Php\Enum\ConstantsAsMembers;
6+
use PetrKnap\Php\Enum\Enum;
7+
8+
/**
9+
* @method static MyBoolean MY_TRUE()
10+
* @method static MyBoolean MY_FALSE()
11+
*/
12+
class MyBoolean extends Enum
13+
{
14+
use ConstantsAsMembers;
15+
16+
const MY_TRUE = 1;
17+
const MY_FALSE = 2;
18+
}

0 commit comments

Comments
 (0)