Skip to content

Commit

Permalink
Merge pull request #20 from jrdnhannah/feature/serialization-of-non-e…
Browse files Browse the repository at this point in the history
…xistant-classes

[Serialization] Throw catchable exception if class does not exist for deserialization
  • Loading branch information
mrsimonbennett committed Dec 8, 2015
2 parents a7b1a19 + 2012fbb commit 0ac2d91
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
13 changes: 13 additions & 0 deletions src/Serialization/Exception/SerializedClassDoesNotExist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php namespace SmoothPhp\Serialization\Exception;

use Exception;

/**
* Class SerializedClassDoesNotExist
* @package SmoothPhp\Serialization\Exception
* @author jrdn hannah <jrdn@jrdnhannah.co.uk>
*/
final class SerializedClassDoesNotExist extends Exception
{

}
11 changes: 8 additions & 3 deletions src/Serialization/ObjectSelfSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use SmoothPhp\Contracts\Serialization\Serializer;
use SmoothPhp\Contracts\Serialization\Serializable;
use SmoothPhp\Serialization\Exception\SerializationException;
use SmoothPhp\Serialization\Exception\SerializedClassDoesNotExist;

/**
* Class ObjectSelfSerializer
Expand Down Expand Up @@ -33,14 +34,18 @@ public function serialize($object)
*/
public function deserialize(array $serializedObject)
{
if (! in_array(Serializable::class, class_implements($serializedObject['class']))) {
if (! class_exists($class = $serializedObject['class'])) {
throw new SerializedClassDoesNotExist("Class does not exist: [{$class}]");
}

if (! in_array(Serializable::class, class_implements($class))) {
throw new SerializationException(
sprintf(
'Class \'%s\' does not implement Serializable',
$serializedObject['class']
$class
)
);
}
return $serializedObject['class']::deserialize($serializedObject['payload']);
return $class::deserialize($serializedObject['payload']);
}
}
12 changes: 12 additions & 0 deletions tests/Serialization/ObjectSelfSerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,18 @@ public function it_should_deserialize_arrays_into_the_correct_object()
$this->assertInstanceOf(SerializableObject::class, $object);
$this->assertEquals('foo', $object->getFoo());
}

/**
* @test
* @expectedException SmoothPhp\Serialization\Exception\SerializedClassDoesNotExist
*/
public function it_should_throw_exception_on_non_existant_class()
{
$serializer = new ObjectSelfSerializer;
$data = ['class' => 'Foo\Bar\Baz', 'payload' => ['foo' => 'bar']];

$object = $serializer->deserialize($data);
}
}

final class SerializableObject implements Serializable
Expand Down

0 comments on commit 0ac2d91

Please sign in to comment.