Skip to content

Commit a5a52ee

Browse files
committed
Extract new relationship instantiation to dedicated methods
This allows you to more easily use your own relationship classes.
1 parent 7227530 commit a5a52ee

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

src/Concerns/HasRelations.php

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,17 @@ public function hasOne(string $itemClass, string $name = null): OneRelationInter
3434
$name = $name ?: Util::stringSnake(debug_backtrace()[1]['function']);
3535

3636
if (!array_key_exists($name, $this->relations)) {
37-
$this->relations[$name] = new HasOneRelation((new $itemClass())->getType());
37+
$this->relations[$name] = $this->newHasOne((new $itemClass())->getType());
3838
}
3939

4040
return $this->relations[$name];
4141
}
4242

43+
protected function newHasOne(string $type): OneRelationInterface
44+
{
45+
return new HasOneRelation($type);
46+
}
47+
4348
/**
4449
* Create a plural relation to another item.
4550
*
@@ -53,12 +58,17 @@ public function hasMany(string $itemClass, string $name = null): ManyRelationInt
5358
$name = $name ?: Util::stringSnake(debug_backtrace()[1]['function']);
5459

5560
if (!array_key_exists($name, $this->relations)) {
56-
$this->relations[$name] = new HasManyRelation((new $itemClass())->getType());
61+
$this->relations[$name] = $this->newHasMany((new $itemClass())->getType());
5762
}
5863

5964
return $this->relations[$name];
6065
}
6166

67+
protected function newHasMany(string $type): ManyRelationInterface
68+
{
69+
return new HasManyRelation($type);
70+
}
71+
6272
/**
6373
* Create a singular relation.
6474
*
@@ -71,12 +81,17 @@ public function morphTo(string $name = null): OneRelationInterface
7181
$name = $name ?: Util::stringSnake(debug_backtrace()[1]['function']);
7282

7383
if (!array_key_exists($name, $this->relations)) {
74-
$this->relations[$name] = new MorphToRelation();
84+
$this->relations[$name] = $this->newMorphTo();
7585
}
7686

7787
return $this->relations[$name];
7888
}
7989

90+
protected function newMorphTo(): OneRelationInterface
91+
{
92+
return new MorphToRelation();
93+
}
94+
8095
/**
8196
* Create a plural relation.
8297
*
@@ -89,12 +104,17 @@ public function morphToMany(string $name = null): ManyRelationInterface
89104
$name = $name ?: Util::stringSnake(debug_backtrace()[1]['function']);
90105

91106
if (!array_key_exists($name, $this->relations)) {
92-
$this->relations[$name] = new MorphToManyRelation();
107+
$this->relations[$name] = $this->newMorphToMany();
93108
}
94109

95110
return $this->relations[$name];
96111
}
97112

113+
protected function newMorphToMany(): ManyRelationInterface
114+
{
115+
return new MorphToManyRelation();
116+
}
117+
98118
/**
99119
* @return \Swis\JsonApi\Client\Interfaces\OneRelationInterface[]|\Swis\JsonApi\Client\Interfaces\ManyRelationInterface[]
100120
*/

0 commit comments

Comments
 (0)