Skip to content

Commit

Permalink
Trigger notice when Enum instance already exists
Browse files Browse the repository at this point in the history
  • Loading branch information
adrium committed Jan 30, 2017
1 parent 6d85390 commit d5c7562
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,17 @@ public function __toString()
return (string)$this->value;
}

/**
* Register object in cache and trigger a notice if it already exists.
*/
public function __wakeup()
{
$enum = EnumManager::get($this);
if ($enum !== $this) {
trigger_error("Enum is already initialized", E_USER_NOTICE);
}
}

/**
* Compares one Enum with another.
*
Expand Down
24 changes: 24 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,28 @@ public function testEqualsComparesProblematicValuesProperly()
$this->assertFalse($emptyString->equals($null));
$this->assertFalse($null->equals($false));
}

/**
* __wakeup()
*/
public function testUnserialize()
{
$ser = 'O:37:"MyCLabs\Tests\Enum\UnserializeFixture":2:{'
. 's:23:"#MyCLabs\Enum\Enum#name";s:4:"ONCE";'
. 's:24:"#MyCLabs\Enum\Enum#value";s:2:"OK";}';
$once = unserialize(strtr($ser, "#", "\0"));

$this->assertSame($once, UnserializeFixture::ONCE());
}

/**
* @expectedException \PHPUnit_Framework_Error_Notice
*/
public function testUnserializeError()
{
$ser = 'O:30:"MyCLabs\Tests\Enum\EnumFixture":2:{'
. 's:23:"#MyCLabs\Enum\Enum#name";s:3:"FOO";'
. 's:24:"#MyCLabs\Enum\Enum#value";s:3:"foo";}';
$foo = unserialize(strtr($ser, "#", "\0"));
}
}
19 changes: 19 additions & 0 deletions tests/UnserializeFixture.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
/**
* @link http://github.com/myclabs/php-enum
* @license http://www.opensource.org/licenses/mit-license.php MIT (see the LICENSE file)
*/

namespace MyCLabs\Tests\Enum;

use MyCLabs\Enum\Enum;

/**
* Class UnserializeFixture
*
* @method static UnserializeFixture ONCE()
*/
class UnserializeFixture extends Enum
{
const ONCE = 'OK';
}

0 comments on commit d5c7562

Please sign in to comment.