Stringify recursively with maximum depth

This commit is contained in:
Marcel Voigt 2015-08-08 20:36:31 +02:00 committed by Henrique Moody
parent 743fafb31b
commit 2de6e0136c
3 changed files with 54 additions and 4 deletions

View file

@ -27,6 +27,10 @@ class ValidationException extends InvalidArgumentException implements Validation
self::STANDARD => 'Data validation failed for %s',
),
);
/**
* @var int Maximum depth when stringifying nested arrays
*/
private static $maxDepthStringify = 3;
protected $id = 'validation';
protected $mode = self::MODE_DEFAULT;
protected $name = '';
@ -49,7 +53,7 @@ class ValidationException extends InvalidArgumentException implements Validation
if (is_string($value)) {
return $value;
} elseif (is_array($value)) {
return 'Array'; //FIXME
return self::stringifyArray($value);
} elseif (is_object($value)) {
return static::stringifyObject($value);
} else {
@ -57,6 +61,34 @@ class ValidationException extends InvalidArgumentException implements Validation
}
}
/**
* @param array $value
* @param int $depth
*
* @return string
*/
private static function stringifyArray($value, $depth = 0)
{
$items = array();
foreach ($value as $val) {
if (is_object($val)) {
$items[] = self::stringifyObject($val);
} elseif (is_array($val)) {
if ($depth >= self::$maxDepthStringify) {
$items[] = '...';
} else {
$items[] = '('.self::stringifyArray($val, $depth + 1).')';
}
} elseif (is_string($val)) {
$items[] = "'$val'";
} else {
$items[] = (string) $val;
}
}
return implode(', ', $items);
}
public static function stringifyObject($value)
{
if (method_exists($value, '__toString')) {

View file

@ -94,9 +94,17 @@ class ValidationExceptionTest extends \PHPUnit_Framework_TestCase
return array(
array('foo', 'foo'),
array(123, '123'),
array(array(), 'Array'),
array(new \stdClass(), 'Object of class stdClass'),
array($x = new \DateTime(), $x->format('Y-m-d H:i:s')),
array(array(), ''),
array(array(array(), 'foo'), "(), 'foo'"),
array(array(array(1), 'foo'), "(1), 'foo'"),
array(array(1, array(2, array(3))), "1, (2, (3))"),
array(array(1, array(2, array(3, array(4)))), "1, (2, (3, (4)))"),
array(array(1, array(2, array(3, array(4, array(5))))), "1, (2, (3, (4, ...)))"),
array(array('foo', 'bar'), "'foo', 'bar'"),
array(array('foo', -1), "'foo', -1"),
array(array(new \stdClass, "foo"), "Object of class stdClass, 'foo'"),
array(new \stdClass, 'Object of class stdClass'),
array($x = new \DateTime, $x->format('Y-m-d H:i:s')),
);
}

View file

@ -35,6 +35,16 @@ class InTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($v->assert($input));
}
/**
* @expectedException Respect\Validation\Exceptions\InException
* @expectedExceptionMessage "x" must be in ('foo', 'bar')
*/
public function testInCheckExceptionMessageWithArray()
{
$v = new In(array('foo', 'bar'));
$v->assert('x');
}
public function providerForIn()
{
return array(