refresh() public méthode

Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.
public refresh ( object $entity )
$entity object The entity to refresh.
Exemple #1
0
 /**
  * Refreshes an entity with real translations
  * @param $entity
  * @param $language
  *
  * @author Yohann Marillet
  */
 public function refreshEntity($entity, $language)
 {
     $translatableProperties = $this->getTranslatableProperties($entity);
     $setLocaleMethod = $translatableProperties['setLocaleMethod'];
     $entity->{$setLocaleMethod}($language);
     $this->em->refresh($entity);
     if ($this->defaultLocale != $language) {
         if (false !== $translatableProperties['usePersonalTranslations']) {
             /** @var HasTranslations $entity */
             $allTranslations = $entity->getTranslations();
             $translations = [];
             /** @var AbstractPersonalTranslation $translationEntity */
             foreach ($allTranslations as $translationEntity) {
                 if (!isset($translations[$translationEntity->getLocale()])) {
                     $translations[$translationEntity->getLocale()] = [];
                 }
                 $translations[$translationEntity->getLocale()][$translationEntity->getField()] = $translationEntity->getContent();
             }
         } else {
             $translations = $this->getRepository()->findTranslations($entity);
         }
         if (!isset($translations[$language])) {
             $translations[$language] = $translatableProperties['fields'];
         }
         foreach ($translations[$language] as $field => $value) {
             $setter = Strings::toSetter($field);
             $entity->{$setter}($value);
         }
     }
 }
Exemple #2
0
 public function insert(array $data)
 {
     $entity = new $this->entity($data);
     $this->em->persist($entity);
     $this->em->flush();
     $this->em->refresh($entity);
     return $entity;
 }
 public function testPut()
 {
     $data = ['isExpanded' => 1, 'layoutPosition' => [2, 20]];
     $this->client->request('PUT', $this->getUrl('oro_api_put_dashboard_widget', ['dashboardId' => $this->widget->getDashboard()->getId(), 'widgetId' => $this->widget->getId()]), $data);
     $result = $this->client->getResponse();
     $this->assertEmptyResponseStatusCodeEquals($result, 204);
     $this->em->refresh($this->widget);
     $model = $this->dashboardManager->findWidgetModel($this->widget->getId());
     $this->assertEquals($data['isExpanded'], $model->isExpanded());
     $this->assertEquals($data['layoutPosition'], $this->widget->getLayoutPosition());
     $this->assertEquals($data['layoutPosition'], $model->getLayoutPosition());
 }
Exemple #4
0
 /**
  * @Given /^пользователь "([^"]*)" должен быть отписан от рассылки$/
  */
 public function userIsUnsubscribed($username)
 {
     $user = $this->em->getRepository('ApplicationUserBundle:User')->findOneBy(['username' => $username]);
     $this->em->refresh($user);
     Assert::assertNotNull($user);
     Assert::assertFalse($user->isSubscribe());
 }
 /**
  * @param EmailFolderModel[]|ArrayCollection $syncedFolderModels
  * @param ImapEmailFolder[]|ArrayCollection $existingImapFolders
  *
  * @return EmailFolderModel[]
  */
 protected function mergeFolders($syncedFolderModels, &$existingImapFolders)
 {
     foreach ($syncedFolderModels as $syncedFolderModel) {
         $f = $existingImapFolders->filter(function (ImapEmailFolder $imapEmailFolder) use($syncedFolderModel) {
             return $imapEmailFolder->getUidValidity() === $syncedFolderModel->getUidValidity();
         });
         if ($f->isEmpty()) {
             // there is a new folder on server, create it
             $imapEmailFolder = $this->createImapEmailFolder($syncedFolderModel);
             // persist ImapEmailFolder and (by cascade) EmailFolder
             $this->em->persist($imapEmailFolder);
         } else {
             /** @var ImapEmailFolder $existingImapFolder */
             $existingImapFolder = $f->first();
             $emailFolder = $existingImapFolder->getFolder();
             $this->em->refresh($emailFolder);
             $emailFolder->setName($syncedFolderModel->getEmailFolder()->getName());
             $emailFolder->setFullName($syncedFolderModel->getEmailFolder()->getFullName());
             $emailFolder->setType($syncedFolderModel->getEmailFolder()->getType());
             $emailFolder->setSynchronizedAt($syncedFolderModel->getEmailFolder()->getSynchronizedAt());
             $syncedFolderModel->setEmailFolder($emailFolder);
             $existingImapFolders->removeElement($existingImapFolder);
         }
         if ($syncedFolderModel->hasSubFolderModels()) {
             $syncedFolderModel->setSubFolderModels($this->mergeFolders($syncedFolderModel->getSubFolderModels(), $existingImapFolders));
         }
     }
     return $syncedFolderModels;
 }
 public function testDeactivateAndActivateActions()
 {
     // set and assert active workflow
     $this->getWorkflowManager()->activateWorkflow(LoadWorkflowDefinitions::WITH_START_STEP);
     $this->assertActiveWorkflow($this->entityClass, LoadWorkflowDefinitions::WITH_START_STEP);
     // create and assert test entity
     $testEntity = $this->createNewEntity();
     $this->assertEntityWorkflowItem($testEntity, LoadWorkflowDefinitions::WITH_START_STEP);
     // deactivate workflow for entity
     $this->client->request('GET', $this->getUrl('oro_workflow_api_rest_workflow_deactivate', array('entityClass' => $this->entityClass)));
     $result = $this->getJsonResponseContent($this->client->getResponse(), 200);
     $this->assertActivationResult($result);
     $this->assertActiveWorkflow($this->entityClass, null);
     // assert that entity still has relation to workflow
     $this->entityManager->refresh($testEntity);
     $this->assertEntityWorkflowItem($testEntity, LoadWorkflowDefinitions::WITH_START_STEP);
     // activate other workflow through API
     $this->client->request('GET', $this->getUrl('oro_workflow_api_rest_workflow_activate', array('workflowDefinition' => LoadWorkflowDefinitions::NO_START_STEP)));
     $result = $this->getJsonResponseContent($this->client->getResponse(), 200);
     $this->assertActivationResult($result);
     $this->assertActiveWorkflow($this->entityClass, LoadWorkflowDefinitions::NO_START_STEP);
     // assert that entity workflow item was reset
     $this->entityManager->refresh($testEntity);
     $this->assertEntityWorkflowItem($testEntity, null);
 }
 public function applicationSignAction(Request $request)
 {
     /** @var ClientAccount $account */
     $account = $this->em->getRepository('WealthbotClientBundle:ClientAccount')->find($request->get('account_id'));
     if (!$account) {
         throw $this->createNotFoundException();
     }
     $signature = $this->signatureManager->findActiveDocumentSignatureBySourceIdAndType($account->getId(), DocumentSignature::TYPE_OPEN_OR_TRANSFER_ACCOUNT);
     if (!$signature) {
         throw $this->createNotFoundException();
     }
     if (null === $signature->getDocusignEnvelopeId()) {
         $this->electronicSignature->sendEnvelopeForApplication($account);
         $this->em->refresh($signature);
     }
     $envelopeId = $signature->getDocusignEnvelopeId();
     $primaryApplicant = $account->getPrimaryApplicant();
     if ($primaryApplicant instanceof AccountOwnerInterface) {
         $recipient = new AccountOwnerRecipientAdapter($primaryApplicant);
         $returnUrl = $this->generateUrl('wealthbot_docusign_application_sign_callback', array('envelope_id' => $envelopeId, 'application_id' => $account->getId()), true);
         $embeddedUrl = $this->api->getEmbeddedSigningUrl($envelopeId, $recipient, $returnUrl);
         if ($embeddedUrl) {
             return $this->render('WealthbotSignatureBundle:Default:application_sign_iframe.html.twig', array('url' => $embeddedUrl));
         }
     }
     return $this->render('WealthbotSignatureBundle:Default:application_sign_error.html.twig', array('message' => 'An error has occurred. Please try again later.'));
 }
 protected function addNewUser($username, $email, $password, $active = true, $banned = false, $persist = true, $andFlush = true)
 {
     $user = new User();
     $user->setUsername($username);
     $user->setEmail($email);
     $user->setPlainPassword($password);
     $user->setEnabled($active);
     $user->setLocked($banned);
     if ($persist) {
         $this->em->persist($user);
         if ($andFlush) {
             $this->em->flush();
             $this->em->refresh($user);
         }
     }
     return $user;
 }
Exemple #9
0
 /**
  * Set parameter value, if parameter does not exist, create one.
  * 
  * @param type $entity
  * @param type $name
  * @param type $value
  * @param type $type   parameter data type (string, integer, boolean, text)
  */
 public function set($entity, $name, $value, $category = E\Parameter::CATEGORY_GENERAL)
 {
     $param = $this->findParameter($entity, $name);
     if (!$param instanceof \Application\MainBundle\Entity\Parameter) {
         list($entityType, $entityId) = $this->getEntityData($entity);
         $param = new E\Parameter();
         $param->setEntityType($entityType)->setEntityId($entityId)->setName($name)->setCategory($category);
     }
     if ($param->isDeleted()) {
         $param->restore();
         $this->em->flush();
         $this->em->refresh($param);
     }
     $param->setValue($value);
     $this->em->persist($param);
     $this->em->flush();
     return $param;
 }
 public function testActivateDeactivate()
 {
     $definition = $this->createNewEnabledProcessDefinition();
     $definitionName = $definition->getName();
     $this->assertTrue($definition->isEnabled());
     // deactivate process
     $this->client->request('GET', $this->getUrl('oro_workflow_api_rest_process_deactivate', array('processDefinition' => $definitionName)));
     $this->assertResult($this->getJsonResponseContent($this->client->getResponse(), 200));
     // assert that process definition item was deactivated
     $this->entityManager->refresh($definition);
     $this->assertFalse($definition->isEnabled());
     // activate process
     $this->client->request('GET', $this->getUrl('oro_workflow_api_rest_process_activate', array('processDefinition' => $definitionName)));
     $this->assertResult($this->getJsonResponseContent($this->client->getResponse(), 200));
     // assert that process definition item was activated
     $this->entityManager->refresh($definition);
     $this->assertTrue($definition->isEnabled());
 }
Exemple #11
0
 /**
  * @param ConnectionInterface $conn
  */
 public function onOpen(ConnectionInterface $conn)
 {
     $userData = $conn->Session->get('user');
     if (count($userData) == 2 && is_int($userData[0])) {
         list($userId, $userRole) = $userData;
         $user = User::find($userId);
         if (null === $user) {
             $conn->close();
             return;
         }
         $this->em->refresh($user);
         $conn->user = $user;
         $this->send(Protocol::userJoin($user));
         $this->clients[$user->id] = $conn;
         $users = array();
         foreach ($this->clients as $conn) {
             $users[] = $conn->user->export();
         }
         $this->sendToUser($user->id, Protocol::data(Protocol::SYNCHRONIZE, $users));
     } else {
         $conn->close();
     }
 }
Exemple #12
0
 private function retrieveConfigurationFromSecret(ConnectionInterface $from, array $msg, $type, $comKey)
 {
     $secret = $msg['secret'];
     $user = $this->em->getRepository('AppBundle:User')->findOneBy(['secret' => $secret]);
     if (!$user) {
         $this->answerError($from, $type, $comKey, 'Invalid secret');
         return;
     }
     $this->em->refresh($user);
     $config = ['socket_url' => $this->socketUrl, 'web_url' => $this->webUrl, 'secret' => $user->getSecret(), 'web_hooks' => []];
     foreach ($user->getWebHooks() as $webHook) {
         $config['web_hooks'][] = ['endpoint' => $webHook->getEndpoint()];
     }
     $this->answer($from, $type, $comKey, $config);
     $this->logger->info("Configuration retrieved for user", ['user' => $user->getUsername(), 'conn' => $from->resourceId, 'ck' => $comKey]);
 }
 protected function addNewSubscription($forum, $topic, $user, $isRead = false, $persist = true, $andFlush = true)
 {
     $subscription = $this->getSubscriptionModel()->createSubscription();
     $subscription->setTopic($topic);
     $subscription->setOwnedBy($user);
     $subscription->setForum($forum);
     $subscription->setRead($isRead);
     $subscription->setSubscribed(true);
     if ($persist) {
         $this->em->persist($subscription);
         if ($andFlush) {
             $this->em->flush();
             $this->em->refresh($subscription);
         }
     }
     return $subscription;
 }
 /**
  * Refresh entity.
  *
  * @param BaseEntityAbstract $entity
  *
  * @return $this
  */
 public function refresh(BaseEntityAbstract $entity)
 {
     $this->entityManager->refresh($entity);
     $metaData = $this->entityManager->getClassMetaData($this->entityName);
     $mappings = $metaData->getAssociationMappings();
     foreach ($mappings as $mapping) {
         $fieldName = $mapping['fieldName'];
         $assoc = $entity->{$fieldName};
         if ($assoc instanceof \Traversable) {
             foreach ($assoc as $ent) {
                 if ($ent instanceof BaseEntityAbstract) {
                     $this->entityManager->refresh($ent);
                 }
             }
         } elseif ($assoc instanceof BaseEntityAbstract) {
             $this->entityManager->refresh($assoc);
         }
     }
     return $this;
 }
 /**
  * @param array $widgets
  * @param array $expectedPositions
  *
  * @dataProvider widgetsProvider
  */
 public function testPositions($widgets, $expectedPositions)
 {
     foreach ($widgets as $widget) {
         $this->em->persist($widget);
     }
     $this->em->flush();
     $dashboard = null;
     $data = ['layoutPositions' => []];
     foreach ($widgets as $widget) {
         /* @var Widget $widget */
         $data['layoutPositions'][$widget->getId()] = array_map(function ($item) {
             return $item * 10;
         }, $widget->getLayoutPosition());
         $dashboard = $widget->getDashboard();
     }
     $this->client->request('PUT', $this->getUrl('oro_api_put_dashboard_widget_positions', ['dashboardId' => $dashboard->getId()]), $data);
     $result = $this->client->getResponse();
     $this->assertEmptyResponseStatusCodeEquals($result, 204);
     foreach ($widgets as $key => $widget) {
         $this->em->refresh($widget);
         $this->assertEquals($expectedPositions[$key], $widget->getLayoutPosition());
     }
 }
 /**
  *
  * @access public
  * @param  Object                                                $entity
  * @return \CCDNUser\SecurityBundle\Gateway\BaseGatewayInterface
  */
 public function refresh($entity)
 {
     $this->em->refresh($entity);
     return $this;
 }
Exemple #17
0
 /**
  * Atualização da entidade
  *
  * @param BaseEntityAbstract $entity
  * @return $this
  */
 public function refresh(BaseEntityAbstract $entity)
 {
     $this->em->refresh($entity);
     return $this;
 }
Exemple #18
0
 /**
  * {@inheritdoc}
  */
 public function refresh($entity)
 {
     if ($logger = $this->getProfilingLogger()) {
         $logger->startRefresh();
         parent::refresh($entity);
         $logger->stopRefresh();
     } else {
         parent::refresh($entity);
     }
 }
Exemple #19
0
 /**
  * {@inheritDoc}
  */
 public function reloadUser(UserInterface $user)
 {
     $this->em->refresh($user);
 }
Exemple #20
0
 /**
  * Refreshes the persistent state of an entity from the database,
  * overriding any local changes that have not yet been persisted.
  *
  * @param object $entity The entity to refresh.
  * @return void 
  * @throws ORMInvalidArgumentException
  * @static 
  */
 public static function refresh($entity)
 {
     \Doctrine\ORM\EntityManager::refresh($entity);
 }
 /**
  * {@inheritdoc}
  */
 public function refresh($entity)
 {
     return $this->wrapped->refresh($entity);
 }
 /**
  * Reload member from the DB.
  *
  * @param MemberInterface $member
  */
 public function reloadMember(MemberInterface $member)
 {
     $this->em->refresh($member);
 }
Exemple #23
0
 /**
  * {@inheritDoc}
  */
 public function reload($data)
 {
     $this->entityManager->refresh($data);
 }
 /**
  * Calls refresh on the current entity -- refreshes the persistence state
  *
  */
 public function refresh()
 {
     $this->_em->refresh($this->_jobEntity);
 }
 /**
  * обработка показа
  *
  * @param VideoView $videoView
  * @param bool      $skipStatusCheck
  *
  * @return boolean false, если транзакция не прошла, в остальных случаях true
  */
 public function reckon(VideoView $videoView, $skipStatusCheck = false)
 {
     $videoViewRepo = $this->em->getRepository('VifeedVideoViewBundle:VideoView');
     $userRepo = $this->em->getRepository('VifeedUserBundle:User');
     $campaignRepo = $this->em->getRepository('VifeedCampaignBundle:Campaign');
     $publisher = $videoView->getPlatform()->getUser();
     $this->em->refresh($publisher);
     // обновляем энтити. Доктрина может брать его из кеша
     if (!$publisher->isEnabled()) {
         // паблишер забанен. Ничего не делаем
         return true;
     }
     // пользователь уже просматривал этот ролик
     $countViewsByViewerId = $videoViewRepo->countCampaignViewsByViewerId($videoView);
     if ($countViewsByViewerId['paid_views'] > 0) {
         return true;
     }
     $campaign = $videoView->getCampaign();
     $this->em->refresh($campaign);
     // обновляем энтити. Доктрина может брать его из кеша
     // перед оплатой обновляем статус по балансу. Если пора выключать - выключаем
     $this->campaignManager->checkUpdateStatusOn($campaign);
     // если просмотр слишком короткий или кампания уже остановлена, инкрементим totalViews и выходим
     if (!$skipStatusCheck && !$this->checkReckonConditions($videoView)) {
         // засчитываем показ только если пользователь ещё не смотрел ролик
         if ($countViewsByViewerId['views'] == 0) {
             // показ участвует в статах
             $videoView->setIsInStats(true);
             $this->em->persist($videoView);
             $campaignRepo->incrementTotalViews($campaign);
         }
         $this->em->flush();
         // на случай, если у кампании обновился статус
         return true;
     }
     $this->em->getConnection()->beginTransaction();
     $this->em->lock($publisher, LockMode::PESSIMISTIC_WRITE);
     $price = $campaign->getBid();
     $comissionValue = round($this->comission * $price, 2);
     $toPay = round($price - $comissionValue, 2);
     $payment = new VideoViewPayment();
     $payment->setVideoView($videoView)->setCharged($price)->setComission($comissionValue)->setPaid($toPay);
     $userRepo->updateBalance($publisher, $toPay);
     $campaignRepo->addPaidView($campaign);
     $this->campaignManager->checkUpdateStatusOn($campaign);
     $videoView->setIsPaid(true)->setIsInStats(true);
     $this->em->persist($publisher);
     $this->em->persist($payment);
     $done = false;
     try {
         $this->em->flush();
         $this->em->getConnection()->commit();
         $this->em->refresh($campaign);
         $this->campaignManager->checkUpdateStatusOn($campaign);
         $this->em->flush();
         // на случай, если у кампании обновился статус
         $done = true;
     } catch (\Exception $e) {
         $this->em->getConnection()->rollback();
         // исключение не бросаем, просто откатываем транзакцию и ставим задачу снова в очередь
     }
     return $done;
 }
 /**
  * {@inheritdoc}
  */
 public function refresh($object)
 {
     $this->em->refresh($object);
 }
