-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHasDocuments.php
64 lines (53 loc) · 1.53 KB
/
HasDocuments.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
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\Relation;
trait HasDocuments
{
public function owns(Document $document): bool
{
$owner = $document->owner;
if ($owner == null) {
return false;
}
return $owner->id == $this->id;
}
/**
* Convenience method for getting the relation associated with the given
* DocumentType.
*/
public function relationFor(DocumentCategory $category): ?Relation
{
if ($category == DocumentCategory::PassportCopy) {
return $this->passport();
}
return null;
}
/**
* Returns the first document matching the category or null if no such
* Document can be found.
*/
public function documentBy(DocumentCategory $category): Document
{
$preExisting = $this->documents()->whereCategory($category)->first();
if ($preExisting != null) {
return $preExisting;
}
$newlyCreated = new Document([
'category' => $category->value,
'type' => Document::TYPE_DIGITAL,
'state' => DocumentState::Missing,
'name' => $category->displayName(),
'owner_id' => $this->id,
]);
$this->documents()->save($newlyCreated);
return $newlyCreated;
}
/**
* @return HasMany<Document>
*/
public function documents(): HasMany
{
return $this->hasMany(Document::class, 'owner_id');
}
}