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

Commit 6eafecb

Browse files
Add constants helper trait
1 parent cb4a148 commit 6eafecb

File tree

2 files changed

+110
-0
lines changed

2 files changed

+110
-0
lines changed

src/Classes/Constants.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
namespace SebastiaanLuca\PhpHelpers\Classes;
4+
5+
use ReflectionClass;
6+
7+
trait Constants
8+
{
9+
/**
10+
* Get all the class constants.
11+
*
12+
* @return array
13+
*/
14+
public static function constants() : array
15+
{
16+
return (new ReflectionClass(__CLASS__))->getConstants();
17+
}
18+
19+
/**
20+
* Get all the names of the class constants.
21+
*
22+
* @return array
23+
*/
24+
public static function keys() : array
25+
{
26+
return array_keys(static::all());
27+
}
28+
29+
/**
30+
* Get all the values of the class constants.
31+
*
32+
* @return array
33+
*/
34+
public static function values() : array
35+
{
36+
return array_values(static::all());
37+
}
38+
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
namespace SebastiaanLuca\Helpers\Tests\Unit\Classes;
4+
5+
use SebastiaanLuca\PhpHelpers\Classes\Constants;
6+
use SebastiaanLuca\PhpHelpers\Tests\TestCase;
7+
8+
class ConstantsHelperTest extends TestCase
9+
{
10+
/**
11+
* @test
12+
*/
13+
public function it returns all constants() : void
14+
{
15+
$class = new class
16+
{
17+
use Constants;
18+
19+
public const FIRST_CONSTANT = 1;
20+
public const SECOND_CONSTANT = 2;
21+
public const THIRD_CONSTANT = 3;
22+
};
23+
24+
$this->assertEquals([
25+
'FIRST_CONSTANT' => 1,
26+
'SECOND_CONSTANT' => 2,
27+
'THIRD_CONSTANT' => 3,
28+
], $class::constants());
29+
}
30+
31+
/**
32+
* @test
33+
*/
34+
public function it returns all constant names() : void
35+
{
36+
$class = new class
37+
{
38+
use Constants;
39+
40+
public const FIRST_CONSTANT = 1;
41+
public const SECOND_CONSTANT = 2;
42+
public const THIRD_CONSTANT = 'three';
43+
};
44+
45+
$this->assertEquals([
46+
'FIRST_CONSTANT',
47+
'SECOND_CONSTANT',
48+
'THIRD_CONSTANT',
49+
], $class::keys());
50+
}
51+
52+
/**
53+
* @test
54+
*/
55+
public function it returns all constant values() : void
56+
{
57+
$class = new class
58+
{
59+
use Constants;
60+
61+
public const FIRST_CONSTANT = 1;
62+
public const SECOND_CONSTANT = 'two';
63+
public const THIRD_CONSTANT = 3;
64+
};
65+
66+
$this->assertEquals([
67+
1,
68+
'two',
69+
3,
70+
], $class::values());
71+
}
72+
}

0 commit comments

Comments
 (0)