Skip to content

Commit 402d313

Browse files
test only
1 parent 4c697b8 commit 402d313

File tree

4 files changed

+53
-5
lines changed

4 files changed

+53
-5
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
"src/IndexOf.php",
4444
"src/Map.php",
4545
"src/None.php",
46+
"src/Only.php",
4647
"src/Pipe.php",
4748
"src/Pull.php",
4849
"src/Pull.php",

src/Only.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace BrenoRoosevelt;
5+
6+
/**
7+
* Returns a subset of the collection with elements that match given keys.
8+
* The keys are preserved
9+
*
10+
* @param array $items The collection
11+
* @param mixed ...$keys keys to be filtered
12+
* @return array
13+
*/
14+
function only(array $items, ...$keys): array
15+
{
16+
return array_intersect_key($items, array_flip($keys));
17+
}

src/array_functions.php

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,6 @@
33

44
namespace BrenoRoosevelt;
55

6-
function only(array $items, ...$keys): array
7-
{
8-
return array_intersect_key($items, array_flip($keys));
9-
}
10-
116
function except(array $items, ...$keys): array
127
{
138
return array_diff_key($items, array_flip($keys));

tests/OnlyTest.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace BrenoRoosevelt\Tests;
5+
6+
use PHPUnit\Framework\TestCase;
7+
use function BrenoRoosevelt\only;
8+
use function BrenoRoosevelt\reject;
9+
10+
class OnlyTest extends TestCase
11+
{
12+
public function testOnly()
13+
{
14+
$elements = [1, 'b', 'c', 'd'];
15+
$this->assertEquals([1, 'b'], only($elements, 0, 1));
16+
}
17+
18+
public function testOnlyPreserveKeys()
19+
{
20+
$elements = [1, 'b', 'c', 'd'];
21+
$this->assertEquals([2 => 'c'], only($elements, 2));
22+
}
23+
24+
public function testOnlyKeyNotExists()
25+
{
26+
$elements = [1, 'b', 'c', 'd'];
27+
$this->assertEquals([], only($elements, 'b'));
28+
}
29+
30+
public function testOnlyKeyPreserveValues()
31+
{
32+
$elements = [1, 'c' => [[[2]]]];
33+
$this->assertEquals(['c' => [[[2]]]], only($elements, 'c'));
34+
}
35+
}

0 commit comments

Comments
 (0)