From 3cc716706c0b36d3e3986962cbebcfa7161fab05 Mon Sep 17 00:00:00 2001 From: Peter Grundmann Date: Thu, 7 Nov 2024 18:38:49 +0100 Subject: [PATCH] new "JsonComplete" attribute --- .gitignore | 1 + src/Attributes/Json.php | 3 ++- src/Attributes/JsonComplete.php | 11 +++++++++++ src/Attributes/JsonDateTime.php | 3 ++- src/Attributes/JsonEnum.php | 3 ++- src/Attributes/JsonType.php | 3 ++- src/JsonDeserializer.php | 30 +++++++++++++++++++++++++++++- 7 files changed, 49 insertions(+), 5 deletions(-) create mode 100644 src/Attributes/JsonComplete.php diff --git a/.gitignore b/.gitignore index 1a3eb7a..28eb210 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ composer.lock vendor/ .vscode/ notes.md +demos2/ \ No newline at end of file diff --git a/src/Attributes/Json.php b/src/Attributes/Json.php index 6f45753..f0b5b11 100644 --- a/src/Attributes/Json.php +++ b/src/Attributes/Json.php @@ -5,6 +5,7 @@ * Attribute that allows overwriting individual property names. */ #[\Attribute] -class Json { +class Json +{ public function __construct(public string $name) {} } \ No newline at end of file diff --git a/src/Attributes/JsonComplete.php b/src/Attributes/JsonComplete.php new file mode 100644 index 0000000..344b6ca --- /dev/null +++ b/src/Attributes/JsonComplete.php @@ -0,0 +1,11 @@ +setValue($object, $value, $prop); } + $this->finalize($object); + return $object; } @@ -205,7 +208,32 @@ private function getEnum(string $enumClass, mixed $value, ?string $propertyName } catch (Exception $ex) { throw new JsonException($ex->getMessage(), $propertyName); } - + } + + /** + * Find and invoke the objects #[JsonFinalize] method (if any). + * + * @param [type] $object + * @return void + */ + public function finalize($object) + { + $reflObject = new \ReflectionObject($object); + $methods = $reflObject->getMethods(); + + foreach ($methods as $method) + { + $attributes = $method->getAttributes(JsonComplete::class); + if (count($attributes) > 0) { + $methodName = $method->getName(); + $method = $reflObject->getMethod($methodName); + if (version_compare(PHP_VERSION, '8.1.0') < 0) { + $method->setAccessible(true); + } + $method->invoke($object); + break; + } + } } } \ No newline at end of file