Skip to content

Commit 1baf0c9

Browse files
committed
feat: Add serializable trait
1 parent ee3aa23 commit 1baf0c9

3 files changed

Lines changed: 50 additions & 0 deletions

File tree

src/Serializable.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
namespace Attributes\Serialization;
1010

11+
use Attributes\Serialization\Exceptions\SerializeException;
12+
1113
interface Serializable
1214
{
1315
/**
@@ -17,6 +19,8 @@ interface Serializable
1719
* @param object $model - Model to serialize
1820
*
1921
* @returns mixed
22+
*
23+
* @throws SerializeException If unable to serialize value
2024
*/
2125
public function serialize(object $model): mixed;
2226
}

src/SerializableTrait.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php
2+
3+
namespace Attributes\Serialization;
4+
5+
use Attributes\Options\Ignore;
6+
use Attributes\Serialization\Exceptions\SerializeException;
7+
8+
trait SerializableTrait
9+
{
10+
#[Ignore]
11+
protected ?Serializable $serializer = null;
12+
13+
/**
14+
* @throws SerializeException
15+
*/
16+
public function serialize(): mixed
17+
{
18+
if ($this->serializer === null) {
19+
$this->serializer = new Serializer;
20+
}
21+
22+
return $this->serializer->serialize($this);
23+
}
24+
}

tests/Integration/SerializersTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
namespace Attributes\Serialization\Tests\Integration;
1212

1313
use Attributes\Serialization\Exceptions\SerializeException;
14+
use Attributes\Serialization\SerializableTrait;
1415
use Attributes\Serialization\Serializer;
1516
use Attributes\Serialization\Tests\Models as Models;
1617
use DateTime;
@@ -323,3 +324,24 @@
323324
]);
324325
})
325326
->group('serializer', 'options');
327+
328+
// Serializable trait
329+
330+
test('Serialize with trait', function (): void {
331+
$model = new class
332+
{
333+
use SerializableTrait;
334+
335+
public int $id = 10;
336+
337+
public string $name = 'Andre';
338+
};
339+
340+
expect($model->serialize())
341+
->toBeArray()
342+
->toBe([
343+
'id' => 10,
344+
'name' => 'Andre',
345+
]);
346+
})
347+
->group('serializer', 'options', 'trait');

0 commit comments

Comments
 (0)