apantle/hashmapper

简单的有序哈希表对象转换器(关联数组的array_map)

1.3.2 2020-08-01 03:05 UTC

README

Build Status Maintainability Test Coverage

目标

这是一个简约的库,旨在重用哈希表映射逻辑,例如:消费API结果传递给Twig视图。

通过简单的源到目标键的键字典,轻松实现过滤/重命名不需要的键。通过回调支持任何转换,并传递另一个可调用对象或另一个HashMapper实例,以便进行复杂关联数组的转换,也就是哈希表。

use function Apantle\HashMapper\hashMapper;

$target = hashMapper($specs, $options)($source);

安装

您可以通过composer安装此包

composer require apantle/hashmapper

简单键映射

更改输入中的一个键,只输出目标中的该键。

回调键映射

对于某些复杂的转换,您可以使用一个函数,该函数将接收以下参数

  • 在源哈希表中指定键的值
  • 整个哈希表(如果您需要其他值)
assert(hashMapper([
    'place' => 'Caso CIDH',
    'date' => [
        'fecha',
        function($date, $source) {
            extract($date);
            $date = date_create_from_format('Y/m/d', "{$year}/{$month}/{$day}");
            return $date->format('Y-m-d');
        }
    ],
])([
    'date' => [
        'year' => 2006,
        'month' => 5,
        'day' => 4,
    ],
    'place' => 'San Salvador Atenco',
]) === [
    'Caso CIDH' => 'San Salvador Atenco',
    'fecha' => '2006-05-04'
]);

使用另一个HashMapper

如果您有一个复杂的子键,不容易用简单的函数映射,可以使用另一个具有该子键规范的HashMapper,作为该键的映射器。

assert(hashMapper([
    'sourceKey' => hashMapper([ 'value' => 'legend' ])
])([
    'sourceKey' => [
        'value' => 'to pass to HashMapper',
        'ignored' => 'it should not appear'
    ],
]) === [
    'sourceKey => [
        'legend' => 'to pass to HashMapper'
    ]
]);

使用可调用对象的展开运算符映射

如果您想将源中的具有子键的键复制到目标上(即展开它),可以传递一个包含字符串'...'作为目标键和您的选择可调用对象的元组。

assert(hashMapper([
    'wp:term' => ['...', 'Apantle\FunPHP\identity']
])([
    'wp:term' => [
         'id' => 31925,
         'link' => 'http://example.com/category/test-term/',
         'name' => 'Test term',
         'slug' => 'test-term',
         'taxonomy' => 'category',
    ],
    'ignored' => 'right'
]) === [
     'id' => 31925,
     'link' => 'http://example.com/category/test-term/',
     'name' => 'Test term',
     'slug' => 'test-term',
     'taxonomy' => 'category',
]);

隐式展开(不指定'...'键)

如果您需要将顶层键内的所有字典展开到目标中,而不是将映射规范作为元组编写,您可以只提供一个可调用对象,在Mapper算子构造函数中指定选项implicitSpread => true

assert(hashMaper(
    [
        'wp:term' => compose('Apantle\FunPHP\head', 'Apantle\FunPHP\identity'),
    ],
    [
        'implicitSpread' => true
    ]
)([
    'wp:term' => [
        [
            'id' => 31925,
            'link' => 'http://example.com/category/test-term/',
            'name' => 'Test term',
            'slug' => 'test-term',
            'taxonomy' => 'category',
        ]
    ],
]) === [
    'id' => 31925,
    'link' => 'http://example.com/category/test-term/',
    'name' => 'Test term',
    'slug' => 'test-term',
    'taxonomy' => 'category',
]);

将HashMapper作为算子对象调用

现在通过__invoke魔法提供了一种更简单的方法来使用它映射关联数组的集合,就像array_maparray_reduceCollection::map(来自Illuminate\Support)。

重用HashMapper转换关联数组数组

您可以使用我们自己的辅助函数来应用相同的转换集到每个传递的数组上,而不是使用HashMapper作为array_mapCollection::map的函数。

$collectionTransformed = collection(hashMapper($specs))($arrayOfAssociativeArrays);

有关更多示例,请参阅问题:1