Skip to content

Commit 9931ceb

Browse files
committed
Trigger notice when Enum instance already exists during unserialize
1 parent 1534d31 commit 9931ceb

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

src/Enum.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,17 @@ public function __toString()
7070
return (string)$this->value;
7171
}
7272

73+
/**
74+
* Register object in cache and trigger a notice if it already exists.
75+
*/
76+
public function __wakeup()
77+
{
78+
$enum = EnumManager::get($this);
79+
if ($enum !== $this) {
80+
trigger_error("Enum is already initialized", E_USER_NOTICE);
81+
}
82+
}
83+
7384
/**
7485
* Compares one Enum with another.
7586
*

tests/EnumTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,4 +248,28 @@ public function testEqualsConflictValues()
248248
{
249249
$this->assertFalse(EnumFixture::FOO()->equals(EnumConflict::FOO()));
250250
}
251+
252+
/**
253+
* __wakeup()
254+
*/
255+
public function testUnserialize()
256+
{
257+
$ser = 'O:37:"MyCLabs\Tests\Enum\UnserializeFixture":2:{'
258+
. 's:23:"#MyCLabs\Enum\Enum#name";s:4:"ONCE";'
259+
. 's:24:"#MyCLabs\Enum\Enum#value";s:2:"OK";}';
260+
$once = unserialize(strtr($ser, "#", "\0"));
261+
262+
$this->assertSame($once, UnserializeFixture::ONCE());
263+
}
264+
265+
/**
266+
* @expectedException \PHPUnit\Framework\Error\Notice
267+
*/
268+
public function testUnserializeError()
269+
{
270+
$ser = 'O:30:"MyCLabs\Tests\Enum\EnumFixture":2:{'
271+
. 's:23:"#MyCLabs\Enum\Enum#name";s:3:"FOO";'
272+
. 's:24:"#MyCLabs\Enum\Enum#value";s:3:"foo";}';
273+
$foo = unserialize(strtr($ser, "#", "\0"));
274+
}
251275
}

tests/UnserializeFixture.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
/**
3+
* @link http://github.com/myclabs/php-enum
4+
* @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
5+
*/
6+
7+
namespace MyCLabs\Tests\Enum;
8+
9+
use MyCLabs\Enum\Enum;
10+
11+
/**
12+
* Class UnserializeFixture
13+
*
14+
* @method static UnserializeFixture ONCE()
15+
*/
16+
class UnserializeFixture extends Enum
17+
{
18+
const ONCE = 'OK';
19+
}

0 commit comments

Comments
 (0)