24
24
use Illuminate \Database \Eloquent \Relations \MorphOne as EloquentMorphOne ;
25
25
use LaravelJsonApi \Eloquent \Contracts \FillableToOne ;
26
26
use LaravelJsonApi \Eloquent \Fields \Concerns \IsReadOnly ;
27
- use LogicException ;
28
27
29
28
class HasOne extends ToOne implements FillableToOne
30
29
{
31
-
30
+ /** @var int */
32
31
private const KEEP_DETACHED_MODEL = 0 ;
32
+
33
+ /** @var int */
33
34
private const DELETE_DETACHED_MODEL = 1 ;
35
+
36
+ /** @var int */
34
37
private const FORCE_DELETE_DETACHED_MODEL = 2 ;
35
38
36
39
use IsReadOnly;
@@ -103,14 +106,24 @@ public function mustExist(): bool
103
106
*/
104
107
public function fill (Model $ model , ?array $ identifier ): void
105
108
{
106
- $ relation = $ model ->{ $ this ->relationName ()} ();
109
+ $ name = $ this ->relationName ();
107
110
108
- if (!$ relation instanceof EloquentHasOne && !$ relation instanceof EloquentMorphOne) {
109
- throw new LogicException ('Expecting an Eloquent has-one or morph-one relation. ' );
110
- }
111
+ assert (method_exists ($ model , $ name ), sprintf (
112
+ 'Expecting method %s to exist on model %s. ' ,
113
+ $ name ,
114
+ $ model ::class,
115
+ ));
116
+
117
+ $ relation = $ model ->{$ name }();
118
+
119
+ assert ($ relation instanceof EloquentHasOne || $ relation instanceof EloquentMorphOne, sprintf (
120
+ 'Expecting method %s on model %s to return a belongs-to-many relation. ' ,
121
+ $ name ,
122
+ $ model ::class,
123
+ ));
111
124
112
125
/** @var Model|null $current */
113
- $ current = $ model ->{$ this -> relationName () };
126
+ $ current = $ model ->{$ name };
114
127
$ related = $ this ->find ($ identifier );
115
128
116
129
if ($ this ->willChange ($ current , $ related )) {
@@ -150,7 +163,7 @@ private function willChange(?Model $current, ?Model $new): bool
150
163
* @param EloquentMorphOne|EloquentHasOne $relation
151
164
* @param Model $current
152
165
*/
153
- private function disassociate ($ relation , Model $ current ): void
166
+ private function disassociate (EloquentMorphOne | EloquentHasOne $ relation , Model $ current ): void
154
167
{
155
168
if (self ::KEEP_DETACHED_MODEL === $ this ->detachMode ) {
156
169
$ this ->setInverseToNull ($ relation , $ current );
@@ -163,11 +176,11 @@ private function disassociate($relation, Model $current): void
163
176
/**
164
177
* Disassociate the related model by setting the relationship column(s) to `null`.
165
178
*
166
- * @param $relation
179
+ * @param EloquentMorphOne|EloquentHasOne $relation
167
180
* @param Model $current
168
181
* @return void
169
182
*/
170
- private function setInverseToNull ($ relation , Model $ current ): void
183
+ private function setInverseToNull (EloquentMorphOne | EloquentHasOne $ relation , Model $ current ): void
171
184
{
172
185
if ($ relation instanceof EloquentMorphOne) {
173
186
$ current ->setAttribute ($ relation ->getMorphType (), null );
0 commit comments