Skip to content

Commit

Permalink
Merge pull request #16 from Bu4ak/fix-division-by-zero
Browse files Browse the repository at this point in the history
Fix division by zero in array_split()
  • Loading branch information
freekmurze committed Oct 14, 2019
2 parents 5f00e94 + c8b2104 commit 94bde41
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ function array_split_filter(array $array, callable $callback)
* @param array $array
* @param int $numberOfPieces
* @param bool $preserveKeys
* @throws \InvalidArgumentException
* @return array
*/
function array_split(array $array, $numberOfPieces = 2, $preserveKeys = false)
Expand Down
5 changes: 5 additions & 0 deletions src/array_functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,16 @@ function array_split_filter(array $array, callable $callback)
* @param array $array
* @param int $numberOfPieces
* @param bool $preserveKeys
* @throws \InvalidArgumentException if the provided argument $numberOfPieces is lower than 1
*
* @return array
*/
function array_split(array $array, $numberOfPieces = 2, $preserveKeys = false)
{
if ($numberOfPieces <= 0) {
throw new \InvalidArgumentException('Number of pieces parameter expected to be greater than 0');
}

if (count($array) === 0) {
return [];
}
Expand Down
25 changes: 25 additions & 0 deletions tests/ArraySplitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,31 @@ public function it_can_handle_an_empty_array()
$this->assertSame(array_split([]), []);
}

/**
* @dataProvider argumentsProvider
* @test
*/
public function it_throws_exception_when_second_parameter_is_lower_than_1($numberOfPieces, $mustThrow)
{
$exception = null;
try {
array_split([], $numberOfPieces);
} catch (\InvalidArgumentException $exception) {}

$this->assertSame($mustThrow, $exception instanceof \InvalidArgumentException);
}

public function argumentsProvider()
{
return [
[2 , false],
[1 , false],
[0 , true],
[-1 , true],
[-2 , true],
];
}

/**
* @test
*/
Expand Down

0 comments on commit 94bde41

Please sign in to comment.