From 6728dd40b0415a6d418eda895d0ec1d2f06dbdfa Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Sun, 8 Aug 2021 00:39:39 +0000 Subject: [PATCH] [ENTITY] Add JsonSerializable interface to Entity base class and implement it for the Note class --- src/Core/Entity.php | 18 +++++++++++++++++- src/Entity/Note.php | 8 ++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Core/Entity.php b/src/Core/Entity.php index 1a5d1266a5..81c0deef9f 100644 --- a/src/Core/Entity.php +++ b/src/Core/Entity.php @@ -23,13 +23,14 @@ namespace App\Core; use App\Core\DB\DB; use App\Util\Exception\NotFoundException; +use App\Util\Exception\ServerException; use App\Util\Formatting; use DateTime; /** * Base class to all entities, with some utilities */ -abstract class Entity +abstract class Entity implements \JsonSerializable { public function __call(string $name , array $arguments): mixed { @@ -86,8 +87,10 @@ abstract class Entity $obj = DB::findOneBy($table, $find_by); } catch (NotFoundException) { $obj = null; + // @codeCoverageIgnoreStart } catch (\Exception $e) { Log::unexpected_exception($e); + // @codeCoverageIgnoreEnd } $is_update = $obj !== null; return [self::create($args, $obj), $is_update]; @@ -119,4 +122,17 @@ abstract class Entity return null; } } + + /** + * Called when json_encode encounters this object. Not all + * entities will need json encoding, so it doesn't make sense to + * make this abstract + * + * @throw ServerException + * @codeCoverageIgnore + */ + public function jsonSerialize() + { + throw new ServerException(_m('Unimplemented method')); + } } diff --git a/src/Entity/Note.php b/src/Entity/Note.php index b252a34fb2..9ccf439a44 100644 --- a/src/Entity/Note.php +++ b/src/Entity/Note.php @@ -262,6 +262,14 @@ class Note extends Entity [], ['id' => $this->id])); } + public function jsonSerialize() + { + return [ + 'content' => $this->getContent(), + 'author' => $this->getGSActorId(), + ]; + } + public static function schemaDef(): array { return [