Add pjson support

This commit is contained in:
2024-06-29 11:46:16 -04:00
parent 50854275a8
commit 478684621c
8 changed files with 146 additions and 12 deletions

View File

@@ -3,8 +3,8 @@
namespace BitBadger\PDODocument\Mapper;
use BitBadger\PDODocument\DocumentException;
use Exception;
use JsonMapper;
use JsonMapper_Exception;
/**
* Map domain class instances from JSON documents
@@ -32,12 +32,15 @@ class DocumentMapper implements Mapper
public function map(array $result): mixed
{
try {
if (method_exists($this->className, 'fromJsonString')) {
return $this->className::fromJsonString($result[$this->fieldName]);
}
$json = json_decode($result[$this->fieldName]);
if (is_null($json)) {
throw new DocumentException("Could not map document for $this->className: " . json_last_error_msg());
}
return (new JsonMapper())->map($json, $this->className);
} catch (JsonMapper_Exception $ex) {
} catch (Exception $ex) {
throw new DocumentException("Could not map document for $this->className", previous: $ex);
}
}

View File

@@ -27,7 +27,10 @@ class Parameters
*/
public static function json(string $name, object|array $document): array
{
return [$name => json_encode($document, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)];
return [$name => match (is_object($document) && method_exists($document, 'toJson')) {
true => $document->toJson(),
false => json_encode($document, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
}];
}
/**