Skip to content

Commit

Permalink
Add super method
Browse files Browse the repository at this point in the history
  • Loading branch information
MGatner committed Mar 10, 2022
1 parent 8cc9acf commit 2e23ad7
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -256,3 +256,4 @@ This library also comes with its own Firestore `Entity` that handles Google's ti
conversions and these methods to access metadata about the underlying Firestore document:
* `document(?DocumentReference $document = null): ?DocumentReference` *Gets or sets the document*
* `id(): string`
* `super(): ?DocumentReference` *Gets an Entity's parent Entity, if it is from a subcollection*
15 changes: 15 additions & 0 deletions src/Firestore/Entity.php
Expand Up @@ -7,6 +7,7 @@
use DateTime;
use Google\Cloud\Core\Timestamp;
use Google\Cloud\Firestore\DocumentReference;
use UnexpectedValueException;

class Entity extends FrameworkEntity
{
Expand Down Expand Up @@ -46,6 +47,20 @@ final public function document(?DocumentReference $document = null): ?DocumentRe
return $this->document;
}

/**
* Returns the next higher DocumentReference for nested objects,
* or null if not part of a subcollection.
*/
public function super(): ?DocumentReference
{
if (null === $reference = $this->document()) {
throw new UnexpectedValueException('Entity must exist before accessing parent.');
}

// The parent is the subcollection, its parent (if it exists) is a document
return $reference->parent()->parent();
}

/**
* Converts the given item into a Time object.
* Adds support for Google's Timestamp
Expand Down
31 changes: 31 additions & 0 deletions tests/firestore/EntityTest.php
Expand Up @@ -2,6 +2,8 @@

use CodeIgniter\I18n\Time;
use Google\Cloud\Core\Timestamp;
use Google\Cloud\Firestore\DocumentReference;
use Tests\Support\Collections\FruitCollection;
use Tests\Support\FirestoreTestCase;

/**
Expand Down Expand Up @@ -55,4 +57,33 @@ public function testMutateDateSupportsNull()

$this->assertNull($result);
}

public function testSuperRequiresDocument()
{
$fruit = $this->collection->fake();

$this->expectException('UnexpectedValueException');
$this->expectExceptionMessage('Entity must exist before accessing parent.');

$this->assertNull($fruit->super());
}

public function testSuperIsNull()
{
$fruit = $this->collection->make();

$this->assertNull($fruit->super());
}

public function testSuperReturnsCollectionDocumentParent()
{
$fruit = $this->collection->make();
$foods = collection(FruitCollection::class, $fruit);
$food = $foods->add(['name' => 'food']);

$result = $food->super();

$this->assertInstanceOf(DocumentReference::class, $result);
$this->assertSame($fruit->id(), $result->id());
}
}

0 comments on commit 2e23ad7

Please sign in to comment.