Skip to content

Commit

Permalink
Add ImmutableObject trait
Browse files Browse the repository at this point in the history
  • Loading branch information
rozsival committed Apr 17, 2021
1 parent c059dc6 commit ec72e12
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Utils/ImmutableObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php declare (strict_types = 1);

namespace Wavevision\Utils;

use Nette\SmartObject;

trait ImmutableObject
{

use SmartObject;

/**
* @param mixed $value
* @return static
*/
final protected function withMutation(string $property, $value)
{
$object = clone $this;
$object->$property = $value;
return $object;
}

}
29 changes: 29 additions & 0 deletions tests/UtilsTests/ImmutableObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php declare (strict_types = 1);

namespace Wavevision\UtilsTests;

use Wavevision\Utils;

class ImmutableObject
{

use Utils\ImmutableObject;

private string $prop;

public function __construct(string $prop)
{
$this->prop = $prop;
}

public function getProp(): string
{
return $this->prop;
}

public function withProp(string $prop): self
{
return $this->withMutation('prop', $prop);
}

}
17 changes: 17 additions & 0 deletions tests/UtilsTests/ImmutableObjectTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php declare (strict_types = 1);

namespace Wavevision\UtilsTests;

use PHPUnit\Framework\TestCase;

class ImmutableObjectTest extends TestCase
{

public function testWithMutation(): void
{
$object = new ImmutableObject('default');
$this->assertSame('default', $object->getProp());
$this->assertNotSame($object, $object->withProp('changed'));
}

}

0 comments on commit ec72e12

Please sign in to comment.