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

Cebe Php Openapi Laravel Package

devizzent/cebe-php-openapi

Fork of cebe/php-openapi providing PHP objects to read/write OpenAPI 3.0/3.1 YAML and JSON. Includes a CLI tool to validate and convert API description files. Install via Composer; works on PHP 7.1+ (including PHP 8).

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require devizzent/cebe-php-openapi

The package now supports Symfony YAML 8.x natively, eliminating the need for manual symfony/yaml installation unless handling complex YAML edge cases.

  1. First Use Case: Reading an OpenAPI File

    use Cebe\OpenApi\Reader;
    use Cebe\OpenApi\OpenApi;
    
    $reader = new Reader();
    $openApi = $reader->read('path/to/openapi.yaml'); // or JSON
    // Access parsed data
    $info = $openApi->getInfo();
    echo $info->getTitle();
    
  2. Where to Look First

    • Documentation: Updated for Symfony YAML 8 compatibility. Check the GitHub repo.
    • Examples: Test cases in tests/ now reflect YAML 8 compatibility.
    • API Reference: Focus on Cebe\OpenApi\Reader, Cebe\OpenApi\Writer, and Cebe\OpenApi\Objects\*.

Implementation Patterns

Workflows

  1. Reading and Validating OpenAPI Specs

    $reader = new Reader();
    $openApi = $reader->read('api-spec.yaml');
    $reader->resolve($openApi); // Strict validation
    
  2. Generating PHP Objects from OpenAPI

    $paths = $openApi->getPaths();
    foreach ($paths as $path => $pathItem) {
        foreach ($pathItem->getOperations() as $method => $operation) {
            echo "Endpoint: {$method} {$path}\n";
            echo "Summary: {$operation->getSummary()}\n";
        }
    }
    
  3. Writing OpenAPI Files

    $openApi = new OpenApi();
    $openApi->info = (new \Cebe\OpenApi\Objects\Info())
        ->title('My API')
        ->version('1.0.0');
    
    $writer = new \Cebe\OpenApi\Writer();
    file_put_contents('output.yaml', $writer->write($openApi));
    
  4. Integration with Laravel

    • Service Provider: Bind the Reader to the container (unchanged):
      $this->app->bind(Reader::class, function () {
          return new Reader();
      });
      
    • Facade: Use the same pattern as before, but note Symfony YAML 8 is now handled internally.
  5. Dynamic API Documentation

    Route::get('/api/docs', function () {
        $openApi = app(Reader::class)->read(storage_path('api-spec.yaml'));
        return response()->json($openApi->toArray());
    });
    

Gotchas and Tips

Pitfalls

  1. Symfony YAML 8 Compatibility

    • No Breaking Changes: The package now internally uses Symfony YAML 8, so manual symfony/yaml installation is no longer required for basic YAML parsing.
    • Edge Cases: If parsing malformed YAML (e.g., custom tags, complex anchors), explicitly install symfony/yaml for advanced use:
      composer require symfony/yaml
      
  2. Validation Strictness

    • resolve() remains strict. Use flags for flexibility:
      $reader->read('spec.yaml', [
          'resolve' => true,
          'allow_outside_references' => true,
          'format_output_for_humans' => true, // Human-readable errors
      ]);
      
  3. Circular References

    • Still handled via resolve_circular_refs:
      $reader->read('spec.yaml', ['resolve_circular_refs' => true]);
      
  4. Performance

    • Cache OpenApi objects to avoid reprocessing:
      $openApi = Cache::remember('openapi_spec', now()->addHours(1), function () {
          return app(Reader::class)->read('spec.yaml');
      });
      

Tips

  1. Leveraging Symfony YAML 8

    • The package now automatically handles YAML 8 features (e.g., stricter parsing, improved anchors). No action required unless debugging YAML issues.
  2. Extending the Library

    • Override Reader for custom validation (unchanged):
      class CustomReader extends Reader {
          protected function customValidation(OpenApi $openApi) {
              // Add logic here
          }
      }
      
  3. Schema Validation

    • Use Objects\Validator to validate requests against OpenAPI schemas:
      $schema = $openApi->getComponents()->getSchemas()['User'];
      $validator = new \Cebe\OpenApi\Objects\Validator();
      $isValid = $validator->validate($request->all(), $schema);
      
  4. Dynamic Laravel Validation Rules

    function generateRulesFromSchema(\Cebe\OpenApi\Objects\Schema $schema): array {
        $rules = [];
        foreach ($schema->getProperties() as $name => $propertySchema) {
            $rules[$name] = 'required';
            if ($propertySchema->getType() === 'string') {
                $rules[$name] .= '|string';
                if ($propertySchema->getFormat() === 'email') {
                    $rules[$name] .= '|email';
                }
            }
        }
        return $rules;
    }
    
  5. Testing

    • Mock Reader in tests (unchanged):
      $mockReader = Mockery::mock(Reader::class);
      $mockReader->shouldReceive('read')->andReturn($mockOpenApi);
      $this->app->instance(Reader::class, $mockReader);
      
  6. Deprecated Dependencies

    • No Breaking Changes: Removed unused dependencies in 1.1.5 do not affect functionality. Focus on Cebe\OpenApi\* classes for core usage.
  7. YAML Best Practices

    • Prefer JSON for specs with special characters (e.g., #, !) to avoid YAML quirks, even with Symfony YAML 8 support.
    • Use inline anchors (&id *) for complex specs to reduce reference bloat.

NO_UPDATE_NEEDED would **not** apply here—this release introduces meaningful changes (Symfony YAML 8 compatibility and dependency cleanup) that warrant updates to the **Gotchas and Tips** section.
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.
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
spatie/mailcoach-vapor
spatie/laravel-javascript-views