| 1 |
<?php |
| 2 |
|
| 3 |
namespace StoreEngine\Classes\Exceptions; |
| 4 |
|
| 5 |
use StoreEngine\Utils\Helper; |
| 6 |
|
| 7 |
if ( ! defined( 'ABSPATH' ) ) { |
| 8 |
die(); |
| 9 |
} |
| 10 |
|
| 11 |
class StoreEngineInvalidArgumentException extends StoreEngineException { |
| 12 |
/** |
| 13 |
* Create a new invalid argument exception with a standardized text. |
| 14 |
* |
| 15 |
* @param int $position The argument position in the function signature. 1-based. |
| 16 |
* @param string $name The argument name in the function signature. |
| 17 |
* @param string|int|float|string[]|int[]|float[] $expected The argument type expected as a string. |
| 18 |
* @param string|int|float $received The actual argument type received. |
| 19 |
* |
| 20 |
* @return StoreEngineInvalidArgumentException |
| 21 |
*/ |
| 22 |
public static function create( int $position, string $name, $expected, $received ): StoreEngineInvalidArgumentException { |
| 23 |
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace |
| 24 |
$stack = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 ); |
| 25 |
$caller = [ |
| 26 |
'name' => 'anonymous-caller', |
| 27 |
'file' => 'unknown', |
| 28 |
]; // Stack 0 is self. |
| 29 |
|
| 30 |
if ( ! empty( $stack[1] ) ) { |
| 31 |
if ( ! empty( $stack[1]['class'] ) ) { |
| 32 |
$caller['name'] = sprintf( '%s::%s()', $stack[1]['class'], $stack[1]['function'] ); |
| 33 |
} else { |
| 34 |
$caller['name'] = sprintf( '%s()', $stack[1]['function'] ); |
| 35 |
} |
| 36 |
|
| 37 |
$caller['file'] = sprintf( 'file:: %s[L:%s]', $stack[1]['file'], $stack[1]['line'] ); |
| 38 |
} |
| 39 |
|
| 40 |
$expected = is_array( $expected ) ? Helper::implode_with( $expected, 'or' ) : $expected; |
| 41 |
if ( ! is_scalar( $expected ) ) { |
| 42 |
// If expected value is not numeric/string, get type of the expected value. |
| 43 |
$expected = gettype( $expected ); |
| 44 |
} |
| 45 |
|
| 46 |
if ( ! is_scalar( $received ) ) { |
| 47 |
$received = gettype( $received ); |
| 48 |
} |
| 49 |
|
| 50 |
return new self( |
| 51 |
sprintf( '%s: Argument #%d (%s) must be (of type) %s, %s given on %s.', $caller['name'], $position, $name, $expected, $received, $caller['file'] ), |
| 52 |
'invalid-argument', |
| 53 |
[ |
| 54 |
'received' => $received, |
| 55 |
'expected' => $expected, |
| 56 |
], |
| 57 |
400 // Can be 422 (Unprocessable Entity). |
| 58 |
); |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
// End of file store-engine-invalid-argument-exception.php. |
| 63 |
|