Skip to content

Commit

Permalink
handle class constant visibility
Browse files Browse the repository at this point in the history
  • Loading branch information
marc-mabe committed Aug 18, 2016
1 parent 7d99150 commit 404f858
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Enum.php
Expand Up @@ -296,7 +296,18 @@ private static function detectConstants($class)
{
if (!isset(self::$constants[$class])) {
$reflection = new ReflectionClass($class);
$constants = $reflection->getConstants();

if (PHP_VERSION_ID >= 70100) {
$reflConstants = $reflection->getReflectionConstants();
$constants = array();
foreach ($reflConstants as $reflConstant) {
if ($reflConstant->isPublic()) {
$constants[ $reflConstant->getName() ] = $reflConstant->getValue();
}
}
} else {
$constants = $reflection->getConstants();
}

// values needs to be unique
$ambiguous = array();
Expand Down
23 changes: 23 additions & 0 deletions tests/MabeEnumTest/EnumTest.php
Expand Up @@ -6,6 +6,7 @@
use MabeEnumTest\TestAsset\EnumInheritance;
use MabeEnumTest\TestAsset\EnumAmbiguous;
use MabeEnumTest\TestAsset\EnumExtendedAmbiguous;
use MabeEnumTest\TestAsset\ConstVisibilityEnum;
use PHPUnit_Framework_TestCase as TestCase;
use ReflectionClass;

Expand Down Expand Up @@ -255,4 +256,26 @@ public function testHas()
$this->assertTrue($enum->has(EnumBasic::ONE()));
$this->assertTrue($enum->has(EnumBasic::ONE));
}

public function testConstVisibility()
{
if (PHP_VERSION_ID < 70100) {
$this->markTestSkipped('This test is for PHP-7 and upper only');
}

$constants = ConstVisibilityEnum::getConstants();
$this-assertArrayHasKey('IPUB'); // indirect public
$this-assertArrayHasKey('PUB'); // public
$this-assertArrayNotHasKey('PRO'); // protected
$this-assertArrayNotHasKey('PRI'); // private

$this->assertTrue(ConstVisibilityEnum::has('IPUB'));
$this->assertSame('indirect public', ConstVisibilityEnum::IPUB()->getValue());

$this->assertTrue(ConstVisibilityEnum::has('PUB'));
$this->assertSame('public', ConstVisibilityEnum::PUB()->getValue());

$this->assertFalse(ConstVisibilityEnum::has('PRO'));
$this->assertFalse(ConstVisibilityEnum::has('PRI'));
}
}
21 changes: 21 additions & 0 deletions tests/MabeEnumTest/TestAsset/ConstVisibilityEnum.php
@@ -0,0 +1,21 @@
<?php

namespace MabeEnumTest\TestAsset;

use MabeEnum\Enum;

/**
* Unit tests for the class MabeEnum\Enum
*
* @link http://github.com/marc-mabe/php-enum for the canonical source repository
* @copyright Copyright (c) 2013 Marc Bennewitz
* @license http://github.com/marc-mabe/php-enum/blob/master/LICENSE.txt New BSD License
*/
class ConstVisibilityEnum extends Enum
{
const IPUB = 'indirect public';
public const PUB = 'public';
protected const PRO = 'protected';
private const PRI = 'private';
}

0 comments on commit 404f858

Please sign in to comment.