44
55use Binaryk \LaravelRestify \Http \Requests \RepositoryAttachRequest ;
66use Binaryk \LaravelRestify \Http \Requests \RestifyRequest ;
7+ use Binaryk \LaravelRestify \Repositories \Repository ;
78use DateTime ;
89use Illuminate \Support \Arr ;
10+ use Illuminate \Support \Str ;
911
1012class RepositoryAttachController extends RepositoryController
1113{
@@ -14,12 +16,16 @@ public function __invoke(RepositoryAttachRequest $request)
1416 $ model = $ request ->findModelOrFail ();
1517 $ repository = $ request ->repository ()->allowToUpdate ($ request );
1618
19+ if (is_callable ($ method = $ this ->guessMethodName ($ request , $ repository ))) {
20+ return call_user_func ($ method , $ request , $ repository , $ model );
21+ }
22+
1723 return $ repository ->attach (
1824 $ request , $ request ->repositoryId ,
1925 collect (Arr::wrap ($ request ->input ($ request ->relatedRepository )))
20- ->map (fn ($ relatedRepositoryId ) => $ this ->initializePivot (
21- $ request , $ model ->{$ request ->viaRelationship ?? $ request ->relatedRepository }(), $ relatedRepositoryId
22- ))
26+ ->map (fn ($ relatedRepositoryId ) => $ this ->initializePivot (
27+ $ request , $ model ->{$ request ->viaRelationship ?? $ request ->relatedRepository }(), $ relatedRepositoryId
28+ ))
2329 );
2430 }
2531
@@ -61,4 +67,21 @@ protected function initializePivot(RestifyRequest $request, $relationship, $rela
6167
6268 return $ pivot ;
6369 }
70+
71+ public function guessMethodName (RestifyRequest $ request , Repository $ repository ): ?callable
72+ {
73+ $ key = $ request ->relatedRepository ;
74+
75+ if (array_key_exists ($ key , $ repository ::getAttachers ()) && is_callable ($ cb = $ repository ::getAttachers ()[$ key ])) {
76+ return $ cb ;
77+ }
78+
79+ $ methodGuesser = 'attach ' .Str::studly ($ request ->relatedRepository );
80+
81+ if (method_exists ($ repository , $ methodGuesser )) {
82+ return [$ repository , $ methodGuesser ];
83+ }
84+
85+ return null ;
86+ }
6487}
0 commit comments