/** * @param TaxonModel $taxon * * @return $this */ public function updateTaxon(TaxonModel $taxon) { $properties = $taxon->getProperties(); foreach ($properties as $propertyName => $propertyValue) { if ($propertyValue instanceof UploadedFile) { $fileId = $this->mc->upload($propertyValue); $taxon->setProperty($propertyName, $fileId); } } $this->persist($taxon, true); return $this; }
/** * @param FormInterface $form * @param Request $request * * @return $this|array */ public function saveItem(FormInterface $form, Request $request) { /** @var ItemModel $item */ $item = $form->getData(); // Проверка и модификация атрибута. В частности загрука картинок и валидация. foreach ($this->getAttributes() as $attribute) { if ($attribute->getIsDedicatedTable()) { continue; } if ($attribute->isType('image') and $item->hasAttribute($attribute->getName())) { // @todo Здесь выполняется нативный SQL т.к. ORM отдаёт скешированный - сделать через UoW. $tableItems = $this->em->getClassMetadata($this->configuration->getItemClass())->getTableName(); $sql = "SELECT * FROM {$tableItems} WHERE id = '{$item->getId()}'"; $res = $this->em->getConnection()->query($sql)->fetch(); if (!empty($res)) { $previousAttributes = unserialize($res['attributes']); $fileId = $previousAttributes[$attribute->getName()]; } else { $fileId = null; } // удаление файла. $_delete_ = $request->request->get('_delete_'); if (is_array($_delete_) and isset($_delete_['attribute:' . $attribute->getName()]) and 'on' === $_delete_['attribute:' . $attribute->getName()]) { $this->mc->remove($fileId); $fileId = null; } else { $file = $item->getAttribute($attribute->getName()); if ($file) { $this->mc->remove($fileId); $fileId = $this->mc->upload($file); } } $item->setAttribute($attribute->getName(), $fileId); } } // Удаление всех связей, чтобы потом просто назначить новые. $item->setTaxons([])->setTaxonsSingle([]); $this->em->persist($item); $this->em->flush(); // @todo если item уже существует, то сделать сохранение в один проход, но придумать как сделать обновление таксономии. // Вторым проходом обрабатываются атрибуты с внешних таблиц т.к. при создании новой записи нужно сгенерировать ID foreach ($this->getAttributes() as $attribute) { if ($attribute->getIsDedicatedTable()) { $valueClass = $attribute->getValueClassNameWithNameSpace(); /* @var AbstractTypeModel $value */ // @todo пока допускается использование одного поля со значениями, но нужно предусмотреть и множественные. $value = $this->em->getRepository($valueClass)->findOneBy(['item' => $item]); if (empty($value)) { $value = new $valueClass(); $value->setItem($item); } $value->setValue($item->getAttr($attribute->getName())); $this->em->persist($value); } else { continue; } } $pd = $request->request->get($form->getName()); $taxons = []; foreach ($pd as $key => $val) { if (false !== strpos($key, 'structure:')) { if (is_array($val)) { foreach ($val as $val2) { $taxons[] = $val2; } } else { $taxons[] = $val; } } } //$request->request->set($form->getName(), $pd); //$taxonsCollection = $this->em->getRepository($this->getTaxonClass())->findIn($taxons); $taxons_ids = implode(',', $taxons); if (!empty($taxons_ids)) { // @todo убрать в Repository $taxonsSingle = $this->em->createQuery("\n SELECT c\n FROM {$this->getTaxonClass()} c\n WHERE c.id IN({$taxons_ids})\n ")->getResult(); $item->setTaxonsSingle($taxonsSingle); $taxonsInherited = []; foreach ($taxonsSingle as $taxon) { $this->getTaxonsInherited($taxonsInherited, $taxon); } $item->setTaxons($taxonsInherited); } $this->em->persist($item); $this->em->flush(); return $this; }