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

  • Strongly-Typed Data Mapping: Valinor excels in transforming raw input (JSON, arrays, HTTP requests) into strongly-typed PHP objects, aligning perfectly with Laravel’s emphasis on type safety and modern PHP practices.
  • Framework-Agnostic but Laravel-Compatible: While dependency-free, it integrates seamlessly with Laravel’s ecosystem (e.g., PSR-7 support, HTTP request mapping) without coupling to Laravel-specific components.
  • Validation-First Approach: Leverages PHPStan/Psalm types for validation, reducing runtime errors and improving developer experience—critical for Laravel’s API-heavy applications.
  • Normalization Capabilities: Useful for standardizing output (e.g., API responses, CSV exports) while preserving structure.

Integration Feasibility

  • HTTP Request Handling: Native support for mapping route/query/body parameters to controller arguments or DTOs, replacing manual parsing (e.g., request()->input()) with type-safe alternatives.
  • Laravel Middleware/Service Container: Can be integrated into Laravel’s middleware pipeline (e.g., validating incoming requests before processing) or as a service provider for global mapping configurations.
  • Existing Laravel Packages: Complements packages like spatie/array-to-object, symfony/serializer, or laravel/validation by offering a more performant, type-driven alternative.
  • API Contracts: Ideal for defining and enforcing API request/response contracts (e.g., OpenAPI/Swagger schemas) with runtime validation.

Technical Risk

  • Learning Curve: Requires adoption of PHPStan/Psalm types and Valinor’s attribute-based syntax (#[FromRoute], etc.), which may necessitate team training.
  • Performance Overhead: While optimized (Blackfire-backed), complex mappings or large payloads could introduce latency. Benchmark against existing solutions (e.g., json_decode + manual validation).
  • Error Handling: Custom MappingError exceptions must be mapped to Laravel’s exception handling (e.g., App\Exceptions\Handler) to ensure consistent API responses.
  • Tooling Dependency: Relies on static analysis tools (PHPStan/Psalm) for type enforcement; teams without these tools may face friction.

Key Questions

  1. Use Case Alignment:
    • Will Valinor replace Laravel’s built-in request validation ($request->validate()) or augment it (e.g., for DTOs)?
    • Is it primarily for API endpoints, form requests, or internal service boundaries?
  2. Tooling Support:
    • Does the team use PHPStan/Psalm? If not, what’s the plan for adoption?
  3. Error Handling Strategy:
    • How will MappingError exceptions be translated into Laravel’s error format (e.g., JSON API errors)?
  4. Performance Requirements:
    • Are there latency-sensitive endpoints where Valinor’s overhead could be problematic?
  5. Migration Path:
    • How will existing manual parsing/validation logic (e.g., in controllers) transition to Valinor?
  6. Testing Impact:
    • Will Valinor’s validation reduce or increase test coverage needs (e.g., fewer unit tests for parsing logic)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • HTTP Layer: Replaces manual request parsing in controllers (e.g., request()->route('id')#[FromRoute] int $id).
    • APIs: Ideal for Laravel Sanctum/Passport APIs where request/response contracts are critical.
    • Forms: Can validate and map form submissions (e.g., #[FromBody(asRoot: true)] for Request objects).
  • Complementary Packages:
    • Laravel Fortify/Sanctum: Validate auth payloads (e.g., login requests) with Valinor’s DTOs.
    • Laravel Scout: Map search query parameters to typed filters.
    • Laravel Nova: Define Nova resource filters/requests as Valinor-mapped DTOs.
  • Non-HTTP Use Cases:
    • Map database results (e.g., Eloquent collections) to typed objects.
    • Normalize data for queues/jobs (e.g., Valinor\Normalizer for JSON payloads).

Migration Path

  1. Pilot Phase:
    • Start with a single API endpoint or form request. Replace manual parsing with Valinor’s attributes.
    • Example: Convert a controller like this:
      public function store(Request $request) {
          $data = $request->validate([
              'name' => 'string|max:255',
              'email' => 'email',
          ]);
          // ...
      }
      
      To:
      public function store(#[FromBody] UserCreationDto $data) {}
      
  2. Incremental Adoption:
    • Step 1: Use Valinor for input mapping (HTTP requests, JSON APIs).
    • Step 2: Extend to output normalization (e.g., API responses).
    • Step 3: Replace internal array-to-object conversions (e.g., in services).
  3. Tooling Setup:
    • Install PHPStan/Psalm and configure to enforce Valinor-compatible types.
    • Add a MappingError exception handler in App\Exceptions\Handler.
  4. Testing:
    • Update tests to use Valinor’s DTOs instead of raw arrays.
    • Add integration tests for error scenarios (e.g., invalid input).

Compatibility

  • Laravel Versions: Supports PHP 8.1+ (Laravel 9+), with no breaking changes expected for minor releases.
  • Existing Code:
    • Minimal changes required for controllers using Request objects (attributes replace manual parsing).
    • Services using arrays can adopt Valinor incrementally (e.g., wrap json_decode with MapperBuilder).
  • Third-Party Packages:
    • No known conflicts; Valinor is dependency-free.
    • May need to adapt packages that expect raw arrays (e.g., some legacy libraries).

Sequencing

  1. Phase 1: Input Mapping
    • Focus on HTTP request handling (controllers, middleware).
    • Prioritize APIs with complex validation rules.
  2. Phase 2: Output Normalization
    • Standardize API responses, CSV exports, or queue payloads.
  3. Phase 3: Internal Services
    • Replace array-to-object conversions in business logic.
  4. Phase 4: Tooling
    • Integrate PHPStan/Psalm checks into CI/CD pipelines.

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Eliminates repetitive validation logic (e.g., validate() arrays).
    • Centralized Rules: Validation rules live in type hints/DTOs, not scattered across controllers.
    • Consistent Errors: Human-readable error messages from Valinor align with API standards.
  • Cons:
    • Configuration Drift: Custom mappers/normalizers may need updates if input schemas change.
    • Dependency Management: Valinor’s MIT license is permissive, but long-term maintenance depends on the community (1.5K stars, active releases).

Support

  • Developer Experience:
    • IDE Support: PHPStorm/Psalm provide autocompletion for DTOs and attributes.
    • Debugging: Clear error messages help diagnose mapping failures.
  • Team Onboarding:
    • Requires training on PHPStan/Psalm types and Valinor’s syntax.
    • Document DTO schemas and mapping rules for new hires.
  • Community:
    • Active GitHub community (150+ contributors) and comprehensive docs.
    • Slack/Discord support may be limited; issues are resolved promptly.

Scaling

  • Performance:
    • Benchmark: Compare Valinor’s mapping speed against json_decode + manual validation for critical paths.
    • Caching: Reuse MapperBuilder instances for repeated mappings (e.g., in middleware).
    • Normalization: Use Normalizer for batch operations (e.g., exporting 1000+ records).
  • Load Handling:
    • Stateless design (no shared state in mappers) scales horizontally.
    • Potential bottleneck: Complex mappings with deep recursion (mitigate with simple DTOs).
  • Database Integration:
    • Useful for mapping Eloquent collections to typed objects (e.g., User[]array<UserDto>).

Failure Modes

  • Runtime Errors:
    • MappingError: Catch and translate to Laravel’s HttpResponse with appropriate status codes (e.g., 422 Unprocessable Entity).
    • Example:
      catch (MappingError $e) {
          return response()->json([
              'errors' => $e->getErrors(),
          ], 422);
      }
      
  • Schema Mismatches:
    • Input data violating type hints (e.g., string where int is expected) will fail fast.
    • Mitigate with runtime checks or fallback defaults (e.g., #[FromQuery] ?int $page = 1).
  • Tooling Failures:
    • PHPStan/Psalm misconfigurations may cause false positives/negatives. Validate CI/CD setup early.

Ramp-Up

  • Initial Setup:
    • **Time Estimate
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata