/** * @param EntityManager $em * @param int $conversation_id * @param int $user_id * @param string $message * @return Message */ public static function addNewMessage(EntityManager $em, $conversation_id, $user_id, $message) { $conversation = $em->find('NaidusvoeBundle:Conversation', $conversation_id); $user = $em->find('NaidusvoeBundle:User', $user_id); $newMessage = new Message(); $newMessage->setUser($user); $newMessage->setConversation($conversation); $newMessage->setMessage($message); $em->persist($newMessage); $em->flush(); return $newMessage; }
/** * @Security("has_role('ROLE_USER')") * @Route("/message/send/{adv_id}-{user_id}", name="message-send", options={"expose"=true}) * @param Request $request * @param int $user_id * @param int $adv_id * @return JsonResponse */ public function sendMessageAction(Request $request, $user_id, $adv_id) { $data = json_decode($request->getContent(), true); $message = $data['message']; /** @var User $user */ $user = $this->getUser(); /** @var EntityManager $em */ $em = $this->getDoctrine()->getManager(); $conversation = Conversation::getConversation($em, $user->getId(), $user_id, $adv_id); if (count($conversation) == 0) { $conversation = Conversation::addConversation($em, $user->getId(), $user_id, $adv_id); } else { $conversation = $conversation[0]; } try { $message = Message::addNewMessage($em, $conversation->getId(), $user->getId(), $message); $userRecipient = $conversation->getUser1(); if ($userRecipient->getId() === $user->getId()) { $userRecipient = $conversation->getUser2(); } $this->get('naidusvoe.notifier')->addNotification([$userRecipient], Notification::CONVERSATION_NOTIFICATION, ['conversationId' => $conversation->getId(), 'messageId' => $message->getId(), 'userInitiatorId' => $user->getId()]); Conversation::updateConversation($em, $conversation->getId()); } catch (\Exception $ex) { $from = 'class: Message, function: addNewMessage'; $this->get('error_logger')->registerException($ex, $from); return new JsonResponse(false); } return new JsonResponse($message->getInArray()); }