Ver código fonte

Merge pull request #552 from MarnuLombard/feature/examples/exclude_from_examples

Allows users to exclude a parameter from having an example
Shalvah 5 anos atrás
pai
commit
9d366efec8

+ 13 - 0
docs/documenting.md

@@ -97,6 +97,19 @@ Note: a random value will be used as the value of each parameter in the example
      */
 ```
 
+Note: To exclude a particular parameter from the generated examples (for all languages), you can annotate it with `No-example`. For instance:
+```php
+       /**
+        * @queryParam location_id required The id of the location. Example: 1
+        * @queryParam user_id required The id of the user. No-example
+        * @queryParam page required The page number. Example: 4
+        */
+```
+Outputs: 
+```bash
+curl -X GET -G "https://example.com/api?location_id=1&page=4"
+```
+
 Note: You can also add the `@queryParam` and `@bodyParam` annotations to a `\Illuminate\Foundation\Http\FormRequest` subclass instead, if you are using one in your controller method
 
 ```php

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

@@ -1,6 +1,6 @@
 ```bash
-curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ''}}"{{ rtrim($baseUrl, '/')}}/{{ ltrim($route['boundUri'], '/') }}@if(count($route['queryParameters']))?@foreach($route['queryParameters'] as $attribute => $parameter)
-{{ urlencode($attribute) }}={{ urlencode($parameter['value']) }}@if(!$loop->last)&@endif
+curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ''}}"{{ rtrim($baseUrl, '/')}}/{{ ltrim($route['boundUri'], '/') }}@if(count($route['cleanQueryParameters']))?@foreach($route['cleanQueryParameters'] as $parameter => $value)
+{{ urlencode($parameter) }}={{ urlencode($value) }}@if(!$loop->last)&@endif
 @endforeach
 @endif" @if(count($route['headers']))\
 @foreach($route['headers'] as $header => $value)
@@ -12,4 +12,4 @@ curl -X {{$route['methods'][0]}} {{$route['methods'][0] == 'GET' ? '-G ' : ''}}"
     -d '{!! json_encode($route['cleanBodyParameters']) !!}'
 @endif
 
-```
+```

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

@@ -1,10 +1,10 @@
 ```javascript
 const url = new URL("{{ rtrim($baseUrl, '/') }}/{{ ltrim($route['boundUri'], '/') }}");
-@if(count($route['queryParameters']))
+@if(count($route['cleanQueryParameters']))
 
     let params = {
-    @foreach($route['queryParameters'] as $attribute => $parameter)
-        "{{ $attribute }}": "{{ $parameter['value'] }}",
+    @foreach($route['cleanQueryParameters'] as $parameter => $value)
+        "{{ $parameter }}": "{{ $value }}",
     @endforeach
     };
     Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
@@ -35,4 +35,4 @@ fetch(url, {
 })
     .then(response => response.json())
     .then(json => console.log(json));
-```
+```

+ 0 - 1
resources/views/partials/route.blade.php

@@ -14,7 +14,6 @@
 @foreach($settings['languages'] as $language)
 @include("apidoc::partials.example-requests.$language")
 
-
 @endforeach
 
 @if(in_array('GET',$route['methods']) || (isset($route['showresponse']) && $route['showresponse']))

+ 17 - 2
src/Tools/Generator.php

