Skip to content

Instantly share code, notes, and snippets.

@DrewAPicture
Last active January 6, 2021 14:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrewAPicture/dfd572692f42417f734d091eccbbfa08 to your computer and use it in GitHub Desktop.
Save DrewAPicture/dfd572692f42417f734d091eccbbfa08 to your computer and use it in GitHub Desktop.
PHPUnit assertion function to check the types of all items in an array
<?php>
/**
* Checks if all first-level items in the array are of the given type.
*
* Example:
*
* function test_get_posts_with_no_fields_arg_should_return_array_of_WP_Post_objects() {
* $this-assertContainsOnlyType( 'WP_Post', get_posts() );
* }
*
* @since 2.1
*
* @param string $type Type to check against.
* @param array $actual Actual array.
*/
public function assertContainsOnlyType( $type, $actual ) {
$standard_types = array(
'numeric', 'integer', 'int', 'float', 'string', 'boolean', 'bool',
'null', 'array', 'object', 'resource', 'scalar'
);
if ( in_array( $type, $standard_types, true ) ) {
/**
* Checks if all items in the array are of the given type.
*
* @since 2.1
*
* @param string $type Type to check against.
* @param array $actual Actual array.
*/
public function assertContainsOnlyType( $type, $actual ) {
$standard_types = array(
'numeric', 'integer', 'int', 'float', 'string', 'boolean', 'bool',
'null', 'array', 'object', 'resource', 'scalar'
);
if ( in_array( $type, $standard_types, true ) ) {
if ( class_exists( '\PHPUnit\Framework\Constraint\IsType' ) ) {
$constraint = new \PHPUnit\Framework\Constraint\IsType( $type );
} else {
$constraint = new \PHPUnit_Framework_Constraint_IsType( $type );
}
} else {
if ( class_exists( '\PHPUnit\Framework\Constraint\IsInstanceOf' ) ) {
$constraint = new \PHPUnit\Framework\Constraint\IsInstanceOf( $type );
} else {
$constraint = new \PHPUnit_Framework_Constraint_IsInstanceOf( $type );
}
}
foreach ( $actual as $item ) {
if ( class_exists( '\PHPUnit\Framework\Assert' ) ) {
\PHPUnit\Framework\Assert::assertThat( $item, $constraint );
} else {
\PHPUnit_Framework_Assert::assertThat( $item, $constraint );
}
}
}
foreach ( $actual as $item ) {
\PHPUnit_Framework_Assert::assertThat( $item, $constraint );
}
}
@duboiss
Copy link

duboiss commented Jan 6, 2021

If you only need to check objects type:

self::assertContainsOnlyInstancesOf('Myclass', $array);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment