/** * Retrieve files * * @param ThemeInterface $theme * @param string $filePath * @return array|\Magento\Framework\View\File[] */ public function getFiles(ThemeInterface $theme, $filePath) { $result = []; $namespace = $module = '*'; $sharedFiles = $this->modulesDirectory->search("{$namespace}/{$module}/view/base/{$this->subDir}{$filePath}"); $filePathPtn = strtr(preg_quote($filePath), ['\\*' => '[^/]+']); $pattern = "#(?<namespace>[^/]+)/(?<module>[^/]+)/view/base/{$this->subDir}" . $filePathPtn . "\$#i"; foreach ($sharedFiles as $file) { $filename = $this->modulesDirectory->getAbsolutePath($file); if (!preg_match($pattern, $filename, $matches)) { continue; } $moduleFull = "{$matches['namespace']}_{$matches['module']}"; $result[] = $this->fileFactory->create($filename, $moduleFull, null, true); } $area = $theme->getData('area'); $themeFiles = $this->modulesDirectory->search("{$namespace}/{$module}/view/{$area}/{$this->subDir}{$filePath}"); $pattern = "#(?<namespace>[^/]+)/(?<module>[^/]+)/view/{$area}/{$this->subDir}" . $filePathPtn . "\$#i"; foreach ($themeFiles as $file) { $filename = $this->modulesDirectory->getAbsolutePath($file); if (!preg_match($pattern, $filename, $matches)) { continue; } $moduleFull = "{$matches['namespace']}_{$matches['module']}"; $result[] = $this->fileFactory->create($filename, $moduleFull); } return $result; }
/** * 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) { $content = $this->rootDirRead->readFile($this->rootDirRead->getRelativePath($file[0])); $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; }
/** * @test * @return void */ public function testLoadData() { $fileContent = 'content file'; $media = ['preview_image' => 'preview.jpg']; $themeTitle = 'Theme title'; $themeConfigFile = 'theme.xml'; $themeConfig = $this->getMockBuilder('Magento\\Framework\\Config\\Theme')->disableOriginalConstructor()->getMock(); $theme = $this->getMockBuilder('Magento\\Theme\\Model\\Theme')->disableOriginalConstructor()->getMock(); $parentTheme = ['parentThemeCode']; $parentThemePath = 'frontend/parent/theme'; $themePackage = $this->getMock('\\Magento\\Framework\\View\\Design\\Theme\\ThemePackage', [], [], '', false); $themePackage->expects($this->any())->method('getArea')->will($this->returnValue('frontend')); $themePackage->expects($this->any())->method('getVendor')->will($this->returnValue('theme')); $themePackage->expects($this->any())->method('getName')->will($this->returnValue('code')); $this->themePackageList->expects($this->once())->method('getThemes')->will($this->returnValue([$themePackage])); $this->directory->expects($this->once())->method('isExist')->with($themeConfigFile)->willReturn(true); $this->directory->expects($this->once())->method('readFile')->with($themeConfigFile)->willReturn($fileContent); $this->themeConfigFactory->expects($this->once())->method('create')->with(['configContent' => $fileContent])->willReturn($themeConfig); $this->entityFactory->expects($this->any())->method('create')->with('Magento\\Theme\\Model\\Theme')->willReturn($theme); $themeConfig->expects($this->once())->method('getMedia')->willReturn($media); $themeConfig->expects($this->once())->method('getParentTheme')->willReturn($parentTheme); $themeConfig->expects($this->once())->method('getThemeTitle')->willReturn($themeTitle); $theme->expects($this->once())->method('addData')->with(['parent_id' => null, 'type' => ThemeInterface::TYPE_PHYSICAL, 'area' => 'frontend', 'theme_path' => 'theme/code', 'code' => 'theme/code', 'theme_title' => $themeTitle, 'preview_image' => $media['preview_image'], 'parent_theme_path' => 'theme/parentThemeCode'])->willReturnSelf(); $theme->expects($this->once())->method('getData')->with('parent_theme_path')->willReturn($parentThemePath); $theme->expects($this->once())->method('getArea')->willReturn('frontend'); $this->assertInstanceOf(get_class($this->model), $this->model->loadData()); }
/** * Current * * @return string */ public function current() { if (!isset($this->cached[$this->key()])) { $this->cached[$this->key()] = $this->directoryRead->readFile($this->key()); } return $this->cached[$this->key()]; }
public function testGetConfig() { $this->baseDir->expects($this->any())->method('getRelativePath')->will($this->returnCallback(function ($path) { return 'relative/' . $path; })); $this->baseDir->expects($this->any())->method('readFile')->will($this->returnCallback(function ($file) { return $file . ' content'; })); $fileOne = $this->getMock('\\Magento\\Framework\\View\\File', [], [], '', false); $fileOne->expects($this->once())->method('getFilename')->will($this->returnValue('file_one.js')); $fileOne->expects($this->once())->method('getModule')->will($this->returnValue('Module_One')); $fileTwo = $this->getMock('\\Magento\\Framework\\View\\File', [], [], '', false); $fileTwo->expects($this->once())->method('getFilename')->will($this->returnValue('file_two.js')); $theme = $this->getMockForAbstractClass('\\Magento\\Framework\\View\\Design\\ThemeInterface'); $this->design->expects($this->once())->method('getDesignTheme')->will($this->returnValue($theme)); $this->fileSource->expects($this->once())->method('getFiles')->with($theme, Config::CONFIG_FILE_NAME)->will($this->returnValue([$fileOne, $fileTwo])); $expected = <<<expected (function(require){ require.config({"baseUrl":""}); (function() { relative/file_one.js content require.config(config); })(); (function() { relative/file_two.js content require.config(config); })(); })(require); expected; $actual = $this->object->getConfig(); $this->assertStringMatchesFormat($expected, $actual); }
/** * Returns contents of License file. * * @return string */ public function getContents() { if (!$this->dir->isFile(self::LICENSE_FILENAME)) { return false; } return $this->dir->readFile(self::LICENSE_FILENAME); }
/** * @param string $area * @param bool $forceReload * @param array $cachedData * @dataProvider dataProviderForTestLoadData * @SuppressWarnings(PHPMD.NPathComplexity) */ public function testLoadData($area, $forceReload, $cachedData) { $this->expectsSetConfig('themeId'); $this->cache->expects($this->exactly($forceReload ? 0 : 1))->method('load')->will($this->returnValue(serialize($cachedData))); if (!$forceReload && $cachedData !== false) { $this->translate->loadData($area, $forceReload); $this->assertEquals($cachedData, $this->translate->getData()); return; } $this->directory->expects($this->any())->method('isExist')->will($this->returnValue(true)); // _loadModuleTranslation() $this->moduleList->expects($this->once())->method('getNames')->will($this->returnValue(['name'])); $moduleData = ['module original' => 'module translated', 'module theme' => 'module-theme original translated', 'module pack' => 'module-pack original translated', 'module db' => 'module-db original translated']; $this->modulesReader->expects($this->any())->method('getModuleDir')->will($this->returnValue('/app/module')); $themeData = ['theme original' => 'theme translated', 'module theme' => 'theme translated overwrite', 'module pack' => 'theme-pack translated overwrite', 'module db' => 'theme-db translated overwrite']; $this->csvParser->expects($this->any())->method('getDataPairs')->will($this->returnValueMap([['/app/module/en_US.csv', 0, 1, $moduleData], ['/app/module/en_GB.csv', 0, 1, $moduleData], ['/theme.csv', 0, 1, $themeData]])); // _loadThemeTranslation() $this->viewFileSystem->expects($this->any())->method('getLocaleFileName')->will($this->returnValue('/theme.csv')); // _loadPackTranslation $packData = ['pack original' => 'pack translated', 'module pack' => 'pack translated overwrite', 'module db' => 'pack-db translated overwrite']; $this->packDictionary->expects($this->once())->method('getDictionary')->will($this->returnValue($packData)); // _loadDbTranslation() $dbData = ['db original' => 'db translated', 'module db' => 'db translated overwrite']; $this->resource->expects($this->any())->method('getTranslationArray')->will($this->returnValue($dbData)); $this->cache->expects($this->exactly(1))->method('save'); $this->translate->loadData($area, $forceReload); $expected = ['module original' => 'module translated', 'module theme' => 'theme translated overwrite', 'module pack' => 'pack translated overwrite', 'module db' => 'db translated overwrite', 'theme original' => 'theme translated', 'pack original' => 'pack translated', 'db original' => 'db translated']; $this->assertEquals($expected, $this->translate->getData()); }
/** * Retrieve files * * @param ThemeInterface $theme * @param string $filePath * @return array|\Magento\Framework\View\File[] * @throws \Magento\Framework\Exception */ public function getFiles(ThemeInterface $theme, $filePath) { $namespace = $module = '*'; $themePath = $theme->getFullPath(); $searchPattern = "{$themePath}/{$namespace}_{$module}/{$this->subDir}*/*/{$filePath}"; $files = $this->themesDirectory->search($searchPattern); if (empty($files)) { return []; } $themes = []; $currentTheme = $theme; while ($currentTheme = $currentTheme->getParentTheme()) { $themes[$currentTheme->getCode()] = $currentTheme; } $result = []; $pattern = "#/(?<module>[^/]+)/{$this->subDir}(?<themeVendor>[^/]+)/(?<themeName>[^/]+)/" . strtr(preg_quote($filePath), ['\\*' => '[^/]+']) . "\$#i"; foreach ($files as $file) { $filename = $this->themesDirectory->getAbsolutePath($file); if (!preg_match($pattern, $filename, $matches)) { continue; } $moduleFull = $matches['module']; $ancestorThemeCode = $matches['themeVendor'] . '/' . $matches['themeName']; if (!isset($themes[$ancestorThemeCode])) { throw new Exception(sprintf("Trying to override modular view file '%s' for theme '%s', which is not ancestor of theme '%s'", $filename, $ancestorThemeCode, $theme->getCode())); } $result[] = $this->fileFactory->create($filename, $moduleFull, $themes[$ancestorThemeCode]); } return $result; }
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->materializationStrategyFactory->expects($this->once())->method('create')->with($this->getAsset())->will($this->returnValue($materializationStrategy)); $materializationStrategy->expects($this->once())->method('publishFile')->with($this->sourceDirWrite, $this->staticDirWrite, 'file.ext', 'some/file.ext')->will($this->returnValue(true)); $this->assertTrue($this->object->publish($this->getAsset())); }
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())); }
/** * @param ReadInterface $reader * @param ThemeInterface $theme * @param array $files * @return array */ protected function createFiles(ReadInterface $reader, ThemeInterface $theme, $files) { $result = []; foreach ($files as $file) { $filename = $reader->getAbsolutePath($file); $result[] = $this->fileFactory->create($filename, false, $theme); } return $result; }
/** * {@inheritdoc} * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function get($filename, $scope) { $configPaths = $this->configDirectory->search('{*' . $filename . ',*/*' . $filename . '}'); $configAbsolutePaths = []; foreach ($configPaths as $configPath) { $configAbsolutePaths[] = $this->configDirectory->getAbsolutePath($configPath); } return $this->iteratorFactory->create($configAbsolutePaths); }
/** * 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)); }
/** * Returns contents of License file. * * @return string|boolean */ public function getContents() { if ($this->dir->isFile(self::LICENSE_FILENAME)) { return $this->dir->readFile(self::LICENSE_FILENAME); } elseif ($this->dir->isFile(self::DEFAULT_LICENSE_FILENAME)) { return $this->dir->readFile(self::DEFAULT_LICENSE_FILENAME); } else { return false; } }
public function testBasePackageInfo() { $this->readerMock->expects($this->once())->method('isExist')->willReturn(true); $this->readerMock->expects($this->once())->method('isReadable')->willReturn(true); $jsonData = json_encode([BasePackageInfo::COMPOSER_KEY_EXTRA => [BasePackageInfo::COMPOSER_KEY_MAP => [[__FILE__, __FILE__], [__DIR__, __DIR__]]]]); $this->readerMock->expects($this->once())->method('readFile')->willReturn($jsonData); $expectedList = [__FILE__, __DIR__]; $actualList = $this->basePackageInfo->getPaths(); $this->assertEquals($expectedList, $actualList); }
/** * Retrieve files * * @param ThemeInterface $theme * @param string $filePath * @return array|\Magento\Framework\View\File[] */ public function getFiles(ThemeInterface $theme, $filePath) { $themePath = $theme->getFullPath(); $files = $this->themesDirectory->search("{$themePath}/{$this->subDir}{$filePath}"); $result = []; foreach ($files as $file) { $filename = $this->themesDirectory->getAbsolutePath($file); $result[] = $this->fileFactory->create($filename, null, $theme); } return $result; }
protected function prepareAttemptToMinifyMock($fileExists, $rootDirExpectations = true, $originalExists = true) { $this->asset->expects($this->atLeastOnce())->method('getPath')->will($this->returnValue('test/admin.js')); $this->asset->expects($this->atLeastOnce())->method('getSourceFile')->will($this->returnValue('/foo/bar/test/admin.js')); if ($rootDirExpectations) { $this->rootDir->expects($this->once())->method('getRelativePath')->with('/foo/bar/test/admin.min.js')->will($this->returnValue('test/admin.min.js')); $this->rootDir->expects($this->once())->method('isExist')->with('test/admin.min.js')->will($this->returnValue(false)); } $this->baseUrl->expects($this->once())->method('getBaseUrl')->will($this->returnValue('http://example.com/')); $this->staticViewDir->expects($this->exactly(2 - intval($originalExists)))->method('isExist')->will($this->returnValue($fileExists)); }
/** * Create mocks of assets to merge, as well as a few related necessary mocks * * @return array */ private function getAssetsToMerge() { $one = $this->getMock('\\Magento\\Framework\\View\\Asset\\File', [], [], '', false); $one->expects($this->once())->method('getSourceFile')->will($this->returnValue('/dir/file/one.txt')); $two = $this->getMock('\\Magento\\Framework\\View\\Asset\\File', [], [], '', false); $two->expects($this->once())->method('getSourceFile')->will($this->returnValue('/dir/file/two.txt')); $this->sourceDir->expects($this->exactly(2))->method('getRelativePath')->will($this->onConsecutiveCalls('file/one.txt', 'file/two.txt')); $this->sourceDir->expects($this->exactly(2))->method('stat')->will($this->returnValue(['mtime' => '1'])); $this->resultAsset->expects($this->once())->method('getPath')->will($this->returnValue('merged/result.txt')); return [$one, $two]; }
/** * Fetches and outputs file to user browser * $info is array with following indexes: * - 'path' - full file path * - 'type' - mime type of file * - 'size' - size of file * - 'title' - user-friendly name of file (usually - original name as uploaded in Magento) * * @param \Magento\Framework\App\ResponseInterface $response * @param string $filePath * @param array $info * @return bool */ public function downloadFileOption($response, $filePath, $info) { try { $response->setHttpResponseCode(200)->setHeader('Pragma', 'public', true)->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)->setHeader('Content-type', $info['type'], true)->setHeader('Content-Length', $info['size'])->setHeader('Content-Disposition', 'inline' . '; filename=' . $info['title'])->clearBody(); $response->sendHeaders(); echo $this->directory->readFile($this->directory->getRelativePath($filePath)); } catch (\Exception $e) { return false; } return true; }
/** * Retrieve full path to a directory of certain type within a module * * @param string $moduleName Fully-qualified module name * @param string $type Type of module's directory to retrieve * @return string * @throws \InvalidArgumentException */ public function getDir($moduleName, $type = '') { $path = $this->_string->upperCaseWords($moduleName, '_', '/'); if ($type) { if (!in_array($type, array('etc', 'sql', 'data', 'i18n', 'view', 'Controller'))) { throw new \InvalidArgumentException("Directory type '{$type}' is not recognized."); } $path .= '/' . $type; } $result = $this->_modulesDirectory->getAbsolutePath($path); return $result; }
/** * Retrieve full path to a directory of certain type within a module * * @param string $moduleName Fully-qualified module name * @param string $type Type of module's directory to retrieve * @return string * @throws \InvalidArgumentException */ public function getDir($moduleName, $type = '') { if (null === ($path = $this->moduleRegistry->getModulePath($moduleName))) { $relativePath = $this->_string->upperCaseWords($moduleName, '_', '/'); $path = $this->_modulesDirectory->getAbsolutePath($relativePath); } if ($type) { if (!in_array($type, [self::MODULE_ETC_DIR, self::MODULE_I18N_DIR, self::MODULE_VIEW_DIR, self::MODULE_CONTROLLER_DIR])) { throw new \InvalidArgumentException("Directory type '{$type}' is not recognized."); } $path .= '/' . $type; } return $path; }
public function testCopyQuoteToOrder() { $optionMock = $this->getMockBuilder('Magento\\Catalog\\Model\\Product\\Configuration\\Item\\Option\\OptionInterface')->disableOriginalConstructor()->setMethods(['getValue'])->getMockForAbstractClass(); $quotePath = '/quote/path/path/uploaded.file'; $orderPath = '/order/path/path/uploaded.file'; $optionMock->expects($this->any())->method('getValue')->will($this->returnValue(['quote_path' => $quotePath, 'order_path' => $orderPath])); $this->rootDirectory->expects($this->any())->method('isFile')->with($this->equalTo($quotePath))->will($this->returnValue(true)); $this->rootDirectory->expects($this->any())->method('isReadable')->with($this->equalTo($quotePath))->will($this->returnValue(true)); $this->rootDirectory->expects($this->any())->method('getAbsolutePath')->will($this->returnValue('/file.path')); $this->coreFileStorageDatabase->expects($this->any())->method('copyFile')->will($this->returnValue('true')); $fileObject = $this->getFileObject(); $fileObject->setData('configuration_item_option', $optionMock); $this->assertInstanceOf('Magento\\Catalog\\Model\\Product\\Option\\Type\\File', $fileObject->copyQuoteToOrder()); }
protected function setUp() { $this->tmpDirectory = $this->getMockForAbstractClass('\\Magento\\Framework\\Filesystem\\Directory\\WriteInterface'); $this->rootDirectory = $this->getMockForAbstractClass('\\Magento\\Framework\\Filesystem\\Directory\\ReadInterface'); $this->rootDirectory->expects($this->any())->method('getRelativePath')->will($this->returnArgument(0)); $this->rootDirectory->expects($this->any())->method('readFile')->will($this->returnCallback(function ($file) { return "content of '{$file}'"; })); $filesystem = $this->getMock('\\Magento\\Framework\\App\\Filesystem', array(), array(), '', false); $filesystem->expects($this->once())->method('getDirectoryWrite')->with(\Magento\Framework\App\Filesystem::VAR_DIR)->will($this->returnValue($this->tmpDirectory)); $this->assetRepo = $this->getMock('\\Magento\\Framework\\View\\Asset\\Repository', array(), array(), '', false); $this->magentoImport = $this->getMock('\\Magento\\Framework\\Less\\PreProcessor\\Instruction\\MagentoImport', array(), array(), '', false); $this->import = $this->getMock('\\Magento\\Framework\\Less\\PreProcessor\\Instruction\\Import', array(), array(), '', false); $this->object = new \Magento\Framework\Less\FileGenerator($filesystem, $this->assetRepo, $this->magentoImport, $this->import); }
/** * @return void */ public function testGetData() { $themePath = 'blank'; $areaCode = 'adminhtml'; $files = [['path1'], ['path2']]; $relativePathMap = [['path1' => 'relativePath1'], ['path2' => 'relativePath2']]; $contentsMap = [['relativePath1' => 'content1$.mage.__("hello1")content1'], ['relativePath2' => 'content2$.mage.__("hello2")content2']]; $patterns = ['~\\$\\.mage\\.__\\([\'|\\"](.+?)[\'|\\"]\\)~']; $this->appStateMock->expects($this->once())->method('getAreaCode')->willReturn($areaCode); $this->filesUtilityMock->expects($this->once())->method('getJsFiles')->with($areaCode, $themePath)->willReturn($files); $this->rootDirectoryMock->expects($this->any())->method('getRelativePath')->willReturnMap($relativePathMap); $this->rootDirectoryMock->expects($this->any())->method('readFile')->willReturnMap($contentsMap); $this->configMock->expects($this->any())->method('getPatterns')->willReturn($patterns); $this->assertEquals([], $this->model->getData($themePath)); }
/** * Get translation data * * @param string $themePath * @return string[] * @throws \Exception * @throws \Magento\Framework\Exception */ public function getData($themePath) { $dictionary = []; $files = $this->filesUtility->getJsFiles($this->appState->getAreaCode(), $themePath); foreach ($files as $filePath) { $content = $this->rootDirectory->readFile($this->rootDirectory->getRelativePath($filePath[0])); foreach ($this->getPhrases($content) as $phrase) { $translatedPhrase = (string) __($phrase); if ($phrase != $translatedPhrase) { $dictionary[$phrase] = $translatedPhrase; } } } return $dictionary; }
/** * Initialize testable object */ protected function setUp() { $this->htmlDirectoryMock = $this->getMockBuilder(Filesystem\Directory\WriteInterface::class)->getMockForAbstractClass(); $this->appDirectoryMock = $this->getMockBuilder(ReadInterface::class)->getMockForAbstractClass(); $this->rootDirectoryMock = $this->getMockBuilder(ReadInterface::class)->getMockForAbstractClass(); $this->filesystemMock = $this->getMockBuilder(Filesystem::class)->disableOriginalConstructor()->getMock(); $this->readFactoryMock = $this->getMockBuilder(Filesystem\Directory\ReadFactory::class)->disableOriginalConstructor()->getMock(); $this->filesystemMock->expects($this->once())->method('getDirectoryWrite')->with(DirectoryList::TEMPLATE_MINIFICATION_DIR)->willReturn($this->htmlDirectoryMock); $this->filesystemMock->expects($this->any())->method('getDirectoryRead')->with(DirectoryList::ROOT, DriverPool::FILE)->willReturn($this->rootDirectoryMock); $this->rootDirectoryMock->expects($this->any())->method('getRelativePath')->willReturnCallback(function ($value) { return ltrim($value, '/'); }); $this->readFactoryMock->expects($this->any())->method('create')->willReturn($this->appDirectoryMock); $this->object = (new ObjectManager($this))->getObject(Minifier::class, ['filesystem' => $this->filesystemMock, 'readFactory' => $this->readFactoryMock]); }
/** * {@inheritdoc} */ public function get($filename, $scope) { switch ($scope) { case 'global': $iterator = $this->_moduleReader->getConfigurationFiles($filename); break; case 'design': $iterator = $this->iteratorFactory->create($this->themesDirectory, $this->themesDirectory->search('/*/*/etc/' . $filename)); break; default: $iterator = $this->iteratorFactory->create($this->themesDirectory, array()); break; } return $iterator; }
/** * Load widget XML config and merge with theme widget config * * @return array|null * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function getWidgetConfigAsArray() { if ($this->_widgetConfigXml === null) { $this->_widgetConfigXml = $this->_widgetModel->getWidgetByClassType($this->getType()); if ($this->_widgetConfigXml) { $configFile = $this->_viewFileSystem->getFilename('widget.xml', ['area' => $this->getArea(), 'theme' => $this->getThemeId(), 'module' => $this->_namespaceResolver->determineOmittedNamespace(preg_replace('/^(.+?)\\/.+$/', '\\1', $this->getType()), true)]); $isReadable = $configFile && $this->_directory->isReadable($this->_directory->getRelativePath($configFile)); if ($isReadable) { $config = $this->_reader->readFile($configFile); $widgetName = isset($this->_widgetConfigXml['name']) ? $this->_widgetConfigXml['name'] : null; $themeWidgetConfig = null; if ($widgetName !== null) { foreach ($config as $widget) { if (isset($widget['name']) && $widgetName === $widget['name']) { $themeWidgetConfig = $widget; break; } } } if ($themeWidgetConfig) { $this->_widgetConfigXml = array_replace_recursive($this->_widgetConfigXml, $themeWidgetConfig); } } } } return $this->_widgetConfigXml; }
public function testGetFilesMultiple() { $dirPath = '/Magento_Customer/css/'; $themePath = '/opt/magento2/app/design/frontend/Magento/blank'; $searchPath = 'css/*.test'; $this->themeMock->expects($this->any())->method('getFullPath')->will($this->returnValue($themePath)); $this->themesDirectoryMock->expects($this->any())->method('getAbsolutePath')->will($this->returnValueMap([['fileA.test', $dirPath . 'fileA.test'], ['fileB.tst', $dirPath . 'fileB.tst'], ['fileC.test', $dirPath . 'fileC.test']])); $fileMock = $this->getMockBuilder('Magento\\Framework\\View\\File')->disableOriginalConstructor()->getMock(); // Verifies correct files are searched for $this->themesDirectoryMock->expects($this->once())->method('search')->with($themePath . '/' . $searchPath)->will($this->returnValue(['fileA.test', 'fileC.test'])); // Verifies Magento_Customer was correctly produced from directory path $this->fileFactoryMock->expects($this->any())->method('create')->with($this->isType('string'), null, $this->equalTo($this->themeMock))->will($this->returnValue($fileMock)); $theme = new Theme($this->filesystemMock, $this->fileFactoryMock); // Only two files should be in array, which were returned from search $this->assertEquals([$fileMock, $fileMock], $theme->getFiles($this->themeMock, 'css/*.test')); }
/** * 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; }