/**
  * @param $data
  * @return mixed|ProfileEntity
  * @throws \Enlight_Exception
  * @throws \Exception
  */
 public function createProfileModel($data)
 {
     $event = Shopware()->Events()->notifyUntil('Shopware_Components_SwagImportExport_Factories_CreateProfileModel', ['subject' => $this, 'data' => $data]);
     if ($event && $event instanceof \Enlight_Event_EventArgs && $event->getReturn() instanceof ProfileEntity) {
         return $event->getReturn();
     }
     if (!isset($data['name'])) {
         throw new \Exception('Profile name is required');
     }
     if (!isset($data['type'])) {
         throw new \Exception('Profile type is required');
     }
     if (isset($data['hidden']) && $data['hidden']) {
         $tree = TreeHelper::getTreeByHiddenProfileType($data['type']);
     } else {
         if (isset($data['baseProfile'])) {
             $tree = TreeHelper::getDefaultTreeByBaseProfile($data['baseProfile']);
         } else {
             $tree = TreeHelper::getDefaultTreeByProfileType($data['type']);
         }
     }
     $profileEntity = new ProfileEntity();
     $profileEntity->setName($data['name']);
     $profileEntity->setBaseProfile($data['baseProfile']);
     $profileEntity->setType($data['type']);
     $profileEntity->setTree($tree);
     if (isset($data['hidden'])) {
         $profileEntity->setHidden($data['hidden']);
     }
     $this->modelManager->persist($profileEntity);
     $this->modelManager->flush();
     return $profileEntity;
 }
 private function importNewsletterDemoData()
 {
     $this->modelManager = Shopware()->Container()->get('models');
     $newsletterGroup = $this->modelManager->find(Group::class, 1);
     for ($addressAmount = 0; $addressAmount < 25; $addressAmount++) {
         $address = new Address();
         $address->setEmail('test_' . $addressAmount . '@example.com');
         $address->setAdded(new \DateTime());
         $address->setNewsletterGroup($newsletterGroup);
         $address->setIsCustomer(false);
         $this->modelManager->persist($address);
     }
     $this->modelManager->flush();
 }
 /**
  * @inheritdoc
  */
 public function write($messages, $status, Session $session)
 {
     $loggerModel = new LoggerEntity();
     if (!is_array($messages)) {
         $messages = [$messages];
     }
     $messages = implode(';', $messages);
     $loggerModel->setSession($session);
     $loggerModel->setMessage($messages);
     $loggerModel->setCreatedAt('now');
     $loggerModel->setStatus($status);
     $this->modelManager->persist($loggerModel);
     $this->modelManager->flush();
 }
 /**
  * Insert/Update data into db
  *
  * @param array $records
  */
 public function write($records)
 {
     $records = $records['default'];
     $this->validateRecordsShouldNotBeEmpty($records);
     $records = Shopware()->Events()->filter('Shopware_Components_SwagImportExport_DbAdapters_CategoriesDbAdapter_Write', $records, ['subject' => $this]);
     foreach ($records as $index => $record) {
         try {
             $record = $this->validator->filterEmptyString($record);
             $category = $this->findCategoryById($record['categoryId']);
             if (!$category instanceof Category) {
                 $record = $this->dataManager->setDefaultFieldsForCreate($record, $this->defaultValues);
                 $category = $this->createCategoryAndSetId($record['categoryId']);
             }
             $this->validator->checkRequiredFields($record);
             $this->validator->validate($record, CategoryDataType::$mapper);
             $record['parent'] = $this->repository->find($record['parentId']);
             $this->validateParentCategory($record);
             $record = $this->prepareData($record, $index, $category->getId(), $records['customerGroups']);
             $category->fromArray($record);
             $this->validateCategoryModel($category);
             /** @var ClassMetadata $metaData */
             $metaData = $this->modelManager->getClassMetaData(Category::class);
             $metaData->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
             $this->modelManager->persist($category);
             $this->modelManager->flush($category);
         } catch (AdapterException $e) {
             $message = $e->getMessage();
             $this->saveMessage($message);
         }
     }
 }
 /**
  * @param $records
  * @throws \Enlight_Event_Exception
  * @throws \Exception
  */
 public function write($records)
 {
     $articleCount = 0;
     if (empty($records['default'])) {
         $message = SnippetsHelper::getNamespace()->get('adapters/articlesInStock/no_records', 'No article stock records were found.');
         throw new \Exception($message);
     }
     $records = Shopware()->Events()->filter('Shopware_Components_SwagImportExport_DbAdapters_ArticlesInStockDbAdapter_Write', $records, ['subject' => $this]);
     foreach ($records['default'] as $record) {
         try {
             $record = $this->validator->filterEmptyString($record);
             $this->validator->checkRequiredFields($record);
             $this->validator->validate($record, ArticleInStockValidator::$mapper);
             $articleDetail = $this->repository->findOneBy(["number" => $record['orderNumber']]);
             if (!$articleDetail) {
                 $message = SnippetsHelper::getNamespace()->get('adapters/articlesImages/article_not_found', 'Article with number %s does not exists.');
                 throw new AdapterException(sprintf($message, $record['orderNumber']));
             }
             $inStock = (int) $record['inStock'];
             $articleDetail->setInStock($inStock);
             if ($articleCount % 50 === 0) {
                 $this->modelManager->flush();
             }
         } catch (AdapterException $e) {
             $message = $e->getMessage();
             $this->saveMessage($message);
         }
     }
     $this->modelManager->flush();
 }
 /**
  * @param int $articleID
  * @return bool
  */
 private function deleteDownloads($articleID)
 {
     /* @var ArticleRepository $articleRepository */
     $articleRepository = $this->getArticleRepository();
     $article = $articleRepository->find($articleID);
     if (!$article instanceof Article) {
         return false;
     }
     $downloads = $article->getDownloads();
     foreach ($downloads as $downloadModel) {
         $filename = $downloadModel->getFile();
         $this->em->remove($downloadModel);
         /* @var MediaRepository $mediaRepository */
         $mediaRepository = $this->getMediaRepository();
         $mediaList = $mediaRepository->findBy(['path' => $filename]);
         foreach ($mediaList as $mediaModel) {
             $this->em->remove($mediaModel);
         }
     }
     $sql = 'SELECT id FROM s_articles_downloads WHERE articleID = ' . $articleID;
     $downloads = $this->db->fetchCol($sql);
     if (!empty($downloads)) {
         $this->deleteTranslation('download', $downloads);
     }
     $this->em->flush();
     return true;
 }
 /**
  * @inheritdoc
  */
 public function install()
 {
     $parentMenuItem = $this->findParent();
     $plugin = $this->findPlugin();
     $menuItem = new Menu();
     $menuItem->setLabel(self::MENU_LABEL);
     $menuItem->setController(self::PLUGIN_NAME);
     $menuItem->setAction('Index');
     $menuItem->setClass(self::MENU_ITEM_CLASS);
     $menuItem->setActive(1);
     $menuItem->setParent($parentMenuItem);
     $menuItem->setPlugin($plugin);
     $menuItem->setPosition(6);
     $this->modelManager->persist($menuItem);
     $this->modelManager->flush();
 }
 /**
  * @param Menu $menuItem
  * @param Plugin $plugin
  */
 private function updateImportExportMenuItem(Menu $menuItem, Plugin $plugin)
 {
     $menuItem->setController(self::SWAG_IMPORT_EXPORT_CONTROLLER);
     $menuItem->setAction(self::SWAG_IMPORT_EXPORT_ACTION);
     $menuItem->setPlugin($plugin);
     $this->modelManager->persist($menuItem);
     $this->modelManager->flush();
 }
 /**
  * Removes the import files on update to version 1.2.2
  */
 private function removeImportFilesAlbum()
 {
     $repo = $this->modelManager->getRepository(Album::class);
     $album = $repo->findOneBy(['name' => 'ImportFiles']);
     if ($album) {
         $this->modelManager->remove($album);
         $this->modelManager->flush();
     }
 }
 /**
  * @param Menu|null $menuItem
  * @param string $menuLabel
  */
 private function createMenuItemIfItDoesNotExist($menuItem, $menuLabel)
 {
     if ($menuItem instanceof Menu) {
         return;
     }
     $menu = new Menu();
     $menu->setLabel($menuLabel);
     $this->modelManger->persist($menu);
     $this->modelManger->flush();
 }
Beispiel #11
0
 private function removePriceGroup()
 {
     $ids = $this->db->fetchCol("SELECT id FROM s_core_pricegroups WHERE description = 'TEST-GROUP'");
     foreach ($ids as $id) {
         $group = $this->entityManager->find('Shopware\\Models\\Price\\Group', $id);
         $this->entityManager->remove($group);
         $this->entityManager->flush();
         $this->entityManager->clear();
     }
 }
 /**
  * @param string $profileType
  * @param string $profileName
  */
 private function createProfile($profileType, $profileName)
 {
     $defaultTree = TreeHelper::getDefaultTreeByProfileType($profileType);
     $profile = new Profile();
     $profile->setHidden(0);
     $profile->setName($profileName);
     $profile->setType($profileType);
     $profile->setTree($defaultTree);
     $this->modelManager->persist($profile);
     $this->modelManager->flush();
     $this->profileIds[$profileType] = $profile->getId();
 }
 /**
  * @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;
 }
 private function removeAclResource()
 {
     $sql = "SELECT id FROM s_core_acl_resources\n                WHERE pluginID = ?;";
     $resourceId = $this->db->fetchOne($sql, [$this->getId()]);
     if (!$resourceId) {
         return;
     }
     $resource = $this->em->getRepository(\Shopware\Models\User\Resource::class)->find($resourceId);
     foreach ($resource->getPrivileges() as $privilege) {
         $this->em->remove($privilege);
     }
     $this->em->remove($resource);
     $this->em->flush();
 }
 /**
  * @inheritdoc
  */
 public function importProfile(UploadedFile $file)
 {
     /** @var \Shopware_Components_Plugin_Namespace $namespace */
     $namespace = $this->snippetManager->getNamespace('backend/swag_import_export/controller');
     if (strtolower($file->getClientOriginalExtension()) !== 'json') {
         $this->fileSystem->remove($file->getPathname());
         throw new \Exception($namespace->get('swag_import_export/profile/profile_import_no_json_error'));
     }
     $content = file_get_contents($file->getPathname());
     if (empty($content)) {
         $this->fileSystem->remove($file->getPathname());
         throw new \Exception($namespace->get('swag_import_export/profile/profile_import_no_data_error'));
     }
     $profileData = (array) json_decode($content);
     if (empty($profileData['name']) || empty($profileData['type']) || empty($profileData['tree'])) {
         $this->fileSystem->remove($file->getPathname());
         throw new \Exception($namespace->get('swag_import_export/profile/profile_import_no_valid_data_error'));
     }
     try {
         $profile = new Profile();
         $profile->setName($profileData['name']);
         $profile->setType($profileData['type']);
         $profile->setTree(json_encode($profileData['tree']));
         $this->modelManager->persist($profile);
         $this->modelManager->flush($profile);
         $this->fileSystem->remove($file->getPathname());
     } catch (\Exception $e) {
         $this->fileSystem->remove($file->getPathname());
         $message = $e->getMessage();
         $msg = $namespace->get('swag_import_export/profile/profile_import_error');
         if (strpbrk('Duplicate entry', $message) !== false) {
             $msg = $namespace->get('swag_import_export/profile/profile_import_duplicate_error');
         }
         throw new \Exception($msg);
     }
 }
