Skip to content

Commit

Permalink
make sure serialzation context is immutable
Browse files Browse the repository at this point in the history
  • Loading branch information
goetas committed Jan 25, 2020
1 parent 5286388 commit b846e6b
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Context.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public function setAttribute(string $key, $value): self
return $this;
}

private function assertMutable(): void
protected final function assertMutable(): void
{
if (!$this->initialized) {
return;
Expand Down
4 changes: 4 additions & 0 deletions src/SerializationContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ public function initialize(string $format, VisitorInterface $visitor, GraphNavig
*/
public function setSerializeNull(bool $bool): self
{
$this->assertMutable();

$this->serializeNull = $bool;

return $this;
Expand Down Expand Up @@ -142,6 +144,8 @@ public function getVisitingSet(): \SplObjectStorage
*/
public function setInitialType(string $type): self
{
$this->assertMutable();

$this->initialType = $type;
$this->setAttribute('initial_type', $type);
return $this;
Expand Down
20 changes: 20 additions & 0 deletions tests/Serializer/ContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace JMS\Serializer\Tests\Serializer;

use JMS\Serializer\Exception\LogicException;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\SerializationContext;
Expand All @@ -14,6 +16,8 @@
use JMS\Serializer\Tests\Fixtures\Node;
use JMS\Serializer\Tests\Fixtures\Publisher;
use JMS\Serializer\Tests\Fixtures\VersionedObject;
use JMS\Serializer\VisitorInterface;
use Metadata\MetadataFactoryInterface;
use PHPUnit\Framework\TestCase;

class ContextTest extends TestCase
Expand Down Expand Up @@ -214,4 +218,20 @@ public function testSerializeNullOption()
$context->setSerializeNull(true);
self::assertTrue($context->shouldSerializeNull());
}

public function testContextBecomesImmutableWhenStartingProcess()
{
$this->expectException(LogicException::class);
$this->expectExceptionMessage('This context was already initialized and is immutable; you cannot modify it anymore.');

$visitor = $this->createMock(VisitorInterface::class);
$navigator = $this->createMock(GraphNavigator::class);
$metadataFactory = $this->createMock(MetadataFactoryInterface::class);

$context = SerializationContext::create();

$context->initialize('json', $visitor, $navigator, $metadataFactory);

$context->setSerializeNull(false);
}
}

0 comments on commit b846e6b

Please sign in to comment.