/**
  * @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();
 }
Exemplo n.º 3
0
 /**
  * @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();
 }
Exemplo n.º 4
0
 private function insertConfiguratorData($groups)
 {
     $pos = 1;
     $data = array();
     foreach ($groups as $groupName => $options) {
         $group = new Models\Article\Configurator\Group();
         $group->setName($groupName);
         $group->setPosition($groups);
         $this->db->executeQuery("DELETE FROM s_article_configurator_groups WHERE name = ?", array($groupName));
         $collection = array();
         $optionPos = 1;
         foreach ($options as $optionName) {
             $this->db->executeQuery("DELETE FROM s_article_configurator_options WHERE name = ?", array($optionName));
             $option = new Models\Article\Configurator\Option();
             $option->setName($optionName);
             $option->setPosition($optionPos);
             $collection[] = $option;
             $optionPos++;
         }
         $group->setOptions($collection);
         $pos++;
         $data[] = $group;
         $this->entityManager->persist($group);
         $this->entityManager->flush();
         $this->entityManager->clear();
         $this->createdConfiguratorGroups[] = $group->getId();
     }
     return $data;
 }
 /**
  * @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();
 }
 /**
  * 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);
         }
     }
 }
Exemplo n.º 7
0
 /**
  * Helper function which iterates the engine\Shopware\Themes directory
  * and registers all stored themes within the directory as \Shopware\Models\Shop\Template.
  *
  * @param \DirectoryIterator $directories
  * @param \Shopware\Models\Plugin\Plugin $plugin
  * @return Theme[]
  */
 private function synchronizeThemeDirectories(\DirectoryIterator $directories, Plugin $plugin = null)
 {
     $themes = array();
     $settings = $this->service->getSystemConfiguration(AbstractQuery::HYDRATE_OBJECT);
     /**@var $directory \DirectoryIterator */
     foreach ($directories as $directory) {
         //check valid directory
         if ($directory->isDot() || !$directory->isDir() || $directory->getFilename() == '_cache') {
             continue;
         }
         try {
             $theme = $this->util->getThemeByDirectory($directory);
         } catch (\Exception $e) {
             continue;
         }
         $data = $this->getThemeDefinition($theme);
         $template = $this->repository->findOneBy(array('template' => $theme->getTemplate()));
         if (!$template instanceof Shop\Template) {
             $template = new Shop\Template();
             if ($plugin) {
                 $template->setPlugin($plugin);
             }
             $this->entityManager->persist($template);
         }
         $template->fromArray($data);
         if (!$template->getId() || $settings->getReloadSnippets()) {
             $this->synchronizeSnippets($template);
         }
         $this->entityManager->flush($template);
         $themes[] = $theme;
     }
     return $themes;
 }
 /**
  * @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();
 }
Exemplo n.º 9
0
 /**
  * Create a privilege in a particular resource
  * @param int $resourceId
  * @param string $name
  */
 public function createPrivilege($resourceId, $name)
 {
     $privilege = new \Shopware\Models\User\Privilege();
     $privilege->setName($name);
     $privilege->setResourceId($resourceId);
     $this->em->persist($privilege);
     $this->em->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();
 }
Exemplo n.º 11
0
 /**
  * Saves the passed configuration data into the database.
  *
  * @param $data
  */
 public function saveSystemConfiguration($data)
 {
     $settings = $this->getSystemConfiguration(AbstractQuery::HYDRATE_OBJECT);
     if (!$settings instanceof Settings) {
         $settings = new Settings();
         $this->entityManager->persist($settings);
     }
     $settings->fromArray($data);
     $this->entityManager->flush();
 }
 /**
  * @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();
 }
Exemplo n.º 13
0
 /**
  * @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;
 }
 /**
  * @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);
     }
 }
 /**
  * @param Option[] $options
  * @param $imageData
  * @param $parent Image
  */
 protected function createImagesForOptions($options, $imageData, $parent)
 {
     $articleId = $parent->getArticle()->getId();
     $imageData['path'] = null;
     $imageData['parent'] = $parent;
     $join = '';
     foreach ($options as $option) {
         $alias = 'alias' . $option->getId();
         $join = $join . ' INNER JOIN s_article_configurator_option_relations alias' . $option->getId() . ' ON ' . $alias . '.option_id = ' . $option->getId() . ' AND ' . $alias . '.article_id = d.id ';
     }
     $sql = "SELECT d.id\n                FROM s_articles_details d\n        " . $join . "\n        WHERE d.articleID = " . (int) $articleId;
     $details = $this->db->fetchCol($sql);
     foreach ($details as $detailId) {
         $detail = $this->manager->getReference(Detail::class, $detailId);
         $image = new Image();
         $image->fromArray($imageData);
         $image->setArticleDetail($detail);
         $this->manager->persist($image);
     }
 }
Exemplo n.º 16
0
 private function createAclResource()
 {
     // If exists: find existing SwagImportExport resource
     $pluginId = $this->db->fetchRow('SELECT pluginID FROM s_core_acl_resources WHERE name = ? ', ["swagimportexport"]);
     $pluginId = isset($pluginId['pluginID']) ? $pluginId['pluginID'] : null;
     if ($pluginId) {
         // prevent creation of new acl resource
         return;
     }
     $resource = new \Shopware\Models\User\Resource();
     $resource->setName('swagimportexport');
     $resource->setPluginId($this->getId());
     foreach (['export', 'import', 'profile', 'read'] as $action) {
         $privilege = new \Shopware\Models\User\Privilege();
         $privilege->setResource($resource);
         $privilege->setName($action);
         $this->em->persist($privilege);
     }
     $this->em->persist($resource);
     $this->em->flush();
 }
Exemplo n.º 17
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();
 }
Exemplo n.º 18
0
 /**
  * @param Plugin $plugin
  * @param string $name
  * @param mixed $value
  * @param Shop $shop
  * @throws \Exception
  */
 public function saveConfigElement(Plugin $plugin, $name, $value, Shop $shop = null)
 {
     if ($shop === null) {
         $shopRepository = $this->em->getRepository('Shopware\\Models\\Shop\\Shop');
         $shop = $shopRepository->find($shopRepository->getActiveDefault()->getId());
     }
     $elementRepository = $this->em->getRepository('Shopware\\Models\\Config\\Element');
     $formRepository = $this->em->getRepository('Shopware\\Models\\Config\\Form');
     $valueRepository = $this->em->getRepository('Shopware\\Models\\Config\\Value');
     /** @var $form \Shopware\Models\Config\Form*/
     $form = $formRepository->findOneBy(['pluginId' => $plugin->getId()]);
     /** @var $element \Shopware\Models\Config\Element */
     $element = $elementRepository->findOneBy(['form' => $form, 'name' => $name]);
     if (!$element) {
         throw new \Exception(sprintf('Config element "%s" not found.', $name));
     }
     if ($element->getScope() == 0) {
         // todo prevent subshop updates
     }
     $defaultValue = $element->getValue();
     $valueModel = $valueRepository->findOneBy(['shop' => $shop, 'element' => $element]);
     if (!$valueModel) {
         if ($value == $defaultValue || $value === null) {
             return;
         }
         $valueModel = new Value();
         $valueModel->setElement($element);
         $valueModel->setShop($shop);
         $valueModel->setValue($value);
         $this->em->persist($valueModel);
         $this->em->flush($valueModel);
         return;
     }
     if ($value == $defaultValue || $value === null) {
         $this->em->remove($valueModel);
     } else {
         $valueModel->setValue($value);
     }
     $this->em->flush($valueModel);
 }
 /**
  * @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();
 }
 /**
  * @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();
 }
Exemplo n.º 21
0
 /**
  * @param Form\Interfaces\Field $field
  * @param Template $template
  * @param TemplateConfig\Layout $parent
  */
 private function saveField(Form\Interfaces\Field $field, Template $template, TemplateConfig\Layout $parent)
 {
     /**@var $field Form\Field */
     $lessCompatible = true;
     if (array_key_exists('lessCompatible', $field->getAttributes())) {
         $attributes = $field->getAttributes();
         $lessCompatible = (bool) $attributes['lessCompatible'];
     }
     $data = array('attributes' => $field->getAttributes(), 'fieldLabel' => $field->getLabel(), 'name' => $field->getName(), 'defaultValue' => $field->getDefaultValue(), 'supportText' => $field->getHelp(), 'allowBlank' => !$field->isRequired(), 'lessCompatible' => $lessCompatible);
     $class = get_class($field);
     switch ($class) {
         case "Shopware\\Components\\Form\\Field\\Text":
             /**@var $field Form\Field\Text */
             $data += array('type' => 'theme-text-field');
             break;
         case "Shopware\\Components\\Form\\Field\\Boolean":
             /**@var $field Form\Field\Boolean */
             $data += array('type' => 'theme-checkbox-field');
             break;
         case "Shopware\\Components\\Form\\Field\\Date":
             /**@var $field Form\Field\Date */
             $data += array('type' => 'theme-date-field');
             break;
         case "Shopware\\Components\\Form\\Field\\Color":
             /**@var $field Form\Field\Color */
             $data += array('type' => 'theme-color-picker');
             break;
         case "Shopware\\Components\\Form\\Field\\Media":
             /**@var $field Form\Field\Media */
             $data += array('type' => 'theme-media-selection');
             break;
         case "Shopware\\Components\\Form\\Field\\Number":
             /**@var $field Form\Field\Number */
             $data += array('type' => 'numberfield');
             break;
         case "Shopware\\Components\\Form\\Field\\Em":
             /**@var $field Form\Field\Number */
             $data += array('type' => 'theme-em-field');
             break;
         case "Shopware\\Components\\Form\\Field\\Percent":
             /**@var $field Form\Field\Number */
             $data += array('type' => 'theme-percent-field');
             break;
         case "Shopware\\Components\\Form\\Field\\Pixel":
             /**@var $field Form\Field\Number */
             $data += array('type' => 'theme-pixel-field');
             break;
         case "Shopware\\Components\\Form\\Field\\TextArea":
             /**@var $field Form\Field\Number */
             $data += array('type' => 'theme-text-area-field');
             break;
         case "Shopware\\Components\\Form\\Field\\Selection":
             /**@var $field Form\Field\Selection */
             $data += array('type' => 'theme-select-field', 'selection' => $field->getStore());
             break;
     }
     $entity = $this->checkExistingElement($template->getElements(), $field->getName());
     $entity->fromArray($data);
     $entity->setTemplate($template);
     $entity->setContainer($parent);
     $this->entityManager->persist($entity);
 }
 /**
  * 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();
 }