/** * Migrate data to plugin database from core table * * @param EntityManager $em * @param OutputInterface $output * * @return void */ public function migrateData($em, $output) { $rsm = new ResultSetMapping(); $rsm->addEntityResult('Newscoop\\CommunityTickerBundle\\Entity\\CommunityTickerEvent', 'e'); $rsm->addFieldResult('e', 'id', 'id'); $rsm->addFieldResult('e', 'event', 'event'); $rsm->addFieldResult('e', 'params', 'params'); $rsm->addFieldResult('e', 'created', 'created'); $rsm->addJoinedEntityResult('Newscoop\\Entity\\User', 'u', 'e', 'user'); $rsm->addFieldResult('u', 'Id', 'id'); $query = $em->createNativeQuery('SELECT e.id, e.event, e.params, e.created, u.Id FROM community_ticker_event e ' . 'LEFT JOIN liveuser_users u ON u.id = e.user_id', $rsm); $events = $query->getArrayResult(); foreach ($events as $key => $event) { $user = $em->getRepository('Newscoop\\Entity\\User')->findOneBy(array('id' => $event['user']['id'])); $existingEvent = $em->getRepository('Newscoop\\CommunityTickerBundle\\Entity\\CommunityTickerEvent')->findOneBy(array('created' => $event['created'], 'params' => $event['params'])); if (!$existingEvent) { $newEvent = new CommunityTickerEvent(); $newEvent->setEvent($event['event']); $newEvent->setParams($event['params'] != '[]' ? json_decode($event['params'], true) : array()); $newEvent->setCreated($event['created']); $newEvent->setIsActive(true); if ($user) { $newEvent->setUser($user); } $em->persist($newEvent); } } $em->flush(); $output->writeln('<info>Data migrated to plugin table!</info>'); $output->writeln('<info>Removing old table...</info>'); }
/** * {@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 testReverseTransform() { $transformer = $this->createTransformer(); $tag = new Tag("name"); $this->em->persist($tag); $this->em->flush(); $this->assertSame($tag, $transformer->reverseTransform(1, null)); }
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 '); } }
protected function persist(array $entities) { foreach ($entities as $entity) { $this->em->persist($entity); } $this->em->flush(); // no clear, because entities managed by the choice field must // be managed! }
/** * Save schema * * @param SchemaInterface $schema * * @return SchemaInterface */ public function save(SchemaInterface $schema) { foreach ($schema->getAttributes() as $attribute) { $attribute->setSchema($schema); $this->em->persist($attribute); } $this->em->persist($schema); $this->em->flush(); return $schema; }
/** * Save template * * @param TemplateInterface $template * * @return TemplateInterface */ public function save(TemplateInterface $template) { foreach ($template->getAttributes() as $attribute) { $attribute->setTemplate($template); $this->em->persist($attribute); } $this->em->persist($template); $this->em->flush(); return $template; }
public function createTagCollection() { $tags = new ArrayCollection(); $tags->add(new Tag("foo")); $tags->add(new Tag("bar")); foreach ($tags as $tag) { $this->em->persist($tag); } $this->em->flush(); $this->em->clear(); return $tags; }
/** * Method actually invoked upon dispatching an event "kernel.response" * * @param FilterResponseEvent $event * * @return void */ public function onKernelRequest(GetResponseEvent $event) { if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { return; } $token = $this->securityContext->getToken(); if ($token instanceof UsernamePasswordToken and $token->isAuthenticated()) { $user = $token->getUser(); $user->setLastActive(new \DateTime(date('Y-m-d H:i:s', time()))); $this->entityManager->persist($user); $this->entityManager->flush(); } }
/** * @param BlockInterface $block * * @return BlockManager */ public function save(BlockInterface $block) { $block->setRootVersion($this->getNewVersion($block)); $this->em->persist($block); $this->em->flush($block); return $this; }
public function testPaginator() { $reader = $this->getAuditReader(); $query = $reader->paginateRevisionsQuery(); $paginatorAdapter = new \ZF2EntityAudit\Paginator\DbalAdapter($query); $paginator = new \Zend\Paginator\Paginator($paginatorAdapter); for ($i = 0; $i < 20; $i++) { $writer = new Writer("tawfek" . rand()); $article = new Article("title", "text", $writer); $this->em->persist($writer); $this->em->persist($article); } $this->em->flush(); $this->assertEquals($reader->countRevisions(), "1"); $this->assertEquals($paginator->count(), "1"); for ($i = 0; $i < 20; $i++) { $writer = new Writer("tawfek" . rand()); $article = new Article("title", "text", $writer); $this->em->persist($writer); $this->em->persist($article); $this->em->flush(); } // its 21 because (20 flushes + 1 flush as bluk flush in line 330 ) $this->assertEquals($reader->countRevisions(), "21"); $this->assertEquals($paginator->getAdapter()->count(), "21"); $this->assertEquals(count($paginator->getAdapter()->getItems(1, 12)), "12"); }
/** * method invoked everytime an event is dispatched(guide updates) * @param EguideEvent $event */ public function updateFreeSearchField(EguideEvent $event) { $eguide = $event->getEguide(); $keywords = array(); /** * needs improvement * @var string */ $categories = $eguide->getCategories(); foreach ($categories as $category) { $categoryName = strtolower($category->getName()); $keywords[] = 'activity:' . $categoryName; } $country = strtolower($eguide->getCountry()->getName()); $locations = $eguide->getLocations(); foreach ($locations as $location) { $address = 'location:' . $location->getAddress(); $keywords[] = $address; } $keywords[] = $country; $keywords = implode(" ", $keywords); $eguide->setFreeSearch($keywords); $this->entityManager->persist($eguide); $this->entityManager->flush(); }
/** * Saves a thread * * @param ThreadInterface $thread * @param Boolean $andFlush Whether to flush the changes (default true) */ public function saveThread(ThreadInterface $thread, $andFlush = true) { $this->denormalize($thread); $this->em->persist($thread); if ($andFlush) { $this->em->flush(); } }
/** * Saves a message * * @param MessageInterface $message * @param Boolean $andFlush Whether to flush the changes (default true) */ public function saveMessage(MessageInterface $message, $andFlush = true) { $this->denormalize($message); $this->em->persist($message); if ($andFlush) { $this->em->flush(); } }
/** * Make sure activities cannot have the same activityId per spec */ public function testActivityUniqueness() { $activity = $this->activityService->denormalize(json_encode($this->getActivityData())); $this->em->persist($activity); $this->em->flush(); $newActivity = clone $activity; $constraintViolationList = $this->validator->validate($newActivity); $this->assertEquals($constraintViolationList->count(), 1); $this->assertEquals($constraintViolationList->get(0)->getInvalidValue(), $activity->getActivityId()); }
/** * Private helper: Persist SubProject * * @param SubProject * * @return SubProject */ private function _persistAndFlush($transaction) { $this->em->persist($transaction); try { $this->em->flush(); } catch (Exception $e) { throw new Exception('Unknown EM error: ' . $e->getCode() . ' - ' . $e->getMessage()); } return $transaction; }
/** * @depends testTransformEmptyCollection */ public function testReverseTransformNewKnownEntity() { $transformer = $this->createTransformer(); $newTag = new Tag("baz"); $this->em->persist($newTag); $this->em->flush(); $tags = $this->createTagCollection(); $tags = $transformer->reverseTransform("foo, bar, baz", $tags); $this->assertEquals(3, count($tags)); $this->assertTrue($tags->contains($newTag)); }
/** /** * Create comment * * @param Request $request * @param string $slug * @throws NotFoundHttpException * @return array * * @Route("/{slug}/create-comment") * @Method("POST") * @Template("CoreBundle:Post:show.html.twig") */ public function createCommentAction(Request $request, $slug) { // exit(\Doctrine\Common\Util\Debug::dump($slug)); // var_dump($request); exit; $post = $this->em->getRepository('ModelBundle:Post')->findOneBy(array('slug' => $slug)); if ($post === null) { throw createNotFoundException('Post Was Not Found'); } $comment = new Comment(); $comment->setPost($post); $form = $this->createForm(new CommentType(), $comment); $form->handleRequest($request); if ($form->isValid()) { $this->em->persist($comment); $this->em->flush(); $this->get('session')->getFlashBag()->add('success', 'Your comment was submitted successfully'); return $this->redirect($this->generateUrl('blog_core_post_show', array('slug' => $post->getSlug()))); } return array('post' => $post, 'form' => $form->createView()); }
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(); }
/** * Private helper: Persist Entity * * @param Entity * * @return Entity */ private function _persistAndFlush($entity) { $this->em->persist($entity); try { $this->em->flush(); } catch (Exception $e) { if ($this->environment == 'dev') { throw new Exception('Entity Manager Error: ' . $e->getMessage()); } throw new Exception('Unknown EM error: ' . $e->getCode() . ' - ' . $e->getMessage()); } return $entity; }
/** * Save directory * * @param DirectoryInterface $directory * * @throws \Exception * * @return DirectoryInterface */ public function save(DirectoryInterface $directory) { $this->em->persist($directory); $this->em->flush(); $repository = $this->getRepository(); // Tree verification is a very (!) expensive operation. So only // run when needed. if (true !== ($errors = $repository->verify())) { throw new \Exception('Directory tree is invalid'); } $repository->recover(); $this->em->flush(); return $directory; }
protected function createArticleFixtures() { $articles = new ArrayCollection(); $articles->add(new Article('foo', 'toto')); $articles->add(new Article('bar', 'toto')); $articles->add(new Article('bar', 'titi')); $articles->add(new Article('foo', 'titi')); $articles->add(new Article('barfoo', 'tata')); foreach ($articles as $article) { $this->em->persist($article); } $this->em->flush(); $this->em->clear(); return $articles; }
public function testFindCurrentRevision() { $user = new UserAudit('Broncha'); $this->em->persist($user); $this->em->flush(); $user->setName("Rajesh"); $this->em->flush(); $reader = $this->auditManager->createAuditReader($this->em); $revision = $reader->getCurrentRevision(get_class($user), $user->getId()); $this->assertEquals(2, $revision); $user->setName("David"); $this->em->flush(); $revision = $reader->getCurrentRevision(get_class($user), $user->getId()); $this->assertEquals(3, $revision); }
/** * Get a marketProduct record for an incoming product, if it does not exist, create it * * @param IncomingProduct $product * * @return MarketProduct * * @throws \Exception */ protected function getMarketProduct(IncomingProduct $product) { $market = $this->getMarket(); $marketProduct = $this->entityManager->getRepository('AppBundle:MarketProduct')->findOneBy(['market' => $market, 'foreignId' => $product->getMarketId()]); if ($marketProduct) { return $marketProduct; } $variant = $this->getProductVariantRecord($product); $marketProduct = new MarketProduct(); $marketProduct->setMarket($market); $marketProduct->setForeignId($product->getMarketId()); $marketProduct->setProductVariantSku($variant); $this->entityManager->persist($marketProduct); $this->entityManager->flush(); return $marketProduct; }
/** * @param Request $request * @param Response $response * @param array $args * * @return Response */ public function create(Request $request, Response $response, array $args) { $validator = $this->createValidator(); $rawData = $request->request->all(); $result = $validator->run($rawData); if ($result->isValid()) { $fields = $result->getValidated(); $data = array_intersect_key($rawData, array_flip($fields)); $entity = $this->createEntity($data); $this->em->persist($entity); $this->em->flush(); return new RedirectResponse($request->getUri()); } $request->attributes->set('repopulate', true); $response = $this->createAction($request, $response, $args); return $response; }
public function testGlobalIgnoreColumns() { $user = new UserAudit("welante"); $article = new ArticleAudit("testcolumn", "yadda!", $user, 'text'); $this->em->persist($user); $this->em->persist($article); $this->em->flush(); $article->setText("testcolumn2"); $this->em->persist($article); $this->em->flush(); $reader = $this->auditManager->createAuditReader($this->em); $revision = $reader->getCurrentRevision(get_class($article), $article->getId()); $this->assertEquals(2, $revision); $article->setIgnoreme("textnew"); $this->em->persist($article); $this->em->flush(); $revision = $reader->getCurrentRevision(get_class($article), $article->getId()); $this->assertEquals(2, $revision); }
/** * Clones an entire tree and persists to database * * @param BlockOwnerInterface $block * * @return BlockOwnerInterface */ public function duplicate(BlockOwnerInterface $block) { $this->killDraftVersionFilter(); $this->killLoggableListener(); $blocks = $this->findByOwner($block); array_unshift($blocks, $block); // 1. Interate over all owned blocks and disconnect parents keeping ids /** @var Block $descendant */ foreach ($blocks as $descendant) { $descendant->originalId = $descendant->getId(); // if it has a parent we need to put it somewhere if ($descendant->getParent()) { $descendant->originalParentId = $descendant->getParent()->getId(); $descendant->setParent(null); } if ($descendant instanceof BlockContainerInterface) { $descendant->setChildren(null); } $descendant->setOwner($block); $descendant->setRootVersion(0); $this->em->detach($descendant); $this->em->persist($descendant); } $this->em->flush(); // 2. Iterate over all new blocks and reset their parents foreach ($blocks as $descendant) { if (isset($descendant->originalParentId)) { foreach ($blocks as $parent) { if ($descendant->originalParentId === $parent->originalId) { $descendant->setParent($parent); $parent->addChild($descendant); } } } } $this->em->flush(); return $block; }
/** * Save attribute. * * @param Form $form * * @return Form */ public function save(Form $form) { $this->em->persist($form); $this->em->flush(); return $form; }
/** * Save layout * * @param LayoutInterface $layout * * @return LayoutInterface */ public function save(LayoutInterface $layout) { $this->em->persist($layout); $this->em->flush(); return $layout; }
/** * Save attribute * * @param AttributeInterface $attribute * * @return AttributeInterface */ public function save(AttributeInterface $attribute) { $this->em->persist($attribute); $this->em->flush(); return $attribute; }