Exemple #27
0
 private function menuArrayToEntities($menuArray, \Doctrine\ORM\EntityManager $em, MenuElement $parent = null, $locale)
 {
     $collection = new \Doctrine\Common\Collections\ArrayCollection();
     $repo = $em->getRepository('SKCMSCoreBundle:MenuElement');
     $repo->setDefaultLocale($locale);
     foreach ($menuArray as $menuElement) {
         //            //dump($menuElement);
         //            die();
         $element = null;
         if (isset($menuElement->elementId)) {
             $element = $repo->find($menuElement->elementId);
             $element->setTranslatableLocale($locale);
             $em->refresh($element);
         }
         if (null === $element) {
             $element = new MenuElement();
         }
         $element->setName($menuElement->name);
         $element->setEntityId($menuElement->targetId);
         $element->setEntityClass($menuElement->entityClass);
         $element->setPosition($menuElement->position);
         if (isset($menuElement->children) && count($menuElement->children)) {
             $element->setChildren($this->menuArrayToEntities($menuElement->children, $em, $element, $locale));
         }
         $collection->add($element);
         if (null !== $parent) {
             $element->setParent($parent);
         }
         $em->persist($element);
     }
     return $collection;
 }
 /**
  * Refresh persisted entities
  */
 public function refresh($entity)
 {
     $this->em->refresh($entity);
 }
 public function process(MassMailQueue $entry, $batchSize = 100)
 {
     $this->debugOut->writeln('-----------------------------------');
     $this->debugOut->writeln("Starting entry: " . $entry->getSubject());
     $start = $entry->getPosition();
     // Don't change (reduce) our original total after the first time it's
     // set as that could cause us to not send to the complete list of users
     // we originally found with our filter
     $total = max($this->countUsers($entry), $entry->getTotal());
     $this->debugOut->writeln("Found total: {$total}");
     if (!$this->simulate) {
         $entry->setTotal($total);
         $entry->setStatus(MassMailQueue::STATUS_PROCESSING);
         $this->em->flush();
     }
     $complete = false;
     // loop through, constantly fetching from the last user + 1, until nothing left.
     // LIMIT x,y would be slow (needs to look at *all* results even before offset),
     // and prone to duplicate/missing sends if a user changes their preferences mid-process.
     while (true) {
         $currentDate = new \DateTime();
         $userLimit = $batchSize;
         // if not a preview, apply batch limiting
         if ($entry->getType() !== MassMailQueue::TYPE_PREVIEW) {
             $remaining = $this->limiter->getMessagesRemaining($currentDate);
             if ($remaining <= 0) {
                 $this->debugOut->writeln('Reached batch limitations, breaking');
                 break;
             }
             $userLimit = min($userLimit, $remaining);
         }
         // allow pausing
         $this->em->refresh($entry);
         if ($entry->getStatus() === MassMailQueue::STATUS_PAUSED) {
             $this->debugOut->writeln('Entry paused, breaking');
             break;
         }
         $users = $this->fetchUsers($entry, $start, $userLimit);
         if (empty($users)) {
             $this->debugOut->writeln('No more users found, breaking loop');
             // Make sure we're not here because we're over our limit
             if ($remaining > 0) {
                 $complete = true;
             }
             break;
         }
         foreach ($users as $user) {
             $this->debugOut->writeln("User #{$user['id']}; un={$user['username']}; em={$user['email']}; " . "fn={$user['properties']['FirstName']} {$user['properties']['LastName']}");
             if (!$this->simulate) {
                 $html = $this->renderTemplate($entry, $user);
                 $message = \Swift_Message::newInstance($entry->getSubject(), $html, 'text/html', 'utf-8');
                 $message->setFrom('*****@*****.**');
                 try {
                     $message->setTo($user['email']);
                 } catch (\Swift_RfcComplianceException $e) {
                     // Just skip over bad e-mail addresses
                     $this->debugOut->writeln("Skipping badly formatted e-mail address: {$user['email']}");
                     continue;
                 }
                 $headers = $message->getHeaders();
                 $headers->addTextHeader('X-Gc-Type', 'mass');
                 $unsub = $this->getUnsubscribeLink($entry, $user);
                 if ($unsub) {
                     $headers->addTextHeader('List-Unsubscribe', '<' . $this->getUnsubscribeLink($entry, $user) . '>');
                 }
                 $this->mailer->send($message);
             }
             $start = $user['id'] + 1;
         }
         if (!$this->simulate) {
             $entry->setPosition($start);
             $entry->setSent($entry->getSent() + count($users));
             $this->em->flush();
         }
         if ($entry->getType() === MassMailQueue::TYPE_PREVIEW) {
             $complete = true;
             break;
         } else {
             $this->limiter->addMessagesSent($currentDate, count($users));
         }
     }
     if (!$this->simulate) {
         if ($complete) {
             // This is more accurate than the reverse, I think.
             $entry->setTotal($entry->getSent());
             $entry->setStatus(MassMailQueue::STATUS_COMPLETE);
         }
         $this->em->flush();
     }
 }