@@ -31,7 +31,7 @@ trait HasRelations
31
31
*/
32
32
public function hasOne (string $ itemClass , string $ name = null ): OneRelationInterface
33
33
{
34
- $ name = $ name ?: Util:: stringSnake ( debug_backtrace ()[ 1 ][ ' function ' ] );
34
+ $ name = $ name ?: $ this -> guessRelationName ( );
35
35
36
36
if (!array_key_exists ($ name , $ this ->relations )) {
37
37
$ this ->relations [$ name ] = $ this ->newHasOne ((new $ itemClass ())->getType ());
@@ -55,7 +55,7 @@ protected function newHasOne(string $type): OneRelationInterface
55
55
*/
56
56
public function hasMany (string $ itemClass , string $ name = null ): ManyRelationInterface
57
57
{
58
- $ name = $ name ?: Util:: stringSnake ( debug_backtrace ()[ 1 ][ ' function ' ] );
58
+ $ name = $ name ?: $ this -> guessRelationName ( );
59
59
60
60
if (!array_key_exists ($ name , $ this ->relations )) {
61
61
$ this ->relations [$ name ] = $ this ->newHasMany ((new $ itemClass ())->getType ());
@@ -78,7 +78,7 @@ protected function newHasMany(string $type): ManyRelationInterface
78
78
*/
79
79
public function morphTo (string $ name = null ): OneRelationInterface
80
80
{
81
- $ name = $ name ?: Util:: stringSnake ( debug_backtrace ()[ 1 ][ ' function ' ] );
81
+ $ name = $ name ?: $ this -> guessRelationName ( );
82
82
83
83
if (!array_key_exists ($ name , $ this ->relations )) {
84
84
$ this ->relations [$ name ] = $ this ->newMorphTo ();
@@ -101,7 +101,7 @@ protected function newMorphTo(): OneRelationInterface
101
101
*/
102
102
public function morphToMany (string $ name = null ): ManyRelationInterface
103
103
{
104
- $ name = $ name ?: Util:: stringSnake ( debug_backtrace ()[ 1 ][ ' function ' ] );
104
+ $ name = $ name ?: $ this -> guessRelationName ( );
105
105
106
106
if (!array_key_exists ($ name , $ this ->relations )) {
107
107
$ this ->relations [$ name ] = $ this ->newMorphToMany ();
@@ -115,6 +115,18 @@ protected function newMorphToMany(): ManyRelationInterface
115
115
return new MorphToManyRelation ();
116
116
}
117
117
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
+
118
130
/**
119
131
* @return \Swis\JsonApi\Client\Interfaces\OneRelationInterface[]|\Swis\JsonApi\Client\Interfaces\ManyRelationInterface[]
120
132
*/
0 commit comments