Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Scramble Laravel Package

dedoc/scramble

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require dedoc/scramble
    php artisan vendor:publish --provider="Dedoc\Scramble\ScrambleServiceProvider" --tag="scramble-config"
    
    • Publish the config file to customize settings (e.g., routes, OpenAPI version).
  2. Run Scramble

    php artisan scramble:generate
    
    • Generates OpenAPI 3.1.0 docs in storage/app/scramble/api.json (default path).
  3. Access Docs

    • Visit /docs/api (UI) or /docs/api.json (raw OpenAPI spec).
    • Ensure the viewApiDocs gate is defined in app/Providers/AuthServiceProvider.php for non-local environments:
      Gate::define('viewApiDocs', fn () => true); // Adjust logic as needed
      
  4. First Use Case: Quick API Exploration

    • Use the /docs/api UI to interactively test endpoints, inspect request/response schemas, and validate parameters without manual testing.

Implementation Patterns

Core Workflows

  1. Automated Documentation Generation

    • Trigger on Demand: Run php artisan scramble:generate manually or integrate into CI/CD (e.g., post-deploy).
    • Scheduled Generation: Add a cron job (* * * * * php artisan scramble:generate) for nightly updates.
      // config/scramble.php
      'schedule' => true,
      
  2. Customizing Documentation

    • Override Defaults: Extend the OpenAPI spec via scramble.php:
      'openapi' => [
          'info' => [
              'title' => 'My Custom API',
              'version' => '1.0.0',
          ],
          'servers' => [
              ['url' => 'https://api.example.com/v1', 'description' => 'Production'],
          ],
      ],
      
    • Add Global Parameters/Responses: Use the scramble:extend command or service provider boot method:
      Scramble::extend(function ($scramble) {
          $scramble->addGlobalParameter('Authorization', 'header', 'string');
      });
      
  3. Integration with Laravel Features

    • API Resources: Scramble auto-discovers ApiResource classes. Ensure your resources extend \Illuminate\Http\Resources\Json\JsonResource.
    • Form Requests: Validate request data via FormRequest classes (Scramble infers schemas from validation rules):
      public function rules(): array
      {
          return [
              'email' => 'required|email',
              'password' => 'string|min:8',
          ];
      }
      
    • Route Model Binding: Scramble resolves route parameters dynamically. Use named routes for clarity:
      Route::get('/users/{user}', [UserController::class, 'show'])->name('users.show');
      
  4. Testing API Documentation

    • Unit Tests: Assert OpenAPI spec structure:
      public function test_api_docs_include_user_endpoint()
      {
          $spec = json_decode(file_get_contents(storage_path('app/scramble/api.json')), true);
          $this->assertArrayHasKey('paths', $spec);
          $this->assertArrayHasKey('/users', $spec['paths']);
      }
      
    • Contract Tests: Validate docs against expected schemas using phpunit/phpunit assertions.
  5. Deployment Workflow

    • Static Hosting: Serve /docs/api via a static host (e.g., Netlify) for production.
    • Versioning: Store generated docs in a docs/ branch or artifact registry (e.g., GitHub Releases).

Integration Tips

  • Laravel Sanctum/Passport: Scramble auto-detects auth middleware (e.g., auth:sanctum). Customize security schemes in scramble.php:
    'components' => [
        'securitySchemes' => [
            'bearerAuth' => [
                'type' => 'http',
                'scheme' => 'bearer',
                'bearerFormat' => 'JWT',
            ],
        ],
    ],
    
  • Polymorphic Relationships: Use morphMap in scramble.php to resolve polymorphic types:
    'morphMap' => [
        'App\Models\User' => 'users',
        'App\Models\Post' => 'posts',
    ],
    
  • Custom Controllers: For non-standard controllers (e.g., App\Http\Controllers\Api\V1\*), configure the scan paths:
    'scan' => [
        'paths' => [
            app_path('Http/Controllers/Api/V1'),
        ],
    ],
    

Gotchas and Tips

Pitfalls

  1. Environment Restrictions

    • Routes are disabled in non-local environments by default. Forgetting to define the viewApiDocs gate will break access.
    • Fix: Explicitly allow docs in staging/production:
      Gate::define('viewApiDocs', fn ($user) => $user->isAdmin());
      
  2. Caching Issues

    • Scramble caches generated docs. Clear the cache after schema changes:
      php artisan scramble:clear-cache
      
    • Tip: Disable caching during development ('cache' => false in scramble.php).
  3. Complex Validation Rules

    • Nested validation arrays (e.g., rules => ['posts.*' => 'required']) may not render intuitively in OpenAPI.
    • Workaround: Use explicit FormRequest rules or extend the schema manually:
      Scramble::extend(function ($scramble) {
          $scramble->addSchema('Post', [
              'type' => 'object',
              'properties' => [
                  'title' => ['type' => 'string'],
                  'content' => ['type' => 'string'],
              ],
          ]);
      });
      
  4. Polymorphic Routes

    • Scramble may misinterpret polymorphic routes (e.g., Route::apiResource('posts', PostController::class)->except(['create', 'edit'])).
    • Fix: Use explicit route definitions or configure morphMap carefully.
  5. Middleware Conflicts

    • Scramble skips routes with scramble:ignore middleware. Ensure critical docs routes aren’t ignored:
      Route::middleware(['scramble:ignore'])->group(function () {
          // Non-doc routes
      });
      
  6. OpenAPI 3.1.0 Quirks

    • Some tools (e.g., Swagger UI) may not fully support OpenAPI 3.1.0. Downgrade to 3.0.3 if needed:
      'openapi' => [
          'version' => '3.0.3',
      ],
      

Debugging

  • Inspect Raw Output: Check storage/app/scramble/api.json for errors or missing endpoints.
  • Verbose Logging: Enable debug mode in scramble.php:
    'debug' => true,
    
  • Command-Line Flags: Generate docs with verbose output:
    php artisan scramble:generate --verbose
    

Extension Points

  1. Custom Schema Providers

    • Implement Dedoc\Scramble\Contracts\SchemaProvider to inject custom schemas:
      class CustomSchemaProvider implements SchemaProvider
      {
          public function getSchemas(): array
          {
              return [
                  'CustomModel' => [
                      'type' => 'object',
                      'properties' => ['custom_field' => ['type' => 'string']],
                  ],
              ];
          }
      }
      
    • Register in scramble.php:
      'schema_providers' => [
          \App\Providers\CustomSchemaProvider::class,
      ],
      
  2. Post-Processing Hooks

    • Modify the generated spec via the scramble:post-process event:
      Scramble::listen('scramble.post-process', function ($spec) {
          $spec['info']['description'] = 'Enhanced API Docs';
          return $spec;
      });
      
  3. UI Customization

    • Override the default Swagger UI by publishing assets:
      php artisan vendor:publish --provider="Dedoc\Scramble\ScrambleServiceProvider" --tag="scramble-assets"
      
    • Extend the blade template (resources/views/vendor/scramble/docs.blade.php).
  4. Dynamic Documentation

    • Use scramble:dynamic to inject runtime data (e.g., feature flags):
      Scramble::extend(function ($scramble) {
          $scramble->addDynamicSchema('FeatureFlags', fn () => [
              'type' => 'object',
              'properties' => [
                  'new_ui' => ['
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware