Browse Source

Standardise Override strategy

Shalvah 3 months ago
parent
commit
407c31c562

+ 1 - 1
config/scribe.php

@@ -37,7 +37,7 @@ return Config\Factory::make(
             metadata: Config\Defaults::METADATA_STRATEGIES,
             urlParameters: Config\Defaults::URL_PARAMETERS_STRATEGIES,
             queryParameters: Config\Defaults::QUERY_PARAMETERS_STRATEGIES,
-            headers: overrideResults(Config\Defaults::HEADERS_STRATEGIES, [
+            headers: overrideResults(Config\Defaults::HEADERS_STRATEGIES, with: [
                 'Content-Type' => 'application/json',
                 'Accept' => 'application/json',
             ]),

+ 10 - 2
src/Config/strategies.php

@@ -3,14 +3,22 @@
 namespace Knuckles\Scribe\Config;
 
 use Illuminate\Support\Arr;
+use Knuckles\Scribe\Extracting\Strategies\Strategy;
 
 // Strategies can be:
 // 1. (Original) A class name, e.g. Strategies\Responses\ResponseCalls::class
 // 2. (New) A tuple containing the class name as item 1, and its config array as item 2
 // 3. (New) A tuple containing "override" as item 1, and the values to override array as item 2
-function overrideResults(array $strategies, array $valuesToOverride): array
+/**
+ * @param array $strategies
+ * @param array $with
+ * @param array $only The routes that should be overridden. Same format as the route matcher.
+ * @param array $except The routes that should not be overridden. Same format as the route matcher.
+ * @return array
+ */
+function overrideResults(array $strategies, array $with, array $only = ['*'], array $except = []): array
 {
-    $overrideStrategy = ['override', $valuesToOverride];
+    $overrideStrategy = Strategy::wrapWithSettings('override', only: $only, except: $except, otherSettings: ['with' => $with]);
     return addStrategies($strategies, [$overrideStrategy]);
 }
 

+ 13 - 0
src/Extracting/Strategies/Override.php

@@ -0,0 +1,13 @@
+<?php
+
+namespace Knuckles\Scribe\Extracting\Strategies;
+
+use Knuckles\Camel\Extraction\ExtractedEndpointData;
+
+class Override extends Strategy
+{
+    public function __invoke(ExtractedEndpointData $endpointData, array $settings = []): ?array
+    {
+        return $settings['with'];
+    }
+}

+ 8 - 1
src/Extracting/Strategies/Responses/ResponseCalls.php

@@ -312,6 +312,13 @@ class ResponseCalls extends Strategy
         array $cookies = [],
     ): array
     {
-        return static::wrapWithSettings(...get_defined_vars());
+        return static::wrapWithSettings(
+            static::class, only: $only, except: $except, otherSettings: compact(
+            'config',
+            'queryParams',
+            'bodyParams',
+            'fileParams',
+            'cookies',
+        ));
     }
 }

+ 3 - 2
src/Extracting/Strategies/Strategy.php

@@ -42,9 +42,10 @@ abstract class Strategy
      * @return array{string,array} Tuple of strategy class FQN and specified settings.
      */
     public static function wrapWithSettings(
+        string $strategyName = self::class,
         array $only = ['*'],
         array $except = [],
-        ...$otherSettings
+        array $otherSettings = []
     ): array
     {
         if (!empty($only) && !empty($except)) {
@@ -54,7 +55,7 @@ abstract class Strategy
         }
 
         return [
-            static::class,
+            $strategyName,
             ['only' => $only, 'except' => $except, ...$otherSettings],
         ];
     }

+ 2 - 5
tests/GenerateDocumentation/OutputTest.php

@@ -522,8 +522,7 @@ class OutputTest extends BaseLaravelTest
     /** @test */
     public function generates_correct_url_params_from_non_resource_routes_and_model_binding()
     {
-        RouteFacade::get('posts/{post}/users', function (TestPost $post) {
-        });
+        RouteFacade::get('posts/{post}/users', fn (TestPost $post) => null);
 
         $this->generate();
 
@@ -537,9 +536,7 @@ class OutputTest extends BaseLaravelTest
         $this->setConfig(['routes.0.exclude' => ['*']]);
         Utils::copyDirectory(__DIR__ . '/../Fixtures/.scribe', '.scribe');
 
-        $output = $this->generate(['--no-extraction' => true]);
-
-        $this->assertStringNotContainsString("Processing route", $output);
+        $this->generateAndExpectConsoleOutput(['--no-extraction' => true], notExpected: ["Processing route"]);
 
         $crawler = new Crawler(file_get_contents($this->htmlOutputPath()));
         [$intro, $auth] = $crawler->filter('h1 + p')->getIterator();

+ 28 - 16
tests/Unit/ExtractorTest.php

@@ -169,21 +169,6 @@ class ExtractorTest extends BaseLaravelTest
         $this->assertEquals(['DELETE'], $parsed->httpMethods);
     }
 
-    /** @test */
-    public function invokes_strategy_based_on_deprecated_route_apply_rules()
-    {
-        $this->config['strategies']['responses'] = [Strategies\Responses\ResponseCalls::class];
-
-        $route = $this->createRoute('GET', '/get', 'shouldFetchRouteResponse');
-        $extractor = $this->makeExtractor();
-        // Use the old routeApply rules rather than new settings
-        $parsed = $extractor->processRoute($route, ['response_calls' => ['methods' => ['POST']]]);
-        $this->assertEmpty($parsed->responses);
-
-        $parsed = $extractor->processRoute($route, ['response_calls' => ['methods' => ['GET']]]);
-        $this->assertNotEmpty($parsed->responses);
-    }
-
     /** @test */
     public function invokes_strategy_based_on_new_strategy_configs()
     {
@@ -208,7 +193,7 @@ class ExtractorTest extends BaseLaravelTest
     }
 
     /** @test */
-    public function adds_override_for_headers_based_on_strategy_configs()
+    public function overrides_headers_based_on_short_strategy_config()
     {
         $route = $this->createRoute('GET', '/get', 'dummy');
         $this->config['strategies']['headers'] = [Strategies\Headers\GetFromHeaderAttribute::class];
@@ -229,6 +214,33 @@ class ExtractorTest extends BaseLaravelTest
         $this->assertArraySubset($parsed->headers, $headers);
     }
 
+    /** @test */
+    public function overrides_headers_based_on_extended_strategy_config()
+    {
+        $route = $this->createRoute('GET', '/get', 'dummy');
+        $this->config['strategies']['headers'] = [Strategies\Headers\GetFromHeaderAttribute::class];
+        $parsed = $this->process($route);
+        $this->assertEmpty($parsed->headers);
+
+        $headers = [
+            'accept' => 'application/json',
+            'Content-Type' => 'application/json+vnd',
+        ];
+        $this->config['strategies']['headers'] = [
+            Strategies\Headers\GetFromHeaderAttribute::class,
+            ['override', ['with' => $headers, 'only' => ['GET *']]],
+        ];
+        $parsed = $this->process($route);
+        $this->assertArraySubset($parsed->headers, $headers);
+
+        $this->config['strategies']['headers'] = [
+            Strategies\Headers\GetFromHeaderAttribute::class,
+            ['override', ['with' => $headers, 'only' => [], 'except' => ['GET *']]],
+        ];
+        $parsed = $this->process($route);
+        $this->assertEmpty($parsed->headers);
+    }
+
     /**
      * @test
      * @dataProvider authRules