Parcourir la source

Support custom "Last updated at" label

shalvah il y a 2 ans
Parent
commit
44996fe6f0

+ 12 - 0
config/scribe.php

@@ -346,6 +346,18 @@ INTRO
      */
     '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,

+ 0 - 1
phpstan.neon

@@ -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\(\).#'

+ 1 - 0
phpunit.xml

@@ -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>

+ 1 - 1
resources/views/themes/default/sidebar.blade.php

@@ -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>

+ 6 - 2
src/Extracting/Strategies/Responses/ResponseCalls.php

@@ -129,7 +129,8 @@ class ResponseCalls extends Strategy
      *
      * @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);
@@ -146,7 +147,10 @@ class ResponseCalls extends Strategy
 
         // 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);
 

+ 33 - 9
src/Writing/HtmlWriter.php

@@ -104,7 +104,7 @@ class HtmlWriter
         return $this->markdownParser->text(file_get_contents($markdownFilePath));
     }
 
-    protected function getMetadata(): array
+    public function getMetadata(): array
     {
         $links = [];
 
@@ -117,26 +117,50 @@ class HtmlWriter
         }
 
         $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 = [];

+ 33 - 0
tests/Unit/HtmlWriterTest.php

@@ -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);
+    }
+}