respect-validation/library/Respect/Validation/Exceptions/ValidationException.php

90 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace Respect\Validation\Exceptions;
use \InvalidArgumentException;
2010-12-03 22:36:46 +01:00
use \Exception;
use \RecursiveTreeIterator;
use Respect\Validation\ExceptionIterator;
class ValidationException extends InvalidArgumentException
{
public static $defaultTemplates = array(
'Data validation failed: "%s"'
);
protected $related = array();
protected $params = array();
2010-12-03 22:36:46 +01:00
public static function create()
{
$instance = new static;
$params = func_get_args();
if (!empty($params))
$instance->configure($params);
return $instance;
}
2010-12-03 01:23:02 +01:00
public function configure()
{
2010-12-03 01:23:02 +01:00
$this->params = array_map(
function($mixed) {
return is_object($mixed) ? get_class($mixed) : strval($mixed);
}, func_get_args()
);
$this->message = $this->getMainMessage();
return $this;
}
2010-12-03 01:23:02 +01:00
public function chooseTemplate()
{
2010-12-03 01:23:02 +01:00
return array_shift(array_keys(static::$defaultTemplates));
}
public function getFullMessage()
{
$message = array();
foreach (new RecursiveTreeIterator(new ExceptionIterator($this)) as $m)
$message[] = $m;
return implode(PHP_EOL, $message);
}
public function getMainMessage()
{
2010-12-03 01:23:02 +01:00
$sprintfParams = $this->params;
array_unshift($sprintfParams, $this->getTemplate());
return call_user_func_array('sprintf', $sprintfParams);
}
public function getRelated()
{
return $this->related;
}
public function setRelated(array $relatedExceptions)
{
2010-12-03 01:23:02 +01:00
foreach ($relatedExceptions as $related)
$this->addRelated($related);
return $this;
}
public function addRelated(Exception $related)
{
2010-12-03 01:23:02 +01:00
$this->related[] = $related;
2010-12-03 22:36:46 +01:00
return $this;
}
public function getTemplate()
{
$templateKey = call_user_func_array(
array($this, 'chooseTemplate'), $this->params
);
return static::$defaultTemplates[$templateKey];
}
public function __toString()
{
return $this->getMainMessage();
}
}