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

Valinor Laravel Package

cuyz/valinor

Valinor maps raw inputs (JSON/arrays) into validated, strongly typed PHP objects. Supports advanced PHPStan/Psalm types (shaped arrays, generics, ranges), produces precise human-readable errors, and can normalize data back to formats like JSON or CSV.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

Valinor excels in Laravel/PHP ecosystems where strong typing, validation, and input normalization are critical. It aligns with Laravel’s dependency injection (DI) patterns, API-first design, and type safety (via PHPStan/Psalm). The package’s decoupled, dependency-free nature makes it a non-intrusive addition to existing Laravel architectures, avoiding framework lock-in while complementing Laravel’s built-in validation (e.g., Form Requests) or third-party libraries like Symfony Serializer or Spatie’s Laravel Data.

Key Fit Areas:

  • API Controllers: Replaces manual Request validation with type-safe, attribute-driven mapping (e.g., #[FromRoute], #[FromQuery]).
  • Command/Job Payloads: Validates CLI/queue inputs (e.g., Artisan commands, Laravel Jobs) without custom parsers.
  • Legacy Array-to-Object Conversion: Modernizes legacy codebases where raw arrays are passed between services.
  • Normalization: Standardizes output formats (e.g., JSON, CSV) for consistency across microservices.

Integration Feasibility

  • Low Friction: Zero Laravel-specific dependencies; integrates via Composer and PSR-7 (for HTTP requests).
  • Framework Agnostic: Works alongside Laravel’s DI container, Symfony components, or plain PHP.
  • PSR-7 Compatibility: Seamlessly integrates with Laravel’s Illuminate\Http\Request via HttpRequest::fromPsr().
  • Existing Validation Overlap: Can replace or augment Laravel’s FormRequest validation for complex nested structures.

Potential Conflicts:

  • Double Validation: If using both Valinor and Laravel’s FormRequest, ensure no redundant validation (e.g., use Valinor for DTOs and FormRequest for auth/CSRF).
  • Performance: Heavy use of runtime reflection (for attribute parsing) may impact cold starts in serverless/Laravel Octane. Benchmark against alternatives like Symfony Serializer.

Technical Risk

Risk Area Mitigation Strategy
Attribute Parsing Test with PHP 8.1+ (attributes are stable). Fallback to constructor injection if needed.
Type System Limits Use PHPStan/Psalm for static checks; Valinor’s runtime validation catches edge cases.
Error Handling Customize MappingError to integrate with Laravel’s exception handler (e.g., return 422 JSON responses).
Normalization Validate output formats early (e.g., ensure Normalizer matches API contracts).
Backward Compatibility Monitor Valinor’s semver (current: ^2.4). Pin major versions in composer.json.

Key Questions for TPM

  1. Use Case Prioritization:
    • Will Valinor replace Laravel’s FormRequest, or supplement it (e.g., for DTOs)?
    • Is it needed for internal services (e.g., queue jobs) or public APIs?
  2. Performance:
    • Will attribute reflection impact Laravel Octane/Horizon? Benchmark against Symfony Serializer.
    • Can mapper configurators reduce runtime overhead for repeated mappings?
  3. Error Strategy:
    • How will MappingError integrate with Laravel’s exception handling (e.g., App\Exceptions\Handler)?
    • Should errors return JSON:API or Laravel’s default 422 responses?
  4. Team Adoption:
    • Does the team prefer attributes (#[FromRoute]) or explicit mapping (e.g., MapperBuilder)?
    • Will PHPStan/Psalm be enforced to leverage static type checks?
  5. Alternatives:
    • Compare with Symfony Serializer (more features, heavier) or Spatie’s Laravel Data (Laravel-specific).
    • Evaluate custom solutions (e.g., hand-written validators) if Valinor’s overhead is prohibitive.

Integration Approach

Stack Fit

Laravel Component Valinor Integration Point Notes
API Controllers #[FromRoute], #[FromQuery], #[FromBody] Replaces manual Request->input() calls.
Form Requests Optional: Use Valinor for DTO validation Keep FormRequest for auth/CSRF; use Valinor for business logic DTOs.
Jobs/Commands MapperBuilder::map() for payloads Validates queue/job inputs (e.g., HandlePayment::dispatch($data)).
Service Layer Normalization for output consistency Ensures API responses match contracts (e.g., Normalizer::toJson()).
PSR-7 Requests HttpRequest::fromPsr() Works with Laravel’s Illuminate\Http\Request.
Testing Mock HttpRequest for unit tests Reduces boilerplate vs. manual Request mocking.

Migration Path

  1. Phase 1: Pilot in Non-Critical Endpoints
    • Start with internal APIs or non-user-facing services (e.g., admin panels).
    • Example: Replace a StorePostRequest with a Valinor-mapped DTO.
    // Before: FormRequest
    public function store(StorePostRequest $request) { ... }
    
    // After: Valinor DTO
    public function store(PostDto $dto) { ... }
    
  2. Phase 2: HTTP Request Mapping
    • Migrate API controllers to use #[FromRoute]/#[FromQuery].
    • Example: Convert Request->route('id') to #[FromRoute] int $id.
  3. Phase 3: Normalization
    • Standardize API responses using Normalizer (e.g., ensure all JSON responses use snake_case).
  4. Phase 4: Legacy Array Replacement
    • Replace raw arrays in service layers with typed objects (e.g., UserRepository::find($id)UserRepository::findAs(User::class, $id)).

Compatibility

  • Laravel 9+: Full support (PHP 8.1+ attributes).
  • Laravel 8: Possible with attribute reflection polyfill (e.g., nikic/php-parser).
  • Symfony Components: Works with Psr\HttpMessage (e.g., Symfony\Component\HttpFoundation\Request via adapter).
  • Testing: Compatible with PestPHP, PHPUnit, and Laravel’s HTTP tests.

Sequencing

  1. Setup:
    • Install: composer require cuyz/valinor.
    • Configure global mapper (e.g., in AppServiceProvider):
      public function boot(): void {
          $this->app->singleton(\CuyZ\Valinor\MapperBuilder::class, fn() => new MapperBuilder());
      }
      
  2. Pilot:
    • Create a DTO test class (e.g., app/Dtos/UserCreateDto.php).
    • Replace one FormRequest with Valinor mapping.
  3. Framework Integration:
    • Build a PSR-7 adapter for Laravel’s Request (if needed).
    • Create a middleware to catch MappingError and return 422 JSON.
  4. Normalization:
    • Add Normalizer to API responses (e.g., in App\Http\Middleware\FormatJson).
  5. Documentation:
    • Update API docs to reflect new DTO-based contracts.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Eliminates manual validation logic (e.g., if (!$request->has('email'))).
    • Type Safety: Catches errors at compile time (PHPStan) and runtime (Valinor).
    • Centralized Rules: Validation logic lives in DTOs, not scattered across controllers.
  • Cons:
    • New Dependency: Adds ~5MB to vendor size (monitor for bloat).
    • Attribute Learning Curve: Team must adopt #[FromRoute] syntax.
    • Debugging: MappingError messages may require familiarity with Valinor’s format.

Support

  • Error Handling:
    • Customize MappingError to include user-friendly messages (e.g., translate field names).
    • Example:
      catch (MappingError $e) {
          return response()->json([
              'errors' => $e->getErrorsAsArray(),
          ], 422);
      }
      
  • Logging:
    • Log failed mappings (e.g
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope