/**
  * @param UserInterface $userEntity
  * @param string $type
  * @param int|null $expire
  *
  * @return string
  */
 public function setCode4User(UserInterface $userEntity, $type, $expire = null)
 {
     $entityManager = $this->entityManager;
     $this->getRepositoryManager()->deleteCodes4User($userEntity->getId(), $type);
     do {
         $found = false;
         $code = $this->formatService->getCode();
         if ($this->getRepositoryManager()->getCode($code)) {
             $found = true;
         }
     } while ($found);
     $userCodesEntity = new Entity();
     $userCodesEntity->setCode($code)->setUser($userEntity)->setType($type);
     if (!$expire) {
         $expireOption = $this->collectionOptions->getUserCodesOptions()->getExpire();
         if (isset($expireOption[$type])) {
             $expire = $expireOption[$type];
         } else {
             $expire = $expireOption['general'];
         }
     }
     if ($expire) {
         $dateTime = new DateTime();
         $userCodesEntity->setExpire($dateTime->setTimestamp(time() + $expire));
     }
     $entityManager->persist($userCodesEntity);
     $entityManager->flush();
     return $code;
 }