Skip to content

Commit d5c7562

Browse files
committed
Trigger notice when Enum instance already exists
1 parent 6d85390 commit d5c7562

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
@@ -73,6 +73,17 @@ public function __toString()
7373
return (string)$this->value;
7474
}
7575

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

tests/EnumTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,4 +229,28 @@ public function testEqualsComparesProblematicValuesProperly()
229229
$this->assertFalse($emptyString->equals($null));
230230
$this->assertFalse($null->equals($false));
231231
}
232+
233+
/**
234+
* __wakeup()
235+
*/
236+
public function testUnserialize()
237+
{
238+
$ser = 'O:37:"MyCLabs\Tests\Enum\UnserializeFixture":2:{'
239+
. 's:23:"#MyCLabs\Enum\Enum#name";s:4:"ONCE";'
240+
. 's:24:"#MyCLabs\Enum\Enum#value";s:2:"OK";}';
241+
$once = unserialize(strtr($ser, "#", "\0"));
242+
243+
$this->assertSame($once, UnserializeFixture::ONCE());
244+
}
245+
246+
/**
247+
* @expectedException \PHPUnit_Framework_Error_Notice
248+
*/
249+
public function testUnserializeError()
250+
{
251+
$ser = 'O:30:"MyCLabs\Tests\Enum\EnumFixture":2:{'
252+
. 's:23:"#MyCLabs\Enum\Enum#name";s:3:"FOO";'
253+
. 's:24:"#MyCLabs\Enum\Enum#value";s:3:"foo";}';
254+
$foo = unserialize(strtr($ser, "#", "\0"));
255+
}
232256
}

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)