Completed
Pull Request — master (#443)
by
unknown
02:22 queued 41s
created

GenerateDocumentation::isValidRoute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Mpociot\ApiDoc\Commands;
4
5
use ReflectionClass;
6
use ReflectionException;
7
use Illuminate\Routing\Route;
8
use Illuminate\Console\Command;
9
use Mpociot\Reflection\DocBlock;
10
use Illuminate\Support\Collection;
11
use Mpociot\ApiDoc\Tools\Generator;
12
use Mpociot\ApiDoc\Tools\RouteMatcher;
13
use Mpociot\Documentarian\Documentarian;
14
use Mpociot\ApiDoc\Postman\CollectionWriter;
15
16
class GenerateDocumentation extends Command
17
{
18
    /**
19
     * The name and signature of the console command.
20
     *
21
     * @var string
22
     */
23
    protected $signature = 'apidoc:generate
24
                            {--force : Force rewriting of existing routes}
25
    ';
26
27
    /**
28
     * The console command description.
29
     *
30
     * @var string
31
     */
32
    protected $description = 'Generate your API documentation from existing Laravel routes.';
33
34
    private $routeMatcher;
35
36
    public function __construct(RouteMatcher $routeMatcher)
37
    {
38
        parent::__construct();
39
        $this->routeMatcher = $routeMatcher;
40
    }
41
42
    /**
43
     * Execute the console command.
44
     *
45
     * @return void
46
     */
47
    public function handle()
48
    {
49
        $usingDingoRouter = strtolower(config('apidoc.router')) == 'dingo';
50
        if ($usingDingoRouter) {
51
            $routes = $this->routeMatcher->getDingoRoutesToBeDocumented(config('apidoc.routes'));
52
        } else {
53
            $routes = $this->routeMatcher->getLaravelRoutesToBeDocumented(config('apidoc.routes'));
54
        }
55
56
        $generator = new Generator();
57
        $parsedRoutes = $this->processRoutes($generator, $routes);
58
        $parsedRoutes = collect($parsedRoutes)->groupBy('group')
59
            ->sortBy(static function ($group) {
60
                /* @var $group Collection */
61
                return $group->first()['group'];
62
            }, SORT_NATURAL);
63
64
        $this->writeMarkdown($parsedRoutes);
65
    }
66
67
    /**
68
     * @param  Collection $parsedRoutes
69
     *
70
     * @return void
71
     */
72
    private function writeMarkdown($parsedRoutes)
73
    {
74
        $outputPath = config('apidoc.output');
75
        $targetFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'index.md';
76
        $compareFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'.compare.md';
77
        $prependFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'prepend.md';
78
        $appendFile = $outputPath.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR.'append.md';
79
80
        $infoText = view('apidoc::partials.info')
81
            ->with('outputPath', ltrim($outputPath, 'public/'))
82
            ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection());
83
84
        $parsedRouteOutput = $parsedRoutes->map(function ($routeGroup) {
85
            return $routeGroup->map(function ($route) {
86
                $route['output'] = (string) view('apidoc::partials.route')->with('route', $route)->render();
87
88
                return $route;
89
            });
90
        });
91
92
        $frontmatter = view('apidoc::partials.frontmatter');
93
        /*
94
         * In case the target file already exists, we should check if the documentation was modified
95
         * and skip the modified parts of the routes.
96
         */
97
        if (file_exists($targetFile) && file_exists($compareFile)) {
98
            $generatedDocumentation = file_get_contents($targetFile);
99
            $compareDocumentation = file_get_contents($compareFile);
100
101
            if (preg_match('/---(.*)---\\s<!-- START_INFO -->/is', $generatedDocumentation, $generatedFrontmatter)) {
102
                $frontmatter = trim($generatedFrontmatter[1], "\n");
103
            }
104
105
            $parsedRouteOutput->transform(function ($routeGroup) use ($generatedDocumentation, $compareDocumentation) {
106
                return $routeGroup->transform(function ($route) use ($generatedDocumentation, $compareDocumentation) {
107
                    if (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $generatedDocumentation, $existingRouteDoc)) {
108
                        $routeDocumentationChanged = (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $compareDocumentation, $lastDocWeGeneratedForThisRoute) && $lastDocWeGeneratedForThisRoute[1] !== $existingRouteDoc[1]);
109
                        if ($routeDocumentationChanged === false || $this->option('force')) {
110
                            if ($routeDocumentationChanged) {
111
                                $this->warn('Discarded manual changes for route ['.implode(',', $route['methods']).'] '.$route['uri']);
112
                            }
113
                        } else {
114
                            $this->warn('Skipping modified route ['.implode(',', $route['methods']).'] '.$route['uri']);
115
                            $route['modified_output'] = $existingRouteDoc[0];
116
                        }
117
                    }
118
119
                    return $route;
120
                });
121
            });
122
        }
123
124
        $prependFileContents = file_exists($prependFile)
125
            ? file_get_contents($prependFile)."\n" : '';
126
        $appendFileContents = file_exists($appendFile)
127
            ? "\n".file_get_contents($appendFile) : '';
128
129
        $documentarian = new Documentarian();
130
131
        $markdown = view('apidoc::documentarian')
132
            ->with('writeCompareFile', false)
133
            ->with('frontmatter', $frontmatter)
134
            ->with('infoText', $infoText)
135
            ->with('prependMd', $prependFileContents)
136
            ->with('appendMd', $appendFileContents)
137
            ->with('outputPath', config('apidoc.output'))
138
            ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection())
139
            ->with('parsedRoutes', $parsedRouteOutput);
140
141
        if (! is_dir($outputPath)) {
142
            $documentarian->create($outputPath);
143
        }
144
145
        // Write output file
146
        file_put_contents($targetFile, $markdown);
147
148
        // Write comparable markdown file
149
        $compareMarkdown = view('apidoc::documentarian')
150
            ->with('writeCompareFile', true)
151
            ->with('frontmatter', $frontmatter)
152
            ->with('infoText', $infoText)
153
            ->with('prependMd', $prependFileContents)
154
            ->with('appendMd', $appendFileContents)
155
            ->with('outputPath', config('apidoc.output'))
156
            ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection())
157
            ->with('parsedRoutes', $parsedRouteOutput);
158
159
        file_put_contents($compareFile, $compareMarkdown);
160
161
        $this->info('Wrote index.md to: '.$outputPath);
162
163
        $this->info('Generating API HTML code');
164
165
        $documentarian->generate($outputPath);
166
167
        $this->info('Wrote HTML documentation to: '.$outputPath.'/index.html');
168
169
        if ($this->shouldGeneratePostmanCollection()) {
170
            $this->info('Generating Postman collection');
171
172
            file_put_contents($outputPath.DIRECTORY_SEPARATOR.'collection.json', $this->generatePostmanCollection($parsedRoutes));
173
        }
174
175
        if ($logo = config('apidoc.logo')) {
176
            copy(
177
                $logo,
178
                $outputPath.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'logo.png'
179
            );
180
        }
181
    }
182
183
    /**
184
     * @param Generator $generator
185
     * @param array $routes
186
     *
187
     * @return array
188
     */
189
    private function processRoutes(Generator $generator, array $routes)
190
    {
191
        $parsedRoutes = [];
192
        foreach ($routes as $routeItem) {
193
            $route = $routeItem['route'];
194
            /** @var Route $route */
195
            if ($this->isValidRoute($route) && $this->isRouteVisibleForDocumentation($route->getAction()['uses'])) {
196
                $parsedRoutes[] = $generator->processRoute($route, $routeItem['apply']);
197
                $this->info('Processed route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
198
            } else {
199
                $this->warn('Skipping route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
200
            }
201
        }
202
203
        return $parsedRoutes;
204
    }
205
206
    /**
207
     * @param $route
208
     *
209
     * @return bool
210
     */
211
    private function isValidRoute(Route $route)
212
    {
213
        return ! is_callable($route->getAction()['uses']) && ! is_null($route->getAction()['uses']);
214
    }
215
216
    /**
217
     * @param $route
218
     *
219
     * @throws ReflectionException
220
     *
221
     * @return bool
222
     */
223
    private function isRouteVisibleForDocumentation($route)
224
    {
225
        list($class, $method) = explode('@', $route);
226
        $reflection = new ReflectionClass($class);
227
228
        if (! $reflection->hasMethod($method)) {
229
            return false;
230
        }
231
232
        $comment = $reflection->getMethod($method)->getDocComment();
233
234
        if ($comment) {
235
            $phpdoc = new DocBlock($comment);
236
237
            return collect($phpdoc->getTags())
238
                ->filter(function ($tag) use ($route) {
239
                    return $tag->getName() === 'hideFromAPIDocumentation';
240
                })
241
                ->isEmpty();
242
        }
243
244
        return true;
245
    }
246
247
    /**
248
     * Generate Postman collection JSON file.
249
     *
250
     * @param Collection $routes
251
     *
252
     * @return string
253
     */
254
    private function generatePostmanCollection(Collection $routes)
255
    {
256
        $writer = new CollectionWriter($routes);
257
258
        return $writer->getCollection();
259
    }
260
261
    /**
262
     * Checks config if it should generate Postman collection.
263
     *
264
     * @return bool
265
     */
266
    private function shouldGeneratePostmanCollection()
267
    {
268
        return config('apidoc.postman.enabled', is_bool(config('apidoc.postman')) ? config('apidoc.postman') : false);
269
    }
270
}
271