Skip to content

Commit

Permalink
Disallow serialization with Serializable interface (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
dbalabka authored Sep 15, 2019
1 parent a16efb0 commit da1fd8c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
24 changes: 23 additions & 1 deletion src/Enumeration/Enumeration.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Dbalabka\Enumeration\Exception\EnumerationException;
use Dbalabka\Enumeration\Exception\InvalidArgumentException;
use Dbalabka\StaticConstructorLoader\StaticConstructorInterface;
use Serializable;
use function array_search;
use function get_class_vars;
use function sprintf;
Expand All @@ -18,7 +19,7 @@
*
* @author Dmitry Balabka <[email protected]>
*/
abstract class Enumeration implements StaticConstructorInterface
abstract class Enumeration implements StaticConstructorInterface, Serializable
{
const INITIAL_ORDINAL = 0;

Expand Down Expand Up @@ -158,6 +159,7 @@ final public function __clone()

/**
* Serialization is not allowed right now. It is not possible to properly serialize the singleton.
* See the documentation for workaround.
*/
final public function __sleep()
{
Expand All @@ -168,4 +170,24 @@ final public function __wakeup()
{
throw new EnumerationException('Enum unserialization is not allowed');
}

final public function __serialize()
{
throw new EnumerationException('Enum serialization is not allowed');
}

final public function __unserialize()
{
throw new EnumerationException('Enum unserialization is not allowed');
}

final public function serialize()
{
throw new EnumerationException('Enum serialization is not allowed');
}

final public function unserialize($data)
{
throw new EnumerationException('Enum unserialization is not allowed');
}
}
7 changes: 6 additions & 1 deletion tests/Enumeration/EnumerationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Dbalabka\Enumeration\Tests\Fixtures\ActionWithPublicConstructor;
use Dbalabka\Enumeration\Tests\Fixtures\Flag;
use Error;
use PHPUnit\Framework\Error\Warning;
use PHPUnit\Framework\TestCase;
use function serialize;
use function version_compare;
Expand Down Expand Up @@ -96,7 +97,11 @@ public function testSerialization()
public function testUnserialization()
{
Flag::initialize();
$this->expectException(EnumerationException::class);
if (version_compare(PHP_VERSION, '7.4.0-dev', '<')) {
$this->expectException(Warning::class);
} else {
$this->expectException(EnumerationException::class);
}
unserialize('O:40:"Dbalabka\Enumeration\Tests\Fixtures\Flag":2:{s:51:" Dbalabka\Enumeration\Tests\Fixtures\Flag flagValue";i:2;s:10:" * ordinal";i:1;}');
}

Expand Down

0 comments on commit da1fd8c

Please sign in to comment.