@@ -133,6 +133,7 @@ class Generator
             })
             ->mapWithKeys(function ($tag) {
                 preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
+                $content = preg_replace('/\s?No-example.?/', '', $content);
                 if (empty($content)) {
                     // this means only name and type were supplied
                     list($name, $type) = preg_split('/\s+/', $tag->getContent());
@@ -150,7 +151,7 @@ class Generator
 
                 $type = $this->normalizeParameterType($type);
                 list($description, $example) = $this->parseDescription($description, $type);
-                $value = is_null($example) ? $this->generateDummyValue($type) : $example;
+                $value = is_null($example) && ! $this->shouldExcludeExample($tag) ? $this->generateDummyValue($type) : $example;
 
                 return [$name => compact('type', 'description', 'required', 'value')];
             })->toArray();
@@ -208,6 +209,7 @@ class Generator
             })
             ->mapWithKeys(function ($tag) {
                 preg_match('/(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
+                $content = preg_replace('/\s?No-example.?/', '', $content);
                 if (empty($content)) {
                     // this means only name was supplied
                     list($name) = preg_split('/\s+/', $tag->getContent());
@@ -224,7 +226,7 @@ class Generator
                 }
 
                 list($description, $value) = $this->parseDescription($description, 'string');
-                if (is_null($value)) {
+                if (is_null($value) && ! $this->shouldExcludeExample($tag)) {
                     $value = str_contains($description, ['number', 'count', 'page'])
                         ? $this->generateDummyValue('integer')
                         : $this->generateDummyValue('string');
@@ -394,6 +396,19 @@ class Generator
         return [$description, $example];
     }
 
+    /**
+     * Allows users to specify that we shouldn't generate an example for the parameter
+     * by writing 'No-example'.
+     *
+     * @param Tag $tag
+     *
+     * @return bool Whether no example should be generated
+     */
+    private function shouldExcludeExample(Tag $tag)
+    {
+        return strpos($tag->getContent(), ' No-example') !== false;
+    }
+
     /**
      * Cast a value from a string to a specified type.
      *

+ 5 - 1
src/Tools/Traits/ParamHelpers.php

@@ -5,7 +5,7 @@ namespace Mpociot\ApiDoc\Tools\Traits;
 trait ParamHelpers
 {
     /**
-     * Create proper arrays from dot-noted parameter names.
+     * Create proper arrays from dot-noted parameter names. Also filter out parameters which were excluded from having examples.
      *
      * @param array $params
      *
@@ -14,6 +14,10 @@ trait ParamHelpers
     protected function cleanParams(array $params)
     {
         $values = [];
+        $params = array_filter($params, function ($details) {
+            return ! is_null($details['value']);
+        });
+
         foreach ($params as $name => $details) {
             $this->cleanValueFrom($name, $details['value'], $values);
         }

+ 10 - 0
tests/Fixtures/TestController.php

@@ -114,6 +114,16 @@ class TestController extends Controller
         return '';
     }
 
+    /**
+     * @bodyParam included string required Exists in examples. Example: 'Here'
+     * @bodyParam  excluded_body_param int Does not exist in examples. No-example
+     * @queryParam excluded_query_param Does not exist in examples. No-example
+     */
+    public function withExcludedExamples()
+    {
+        return '';
+    }
+
     /**
      * @authenticated
      */

+ 33 - 0
tests/Unit/GeneratorTestCase.php

@@ -209,6 +209,39 @@ abstract class GeneratorTestCase extends TestCase
         ], $queryParameters);
     }
 
+    /** @test */
+    public function it_does_not_generate_values_for_excluded_params_and_excludes_them_from_clean_params()
+    {
+        $route = $this->createRoute('GET', '/api/test', 'withExcludedExamples');
+        $parsed = $this->generator->processRoute($route);
+        $cleanBodyParameters = $parsed['cleanBodyParameters'];
+        $cleanQueryParameters = $parsed['cleanQueryParameters'];
+        $bodyParameters = $parsed['bodyParameters'];
+        $queryParameters = $parsed['queryParameters'];
+
+        $this->assertArrayHasKey('included', $cleanBodyParameters);
+        $this->assertArrayNotHasKey('excluded_body_param', $cleanBodyParameters);
+        $this->assertEmpty($cleanQueryParameters);
+
+        $this->assertArraySubset([
+            'included' => [
+                'required' => true,
+                'type' => 'string',
+                'description' => 'Exists in examples.',
+            ],
+            'excluded_body_param' => [
+                'type' => 'integer',
+                'description' => 'Does not exist in examples.',
+            ],
+        ], $bodyParameters);
+
+        $this->assertArraySubset([
+            'excluded_query_param' => [
+                'description' => 'Does not exist in examples.',
+            ],
+        ], $queryParameters);
+    }
+
     /** @test */
     public function can_parse_route_group()
     {