babenkoivan/fluent-array

该包为数组管理提供流畅的接口

v1.0.0 2018-12-08 11:51 UTC

This package is auto-updated.

Last update: 2024-09-16 03:56:44 UTC


README

Packagist Packagist Build Status license Donate

简介

流畅数组库为您提供了便捷的可链式接口。如果您喜欢面向对象语法或者只是想要更易读的数组声明,流畅数组将为您提供帮助。

基本用法

$order = (new FluentArray())
    ->user()
        ->id(1)
        ->name('John')
    ->end()
    ->coupon('SALE10')
    ->status('delivered')
    ->products()
        ->push()
            ->id(1)
            ->name('iPhone X')
            ->price(1200)
        ->end()
        ->push()
            ->id(2)
            ->name('Beats By Dre Studio3')
            ->price(360)
        ->end()
    ->end();

如果我们通过调用 $order->toArray() 将流畅数组转换为关联数组,我们将得到以下输出

[
    'user' => [
        'id' => 1,
        'name' => 'John'
    ],
    'coupon' => 'SALE10',
    'status' => 'delivered',
    'products' => [
        [
            'id' => 1,
            'name' => 'iPhone X',
            'price' => 1200
        ],
        [
            'id' => 2,
            'name' => 'Beats By Dre Studio3'
            'price' => 360
        ]
    ]
]

存储数组

每次您调用 setget,或任何其他修改或检索状态的方法时,您都在更新流畅数组的内部存储。

$fluentArray = new FluentArray();

// we set the key `one` and the corresponding value `1` in the storage 
$fluentArray->set('one', 1);
    
// we get the value, that corresponds the key `one` from the storage
$fluentArray->get('one');

安装

使用 composer 安装库

composer require babenkoivan/fluent-array

配置

该配置允许您更改流畅数组的 行为 并添加 新功能

局部作用域

要配置特定的流畅数组实例,请使用局部作用域。

$config = (clone FluentArray::globalConfig())
    ->namingStrategy(new CamelCaseStrategy());

$fluentArray = (new FluentArray($config))
    ->one(1)
    ->two(2);

// alternatively you can set configuration, using the `config` method
$fluentArray = (new FluentArray())
    ->config($config)
    ->one(1)
    ->two(2);

$fluentArray->all();
// ['One' => 1, 'Two' => 2]

全局作用域

要配置所有流畅数组,请使用全局作用域。

$globalConfig = FluentArray::globalConfig();

$globalConfig->namingStrategy(new CamelCaseStrategy());

$fluentArray = (new FluentArray())
    ->one(1)
    ->two(2);
    
$fluentArray->all();
// ['One' => 1, 'Two' => 2]    

您可以使用宏来扩展流畅数组的函数。这可以通过在 全局局部 作用域中进行配置来完成。

$globalConfig = FluentArray::globalConfig();

$globalConfig
    ->macros()
        ->format(function (string $key, int $decimals = 0) {
            $value = $this->get($key);
        
            if (is_numeric($value)) {
                return number_format($value, $decimals);
            } else {
                return $value;
            }
        })
    ->end();
    
$fluentArray = (new FluentArray())
    ->set('one', 10.567)
    ->set('two', 2.89);
    
$fluentArray->format('one', 2);
// 10.57

$fluentArray->format('two', 1);
// 2.9    

命名策略

命名策略描述了动态方法中的键转换。

例如,我们希望所有键在 存储数组 中都以下划线命名。

$config = (clone FluentArray::globalConfig())
    ->namingStrategy(new UnderscoreStrategy());

$fluentArray = (new FluentArray($config))
    ->firstValue(1)
    ->secondValue(2);

$fluentArray->all();
// ['first_value' => 1, 'second_value' => 2]

现在我们希望它们采用驼峰命名法。

$config = (clone FluentArray::globalConfig())
    ->namingStrategy(new CamelCaseStrategy());

$fluentArray = (new FluentArray($config))
    ->firstValue(1)
    ->secondValue(2);

$fluentArray->all();
// ['first_value' => 1, 'second_value' => 2]

支持以下命名策略

默认命名策略是 UnderscoreStrategy

固定方法

all

all 方法返回 存储数组

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->all();    
// ['one' => 1, 'two' => 2]

clean

clean 方法从 存储数组 中删除所有键和值。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);

$fluentArray->all();    
// ['one' => 1, 'two' => 2]

$fluentArray->clean()->all();    
// []    

config

config 方法允许您设置或检索 局部配置

$config = (new FluentArray())
    ->set('naming_strategy', new NullStrategy());
    
$fluentArray = (new FluentArray())
    ->config($config);
    
$fluentArray->config()->get('naming_strategy');
// instance of NullStrategy       

count

count 方法返回 存储数组 中的值数量。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2)
    ->set('three', 3);

$fluentArray->count();
// 3

each

each 方法遍历 存储数组 中的值。

$odds = [];

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2)
    ->set('three', 3)
    ->set('four', 4);

$fluentArray->each(function ($value, $key) use (&$odds) {
    if ($value % 2 !== 0) {
        $odds[] = $value;
    }
});

$odds;
// [1, 3]

要停止迭代,从回调函数返回 false

$counter = 0;

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2)
    ->set('three', 3);

$fluentArray->each(function ($value, $key) use (&$counter) {
    if ($value > 1) {
        return false;
    }
    
    $counter++;
});

$counter;
// 1

filter

filter方法通过给定的回调函数过滤存储数组。在回调函数中返回false以移除值。

$sourceFluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$filteredFluentArray = $sourceFluentArray->filter(function ($value, $key) {
    return $value > 1;
});

$filteredFluentArray->all();
// ['two' => 2]    

如果没有指定回调函数,所有可以转换为false的值都将被移除。

$fluentArray = (new FluentArray())
    ->set('zero', 0)
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->filter()->all();
// ['one' => 1, 'two' => 2]    

first

first方法从存储数组中检索第一个值。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->first();
// 1        

fromArray

fromArray方法将数组转换为流数组。

$array = ['one' => 1, 'two' => 2];

$fluentArray = FluentArray::fromArray($array);

$fluentArray->all();
// ['one' => 1, 'two' => 2]

fromJson

fromJson方法将JSON转换为流数组。

$json = '{"one":1,"two":2}';

$fluentArray = FluentArray::fromJson($json);

$fluentArray->all();
// ['one' => 1, 'two' => 2]

get

get方法从存储数组中检索与给定键相对应的值。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->get('two');
// 2    

globalConfig

globalConfig方法允许您设置或检索全局配置

$globalConfig = (new FluentArray())
    ->set('naming_strategy', new NullStrategy());
   
FluentArray::globalConfig($globalConfig);

FluentArray::globalConfig()->get('naming_strategy');
// instance of NullStrategy       

has

has方法检查给定的键是否存在于存储数组中。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->has('one');
// true

$fluentArray->has('three');
// false    

keys

keys方法从存储数组中检索所有键。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->keys();
// ['one', 'two'] 

krsort

krsort方法按键的降序对存储数组进行排序。您可以将排序标志作为第一个参数指定。

$fluentArray = (new FluentArray())
    ->set('b', 1)
    ->set('a', 2)
    ->set('c', 3);
    
$fluentArray->krsort(SORT_STRING)->all();
// ['c' => 3, 'b' => 1, 'a' => 2] 

ksort

ksort方法按键的升序对存储数组进行排序。您可以将排序标志作为第一个参数指定。

$fluentArray = (new FluentArray())
    ->set('b', 1)
    ->set('a', 2)
    ->set('c', 3);
    
$fluentArray->ksort(SORT_STRING)->all();
// ['a' => 2, 'b' => 1, 'c' => 3] 

last

last方法从存储数组中检索最后一个值。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->last();
// 2        

map

map方法将给定的回调函数应用于存储数组中的所有值,并返回一个新的流数组。

$sourceFluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);

$resultFluentArray = $sourceFluentArray->map(function ($value, $key) {
    return $value * 10;
});

$resultFluentArray->all();
// ['one' => 10, 'two' => 20]

pluck

