Skip to content

Commit

Permalink
Merge pull request #1791 from hydephp/automatic-serialization-method
Browse files Browse the repository at this point in the history
Update the `Serializable` trait to provide a default automatic `toArray` method
  • Loading branch information
caendesilva authored Jul 6, 2024
2 parents 05edd65 + 9022c2a commit c2f9d5d
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
2 changes: 1 addition & 1 deletion RELEASE_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ This serves two purposes:
- Updated the `HydeKernel` array representation to include the Hyde version in https://github.com/hydephp/develop/pull/1786

### Changed
- for changes in existing functionality.
- Updated the `Serializable` trait to provide a default automatic `toArray` method in https://github.com/hydephp/develop/pull/1791

### Deprecated
- for soon-to-be removed features.
Expand Down
9 changes: 7 additions & 2 deletions packages/framework/src/Support/Concerns/Serializable.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@
*/
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
{
// Calling the function from a different scope means we only get the public properties.

return get_object_vars(...)->__invoke($this);
}

/** Recursively serialize Arrayables */
public function arraySerialize(): array
Expand Down
35 changes: 35 additions & 0 deletions packages/framework/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 c2f9d5d

Please sign in to comment.