Ejemplo n.º 1
0
 /**
  * Run 'composer remove'
  *
  * @param array $packages
  * @return void
  */
 public function remove(array $packages)
 {
     $this->composerApp->resetComposer();
     $this->composerApp->setAutoExit(false);
     $vendor = (include $this->directoryList->getPath(DirectoryList::CONFIG) . '/vendor_path.php');
     $this->composerApp->run(new ArrayInput(['command' => 'remove', 'packages' => $packages, '--working-dir' => $this->directoryList->getRoot() . '/' . $vendor . '/..']));
 }
Ejemplo n.º 2
0
 /**
  * Create \Composer\Composer
  *
  * @return \Composer\Composer
  * @throws \Exception
  */
 public function create()
 {
     if (!getenv('COMPOSER_HOME')) {
         putenv('COMPOSER_HOME=' . $this->directoryList->getPath(DirectoryList::COMPOSER_HOME));
     }
     return \Composer\Factory::create(new BufferIO(), $this->composerJsonFinder->findComposerJson());
 }
Ejemplo n.º 3
0
 /**
  * Loads the configuration file
  *
  * @param string $fileKey
  * @return array
  * @throws \Exception
  */
 public function load($fileKey = null)
 {
     $path = $this->dirList->getPath(DirectoryList::CONFIG);
     if ($fileKey) {
         $result = @(include $path . '/' . $this->configFilePool->getPath($fileKey));
     } else {
         $configFiles = $this->configFilePool->getPaths();
         $result = [];
         foreach (array_keys($configFiles) as $fileKey) {
             $configFile = $path . '/' . $this->configFilePool->getPath($fileKey);
             $fileData = @(include $configFile);
             if (!empty($fileData)) {
                 $intersection = array_intersect_key($result, $fileData);
                 if (!empty($intersection)) {
                     $displayList = '';
                     foreach (array_keys($intersection) as $key) {
                         $displayList .= $key . PHP_EOL;
                     }
                     throw new \Exception("Key collision! The following keys occur in multiple config files:" . PHP_EOL . $displayList);
                 }
                 $result = array_merge($result, $fileData);
             }
         }
     }
     return $result ?: [];
 }
Ejemplo n.º 4
0
 /**
  * Loads the configuration file
  *
  * @param string $fileKey
  * @return array
  * @throws \Exception
  */
 public function load($fileKey = null)
 {
     $path = $this->dirList->getPath(DirectoryList::CONFIG);
     $fileDriver = $this->driverPool->getDriver(DriverPool::FILE);
     $result = [];
     if ($fileKey) {
         $filePath = $path . '/' . $this->configFilePool->getPath($fileKey);
         if ($fileDriver->isExists($filePath)) {
             $result = (include $filePath);
         }
     } else {
         $configFiles = $this->configFilePool->getPaths();
         $allFilesData = [];
         $result = [];
         foreach (array_keys($configFiles) as $fileKey) {
             $configFile = $path . '/' . $this->configFilePool->getPath($fileKey);
             if ($fileDriver->isExists($configFile)) {
                 $fileData = (include $configFile);
             } else {
                 continue;
             }
             $allFilesData[$configFile] = $fileData;
             if (!empty($fileData)) {
                 $intersection = array_intersect_key($result, $fileData);
                 if (!empty($intersection)) {
                     $displayMessage = $this->findFilesWithKeys(array_keys($intersection), $allFilesData);
                     throw new \Exception("Key collision! The following keys occur in multiple config files:" . PHP_EOL . $displayMessage);
                 }
                 $result = array_merge($result, $fileData);
             }
         }
     }
     return $result ?: [];
 }
 /**
  * @param string $content
  * @return void
  */
 public function updateTranslationFileContent($content)
 {
     $translationDir = $this->directoryList->getPath(DirectoryList::STATIC_VIEW) . \DIRECTORY_SEPARATOR . $this->assetRepo->getStaticViewFileContext()->getPath();
     if (!$this->driverFile->isExists($this->getTranslationFileFullPath())) {
         $this->driverFile->createDirectory($translationDir, \Magento\Framework\Filesystem\Driver\File::WRITEABLE_DIRECTORY_MODE);
     }
     $this->driverFile->filePutContents($this->getTranslationFileFullPath(), $content);
 }
