Skip to content

Commit

Permalink
Merge pull request #674 from hydephp/automatic-serialization-method
Browse files Browse the repository at this point in the history
Improve the `Serializable` trait to support automatic serialization
  • Loading branch information
caendesilva authored Dec 21, 2024
2 parents 9a2c623 + e1da184 commit a4dca7b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
15 changes: 13 additions & 2 deletions src/Support/Concerns/Serializable.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@
*/
trait Serializable
{
/** @inheritDoc */
abstract public function toArray(): array;
/** Default implementation to dynamically serialize all public properties. Can be overridden for increased control. */
public function toArray(): array
{
return $this->automaticallySerialize();
}

/** Recursively serialize Arrayables */
public function arraySerialize(): array
Expand All @@ -34,4 +37,12 @@ public function toJson($options = 0): string
{
return json_encode($this->jsonSerialize(), $options);
}

/** Automatically serialize all public properties. */
protected function automaticallySerialize(): array
{
// Calling the function from a different scope means we only get the public properties.

return get_object_vars(...)->__invoke($this);
}
}
35 changes: 35 additions & 0 deletions tests/Unit/SerializableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ public function testToJsonWithArrayable()
{
$this->assertSame('{"foo":"bar","arrayable":{"foo":"bar"}}', (new SerializableTestClassWithArrayable)->toJson());
}

public function testAutomaticallySerialization()
{
$this->assertSame([
'foo' => 'foo',
'bar' => 'bar',
'baz' => ['baz' => 'baz'],
], (new AutomaticallySerializableTestClass)->toArray());
}
}

class SerializableTestClass implements SerializableContract
Expand Down Expand Up @@ -82,3 +91,29 @@ public function toArray(): array
return ['foo' => 'bar'];
}
}

class AutomaticallySerializableTestClass implements SerializableContract
{
use Serializable;

public string $foo;
public string $bar;
public array $baz;

public string $uninitialized;

protected string $hidden;
private string $private;

public static string $static;

public function __construct()
{
$this->foo = 'foo';
$this->bar = 'bar';
$this->baz = ['baz' => 'baz'];
$this->hidden = 'hidden';
$this->private = 'private';
static::$static = 'static';
}
}

0 comments on commit a4dca7b

Please sign in to comment.