Skip to content

Commit

Permalink
feat: add isList() and isAssoc() methods in ArrayHelper for array…
Browse files Browse the repository at this point in the history
… type checking (#566)

Co-authored-by: brendt <brent.roose@gmail.com>
  • Loading branch information
yassiNebeL and brendt authored Oct 12, 2024
1 parent b1495b2 commit f465060
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Tempest/Support/src/ArrayHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,26 @@ public function __construct(
}
}

/**
* Determines if the array is a list.
*
* An array is a list if its keys consist of consecutive numbers.
*/
public function isList(): bool
{
return array_is_list($this->array);
}

/**
* Determines if the array is an associative.
*
* An array is associative if its keys doesn't consist of consecutive numbers.
*/
public function isAssoc(): bool
{
return ! $this->isList();
}

/**
* Get one or a specified number of random values from the array.
*
Expand Down
29 changes: 29 additions & 0 deletions src/Tempest/Support/tests/ArrayHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1080,4 +1080,33 @@ public function test_random_throw_exception_when_giving_negative_integer(): void

$collection->random(-1);
}

public function test_is_list(): void
{
$this->assertTrue(arr()->isList());
$this->assertTrue(arr(['a', 2, 3])->isList());
$this->assertTrue(arr([0 => 'a', 'b'])->isList());

$this->assertFalse(arr([1 => 'a', 'b'])->isList());
$this->assertFalse(arr([1 => 'a', 0 => 'b'])->isList());
$this->assertFalse(arr([0 => 'a', 'foo' => 'b'])->isList());
$this->assertFalse(arr([0 => 'a', 2 => 'b'])->isList());
}

public function test_is_assoc(): void
{
$this->assertTrue(arr([1 => 'a', 'b'])->isAssoc());
$this->assertTrue(arr([1 => 'a', 0 => 'b'])->isAssoc());
$this->assertTrue(arr([0 => 'a', 'foo' => 'b'])->isAssoc());
$this->assertTrue(arr([0 => 'a', 2 => 'b'])->isAssoc());

$this->assertFalse(arr()->isAssoc());
$this->assertFalse(arr([1, 2, 3])->isAssoc());
$this->assertFalse(arr(['a', 2, 3])->isAssoc());
$this->assertFalse(arr([0 => 'a', 'b'])->isAssoc());

$this->assertTrue(arr([0 => 'a', 'foo' => 'b'])->isAssoc());
$this->assertTrue(arr([0 => 'a', 2 => 'b'])->isAssoc());
$this->assertTrue(arr(['foo' => 'a', 'baz' => 'b'])->isAssoc());
}
}

0 comments on commit f465060

Please sign in to comment.