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

97 lines
2.5 KiB
PHP
Raw Normal View History

2010-12-03 22:36:46 +01:00
<?php
namespace Respect\Validation\Exceptions;
use RecursiveIteratorIterator;
use RecursiveTreeIterator;
use Respect\Validation\ExceptionIterator;
2010-12-03 22:36:46 +01:00
class AbstractNestedException extends ValidationException
2010-12-03 22:36:46 +01:00
{
const ITERATE_TREE = 1;
const ITERATE_ALL = 2;
protected $related = array();
2010-12-03 22:36:46 +01:00
public function addRelated(ValidationException $related)
{
2011-02-20 19:03:09 +01:00
$this->related[spl_object_hash($related)] = $related;
return $this;
}
public function findMessages(array $paths)
{
$messages = array();
foreach ($paths as $key => $value) {
$numericKey = is_numeric($key);
$path = $numericKey ? $value : $key;
$e = $this->findRelated($path);
2011-05-03 00:35:08 +02:00
if (is_object($e) && !$numericKey)
$e->setTemplate($value);
$path = str_replace('.', '_', $path);
$messages[$path] = $e ? $e->getMainMessage() : '';
}
return $messages;
}
public function findRelated($path)
{
$target = $this;
$path = explode('.', $path);
while (!empty($path) && $target !== false)
$target = $target->getRelatedByName(array_shift($path));
return $target;
}
public function getIterator($full=false, $mode=self::ITERATE_ALL)
{
$exceptionIterator = new ExceptionIterator($this, $full);
if ($mode == self::ITERATE_ALL)
return new RecursiveIteratorIterator($exceptionIterator, 1);
else
return new RecursiveTreeIterator($exceptionIterator);
}
public function getFullMessage()
{
$message = array();
$iterator = $this->getIterator(false, self::ITERATE_TREE);
foreach ($iterator as $m)
$message[] = $m;
return implode(PHP_EOL, $message);
}
public function getRelated($full=false)
{
if (!$full && 1 === count($this->related)
&& current($this->related) instanceof AbstractNestedException)
return current($this->related)->getRelated();
else
return $this->related;
}
public function getRelatedByName($name)
2010-12-03 22:36:46 +01:00
{
foreach ($this->getIterator(true) as $e)
if ($e->getId() === $name || $e->getName() === $name)
return $e;
return false;
2010-12-03 22:36:46 +01:00
}
public function setRelated(array $relatedExceptions)
{
foreach ($relatedExceptions as $related)
$this->addRelated($related);
2011-02-19 20:47:34 +01:00
return $this;
}
}