/**
  * @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 $filePath
  */
 public function importNewsletter($filePath)
 {
     $results = new Shopware_Components_CsvIterator($filePath, ';');
     $insertCount = 0;
     $updateCount = 0;
     $errors = array();
     $emailValidator = new Zend_Validate_EmailAddress();
     $emailValidator->getHostnameValidator()->setValidateTld(false);
     foreach ($results as $newsletterData) {
         if (empty($newsletterData['email'])) {
             $errors[] = "Empty email field";
             continue;
         }
         if (!$emailValidator->isValid($newsletterData['email'])) {
             $errors[] = "Invalid email address: " . $newsletterData['email'];
             continue;
         }
         // Set newsletter recipient/group
         $group = null;
         if ($newsletterData['group']) {
             $group = $this->getGroupRepository()->findOneByName($newsletterData['group']);
         }
         if (!$group && $newsletterData['group']) {
             $group = new Group();
             $group->setName($newsletterData['group']);
             $this->getManager()->persist($group);
         } elseif (!$group && ($groupId = Shopware()->Config()->get("sNEWSLETTERDEFAULTGROUP"))) {
             $group = $this->getGroupRepository()->findOneBy($groupId);
         } elseif (!$group) {
             // If no group is specified and no default config exists, don't import the address
             // This should never actually happen, as a default should always exist
             // but its better to be safe than sorry
             continue;
         }
         //Create/Update the Address entry
         $recipient = $this->getAddressRepository()->findOneByEmail($newsletterData['email']) ?: new Address();
         if ($recipient->getId()) {
             $updateCount++;
         } else {
             $insertCount++;
         }
         $recipient->setEmail($newsletterData['email']);
         $recipient->setIsCustomer(!empty($newsletterData['userID']));
         //Only set the group if it was explicitly provided or it's a new entry
         if ($group && ($newsletterData['group'] || !$recipient->getId())) {
             $recipient->setNewsletterGroup($group);
         }
         $this->getManager()->persist($recipient);
         $this->getManager()->flush();
         //Create/Update the ContactData entry
         $contactData = $this->getContactDataRepository()->findOneByEmail($newsletterData['email']) ?: new ContactData();
         //sanitize to avoid setting fields the user's not supposed to access
         unset($newsletterData['added']);
         unset($newsletterData['deleted']);
         $contactData->fromArray($newsletterData);
         //Only set the group if it was explicitly provided or it's a new entry
         if ($group && ($newsletterData['group'] || !$contactData->getId())) {
             $contactData->setGroupId($group->getId());
         }
         $contactData->setAdded(new \DateTime());
         $this->getManager()->persist($contactData);
         $this->getManager()->flush();
     }
     if (!empty($errors)) {
         $message = implode("<br>\n", $errors);
         echo json_encode(array('success' => false, 'message' => sprintf("Errors: {$message}")));
         return;
     }
     echo json_encode(array('success' => true, 'message' => sprintf("Imported: %s. Updated: %s.", $insertCount, $updateCount)));
     return;
 }