Beispiel #16
0
 /**
  * Helper function which resolves the theme parent for each
  * passed theme
  *
  * @param array $themes
  * @throws \Exception
  */
 private function setParents(array $themes)
 {
     /**@var $theme Theme */
     foreach ($themes as $theme) {
         if ($theme->getExtend() === null) {
             continue;
         }
         $template = $this->repository->findOneBy(array('template' => $theme->getTemplate()));
         $parent = $this->repository->findOneBy(array('template' => $theme->getExtend()));
         if (!$parent instanceof Shop\Template) {
             throw new \Exception(sprintf("Parent %s of theme %s not found", $theme->getExtend(), $theme->getTemplate()));
         }
         $template->setParent($parent);
         $this->entityManager->flush();
     }
 }
Beispiel #17
0
 /**
  * Delete resource and its privileges from database
  * @param $resourceName
  * @return bool
  */
 public function deleteResource($resourceName)
 {
     $repository = $this->em->getRepository('Shopware\\Models\\User\\Resource');
     /** @var $resource \Shopware\Models\User\Resource */
     $resource = $repository->findOneBy(array("name" => $resourceName));
     if (empty($resource)) {
         return false;
     }
     // remove the resource flag in the s_core_menu manually.
     $this->em->getConnection()->executeUpdate("UPDATE s_core_menu SET resourceID = NULL WHERE resourceID = ?", [$resource->getId()]);
     //The mapping table s_core_acl_roles must be cleared manually.
     $this->em->getConnection()->executeUpdate("DELETE FROM s_core_acl_roles WHERE resourceID = ?", [$resource->getId()]);
     //The privileges will be removed automatically
     $this->em->remove($resource);
     $this->em->flush();
     return true;
 }
Beispiel #18
0
 /**
  * Helper function which removes all unused configuration containers and elements
  * which are stored in the database but not in the passed container.
  *
  * @param \Doctrine\Common\Collections\ArrayCollection $containers
  * @param \Doctrine\Common\Collections\ArrayCollection $fields
  * @param Form\Container $container
  */
 private function removeUnused(ArrayCollection $containers, ArrayCollection $fields, Form\Container $container)
 {
     $structure = $this->getContainerNames($container);
     $structure = $this->eventManager->filter('Theme_Configurator_Container_Names_Loaded', $structure, array('containers' => $container, 'fields' => $fields, 'container' => $container));
     /**@var $layout Shop\TemplateConfig\Layout */
     foreach ($containers as $layout) {
         if (!in_array($layout->getName(), $structure['containers'])) {
             $this->entityManager->remove($layout);
         }
     }
     /**@var $layout Shop\TemplateConfig\Element */
     foreach ($fields as $layout) {
         if (!in_array($layout->getName(), $structure['fields'])) {
             $this->entityManager->remove($layout);
         }
     }
     $this->entityManager->flush();
 }
 /**
  *
  */
 public function refreshPluginList()
 {
     $refreshed = \Zend_Date::now();
     $repository = $this->em->getRepository('Shopware\\Models\\Plugin\\Plugin');
     /** @var $collection \Shopware_Components_Plugin_Namespace */
     foreach ($this->plugins as $namespace => $collection) {
         if (!$collection instanceof \Shopware_Components_Plugin_Namespace) {
             continue;
         }
         foreach (['Local', 'Community', 'Commercial', 'Default'] as $source) {
             $path = Shopware()->AppPath('Plugins_' . $source . '_' . $namespace);
             if (!is_dir($path)) {
                 continue;
             }
             foreach (new \DirectoryIterator($path) as $dir) {
                 if (!$dir->isDir() || $dir->isDot()) {
                     continue;
                 }
                 $file = $dir->getPathname() . DIRECTORY_SEPARATOR . 'Bootstrap.php';
                 if (!file_exists($file)) {
                     continue;
                 }
                 $name = $dir->getFilename();
                 $plugin = $collection->get($name);
                 if ($this->validateIonCube($file)) {
                     throw new \Exception(sprintf('Plugin %s is encrypted but ioncube Loader extension is not installed', $name));
                 }
                 if ($plugin === null) {
                     $plugin = $collection->initPlugin($name, new \Enlight_Config(['source' => $source, 'path' => $dir->getPathname() . DIRECTORY_SEPARATOR]));
                 }
                 $collection->registerPlugin($plugin);
             }
         }
     }
     $sql = 'SELECT id, refresh_date FROM s_core_plugins WHERE refresh_date<?';
     $pluginIds = Shopware()->Db()->fetchCol($sql, [$refreshed]);
     foreach ($pluginIds as $pluginId) {
         $plugin = $repository->find($pluginId);
         $this->em->remove($plugin);
     }
     $this->em->flush();
 }
Beispiel #20
0
 /**
  * Saves the passed shop configuration values to the passed
  * template.
  * The configuration elements are identified over the
  * element name.
  * The values array can contains multiple sub shop values,
  * which identified over the shopId parameter inside the values array.
  *
  * @param Shop\Template $template
  * @param array $values
  */
 public function saveConfig(Shop\Template $template, array $values)
 {
     foreach ($values as $data) {
         //get the element over the name
         $element = $this->getElementByName($template->getElements(), $data['elementName']);
         if (!$element instanceof Shop\TemplateConfig\Element) {
             continue;
         }
         $value = $this->getElementShopValue($element->getValues(), $data['shopId']);
         /**@var $shop Shop\Shop */
         $shop = $this->entityManager->getReference('Shopware\\Models\\Shop\\Shop', $data['shopId']);
         if ($element->getType() === 'theme-media-selection') {
             $data['value'] = $this->mediaService->normalize($data['value']);
         }
         $value->setShop($shop);
         $value->setElement($element);
         $value->setValue($data['value']);
     }
     $this->entityManager->flush();
 }
Beispiel #21
0
 /**
  * gets the old data of the Trusted Shops core integration and the Trusted Shops Excellence plugin
  * and fills them into the new DB table of this plugin
  *
  * @param $pluginId
  */
 public function migrateData($pluginId)
 {
     $tsValues = $this->getTsClassicData();
     $tsExcValues = $this->getTsExcellenceData($pluginId);
     /** @var Repository $shopRepository */
     $shopRepository = $this->em->getRepository('Shopware\\Models\\Shop\\Shop');
     $shops = $shopRepository->getActiveShops();
     /** @var Shop $shop */
     foreach ($shops as $shop) {
         if (!$shop) {
             continue;
         }
         $shopId = $shop->getId();
         $oldTsId = $tsValues[$shopId];
         $oldTsEID = $tsExcValues['tsEID'][$shopId];
         $oldTsWebServiceUser = $tsExcValues['tsWebServiceUser'][$shopId];
         $oldTsWebServicePassword = $tsExcValues['tsWebServicePassword'][$shopId];
         $tsExcValues['testSystemActive'][$shopId] ? $oldTestSystemActive = $tsExcValues['testSystemActive'][$shopId] : ($oldTestSystemActive = 0);
         $tsExcValues['ratingActive'][$shopId] ? $oldRatingActive = $tsExcValues['ratingActive'][$shopId] : ($oldRatingActive = 1);
         /* @var TrustedShops $trustedShopsModel */
         $trustedShopsModel = $this->em->getRepository('Shopware\\CustomModels\\TrustedShops\\TrustedShops')->findOneBy(array('shopId' => $shopId));
         if (!$oldTsId && !$oldTsEID) {
             continue;
         }
         if (!$trustedShopsModel) {
             $trustedShopsModel = new TrustedShops();
             $trustedShopsModel->setShopId($shopId);
             $oldTsEID ? $trustedShopsModel->setTrustedShopsId($oldTsEID) : $trustedShopsModel->setTrustedShopsId($oldTsId);
             $trustedShopsModel->setTrustedShopsUser($oldTsWebServiceUser);
             $trustedShopsModel->setTrustedShopsPassword($oldTsWebServicePassword);
             $trustedShopsModel->setTrustedShopsTestSystem($oldTestSystemActive);
             $trustedShopsModel->setTrustedShopsShowRatingWidget($oldRatingActive);
             $trustedShopsModel->setTrustedShopsShowRatingsButtons(0);
             $trustedShopsModel->setTrustedShopsRateLaterDays(7);
         }
         $this->em->persist($trustedShopsModel);
         $this->em->flush();
     }
     $this->deactivateOldTsComponents();
 }
 /**
  * Sets image mapping for variants
  *
  * @param array $relationGroups
  * @param int $imageId
  */
 protected function setImageMappings($relationGroups, $imageId)
 {
     /** @var Repository $articleRepository */
     $articleRepository = $this->manager->getRepository(Article::class);
     $query = $articleRepository->getArticleImageDataQuery($imageId);
     $image = $query->getOneOrNullResult(AbstractQuery::HYDRATE_OBJECT);
     $imageData = $query->getOneOrNullResult(AbstractQuery::HYDRATE_ARRAY);
     foreach ($relationGroups as $relationGroup) {
         $optionCollection = [];
         $mapping = new Image\Mapping();
         foreach ($relationGroup as $relation) {
             $optionModel = $relation['option'];
             $optionCollection[] = $optionModel;
             $rule = new Image\Rule();
             $rule->setMapping($mapping);
             $rule->setOption($optionModel);
             $mapping->getRules()->add($rule);
             $mapping->setImage($image);
             $this->manager->persist($mapping);
         }
         $this->createImagesForOptions($optionCollection, $imageData, $image);
         $this->manager->flush();
     }
 }
 /**
  * @param array $records
  * @throws \Enlight_Event_Exception
  * @throws \Exception
  */
 public function write($records)
 {
     if (empty($records['default'])) {
         $message = SnippetsHelper::getNamespace()->get('adapters/newsletter/no_records', 'No newsletter records were found.');
         throw new \Exception($message);
     }
     $records = Shopware()->Events()->filter('Shopware_Components_SwagImportExport_DbAdapters_CategoriesDbAdapter_Write', $records, ['subject' => $this]);
     $defaultValues = $this->getDefaultValues();
     /** @var EntityRepository $addressRepository */
     $addressRepository = $this->manager->getRepository(Address::class);
     /** @var EntityRepository $groupRepository */
     $groupRepository = $this->manager->getRepository(Group::class);
     /** @var EntityRepository $contactDataRepository */
     $contactDataRepository = $this->manager->getRepository(ContactData::class);
     $count = 0;
     foreach ($records['default'] as $newsletterData) {
         try {
             $count++;
             $newsletterData = $this->validator->filterEmptyString($newsletterData);
             $this->validator->checkRequiredFields($newsletterData);
             $recipient = $addressRepository->findOneBy(['email' => $newsletterData['email']]);
             if ($recipient instanceof Address && empty($newsletterData['groupName'])) {
                 continue;
             }
             if (!$recipient instanceof Address) {
                 $newsletterData = $this->dataManager->setDefaultFieldsForCreate($newsletterData, $defaultValues);
                 $recipient = new Address();
             }
             $this->validator->validate($newsletterData, NewsletterDataType::$mapper);
             if ($newsletterData['groupName']) {
                 /** @var Group $group */
                 $group = $groupRepository->findOneBy(['name' => $newsletterData['groupName']]);
                 if (!$group instanceof Group) {
                     $group = new Group();
                     $group->setName($newsletterData['groupName']);
                     $this->manager->persist($group);
                     $this->manager->flush($group);
                 }
                 $newsletterData['groupId'] = $group->getId();
             }
             // save newsletter address
             $newsletterAddress = $this->prepareNewsletterAddress($newsletterData);
             $recipient->fromArray($newsletterAddress);
             $this->manager->persist($recipient);
             if ($recipient->getGroupId() !== 0) {
                 // save mail data
                 $contactData = $contactDataRepository->findOneBy(['email' => $newsletterData['email']]);
                 if (!$contactData instanceof ContactData) {
                     $contactData = new ContactData();
                     $contactData->setAdded(new \DateTime());
                     $this->manager->persist($contactData);
                 }
                 $contactData->fromArray($newsletterData);
             }
             if ($count % 20 === 0) {
                 $this->manager->flush();
             }
         } catch (AdapterException $e) {
             $message = $e->getMessage();
             $this->saveMessage($message);
         }
     }
     $this->manager->flush();
 }
