Skip to content

Commit

Permalink
Handle situation where the error validations are coming from a dingo …
Browse files Browse the repository at this point in the history
…store resource failed exception, and the errors are in a messagebag.

Specify default key case, in case it's not set in api.php
  • Loading branch information
specialtactics committed Jul 4, 2019
1 parent d267729 commit e4a9d69
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/APIBoilerplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class APIBoilerplate
*/
const CAMEL_CASE = 'camel-case';
const SNAKE_CASE = 'snake-case';
const DEFAULT_CASE = self::CAMEL_CASE;

/**
* Case type config path
Expand Down
15 changes: 13 additions & 2 deletions src/Exceptions/RestfulApiExceptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ protected function prepareReplacements(Exception $exception)
$replacements = parent::prepareReplacements($exception);

// Format error message field keys
if ($exception instanceof \Illuminate\Validation\ValidationException) {
if ($exception instanceof \Illuminate\Validation\ValidationException || $exception instanceof \Dingo\Api\Exception\StoreResourceFailedException) {
$replacements = $this->formatCaseOfValidationMessages($replacements);
}

Expand All @@ -52,12 +52,23 @@ protected function formatCaseOfValidationMessages($replacements)
if (array_key_exists($errorKey, $replacements)) {
$errorMessages = $replacements[$errorKey];

if (Config(APIBoilerplate::CASE_TYPE_CONFIG_PATH) == APIBoilerplate::CAMEL_CASE) {
// Handle MessageBag situation
$usingMessageBag = false;
if (!is_array($errorMessages) && $errorMessages instanceof \Illuminate\Support\MessageBag) {
$errorMessages = $errorMessages->toArray();
$usingMessageBag = true;
}

if (Config(APIBoilerplate::CASE_TYPE_CONFIG_PATH, APIBoilerplate::DEFAULT_CASE) == APIBoilerplate::CAMEL_CASE) {
$errorMessages = camel_case_array_keys($errorMessages);
} else {
$errorMessages = snake_case_array_keys($errorMessages);
}

if ($usingMessageBag) {
$errorMessages = new \Illuminate\Support\MessageBag($errorMessages);
}

$replacements[$errorKey] = $errorMessages;
}

Expand Down

0 comments on commit e4a9d69

Please sign in to comment.