Extracted function to render arrays from inside ValidationException

This commit is contained in:
Alejandro Celaya 2021-01-10 20:28:52 +01:00
parent 7a19b8765d
commit 1f2e16184c
3 changed files with 17 additions and 16 deletions

View File

@ -10,6 +10,9 @@ use Fig\Http\Message\StatusCodeInterface;
use Laminas\InputFilter\InputFilter;
use PUGX\Shortid\Factory as ShortIdFactory;
use function Functional\reduce_left;
use function is_array;
use function print_r;
use function sprintf;
const DEFAULT_DELETE_SHORT_URL_THRESHOLD = 15;
@ -75,3 +78,12 @@ function getOptionalBoolFromInputFilter(InputFilter $inputFilter, string $fieldN
$value = $inputFilter->getValue($fieldName);
return $value !== null ? (bool) $value : null;
}
function arrayToString(array $array): string
{
return reduce_left($array, fn ($messages, string $name, $_, string $acc) => $acc . sprintf(
"\n '%s' => %s",
$name,
is_array($messages) ? print_r($messages, true) : $messages,
), '');
}

View File

@ -11,9 +11,7 @@ use Mezzio\ProblemDetails\Exception\ProblemDetailsExceptionInterface;
use Throwable;
use function array_keys;
use function Functional\reduce_left;
use function is_array;
use function print_r;
use function Shlinkio\Shlink\Core\arrayToString;
use function sprintf;
use const PHP_EOL;
@ -60,19 +58,10 @@ class ValidationException extends InvalidArgumentException implements ProblemDet
$this->getMessage(),
$this->getFile(),
$this->getLine(),
$this->invalidElementsToString(),
arrayToString($this->getInvalidElements()),
PHP_EOL,
PHP_EOL,
$this->getTraceAsString(),
);
}
private function invalidElementsToString(): string
{
return reduce_left($this->getInvalidElements(), fn ($messages, string $name, $_, string $acc) => $acc . sprintf(
"\n '%s' => %s",
$name,
is_array($messages) ? print_r($messages, true) : $messages,
), '');
}
}

View File

@ -32,9 +32,9 @@ class ValidationExceptionTest extends TestCase
];
$barValue = print_r(['baz', 'foo'], true);
$expectedStringRepresentation = <<<EOT
'foo' => bar
'something' => {$barValue}
EOT;
'foo' => bar
'something' => {$barValue}
EOT;
$inputFilter = $this->prophesize(InputFilterInterface::class);
$getMessages = $inputFilter->getMessages()->willReturn($invalidData);