Skip to content

Commit

Permalink
Add array utility
Browse files Browse the repository at this point in the history
  • Loading branch information
parsilver committed Dec 8, 2023
1 parent 8527352 commit bd6bd55
Show file tree
Hide file tree
Showing 2 changed files with 124 additions and 0 deletions.
59 changes: 59 additions & 0 deletions src/Arr.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace Farzai\Support;

use ArrayAccess;

class Arr
{
/**
* Get an item from an array using "dot" notation.
*
* @param mixed $array
* @return mixed
*/
public static function get($array, $key, $default = null)
{
if (! static::accessible($array)) {
return $default;
}

if (is_null($key)) {
return $array;
}

foreach (explode('.', $key) as $segment) {
if (static::accessible($array) && static::exists($array, $segment)) {
$array = $array[$segment];
} else {
return $default;
}
}

return $array;
}

/**
* Determine if the given key exists in the provided array.
*/
public static function exists($array, $key): bool
{
foreach (explode('.', $key) as $segment) {
if (static::accessible($array) && ($array[$segment] ?? false)) {
$array = $array[$segment];
} else {
return false;
}
}

return true;
}

/**
* Determine if the given value is array accessible.
*/
public static function accessible($value): bool
{
return is_array($value) || $value instanceof ArrayAccess;
}
}
65 changes: 65 additions & 0 deletions tests/ArrTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

use Farzai\Support\Arr;

it('can check if key exists in array', function () {
$array = [
'foo' => 'bar',
];

$this->assertTrue(Arr::exists($array, 'foo'));
$this->assertFalse(Arr::exists($array, 'bar'));
});

it('can check if key exists in array using dot notation', function () {
$array = [
'foo' => [
'bar' => 'baz',
'baz' => [
'qux' => 'quux',
],
],
];

$this->assertTrue(Arr::exists($array, 'foo.bar'));
$this->assertFalse(Arr::exists($array, 'foo.qux'));
$this->assertTrue(Arr::exists($array, 'foo.baz.qux'));
});

it('can get value from array', function () {
$array = [
'foo' => 'bar',
];

$this->assertEquals('bar', Arr::get($array, 'foo'));
});

it('can get value from array using dot notation', function () {
$array = [
'foo' => [
'bar' => 'baz',
],
];

$this->assertEquals('baz', Arr::get($array, 'foo.bar'));
});

it('can get value from array using dot notation with default value', function () {
$array = [
'foo' => [
'bar' => 'baz',
],
];

$this->assertEquals('qux', Arr::get($array, 'foo.qux', 'qux'));
});

it('can get value from array using dot notation with null default value', function () {
$array = [
'foo' => [
'bar' => 'baz',
],
];

$this->assertNull(Arr::get($array, 'foo.qux'));
});

0 comments on commit bd6bd55

Please sign in to comment.