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 Index Laravel Package

common-gateway/open-index

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Integration

  1. Installation Add the package via Composer:

    composer require common-gateway/open-index
    

    Publish the config file (if available) to customize behavior:

    php artisan vendor:publish --provider="CommonGateway\OpenIndex\OpenIndexServiceProvider"
    
  2. First Use Case: Validating a Publication OpenIndex is designed to validate structured data against OpenRegisters schemas. Start by defining a publication payload (e.g., a JSON object representing a dataset or catalog entry) and use the validator:

    use CommonGateway\OpenIndex\Validators\PublicationValidator;
    
    $validator = new PublicationValidator();
    $isValid = $validator->validate($publicationPayload);
    
    if (!$isValid) {
        $errors = $validator->errors(); // Get validation error details
    }
    
  3. Key Classes to Explore

    • PublicationValidator: Core class for validating publications against OpenRegisters schemas.
    • OpenIndexService: Service class for interacting with the OpenIndex API (if applicable).
    • SchemaManager: Manages schema definitions (if the package includes schema handling).

    Refer to the src/ directory for these classes and their methods.


Implementation Patterns

Workflow: Integrating OpenIndex into a Laravel Application

  1. Data Ingestion Use OpenIndex to validate incoming data (e.g., from APIs, forms, or CSV uploads) before processing:

    public function store(Request $request)
    {
        $publication = $request->validate([
            'data' => 'required|json',
        ]);
    
        $validator = new PublicationValidator();
        if (!$validator->validate(json_decode($publication['data'], true))) {
            return response()->json(['errors' => $validator->errors()], 422);
        }
    
        // Proceed with saving/processing the validated data
    }
    
  2. Scheduled Validation Validate existing publications in your database periodically (e.g., via Laravel's scheduler):

    use CommonGateway\OpenIndex\Validators\PublicationValidator;
    
    public function validateExistingPublications()
    {
        $publications = Publication::all();
        foreach ($publications as $publication) {
            $validator = new PublicationValidator();
            if (!$validator->validate($publication->data)) {
                // Log or notify about invalid data
                Log::error('Invalid publication', ['data' => $publication->data, 'errors' => $validator->errors()]);
            }
        }
    }
    

    Add to app/Console/Kernel.php:

    protected function schedule(Schedule $schedule)
    {
        $schedule->command('publications:validate')->daily();
    }
    
  3. API Response Filtering Use OpenIndex to filter or transform API responses before returning them to clients:

    public function show(Publication $publication)
    {
        $validator = new PublicationValidator();
        if (!$validator->validate($publication->data)) {
            return response()->json(['status' => 'invalid'], 400);
        }
    
        return response()->json($this->transformPublication($publication));
    }
    
  4. Event-Driven Validation Trigger validation when specific events occur (e.g., created, updated):

    use Illuminate\Support\Facades\Event;
    
    Publication::created(function ($publication) {
        $validator = new PublicationValidator();
        if (!$validator->validate($publication->data)) {
            Event::dispatch('publication.invalid', $publication);
        }
    });
    
  5. Custom Schema Handling If the package supports custom schemas, extend the SchemaManager or create a decorator:

    class CustomSchemaManager extends \CommonGateway\OpenIndex\SchemaManager
    {
        public function getSchema(string $schemaName)
        {
            // Override or extend schema logic
            return parent::getSchema($schemaName);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Schema Mismatches

    • OpenIndex relies on OpenRegisters schemas. Ensure your data matches the expected structure. Use the errors() method to debug mismatches:
      $validator = new PublicationValidator();
      $validator->validate($data);
      dd($validator->errors()); // Inspect schema-specific errors
      
    • Tip: Test with a minimal valid payload first to isolate issues.
  2. Performance with Large Datasets

    • Validating large datasets (e.g., thousands of records) can be slow. Batch processing is recommended:
      Publication::chunk(100, function ($publications) {
          foreach ($publications as $publication) {
              $validator = new PublicationValidator();
              $validator->validate($publication->data);
              // Handle errors per batch
          }
      });
      
  3. Missing Documentation

    • The package has limited documentation. Use PHPDoc blocks and method signatures as primary references:
      // Example: Inspect method signatures in PublicationValidator
      $reflection = new ReflectionClass(PublicationValidator::class);
      foreach ($reflection->getMethods() as $method) {
          echo $method->getName() . ': ' . $method->getDocComment() . "\n";
      }
      
  4. API Dependencies

    • If OpenIndex interacts with an external API (e.g., OpenRegisters), handle rate limits and retries gracefully:
      use Illuminate\Support\Facades\Http;
      
      Http::timeout(30)->retry(3, 100)->get('https://api.openregisters.app/validate');
      
  5. Localization Issues

    • Error messages may be in Dutch (based on the README). Override them in your language files:
      // config/app.php
      'locale' => 'en',
      
      // resources/lang/en/validation.php
      'open_index' => [
          'invalid_schema' => 'The provided data does not match the expected schema.',
      ],
      

Debugging Tips

  1. Enable Debug Mode Set OPEN_INDEX_DEBUG=true in your .env to log detailed validation steps:

    OPEN_INDEX_DEBUG=true
    
  2. Mock External Dependencies Use Laravel's HTTP mocking to test without hitting external APIs:

    Http::fake([
        'api.openregisters.app/validate' => Http::response(['valid' => true], 200),
    ]);
    
  3. Log Validation Errors Create a custom log channel for OpenIndex errors:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        \Log::extend('open_index', function ($app) {
            return new \Monolog\Logger('open_index', [
                new \Monolog\Handler\StreamHandler(storage_path('logs/open_index.log')),
            ]);
        });
    }
    

Extension Points

  1. Custom Validators Extend the base validator to add domain-specific rules:

    use CommonGateway\OpenIndex\Validators\PublicationValidator;
    
    class CustomPublicationValidator extends PublicationValidator
    {
        protected function rules()
        {
            return array_merge(parent::rules(), [
                'custom_field' => 'required|string|max:255',
            ]);
        }
    }
    
  2. Schema Extensions Add custom schemas by extending the SchemaManager:

    class ExtendedSchemaManager extends \CommonGateway\OpenIndex\SchemaManager
    {
        public function registerCustomSchemas()
        {
            $this->schemas['custom_schema'] = json_decode(file_get_contents('path/to/schema.json'), true);
        }
    }
    
  3. Event Listeners Listen for validation events to trigger side effects (e.g., notifications):

    Event::listen('publication.validated', function ($publication) {
        Notification::send($publication->owner, new PublicationValidated($publication));
    });
    
  4. Middleware for API Routes Protect API routes with OpenIndex validation middleware:

    Route::middleware(['validate.publication'])->group(function () {
        Route::post('/publications', [PublicationController::class, 'store']);
    });
    

    Register the middleware in app/Http/Kernel.php:

    protected $routeMiddleware = [
        'validate.publication' => \CommonGateway\OpenIndex\Http\Middleware\ValidatePublication::class,
    ];
    
  5. Testing Use Laravel's testing tools to assert validation outcomes:

    public function test_publication_validation()
    {
        $validator = new PublicationValidator();
        $this->assertFalse($validator->validate(['invalid' => 'data']));
        $this->assertCount(2, $validator->errors());
    }
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle