/**
  * @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;
 }
 /**
  *
  * @param OutputInterface $output
  * @param ProfileEntity $profileModel
  * @param string $file
  * @param string $format
  */
 protected function start(OutputInterface $output, $profileModel, $file, $format)
 {
     $helper = new CommandHelper(array('profileEntity' => $profileModel, 'filePath' => $file, 'format' => $format, 'username' => 'Commandline'));
     $output->writeln('<info>' . sprintf("Using profile: %s.", $profileModel->getName()) . '</info>');
     $output->writeln('<info>' . sprintf("Using format: %s.", $format) . '</info>');
     $output->writeln('<info>' . sprintf("Using file: %s.", $file) . '</info>');
     $return = $helper->prepareImport();
     $count = $return['count'];
     $output->writeln('<info>' . sprintf("Total count: %d.", $count) . '</info>');
     $return = $helper->importAction();
     $position = $return['data']['position'];
     $output->writeln('<info>' . sprintf("Processed: %d.", $position) . '</info>');
     while ($position < $count) {
         $return = $helper->importAction();
         $position = $return['data']['position'];
         $output->writeln('<info>' . sprintf("Processed: %d.", $position) . '</info>');
     }
 }
 /**
  * @param InputInterface $input
  */
 protected function validateProfiles(InputInterface $input)
 {
     if (!$this->profileEntity) {
         throw new Exception(sprintf('Invalid profile: \'%s\'!', $this->profile));
     }
     if ($this->profileEntity->getType() != 'articles' && $input->getOption('exportVariants')) {
         throw new \InvalidArgumentException('You can only export variants when exporting the articles profile type.');
     }
     if ($this->profileEntity->getType() == 'articlesImages') {
         throw new \InvalidArgumentException("articlesImages profile type is not supported at the moment.");
     }
 }
 /**
  * @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 Profile $profile
  */
 public function __construct(Profile $profile)
 {
     $this->name = $profile->getName();
     $this->type = $profile->getType();
     $this->tree = json_decode($profile->getTree(), true);
 }
 /**
  * @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();
 }
 /**
  * Executes import action
  *
  * @return array
  */
 public function importAction()
 {
     /** @var UploadPathProvider $uploadPathProvider */
     $uploadPathProvider = Shopware()->Container()->get('swag_import_export.upload_path_provider');
     $postData = array('type' => 'import', 'profileId' => (int) $this->profileEntity->getId(), 'importFile' => $this->filePath, 'sessionId' => $this->sessionId, 'format' => $this->format, 'columnOptions' => null, 'limit' => array(), 'filter' => null, 'max_record_count' => null);
     $inputFile = $postData['importFile'];
     $logger = $this->getLogger();
     // we create the file reader that will read the result file
     /** @var FileIOFactory $fileFactory */
     $fileFactory = $this->Plugin()->getFileIOFactory();
     $fileReader = $fileFactory->createFileReader($postData['format']);
     //load profile
     /** @var Profile $profile */
     $profile = $this->Plugin()->getProfileFactory()->loadProfile($postData);
     //get profile type
     $postData['adapter'] = $profile->getType();
     //setting up the batch size
     $postData['batchSize'] = $profile->getType() === 'articlesImages' ? 1 : 50;
     /** @var DataFactory $dataFactory */
     $dataFactory = $this->Plugin()->getDataFactory();
     $dbAdapter = $dataFactory->createDbAdapter($profile->getType());
     $dataSession = $dataFactory->loadSession($postData);
     //create dataIO
     $dataIO = $dataFactory->createDataIO($dbAdapter, $dataSession, $logger);
     $colOpts = $dataFactory->createColOpts($postData['columnOptions']);
     $limit = $dataFactory->createLimit($postData['limit']);
     $filter = $dataFactory->createFilter($postData['filter']);
     $maxRecordCount = $postData['max_record_count'];
     $type = $postData['type'];
     $format = $postData['format'];
     $dataIO->initialize($colOpts, $limit, $filter, $type, $format, $maxRecordCount);
     $dataIO->setUsername($this->username);
     /** @var DataTransformerChain $dataTransformerChain */
     $dataTransformerChain = $this->Plugin()->getDataTransformerFactory()->createDataTransformerChain($profile, array('isTree' => $fileReader->hasTreeStructure()));
     $sessionState = $dataIO->getSessionState();
     $dataWorkflow = new DataWorkflow($dataIO, $profile, $dataTransformerChain, $fileReader);
     try {
         $post = $dataWorkflow->import($postData, $inputFile);
         if (isset($post['unprocessedData']) && $post['unprocessedData']) {
             $data = array('data' => $post['unprocessedData'], 'session' => array('prevState' => $sessionState, 'currentState' => $dataIO->getSessionState()));
             $pathInfo = pathinfo($inputFile);
             foreach ($data['data'] as $key => $value) {
                 $outputFile = $uploadPathProvider->getRealPath($pathInfo['filename'] . '-' . $key . '-tmp.csv');
                 $post['unprocessed'][] = array('profileName' => $key, 'fileName' => $outputFile);
                 $this->afterImport($data, $key, $outputFile);
             }
         }
         $this->sessionId = $post['sessionId'];
         if ($dataSession->getTotalCount() > 0 && $dataSession->getTotalCount() == $post['position'] && $logger->getMessage() === null) {
             $message = sprintf('%s %s %s', $post['position'], SnippetsHelper::getNamespace('backend/swag_import_export/default_profiles')->get($post['adapter']), SnippetsHelper::getNamespace('backend/swag_import_export/log')->get('import/success'));
             $logger->write($message, 'false', $dataSession->getEntity());
             $logDataStruct = new LogDataStruct(date("Y-m-d H:i:s"), $inputFile, $profile->getName(), $message, 'false');
             $logger->writeToFile($logDataStruct);
         }
         return array('success' => true, 'data' => $post);
     } catch (\Exception $e) {
         $logger->write($e->getMessage(), 'true', $dataSession->getEntity());
         $logDataStruct = new LogDataStruct(date("Y-m-d H:i:s"), $inputFile, $profile->getName(), $e->getMessage(), 'false');
         $logger->writeToFile($logDataStruct);
         throw $e;
     }
 }
 /**
  * @return Enlight_View|Enlight_View_Default
  * @throws Exception
  */
 public function duplicateProfileAction()
 {
     $manager = $this->getModelManager();
     $snippetManager = $this->get('snippets');
     $profileId = (int) $this->Request()->getParam('profileId');
     $loadedProfile = $manager->find(Profile::class, $profileId);
     if (!$loadedProfile) {
         throw new \Exception(sprintf('Profile with id %s does NOT exist', $profileId));
     }
     $profile = new Profile();
     $profile->setBaseProfile($loadedProfile->getId());
     $profile->setName($loadedProfile->getName() . ' (' . $snippetManager->getNamespace('backend/swag_import_export/controller')->get('swag_import_export/profile/copy') . ')');
     $profile->setType($loadedProfile->getType());
     $profile->setTree($loadedProfile->getTree());
     $manager->persist($profile);
     try {
         $manager->flush();
     } catch (DBALException $e) {
         return $this->View()->assign(['success' => false, 'message' => $snippetManager->getNamespace('backend/swag_import_export/controller')->get('swag_import_export/profile/duplicate_unique_error_msg')]);
     } catch (\Exception $e) {
         return $this->View()->assign(['success' => false, 'message' => $e->getMessage()]);
     }
     return $this->View()->assign(['success' => true, 'data' => ['id' => $profile->getId(), 'name' => $profile->getName(), 'type' => $profile->getType(), 'baseProfile' => $profile->getBaseProfile(), 'tree' => $profile->getTree(), 'default' => $profile->getDefault()]]);
 }