Beispiel #24
0
 /**
  * Saves the given container to the database, files or wherever.
  *
  * @param \Shopware\Components\Form\Interfaces\Container $container
  * @param Template $reference
  */
 public function save(Form\Interfaces\Container $container, $reference)
 {
     $this->saveContainer($container, $reference);
     $this->entityManager->flush();
 }
 /**
  * @param array $records
  * @throws \Enlight_Event_Exception
  * @throws \Exception
  * @throws \Zend_Db_Adapter_Exception
  */
 public function write($records)
 {
     $customerCount = 0;
     if (empty($records)) {
         $message = SnippetsHelper::getNamespace()->get('adapters/customer/no_records', 'No customer records were found.');
         throw new \Exception($message);
     }
     $records = $this->eventManager->filter('Shopware_Components_SwagImportExport_DbAdapters_CustomerDbAdapter_Write', $records, ['subject' => $this]);
     $defaultValues = $this->getDefaultValues();
     foreach ($records['default'] as $record) {
         try {
             $customerCount++;
             $record = $this->validator->filterEmptyString($record);
             $customer = $this->findExistingEntries($record);
             $createNewCustomer = false;
             if (!$customer instanceof Customer) {
                 $createNewCustomer = true;
                 $record = $this->dataManager->setDefaultFieldsForCreate($record, $defaultValues);
                 $this->validator->checkRequiredFieldsForCreate($record);
                 $customer = new Customer();
             }
             $this->preparePassword($record);
             $this->validator->checkRequiredFields($record);
             $this->validator->validate($record, CustomerDataType::$mapper);
             $customerData = $this->prepareCustomer($record);
             $customerData['billing'] = $this->prepareBilling($record);
             $customerData['shipping'] = $this->prepareShipping($record, $createNewCustomer, $customerData['billing']);
             $customer->fromArray($customerData);
             if (isset($customerData['subshopID'])) {
                 $shop = $this->manager->getRepository(Shop::class)->find($customerData['subshopID']);
                 if (!$shop) {
                     $message = SnippetsHelper::getNamespace()->get('adapters/shop_not_found', 'Shop with id %s was not found');
                     throw new AdapterException(sprintf($message, $customerData['subshopID']));
                 }
                 $customer->setShop($shop);
             }
             if (isset($customerData['languageId'])) {
                 $languageSubShop = $this->manager->getRepository(Shop::class)->find($customerData['languageId']);
                 if (!$languageSubShop) {
                     $message = SnippetsHelper::getNamespace()->get('adapters/language_shop_not_found', 'Language-Shop with id %s was not found');
                     throw new AdapterException(sprintf($message, $customerData['languageId']));
                 }
                 $customer->setLanguageSubShop($languageSubShop);
             }
             $billing = $customer->getDefaultBillingAddress();
             if (!$billing instanceof Address) {
                 $billing = new Address();
                 $billing->setCustomer($customer);
             }
             if (isset($customerData['billing']['countryId'])) {
                 $customerData['billing']['country'] = $this->manager->find(Country::class, $customerData['billing']['countryId']);
             }
             if (isset($customerData['billing']['stateId'])) {
                 $customerData['billing']['state'] = $this->manager->find(State::class, $customerData['billing']['stateId']);
             }
             $billing->fromArray($customerData['billing']);
             $shipping = $customer->getDefaultShippingAddress();
             if (!$shipping instanceof Address) {
                 $shipping = new Address();
                 $shipping->setCustomer($customer);
             }
             if (isset($customerData['shipping']['countryId'])) {
                 $customerData['shipping']['country'] = $this->manager->find(Country::class, $customerData['shipping']['countryId']);
             }
             if (isset($customerData['shipping']['stateId'])) {
                 $customerData['shipping']['state'] = $this->manager->find(State::class, $customerData['shipping']['stateId']);
             }
             $shipping->fromArray($customerData['shipping']);
             $customer->setFirstname($billing->getFirstname());
             $customer->setLastname($billing->getLastname());
             $customer->setSalutation($billing->getSalutation());
             $customer->setTitle($billing->getTitle());
             $violations = $this->manager->validate($customer);
             if ($violations->count() > 0) {
                 $message = SnippetsHelper::getNamespace()->get('adapters/customer/no_valid_customer_entity', 'No valid user entity for email %s');
                 $message = sprintf($message, $customer->getEmail());
                 foreach ($violations as $violation) {
                     $message .= "\n" . $violation->getPropertyPath() . ': ' . $violation->getMessage();
                 }
                 throw new AdapterException($message);
             }
             $this->manager->persist($customer);
             if ($createNewCustomer) {
                 $this->manager->flush();
             }
             $customer->setDefaultBillingAddress($billing);
             $this->manager->persist($billing);
             $customer->setDefaultShippingAddress($shipping);
             $this->manager->persist($shipping);
             $this->insertCustomerAttributes($customerData, $customer->getId(), $createNewCustomer);
             if ($customerCount % 20 === 0) {
                 $this->manager->flush();
             }
         } catch (AdapterException $e) {
             $message = $e->getMessage();
             $this->saveMessage($message);
         }
     }
     $this->manager->flush();
 }
 /**
  * Update order
  *
  * @param array $records
  * @throws \Exception
  */
 public function write($records)
 {
     $records = Shopware()->Events()->filter('Shopware_Components_SwagImportExport_DbAdapters_OrdersDbAdapter_Write', $records, ['subject' => $this]);
     if (empty($records['default'])) {
         $message = SnippetsHelper::getNamespace()->get('adapters/orders/no_records', 'No order records were found.');
         throw new \Exception($message);
     }
     $orderRepository = $this->modelManager->getRepository(Detail::class);
     $orderStatusRepository = $this->modelManager->getRepository(Status::class);
     $orderDetailStatusRepository = $this->modelManager->getRepository(DetailStatus::class);
     foreach ($records['default'] as $index => $record) {
         try {
             $record = $this->validator->filterEmptyString($record);
             $this->validator->checkRequiredFields($record);
             $this->validator->validate($record, OrderValidator::$mapper);
             if (isset($record['orderDetailId']) && $record['orderDetailId']) {
                 /** @var \Shopware\Models\Order\Detail $orderDetailModel */
                 $orderDetailModel = $orderRepository->find($record['orderDetailId']);
             } else {
                 $orderDetailModel = $orderRepository->findOneBy(['number' => $record['number']]);
             }
             if (!$orderDetailModel) {
                 $message = SnippetsHelper::getNamespace()->get('adapters/orders/order_detail_id_not_found', 'Order detail id %s was not found');
                 throw new AdapterException(sprintf($message, $record['orderDetailId']));
             }
             $orderModel = $orderDetailModel->getOrder();
             if (isset($record['paymentId']) && is_numeric($record['paymentId'])) {
                 $paymentStatusModel = $orderStatusRepository->find($record['cleared']);
                 if (!$paymentStatusModel) {
                     $message = SnippetsHelper::getNamespace()->get('adapters/orders/payment_status_id_not_found', 'Payment status id %s was not found for order %s');
                     throw new AdapterException(sprintf($message, $record['cleared'], $orderModel->getNumber()));
                 }
                 $orderModel->setPaymentStatus($paymentStatusModel);
             }
             if (isset($record['status']) && is_numeric($record['status'])) {
                 $orderStatusModel = $orderStatusRepository->find($record['status']);
                 if (!$orderStatusModel) {
                     $message = SnippetsHelper::getNamespace()->get('adapters/orders/status_not_found', 'Status %s was not found for order %s');
                     throw new AdapterException(sprintf($message, $record['status'], $orderModel->getNumber()));
                 }
                 $orderModel->setOrderStatus($orderStatusModel);
             }
             if (isset($record['trackingCode'])) {
                 $orderModel->setTrackingCode($record['trackingCode']);
             }
             if (isset($record['comment'])) {
                 $orderModel->setComment($record['comment']);
             }
             if (isset($record['customerComment'])) {
                 $orderModel->setCustomerComment($record['customerComment']);
             }
             if (isset($record['internalComment'])) {
                 $orderModel->setInternalComment($record['internalComment']);
             }
             if (isset($record['transactionId'])) {
                 $orderModel->setTransactionId($record['transactionId']);
             }
             if (isset($record['clearedDate'])) {
                 $orderModel->setClearedDate($record['clearedDate']);
             }
             if (isset($record['shipped'])) {
                 $orderDetailModel->setShipped($record['shipped']);
             }
             if (isset($record['statusId']) && is_numeric($record['statusId'])) {
                 $detailStatusModel = $orderDetailStatusRepository->find($record['statusId']);
                 if (!$detailStatusModel) {
                     $message = SnippetsHelper::getNamespace()->get('adapters/orders/detail_status_not_found', 'Detail status with id %s was not found');
                     throw new AdapterException(sprintf($message, $record['statusId']));
                 }
                 $orderDetailModel->setStatus($detailStatusModel);
             }
             //prepares the attributes
             foreach ($record as $key => $value) {
                 if (preg_match('/^attribute/', $key)) {
                     $newKey = lcfirst(preg_replace('/^attribute/', '', $key));
                     $orderData['attribute'][$newKey] = $value;
                     unset($record[$key]);
                 }
             }
             if ($orderData) {
                 $orderModel->fromArray($orderData);
             }
             $this->modelManager->persist($orderModel);
             unset($orderDetailModel);
             unset($orderModel);
             unset($orderData);
         } catch (AdapterException $e) {
             $message = $e->getMessage();
             $this->saveMessage($message);
         }
     }
     $this->modelManager->flush();
 }