-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Entity.php
86 lines (73 loc) · 2.33 KB
/
Entity.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace Tatter\Firebase\Firestore;
use CodeIgniter\Entity\Entity as FrameworkEntity;
use CodeIgniter\I18n\Time;
use DateTime;
use Google\Cloud\Core\Timestamp;
use Google\Cloud\Firestore\DocumentReference;
use Google\Cloud\Firestore\FieldValue\ServerTimestampValue;
use UnexpectedValueException;
class Entity extends FrameworkEntity
{
protected $dates = [
'createdAt',
'updatedAt',
];
/**
* The originating Document from Firestore.
*/
private ?DocumentReference $document = null;
/**
* Returns the ID of the underlying document, if it exists.
*/
final public function id(): ?string
{
if ($document = $this->document()) {
return $document->id();
}
return $this->attributes['uid'] ?? null;
}
/**
* Gets or sets the originating document reference.
* Named to avoid attribute get/set magic methods.
*/
final public function document(?DocumentReference $document = null): ?DocumentReference
{
if ($document !== null) {
$this->document = $document;
$this->attributes['uid'] = $document->id();
}
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
*
* @param DateTime|int|string|Time|Timestamp|null $value
*/
protected function mutateDate($value): ?Time
{
if ($value instanceof Timestamp) {
// Convert to an int timestamp
$value = $value->formatForApi()['seconds'];
}
// If the document has not been created then a ServerTimestampValue
// may exist to indicated "current timestamp" which should be ignored.
if ($value instanceof ServerTimestampValue) {
return null;
}
return parent::mutateDate($value);
}
}