1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Umbrellio\LTree\Traits; |
6
|
|
|
|
7
|
|
|
use Illuminate\Database\Eloquent\Concerns\HasRelationships; |
8
|
|
|
use Illuminate\Database\Eloquent\Model; |
9
|
|
|
use Umbrellio\LTree\Exceptions\InvalidTraitInjectionClass; |
10
|
|
|
use Umbrellio\LTree\Interfaces\LTreeModelInterface; |
11
|
|
|
use Umbrellio\LTree\Relations\AbstractBelongsToTree; |
12
|
|
|
use Umbrellio\LTree\Relations\BelongsToAncestorsTree; |
13
|
|
|
use Umbrellio\LTree\Relations\BelongsToDescendantsTree; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @mixin HasRelationships |
17
|
|
|
* @mixin LTreeModelTrait |
18
|
|
|
* @mixin Model |
19
|
|
|
*/ |
20
|
|
|
trait HasTreeRelationships |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* @throws InvalidTraitInjectionClass |
24
|
|
|
*/ |
25
|
3 |
|
final protected function belongsToAncestorsTree( |
26
|
|
|
string $related, |
27
|
|
|
string $throwRelation, |
28
|
|
|
?string $foreignKey = null, |
29
|
|
|
$ownerKey = null |
30
|
|
|
) { |
31
|
3 |
|
return $this->belongsToTree(BelongsToAncestorsTree::class, $related, $throwRelation, $foreignKey, $ownerKey); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @throws InvalidTraitInjectionClass |
36
|
|
|
*/ |
37
|
1 |
|
final protected function belongsToDescendantsTree( |
38
|
|
|
string $related, |
39
|
|
|
string $throwRelation, |
40
|
|
|
?string $foreignKey = null, |
41
|
|
|
$ownerKey = null |
42
|
|
|
) { |
43
|
1 |
|
return $this->belongsToTree( |
44
|
1 |
|
BelongsToDescendantsTree::class, |
45
|
|
|
$related, |
46
|
|
|
$throwRelation, |
47
|
|
|
$foreignKey, |
48
|
|
|
$ownerKey |
49
|
|
|
); |
50
|
|
|
} |
51
|
|
|
|
52
|
4 |
|
final private function belongsToTree( |
53
|
|
|
string $relationClass, |
54
|
|
|
string $related, |
55
|
|
|
string $throwRelation, |
56
|
|
|
?string $foreignKey = null, |
57
|
|
|
$ownerKey = null |
58
|
|
|
): AbstractBelongsToTree { |
59
|
4 |
|
$instance = $this->newRelatedInstance($related); |
|
|
|
|
60
|
|
|
|
61
|
4 |
|
if (!$instance instanceof LTreeModelInterface) { |
62
|
1 |
|
throw new InvalidTraitInjectionClass(sprintf( |
63
|
1 |
|
'A class using this trait must implement an interface %s', |
64
|
1 |
|
LTreeModelInterface::class |
65
|
|
|
)); |
66
|
|
|
} |
67
|
|
|
|
68
|
3 |
|
if ($foreignKey === null) { |
69
|
|
|
$foreignKey = $this |
70
|
3 |
|
->{$throwRelation}() |
71
|
3 |
|
->getForeignKeyName(); |
72
|
|
|
} |
73
|
|
|
|
74
|
3 |
|
$ownerKey = $ownerKey ?: $instance->getKeyName(); |
75
|
|
|
|
76
|
3 |
|
return new $relationClass($instance->newQuery(), $this, $throwRelation, $foreignKey, $ownerKey); |
|
|
|
|
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|