Selaa lähdekoodia

Allow method to override controller `@group` (closes #339)

shalvah 6 vuotta sitten
vanhempi
commit
bb96d0f8fc

+ 8 - 39
CHANGELOG.md

@@ -14,49 +14,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 ### Removed
 
 
-## [2.1.5] - 123h September, 2018
-### Fixed
-- Parse JSON responses from `@transformer` tag for DIngo router (https://github.com/mpociot/laravel-apidoc-generator/pull/323)
-
-## [2.1.4] - 12th September, 2018
-### Fixed
-- Parse JSON responses from  `@response` and `@transformer` tags correctly (https://github.com/mpociot/laravel-apidoc-generator/pull/321)
-
-## [2.1.3] - 11th September, 2018
-### Fixed
-- Parse `@response` tags regardless of HTTP method (https://github.com/mpociot/laravel-apidoc-generator/pull/318)
-
-## [2.1.2] - 10th September, 2018
-### Fixed
-- Set correct HTTP method when parsing FormRequest (https://github.com/mpociot/laravel-apidoc-generator/pull/314)
-
-## [2.1.1] - 10th September, 2018
-### Fixed
-- Print the correct file path of generated documentation (https://github.com/mpociot/laravel-apidoc-generator/pull/311)
-- Removed any extra slashes in URLs displayed in code samples (https://github.com/mpociot/laravel-apidoc-generator/pull/310)
-- Response calls are now also made for only GET in DIngo Router (https://github.com/mpociot/laravel-apidoc-generator/pull/309)
-- HEAD routes are no longer automatically generated for GET routes in DIngo Router (https://github.com/mpociot/laravel-apidoc-generator/pull/309)
-
-## [2.1.0] - 9th September, 2018
+## [3.0] - unreleased
 ### Added
-- Added support for multiple route domains (https://github.com/mpociot/laravel-apidoc-generator/pull/255) 
-- Added support for descriptions in custom validation rules (https://github.com/mpociot/laravel-apidoc-generator/pull/208)
-- Added support for multiple route prefixes (https://github.com/mpociot/laravel-apidoc-generator/pull/203)
-- Added support for formatting and `<aside>` tags (https://github.com/mpociot/laravel-apidoc-generator/pull/261)
-- Support for Laravel 5.5 auto-discovery (https://github.com/mpociot/laravel-apidoc-generator/pull/217)
+- `@bodyParam` annotation (https://github.com/mpociot/laravel-apidoc-generator/pull/362, https://github.com/mpociot/laravel-apidoc-generator/pull/366)
+- `@authenticated` annotation (https://github.com/mpociot/laravel-apidoc-generator/pull/369)
+- Ability to override the controller `@group` from the method. ()
 
 ### Changed
-- Response calls are now only made when route is GET (https://github.com/mpociot/laravel-apidoc-generator/pull/279)
-- Validator factory is now passed to `FormRequest::validator` method (https://github.com/mpociot/laravel-apidoc-generator/pull/236)
-- Bind optional model parameters in routes (https://github.com/mpociot/laravel-apidoc-generator/pull/297/)
-- HEAD routes are no longer automatically generated for GET routes (https://github.com/mpociot/laravel-apidoc-generator/pull/180)
-- `actAsUserId` option is no longer cast to an int (https://github.com/mpociot/laravel-apidoc-generator/pull/257)
+- Moved from command-line options to a config file  (https://github.com/mpociot/laravel-apidoc-generator/pull/362)
+- Commands have been renamed to the `apidoc` namespace (previously `api`). (https://github.com/mpociot/laravel-apidoc-generator/pull/350)
+- The `update` command has been renamed to `rebuild` and now uses the output path configured in the config file. (https://github.com/mpociot/laravel-apidoc-generator/pull/370)
+- `@resource` renamed to `@group` ()
 
 ### Fixed
-- `useMiddleware` option is now actually used (https://github.com/mpociot/laravel-apidoc-generator/pull/297/)
-- Changes to the info vendor view are now persisted (https://github.com/mpociot/laravel-apidoc-generator/pull/120)
-- Fixed memory leak issues (https://github.com/mpociot/laravel-apidoc-generator/pull/256)
-- Fixed issues with validating array parameters (https://github.com/mpociot/laravel-apidoc-generator/pull/299)
-- `@response` tag now parses content correctly as JSON (https://github.com/mpociot/laravel-apidoc-generator/pull/271)
 
 ### Removed

+ 38 - 19
README.md

@@ -1,6 +1,6 @@
 ## Laravel API Documentation Generator
 
-Automatically generate your API documentation from your existing Laravel/Lumen/[Dingo](https://github.com/dingo/api) routes. [Here's what the output looks like](http://marcelpociot.de/whiteboard/).
+Automatically generate your API documentation from your existing Laravel routes. Take a look at the [example documentation](http://marcelpociot.de/whiteboard/).
 
 `php artisan apidoc:generate`
 
@@ -11,13 +11,17 @@ Automatically generate your API documentation from your existing Laravel/Lumen/[
 [![Build Status](https://travis-ci.org/mpociot/laravel-apidoc-generator.svg?branch=master)](https://travis-ci.org/mpociot/laravel-apidoc-generator)
 [![StyleCI](https://styleci.io/repos/57999295/shield?style=flat)](https://styleci.io/repos/57999295)
 
-> Note: this is the documentation for version 3, which changes significantly from version 2. if you're on v2, you can check out its documentation [here](https://github.com/mpociot/laravel-apidoc-generator/blob/2.x/README.md). We strongly recommend you upgrade, though, as v3 is more robust and fixes a lot of the problems with v2.
 
 ## Installation
-> Note: version 3.x requires PHP 7 and Laravel 5.5 or higher.
+> Note: version 3.x requires PHP 7 and Laravel 5.5 or higher. Version 2.x requires Laravel 5.4.
 
 ```sh
-$ composer require mpociot/laravel-apidoc-generator:dev-master
+$ composer require mpociot/laravel-apidoc-generator
+```
+Using Laravel < 5.5? Go to your `config/app.php` and add the service provider:
+
+```php
+Mpociot\ApiDoc\ApiDocGeneratorServiceProvider::class,
 ```
 
 Then publish the config file by running:
@@ -29,21 +33,22 @@ This will create an `apidoc.php` file in your `config` folder.
 
 ## Usage
 Before you can generate your documentation, you'll need to configure a few things in your `config/apidoc.php`.
-- `output`
-This is the file path where the generated documentation will be written to. Default: **public/docs**
+### output
+This is the file path where the generated documentation will be written to. Default: `**public/docs**
 
-- `postman`
-Set this option to true if you want a Postman collection to be generated along with the documentation. Default: **true**
+### postman
+Set this option to true if you want a Postman collection to be generated along with the documentation. Default: `**true**
 
-- `router`
+### router
 The router to use when processing the route (can be Laravel or Dingo. Defaults to **Laravel**)
 
-- `routes`
+### routes
 This is where you specify what rules documentation should be generated for. You specify routes to be parsed by defining conditions that the routes should meet and rules that should be applied when generating documentation. These conditions and rules are specified in groups, allowing you to apply different rules to different routes.
 
 For instance, suppose your configuration looks like this:
 
 ```php
+<?php
 return [
      //...,
   
@@ -65,7 +70,7 @@ return [
 ];
 ```
 
-This means documentation will be generated for routes in all domains ('&ast;' is a wildcard meaning 'any character') which match any of the patterns 'api/&ast;' or 'v2-api/&ast;', excluding the 'users.create' route, and including the 'users.index' route. (The `versions` key is ignored unless you are using Dingo router).
+This means documentation will be generated for routes in all domains ('*' is a wildcard meaning 'any character') which match any of the patterns 'api/*' or 'v2-api/*', excluding the 'users.create' route, and including the 'users.index' route. (The `versions` key is ignored unless you are using Dingo router).
 Also, in the generated documentation, these routes will have the header 'Authorization: Bearer: {token}' added to the example requests.
 
 You can also separate routes into groups to apply different rules to them:
@@ -128,25 +133,39 @@ This package uses these resources to generate the API documentation:
 
 This package uses the HTTP controller doc blocks to create a table of contents and show descriptions for your API methods.
 
-Using `@group` in a doc block prior to each controller is useful as it creates a Group within the API documentation for all methods defined in that controller (rather than listing every method in a single list for all your controllers), but using `@resource` is not required. The short description after the `@resource` should be unique to allow anchor tags to navigate to this section. A longer description can be included below. Custom formatting and `<aside>` tags are also supported. (see the [Documentarian docs](http://marcelpociot.de/documentarian/installation/markdown_syntax))
+Using `@group` in a controller doc block creates a Group within the API documentation. All routes handled by that controller will be grouped under this group in the sidebar. The short description after the `@group` should be unique to allow anchor tags to navigate to this section. A longer description can be included below. Custom formatting and `<aside>` tags are also supported. (see the [Documentarian docs](http://marcelpociot.de/documentarian/installation/markdown_syntax))
+
+> Note: using `@group` is optional. Ungrouped routes will be placed in a "general" group.
 
 Above each method within the controller you wish to include in your API documentation you should have a doc block. This should include a unique short description as the first entry. An optional second entry can be added with further information. Both descriptions will appear in the API documentation in a different format as shown below.
+You can also specify an `@group` on a single method to override the group defined at the controller level.
 
 ```php
 /**
- * @resource Example
+ * @group User management
  *
- * Longer description
+ * APIs for managing users
  */
-class ExampleController extends Controller {
+class UserController extends Controller
+{
 
 	/**
-	 * This is the short description [and should be unique as anchor tags link to this in navigation menu]
+	 * Create a user
 	 *
-	 * This can be an optional longer description of your API call, used within the documentation.
+	 * [Insert optional longer description of the API endpoint here.]
+	 *
+	 */
+	 public function createUser()
+	 {
+
+	 }
+	 
+	/**
+	 * @group Account management
 	 *
 	 */
-	 public function foo(){
+	 public function changePassword()
+	 {
 
 	 }
 ```
@@ -264,7 +283,7 @@ If you are referring to the environment setting as shown above, then you should
 APP_URL=http://yourapp.app
 ```
 
-## Modifying the generated documentation
+## Modify the generated documentation
 
 If you want to modify the content of your generated documentation, go ahead and edit the generated `index.md` file.
 The default location of this file is: `public/docs/source/index.md`.

+ 23 - 10
src/Generators/AbstractGenerator.php

@@ -198,13 +198,13 @@ abstract class AbstractGenerator
     }
 
     /**
-     * @param  \Illuminate\Routing\Route  $route
+     * @param  \Illuminate\Routing\Route  $routeAction
      *
      * @return array
      */
-    protected function parseDocBlock($route)
+    protected function parseDocBlock(string $routeAction)
     {
-        list($class, $method) = explode('@', $route);
+        list($class, $method) = explode('@', $routeAction);
         $reflection = new ReflectionClass($class);
         $reflectionMethod = $reflection->getMethod($method);
 
@@ -219,17 +219,30 @@ abstract class AbstractGenerator
     }
 
     /**
-     * @param  string  $route
+     * @param  string  $routeAction
      *
      * @return string
      */
-    protected function getRouteGroup($route)
+    protected function getRouteGroup(string $routeAction)
     {
-        list($class, $method) = explode('@', $route);
-        $reflection = new ReflectionClass($class);
-        $comment = $reflection->getDocComment();
-        if ($comment) {
-            $phpdoc = new DocBlock($comment);
+        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();

+ 74 - 0
src/Tools/ResponseResolver.php

@@ -0,0 +1,74 @@
+<?php
+
+namespace Mpociot\ApiDoc\Tools;
+
+use Illuminate\Routing\Route;
+use Dingo\Api\Routing\RouteCollection;
+use Illuminate\Support\Facades\Route as RouteFacade;
+
+class RouteMatcher
+{
+    public function getDingoRoutesToBeDocumented(array $routeRules)
+    {
+        return $this->getRoutesToBeDocumented($routeRules, true);
+    }
+
+    public function getLaravelRoutesToBeDocumented(array $routeRules)
+    {
+        return $this->getRoutesToBeDocumented($routeRules);
+    }
+
+    public function getRoutesToBeDocumented(array $routeRules, bool $usingDingoRouter = false)
+    {
+        $matchedRoutes = [];
+
+        foreach ($routeRules as $routeRule) {
+            $excludes = $routeRule['exclude'] ?? [];
+            $includes = $routeRule['include'] ?? [];
+            $allRoutes = $this->getAllRoutes($usingDingoRouter, $routeRule['match']['versions'] ?? []);
+
+            foreach ($allRoutes as $route) {
+                /** @var Route $route */
+                if (in_array($route->getName(), $excludes)) {
+                    continue;
+                }
+
+                if ($this->shouldIncludeRoute($route, $routeRule, $includes, $usingDingoRouter)) {
+                    $matchedRoutes[] = [
+                        'route' => $route,
+                        'apply' => $routeRule['apply'] ?? [],
+                    ];
+                    continue;
+                }
+            }
+        }
+
+        return $matchedRoutes;
+    }
+
+    private function getAllRoutes(bool $usingDingoRouter, array $versions = [])
+    {
+        if (! $usingDingoRouter) {
+            return RouteFacade::getRoutes();
+        }
+
+        $allRouteCollections = app(\Dingo\Api\Routing\Router::class)->getRoutes();
+
+        return collect($allRouteCollections)
+            ->flatMap(function (RouteCollection $collection) {
+                return $collection->getRoutes();
+            })->toArray();
+    }
+
+    private function shouldIncludeRoute(Route $route, array $routeRule, array $mustIncludes, bool $usingDingoRouter)
+    {
+        $matchesVersion = $usingDingoRouter
+            ? ! empty(array_intersect($route->versions(), $routeRule['match']['versions'] ?? []))
+            : true;
+
+        return in_array($route->getName(), $mustIncludes)
+            || (str_is($routeRule['match']['domains'] ?? [], $route->getDomain())
+            && str_is($routeRule['match']['prefixes'] ?? [], $route->uri())
+            && $matchesVersion);
+    }
+}

+ 11 - 0
tests/Fixtures/TestController.php

@@ -5,6 +5,9 @@ namespace Mpociot\ApiDoc\Tests\Fixtures;
 use Illuminate\Http\Request;
 use Illuminate\Routing\Controller;
 
+/**
+ * @group Group A
+ */
 class TestController extends Controller
 {
     public function dummy()
@@ -22,6 +25,14 @@ class TestController extends Controller
         return '';
     }
 
+    /**
+     * @group Group B
+     */
+    public function withGroupOverride()
+    {
+        return '';
+    }
+
     /**
      * @bodyParam user_id int required The id of the user.
      * @bodyParam room_id string The id of the room.

+ 1 - 1
tests/Fixtures/collection.json

@@ -1 +1 @@
-{"variables":[],"info":{"name":"","_postman_id":"","description":"","schema":"https:\/\/schema.getpostman.com\/json\/collection\/v2.0.0\/collection.json"},"item":[{"name":"general","description":"","item":[{"name":"Example title.","request":{"url":"http:\/\/localhost\/api\/test","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"This will be the long description.\nIt can also be multiple lines long.","response":[]}},{"name":"http:\/\/localhost\/api\/responseTag","request":{"url":"http:\/\/localhost\/api\/responseTag","method":"POST","body":{"mode":"formdata","formdata":[]},"description":"","response":[]}}]}]}
+{"variables":[],"info":{"name":"","_postman_id":"","description":"","schema":"https:\/\/schema.getpostman.com\/json\/collection\/v2.0.0\/collection.json"},"item":[{"name":"Group A","description":"","item":[{"name":"Example title.","request":{"url":"http:\/\/localhost\/api\/test","method":"GET","body":{"mode":"formdata","formdata":[]},"description":"This will be the long description.\nIt can also be multiple lines long.","response":[]}},{"name":"http:\/\/localhost\/api\/responseTag","request":{"url":"http:\/\/localhost\/api\/responseTag","method":"POST","body":{"mode":"formdata","formdata":[]},"description":"","response":[]}}]}]}

+ 27 - 9
tests/Unit/GeneratorTestCase.php

@@ -31,7 +31,7 @@ abstract class GeneratorTestCase extends TestCase
     }
 
     /** @test */
-    public function test_can_parse_endpoint_description()
+    public function can_parse_endpoint_description()
     {
         $route = $this->createRoute('GET', '/api/test', 'withEndpointDescription');
         $parsed = $this->generator->processRoute($route);
@@ -41,7 +41,7 @@ abstract class GeneratorTestCase extends TestCase
     }
 
     /** @test */
-    public function test_can_parse_body_parameters()
+    public function can_parse_body_parameters()
     {
         $route = $this->createRoute('GET', '/api/test', 'withBodyParameters');
         $parameters = $this->generator->processRoute($route)['parameters'];
@@ -79,9 +79,27 @@ abstract class GeneratorTestCase extends TestCase
             ],
         ], $parameters);
     }
+    
+    /** @test */
+    public function can_parse_route_group()
+    {
+        $route = $this->createRoute('GET', '/api/test', 'dummy');
+        $routeGroup = $this->generator->processRoute($route)['group'];
+
+        $this->assertSame('Group A', $routeGroup);
+    }
+    
+    /** @test */
+    public function method_can_override_controller_group()
+    {
+        $route = $this->createRoute('GET', '/api/test', 'withGroupOverride');
+        $routeGroup = $this->generator->processRoute($route)['group'];
+
+        $this->assertSame('Group B', $routeGroup);
+    }
 
     /** @test */
-    public function test_can_parse_auth_tags()
+    public function can_parse_auth_tags()
     {
         $route = $this->createRoute('GET', '/api/test', 'withAuthenticatedTag');
         $authenticated = $this->generator->processRoute($route)['authenticated'];
@@ -93,7 +111,7 @@ abstract class GeneratorTestCase extends TestCase
     }
 
     /** @test */
-    public function test_can_parse_route_methods()
+    public function can_parse_route_methods()
     {
         $route = $this->createRoute('GET', '/get', 'withEndpointDescription');
         $parsed = $this->generator->processRoute($route);
@@ -113,7 +131,7 @@ abstract class GeneratorTestCase extends TestCase
     }
 
     /** @test */
-    public function test_can_parse_response_tag()
+    public function can_parse_response_tag()
     {
         $route = $this->createRoute('POST', '/responseTag', 'withResponseTag');
 
@@ -132,7 +150,7 @@ abstract class GeneratorTestCase extends TestCase
     }
 
     /** @test */
-    public function test_can_parse_transformer_tag()
+    public function can_parse_transformer_tag()
     {
         $route = $this->createRoute('GET', '/transformerTag', 'transformerTag');
         $parsed = $this->generator->processRoute($route);
@@ -146,7 +164,7 @@ abstract class GeneratorTestCase extends TestCase
     }
 
     /** @test */
-    public function test_can_parse_transformer_tag_with_model()
+    public function can_parse_transformer_tag_with_model()
     {
         $route = $this->createRoute('GET', '/transformerTagWithModel', 'transformerTagWithModel');
         $parsed = $this->generator->processRoute($route);
@@ -160,7 +178,7 @@ abstract class GeneratorTestCase extends TestCase
     }
 
     /** @test */
-    public function test_can_parse_transformer_collection_tag()
+    public function can_parse_transformer_collection_tag()
     {
         $route = $this->createRoute('GET', '/transformerCollectionTag', 'transformerCollectionTag');
         $parsed = $this->generator->processRoute($route);
@@ -175,7 +193,7 @@ abstract class GeneratorTestCase extends TestCase
     }
 
     /** @test */
-    public function test_can_parse_transformer_collection_tag_with_model()
+    public function can_parse_transformer_collection_tag_with_model()
     {
         $route = $this->createRoute('GET', '/transformerCollectionTagWithModel', 'transformerCollectionTagWithModel');
         $parsed = $this->generator->processRoute($route);