Skip to content

Commit 86f9303

Browse files
refacoring index_of
1 parent d4fdb43 commit 86f9303

File tree

2 files changed

+67
-7
lines changed

2 files changed

+67
-7
lines changed

src/IndexOf.php

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,8 @@
1313
*/
1414
function index_of(iterable $haystack, $element, bool $strict = true)
1515
{
16-
if (is_array($haystack)) {
17-
return array_search($element, $haystack, $strict);
18-
}
19-
2016
foreach ($haystack as $index => $value) {
21-
$matchStrict = $strict && $element === $value;
22-
$matchNonStrict = !$strict && $element == $value;
23-
if ($matchStrict || $matchNonStrict) {
17+
if (($strict && $element === $value) || (!$strict && $element == $value)) {
2418
return $index;
2519
}
2620
}

tests/DotNotationTest.php

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace BrenoRoosevelt\Tests;
5+
6+
use PHPUnit\Framework\TestCase;
7+
use function BrenoRoosevelt\set_path;
8+
9+
class DotNotationTest extends TestCase
10+
{
11+
public function setPathProvider(): array
12+
{
13+
return [
14+
'case_1' => [
15+
[],
16+
'a',
17+
1,
18+
'.',
19+
['a' => 1]
20+
],
21+
'case_2' => [
22+
['a' => [0, 1]],
23+
'a.b',
24+
9,
25+
'.',
26+
['a' => [0, 1, 'b' => 9]]
27+
],
28+
'case_3' => [
29+
['a' => [0, 1]],
30+
'a.b.c',
31+
9,
32+
'.',
33+
['a' => [0, 1, 'b' => ['c' => 9]]]
34+
],
35+
'case_4' => [
36+
['a' => [0, 1]],
37+
'a.0',
38+
9,
39+
'.',
40+
['a' => [9, 1]]
41+
],
42+
'case_5' => [
43+
['a' => [0, 1, 'b' => ['c' => 9]]],
44+
'a.b.c.2',
45+
9,
46+
'.',
47+
['a' => [0, 1, 'b' => ['c' => [2 => 9]]]],
48+
]
49+
];
50+
}
51+
52+
/**
53+
* @param array $haystack
54+
* @param string $path
55+
* @param $value
56+
* @param string $separator
57+
* @param array $expected
58+
* @return void
59+
* @dataProvider setPathProvider
60+
*/
61+
public function testSetPath(array $haystack, string $path, $value, string $separator, array $expected): void
62+
{
63+
set_path($haystack, $path, $value, $separator);
64+
$this->assertEquals($expected, $haystack);
65+
}
66+
}

0 commit comments

Comments
 (0)