ArrayUtil.php
6 months ago
BlocksUtil.php
4 months ago
COTMigrationUtil.php
1 year ago
DatabaseUtil.php
1 year ago
FilesystemUtil.php
6 months ago
HtmlSanitizer.php
2 years ago
LegacyRestApiStub.php
1 year ago
PluginInstaller.php
1 year ago
ProductUtil.php
7 months ago
Types.php
1 year ago
URL.php
1 year ago
URLException.php
4 years ago
Users.php
3 months ago
WebhookUtil.php
1 year ago
Types.php
66 lines
| 1 | <?php |
| 2 | |
| 3 | declare( strict_types = 1 ); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Internal\Utilities; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | |
| 9 | /** |
| 10 | * Utilities to help ensure type safety. |
| 11 | */ |
| 12 | class Types { |
| 13 | /** |
| 14 | * Checks if $thing is an instance of $desired_type. |
| 15 | * |
| 16 | * If the check succeeds, $thing will be returned without further modification. If the check fails, then either |
| 17 | * an exception will be thrown or, if an $on_failure callback was supplied, it will be invoked to either generate |
| 18 | * an appropriate return value or to throw a more specific exception. |
| 19 | * |
| 20 | * Please note that the failure handler will be passed two arguments: |
| 21 | * |
| 22 | * $on_failure( $object, $desired_type ) |
| 23 | * |
| 24 | * @since 9.1.0 |
| 25 | * @throws InvalidArgumentException If $object does not match $desired_type, and an $on_failure callback was not supplied. |
| 26 | * |
| 27 | * @param mixed $thing The value or reference to be assessed. |
| 28 | * @param string $desired_type What we expect the return type to be, if it is not a WP_Error. |
| 29 | * @param ?callable $on_failure If provided, and if evaluation fails, this will be invoked to generate a return value. |
| 30 | * |
| 31 | * @return mixed |
| 32 | */ |
| 33 | public static function ensure_instance_of( $thing, string $desired_type, ?callable $on_failure = null ) { |
| 34 | // If everything looks good, return early. |
| 35 | if ( $thing instanceof $desired_type ) { |
| 36 | return $thing; |
| 37 | } |
| 38 | |
| 39 | // Summarize the error for use in logging and in case we have to throw an exception. |
| 40 | $summary = sprintf( |
| 41 | 'Object was not of expected type %1$s.', |
| 42 | $desired_type |
| 43 | ); |
| 44 | |
| 45 | // Otherwise, let's log the problem so the site operator has a record of where things went wrong. |
| 46 | $logger = wc_get_logger(); |
| 47 | |
| 48 | if ( $logger ) { |
| 49 | $logger->error( |
| 50 | $summary, |
| 51 | array( |
| 52 | 'source' => 'wc-type-check-utility', |
| 53 | 'backtrace' => true, |
| 54 | ) |
| 55 | ); |
| 56 | } |
| 57 | |
| 58 | // Invoke the $on_failure handler, if specified. |
| 59 | if ( null !== $on_failure ) { |
| 60 | return $on_failure( $thing, $desired_type ); |
| 61 | } |
| 62 | |
| 63 | throw new InvalidArgumentException( esc_html( $summary ) ); |
| 64 | } |
| 65 | } |
| 66 |