Last active
January 6, 2021 14:52
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you only need to check objects type: