Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Headers from tags #812

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config/apidoc.php
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@
],
'headers' => [
\Mpociot\ApiDoc\Extracting\Strategies\RequestHeaders\GetFromRouteRules::class,
\Mpociot\ApiDoc\Extracting\Strategies\RequestHeaders\GetFromHeaderTag::class,
],
'bodyParameters' => [
\Mpociot\ApiDoc\Extracting\Strategies\BodyParameters\GetFromBodyParamTag::class,
Expand Down
2 changes: 1 addition & 1 deletion resources/views/partials/example-requests/bash.blade.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
```bash
curl -X {{$route['methods'][0]}} \
{{$route['methods'][0] == 'GET' ? '-G ' : ''}}"{{ rtrim($baseUrl, '/')}}/{{ ltrim($route['boundUri'], '/') }}@if(count($route['cleanQueryParameters']))?{!! \Mpociot\ApiDoc\Tools\Utils::printQueryParamsAsString($route['cleanQueryParameters']) !!}@endif" @if(count($route['headers']))\
@foreach($route['headers'] as $header => $value)
@foreach($route['cleanHeaders'] as $header => $value)
-H "{{$header}}: {{ addslashes($value) }}"@if(! ($loop->last) || ($loop->last && count($route['bodyParameters']))) \
@endif
@endforeach
Expand Down
21 changes: 21 additions & 0 deletions src/Extracting/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public function processRoute(Route $route, array $routeRules = [])

$headers = $this->fetchRequestHeaders($controller, $method, $route, $routeRules, $parsedRoute);
$parsedRoute['headers'] = $headers;
$parsedRoute['cleanHeaders'] = $this->cleanHeaders($headers);

$bodyParameters = $this->fetchBodyParameters($controller, $method, $route, $routeRules, $parsedRoute);
$parsedRoute['bodyParameters'] = $bodyParameters;
Expand Down Expand Up @@ -222,6 +223,26 @@ protected function cleanParams(array $params)
return $values;
}

/**
* Create samples at index 0 for array parameters.
* Also filter out header which were excluded from having examples.
*
* @param array $params
*
* @return array
*/
protected function cleanHeaders(array $params)
{
$values = [];

// Remove params which have no examples.
$params = array_filter($params, function ($details) {
return ! empty($details);
});

return $params;
}

/**
* For each array notation parameter (eg user.*, item.*.name, object.*.*, user[])
* generate concrete sample (user.0, item.0.name, object.0.0, user.0) with example as value.
Expand Down
73 changes: 73 additions & 0 deletions src/Extracting/Strategies/RequestHeaders/GetFromHeaderTag.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

namespace Mpociot\ApiDoc\Extracting\Strategies\RequestHeaders;

use Dingo\Api\Http\FormRequest as DingoFormRequest;
use Illuminate\Foundation\Http\FormRequest as LaravelFormRequest;
use Illuminate\Routing\Route;
use Illuminate\Support\Str;
use Mpociot\ApiDoc\Extracting\ParamHelpers;
use Mpociot\ApiDoc\Extracting\RouteDocBlocker;
use Mpociot\ApiDoc\Extracting\Strategies\Strategy;
use Mpociot\Reflection\DocBlock;
use Mpociot\Reflection\DocBlock\Tag;
use ReflectionClass;
use ReflectionMethod;

class GetFromHeaderTag extends Strategy
{
use ParamHelpers;

public function __invoke(Route $route, ReflectionClass $controller, ReflectionMethod $method, array $routeRules, array $context = [])
{
foreach ($method->getParameters() as $param) {
$paramType = $param->getType();
if ($paramType === null) {
continue;
}

$parameterClassName = $paramType->getName();

try {
$parameterClass = new ReflectionClass($parameterClassName);
} catch (\ReflectionException $e) {
continue;
}

// If there's a FormRequest, we check there for @urlParam tags.
if (class_exists(LaravelFormRequest::class) && $parameterClass->isSubclassOf(LaravelFormRequest::class)
|| class_exists(DingoFormRequest::class) && $parameterClass->isSubclassOf(DingoFormRequest::class)) {
$formRequestDocBlock = new DocBlock($parameterClass->getDocComment());
$headersFromDocBlock = $this->getHeadersFromDocBlock($formRequestDocBlock->getTags());

if (count($headersFromDocBlock)) {
return $headersFromDocBlock;
}
}
}

/** @var DocBlock $methodDocBlock */
$methodDocBlock = RouteDocBlocker::getDocBlocksFromRoute($route)['method'];

return $this->getHeadersFromDocBlock($methodDocBlock->getTags());
}

private function getHeadersFromDocBlock($tags)
{
$parameters = collect($tags)
->filter(function ($tag) {
return $tag instanceof Tag && $tag->getName() === 'header';
})
->mapWithKeys(function (Tag $tag) {
// Format:
// @header <content>
// Examples:
// @header Cookie foo Example: crumbs
preg_match('/(.+?)\s+(.*)/', $tag->getContent(), $content);
list($content, $name, $value) = $content;
return [$name => $value];
})->toArray();

return $parameters;
}
}
9 changes: 7 additions & 2 deletions src/Extracting/Strategies/Responses/UseResponseFileTag.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,13 @@ protected function getFileResponses(array $tags)
}
$status = $result[1] ?: 200;
$content = $result[2] ? file_get_contents($filePath, true) : '{}';
$json = ! empty($result[3]) ? str_replace("'", '"', $result[3]) : '{}';
$merged = array_merge(json_decode($content, true), json_decode($json, true));

try {
$json = ! empty($result[3]) ? str_replace("'", '"', $result[3]) : '{}';
$merged = array_merge(json_decode($content, true), json_decode($json, true));
} catch (\Exception $e) {
$merged = $content;
}

return ['content' => json_encode($merged), 'status' => (int) $status];
}, $responseFileTags);
Expand Down
1 change: 1 addition & 0 deletions tests/Unit/GeneratorTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ abstract class GeneratorTestCase extends TestCase
\Mpociot\ApiDoc\Extracting\Strategies\QueryParameters\GetFromQueryParamTag::class,
],
'headers' => [
\Mpociot\ApiDoc\Extracting\Strategies\RequestHeaders\GetFromHeaderTag::class,
\Mpociot\ApiDoc\Extracting\Strategies\RequestHeaders\GetFromRouteRules::class,
],
'bodyParameters' => [
Expand Down