jn-jairo/laravel-cast

Laravel类型转换器。

v2.0.1 2024-03-14 23:41 UTC

This package is auto-updated.

Last update: 2024-09-15 00:36:56 UTC


README

Total Downloads Latest Stable Version License

Laravel类型转换器

此包为Laravel提供类型转换功能。

版本兼容性

安装

您可以通过composer安装此包

composer require jn-jairo/laravel-cast

CastServiceProvider将自动为您注册。

用法

提供了契约 \JnJairo\Laravel\Cast\Contracts\Cast外观 \JnJairo\Laravel\Cast\Facades\Cast

有三个方法:Cast::cast()Cast::castDb()Cast::castJson()

  • Cast::cast() 转换为PHP类型
  • Cast::castDb() 转换为数据库类型
  • Cast::castJson() 转换为JSON类型

所有方法接受三个参数:mixed $valuestring $type 和可选的 string $format

示例

print_r(Cast::cast('{"foo":"bar"}', 'array'));
/*
Array
(
    [foo] => bar
)
*/

print_r(Cast::castDb(1234.555, 'decimal', '10:2'));
// 1234.56

print_r(Cast::castDb(['foo' => 'bar'], 'json'));
// {"foo":"bar"}

print_r(Cast::castJson(new DateTime('01 jan 2000'), 'date'));
// 2000-01-01

支持的类型

  • intinteger
  • floatrealdouble
  • decimal
  • boolboolean
  • date
  • datetime
  • timestamp
  • json
  • array
  • object
  • collection
  • stringtext
  • uuid
  • encrypted
  • compressed
  • base64
  • pipe
  • enum

格式参数

  • decimal - precision:places,(up|down|ceiling|floor|half_up|half_down|half_even|half_odd|truncate)。示例:10:2,half_up10:22half_up。默认:28:2,half_up。decimal类型使用https://php-decimal.io扩展,要使用此类型,请运行composer require php-decimal/php-decimal:^1.1并安装decimal扩展。
  • date - 示例:Y-m-d。默认:Y-m-d
  • datetimetimestamp - 示例:Y-m-d H:i:s。默认:Y-m-d H:i:s
  • uuid - (uuid1|uuid4|ordered)。示例:uuid1。默认:uuid4。空字符串值将返回新的UUID。要使用有序UUID格式,请运行composer require moontoast/math:^1.1
  • encrypted - (one|all),base64:key,cipher。空密钥和加密算法使用laravel配置app.keyapp.cipher。示例:base64:N38XBrdzg505959nDEqefo6fNpeTmGy0wTBHRSxrpcQ=,aes-256-cbc。默认:one
    • one - 允许双重加密,只解密一次。
    • all - 防止双重加密,递归解密所有加密。
$decrypted = Cast::cast($encrypted, 'encrypted');
$encrypted = Cast::castDb($decrypted, 'encrypted');
$decrypted = Cast::castJson($encrypted, 'encrypted');
  • compressed - (always|smaller),(one|all),level,(raw|deflate|gzip)。示例:smaller,all,9,gzip。默认:always,one,-1,raw
    • always - 总是使用压缩结果,即使结果大于原始值。
    • smaller - 只有当结果小于原始值时才使用压缩结果。
    • one - 允许双重压缩,只解压一次。
    • all - 防止双重压缩,递归解压所有压缩。
    • level - 压缩级别,从0(无压缩)到9(最大压缩)。如果使用-1,则使用zlib库的默认压缩。
    • raw - 使用编码ZLIB_ENCODING_RAWgzdeflate以及gzinflate
    • deflate - 使用编码ZLIB_ENCODING_DEFLATEgzcompress以及gzuncompress
    • gzip - 使用编码ZLIB_ENCODING_GZIPgzencode以及gzdecode
$decompressed = Cast::cast($compressed, 'compressed');
$compressed = Cast::castDb($decompressed, 'compressed');
$decompressed = Cast::castJson($compressed, 'compressed');
  • base64 - (one|all),prefix。示例:base64:。默认:one
    • one - 允许双重编码,只解码一次。
    • all - 防止双重编码,递归解码所有编码(需要前缀)。
$decoded = Cast::cast('base64:Rm9vQmFy', 'base64', 'base64:'); // FooBar
$encoded = Cast::castDb('FooBar', 'base64', 'base64:'); // base64:Rm9vQmFy
$decoded = Cast::castJson('base64:Rm9vQmFy', 'base64', 'base64:'); // FooBar
  • 管道 - |类型:格式|类型:格式|...|方向。示例:|加密|压缩|数组|。默认:||php:>,db:<,json:>
    • 方向格式为 >|<|php:(>|<),db:(>|<),json:(>|<)> 从左到右,< 从右到左。
    • 第一个字符用作类型分隔符,其他分隔符如果与类型分隔符冲突,则使用 | 分隔符。
    • 有效参数的示例
      |加密|数组|
      |加密|数组|<
      |加密|数组|>,db:<
      |加密|decimal:2|php:>,db:<,json:>
      ,encrypted,decimal:2,php:>|db:<|json:>
      :encrypted:decimal|2:php|>,db|<,json|>
$array = Cast::cast('q1ZKy89XslJKSixSqgUA', 'pipe', '|base64|compressed|array|'); // ['foo' => 'bar']
$base64Compressed = Cast::castDb(['foo' => 'bar'], 'pipe', '|base64|compressed|array|'); // q1ZKy89XslJKSixSqgUA
$array = Cast::castJson('q1ZKy89XslJKSixSqgUA', 'pipe', '|base64|compressed|array|'); // ['foo' => 'bar']
  • 枚举 - 示例:MyEnum::class。默认:
enum MyEnum : int
{
    case foo = 1;
    case bar = 2;
}

Cast::cast(1, 'enum', MyEnum::class); // MyEnum::foo
Cast::castDb(MyEnum::foo, 'enum', MyEnum::class); // 1
Cast::castJson(MyEnum::foo, 'enum', MyEnum::class); // 1

它可以是一个 \Illuminate\Contracts\Support\Arrayable\Illuminate\Contracts\Support\Jsonable 的实例。

use Illuminate\Contracts\Support\Arrayable;

enum MyEnum : string implements Arrayable
{
    case foo = 1;
    case bar = 2;

    public function description() : string
    {
        return match ($this) {
            self::foo => 'foo description',
            self::bar => 'bar description',
        };
    }

    public function toArray()
    {
        return [
            'name' => $this->name,
            'value' => $this->value,
            'description' => $this->description(),
        ];
    }
}

Cast::cast(1, 'enum', MyEnum::class); // MyEnum::foo
Cast::castDb(MyEnum::foo, 'enum', MyEnum::class); // 1
Cast::castJson(MyEnum::foo, 'enum', MyEnum::class);
// [
//      'name' => 'foo',
//      'value' => 1,
//      'description' => 'foo description'
// ]

自定义类型

要创建自定义类型,只需实现合约 \JnJairo\Laravel\Cast\Contracts\Type

class CustomType implements \JnJairo\Laravel\Cast\Contracts\Type
{
    // ...
}

或扩展抽象类 \JnJairo\Laravel\Cast\Types\Type

class CustomType extends \JnJairo\Laravel\Cast\Types\Type
{
    // ...
}

将配置发布到 config/cast.php

php artisan vendor:publish --provider=JnJairo\\Laravel\\Cast\\CastServiceProvider

在配置中设置新类型。

// config/cast.php

return [
    'types' => [
        'custom_type' => CustomType::class,
    ],
];

自定义类型将可用。

Cast::cast('foo', 'custom_type');

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅许可证文件