lyhty/macros

为您的 Laravel 项目提供有用的宏。

v5.1.0 2024-09-21 19:38 UTC

README

Latest Version on Packagist PHP Laravel Total Downloads StyleCI License

此包为您提供了使用 Laravel 项目的一些额外的、方便的宏。

安装

使用 Composer 安装包

composer require lyhty/macros

该包将自动注册自己。

以下是该包提供的宏的简要文档。

Illuminate\Database\Eloquent\Builder

Builder::selectKey

选择查询中的模型键(使用模型的 getKey 方法)。

$query = User::query()->selectKey();

$query->toSql(); // "select `id` from `users`"

Illuminate\Database\Query\Builder

Builder::whereLike & orWhereLike

⚠️ 此宏依赖于 Str::explodeReverse 宏。如果您想禁用后者宏,则此宏将不再起作用。

⚠️ Builder::orWhereLike 宏依赖于 Builder::whereLike 宏。如果您想禁用 whereLike 宏,请确保禁用 orWhereLike 宏。

$query = User::query()
    ->whereLike('name', 'Matti Suo', 'right')
    ->orWhereLike('name', 'ranie')
    ->orWhereLike('name', 'mi', 'left');

$query->toSql();
// "select * from `users` where (`users`.`name` LIKE ?) or (`users`.`name` LIKE ?) or (`users`.`name` LIKE ?)"
// First ? being "Matti Suo%", second "%ranie%" and third "%mi"

$query = User::query()->whereLike('games.name', 'Apex Leg', 'right');

$query->toSql();
// select * from `users` where (exists
//   (select * from `games` where `users`.`id` = `games`.`user_id` and `games`.`name` LIKE ?)
// )
// ? being "Apex Leg%"

$query = User::query()->whereLike(['games.console.name', 'games.platforms.name'], 'Xbox');

$query->toSql();
// select * from `users` where (exists (select * from `games` where `users`.`id` = `games`.`user_id` and (exists
// (select * from `consoles` where `games`.`console_id` = `consoles`.`id` and (`consoles`.`name` LIKE ?)) or exists
// (select * from `platforms` inner join `platform_game` on `platforms`.`id` = `platform_game`.`platform_id` where
// `games`.`id` = `platform_game`.`game_id` and (`platforms`.`name` LIKE ?)))))
// ? being "Xbox"

Builder::selectRawArr

将原始选择语句作为数组添加,而不是作为难看的字符串(selectRaw)。

$query = User::query()->selectRawArr([
    'concat(`id`, "-", `name`) as id_name',
    'concat(`email`, "-", `name`) as email_name'
]);
// 🤩

$query->first()->toArray(); // ["id_name" => "1-Matti", "email_name" => "matti@suoraniemi.com-Matti"]

// Instead of:
$query = User::query()->selectRaw('concat(`id`, "-", `name`) as id_name, concat(`email`, "-", `name`) as email_name');
// 🤢

Illuminate\Support\Collection

Collection::mergeMany

一次将多个数组/集合合并到集合中。

$data = new Collection([1,2,3]);

$data->mergeMany([4], [5], [6]); // [1, 2, 3, 4, 5, 6]

Collection::pick (之前为 pluckMany)

从集合项中选取多个键。第一个值应该是您想要从集合项中选取的键的数组。第二个值确定是否保留键以及哪种格式

  • PICK_WITH_FULL_KEYS (>= 2):
    • 保留可能嵌套的值在其原始深度。
  • PICK_WITH_PARTIAL_KEYS (1):
    • 扁平化结果,同时保留键。
  • PICK_WITHOUT_KEYS (0):
    • 不会保留任何键
$data = User::query()->get();

$data->pick(['id', 'name', 'metadata.loggedIn'])->toArray();
// [[1, "Matti Suoraniemi", true], [2, "Foo Bar", false]]

$data->pick(['id', 'name', 'metadata.loggedIn'], 1)->toArray();
// [
//   ["id" => 1, "name" => "Matti Suoraniemi", "loggedIn" => true],
//   ["id" => 2, "name" => "Foo Bar", "loggedIn" => false]
// ]

$data->pick(['id', 'name', 'metadata.loggedIn'], 2)->toArray();
// [
//   ["id" => 1, "name" => "Matti Suoraniemi", "metadata" => ["loggedIn" => true]],
//   ["id" => 2, "name" => "Foo Bar", "metadata" => ["loggedIn" => false]]
// ]

Collection::whereExtends

筛选扩展给定类的类和/或对象。

use Illuminate\Database\Eloquent\Model;

$data = new Collection([
    \App\Models\User::class,
    \App\Models\Game::class,
    \App\Models\Console::class,
    \App\Models\Hobby::class,
]);

$data->whereExtends(Model::class)->count(); // 4

Collection::whereImplements

筛选实现给定接口的类和/或对象。

use App\Contracts\PlayableOnConsole;

$data = new Collection([
    \App\Models\User::class,
    \App\Models\Game::class,
    \App\Models\Console::class,
    \App\Models\Hobby::class,
]);

$data->whereImplements(PlayableOnConsole::class)->toArray(); // ["App\Models\Game"]

Collection::whereUses

