Skip to content

anothanj/casterly

Repository files navigation

Casterly

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 boolean
  • Cast::toInt(mixed $value): int - Cast value to integer
  • Cast::toFloat(mixed $value): float - Cast value to float
  • Cast::toString(mixed $value): string - Cast value to string

All methods throw CastException when the value cannot be safely cast.

Caster Classes

  • BoolCaster - Casts to boolean
  • IntCaster - Casts to integer
  • FloatCaster - 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 → true
  • false, 0, "", nullfalse

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
  • true becomes "1", false becomes ""

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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages