-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Create ModelFormInvalidException.php * Update ModelFormInvalidException.php
- Loading branch information
Showing
1 changed file
with
92 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace HandcraftedInTheAlps\Bundle\SuluResourceBundle\Exception; | ||
|
||
use RuntimeException; | ||
use Symfony\Component\Form\FormError; | ||
use Symfony\Component\Form\FormInterface; | ||
|
||
class ModelFormInvalidException extends RuntimeException | ||
{ | ||
/** | ||
* @var FormInterface<mixed> | ||
*/ | ||
protected $form; | ||
|
||
/** | ||
* @param FormInterface<mixed> $form | ||
*/ | ||
public function __construct(FormInterface $form) | ||
{ | ||
$this->form = $form; | ||
|
||
parent::__construct( | ||
sprintf( | ||
'Invalid form data for "%s" on form "%s": ' . json_encode($this->getErrors(), JSON_PRETTY_PRINT), | ||
\get_class($this->form->getData()), | ||
\get_class($this->form) | ||
) | ||
); | ||
} | ||
|
||
/** | ||
* @return array<string, mixed> | ||
*/ | ||
public function toArray(): array | ||
{ | ||
$message = ''; | ||
|
||
foreach ($this->getErrors() as $fieldName => $field) { | ||
$message .= ucfirst($fieldName) . ': ' . implode(',', $field['messages']) . PHP_EOL; | ||
} | ||
|
||
return [ | ||
'code' => $this->code, | ||
'message' => trim($message), | ||
'errors' => $this->getErrors(), | ||
]; | ||
} | ||
|
||
/** | ||
* @return FormInterface<mixed> | ||
*/ | ||
public function getForm(): FormInterface | ||
{ | ||
return $this->form; | ||
} | ||
|
||
/** | ||
* @return mixed[] | ||
*/ | ||
public function getErrors(): array | ||
{ | ||
$errors = []; | ||
|
||
/** @var FormError $error */ | ||
foreach ($this->form->getErrors(true) as $key => $error) { | ||
$origin = $error->getOrigin(); | ||
|
||
if (null === $origin) { | ||
continue; | ||
} | ||
|
||
$field = $origin->getName(); | ||
|
||
if (!isset($errors[$field])) { | ||
$data = $origin->getData(); | ||
$viewData = $origin->getViewData(); | ||
|
||
$errors[$field] = [ | ||
'value' => is_scalar($data) ? $data : $viewData, | ||
'messages' => [], | ||
]; | ||
} | ||
|
||
$errors[$field]['messages'][] = $error->getMessage(); | ||
} | ||
|
||
return $errors; | ||
} | ||
} |