Skip to content

Commit 552324c

Browse files
authored
Merge pull request #77 from marc-mabe/Enum_is_unserialized
Added additional check to Enum::is() to return TRUE …
2 parents a496c91 + 0c9a7f7 commit 552324c

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

README.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -271,8 +271,9 @@ class CardinalDirection extends Enum implements Serializable
271271
$north1 = CardinalDirection::NORTH();
272272
$north2 = unserialize(serialize($north1));
273273

274-
// The following could be FALSE as described above
275-
var_dump($north1 === $north2);
274+
var_dump($north1 === $north2); // returns FALSE as described above
275+
var_dump($north1->is($north2)); // returns TRUE - this way the two instances are treated equal
276+
var_dump($north2->is($north1)); // returns TRUE - equality works in both directions
276277
```
277278

278279
# Why not `SplEnum`

src/Enum.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,13 @@ final public function getOrdinal()
146146
*/
147147
final public function is($enumerator)
148148
{
149-
return $this === $enumerator || $this->value === $enumerator;
149+
return $this === $enumerator || $this->value === $enumerator
150+
151+
// The following additional conditions are required only because of the issue of serializable singletons
152+
|| ($enumerator instanceof static
153+
&& get_class($enumerator) === get_called_class()
154+
&& $enumerator->value === $this->value
155+
);
150156
}
151157

152158
/**

tests/MabeEnumTest/EnumTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use MabeEnumTest\TestAsset\EnumExtendedAmbiguous;
99
use MabeEnumTest\TestAsset\ConstVisibilityEnum;
1010
use MabeEnumTest\TestAsset\ConstVisibilityEnumExtended;
11+
use MabeEnumTest\TestAsset\SerializableEnum;
1112
use PHPUnit_Framework_TestCase as TestCase;
1213
use ReflectionClass;
1314

@@ -285,4 +286,17 @@ public function testConstVisibilityExtended()
285286
'PUB2' => ConstVisibilityEnumExtended::PUB2,
286287
), $constants);
287288
}
289+
290+
public function testIsSerializableIssue()
291+
{
292+
if (PHP_VERSION_ID < 50400) {
293+
$this->markTestSkipped('This test is for PHP-5.4 and upper only');
294+
}
295+
296+
$enum1 = SerializableEnum::INT();
297+
$enum2 = unserialize(serialize($enum1));
298+
299+
$this->assertFalse($enum1 === $enum2, 'Wrong test implementation');
300+
$this->assertTrue($enum1->is($enum2), 'Two different instances of exact the same enumerator should be equal');
301+
}
288302
}

0 commit comments

Comments
 (0)