code-distortion/laravel-collection-macros

一组有用的 Laravel 集合宏 - 一个 spatie/laravel-collection-macros 分支

7.0.3 2020-09-08 18:54 UTC

README

Latest Version on Packagist PHP from Packagist Laravel GitHub Workflow Status

此包是 spatie/laravel-collection-macros 的分支。它包含原始宏的子集以及一些额外的宏。

此包旨在供个人使用。如果您想提交 PR 或请求功能,请参阅原始的 Spatie 包。

安装

使用 composer 安装此包

composer require code-distortion/laravel-collection-macros

该包将自动注册自己。

从原始 spatie 包保留的宏

新增宏

catch

Try

extract

从集合中提取键。这与 only 非常相似,有两个主要区别

  • extract 返回一个值数组,而不是关联数组
  • 如果不存在值,则用 null 填充值而不是省略它

extract 在使用 PHP 7.1 短 list() 语法时非常有用。

[$name, $role] = collect($user)->extract('name', 'role.name');

glob

返回一个包含 glob() 结果的集合。

Collection::glob('config/*.php');

ifAny

如果集合不为空,则执行传入的可调用参数。将返回整个集合。

collect()->ifAny(function(Collection $collection) { // empty collection so this won't get called
   echo 'Hello';
});

collect([1, 2, 3])->ifAny(function(Collection $collection) { // non-empty collection so this will get called
   echo 'Hello';
});

ifEmpty

如果集合为空,则执行传入的可调用参数。将返回整个集合。

collect()->ifEmpty(function(Collection $collection) { // empty collection so this will called
   echo 'Hello';
});

collect([1, 2, 3])->ifEmpty(function(Collection $collection) { // non-empty collection so this won't get called
   echo 'Hello';
});

keepValues

返回包含给定列表中值的集合。

collect(['foo', 'bar'])->keepValues(['foo'])->toArray(); // ['foo']

keepValues 接受第二个参数以启用严格比较(默认 false)。

collect(['123', 456])->keepValues(['123', '456'], true)->toArray(); // ['123']

keyedKeys

返回值与键相同的集合。

collect(['foo' => 1, 'bar' => 2])->keyedKeys()->toArray(); // ['foo' => 'foo', 'bar' => 'bar']

none

检查集合是否不包含给定项目、键值对或通过真值测试的任何给定项。该函数接受与 contains 集合方法相同的参数。

collect(['foo'])->none('bar'); // returns true
collect(['foo'])->none('foo'); // returns false

collect([['name' => 'foo']])->none('name', 'bar'); // returns true
collect([['name' => 'foo']])->none('name', 'foo'); // returns false

collect(['name' => 'foo'])->none(function ($key, $value) {
   return $key === 'name' && $value === 'bar';
}); // returns true

paginate

为集合中的项创建 LengthAwarePaginator 实例。

collect($posts)->paginate(5);

此代码以每页 5 项对 $posts 的内容进行分页。 paginate 接受相当多的选项,有关深入了解,请参阅 Laravel 文档

paginate(int $perPage = 15, string $pageName = 'page', int $page = null, int $total = null, array $options = [])

prioritize

将元素移到集合的起始位置。

$collection = collect([
    ['id' => 1],
    ['id' => 2],
    ['id' => 3],
]);

$collection
   ->prioritize(function(array $item) {
      return $item['id'] === 2;
   })
   ->pluck('id')
   ->toArray(); // returns [2, 1, 3]

rejectValues

从集合中删除给定的值。

collect(['foo', 'bar'])->rejectValues(['foo'])->toArray(); // ['bar']

rejectValues 接受第二个参数以启用严格比较(默认 false)。

collect(['123', 456])->rejectValues(['123', '456'], true)->toArray(); // [456]

simplePaginate

为集合中的项创建 Paginator 实例。

collect($posts)->simplePaginate(5);

此代码以每页 5 项对 $posts 的内容进行分页。 simplePaginate 接受相当多的选项,有关深入了解,请参阅 Laravel 文档

simplePaginate(int $perPage = 15, string $pageName = 'page', int $page = null, int $total = null, array $options = [])

有关分页的深入了解,请参阅 Laravel 文档

try

如果在 trycatch 之间有任何方法抛出异常,则可以在 catch 中处理该异常。

collect(['a', 'b', 'c', 1, 2, 3])
    ->try()
    ->map(fn ($letter) => strtoupper($letter))
    ->each(function() {
        throw new Exception('Explosions in the sky');
    })
    ->catch(function (Exception $exception) {
        // handle exception here
    })
    ->map(function() {
        // further operations can be done, if the exception wasn't rethrow in the `catch`
    });

虽然这些方法被命名为 try/catch 以便于与 PHP 中的用法相熟悉,但实际上这个集合本身更像是一个数据库事务。所以,当抛出异常时,会返回原始集合(try 之前的状态)。

您可以在 catch 中通过添加第二个参数来访问集合。您还可以通过返回一个值来在 catch 中操作集合。

$collection = collect(['a', 'b', 'c', 1, 2, 3])
    ->try()
    ->map(function ($item) {
        throw new Exception();
    })
    ->catch(function (Exception $exception, $collection) {
        return collect(['d', 'e', 'f']);
    })
    ->map(function ($item) {
        return strtoupper($item);
    });

// ['D', 'E', 'F']

transpose

transpose 的目标是对多维数组进行旋转,将行转换为列,将列转换为行。

collect([
    ['Jane', 'Bob', 'Mary'],
    ['jane@example.com', 'bob@example.com', 'mary@example.com'],
    ['Doctor', 'Plumber', 'Dentist'],
])->transpose()->toArray();

// [
//     ['Jane', 'jane@example.com', 'Doctor'],
//     ['Bob', 'bob@example.com', 'Plumber'],
//     ['Mary', 'mary@example.com', 'Dentist'],
// ]

validate

如果给定的 $callback 对每个项目都返回 true,则返回 true。如果 $callback 是一个字符串或数组,则将其视为验证规则。

collect(['foo', 'foo'])->validate(function ($item) {
   return $item === 'foo';
}); // returns true


collect(['sebastian@spatie.be', 'bla'])->validate('email'); // returns false
collect(['sebastian@spatie.be', 'freek@spatie.be'])->validate('email'); // returns true

变更日志

有关最近更改的更多信息,请参阅 变更日志

测试

$ composer test

贡献

此包目前不接受贡献。如果您想进行贡献,请参阅原始的 spatie/laravel-collection-macros 包。

安全

如果您发现任何安全相关的问题,请通过电子邮件 tim@code-distortion.net 联系,而不是使用问题跟踪器。

鸣谢

许可

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