/**
  * {@inheritDoc}
  */
 public function getOrCreateUser($email, $googleId)
 {
     if ($this->isConfiguredDomain($email)) {
         $user = $this->userFinder->findUserByGoogleSignInData($email, $googleId);
         if (!$user instanceof $this->userClass) {
             //User not present in database, create new one
             $user = new $this->userClass();
             $user->setUsername($email);
             $user->setEmail($email);
             $user->setPlainPassword($googleId . $email . time());
             $user->setEnabled(true);
             $user->setLocked(false);
             $user->setAdminLocale('en');
             $user->setPasswordChanged(true);
         }
         foreach ($this->getAccessLevels($email) as $accessLevel) {
             $user->addRole($accessLevel);
         }
         $user->setGoogleId($googleId);
         // Persist
         $this->em->persist($user);
         $this->em->flush();
     }
     return isset($user) ? $user : null;
 }
 public function testconfiguration()
 {
     $config = new Configuration();
     $config->setCurrentUser($this->ZfcUserMock);
     $prefix = "prefix";
     $config->setTablePrefix($prefix);
     $suffix = "suffix";
     $config->setTableSuffix($suffix);
     $fieldName = "fieldName";
     $config->setRevisionFieldName($fieldName);
     $revisionIdFieldType = "string";
     $config->setRevisionIdFieldType($revisionIdFieldType);
     $tableName = "tableName";
     $config->setRevisionTableName($tableName);
     $revisionTypeFieldName = "string";
     $config->setRevisionTypeFieldName($revisionTypeFieldName);
     $ipaddress = $config->getIpAddress();
     $config->setAuditedEntityClasses(array('ZF2EntityAuditTest\\Entity\\Article', 'ZF2EntityAuditTest\\Entity\\Writer'));
     $config->setNote("default note");
     $this->auditManager = new Manager($config);
     $this->auditManager->registerEvents($this->em->getEventManager());
     /// creating the tables
     $this->schemaTool = $this->getSchemaTool();
     $this->schemaTool->createSchema(array($this->em->getClassMetadata('ZF2EntityAuditTest\\Entity\\Article'), $this->em->getClassMetadata('ZF2EntityAuditTest\\Entity\\Writer')));
     $this->assertInstanceOf("ZfcUser\\Entity\\User", $this->ZfcUserMock);
     $this->assertEquals($prefix, $config->getTablePrefix());
     $this->assertEquals($suffix, $config->getTableSuffix());
     $this->assertEquals($fieldName, $config->getRevisionFieldName());
     $this->assertEquals($tableName, $config->getRevisionTableName());
     $this->assertEquals($revisionIdFieldType, $config->getRevisionIdFieldType());
     $this->assertEquals($revisionTypeFieldName, $config->getRevisionIdFieldType());
     $this->assertEquals($ipaddress, "1.1.1.9");
 }
 /**
  * @expectedException \RuntimeException
  * @expectedExceptionMessage Unable to find the mapping information for the class classname. Please check the 'auto_mapping' option (http://symfony.com/doc/current/reference/configuration/doctrine.html#configuration-overview) or add the bundle to the 'mappings' section in the doctrine configuration
  */
 public function testExceptionOnNonMappedEntity()
 {
     $registry = $this->getMock('Doctrine\\Common\\Persistence\\ManagerRegistry');
     $registry->expects($this->once())->method('getManagerForClass')->will($this->returnValue(null));
     $manager = new EntityManager('classname', $registry);
     $manager->getObjectManager();
 }
Exemple #4
0
 public function savePdf()
 {
     $pnr = $this->em->getRepository('AppCoreBundle:Pnr')->find($this->id);
     if (!$pnr) {
         return \Exception('PNR not found');
     }
     //Trick to prevent cache size exceeded
     //set_time_limit(0);
     while (ob_get_level()) {
         ob_end_clean();
     }
     ob_implicit_flush(true);
     /*
      * Construct PDF with Mpdf service
      * Layout based on HTML twig template
      */
     $service = $this->tfox;
     $pdf = $service->getMpdf(array('', 'A4', 8, 'Helvetica', 10, 10, 15, 15, 9, 9, 'L'));
     $pdf->AliasNbPages('{NBPAGES}');
     $pdf->setTitle('billet-' . date('d-m-Y-H-i', time()) . '.pdf');
     $pdf->SetHeader('Billet');
     $pdf->SetFooter('{DATE j/m/Y}|{PAGENO}/{NBPAGES}');
     $html = $this->templating->renderResponse('AppCoreBundle:Pnr:billetpdf.pdf.twig', array('pnr' => $pnr));
     $pdf->WriteHTML($html);
     //$url = 'billet-'.$pnr->getNumero().'.pdf';
     //$pdf->Output($url, 'F');
     $pdf->Output();
     /*$this->get('session')->getFlashBag()->add(
     		 'success',
     				'Le billet a bien été enregistré !'
     		);*/
     //return $this->redirect($this->generateUrl('pnr_emit', array('id' => $id)));
     //return $url;
 }
Exemple #5
0
 /**
  * Gather all entities in a given directory
  *
  * Assumes PSR-0/4 compliant entity class names, and an appropriate auto-loader is installed.
  *
  * @param string $dir       Directory to scan
  * @param string $namespace PSR base namespace for the directory
  * @param string $regex     Filter for file matching
  * @return string[]
  */
 public function locateEntities($dir, $namespace, $regex = '/^.+\\.php$/i')
 {
     $dir = str_replace('\\', '/', $dir);
     if (substr($dir, -1) != '/') {
         $dir .= '/';
     }
     $base_len = strlen($dir);
     $namespace = str_replace('/', '\\', $namespace);
     if (substr($namespace, -1) != '\\') {
         $namespace .= '\\';
     }
     $normaliser = $this->getNormaliser();
     $iterator = new \RegexIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir)), $regex, \RecursiveRegexIterator::GET_MATCH);
     $out = [];
     foreach ($iterator as $fn => $data) {
         $suffix = str_replace('/', '\\', substr($fn, $base_len));
         $class = $normaliser($namespace . $suffix);
         if (!class_exists($class)) {
             continue;
         }
         if ($this->entity_manager) {
             try {
                 $this->entity_manager->getMapper()->getEntityMetadata($class);
             } catch (\Exception $e) {
                 continue;
             }
         }
         $out[] = $class;
     }
     return $out;
 }
 /**
  * @param stdClass      $stdClass
  * @param EntityManager $manager
  *
  * @return $this
  */
 public function setFromStdClass($stdClass, $manager)
 {
     $this->id = $stdClass->id;
     $this->name = $stdClass->title;
     $this->city = $manager->find('NetworkStoreBundle:City', $stdClass->city_id);
     return $this;
 }
 /**
  * @group DDC-1439
  */
 public function testInvalidToOneJoinColumnSchema()
 {
     $class1 = $this->em->getClassMetadata(__NAMESPACE__ . '\\InvalidEntity1');
     $class2 = $this->em->getClassMetadata(__NAMESPACE__ . '\\InvalidEntity2');
     $ce = $this->validator->validateClass($class2);
     $this->assertEquals(array("The referenced column name 'id' does not have a corresponding field with this column name on the class 'Doctrine\\Tests\\ORM\\Tools\\InvalidEntity1'.", "The join columns of the association 'assoc' have to match to ALL identifier columns of the source entity 'Doctrine\\Tests\\ORM\\Tools\\InvalidEntity2', however 'key3, key4' are missing."), $ce);
 }
 public function testReverseTransform()
 {
     $transformer = $this->createTransformer();
     $tag = new Tag("name");
     $this->em->persist($tag);
     $this->em->flush();
     $this->assertSame($tag, $transformer->reverseTransform(1, null));
 }
 /**
  * Clears old webcode
  *
  * @param EntityManager $em            Entity Manager
  * @param string        $articleNumber Article
  *
  * @return void
  */
 private function clearWebcode($em, $articleNumber, $articleLanguage)
 {
     $webcode = $em->getRepository('Newscoop\\Entity\\Webcode')->createQueryBuilder('w')->leftJoin('w.article', 'a')->where('a.number = :number')->andWhere('a.language = :language')->setParameter('number', $articleNumber)->setParameter('language', $articleLanguage)->getQuery()->getOneOrNullResult();
     if ($webcode) {
         $em->remove($webcode);
         $em->flush();
     }
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     $this->em = $this->getEntityManager();
     $this->purgeDatabase();
     $this->setUpTestData();
     $this->em->flush();
     $this->client = $this->createAuthenticatedClient();
 }
 /**
  * Rollback changes.
  */
 public function tearDown()
 {
     $this->_em->rollback();
     @exec('php app/console syw:user:delete ' . $this->test1_username . ' >/dev/null 2>&1');
     @exec('php app/console syw:user:delete ' . $this->test2_username . ' >/dev/null 2>&1');
     parent::tearDown();
     $this->_em->close();
 }
 public function createSchema()
 {
     $metas = [];
     foreach (Deployment::instance()->models as $model) {
         $metas[] = $this->entityManager->getClassMetadata($model);
     }
     $this->schemaTool->createSchema($metas);
 }
 public function findOneById($area_id)
 {
     try {
         $area = $this->em->find(Area_tematica_dao::REPOSITORY, $area_id);
         return $area;
     } catch (Exception $ex) {
         $this->CI->log->write_log('error', $ex->getMessage() . ' - area_tematica_dao::findOneById ');
     }
 }
 public function getLastPosition($entity)
 {
     $query = $this->em->createQuery(sprintf('SELECT MAX(m.%s) FROM %s m', $positionFiles = $this->getPositionFieldByEntity($entity), $entity));
     $result = $query->getResult();
     if (array_key_exists(0, $result)) {
         return intval($result[0][1]);
     }
     return 0;
 }
 /** @test */
 public function should_add_new_group()
 {
     $this->repository->add(new Group(GroupId::generate(), 'Cribbb'));
     $this->em->clear();
     $group = $this->repository->groupOfName('Cribbb');
     $this->assertInstanceOf('Cribbb\\Domain\\Model\\Groups\\GroupId', $group->id());
     $this->assertEquals('Cribbb', $group->name());
     $this->assertEquals('cribbb', $group->slug());
 }
 public function insert(Entity\AvaliadorArea $avaliadorArea)
 {
     try {
         $this->em->persist($avaliadorArea);
         $this->em->flush();
     } catch (Exception $ex) {
         $this->CI->log->write_log('error', $ex->getMessage() . ' - avaliador_area_dao::insert ');
     }
 }
