From d5cf4c7691e0f0d7327b2471d8d4c2d2a1768cb4 Mon Sep 17 00:00:00 2001 From: nunoxavier Date: Thu, 20 Jun 2024 14:53:06 +0100 Subject: [PATCH] Added str macro for first and last words of a string --- src/Macros/StrMacros.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Macros/StrMacros.php b/src/Macros/StrMacros.php index 35690f7..b3fec98 100644 --- a/src/Macros/StrMacros.php +++ b/src/Macros/StrMacros.php @@ -7,6 +7,7 @@ use Flavorly\LaravelHelpers\Contracts\RegistersMacros; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Collection; use Illuminate\Support\Str; final class StrMacros implements RegistersMacros @@ -16,6 +17,7 @@ public static function register(): void self::normalizeCharacters(); self::acronimize(); self::username(); + self::firstAndLastWords(); self::money(); self::spin(); } @@ -49,6 +51,19 @@ public static function username(): void }); } + public static function firstAndLastWords(): void + { + Str::macro('firstAndLastWords', function (string $string): string { + return Str::of($string) + ->explode(' ') + ->filter() + ->values() + ->whenNotEmpty(function (Collection $words): string { + return trim($words->first().' '.$words->last()); + }, $string); + }); + } + public static function spin(): void { Str::macro('spin', function (string $string): string {