-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Objects] Create Experimental JsonSerializer (#32)
Co-authored-by: onairmarc <[email protected]>
- Loading branch information
Showing
3 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
<?php | ||
|
||
namespace EncoreDigitalGroup\StdLib\Objects; | ||
|
||
use Illuminate\Support\Collection; | ||
use Symfony\Component\Serializer\Encoder\JsonEncoder; | ||
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; | ||
use Symfony\Component\Serializer\Serializer; | ||
|
||
/** @experimental */ | ||
class JsonSerializer | ||
{ | ||
protected static Collection $normalizers; | ||
protected static Serializer $serializer; | ||
|
||
public static function normalizers(): Collection | ||
{ | ||
$defaultNormalizers = [ | ||
ObjectNormalizer::class, | ||
]; | ||
|
||
if (!isset(static::$normalizers)) { | ||
static::$normalizers = new Collection($defaultNormalizers); | ||
} | ||
|
||
return static::$normalizers; | ||
} | ||
|
||
public static function serialize(object $object): string | ||
{ | ||
$serializer = new Serializer(static::normalizers()->all(), [(new JsonEncoder)]); | ||
$normalized = $serializer->normalize($object); | ||
|
||
return $serializer->serialize($normalized, "json"); | ||
} | ||
|
||
public static function deserialize(string $class, string $data): mixed | ||
{ | ||
$serializer = new Serializer(static::normalizers()->all(), [(new JsonEncoder)]); | ||
$json = $serializer->deserialize($data, $class, "json"); | ||
|
||
return $serializer->denormalize($json, $class); | ||
} | ||
} |