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.
Installation
composer require php-standard-library/type
Add to composer.json under require if not using Composer globally.
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');
Where to Look First
Type::is*() methods (e.g., isString, isArray, isCallable).Type::assert*() methods (e.g., assertString, assertArray).Type::isNullable() or Type::assertNullable() for nullable checks.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).
Combining Checks Use logical operators for complex conditions:
if (Type::isArray($data) && Type::isNonEmpty($data)) {
// Process non-empty array
}
Dynamic Type Validation Validate API inputs or user-provided data:
$validated = Type::assertArray($request->input('data'), 'Invalid data format');
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...
}
Nullable Handling Explicitly declare nullable expectations:
Type::assertNullableString($value, 'Value must be a string or null');
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');
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');
});
}
Service Layer Type Safety Enforce types in service methods:
public function calculateTotal(array $items): float {
Type::assertArray($items, 'Items must be an array');
// ...
}
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);
}
Overuse of Assertions
Null Handling Inconsistencies
Type::isString() with is_string() may lead to inconsistent null behavior.Type::isNullableString() or Type::isString($value) && $value !== null for clarity.False Positives in Custom Validation
assert() callbacks may not handle edge cases (e.g., null).null or use Type::isNullable() in custom logic.Performance with Large Arrays
Type::isAssoc()) on large arrays may be slow.Enable Strict Typing
Add to composer.json for better type safety:
"config": {
"platform": {
"php": "8.1"
}
}
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;
}
Test Edge Cases Write tests for:
null inputs.array vs. object).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');
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);
}
}
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);
}
}
No Runtime Configuration
The package is stateless; all behavior is defined via static methods. No .env or config file is required.
Thread Safety Safe for concurrent use (e.g., in queues or parallel processing).
PHP Version Compatibility
Tested on PHP 8.1+. For older versions, check for deprecated features (e.g., is_callable vs. is_callable behavior changes).
How can I help you explore Laravel packages today?