/**
* @param int $accountId
* @param int j$contactId
* @param Request $request
*
* @throws \Exception
*
* @return Response
*/
public function putContactsAction($accountId, $contactId, Request $request)
{
try {
// Get account.
/** @var AccountInterface $account */
$account = $this->getDoctrine()->getRepository($this->getAccountEntityName())->find($accountId);
if (!$account) {
throw new EntityNotFoundException('account', $accountId);
}
// Get contact.
$contact = $this->getDoctrine()->getRepository($this->container->getParameter('sulu.model.contact.class'))->find($contactId);
if (!$contact) {
throw new EntityNotFoundException('contact', $contactId);
}
// Check if relation already exists.
$accountContact = $this->getDoctrine()->getRepository(self::$accountContactEntityName)->findOneBy(['contact' => $contact, 'account' => $account]);
if ($accountContact) {
throw new \Exception('Relation already exists');
}
// Create relation.
$accountContact = new AccountContactEntity();
// If contact has no main relation - set as main.
$accountContact->setMain($contact->getAccountContacts()->isEmpty());
$accountContact->setAccount($account);
$accountContact->setContact($contact);
// Set position on contact.
$position = $this->getAccountManager()->getPosition($request->get('position', null));
$accountContact->setPosition($position);
$contact->setCurrentPosition($position);
$em = $this->getDoctrine()->getManager();
$em->persist($accountContact);
$em->flush();
$isMainContact = false;
if ($account->getMainContact()) {
$isMainContact = $account->getMainContact()->getId() === $contact->getId();
}
$contactArray = ['id' => $contact->getId(), 'fullName' => $contact->getFullName(), 'isMainContact' => $isMainContact];
if ($position) {
$contactArray['position'] = $position->getPosition();
}
$view = $this->view($contactArray, 200);
} catch (EntityNotFoundException $enfe) {
$view = $this->view($enfe->toArray(), 404);
} catch (RestException $exc) {
$view = $this->view($exc->toArray(), 400);
} catch (\Exception $e) {
$view = $this->view($e->getMessage(), 400);
}
return $this->handleView($view);
}