/**
  * CategoryImporter constructor.
  *
  * @param PDOConnection $db
  * @param ModelManager $em
  * @param Logger $logger
  */
 public function __construct(PDOConnection $db, ModelManager $em, Logger $logger)
 {
     $this->db = $db;
     $this->em = $em;
     $this->repository = $this->em->getRepository('Shopware\\Models\\Category\\Category');
     $this->logger = $logger;
 }
 /**
  * @inheritdoc
  */
 public function exportProfile($profileId)
 {
     $profileRepository = $this->modelManager->getRepository(Profile::class);
     $profile = $profileRepository->findOneBy(['id' => $profileId]);
     $profileDataStruct = new ProfileDataStruct($profile);
     return $profileDataStruct;
 }
Beispiel #3
0
 protected function getDefaultData($shopId, $builder)
 {
     $shopRepository = $this->em->getRepository('Shopware\\Models\\Shop\\Shop');
     $shop = $shopRepository->getActiveDefault();
     //get default shop's settings
     $builder->setParameters(array('shopId' => $shop->getId()));
     $data = $builder->getQuery()->getArrayResult();
     if (array_key_exists(0, $data)) {
         $data = $data[0];
     }
     //check whether default shop's settings are empty too
     if (empty($data)) {
         $data = array('id' => $shopId, 'shopId' => $shopId, 'trustedShopsTestSystem' => 0, 'trustedShopsShowRatingWidget' => 1, 'trustedShopsShowRatingsButtons' => 0, 'trustedShopsRateLaterDays' => 7, 'trustedShopsLanguageRatingButtons' => 'de', 'trustedShopsWidthRatingButtons' => 290);
     } else {
         $data['id'] = $shopId;
         $data['shopId'] = $shopId;
         $data['emptyId'] = $data['trustedShopsId'];
         $data['emptyUser'] = $data['trustedShopsUser'];
         $data['emptyPassword'] = $data['trustedShopsPassword'];
         $data['trustedShopsId'] = '';
         $data['trustedShopsUser'] = '';
         $data['trustedShopsPassword'] = '';
         $data['trustedShopsTrustBadgeCode'] = '';
     }
     return $data;
 }
 private function getSortRepository()
 {
     if ($this->customSortRepo === null) {
         $this->customSortRepo = $this->em->getRepository('Shopware\\CustomModels\\CustomSort\\ArticleSort');
     }
     return $this->customSortRepo;
 }
 /**
  * @return MediaRepository
  */
 private function getMediaRepository()
 {
     if ($this->mediaRepository === null) {
         $this->mediaRepository = $this->em->getRepository('Shopware\\Models\\Media\\Media');
     }
     return $this->mediaRepository;
 }
 public function __construct()
 {
     $this->validator = new ArticleInStockValidator();
     $this->snippetHelper = new SnippetsHelper();
     $this->modelManager = Shopware()->Container()->get('models');
     $this->repository = $this->modelManager->getRepository(Detail::class);
 }
 public function test_install_should_remove_old_menu_item()
 {
     $menuRepository = $this->modelManger->getRepository(Menu::class);
     $oldMenuItem = $menuRepository->findOneBy(['label' => self::OLD_MENU_LABEL]);
     $this->createMenuItemIfItDoesNotExist($oldMenuItem, self::OLD_MENU_LABEL);
     $this->mainMenuItemInstaller->install();
     $removedMenuItem = $menuRepository->findOneBy(['label' => self::OLD_MENU_LABEL]);
     $this->assertNull($removedMenuItem, 'Old menu item for SwagImportExport advanced should be removed on update or installation to 5.3.');
 }
 /**
  * Resolve username/realm to password/hash/etc.
  *
  * @param  string $username Username
  * @param  string $realm    Authentication Realm
  * @return string|false User's shared secret, if the user is found in the
  *         realm, false otherwise.
  */
 public function resolve($username, $realm)
 {
     $repository = $this->modelManager->getRepository('Shopware\\Models\\User\\User');
     $user = $repository->findOneBy(array('username' => $username, 'active' => true));
     if (!$user) {
         return false;
     }
     if ($user->getApiKey() === null) {
         return false;
     }
     $apiKey = $user->getApiKey();
     return md5($username . ':' . $realm . ':' . $apiKey);
 }
 /**
  * Given a category id, returns the category path
  *
  * @param int $categoryId Id of the category
  * @return array Array containing the path parts
  */
 public function sCategoryPath($categoryId)
 {
     $parts = $this->modelManager->getRepository('Shopware\\Models\\Category\\Category')->getPathById($categoryId, 'name');
     $level = Shopware()->Shop()->getCategory()->getLevel();
     $parts = array_slice($parts, $level);
     return $parts;
 }
Beispiel #10
0
 /**
  * @param Model\ModelManager $entityManager
  * @param Util $util
  * @param Form\Persister\Theme $persister
  * @param \Enlight_Event_EventManager $eventManager
  */
 public function __construct(Model\ModelManager $entityManager, Util $util, Form\Persister\Theme $persister, \Enlight_Event_EventManager $eventManager)
 {
     $this->entityManager = $entityManager;
     $this->persister = $persister;
     $this->util = $util;
     $this->eventManager = $eventManager;
     $this->repository = $entityManager->getRepository('Shopware\\Models\\Shop\\Template');
 }
 /**
  * @return \Doctrine\ORM\QueryBuilder
  */
 public function getElementBuilder()
 {
     $repository = $this->modelManager->getRepository(Element::class);
     $builder = $repository->createQueryBuilder('attribute');
     $builder->andWhere('attribute.translatable = 1');
     $builder->orderBy('attribute.position');
     return $builder;
 }
 /**
  * Helper function that queries all sub shops (including language sub shops).
  * @return array
  */
 private function getData()
 {
     /** @var \Shopware\Models\Shop\Repository $repository */
     $repository = $this->models->getRepository('Shopware\\Models\\Shop\\Shop');
     $builder = $repository->getActiveQueryBuilder();
     $builder->orderBy('shop.id');
     return $builder->getQuery()->getArrayResult();
 }
Beispiel #13
0
 /**
  * initialises the bootstrapPath variable
  *
  * @param $em
  * @param $soapApi
  * @param $config
  */
 public function __construct(ModelManager $em, SoapApi $soapApi, Config $config)
 {
     $this->db = $em->getConnection();
     $this->tsSoapApi = $soapApi;
     $this->tsConfig = $config;
     /** @var Repository $shopRepository */
     $shopRepository = $em->getRepository('Shopware\\Models\\Shop\\Shop');
     $this->shops = $shopRepository->getActiveShops(AbstractQuery::HYDRATE_ARRAY);
 }
 /**
  * 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 $type
  * @return Profile
  * @throws \Exception
  */
 public function loadHiddenProfile($type)
 {
     /** @var Repository $profileRepository */
     $profileRepository = $this->modelManager->getRepository(ProfileEntity::class);
     $profileEntity = $profileRepository->findOneBy(['type' => $type, 'hidden' => 1]);
     if (!$profileEntity) {
         $data = ['name' => $type . 'Shopware', 'type' => $type, 'hidden' => 1];
         $profileEntity = $this->createProfileModel($data);
     }
     return new Profile($profileEntity);
 }
 /**
  * Helper function to read the landing pages urls
  *
  * @return array
  */
 private function readLandingPageUrls()
 {
     $categoryId = $this->contextService->getShopContext()->getShop()->getCategory()->getId();
     $emotionRepository = $this->em->getRepository('Shopware\\Models\\Emotion\\Emotion');
     $builder = $emotionRepository->getCampaignsByCategoryId($categoryId);
     $campaigns = $builder->getQuery()->getArrayResult();
     foreach ($campaigns as &$campaign) {
         $campaign['show'] = $this->filterCampaign($campaign[0]['validFrom'], $campaign[0]['validTo']);
         $campaign['urlParams'] = array('sViewport' => 'campaign', 'emotionId' => $campaign[0]['id'], 'sCategory' => $campaign['categoryId']);
     }
     return $campaigns;
 }
Beispiel #17
0
 /**
  * Generates and inserts static page urls
  *
  * @param $offset
  * @param $limit
  */
 private function insertStaticPageUrls($offset, $limit)
 {
     $shopId = Shopware()->Shop()->getId();
     $sitesData = $this->modelManager->getRepository('Shopware\\Models\\Site\\Site')->getSitesWithoutLinkQuery($shopId, $offset, $limit)->getArrayResult();
     foreach ($sitesData as $site) {
         $org_path = 'sViewport=custom&sCustom=' . $site['id'];
         $this->data->assign('site', $site);
         $path = $this->template->fetch('string:' . $this->config->get('seoCustomSiteRouteTemplate'), $this->data);
         $path = $this->sCleanupPath($path, false);
         $this->sInsertUrl($org_path, $path);
     }
 }
