Quellcode durchsuchen

Support separate base URLs

shalvah vor 4 Jahren
Ursprung
Commit
e9cf24151f

+ 3 - 1
CHANGELOG.md

@@ -28,4 +28,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
 - Removed `$stage`
 - More validation rules support
 - Inline validators
-- Infer URL parameter type
+- Infer URL parameter type and name
+- Renamed `interactive` to `try_it_out`
+- 3 base URLs

+ 13 - 5
config/scribe.php

@@ -167,11 +167,19 @@ return [
         'middleware' => [],
     ],
 
-    /**
-     * Add a Try It Out button to your endpoints so consumers can test endpoints right from their browser.
-     * Don't forget to enable CORS headers for your endpoints.
-     */
-    'interactive' => true,
+    'try_it_out' => [
+        /**
+         * Add a Try It Out button to your endpoints so consumers can test endpoints right from their browser.
+         * Don't forget to enable CORS headers for your endpoints.
+         */
+        'enabled' => true,
+
+        /**
+         * The base URL for the API tester to use (for example, you can set this to your staging URL).
+         * Leave as null to use the current app URL (config(app.url)).
+         */
+        'base_url' => null,
+    ],
 
     /*
      * How is your API authenticated? This information will be used in the displayed docs, generated examples and response calls.

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

@@ -66,7 +66,7 @@
       onsubmit="event.preventDefault(); executeTryOut('{{ $endpoint->endpointId() }}', this);">
     <h3>
         Request&nbsp;&nbsp;&nbsp;
-        @if($metadata['interactive'])
+        @if($metadata['try_it_out']['enabled'] ?? false)
             <button type="button"
                     style="background-color: #8fbcd4; padding: 5px 10px; border-radius: 5px; border-width: thin;"
                     id="btn-tryout-{{ $endpoint->endpointId() }}"

+ 2 - 2
resources/views/themes/default/index.blade.php

@@ -19,10 +19,10 @@
     <script src="https://unpkg.com/prismjs@v1.x/components/prism-core.min.js"></script>
     <script src="https://unpkg.com/prismjs@v1.x/plugins/autoloader/prism-autoloader.min.js"></script>
 
-@if($isInteractive)
+@if($tryItOut['enabled'] ?? false)
     <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
     <script>
-        var baseUrl = "{{ $baseUrl }}";
+        var baseUrl = "{{ $tryItOut['base_url'] ?? config('app.url') }}";
     </script>
     <script src="{{ u::getVersionedAsset('js/tryitout.js') }}"></script>
 @endif

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

@@ -128,7 +128,7 @@ class ResponseCalls extends Strategy
         $uri = Utils::getUrlWithBoundParameters($route->uri(), $urlParams);
         $routeMethods = $this->getMethods($route);
         $method = array_shift($routeMethods);
-        $cookies = isset($rulesToApply['cookies']) ? $rulesToApply['cookies'] : [];
+        $cookies = $rulesToApply['cookies'] ?? [];
 
         // Note that we initialise the request with the bodyParams here
         // and later still add them to the ParameterBag (`addBodyParameters`)
@@ -138,7 +138,9 @@ class ResponseCalls extends Strategy
         // (where Symfony usually reads from and Laravel sometimes does)
         // Adding to both ensures consistency
 
-        $request = Request::create($uri, $method, [], $cookies, $fileParameters, $this->transformHeadersToServerVars($headers), json_encode($bodyParams));
+        // 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));
         // Doing it again to catch any ones we didn't transform properly.
         $request = $this->addHeaders($request, $route, $headers);
 

+ 5 - 14
src/Writing/HtmlWriter.php

@@ -14,18 +14,9 @@ use Parsedown;
  */
 class HtmlWriter
 {
-    /**
-     * @var DocumentationConfig
-     */
-    protected $config;
-
-    /** @var string */
-    protected $baseUrl;
-
-    /**
-     * @var Parsedown
-     */
-    protected $markdownParser;
+    protected DocumentationConfig $config;
+    protected string $baseUrl;
+    protected Parsedown $markdownParser;
 
     public function __construct(DocumentationConfig $config = null)
     {
@@ -48,7 +39,7 @@ class HtmlWriter
         $output = View::make("scribe::themes.$theme.index", [
             'metadata' => $this->getMetadata(),
             'baseUrl' => $this->baseUrl,
-            'isInteractive' => $this->config->get('interactive', true),
+            'tryItOut' => $this->config->get('try_it_out'),
             'prepend' => $prepend,
             'index' => $index,
             'authentication' => $authentication,
@@ -106,7 +97,7 @@ class HtmlWriter
             'logo' => $this->config->get('logo') ?? false,
             'last_updated' => date("F j Y"),
             'auth' => $auth,
-            'interactive' => $this->config->get('interactive', true),
+            'try_it_out' => $this->config->get('try_it_out'),
             'links' => $links + ['<a href="http://github.com/knuckleswtf/scribe">Documentation powered by Scribe ✍</a>'],
         ];
     }

+ 4 - 7
src/Writing/OpenAPISpecWriter.php

@@ -6,6 +6,7 @@ use Illuminate\Support\Arr;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Str;
 use Knuckles\Camel\Camel;
+use Knuckles\Camel\Extraction\Response;
 use Knuckles\Camel\Output\OutputEndpointData;
 use Knuckles\Camel\Output\Group;
 use Knuckles\Camel\Output\Parameter;
@@ -19,18 +20,14 @@ class OpenAPISpecWriter
 
     const VERSION = '3.0.3';
 
-    /**
-     * @var DocumentationConfig
-     */
-    private $config;
+    private DocumentationConfig $config;
 
     /**
      * Object to represent empty values, since empty arrays get serialised as objects.
      * Can't use a constant because of initialisation expression.
      *
-     * @var \stdClass
      */
-    public $EMPTY;
+    public \stdClass $EMPTY;
 
     public function __construct(DocumentationConfig $config = null)
     {
@@ -277,7 +274,7 @@ class OpenAPISpecWriter
         return count($responses) > 0 ? $responses : $this->EMPTY;
     }
 
-    protected function getResponseDescription($response)
+    protected function getResponseDescription(Response $response): string
     {
         if (Str::startsWith($response->content, "<<binary>>")) {
             return trim(str_replace("<<binary>>", "", $response->content));

+ 7 - 10
src/Writing/PostmanCollectionWriter.php

@@ -17,17 +17,14 @@ class PostmanCollectionWriter
      */
     const VERSION = '2.1.0';
 
-    /**
-     * @var DocumentationConfig
-     */
-    protected $config;
+    protected DocumentationConfig $config;
 
-    protected $baseUrl;
+    protected string $baseUrl;
 
     public function __construct(DocumentationConfig $config = null)
     {
         $this->config = $config ?: new DocumentationConfig(config('scribe', []));
-        $this->baseUrl = ($this->config->get('postman.base_url') ?: $this->config->get('base_url')) ?: config('app.url');
+        $this->baseUrl = $this->config->get('base_url') ?: config('app.url');
     }
 
     /**
@@ -35,7 +32,7 @@ class PostmanCollectionWriter
      *
      * @return array
      */
-    public function generatePostmanCollection(array $groupedEndpoints)
+    public function generatePostmanCollection(array $groupedEndpoints): array
     {
         $collection = [
             'variable' => [
@@ -65,7 +62,7 @@ class PostmanCollectionWriter
         return $collection;
     }
 
-    protected function generateAuthObject()
+    protected function generateAuthObject(): array
     {
         if (!$this->config->get('auth.enabled')) {
             return [
@@ -187,7 +184,7 @@ class PostmanCollectionWriter
         return $body;
     }
 
-    protected function resolveHeadersForEndpoint(OutputEndpointData $endpointData)
+    protected function resolveHeadersForEndpoint(OutputEndpointData $endpointData): array
     {
         [$where, $authParam] = $this->getAuthParamToExclude();
 
@@ -215,7 +212,7 @@ class PostmanCollectionWriter
         return $headers;
     }
 
-    protected function generateUrlObject(OutputEndpointData $endpointData)
+    protected function generateUrlObject(OutputEndpointData $endpointData): array
     {
         $base = [
             'protocol' => Str::startsWith($this->baseUrl, 'https') ? 'https' : 'http',

+ 0 - 3
src/Writing/Writer.php

@@ -12,8 +12,6 @@ class Writer
 {
     private DocumentationConfig $config;
 
-    private string $baseUrl;
-
     private bool $isStatic;
 
     private string $markdownOutputPath = '.scribe';
@@ -26,7 +24,6 @@ class Writer
     {
         // If no config is injected, pull from global. Makes testing easier.
         $this->config = $config ?: new DocumentationConfig(config('scribe'));
-        $this->baseUrl = $this->config->get('base_url') ?? config('app.url');
 
         $this->isStatic = $this->config->get('type') === 'static';
         $this->staticTypeOutputPath = rtrim($this->config->get('static.output_path', 'public/docs'), '/');