You are here

public function ArrayHelperTest::testChunkEvenly in Helper 7

File

tests/ArrayHelperTest.test, line 117

Class

ArrayHelperTest

Code

public function testChunkEvenly() {
  $input = array_combine(range(10, 1, -1), range(1, 10));
  $result = ArrayHelper::chunkEvenly($input, 3);
  $this
    ->assertIdentical($result, array(
    0 => array(
      1,
      2,
      3,
      4,
    ),
    1 => array(
      5,
      6,
      7,
    ),
    2 => array(
      8,
      9,
      10,
    ),
  ));
  $result = ArrayHelper::chunkEvenly($input, 4, TRUE);
  $this
    ->assertIdentical($result, array(
    0 => array(
      10 => 1,
      9 => 2,
      8 => 3,
    ),
    1 => array(
      7 => 4,
      6 => 5,
      5 => 6,
    ),
    2 => array(
      4 => 7,
      3 => 8,
    ),
    3 => array(
      2 => 9,
      1 => 10,
    ),
  ));

  // Test using $num greater than items in the array.
  $result = ArrayHelper::chunkEvenly($input, 11);
  $this
    ->assertIdentical($result, array(
    0 => array(
      1,
    ),
    1 => array(
      2,
    ),
    2 => array(
      3,
    ),
    3 => array(
      4,
    ),
    4 => array(
      5,
    ),
    5 => array(
      6,
    ),
    6 => array(
      7,
    ),
    7 => array(
      8,
    ),
    8 => array(
      9,
    ),
    9 => array(
      10,
    ),
  ));

  // Test empty array.
  $this
    ->assertIdentical(ArrayHelper::chunkEvenly(array(), 1), array());
  $this
    ->assertIdentical(ArrayHelper::chunkEvenly(array(), 5), array());

  // Test $num less than 1.
  try {
    $this
      ->assertIdentical(ArrayHelper::chunkEvenly($input, 0), array());
    throw new Exception();
  } catch (InvalidArgumentException $e) {
    $this
      ->pass("InvalidArgumentException thrown.");
  } catch (Exception $e) {
    $this
      ->fail("InvalidArgumentException not thrown.");
  }

  // Test non-numeric $num
  try {
    $this
      ->assertIdentical(ArrayHelper::chunkEvenly($input, 'invalid'), array());
    throw new Exception();
  } catch (InvalidArgumentException $e) {
    $this
      ->pass("InvalidArgumentException thrown.");
  } catch (Exception $e) {
    $this
      ->fail("InvalidArgumentException not thrown.");
  }
}