collab-corp/formatter

此包已被废弃,不再维护。未建议替代包。

PHP格式化实用程序包

v4.0.2 2022-04-15 04:26 UTC

README

Tests

StyleCI

一个用于使用laravel验证语法格式化数据/值的PHP包,由Illuminate\Support组件驱动。

安装

composer require collab-corp/formatter

使用

最基本的使用方法是简单的,只需传递你的值和你的值应该调用的调用者数组

use CollabCorp\Formatter\Support\ValueFormatter;

$formatter = new ValueFormatter("   uncle bob   ", ['trim', 'ucwords']);

$formatter->apply()->get(); // returns "Uncle Bob"

传递参数到调用者

您可以使用冒号后跟逗号分隔的列表指定参数e.g callable:arg1,arg2

function suffix_string($value, $suffix)
{
    return $value.$suffix;
}

$formatter = new ValueFormatter("  Foo  ", ['trim', 'suffix_string:Bar']);

$formatter->apply()->get(); // returns "FooBar"

注意:请注意,我们仅指定了suffix参数。《ValueFormatter》类会自动将您的值作为第一个参数传递给每个函数,除了委派给对象/实例(见下文使用实例部分)。

如果值不是我的函数的第一个参数怎么办?

没问题,您可以使用:value:占位符指定您希望值传递的顺序

例如,preg_replace接受一个值作为第三个参数进行格式化

// trim & replace all non numerics with "#"
$formatter = new ValueFormatter("   ABC123   ", [
    'trim',
    'preg_replace:/[^0-9]/,#,:value:'
]);

$formatter->apply()->get(); // returns "###123"

白名单允许的调用者

默认情况下,所有调用者都可以被调用,但如果您正在动态调用调用者或想添加一个保护层,可能值得指定应该允许哪些调用者函数

$formatter = new ValueFormatter("   uncle bob   ", ['trim', 'ucwords']);

$formatter->allowedCallables(["trim"]); //only trim is allowed

// throws  InvalidArgumentException:
// "Encountered non whitelisted function or non callable [ucwords]"
$formatter->apply()->get();

使用实例/对象值 & 方法链

可以将对象/实例传递给格式化器并利用该实例上的任何方法。使用.<methodName>约定,您可以指定该实例上的方法链。例如,考虑一个Carbon实例

$formatter = new ValueFormatter(new Carbon\Carbon('2020-05-24'), [
    '.addDays:1',
    '.format:m/d/Y'
]);

$formatter->apply()->get() // returns "05/25/2020"

闭包/可格式化类

您也可以使用闭包来格式化您的值

$formatter = new ValueFormatter("the value", [
    function($value){
        //do something to the value
        return $value;
    },
    ...
]);

或者,您还可以实现CollabCorp\Formatter\Support\Contracts\Formattable合约并使用实例

use CollabCorp\Formatter\Support\Contracts\Formattable;
use Closure;

class FormatValue implements Formattable
{
    /**
     * Format the value.
     *
     * @param  mixed $value
     * @param  Closure $exit
     * @return mixed
     */
    public function format($value, Closure $exit)
    {
        // quit formatting value(s)
        if($someCondition){
            $exit();
        }

        // or change the $value
        $value = "Changed"

        return $value;
    }
}


$formatter = new ValueFormatter("The value", [
    "trim"
    new FormatValue
    // or using class constant:
     FormatValue::class // formatter will new up the class.
]);

可选格式化/空白输入

有时您可能只想在值不是null或“空白”时格式化值:您可以在调用者链中的任何位置指定?以指定格式化器是否应退出调用者处理,通常这应该在所有调用者之前定义

$formatter = new ValueFormatter(null, [
    "?", //tells the class not to process callables if value is blank
    'to_carbon',
    '.addDays:1',
    '.format:m/d/Y'
]);

$formatter->apply()->get(); // returns original null value

注意:此包使用Laravel的blank辅助函数来确定空白/空值。如果您有更复杂的逻辑来退出规则,请使用闭包或Formattable类并调用第二个参数exit回调

$formatter = new ValueFormatter(null, [
    function($value, $exit){
        if($quitProcessing){
            $exit(); // tells formatter to quit processing.
        }
    },
    'to_carbon',
    '.addDays:1',
    '.format:m/d/Y'
]);

格式化多个值

到目前为止,所有示例都使用单个值,但很多时候我们处理的是来自客户端请求的大量数据。这就是为什么我们更喜欢使用 DataFormatter 类。

use CollabCorp\Formatter\DataFormatter;

$data = [
  'first_name'=>'    jim    ',
  'last_name'=>'   thompson',
  'phone_number'=>'123-456-7890',
  'date_of_birth'=>"1991-05-01",
  ...
];

$callables = [
    'first_name'=>'trim|ucfirst',
    'last_name'=>'trim|ucfirst',
    'phone_number'=>'preg_replace:/[^0-9]/,,:value:',
    'date_of_birth'=>'?|to_carbon|.format:m/d/y',
    ...
];

$formatter = new DataFormatter($data, $callables);

$formatter->apply()->get(); //returns formatted data

数组输入

您也可以使用点符号格式化数组数据。

$data = [
  'contact_info'=>[
    'first_name'=>'    jim    ',
    'last_name'=>'   thompson',
    'phone_number'=>'123-456-7890',
    'address'=>'123 some lane.'
  ]
];

$callables = [
    'contact_info.first_name'=>'trim|ucwords',
    'contact_info.last_name'=>'trim|ucwords',
    'contact_info.phone_number'=>'preg_replace:/[^0-9]/,,:value:',
    'contact_info.address'=>[function ($address) {
      return 'Address Is: '.$address;
    }],
];
$formatter = new DataFormatter($data, $callables);

$formatter->apply()->get();

通配符格式化

可调用对象也可以包含通配符。

$data = [
    'first_name'=>'    jim    ',
    'last_name'=>'   thompson',
    ...
];
$callables = [
    //apply to all keys that contain "name"
    '*name*'=>'trim|ucwords',
];

$formatter = new DataFormatter($data, $callables);

$formatter->apply()->get();

这包括数组输入。

$callables = [
    'contact_info.*name*'=>'trim|ucwords',
    // 'contact_info.*name'=>'trim|ucwords',
    // 'contact_info.name*'=>'trim|ucwords',
];

$formatter = new DataFormatter($data, $callables);

$formatter->apply()->get();

注意事项

如果您更喜欢使用特质轻松创建格式化实例,我们提供了 CollabCorp\Formatter\Support\Concerns\FormatsData 特质以方便访问。

<?php

use CollabCorp\Formatter\Support\Concerns\FormatsData;

class SomeClass
{

    use FormatsData;

    public function someFunction()
    {
        //returns ValueFormatter
        $this->formatValue("...", [...])->apply()->get();
        //returns DataFormatter
        $this->formatData([...], [...])->apply()->get();
    }
}

贡献

以下方式下,贡献总是受欢迎的

  • 问题跟踪器
  • 拉取请求
  • Collab Corp Discord(如有需求,将发送邀请)

许可证

该项目采用 MIT 许可证。