2018-01-07 21:51:25 +03:00
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Shlinkio\Shlink\Core\Exception;
|
|
|
|
|
2018-10-28 10:24:06 +03:00
|
|
|
use Throwable;
|
2018-01-07 21:51:25 +03:00
|
|
|
use Zend\InputFilter\InputFilterInterface;
|
2018-10-28 10:34:02 +03:00
|
|
|
use const PHP_EOL;
|
2018-10-28 10:24:06 +03:00
|
|
|
use function is_array;
|
|
|
|
use function print_r;
|
|
|
|
use function sprintf;
|
2018-01-07 21:51:25 +03:00
|
|
|
|
|
|
|
class ValidationException extends RuntimeException
|
|
|
|
{
|
2018-11-20 21:30:27 +03:00
|
|
|
/** @var array */
|
2018-01-07 21:51:25 +03:00
|
|
|
private $invalidElements;
|
|
|
|
|
|
|
|
public function __construct(
|
|
|
|
string $message = '',
|
|
|
|
array $invalidElements = [],
|
|
|
|
int $code = 0,
|
2018-10-28 10:24:06 +03:00
|
|
|
Throwable $previous = null
|
2018-01-07 21:51:25 +03:00
|
|
|
) {
|
|
|
|
$this->invalidElements = $invalidElements;
|
|
|
|
parent::__construct($message, $code, $previous);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param InputFilterInterface $inputFilter
|
|
|
|
* @param \Throwable|null $prev
|
|
|
|
* @return ValidationException
|
|
|
|
*/
|
2018-10-28 10:24:06 +03:00
|
|
|
public static function fromInputFilter(InputFilterInterface $inputFilter, Throwable $prev = null): self
|
2018-01-07 21:51:25 +03:00
|
|
|
{
|
|
|
|
return static::fromArray($inputFilter->getMessages(), $prev);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param array $invalidData
|
|
|
|
* @param \Throwable|null $prev
|
|
|
|
* @return ValidationException
|
|
|
|
*/
|
2018-11-17 21:32:31 +03:00
|
|
|
private static function fromArray(array $invalidData, Throwable $prev = null): self
|
2018-01-07 21:51:25 +03:00
|
|
|
{
|
|
|
|
return new self(
|
2018-10-28 10:24:06 +03:00
|
|
|
sprintf(
|
2018-01-07 21:51:25 +03:00
|
|
|
'Provided data is not valid. These are the messages:%s%s%s',
|
|
|
|
PHP_EOL,
|
|
|
|
self::formMessagesToString($invalidData),
|
|
|
|
PHP_EOL
|
|
|
|
),
|
|
|
|
$invalidData,
|
|
|
|
-1,
|
|
|
|
$prev
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
private static function formMessagesToString(array $messages = [])
|
|
|
|
{
|
|
|
|
$text = '';
|
|
|
|
foreach ($messages as $name => $messageSet) {
|
2018-10-28 10:24:06 +03:00
|
|
|
$text .= sprintf(
|
2018-01-07 21:51:25 +03:00
|
|
|
"\n\t'%s' => %s",
|
|
|
|
$name,
|
2018-10-28 10:24:06 +03:00
|
|
|
is_array($messageSet) ? print_r($messageSet, true) : $messageSet
|
2018-01-07 21:51:25 +03:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return $text;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
public function getInvalidElements(): array
|
|
|
|
{
|
|
|
|
return $this->invalidElements;
|
|
|
|
}
|
|
|
|
}
|