public function testGenerateLessFileTree() { $originalContent = 'original content'; $expectedContent = 'updated content'; $expectedRelativePath = 'view_preprocessed/less/some/file.less'; $expectedPath = '/var/view_preprocessed/less/some/file.less'; $asset = $this->getMock('\\Magento\\Framework\\View\\Asset\\File', [], [], '', false); $asset->expects($this->once())->method('getPath')->will($this->returnValue('some/file.css')); $chain = new \Magento\Framework\View\Asset\PreProcessor\Chain($asset, $originalContent, 'less'); $this->magentoImport->expects($this->once())->method('process')->with($chain); $this->import->expects($this->once())->method('process')->with($chain); $relatedAssetOne = $this->getMock('\\Magento\\Framework\\View\\Asset\\File', [], [], '', false); $relatedAssetOne->expects($this->any())->method('getPath')->will($this->returnValue('related/file_one.css')); $relatedAssetOne->expects($this->any())->method('getContent')->will($this->returnValue("content of 'related/file_one.css'")); $relatedAssetTwo = $this->getMock('\\Magento\\Framework\\View\\Asset\\File', [], [], '', false); $relatedAssetTwo->expects($this->any())->method('getPath')->will($this->returnValue('related/file_two.css')); $relatedAssetTwo->expects($this->any())->method('getContent')->will($this->returnValue("content of 'related/file_two.css'")); $assetsMap = [['related/file_one.css', $asset, $relatedAssetOne], ['related/file_two.css', $asset, $relatedAssetTwo]]; $this->assetRepo->expects($this->any())->method('createRelated')->will($this->returnValueMap($assetsMap)); $relatedFilesOne = [['related/file_one.css', $asset]]; $this->import->expects($this->at(1))->method('getRelatedFiles')->will($this->returnValue($relatedFilesOne)); $relatedFilesTwo = [['related/file_two.css', $asset]]; $this->import->expects($this->at(3))->method('getRelatedFiles')->will($this->returnValue($relatedFilesTwo)); $this->import->expects($this->at(5))->method('getRelatedFiles')->will($this->returnValue([])); $writeMap = [[$expectedRelativePath, $expectedContent], ['related/file_one.css', "content of 'related/file_one.css'"], ['related/file_two.css', "content of 'related/file_two.css'"]]; $pathsMap = [[$expectedRelativePath, $expectedPath], ['related/file_one.css', '/var/view_preprocessed/less/related/file_one.css'], ['related/file_two.css', '/var/view_preprocessed/less/related/file_two.css']]; $this->tmpDirectory->expects($this->any())->method('writeFile')->will($this->returnValueMap($writeMap)); $this->tmpDirectory->expects($this->any())->method('getAbsolutePath')->will($this->returnValueMap($pathsMap)); $actual = $this->object->generateLessFileTree($chain); $this->assertSame($expectedPath, $actual); }
/** * Clear state file */ protected function tearDown() { $this->filesystem->expects($this->any())->method('getDirectoryWrite')->willReturn($this->writeInterface); $this->writeInterface->expects($this->any())->method('openFile')->willReturnSelf($this->absolutePath); $this->state->clearState(); }
/** * Returns CSV file * * @return array * @throws LocalizedException */ public function getCsvFile() { $component = $this->filter->getComponent(); $name = md5(microtime()); $file = 'export/' . $component->getName() . $name . '.csv'; $this->filter->prepareComponent($component); $this->filter->applySelectionOnTargetProvider(); $dataProvider = $component->getContext()->getDataProvider(); $fields = $this->metadataProvider->getFields($component); $options = $this->metadataProvider->getOptions(); $this->directory->create('export'); $stream = $this->directory->openFile($file, 'w+'); $stream->lock(); $stream->writeCsv($this->metadataProvider->getHeaders($component)); $i = 1; $searchCriteria = $dataProvider->getSearchCriteria()->setCurrentPage($i)->setPageSize($this->pageSize); $totalCount = (int) $dataProvider->getSearchResult()->getTotalCount(); while ($totalCount > 0) { $items = $dataProvider->getSearchResult()->getItems(); foreach ($items as $item) { $this->metadataProvider->convertDate($item, $component->getName()); $stream->writeCsv($this->metadataProvider->getRowData($item, $fields, $options)); } $searchCriteria->setCurrentPage(++$i); $totalCount = $totalCount - $this->pageSize; } $stream->unlock(); $stream->close(); return ['type' => 'filename', 'value' => $file, 'rm' => true]; }
public function testPublish() { $this->appState->expects($this->once())->method('getMode')->will($this->returnValue(\Magento\Framework\App\State::MODE_PRODUCTION)); $this->staticDirRead->expects($this->once())->method('isExist')->with('some/file.ext')->will($this->returnValue(false)); $this->rootDirWrite->expects($this->once())->method('getRelativePath')->with('/root/some/file.ext')->will($this->returnValue('some/file.ext')); $this->rootDirWrite->expects($this->once())->method('copyFile')->with('some/file.ext', 'some/file.ext', $this->staticDirWrite)->will($this->returnValue(true)); $this->assertTrue($this->object->publish($this->getAsset())); }
/** * Write down contents to a temporary file and return its absolute path * * @param string $relativePath * @param string $contents * @return string */ public function createFile($relativePath, $contents) { $filePath = $this->config->getLessMaterializationRelativePath() . '/' . $relativePath; if (!$this->tmpDirectory->isExist($filePath)) { $this->tmpDirectory->writeFile($filePath, $contents); } return $this->tmpDirectory->getAbsolutePath($filePath); }
public function testCreateRequireJsAssetDevMode() { $this->appState->expects($this->once())->method('getMode')->will($this->returnValue(\Magento\Framework\App\State::MODE_DEVELOPER)); $this->dir->expects($this->never())->method('isExist'); $data = 'requirejs config data'; $this->config->expects($this->once())->method('getConfig')->will($this->returnValue($data)); $this->dir->expects($this->once())->method('writeFile')->with('requirejs/file.js', $data); $this->assertSame($this->asset, $this->object->createRequireJsAsset()); }
public function testPublish() { $this->staticDirRead->expects($this->once())->method('isExist')->with('some/file.ext')->will($this->returnValue(false)); $materializationStrategy = $this->getMock('Magento\\Framework\\App\\View\\Asset\\MaterializationStrategy\\StrategyInterface', [], [], '', false); $this->rootDirWrite->expects($this->once())->method('getRelativePath')->with('/root/some/file.ext')->will($this->returnValue('some/file.ext')); $this->materializationStrategyFactory->expects($this->once())->method('create')->with($this->getAsset())->will($this->returnValue($materializationStrategy)); $materializationStrategy->expects($this->once())->method('publishFile')->with($this->rootDirWrite, $this->staticDirWrite, 'some/file.ext', 'some/file.ext')->will($this->returnValue(true)); $this->assertTrue($this->object->publish($this->getAsset())); }
public function testMergeMtimeUnchanged() { $this->targetDir->expects($this->once())->method('isExist')->with('merged/result.txt.dat')->will($this->returnValue(true)); $this->targetDir->expects($this->once())->method('readFile')->with('merged/result.txt.dat')->will($this->returnValue('11')); $assets = $this->getAssetsToMerge(); $this->mergerMock->expects($this->never())->method('merge'); $this->targetDir->expects($this->never())->method('writeFile'); $this->checksum->merge($assets, $this->resultAsset); }
/** * Minify template file * * @param string $file * @return void */ public function minify($file) { $file = $this->rootDirectory->getRelativePath($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', preg_replace('#//[^\\n\\r]*(\\<\\?php)[^\\n\\r]*(\\s\\?\\>)[^\\n\\r]*#', '', $this->rootDirectory->readFile($file)))))))); if (!$this->htmlDirectory->isExist()) { $this->htmlDirectory->create(); } $this->htmlDirectory->writeFile($file, rtrim($content)); }
protected function setUp() { $this->stream = $this->getMockForAbstractClass('\\Magento\\Framework\\Filesystem\\File\\WriteInterface'); $this->dir = $this->getMockForAbstractClass('\\Magento\\Framework\\Filesystem\\Directory\\WriteInterface'); $this->dir->expects($this->any())->method('openFile')->with(self::DEBUG_FILE, 'a')->will($this->returnValue($this->stream)); $filesystem = $this->getMock('Magento\\Framework\\Filesystem', [], [], '', false); $filesystem->expects($this->any())->method('getDirectoryWrite')->will($this->returnValue($this->dir)); $this->object = new File($filesystem, self::DEBUG_FILE); }
/** * {@inheritdoc} */ public function log($str) { $str = '## ' . date('Y-m-d H:i:s') . "\r\n" . $str; $stream = $this->dir->openFile($this->debugFile, 'a'); $stream->lock(); $stream->write($str); $stream->unlock(); $stream->close(); }
/** * Flash ISM_BaseRunner cache * @param \Magento\Framework\Event\Observer $observer * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute(\Magento\Framework\Event\Observer $observer) { $dir = $this->_mediaDirectory->getAbsolutePath(Upload::UPLOAD_POST_IMAGE_DIR . 'cache/'); if (is_dir($dir)) { $dir = $this->_mediaDirectory->getDriver()->readDirectory($dir); foreach ($dir as $file) { $this->_mediaDirectory->delete(Upload::UPLOAD_POST_IMAGE_DIR . 'cache/' . basename($file)); } } }
/** * Get backup-specific data from model for each row * * @param string $filename * @return array */ protected function _generateRow($filename) { $row = parent::_generateRow($filename); foreach ($this->_backup->load($row['basename'], $this->_varDirectory->getAbsolutePath($this->_path))->getData() as $key => $value) { $row[$key] = $value; } $row['size'] = $this->_varDirectory->stat($this->_varDirectory->getRelativePath($filename))['size']; $row['id'] = $row['time'] . '_' . $row['type']; return $row; }
public function testMergeCss() { $this->resultAsset->expects($this->exactly(3))->method('getPath')->will($this->returnValue('foo/result')); $this->resultAsset->expects($this->any())->method('getContentType')->will($this->returnValue('css')); $assets = $this->prepareAssetsToMerge(['one', 'two']); $this->cssUrlResolver->expects($this->exactly(2))->method('relocateRelativeUrls')->will($this->onConsecutiveCalls('1', '2')); $this->cssUrlResolver->expects($this->once())->method('aggregateImportDirectives')->with('12')->will($this->returnValue('1020')); $this->writeDir->expects($this->once())->method('writeFile')->with('foo/result', '1020'); $this->object->merge($assets, $this->resultAsset); }
/** * Get file handler by process ID * * @param string $processId * @return File */ public function getFile($processId) { if (!isset($this->_fileHandlers[$processId])) { $this->_varDirectory->create('locks'); $fileName = 'locks/index_process_' . $processId . '.lock'; $stream = $this->_varDirectory->openFile($fileName, 'w+'); $stream->write(date('r')); $this->_fileHandlers[$processId] = $this->_fileFactory->create(array('streamHandler' => $stream)); } return $this->_fileHandlers[$processId]; }
public function testCreateRequireJsAssetDevMode() { $this->config->expects($this->once())->method('getConfigFileRelativePath')->will($this->returnValue('requirejs/file.js')); $this->fileSystem->expects($this->once())->method('getDirectoryWrite')->with(DirectoryList::STATIC_VIEW)->will($this->returnValue($this->dir)); $this->assetRepo->expects($this->once())->method('createArbitrary')->with('requirejs/file.js', '')->will($this->returnValue($this->asset)); $this->appState->expects($this->once())->method('getMode')->will($this->returnValue(\Magento\Framework\App\State::MODE_DEVELOPER)); $this->dir->expects($this->never())->method('isExist'); $data = 'requirejs config data'; $this->config->expects($this->once())->method('getConfig')->will($this->returnValue($data)); $this->dir->expects($this->once())->method('writeFile')->with('requirejs/file.js', $data); $this->assertSame($this->asset, $this->object->createRequireJsConfigAsset()); }
/** * Check whether generation process has already locked * * @return bool * @throws FileSystemException */ private function isProcessLocked() { if ($this->tmpDirectory->isExist($this->lockFilePath)) { $lockTime = (int) $this->tmpDirectory->readFile($this->lockFilePath); if (time() - $lockTime >= self::MAX_LOCK_TIME) { $this->tmpDirectory->delete($this->lockFilePath); return false; } return true; } return false; }
public function testBeforeSave() { $value = 'filename.jpg'; $tmpMediaPath = 'tmp/image/' . $value; $this->imageBackend->setScope('store'); $this->imageBackend->setScopeId(1); $this->imageBackend->setValue([['url' => 'http://magento2.com/pub/media/tmp/image/' . $value, 'file' => $value, 'size' => 234234]]); $this->imageConfig->expects($this->exactly(2))->method('getTmpMediaPath')->with($value)->willReturn($tmpMediaPath); $this->mediaDirectory->expects($this->once())->method('copyFile')->with($tmpMediaPath, 'image/store/1/' . $value)->willReturn(true); $this->mediaDirectory->expects($this->once())->method('delete')->with($tmpMediaPath); $this->imageBackend->beforeSave(); $this->assertEquals('store/1/filename.jpg', $this->imageBackend->getValue()); }
/** * Save config in cache file * * @return void */ public function save() { /** @var Write $file */ $file = $this->rootDirectory->openFile($this->rootDirectory->getRelativePath($this->cacheFilePath), 'w'); try { $file->lock(); $file->write(json_encode($this->config)); $file->unlock(); $file->close(); } catch (FileSystemException $e) { $file->close(); } }
public function testBeforeSave() { $value = 'filename.jpg'; $tmpMediaPath = 'tmp/design/file/' . $value; $this->fileBackend->setScope('store'); $this->fileBackend->setScopeId(1); $this->fileBackend->setValue([['url' => 'http://magento2.com/pub/media/tmp/image/' . $value, 'file' => $value, 'size' => 234234]]); $this->fileBackend->setFieldConfig(['upload_dir' => ['value' => 'value', 'config' => 'system/filesystem/media']]); $this->mediaDirectory->expects($this->once())->method('copyFile')->with($tmpMediaPath, '/' . $value)->willReturn(true); $this->mediaDirectory->expects($this->once())->method('delete')->with($tmpMediaPath); $this->fileBackend->beforeSave(); $this->assertEquals('filename.jpg', $this->fileBackend->getValue()); }
/** * Get backup-specific data from model for each row * * @param string $filename * @return array */ protected function _generateRow($filename) { $row = parent::_generateRow($filename); foreach ($this->_backup->load($row['basename'], $this->_varDirectory->getAbsolutePath($this->_path))->getData() as $key => $value) { $row[$key] = $value; } $row['size'] = $this->_varDirectory->stat($this->_varDirectory->getRelativePath($filename))['size']; if (isset($row['display_name']) && $row['display_name'] == '') { $row['display_name'] = 'WebSetupWizard'; } $row['id'] = $row['time'] . '_' . $row['type'] . (isset($row['display_name']) ? $row['display_name'] : ''); return $row; }
/** * Perform necessary preprocessing and materialization when the specified asset is requested * * Returns an array of two elements: * - directory where the file is supposed to be found * - relative path to the file * * returns false if source file was not found * * @param LocalInterface $asset * @return array|bool */ private function preProcess(LocalInterface $asset) { $sourceFile = $this->findSourceFile($asset); $dir = $this->rootDir->getAbsolutePath(); $path = ''; if ($sourceFile) { $path = basename($sourceFile); $dir = dirname($sourceFile); } $chain = $this->createChain($asset, $dir, $path); $this->preProcessorPool->process($chain); $chain->assertValid(); if ($chain->isChanged()) { $dir = $this->varDir->getAbsolutePath(); $path = DirectoryList::TMP_MATERIALIZATION_DIR . '/source/' . $chain->getTargetAssetPath(); $this->varDir->writeFile($path, $chain->getContent()); } if (empty($path)) { $result = false; } else { $result = [$dir, $path]; } return $result; }
/** * Checking file for save and save it to tmp dir * * @param string $fileId * * @return string[] * * @throws \Magento\Framework\Exception\LocalizedException */ public function saveFileToTmpDir($fileId) { $baseTmpPath = $this->getBaseTmpPath(); $uploader = $this->uploaderFactory->create(['fileId' => $fileId]); $uploader->setAllowedExtensions($this->getAllowedExtensions()); $uploader->setAllowRenameFiles(true); $result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath)); if (!$result) { throw new \Magento\Framework\Exception\LocalizedException(__('File can not be saved to the destination folder.')); } /** * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS */ $result['tmp_name'] = str_replace('\\', '/', $result['tmp_name']); $result['path'] = str_replace('\\', '/', $result['path']); $result['url'] = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . $this->getFilePath($baseTmpPath, $result['file']); $result['name'] = $result['file']; if (isset($result['file'])) { try { $relativePath = rtrim($baseTmpPath, '/') . '/' . ltrim($result['file'], '/'); $this->coreFileStorageDatabase->saveFile($relativePath); } catch (\Exception $e) { $this->logger->critical($e); throw new \Magento\Framework\Exception\LocalizedException(__('Something went wrong while saving the file(s).')); } } return $result; }
/** * Perform necessary preprocessing and materialization when the specified asset is requested * * Returns an array of two elements: * - directory code where the file is supposed to be found * - relative path to the file * * Automatically caches the obtained successful results or returns false if source file was not found * * @param LocalInterface $asset * @return array|bool */ private function preProcess(LocalInterface $asset) { $sourceFile = $this->findSourceFile($asset); $dirCode = DirectoryList::ROOT; $path = $this->rootDir->getRelativePath($sourceFile); $cacheId = $path . ':' . $asset->getPath(); $cached = $this->cache->load($cacheId); if ($cached) { return unserialize($cached); } $origContent = $path ? $this->rootDir->readFile($path) : ''; $origContentType = $this->getContentType($path) ?: $asset->getContentType(); $chain = $this->chainFactory->create( [ 'asset' => $asset, 'origContent' => $origContent, 'origContentType' => $origContentType, 'origAssetPath' => $path ] ); $this->preProcessorPool->process($chain); $chain->assertValid(); if ($chain->isChanged()) { $dirCode = DirectoryList::VAR_DIR; $path = DirectoryList::TMP_MATERIALIZATION_DIR . '/source/' . $chain->getTargetAssetPath(); $this->varDir->writeFile($path, $chain->getContent()); } $result = [$dirCode, $path]; $this->cache->save(serialize($result), $cacheId); return $result; }
/** * Returns XML file * * @return array * @throws LocalizedException */ public function getXmlFile() { $component = $this->filter->getComponent(); $name = md5(microtime()); $file = 'export/' . $component->getName() . $name . '.xml'; $this->filter->prepareComponent($component); $this->filter->applySelectionOnTargetProvider(); $component->getContext()->getDataProvider()->setLimit(0, 0); /** @var SearchResultInterface $searchResult */ $searchResult = $component->getContext()->getDataProvider()->getSearchResult(); /** @var DocumentInterface[] $searchResultItems */ $searchResultItems = $searchResult->getItems(); $this->prepareItems($component->getName(), $searchResultItems); /** @var SearchResultIterator $searchResultIterator */ $searchResultIterator = $this->iteratorFactory->create(['items' => $searchResultItems]); /** @var Excel $excel */ $excel = $this->excelFactory->create(['iterator' => $searchResultIterator, 'rowCallback' => [$this, 'getRowData']]); $this->directory->create('export'); $stream = $this->directory->openFile($file, 'w+'); $stream->lock(); $excel->setDataHeader($this->metadataProvider->getHeaders($component)); $excel->write($stream, $component->getName() . '.xml'); $stream->unlock(); $stream->close(); return ['type' => 'filename', 'value' => $file, 'rm' => true]; }
/** * Perform necessary preprocessing and materialization when the specified asset is requested * * Returns an array of two elements: * - directory code where the file is supposed to be found * - relative path to the file * * Automatically caches the obtained successful results or returns false if source file was not found * * @param LocalInterface $asset * @return array|bool */ private function preProcess(LocalInterface $asset) { $sourceFile = $this->findSourceFile($asset); if ($sourceFile !== false) { $path = $this->rootDir->getRelativePath($sourceFile); } else { // No original file, the resulting file may be generated by a pre-processor $path = false; } $cacheId = $path . ':' . $asset->getPath(); $cached = $this->cache->load($cacheId); if ($cached) { return unserialize($cached); } $chain = $this->createChain($asset, $path); $this->preProcessorPool->process($chain); $chain->assertValid(); $dirCode = DirectoryList::ROOT; if ($chain->isChanged()) { $dirCode = DirectoryList::VAR_DIR; $path = DirectoryList::TMP_MATERIALIZATION_DIR . '/source/' . $chain->getTargetAssetPath(); $this->varDir->writeFile($path, $chain->getContent()); } $result = [$dirCode, $path]; $this->cache->save(serialize($result), $cacheId); return $result; }
/** * Perform necessary preprocessing and materialization when the specified asset is requested * * Returns an array of two elements: * - directory code where the file is supposed to be found * - relative path to the file * * Automatically caches the obtained successful results or returns false if source file was not found * * @param LocalInterface $asset * @return array|bool */ private function preProcess(LocalInterface $asset) { $sourceFile = $this->findSourceFile($asset); if (!$sourceFile) { return false; } $dirCode = \Magento\Framework\App\Filesystem::ROOT_DIR; $path = $this->rootDir->getRelativePath($sourceFile); $cacheId = $path . ':' . $asset->getPath(); $cached = $this->cache->load($cacheId); if ($cached) { return unserialize($cached); } $chain = new \Magento\Framework\View\Asset\PreProcessor\Chain($asset, $this->rootDir->readFile($path), $this->getContentType($path)); $preProcessors = $this->preProcessorPool->getPreProcessors($chain->getOrigContentType(), $chain->getTargetContentType()); foreach ($preProcessors as $processor) { $processor->process($chain); } $chain->assertValid(); if ($chain->isChanged()) { $dirCode = \Magento\Framework\App\Filesystem::VAR_DIR; $path = self::TMP_MATERIALIZATION_DIR . '/source/' . $asset->getPath(); $this->varDir->writeFile($path, $chain->getContent()); } $result = array($dirCode, $path); $this->cache->save(serialize($result), $cacheId); return $result; }
/** * Move files from TMP folder into destination folder * * @param string $tmpPath * @param string $destPath * @return bool */ protected function _moveFile($tmpPath, $destPath) { if ($this->_directory->isFile($tmpPath)) { return $this->_directory->copyFile($tmpPath, $destPath); } else { return false; } }
/** * Save new image and remove old image. * * @param $file string new file * @param $old string old file * * @return string file name * @throws LocalizedException */ public function saveImage($file, $old) { $uploadDir = $this->_mediaDirectory->getAbsolutePath(self::UPLOAD_POST_IMAGE_DIR); try { $uploader = $this->_uploaderFactory->create(['fileId' => $file]); $uploader->setAllowedExtensions(self::TYPES_ALLOWED); $uploader->setAllowRenameFiles(true); $uploader->addValidateCallback('size', $this, 'validateMaxSize'); $result = $uploader->save($uploadDir); } catch (\Exception $e) { throw new LocalizedException(__($e->getMessage())); } if ($old) { $this->removeImage($old); } return $result['file']; }
/** * Check and remove outdated certificate file by website * * @return void */ protected function _removeOutdatedCertFile() { $pattern = sprintf('cert_%s*', $this->getWebsiteId()); $entries = $this->varDirectory->search($pattern, self::BASEPATH_PAYPAL_CERT); foreach ($entries as $entry) { $this->varDirectory->delete($entry); } }