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 input (JSON/arrays) into fully typed PHP objects, validating along the way with clear, human-readable errors. Supports advanced types (PHPStan/Psalm), shaped arrays, generics, ranges, and can normalize objects back to JSON/CSV while preserving structure.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strong Typing & Validation: Valinor excels in mapping untrusted input (e.g., JSON, arrays) into strongly typed PHP objects, aligning with modern Laravel/Lumen architectures that prioritize type safety and validation. It complements Laravel’s built-in validation (e.g., Form Requests) by enabling compile-time checks via PHPStan/Psalm integration, reducing runtime errors.
  • Domain-Driven Design (DDD) Support: Ideal for mapping raw API responses, database records, or user input into domain entities (e.g., User, Order). Reduces boilerplate for manual type casting/validation.
  • Normalization: Useful for serializing domain objects back to APIs (e.g., JSON, CSV) while preserving structure, though Laravel’s built-in Resource classes may overlap here.
  • Framework Agnosticism: While Laravel-specific integrations (e.g., Symfony bundle) exist, Valinor’s core is framework-agnostic, making it adaptable to custom Laravel extensions (e.g., API middleware, service layers).

Integration Feasibility

  • Low Friction: No Laravel-specific dependencies; integrates via Composer (cuyz/valinor). Minimal setup required beyond basic configuration (e.g., cache, builders).
  • HTTP Request Mapping: Can replace or augment Laravel’s native request resolution (e.g., Illuminate\Http\Request). The HttpRequest adapter supports PSR-7, compatible with Laravel’s underlying stack.
  • Service Container Integration: Easily register MapperBuilder/NormalizerBuilder as Laravel services (e.g., in AppServiceProvider). Shared instances improve performance via caching.
  • Middleware Potential: Can be used to validate/transform incoming requests before they reach controllers (e.g., API gateways).

Technical Risk

  • Performance Overhead: Initial mapping/normalization may introduce latency if caching isn’t configured. Mitigate by:
    • Enabling FileSystemCache (or Redis/Memcached via custom adapters).
    • Pre-warming cache for critical classes (e.g., during bootstrap/cache generation).
  • Static Analysis Dependencies: PHPStan/Psalm integration requires setup and may conflict with existing configs. Test compatibility with Laravel’s default static analysis tools.
  • Error Handling: Valinor’s MappingError must be caught and translated to Laravel’s exception handling (e.g., HttpResponse for APIs). Consider wrapping in a custom exception class.
  • Custom Constructors: If domain objects use non-standard constructors (e.g., factories), Valinor’s custom constructor support must be tested.
  • Laravel-Specific Quirks: Potential edge cases with Laravel’s:
    • Dynamic Properties: Valinor may not handle magic __get/__set methods.
    • Collection Macros: Shaped arrays (e.g., array{key: type}) might conflict with Laravel’s Collection macros.
    • Eloquent Models: Direct mapping to Eloquent models may require custom type hints (e.g., Carbon instances).

Key Questions

  1. Use Case Prioritization:
    • Is Valinor primarily for input validation (replacing Form Requests) or domain mapping (e.g., API responses → entities)?
    • Will it replace Laravel’s built-in validation (e.g., Validator facade) or augment it?
  2. Performance Requirements:
    • What’s the expected throughput for mapped objects (e.g., high-volume APIs)?
    • Is cache warming feasible during deployment (e.g., Artisan command)?
  3. Static Analysis Strategy:
    • Will PHPStan/Psalm be enforced in CI? If so, how will Valinor’s extensions be configured?
  4. Error Handling:
    • Should MappingError be mapped to Laravel’s ValidationException or a custom API error format?
  5. Testing:
    • How will edge cases (e.g., malformed JSON, nested generics) be tested in CI?
  6. Long-Term Maintenance:
    • Will Valinor’s roadmap (e.g., new features) align with Laravel’s lifecycle?
    • Is the MIT license acceptable for the project’s licensing model?

Integration Approach

