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

Type Laravel Package

php-standard-library/type

Runtime type validation for PHP using “Parse, Don’t Validate”: coerce and assert unstructured input into well-typed data. Useful for APIs, configs, and user input with clear parsing rules, assertions, and predictable failures.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-standard-library/type
    

    Add to composer.json under require if not using Composer globally.

  2. First Use Case Replace ad-hoc is_* checks with centralized type helpers. Example:

    use PhpStandardLibrary\Type\Type;
    
    // Detect type
    if (Type::isString($value)) {
        // Handle string
    }
    
    // Validate with assertion
    Type::assertString($value, 'Expected a string');
    
  3. Where to Look First

    • Core Helpers: Type::is*() methods (e.g., isString, isArray, isCallable).
    • Validation: Type::assert*() methods (e.g., assertString, assertArray).
    • Null Handling: Use Type::isNullable() or Type::assertNullable() for nullable checks.

Implementation Patterns

Type Detection Workflows

  1. Centralized Type Checks Replace scattered is_string(), is_array(), etc., with:

    if (Type::isString($input)) {
        // Process string
    }
    

    Benefit: Consistent behavior across the codebase (e.g., handling null uniformly).

  2. Combining Checks Use logical operators for complex conditions:

    if (Type::isArray($data) && Type::isNonEmpty($data)) {
        // Process non-empty array
    }
    
  3. Dynamic Type Validation Validate API inputs or user-provided data:

    $validated = Type::assertArray($request->input('data'), 'Invalid data format');
    

Validation Patterns

  1. Guard Clauses Use assert* methods early in functions to fail fast:

    public function processData($data) {
        Type::assertArray($data, 'Data must be an array');
        Type::assertNonEmpty($data, 'Array cannot be empty');
        // Proceed...
    }
    
  2. Nullable Handling Explicitly declare nullable expectations:

    Type::assertNullableString($value, 'Value must be a string or null');
    
  3. Custom Validation Logic Extend with custom rules (see Gotchas for extension points):

    Type::assert($value, fn($v) => is_int($v) && $v > 0, 'Must be a positive integer');
    

Integration with Laravel

  1. Form Request Validation Replace Laravel’s validated() with type assertions for stricter control:

    public function rules() {
        return [
            'name' => 'required|string',
            'age' => 'nullable|integer',
        ];
    }
    
    public function withValidator($validator) {
        $validator->after(function ($validator) {
            Type::assertString($this->name, 'Name must be a string');
        });
    }
    
  2. Service Layer Type Safety Enforce types in service methods:

    public function calculateTotal(array $items): float {
        Type::assertArray($items, 'Items must be an array');
        // ...
    }
    
  3. Middleware for API Inputs Validate incoming requests in middleware:

    public function handle($request, Closure $next) {
        Type::assertArray($request->json()->all(), 'Request body must be an array');
        return $next($request);
    }
    

Gotchas and Tips

Pitfalls

  1. Overuse of Assertions

    • Issue: Excessive assertions can lead to noisy error messages or performance overhead.
    • Fix: Use assertions for critical paths (e.g., API inputs) and type checks for optional logic.
  2. Null Handling Inconsistencies

    • Issue: Mixing Type::isString() with is_string() may lead to inconsistent null behavior.
    • Fix: Stick to Type::isNullableString() or Type::isString($value) && $value !== null for clarity.
  3. False Positives in Custom Validation

    • Issue: Custom assert() callbacks may not handle edge cases (e.g., null).
    • Fix: Explicitly handle null or use Type::isNullable() in custom logic.
  4. Performance with Large Arrays

    • Issue: Deep type checks (e.g., Type::isAssoc()) on large arrays may be slow.
    • Fix: Cache results or use early returns for performance-critical code.

Debugging Tips

  1. Enable Strict Typing Add to composer.json for better type safety:

    "config": {
        "platform": {
            "php": "8.1"
        }
    }
    
  2. Log Validation Failures Extend assertions to log context:

    try {
        Type::assertString($value);
    } catch (TypeException $e) {
        logger()->error("Type validation failed for {$e->getPath()}: {$e->getMessage()}");
        throw $e;
    }
    
  3. Test Edge Cases Write tests for:

    • null inputs.
    • Mixed types (e.g., array vs. object).
    • Nested structures (e.g., arrays of arrays).

Extension Points

  1. Custom Type Guards Add reusable type checks:

    Type::extend('positive_int', fn($value) => is_int($value) && $value > 0);
    Type::assert('positive_int', $value, 'Must be a positive integer');
    
  2. Integration with Laravel Validators Create a custom validator rule:

    use PhpStandardLibrary\Type\Type;
    
    class IsPositiveInteger implements Rule
    {
        public function passes($attribute, $value) {
            return Type::isPositiveInteger($value);
        }
    }
    
  3. Override Default Behavior Replace core methods (e.g., isArray) by extending the Type class:

    class CustomType extends Type {
        public static function isArray(mixed $value): bool {
            return parent::isArray($value) && !empty($value);
        }
    }
    

Config Quirks

  1. No Runtime Configuration The package is stateless; all behavior is defined via static methods. No .env or config file is required.

  2. Thread Safety Safe for concurrent use (e.g., in queues or parallel processing).

  3. PHP Version Compatibility Tested on PHP 8.1+. For older versions, check for deprecated features (e.g., is_callable vs. is_callable behavior changes).

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
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
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