Skip to content

Commit

Permalink
Add api violation exception
Browse files Browse the repository at this point in the history
  • Loading branch information
lbacik committed Jan 16, 2025
1 parent 2c6fa01 commit fbe190b
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/SDK/ClientRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@

namespace JsonHub\SDK;

use JsonException;
use JsonHub\SDK\Client\MapperService;
use JsonHub\SDK\ClientRequest\JsonHubConnector;
use JsonHub\SDK\ClientRequest\RequestCollection;
use JsonHub\SDK\Exception\ApiViolationException;
use JsonHub\SDK\Exception\UnauthorizedException;
use RuntimeException;
use Saloon\Http\Response;

class ClientRequest
{
Expand All @@ -32,6 +35,7 @@ public function request(
match ($response->status()) {
200, 201, 204 => null,
401 => throw UnauthorizedException::create(),
422 => $this->mapResponseToException($response),
default => throw new RuntimeException('Response status code', $response->status()),
};

Expand All @@ -57,4 +61,19 @@ private function extractFromJsonLD(string $json): string
$this->lastQueryCount = $data['hydra:totalItems'] ?? -1;
return isset($data['hydra:member']) ? json_encode($data['hydra:member']) : $json;
}

/** @throws ApiViolationException|JsonException */
private function mapResponseToException(Response $response): void
{
$parsedResponse = json_decode($response->body(), true, 512, JSON_THROW_ON_ERROR);

$violations = $parsedResponse['violations'] ?? [];

$result = [];
foreach ($violations as $violation) {
$result[$violation['propertyPath']] = $violation['message'];
}

throw ApiViolationException::violations($result);
}
}
31 changes: 31 additions & 0 deletions src/SDK/Exception/ApiViolationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace JsonHub\SDK\Exception;

class ApiViolationException extends \RuntimeException
{
private array $violations;

public function getViolations(): array
{
return $this->violations;
}

private function addViolation(string $field, string $violation): void
{
$this->violations[$field] = $violation;
}

public static function violations(array $lines): self
{
$exception = new self();

foreach ($lines as $field => $violation) {
$exception->addViolation($field, $violation);
}

return $exception;
}
}

0 comments on commit fbe190b

Please sign in to comment.