mirror of
https://github.com/anikeen-com/id.git
synced 2026-11-07 16:18:33 +00:00
Throw ValidationFailedException with per-field codes for 422 responses
This commit is contained in:
4 files changed
+119
-2
No files matched your search
@@ -35,6 +35,11 @@ class ApiException extends ResourceException
|
||||
return PreconditionFailedException::fromResult($result);
|
||||
}
|
||||
|
||||
// refused input, with per-field codes on some endpoints
|
||||
if ($status === 422 && static::class === self::class) {
|
||||
return ValidationFailedException::fromResult($result);
|
||||
}
|
||||
|
||||
return new static(
|
||||
rtrim((string) ($body->message ?? $result->error()), '.'),
|
||||
$status,
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Anikeen\Id\Exceptions;
|
||||
|
||||
/**
|
||||
* Anikeen ID refused the input (422). `error` is the first code; endpoints with per-field codes
|
||||
* (the profile API) send them as `codes`: `{field: code}`, e.g. `["username" => "username_taken"]`.
|
||||
* Branch on the codes, the messages are for people and may change.
|
||||
*/
|
||||
class ValidationFailedException extends ApiException
|
||||
{
|
||||
/**
|
||||
* @return array<string, string> field => code; empty when the endpoint sends none
|
||||
*/
|
||||
public function errorCodes(): array
|
||||
{
|
||||
$codes = $this->body()->codes ?? null;
|
||||
|
||||
return is_object($codes) || is_array($codes) ? array_map('strval', (array) $codes) : [];
|
||||
}
|
||||
|
||||
public function errorCodeFor(string $field): ?string
|
||||
{
|
||||
return $this->errorCodes()[$field] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether any field failed with $code, or the response's `error` is $code.
|
||||
*/
|
||||
public function hasErrorCode(string $code): bool
|
||||
{
|
||||
return $this->error === $code || in_array($code, $this->errorCodes(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The messages per field (`errors`), for showing them to people.
|
||||
*
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
public function errors(): array
|
||||
{
|
||||
$errors = $this->body()->errors ?? null;
|
||||
|
||||
return is_object($errors) || is_array($errors) ? array_map(fn ($messages) => array_values((array) $messages), (array) $errors) : [];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user