em = $em; $this->eventManager = $eventManager; } public function storeSms(string $hashKey, int $direction, array $requestData): bool { $normalizedDate = str_replace("at ", "", $requestData['when']); $user = $this->ensureUserExists($hashKey); $sms = new Sms(); $sms->setDirection($direction) ->setContactName($requestData['contactName']) ->setContactNumber($requestData['contactNumber']) ->setOccuredAt(new \DateTime($normalizedDate)) ->setOwner($user) ->setText($requestData['text']); $this->em->persist($sms); $this->em->flush(); $this->eventManager->trigger('store.sms.persisted', $this, [ 'sms' => $sms, ]); return true; } /** * @param string $hashKey * @return User * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException */ private function ensureUserExists(string $hashKey): User { /** @var User $user */ $user = $this->em->getRepository(User::class)->findOneBy([ 'hashKey' => $hashKey ]); if($user === null) { $user = new User(); $user->setHashKey($hashKey)->setName("Unknown"); $this->em->persist($user); $this->em->flush(); } return $user; } }