Skip to content

Commit 1b12632

Browse files
committed
Refactor relationship name guessing to a dedicated method
1 parent 3b16d26 commit 1b12632

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/Concerns/HasRelations.php

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ trait HasRelations
3131
*/
3232
public function hasOne(string $itemClass, string $name = null): OneRelationInterface
3333
{
34-
$name = $name ?: Util::stringSnake(debug_backtrace()[1]['function']);
34+
$name = $name ?: $this->guessRelationName();
3535

3636
if (!array_key_exists($name, $this->relations)) {
3737
$this->relations[$name] = $this->newHasOne((new $itemClass())->getType());
@@ -55,7 +55,7 @@ protected function newHasOne(string $type): OneRelationInterface
5555
*/
5656
public function hasMany(string $itemClass, string $name = null): ManyRelationInterface
5757
{
58-
$name = $name ?: Util::stringSnake(debug_backtrace()[1]['function']);
58+
$name = $name ?: $this->guessRelationName();
5959

6060
if (!array_key_exists($name, $this->relations)) {
6161
$this->relations[$name] = $this->newHasMany((new $itemClass())->getType());
@@ -78,7 +78,7 @@ protected function newHasMany(string $type): ManyRelationInterface
7878
*/
7979
public function morphTo(string $name = null): OneRelationInterface
8080
{
81-
$name = $name ?: Util::stringSnake(debug_backtrace()[1]['function']);
81+
$name = $name ?: $this->guessRelationName();
8282

8383
if (!array_key_exists($name, $this->relations)) {
8484
$this->relations[$name] = $this->newMorphTo();
@@ -101,7 +101,7 @@ protected function newMorphTo(): OneRelationInterface
101101
*/
102102
public function morphToMany(string $name = null): ManyRelationInterface
103103
{
104-
$name = $name ?: Util::stringSnake(debug_backtrace()[1]['function']);
104+
$name = $name ?: $this->guessRelationName();
105105

106106
if (!array_key_exists($name, $this->relations)) {
107107
$this->relations[$name] = $this->newMorphToMany();
@@ -115,6 +115,18 @@ protected function newMorphToMany(): ManyRelationInterface
115115
return new MorphToManyRelation();
116116
}
117117

118+
/**
119+
* Guess the relationship name.
120+
*
121+
* @return string
122+
*/
123+
protected function guessRelationName(): string
124+
{
125+
[$one, $two, $caller] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
126+
127+
return Util::stringSnake($caller['function']);
128+
}
129+
118130
/**
119131
* @return \Swis\JsonApi\Client\Interfaces\OneRelationInterface[]|\Swis\JsonApi\Client\Interfaces\ManyRelationInterface[]
120132
*/

0 commit comments

Comments
 (0)