persist() public method

The entity will be entered into the database at or before transaction commit or as a result of the flush operation. NOTE: The persist operation always considers entities that are not yet known to this EntityManager as NEW. Do not pass detached entities to the persist operation.
public persist ( $entity )
Beispiel #1
1
 /**
  * @param EntityManager $em
  * @param array $imagesArray
  * @param Advertisment $adv
  * @return array
  */
 public static function uploadImages(EntityManager $em, $imagesArray, $adv)
 {
     $dummyImage = '/resources/images/adv-default.png';
     $basePath = 'uploads/' . $adv->getId();
     $uploadedImages = array();
     $adv = $em->getRepository('NaidusvoeBundle:Advertisment')->find($adv->getId());
     $fs = new Filesystem();
     $counter = 1;
     if ($imagesArray) {
         foreach ($imagesArray as $image) {
             $image = (object) $image;
             if ($image->image !== null) {
                 $imagePath = $basePath . '/' . $counter . '.jpg';
                 $image = explode(',', $image->image);
                 $image = base64_decode($image[1]);
                 $fs->dumpFile($imagePath, $image);
                 $attachment = new Attachment();
                 $attachment->setAdvertisment($adv);
                 $attachment->setImage($imagePath);
                 $em->persist($attachment);
                 $uploadedImages[] = $attachment;
                 $counter++;
             }
         }
     }
     if ($counter === 1) {
         $attachment = new Attachment();
         $attachment->setAdvertisment($adv);
         $attachment->setImage($dummyImage);
         $em->persist($attachment);
         $uploadedImages[] = $attachment;
     }
     return $uploadedImages;
 }
 /**
  * @param PostFlushEventArgs $args
  */
 public function postFlush(PostFlushEventArgs $args)
 {
     if ($this->isInProgress) {
         return;
     }
     $this->initializeFromEventArgs($args);
     if (count($this->queued) > 0) {
         $toOutDate = [];
         foreach ($this->queued as $customerIdentity => $groupedByEntityUpdates) {
             foreach ($groupedByEntityUpdates as $data) {
                 /** @var Account $account */
                 $account = is_object($data['account']) ? $data['account'] : $this->em->getReference('OroCRMAccountBundle:Account', $data['account']);
                 /** @var Channel $channel */
                 $channel = is_object($data['channel']) ? $data['channel'] : $this->em->getReference('OroCRMChannelBundle:Channel', $data['channel']);
                 $entity = $this->createHistoryEntry($customerIdentity, $account, $channel);
                 $toOutDate[] = [$account, $channel, $entity];
                 $this->em->persist($entity);
             }
         }
         $this->isInProgress = true;
         $this->em->flush();
         foreach (array_chunk($toOutDate, self::MAX_UPDATE_CHUNK_SIZE) as $chunks) {
             $this->lifetimeRepo->massStatusUpdate($chunks);
         }
         $this->queued = [];
         $this->isInProgress = false;
     }
 }
 public function clearCustomerShoppingCarts()
 {
     $customer = $this->getCustomer();
     $customer->setSessionId(new ArrayCollection());
     $this->entityManager->persist($customer);
     $this->entityManager->flush();
 }
