public function addCustomAction() { if ($this->_request->isPost()) { $addQuoteForm = new \App\Form\AddQuote(); if ($addQuoteForm->isValid($this->_request->getPost())) { $values = $addQuoteForm->getValues(); $newQuote = new \App\Entity\Quote(); $newQuote->setWording($values['quote']); $newQuote->setAuthor($values['name']); try { $this->_em->persist($newQuote); $this->_em->flush(); $this->indexQuote($newQuote); } catch (Exception $e) { $this->_redirect('/'); } } else { $addQuoteForm->buildBootstrapErrorDecorators(); } $data = $this->_em->getRepository("\\App\\Entity\\Quote")->findThemAll(); $this->view->data = $data; $this->_helper->viewRenderer('index'); } else { $this->_redirect('/'); } }
public function registraContacto(ContactoDTO $to) { $contacto = new Contacto($to->getId()); $contacto->setNombre($to->getNombre()); $contacto->setApellido($to->getApellido()); $contacto->setTelefono($to->getTelefono()); $contacto->setAsunto($to->getAsunto()); $contacto->setMensaje($to->getMensaje()); $contacto; try { $this->em->persist($contacto); $this->em->flush(); } catch (ORMInvalidArgumentException $exc) { echo '<pre>'; print_r($exc->getTraceAsString()); } catch (\Doctrine\ORM\ORMException $exc) { echo '<pre>'; print_r($exc->getTraceAsString()); echo '<pre>'; print_r($exc->getTrace()); } catch (Exception $e) { echo '<pre>'; print_r($e->getTraceAsString()); } //return $contacto->getIdContact(); }
public function fixturesAction() { $c1 = new \Models\Entity\Categoria(); $c1->setName('categoria 1'); $this->em->persist($c1); $c2 = new \Models\Entity\Categoria(); $c2->setName('categoria 2'); $this->em->persist($c2); $c3 = new \Models\Entity\Categoria(); $c3->setName('categoria 3'); $this->em->persist($c3); // crando 12 fabricantes aleatoriamente foreach (range(1, 12) as $n) { $f = 'f' . $n; ${$f} = new \Models\Entity\Fabricante(); ${$f}->setName('Fabricante ' . $n); $cat = 'c' . rand(1, 3); ${$f}->setCategoria(${$cat}); $this->em->persist(${$f}); } //creando 50 productos aleatoriamente foreach (range(1, 50) as $n) { $p = 'p' . $n; ${$p} = new \Models\Entity\Producto(); ${$p}->setName('Producto ' . $n); $fab = 'f' . rand(1, 12); ${$p}->setFabricante(${$fab}); $this->em->persist(${$p}); } $this->em->flush(); $this->_redirect('/'); }
/** * * @param \calavera\customerBundle\DTO\CustomerDTO $customer */ public function registerNewsletter(\calavera\customerBundle\DTO\NewsletterDTO $newsletter) { $subscription = new NewsletterSubscription(); $gender = new CatGender(); $status = new CatNewsletterStatus(); $gender->setGender($newsletter->getGender()); $dql = "select s from \\calavera\\customerBundle\\Entity\\CatNewsletterStatus s where s.status = 'subscribed'"; try { $query = $this->em->createQuery($dql); $status = $query->getOneOrNullResult(); } catch (\Doctrine\ORM\ORMException $orme) { echo $orme->getTraceAsString(); } catch (\Doctrine\ORM\NoResultException $nre) { } catch (\Doctrine\ORM\ORMInvalidArgumentException $ormiae) { } $subscription->setIdNewsletterStatus($status); $subscription->setEmail($newsletter->getEmail()); $subscription->getGener(); $dql = ""; try { $this->em->persist($subscription); $this->em->flush(); $status = "Ha sido registrado en nuestro newsletter"; } catch (\Doctrine\ORM\ORMException $orme) { echo $orme->getTraceAsString(); $status = "No pudo ser registrado en nuestro newsletter."; } catch (\Doctrine\ORM\NoResultException $nre) { $status = "No pudo ser registrado en nuestro newsletter."; } catch (\Doctrine\ORM\ORMInvalidArgumentException $ormiae) { $status = "No pudo ser registrado en nuestro newsletter."; } catch (\Exception $e) { $status = "No pudo ser registrado en nuestro newsletter."; } return $status; }
public function testCheckInvalidDate() { $token = new UserToken($this->user, 'test', 'qwerty'); $this->em->persist($token); $this->em->flush(); $property = new \ReflectionProperty($token, 'created'); $property->setAccessible(true); $property->setValue($token, new \DateTime('-3 days')); $this->assertFalse($this->service->checkToken($this->user, 'qwerty', 'test')); }
public function testFind() { foreach (array('tic', 'tic tac', 'tac', 'tac toc', 'toc') as $description) { $image = new LocalImage($description); $image->setDescription($description); $this->orm->persist($image); } $this->orm->flush(); $this->assertEquals(2, count($this->service->find('tic'))); }
public function insert(\Entity\Voluntario $voluntario) { try { $this->em->persist($voluntario); $this->em->flush(); return true; } catch (Exception $ex) { $this->CI->log->write_log('error', $ex->getMessage() . ' - voluntario_dao::insert '); } return false; }
public function insert(\Entity\Avaliador $avaliador) { try { $this->em->persist($avaliador); $this->em->flush(); return true; } catch (Exception $ex) { $this->CI->log->write_log('error', $ex->getMessage() . ' - avaliador_dao::insert '); } return false; }
public function insert(\Entity\Ouvinte $ouvinte) { try { $this->em->persist($ouvinte); $this->em->flush(); return true; } catch (Exception $ex) { $this->CI->log->write_log('error', $ex->getMessage() . ' - ouvinte_dao::insert '); } return false; }
private function loadBaseInventory() { foreach (self::$inventoryArray as $inventoryArray) { $item = new Inventory(); $item->setItemDescription($inventoryArray['description']); $item->setItemName($inventoryArray['name']); $item->setPrice($inventoryArray['price']); $item->setQuantityInStock($inventoryArray['quantity']); $this->em->persist($item); } $this->em->flush(); }
public function register($name, $email, $login, $password) { if ($this->getUser($login) != null) { return "User with login '{$login}' already exists"; } $u = new \Model\User(); $u->setEmail($email); $u->setLogin($login); $u->setName($name); $u->setPassword($password); $this->entityManager->persist($u); $this->entityManager->flush(); return true; }
public function delete($id) { try { $curso = $this->find_one_by($id); if ($curso) { $this->em->remove($curso); $this->em->flush(); } return true; } catch (Exception $ex) { $this->CI->log->write_log('error', $ex->getMessage() . ' - curso_dao::delete '); } return false; }
public function testTwoSameManagers() { $em1Article = new \Sluggable\Fixture\Article(); $em1Article->setCode('code'); $em1Article->setTitle('title'); $this->em1->persist($em1Article); $this->em1->flush(); $this->assertEquals('title-code', $em1Article->getSlug()); $user = new \Mapping\Fixture\Yaml\User(); $user->setUsername('user'); $user->setPassword('secret'); $this->em2->persist($user); $this->em2->flush(); $this->assertEquals(1, $user->getId()); }
/** * adiciona o usuário já cadastrado ao papel de orientador * @param int $campus_id o id do campus no banco * @param int tipo_servidor 1 - Docente, 2 - Técnico administrativo * @return void */ public function fazerCadastroIncremental($campus_id, $tipoServidor) { $this->em->beginTransaction(); try { $session_user = $this->usuario_bo->getUserSession(); $user = $this->usuario_bo->findUserById($session_user['id']); $orientador_orig = $this->orientador_dao->find_orientador_by_cpf($user->getCpf()); if ($orientador_orig != NULL) { $this->CI->session->set_flashdata('erro', 'Este orientador já existe.'); throw new Exception("Este orientador já existe", 2); } $orientador = new Entity\Orientador(); $orientador->setUsuario($user); $orientador->setTipoServidor($tipoServidor); $this->fazerCadastroOrientadorAux($orientador, $campus_id); $this->em->flush(); $this->em->refresh($user); $this->usuario_bo->redefinirUserRegras($user->getIdUsuario()); sendEmailAfterRecordUser($user->getCpf(), $user->getNome(), $user->getEmail(), "orientador"); return $user->getIdUsuario(); } catch (Exception $ex) { $this->CI->log->write_log('error', $ex->getMessage()); $this->em->getConnection()->rollBack(); } }
/** * validates users if invited to use the beta site * @param string $email * @param string $token * * @return self */ public function authenticate($email, $token) { $invite = $this->entityManager->getRepository('BugglMainBundle:BetaInvite')->retrieveByEmailAndToken($email, $token); $this->allowed = !is_null($invite); if ($this->allowed) { $name = $this->constants->get('buggl_beta_authenticated'); $this->session->set($name, true); $this->session->set('beta_invite_email', $email); $this->session->set('beta_invite_token', $token); if ($invite->getStatus() == $this->constants->get('BETA_INVITE_PENDING')) { $invite->setStatus($this->constants->get('BETA_INVITE_ACCEPTED')); $this->entityManager->flush(); } } return $this; }
public function cadastrarOuvinte(\Entity\Ouvinte $ouvinte, \Entity\Usuario $usuario, $instituicao_id, $campus_id, $curso_id) { $this->em->getConnection()->beginTransaction(); try { $ouvinte_orig = $this->ouvinte_dao->findOuvinteByCPF($usuario->getCpf()); if ($ouvinte_orig != NULL) { $this->CI->session->set_flashdata('erro', 'Este ouvinte já existe.'); throw new Exception("Este ouvinte já existe", 2); } // TODO: consultar CPF aqui, mover para um método abstrato no usuario_bo $senha = $usuario->getSenha(); $usuario->setSenha(md5($senha)); // cadastra o usuário $this->usuario_dao->insert($usuario); $ouvinte->setUsuario($usuario); $this->_fazerCadastroOuvinteAux($ouvinte, $instituicao_id, $campus_id, $curso_id); $this->em->flush(); $this->em->refresh($usuario); $this->usuario_bo->redefinirUserRegras($usuario->getIdUsuario()); sendEmailAfterRecordUser($usuario->getCpf(), $usuario->getNome(), $usuario->getEmail(), "ouvinte"); return $usuario->getIdUsuario(); } catch (Exception $ex) { $this->em->getConnection()->rollBack(); $this->CI->log->write_log('error', $ex->getMessage()); } return false; }
/** * Get rendition * * @param int $width * @param int $height * @param string $specs * @param string $name * @return Newscoop\Image\Rendition */ private function getRendition($width, $height, $specs, $name) { $rendition = new Rendition($width, $height, $specs, $name); $this->orm->persist($rendition); $this->orm->flush($rendition); return $rendition; }
/** * @param Doctrine\ORM\EntityManager $em * @param string $entityName * @param integer $count * @return \Ojs\JournalBundle\Entity\Sums */ private function saveSum($em, $entityName, $count) { $check = $em->getRepository("OjsJournalBundle:Sums")->findOneBy(array('entity' => $entityName)); $sum = $check ? $check : new Sums(); $sum->setEntity($entityName); $sum->setSum($count); $em->persist($sum); $em->flush(); }
public function editAction() { $form = new Application_Form_Stand(); $id = $this->getRequest()->getParam('id'); if ($id == null) { throw new Exception('Id must be provided for the edit action'); } $stand = $this->standRepository->findOneBy(array('id' => $id)); if ($this->getRequest()->isPost() && $form->isValid($_POST)) { $this->standRepository->saveStand($stand, $form->getValues()); $this->entityManager->flush(); $this->_helper->flashMessenger->addMessage('Stand saved.'); return $this->_redirect('/stand/list'); } $form->setDefaultsFromEntity($stand); // pass values to form $this->view->form = $form; }
public function testFindBy() { $this->assertEquals(0, count($this->service->findBy(array()))); $this->assertEquals(0, $this->service->getCountBy(array())); $this->orm->persist(new LocalImage(self::PICTURE_LANDSCAPE)); $this->orm->persist(new LocalImage('file://' . realpath(APPLICATION_PATH . '/../' . self::PICTURE_LANDSCAPE))); $this->orm->flush(); $this->assertEquals(2, count($this->service->findBy(array()))); $this->assertEquals(2, $this->service->getCountBy(array())); }
/** * Commits the current transaction, writing any unflushed changes to the database. * If the commit fails, the running transaction is rolled back. * * @throws Doctrine\DBAL\ConnectionException If the commit failed due to no active transaction or * because the transaction was marked for rollback only. * @throws Doctrine\ORM\OptimisticLockException If a version check on an entity that * makes use of optimistic locking fails. */ public function commit() { try { $this->_em->flush(); $this->_conn->commit(); } catch (Exception $e) { $this->rollback(); throw $e; } }
/** * Upload image and create entity * * @param UploadedFile $file * @param array $attributes * * @return Local */ public function upload(UploadedFile $file, array $attributes) { $filesystem = new Filesystem(); $imagine = new Imagine(); $errors = array(); $mimeType = $file->getClientMimeType(); if (!in_array($mimeType, $this->supportedTypes)) { $errors[] = $this->translator->trans('ads.error.unsupportedType', array('%type%' => $mimeType)); } if (!file_exists($this->config['image_path']) || !is_writable($this->config['image_path'])) { $errors[] = $this->translator->trans('ads.error.notwritable', array('%dir%' => $this->config['image_dir'])); } if (!file_exists($this->config['thumbnail_path']) || !is_writable($this->config['thumbnail_path'])) { $errors[] = $this->translator->trans('ads.error.notwritable', array('%dir%' => $this->config['thumbnail_dir'])); } if (!empty($errors)) { return $errors; } $attributes = array_merge(array('content_type' => $mimeType), $attributes); $image = new Image($file->getClientOriginalName()); $this->orm->persist($image); $this->fillImage($image, $attributes); $this->orm->flush(); $imagePath = $this->generateImagePath($image->getId(), $file->getClientOriginalExtension()); $thumbnailPath = $this->generateThumbnailPath($image->getId(), $file->getClientOriginalExtension()); $image->setBasename($this->generateImagePath($image->getId(), $file->getClientOriginalExtension(), true)); $image->setThumbnailPath($this->generateThumbnailPath($image->getId(), $file->getClientOriginalExtension(), true)); $this->orm->flush(); try { $file->move($this->config['image_path'], $this->generateImagePath($image->getId(), $file->getClientOriginalExtension(), true)); $filesystem->chmod($imagePath, 0644); $imagine->open($imagePath)->resize(new Box($this->config['thumbnail_max_size'], $this->config['thumbnail_max_size']))->save($thumbnailPath, array()); $filesystem->chmod($thumbnailPath, 0644); } catch (\Exceptiom $e) { $filesystem->remove($imagePath); $filesystem->remove($thumbnailPath); $this->orm->remove($image); $this->orm->flush(); return array($e->getMessage()); } return $image; }
public function testGetPublicUserCount() { $this->assertEquals(0, $this->service->getPublicUserCount()); $this->user->setActive(); $this->em->persist($this->user); $this->em->flush(); $this->assertEquals(0, $this->service->getPublicUserCount()); $this->user->setPublic(); $this->em->flush(); $this->assertEquals(1, $this->service->getPublicUserCount()); }
/** * Set renditions labels * * @param array $labels * @return void */ public function setRenditionsLabels(array $labels) { $renditions = $this->getRenditions(); foreach ($labels as $renditionName => $label) { if (array_key_exists($renditionName, $renditions)) { $renditions[$renditionName]->setLabel($label); } } $this->orm->flush(); $this->renditions = null; }
/** * Add addtional Jobs so we can test record limits and pagers. * * @param Doctrine\ORM\EntityManager $manager * @param Job $job */ protected function duplicateLastJob($manager, $job) { for ($i = 100; $i <= 130; $i++) { $jobClone = clone $job; $jobClone->setCompany(sprintf($job->getCompany(), $i)); $jobClone->setHowToApply(sprintf($job->getHowToApply(), $i)); $jobClone->setToken(sprintf($job->getToken(), $i)); $manager->persist($jobClone); $manager->flush(); } }
private function addUser() { $user = new User(); $user->username = '******'; $user->password = md5('apple'); $user->name = 'Steve <b>Jobs</b>'; $user->valid = 1; $user->role = 'admin'; $this->em->persist($user); $this->em->flush(); return $user; }
/** * Get default article image * * @param int $articleNumber * * @return Newscoop\Image\ArticleImage */ public function getDefaultArticleImage($articleNumber) { $image = $this->orm->getRepository('Newscoop\\Image\\ArticleImage')->findOneBy(array('articleNumber' => (int) $articleNumber, 'isDefault' => true)); if ($image === null) { $image = $this->orm->getRepository('Newscoop\\Image\\ArticleImage')->findOneBy(array('articleNumber' => (int) $articleNumber), array('number' => 'asc')); if ($image !== null) { $image->setIsDefault(true); $this->orm->flush($image); } } return $image; }
public function testLiftEmbargoOld() { $feed = new Feed('SDA'); $this->service->addFeed($feed); $entry = $this->getEntry(array('getTitle' => 'test', 'getContent' => 'test', 'getStatus' => 'Embargoed', 'getLiftEmbargo' => new \DateTime('-2 day'))); $this->em->persist($entry); $this->em->flush(); $this->em->clear(); $this->service->updateSDA(); $loaded = $this->em->find('Newscoop\\Entity\\Ingest\\Feed\\Entry', $entry->getId()); $this->assertEquals('Usable', $loaded->getStatus()); }
/** * doLog * * @param string $type Type of log message * @param string $message The message * @param mixed $user Optional User instance, null ou 'me' (string), for get current user instance * * @return void */ public function doLog($type, $message, $user = null, $subscription = null) { if (strtolower($user) == 'me') { $user = $this->security_context->getToken()->getUser(); } if (null !== $user && !$user instanceof User) { throw new Exception('Third option must be null or instance of Coregen\\AdminBundle\\Entity\\User'); } if (null !== $subscription && !$subscription instanceof Subscription) { throw new Exception('Fourth option must be null or instance of Gpupo\\CamelSpiderBundle\\Entity\\Subscription'); } $log = new Log(); $log->setCreatedAt(new \DateTime("now")); $log->setType($type); $log->setMessage($message); if (null !== $user) { $log->setUser($user); } if (null !== $subscription) { $log->setSubscription($subscription); } $this->em->persist($log); $this->em->flush(); }
public function createCallContactSugar(ContactoDTO $to, $idCall) { $callContact = new CallsContacts(Utils::createIdSugar()); $callContact->setCallId($idCall); $callContact->setContactId($to->getId()); $callContact->setRequired('1'); $callContact->setAcceptStatus('none'); $callContact->setDateModified(Utils::getCurrentDateAndTime()); $callContact->setDeleted(FALSE); try { $this->em->persist($callContact); $this->em->flush(); } catch (Exception $exc) { echo $exc->getTraceAsString(); } }