Exemple #17
0
 protected function getRoleChoices()
 {
     $roots = $this->em->getRepository('FpUserBundle:Role')->findAll();
     $choices = array();
     foreach ($roots as $role) {
         $choices[$role->getId()] = $role;
     }
     return $choices;
 }
Exemple #18
0
 public function load()
 {
     if ($this->loaded) {
         return true;
     }
     $this->proxy = $this->em->find($this->entity, $this->reference);
     $this->loaded = true;
     $this->em = null;
 }
 /**
  * Counts the number of entries in each tables.
  *
  * @param EntityManager $em
  * @param int $expected
  */
 protected function assertDatabaseEntries($em, $expected)
 {
     $number = $em->getRepository(self::ENTITY_TRANS_UNIT_CLASS)->createQueryBuilder('tu')->select('COUNT(tu.id)')->getQuery()->getSingleScalarResult();
     $this->assertEquals($expected, $number);
     $number = $em->getRepository(self::ENTITY_TRANSLATION_CLASS)->createQueryBuilder('t')->select('COUNT(t.id)')->getQuery()->getSingleScalarResult();
     $this->assertEquals($expected * 2, $number);
     $number = $em->getRepository(self::ENTITY_FILE_CLASS)->createQueryBuilder('f')->select('COUNT(f.id)')->getQuery()->getSingleScalarResult();
     $this->assertEquals($expected, $number);
 }
 public function testRemoveStock()
 {
     $productBefore = $this->_em->getRepository('DreamStoreSellerBundle:Product')->findOneById(1);
     $stockBefor = $productBefore->getStock();
     $table = ['operation' => 'remove', 'stock' => 5];
     $home = new HomeController();
     $productAfter = $home->addNewStock($productBefore, $table);
     $this->assertEquals($stockBefor - 5, $productAfter->getStock());
 }
Exemple #21
0
 /**
  * Find entrie in DB by given user
  *
  * @param  \Entity\User $user
  * @return array of \Entity\Post
  * @since  1.0
  */
 public function findByUser($user)
 {
     $postsData = $this->em->query('SELECT * FROM posts WHERE user_id = ' . $user->getId() . ';')->fetchAll();
     $posts = array();
     foreach ($postsData as $postData) {
         $newPost = new PostEntity();
         $posts[] = $this->mapper->populate($postData, $newPost);
     }
     return $posts;
 }
 /**
  * @var string slug
  * @throws NotFoundHttpException
  *
  * @Route("/author/{slug}")
  * @Template()
  * @return array
  */
 public function showAction($slug)
 {
     $author = $this->em->getRepository('ModelBundle:Author')->findOneBy(array('slug' => $slug));
     if ($author == null) {
         throw $this->createNotFoundException('Author Not Found');
     } else {
         $posts = $this->em->getRepository('ModelBundle:Post')->findBy(array('author' => $author));
     }
     return array('author' => $author, 'posts' => $posts);
 }
 /**
  * Borrar todas las relaciones existentes con la entidad e
  * id de entidad origen
  * 
  * @param integer $entidadOrigen El nombre la entidad origen
  * @param integer $idOrigen El id de la entidad origen
  */
 public function eraseRelaciones($entidadOrigen, $idOrigen)
 {
     $em = new EntityManager($this->getConectionName());
     if ($em->getDbLink()) {
         $query = "delete from {$this->getDataBaseName()}.{$this->getTableName()} WHERE EntidadOrigen='{$entidadOrigen}' AND IdEntidadOrigen='{$idOrigen}'";
         $em->query($query);
         $em->desConecta();
     }
     unset($em);
 }
 /**
  * Execute the query and get the first result.
  *
  * @return mixed
  */
 public function first()
 {
     if ($entity = $this->manager->hydrateOne($this->query->limit(1)->execute(), $this->metadata)) {
         foreach ($this->getRelations() as $name => $query) {
             $this->manager->related($entity, $name, $query);
         }
         return $entity;
     }
     return null;
 }
Exemple #25
0
 /**
  * Saves Entity User in DB
  *
  * @param  \Entity\User $user
  * @return \PDOStatement
  * @since  1.1
  */
 public function saveUser(\Entity\User $user)
 {
     $userMapper = new UserMapper();
     $data = $userMapper->extract($user);
     $userId = call_user_func(array($user, 'get' . ucfirst($userMapper->getIdColumn())));
     if (array_key_exists($userId, $this->identityMap['users'])) {
         return $this->em->update('users', $data, $userId, $userMapper->getIdColumn());
     }
     return $this->em->insert('users', $data);
 }
 /**
  * @param null $entity
  * @return EntityManager|array|object
  */
 public function getEm($entity = null)
 {
     if ($this->em === null) {
         $this->em = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
     }
     if ($entity !== null) {
         return $this->em->getRepository($entity);
     }
     return $this->em;
 }
 public function setUp()
 {
     $config = new \Doctrine\ORM\Configuration();
     $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     $config->setProxyDir(__DIR__ . '/_files');
     $config->setProxyNamespace('DoctrineExtensions\\LargeCollections\\Proxies');
     $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver());
     $conn = array('driver' => 'pdo_sqlite', 'memory' => true);
     #$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
     $this->em = \Doctrine\ORM\EntityManager::create($conn, $config);
     $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
     $schemaTool->createSchema(array($this->em->getClassMetadata('DoctrineExtensions\\LargeCollections\\Article'), $this->em->getClassMetadata('DoctrineExtensions\\LargeCollections\\Tag'), $this->em->getClassMetadata('DoctrineExtensions\\LargeCollections\\Comment')));
     $article = new Article();
     $tag1 = new Tag();
     $tag2 = new Tag();
     $comment1 = new Comment();
     $comment2 = new Comment();
     $article->addComment($comment1);
     $article->addComment($comment2);
     $article->addTag($tag1);
     $article->addTag($tag2);
     $this->em->persist($article);
     $this->em->persist($tag1);
     $this->em->persist($tag2);
     $this->em->persist($comment1);
     $this->em->persist($comment2);
     $this->em->flush();
     $this->articleId = $article->id();
     $this->em->clear();
 }
 public function testHistorical()
 {
     $product = $this->_em->getRepository('DreamStoreSellerBundle:Product')->findOneById(1);
     $quantity = 50;
     $userName = '******';
     $token = 'z49er8c4z9ec';
     $status = 'en cours';
     $payment = new PaymentController();
     $historical = $payment->historical($product, $quantity, $userName, $token, $status);
     $this->assertInstanceOf('DreamStore\\CustomerBundle\\Entity\\Historical', $historical);
 }
 /**
  * @group DDC-2109
  */
 public function testAssertTableColumnsAreNotAddedInManyToMany()
 {
     $evm = $this->em->getEventManager();
     $this->listener->addResolveTargetEntity('Doctrine\\Tests\\ORM\\Tools\\ResolveTargetInterface', 'Doctrine\\Tests\\ORM\\Tools\\ResolveTargetEntity', array());
     $this->listener->addResolveTargetEntity('Doctrine\\Tests\\ORM\\Tools\\TargetInterface', 'Doctrine\\Tests\\ORM\\Tools\\TargetEntity', array());
     $evm->addEventListener(Events::loadClassMetadata, $this->listener);
     $cm = $this->factory->getMetadataFor('Doctrine\\Tests\\ORM\\Tools\\ResolveTargetEntity');
     $meta = $cm->associationMappings['manyToMany'];
     $this->assertSame('Doctrine\\Tests\\ORM\\Tools\\TargetEntity', $meta['targetEntity']);
     $this->assertEquals(array('resolvetargetentity_id', 'targetinterface_id'), $meta['joinTableColumns']);
 }
 /** @test */
 public function should_add_new_thread()
 {
     $group = new Group(GroupId::generate(), 'Cribbb');
     $id = ThreadId::generate();
     $thread = new Thread($id, $group, 'Hello World');
     $this->repository->add($thread);
     $this->em->clear();
     $thread = $this->repository->threadOfId($id);
     $this->assertInstanceOf('Cribbb\\Domain\\Model\\Discussion\\ThreadId', $thread->id());
     $this->assertEquals('hello-world', $thread->slug());
 }