Parcourir la source

Merge pull request #581 from mpociot/plugin-fixes-improvements

Plugin fixes and other improvements
Shalvah il y a 5 ans
Parent
commit
083281d95c

+ 5 - 1
docs/plugins.md

@@ -8,7 +8,11 @@ Route processing is performed in four stages:
 - queryParameters
 - responses
 
-For each stage, the Generator attempts one or more configured strategies to fetch data. The Generator will call of the strategies configured, progressively combining their results together before to produce the final output of that stage.
+For each stage, the Generator attempts the specified strategies to fetch data. The Generator will call of the strategies configured, progressively combining their results together before to produce the final output of that stage.
+
+There are a number of strategies inccluded with the package, so you don't have to set up anything to get it working.
+
+> Note: The included ResponseCalls strategy is designed to stop if a response has already been gotten from any other strategy.
 
 ## Strategies
 To create a strategy, create a class that extends `\Mpociot\ApiDoc\Strategies\Strategy`.

+ 2 - 1
src/Strategies/Responses/ResponseCalls.php

@@ -43,7 +43,8 @@ class ResponseCalls extends Strategy
         $request = $this->prepareRequest($route, $rulesToApply, $bodyParameters, $queryParameters);
 
         try {
-            $response = [200 => $this->makeApiCall($request)->getContent()];
+            $response = $this->makeApiCall($request);
+            $response = [$response->getStatusCode() => $response->getContent()];
         } catch (\Exception $e) {
             echo 'Exception thrown during response call for ['.implode(',', $route->methods)."] {$route->uri}.\n";
             if (Flags::$shouldBeVerbose) {

+ 10 - 5
src/Strategies/Responses/UseTransformerTags.php

@@ -54,7 +54,7 @@ class UseTransformerTags extends Strategy
                 return null;
             }
 
-            $transformer = $this->getTransformerClass($transformerTag);
+            list($statusCode, $transformer) = $this->getStatusCodeAmdTransformerClass($transformerTag);
             $model = $this->getClassToBeTransformed($tags, (new ReflectionClass($transformer))->getMethod('transform'));
             $modelInstance = $this->instantiateTransformerModel($model);
 
@@ -68,7 +68,7 @@ class UseTransformerTags extends Strategy
                 ? new Collection([$modelInstance, $modelInstance], new $transformer)
                 : new Item($modelInstance, new $transformer);
 
-            return [200 => response($fractal->createData($resource)->toJson())->getContent()];
+            return [$statusCode => response($fractal->createData($resource)->toJson())->getContent()];
         } catch (\Exception $e) {
             return null;
         }
@@ -77,11 +77,16 @@ class UseTransformerTags extends Strategy
     /**
      * @param Tag $tag
      *
-     * @return string|null
+     * @return array
      */
-    private function getTransformerClass($tag)
+    private function getStatusCodeAmdTransformerClass($tag): array
     {
-        return $tag->getContent();
+        $content = $tag->getContent();
+        preg_match('/^(\d{3})?\s?([\s\S]*)$/', $content, $result);
+        $status = $result[1] ?: 200;
+        $transformerClass = $result[2];
+
+        return [$status, $transformerClass];
     }
 
     /**

+ 20 - 1
src/Tools/Generator.php

@@ -120,7 +120,26 @@ class Generator
 
     protected function iterateThroughStrategies(string $stage, array $context, array $arguments)
     {
-        $strategies = $this->config->get("strategies.$stage", []);
+        $defaultStrategies = [
+            'metadata' => [
+                \Mpociot\ApiDoc\Strategies\Metadata\GetFromDocBlocks::class,
+            ],
+            'bodyParameters' => [
+                \Mpociot\ApiDoc\Strategies\BodyParameters\GetFromBodyParamTag::class,
+            ],
+            'queryParameters' => [
+                \Mpociot\ApiDoc\Strategies\QueryParameters\GetFromQueryParamTag::class,
+            ],
+            'responses' => [
+                \Mpociot\ApiDoc\Strategies\Responses\UseResponseTag::class,
+                \Mpociot\ApiDoc\Strategies\Responses\UseResponseFileTag::class,
+                \Mpociot\ApiDoc\Strategies\Responses\UseTransformerTags::class,
+                \Mpociot\ApiDoc\Strategies\Responses\ResponseCalls::class,
+            ],
+        ];
+
+        // Use the default strategies for the stage, unless they were explicitly set
+        $strategies = $this->config->get("strategies.$stage", $defaultStrategies[$stage]);
         $context[$stage] = $context[$stage] ?? [];
         foreach ($strategies as $strategyClass) {
             $strategy = new $strategyClass($stage, $this->config);

+ 8 - 0
tests/Fixtures/TestController.php

@@ -251,6 +251,14 @@ class TestController extends Controller
         return '';
     }
 
+    /**
+     * @transformer 201 \Mpociot\ApiDoc\Tests\Fixtures\TestTransformer
+     */
+    public function transformerTagWithStatusCode()
+    {
+        return '';
+    }
+
     /**
      * @transformer \Mpociot\ApiDoc\Tests\Fixtures\TestTransformer
      * @transformermodel \Mpociot\ApiDoc\Tests\Fixtures\TestModel

+ 20 - 2
tests/Unit/GeneratorTestCase.php

@@ -435,8 +435,26 @@ abstract class GeneratorTestCase extends TestCase
         $this->assertTrue(is_array($response));
         $this->assertEquals(200, $response['status']);
         $this->assertSame(
-            $response['content'],
-            '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}'
+            '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}',
+            $response['content']
+        );
+    }
+
+    /** @test */
+    public function can_parse_transformer_tag_with_status_code()
+    {
+        $route = $this->createRoute('GET', '/transformerTagWithStatusCode', 'transformerTagWithStatusCode');
+        $parsed = $this->generator->processRoute($route);
+        $response = Arr::first($parsed['response']);
+
+        $this->assertTrue(is_array($parsed));
+        $this->assertArrayHasKey('showresponse', $parsed);
+        $this->assertTrue($parsed['showresponse']);
+        $this->assertTrue(is_array($response));
+        $this->assertEquals(201, $response['status']);
+        $this->assertSame(
+            '{"data":{"id":1,"description":"Welcome on this test versions","name":"TestName"}}',
+            $response['content']
         );
     }