Browse Source

feat: add afterResponseCall hook (#847)

* feat: add after response hook

* fix(runPostRequestHook): avoid forcing using JsonResponse

* fix(runPostRequestHook): cleaning
max13fr 11 months ago
parent
commit
eb179c6f3f
3 changed files with 25 additions and 2 deletions
  1. 12 2
      src/Extracting/Strategies/Responses/ResponseCalls.php
  2. 11 0
      src/Scribe.php
  3. 2 0
      src/Tools/Globals.php

+ 12 - 2
src/Extracting/Strategies/Responses/ResponseCalls.php

@@ -2,8 +2,6 @@
 
 namespace Knuckles\Scribe\Extracting\Strategies\Responses;
 
-use Illuminate\Support\Facades\Config;
-use Knuckles\Camel\Extraction\ExtractedEndpointData;
 use Dingo\Api\Dispatcher;
 use Dingo\Api\Routing\Route as DingoRoute;
 use Exception;
@@ -12,7 +10,9 @@ use Illuminate\Http\Request;
 use Illuminate\Http\Response;
 use Illuminate\Http\UploadedFile;
 use Illuminate\Routing\Route;
+use Illuminate\Support\Facades\Config;
 use Illuminate\Support\Str;
+use Knuckles\Camel\Extraction\ExtractedEndpointData;
 use Knuckles\Scribe\Extracting\DatabaseTransactionHelpers;
 use Knuckles\Scribe\Extracting\ParamHelpers;
 use Knuckles\Scribe\Extracting\Strategies\Strategy;
@@ -89,6 +89,9 @@ class ResponseCalls extends Strategy
 
         try {
             $response = $this->makeApiCall($request, $endpointData->route);
+
+            $this->runPostRequestHook($request, $endpointData, $response);
+
             $response = [
                 [
                     'status' => $response->getStatusCode(),
@@ -170,6 +173,13 @@ class ResponseCalls extends Strategy
         }
     }
 
+    protected function runPostRequestHook(Request $request, ExtractedEndpointData $endpointData, mixed $response): void
+    {
+        if (is_callable(Globals::$__afterResponseCall)) {
+            call_user_func_array(Globals::$__afterResponseCall, [$request, $endpointData, $response]);
+        }
+    }
+
     private function setLaravelConfigs(array $config)
     {
         if (empty($config)) {

+ 11 - 0
src/Scribe.php

@@ -22,6 +22,17 @@ class Scribe
         Globals::$__beforeResponseCall = $callable;
     }
 
+    /**
+     * Specify a callback that will be executed just after a response call is done
+     * (allowing to modify the response).
+     *
+     * @param callable(Request, ExtractedEndpointData, mixed): mixed $callable
+     */
+    public static function afterResponseCall(callable $callable)
+    {
+        Globals::$__afterResponseCall = $callable;
+    }
+
     /**
      * Specify a callback that will be executed just before the generate command is executed
      *

+ 2 - 0
src/Tools/Globals.php

@@ -12,6 +12,8 @@ class Globals
 
     public static $__beforeResponseCall;
 
+    public static $__afterResponseCall;
+
     public static $__bootstrap;
 
     public static $__afterGenerating;