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

Oooas Laravel Package

goldspecdigital/oooas

Dependency-free PHP library for building OpenAPI specs with immutable, strongly-typed objects. Compose info, paths, operations, schemas, responses, and tags in code, then export the finished specification to JSON (YAML via another package).

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require goldspecdigital/oooas:^2.10

Add to composer.json if not using autoloading:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Oooas\\": "vendor/goldspecdigital/oooas/src/"
    }
}

Run composer dump-autoload.

  1. First Use Case: Basic API Definition with Schema Contracts Create a simple API class extending Oooas\OpenApi\OpenApi and leverage the new SchemaContract support:

    use Oooas\OpenApi\OpenApi;
    use Oooas\OpenApi\Schema;
    
    class MyApi extends OpenApi
    {
        public function init(): void
        {
            $this->info->title = 'My API';
            $this->info->version = '1.0.0';
    
            // Define a schema using SchemaContract (new in v2.10)
            $this->components->schemas->user = new class extends Schema {
                public function init(): void
                {
                    $this->type = 'object';
                    $this->properties = [
                        'id' => new class extends Schema {
                            public function init(): void {
                                $this->type = 'integer';
                            }
                        },
                        'name' => new class extends Schema {
                            public function init(): void {
                                $this->type = 'string';
                            }
                        },
                    ];
                }
            };
        }
    }
    
  2. Generate Spec

    $api = new MyApi();
    $api->generate();
    echo $api->toJson();
    

Key Starting Points

  • Documentation: GitHub README (updated for v2.10).
  • Core Classes:
    • Oooas\OpenApi\OpenApi (base class)
    • Oooas\OpenApi\Schema (now supports SchemaContract instances in properties())
    • Oooas\OpenApi\MediaType (for request/response bodies)
    • Oooas\OpenApi\Operation (for endpoints)
  • Example Projects: Check for Laravel-specific examples or fork the repo for samples.

Implementation Patterns

1. Laravel Integration Workflow

Route-Based API Documentation

Use middleware to auto-generate OpenAPI specs from Laravel routes (unchanged):

// app/Http/Middleware/DocumentApi.php
public function handle($request, Closure $next)
{
    if ($request->path() === 'api/docs') {
        $api = new MyApi();
        $api->generate();
        return response()->json($api->toArray());
    }
    return $next($request);
}

Dynamic Endpoint Mapping

Map Laravel routes to OpenAPI operations (unchanged):

use Oooas\OpenApi\Operation;

class MyApi extends OpenApi
{
    public function init(): void
    {
        $this->path('/users', function (Operation $path) {
            $path->get(function (Operation $operation) {
                $operation->summary = 'Get all users';
                $operation->operationId = 'getUsers';
                $operation->responses->{'200'} = new \stdClass();
            });
        });
    }
}

2. Component-Based Patterns

Reusable Schema Contracts (Updated for v2.10)

Leverage the new SchemaContract support for nested schemas:

// app/OpenApi/Components/UserSchema.php
use Oooas\OpenApi\Schema;

class UserSchema extends Schema
{
    public function init(): void
    {
        $this->type = 'object';
        $this->properties = [
            'id' => new class extends Schema {
                public function init(): void {
                    $this->type = 'integer';
                    $this->format = 'int64';
                }
            },
            'name' => new class extends Schema {
                public function init(): void {
                    $this->type = 'string';
                    $this->maxLength = 100;
                }
            },
            'address' => new AddressSchema(), // Another SchemaContract
        ];
    }
}

Security Schemes (Unchanged)

Define JWT or API key security globally:

$this->components->securitySchemes->bearerAuth = [
    'type' => 'http',
    'scheme' => 'bearer',
    'bearerFormat' => 'JWT',
];

3. Testing and Validation

Validate Against OpenAPI Spec (Unchanged)

Use zircote/swagger-php to validate generated specs:

composer require zircote/swagger-php
use Zircote\Swagger\Validator;

$validator = new Validator();
$results   = $validator->validate($api->toArray());

Unit Test Schema Contracts (Updated)

Test nested SchemaContract instances:

public function testUserSchemaWithContracts()
{
    $schema = new UserSchema();
    $this->assertInstanceOf(Schema::class, $schema->properties['id']);
    $this->assertEquals('int64', $schema->properties['id']->format);
}

Gotchas and Tips

Pitfalls

  1. SchemaContract Initialization Order

    • Ensure all nested SchemaContract instances are properly initialized in init().
    • Avoid circular references between contracts.
  2. Operation ID Conflicts (Unchanged)

    • Ensure operationId is unique across all endpoints.
  3. Media Type Mismatches (Unchanged)

    • OOOAS uses MediaType for request/response bodies. Ensure schema is properly set:
      $response->content->{'application/json'} = new MediaType();
      $response->content->{'application/json'}->schema = new UserSchema();
      
  4. Server URL Handling (Unchanged)

    • OOOAS expects absolute URLs in servers. Use Laravel’s url() helper.

Debugging Tips

  1. Inspect Schema Contracts Dump nested schemas to verify initialization:

    dd($api->components->schemas->user->properties['address']);
    
  2. Validate Incrementally (Unchanged) Test components (schemas, paths) in isolation before combining them.

  3. Leverage Laravel’s dd() (Unchanged) Debug complex objects:

    dd($api->paths->{'/users'}->get->responses);
    

Extension Points

  1. Custom Schema Contracts Create reusable contracts for complex nested structures:

    class PaginationSchema extends Schema {
        public function init(): void {
            $this->type = 'object';
            $this->properties = [
                'total' => new class extends Schema {
                    public function init(): void { $this->type = 'integer'; }
                },
                'per_page' => new class extends Schema {
                    public function init(): void { $this->type = 'integer'; }
                },
            ];
        }
    }
    
  2. Plugin System (Unchanged) Create plugins for auto-generating specs from Laravel controllers.

  3. Event System (Unchanged) Hook into Oooas\OpenApi\Events to modify the spec dynamically.


Laravel-Specific Quirks

  1. Route Caching (Unchanged) If using php artisan route:cache, regenerate the OpenAPI spec manually.

  2. Dynamic Routes (Unchanged) Handle dynamic segments (e.g., {id}) in paths.

  3. Middleware Integration (Unchanged) Exclude middleware-heavy routes from OpenAPI docs.


Performance Tips

  1. Cache Generated Specs (Unchanged) Store the JSON output in Laravel’s cache.

  2. Lazy-Load Schema Contracts Defer loading heavy contracts until needed (e.g., only include PaginationSchema for paginated endpoints).


Breaking Changes in v2.10

  • Schema Properties Now Accept Contracts The Schema::properties() method now expects SchemaContract instances for nested schemas. Ensure all schema definitions are updated to use the new syntax:
    // Old (deprecated)
    $this->properties = ['id' => ['type' => 'integer']];
    
    // New (v2.10+)
    $this->properties = ['id' => new class extends Schema {
        public function init(): void { $this->type = 'integer'; }
    }];
    
  • Dev Dependency Updates The CI pipeline fixes may introduce minor dependency updates. Test thoroughly if using dev dependencies.

NO_UPDATE_NEEDED would not apply here due to the breaking change in schema handling.
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity