Skip to content

Commit

Permalink
added Arrays::first(), last() & contains()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jan 10, 2021
1 parent ff63fa0 commit 740520b
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/Utils/Arrays.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,36 @@ public static function searchKey(array $array, $key): ?int
}


/**
* Tests an array for the presence of value.
* @param mixed $value
*/
public static function contains(array $array, $value): bool
{
return in_array($value, $array, true);
}


/**
* Returns the first item from the array or null.
* @return mixed
*/
public static function first(array $array)
{
return count($array) ? reset($array) : null;
}


/**
* Returns the last item from the array or null.
* @return mixed
*/
public static function last(array $array)
{
return count($array) ? end($array) : null;
}


/**
* Inserts the contents of the $inserted array into the $array immediately after the $key.
* If $key is null (or does not exist), it is inserted at the beginning.
Expand Down
16 changes: 16 additions & 0 deletions tests/Utils/Arrays.contains().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

use Nette\Utils\Arrays;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


Assert::false(Arrays::contains([], 'a'));
Assert::true(Arrays::contains(['a'], 'a'));
Assert::true(Arrays::contains([1, 2, 'a'], 'a'));
Assert::false(Arrays::contains([1, 2, 3], 'a'));
Assert::false(Arrays::contains([1, 2, 3], '1'));
21 changes: 21 additions & 0 deletions tests/Utils/Arrays.first().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

use Nette\Utils\Arrays;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


Assert::null(Arrays::first([]));
Assert::null(Arrays::first([null]));
Assert::false(Arrays::first([false]));
Assert::same(1, Arrays::first([1, 2, 3]));


$arr = [1, 2, 3];
end($arr);
Assert::same(1, Arrays::first($arr));
Assert::same(3, current($arr));
20 changes: 20 additions & 0 deletions tests/Utils/Arrays.last().phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

use Nette\Utils\Arrays;
use Tester\Assert;


require __DIR__ . '/../bootstrap.php';


Assert::null(Arrays::last([]));
Assert::null(Arrays::last([null]));
Assert::false(Arrays::last([false]));
Assert::same(3, Arrays::last([1, 2, 3]));


$arr = [1, 2, 3];
Assert::same(3, Arrays::last($arr));
Assert::same(1, current($arr));

0 comments on commit 740520b

Please sign in to comment.