Skip to content

Commit

Permalink
Support custom "Last updated at" label
Browse files Browse the repository at this point in the history
  • Loading branch information
shalvah committed Oct 15, 2022
1 parent 6bc3487 commit 44996fe
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 13 deletions.
12 changes: 12 additions & 0 deletions config/scribe.php
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,18 @@
*/
'logo' => false,

/**
* Customize the "Last updated" value displayed in the docs by specifying tokens and formats.
* Examples:
* - {date:F j Y} => March 28, 2022
* - {git:short} => Short hash of the last Git commit
*
* Available tokens are `{date:<format>}` and `{git:<format>}`.
* The format you pass to `date` will be passed to PhP's `date()` function.
* The format you pass to `git` can be either "short" or "long".
*/
'last_updated' => 'Last updated: {date:F j, Y}',

'examples' => [
/*
* If you would like the package to generate the same example values for parameters on each run,
Expand Down
1 change: 0 additions & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ parameters:
reportUnmatchedIgnoredErrors: true
inferPrivatePropertyTypeFromConstructor: true
ignoreErrors:
- '#Call to an undefined static method Illuminate\\Support\\Facades\\URL::forceRootUrl\(\)#'
- '#Call to an undefined method Illuminate\\Routing\\Route::versions\(\).#'
- '#Call to an undefined method Illuminate\\Contracts\\Validation\\Validator::getRules\(\).#'
- '#Call to an undefined method ReflectionType::getName\(\).#'
Expand Down
1 change: 1 addition & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
</testsuite>
<testsuite name="Unit Tests 4">
<file>tests/Unit/ValidationRuleParsingTest.php</file>
<file>tests/Unit/HtmlWriterTest.php</file>
</testsuite>
</testsuites>
</phpunit>
2 changes: 1 addition & 1 deletion resources/views/themes/default/sidebar.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@
</ul>
@endif
<ul class="toc-footer" id="last-updated">
<li>Last updated: {{ $metadata['last_updated'] }}</li>
<li>{{ $metadata['last_updated'] }}</li>
</ul>
</div>
8 changes: 6 additions & 2 deletions src/Extracting/Strategies/Responses/ResponseCalls.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ private function configureEnvironment(array $rulesToApply)
*
* @return Request
*/
protected function prepareRequest(Route $route, array $rulesToApply, array $urlParams, array $bodyParams, array $queryParams, array $fileParameters, array $headers): Request
protected function prepareRequest(Route $route, array $rulesToApply, array $urlParams, array $bodyParams,
array $queryParams, array $fileParameters, array $headers): Request
{
$uri = Utils::getUrlWithBoundParameters($route->uri(), $urlParams);
$routeMethods = $this->getMethods($route);
Expand All @@ -146,7 +147,10 @@ protected function prepareRequest(Route $route, array $rulesToApply, array $urlP

// Always use the current app domain for response calls
$rootUrl = config('app.url');
$request = Request::create("$rootUrl/$uri", $method, [], $cookies, $fileParameters, $this->transformHeadersToServerVars($headers), json_encode($bodyParams));
$request = Request::create(
"$rootUrl/$uri", $method, [], $cookies, $fileParameters,
$this->transformHeadersToServerVars($headers), json_encode($bodyParams)
);
// Doing it again to catch any ones we didn't transform properly.
$request = $this->addHeaders($request, $route, $headers);

Expand Down
42 changes: 33 additions & 9 deletions src/Writing/HtmlWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ protected function transformMarkdownFileToHTML(string $markdownFilePath): string
return $this->markdownParser->text(file_get_contents($markdownFilePath));
}

protected function getMetadata(): array
public function getMetadata(): array
{
$links = [];

Expand All @@ -117,26 +117,50 @@ protected function getMetadata(): array
}

$auth = $this->config->get('auth');
if ($auth['in'] === 'bearer' || $auth['in'] === 'basic') {
$auth['name'] = 'Authorization';
$auth['location'] = 'header';
$auth['prefix'] = ucfirst($auth['in']) . ' ';
} else {
$auth['location'] = $auth['in'];
$auth['prefix'] = '';
if ($auth) {
if ($auth['in'] === 'bearer' || $auth['in'] === 'basic') {
$auth['name'] = 'Authorization';
$auth['location'] = 'header';
$auth['prefix'] = ucfirst($auth['in']) . ' ';
} else {
$auth['location'] = $auth['in'];
$auth['prefix'] = '';
}
}

return [
'title' => $this->config->get('title') ?: config('app.name', '') . ' Documentation',
'example_languages' => $this->config->get('example_languages'),
'logo' => $this->config->get('logo') ?? false,
'last_updated' => date("F j Y"),
'last_updated' => $this->getLastUpdated(),
'auth' => $auth,
'try_it_out' => $this->config->get('try_it_out'),
'links' => array_merge($links, ['<a href="http://github.com/knuckleswtf/scribe">Documentation powered by Scribe ✍</a>']),
];
}

protected function getLastUpdated()
{
$lastUpdated = $this->config->get('last_updated', 'Last updated: {date:F j, Y}');

$tokens = [
"date" => fn($format) => date($format),
"git" => fn($option) => match ($option) {
"short" => trim(shell_exec('git rev-parse --short HEAD')),
"long" => trim(shell_exec('git rev-parse HEAD')),
},
];

foreach ($tokens as $token => $resolver) {
$matches = [];
if(preg_match('#(\{'.$token.':(.+?)})#', $lastUpdated, $matches)) {
$lastUpdated = str_replace($matches[1], $resolver($matches[2]), $lastUpdated);
}
}

return $lastUpdated;
}

protected function getHeadings(array $headingsBeforeEndpoints, array $endpointsByGroupAndSubgroup, array $headingsAfterEndpoints)
{
$headings = [];
Expand Down
33 changes: 33 additions & 0 deletions tests/Unit/HtmlWriterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace Knuckles\Scribe\Tests\Unit;

use Knuckles\Scribe\Tools\DocumentationConfig;
use Knuckles\Scribe\Writing\HtmlWriter;
use PHPUnit\Framework\TestCase;

class HtmlWriterTest extends TestCase
{
/** @test */
public function sets_last_updated_correctly()
{
$config = ["base_url" => "http://local.test", "title" => "API Docs"];
$config["last_updated"] = '';
$writer = new HtmlWriter(new DocumentationConfig($config));
$lastUpdated = $writer->getMetadata()["last_updated"];
$this->assertEquals('', $lastUpdated);

$config["last_updated"] = "Last updated on {date:l}";
$writer = new HtmlWriter(new DocumentationConfig($config));
$lastUpdated = $writer->getMetadata()["last_updated"];
$today = date("l");
$this->assertEquals("Last updated on $today", $lastUpdated);

$config["last_updated"] = "Last updated on {date:l, jS F} (Git commit {git:short})";
$writer = new HtmlWriter(new DocumentationConfig($config));
$lastUpdated = $writer->getMetadata()["last_updated"];
$date = date("l, jS F");
$commit = trim(shell_exec('git rev-parse --short HEAD'));
$this->assertEquals("Last updated on $date (Git commit $commit)", $lastUpdated);
}
}

0 comments on commit 44996fe

Please sign in to comment.