瀏覽代碼

Merge pull request #377 from shalvah/v3

Reimplement response calls
Shalvah A 6 年之前
父節點
當前提交
622b7c83eb

+ 13 - 4
README.md

@@ -200,8 +200,7 @@ They will be included in the generated documentation text and example requests.
 You can use the `@authenticated` annotation on a method to indicate if the endpoint is authenticated. A "Requires authentication" badge will be added to that route in the generated documentation.
 
 ### Providing an example response
-You can provide an example response for a route. This will be disaplyed in the examples section. There are several ways of doing this.
-
+You can provide an example response for a route. This will be displayed in the examples section. There are several ways of doing this.
 
 #### @response
 You can provide an example response for a route by using the `@response` annotation with valid JSON:
@@ -223,7 +222,7 @@ public function show($id)
 #### @transformer, @transformerCollection, and @transformerModel
 You can define the transformer that is used for the result of the route using the `@transformer` tag (or `@transformerCollection` if the route returns a list). The package will attempt to generate an instance of the model to be transformed using the following steps, stopping at the first successful one:
 
-1. Check if there is a `@transformerModel` tag to define the model being transformed. If there is none, use the class of the first parameter to the method.
+1. Check if there is a `@transformerModel` tag to define the model being transformed. If there is none, use the class of the first parameter to the transformer's `transform()` method.
 2. Get an instance of the model from the Eloquent model factory
 2. If the parameter is an Eloquent model, load the first from the database.
 3. Create an instance using `new`.