Beispiel #18
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();
 }
 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();
 }
Beispiel #20
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;
 }
 /**
  * @param array $taxData
  * @return float
  * @throws \Doctrine\ORM\ORMException
  * @throws \Doctrine\ORM\OptimisticLockException
  * @throws \Doctrine\ORM\TransactionRequiredException
  */
 private function calculateTaxSum($taxData)
 {
     if (empty($taxData['taxRate'])) {
         $taxModel = $this->modelManager->getRepository(Tax::class)->find($taxData['taxId']);
         if ($taxModel && $taxModel->getId() !== 0 && $taxModel->getId() !== null && $taxModel->getTax() !== null) {
             $taxValue = $taxModel->getTax();
         }
     } else {
         $taxValue = $taxData['taxRate'];
     }
     $price = $taxData['price'] * $taxData['quantity'];
     if ($taxData['net']) {
         return round($taxValue / 100 * $price, 2);
     } else {
         return round($price * ($taxValue / (100 + $taxValue)), 2);
     }
 }
Beispiel #22
0
 /**
  * prepares the data for the soap request
  *
  * @param sOrder $order
  * @param string $tsProductId
  * @param $shopId
  * @return array | data for the soap call
  */
 private function prepareDataForSoapRequest(sOrder $order, $tsProductId, $shopId)
 {
     /** @var Repository $shopRepository */
     $shopRepository = $this->em->getRepository('Shopware\\Models\\Shop\\Shop');
     $shop = $shopRepository->findOneBy(array('id' => $shopId));
     $settings = $this->tsConfig->getSettings($shopId);
     $user = $order->sUserData;
     $basket = $order->sBasketData;
     $userID = $user['billingaddress']['customernumber'];
     $currency = $shop->getCurrency()->toArray();
     $payment = $user['additional']['payment']['name'];
     $payment = $this->tsConfig->getTsPaymentCode($payment);
     $orderNumber = $order->sOrderNumber;
     $orderDate = date('Y-m-d', time()) . 'T' . date('H:i:s', time());
     $shopSystemVersion = 'Shopware/' . $this->config->get('Version') . ' ? TS v0.1';
     $decimalAmount = (double) $basket['AmountNumeric'];
     $tsId = $settings['trustedShopsId'];
     return array($tsId, $tsProductId, $decimalAmount, strtoupper($currency['currency']), strtoupper($payment), $user['additional']['user']['email'], $userID, $orderNumber, $orderDate, $shopSystemVersion, $settings['trustedShopsUser'], $settings['trustedShopsPassword']);
 }
 /**
  *
  */
 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 #24
