public function __construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\Module\ModuleList $moduleList, \Magento\Framework\App\Config\MutableScopeConfigInterface $scopeConfig, \Magento\Framework\UrlInterface $urlBuilder, \Magento\Framework\Session\SessionManagerInterface $session, \Wyomind\Core\Helper\Data $coreHelper, \Magento\Framework\Filesystem\Directory\ReadFactory $directoryRead, \Magento\Framework\Filesystem\File\ReadFactory $fileRead, \Magento\Framework\App\Filesystem\DirectoryList $directoryList, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = []) { parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_magentoVersion = $coreHelper->getMagentoVersion(); $this->_moduleList = $moduleList; $this->_scopeConfig = $scopeConfig; $this->_urlBuilder = $urlBuilder; $this->_cacheManager = $context->getCacheManager(); $this->_session = $session; $this->_coreHelper = $coreHelper; $root = $directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::ROOT); if (file_exists($root . "/vendor/wyomind/")) { $this->_directoryRead = $directoryRead->create($root . "/vendor/wyomind/"); } else { $this->_directoryRead = $directoryRead->create($root . "/app/code/Wyomind/"); } $this->_httpRead = $fileRead; $this->_directoryList = $directoryList; $this->_version = $this->_moduleList->getOne("Wyomind_Core")['setup_version']; $this->_refreshCache = false; $this->getValues(); foreach ($this->_values as $ext) { $this->checkActivation($ext); } if ($this->_refreshCache) { $this->_cacheManager->clean(['config']); } }
/** * Get an array of URNs * * @param OutputInterface $output * @return array */ private function getUrnDictionary(OutputInterface $output) { $files = $this->filesUtility->getXmlCatalogFiles('*.xml'); $files = array_merge($files, $this->filesUtility->getXmlCatalogFiles('*.xsd')); $urns = []; foreach ($files as $file) { $fileDir = dirname($file[0]); $fileName = basename($file[0]); $read = $this->readFactory->create($fileDir); $content = $read->readFile($fileName); $matches = []; preg_match_all('/schemaLocation="(urn\\:magento\\:[^"]*)"/i', $content, $matches); if (isset($matches[1])) { $urns = array_merge($urns, $matches[1]); } } $urns = array_unique($urns); $paths = []; foreach ($urns as $urn) { try { $paths[$urn] = $this->urnResolver->getRealPath($urn); } catch (\Exception $e) { // don't add unsupported element to array if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $output->writeln($e->getMessage()); } } } return $paths; }
/** * Create an instance of directory with read permissions * * @param string $directoryCode * @param string $driverCode * @return \Magento\Framework\Filesystem\Directory\ReadInterface */ public function getDirectoryRead($directoryCode, $driverCode = DriverPool::FILE) { $code = $directoryCode . '_' . $driverCode; if (!array_key_exists($code, $this->readInstances)) { $this->readInstances[$code] = $this->readFactory->create($this->getDirPath($directoryCode), $driverCode); } return $this->readInstances[$code]; }
/** * Minify template file * * @param string $file * @return void */ public function minify($file) { $dir = dirname($file); $fileName = basename($file); $content = preg_replace('#(?<!]]>)\\s+</#', '</', preg_replace('#((?:<\\?php\\s+(?!echo|print|if|elseif|else)[^\\?]*)\\?>)\\s+#', '$1 ', preg_replace('#(?<!' . implode('|', $this->inlineHtmlTags) . ')\\> \\<#', '><', preg_replace('#(?ix)(?>[^\\S ]\\s*|\\s{2,})(?=(?:(?:[^<]++|<(?!/?(?:textarea|pre|script)\\b))*+)' . '(?:<(?>textarea|pre|script)\\b|\\z))#', ' ', preg_replace('#(?<!:|\\\\|\'|")//(?!\\s*\\<\\!\\[)(?!\\s*]]\\>)[^\\n\\r]*#', '', preg_replace('#(?<!:)//[^\\n\\r]*(\\s\\?\\>)#', '$1', $this->readFactory->create($dir)->readFile($fileName))))))); if (!$this->htmlDirectory->isExist()) { $this->htmlDirectory->create(); } $this->htmlDirectory->writeFile($this->getRelativeGeneratedPath($file), rtrim($content)); }
/** * Get path of file after using fallback rules * * @param RuleInterface $fallbackRule * @param string $file * @param array $params * @return string|bool */ protected function resolveFile(RuleInterface $fallbackRule, $file, array $params = []) { foreach ($fallbackRule->getPatternDirs($params) as $dir) { $path = "{$dir}/{$file}"; $dirRead = $this->readFactory->create($dir); if ($dirRead->isExist($file)) { return $path; } } return false; }
/** * @param $filePath Absolute file path to CSV file */ public function setFile($filePath) { if (!file_exists($filePath)) { throw new FileNotFoundException(); } // Hacky but quick fix for https://github.com/cedricblondeau/magento2-module-catalog-import-command/issues/1 $pathInfo = pathinfo($filePath); $validate = $this->importModel->validateSource($this->csvSourceFactory->create(['file' => $pathInfo['basename'], 'directory' => $this->readFactory->create($pathInfo['dirname'])])); if (!$validate) { throw new \InvalidArgumentException(); } }
/** * Initialize package name to full theme path map * * @return void * @throws \Zend_Json_Exception */ private function initializeMap() { $themePaths = $this->componentRegistrar->getPaths(ComponentRegistrar::THEME); /** @var \Magento\Theme\Model\Theme $theme */ foreach ($themePaths as $fullThemePath => $themeDir) { $themeDirRead = $this->readDirFactory->create($themeDir); if ($themeDirRead->isExist('composer.json')) { $rawData = \Zend_Json::decode($themeDirRead->readFile('composer.json')); if (isset($rawData['name'])) { $this->packageNameToFullPathMap[$rawData['name']] = $fullThemePath; } } } }
/** * @inheritdoc */ public function install() { $this->eavConfig->clear(); $importModel = $this->importModel; $importModel->setData(['entity' => 'catalog_product', 'behavior' => 'append', 'import_images_file_dir' => 'pub/media/catalog/product', Import::FIELD_NAME_VALIDATION_STRATEGY => ProcessingErrorAggregatorInterface::VALIDATION_STRATEGY_SKIP_ERRORS]); $source = $this->csvSourceFactory->create(['file' => 'fixtures/products.csv', 'directory' => $this->readFactory->create($this->componentRegistrar->getPath(ComponentRegistrar::MODULE, 'Magento_ConfigurableSampleData'))]); $currentPath = getcwd(); chdir(BP); $importModel->validateSource($source); $importModel->importSource(); chdir($currentPath); $this->eavConfig->clear(); $this->reindex(); }
/** * Retrieve files * * @param ThemeInterface $theme * @param string $filePath * @return \Magento\Framework\View\File[] */ public function getFiles(ThemeInterface $theme, $filePath) { $namespace = $module = '*'; $themePath = $theme->getFullPath(); if (empty($themePath)) { return []; } $themeAbsolutePath = $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $themePath); if (!$themeAbsolutePath) { return []; } $themeDir = $this->readDirFactory->create($themeAbsolutePath); $searchPattern = "{$namespace}_{$module}/{$this->subDir}{$filePath}"; $files = $themeDir->search($searchPattern); $result = []; $pattern = "#(?<moduleName>[^/]+)/{$this->subDir}" . $this->pathPatternHelper->translatePatternFromGlob($filePath) . "\$#i"; foreach ($files as $file) { $filename = $themeDir->getAbsolutePath($file); if (!preg_match($pattern, $filename, $matches)) { continue; } $result[] = $this->fileFactory->create($filename, $matches['moduleName']); } return $result; }
/** * @param \Magento\Backend\Block\Context $context * @param \Magento\Framework\Filesystem $filesystem * @param \Magento\Framework\Filesystem\Directory\ReadFactory $directoryRead * @param \Magento\Framework\Stdlib\DateTime\DateTime $coreDate * @param array $data */ public function __construct(\Magento\Backend\Block\Context $context, \Magento\Framework\Filesystem $filesystem, \Magento\Framework\Filesystem\Directory\ReadFactory $directoryRead, \Magento\Framework\Stdlib\DateTime\DateTime $coreDate, array $data = []) { parent::__construct($context, $data); $this->_ioRead = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::ROOT); $this->_coreDate = $coreDate; $this->_directoryRead = $directoryRead->create(""); }
/** * Find all theme-based email templates for a given template ID * * @param string $templateId * @return array[] */ public function getThemeTemplates($templateId) { $templates = []; $area = $this->getTemplateArea($templateId); $module = $this->getTemplateModule($templateId); $filename = $this->_getInfo($templateId, 'file'); foreach ($this->themePackages->getThemes() as $theme) { if ($theme->getArea() == $area) { $themeDir = $this->readDirFactory->create($theme->getPath()); $file = "{$module}/email/{$filename}"; if ($themeDir->isExist($file)) { $templates[] = ['value' => sprintf('%s/%s/%s', $templateId, $theme->getVendor(), $theme->getName()), 'label' => sprintf('%s (%s/%s)', $this->getTemplateLabel($templateId), $theme->getVendor(), $theme->getName()), 'group' => $this->getTemplateModule($templateId)]; } } } return $templates; }
/** * Create an instance of directory with write permissions * * @param string $code * @return \Magento\Framework\Filesystem\Directory\ReadInterface */ public function getDirectoryRead($code) { if (!array_key_exists($code, $this->readInstances)) { $config = $this->directoryList->getConfig($code); $this->readInstances[$code] = $this->readFactory->create($config, $this->driverFactory); } return $this->readInstances[$code]; }
/** * Collect files in components * If $withContext is true, returns array of file objects with component context * * @param string $componentType * @param string $pattern * @param bool|false $withContext * @return array */ private function collect($componentType, $pattern, $withContext) { $files = []; foreach ($this->registrar->getPaths($componentType) as $componentName => $path) { $directoryRead = $this->readFactory->create($path); $foundFiles = $directoryRead->search($pattern); foreach ($foundFiles as $foundFile) { $foundFile = $directoryRead->getAbsolutePath($foundFile); if ($withContext) { $files[] = new ComponentFile($componentType, $componentName, $foundFile); } else { $files[] = $foundFile; } } } return $files; }
/** * Retrieve files * * @param ThemeInterface $theme * @param string $filePath * @return \Magento\Framework\View\File[] */ public function getFiles(ThemeInterface $theme, $filePath) { $list = $this->fileListFactory->create('Magento\\Framework\\Css\\PreProcessor\\File\\FileList\\Collator'); $files = $this->libraryDirectory->search($filePath); $list->add($this->createFiles($this->libraryDirectory, $theme, $files)); foreach ($theme->getInheritedThemes() as $currentTheme) { $themeFullPath = $currentTheme->getFullPath(); $path = $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $themeFullPath); if (empty($path)) { continue; } $directoryRead = $this->readFactory->create($path); $foundFiles = $directoryRead->search("web/{$filePath}"); $list->replace($this->createFiles($directoryRead, $theme, $foundFiles)); } return $list->getAll(); }
/** * Return generated varnish.vcl configuration file * * @param string $vclTemplatePath * @return string * @api */ public function getVclFile($vclTemplatePath) { $moduleEtcPath = $this->reader->getModuleDir(Dir::MODULE_ETC_DIR, 'Magento_PageCache'); $configFilePath = $moduleEtcPath . '/' . $this->_scopeConfig->getValue($vclTemplatePath); $directoryRead = $this->readFactory->create($moduleEtcPath); $configFilePath = $directoryRead->getRelativePath($configFilePath); $data = $directoryRead->readFile($configFilePath); return strtr($data, $this->_getReplacements()); }
/** * Return configuration model for the theme * * @param ThemePackage $themePackage * @return \Magento\Framework\Config\Theme */ protected function _getConfigModel($themePackage) { $themeDir = $this->dirReadFactory->create($themePackage->getPath()); if ($themeDir->isExist('theme.xml')) { $configContent = $themeDir->readFile('theme.xml'); } else { $configContent = ''; } return $this->themeConfigFactory->create(['configContent' => $configContent]); }
/** * Collect files * * @param string|null $searchPattern * @return array * @throws \Exception */ public function collectFiles($searchPattern = null) { $result = []; if ($searchPattern === null) { $searchPattern = $this->searchPattern; } if ($searchPattern === null) { throw new \Exception('Search pattern cannot be empty.'); } $files = $this->collectorAggregated->getFiles($this->design->getDesignTheme(), $searchPattern); foreach ($files as $file) { $fullFileName = $file->getFileName(); $fileDir = dirname($fullFileName); $fileName = basename($fullFileName); $dirRead = $this->readFactory->create($fileDir); $result[$fullFileName] = $dirRead->readFile($fileName); } return $result; }
/** * Get content of include file (in adminhtml area) * * @param string $includePath * @return string * @throws LocalizedException */ protected function getContent($includePath) { // <include path="Magento_Payment::my_payment.xml" /> list($moduleName, $filename) = explode('::', $includePath); $path = 'adminhtml/' . $filename; $directoryRead = $this->readFactory->create($this->moduleReader->getModuleDir(Dir::MODULE_ETC_DIR, $moduleName)); if ($directoryRead->isExist($path) && $directoryRead->isFile($path)) { return $directoryRead->readFile($path); } throw new LocalizedException(__('The file "%1" does not exist', $path)); }
/** * Download sample file action * * @return \Magento\Framework\Controller\Result\Raw */ public function execute() { $fileName = $this->getRequest()->getParam('filename') . '.csv'; $moduleDir = $this->reader->getModuleDir('', self::SAMPLE_FILES_MODULE); $fileAbsolutePath = $moduleDir . '/' . $fileName; $directoryRead = $this->readFactory->create($moduleDir); $filePath = $directoryRead->getRelativePath($fileAbsolutePath); if (!$directoryRead->isFile($filePath)) { /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $this->messageManager->addError(__('There is no sample file for this entity.')); $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/import'); return $resultRedirect; } $fileSize = isset($directoryRead->stat($filePath)['size']) ? $directoryRead->stat($filePath)['size'] : null; $this->fileFactory->create($fileName, null, DirectoryList::VAR_DIR, 'application/octet-stream', $fileSize); /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */ $resultRaw = $this->resultRawFactory->create(); $resultRaw->setContents($directoryRead->readFile($filePath)); return $resultRaw; }
/** * Creates a chain for pre-processing * * @param LocalInterface $asset * @param string|bool $dir * @param string|bool $path * @return PreProcessor\Chain */ private function createChain(LocalInterface $asset, $dir, $path) { if ($path) { $origContent = $this->readFactory->create($dir)->readFile($path); $origContentType = $this->getContentType($path); } else { $origContent = ''; $origContentType = $asset->getContentType(); } $chain = $this->chainFactory->create(['asset' => $asset, 'origContent' => $origContent, 'origContentType' => $origContentType, 'origAssetPath' => $dir . '/' . $path]); return $chain; }
/** * Go through all modules and find corresponding files of active modules * * @param string $filename * @param string $subDir * @return array */ private function getFiles($filename, $subDir = '') { $result = []; foreach ($this->modulesList->getNames() as $moduleName) { $moduleEtcDir = $this->getModuleDir($subDir, $moduleName); $file = $moduleEtcDir . '/' . $filename; $directoryRead = $this->readFactory->create($moduleEtcDir); $path = $directoryRead->getRelativePath($file); if ($directoryRead->isExist($path)) { $result[] = $file; } } return $result; }
/** * Read the CSV-files in a language package * * The files are sorted alphabetically, then each of them is read, and results are recorded into key => value array * * @param string $vendor * @param string $package * @return array */ private function readPackCsv($vendor, $package) { $path = $this->componentRegistrar->getPath(ComponentRegistrar::LANGUAGE, strtolower($vendor . '_' . $package)); $result = []; if (isset($path)) { $directoryRead = $this->directoryReadFactory->create($path); $foundCsvFiles = $directoryRead->search("*.csv"); foreach ($foundCsvFiles as $foundCsvFile) { $file = $directoryRead->openFile($foundCsvFile); while (($row = $file->readCsv()) !== false) { $result[$row[0]] = $row[1]; } } } return $result; }
/** * @param \Magento\Backend\App\Action\Context $context * @param \Magento\Framework\Model\Context $contextModel * @param \Magento\Framework\Registry $coreRegistry * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory * @param \Wyomind\Core\Helper\Data $coreHelper * @param \Wyomind\SimpleGoogleShopping\Helper\Data $sgsHelper * @param \Wyomind\SimpleGoogleShopping\Model\Feeds $sgsModel * @param \Magento\Framework\Model\Context $context_ * @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory * @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory * @param \Magento\Framework\Filesystem\Directory\ReadFactory $directoryRead * @param \Wyomind\SimpleGoogleShopping\Helper\Parser $parserHelper * @param \Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository */ public function __construct(\Magento\Backend\App\Action\Context $context, \Magento\Framework\Model\Context $contextModel, \Magento\Framework\Registry $coreRegistry, \Magento\Framework\View\Result\PageFactory $resultPageFactory, \Wyomind\Core\Helper\Data $coreHelper, \Wyomind\SimpleGoogleShopping\Helper\Data $sgsHelper, \Wyomind\SimpleGoogleShopping\Model\Feeds $sgsModel, \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory, \Magento\Framework\Controller\Result\RawFactory $resultRawFactory, \Magento\Framework\Filesystem\Directory\ReadFactory $directoryRead, \Wyomind\SimpleGoogleShopping\Helper\Parser $parserHelper, \Magento\Eav\Api\AttributeRepositoryInterface $attributeRepository) { $this->coreRegistry = $coreRegistry; $this->resultPageFactory = $resultPageFactory; $this->coreHelper = $coreHelper; $this->cacheManager = $contextModel->getCacheManager(); $this->sgsHelper = $sgsHelper; $this->sgsModel = $sgsModel; $this->resultForwardFactory = $resultForwardFactory; $this->resultRedirectFactory = $context->getResultRedirectFactory(); $this->resultRawFactory = $resultRawFactory; $this->parserHelper = $parserHelper; $this->attributeRepository = $attributeRepository; $this->directoryRead = $directoryRead->create("app/code/Wyomind/SimpleGoogleShopping"); parent::__construct($context); }
/** * Internal constructor * * @return void */ protected function _construct() { parent::_construct(); $paymentCode = $this->_getCheckout()->getQuote()->getPayment()->getMethod(); if (in_array($paymentCode, $this->_hssHelper->getHssMethods())) { $this->_paymentMethodCode = $paymentCode; $templatePath = str_replace('_', '', $paymentCode); $templateFile = "{$templatePath}/iframe.phtml"; $directory = $this->readFactory->create($this->reader->getModuleDir('', 'Magento_Paypal')); $file = $this->resolver->getTemplateFileName($templateFile, ['module' => 'Magento_Paypal']); if ($file && $directory->isExist($directory->getRelativePath($file))) { $this->setTemplate($templateFile); } else { $this->setTemplate('hss/iframe.phtml'); } } }
/** * Get persistent XML config xpath * * @return \DOMXPath * @throws \Magento\Framework\Exception\LocalizedException */ protected function _getConfigDomXPath() { if ($this->_configDomXPath === null) { $dir = explode("/", $this->_configFilePath); array_pop($dir); $dir = implode("/", $dir); $directoryRead = $this->readFactory->create($dir); $filePath = $directoryRead->getRelativePath($this->_configFilePath); $isFile = $directoryRead->isFile($filePath); $isReadable = $directoryRead->isReadable($filePath); if (!$isFile || !$isReadable) { throw new \Magento\Framework\Exception\LocalizedException(__('We cannot load the configuration from file %1.', $this->_configFilePath)); } $xml = $directoryRead->readFile($filePath); /** @var \Magento\Framework\Config\Dom $configDom */ $configDom = $this->_domFactory->createDom(['xml' => $xml, 'idAttributes' => ['config/instances/blocks/reference' => 'id'], 'schemaFile' => $this->_moduleReader->getModuleDir(Dir::MODULE_ETC_DIR, 'Magento_Persistent') . '/persistent.xsd']); $this->_configDomXPath = new \DOMXPath($configDom->getDom()); } return $this->_configDomXPath; }
/** * Retrieve files * * @param ThemeInterface $theme * @param string $filePath * @return \Magento\Framework\View\File[] * @throws \Magento\Framework\Exception\LocalizedException */ public function getFiles(ThemeInterface $theme, $filePath) { $namespace = $module = '*'; $themePath = $theme->getFullPath(); if (empty($themePath)) { return []; } $themeAbsolutePath = $this->componentRegistrar->getPath(ComponentRegistrar::THEME, $themePath); if (!$themeAbsolutePath) { return []; } $themeDir = $this->readDirFactory->create($themeAbsolutePath); $files = $themeDir->search("{$namespace}_{$module}/{$this->subDir}*/*/{$filePath}"); if (empty($files)) { return []; } $themes = []; $currentTheme = $theme; while ($currentTheme = $currentTheme->getParentTheme()) { $themes[$currentTheme->getCode()] = $currentTheme; } $result = []; $pattern = "#/(?<module>[^/]+)/{$this->subDir}(?<themeVendor>[^/]+)/(?<themeName>[^/]+)/" . $this->pathPatternHelper->translatePatternFromGlob($filePath) . "\$#i"; foreach ($files as $file) { $filename = $themeDir->getAbsolutePath($file); if (!preg_match($pattern, $filename, $matches)) { continue; } $moduleFull = $matches['module']; $ancestorThemeCode = $matches['themeVendor'] . '/' . $matches['themeName']; if (!isset($themes[$ancestorThemeCode])) { throw new LocalizedException(new \Magento\Framework\Phrase("Trying to override modular view file '%1' for theme '%2', which is not ancestor of theme '%3'", [$filename, $ancestorThemeCode, $theme->getCode()])); } $result[] = $this->fileFactory->create($filename, $moduleFull, $themes[$ancestorThemeCode]); } return $result; }
/** * Get Country Params by Country Code * * @param string $countryCode * @return \Magento\Framework\DataObject * * @see $countryCode ISO 3166 Codes (Countries) A2 */ protected function getCountryParams($countryCode) { if (empty($this->_countryParams)) { $etcPath = $this->_configReader->getModuleDir(Dir::MODULE_ETC_DIR, 'Magento_Dhl'); $directoryRead = $this->readFactory->create($etcPath); $countriesXml = $directoryRead->readFile('countries.xml'); $this->_countryParams = $this->_xmlElFactory->create(['data' => $countriesXml]); } if (isset($this->_countryParams->{$countryCode})) { $countryParams = new \Magento\Framework\DataObject($this->_countryParams->{$countryCode}->asArray()); } return isset($countryParams) ? $countryParams : new \Magento\Framework\DataObject(); }
protected function readFile($fileName) { $path = $this->directory_list->getRoot(); $directoryRead = $this->readFactory->create($path); return $directoryRead->readFile($fileName); }
/** * Upload table rate file and import data from it * * @param \Magento\Framework\Object $object * @throws \Magento\Framework\Exception\LocalizedException * @return \WebShopApps\MatrixRate\Model\ResourceModel\Carrier\Matrixrate * @todo: this method should be refactored as soon as updated design will be provided * @see https://wiki.corp.x.com/display/MCOMS/Magento+Filesystem+Decisions * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function uploadAndImport(\Magento\Framework\DataObject $object) { if (empty($_FILES['groups']['tmp_name']['matrixrate']['fields']['import']['value'])) { return $this; } $csvFile = $_FILES['groups']['tmp_name']['matrixrate']['fields']['import']['value']; $website = $this->_storeManager->getWebsite($object->getScopeId()); $this->_importWebsiteId = (int) $website->getId(); $this->_importUniqueHash = []; $this->_importErrors = []; $this->_importedRows = 0; $uploadDirectory = $this->_readFactory->create(ini_get('upload_tmp_dir') ?: sys_get_temp_dir()); $path = $uploadDirectory->getRelativePath($csvFile); $stream = $uploadDirectory->openFile($path); // check and skip headers $headers = $stream->readCsv(); if ($headers === false || count($headers) < 5) { $stream->close(); throw new \Magento\Framework\Exception\LocalizedException(__('Please correct Matrix Rates File Format.')); } if ($object->getData('groups/matrixrate/fields/condition_name/inherit') == '1') { $conditionName = (string) $this->_coreConfig->getValue('carriers/matrixrate/condition_name', 'default'); } else { $conditionName = $object->getData('groups/matrixrate/fields/condition_name/value'); } $this->_importConditionName = $conditionName; $adapter = $this->getConnection(); $adapter->beginTransaction(); try { $rowNumber = 1; $importData = []; $this->_loadDirectoryCountries(); $this->_loadDirectoryRegions(); // delete old data by website and condition name $condition = ['website_id = ?' => $this->_importWebsiteId, 'condition_name = ?' => $this->_importConditionName]; $adapter->delete($this->getMainTable(), $condition); while (false !== ($csvLine = $stream->readCsv())) { $rowNumber++; if (empty($csvLine)) { continue; } $row = $this->_getImportRow($csvLine, $rowNumber); if ($row !== false) { $importData[] = $row; } if (count($importData) == 5000) { $this->_saveImportData($importData); $importData = []; } } $this->_saveImportData($importData); $stream->close(); } catch (\Magento\Framework\Exception\LocalizedException $e) { $adapter->rollback(); $stream->close(); throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage())); } catch (\Exception $e) { $adapter->rollback(); $stream->close(); $this->_logger->critical($e); throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong while importing matrix rates.')); } $adapter->commit(); if ($this->_importErrors) { $error = __('We couldn\'t import this file because of these errors: %1', implode(" \n", $this->_importErrors)); throw new \Magento\Framework\Exception\LocalizedException($error); } return $this; }
/** * @param ReadFactory $readFactory * @param \Magento\Framework\Filesystem\File\WriteFactory $fileWriteFactory */ public function __construct(ReadFactory $readFactory, \Magento\Framework\Filesystem\File\WriteFactory $fileWriteFactory) { $this->currentDirRead = $readFactory->create(getcwd()); $this->fileWriteFactory = $fileWriteFactory; }