/**
  * {@inheritdoc}
  */
 public function convert($value)
 {
     if ($value) {
         return $this->em->getReference($this->entityClass, $value);
     }
     return null;
 }
 public function deserializeRelation(JsonDeserializationVisitor $visitor, $relation, array $type, Context $context)
 {
     $className = isset($type['params'][0]['name']) ? $type['params'][0]['name'] : null;
     if (!class_exists($className)) {
         throw new \InvalidArgumentException('Class name should be explicitly set for deserialization');
     }
     /** @var ClassMetadata $metadata */
     $metadata = $this->manager->getClassMetadata($className);
     if (!is_array($relation)) {
         return $this->manager->getReference($className, $relation);
     }
     $single = false;
     if ($metadata->isIdentifierComposite) {
         $single = true;
         foreach ($metadata->getIdentifierFieldNames() as $idName) {
             $single = $single && array_key_exists($idName, $relation);
         }
     }
     if ($single) {
         return $this->manager->getReference($className, $relation);
     }
     $objects = [];
     foreach ($relation as $idSet) {
         $objects[] = $this->manager->getReference($className, $idSet);
     }
     return $objects;
 }
 public function renderDeletePost()
 {
     //	$post = $this->getPostRepository()
     //			->find(1);
     // nekomunikuje s db, vyžaduje jistotu, že záznam s id existuje
     $post = $this->entityManager->getReference(Post::class, 1);
     $this->entityManager->remove($post);
     $this->entityManager->flush();
     die;
 }
 /**
  * Retrieves the entity data resolving cache entries
  *
  * @param \Doctrine\ORM\EntityManagerInterfac $em
  *
  * @return array
  */
 public function resolveAssociationEntries(EntityManagerInterface $em)
 {
     return array_map(function ($value) use($em) {
         if (!$value instanceof AssociationCacheEntry) {
             return $value;
         }
         return $em->getReference($value->class, $value->identifier);
     }, $this->data);
 }
 /**
  * @param string $fileName
  * @param int $userId
  * @param null|\DateTime $ignoreBeforeDate
  *
  * @return bool
  * @throws \AppBundle\Exception\WrongFileFormatException
  */
 public function importFromFile($fileName, $userId, DateTime $ignoreBeforeDate = null)
 {
     $content = file_get_contents($fileName);
     $content = mb_convert_encoding($content, 'UTF-8', 'UCS-2LE');
     $rows = ArrayUtil::trimExplode("\n", $content);
     foreach ($rows as $row) {
         $data = str_getcsv($row, ',', '"', '""');
         if (count($data) !== 4) {
             throw new WrongFileFormatException($this->translator->trans('field_notes.error.wrong_file_format'));
         }
         $date = DateTime::createFromFormat(self::FIELD_NOTE_DATETIME_FORMAT, $data[1], new DateTimeZone('UTC'));
         if ($ignoreBeforeDate !== null && $date < $ignoreBeforeDate) {
             continue;
         }
         if (!array_key_exists($data[2], self::LOG_TYPE)) {
             $this->addError($this->translator->trans('field_notes.error.log_type_not_implemented', ['%type%' => $data[2]]));
             continue;
         }
         $type = self::LOG_TYPE[$data[2]];
         $geocache = $this->entityManager->getRepository('AppBundle:Geocache')->findOneBy(['wpOc' => $data[0]]);
         if (!$geocache) {
             $this->addError($this->translator->trans('field_notes.error.geocache_not_found', ['%code%' => $data[0]]));
             continue;
         }
         $fieldNote = new FieldNote();
         $fieldNote->setUser($this->entityManager->getReference('AppBundle:User', $userId));
         $fieldNote->setGeocache($geocache);
         $fieldNote->setDate($date);
         $fieldNote->setType($type);
         $fieldNote->setText($data[3]);
         $this->entityManager->persist($fieldNote);
     }
     $this->entityManager->flush();
     if ($this->hasErrors()) {
         return false;
     }
     return true;
 }
 /**
  * Add the associated objects in case the item have for persist its relation
  *
  * @param array  $item
  * @param object $entity
  */
 protected function loadAssociationObjectsToEntity(array $item, $entity)
 {
     foreach ($this->entityMetadata->getAssociationMappings() as $associationMapping) {
         $value = null;
         if (isset($item[$associationMapping['fieldName']]) && !is_object($item[$associationMapping['fieldName']])) {
             $value = $this->entityManager->getReference($associationMapping['targetEntity'], $item[$associationMapping['fieldName']]);
         }
         if (null === $value) {
             continue;
         }
         $setter = 'set' . ucfirst($associationMapping['fieldName']);
         $this->setValue($entity, $value, $setter);
     }
 }
 /**
  * Simplified and stolen code from UnitOfWork::createEntity.
  *
  * @param string $className
  * @param array $data
  * @param $revision
  * @throws DeletedException
  * @throws NoRevisionFoundException
  * @throws NotAuditedException
  * @throws \Doctrine\DBAL\DBALException
  * @throws \Doctrine\ORM\Mapping\MappingException
  * @throws \Doctrine\ORM\ORMException
  * @throws \Exception
  * @return object
  */
 private function createEntity($className, array $data, $revision)
 {
     /** @var ClassMetadataInfo|ClassMetadata $class */
     $class = $this->em->getClassMetadata($className);
     //lookup revisioned entity cache
     $keyParts = array();
     foreach ($class->getIdentifierFieldNames() as $name) {
         $keyParts[] = $data[$name];
     }
     $key = implode(':', $keyParts);
     if (isset($this->entityCache[$className]) && isset($this->entityCache[$className][$key]) && isset($this->entityCache[$className][$key][$revision])) {
         return $this->entityCache[$className][$key][$revision];
     }
     if (!$class->isInheritanceTypeNone()) {
         if (!isset($data[$class->discriminatorColumn['name']])) {
             throw new \RuntimeException('Expecting discriminator value in data set.');
         }
         $discriminator = $data[$class->discriminatorColumn['name']];
         if (!isset($class->discriminatorMap[$discriminator])) {
             throw new \RuntimeException("No mapping found for [{$discriminator}].");
         }
         if ($class->discriminatorValue) {
             $entity = $this->em->getClassMetadata($class->discriminatorMap[$discriminator])->newInstance();
         } else {
             //a complex case when ToOne binding is against AbstractEntity having no discriminator
             $pk = array();
             foreach ($class->identifier as $field) {
                 $pk[$class->getColumnName($field)] = $data[$field];
             }
             return $this->find($class->discriminatorMap[$discriminator], $pk, $revision);
         }
     } else {
         $entity = $class->newInstance();
     }
     //cache the entity to prevent circular references
     $this->entityCache[$className][$key][$revision] = $entity;
     foreach ($data as $field => $value) {
         if (isset($class->fieldMappings[$field])) {
             $type = Type::getType($class->fieldMappings[$field]['type']);
             $value = $type->convertToPHPValue($value, $this->platform);
             $class->reflFields[$field]->setValue($entity, $value);
         }
     }
     foreach ($class->associationMappings as $field => $assoc) {
         // Check if the association is not among the fetch-joined associations already.
         if (isset($hints['fetched'][$className][$field])) {
             continue;
         }
         /** @var ClassMetadataInfo|ClassMetadata $targetClass */
         $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
         if ($assoc['type'] & ClassMetadata::TO_ONE) {
             //print_r($targetClass->discriminatorMap);
             if ($this->metadataFactory->isAudited($assoc['targetEntity'])) {
                 if ($this->loadAuditedEntities) {
                     $pk = array();
                     if ($assoc['isOwningSide']) {
                         foreach ($assoc['targetToSourceKeyColumns'] as $foreign => $local) {
                             $pk[$foreign] = $data[$local];
                         }
                     } else {
                         /** @var ClassMetadataInfo|ClassMetadata $otherEntityMeta */
                         $otherEntityMeta = $this->em->getClassMetadata($assoc['targetEntity']);
                         foreach ($otherEntityMeta->associationMappings[$assoc['mappedBy']]['targetToSourceKeyColumns'] as $local => $foreign) {
                             $pk[$foreign] = $data[$class->getFieldName($local)];
                         }
                     }
                     $pk = array_filter($pk, function ($value) {
                         return !is_null($value);
                     });
                     if (!$pk) {
                         $class->reflFields[$field]->setValue($entity, null);
                     } else {
                         try {
                             $value = $this->find($targetClass->name, $pk, $revision, array('threatDeletionsAsExceptions' => true));
                         } catch (DeletedException $e) {
                             $value = null;
                         }
                         $class->reflFields[$field]->setValue($entity, $value);
                     }
                 } else {
                     $class->reflFields[$field]->setValue($entity, null);
                 }
             } else {
                 if ($this->loadNativeEntities) {
                     if ($assoc['isOwningSide']) {
                         $associatedId = array();
                         foreach ($assoc['targetToSourceKeyColumns'] as $targetColumn => $srcColumn) {
                             $joinColumnValue = isset($data[$srcColumn]) ? $data[$srcColumn] : null;
                             if ($joinColumnValue !== null) {
                                 $associatedId[$targetClass->fieldNames[$targetColumn]] = $joinColumnValue;
                             }
                         }
                         if (!$associatedId) {
                             // Foreign key is NULL
                             $class->reflFields[$field]->setValue($entity, null);
                         } else {
                             $associatedEntity = $this->em->getReference($targetClass->name, $associatedId);
                             $class->reflFields[$field]->setValue($entity, $associatedEntity);
                         }
                     } else {
                         // Inverse side of x-to-one can never be lazy
                         $class->reflFields[$field]->setValue($entity, $this->getEntityPersister($assoc['targetEntity'])->loadOneToOneEntity($assoc, $entity));
                     }
                 } else {
                     $class->reflFields[$field]->setValue($entity, null);
                 }
             }
         } elseif ($assoc['type'] & ClassMetadata::ONE_TO_MANY) {
             if ($this->metadataFactory->isAudited($assoc['targetEntity'])) {
                 if ($this->loadAuditedCollections) {
                     $foreignKeys = array();
                     foreach ($targetClass->associationMappings[$assoc['mappedBy']]['sourceToTargetKeyColumns'] as $local => $foreign) {
                         $field = $class->getFieldForColumn($foreign);
                         $foreignKeys[$local] = $class->reflFields[$field]->getValue($entity);
                     }
                     $collection = new AuditedCollection($this, $targetClass->name, $targetClass, $assoc, $foreignKeys, $revision);
                     $class->reflFields[$assoc['fieldName']]->setValue($entity, $collection);
                 } else {
                     $class->reflFields[$assoc['fieldName']]->setValue($entity, new ArrayCollection());
                 }
             } else {
                 if ($this->loadNativeCollections) {
                     $collection = new PersistentCollection($this->em, $targetClass, new ArrayCollection());
                     $this->getEntityPersister($assoc['targetEntity'])->loadOneToManyCollection($assoc, $entity, $collection);
                     $class->reflFields[$assoc['fieldName']]->setValue($entity, $collection);
                 } else {
                     $class->reflFields[$assoc['fieldName']]->setValue($entity, new ArrayCollection());
                 }
             }
         } else {
             // Inject collection
             $reflField = $class->reflFields[$field];
             $reflField->setValue($entity, new ArrayCollection());
         }
     }
     return $entity;
 }
Exemple #8
0
 /**
  * {@inheritdoc}
  */
 public function removeMultiple(array $ids)
 {
     foreach ($ids as $id) {
         $this->entityManager->remove($this->entityManager->getReference(Analytics::class, $id));
     }
 }
Exemple #9
0
 /**
  * {@inheritdoc}
  */
 public function save($data, $userId, $locale, $patch = false)
 {
     if ($this->getProperty($data, 'id')) {
         $categoryEntity = $this->findById($this->getProperty($data, 'id'));
     } else {
         $categoryEntity = $this->categoryRepository->createNew();
     }
     // set user properties if userId is set. else these properties are set by the UserBlameSubscriber on save.
     if ($user = $userId ? $this->userRepository->findUserById($userId) : null) {
         if (!$categoryEntity->getCreator()) {
             $categoryEntity->setCreator($user);
         }
         $categoryEntity->setChanger($user);
     }
     $categoryWrapper = $this->getApiObject($categoryEntity, $locale);
     if (!$patch || $this->getProperty($data, 'name')) {
         $translationEntity = $this->findOrCreateCategoryTranslation($categoryEntity, $categoryWrapper, $locale);
         $translationEntity->setTranslation($this->getProperty($data, 'name', null));
     }
     if (!$patch || $this->getProperty($data, 'description')) {
         $translationEntity = $this->findOrCreateCategoryTranslation($categoryEntity, $categoryWrapper, $locale);
         $translationEntity->setDescription($this->getProperty($data, 'description', null));
     }
     if (!$patch || $this->getProperty($data, 'medias')) {
         $translationEntity = $this->findOrCreateCategoryTranslation($categoryEntity, $categoryWrapper, $locale);
         $translationEntity->setMedias(array_map(function ($item) {
             return $this->em->getReference(Media::class, $item);
         }, $this->getProperty($data, 'medias', [])));
     }
     $key = $this->getProperty($data, 'key');
     if (!$patch || $key) {
         $categoryWrapper->setKey($key);
     }
     if (!$patch || $this->getProperty($data, 'meta')) {
         $metaData = is_array($this->getProperty($data, 'meta')) ? $this->getProperty($data, 'meta') : [];
         $metaEntities = [];
         foreach ($metaData as $meta) {
             $metaEntity = $this->categoryMetaRepository->createNew();
             $metaEntity->setId($this->getProperty($meta, 'id'));
             $metaEntity->setKey($this->getProperty($meta, 'key'));
             $metaEntity->setValue($this->getProperty($meta, 'value'));
             $metaEntity->setLocale($this->getProperty($meta, 'locale'));
             $metaEntities[] = $metaEntity;
         }
         $categoryWrapper->setMeta($metaEntities);
     }
     if (!$patch || $this->getProperty($data, 'parent')) {
         if ($this->getProperty($data, 'parent')) {
             $parentEntity = $this->findById($this->getProperty($data, 'parent'));
         } else {
             $parentEntity = null;
         }
         $categoryWrapper->setParent($parentEntity);
     }
     if (!$categoryWrapper->getName()) {
         throw new CategoryNameMissingException();
     }
     $categoryEntity = $categoryWrapper->getEntity();
     $this->em->persist($categoryEntity);
     try {
         $this->em->flush();
     } catch (UniqueConstraintViolationException $e) {
         throw new CategoryKeyNotUniqueException($key);
     }
     return $categoryEntity;
 }
 /**
  * {@inheritdoc}
  */
 public function getReference($entityName, $id)
 {
     return $this->wrapped->getReference($entityName, $id);
 }
 /**
  * Gets a reference to the entity identified by the given type and identifier
  * without actually loading it, if the entity is not yet loaded.
  *
  * @param string $id
  *
  * @return IdInterface
  */
 public function getReferenceById($id)
 {
     return $this->entityManager->getReference($this->class, $id);
 }