Skip to content

Instantly share code, notes, and snippets.

@makomweb
Created January 28, 2022 11:45
Show Gist options
  • Save makomweb/2db8cb990bfbdfe30bde3a28d6077d7d to your computer and use it in GitHub Desktop.
Save makomweb/2db8cb990bfbdfe30bde3a28d6077d7d to your computer and use it in GitHub Desktop.
PHP collection assert
<?php
declare(strict_types=1);
namespace App\Tests\Unit;
use LogicException;
use PHPUnit\Framework\TestCase;
class MyClass {}
class MyOtherClass {}
class CollectionAssertTests extends TestCase
{
/** @test */
public function works_for_an_empty_collection()
{
/** @var MyClass[] $collection */
$collection = [];
self::assertSameType($collection);
self::assertTrue(true, 'Should NOT have thrown before!');
}
/** @test */
public function works_for_a_collection_of_objects_of_the_same_type()
{
$collection = [
new MyClass(),
new MyClass(),
new MyClass()
];
self::assertSameType($collection);
self::assertTrue(true, 'Should NOT have thrown before!');
}
/** @test */
public function works_for_a_collection_of_objects_of_different_types()
{
$collection = [
new MyClass(),
new MyOtherClass()
];
$this->expectException(LogicException::class);
self::assertSameType($collection);
self::fail('Should have thrown before!');
}
/** @test */
public function works_for_a_collection_of_arrays()
{
/** @var MyClass[] $collection */
$collection = [
['foo' => 'bar'],
['value' => 42]
];
self::assertSameType($collection);
self::assertTrue(true, 'Should NOT have thrown before!');
}
/** @test */
public function works_for_a_collection_of_objects_of_same_base_class()
{
self::fail('Not yet implemented!');
}
private static function assertSameType(array $data)
{
$collection = array_values($data);
$types = array_map(static function($item) {
return get_class($item);
}, $collection);
if (count($types) && !(count(array_unique($types)) === 1))
{
throw new LogicException('Not all items in the collection are of the same type!');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment