Scramble

repository·main·Indexed 24 days ago

https://github.com/dedoc/scramble

A Laravel package that automatically generates OpenAPI 3.1.0 documentation by analyzing code, eliminating the need for manual PHPDoc annotations. It provides an interactive UI viewer at `/docs/api` and a raw JSON specification at `/docs/api.json`. Includes CLI commands for analysis (`scramble:analyze`), caching (`scramble:cache`, `scramble:clear`), and exporting (`scramble:export`), as well as configuration options for parameter extractors and rule transformers.

Tokens
3.9K
Snippets
12
Records
31
Agent score
80%

What's inside scramble

  1. Overview of Scramble

    main
    Scramble is an API documentation generator for Laravel projects. It generates documentation in the OpenAPI 3.1.0 format by analyzing your code directly, eliminating the need to manually write and maintain PHPDoc annotations. This ensures your documentation stays synchronized with your actual implementation.
  2. Access Scramble API documentation and JSON schema

    main

    Once installed, Scramble automatically provides two routes in your Laravel application:

    • /docs/api: The interactive UI viewer for browsing your API documentation.
    • /docs/api.json: The raw OpenAPI 3.1.0 specification in JSON format.

    Note: By default, these routes are only accessible in the local environment. To change this behavior or restrict access in other environments, you must define the viewApiDocs gate.

    /docs/api
    /docs/api.json
  3. Use the Index class to retrieve class and function definitions

    main

    The Dedoc\Scramble\Infer\Scope\Index class acts as a central repository for type information discovered during analysis. It stores and provides access to ClassDefinition and FunctionLikeDefinition objects for classes, functions, and constants found in the analyzed codebase.

    Key behaviors:

    • Lazy Loading: If a class or function is requested via getClass() or getFunction() but hasn't been registered yet, the Index will attempt to reflect on it and build a definition on the fly.
    • AST Analysis: For classes, if the Scramble configuration shouldAnalyzeAst is enabled for a specific class name, getClass() will use a ClassAnalyzer to perform a deep analysis. Otherwise, it falls back to a ShallowClassReflectionDefinitionBuilder.
    • Caching: Once a definition is built or registered, it is stored in the internal $classesDefinitions or $functionsDefinitions arrays for subsequent calls.
  4. Manage inference extensions with ExtensionsBroker

    main

    The ExtensionsBroker acts as a central registry and dispatcher for inference extensions. When Scramble performs analysis, it uses the broker to query extensions for specific information.

    Supported extension types managed by the broker include:

    • PropertyTypeExtension: Resolves property types.
    • MethodReturnTypeExtension: Resolves return types for specific methods.
    • AnyMethodReturnTypeExtension: Resolves return types for any method call (catch-all).
    • MethodCallExceptionsExtension: Identifies exceptions thrown by method calls.
    • StaticMethodReturnTypeExtension: Resolves return types for static methods.
    • FunctionReturnTypeExtension: Resolves return types for global functions.
    • AfterClassDefinitionCreatedExtension: Hooks into the process after a class definition is created.
    • AfterSideEffectCallAnalyzed: Hooks into the process after a side-effect call is analyzed.
    • TypeResolverExtension: Resolves complex or custom types via ReferenceResolutionEvent.
  5. Configure error handling during generation

    main

    You can control whether Scramble should throw exceptions when it encounters errors during the documentation generation process using Scramble::throwOnError(bool $throw = true).

    • When true: An exception is thrown and documentation generation fails immediately.
    • When false: Documentation is still generated, but issues are added to the endpoint descriptions of the failed parts.
  6. Resolve API tags using a custom resolver

    main
    By default, Scramble uses internal logic to group operations into tags. You can override this behavior using Scramble::resolveTagsUsing(callable $tagResolver). The resolver callback receives a RouteInfo and an Operation object and should return an array of strings representing the tags.
  7. Customize rule transformers in Scramble

    main

    You can control which RuleTransformer or AllRulesSchemasTransformer classes are used to process validation rules in your OpenAPI documentation. The RuleTransformers class allows you to replace the default set of transformers, or add new ones to the beginning or end of the processing chain.

    Available Methods

    • use(array $transformers): Replaces the entire set of transformers with the provided list of class strings.
    • prepend(array|string $transformers): Adds one or more transformer class strings to the start of the transformer list.
    • append(array|string $transformers): Adds one or more transformer class strings to the end of the transformer list.

    Default Transformers

    If no transformers are explicitly set using use(), Scramble uses the following default set:

    • AcceptedRule
    • EnumRule
    • InRule
    • FileRule
    • ConfirmedRule
    • ExistsRule
    • RegexRule
  8. Enforce schema rules and prevent forbidden types

    main

    You can enforce rules during documentation generation to ensure your API adheres to specific schema standards.

    • Scramble::enforceSchema(callable $cb, string|callable $errorMessageGetter, array $ignorePaths = [], bool $throw = true): Allows you to define a custom validation callback. If the callback returns false, the error is triggered.
    • Scramble::preventSchema(string|array $schemaTypes, array $ignorePaths = [], bool $throw = true): A convenience method to forbid specific schema classes from appearing in your documentation.

    If $throw is set to true, generation will fail when a rule is violated. If false, errors will be collected and available via the scramble:analyze command.

  9. Retrieve instantiated rule transformer instances

    main

    If you need to access the actual instances of the configured transformers (rather than just their class names), use the instances method. This method resolves the classes from the container and injects any provided contextful bindings.

    • Parameters:
      • string $type: The class name or interface you want to filter by (e.g., RuleTransformer::class).
      • array $contextfulBindings: An associative array of bindings to be injected into the transformer instances.
    • Returns: A Illuminate\Support\Collection containing the instantiated objects.
  10. Register extensions for Scramble

    main

    You can extend Scramble's functionality by registering custom extension classes. Supported extension classes must implement one of the following interfaces: ExceptionToResponseExtension, OperationExtension, TypeToSchemaExtension, or InferExtension.

    Use Scramble::registerExtension($className) for a single class or Scramble::registerExtensions($classNames) for an array of classes.

  11. Configure Scramble API settings

    main
    Use Scramble::configure() to access the GeneratorConfig for the default API. This allows you to customize how documentation is generated, including route resolution, server variables, and document transformers. To configure a specific named API instead of the default, use Scramble::registerApi($name, $config) or Scramble::getGeneratorConfig($name).