Skip to content

Commit 82368fb

Browse files
committed
Add support for custom headers on example calls #76
1 parent de38dad commit 82368fb

File tree

7 files changed

+53
-10
lines changed

7 files changed

+53
-10
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ Option | Description
5050
`router` | The router to use, when processing the route files (can be Laravel or Dingo - defaults to Laravel)
5151
`bindings` | List of route bindings that should be replaced when trying to retrieve route results. Syntax format: `binding_one,id|binding_two,id`
5252
`force` | Force the re-generation of existing/modified API routes
53+
`header` | Custom HTTP headers to add to the example requests. Separate the header name and value with ":". For example: `--header 'Authorization: CustomToken'`
5354

5455
## Publish rule descriptions for customisation or translation.
5556

src/Mpociot/ApiDoc/Commands/GenerateDocumentation.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ class GenerateDocumentation extends Command
3131
{--router=laravel : The router to be used (Laravel or Dingo)}
3232
{--force : Force rewriting of existing routes}
3333
{--bindings= : Route Model Bindings}
34+
{--header=* : Custom HTTP headers to add to the example requests. Separate the header name and value with ":"}
3435
';
3536

3637
/**
@@ -253,7 +254,7 @@ private function processLaravelRoutes(AbstractGenerator $generator, $allowedRout
253254
foreach ($routes as $route) {
254255
if (in_array($route->getName(), $allowedRoutes) || str_is($routePrefix, $route->getUri()) || in_array($middleware, $route->middleware())) {
255256
if ($this->isValidRoute($route) && $this->isRouteVisibleForDocumentation($route->getAction()['uses'])) {
256-
$parsedRoutes[] = $generator->processRoute($route, $bindings, $withResponse);
257+
$parsedRoutes[] = $generator->processRoute($route, $bindings, $this->option('header'), $withResponse);
257258
$this->info('Processed route: ['.implode(',', $route->getMethods()).'] '.$route->getUri());
258259
} else {
259260
$this->warn('Skipping route: ['.implode(',', $route->getMethods()).'] '.$route->getUri());
@@ -279,7 +280,7 @@ private function processDingoRoutes(AbstractGenerator $generator, $allowedRoutes
279280
$parsedRoutes = [];
280281
foreach ($routes as $route) {
281282
if (empty($allowedRoutes) || in_array($route->getName(), $allowedRoutes) || str_is($routePrefix, $route->uri()) || in_array($middleware, $route->middleware())) {
282-
$parsedRoutes[] = $generator->processRoute($route, $bindings, $withResponse);
283+
$parsedRoutes[] = $generator->processRoute($route, $bindings, $this->option('header'), $withResponse);
283284
$this->info('Processed route: ['.implode(',', $route->getMethods()).'] '.$route->uri());
284285
}
285286
}

src/Mpociot/ApiDoc/Generators/AbstractGenerator.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,16 +58,24 @@ protected function getParameters($routeData, $routeAction, $bindings)
5858

5959
/**
6060
* @param $route
61+
* @param $bindings
62+
* @param $headers
6163
*
6264
* @return \Illuminate\Http\Response
6365
*/
64-
protected function getRouteResponse($route, $bindings)
66+
protected function getRouteResponse($route, $bindings, $headers = [])
6567
{
6668
$uri = $this->addRouteModelBindings($route, $bindings);
6769

6870
$methods = $route->getMethods();
6971

70-
return $this->callRoute(array_shift($methods), $uri);
72+
// Split headers into key - value pairs
73+
$headers = collect($headers)->map(function($value) {
74+
$split = explode(':', $value);
75+
return [trim($split[0]) => trim($split[1])];
76+
})->collapse()->toArray();
77+
78+
return $this->callRoute(array_shift($methods), $uri, [], [], [], $headers);
7179
}
7280

7381
/**

src/Mpociot/ApiDoc/Generators/DingoGenerator.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,18 @@ class DingoGenerator extends AbstractGenerator
99
/**
1010
* @param \Illuminate\Routing\Route $route
1111
* @param array $bindings
12+
* @param array $headers
1213
* @param bool $withResponse
1314
*
1415
* @return array
1516
*/
16-
public function processRoute($route, $bindings = [], $withResponse = true)
17+
public function processRoute($route, $bindings = [], $headers = [], $withResponse = true)
1718
{
1819
$response = '';
1920

2021
if ($withResponse) {
2122
try {
22-
$response = $this->getRouteResponse($route, $bindings);
23+
$response = $this->getRouteResponse($route, $bindings, $headers);
2324
} catch (Exception $e) {
2425
}
2526
}
@@ -46,6 +47,10 @@ public function processRoute($route, $bindings = [], $withResponse = true)
4647
public function callRoute($method, $uri, $parameters = [], $cookies = [], $files = [], $server = [], $content = null)
4748
{
4849
$dispatcher = app('Dingo\Api\Dispatcher')->raw();
50+
51+
collect($server)->map(function($key, $value) use ($dispatcher) {
52+
$dispatcher->header($key, $value);
53+
});
4954

5055
return call_user_func_array([$dispatcher, strtolower($method)], [$uri]);
5156
}

src/Mpociot/ApiDoc/Generators/LaravelGenerator.php

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@ protected function getUri($route)
2121
/**
2222
* @param \Illuminate\Routing\Route $route
2323
* @param array $bindings
24+
* @param array $headers
2425
* @param bool $withResponse
2526
*
2627
* @return array
2728
*/
28-
public function processRoute($route, $bindings = [], $withResponse = true)
29+
public function processRoute($route, $bindings = [], $headers = [], $withResponse = true)
2930
{
3031
$content = '';
3132

@@ -35,7 +36,7 @@ public function processRoute($route, $bindings = [], $withResponse = true)
3536

3637

3738
if ($withResponse) {
38-
$response = $this->getRouteResponse($route, $bindings);
39+
$response = $this->getRouteResponse($route, $bindings, $headers);
3940
if ($response->headers->get('Content-Type') === 'application/json') {
4041
$content = json_encode(json_decode($response->getContent()), JSON_PRETTY_PRINT);
4142
} else {
@@ -73,10 +74,10 @@ public function callRoute($method, $uri, $parameters = [], $cookies = [], $files
7374
$kernel = App::make('Illuminate\Contracts\Http\Kernel');
7475
App::instance('middleware.disable', true);
7576

76-
$server = [
77+
$server = collect([
7778
'CONTENT_TYPE' => 'application/json',
7879
'Accept' => 'application/json',
79-
];
80+
])->merge($server)->toArray();
8081

8182
$request = Request::create(
8283
$uri, $method, $parameters,

tests/Fixtures/TestController.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Mpociot\ApiDoc\Tests\Fixtures;
44

5+
use Illuminate\Http\Request;
56
use Illuminate\Routing\Controller;
67

78
class TestController extends Controller
@@ -31,6 +32,11 @@ public function addRouteBindingsToRequestClass(DynamicRequest $request)
3132
return '';
3233
}
3334

35+
public function checkCustomHeaders(Request $request)
36+
{
37+
return $request->headers->all();
38+
}
39+
3440
public function fetchRouteResponse()
3541
{
3642
$fixture = new \stdClass();

tests/GenerateDocumentationTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,27 @@ public function testGeneratedPostmanCollectionFileIsCorrect()
120120
$this->assertEquals($generatedCollection, $fixtureCollection);
121121
}
122122

123+
public function testCanAppendCustomHttpHeaders()
124+
{
125+
RouteFacade::get('/api/headers', TestController::class.'@checkCustomHeaders');
126+
127+
$output = $this->artisan('api:generate', [
128+
'--routePrefix' => 'api/*',
129+
'--header' => [
130+
'Authorization: customAuthToken',
131+
'X-Custom-Header: foobar',
132+
]
133+
]);
134+
135+
$generatedMarkdown = file_get_contents(__DIR__.'/../public/docs/source/index.md');
136+
$this->assertContains('"authorization": [
137+
"customAuthToken"
138+
],
139+
"x-custom-header": [
140+
"foobar"
141+
]', $generatedMarkdown);
142+
}
143+
123144
/**
124145
* @param string $command
125146
* @param array $parameters

0 commit comments

Comments
 (0)