2018-01-07 21:51:25 +03:00
|
|
|
<?php
|
2019-10-05 18:26:10 +03:00
|
|
|
|
2018-01-07 21:51:25 +03:00
|
|
|
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;
|
2019-02-27 00:56:43 +03:00
|
|
|
|
2019-08-08 17:20:37 +03:00
|
|
|
use function Functional\reduce_left;
|
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
|
|
|
|
2019-08-01 20:49:54 +03:00
|
|
|
use const PHP_EOL;
|
|
|
|
|
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,
|
2019-08-01 20:49:54 +03:00
|
|
|
?Throwable $previous = null
|
2018-01-07 21:51:25 +03:00
|
|
|
) {
|
|
|
|
$this->invalidElements = $invalidElements;
|
|
|
|
parent::__construct($message, $code, $previous);
|
|
|
|
}
|
|
|
|
|
2019-08-01 20:49:54 +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);
|
|
|
|
}
|
|
|
|
|
2019-08-01 20:49:54 +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
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2019-08-08 17:20:37 +03:00
|
|
|
private static function formMessagesToString(array $messages = []): string
|
2018-01-07 21:51:25 +03:00
|
|
|
{
|
2019-08-08 17:20:37 +03:00
|
|
|
return reduce_left($messages, function ($messageSet, $name, $_, string $acc) {
|
|
|
|
return $acc . sprintf(
|
|
|
|
"\n '%s' => %s",
|
2018-01-07 21:51:25 +03:00
|
|
|
$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
|
|
|
);
|
2019-08-08 17:20:37 +03:00
|
|
|
}, '');
|
2018-01-07 21:51:25 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
public function getInvalidElements(): array
|
|
|
|
{
|
|
|
|
return $this->invalidElements;
|
|
|
|
}
|
|
|
|
}
|