Skip to content

Commit 94bde41

Browse files
authored
Merge pull request #16 from Bu4ak/fix-division-by-zero
Fix division by zero in array_split()
2 parents 5f00e94 + c8b2104 commit 94bde41

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ function array_split_filter(array $array, callable $callback)
111111
* @param array $array
112112
* @param int $numberOfPieces
113113
* @param bool $preserveKeys
114+
* @throws \InvalidArgumentException
114115
* @return array
115116
*/
116117
function array_split(array $array, $numberOfPieces = 2, $preserveKeys = false)

src/array_functions.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,11 +111,16 @@ function array_split_filter(array $array, callable $callback)
111111
* @param array $array
112112
* @param int $numberOfPieces
113113
* @param bool $preserveKeys
114+
* @throws \InvalidArgumentException if the provided argument $numberOfPieces is lower than 1
114115
*
115116
* @return array
116117
*/
117118
function array_split(array $array, $numberOfPieces = 2, $preserveKeys = false)
118119
{
120+
if ($numberOfPieces <= 0) {
121+
throw new \InvalidArgumentException('Number of pieces parameter expected to be greater than 0');
122+
}
123+
119124
if (count($array) === 0) {
120125
return [];
121126
}

tests/ArraySplitTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,31 @@ public function it_can_handle_an_empty_array()
1515
$this->assertSame(array_split([]), []);
1616
}
1717

18+
/**
19+
* @dataProvider argumentsProvider
20+
* @test
21+
*/
22+
public function it_throws_exception_when_second_parameter_is_lower_than_1($numberOfPieces, $mustThrow)
23+
{
24+
$exception = null;
25+
try {
26+
array_split([], $numberOfPieces);
27+
} catch (\InvalidArgumentException $exception) {}
28+
29+
$this->assertSame($mustThrow, $exception instanceof \InvalidArgumentException);
30+
}
31+
32+
public function argumentsProvider()
33+
{
34+
return [
35+
[2 , false],
36+
[1 , false],
37+
[0 , true],
38+
[-1 , true],
39+
[-2 , true],
40+
];
41+
}
42+
1843
/**
1944
* @test
2045
*/

0 commit comments

Comments
 (0)