/** * @param array $category * @return bool|int */ public function import(array $category) { $category = $this->prepareCategoryData($category); // Try to find an existing category by name and parent $model = null; if (isset($category['parent']) && isset($category['name'])) { $model = $this->repository->findOneBy(['parent' => $category['parent'], 'name' => $category['name']]); } if (!$model instanceof Category) { $model = new Category(); } $parentModel = null; if (isset($category['parent'])) { $parentModel = $this->repository->find((int) $category['parent']); if (!$parentModel instanceof Category) { $this->logger->error("Parent category {$category['parent']} not found!"); return false; } } $model->fromArray($category); $model->setParent($parentModel); $this->em->persist($model); $this->em->flush(); // Set category attributes $attributes = $this->prepareCategoryAttributesData($category); unset($category); $categoryId = $model->getId(); if (!empty($attributes)) { $attributeID = $this->db->fetchOne("SELECT id FROM s_categories_attributes WHERE categoryID = ?", [$categoryId]); if ($attributeID === false) { $attributes['categoryID'] = $categoryId; $this->db->insert('s_categories_attributes', $attributes); } else { $this->db->update('s_categories_attributes', $attributes, ['categoryID = ?' => $categoryId]); } } return $categoryId; }
/** * @param array $category * @param \Shopware\Models\Category\Repository $categoryRepository * @param $metaData * @return Shopware\Models\Category\Category */ public function saveCategory($category, \Shopware\Models\Category\Repository $categoryRepository, $metaData) { $parent = $categoryRepository->find($category['parentID']); if (!$parent) { throw new \Exception(sprintf('Could not update/insert category with id %s, could not find parentId %s', $category['categoryID'], $category['parentID'])); } $category = $this->toUtf8($category); $mapping = array(); foreach ($metaData->fieldMappings as $fieldMapping) { $mapping[$fieldMapping['columnName']] = $fieldMapping['fieldName']; } $mapping = $mapping + array('categoryID' => 'id', 'ac_attr1' => 'attribute_attribute1', 'ac_attr2' => 'attribute_attribute2', 'ac_attr3' => 'attribute_attribute3', 'ac_attr4' => 'attribute_attribute4', 'ac_attr5' => 'attribute_attribute5', 'ac_attr6' => 'attribute_attribute6'); $updateData = $this->mapFields($category, $mapping); $updateData['parent'] = $parent; $attribute = $this->prefixToArray($updateData, 'attribute_'); if (!empty($attribute)) { $updateData['attribute'] = $attribute; } /** @var $categoryModel \Shopware\Models\Category\Category */ $categoryModel = $categoryRepository->find($category['categoryID']); if (!$categoryModel) { $categoryModel = new \Shopware\Models\Category\Category(); $categoryModel->setPrimaryIdentifier($category['categoryID']); $this->getManager()->persist($categoryModel); } $categoryModel->fromArray($updateData); return $categoryModel; }