1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132:
<?php
namespace Teto\Object;
trait TypeAssert
{
protected static function assertValue($expected_type, $name, $value, $is_nullable)
{
if ($is_nullable && $value === null) {
return;
} elseif ($expected_type === 'mixed') {
return;
} elseif ($expected_type === 'enum') {
if (!isset(self::$enum_values) || !isset(self::$enum_values[$name])) {
new \LogicException("Doesn't set self::\$enum_values[$name]");
}
if (in_array($value, self::$enum_values[$name], true)) {
return;
}
$expects = '['. implode(', ', self::$enum_values[$name]) . ']';
throw new \InvalidArgumentException(self::message($expects, $value, $name));
} elseif (
($expected_type === 'int' && is_int($value))
|| ($expected_type === 'string' && is_string($value))
|| ($expected_type === 'float' && is_float($value))
|| ($expected_type === 'array' && is_array($value))
|| ($expected_type === 'bool' && is_bool($value))
|| ($expected_type === 'object' && is_object($value))
|| ($expected_type === 'scalar' && is_scalar($value))
|| ($expected_type === 'callable' && is_callable($value))
|| ($expected_type === 'resource' && is_resource($value))
) {
return;
} elseif (is_object($value) && $value instanceof $expected_type) {
return;
}
throw new \InvalidArgumentException(self::message($expected_type, $value, $name));
}
protected static function assertInt($value, $name = null)
{
if (!is_int($value)) {
throw new \InvalidArgumentException(self::message('int', $value, $name));
}
}
protected static function assertString($value, $name = null)
{
if (!is_string($value)) {
throw new \InvalidArgumentException(self::message('string', $value, $name));
}
}
protected static function assertArrayOrObject($value, $name = null)
{
if (!is_array($value) && !$value instanceof \ArrayAccess) {
throw new \InvalidArgumentException(self::message('array or ArrayAccess', $value, $name));
}
}
protected static function assertInstanceOf($value, $class, $name = null)
{
if (!$value instanceof $class) {
throw new \InvalidArgumentException(self::message($class, $value, $name));
}
}
private static function message($expected_type, $value, $name)
{
$type = is_object($value) ? get_class($value) : gettype($value);
$vars = ($name === null) ? $type : "$name as $type";
return "got \$$vars (expects $expected_type)";
}
}