筛选使用给定特质(trait)的类和/或对象。

use Illuminate\Notifications\Notifiable;

$data = new Collection([
    \App\Models\User::class,
    \App\Models\Game::class,
    \App\Models\Console::class,
    \App\Models\Hobby::class,
]);

$data->whereUses(Notifiable::class)->toArray(); // ["App\Models\User"]

Illuminate\Support\Arr

Arr::associate

通过将具有整数键的任何值转换为填充给定填充值的键来将数组转换为完全关联数组。具有字符串键的值将保持不变。

Arr::associate(['foo']); // ["foo" => null]
Arr::associate(['foo', 'bar' => []], []); // ["foo" => [], "bar" => []]
Arr::associate(['foo', 'bar' => []], fn () => Arr::random(['foo', 'bar'])); // ["foo" => "foo", "bar" => []]
Arr::associate([fn () => Str::reverse('foo'), 'bar' => []]); // ["oof" => null, "bar" => []]

Arr::combine

类似于 array_combine,但允许有比值更多的键。没有值的键将被设置为 null。

Arr::combine(['foo', 'zoo'], ["bar", "gar"]); // ["foo" => "bar", "zoo" => "gar"]
Arr::combine(['foo', 'zoo'], ["bar"]); // ["foo" => "bar", "zoo" => null]

Arr::fillKeys

使用给定值填充给定的键。您还可以设置只有数组中已经存在的键才能被填充。换句话说,如果键 foo 要填充为值 bar,但键 foo 不在数组中,则数组将保持不变。

$array = ['foo' => 'bar', 'zoo' => 'gar'];

Arr::fillKeys($array, ['foo', 'zoo'], null); // ["foo" => null, "zoo" => null]
Arr::fillKeys($array, ['foo', 'zoo', 'boo'], null); // ["foo" => null, "zoo" => null, "boo" => null]
Arr::fillKeys($array, ['foo', 'zoo', 'boo'], null, true); // ["foo" => null, "zoo" => null]

Arr::implode

使用给定的分隔符将给定的数组Implode为 \Illuminate\Support\Stringable 实例。

$array = ['foo', 'bar'];

(string) Arr::implode($array, ' ')->upper(); // "FOO BAR"

Arr::join

将集合的优美连接方法带到 Arr。

Arr::join(['foo', 'bar', 'zoo'], ', ', ' and '); // "foo, bar and zoo"

Arr::zip

使用给定的打包器将键和值一起打包。

Arr::zip(['foo' => 'bar', 'zoo' => 'gar'], ':'); // ["foo:bar", "zoo:gar"]

Arr::unzip

使用给定的打包器将键解包到键和值。

Arr::unzip(['foo:bar', 'zoo:gar'], ':'); // ["foo" => "bar", "zoo" => "gar"]

Str::explodeReverse

从末尾开始拆分给定的字符串,并将其作为 Illuminate\Support\Collection 类实例返回。

Str::explodeReverse('games.platforms.name', '.', 2)->toArray(); // ['games.platforms', 'name']

// Whereas normal explode function would do:
explode('.', 'games.platforms.name', 2); // ['games', 'platforms.name']

Illuminate\Support\Str

Str::wrapWith

用指定的字符将字符串包裹。

Str::wrapWith('foo', ':'); // ":foo:"
Str::wrapWith('bar', '<', '>'); // "<bar>"
Str::wrapWith('!zoo', '!'); // "!zoo!"

⚠️ 由于 Laravel 9 引入了 Str::wrap 宏,从 v4.0 版本开始,此宏现在称为 Str::wrapWith 以避免冲突。注意:这两个宏的行为不同

Str::wrapWith(':foo', ':'); // ":foo:"
Str::wrap(':foo', ':'); // "::foo:"

Illuminate\Support\Stringable

Stringable::explodeReverse

⚠️ 此宏依赖于 Str::explodeReverse 宏。如果您想禁用此宏,则此宏将不再起作用。

参见 Illuminate\Support\Str::explodeReverse

Str::of('games.platforms.name')->explodeReverse('.', 2)->toArray(); // ['games.platforms', 'name']

// Whereas normal explode function would do:
Str::of('games.platforms.name')->explode('.', 2)->toArray(); // ['games', 'platforms.name']

Stringable::wrapWith

⚠️ 由于 Laravel 9 引入了 Str::wrap 宏,从 v4.0 版本开始,此宏现在称为 Str::wrapWith 以避免冲突。

⚠️ 此宏依赖于 Str::wrapWith 宏。如果您想禁用此宏,则此宏将不再起作用。

参见 Illuminate\Support\Str::wrapWith

(string) Str::of('foo')->upper()->wrapWith(':'); // ":FOO:"
(string) Str::of('bar')->upper()->wrapWith('<', '>'); // "<BAR>"
(string) Str::of('!zoo')->upper()->wrapWith('!'); // "!ZOO!"

Carbon\CarbonPeriod

CarbonPeriod::collect

$dates = CarbonPeriod::between('yesterday', 'today')->collect();

$dates->first()->toDateTimeString(); // "2022-06-14 00:00:00"

许可协议

Lyhty 宏是开源软件,采用 MIT 许可协议 许可。