Stack Fit

  • Laravel Core: Compatible with Laravel 10+ (PHP 8.1+). No conflicts with:
    • Service container (register as singleton).
    • Blade templates (if used for normalization).
    • Eloquent (if mapping to DTOs instead of models).
  • API Layer: Ideal for:
    • Request Validation: Replace FormRequest::rules() with type hints + Valinor.
    • Resource Serialization: Normalize domain objects to JSON/XML for APIs.
    • GraphQL: Map input variables to strongly typed objects (e.g., with repositories package).
  • CLI/Artisan: Useful for parsing command arguments or config files into typed objects.
  • Queue Workers: Validate payloads before processing (e.g., job data).

Migration Path

  1. Pilot Phase:
    • Start with a single high-impact endpoint (e.g., API resource) to validate performance/error handling.
    • Replace manual json_decode() + assert checks with Valinor.
  2. Incremental Adoption:
    • Step 1: Use Valinor for DTOs in service layers (e.g., CreateUserRequestDTO).
    • Step 2: Integrate into API controllers via middleware or argument resolution.
    • Step 3: Replace Form Request validation logic with Valinor + PHPStan.
  3. Framework Integration:
    • Create a custom Laravel package (e.g., laravel-valinor) to:
      • Register MapperBuilder as a singleton.
      • Provide Artisan commands for cache management.
      • Add middleware for automatic request mapping.
    • Example middleware:
      public function handle(Request $request, Closure $next) {
          $mapper = app(MapperBuilder::class)->mapper();
          $request->merge([
              'validated' => $mapper->map(YourDTO::class, $request->all())
          ]);
          return $next($request);
      }
      
  4. Testing:
    • Write PHPUnit tests for critical mappings (e.g., DataProvider for edge cases).
    • Verify static analysis (PHPStan/Psalm) catches type errors early.

Compatibility

  • Laravel-Specific:
    • Collections: Valinor’s shaped arrays (array{key: type}) may conflict with Laravel’s Collection macros. Use explicit type hints (e.g., array<int, Model>).
    • Carbon: Replace DateTime with Carbon via custom type mappings.
    • Filesystem: Use Valinor’s FileSystemCache with Laravel’s storage_path().
  • Third-Party Packages:
    • API Packages (e.g., spatie/array-to-object): Evaluate overlap/duplication.
    • Validation Packages (e.g., laravel-validator): Decide whether to replace or complement.
  • PHP Extensions:
    • Requires json and ctype extensions (standard in Laravel).

Sequencing

Phase Task Dependencies
1. Setup Install Valinor, configure cache, add PHPStan/Psalm extensions. Composer, Laravel service container.
2. Core Mapping Map 1–2 critical DTOs (e.g., API requests/responses). Basic Valinor usage.
3. Integration Register MapperBuilder as a service, create middleware. Laravel service container.
4. Validation Replace Form Requests with Valinor + PHPStan. Static analysis tools.
5. Normalization Use normalizers for API responses. Valinor normalizer setup.
6. Testing Add unit/integration tests for mappings. PHPUnit, Pest.
7. Optimization Warm cache, profile performance. Production monitoring.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Eliminates manual validation logic (e.g., Validator::make()).
    • Type Safety: Catches errors at development time via PHPStan/Psalm.
    • Centralized Logic: Mapping rules live with domain objects (not scattered in controllers).
  • Cons:
    • Cache Management: Requires manual cache clearing during deployments (mitigate with FileWatchingCache in dev).
    • Static Analysis Overhead: PHPStan/Psalm configs may need tuning for Valinor-specific types.
    • Dependency Updates: Monitor Valinor’s release cycle for breaking changes (e.g., new PHP features).
  • Tooling:
    • Artisan Commands: Add custom commands for cache warming/clearing:
      php artisan valinor:warmup --classes="App\\DTO\\*"
      php artisan valinor:clear-cache
      
    • IDE Support: Configure PHPStorm to recognize Valinor’s type
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests