From e6aaef43cdd0292bce16909a07908a822588570b Mon Sep 17 00:00:00 2001 From: Steven Nguyen Date: Wed, 12 Jul 2023 16:50:40 -0700 Subject: [PATCH] Add method to Document to set multiple attributes This makes it easier and quicker to update several attributes on a document from a different document. --- src/Database/Document.php | 17 ++++++++++++++++- tests/Database/DocumentTest.php | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/Database/Document.php b/src/Database/Document.php index 93416243f..f53f5a9da 100644 --- a/src/Database/Document.php +++ b/src/Database/Document.php @@ -216,7 +216,7 @@ public function getAttribute(string $name, mixed $default = null): mixed * * @return self */ - public function setAttribute(string $key, $value, string $type = self::SET_TYPE_ASSIGN): self + public function setAttribute(string $key, mixed $value, string $type = self::SET_TYPE_ASSIGN): self { switch ($type) { case self::SET_TYPE_ASSIGN: @@ -235,6 +235,21 @@ public function setAttribute(string $key, $value, string $type = self::SET_TYPE_ return $this; } + /** + * Set Attributes. + * + * @param array $attributes + * @return self + */ + public function setAttributes(array $attributes): self + { + foreach ($attributes as $key => $value) { + $this->setAttribute($key, $value); + } + + return $this; + } + /** * Remove Attribute. * diff --git a/tests/Database/DocumentTest.php b/tests/Database/DocumentTest.php index 81e180fcc..8acb95096 100644 --- a/tests/Database/DocumentTest.php +++ b/tests/Database/DocumentTest.php @@ -175,6 +175,30 @@ public function testSetAttribute(): void $this->assertEquals(['one'], $this->document->getAttribute('list', [])); } + public function testSetAttributes(): void + { + $document = new Document(['$id' => ID::custom(''), '$collection' => 'users']); + + $otherDocument = new Document([ + '$id' => ID::custom('new'), + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::user('new')), + Permission::delete(Role::user('new')), + ], + 'email' => 'joe@example.com', + 'prefs' => new \stdClass(), + ]); + + $document->setAttributes($otherDocument->getArrayCopy()); + + $this->assertEquals($otherDocument->getId(), $document->getId()); + $this->assertEquals('users', $document->getCollection()); + $this->assertEquals($otherDocument->getPermissions(), $document->getPermissions()); + $this->assertEquals($otherDocument->getAttribute('email'), $document->getAttribute('email')); + $this->assertEquals($otherDocument->getAttribute('prefs'), $document->getAttribute('prefs')); + } + public function testRemoveAttribute(): void { $this->document->removeAttribute('list');