jasny/typecast

此包已被废弃且不再维护。作者建议使用improved/type包代替。

基本逻辑的类型转换

v2.1.1 2016-12-08 14:34 UTC

This package is auto-updated.

Last update: 2024-08-29 21:15:14 UTC


README

Build Status Code Coverage Scrutinizer Code Quality SensioLabsInsight

此库在PHP中执行类型转换。

PHP原生支持类型转换。此库在转换过程中添加了一些基本逻辑,例如将字符串如"FOO"转换为整数时触发警告。

与PHP内部类型转换不同,将null转换为任何类型都始终返回null

安装

Jasny TypeCast包可在packagist上找到。使用composer安装它

composer require jasny/typecast

使用

use Jasny\TypeCast;

$typecast = new TypeCast();

$typecast->to('string')->cast(null); // null

$typecast->to('integer')->cast('987'); // 987
$typecast->to(DateTime::class)->cast('2015-01-01'); // new DateTime('2015-01-01)
$typecast->to(FooBar::class)->cast($data); // FooBar::__set_state($data)

// Unable to cast
$typecast->to('float')->cast('red'); // 'red' + triggers a notice
$typecast->to('int')->cast(new stdClass()); // stdClass object + triggers a notice

别名

在需要将值转换为接口或抽象类或想要将值转换为子类的情况下,您可以设置别名。

$typecast = new TypeCast();
$typecast->alias(FooBarInterface::class, FooBar::class);

$typecast->to(FooBarInterface::class)->cast($data); // FooBar::__set_state($data)

错误

默认情况下,如果无法将值转换为所需类型,则触发E_NOTICE。与PHP相比,Jasny\TypeCast对类型转换的值遵循更严格的规则。

除了通知外,还可以触发任何严重程度的错误。或者,可以抛出任何Throwable,如异常或错误。

$typecast = new TypeCast();

$typecast->failWith(E_USER_WARNING);
$typecast->failWith(TypeError::class);
$typecast->failWith(UnexpectedValueException::class);

错误中的变量名

您可以使用setName()方法设置被转换的属性或变量名。此名称将包含在触发类型转换时引发的任何错误中。这有助于确定问题。

$foo = 'red';
$typecast->value($foo)->setName('foo')->to('float');

依赖注入

如果您的应用程序支持通过容器进行依赖注入,请创建一个新的TypeCast对象并将其作为服务添加到容器中。

value()方法将克隆TypeCast对象。设置如别名或自定义处理程序等将传播。

use Jasny\TypeCast;
use Jasny\TypeCastInterface;

$container = new Container([
  TypeCastInterface::class => function() {
    $typecast = new TypeCast();
    $typecast->alias(FooBarInterface::class, FooBar::class);
    
    return $typecast;
  }
]);

$container->get(TypeCastInterface::class)->value('987')->to('integer');

假设Container是任何PSR-11兼容的容器

处理程序

Typecast对象使用处理程序来转换值。每个处理程序可以将值转换为特定类型。以下定义了以下处理程序

  • 数组(包括类型数组如string[]DateTime[]
  • 布尔值
  • 浮点数
  • 整数
  • 数字(int|float
  • 混合类型
  • 对象(包括转换为特定类)
  • 资源
  • 字符串
  • 多重类型(例如int|stringstring|string[]

您可以在创建TypeCast对象时覆盖处理程序。

愿望

desire方法将返回处理程序。这是使用value方法的替代方法。如果您需要将多个值转换为相同类型,则建议使用desire一次性获取处理程序。

use Jasny\TypeCast;

$typecast = new TypeCast();
$typecast->desire('integer')->cast('10');

$arrayHandler = $typecast->desire('array'); 
foreach ($items as &$item) {
  $item = $arrayHandler->cast($item);
}

多重处理程序

在转换多个类型时,处理程序将尝试猜测值应该转换为哪种类型。这可能会影响性能。您可以使用NoTypeGuess让处理程序在无法确定类型时引发错误。

use Jasny\TypeCast;

$multipleHandler = new TypeCast\Handlers\MultipleHandler(new TypeCast\NoTypeGuess()); 
$typecast = new TypeCast(null, ['multiple' => $multipleHandler] + TypeCast::getDefaultHandlers());