Completed
Pull Request — master (#445)
by
unknown
02:10
created

GenerateDocumentation::writeMarkdown()   D

Complexity

Conditions 15
Paths 96

Size

Total Lines 113

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 113
rs 4.7333
c 0
b 0
f 0
cc 15
nc 96
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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', config('apidoc.postman'));
83
84
        $parsedRouteOutput = $parsedRoutes->map(function ($routeGroup) {
85
            return $routeGroup->map(function ($route) {
86
                if (count($route['cleanBodyParameters'])) {
87
                    $route['headers']['Content-Type'] = 'application/json';
88
                }
89
                $route['output'] = (string) view('apidoc::partials.route')->with('route', $route)->render();
90
91
                return $route;
92
            });
93
        });
94
95
        $frontmatter = view('apidoc::partials.frontmatter');
96
        /*
97
         * In case the target file already exists, we should check if the documentation was modified
98
         * and skip the modified parts of the routes.
99
         */
100
        if (file_exists($targetFile) && file_exists($compareFile)) {
101
            $generatedDocumentation = file_get_contents($targetFile);
102
            $compareDocumentation = file_get_contents($compareFile);
103
104
            if (preg_match('/---(.*)---\\s<!-- START_INFO -->/is', $generatedDocumentation, $generatedFrontmatter)) {
105
                $frontmatter = trim($generatedFrontmatter[1], "\n");
106
            }
107
108
            $parsedRouteOutput->transform(function ($routeGroup) use ($generatedDocumentation, $compareDocumentation) {
109
                return $routeGroup->transform(function ($route) use ($generatedDocumentation, $compareDocumentation) {
110
                    if (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $generatedDocumentation, $existingRouteDoc)) {
111
                        $routeDocumentationChanged = (preg_match('/<!-- START_'.$route['id'].' -->(.*)<!-- END_'.$route['id'].' -->/is', $compareDocumentation, $lastDocWeGeneratedForThisRoute) && $lastDocWeGeneratedForThisRoute[1] !== $existingRouteDoc[1]);
112
                        if ($routeDocumentationChanged === false || $this->option('force')) {
113
                            if ($routeDocumentationChanged) {
114
                                $this->warn('Discarded manual changes for route ['.implode(',', $route['methods']).'] '.$route['uri']);
115
                            }
116
                        } else {
117
                            $this->warn('Skipping modified route ['.implode(',', $route['methods']).'] '.$route['uri']);
118
                            $route['modified_output'] = $existingRouteDoc[0];
119
                        }
120
                    }
121
122
                    return $route;
123
                });
124
            });
125
        }
126
127
        $prependFileContents = file_exists($prependFile)
128
            ? file_get_contents($prependFile)."\n" : '';
129
        $appendFileContents = file_exists($appendFile)
130
            ? "\n".file_get_contents($appendFile) : '';
131
132
        $documentarian = new Documentarian();
133
134
        $markdown = view('apidoc::documentarian')
135
            ->with('writeCompareFile', false)
136
            ->with('frontmatter', $frontmatter)
137
            ->with('infoText', $infoText)
138
            ->with('prependMd', $prependFileContents)
139
            ->with('appendMd', $appendFileContents)
140
            ->with('outputPath', config('apidoc.output'))
141
            ->with('showPostmanCollectionButton', config('apidoc.postman'))
142
            ->with('parsedRoutes', $parsedRouteOutput);
143
144
        if (! is_dir($outputPath)) {
145
            $documentarian->create($outputPath);
146
        }
147
148
        // Write output file
149
        file_put_contents($targetFile, $markdown);
150
151
        // Write comparable markdown file
152
        $compareMarkdown = view('apidoc::documentarian')
153
            ->with('writeCompareFile', true)
154
            ->with('frontmatter', $frontmatter)
155
            ->with('infoText', $infoText)
156
            ->with('prependMd', $prependFileContents)
157
            ->with('appendMd', $appendFileContents)
158
            ->with('outputPath', config('apidoc.output'))
159
            ->with('showPostmanCollectionButton', config('apidoc.postman'))
160
            ->with('parsedRoutes', $parsedRouteOutput);
161
162
        file_put_contents($compareFile, $compareMarkdown);
163
164
        $this->info('Wrote index.md to: '.$outputPath);
165
166
        $this->info('Generating API HTML code');
167
168
        $documentarian->generate($outputPath);
169
170
        $this->info('Wrote HTML documentation to: '.$outputPath.'/index.html');
171
172
        if (config('apidoc.postman')) {
173
            $this->info('Generating Postman collection');
174
175
            file_put_contents($outputPath.DIRECTORY_SEPARATOR.'collection.json', $this->generatePostmanCollection($parsedRoutes));
176
        }
177
178
        if ($logo = config('apidoc.logo')) {
179
            copy(
180
                $logo,
181
                $outputPath.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'logo.png'
182
            );
183
        }
184
    }
185
186
    /**
187
     * @param Generator $generator
188
     * @param array $routes
189
     *
190
     * @return array
191
     */
192
    private function processRoutes(Generator $generator, array $routes)
193
    {
194
        $parsedRoutes = [];
195
        foreach ($routes as $routeItem) {
196
            $route = $routeItem['route'];
197
            /** @var Route $route */
198
            if ($this->isValidRoute($route) && $this->isRouteVisibleForDocumentation($route->getAction()['uses'])) {
199
                $parsedRoutes[] = $generator->processRoute($route, $routeItem['apply']);
200
                $this->info('Processed route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
201
            } else {
202
                $this->warn('Skipping route: ['.implode(',', $generator->getMethods($route)).'] '.$generator->getUri($route));
203
            }
204
        }
205
206
        return $parsedRoutes;
207
    }
208
209
    /**
210
     * @param $route
211
     *
212
     * @return bool
213
     */
214
    private function isValidRoute(Route $route)
215
    {
216
        return ! is_callable($route->getAction()['uses']) && ! is_null($route->getAction()['uses']);
217
    }
218
219
    /**
220
     * @param $route
221
     *
222
     * @throws ReflectionException
223
     *
224
     * @return bool
225
     */
226
    private function isRouteVisibleForDocumentation($route)
227
    {
228
        list($class, $method) = explode('@', $route);
229
        $reflection = new ReflectionClass($class);
230
231
        if (! $reflection->hasMethod($method)) {
232
            return false;
233
        }
234
235
        $comment = $reflection->getMethod($method)->getDocComment();
236
237
        if ($comment) {
238
            $phpdoc = new DocBlock($comment);
239
240
            return collect($phpdoc->getTags())
241
                ->filter(function ($tag) use ($route) {
242
                    return $tag->getName() === 'hideFromAPIDocumentation';
243
                })
244
                ->isEmpty();
245
        }
246
247
        return true;
248
    }
249
250
    /**
251
     * Generate Postman collection JSON file.
252
     *
253
     * @param Collection $routes
254
     *
255
     * @return string
256
     */
257
    private function generatePostmanCollection(Collection $routes)
258
    {
259
        $writer = new CollectionWriter($routes);
260
261
        return $writer->getCollection();
262
    }
263
}
264