Ejemplo n.º 6
0
 /**
  * @param string $content
  * @return void
  */
 public function updateTranslationFileContent($content)
 {
     $translationDir = $this->directoryList->getPath(DirectoryList::STATIC_VIEW) . \DIRECTORY_SEPARATOR . $this->assetRepo->getStaticViewFileContext()->getPath();
     if (!$this->driverFile->isExists($this->getTranslationFileFullPath())) {
         $this->driverFile->createDirectory($translationDir);
     }
     $this->driverFile->filePutContents($this->getTranslationFileFullPath(), $content);
 }
Ejemplo n.º 7
0
 /**
  * Find absolute path to root Composer json file
  *
  * @return string
  * @throws \Exception
  */
 public function findComposerJson()
 {
     $composerJson = $this->directoryList->getPath(DirectoryList::ROOT) . '/composer.json';
     $composerJson = realpath($composerJson);
     if ($composerJson === false) {
         throw new \Exception('Composer file not found');
     }
     return $composerJson;
 }
Ejemplo n.º 8
0
 /**
  * Retrieve list of recommended non-writable directories for application
  *
  * @return array
  */
 public function getApplicationNonWritableDirectories()
 {
     if (!$this->applicationNonWritableDirectories) {
         $data = [DirectoryList::CONFIG];
         foreach ($data as $code) {
             $this->applicationNonWritableDirectories[$code] = $this->directoryList->getPath($code);
         }
     }
     return array_values($this->applicationNonWritableDirectories);
 }
Ejemplo n.º 9
0
 public function testDirectoriesCustomization()
 {
     $config = [DirectoryList::APP => [DirectoryList::PATH => 'foo', DirectoryList::URL_PATH => 'bar']];
     $object = new DirectoryList('/root/dir', $config);
     $this->assertFileExists($object->getPath(DirectoryList::SYS_TMP));
     $this->assertEquals('/root/dir/foo', $object->getPath(DirectoryList::APP));
     $this->assertEquals('bar', $object->getUrlPath(DirectoryList::APP));
     $this->setExpectedException('\\Magento\\Framework\\Filesystem\\FilesystemException', "Unknown directory type: 'unknown'");
     $object->getPath('unknown');
 }
Ejemplo n.º 10
0
 /**
  * Loads the configuration file
  *
  * @param string $configFile
  * @return array
  */
 public function load($configFile = null)
 {
     if ($configFile) {
         $file = $this->dirList->getPath(DirectoryList::CONFIG) . '/' . $configFile;
     } else {
         $file = $this->dirList->getPath(DirectoryList::CONFIG) . '/' . $this->file;
     }
     $result = @(include $file);
     return $result ?: [];
 }
Ejemplo n.º 11
0
 /**
  * Find absolute path to root Composer json file
  *
  * @return string
  * @throws \Exception
  */
 public function findComposerJson()
 {
     // composer.json is in same directory as vendor
     $vendorPath = $this->directoryList->getPath(DirectoryList::CONFIG) . '/vendor_path.php';
     $vendorDir = (require "{$vendorPath}");
     $composerJson = $this->directoryList->getPath(DirectoryList::ROOT) . "/{$vendorDir}/../composer.json";
     $composerJson = realpath($composerJson);
     if ($composerJson === false) {
         throw new \Exception('Composer file not found');
     }
     return $composerJson;
 }
Ejemplo n.º 12
0
 /**
  * @param AutoloaderInterface $autoloader
  * @param DirectoryList $dirList
  * @return void
  */
 public static function populateMappings(AutoloaderInterface $autoloader, DirectoryList $dirList)
 {
     $generationDir = $dirList->getPath(DirectoryList::GENERATION);
     $frameworkDir = $dirList->getPath(DirectoryList::LIB_INTERNAL);
     $autoloader->addPsr4('Magento\\', [$generationDir . '/Magento/'], true);
     $autoloader->addPsr0('Cm_', $frameworkDir, true);
     $autoloader->addPsr0('Credis_', $frameworkDir, true);
     /** Required for Zend functionality */
     FileResolver::addIncludePath($frameworkDir);
     /** Required for code generation to occur */
     FileResolver::addIncludePath($generationDir);
     /** Required to autoload custom classes */
     $autoloader->addPsr0('', [$generationDir]);
 }
Ejemplo n.º 13
0
 public function add($contentFile, $cssFile)
 {
     $styleContent = preg_replace('/^\\/\\*[\\s\\S]+\\*\\//', '', file_get_contents($contentFile));
     if (empty($styleContent)) {
         return;
     }
     $mediaDir = $this->directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
     file_put_contents("{$mediaDir}/{$cssFile}", $styleContent, FILE_APPEND);
     $linkText = sprintf('<link  rel="stylesheet" type="text/css"  media="all" href="{{MEDIA_URL}}%s" />', $cssFile);
     $miscScriptsNode = 'design/head/includes';
     $miscScripts = $this->scopeConfig->getValue($miscScriptsNode);
     if (!$miscScripts || strpos($miscScripts, $linkText) === false) {
         $this->configWriter->save($miscScriptsNode, $miscScripts . $linkText);
         $this->configCacheType->clean();
     }
 }
Ejemplo n.º 14
0
 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']);
     }
 }
Ejemplo n.º 15
0
 /**
  * Add Link to Head
  *
  * @return void
  */
 protected function addHeadInclude()
 {
     $styleContent = '';
     foreach ($this->moduleList->getNames() as $moduleName) {
         $fileName = substr($moduleName, strpos($moduleName, "_") + 1) . '/styles.css';
         $fileName = $this->fixtureHelper->getPath($fileName);
         if (!$fileName) {
             continue;
         }
         $style = file_get_contents($fileName);
         $styleContent .= preg_replace('/^\\/\\*[\\s\\S]+\\*\\//', '', $style);
     }
     if (empty($styleContent)) {
         return;
     }
     $mediaDir = $this->directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
     file_put_contents("{$mediaDir}/styles.css", $styleContent);
     $linkTemplate = '<link  rel="stylesheet" type="text/css"  media="all" href="%sstyles.css" />';
     $baseUrl = $this->baseUrl->getBaseUrl(['_type' => \Magento\Framework\UrlInterface::URL_TYPE_MEDIA]);
     $linkText = sprintf($linkTemplate, $baseUrl);
     $miscScriptsNode = 'design/head/includes';
     $miscScripts = $this->scopeConfig->getValue($miscScriptsNode);
     if (!$miscScripts || strpos($miscScripts, $linkText) === false) {
         $this->configWriter->save($miscScriptsNode, $miscScripts . $linkText);
         $this->configCacheType->clean();
     }
 }
