anothanj / casterly
A PHP library for type casting.
Requires
- php: >=8.4
Requires (Dev)
- friendsofphp/php-cs-fixer: v3.92.5
- phpstan/phpstan: 2.1.33
- phpunit/phpunit: 12.5.5
This package is auto-updated.
Last update: 2026-03-22 09:26:48 UTC
README
A PHP library for safe type casting that is compatible with PHPStan static analysis.
Casterly provides type casting utilities that help you cast mixed values to scalar types while maintaining type safety and PHPStan compatibility. This is particularly useful when working with data from external sources (APIs, form inputs, configuration files) where you know the expected type but need to satisfy static analysis requirements.
Installation
Install via Composer:
composer require anothanj/casterly
Requirements
- PHP 8.4 or higher
Usage
Quick Start with the Cast Utility Class
The simplest way to use Casterly is through the static Cast utility class:
<?php use Casterly\Cast; use Casterly\Exceptions\CastException; try { // Cast to boolean $bool = Cast::toBool('1'); // true $bool = Cast::toBool(0); // false $bool = Cast::toBool(null); // false // Cast to integer $int = Cast::toInt('42'); // 42 $int = Cast::toInt(3.14); // 3 $int = Cast::toInt(true); // 1 // Cast to float $float = Cast::toFloat('3.14'); // 3.14 $float = Cast::toFloat(42); // 42.0 $float = Cast::toFloat('inf'); // INF // Cast to string $string = Cast::toString(42); // "42" $string = Cast::toString(true); // "1" $string = Cast::toString(false); // "" } catch (CastException $e) { // Handle casting errors echo "Casting failed: " . $e->getMessage(); }
Using Individual Caster Classes
For more control or dependency injection scenarios, you can use the individual caster classes:
<?php use Casterly\Casters\BoolCaster; use Casterly\Casters\IntCaster; use Casterly\Casters\FloatCaster; use Casterly\Casters\StringCaster; $boolCaster = new BoolCaster(); $result = $boolCaster->cast($mixedValue); $intCaster = new IntCaster(); $result = $intCaster->cast($mixedValue); $floatCaster = new FloatCaster(); $result = $floatCaster->cast($mixedValue); $stringCaster = new StringCaster(); $result = $stringCaster->cast($mixedValue);
Creating Custom Casters
You can create your own casters by implementing the Castable interface:
<?php use Casterly\Castable; use Casterly\Exceptions\CastException; /** * @implements Castable<MyType> */ class MyTypeCaster implements Castable { public function cast(mixed $value): MyType { if (!$this->canCast($value)) { throw CastException::forValue($value, 'MyType'); } return new MyType($value); } private function canCast(mixed $value): bool { // Your validation logic here } }
API Reference
Cast Class
Static Methods
Cast::toBool(mixed $value): bool- Cast value to booleanCast::toInt(mixed $value): int- Cast value to integerCast::toFloat(mixed $value): float- Cast value to floatCast::toString(mixed $value): string- Cast value to string
All methods throw CastException when the value cannot be safely cast.
Caster Classes
BoolCaster- Casts to booleanIntCaster- Casts to integerFloatCaster- Casts to float (handles INF/NAN edge cases)StringCaster- Casts to string
Exceptions
CastException
Thrown when a value cannot be safely cast to the target type.
Methods:
CastException::forValue(mixed $value, string $targetType): self- Factory method that creates an exception with contextual error message
Safe Casting Rules
Casterly only performs "safe" casts on scalar values and null:
- ✅ Allowed:
string,int,float,bool,null - ❌ Rejected:
object,array,resource,callable
Boolean Casting
true,1,"1", non-empty strings →truefalse,0,"",null→false
Integer Casting
- Numeric strings, floats, booleans, null are cast using PHP's
(int)operator - Floats are truncated (not rounded)
Float Casting
- Numeric strings, integers, booleans, null are cast using PHP's
(float)operator - Special string values like
"inf","infinity","nan"are allowed - Invalid numeric strings that would result in unexpected INF/NAN are rejected
String Casting
- All scalar types and null are cast using PHP's
(string)operator truebecomes"1",falsebecomes""
PHPStan Integration
Casterly is designed to work seamlessly with PHPStan. The generic Castable<T> interface and specific return types ensure that PHPStan understands the result types:
<?php // PHPStan knows $result is bool $result = Cast::toBool($mixedValue); // PHPStan knows $number is int $number = Cast::toInt($userInput);
License
GPL-3.0-only
Contributing
Contributions are welcome! Please ensure all tests pass and follow the existing code style.
# Run tests composer test # Run PHPStan composer phpstan # Check code style composer cs-check