0
 /**
  * When a Criteria is created, check for plugin sorting options. If plugin sorting options exist, add them.
  *
  * @param Enlight_Event_EventArgs $args
  */
 public function onCreateListingCriteria(Enlight_Event_EventArgs $args)
 {
     /** @var Request $request */
     $request = $args->get('request');
     /** @var Criteria $criteria */
     $criteria = $args->get('criteria');
     $allowedActions = ['index', 'ajaxListing', 'productNavigation'];
     //Don't apply custom sort if we are not in category listing
     if (!in_array($request->getActionName(), $allowedActions)) {
         return;
     }
     if (!$this->listingComponent instanceof Listing) {
         return;
     }
     $categoryId = (int) $request->getParam('sCategory');
     $useDefaultSort = $this->listingComponent->showCustomSortAsDefault($categoryId);
     $sortName = $this->listingComponent->getFormattedSortName();
     $baseSort = $this->listingComponent->getCategoryBaseSort($categoryId);
     $sortId = $request->getParam('sSort');
     if ($request->getParam('sSort') == SortFactory::DRAG_DROP_SORTING) {
         $useDefaultSort = true;
     }
     if (!$useDefaultSort && $baseSort || empty($sortName) || $sortId !== null && $sortId != SortFactory::DRAG_DROP_SORTING) {
         return;
     }
     $criteria->resetSorting();
     $request->setParam('sSort', SortFactory::DRAG_DROP_SORTING);
     $page = (int) $request->getParam('sPage');
     $offset = (int) $criteria->getOffset();
     $limit = (int) $criteria->getLimit();
     //Get all sorted products for current category and set them in components for further sorting
     $linkedCategoryId = $this->listingComponent->getLinkedCategoryId($categoryId);
     $sortedProducts = $this->em->getRepository('\\Shopware\\CustomModels\\CustomSort\\ArticleSort')->getSortedProducts($categoryId, $linkedCategoryId);
     $this->sortingComponent->setSortedProducts($sortedProducts);
     //Get new offset based on page so we can get correct position of unsorted products
     $newOffset = $this->sortingComponent->getOffset($offset, $page, $limit);
     $this->sortingComponent->setOffsetAndLimit($offset, $limit);
     $criteria->offset($newOffset);
     $sorter = new SortFactory($request, $criteria);
     $sorter->addSort();
 }
 /**
  * @param array $record
  * @return array
  * @throws AdapterException
  * @throws \Doctrine\ORM\ORMException
  * @throws \Doctrine\ORM\OptimisticLockException
  * @throws \Doctrine\ORM\TransactionRequiredException
  * @throws \Exception
  */
 protected function prepareCustomer(array &$record)
 {
     if ($this->customerMap === null) {
         $columns = $this->getCustomerColumns();
         $columns = array_merge($columns, ['customer.subshopID as subshopID', 'customer.languageID as languageId']);
         foreach ($columns as $column) {
             $map = DataHelper::generateMappingFromColumns($column);
             if (empty($map)) {
                 continue;
             }
             $this->customerMap[$map[0]] = $map[1];
         }
     }
     $customerData = [];
     foreach ($record as $key => $value) {
         if (preg_match('/^attrCustomer/', $key)) {
             $newKey = lcfirst(preg_replace('/^attrCustomer/', '', $key));
             $customerData['attribute'][$newKey] = $value;
             unset($record[$key]);
         } elseif (isset($this->customerMap[$key])) {
             $customerData[$this->customerMap[$key]] = $value;
             unset($record[$key]);
         }
     }
     if (isset($customerData['groupKey'])) {
         $customerData['group'] = $this->manager->getRepository(Group::class)->findOneBy(['key' => $customerData['groupKey']]);
         if (!$customerData['group']) {
             $message = SnippetsHelper::getNamespace()->get('adapters/customerGroup_not_found', 'Customer Group by key %s not found');
             throw new \Exception(sprintf($message, $customerData['groupKey']));
         }
     }
     if (isset($customerData['hashPassword']) && !empty($customerData['hashPassword'])) {
         $customerData['rawPassword'] = $customerData['hashPassword'];
     }
     unset($record['hashPassword']);
     return $customerData;
 }
 /**
  * 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();
     }
 }
Beispiel #27
0
 public function createPriceGroup($discounts = array())
 {
     if (empty($discounts)) {
         $discounts = array(array('key' => 'PHP', 'quantity' => 1, 'discount' => 10), array('key' => 'PHP', 'quantity' => 5, 'discount' => 20), array('key' => 'PHP', 'quantity' => 10, 'discount' => 30));
     }
     $this->removePriceGroup();
     $priceGroup = new Models\Price\Group();
     $priceGroup->setName('TEST-GROUP');
     $repo = $this->entityManager->getRepository('Shopware\\Models\\Customer\\Group');
     $collection = array();
     foreach ($discounts as $data) {
         $discount = new Models\Price\Discount();
         $discount->setCustomerGroup($repo->findOneBy(array('key' => $data['key'])));
         $discount->setGroup($priceGroup);
         $discount->setStart($data['quantity']);
         $discount->setDiscount($data['discount']);
         $collection[] = $discount;
     }
     $priceGroup->setDiscounts($collection);
     $this->entityManager->persist($priceGroup);
     $this->entityManager->flush();
     $this->entityManager->clear();
     return $priceGroup;
 }
 /**
  * @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();
 }
 /**
  * A helper function that returns a snippet namespace by a specific locale id
  *
  * @param $localeId
  * @return Enlight_Components_Snippet_Namespace
  */
 private function getSnippetNamespace($localeId)
 {
     /** @var \Shopware\Models\Shop\Locale $locale */
     $locale = $this->models->getRepository('Shopware\\Models\\Shop\\Locale')->find($localeId);
     return $this->snippets->setLocale($locale)->getNamespace('frontend/swag_browser_language/main');
 }
 /**
  * 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();
 }