PHPLIB-511: Allow passing multiple types to InvalidArgumentException

parent 8567a314
...@@ -18,8 +18,12 @@ ...@@ -18,8 +18,12 @@
namespace MongoDB\Exception; namespace MongoDB\Exception;
use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException; use MongoDB\Driver\Exception\InvalidArgumentException as DriverInvalidArgumentException;
use function array_pop;
use function count;
use function get_class; use function get_class;
use function gettype; use function gettype;
use function implode;
use function is_array;
use function is_object; use function is_object;
use function sprintf; use function sprintf;
...@@ -30,11 +34,30 @@ class InvalidArgumentException extends DriverInvalidArgumentException implements ...@@ -30,11 +34,30 @@ class InvalidArgumentException extends DriverInvalidArgumentException implements
* *
* @param string $name Name of the argument or option * @param string $name Name of the argument or option
* @param mixed $value Actual value (used to derive the type) * @param mixed $value Actual value (used to derive the type)
* @param string $expectedType Expected type * @param string|string[] $expectedType Expected type
* @return self * @return self
*/ */
public static function invalidType($name, $value, $expectedType) public static function invalidType($name, $value, $expectedType)
{ {
if (is_array($expectedType)) {
switch (count($expectedType)) {
case 1:
$typeString = array_pop($expectedType);
break;
case 2:
$typeString = implode('" or "', $expectedType);
break;
default:
$lastType = array_pop($expectedType);
$typeString = sprintf('%s", or "%s', implode('", "', $expectedType), $lastType);
break;
}
$expectedType = $typeString;
}
return new static(sprintf('Expected %s to have type "%s" but found "%s"', $name, $expectedType, is_object($value) ? get_class($value) : gettype($value))); return new static(sprintf('Expected %s to have type "%s" but found "%s"', $name, $expectedType, is_object($value) ? get_class($value) : gettype($value)));
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment