Scramble
repository·main·Indexed 24 days ago
https://github.com/dedoc/scrambleA 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.
What's inside scramble
- 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.
Access Scramble API documentation and JSON schema
mainOnce 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
localenvironment. To change this behavior or restrict access in other environments, you must define theviewApiDocsgate./docs/api /docs/api.jsonInstall Scramble via Composer
mainTo add Scramble to your Laravel project, install the package using Composer:
composer require dedoc/scrambleUse the Index class to retrieve class and function definitions
mainThe
Dedoc\Scramble\Infer\Scope\Indexclass acts as a central repository for type information discovered during analysis. It stores and provides access toClassDefinitionandFunctionLikeDefinitionobjects for classes, functions, and constants found in the analyzed codebase.Key behaviors:
- Lazy Loading: If a class or function is requested via
getClass()orgetFunction()but hasn't been registered yet, theIndexwill attempt to reflect on it and build a definition on the fly. - AST Analysis: For classes, if the Scramble configuration
shouldAnalyzeAstis enabled for a specific class name,getClass()will use aClassAnalyzerto perform a deep analysis. Otherwise, it falls back to aShallowClassReflectionDefinitionBuilder. - Caching: Once a definition is built or registered, it is stored in the internal
$classesDefinitionsor$functionsDefinitionsarrays for subsequent calls.
- Lazy Loading: If a class or function is requested via
Manage inference extensions with ExtensionsBroker
mainThe
ExtensionsBrokeracts 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 viaReferenceResolutionEvent.
Configure error handling during generation
mainYou 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.
- When
Resolve API tags using a custom resolver
mainBy default, Scramble uses internal logic to group operations into tags. You can override this behavior usingScramble::resolveTagsUsing(callable $tagResolver). The resolver callback receives aRouteInfoand anOperationobject and should return an array of strings representing the tags.Customize rule transformers in Scramble
mainYou can control which
RuleTransformerorAllRulesSchemasTransformerclasses are used to process validation rules in your OpenAPI documentation. TheRuleTransformersclass 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:AcceptedRuleEnumRuleInRuleFileRuleConfirmedRuleExistsRuleRegexRule
Enforce schema rules and prevent forbidden types
mainYou 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 returnsfalse, 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
$throwis set totrue, generation will fail when a rule is violated. Iffalse, errors will be collected and available via thescramble:analyzecommand.Retrieve instantiated rule transformer instances
mainIf you need to access the actual instances of the configured transformers (rather than just their class names), use the
instancesmethod. 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\Collectioncontaining the instantiated objects.
- Parameters:
Register extensions for Scramble
mainYou can extend Scramble's functionality by registering custom extension classes. Supported extension classes must implement one of the following interfaces:
ExceptionToResponseExtension,OperationExtension,TypeToSchemaExtension, orInferExtension.Use
Scramble::registerExtension($className)for a single class orScramble::registerExtensions($classNames)for an array of classes.Configure Scramble API settings
mainUseScramble::configure()to access theGeneratorConfigfor 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, useScramble::registerApi($name, $config)orScramble::getGeneratorConfig($name).