Skip to content

Commit

Permalink
Add macros "hasValue" to Arr
Browse files Browse the repository at this point in the history
  • Loading branch information
MCMatters committed Dec 10, 2020
1 parent 12c0fff commit b96e37b
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 3 deletions.
34 changes: 31 additions & 3 deletions src/Macros/ArrMacros.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

use function array_change_key_case, array_key_exists, array_keys, array_slice,
count, data_get, explode, implode, is_array, is_numeric, is_string,
mb_strpos, preg_grep, preg_quote, shuffle;
use function array_change_key_case, array_key_exists, array_keys, array_map,
array_slice, count, data_get, explode, implode, in_array, is_array,
is_numeric, is_string, mb_strpos, mb_strtolower, preg_grep, preg_quote,
shuffle;

use const false, null, true, CASE_LOWER;

Expand Down Expand Up @@ -230,4 +231,31 @@ protected function registerChangeKeyCaseRecursive()
return array_change_key_case($array, $case);
});
}

/**
* @return void
*/
protected function registerHasValue()
{
Arr::macro('hasValue', function (
$needle,
array $array,
bool $strict = false,
bool $insensitive = false
) {
if (!$insensitive || !is_string($needle)) {
return in_array($needle, $array, $strict);
}

return in_array(
mb_strtolower($needle, 'UTF-8'),
array_map(static function ($value) {
return is_string($value)
? mb_strtolower($value, 'UTF-8')
: $value;
}, $array),
$strict
);
});
}
}
18 changes: 18 additions & 0 deletions tests/ArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,24 @@ public function testArrayChangeKeyCaseRecursive()
$this->checkArrayKeysCase($upperCased, 'strtoupper');
}

/**
* @return void
*/
public function testArrayHasValue()
{
$array = require __DIR__.'/mocks/arrays/hasValue.php';

$this->assertTrue(Arr::hasValue('foo', $array));
$this->assertTrue(Arr::hasValue('bar', $array));
$this->assertTrue(Arr::hasValue('Foo', $array));
$this->assertTrue(Arr::hasValue('FOO', $array));
$this->assertTrue(Arr::hasValue('BAZ', $array));
$this->assertFalse(Arr::hasValue('BaZ', $array));
$this->assertTrue(Arr::hasValue('baz', $array, true, true));
$this->assertTrue(Arr::hasValue('bAz', $array, true, true));
$this->assertTrue(Arr::hasValue('qWe', $array, true, true));
}

/**
* @param array $array
* @param string $method
Expand Down
12 changes: 12 additions & 0 deletions tests/mocks/arrays/hasValue.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

return [
'foo',
'bar',
'Foo',
'FOO',
'BAZ',
'QwE',
];

0 comments on commit b96e37b

Please sign in to comment.