定制 anothanj/casterly 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

anothanj/casterly

Composer 安装命令:

composer require anothanj/casterly

包简介

A PHP library for type casting.

README 文档

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 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

统计信息

  • 总下载量: 174
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: GPL-3.0-only
  • 更新时间: 2026-01-22

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固