diff --git a/README.md b/README.md index 43873ea..e9c4e1b 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Collection of helpers for re-use accross a few of our projects - [Helpers](#helpers) - [Delayed notifications blocking:](#delayed-notifications-blocking) - [DB Macros](#db-macros) + - [String Macros](#string-macros) - [Credits](#credits) ## Installation @@ -115,6 +116,9 @@ Model::whereNullOrEmpty('column_name'); //generates select * where 1=1 and (colu Model::orWhereNullOrEmpty('column_name'); //generates select * where 1=1 or (column_name is null or column_name = '') Model::whereNotNullOrEmpty('column_name'); //generates select * where 1=1 and (column_name is not null and column_name != '') Model::orWhereNotNullOrEmpty('column_name'); //generates select * where 1=1 or (column_name is not null and column_name != '') +``` +## String Macros +`Str::reverse(string)` - to safely reverse a string that is multibyte safe. ## Credits diff --git a/src/ServiceProvider.php b/src/ServiceProvider.php index 17277c1..0e08c90 100644 --- a/src/ServiceProvider.php +++ b/src/ServiceProvider.php @@ -2,6 +2,7 @@ namespace CustomD\LaravelHelpers; +use Illuminate\Support\Str; use Illuminate\Support\Facades\Event; use Illuminate\Database\Query\Builder; use CustomD\LaravelHelpers\Database\Query\Mixins\NullOrEmptyMixin; @@ -15,6 +16,7 @@ public function boot() { $this->registerEvents(); $this->registerDbMacros(); + $this->registerStringMacros(); } public function register() @@ -34,4 +36,13 @@ protected function registerDbMacros() { Builder::mixin(new NullOrEmptyMixin()); } + + protected function registerStringMacros() + { + /** @macro \Illuminate\Support\Str */ + Str::macro('reverse', function ($string, $encoding = null) { + $chars = mb_str_split($string, 1, $encoding ?? mb_internal_encoding()); + return implode('', array_reverse($chars)); + }); + } } diff --git a/tests/StringMacrosTest.php b/tests/StringMacrosTest.php new file mode 100644 index 0000000..5072e99 --- /dev/null +++ b/tests/StringMacrosTest.php @@ -0,0 +1,34 @@ + LaravelHelpers::class, + ]; + } + + public function testReverseStringMacro() + { + $str = "hello World"; + $rev = 'dlroW olleh'; + $this->assertEquals($rev, Str::reverse($str)); + + $encodedStr = 'te reo māori'; + $encodedRev = 'iroām oer et'; + $this->assertEquals($encodedRev, Str::reverse($encodedStr)); + } +}