Ejemplo n.º 16
0
 /**
  * Returns path to env.php file
  *
  * @return string
  * @throws \Exception
  */
 private function getEnvPath()
 {
     $deploymentConfig = $this->directoryList->getPath(DirectoryList::CONFIG);
     $configPool = new ConfigFilePool();
     $envPath = $deploymentConfig . '/' . $configPool->getPath(ConfigFilePool::APP_ENV);
     return $envPath;
 }
 /**
  * Check var/generation read and write access
  *
  * @return bool
  */
 public function check()
 {
     $initParams = $this->serviceManager->get(InitParamListener::BOOTSTRAP_PARAM);
     $filesystemDirPaths = isset($initParams[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS]) ? $initParams[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS] : [];
     $directoryList = new DirectoryList(BP, $filesystemDirPaths);
     $generationDirectoryPath = $directoryList->getPath(DirectoryList::GENERATION);
     $driverPool = new DriverPool();
     $fileWriteFactory = new WriteFactory($driverPool);
     /** @var \Magento\Framework\Filesystem\DriverInterface $driver */
     $driver = $driverPool->getDriver(DriverPool::FILE);
     $directoryWrite = new Write($fileWriteFactory, $driver, $generationDirectoryPath);
     if ($directoryWrite->isExist()) {
         if ($directoryWrite->isDirectory() || $directoryWrite->isReadable()) {
             try {
                 $probeFilePath = $generationDirectoryPath . DIRECTORY_SEPARATOR . uniqid(mt_rand()) . 'tmp';
                 $fileWriteFactory->create($probeFilePath, DriverPool::FILE, 'w');
                 $driver->deleteFile($probeFilePath);
             } catch (\Exception $e) {
                 return false;
             }
         } else {
             return false;
         }
     } else {
         try {
             $directoryWrite->create();
         } catch (\Exception $e) {
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 18
0
    /**
     * Check all sub-directories and files except for var/generation and var/di
     *
     * @param string $directory
     * @return bool
     */
    private function checkRecursiveDirectories($directory)
    {
        $directoryIterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::CHILD_FIRST
        );
        $noWritableFilesFolders = [
            $this->directoryList->getPath(DirectoryList::GENERATION) . '/',
            $this->directoryList->getPath(DirectoryList::DI) . '/',
        ];

        $directoryIterator = new Filter($directoryIterator, $noWritableFilesFolders);

        $directoryIterator = new ExcludeFilter(
            $directoryIterator,
            [
                $this->directoryList->getPath(DirectoryList::SESSION) . '/',
            ]
        );

        $foundNonWritable = false;

        try {
            foreach ($directoryIterator as $subDirectory) {
                if (!$subDirectory->isWritable() && !$subDirectory->isLink()) {
                    $this->nonWritablePathsInDirectories[$directory][] = $subDirectory;
                    $foundNonWritable = true;
                }
            }
        } catch (\UnexpectedValueException $e) {
            return false;
        }
        return !$foundNonWritable;
    }
Ejemplo n.º 19
0
 /**
  * Get Vendors Path for sample-data-media package
  *
  * @return string
  */
 protected function getVendorsMagentoMediaPath()
 {
     $vendorPathConfig = $this->directoryList->getPath(DirectoryList::CONFIG) . '/vendor_path.php';
     if (!file_exists($vendorPathConfig)) {
         return null;
     }
     $vendorPath = (include $vendorPathConfig);
     $vendorsMagentoDir = $this->directoryList->getPath(DirectoryList::ROOT) . '/' . $vendorPath . '/magento';
     if (!file_exists($vendorsMagentoDir)) {
         return null;
     }
     $vendorsMagentoMedia = $vendorsMagentoDir . '/sample-data-media';
     if (file_exists($vendorsMagentoMedia)) {
         return $vendorsMagentoMedia;
     }
     return null;
 }
 /**
  * Run Composer dependency check
  *
  * @param array $packages
  * @return array
  * @throws \Exception
  */
 public function runReadinessCheck(array $packages)
 {
     $composerJson = $this->composerJsonFinder->findComposerJson();
     $this->file->copy($composerJson, $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/composer.json');
     $workingDir = $this->directoryList->getPath(DirectoryList::VAR_DIR);
     try {
         foreach ($packages as $package) {
             if (strpos($package, 'magento/product-enterprise-edition') !== false) {
                 $this->magentoComposerApplication->runComposerCommand(['command' => 'remove', 'packages' => ['magento/product-community-edition'], '--no-update' => true], $workingDir);
             }
         }
         $this->requireUpdateDryRunCommand->run($packages, $workingDir);
         return ['success' => true];
     } catch (\RuntimeException $e) {
         $message = str_replace(PHP_EOL, '<br/>', htmlspecialchars($e->getMessage()));
         return ['success' => false, 'error' => $message];
     }
 }
Ejemplo n.º 21
0
 /**
  * Change permissions for directories by their code
  *
  * @param array $directoryCodeList
  * @param int $dirPermissions
  * @param int $filePermissions
  * @return void
  * @deprecated
  */
 protected function changePermissions($directoryCodeList, $dirPermissions, $filePermissions)
 {
     foreach ($directoryCodeList as $code) {
         $directoryPath = $this->directoryList->getPath($code);
         if ($this->driverFile->isExists($directoryPath)) {
             $this->filesystem->getDirectoryWrite($code)->changePermissionsRecursively('', $dirPermissions, $filePermissions);
         } else {
             $this->driverFile->createDirectory($directoryPath, $dirPermissions);
         }
     }
 }
Ejemplo n.º 22
0
 /**
  * Determine whether a CLI command is for compilation, and if so, clear the directory
  *
  * @throws \Magento\Framework\Exception\FileSystemException
  * @return void
  */
 public function handleCompilerEnvironment()
 {
     $compilationCommands = [DiCompileCommand::NAME];
     $cmdName = $this->input->getFirstArgument();
     $isHelpOption = $this->input->hasParameterOption('--help') || $this->input->hasParameterOption('-h');
     if (!in_array($cmdName, $compilationCommands) || $isHelpOption) {
         return;
     }
     $compileDirList = [];
     $mageInitParams = $this->serviceManager->get(InitParamListener::BOOTSTRAP_PARAM);
     $mageDirs = isset($mageInitParams[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS]) ? $mageInitParams[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS] : [];
     $directoryList = new DirectoryList(BP, $mageDirs);
     $compileDirList[] = $directoryList->getPath(DirectoryList::GENERATION);
     $compileDirList[] = $directoryList->getPath(DirectoryList::DI);
     foreach ($compileDirList as $compileDir) {
         if ($this->filesystemDriver->isExists($compileDir)) {
             $this->filesystemDriver->deleteDirectory($compileDir);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $backupsDir = $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/' . BackupRollback::DEFAULT_BACKUP_DIRECTORY;
     if ($this->file->isExists($backupsDir)) {
         $contents = $this->file->readDirectoryRecursively($backupsDir);
         $tempTable = [];
         foreach ($contents as $path) {
             $partsOfPath = explode('/', str_replace('\\', '/', $path));
             $fileName = $partsOfPath[count($partsOfPath) - 1];
             // if filename starts with '.' skip, e.g. '.git'
             if (!(strpos($fileName, '.') === 0)) {
                 $filenameWithoutExtension = explode('.', $fileName);
                 // actually first part of $filenameWithoutExtension contains only the filename without extension
                 // and filename contains the type of backup separated by '_'
                 $fileNameParts = explode('_', $filenameWithoutExtension[0]);
                 if (in_array(Factory::TYPE_MEDIA, $fileNameParts)) {
                     $tempTable[$fileName] = Factory::TYPE_MEDIA;
                 } elseif (in_array(Factory::TYPE_DB, $fileNameParts)) {
                     $tempTable[$fileName] = Factory::TYPE_DB;
                 } elseif (in_array('code', $fileNameParts)) {
                     $tempTable[$fileName] = 'code';
                 }
             }
         }
         if (empty($tempTable)) {
             $output->writeln('<info>No backup files found.</info>');
             return;
         }
         $output->writeln("<info>Showing backup files in {$backupsDir}.</info>");
         /** @var \Symfony\Component\Console\Helper\Table $table */
         $table = $this->getHelperSet()->get('table');
         $table->setHeaders(['Backup Filename', 'Backup Type']);
         asort($tempTable);
         foreach ($tempTable as $key => $value) {
             $table->addRow([$key, $value]);
         }
         $table->render($output);
     } else {
         $output->writeln('<info>No backup files found.</info>');
     }
 }
Ejemplo n.º 24
0
 /**
  * File constructor.
  *
  * @param Data                                            $helper
  * @param \Magento\Framework\App\Filesystem\DirectoryList $directoryList
  * @param \Magento\Framework\Filesystem                   $filesystem
  */
 public function __construct(\Dotdigitalgroup\Email\Helper\Data $helper, \Magento\Framework\App\Filesystem\DirectoryList $directoryList, \Magento\Framework\Filesystem $filesystem)
 {
     $this->helper = $helper;
     $this->directoryList = $directoryList;
     $this->filesystem = $filesystem;
     $var = $directoryList->getPath('var');
     $this->outputFolder = $var . DIRECTORY_SEPARATOR . 'export' . DIRECTORY_SEPARATOR . 'email';
     $this->outputArchiveFolder = $this->outputFolder . DIRECTORY_SEPARATOR . 'archive';
     $this->delimiter = ',';
     // tab character
     $this->enclosure = '"';
 }
 /**
  * Checks disk space availability
  *
  * @return JsonModel
  */
 public function checkAction()
 {
     $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY);
     $backupDir = $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/' . BackupRollback::DEFAULT_BACKUP_DIRECTORY;
     try {
         $totalSize = 0;
         if (isset($params['options']['code']) && $params['options']['code']) {
             $totalSize += $this->backupHandler->getFSDiskSpace();
         }
         if (isset($params['options']['media']) && $params['options']['media']) {
             $totalSize += $this->backupHandler->getFSDiskSpace(Factory::TYPE_MEDIA);
         }
         if (isset($params['options']['db']) && $params['options']['db']) {
             $totalSize += $this->backupHandler->getDBDiskSpace();
         }
         $this->fileSystem->validateAvailableDiscSpace($backupDir, $totalSize);
         return new JsonModel(['responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, 'size' => true]);
     } catch (\Exception $e) {
         return new JsonModel(['responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, 'error' => $e->getMessage()]);
     }
 }
Ejemplo n.º 26
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $errors = $this->checkEnvironment();
     if ($errors) {
         foreach ($errors as $line) {
             $output->writeln($line);
         }
         // we must have an exit code higher than zero to indicate something was wrong
         return \Magento\Framework\Console\Cli::RETURN_FAILURE;
     }
     $modulePaths = $this->componentRegistrar->getPaths(ComponentRegistrar::MODULE);
     $libraryPaths = $this->componentRegistrar->getPaths(ComponentRegistrar::LIBRARY);
     $generationPath = $this->directoryList->getPath(DirectoryList::GENERATION);
     $this->objectManager->get('Magento\\Framework\\App\\Cache')->clean();
     $compiledPathsList = ['application' => $modulePaths, 'library' => $libraryPaths, 'generated_helpers' => $generationPath];
     $excludedModulePaths = [];
     foreach ($modulePaths as $appCodePath) {
         $excludedModulePaths[] = '#^' . $appCodePath . '/Test#';
     }
     $excludedLibraryPaths = [];
     foreach ($libraryPaths as $libraryPath) {
         $excludedLibraryPaths[] = '#^' . $libraryPath . '/([\\w]+/)?Test#';
     }
     $this->excludedPathsList = ['application' => $excludedModulePaths, 'framework' => $excludedLibraryPaths];
     $this->configureObjectManager($output);
     $operations = $this->getOperationsConfiguration($compiledPathsList);
     try {
         $this->cleanupFilesystem([DirectoryList::CACHE, DirectoryList::DI]);
         foreach ($operations as $operationCode => $arguments) {
             $this->taskManager->addOperation($operationCode, $arguments);
         }
         /** @var ProgressBar $progressBar */
         $progressBar = $this->objectManager->create('Symfony\\Component\\Console\\Helper\\ProgressBar', ['output' => $output, 'max' => count($operations)]);
         $progressBar->setFormat('<info>%message%</info> %current%/%max% [%bar%] %percent:3s%% %elapsed% %memory:6s%');
         $output->writeln('<info>Compilation was started.</info>');
         $progressBar->start();
         $progressBar->display();
         $this->taskManager->process(function (OperationInterface $operation) use($progressBar) {
             $progressBar->setMessage($operation->getName() . '...');
             $progressBar->display();
         }, function (OperationInterface $operation) use($progressBar) {
             $progressBar->advance();
         });
         $progressBar->finish();
         $output->writeln('');
         $output->writeln('<info>Generated code and dependency injection configuration successfully.</info>');
     } catch (OperationException $e) {
         $output->writeln('<error>' . $e->getMessage() . '</error>');
         // we must have an exit code higher than zero to indicate something was wrong
         return \Magento\Framework\Console\Cli::RETURN_FAILURE;
     }
 }
    /**
     * Build Framework dependencies report
     *
     * @param string $outputPath
     * @return void
     */
    protected function buildReport($outputPath)
    {
        $root = $this->directoryList->getRoot();
        $filePath = str_replace(
            $root,
            Files::init()->getPathToSource(),
            $this->directoryList->getPath(DirectoryList::MODULES) . '/Magento'
        );
        $filesForParse = Files::init()->getFiles([$filePath], '*');
        $configFiles = Files::init()->getConfigFiles('module.xml', [], false);

        ServiceLocator::getFrameworkDependenciesReportBuilder()->build(
            [
                'parse' => [
                    'files_for_parse' => $filesForParse,
                    'config_files' => $configFiles,
                    'declared_namespaces' => Files::init()->getNamespaces(),
                ],
                'write' => ['report_filename' => $outputPath],
            ]
        );
    }
Ejemplo n.º 28
0
 protected function setUp()
 {
     $this->_shell = new \Magento\Framework\Shell(new \Magento\Framework\Shell\CommandRenderer());
     $basePath = BP;
     $basePath = str_replace('\\', '/', $basePath);
     $directoryList = new DirectoryList($basePath);
     $this->_generationDir = $directoryList->getPath(DirectoryList::GENERATION);
     $this->_compilationDir = $directoryList->getPath(DirectoryList::DI);
     $this->_command = 'php ' . $basePath . '/bin/magento setup:di:compile';
     $booleanUtils = new \Magento\Framework\Stdlib\BooleanUtils();
     $constInterpreter = new \Magento\Framework\Data\Argument\Interpreter\Constant();
     $argumentInterpreter = new \Magento\Framework\Data\Argument\Interpreter\Composite(['boolean' => new \Magento\Framework\Data\Argument\Interpreter\Boolean($booleanUtils), 'string' => new \Magento\Framework\Data\Argument\Interpreter\StringUtils($booleanUtils), 'number' => new \Magento\Framework\Data\Argument\Interpreter\Number(), 'null' => new \Magento\Framework\Data\Argument\Interpreter\NullType(), 'object' => new \Magento\Framework\Data\Argument\Interpreter\DataObject($booleanUtils), 'const' => $constInterpreter, 'init_parameter' => new \Magento\Framework\App\Arguments\ArgumentInterpreter($constInterpreter)], \Magento\Framework\ObjectManager\Config\Reader\Dom::TYPE_ATTRIBUTE);
     // Add interpreters that reference the composite
     $argumentInterpreter->addInterpreter('array', new \Magento\Framework\Data\Argument\Interpreter\ArrayType($argumentInterpreter));
     $this->_mapper = new \Magento\Framework\ObjectManager\Config\Mapper\Dom($argumentInterpreter, $booleanUtils, new \Magento\Framework\ObjectManager\Config\Mapper\ArgumentParser());
     $this->_validator = new \Magento\Framework\Code\Validator();
     $this->_validator->add(new \Magento\Framework\Code\Validator\ConstructorIntegrity());
     $this->_validator->add(new \Magento\Framework\Code\Validator\ContextAggregation());
     $this->_validator->add(new \Magento\Framework\Code\Validator\TypeDuplication());
     $this->_validator->add(new \Magento\Framework\Code\Validator\ArgumentSequence());
     $this->_validator->add(new \Magento\Framework\Code\Validator\ConstructorArgumentTypes());
     $this->pluginValidator = new \Magento\Framework\Interception\Code\InterfaceValidator();
 }
Ejemplo n.º 29
0
 /**
  * Get paths that should be excluded during iterative searches for locations for media backup only
  *
  * @return array
  */
 private function getMediaBackupIgnorePaths()
 {
     $ignorePaths = [];
     foreach (new \DirectoryIterator($this->directoryList->getRoot()) as $item) {
         if (!$item->isDot() && $this->directoryList->getPath(DirectoryList::PUB) !== $item->getPathname()) {
             $ignorePaths[] = str_replace('\\', '/', $item->getPathname());
         }
     }
     foreach (new \DirectoryIterator($this->directoryList->getPath(DirectoryList::PUB)) as $item) {
         if (!$item->isDot() && $this->directoryList->getPath(DirectoryList::MEDIA) !== $item->getPathname()) {
             $ignorePaths[] = str_replace('\\', '/', $item->getPathname());
         }
     }
     return $ignorePaths;
 }
Ejemplo n.º 30
0
 /**
  * Get Resource Code by Module Name
  *
  * @param string $moduleName
  * @return string
  */
 public function getResourceCode($moduleName)
 {
     $sqlResources = [];
     $dataResources = [];
     $modulePath = str_replace('_', '/', $moduleName);
     // Collect files by /app/code/{modulePath}/sql/*/ pattern
     $pattern = $this->directoryList->getPath(DirectoryList::MODULES) . '/' . $modulePath . '/sql/*';
     $resourceDirs = Glob::glob($pattern, Glob::GLOB_ONLYDIR);
     if (!empty($resourceDirs)) {
         foreach ($resourceDirs as $resourceDir) {
             $sqlResources[] = basename($resourceDir);
         }
     }
     // Collect files by /app/code/{modulePath}/data/*/ pattern
     $pattern = $this->directoryList->getPath(DirectoryList::MODULES) . '/' . $modulePath . '/data/*';
     $resourceDirs = Glob::glob($pattern, Glob::GLOB_ONLYDIR);
     if (!empty($resourceDirs)) {
         foreach ($resourceDirs as $resourceDir) {
             $dataResources[] = basename($resourceDir);
         }
     }
     $resources = array_unique(array_merge($sqlResources, $dataResources));
     return array_shift($resources);
 }