Beispiel #4
0
 protected function createImage(LoaderResult $loaderResult, $mimeType) : ImageInterface
 {
     $image = ($image = new Image())->setPath($loaderResult->getPath())->setSize($loaderResult->getSize())->setMimeType($mimeType)->setUploadedAt(new \DateTime());
     $this->em->persist($image);
     $this->em->flush($image);
     return $image;
 }
 /**
  * Imports units.
  *
  * @return array An array with the keys "skipped" and "imported" which contain the number of units skipped and imported
  * @throws \Exception If an error occured
  */
 public function importUnits()
 {
     $path = $this->kernel->locateResource(self::UNIT_PATH . self::UNIT_DATA);
     $yaml = new Parser();
     $data = $yaml->parse(file_get_contents($path));
     $count = 0;
     $skipped = 0;
     foreach ($data as $unitName => $unitData) {
         $unit = $this->getUnit($unitName);
         if ($unit === null) {
             $unit = new Unit();
             $unit->setName($unitName);
             $unit->setSymbol($unitData["symbol"]);
             if (array_key_exists("prefixes", $unitData)) {
                 if (!is_array($unitData["prefixes"])) {
                     throw new \Exception($unitName . " doesn't contain a prefix list, or the prefix list is not an array.");
                 }
                 foreach ($unitData["prefixes"] as $name) {
                     $prefix = $this->getSiPrefix($name);
                     if ($prefix === null) {
                         throw new \Exception("Unable to find SI Prefix " . $name);
                     }
                     $unit->getPrefixes()->add($prefix);
                 }
             }
             $this->entityManager->persist($unit);
             $this->entityManager->flush();
             $count++;
         } else {
             $skipped++;
         }
     }
     return array("imported" => $count, "skipped" => $skipped);
 }
 public function schedule()
 {
     $licenseRepo = $this->em->getRepository('AppBundle:License');
     $drillSchemaEventsRepo = $this->em->getRepository('AppBundle:DrillSchemaEvent');
     $licensesWithoutSchema = $licenseRepo->findWithoutRegisteredSchema();
     foreach ($licensesWithoutSchema as $license) {
         $drillSchemaEvents = $drillSchemaEventsRepo->findByAddonKey($license->getAddonKey());
         if (empty($drillSchemaEvents)) {
             continue;
         }
         $drillRegisteredSchema = new DrillRegisteredSchema();
         $drillRegisteredSchema->setLicenseId($license->getLicenseId());
         $drillRegisteredSchema->setAddonKey($license->getAddonKey());
         $this->em->persist($drillRegisteredSchema);
         foreach ($drillSchemaEvents as $drillSchemaEvent) {
             $sendDate = $this->calculateSendDate($drillSchemaEvent, $license);
             $today = new \DateTime();
             // prevent creating events from past
             if ($sendDate < $today->modify('-2 days')) {
                 continue;
             }
             $drillRegisteredEvent = new DrillRegisteredEvent();
             $drillRegisteredEvent->setDrillRegisteredSchema($drillRegisteredSchema);
             $drillRegisteredEvent->setDrillSchemaEvent($drillSchemaEvent);
             // Calculate
             $drillRegisteredEvent->setSendDate($sendDate);
             $drillRegisteredEvent->setStatus('new');
             $this->em->persist($drillRegisteredEvent);
         }
     }
     $this->em->flush();
 }
 /**
  * @param ProviderLocation $providerLocation
  * @param bool             $withFlush
  */
 public function save(ProviderLocation $providerLocation, $withFlush = true)
 {
     $this->entityManager->persist($providerLocation);
     if ($withFlush) {
         $this->entityManager->flush();
     }
 }
Beispiel #8
0
 /**
  * @param Widget $widget
  * @param User $user
  * @return WidgetState
  */
 protected function createWidgetState(Widget $widget, User $user)
 {
     $state = new WidgetState();
     $state->setOwner($user)->setWidget($widget);
     $this->entityManager->persist($state);
     return $state;
 }
 /**
  * Process onReslonse event, updates user history information
  *
  * @param  FilterResponseEvent $event
  * @return bool|void
  */
 public function onResponse(FilterResponseEvent $event)
 {
     if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
         // Do not do anything
         return;
     }
     $request = $event->getRequest();
     $response = $event->getResponse();
     // do not process requests other than in html format
     // with 200 OK status using GET method and not _internal and _wdt
     if (!$this->matchRequest($response, $request)) {
         return false;
     }
     $postArray = ['url' => $request->getRequestUri(), 'user' => $this->user];
     /** @var $historyItem  NavigationHistoryItem */
     $historyItem = $this->em->getRepository('Oro\\Bundle\\NavigationBundle\\Entity\\NavigationHistoryItem')->findOneBy($postArray);
     if (!$historyItem) {
         /** @var $historyItem \Oro\Bundle\NavigationBundle\Entity\NavigationItemInterface */
         $historyItem = $this->navItemFactory->createItem(NavigationHistoryItem::NAVIGATION_HISTORY_ITEM_TYPE, $postArray);
     }
     $historyItem->setTitle($this->titleService->getSerialized());
     // force update
     $historyItem->doUpdate();
     $this->em->persist($historyItem);
     $this->em->flush($historyItem);
     return true;
 }
Beispiel #10
0
 /**
  * {@inheritdoc}
  */
 public function add(TextNodeInterface $textNode, $save = false)
 {
     $this->em->persist($textNode);
     if (true === $save) {
         $this->save();
     }
 }
Beispiel #11
0
 /**
  * Duplicate Jam entities
  *
  * For details see
  * {@link http://stackoverflow.com/questions/9071094/how-to-re-save-the-entity-as-another-row-in-doctrine-2}
  *
  * @param Jam $entity
  * @param integer $count
  */
 public function duplicate(Jam $entity, $count = 0)
 {
     for ($i = 0; $i < $count; $i++) {
         $this->em->persist($this->cloneService->cloneObject($entity));
     }
     $this->em->flush();
 }
 public function updateAttendee(AttendeeInterface $attendee)
 {
     $attendee->setUpdatedAt(new \DateTime());
     $this->em->persist($attendee);
     $this->em->flush();
     return true;
 }
Beispiel #13
0
 public function create($data)
 {
     $person = new Person($data->first_name, $data->last_name);
     if (isset($data->middle_name)) {
         $person->setMiddleName($data->middle_name);
     }
     if (isset($data->display_name)) {
         $person->setDisplayName($data->display_name);
     }
     $account = new Account($person);
     switch ($data->status) {
         case 'active':
             $account->setStatus(AccountInterface::STATUS_ACTIVE);
             break;
         case 'inactive':
             $account->setStatus(AccountInterface::STATUS_INACTIVE);
             break;
         default:
             throw new RuntimeException('Invalid account status provided.');
     }
     $this->entityManager->persist($person);
     $this->entityManager->persist($account);
     $this->entityManager->flush($account);
     return new AccountEntity($account);
 }
Beispiel #14
0
 /**
  * {@inheritdoc}
  */
 public function add(SiteInterface $site, $save = false)
 {
     $this->em->persist($site);
     if (true === $save) {
         $this->save();
     }
 }
 /**
  * Make sure the menu objects exist in the database for each locale.
  */
 public function makeSureMenusExist()
 {
     $locales = array_unique($this->getLocales());
     $required = array();
     foreach ($this->menuNames as $name) {
         $required[$name] = $locales;
     }
     $menuObjects = $this->em->getRepository('KunstmaanMenuBundle:Menu')->findAll();
     foreach ($menuObjects as $menu) {
         if (array_key_exists($menu->getName(), $required)) {
             $index = array_search($menu->getLocale(), $required[$menu->getName()]);
             if ($index !== false) {
                 unset($required[$menu->getName()][$index]);
             }
         }
     }
     foreach ($required as $name => $locales) {
         foreach ($locales as $locale) {
             $menu = new Menu();
             $menu->setName($name);
             $menu->setLocale($locale);
             $this->em->persist($menu);
         }
     }
     $this->em->flush();
 }
 /**
  * Processes the form and build the Response object
  *
  * @param Request $request
  * @param Organization $organization
  * @return Response|static
  * @throws BadRequestHttpException
  */
 public function processForm(Request $request, Organization $organization)
 {
     $statusCode = !$this->em->contains($organization) ? 201 : 204;
     $form = $this->container->get('form.factory')->create(OrganizationType::class, $organization);
     $formData = json_decode($request->getContent(), true);
     $form->submit($this->prepareFormData($formData));
     if (!$form->isValid()) {
         return View::create($form, 400);
     }
     if (!$this->em->contains($organization)) {
         $this->em->persist($organization);
     }
     try {
         $this->em->flush();
     } catch (\Exception $e) {
         $pdoException = $e->getPrevious();
         // unique constraint
         if ($pdoException->getCode() === '23000') {
             throw new BadRequestHttpException('Error 23000!');
         }
         throw new BadRequestHttpException('Unknown error code: ' . $pdoException->getCode());
     }
     $response = new Response();
     $response->setStatusCode($statusCode);
     if (201 === $statusCode) {
         $response->headers->set('Access-Control-Expose-Headers', 'Location');
         $response->headers->set('Location', $this->container->get('router')->generate('api_v1_get_organization', ['organization' => $organization->getId()], UrlGeneratorInterface::RELATIVE_PATH));
     }
     return $response;
 }
 /**
  * onAuthenticationSuccess
  *
  * @author     Joe Sexton <*****@*****.**>
  * @param     InteractiveLoginEvent $event
  */
 public function onAuthenticationSuccess(InteractiveLoginEvent $event)
 {
     $user = $this->getUser();
     $user->setLoginAttempts(0);
     $this->em->persist($user);
     $this->em->flush();
 }
 public function testRemovePage()
 {
     $page = new Page();
     $page->setTitle('Test')->setContent('<p>test</p>')->setCurrentSlugUrl('/remove');
     $this->entityManager->persist($page);
     $childPage1 = new Page();
     $childPage1->setTitle('Test child Page 1')->setContent('<p>test child page</p>')->setCurrentSlugUrl('/child1');
     $this->entityManager->persist($childPage1);
     $childPage2 = new Page();
     $childPage2->setTitle('Test child Page 2')->setContent('<p>test child page</p>')->setCurrentSlugUrl('/child2');
     $this->entityManager->persist($childPage2);
     $page->addChildPage($childPage1);
     $page->addChildPage($childPage2);
     $this->entityManager->flush($page);
     $pageSlugId = $page->getCurrentSlug()->getId();
     $childPage1SlugId = $childPage1->getCurrentSlug()->getId();
     $childPage2SlugId = $childPage2->getCurrentSlug()->getId();
     $this->entityManager->remove($page);
     $this->entityManager->flush();
     // make sure data updated correctly
     $this->entityManager->clear();
     $this->assertNull($this->entityManager->find('OroB2BRedirectBundle:Slug', $pageSlugId));
     $this->assertNull($this->entityManager->find('OroB2BRedirectBundle:Slug', $childPage1SlugId));
     $this->assertNull($this->entityManager->find('OroB2BRedirectBundle:Slug', $childPage2SlugId));
 }
 /**
  * Run all new tasks
  *
  * @throws \InvalidArgumentException
  * @return void
  */
 public function runJobs()
 {
     $cronRepo = $this->entityManager->getRepository('KingdomHallTaskBundle:Task');
     $jobs = $cronRepo->getNewJobs();
     foreach ($jobs as $job) {
         $task = $job->getTask();
         if (!array_key_exists($task, $this->taskServices)) {
             throw new \InvalidArgumentException($task . ' service not found. Available task services : ' . implode(', ', array_keys($this->taskServices)));
         }
         $service = $this->taskServices[$task];
         $parameters = json_decode($job->getParameters());
         $job->setStatus(Task::TASK_STATUS_PENDING);
         $this->entityManager->persist($job);
         $this->entityManager->flush();
         try {
             $service->process($job->getId(), $parameters);
         } catch (\Exception $e) {
             $job->setStatus(Task::TASK_STATUS_ERROR);
             $job->setErrorMessage($e->getMessage());
             $this->entityManager->persist($job);
             $this->entityManager->flush();
             return;
         }
         $job->setStatus(Task::TASK_STATUS_SUCCESS);
         $this->entityManager->persist($job);
         $this->entityManager->flush();
     }
     // Purge old jobs
     $cronRepo->purge();
 }
 /**
  * @param string $name
  * @param mixed $value string, int, boolean, object, ...
  * @param int $owner
  * @param null|string $group
  * @return $this
  * @throws \Doctrine\ORM\OptimisticLockException
  * @throws \Doctrine\ORM\ORMInvalidArgumentException
  */
 public function set($name, $value, $owner = null, $group = null)
 {
     try {
         $item = $this->get($name, $owner, $group);
     } catch (PropertyNotExistsException $ex) {
         $item = null;
     }
     $nname = null !== $owner ? $name . '_' . $owner : $name;
     if (null !== $item || !(array_key_exists($name, $this->defaults) && $this->defaults[$name] === $item)) {
         $setting = $this->em->getRepository('SettingsBundle:Setting')->findOneBy(['name' => $nname, 'ownerId' => $owner, 'group' => $group]);
         if (null === $setting) {
             $setting = new Setting();
         }
     } else {
         $setting = new Setting();
     }
     $setting->setName($nname);
     $setting->setValue($value);
     $setting->setOwnerId($owner);
     $setting->setGroup($group);
     $this->em->persist($setting);
     $this->em->flush($setting);
     if ($this->cacheProvider) {
         $this->cacheProvider->save($nname, serialize($setting));
     }
     return $this;
 }
 /**
  * @param Organization $organization
  * @param bool         $flush
  */
 public function updateOrganization(Organization $organization, $flush = true)
 {
     $this->em->persist($organization);
     if ($flush) {
         $this->em->flush();
     }
 }
 public function onKernelTerminate(PostResponseEvent $event)
 {
     /** @var Request $request */
     $request = $event->getRequest();
     if (!$this->isEnable || !$this->isLoggableRequest($request)) {
         return;
     }
     try {
         /** @var Response $response */
         $response = $event->getResponse();
         $route = $request->get('_route');
         $content = $this->cleanSensitiveContent($route, $request->getContent());
         $token = $this->tokenStorage->getToken();
         $user = !is_null($token) ? $token->getUser() : null;
         $logRequest = new LogRequest();
         $logRequest->setRoute($route)->setPath($request->getPathInfo())->setMethod($request->getMethod())->setQuery(urldecode($request->getQueryString()))->setContent($content)->setStatus($response->getStatusCode())->setIp($request->getClientIp())->setUser(!is_string($user) ? $user : null);
         if ($this->logResponse($response)) {
             $logRequest->setResponse($response->getContent());
         }
         $this->em->persist($logRequest);
         $this->em->flush();
     } catch (\Exception $e) {
         $this->logger->error(sprintf("LogRequest couldn't be persist : %s", $e->getMessage()));
     }
 }
 /**
  * @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);
     /** @var  EntityManager $em */
     $em = $this->client->getContainer()->get('doctrine.orm.entity_manager');
     $widgetRepository = $em->getRepository('OroDashboardBundle:Widget');
     foreach ($widgets as $key => $widget) {
         $updatedWidget = $widgetRepository->findOneBy(['id' => $widget->getId()]);
         $this->assertEquals($expectedPositions[$key], $updatedWidget->getLayoutPosition());
     }
 }
Beispiel #24
0
 public function get($name)
 {
     $uppername = strtoupper($name);
     /*
             //create unique key for kind and uppercased name
             $key = md5('kind.' . $uppername);
             //cache has value return this one
             $cached = Cache::get($key);
             if ($cached) {
                 return $cached;
             }*/
     //find or create in store
     $kind = $this->em->getRepository($this->class)->findOneBy(['name' => $uppername]);
     if (!$kind) {
         $kind = new Kind(new Name($uppername));
         $this->em->persist($kind);
         $this->em->flush();
     }
     /*
             //cache it for next request
             Cache::forever($key, $kind);
             return Cache::get($key);
     */
     return $kind;
 }
Beispiel #25
0
 /**
  * Update the user "lastActivity" on each request
  *
  * @param FilterControllerEvent $event
  */
 public function onCoreController(FilterControllerEvent $event)
 {
     // Here we are checking that the current request is a "MASTER_REQUEST",
     // and ignore any
     // subrequest in the process (for example when
     // doing a render() in a twig template)
     if ($event->getRequestType() !== HttpKernel::MASTER_REQUEST) {
         return;
     }
     // We are checking a token authentification is available before using
     // the User
     if ($this->securityContext->getToken()) {
         $user = $this->securityContext->getToken()->getUser();
         // We are using a delay during wich the user will be considered as
         // still active, in order to
         // avoid too much UPDATE in the
         // database
         // $delay = new \DateTime ();
         // $delay->setTimestamp (strtotime ('2 minutes ago'));
         // We are checking the Admin class in order to be certain we can
         // call "getLastActivity".
         // && $user->getLastActivity() < $delay) {
         if ($user instanceof User) {
             $user->isActiveNow();
             $this->em->persist($user);
             $this->em->flush();
         }
     }
 }
 /**
  * @param int $id
  * @param string $state
  */
 protected function saveState($id, $state)
 {
     $notification = $this->getById($id);
     $notification->setState($state);
     $this->entityManager->persist($notification);
     $this->entityManager->flush();
 }
 public function down(Schema $schema)
 {
     $lookingFor = new Profile\LookingFor();
     $lookingFor->setName('Intimate');
     $this->em->persist($lookingFor);
     $this->em->flush();
 }
Beispiel #28
0
 /**
  * @param $entity
  * @param bool $andFlush
  */
 public function update($entity, $andFlush = true)
 {
     $this->em->persist($entity);
     if ($andFlush) {
         $this->em->flush();
     }
 }
Beispiel #29
0
 protected function setUp()
 {
     if (!class_exists('Symfony\\Component\\Form\\Form')) {
         $this->markTestSkipped('The "Form" component is not available');
     }
     if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) {
         $this->markTestSkipped('Doctrine DBAL is not available.');
     }
     if (!class_exists('Doctrine\\Common\\Version')) {
         $this->markTestSkipped('Doctrine Common is not available.');
     }
     if (!class_exists('Doctrine\\ORM\\EntityManager')) {
         $this->markTestSkipped('Doctrine ORM is not available.');
     }
     $this->em = DoctrineOrmTestCase::createTestEntityManager();
     parent::setUp();
     $schemaTool = new SchemaTool($this->em);
     $classes = array($this->em->getClassMetadata(self::ENTITY_CLASS));
     try {
         $schemaTool->dropSchema($classes);
     } catch (\Exception $e) {
     }
     try {
         $schemaTool->createSchema($classes);
     } catch (\Exception $e) {
     }
     $ids = range(1, 300);
     foreach ($ids as $id) {
         $name = 65 + chr($id % 57);
         $this->em->persist(new SingleIdentEntity($id, $name));
     }
     $this->em->flush();
 }
Beispiel #30
0
 protected static function browseTree($tag, EntityManager $em)
 {
     $childObj = [];
     $sourceObj = [];
     foreach ($tag->getChildren() as $child) {
         $childObj[] = static::browseTree($child);
     }
     $tag->getChildren()->clear();
     foreach ($tag->getTranslatedTags() as $tagTranslation) {
         $trans = $em->getRepository("RZ\\Roadiz\\Core\\Entities\\Translation")->findOneByLocale($tagTranslation->getTranslation()->getLocale());
         if (empty($trans)) {
             $trans = new Translation();
             $trans->setLocale($tagTranslation->getTranslation()->getLocale());
             $trans->setName(Translation::$availableLocales[$tagTranslation->getTranslation()->getLocale()]);
             $em->persist($trans);
         }
         $tagTranslation->setTranslation($trans);
         $tagTranslation->setTag(null);
         $em->persist($tagTranslation);
         $sourceObj[] = $tagTranslation;
     }
     $em->persist($tag);
     foreach ($childObj as $child) {
         $child->setParent($tag);
     }
     foreach ($sourceObj as $tagTranslation) {
         $tagTranslation->setTag($tag);
     }
     $em->flush();
     return $tag;
 }