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

Php Array Of Laravel Package

chrisharrison/php-array-of

A lightweight PHP helper for creating and working with typed “array of” value collections. Simplifies validation/coercion so arrays contain only the expected item type, improving safety and readability for DTOs, configs, and API payload handling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chrisharrison/php-array-of
    

    No configuration required—just autoload the package.

  2. First Use Case: Enforce an array of strings in a Laravel request handler:

    use ArrayOf\ArrayOf;
    
    $validated = request()->validate(['tags' => 'array']);
    $typedTags = ArrayOf::of('string')->from($validated['tags']);
    
    • If $validated['tags'] contains a non-string (e.g., 123 or null), it throws ArrayOf\Exception\InvalidTypeException.

Where to Look First

  • Core Methods:
    • ArrayOf::of($type) → Creates a validator for type $type (e.g., 'int', User::class).
    • ->from($array) → Validates and returns the array (throws on failure).
    • ->validate($array) → Validates without returning (returns bool).
  • Custom Rules:
    • Use ArrayOf::of(function($value) { return $value > 0; }) for custom logic.

Implementation Patterns

1. DTO Validation

Replace manual foreach checks with php-array-of in DTO constructors:

class UserDTO {
    public function __construct(
        private array $roles,
        private array $permissions
    ) {
        $this->roles = ArrayOf::of('string')->from($roles);
        $this->permissions = ArrayOf::of(Permission::class)->from($permissions);
    }
}
  • Laravel Integration: Use in FormRequest validation:
    public function rules() {
        return ['roles' => 'array'];
    }
    
    public function withValidator($validator) {
        $validator->after(function ($validator) {
            ArrayOf::of('string')->validate($this->input['roles']);
        });
    }
    

2. Domain Model Guarding

Ensure collections in domain objects are type-safe:

class Order {
    public function __construct(
        private array $items
    ) {
        $this->items = ArrayOf::of(OrderItem::class)->from($items);
    }

    public function addItem(OrderItem $item) {
        $this->items[] = $item; // No need for manual type checks
    }
}

3. Input Normalization

Sanitize and validate nested arrays:

$rawData = ['tags' => ['admin', 123, null]];
$cleanTags = ArrayOf::of('string')->from($rawData['tags']);
// Throws on `123` or `null`; returns `['admin']` on success.

4. Custom Validation Rules

Extend Laravel’s validation with reusable rules:

use Illuminate\Validation\Rule;

class ArrayOfRule extends Rule {
    public function __construct($type) {
        $this->type = $type;
    }

    public function passes($attribute, $value) {
        return ArrayOf::of($this->type)->validate($value);
    }
}

// Usage:
'roles' => ['array', new ArrayOfRule('string')],

5. Performance Tips

  • Cache Validators: Reuse validators for repeated checks:
    $validator = ArrayOf::of(User::class);
    foreach ($users as $user) {
        $validator->validate([$user]); // Reuse instance
    }
    
  • Batch Validation: Validate large arrays efficiently:
    $chunks = array_chunk($largeArray, 100);
    foreach ($chunks as $chunk) {
        ArrayOf::of('int')->validate($chunk);
    }
    

Gotchas and Tips

Pitfalls

  1. Null Handling:

    • ArrayOf::of('string')->from([null]) throws an exception.
    • Fix: Use ArrayOf::of('string')->nullable()->from([null]) (if supported; check docs for nullable methods).
  2. Class Validation Quirks:

    • Validates instances, not class names. Pass User::class (not 'User').
    • Gotcha: Namespace-aware! Use App\Models\User::class, not User.
  3. Custom Callables:

    • Callables must return bool. Silent failures (returning false without throwing) may hide bugs.
    • Tip: Log or throw exceptions in custom rules for clarity.
  4. Empty Arrays:

    • ArrayOf::of('int')->from([]) passes (empty arrays are valid).
    • Tip: Add a separate check if empty arrays are invalid:
      if (empty($array)) throw new \InvalidArgumentException('Array cannot be empty');
      

Debugging

  1. Silent Failures:

    • Always check return types. validate() returns bool, while from() throws.
    • Tip: Use try-catch for graceful handling:
      try {
          $typedArray = ArrayOf::of('int')->from($input);
      } catch (InvalidTypeException $e) {
          report($e); // Log without crashing
          return response()->json(['error' => 'Invalid data'], 400);
      }
      
  2. Type Hints:

    • Add PHPDoc @throws to methods using php-array-of:
      /**
       * @throws InvalidTypeException
       */
      public function process(array $items) {
          $validItems = ArrayOf::of(Item::class)->from($items);
          // ...
      }
      

Extension Points

  1. Custom Exceptions:

    • Extend ArrayOf\Exception\InvalidTypeException for domain-specific errors:
      class InvalidOrderItemException extends InvalidTypeException {}
      ArrayOf::of(OrderItem::class)->onInvalidThrow(new InvalidOrderItemException());
      
  2. Lazy Validation:

    • Defer validation until access (e.g., in a lazy-loaded collection):
      class LazyArray {
          private $array;
          private $validator;
      
          public function __construct(array $array, $type) {
              $this->array = $array;
              $this->validator = ArrayOf::of($type);
          }
      
          public function get() {
              return $this->validator->from($this->array);
          }
      }
      
  3. Integration with Laravel Collectives:

    • Combine with Illuminate\Support\Collection for fluent validation:
      $collection = collect($rawData)
          ->pipe(function ($coll) {
              return ArrayOf::of('string')->from($coll->all());
          });
      

Config Quirks

  • No Config File: The package is zero-config. All behavior is runtime-defined.
  • Type Flexibility:
    • Supports scalar types ('int', 'bool'), classes (User::class), and callables.
    • Tip: For complex types, use callables:
      ArrayOf::of(function ($value) {
          return $value instanceof User && $value->isActive();
      })->from($users);
      

Pro Tips

  1. Combine with Laravel’s ensure():

    $user = User::query()->findOrFail($id)->ensure(fn ($user) =>
        ArrayOf::of(User::class)->from([$user])
    );
    
  2. API Response Wrapping: Ensure API responses are typed:

    return response()->json([
        'data' => ArrayOf::of(UserResource::class)->from(UserResource::collection($users))
    ]);
    
  3. Testing:

    • Mock ArrayOf in unit tests to simulate validation failures:
      $this->partialMock(ArrayOf::class, 'of')
           ->shouldReceive('from')
           ->andThrow(new InvalidTypeException());
      
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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