Skip to content

Commit

Permalink
Merge pull request #111 from spatie/improve-unserializable-response-h…
Browse files Browse the repository at this point in the history
…andling

Improve unserializable response handling
  • Loading branch information
sebastiandedeyne authored Jan 30, 2018
2 parents f2fc02f + 6db7f3b commit b46de0e
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Exceptions/CouldNotUnserialize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Spatie\ResponseCache\Exceptions;

use Exception;

class CouldNotUnserialize extends Exception
{
public static function serializedResponse(string $serializedResponse): self
{
return new static("Could not unserialize `{$serializedResponse}`");
}
}
18 changes: 18 additions & 0 deletions src/ResponseSerializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Spatie\ResponseCache;

use Symfony\Component\HttpFoundation\Response;
use Spatie\ResponseCache\Exceptions\CouldNotUnserialize;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class ResponseSerializer
Expand All @@ -19,6 +20,10 @@ public function unserialize(string $serializedResponse): Response
{
$responseProperties = unserialize($serializedResponse);

if (! $this->containsValidResponseProperties($responseProperties)) {
throw CouldNotUnserialize::serializedResponse($serializedResponse);
}

$response = $this->buildResponse($responseProperties);

$response->headers = $responseProperties['headers'];
Expand All @@ -44,6 +49,19 @@ protected function getResponseData(Response $response): array
return compact('statusCode', 'headers', 'content', 'type');
}

protected function containsValidResponseProperties($properties): bool
{
if (! is_array($properties)) {
return false;
}

if (! isset($properties['content'], $properties['statusCode'])) {
return false;
}

return true;
}

protected function buildResponse(array $responseProperties): Response
{
$type = $responseProperties['type'] ?? self::RESPONSE_TYPE_NORMAL;
Expand Down
9 changes: 9 additions & 0 deletions tests/ResponseSerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Spatie\ResponseCache\ResponseSerializer;
use Symfony\Component\HttpFoundation\Response;
use Spatie\ResponseCache\Exceptions\CouldNotUnserialize;

class ResponseSerializerTest extends TestCase
{
Expand Down Expand Up @@ -46,4 +47,12 @@ public function it_can_serialize_and_unserialize_a_response()

$this->assertEquals('testValue', $unserializedResponse->headers->get('testHeader'));
}

/** @test */
public function it_throws_an_exception_when_something_else_than_a_response_is_unserialized()
{
$this->expectException(CouldNotUnserialize::class);

$this->responseSerializer->unserialize('b:0;');
}
}

0 comments on commit b46de0e

Please sign in to comment.