Просмотр исходного кода

Easier example language customisations

shalvah 6 лет назад
Родитель
Сommit
0aa737a2e5

+ 13 - 0
config/apidoc.php

@@ -190,6 +190,19 @@ return [
      */
     'default_group' => 'general',
 
+    /*
+     * Example requests for each endpoint will be shown in each of these languages.
+     * Supported options are: bash, javascript, php
+     * You can add a language of your own, but you must publish the package's views
+     * and define a corresponding view for it in the partials/example-requests directory.
+     * See https://laravel-apidoc-generator.readthedocs.io/en/latest/generating-documentation.html
+     *
+     */
+    'example_languages' => [
+        'bash',
+        'javascript',
+    ],
+
     /*
      * Configure how responses are transformed using @transformer and @transformerCollection
      * Requires league/fractal package: composer require league/fractal

+ 3 - 0
docs/config.md

@@ -31,6 +31,9 @@ If you want to use this, please note that the image size must be 230 x 52.
 ## `default_group`
 When [documenting your api](documenting.md), you use `@group` annotations to group API endpoints. Endpoints which do not have a ggroup annotation will be grouped under the `default_group`. Defaults to **"general"**.
 
+## example_languages
+For each endpoint, an example request is shown in each of the languages specified in this array. Currently only `bash`, `javascript` and `php` are supported. You can add your own language, but you must also define the corresponding view (see [Specifying languages for examples](generating-documentation.html#specifying-language-for-examples)). Default: `["bash", "javascript"]` 
+ 
 ##  `faker_seed`
 When generating example requests, this package uses fzanninoto/faker to generate random values. If you would like the package to generate the same example values for parameters on each run, set this to any number (eg. 1234). (Note: alternatively, you can set example values for parameters when [documenting them.](documenting.html#specifying-request-parameters))
        

+ 22 - 0
docs/generating-documentation.md

@@ -35,6 +35,28 @@ php artisan apidoc:rebuild
  If you wish to automatically add the same content to the docs every time you generate (for instance, an introduction, a disclaimer or an authenticatino guide), you can add a `prepend.md` and/or `append.md` file to the `source` folder in the `output` directory, and they will be added to the generated documentation. 
  
  The contents of `prepend.md` will be added after the front matter and info text, while the contents of `append.md` will be added at the end of the document.
+ 
+ ## Specifying language for examples
+ For each endpoint, an example request is shown in [each language configured](config.html#example_languages). To add a language which is not supported by this package, you'll have to create your own view for how an example should render. Here's how:
+ 
+ - Publish the vendor views by running:
+ 
+ ```bash
+ php artisan vendor:publish --provider="Mpociot\ApiDoc\ApiDocGeneratorServiceProvider" --tag=apidoc-views
+ ```
+ 
+ This will copy the views files to `\resources\views\vendor\apidoc`.
+ 
+ - Next, create a file called {language-name}.blade.php (for example, python.blade.php) in the partials/example-requests directory. You can then write Markdown with Blade templating that describes how the example request for the language should be rendered. You have the `$route` variable available to you. This variable is an array with the following keys:
+    - `methods`: an array of the HTTP methods for that route
+    - `boundUri`: the complete URL for the route, with any url parameters replaced (/users/{id} -> /users/1)
+    - `headers`: key-value array of headers to be sent with route (according to your configuration)
+    - `cleanQueryParameters`: key-value array of query parameters (with example values) to be sent with the request
+    - `cleanBodyParameters`: key-value array of body parameters (with example values) to be sent with the request
+
+- Add the language to the `example_languages` array in the package config.
+
+- Generate your documentation 
 
 ## Further modification
 

+ 12 - 0
resources/views/partials/example-requests/bash.blade.php

@@ -0,0 +1,12 @@
+```bash
+curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ''}}"{{ trim(config('app.docs_url') ?: config('app.url'), '/')}}/{{ ltrim($route['boundUri'], '/') }}" @if(count($route['headers']))\
+@foreach($route['headers'] as $header => $value)
+    -H "{{$header}}: {{$value}}"@if(! ($loop->last) || ($loop->last && count($route['bodyParameters']))) \
+@endif
+@endforeach
+@endif
+@if(count($route['cleanBodyParameters']))
+    -d '{!! json_encode($route['cleanBodyParameters']) !!}'
+@endif
+
+```

+ 38 - 0
resources/views/partials/example-requests/javascript.blade.php

@@ -0,0 +1,38 @@
+```javascript
+const url = new URL("{{ rtrim(config('app.docs_url') ?: config('app.url'), '/') }}/{{ ltrim($route['boundUri'], '/') }}");
+@if(count($route['queryParameters']))
+
+    let params = {
+    @foreach($route['queryParameters'] as $attribute => $parameter)
+        "{{ $attribute }}": "{{ $parameter['value'] }}",
+    @endforeach
+    };
+    Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
+@endif
+
+let headers = {
+@foreach($route['headers'] as $header => $value)
+    "{{$header}}": "{{$value}}",
+@endforeach
+@if(!array_key_exists('Accept', $route['headers']))
+    "Accept": "application/json",
+@endif
+@if(!array_key_exists('Content-Type', $route['headers']))
+    "Content-Type": "application/json",
+@endif
+}
+@if(count($route['bodyParameters']))
+
+let body = {!! json_encode($route['cleanBodyParameters'], JSON_PRETTY_PRINT) !!}
+@endif
+
+fetch(url, {
+    method: "{{$route['methods'][0]}}",
+    headers: headers,
+@if(count($route['bodyParameters']))
+    body: body
+@endif
+})
+    .then(response => response.json())
+    .then(json => console.log(json));
+```

+ 5 - 3
resources/views/partials/frontmatter.blade.php

@@ -1,12 +1,14 @@
 title: API Reference
 
 language_tabs:
-- bash
-- javascript
+@foreach($settings['languages'] as $language)
+- {{ $language }}
+
+@endforeach
 
 includes:
 
 search: true
 
 toc_footers:
-- <a href='http://github.com/mpociot/documentarian'>Documentation Powered by Documentarian</a>
+- <a href='http://github.com/mpociot/documentarian'>Documentation Powered by Documentarian</a>

+ 3 - 49
resources/views/partials/route.blade.php

@@ -11,63 +11,17 @@
 
 > Example request:
 
-```bash
-curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ''}}"{{ trim(config('app.docs_url') ?: config('app.url'), '/')}}/{{ ltrim($route['boundUri'], '/') }}" @if(count($route['headers']))\
-@foreach($route['headers'] as $header => $value)
-    -H "{{$header}}: {{$value}}"@if(! ($loop->last) || ($loop->last && count($route['bodyParameters']))) \
-@endif
-@endforeach
-@endif
-@if(count($route['cleanBodyParameters']))
-    -d '{!! json_encode($route['cleanBodyParameters']) !!}'
-@endif
-
-```
-
-```javascript
-const url = new URL("{{ rtrim(config('app.docs_url') ?: config('app.url'), '/') }}/{{ ltrim($route['boundUri'], '/') }}");
-@if(count($route['queryParameters']))
-
-    let params = {
-    @foreach($route['queryParameters'] as $attribute => $parameter)
-        "{{ $attribute }}": "{{ $parameter['value'] }}",
-    @endforeach
-    };
-    Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
-@endif
+@foreach($settings['languages'] as $language)
+@include("apidoc::partials.example-requests.$language")
 
-let headers = {
-@foreach($route['headers'] as $header => $value)
-    "{{$header}}": "{{$value}}",
 @endforeach
-@if(!array_key_exists('Accept', $route['headers']))
-    "Accept": "application/json",
-@endif
-@if(!array_key_exists('Content-Type', $route['headers']))
-    "Content-Type": "application/json",
-@endif
-}
-@if(count($route['bodyParameters']))
-
-let body = {!! json_encode($route['cleanBodyParameters'], JSON_PRETTY_PRINT) !!}
-@endif
-
-fetch(url, {
-    method: "{{$route['methods'][0]}}",
-    headers: headers,
-@if(count($route['bodyParameters']))
-    body: body
-@endif
-})
-    .then(response => response.json())
-    .then(json => console.log(json));
-```
 
 @if(in_array('GET',$route['methods']) || (isset($route['showresponse']) && $route['showresponse']))
 @if(is_array($route['response']))
 @foreach($route['response'] as $response)
 > Example response ({{$response['status']}}):
 
+
 ```json
 @if(is_object($response['content']) || is_array($response['content']))
 {!! json_encode($response['content'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) !!}

+ 9 - 4
src/Commands/GenerateDocumentation.php

@@ -83,18 +83,23 @@ class GenerateDocumentation extends Command
             ->with('outputPath', ltrim($outputPath, 'public/'))
             ->with('showPostmanCollectionButton', $this->shouldGeneratePostmanCollection());
 
-        $parsedRouteOutput = $parsedRoutes->map(function ($routeGroup) {
-            return $routeGroup->map(function ($route) {
+        $settings = ['languages' => config('apidoc.example_languages')];
+        $parsedRouteOutput = $parsedRoutes->map(function ($routeGroup) use ($settings) {
+            return $routeGroup->map(function ($route) use ($settings) {
                 if (count($route['cleanBodyParameters']) && ! isset($route['headers']['Content-Type'])) {
                     $route['headers']['Content-Type'] = 'application/json';
                 }
-                $route['output'] = (string) view('apidoc::partials.route')->with('route', $route)->render();
+                $route['output'] = (string) view('apidoc::partials.route')
+                    ->with('route', $route)
+                    ->with('settings', $settings)
+                    ->render();
 
                 return $route;
             });
         });
 
-        $frontmatter = view('apidoc::partials.frontmatter');
+        $frontmatter = view('apidoc::partials.frontmatter')
+            ->with('settings', $settings);
         /*
          * In case the target file already exists, we should check if the documentation was modified
          * and skip the modified parts of the routes.

+ 1 - 0
src/Tools/Generator.php

@@ -79,6 +79,7 @@ class Generator
             'queryParameters' => $queryParameters,
             'bodyParameters' => $bodyParameters,
             'cleanBodyParameters' => $this->cleanParams($bodyParameters),
+            'cleanQueryParameters' => $this->cleanParams($queryParameters),
             'authenticated' => $this->getAuthStatusFromDocBlock($docBlock['tags']),
             'response' => $content,
             'showresponse' => ! empty($content),