pluck方法从子流数组中提取具有给定键的值,到一个新的流数组。

$fluentArray = (new FluentArray())
    ->set('one', (new FluentArray())->set('id', 1))
    ->set('two', (new FluentArray())->set('id', 2));
    
$fluentArray->pluck('id')->all();
// [1, 2]   

push

push方法将给定的值追加到存储数组中。

$fluentArray = (new FluentArray())
    ->push(1)
    ->push(2);
    
$fluentArray->all();
// [1, 2]    

push方法的另一种使用方法

$fluentArray = (new FluentArray())
    ->push()
        ->one(1)
        ->two(2)
    ->end()
    ->push()
        ->three(3)
    ->end();
    
$fluentArray->toArray();
// [['one' => 1, 'two' => 2], ['three' => 3]]    

pushWhen

pushWhen方法如果第一个参数等同于true,则将给定的值追加到存储数组中。

$fluentArray = (new FluentArray())
    ->pushWhen(true, 1)
    ->pushWhen(false, 2)
    ->pushWhen(function () { return true; }, 3);
    
$fluentArray->all();
// [1, 3]    

pushWhen方法的另一种使用方法

$fluentArray = (new FluentArray())
    ->pushWhen(true)
        ->one(1)
    ->end(false)
    ->pushWhen(false)
        ->two(2)
    ->end()
    ->pushWhen(function () { return true; })
        ->three(3)
    ->end();
    
$fluentArray->toArray();
// [['one' => 1], ['three' => 3]]    

rsort

rsort方法按降序对存储数组进行排序。您可以将排序标志作为第一个参数指定。

$fluentArray = (new FluentArray())
    ->set('three', 3)
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->rsort(SORT_NUMERIC)->all();
// ['three' => 3, 'two' => 2, 'one' => 1]    

set

set方法在存储数组中设置给定的键和值。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->all();
// ['one' => 1, 'two' => 2]    

setWhen

setWhen方法如果第一个参数等同于true,则在存储数组中设置给定的键和值。

$fluentArray = (new FluentArray())
    ->setWhen(true, 'one', 1)
    ->setWhen(false, 'two', 2)
    ->setWhen(function () { return true; }, 'three', 3);
    
$fluentArray->all();
// ['one' => 1, 'three' => 3]    

sort

sort方法按升序对存储数组进行排序。您可以将排序标志作为第一个参数指定。

$fluentArray = (new FluentArray())
    ->set('three', 3)
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->sort(SORT_NUMERIC)->all();
// ['one' => 1, 'two' => 2, 'three' => 3]    

toArray

toArray方法将流数组转换为数组。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);

$fluentArray->toArray();
// ['one' => 1, 'two' => 2]

toJson

toJson方法将流数组转换为JSON。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);

$fluentArray->toJson();
// "{"one":1,"two":2}"

unset

unset方法通过给定的键从存储数组中删除值。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->unset('one')->all();
// ['two' => 2]    

usort

usort方法使用给定的比较函数对存储数组进行排序。

$fluentArray = (new FluentArray())
    ->set('three', 3)
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->usort(function ($a, $b) {
    return $a <=> $b;
});    
    
$fluentArray->all();
// ['one' => 1, 'two' => 2, 'three' => 3]    

values

values方法从存储数组中检索所有值。

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$fluentArray->all();
// [1, 2]    

when

when方法执行给定的回调函数时,如果第一个参数等于true

$fluentArray = new FluentArray();

$fluentArray->when(true, function () use ($fluentArray) {
    $fluentArray->set('one', 1);
});

$fluentArray->when(false, function () use ($fluentArray) {
    $fluentArray->set('two', 2);
});

$fluentArray->when(
    function () {
        return true;
    }, 
    function () use ($fluentArray) {
        $fluentArray->set('three', 3);
    }
);

$fluentArray->all();
// ['one' => 1, 'three' => 3]

您可以指定一个默认的回调函数,如果第一个参数等于false,则执行该回调函数。

$fluentArray = new FluentArray();

$fluentArray->when(
    false, 
    function () use ($fluentArray) {
        $fluentArray->set('one', 1);
    },
    function () use ($fluentArray) {
        $fluentArray->set('two', 2);
    }
);

$fluentArray->all();
// ['two' => 2]

动态方法

动态设置器

您还可以使用动态设置器在存储数组中设置键值对。

$fluentArray = (new FluentArray())
    ->one(1)
    ->two(2);
    
$fluentArray->all();
// ['one' => 1, 'two' => 2]    

如果您想设置一个保留给方法名的键,您可以对其进行转义。

$fluentArray = (new FluentArray())
    ->{'\set'}(1)
    ->{'\get'}(2);
    
$fluentArray->all();
// ['set' => 1, 'get' => 2]    

添加When来设置给定的值,如果第一个参数等于true

$fluentArray = (new FluentArray())
    ->oneWhen(true, 1)
    ->twoWhen(false, 2)
    ->threeWhen(function () { return true; }, 3);
    
$fluentArray->all();
// ['one' => 1, 'three' => 3]    

您还可以链式创建子流畅数组。

$fluentArray = (new FluentArray())
    ->one()
        ->two(3)
    ->end()
    ->three()
        ->four(4)
        ->five(5)
    ->end();
    
$fluentArray->toArray();
// ['one' => ['two' => 2], 'three' => ['four' => 4, 'five' => 5]]    

动态获取器

要从存储数组中检索值,您可以使用动态获取器。

$fluentArray = (new FluentArray())
    ->one(1)
    ->two(2);
    
$fluentArray->two();
// 2    

动态存在

要检查存储数组中是否存在键,您可以使用动态has方法。

$fluentArray = (new FluentArray())
    ->one(1)
    ->two(2);
    
$fluentArray->hasOne();
// true

$fluentArray->hasThree();
// false    

动态提取

要从子流畅数组中提取值,您可以使用动态pluck方法。

$fluentArray = (new FluentArray())
    ->one()
        ->id(1)
    ->end()
    ->two()
        ->id(2)
    ->end();
    
$fluentArray->pluckId()->all();
// [1, 2]   

动态删除

要从存储数组中删除值,您可以使用动态unset方法。

$fluentArray = (new FluentArray())
    ->one(1)
    ->two(2);
    
$fluentArray->unsetOne()->all();
// ['two' => 2]    

实现接口

可计数

Countable接口提供了count方法的支持。更多信息请参阅这里

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
count($fluentArray);
// 2

可序列化

Serializable接口提供了序列化支持。更多信息请参阅这里

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
$serialized = serialize($fluentArray);
$unserialized = unserialize($serialized);

$unserialized->all();
// ['one' => 1, 'two' => 2]    

数组访问

ArrayAccess接口提供了数组访问。更多信息请参阅这里

$fluentArray = new FluentArray();

$fluentArray['one'] = 1;
$fluentArray['two'] = 2;

$fluentArray['two'];
// 2

迭代聚合

IteratorAggregate接口使您能够遍历存储数组更多信息请参阅这里

$fluentArray = (new FluentArray())
    ->set('one', 1)
    ->set('two', 2);
    
foreach ($fluentArray as $key => $value) {
    $fluentArray->set($key, $value * 10);
}    

$fluentArray->all();
// ['one' => 10, 'two' => 20]

代码格式化

如果您使用PhpStorm并且开启代码自动格式化,您可能会遇到以下代码

$fluentArray = (new FluentArray())
    ->one()
        ->id(1)
    ->end()
    ->two()
        ->id(2)
    ->end();

将被PhpStorm转换成

$fluentArray = (new FluentArray())
    ->one()
    ->id(1)
    ->end()
    ->two()
    ->id(2)
    ->end();

现在代码的可读性降低,但幸运的是我们可以配置PhpStorm来禁用指定代码块的自动格式化。要这样做,请打开PhpStorm首选项,转到Editor > Code Style部分并选择选项Enable formatter markers in comments

现在您可以关闭代码格式化,针对您代码的特定部分

// @formatter:off
$fluentArray = (new FluentArray())
    ->one()
        ->id(1)
    ->end()
    ->two()
        ->id(2)
    ->end();
// @formatter:on