File tree Expand file tree Collapse file tree 3 files changed +38
-2
lines changed Expand file tree Collapse file tree 3 files changed +38
-2
lines changed Original file line number Diff line number Diff line change @@ -38,14 +38,27 @@ public function __construct($value)
38
38
$ reflectionClass = new ReflectionClass ($ this );
39
39
$ constants = $ reflectionClass ->getConstants ();
40
40
41
+ // Constant values needs to be unique
42
+ if (count ($ constants ) > count (array_unique ($ constants ))) {
43
+ $ ambiguous = array ();
44
+ foreach (array_count_values ($ constants ) as $ constValue => $ countValue ) {
45
+ if ($ countValue < 2 ) {
46
+ continue ;
47
+ }
48
+ $ ambiguous [] = $ constValue ;
49
+ }
50
+ throw new LogicException (sprintf (
51
+ 'All possible values needs to be unique. The following are ambiguous: %s ' ,
52
+ "' " . implode ("', ' " , $ ambiguous ) . "' "
53
+ ));
54
+ }
55
+
41
56
// This is required to make sure that constants of base classes will be the first
42
57
while ( ($ reflectionClass = $ reflectionClass ->getParentClass ()) ) {
43
58
$ constants = $ reflectionClass ->getConstants () + $ constants ;
44
59
}
45
60
$ this ->constants = $ constants ;
46
61
47
- // TODO: Check that constant values are equal (non strict comparison)
48
-
49
62
// find and set the given value
50
63
// set the defined value because of non strict comparison
51
64
$ const = array_search ($ value , $ this ->constants );
Original file line number Diff line number Diff line change @@ -103,4 +103,10 @@ public function testInstantiateUsingMagicMethodThrowsBadMethodCallException()
103
103
$ this ->setExpectedException ('BadMethodCallException ' );
104
104
MabeEnumTest_TestAsset_EnumInheritance::UNKNOWN ();
105
105
}
106
+
107
+ public function testAmbuguousConstantsThrowsLogicException ()
108
+ {
109
+ $ this ->setExpectedException ('LogicException ' );
110
+ new MabeEnumTest_TestAsset_EnumAmbiguous (MabeEnumTest_TestAsset_EnumAmbiguous::AMBIGUOUS1 );
111
+ }
106
112
}
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ /**
4
+ * Unit tests for the class MabeEnum_Enum
5
+ *
6
+ * @link http://github.com/marc-mabe/php-enum for the canonical source repository
7
+ * @copyright Copyright (c) 2012 Marc Bennewitz
8
+ * @license http://github.com/marc-mabe/php-enum/blob/master/LICENSE.txt New BSD License
9
+ */
10
+ class MabeEnumTest_TestAsset_EnumAmbiguous extends MabeEnum_Enum
11
+ {
12
+ const UNIQUE1 = 'unique1 ' ;
13
+ const AMBIGUOUS1 = 1 ;
14
+ const UNIQUE2 = 'unique2 ' ;
15
+ const AMBIGUOUS2 = '1 ' ;
16
+ const UNIQUE3 = 'unique3 ' ;
17
+ }
You can’t perform that action at this time.
0 commit comments