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

Open Api Common Laravel Package

jane-php/open-api-common

Shared utilities and models used by Jane PHP for OpenAPI/Swagger code generation and runtime support. Provides common components like normalizers, reference handling, and helpers for building OpenAPI-based API clients and servers in PHP.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require jane-php/open-api-common
    

    No publisher or service provider is required—this is a pure utility library.

  2. First Use Case Use the Jane\OpenApi\Common\OpenApi class to generate or parse OpenAPI specs:

    use Jane\OpenApi\Common\OpenApi;
    
    $openApi = new OpenApi();
    $openApi->info->title = 'My API';
    $openApi->info->version = '1.0.0';
    echo $openApi->toJson(); // Outputs JSON representation
    
  3. Where to Look First

    • Core Classes: Jane\OpenApi\Common\OpenApi (main spec container), Jane\OpenApi\Common\Components (reusable components).
    • Utilities: Jane\OpenApi\Common\Factory (for creating spec objects), Jane\OpenApi\Common\Normalizer (for JSON serialization).
    • Examples: Check the Jane OpenAPI repo for integration examples (though this is a subtree split).

Implementation Patterns

Common Workflows

  1. Generating OpenAPI Specs Dynamically Use the OpenApi class to build specs programmatically:

    $openApi = new OpenApi();
    $openApi->info->title = 'User API';
    $openApi->servers[] = ['url' => 'https://api.example.com/v1'];
    
    // Add a path
    $openApi->paths['/users'] = new \Jane\OpenApi\Common\PathItem();
    $openApi->paths['/users']->get = new \Jane\OpenApi\Common\Operation();
    $openApi->paths['/users']->get->summary = 'List users';
    
  2. Reusing Components Define reusable schemas, responses, or security schemes in components:

    $openApi->components->schemas['User'] = new \Jane\OpenApi\Common\Schema();
    $openApi->components->schemas['User']->type = 'object';
    $openApi->components->schemas['User']->properties['id'] = new \Jane\OpenApi\Common\Property();
    $openApi->components->schemas['User']->properties['id']->type = 'integer';
    
  3. Integration with Laravel

    • API Documentation: Use the generated JSON with tools like Swagger UI or Redoc.
      return response()->json($openApi->toArray());
      
    • Validation: Combine with respect/validation or Laravel’s built-in validation to enforce OpenAPI schemas.
    • Testing: Generate specs dynamically in tests to validate API contracts.
  4. Parsing Existing Specs Load an existing OpenAPI spec from JSON:

    $json = file_get_contents('api-spec.json');
    $openApi = OpenApi::fromJson($json);
    

Integration Tips

  • Laravel Service Container: Bind the OpenApi class for dependency injection:
    $this->app->bind(OpenApi::class, function () {
        return new OpenApi();
    });
    
  • Caching: Cache generated specs in Laravel’s cache system to avoid reprocessing:
    $spec = Cache::remember('openapi-spec', now()->addHours(1), function () {
        return $openApi->toArray();
    });
    
  • Versioning: Use the version field in info to manage API versions explicitly.

Gotchas and Tips

Pitfalls

  1. No Built-in Validation The library does not validate OpenAPI specs against the OpenAPI standard. Use tools like zircote/swagger-php for validation:

    composer require zircote/swagger-php
    
    use Zircote\Swagger\Validator;
    
    $validator = new Validator();
    $validator->validate($openApi->toArray());
    
  2. Immutable Properties Some properties (e.g., OpenApi->info) are objects, not arrays. Direct array assignment won’t work:

    // ❌ Wrong
    $openApi->info = ['title' => 'API']; // Fails
    
    // ✅ Correct
    $openApi->info->title = 'API';
    
  3. Namespace Conflicts The package uses Jane\OpenApi\Common namespace. Ensure no naming collisions with other OpenAPI libraries (e.g., darkghosthunter/openapi).

  4. JSON Serialization Quirks

    • Use toJson() or toArray() for output. Avoid json_encode($openApi) directly.
    • Customize serialization with Jane\OpenApi\Common\Normalizer if needed.

Debugging Tips

  • Dump Specs: Use dd($openApi->toArray()) to inspect the generated spec.
  • Check for Undefined Properties: Laravel IDE helpers (e.g., barryvdh/laravel-ide-helper) can highlight missing properties in autocompletion.
  • Partial Specs: The library allows partial specs, but tools like Swagger UI may fail if required fields (e.g., info) are missing.

Extension Points

  1. Custom Normalizers Extend Jane\OpenApi\Common\Normalizer\NormalizerInterface to modify serialization:

    class CustomNormalizer implements NormalizerInterface {
        public function normalize($object, $format = null, array $context = []) {
            // Custom logic
        }
    }
    
  2. Event Listeners Attach listeners to spec generation (e.g., log changes):

    $openApi->addListener('postGenerate', function ($spec) {
        Log::info('Spec generated:', $spec->toArray());
    });
    
  3. Hybrid Specs Merge dynamic and static specs:

    $dynamicSpec = new OpenApi();
    $staticSpec = OpenApi::fromJson(file_get_contents('static-spec.json'));
    $mergedSpec = $dynamicSpec->merge($staticSpec);
    

Performance Notes

  • Large Specs: Avoid deep nesting in components or paths for complex APIs—it may bloat memory.
  • Lazy Loading: Load only required parts of the spec (e.g., paths or components) when possible.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky