public function getOrderRequest($sessionId) { /** @var PayuOrderRequest $orderRequest */ $orderRequest = $this->em->find($this->orderRequestClass, $sessionId); if (!$orderRequest) { throw new EntityNotFoundException(); } return $orderRequest; }
/** * @param $value * @return object|null */ public function validate($value) { if (isset($this->valuesCallback)) { $values = call_user_func($this->valuesCallback, $value); return $this->em->getRepository($this->entityClass)->findOneBy($values); } elseif ($this->identifierField) { return boolval($this->em->getRepository($this->entityClass)->findOneBy([$this->identifierField => $value])); } return boolval($this->em->find($this->entityClass, $value)); }
/** * @param array $countries */ public function saveCountries($countries) { foreach ($countries as $country) { if ($this->em->find('MainBundle:Country', $country->getCodeCountry())) { $this->em->merge($country); } else { $this->em->persist($country); } } $this->em->flush(); }
/** * @param int $pageId * * @return Pages */ protected function updatePending($pageId) { $pageEntity = $this->entityManager->find('Application\\V1\\Entity\\Pages', $pageId, LockMode::PESSIMISTIC_WRITE); $imagesCnt = $pageEntity->getPendingImagesCnt(); if ($imagesCnt > 0) { $pageEntity->setPendingImagesCnt($imagesCnt - 1); if ($pageEntity->getPendingImagesCnt() == 0) { $pageEntity->setStatus(PageInterface::STATUS_DONE); } } return $pageEntity; }
public function saveRegId($regId, $section) { $regIdDb = $this->em->find('MainBundle:RegId', $regId); $section = $this->em->find('MainBundle:Section', $section); if ($regIdDb) { $regIdDb->setSection($section)->setUpdatedAt(); } else { $regIdDb = $this->regIdCreator->createRegId($regId, $section); $this->em->persist($regIdDb); } $this->em->flush(); return $regIdDb; }
public function move(Category $category, $parentId, $newPosition) { if ($parentId) { $parentCategory = $this->em->find('MainBundle:Category', $parentId); $newSiblings = $parentCategory->getChildren(); } else { $guide = $category->getGuide(); $newSiblings = $guide->getCategoriesWithoutParent(); } $oldPosition = $category->getPosition(); // if we just move the position if ($category->getParent() == null && $parentId == null || $category->getParent() != null && $category->getParent()->getId() == $parentId) { if ($oldPosition > $newPosition) { foreach ($newSiblings as $child) { if ($child->getPosition() >= $newPosition && $child->getPosition() < $oldPosition) { $child->setPosition($child->getPosition() + 1); } $this->em->persist($child); } } else { foreach ($newSiblings as $child) { if ($child->getPosition() <= $newPosition && $child->getPosition() > $oldPosition) { $child->setPosition($child->getPosition() - 1); } $this->em->persist($child); } } } else { $oldSiblings = $category->getParent() ? $category->getParent()->getChildren() : $category->getGuide()->getCategoriesWithoutParent(); foreach ($oldSiblings as $child) { if ($child->getPosition() >= $oldPosition) { $child->setPosition($child->getPosition() - 1); } $this->em->persist($child); } foreach ($newSiblings as $child) { if ($child->getPosition() >= $newPosition) { $child->setPosition($child->getPosition() + 1); } $this->em->persist($child); } } $category->setPosition($newPosition); if (isset($parentCategory)) { $category->setParent($parentCategory); } else { $category->setParent(null); } $this->em->persist($category); $this->em->flush(); }
/** * @param object $object * * @return object */ private function reFetchObject($object) { $metadata = $this->entityManager->getClassMetadata(get_class($object)); $freshValue = $this->entityManager->find($metadata->getName(), $metadata->getIdentifierValues($object)); if (!$freshValue) { throw MissingBatchItemException::fromInvalidReference($metadata, $object); } return $freshValue; }
/** * {@inheritdoc} */ public function get($key) { if (!$this->initialized && $this->association['fetch'] === ClassMetadata::FETCH_EXTRA_LAZY && isset($this->association['indexBy'])) { if (!$this->typeClass->isIdentifierComposite && $this->typeClass->isIdentifier($this->association['indexBy'])) { return $this->em->find($this->typeClass->name, $key); } return $this->em->getUnitOfWork()->getCollectionPersister($this->association)->get($this, $key); } return parent::get($key); }
/** * Process form * * @param ContactPhone $entity * * @return bool True on successful processing, false otherwise * * @throws AccessDeniedException */ public function process(ContactPhone $entity) { $this->form->setData($entity); $submitData = ['phone' => $this->request->request->get('phone'), 'primary' => $this->request->request->get('primary')]; if (in_array($this->request->getMethod(), ['POST', 'PUT'])) { $this->form->submit($submitData); if ($this->form->isValid() && $this->request->request->get('contactId')) { $contact = $this->manager->find('OroCRMContactBundle:Contact', $this->request->request->get('contactId')); if (!$this->securityFacade->isGranted('EDIT', $contact)) { throw new AccessDeniedException(); } if ($contact->getPrimaryPhone() && $this->request->request->get('primary') === true) { return false; } $this->onSuccess($entity, $contact); return true; } } return false; }
/** * @param Request $request * @param Response $response * @param $args * @return Response * @throws \Doctrine\ORM\EntityNotFoundException */ public function remove(Request $request, Response $response, $args) { foreach (explode(',', $request->getHeader('id')[0]) as $id) { $ticket = $this->em->find('App\\Entity\\Ticket', $id); if ($ticket) { $this->em->remove($ticket); } else { throw new EntityNotFoundException(); } } $this->em->flush(); return $response; }
public function execute() { $payload = $this->getContent(); echo "processing >> " . $payload['page_url'] . " >> for id >> " . $payload['page_id'] . "\n"; /* @var \Application\V1\Entity\Pages $pageEntity */ $pageEntity = $this->entityManager->find('Application\\V1\\Entity\\Pages', $payload['page_id']); try { $this->httpClient->setUri($payload['page_url']); $response = $this->httpClient->send(); $document = new Document($response->getBody()); $manager = $this->grabImageQueue->getJobPluginManager(); $jobs = []; $parsedPageUrl = parse_url($this->httpClient->getRequest()->getUriString()); $cnt = 0; /* @var \DOMElement $node */ foreach ($this->documentQuery->execute('//body//img', $document) as $node) { $job = $manager->get('Application\\QueueJob\\GrabImage'); $src = $this->normalizeSchemeAndHost($node->getAttribute('src'), $parsedPageUrl['scheme'], $parsedPageUrl['host']); $ext = strtolower(pathinfo($src, PATHINFO_EXTENSION)); $job->setContent(['image_src' => $src, 'image_ext' => $ext, 'page_id' => $payload['page_id']]); $jobs[] = $job; $cnt++; } if ($cnt < 1) { $pageEntity->setStatus(PageInterface::STATUS_DONE); } else { $pageEntity->setStatus(PageInterface::STATUS_RUNNING); } $pageEntity->setPendingImagesCnt($cnt); $pageEntity->setTotalImagesCnt($cnt); $this->entityManager->flush(); foreach ($jobs as $job) { $this->grabImageQueue->push($job); } echo "Jobs to push >> " . count($jobs) . " count pending images >>" . $cnt . "\n"; } catch (\Exception $e) { echo 'Exception: >> ' . $e->getMessage(); $pageEntity->setErrorMessage($e->getMessage()); if ($pageEntity->getStatusNumeric() == PageInterface::STATUS_RECOVERING) { $pageEntity->setStatus(PageInterface::STATUS_ERROR); $this->entityManager->flush(); return WorkerEvent::JOB_STATUS_FAILURE; } else { $pageEntity->setStatus(PageInterface::STATUS_RECOVERING); $this->entityManager->flush(); throw new ReleasableException(array('priority' => 10, 'delay' => 15)); } } }
/** * @return User|null */ protected function getUser() { if (!($token = $this->tokenStorage->getToken())) { return null; } $user = $token->getUser(); /** * Check cases when user is not in the entity manager * (e.g. after clear or if it is in the different entity manager) */ if ($user instanceof User && !$this->entityManager->contains($user)) { $user = $this->entityManager->find('OroUserBundle:User', $user->getId()); } return $user; }
/** * @param array $criteria The criteria. * @return object The object. */ public function findOneBy(array $criteria) { return $this->em->find(Log::class, $criteria); }
/** * @param object $entity * @param object $managedCopy * * @throws ORMException * @throws OptimisticLockException * @throws TransactionRequiredException */ private function mergeEntityStateIntoManagedCopy($entity, $managedCopy) { $class = $this->em->getClassMetadata(get_class($entity)); foreach ($this->reflectionPropertiesGetter->getProperties($class->name) as $prop) { $name = $prop->name; $prop->setAccessible(true); if (!isset($class->associationMappings[$name])) { if (!$class->isIdentifier($name)) { $prop->setValue($managedCopy, $prop->getValue($entity)); } } else { $assoc2 = $class->associationMappings[$name]; if ($assoc2['type'] & ClassMetadata::TO_ONE) { $other = $prop->getValue($entity); if ($other === null) { $prop->setValue($managedCopy, null); } else { if ($other instanceof Proxy && !$other->__isInitialized()) { // do not merge fields marked lazy that have not been fetched. return; } if (!$assoc2['isCascadeMerge']) { if ($this->getEntityState($other) === self::STATE_DETACHED) { $targetClass = $this->em->getClassMetadata($assoc2['targetEntity']); $relatedId = $targetClass->getIdentifierValues($other); if ($targetClass->subClasses) { $other = $this->em->find($targetClass->name, $relatedId); } else { $other = $this->em->getProxyFactory()->getProxy($assoc2['targetEntity'], $relatedId); $this->registerManaged($other, $relatedId, array()); } } $prop->setValue($managedCopy, $other); } } } else { $mergeCol = $prop->getValue($entity); if ($mergeCol instanceof PersistentCollection && !$mergeCol->isInitialized()) { // do not merge fields marked lazy that have not been fetched. // keep the lazy persistent collection of the managed copy. return; } $managedCol = $prop->getValue($managedCopy); if (!$managedCol) { $managedCol = new PersistentCollection($this->em, $this->em->getClassMetadata($assoc2['targetEntity']), new ArrayCollection()); $managedCol->setOwner($managedCopy, $assoc2); $prop->setValue($managedCopy, $managedCol); $this->originalEntityData[spl_object_hash($entity)][$name] = $managedCol; } if ($assoc2['isCascadeMerge']) { $managedCol->initialize(); // clear and set dirty a managed collection if its not also the same collection to merge from. if (!$managedCol->isEmpty() && $managedCol !== $mergeCol) { $managedCol->unwrap()->clear(); $managedCol->setDirty(true); if ($assoc2['isOwningSide'] && $assoc2['type'] == ClassMetadata::MANY_TO_MANY && $class->isChangeTrackingNotify()) { $this->scheduleForDirtyCheck($managedCopy); } } } } } if ($class->isChangeTrackingNotify()) { // Just treat all properties as changed, there is no other choice. $this->propertyChanged($managedCopy, $name, null, $prop->getValue($managedCopy)); } } }
/** * @inheritdoc */ public function load(LinkInterface $link) { return $this->entityManager->find($this->subjectRegistry->getByAlias($link->getResourceType())->getClass(), $link->getResourceId()); }
/** * {@inheritdoc} */ public function find($entityName, $id, $lockMode = null, $lockVersion = null) { return $this->wrapped->find($entityName, $id, $lockMode, $lockVersion); }
/** * Returns news-item with given id. * * @param int $id * * @return NewsItem */ public function read($id) { return $this->entityManager->find(NewsItem::class, $id); }
private function findEntity(EntityManagerInterface $em, $label) { $times = 10; $size = 500; $countries = array(); $startPersist = microtime(true); echo PHP_EOL . $label; for ($i = 0; $i < $size; $i++) { $country = new Country("Country {$i}"); $em->persist($country); $countries[] = $country; } $em->flush(); $em->clear(); printf("\n[%s] persist %s countries", number_format(microtime(true) - $startPersist, 6), $size); $startFind = microtime(true); for ($i = 0; $i <= $times; $i++) { foreach ($countries as $country) { $em->find(Country::CLASSNAME, $country->getId()); $em->clear(); } } printf("\n[%s] find %s countries (%s times)", number_format(microtime(true) - $startFind, 6), $size, $times); printf("\n%s\n", str_repeat('-', 50)); }
/** * @param string $setting * @return Setting */ public function getSetting($setting) { return $this->entityManager->find("Eye4web\\ZfcUser\\Settings\\Entity\\Setting", $setting); }
/** * INTERNAL: * Creates an entity. Used for reconstitution of persistent entities. * * Internal note: Highly performance-sensitive method. * * @ignore * * @param string $className The name of the entity class. * @param array $data The data for the entity. * @param array $hints Any hints to account for during reconstitution/lookup of the entity. * * @return object The managed entity instance. * * @todo Rename: getOrCreateEntity */ public function createEntity($className, array $data, &$hints = array()) { $class = $this->em->getClassMetadata($className); //$isReadOnly = isset($hints[Query::HINT_READ_ONLY]); $id = $this->identifierFlattener->flattenIdentifier($class, $data); $idHash = implode(' ', $id); if (isset($this->identityMap[$class->rootEntityName][$idHash])) { $entity = $this->identityMap[$class->rootEntityName][$idHash]; $oid = spl_object_hash($entity); if (isset($hints[Query::HINT_REFRESH]) && isset($hints[Query::HINT_REFRESH_ENTITY]) && ($unmanagedProxy = $hints[Query::HINT_REFRESH_ENTITY]) !== $entity && $unmanagedProxy instanceof Proxy && $this->isIdentifierEquals($unmanagedProxy, $entity)) { // DDC-1238 - we have a managed instance, but it isn't the provided one. // Therefore we clear its identifier. Also, we must re-fetch metadata since the // refreshed object may be anything foreach ($class->identifier as $fieldName) { $class->reflFields[$fieldName]->setValue($unmanagedProxy, null); } return $unmanagedProxy; } if ($entity instanceof Proxy && !$entity->__isInitialized()) { $entity->__setInitialized(true); $overrideLocalValues = true; if ($entity instanceof NotifyPropertyChanged) { $entity->addPropertyChangedListener($this); } } else { $overrideLocalValues = isset($hints[Query::HINT_REFRESH]); // If only a specific entity is set to refresh, check that it's the one if (isset($hints[Query::HINT_REFRESH_ENTITY])) { $overrideLocalValues = $hints[Query::HINT_REFRESH_ENTITY] === $entity; } } if ($overrideLocalValues) { // inject ObjectManager upon refresh. if ($entity instanceof ObjectManagerAware) { $entity->injectObjectManager($this->em, $class); } $this->originalEntityData[$oid] = $data; } } else { $entity = $this->newInstance($class); $oid = spl_object_hash($entity); $this->entityIdentifiers[$oid] = $id; $this->entityStates[$oid] = self::STATE_MANAGED; $this->originalEntityData[$oid] = $data; $this->identityMap[$class->rootEntityName][$idHash] = $entity; if ($entity instanceof NotifyPropertyChanged) { $entity->addPropertyChangedListener($this); } $overrideLocalValues = true; } if (!$overrideLocalValues) { return $entity; } foreach ($data as $field => $value) { if (isset($class->fieldMappings[$field])) { $class->reflFields[$field]->setValue($entity, $value); } } // Loading the entity right here, if its in the eager loading map get rid of it there. unset($this->eagerLoadingEntities[$class->rootEntityName][$idHash]); if (isset($this->eagerLoadingEntities[$class->rootEntityName]) && !$this->eagerLoadingEntities[$class->rootEntityName]) { unset($this->eagerLoadingEntities[$class->rootEntityName]); } // Properly initialize any unfetched associations, if partial objects are not allowed. if (isset($hints[Query::HINT_FORCE_PARTIAL_LOAD])) { return $entity; } foreach ($class->associationMappings as $field => $assoc) { // Check if the association is not among the fetch-joined associations already. if (isset($hints['fetchAlias']) && isset($hints['fetched'][$hints['fetchAlias']][$field])) { continue; } $targetClass = $this->em->getClassMetadata($assoc['targetEntity']); switch (true) { case $assoc['type'] & ClassMetadata::TO_ONE: if (!$assoc['isOwningSide']) { // use the given entity association if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) { $this->originalEntityData[$oid][$field] = $data[$field]; $class->reflFields[$field]->setValue($entity, $data[$field]); $targetClass->reflFields[$assoc['mappedBy']]->setValue($data[$field], $entity); continue 2; } // Inverse side of x-to-one can never be lazy $class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity)); continue 2; } // use the entity association if (isset($data[$field]) && is_object($data[$field]) && isset($this->entityStates[spl_object_hash($data[$field])])) { $class->reflFields[$field]->setValue($entity, $data[$field]); $this->originalEntityData[$oid][$field] = $data[$field]; continue; } $associatedId = array(); // TODO: Is this even computed right in all cases of composite keys? foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) { $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null; if ($joinColumnValue !== null) { if ($targetClass->containsForeignIdentifier) { $associatedId[$targetClass->getFieldForColumn($targetColumn)] = $joinColumnValue; } else { $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue; } } elseif ($targetClass->containsForeignIdentifier && in_array($targetClass->getFieldForColumn($targetColumn), $targetClass->identifier, true)) { // the missing key is part of target's entity primary key $associatedId = array(); break; } } if (!$associatedId) { // Foreign key is NULL $class->reflFields[$field]->setValue($entity, null); $this->originalEntityData[$oid][$field] = null; continue; } if (!isset($hints['fetchMode'][$class->name][$field])) { $hints['fetchMode'][$class->name][$field] = $assoc['fetch']; } // Foreign key is set // Check identity map first // FIXME: Can break easily with composite keys if join column values are in // wrong order. The correct order is the one in ClassMetadata#identifier. $relatedIdHash = implode(' ', $associatedId); switch (true) { case isset($this->identityMap[$targetClass->rootEntityName][$relatedIdHash]): $newValue = $this->identityMap[$targetClass->rootEntityName][$relatedIdHash]; // If this is an uninitialized proxy, we are deferring eager loads, // this association is marked as eager fetch, and its an uninitialized proxy (wtf!) // then we can append this entity for eager loading! if ($hints['fetchMode'][$class->name][$field] == ClassMetadata::FETCH_EAGER && isset($hints[self::HINT_DEFEREAGERLOAD]) && !$targetClass->isIdentifierComposite && $newValue instanceof Proxy && $newValue->__isInitialized__ === false) { $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId); } break; case $targetClass->subClasses: // If it might be a subtype, it can not be lazy. There isn't even // a way to solve this with deferred eager loading, which means putting // an entity with subclasses at a *-to-one location is really bad! (performance-wise) $newValue = $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity, $associatedId); break; default: switch (true) { // We are negating the condition here. Other cases will assume it is valid! case $hints['fetchMode'][$class->name][$field] !== ClassMetadata::FETCH_EAGER: $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId); break; // Deferred eager load only works for single identifier classes // Deferred eager load only works for single identifier classes case isset($hints[self::HINT_DEFEREAGERLOAD]) && !$targetClass->isIdentifierComposite: // TODO: Is there a faster approach? $this->eagerLoadingEntities[$targetClass->rootEntityName][$relatedIdHash] = current($associatedId); $newValue = $this->em->getProxyFactory()->getProxy($assoc['targetEntity'], $associatedId); break; default: // TODO: This is very imperformant, ignore it? $newValue = $this->em->find($assoc['targetEntity'], $associatedId); break; } // PERF: Inlined & optimized code from UnitOfWork#registerManaged() $newValueOid = spl_object_hash($newValue); $this->entityIdentifiers[$newValueOid] = $associatedId; $this->identityMap[$targetClass->rootEntityName][$relatedIdHash] = $newValue; if ($newValue instanceof NotifyPropertyChanged && (!$newValue instanceof Proxy || $newValue->__isInitialized())) { $newValue->addPropertyChangedListener($this); } $this->entityStates[$newValueOid] = self::STATE_MANAGED; // make sure that when an proxy is then finally loaded, $this->originalEntityData is set also! break; } $this->originalEntityData[$oid][$field] = $newValue; $class->reflFields[$field]->setValue($entity, $newValue); if ($assoc['inversedBy'] && $assoc['type'] & ClassMetadata::ONE_TO_ONE) { $inverseAssoc = $targetClass->associationMappings[$assoc['inversedBy']]; $targetClass->reflFields[$inverseAssoc['fieldName']]->setValue($newValue, $entity); } break; default: // Ignore if its a cached collection if (isset($hints[Query::HINT_CACHE_ENABLED]) && $class->getFieldValue($entity, $field) instanceof PersistentCollection) { break; } // use the given collection if (isset($data[$field]) && $data[$field] instanceof PersistentCollection) { $data[$field]->setOwner($entity, $assoc); $class->reflFields[$field]->setValue($entity, $data[$field]); $this->originalEntityData[$oid][$field] = $data[$field]; break; } // Inject collection $pColl = new PersistentCollection($this->em, $targetClass, new ArrayCollection()); $pColl->setOwner($entity, $assoc); $pColl->setInitialized(false); $reflField = $class->reflFields[$field]; $reflField->setValue($entity, $pColl); if ($assoc['fetch'] == ClassMetadata::FETCH_EAGER) { $this->loadCollection($pColl); $pColl->takeSnapshot(); } $this->originalEntityData[$oid][$field] = $pColl; break; } } if ($overrideLocalValues) { // defer invoking of postLoad event to hydration complete step $this->hydrationCompleteHandler->deferPostLoadInvoking($class, $entity); } return $entity; }
/** * @param $id * @return mixed */ public function find($id) { return $this->entityManager->find($this->getEntity(), $id); }