/**
* Processes the form and build the Response object
*
* @param Request $request
* @param Organization $organization
* @return Response|static
* @throws BadRequestHttpException
*/
public function processForm(Request $request, Organization $organization)
{
$statusCode = !$this->em->contains($organization) ? 201 : 204;
$form = $this->container->get('form.factory')->create(OrganizationType::class, $organization);
$formData = json_decode($request->getContent(), true);
$form->submit($this->prepareFormData($formData));
if (!$form->isValid()) {
return View::create($form, 400);
}
if (!$this->em->contains($organization)) {
$this->em->persist($organization);
}
try {
$this->em->flush();
} catch (\Exception $e) {
$pdoException = $e->getPrevious();
// unique constraint
if ($pdoException->getCode() === '23000') {
throw new BadRequestHttpException('Error 23000!');
}
throw new BadRequestHttpException('Unknown error code: ' . $pdoException->getCode());
}
$response = new Response();
$response->setStatusCode($statusCode);
if (201 === $statusCode) {
$response->headers->set('Access-Control-Expose-Headers', 'Location');
$response->headers->set('Location', $this->container->get('router')->generate('api_v1_get_organization', ['organization' => $organization->getId()], UrlGeneratorInterface::RELATIVE_PATH));
}
return $response;
}