@@ -261,7 +260,17 @@ public function showUser(int $id)
 ```
 For the first route above, this package will generate a set of two users then pass it through the transformer. For the last two, it will generate a single user and then pass it through the transformer.
 
-#### Postman collections
+#### Gnerating responses automatically
+If you don't specify an example response using any of the above means, this package will attempt to get a sample response by making a request to the route (a "response call"). A few things to note about response calls:
+- They are done within a database transaction and changes are rolled back afterwards.
+- The configuration for response calls is located in the `config/apidoc.php`. They are configured within the `['apply']['response_calls']` section for each route group, allowing you to apply different settings for different sets of routes.
+- By default, response calls are only made for GET routes, but you can configure this. Set the `methods` key to an array of methods or '*' to mean all methods. Leave it as an empty array to turn off response calls for that route group.
+- Parameters in URLs (example: `/users/{user}`, `/orders/{id?}`) will be replaced with '1' by default. You can configure this, however.Put the parameter names (including curly braces and question marks) as the keys and their replacements as the values in the `bindings` key.
+- You can configure environment variables (this is useful so you can prevent external services like notifications from being triggered). By default the APP_ENV is set to 'documentation'. You can add more variables in the `env` key.
+- You can also configure what headers, query parameters and body parameters should be sent when making the request (the `headers`, `query`, and `body` keys respectively).
+
+
+### Postman collections
 
 The generator automatically creates a Postman collection file, which you can import to use within your [Postman app](https://www.getpostman.com/apps) for even simpler API testing and usage.
 

+ 56 - 0
config/apidoc.php

@@ -84,6 +84,62 @@ return [
                     // 'Authorization' => 'Bearer: {token}',
                     // 'Api-Version' => 'v2',
                 ],
+
+                /*
+                 * If no @response or @transformer declaratons are found for the route,
+                 * we'll try to get a sample response by attempting an API call.
+                 * Configure the settings for the API call here,
+                 */
+                'response_calls' => [
+                    /*
+                     * API calls will be made only for routes in this group matching these HTTP methods (GET, POST, etc).
+                     * List the methods here or use '*' to mean all methods. Leave empty to disable API calls.
+                     */
+                    'methods' => ['GET'],
+
+                    /*
+                     * For URLs which have parameters (/users/{user}, /orders/{id?}),
+                     * specify what values the parameters should be replaced with.
+                     * Note that you must specify the full parameter, including curly brackets and question marks if any.
+                     */
+                    'bindings' => [
+                        // '{user}' => 1
+                    ],
+
+                    /*
+                     * Environment variables which should be set for the API call.
+                     * This is a good place to ensure that notifications, emails
+                     * and other external services are not triggered during the documentation API calls
+                     */
+                    'env' => [
+                        'APP_ENV' => 'documentation',
+                        'APP_DEBUG' => false,
+                        // 'env_var' => 'value',
+                    ],
+
+                    /*
+                     * Headers which should be sent with the API call.
+                     */
+                    'headers' => [
+                        'Content-Type' => 'application/json',
+                        'Accept' => 'application/json',
+                        // 'key' => 'value',
+                    ],
+
+                    /*
+                     * Query parameters which should be sent with the API call.
+                     */
+                    'query' => [
+                        // 'key' => 'value',
+                    ],
+
+                    /*
+                     * Body parameters which should be sent with the API call.
+                     */
+                    'body' => [
+                        // 'key' => 'value',
+                    ],
+                ],
             ],
         ],
     ],

+ 7 - 10
src/Commands/GenerateDocumentation.php

@@ -8,11 +8,9 @@ use Illuminate\Console\Command;
 use Mpociot\Reflection\DocBlock;
 use Illuminate\Support\Collection;
 use Mpociot\ApiDoc\Tools\RouteMatcher;
+use Mpociot\ApiDoc\Generators\Generator;
 use Mpociot\Documentarian\Documentarian;
 use Mpociot\ApiDoc\Postman\CollectionWriter;
-use Mpociot\ApiDoc\Generators\DingoGenerator;
-use Mpociot\ApiDoc\Generators\LaravelGenerator;
-use Mpociot\ApiDoc\Generators\AbstractGenerator;
 
 class GenerateDocumentation extends Command
 {
@@ -47,15 +45,14 @@ class GenerateDocumentation extends Command
      */
     public function handle()
     {
-        $usingDIngoRouter = config('apidoc.router') == 'dingo';
-        if ($usingDIngoRouter) {
+        $usingDingoRouter = config('apidoc.router') == 'dingo';
+        if ($usingDingoRouter) {
             $routes = $this->routeMatcher->getDingoRoutesToBeDocumented(config('apidoc.routes'));
-            $generator = new DingoGenerator();
         } else {
             $routes = $this->routeMatcher->getLaravelRoutesToBeDocumented(config('apidoc.routes'));
-            $generator = new LaravelGenerator();
         }
 
+        $generator = new Generator();
         $parsedRoutes = $this->processRoutes($generator, $routes);
         $parsedRoutes = collect($parsedRoutes)->groupBy('group')
             ->sort(function ($a, $b) {
@@ -175,19 +172,19 @@ class GenerateDocumentation extends Command
     }
 
     /**
-     * @param AbstractGenerator $generator
+     * @param Generator $generator
      * @param array $routes
      *
      * @return array
      */
-    private function processRoutes(AbstractGenerator $generator, array $routes)
+    private function processRoutes(Generator $generator, array $routes)
     {
         $parsedRoutes = [];
         foreach ($routes as $routeItem) {
             $route = $routeItem['route'];
             /** @var Route $route */
             if ($this->isValidRoute($route) && $this->isRouteVisibleForDocumentation($route->getAction()['uses'])) {
-                $parsedRoutes[] = $generator->processRoute($route) + $routeItem['apply'];
+                $parsedRoutes[] = $generator->processRoute($route, $routeItem['apply']);
                 $this->info('Processed route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
             } else {
                 $this->warn('Skipping route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));

+ 0 - 466
src/Generators/AbstractGenerator.php

@@ -1,466 +0,0 @@
-<?php
-
-namespace Mpociot\ApiDoc\Generators;
-
-use Faker\Factory;
-use ReflectionClass;
-use Illuminate\Support\Str;
-use League\Fractal\Manager;
-use Illuminate\Routing\Route;
-use Mpociot\Reflection\DocBlock;
-use League\Fractal\Resource\Item;
-use Mpociot\Reflection\DocBlock\Tag;
-use League\Fractal\Resource\Collection;
-
-abstract class AbstractGenerator
-{
-    /**
-     * @param Route $route
-     *
-     * @return mixed
-     */
-    public function getDomain(Route $route)
-    {
-        return $route->domain() == null ? '*' : $route->domain();
-    }
-
-    /**
-     * @param Route $route
-     *
-     * @return mixed
-     */
-    public function getUri(Route $route)
-    {
-        return $route->uri();
-    }
-
-    /**
-     * @param Route $route
-     *
-     * @return mixed
-     */
-    public function getMethods(Route $route)
-    {
-        return array_diff($route->methods(), ['HEAD']);
-    }
-
-    /**
-     * @param  \Illuminate\Routing\Route $route
-     * @param array $apply Rules to apply when generating documentation for this route
-     *
-     * @return array
-     */
-    public function processRoute($route)
-    {
-        $routeAction = $route->getAction();
-        $routeGroup = $this->getRouteGroup($routeAction['uses']);
-        $docBlock = $this->parseDocBlock($routeAction['uses']);
-        $content = $this->getResponse($docBlock['tags']);
-
-        return [
-            'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
-            'group' => $routeGroup,
-            'title' => $docBlock['short'],
-            'description' => $docBlock['long'],
-            'methods' => $this->getMethods($route),
-            'uri' => $this->getUri($route),
-            'parameters' => $this->getParametersFromDocBlock($docBlock['tags']),
-            'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
-            'response' => $content,
-            'showresponse' => ! empty($content),
-        ];
-    }
-
-    /**
-     * Prepares / Disables route middlewares.
-     *
-     * @param  bool $disable
-     *
-     * @return  void
-     */
-    abstract public function prepareMiddleware($enable = false);
-
-    /**
-     * Get the response from the docblock if available.
-     *
-     * @param array $tags
-     *
-     * @return mixed
-     */
-    protected function getDocblockResponse($tags)
-    {
-        $responseTags = array_filter($tags, function ($tag) {
-            return $tag instanceof Tag && \strtolower($tag->getName()) == 'response';
-        });
-        if (empty($responseTags)) {
-            return;
-        }
-        $responseTag = \array_first($responseTags);
-
-        return \response(json_encode($responseTag->getContent()), 200, ['Content-Type' => 'application/json']);
-    }
-
-    /**
-     * @param array $tags
-     *
-     * @return array
-     */
-    protected function getParametersFromDocBlock(array $tags)
-    {
-        $parameters = collect($tags)
-            ->filter(function ($tag) {
-                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
-            })
-            ->mapWithKeys(function ($tag) {
-                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
-                if (empty($content)) {
-                    // this means only name and type were supplied
-                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
-                    $required = false;
-                    $description = '';
-                } else {
-                    list($_, $name, $type, $required, $description) = $content;
-                    $description = trim($description);
-                    if ($description == 'required' && empty(trim($required))) {
-                        $required = $description;
-                        $description = '';
-                    }
-                    $required = trim($required) == 'required' ? true : false;
-                }
-
-                $type = $this->normalizeParameterType($type);
-                $value = $this->generateDummyValue($type);
-
-                return [$name => compact('type', 'description', 'required', 'value')];
-            })->toArray();
-
-        return $parameters;
-    }
-
-    /**
-     * @param array $tags
-     *
-     * @return bool
-     */
-    protected function getAuthStatusFromDocBlock(array $tags)
-    {
-        $authTag = collect($tags)
-            ->first(function ($tag) {
-                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
-            });
-
-        return (bool) $authTag;
-    }
-
-    /**
-     * @param  $route
-     * @param  $bindings
-     * @param  $headers
-     *
-     * @return \Illuminate\Http\Response
-     */
-    protected function getRouteResponse($route, $bindings, $headers = [])
-    {
-        $uri = $this->addRouteModelBindings($route, $bindings);
-
-        $methods = $this->getMethods($route);
-
-        // Split headers into key - value pairs
-        $headers = collect($headers)->map(function ($value) {
-            $split = explode(':', $value); // explode to get key + values
-            $key = array_shift($split); // extract the key and keep the values in the array
-            $value = implode(':', $split); // implode values into string again
-
-            return [trim($key) => trim($value)];
-        })->collapse()->toArray();
-
-        //Changes url with parameters like /users/{user} to /users/1
-        $uri = preg_replace('/{(.*?)}/', 1, $uri); // 1 is the default value for route parameters
-
-        return $this->callRoute(array_shift($methods), $uri, [], [], [], $headers);
-    }
-
-    /**
-     * @param $route
-     * @param array $bindings
-     *
-     * @return mixed
-     */
-    protected function addRouteModelBindings($route, $bindings)
-    {
-        $uri = $this->getUri($route);
-        foreach ($bindings as $model => $id) {
-            $uri = str_replace('{'.$model.'}', $id, $uri);
-            $uri = str_replace('{'.$model.'?}', $id, $uri);
-        }
-
-        return $uri;
-    }
-
-    /**
-     * @param  \Illuminate\Routing\Route  $routeAction
-     *
-     * @return array
-     */
-    protected function parseDocBlock(string $routeAction)
-    {
-        list($class, $method) = explode('@', $routeAction);
-        $reflection = new ReflectionClass($class);
-        $reflectionMethod = $reflection->getMethod($method);
-
-        $comment = $reflectionMethod->getDocComment();
-        $phpdoc = new DocBlock($comment);
-
-        return [
-            'short' => $phpdoc->getShortDescription(),
-            'long' => $phpdoc->getLongDescription()->getContents(),
-            'tags' => $phpdoc->getTags(),
-        ];
-    }
-
-    /**
-     * @param  string  $routeAction
-     *
-     * @return string
-     */
-    protected function getRouteGroup(string $routeAction)
-    {
-        list($class, $method) = explode('@', $routeAction);
-        $controller = new ReflectionClass($class);
-
-        // @group tag on the method overrides that on the controller
-        $method = $controller->getMethod($method);
-        $docBlockComment = $method->getDocComment();
-        if ($docBlockComment) {
-            $phpdoc = new DocBlock($docBlockComment);
-            foreach ($phpdoc->getTags() as $tag) {
-                if ($tag->getName() === 'group') {
-                    return $tag->getContent();
-                }
-            }
-        }
-
-        $docBlockComment = $controller->getDocComment();
-        if ($docBlockComment) {
-            $phpdoc = new DocBlock($docBlockComment);
-            foreach ($phpdoc->getTags() as $tag) {
-                if ($tag->getName() === 'group') {
-                    return $tag->getContent();
-                }
-            }
-        }
-
-        return 'general';
-    }
-
-    /**
-     * Call the given URI and return the Response.
-     *
-     * @param  string  $method
-     * @param  string  $uri
-     * @param  array  $parameters
-     * @param  array  $cookies
-     * @param  array  $files
-     * @param  array  $server
-     * @param  string  $content
-     *
-     * @return \Illuminate\Http\Response
-     */
-    abstract public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null);
-
-    /**
-     * Transform headers array to array of $_SERVER vars with HTTP_* format.
-     *
-     * @param  array  $headers
-     *
-     * @return array
-     */
-    protected function transformHeadersToServerVars(array $headers)
-    {
-        $server = [];
-        $prefix = 'HTTP_';
-
-        foreach ($headers as $name => $value) {
-            $name = strtr(strtoupper($name), '-', '_');
-
-            if (! Str::startsWith($name, $prefix) && $name !== 'CONTENT_TYPE') {
-                $name = $prefix.$name;
-            }
-
-            $server[$name] = $value;
-        }
-
-        return $server;
-    }
-
-    /**
-     * @param $response
-     *
-     * @return mixed
-     */
-    private function getResponseContent($response)
-    {
-        if (empty($response)) {
-            return '';
-        }
-        if ($response->headers->get('Content-Type') === 'application/json') {
-            $content = json_decode($response->getContent(), JSON_PRETTY_PRINT);
-        } else {
-            $content = $response->getContent();
-        }
-
-        return $content;
-    }
-
-    /**
-     * Get a response from the transformer tags.
-     *
-     * @param array $tags
-     *
-     * @return mixed
-     */
-    protected function getTransformerResponse($tags)
-    {
-        try {
-            $transFormerTags = array_filter($tags, function ($tag) {
-                if (! ($tag instanceof Tag)) {
-                    return false;
-                }
-
-                return \in_array(\strtolower($tag->getName()), ['transformer', 'transformercollection']);
-            });
-            if (empty($transFormerTags)) {
-                // we didn't have any of the tags so goodbye
-                return false;
-            }
-
-            $modelTag = array_first(array_filter($tags, function ($tag) {
-                if (! ($tag instanceof Tag)) {
-                    return false;
-                }
-
-                return \in_array(\strtolower($tag->getName()), ['transformermodel']);
-            }));
-            $tag = \array_first($transFormerTags);
-            $transformer = $tag->getContent();
-            if (! \class_exists($transformer)) {
-                // if we can't find the transformer we can't generate a response
-                return;
-            }
-            $demoData = [];
-
-            $reflection = new ReflectionClass($transformer);
-            $method = $reflection->getMethod('transform');
-            $parameter = \array_first($method->getParameters());
-            $type = null;
-            if ($modelTag) {
-                $type = $modelTag->getContent();
-            }
-            if (\is_null($type)) {
-                if ($parameter->hasType() &&
-                    ! $parameter->getType()->isBuiltin() &&
-                    \class_exists((string) $parameter->getType())) {
-                    //we have a type
-                    $type = (string) $parameter->getType();
-                }
-            }
-            if ($type) {
-                // we have a class so we try to create an instance
-                $demoData = new $type;
-                try {
-                    // try a factory
-                    $demoData = \factory($type)->make();
-                } catch (\Exception $e) {
-                    if ($demoData instanceof \Illuminate\Database\Eloquent\Model) {
-                        // we can't use a factory but can try to get one from the database
-                        try {
-                            // check if we can find one
-                            $newDemoData = $type::first();
-                            if ($newDemoData) {
-                                $demoData = $newDemoData;
-                            }
-                        } catch (\Exception $e) {
-                            // do nothing
-                        }
-                    }
-                }
-            }
-
-            $fractal = new Manager();
-            $resource = [];
-            if ($tag->getName() == 'transformer') {
-                // just one
-                $resource = new Item($demoData, new $transformer);
-            }
-            if ($tag->getName() == 'transformercollection') {
-                // a collection
-                $resource = new Collection([$demoData, $demoData], new $transformer);
-            }
-
-            return \response($fractal->createData($resource)->toJson());
-        } catch (\Exception $e) {
-            // it isn't possible to parse the transformer
-            return;
-        }
-    }
-
-    private function getResponse(array $annotationTags)
-    {
-        $response = null;
-        if ($docblockResponse = $this->getDocblockResponse($annotationTags)) {
-            // we have a response from the docblock ( @response )
-            $response = $docblockResponse;
-        }
-        if (! $response && ($transformerResponse = $this->getTransformerResponse($annotationTags))) {
-            // we have a transformer response from the docblock ( @transformer || @transformercollection )
-            $response = $transformerResponse;
-        }
-
-        $content = $response ? $this->getResponseContent($response) : null;
-
-        return $content;
-    }
-
-    private function normalizeParameterType($type)
-    {
-        $typeMap = [
-            'int' => 'integer',
-            'bool' => 'boolean',
-            'double' => 'float',
-        ];
-
-        return $type ? ($typeMap[$type] ?? $type) : 'string';
-    }
-
-    private function generateDummyValue(string $type)
-    {
-        $faker = Factory::create();
-        $fakes = [
-            'integer' => function () {
-                return rand(1, 20);
-            },
-            'number' => function () use ($faker) {
-                return $faker->randomFloat();
-            },
-            'float' => function () use ($faker) {
-                return $faker->randomFloat();
-            },
-            'boolean' => function () use ($faker) {
-                return $faker->boolean();
-            },
-            'string' => function () use ($faker) {
-                return str_random();
-            },
-            'array' => function () {
-                return '[]';
-            },
-            'object' => function () {
-                return '{}';
-            },
-        ];
-
-        $fake = $fakes[$type] ?? $fakes['string'];
-
-        return $fake();
-    }
-}

+ 0 - 33
src/Generators/DingoGenerator.php

@@ -1,33 +0,0 @@
-<?php
-
-namespace Mpociot\ApiDoc\Generators;
-
-class DingoGenerator extends AbstractGenerator
-{
-    /**
-     * Prepares / Disables route middlewares.
-     *
-     * @param  bool $disable
-     *
-     * @return  void
-     */
-    public function prepareMiddleware($disable = true)
-    {
-        // Not needed by Dingo
-        return false;
-    }
-
-    /**
-     * {@inheritdoc}
-     */
-    public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
-    {
-        $dispatcher = app('Dingo\Api\Dispatcher')->raw();
-
-        collect($server)->map(function ($key, $value) use ($dispatcher) {
-            $dispatcher->header($value, $key);
-        });
-
-        return call_user_func_array([$dispatcher, strtolower($method)], [$uri]);
-    }
-}

+ 212 - 0
src/Generators/Generator.php

@@ -0,0 +1,212 @@
+<?php
+
+namespace Mpociot\ApiDoc\Generators;
+
+use Faker\Factory;
+use ReflectionClass;
+use ReflectionMethod;
+use Illuminate\Routing\Route;
+use Mpociot\Reflection\DocBlock;
+use Mpociot\Reflection\DocBlock\Tag;
+use Mpociot\ApiDoc\Tools\ResponseResolver;
+
+class Generator
+{
+    /**
+     * @param Route $route
+     *
+     * @return mixed
+     */
+    public function getUri(Route $route)
+    {
+        return $route->uri();
+    }
+
+    /**
+     * @param Route $route
+     *
+     * @return mixed
+     */
+    public function getMethods(Route $route)
+    {
+        return array_diff($route->methods(), ['HEAD']);
+    }
+
+    /**
+     * @param  \Illuminate\Routing\Route $route
+     * @param array $apply Rules to apply when generating documentation for this route
+     *
+     * @return array
+     */
+    public function processRoute(Route $route, array $rulesToApply = [])
+    {
+        $routeAction = $route->getAction();
+        list($class, $method) = explode('@', $routeAction['uses']);
+        $controller = new ReflectionClass($class);
+        $method = $controller->getMethod($method);
+
+        $routeGroup = $this->getRouteGroup($controller, $method);
+        $docBlock = $this->parseDocBlock($method);
+        $content = ResponseResolver::getResponse($route, $docBlock['tags'], $rulesToApply);
+
+        $parsedRoute = [
+            'id' => md5($this->getUri($route).':'.implode($this->getMethods($route))),
+            'group' => $routeGroup,
+            'title' => $docBlock['short'],
+            'description' => $docBlock['long'],
+            'methods' => $this->getMethods($route),
+            'uri' => $this->getUri($route),
+            'parameters' => $this->getParametersFromDocBlock($docBlock['tags']),
+            'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
+            'response' => $content,
+            'showresponse' => ! empty($content),
+        ];
+        $parsedRoute['headers'] = $rulesToApply['headers'] ?? [];
+
+        return $parsedRoute;
+    }
+
+    /**
+     * @param array $tags
+     *
+     * @return array
+     */
+    protected function getParametersFromDocBlock(array $tags)
+    {
+        $parameters = collect($tags)
+            ->filter(function ($tag) {
+                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
+            })
+            ->mapWithKeys(function ($tag) {
+                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
+                if (empty($content)) {
+                    // this means only name and type were supplied
+                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
+                    $required = false;
+                    $description = '';
+                } else {
+                    list($_, $name, $type, $required, $description) = $content;
+                    $description = trim($description);
+                    if ($description == 'required' && empty(trim($required))) {
+                        $required = $description;
+                        $description = '';
+                    }
+                    $required = trim($required) == 'required' ? true : false;
+                }
+
+                $type = $this->normalizeParameterType($type);
+                $value = $this->generateDummyValue($type);
+
+                return [$name => compact('type', 'description', 'required', 'value')];
+            })->toArray();
+
+        return $parameters;
+    }
+
+    /**
+     * @param array $tags
+     *
+     * @return bool
+     */
+    protected function getAuthStatusFromDocBlock(array $tags)
+    {
+        $authTag = collect($tags)
+            ->first(function ($tag) {
+                return $tag instanceof Tag && strtolower($tag->getName()) === 'authenticated';
+            });
+
+        return (bool) $authTag;
+    }
+
+    /**
+     * @param ReflectionMethod $method
+     *
+     * @return array
+     */
+    protected function parseDocBlock(ReflectionMethod $method)
+    {
+        $comment = $method->getDocComment();
+        $phpdoc = new DocBlock($comment);
+
+        return [
+            'short' => $phpdoc->getShortDescription(),
+            'long' => $phpdoc->getLongDescription()->getContents(),
+            'tags' => $phpdoc->getTags(),
+        ];
+    }
+
+    /**
+     * @param ReflectionClass $controller
+     * @param ReflectionMethod $method
+     *
+     * @return string
+     */
+    protected function getRouteGroup(ReflectionClass $controller, ReflectionMethod $method)
+    {
+        // @group tag on the method overrides that on the controller
+        $docBlockComment = $method->getDocComment();
+        if ($docBlockComment) {
+            $phpdoc = new DocBlock($docBlockComment);
+            foreach ($phpdoc->getTags() as $tag) {
+                if ($tag->getName() === 'group') {
+                    return $tag->getContent();
+                }
+            }
+        }
+
+        $docBlockComment = $controller->getDocComment();
+        if ($docBlockComment) {
+            $phpdoc = new DocBlock($docBlockComment);
+            foreach ($phpdoc->getTags() as $tag) {
+                if ($tag->getName() === 'group') {
+                    return $tag->getContent();
+                }
+            }
+        }
+
+        return 'general';
+    }
+
+    private function normalizeParameterType($type)
+    {
+        $typeMap = [
+            'int' => 'integer',
+            'bool' => 'boolean',
+            'double' => 'float',
+        ];
+
+        return $type ? ($typeMap[$type] ?? $type) : 'string';
+    }
+
+    private function generateDummyValue(string $type)
+    {
+        $faker = Factory::create();
+        $fakes = [
+            'integer' => function () {
+                return rand(1, 20);
+            },
+            'number' => function () use ($faker) {
+                return $faker->randomFloat();
+            },
+            'float' => function () use ($faker) {
+                return $faker->randomFloat();
+            },
+            'boolean' => function () use ($faker) {
+                return $faker->boolean();
+            },
+            'string' => function () use ($faker) {
+                return str_random();
+            },
+            'array' => function () {
+                return '[]';
+            },
+            'object' => function () {
+                return '{}';
+            },
+        ];
+
+        $fake = $fakes[$type] ?? $fakes['string'];
+
+        return $fake();
+    }
+}

+ 0 - 85
src/Generators/LaravelGenerator.php

@@ -1,85 +0,0 @@
-<?php
-
-namespace Mpociot\ApiDoc\Generators;
-
-use Illuminate\Routing\Route;
-use Illuminate\Support\Facades\App;
-use Illuminate\Support\Facades\Request;
-
-class LaravelGenerator extends AbstractGenerator
-{
-    /**
-     * @param Route $route
-     *
-     * @return mixed
-     */
-    public function getUri(Route $route)
-    {
-        if (version_compare(app()->version(), '5.4', '<')) {
-            return $route->getUri();
-        }
-
-        return $route->uri();
-    }
-
-    /**
-     * @param Route $route
-     *
-     * @return mixed
-     */
-    public function getMethods(Route $route)
-    {
-        if (version_compare(app()->version(), '5.4', '<')) {
-            $methods = $route->getMethods();
-        } else {
-            $methods = $route->methods();
-        }
-
-        return array_diff($methods, ['HEAD']);
-    }
-
-    /**
-     * Prepares / Disables route middlewares.
-     *
-     * @param  bool $disable
-     *
-     * @return  void
-     */
-    public function prepareMiddleware($enable = true)
-    {
-        App::instance('middleware.disable', ! $enable);
-    }
-
-    /**
-     * Call the given URI and return the Response.
-     *
-     * @param  string  $method
-     * @param  string  $uri
-     * @param  array  $parameters
-     * @param  array  $cookies
-     * @param  array  $files
-     * @param  array  $server
-     * @param  string  $content
-     *
-     * @return \Illuminate\Http\Response
-     */
-    public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
-    {
-        $server = collect([
-            'CONTENT_TYPE' => 'application/json',
-            'Accept' => 'application/json',
-        ])->merge($server)->toArray();
-
-        $request = Request::create(
-            $uri, $method, $parameters,
-            $cookies, $files, $this->transformHeadersToServerVars($server), $content
-        );
-
-        $kernel = App::make('Illuminate\Contracts\Http\Kernel');
-        $response = $kernel->handle($request);
-
-        $kernel->terminate($request, $response);
-
-        return $response;
-    }
-}

+ 54 - 0
src/Tools/ResponseResolver.php

@@ -0,0 +1,54 @@
+<?php
+
+namespace Mpociot\ApiDoc\Tools;
+
+use Illuminate\Routing\Route;
+use Mpociot\ApiDoc\Tools\ResponseStrategies\ResponseTagStrategy;
+use Mpociot\ApiDoc\Tools\ResponseStrategies\ResponseCallStrategy;
+use Mpociot\ApiDoc\Tools\ResponseStrategies\TransformerTagsStrategy;
+
+class ResponseResolver
+{
+    public static $strategies = [
+        ResponseTagStrategy::class,
+        TransformerTagsStrategy::class,
+        ResponseCallStrategy::class,
+    ];
+
+    /**
+     * @var Route
+     */
+    private $route;
+
+    public function __construct(Route $route)
+    {
+        $this->route = $route;
+    }
+
+    private function resolve(array $tags, array $rulesToApply)
+    {
+        $response = null;
+        foreach (static::$strategies as $strategy) {
+            $strategy = new $strategy();
+            $response = $strategy($this->route, $tags, $rulesToApply);
+            if (! is_null($response)) {
+                return $this->getResponseContent($response);
+            }
+        }
+    }
+
+    public static function getResponse($route, $tags, $rulesToApply)
+    {
+        return (new static($route))->resolve($tags, $rulesToApply);
+    }
+
+    /**
+     * @param $response
+     *
+     * @return mixed
+     */
+    private function getResponseContent($response)
+    {
+        return $response ? $response->getContent() : '';
+    }
+}

+ 244 - 0
src/Tools/ResponseStrategies/ResponseCallStrategy.php

@@ -0,0 +1,244 @@
+<?php
+
+namespace Mpociot\ApiDoc\Tools\ResponseStrategies;
+
+use Dingo\Api\Dispatcher;
+use Illuminate\Http\Request;
+use Illuminate\Http\Response;
+use Illuminate\Routing\Route;
+
+/**
+ * Make a call to the route and retrieve its response.
+ */
+class ResponseCallStrategy
+{
+    public function __invoke(Route $route, array $tags, array $rulesToApply)
+    {
+        $rulesToApply = $rulesToApply['response_calls'] ?? [];
+        if (! $this->shouldMakeApiCall($route, $rulesToApply)) {
+            return;
+        }
+
+        $this->configureEnvironment($rulesToApply);
+        $request = $this->prepareRequest($route, $rulesToApply);
+        try {
+            $response = $this->makeApiCall($request);
+        } catch (\Exception $e) {
+            $response = null;
+        } finally {
+            $this->finish();
+        }
+
+        return $response;
+    }
+
+    private function configureEnvironment(array $rulesToApply)
+    {
+        $this->startDbTransaction();
+        $this->setEnvironmentVariables($rulesToApply['env'] ?? []);
+    }
+
+    private function prepareRequest(Route $route, array $rulesToApply)
+    {
+        $uri = $this->replaceUrlParameterBindings($route, $rulesToApply['bindings'] ?? []);
+        $routeMethods = $this->getMethods($route);
+        $method = array_shift($routeMethods);
+        $request = Request::create($uri, $method, [], [], [], $this->transformHeadersToServerVars($rulesToApply['headers'] ?? []));
+        $request = $this->addHeaders($request, $route, $rulesToApply['headers'] ?? []);
+        $request = $this->addQueryParameters($request, $rulesToApply['query'] ?? []);
+        $request = $this->addBodyParameters($request, $rulesToApply['body'] ?? []);
+
+        return $request;
+    }
+
+    /**
+     * Transform parameters in URLs into real values (/users/{user} -> /users/2).
+     * Uses bindings specified by caller, otherwise just uses '1'.
+     *
+     * @param Route $route
+     * @param array $bindings
+     *
+     * @return mixed
+     */
+    protected function replaceUrlParameterBindings(Route $route, $bindings)
+    {
+        $uri = $route->uri();
+        foreach ($bindings as $parameter => $binding) {
+            $uri = str_replace($parameter, $binding, $uri);
+        }
+        // Replace any unbound parameters with '1'
+        $uri = preg_replace('/{(.*?)}/', 1, $uri);
+
+        return $uri;
+    }
+
+    private function setEnvironmentVariables(array $env)
+    {
+        foreach ($env as $name => $value) {
+            putenv("$name=$value");
+
+            $_ENV[$name] = $value;
+            $_SERVER[$name] = $value;
+        }
+    }
+
+    private function startDbTransaction()
+    {
+        try {
+            app('db')->beginTransaction();
+        } catch (\Exception $e) {
+        }
+    }
+
+    private function endDbTransaction()
+    {
+        try {
+            app('db')->rollBack();
+        } catch (\Exception $e) {
+        }
+    }
+
+    private function finish()
+    {
+        $this->endDbTransaction();
+    }
+
+    public function callDingoRoute(Request $request)
+    {
+        /** @var Dispatcher $dispatcher */
+        $dispatcher = app(\Dingo\Api\Dispatcher::class);
+
+        foreach ($request->headers as $header => $value) {
+            $dispatcher->header($header, $value);
+        }
+
+        // set domain and body parameters
+        $dispatcher->on($request->header('SERVER_NAME'))
+            ->with($request->request->all());
+
+        // set URL and query parameters
+        $uri = $request->getRequestUri();
+        $query = $request->getQueryString();
+        if (! empty($query)) {
+            $uri .= "?$query";
+        }
+        $response = call_user_func_array([$dispatcher, strtolower($request->method())], [$uri]);
+
+        // the response from the Dingo dispatcher is the 'raw' response from the controller,
+        // so we have to ensure it's JSON first
+        if (! $response instanceof Response) {
+            $response = response()->json($response);
+        }
+
+        return $response;
+    }
+
+    public function getMethods(Route $route)
+    {
+        return array_diff($route->methods(), ['HEAD']);
+    }
+
+    private function addHeaders(Request $request, Route $route, $headers)
+    {
+        // set the proper domain
+        if ($route->getDomain()) {
+            $request->server->add([
+                'HTTP_HOST' => $route->getDomain(),
+                'SERVER_NAME' => $route->getDomain(),
+            ]);
+        }
+
+        $headers = collect($headers);
+
+        if (($headers->get('Accept') ?: $headers->get('accept')) === 'application/json') {
+            $request->setRequestFormat('json');
+        }
+
+        return $request;
+    }
+
+    private function addQueryParameters(Request $request, array $query)
+    {
+        $request->query->add($query);
+        $request->server->add(['QUERY_STRING' => http_build_query($query)]);
+
+        return $request;
+    }
+
+    private function addBodyParameters(Request $request, array $body)
+    {
+        $request->request->add($body);
+
+        return $request;
+    }
+
+    private function makeApiCall(Request $request)
+    {
+        if (config('apidoc.router') == 'dingo') {
+            $response = $this->callDingoRoute($request);
+        } else {
+            $response = $this->callLaravelRoute($request);
+        }
+
+        return $response;
+    }
+
+    /**
+     * @param $request
+     *
+     * @return \Symfony\Component\HttpFoundation\Response
+     */
+    private function callLaravelRoute($request): \Symfony\Component\HttpFoundation\Response
+    {
+        $kernel = app(\Illuminate\Contracts\Http\Kernel::class);
+        $response = $kernel->handle($request);
+        $kernel->terminate($request, $response);
+
+        return $response;
+    }
+
+    private function shouldMakeApiCall(Route $route, array $rulesToApply): bool
+    {
+        $allowedMethods = $rulesToApply['methods'] ?? [];
+        if (empty($allowedMethods)) {
+            return false;
+        }
+
+        if (is_string($allowedMethods) && $allowedMethods == '*') {
+            return true;
+        }
+
+        if (array_search('*', $allowedMethods) !== false) {
+            return true;
+        }
+
+        $routeMethods = $this->getMethods($route);
+        if (in_array(array_shift($routeMethods), $allowedMethods)) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Transform headers array to array of $_SERVER vars with HTTP_* format.
+     *
+     * @param  array  $headers
+     *
+     * @return array
+     */
+    protected function transformHeadersToServerVars(array $headers)
+    {
+        $server = [];
+        $prefix = 'HTTP_';
+        foreach ($headers as $name => $value) {
+            $name = strtr(strtoupper($name), '-', '_');
+            if (! starts_with($name, $prefix) && $name !== 'CONTENT_TYPE') {
+                $name = $prefix.$name;
+            }
+            $server[$name] = $value;
+        }
+
+        return $server;
+    }
+}

+ 37 - 0
src/Tools/ResponseStrategies/ResponseTagStrategy.php

@@ -0,0 +1,37 @@
+<?php
+
+namespace Mpociot\ApiDoc\Tools\ResponseStrategies;
+
+use Illuminate\Routing\Route;
+use Mpociot\Reflection\DocBlock\Tag;
+
+/**
+ * Get a response from the docblock ( @response ).
+ */
+class ResponseTagStrategy
+{
+    public function __invoke(Route $route, array $tags, array $rulesToApply)
+    {
+        return $this->getDocBlockResponse($tags);
+    }
+
+    /**
+     * Get the response from the docblock if available.
+     *
+     * @param array $tags
+     *
+     * @return mixed
+     */
+    protected function getDocBlockResponse(array $tags)
+    {
+        $responseTags = array_filter($tags, function ($tag) {
+            return $tag instanceof Tag && strtolower($tag->getName()) == 'response';
+        });
+        if (empty($responseTags)) {
+            return;
+        }
+        $responseTag = array_first($responseTags);
+
+        return response()->json(json_decode($responseTag->getContent(), true));
+    }
+}

+ 129 - 0
src/Tools/ResponseStrategies/TransformerTagsStrategy.php

@@ -0,0 +1,129 @@
+<?php
+
+namespace Mpociot\ApiDoc\Tools\ResponseStrategies;
+
+use ReflectionClass;
+use ReflectionMethod;
+use League\Fractal\Manager;
+use Illuminate\Routing\Route;
+use League\Fractal\Resource\Item;
+use Mpociot\Reflection\DocBlock\Tag;
+use League\Fractal\Resource\Collection;
+
+/**
+ * Parse a transformer response from the docblock ( @transformer || @transformercollection ).
+ */
+class TransformerTagsStrategy
+{
+    public function __invoke(Route $route, array $tags, array $rulesToApply)
+    {
+        return $this->getTransformerResponse($tags);
+    }
+
+    /**
+     * Get a response from the transformer tags.
+     *
+     * @param array $tags
+     *
+     * @return mixed
+     */
+    protected function getTransformerResponse(array $tags)
+    {
+        try {
+            if (empty($transformerTag = $this->getTransformerTag($tags))) {
+                return;
+            }
+
+            $transformer = $this->getTransformerClass($transformerTag);
+            $model = $this->getClassToBeTransformed($tags, (new ReflectionClass($transformer))->getMethod('transform'));
+            $modelInstance = $this->instantiateTransformerModel($model);
+
+            $fractal = new Manager();
+            $resource = (strtolower($transformerTag->getName()) == 'transformercollection')
+                ? new Collection([$modelInstance, $modelInstance], new $transformer)
+                : new Item($modelInstance, new $transformer);
+
+            return response($fractal->createData($resource)->toJson());
+        } catch (\Exception $e) {
+            return;
+        }
+    }
+
+    /**
+     * @param Tag $tag
+     *
+     * @return string|null
+     */
+    private function getTransformerClass($tag)
+    {
+        return $tag->getContent();
+    }
+
+    /**
+     * @param array $tags
+     * @param ReflectionMethod $transformerMethod
+     *
+     * @return null|string
+     */
+    private function getClassToBeTransformed(array $tags, ReflectionMethod $transformerMethod)
+    {
+        $modelTag = array_first(array_filter($tags, function ($tag) {
+            return ($tag instanceof Tag) && strtolower($tag->getName()) == 'transformermodel';
+        }));
+
+        $type = null;
+        if ($modelTag) {
+            $type = $modelTag->getContent();
+        } else {
+            $parameter = array_first($transformerMethod->getParameters());
+            if ($parameter->hasType() && ! $parameter->getType()->isBuiltin() && class_exists((string) $parameter->getType())) {
+                // ladies and gentlemen, we have a type!
+                $type = (string) $parameter->getType();
+            }
+        }
+
+        return $type;
+    }
+
+    /**
+     * @param string $type
+     *
+     * @return mixed
+     */
+    protected function instantiateTransformerModel(string $type)
+    {
+        try {
+            // try Eloquent model factory
+            return factory($type)->make();
+        } catch (\Exception $e) {
+            $instance = new $type;
+            if ($instance instanceof \Illuminate\Database\Eloquent\Model) {
+                try {
+                    // we can't use a factory but can try to get one from the database
+                    $firstInstance = $type::first();
+                    if ($firstInstance) {
+                        return $firstInstance;
+                    }
+                } catch (\Exception $e) {
+                    // okay, we'll stick with `new`
+                }
+            }
+        }
+
+        return $instance;
+    }
+
+    /**
+     * @param array $tags
+     *
+     * @return Tag|null
+     */
+    private function getTransformerTag(array $tags)
+    {
+        $transFormerTags = array_filter($tags, function ($tag) {
+            return ($tag instanceof Tag) && in_array(strtolower($tag->getName()), ['transformer', 'transformercollection']);
+        });
+
+        return array_first($transFormerTags);
+    }
+}

+ 22 - 11
tests/Fixtures/TestController.php

@@ -61,19 +61,30 @@ class TestController extends Controller
 
     public function shouldFetchRouteResponse()
     {
-        $fixture = new \stdClass();
-        $fixture->id = 1;
-        $fixture->name = 'banana';
-        $fixture->color = 'red';
-        $fixture->weight = 300;
-        $fixture->delicious = 1;
+        $fruit = new \stdClass();
+        $fruit->id = 4;
+        $fruit->name = ' banana  ';
+        $fruit->color = 'RED';
+        $fruit->weight = 1;
+        $fruit->delicious = true;
 
         return [
-            'id' => (int) $fixture->id,
-            'name' => ucfirst($fixture->name),
-            'color' => ucfirst($fixture->color),
-            'weight' => $fixture->weight.' grams',
-            'delicious' => (bool) $fixture->delicious,
+            'id' => (int) $fruit->id,
+            'name' => trim($fruit->name),
+            'color' => strtolower($fruit->color),
+            'weight' => $fruit->weight.' kg',
+            'delicious' => $fruit->delicious,
+        ];
+    }
+
+    public function shouldFetchRouteResponseWithEchoedSettings($id)
+    {
+        return [
+            '{id}' => $id,
+            'APP_ENV' => getenv('APP_ENV'),
+            'header' => request()->header('header'),
+            'queryParam' => request()->query('queryParam'),
+            'bodyParam' => request()->get('bodyParam'),
         ];
     }
 

+ 0 - 9
tests/Fixtures/TestResourceController.php

@@ -48,9 +48,6 @@ class TestResourceController extends Controller
      */
     public function store(Request $request)
     {
-        return [
-            'store_resource' => true,
-        ];
     }
 
     /**
@@ -99,9 +96,6 @@ class TestResourceController extends Controller
      */
     public function update(Request $request, $id)
     {
-        return [
-            'update_resource' => $id,
-        ];
     }
 
     /**
@@ -113,8 +107,5 @@ class TestResourceController extends Controller
      */
     public function destroy($id)
     {
-        return [
-            'destroy_resource' => $id,
-        ];
     }
 }

+ 3 - 4
tests/Unit/DingoGeneratorTest.php

@@ -3,7 +3,6 @@
 namespace Mpociot\ApiDoc\Tests\Unit;
 
 use Dingo\Api\Routing\Router;
-use Mpociot\ApiDoc\Generators\DingoGenerator;
 use Mpociot\ApiDoc\Tests\Fixtures\TestController;
 use Mpociot\ApiDoc\ApiDocGeneratorServiceProvider;
 
@@ -12,8 +11,8 @@ class DingoGeneratorTest extends GeneratorTestCase
     protected function getPackageProviders($app)
     {
         return [
-            \Dingo\Api\Provider\LaravelServiceProvider::class,
             ApiDocGeneratorServiceProvider::class,
+            \Dingo\Api\Provider\LaravelServiceProvider::class,
         ];
     }
 
@@ -21,10 +20,10 @@ class DingoGeneratorTest extends GeneratorTestCase
     {
         parent::setUp();
 
-        $this->generator = new DingoGenerator();
+        config(['apidoc.router' => 'dingo']);
     }
 
-    public function createRoute(string $httpMethod, string $path, string $controllerMethod)
+    public function createRoute(string $httpMethod, string $path, string $controllerMethod, $register = false)
     {
         $route = null;
         /** @var Router $api */

+ 74 - 6
tests/Unit/GeneratorTestCase.php

@@ -3,13 +3,13 @@
 namespace Mpociot\ApiDoc\Tests\Unit;
 
 use Orchestra\Testbench\TestCase;
-use Mpociot\ApiDoc\Generators\LaravelGenerator;
+use Mpociot\ApiDoc\Generators\Generator;
 use Mpociot\ApiDoc\ApiDocGeneratorServiceProvider;
 
 abstract class GeneratorTestCase extends TestCase
 {
     /**
-     * @var \Mpociot\ApiDoc\Generators\AbstractGenerator
+     * @var \Mpociot\ApiDoc\Generators\Generator
      */
     protected $generator;
 
@@ -27,7 +27,7 @@ abstract class GeneratorTestCase extends TestCase
     {
         parent::setUp();
 
-        $this->generator = new LaravelGenerator();
+        $this->generator = new Generator();
     }
 
     /** @test */
@@ -140,13 +140,13 @@ abstract class GeneratorTestCase extends TestCase
         $this->assertTrue(is_array($parsed));
         $this->assertArrayHasKey('showresponse', $parsed);
         $this->assertTrue($parsed['showresponse']);
-        $this->assertJsonStringEqualsJsonString(json_encode([
+        $this->assertArraySubset([
             'id' => 4,
             'name' => 'banana',
             'color' => 'red',
             'weight' => '1 kg',
             'delicious' => true,
-        ]), $parsed['response']);
+        ], json_decode($parsed['response'], true));
     }
 
     /** @test */
@@ -207,5 +207,73 @@ abstract class GeneratorTestCase extends TestCase
         );
     }
 
-    abstract public function createRoute(string $httpMethod, string $path, string $controllerMethod);
+    /** @test */
+    public function can_call_route_and_generate_response()
+    {
+        $route = $this->createRoute('PUT', '/shouldFetchRouteResponse', 'shouldFetchRouteResponse', true);
+
+        $rules = [
+            'response_calls' => [
+                'methods' => ['*'],
+                'headers' => [
+                    'Content-Type' => 'application/json',
+                    'Accept' => 'application/json',
+                ],
+            ],
+        ];
+        $parsed = $this->generator->processRoute($route, $rules);
+
+        $this->assertTrue(is_array($parsed));
+        $this->assertArrayHasKey('showresponse', $parsed);
+        $this->assertTrue($parsed['showresponse']);
+        $this->assertArraySubset([
+            'id' => 4,
+            'name' => 'banana',
+            'color' => 'red',
+            'weight' => '1 kg',
+            'delicious' => true,
+        ], json_decode($parsed['response'], true));
+    }
+
+    /** @test */
+    public function uses_configured_settings_when_calling_route()
+    {
+        $route = $this->createRoute('PUT', '/echo/{id}', 'shouldFetchRouteResponseWithEchoedSettings', true);
+
+        $rules = [
+            'response_calls' => [
+                'methods' => ['*'],
+                'headers' => [
+                    'Content-Type' => 'application/json',
+                    'Accept' => 'application/json',
+                    'header' => 'value',
+                ],
+                'bindings' => [
+                    '{id}' => 3,
+                ],
+                'env' => [
+                    'APP_ENV' => 'documentation',
+                ],
+                'query' => [
+                    'queryParam' => 'queryValue',
+                ],
+                'body' => [
+                    'bodyParam' => 'bodyValue',
+                ],
+            ],
+        ];
+        $parsed = $this->generator->processRoute($route, $rules);
+
+        $this->assertTrue(is_array($parsed));
+        $this->assertArrayHasKey('showresponse', $parsed);
+        $this->assertTrue($parsed['showresponse']);
+        $response = json_decode($parsed['response'], true);
+        $this->assertEquals(3, $response['{id}']);
+        $this->assertEquals('documentation', $response['APP_ENV']);
+        $this->assertEquals('queryValue', $response['queryParam']);
+        $this->assertEquals('bodyValue', $response['bodyParam']);
+        $this->assertEquals('value', $response['header']);
+    }
+
+    abstract public function createRoute(string $httpMethod, string $path, string $controllerMethod, $register = false);
 }

+ 7 - 10
tests/Unit/LaravelGeneratorTest.php

@@ -3,9 +3,9 @@
 namespace Mpociot\ApiDoc\Tests\Unit;
 
 use Illuminate\Routing\Route;
-use Mpociot\ApiDoc\Generators\LaravelGenerator;
 use Mpociot\ApiDoc\Tests\Fixtures\TestController;
 use Mpociot\ApiDoc\ApiDocGeneratorServiceProvider;
+use Illuminate\Support\Facades\Route as RouteFacade;
 
 class LaravelGeneratorTest extends GeneratorTestCase
 {
@@ -16,15 +16,12 @@ class LaravelGeneratorTest extends GeneratorTestCase
         ];
     }
 
-    public function setUp()
+    public function createRoute(string $httpMethod, string $path, string $controllerMethod, $register = false)
     {
-        parent::setUp();
-
-        $this->generator = new LaravelGenerator();
-    }
-
-    public function createRoute(string $httpMethod, string $path, string $controllerMethod)
-    {
-        return new Route([$httpMethod], $path, ['uses' => TestController::class."@$controllerMethod"]);
+        if ($register) {
+            return RouteFacade::{$httpMethod}($path, TestController::class."@$controllerMethod");
+        } else {
+            return new Route([$httpMethod], $path, ['uses' => TestController::class."@$controllerMethod"]);
+        }
     }
 }