Skip to content

Commit

Permalink
Setters refactoring + Immutability (#3)
Browse files Browse the repository at this point in the history
* Update project structure

* Introduce other way of setting values

* Immutability
  • Loading branch information
antoninmasek authored Jun 5, 2022
1 parent 3c890f6 commit 86725e2
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/DataObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,25 @@ public static function fromArray(array $data = null): ?static
return Hydrator::hydrate(static::class, $data);
}

public function __call($method, $arguments): self
public function set(string $propertyName, mixed $value): static
{
$reflectionClass = new ReflectionObject($this);
$clone = clone $this;
$reflectionClass = new ReflectionObject($clone);
$properties = $reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC);

foreach ($properties as $property) {
$name = $property->getName();

if (Str::camel($name) === Str::camel($method)) {
$property->setValue($this, ...$arguments);
if (Str::camel($name) === Str::camel($propertyName)) {
$property->setValue($clone, $value);
}
}

return $this;
return $clone;
}

public function __call($method, $arguments): static
{
return $this->set($method, ...$arguments);
}
}
32 changes: 32 additions & 0 deletions tests/SimpleHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,38 @@ public function testObjectCanSetValues()
$this->assertSame('John', $person->first_name);
}

public function testObjectCanSetValuesUsingSetter()
{
$person = Human::fromArray($this->data)->set('firstName', 'John');
$this->assertSame('John', $person->first_name);

$person = Human::fromArray($this->data)->set('FirstName', 'Dave');
$this->assertSame('Dave', $person->first_name);

$person = Human::fromArray($this->data)->set('First_Name', 'Pete');
$this->assertSame('Pete', $person->first_name);

$person = Human::fromArray($this->data)->set('First_name', 'Tony');
$this->assertSame('Tony', $person->first_name);

$person = Human::fromArray($this->data)->set('first_name', 'Steve');
$this->assertSame('Steve', $person->first_name);
}

public function testImmutability()
{
$person = Human::fromArray($this->data);
$this->assertSame('John', $person->name);

$person->set('name', 'Dave');
$this->assertSame('John', $person->name);

$person2 = $person->set('name', 'Dave');
$this->assertSame('Dave', $person2->name);

$this->assertNotSame(spl_object_id($person), spl_object_id($person2));
}

public function testObjectTypeError()
{
$this->expectException(TypeError::class);
Expand Down

0 comments on commit 86725e2

Please sign in to comment.