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

Documentator Laravel Package

tsitsishvili/documentator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tsitsishvili/documentator:^1.8
    

    No additional configuration is required for basic usage—Documentator auto-discovers routes under api/* by default.

  2. First Use Case:

    • Visit /documentation (or /docs if using the docs_path config) to see auto-generated API docs.
    • Example: A simple GET /api/users route with a UserResource will infer:
      • Path, method, and description (from PHPDoc).
      • Response schema (from UserResource).
      • New: Conditional fields (e.g., when*/mergeWhen in FormRequests) are now correctly marked as optional instead of nullable.
      • No manual work needed unless you want to refine details.
  3. Where to Look First:

    • Config: config/documentator.php (published via php artisan vendor:publish --tag=documentator-config).
      • Key settings: paths, auth, scalar, and new check options for contract validation.
    • CLI:
      • Explain inference: Run php artisan documentator:explain GET /api/users to debug how parameters/fields are inferred. Use --json for machine-readable output.
      • Contract validation: Use php artisan documentator:check --against=old-spec.json --fail-on=breaking to enforce backward compatibility.
    • Attributes: Use #[Documentation] or #[OpenApi] to override inferred docs (now with improved schema accuracy for resources and Spatie Data).

Implementation Patterns

Core Workflows

  1. Auto-Inference Workflow (Enhanced):

    • Routes: Documentator now infers responses from:
      • Controller return types (e.g., UserResource).
      • New: abort(), abort_if(), abort_unless(), and HTTP exceptions (e.g., HttpResponseException). Example: abort(404, 'User not found') auto-generates a 404 response with the message.
    • FormRequests: Validation rules map to OpenAPI schemas with:
      • New: Required fields marked accurately (no false positives).
      • Conditional fields (e.g., when('active', ...)) are now optional (type: object, properties: {...}) instead of nullable.
    • API Resources:
      • New: Composition preserves field descriptions, @var types, and examples. Example: A UserResource with PostResource composition retains all metadata.
      • Spatie Data schemas now respect Optional/Lazy properties and input/output name mapping. Example: with(['name', 'Optional.email']) generates a schema with name (required) and email (optional).
  2. Override and Refine:

    • Use PHP attributes to customize inferred docs with improved schema support:
      #[OpenApi(
          responses: [
              new Response(
                  ref: "#/components/schemas/User",
                  description: "User data",
                  headers: [new Header(name: "X-RateLimit", schema: new Schema(type: "integer"))]
              ),
              new Response(404, description: "User not found", content: new Content(mediaType: "application/json", schema: new Schema(type: "object", properties: ["error" => ["type" => "string"]]))),
          ],
          security: [["bearerAuth" => []]]
      )]
      public function show(User $user) { ... }
      
    • New: Use #[OpenApi(oneOf: [...])] to group distinct responses with the same status code (e.g., 200 OK with different payloads).
  3. Authentication:

    • Auto-detects Laravel auth middleware (e.g., auth:sanctum) and maps it to OpenAPI securitySchemes.
    • New: Security scopes (e.g., scopes: ["read:users"]) are now inferred from middleware like authorizes:users.
  4. Scalar UI Integration:

    • Enable Scalar by setting scalar config:
      'scalar' => [
          'enabled' => true,
          'api_key' => env('SCALAR_API_KEY'),
      ],
      
    • Note: Scalar’s UI now reflects improved schema accuracy (e.g., optional vs. nullable fields).
  5. Manual Generation:

    • Regenerate the OpenAPI spec after changes:
      php artisan documentator:generate
      
    • New: Use --fail-on=breaking with documentator:check to enforce contract compatibility:
      php artisan documentator:check --against=old-spec.json --fail-on=breaking
      
      • Outputs to storage/app/documentator/openapi.json (configurable).

Integration Tips

  1. Testing:

    • Use Documentator::generate() in tests to verify OpenAPI spec:
      $spec = Documentator::generate();
      $this->assertArrayHasKey('paths', $spec);
      
    • New: Test contract compatibility with:
      $this->artisan('documentator:check', ['--against' => 'old-spec.json', '--fail-on' => 'breaking'])
          ->assertExitCode(0); // Fails if breaking changes detected.
      
  2. Custom Schemas:

    • Define reusable schemas in config/documentator.php under components.schemas:
      'components' => [
          'schemas' => [
              'Pagination' => [
                  'type' => 'object',
                  'properties' => [
                      'total' => ['type' => 'integer'],
                      'per_page' => ['type' => 'integer'],
                      'optional_meta' => ['type' => 'object', 'nullable' => true], // Now correctly marked as optional
                  ],
              ],
          ],
      ],
      
    • New: Reference them in responses with oneOf for polymorphic responses:
      #[OpenApi(
          responses: [
              new Response(
                  200,
                  oneOf: [
                      new Reference(ref: "#/components/schemas/User"),
                      new Reference(ref: "#/components/schemas/Team"),
                  ]
              )
          ]
      )]
      
  3. Webhooks/Events:

    • Listen to DocumentatorGenerated event to post-process the spec:
      use Tsitsishvili\Documentator\Events\DocumentatorGenerated;
      
      DocumentatorGenerated::listen(function (DocumentatorGenerated $event) {
          $event->spec['info']['x-generated-with'] = 'Documentator v1.8.0';
          // Add custom validation logic here.
      });
      
    • New: Use documentator:explain to debug inference before extending:
      $explanation = $this->artisan('documentator:explain', ['GET', '/api/users'], ['--json' => true])->output();
      
  4. Laravel Sanctum/Passport:

    • Auto-detects Sanctum/Passport auth and adds securitySchemes to the spec.
    • New: Security scopes (e.g., scopes: ["write:posts"]) are inferred from middleware like authorizes:posts,create.
  5. Dynamic Routes:

    • For routes like GET /api/users/{user}, Documentator infers:
      • Path parameter user (type inferred from route model binding).
      • New: Nested resources (e.g., UserResource with PostResource) preserve field descriptions and examples.
    • Override with attributes:
      #[OpenApi(
          parameters: [new Parameter(
              name: 'user',
              in: 'path',
              schema: new Schema(type: 'string', format: 'uuid', description: 'User UUID')
          )]
      )]
      

Gotchas and Tips

Pitfalls

  1. Route Caching:

    • Laravel’s route caching (php artisan route:cache) can cause Documentator to miss new routes.
    • Fix: Clear cache after adding routes:
      php artisan route:clear
      php artisan documentator:generate
      
  2. Schema Accuracy Changes:

    • New: Regenerated OpenAPI specs may differ due to:
      • Required fields now marked accurately (no false positives).
      • Conditional fields (when*/mergeWhen) are optional instead of nullable.
      • Error responses from abort()/HttpResponseException are included.
    • Fix: Review diffs with:
      php artisan documentator:check --against=old-spec.json
      
  3. Circular References:

    • Complex API Resources with circular references (e.g., UserPostUser) may still cause issues.
    • Fix: Use #[OpenApi(ignore: true)] on problematic properties or simplify schemas.
    • New: Composition now preserves descriptions/examples, reducing the need for manual overrides.
  4. PHPDoc Parsing:

    • Documentator relies on PHPDoc for type hints. Incorrect PHPDoc (e.g., wrong FQCN) leads to invalid schemas.
    • Fix:
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle