diff --git a/classes/Parameters/FileStorage.php b/classes/Parameters/FileStorage.php index b67ec9dd69..e27bf62a07 100644 --- a/classes/Parameters/FileStorage.php +++ b/classes/Parameters/FileStorage.php @@ -47,10 +47,10 @@ class FileStorage */ private $filesystem; - public function __construct(string $path) + public function __construct(Filesystem $filesystem, string $path) { + $this->filesystem = $filesystem; $this->configPath = $path; - $this->filesystem = new Filesystem(); } /** @@ -65,7 +65,7 @@ public function load(string $fileName = '') $configFilePath = $this->configPath . $fileName; $config = []; - if (file_exists($configFilePath)) { + if ($this->filesystem->exists($configFilePath)) { $config = @unserialize(base64_decode(Tools14::file_get_contents($configFilePath))); } diff --git a/classes/PrestashopConfiguration.php b/classes/PrestashopConfiguration.php index d3e87fcf4a..c48e3b0645 100644 --- a/classes/PrestashopConfiguration.php +++ b/classes/PrestashopConfiguration.php @@ -28,9 +28,14 @@ namespace PrestaShop\Module\AutoUpgrade; use Exception; +use Symfony\Component\Filesystem\Filesystem; class PrestashopConfiguration { + /** + * @var Filesystem + */ + private $filesystem; // Variables used for cache /** * @var string @@ -43,8 +48,9 @@ class PrestashopConfiguration */ private $psRootDir; - public function __construct(string $psRootDir) + public function __construct(Filesystem $filesystem, string $psRootDir) { + $this->filesystem = $filesystem; $this->psRootDir = $psRootDir; } @@ -60,7 +66,7 @@ public function getModuleVersion(): ?string // TODO: to be moved as property class in order to make tests possible $path = _PS_ROOT_DIR_ . '/modules/autoupgrade/config.xml'; - if (file_exists($path) + if ($this->filesystem->exists($path) && $xml_module_version = simplexml_load_file($path) ) { $this->moduleVersion = (string) $xml_module_version->version; @@ -84,7 +90,7 @@ public function getPrestaShopVersion(): string $this->psRootDir . '/src/Core/Version.php', ]; foreach ($files as $file) { - if (!file_exists($file)) { + if (!$this->filesystem->exists($file)) { continue; } $version = $this->findPrestaShopVersionInFile(file_get_contents($file)); diff --git a/classes/Services/ComposerService.php b/classes/Services/ComposerService.php index 7264223810..f5432f9157 100644 --- a/classes/Services/ComposerService.php +++ b/classes/Services/ComposerService.php @@ -27,10 +27,22 @@ namespace PrestaShop\Module\AutoUpgrade\Services; +use Symfony\Component\Filesystem\Filesystem; + class ComposerService { const COMPOSER_PACKAGE_TYPE = 'prestashop-module'; + /** + * @var Filesystem + */ + private $filesystem; + + public function __construct(Filesystem $filesystem) + { + $this->filesystem = $filesystem; + } + /** * Returns packages defined as PrestaShop modules in composer.lock * @@ -38,7 +50,7 @@ class ComposerService */ public function getModulesInComposerLock(string $composerFile): array { - if (!file_exists($composerFile)) { + if (!$this->filesystem->exists($composerFile)) { return []; } // Native modules are the one integrated in PrestaShop release via composer @@ -52,7 +64,8 @@ public function getModulesInComposerLock(string $composerFile): array $modules = array_filter($content['packages'], function (array $package) { return self::COMPOSER_PACKAGE_TYPE === $package['type'] && !empty($package['name']); }); - $modules = array_map(function (array $package) { + + return array_map(function (array $package) { $vendorName = explode('/', $package['name']); return [ @@ -60,7 +73,5 @@ public function getModulesInComposerLock(string $composerFile): array 'version' => ltrim($package['version'], 'v'), ]; }, $modules); - - return $modules; } } diff --git a/classes/Services/PrestashopVersionService.php b/classes/Services/PrestashopVersionService.php index cb55407b55..99af0bcb2a 100644 --- a/classes/Services/PrestashopVersionService.php +++ b/classes/Services/PrestashopVersionService.php @@ -7,6 +7,7 @@ use RuntimeException; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Exception\IOException; +use Symfony\Component\Filesystem\Filesystem; class PrestashopVersionService { @@ -15,9 +16,15 @@ class PrestashopVersionService */ private $zipAction; - public function __construct(ZipAction $zipAction) + /** + * @var Filesystem + */ + private $filesystem; + + public function __construct(ZipAction $zipAction, Filesystem $filesystem) { $this->zipAction = $zipAction; + $this->filesystem = $filesystem; } /** @@ -29,7 +36,7 @@ public function extractPrestashopVersionFromZip(string $zipFile): string $internalZipFileName = 'prestashop.zip'; $versionFile = 'install/install_version.php'; - if (!file_exists($zipFile)) { + if (!$this->filesystem->exists($zipFile)) { throw new FileNotFoundException("Unable to find $zipFile file"); } $zip = $this->zipAction->open($zipFile); @@ -42,7 +49,7 @@ public function extractPrestashopVersionFromZip(string $zipFile): string $fileContent = $this->zipAction->extractFileFromArchive($internalZip, $versionFile); $internalZip->close(); - @unlink($tempInternalZipPath); + $this->filesystem->remove($tempInternalZipPath); return $this->extractVersionFromContent($fileContent); } @@ -66,10 +73,8 @@ public function extractPrestashopVersionFromXml(string $xmlPath): string */ private function createTemporaryFile(string $content): string { - $tempFilePath = tempnam(sys_get_temp_dir(), 'internal_zip_'); - if (file_put_contents($tempFilePath, $content) === false) { - throw new IOException('Unable to create temporary file'); - } + $tempFilePath = $this->filesystem->tempnam(sys_get_temp_dir(), 'internal_zip_'); + $this->filesystem->appendToFile($tempFilePath, $content); return $tempFilePath; } diff --git a/classes/Task/Backup/BackupDatabase.php b/classes/Task/Backup/BackupDatabase.php index 0208f3759d..66611d9ffb 100644 --- a/classes/Task/Backup/BackupDatabase.php +++ b/classes/Task/Backup/BackupDatabase.php @@ -118,8 +118,8 @@ public function run(): int !(isset($schema[0]['Table'], $schema[0]['Create Table']) || isset($schema[0]['View'], $schema[0]['Create View']))) { fclose($fp); - if (file_exists($backupfile)) { - unlink($backupfile); + if ($this->container->getFileSystem()->exists($backupfile)) { + $this->container->getFileSystem()->remove($backupfile); } $this->logger->error($this->translator->trans('An error occurred while backing up. Unable to obtain the schema of %s', [$table])); $this->logger->info($this->translator->trans('Error during database backup.')); @@ -279,7 +279,7 @@ protected function warmUp(): int } if (!is_dir($this->container->getProperty(UpgradeContainer::BACKUP_PATH) . DIRECTORY_SEPARATOR . $state->getBackupName())) { - mkdir($this->container->getProperty(UpgradeContainer::BACKUP_PATH) . DIRECTORY_SEPARATOR . $state->getBackupName()); + $this->container->getFileSystem()->mkdir($this->container->getProperty(UpgradeContainer::BACKUP_PATH) . DIRECTORY_SEPARATOR . $state->getBackupName()); } $state->setDbStep(0); $listOfTables = $this->filterTablesToSync( @@ -345,7 +345,7 @@ private function getTablesToIgnore(): array private function openPartialBackupFile(string $backupfile) { // Figure out what compression is available and open the file - if (file_exists($backupfile)) { + if ($this->container->getFileSystem()->exists($backupfile)) { throw (new UpgradeException($this->translator->trans('Backup file %s already exists. Operation aborted.', [$backupfile])))->setSeverity(UpgradeException::SEVERITY_ERROR); } diff --git a/classes/Task/Backup/BackupFiles.php b/classes/Task/Backup/BackupFiles.php index befbbb977b..2548a89286 100644 --- a/classes/Task/Backup/BackupFiles.php +++ b/classes/Task/Backup/BackupFiles.php @@ -71,8 +71,8 @@ public function run(): int } // delete old backup, create new - if (file_exists($this->container->getProperty(UpgradeContainer::BACKUP_PATH) . DIRECTORY_SEPARATOR . $backupFilesFilename)) { - unlink($this->container->getProperty(UpgradeContainer::BACKUP_PATH) . DIRECTORY_SEPARATOR . $backupFilesFilename); + if ($this->container->getFileSystem()->exists($this->container->getProperty(UpgradeContainer::BACKUP_PATH) . DIRECTORY_SEPARATOR . $backupFilesFilename)) { + $this->container->getFileSystem()->remove($this->container->getProperty(UpgradeContainer::BACKUP_PATH) . DIRECTORY_SEPARATOR . $backupFilesFilename); } $this->logger->debug($this->translator->trans('Backup files initialized in %s', [$backupFilesFilename])); diff --git a/classes/Task/Restore/RestoreDatabase.php b/classes/Task/Restore/RestoreDatabase.php index fb76ea2dc2..3883bec1af 100644 --- a/classes/Task/Restore/RestoreDatabase.php +++ b/classes/Task/Restore/RestoreDatabase.php @@ -64,9 +64,10 @@ public function run(): int _DB_PREFIX_ . 'statssearch', ]; $startTime = time(); + $queriesToRestoreListPath = $this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::QUERIES_TO_RESTORE_LIST; // deal with running backup rest if exist - if (file_exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::QUERIES_TO_RESTORE_LIST)) { + if ($this->container->getFileSystem()->exists($queriesToRestoreListPath)) { $backlog = Backlog::fromContents($this->container->getFileStorage()->load(UpgradeFileNames::QUERIES_TO_RESTORE_LIST)); } @@ -170,8 +171,8 @@ public function run(): int do { // @phpstan-ignore booleanNot.alwaysFalse (Need a refacto of this whole task) if (!$backlog->getRemainingTotal()) { - if (file_exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::QUERIES_TO_RESTORE_LIST)) { - unlink($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::QUERIES_TO_RESTORE_LIST); + if ($this->container->getFileSystem()->exists($queriesToRestoreListPath)) { + $this->container->getFileSystem()->remove($queriesToRestoreListPath); } $restoreDbFilenamesCount = count($state->getRestoreDbFilenames()); @@ -207,7 +208,7 @@ public function run(): int if (!$this->container->getDb()->execute($query, false)) { $this->logger->error($this->translator->trans('Error during database restoration: ') . ' ' . $query . ' - ' . $this->container->getDb()->getMsgError()); $this->setErrorFlag(); - unlink($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::QUERIES_TO_RESTORE_LIST); + $this->container->getFileSystem()->remove($queriesToRestoreListPath); return ExitCode::FAIL; } @@ -220,8 +221,8 @@ public function run(): int if ($queries_left > 0) { $this->container->getFileStorage()->save($backlog->dump(), UpgradeFileNames::QUERIES_TO_RESTORE_LIST); - } elseif (file_exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::QUERIES_TO_RESTORE_LIST)) { - unlink($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::QUERIES_TO_RESTORE_LIST); + } elseif ($this->container->getFileSystem()->exists($queriesToRestoreListPath)) { + $this->container->getFileSystem()->remove($queriesToRestoreListPath); } $this->stepDone = false; @@ -251,7 +252,7 @@ public function init(): void $this->container->initPrestaShopAutoloader(); // Loads the parameters.php file on PrestaShop 1.7, needed for accessing the database - if (file_exists($this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/config/bootstrap.php')) { + if ($this->container->getFileSystem()->exists($this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/config/bootstrap.php')) { require_once $this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . '/config/bootstrap.php'; } } diff --git a/classes/Task/Restore/RestoreFiles.php b/classes/Task/Restore/RestoreFiles.php index b0446597d1..6200624118 100644 --- a/classes/Task/Restore/RestoreFiles.php +++ b/classes/Task/Restore/RestoreFiles.php @@ -55,8 +55,8 @@ public function run(): int // loop $this->next = TaskName::TASK_RESTORE_FILES; - if (!file_exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_FROM_ARCHIVE_LIST) - || !file_exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_TO_REMOVE_LIST)) { + if (!$this->container->getFileSystem()->exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_FROM_ARCHIVE_LIST) + || !$this->container->getFileSystem()->exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_TO_REMOVE_LIST)) { // cleanup current PS tree $fromArchive = $this->container->getZipAction()->listContent($this->container->getProperty(UpgradeContainer::BACKUP_PATH) . DIRECTORY_SEPARATOR . $state->getRestoreFilesFilename()); foreach ($fromArchive as $k => $v) { @@ -119,7 +119,7 @@ public function run(): int if (!empty($toRemoveOnly)) { foreach ($toRemoveOnly as $fileToRemove) { - @unlink($this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . $fileToRemove); + $this->container->getFileSystem()->remove($this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . $fileToRemove); } } diff --git a/classes/Task/Restore/RestoreInitialization.php b/classes/Task/Restore/RestoreInitialization.php index d59de648bd..28c21b71b1 100644 --- a/classes/Task/Restore/RestoreInitialization.php +++ b/classes/Task/Restore/RestoreInitialization.php @@ -104,11 +104,11 @@ public function run(): int $this->next = TaskName::TASK_RESTORE_FILES; $this->logger->info($this->translator->trans('Restoring files ...')); // remove tmp files related to restoreFiles - if (file_exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_FROM_ARCHIVE_LIST)) { - unlink($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_FROM_ARCHIVE_LIST); + if ($this->container->getFileSystem()->exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_FROM_ARCHIVE_LIST)) { + $this->container->getFileSystem()->remove($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_FROM_ARCHIVE_LIST); } - if (file_exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_TO_REMOVE_LIST)) { - unlink($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_TO_REMOVE_LIST); + if ($this->container->getFileSystem()->exists($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_TO_REMOVE_LIST)) { + $this->container->getFileSystem()->remove($this->container->getProperty(UpgradeContainer::WORKSPACE_PATH) . DIRECTORY_SEPARATOR . UpgradeFileNames::FILES_TO_REMOVE_LIST); } $this->container->getAnalytics()->track('Restore Launched', Analytics::WITH_RESTORE_PROPERTIES); diff --git a/classes/Task/Update/Download.php b/classes/Task/Update/Download.php index e977922d1c..254c556ebf 100644 --- a/classes/Task/Update/Download.php +++ b/classes/Task/Update/Download.php @@ -33,7 +33,6 @@ use PrestaShop\Module\AutoUpgrade\Task\TaskName; use PrestaShop\Module\AutoUpgrade\Task\TaskType; use PrestaShop\Module\AutoUpgrade\UpgradeContainer; -use PrestaShop\Module\AutoUpgrade\UpgradeTools\FilesystemAdapter; /** * Download PrestaShop archive according to the chosen channel. @@ -62,12 +61,20 @@ public function run(): int $this->logger->debug($this->translator->trans('Downloading from %s', [$upgrader->getOnlineDestinationRelease()->getZipDownloadUrl()])); $this->logger->debug($this->translator->trans('File will be saved in %s', [$this->container->getFilePath()])); - if (file_exists($this->container->getProperty(UpgradeContainer::DOWNLOAD_PATH))) { - FilesystemAdapter::deleteDirectory($this->container->getProperty(UpgradeContainer::DOWNLOAD_PATH), false); + + $downloadPath = $this->container->getProperty(UpgradeContainer::DOWNLOAD_PATH); + + if ($this->container->getFileSystem()->exists($downloadPath)) { + foreach (scandir($downloadPath) as $item) { + if ($item !== '.' && $item !== '..') { + $path = $downloadPath . DIRECTORY_SEPARATOR . $item; + $this->container->getFileSystem()->remove($path); + } + } $this->logger->debug($this->translator->trans('Download directory has been emptied')); } $report = ''; - $relative_download_path = str_replace(_PS_ROOT_DIR_, '', $this->container->getProperty(UpgradeContainer::DOWNLOAD_PATH)); + $relative_download_path = str_replace(_PS_ROOT_DIR_, '', $downloadPath); if (\ConfigurationTest::test_dir($relative_download_path, false, $report)) { $res = $upgrader->downloadLast( $this->container->getProperty(UpgradeContainer::DOWNLOAD_PATH), diff --git a/classes/Task/Update/Unzip.php b/classes/Task/Update/Unzip.php index 7784484dd8..edfa9cc3a0 100644 --- a/classes/Task/Update/Unzip.php +++ b/classes/Task/Update/Unzip.php @@ -34,8 +34,6 @@ use PrestaShop\Module\AutoUpgrade\Task\TaskName; use PrestaShop\Module\AutoUpgrade\Task\TaskType; use PrestaShop\Module\AutoUpgrade\UpgradeContainer; -use PrestaShop\Module\AutoUpgrade\UpgradeTools\FilesystemAdapter; -use Symfony\Component\Filesystem\Filesystem; /** * extract chosen version into $this->upgradeClass->latestPath directory. @@ -56,8 +54,14 @@ public function run(): int $this->container->getCompletionCalculator()->getBasePercentageOfTask(self::class) ); - if (file_exists($destExtract)) { - FilesystemAdapter::deleteDirectory($destExtract, false); + if ($this->container->getFileSystem()->exists($destExtract)) { + foreach (scandir($destExtract) as $item) { + if ($item !== '.' && $item !== '..') { + $path = $destExtract . DIRECTORY_SEPARATOR . $item; + $this->container->getFileSystem()->remove($path); + } + } + $this->logger->debug($this->translator->trans('"/latest" directory has been emptied')); } $relative_extract_path = str_replace(_PS_ROOT_DIR_, '', $destExtract); @@ -89,9 +93,9 @@ public function run(): int // From PrestaShop 1.7, we zip all the files in another package // which must be unzipped too $newZip = $destExtract . DIRECTORY_SEPARATOR . 'prestashop.zip'; - if (file_exists($newZip)) { - @unlink($destExtract . DIRECTORY_SEPARATOR . '/index.php'); - @unlink($destExtract . DIRECTORY_SEPARATOR . '/Install_PrestaShop.html'); + if ($this->container->getFileSystem()->exists($newZip)) { + $this->container->getFileSystem()->remove($destExtract . DIRECTORY_SEPARATOR . '/index.php'); + $this->container->getFileSystem()->remove($destExtract . DIRECTORY_SEPARATOR . '/Install_PrestaShop.html'); $subRes = $this->container->getZipAction()->extract($newZip, $destExtract); if (!$subRes) { @@ -107,7 +111,6 @@ public function run(): int return ExitCode::FAIL; } } else { - $filesystem = new Filesystem(); $zipSubfolder = $destExtract . '/prestashop/'; if (!is_dir($zipSubfolder)) { $this->next = TaskName::TASK_ERROR; @@ -121,7 +124,7 @@ public function run(): int if ($file[0] === '.') { continue; } - $filesystem->rename($zipSubfolder . $file, $destExtract . '/' . $file); + $this->container->getFileSystem()->rename($zipSubfolder . $file, $destExtract . '/' . $file); } } @@ -130,7 +133,7 @@ public function run(): int $this->container->getAnalytics()->track('Backup Launched', Analytics::WITH_BACKUP_PROPERTIES); - @unlink($newZip); + $this->container->getFileSystem()->remove($newZip); return ExitCode::SUCCESS; } diff --git a/classes/Task/Update/UpdateComplete.php b/classes/Task/Update/UpdateComplete.php index 90af0c8efe..62f9d6c323 100644 --- a/classes/Task/Update/UpdateComplete.php +++ b/classes/Task/Update/UpdateComplete.php @@ -34,7 +34,7 @@ use PrestaShop\Module\AutoUpgrade\Task\TaskName; use PrestaShop\Module\AutoUpgrade\Task\TaskType; use PrestaShop\Module\AutoUpgrade\UpgradeContainer; -use PrestaShop\Module\AutoUpgrade\UpgradeTools\FilesystemAdapter; +use Symfony\Component\Filesystem\Exception\IOException; /** * Ends the upgrade process and displays the success message. @@ -62,16 +62,20 @@ public function run(): int $this->next = TaskName::TASK_COMPLETE; - if ($this->container->getUpdateConfiguration()->isChannelOnline() && file_exists($this->container->getFilePath()) && unlink($this->container->getFilePath())) { - $this->logger->debug($this->translator->trans('%s removed', [$this->container->getFilePath()])); - } elseif (is_file($this->container->getFilePath())) { - $this->logger->debug($this->translator->trans('Please remove %s by FTP', [$this->container->getFilePath()])); + $filesystem = $this->container->getFileSystem(); + $filePath = $this->container->getFilePath(); + $latestPath = $this->container->getProperty(UpgradeContainer::LATEST_PATH); + + if ($filesystem->exists($filePath)) { + if ($this->container->getUpdateConfiguration()->isChannelOnline()) { + $this->removeFile($filePath); + } else { + $this->logger->debug($this->translator->trans('Please remove %s by FTP', [$filePath])); + } } - if (file_exists($this->container->getProperty(UpgradeContainer::LATEST_PATH)) && FilesystemAdapter::deleteDirectory($this->container->getProperty(UpgradeContainer::LATEST_PATH))) { - $this->logger->debug($this->translator->trans('%s removed', [$this->container->getProperty(UpgradeContainer::LATEST_PATH)])); - } elseif (is_dir($this->container->getProperty(UpgradeContainer::LATEST_PATH))) { - $this->logger->debug($this->translator->trans('Please remove %s by FTP', [$this->container->getProperty(UpgradeContainer::LATEST_PATH)])); + if ($filesystem->exists($latestPath)) { + $this->removeFile($latestPath); } // removing temporary files @@ -80,4 +84,14 @@ public function run(): int return ExitCode::SUCCESS; } + + private function removeFile(string $filePath): void + { + try { + $this->container->getFileSystem()->remove($filePath); + $this->logger->debug($this->translator->trans('%s removed', [$filePath])); + } catch (IOException $e) { + $this->logger->debug($this->translator->trans('Please remove %s by FTP', [$filePath])); + } + } } diff --git a/classes/Task/Update/UpdateFiles.php b/classes/Task/Update/UpdateFiles.php index 6a5eb7cbf9..e2025cd160 100644 --- a/classes/Task/Update/UpdateFiles.php +++ b/classes/Task/Update/UpdateFiles.php @@ -35,7 +35,7 @@ use PrestaShop\Module\AutoUpgrade\Task\TaskName; use PrestaShop\Module\AutoUpgrade\Task\TaskType; use PrestaShop\Module\AutoUpgrade\UpgradeContainer; -use PrestaShop\Module\AutoUpgrade\UpgradeTools\FilesystemAdapter; +use Symfony\Component\Filesystem\Exception\IOException; class UpdateFiles extends AbstractTask { @@ -126,18 +126,19 @@ public function upgradeThisFile($orig): bool } if (is_dir($orig)) { // if $dest is not a directory (that can happen), just remove that file - if (!is_dir($dest) && file_exists($dest)) { - unlink($dest); + if (!is_dir($dest) && $this->container->getFileSystem()->exists($dest)) { + $this->container->getFileSystem()->remove($dest); $this->logger->debug($this->translator->trans('File %1$s has been deleted.', [$file])); } - if (!file_exists($dest)) { - if (mkdir($dest)) { + if (!$this->container->getFileSystem()->exists($dest)) { + try { + $this->container->getFileSystem()->mkdir($dest); $this->logger->debug($this->translator->trans('Directory %1$s created.', [$file])); return true; - } else { + } catch (IOException $e) { $this->next = TaskName::TASK_ERROR; - $this->logger->error($this->translator->trans('Error while creating directory %s.', [$dest])); + $this->logger->error($this->translator->trans('Error while creating directory %s: %s.', [$dest, $e->getMessage()])); return false; } @@ -148,7 +149,7 @@ public function upgradeThisFile($orig): bool } } elseif (is_file($orig)) { $translationAdapter = $this->container->getTranslationAdapter(); - if ($translationAdapter->isTranslationFile($file) && file_exists($dest)) { + if ($translationAdapter->isTranslationFile($file) && $this->container->getFileSystem()->exists($dest)) { $type_trad = $translationAdapter->getTranslationFileType($file); if ($translationAdapter->mergeTranslationFile($orig, $dest, $type_trad)) { $this->logger->info($this->translator->trans('The translation files have been merged into file %s.', [$dest])); @@ -163,25 +164,24 @@ public function upgradeThisFile($orig): bool // upgrade exception were above. This part now process all files that have to be upgraded (means to modify or to remove) // delete before updating (and this will also remove deprecated files) - if (copy($orig, $dest)) { + try { + $this->container->getFileSystem()->copy($orig, $dest); $this->logger->debug($this->translator->trans('Copied %1$s.', [$file])); return true; - } else { + } catch (IOException $e) { $this->next = TaskName::TASK_ERROR; - $this->logger->error($this->translator->trans('Error while copying file %s', [$file])); + $this->logger->error($this->translator->trans('Error while copying file %s: %s', [$file, $e->getMessage()])); return false; } } elseif (is_file($dest)) { - if (file_exists($dest)) { - unlink($dest); - } + $this->container->getFileSystem()->remove($dest); $this->logger->debug(sprintf('Removed file %1$s.', $file)); return true; } elseif (is_dir($dest)) { - FilesystemAdapter::deleteDirectory($dest); + $this->container->getFileSystem()->remove($dest); $this->logger->debug(sprintf('Removed dir %1$s.', $file)); return true; @@ -214,15 +214,15 @@ protected function warmUp(): int // Replace the name of the admin folder inside the release to match our admin folder name $admin_dir = str_replace($this->container->getProperty(UpgradeContainer::PS_ROOT_PATH) . DIRECTORY_SEPARATOR, '', $this->container->getProperty(UpgradeContainer::PS_ADMIN_PATH)); - if (file_exists($newReleasePath . DIRECTORY_SEPARATOR . 'admin')) { - rename($newReleasePath . DIRECTORY_SEPARATOR . 'admin', $newReleasePath . DIRECTORY_SEPARATOR . $admin_dir); - } elseif (file_exists($newReleasePath . DIRECTORY_SEPARATOR . 'admin-dev')) { - rename($newReleasePath . DIRECTORY_SEPARATOR . 'admin-dev', $newReleasePath . DIRECTORY_SEPARATOR . $admin_dir); + if ($this->container->getFileSystem()->exists($newReleasePath . DIRECTORY_SEPARATOR . 'admin')) { + $this->container->getFileSystem()->rename($newReleasePath . DIRECTORY_SEPARATOR . 'admin', $newReleasePath . DIRECTORY_SEPARATOR . $admin_dir); + } elseif ($this->container->getFileSystem()->exists($newReleasePath . DIRECTORY_SEPARATOR . 'admin-dev')) { + $this->container->getFileSystem()->rename($newReleasePath . DIRECTORY_SEPARATOR . 'admin-dev', $newReleasePath . DIRECTORY_SEPARATOR . $admin_dir); } // Rename develop installer directory, it would be ignored anyway because it's present in getFilesToIgnoreOnUpgrade() - if (file_exists($newReleasePath . DIRECTORY_SEPARATOR . 'install-dev')) { - rename($newReleasePath . DIRECTORY_SEPARATOR . 'install-dev', $newReleasePath . DIRECTORY_SEPARATOR . 'install'); + if ($this->container->getFileSystem()->exists($newReleasePath . DIRECTORY_SEPARATOR . 'install-dev')) { + $this->container->getFileSystem()->rename($newReleasePath . DIRECTORY_SEPARATOR . 'install-dev', $newReleasePath . DIRECTORY_SEPARATOR . 'install'); } $destinationVersion = $state->getDestinationVersion(); diff --git a/classes/Task/Update/UpdateModules.php b/classes/Task/Update/UpdateModules.php index e0f2950b92..5fee7676ca 100644 --- a/classes/Task/Update/UpdateModules.php +++ b/classes/Task/Update/UpdateModules.php @@ -44,7 +44,6 @@ use PrestaShop\Module\AutoUpgrade\UpgradeTools\Module\ModuleUnzipperContext; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Module\ModuleVersionAdapter; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Module\Source\ModuleSourceAggregate; -use Symfony\Component\Filesystem\Filesystem; /** * Upgrade all partners modules according to the installed prestashop version. @@ -69,7 +68,7 @@ public function run(): int $moduleSourceList = new ModuleSourceAggregate($this->container->getModuleSourceProviders()); $moduleDownloader = new ModuleDownloader($this->translator, $this->logger, $this->container->getProperty(UpgradeContainer::TMP_PATH)); $moduleUnzipper = new ModuleUnzipper($this->translator, $this->container->getZipAction(), $modulesPath); - $moduleMigration = new ModuleMigration($this->translator, $this->logger, $this->container->getProperty(UpgradeContainer::TMP_PATH)); + $moduleMigration = new ModuleMigration($this->container->getFileSystem(), $this->translator, $this->logger, $this->container->getProperty(UpgradeContainer::TMP_PATH)); if ($listModules->getRemainingTotal()) { $moduleInfos = $listModules->getNext(); @@ -112,7 +111,7 @@ public function run(): int } finally { // Cleanup of module assets if (!empty($moduleDownloaderContext) && !empty($moduleDownloaderContext->getPathToModuleUpdate())) { - (new Filesystem())->remove([$moduleDownloaderContext->getPathToModuleUpdate()]); + $this->container->getFileSystem()->remove([$moduleDownloaderContext->getPathToModuleUpdate()]); } } } diff --git a/classes/Tools14.php b/classes/Tools14.php index c8adaf9115..66c78014e3 100755 --- a/classes/Tools14.php +++ b/classes/Tools14.php @@ -116,38 +116,6 @@ public static function htmlentitiesUTF8($string, int $type = ENT_QUOTES) return htmlentities($string, $type, 'utf-8'); } - /** - * Delete directory and subdirectories. - * - * @param string $dirname Directory name - */ - public static function deleteDirectory(string $dirname, bool $delete_self = true): bool - { - $dirname = rtrim($dirname, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; - if (file_exists($dirname)) { - if ($files = scandir($dirname)) { - foreach ($files as $file) { - if ($file != '.' && $file != '..' && $file != '.svn') { - if (is_file($dirname . $file)) { - unlink($dirname . $file); - } elseif (is_dir($dirname . $file . DIRECTORY_SEPARATOR)) { - self::deleteDirectory($dirname . $file . DIRECTORY_SEPARATOR, true); - } - } - } - if ($delete_self && file_exists($dirname)) { - if (!rmdir($dirname)) { - return false; - } - } - - return true; - } - } - - return false; - } - /** * Check if submit has been posted. * diff --git a/classes/UpgradeContainer.php b/classes/UpgradeContainer.php index 4b0d4dc8ee..764ee0ee11 100644 --- a/classes/UpgradeContainer.php +++ b/classes/UpgradeContainer.php @@ -69,6 +69,7 @@ use PrestaShop\Module\AutoUpgrade\Xml\ChecksumCompare; use PrestaShop\Module\AutoUpgrade\Xml\FileLoader; use Symfony\Component\Dotenv\Dotenv; +use Symfony\Component\Filesystem\Filesystem; use Twig\Environment; use Twig\Error\LoaderError; use Twig\Loader\FilesystemLoader; @@ -95,9 +96,7 @@ class UpgradeContainer const ARCHIVE_FILEPATH = 'destDownloadFilepath'; const PS_VERSION = 'version'; - /** - * @var Analytics - */ + /** @var Analytics */ private $analytics; /** @var BackupFinder */ @@ -106,179 +105,120 @@ class UpgradeContainer /** @var BackupManager */ private $backupManager; - /** - * @var CacheCleaner - */ + /** @var CacheCleaner */ private $cacheCleaner; - /** - * @var ChecksumCompare - */ + /** @var ChecksumCompare */ private $checksumCompare; /** @var ComposerService */ private $composerService; - /** - * @var Cookie - */ + /** @var Cookie */ private $cookie; - /** - * @var \Db - */ + /** @var \Db */ public $db; - /** - * @var FileStorage - */ + /** @var FileStorage */ private $fileStorage; - /** - * @var FileFilter - */ + /** @var FileFilter */ private $fileFilter; - /** - * @var PrestashopConfiguration - */ + /** @var PrestashopConfiguration */ private $prestashopConfiguration; - /** - * @var ConfigurationStorage - */ + /** @var ConfigurationStorage */ private $configurationStorage; - /** - * @var UpgradeConfiguration - */ + /** @var UpgradeConfiguration */ private $updateConfiguration; - /** - * @var RestoreConfiguration - */ + /** @var RestoreConfiguration */ private $restoreConfiguration; - /** - * @var FilesystemAdapter - */ + /** @var FilesystemAdapter */ private $filesystemAdapter; - /** - * @var FileLoader - */ + /** @var FileLoader */ private $fileLoader; - /** - * @var Logger - */ + /** @var Logger */ private $logger; - /** - * @var LogsService - */ + /** @var LogsService */ private $logsService; - /** - * @var ModuleAdapter - */ + /** @var ModuleAdapter */ private $moduleAdapter; - /** - * @var AbstractModuleSourceProvider[] - */ + /** @var AbstractModuleSourceProvider[] */ private $moduleSourceProviders; - /** - * @var CompletionCalculator - */ + /** @var CompletionCalculator */ private $completionCalculator; - /** - * @var Twig_Environment|\Twig\Environment - */ + /** @var Twig_Environment|\Twig\Environment */ private $twig; - /** - * @var BackupState - */ + /** @var BackupState */ private $backupState; - /** - * @var LogsState - */ + /** @var LogsState */ private $logsState; - /** - * @var RestoreState - */ + /** @var RestoreState */ private $restoreState; - /** - * @var UpdateState - */ + /** @var UpdateState */ private $updateState; - /** - * @var SymfonyAdapter - */ + /** @var SymfonyAdapter */ private $symfonyAdapter; - /** - * @var Upgrader - */ + /** @var Upgrader */ private $upgrader; - /** - * @var Workspace - */ + /** @var Workspace */ private $workspace; - /** - * @var ZipAction - */ + /** @var ZipAction */ private $zipAction; - /** - * @var LocalArchiveRepository - */ + /** @var LocalArchiveRepository */ private $localArchiveRepository; - /** - * @var AssetsEnvironment - */ + /** @var AssetsEnvironment */ private $assetsEnvironment; - /** - * @var ConfigurationValidator - */ + /** @var ConfigurationValidator */ private $configurationValidator; - /** - * @var LocalChannelConfigurationValidator - */ + /** @var LocalChannelConfigurationValidator */ private $localChannelConfigurationValidator; - /** - * @var PrestashopVersionService - */ + /** @var PrestashopVersionService */ private $prestashopVersionService; - /** - * @var UpgradeSelfCheck - */ + /** @var UpgradeSelfCheck */ private $upgradeSelfCheck; - /** - * @var PhpVersionResolverService - */ + /** @var PhpVersionResolverService */ private $phpVersionResolverService; - /** - * @var DistributionApiService - */ + /** @var DistributionApiService */ private $distributionApiService; + /** @var Filesystem */ + private $filesystem; + + /** @var Translator */ + private $translator; + + /** @var Translation */ + private $translation; + /** * AdminSelfUpgrade::$autoupgradePath * Ex.: /var/www/html/PrestaShop/admin-dev/autoupgrade. @@ -303,7 +243,7 @@ public function __construct(string $psRootDir, string $adminDir, string $moduleS $this->adminDir = $adminDir; $this->psRootDir = $psRootDir; - if (file_exists($psRootDir . '/modules/autoupgrade/.env')) { + if ($this->getFileSystem()->exists($psRootDir . '/modules/autoupgrade/.env')) { $dotenv = new Dotenv(); $dotenv->load($psRootDir . '/modules/autoupgrade/.env'); } @@ -422,7 +362,7 @@ public function getChecksumCompare(): ChecksumCompare public function getComposerService(): ComposerService { if (null === $this->composerService) { - $this->composerService = new ComposerService(); + $this->composerService = new ComposerService($this->getFileSystem()); } return $this->composerService; @@ -460,7 +400,7 @@ public function getFilePath(): string public function getFileStorage(): FileStorage { if (null === $this->fileStorage) { - $this->fileStorage = new FileStorage($this->getProperty(self::WORKSPACE_PATH) . DIRECTORY_SEPARATOR); + $this->fileStorage = new FileStorage($this->getFileSystem(), $this->getProperty(self::WORKSPACE_PATH) . DIRECTORY_SEPARATOR); } return $this->fileStorage; @@ -495,6 +435,8 @@ public function getUpgrader(): Upgrader $upgrader = new Upgrader( $this->getPhpVersionResolverService(), $this->getUpdateConfiguration(), + $this->getFileSystem(), + $this->getFileLoader(), $this->getProperty(self::PS_VERSION) ); @@ -531,7 +473,7 @@ public function getFilesystemAdapter(): FilesystemAdapter public function getFileLoader(): FileLoader { if (null === $this->fileLoader) { - $this->fileLoader = new FileLoader(); + $this->fileLoader = new FileLoader($this->getFileSystem()); } return $this->fileLoader; @@ -676,21 +618,32 @@ public function getStateFromTaskType($taskType): AbstractState */ public function getTranslationAdapter(): Translation { - return new Translation($this->getTranslator(), $this->getLogger(), $this->getUpdateState()->getInstalledLanguagesIso()); + if (null === $this->translation) { + $this->translation = new Translation($this->getTranslator(), $this->getFileSystem(), $this->getLogger(), $this->getUpdateState()->getInstalledLanguagesIso()); + } + + return $this->translation; } + /** + * @throws Exception + */ public function getTranslator(): Translator { - $locale = null; - // @phpstan-ignore booleanAnd.rightAlwaysTrue (If PrestaShop core is not instantiated properly, do not try to translate) - if (method_exists('\Context', 'getContext') && \Context::getContext()->language) { - $locale = \Context::getContext()->language->iso_code; + if (null === $this->translator) { + $locale = null; + // @phpstan-ignore booleanAnd.rightAlwaysTrue (If PrestaShop core is not instantiated properly, do not try to translate) + if (method_exists('\Context', 'getContext') && \Context::getContext()->language) { + $locale = \Context::getContext()->language->iso_code; + } + + $this->translator = new Translator( + $this->getProperty(self::PS_ROOT_PATH) . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'autoupgrade' . DIRECTORY_SEPARATOR . 'translations' . DIRECTORY_SEPARATOR, + $locale + ); } - return new Translator( - $this->getProperty(self::PS_ROOT_PATH) . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . 'autoupgrade' . DIRECTORY_SEPARATOR . 'translations' . DIRECTORY_SEPARATOR, - $locale - ); + return $this->translator; } /** @@ -729,6 +682,7 @@ public function getPrestaShopConfiguration(): PrestashopConfiguration { if (null === $this->prestashopConfiguration) { $this->prestashopConfiguration = new PrestashopConfiguration( + $this->getFileSystem(), $this->getProperty(self::PS_ROOT_PATH) ); } @@ -853,6 +807,7 @@ public function getWorkspace(): Workspace $this->workspace = new Workspace( $this->getTranslator(), + $this->getFileSystem(), $paths ); } @@ -867,6 +822,7 @@ public function getZipAction(): ZipAction { if (null === $this->zipAction) { $this->zipAction = new ZipAction( + $this->getFileSystem(), $this->getTranslator(), $this->getLogger(), $this->getUpdateConfiguration(), @@ -938,12 +894,21 @@ public function getLocalChannelConfigurationValidator(): LocalChannelConfigurati public function getPrestashopVersionService(): PrestashopVersionService { if (null === $this->prestashopVersionService) { - $this->prestashopVersionService = new PrestashopVersionService($this->getZipAction()); + $this->prestashopVersionService = new PrestashopVersionService($this->getZipAction(), $this->getFileSystem()); } return $this->prestashopVersionService; } + public function getFileSystem(): Filesystem + { + if (null === $this->filesystem) { + $this->filesystem = new Filesystem(); + } + + return $this->filesystem; + } + /** * Checks if the composer autoload exists, and loads it. * @@ -952,7 +917,7 @@ public function getPrestashopVersionService(): PrestashopVersionService public function initPrestaShopAutoloader(): void { $autoloader = $this->getProperty(self::PS_ROOT_PATH) . '/vendor/autoload.php'; - if (file_exists($autoloader)) { + if ($this->getFileSystem()->exists($autoloader)) { require_once $autoloader; } diff --git a/classes/UpgradeTools/CacheCleaner.php b/classes/UpgradeTools/CacheCleaner.php index f2d35cb73c..8b1060a46f 100644 --- a/classes/UpgradeTools/CacheCleaner.php +++ b/classes/UpgradeTools/CacheCleaner.php @@ -73,7 +73,7 @@ public function cleanFolders(): void } foreach ($dirsToClean as $dir) { - if (!file_exists($dir)) { + if (!$this->container->getFileSystem()->exists($dir)) { $this->logger->debug($this->container->getTranslator()->trans('[SKIP] directory "%s" does not exist and cannot be emptied.', [str_replace($this->container->getProperty(UpgradeContainer::PS_ROOT_PATH), '', $dir)])); continue; } @@ -81,12 +81,7 @@ public function cleanFolders(): void if ($file[0] === '.' || $file === 'index.php') { continue; } - // ToDo: Use Filesystem instead ? - if (is_file($dir . $file)) { - unlink($dir . $file); - } elseif (is_dir($dir . $file . DIRECTORY_SEPARATOR)) { - FilesystemAdapter::deleteDirectory($dir . $file . DIRECTORY_SEPARATOR); - } + $this->container->getFileSystem()->remove($dir . $file); $this->logger->debug($this->container->getTranslator()->trans('[CLEANING CACHE] File %s removed', [$file])); } } diff --git a/classes/UpgradeTools/CoreUpgrader/CoreUpgrader.php b/classes/UpgradeTools/CoreUpgrader/CoreUpgrader.php index 2c9130e6c5..15fe0d20e9 100644 --- a/classes/UpgradeTools/CoreUpgrader/CoreUpgrader.php +++ b/classes/UpgradeTools/CoreUpgrader/CoreUpgrader.php @@ -66,11 +66,6 @@ abstract class CoreUpgrader */ protected $logger; - /** - * @var Filesystem - */ - private $filesystem; - /** * Version PrestaShop is upgraded to. * @@ -96,11 +91,10 @@ public function __construct(UpgradeContainer $container, LoggerInterface $logger { $this->container = $container; $this->logger = $logger; - $this->filesystem = new Filesystem(); $this->destinationUpgradeVersion = $this->container->getUpdateState()->getDestinationVersion(); $this->pathToInstallFolder = realpath($this->container->getProperty(UpgradeContainer::LATEST_PATH) . DIRECTORY_SEPARATOR . 'install'); $this->pathToUpgradeScripts = dirname(__DIR__, 3) . '/upgrade/'; - if (file_exists($this->pathToInstallFolder . DIRECTORY_SEPARATOR . 'autoload.php')) { + if ($this->container->getFileSystem()->exists($this->pathToInstallFolder . DIRECTORY_SEPARATOR . 'autoload.php')) { require_once $this->pathToInstallFolder . DIRECTORY_SEPARATOR . 'autoload.php'; } $this->db = \Db::getInstance(); @@ -271,7 +265,7 @@ public function disableCustomModules(): void */ protected function getUpgradeSqlFilesListToApply(string $upgrade_dir_sql, string $oldversion): array { - if (!file_exists($upgrade_dir_sql)) { + if (!$this->container->getFileSystem()->exists($upgrade_dir_sql)) { throw new UpgradeException($this->container->getTranslator()->trans('Unable to find upgrade directory in the installation path.')); } @@ -424,7 +418,7 @@ protected function runPhpQuery(string $upgrade_file, string $query): void $func_name = str_replace($stringParameters, '', $php[0]); $pathToPhpDirectory = $this->pathToUpgradeScripts . 'php/'; - if (!file_exists($pathToPhpDirectory . strtolower($func_name) . '.php')) { + if (!$this->container->getFileSystem()->exists($pathToPhpDirectory . strtolower($func_name) . '.php')) { $this->logMissingFileError($pathToPhpDirectory, $func_name, $query); return; @@ -566,7 +560,7 @@ protected function generateHtaccess(): void { $this->loadEntityInterface(); - if (file_exists(_PS_ROOT_DIR_ . '/classes/Tools.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Tools.php')) { require_once _PS_ROOT_DIR_ . '/classes/Tools.php'; } @@ -583,105 +577,105 @@ protected function generateHtaccess(): void define('_PS_USE_SQL_SLAVE_', false); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/ObjectModel.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/ObjectModel.php')) { require_once _PS_ROOT_DIR_ . '/classes/ObjectModel.php'; } if (!class_exists('ObjectModel', false) && class_exists('ObjectModelCore')) { eval('abstract class ObjectModel extends ObjectModelCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Configuration.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Configuration.php')) { require_once _PS_ROOT_DIR_ . '/classes/Configuration.php'; } if (!class_exists('Configuration', false) && class_exists('ConfigurationCore')) { eval('class Configuration extends ConfigurationCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/cache/Cache.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/cache/Cache.php')) { require_once _PS_ROOT_DIR_ . '/classes/cache/Cache.php'; } if (!class_exists('Cache', false) && class_exists('CacheCore')) { eval('abstract class Cache extends CacheCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/PrestaShopCollection.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/PrestaShopCollection.php')) { require_once _PS_ROOT_DIR_ . '/classes/PrestaShopCollection.php'; } if (!class_exists('PrestaShopCollection', false) && class_exists('PrestaShopCollectionCore')) { eval('class PrestaShopCollection extends PrestaShopCollectionCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/shop/ShopUrl.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/shop/ShopUrl.php')) { require_once _PS_ROOT_DIR_ . '/classes/shop/ShopUrl.php'; } if (!class_exists('ShopUrl', false) && class_exists('ShopUrlCore')) { eval('class ShopUrl extends ShopUrlCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/shop/Shop.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/shop/Shop.php')) { require_once _PS_ROOT_DIR_ . '/classes/shop/Shop.php'; } if (!class_exists('Shop', false) && class_exists('ShopCore')) { eval('class Shop extends ShopCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Translate.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Translate.php')) { require_once _PS_ROOT_DIR_ . '/classes/Translate.php'; } if (!class_exists('Translate', false) && class_exists('TranslateCore')) { eval('class Translate extends TranslateCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/module/Module.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/module/Module.php')) { require_once _PS_ROOT_DIR_ . '/classes/module/Module.php'; } if (!class_exists('Module', false) && class_exists('ModuleCore')) { eval('class Module extends ModuleCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Validate.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Validate.php')) { require_once _PS_ROOT_DIR_ . '/classes/Validate.php'; } if (!class_exists('Validate', false) && class_exists('ValidateCore')) { eval('class Validate extends ValidateCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Language.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Language.php')) { require_once _PS_ROOT_DIR_ . '/classes/Language.php'; } if (!class_exists('Language', false) && class_exists('LanguageCore')) { eval('class Language extends LanguageCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Tab.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Tab.php')) { require_once _PS_ROOT_DIR_ . '/classes/Tab.php'; } if (!class_exists('Tab', false) && class_exists('TabCore')) { eval('class Tab extends TabCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Dispatcher.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Dispatcher.php')) { require_once _PS_ROOT_DIR_ . '/classes/Dispatcher.php'; } if (!class_exists('Dispatcher', false) && class_exists('DispatcherCore')) { eval('class Dispatcher extends DispatcherCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Hook.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Hook.php')) { require_once _PS_ROOT_DIR_ . '/classes/Hook.php'; } if (!class_exists('Hook', false) && class_exists('HookCore')) { eval('class Hook extends HookCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Context.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Context.php')) { require_once _PS_ROOT_DIR_ . '/classes/Context.php'; } if (!class_exists('Context', false) && class_exists('ContextCore')) { eval('class Context extends ContextCore{}'); } - if (file_exists(_PS_ROOT_DIR_ . '/classes/Group.php')) { + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . '/classes/Group.php')) { require_once _PS_ROOT_DIR_ . '/classes/Group.php'; } if (!class_exists('Group', false) && class_exists('GroupCore')) { @@ -718,8 +712,8 @@ protected function cleanXmlFiles(): void _PS_ROOT_DIR_ . '/var/cache/prod/class_index.php', ]; foreach ($files as $path) { - if (file_exists($path)) { - unlink($path); + if ($this->container->getFileSystem()->exists($path)) { + $this->container->getFileSystem()->remove($path); } } } @@ -834,7 +828,7 @@ private function removeExistingRTLFiles(array $themes): void { foreach ($themes as $theme) { $files = $this->container->getFilesystemAdapter()->listSampleFiles($theme['directory'], '_rtl.css'); - $this->filesystem->remove($files); + $this->container->getFileSystem()->remove($files); } } diff --git a/classes/UpgradeTools/CoreUpgrader/CoreUpgrader80.php b/classes/UpgradeTools/CoreUpgrader/CoreUpgrader80.php index a654133380..fdd87e8870 100644 --- a/classes/UpgradeTools/CoreUpgrader/CoreUpgrader80.php +++ b/classes/UpgradeTools/CoreUpgrader/CoreUpgrader80.php @@ -55,8 +55,8 @@ protected function forceRemovingFiles(): void ]; foreach ($filesToForceRemove as $file) { - if (file_exists(_PS_ROOT_DIR_ . $file)) { - unlink(_PS_ROOT_DIR_ . $file); + if ($this->container->getFileSystem()->exists(_PS_ROOT_DIR_ . $file)) { + $this->container->getFileSystem()->remove(_PS_ROOT_DIR_ . $file); } } } diff --git a/classes/UpgradeTools/FilesystemAdapter.php b/classes/UpgradeTools/FilesystemAdapter.php index 7b76fabd78..f2512ee823 100644 --- a/classes/UpgradeTools/FilesystemAdapter.php +++ b/classes/UpgradeTools/FilesystemAdapter.php @@ -28,7 +28,6 @@ namespace PrestaShop\Module\AutoUpgrade\UpgradeTools; use FilesystemIterator; -use PrestaShop\Module\AutoUpgrade\Tools14; use RecursiveCallbackFilterIterator; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; @@ -85,16 +84,6 @@ public function __construct( $this->prodRootDir = $prodRootDir; } - /** - * Delete directory and subdirectories. - * - * @param string $dirname Directory name - */ - public static function deleteDirectory(string $dirname, bool $delete_self = true): bool - { - return Tools14::deleteDirectory($dirname, $delete_self); - } - /** * @param 'upgrade'|'restore'|'backup' $way * diff --git a/classes/UpgradeTools/Module/ModuleMigration.php b/classes/UpgradeTools/Module/ModuleMigration.php index 26c6220cea..12432b02a2 100644 --- a/classes/UpgradeTools/Module/ModuleMigration.php +++ b/classes/UpgradeTools/Module/ModuleMigration.php @@ -27,14 +27,19 @@ namespace PrestaShop\Module\AutoUpgrade\UpgradeTools\Module; +use Exception; use LogicException; use PrestaShop\Module\AutoUpgrade\Exceptions\UpgradeException; use PrestaShop\Module\AutoUpgrade\Log\Logger; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Translator; +use Symfony\Component\Filesystem\Filesystem; use Throwable; class ModuleMigration { + /** @var Filesystem */ + private $filesystem; + /** @var Translator */ private $translator; @@ -44,8 +49,9 @@ class ModuleMigration /** @var string */ private $sandboxFolder; - public function __construct(Translator $translator, Logger $logger, string $sandboxFolder) + public function __construct(Filesystem $filesystem, Translator $translator, Logger $logger, string $sandboxFolder) { + $this->filesystem = $filesystem; $this->translator = $translator; $this->logger = $logger; $this->sandboxFolder = $sandboxFolder; @@ -154,15 +160,16 @@ private function loadAndCallFunction(string $filePath, string $methodName, Modul $uniqueMethodName = $moduleMigrationContext->getModuleName() . '_' . $methodName; $sandboxedFilePath = $this->sandboxFolder . DIRECTORY_SEPARATOR . $uniqueMethodName . '.php'; - $pushedFileContents = file_put_contents($sandboxedFilePath, str_replace($methodName, $uniqueMethodName, file_get_contents($filePath))); - if ($pushedFileContents === false) { - throw (new UpgradeException($this->translator->trans('[WARNING] Could not write temporary file %s.', [$sandboxedFilePath])))->setSeverity(UpgradeException::SEVERITY_WARNING); + try { + $this->filesystem->dumpFile($sandboxedFilePath, str_replace($methodName, $uniqueMethodName, file_get_contents($filePath))); + } catch (Exception $e) { + throw (new UpgradeException($this->translator->trans('Could not write temporary file %s.', [$sandboxedFilePath])))->setSeverity(UpgradeException::SEVERITY_WARNING); } require_once $sandboxedFilePath; if (!function_exists($uniqueMethodName)) { - throw (new UpgradeException($this->translator->trans('[WARNING] Method %s does not exist. Module %s disabled.', [$uniqueMethodName, $moduleMigrationContext->getModuleName()])))->setSeverity(UpgradeException::SEVERITY_WARNING); + throw (new UpgradeException($this->translator->trans('Method %s does not exist. Module %s disabled.', [$uniqueMethodName, $moduleMigrationContext->getModuleName()])))->setSeverity(UpgradeException::SEVERITY_WARNING); } return call_user_func($uniqueMethodName, $moduleMigrationContext->getModuleInstance()); diff --git a/classes/UpgradeTools/Translation.php b/classes/UpgradeTools/Translation.php index 559a52cbd9..248112472b 100644 --- a/classes/UpgradeTools/Translation.php +++ b/classes/UpgradeTools/Translation.php @@ -29,6 +29,7 @@ use PrestaShop\Module\AutoUpgrade\Log\LoggerInterface; use PrestaShop\Module\AutoUpgrade\Tools14; +use Symfony\Component\Filesystem\Filesystem; class Translation { @@ -38,14 +39,17 @@ class Translation private $logger; /** @var Translator */ private $translator; + /** @var Filesystem */ + private $filesystem; /** * @param string[] $installedLanguagesIso */ - public function __construct(Translator $translator, LoggerInterface $logger, array $installedLanguagesIso) + public function __construct(Translator $translator, Filesystem $filesystem, LoggerInterface $logger, array $installedLanguagesIso) { $this->logger = $logger; $this->translator = $translator; + $this->filesystem = $filesystem; $this->installedLanguagesIso = $installedLanguagesIso; } @@ -120,7 +124,7 @@ public function mergeTranslationFile(string $orig, string $dest, string $type): return false; } - if (!file_exists($orig)) { + if (!$this->filesystem->exists($orig)) { $this->logger->notice($this->translator->trans('File %s does not exist, merge skipped.', [$orig])); return true; @@ -139,7 +143,7 @@ public function mergeTranslationFile(string $orig, string $dest, string $type): } $var_orig = $$var_name; - if (!file_exists($dest)) { + if (!$this->filesystem->exists($dest)) { $this->logger->notice($this->translator->trans('File %s does not exist, merge skipped.', [$dest])); return false; @@ -149,7 +153,7 @@ public function mergeTranslationFile(string $orig, string $dest, string $type): // in that particular case : file exists, but variable missing, we need to delete that file // (if not, this invalid file will be copied in /translations during upgradeDb process) if ('module' == $type) { - unlink($dest); + $this->filesystem->remove($dest); } $this->logger->warning($this->translator->trans( '%variablename% variable missing in file %filename%. File %filename% deleted and merge skipped.', diff --git a/classes/Upgrader.php b/classes/Upgrader.php index b349cd5d61..5a9f2a399a 100755 --- a/classes/Upgrader.php +++ b/classes/Upgrader.php @@ -48,15 +48,23 @@ class Upgrader protected $phpVersionResolverService; /** @var UpgradeConfiguration */ protected $updateConfiguration; + /** @var Filesystem */ + protected $filesystem; + /** @var FileLoader */ + protected $fileLoader; public function __construct( PhpVersionResolverService $phpRequirementService, UpgradeConfiguration $updateConfiguration, + Filesystem $filesystem, + FileLoader $fileLoader, string $currentPsVersion ) { $this->currentPsVersion = $currentPsVersion; $this->phpVersionResolverService = $phpRequirementService; $this->updateConfiguration = $updateConfiguration; + $this->filesystem = $filesystem; + $this->fileLoader = $fileLoader; } /** @@ -79,8 +87,7 @@ public function downloadLast(string $dest, string $filename): bool $destPath = realpath($dest) . DIRECTORY_SEPARATOR . $filename; try { - $filesystem = new Filesystem(); - $filesystem->copy($this->onlineDestinationRelease->getZipDownloadUrl(), $destPath); + $this->filesystem->copy($this->onlineDestinationRelease->getZipDownloadUrl(), $destPath); } catch (IOException $e) { // If the Symfony filesystem failed, we can try with // the legacy method which uses curl. @@ -150,9 +157,7 @@ public function getDestinationVersion(): ?string */ public function getLatestModuleVersion(): string { - $fileLoader = new FileLoader(); - - $channelFile = $fileLoader->getXmlChannel(); + $channelFile = $this->fileLoader->getXmlChannel(); if (empty($channelFile)) { throw new UpgradeException('Unable to retrieve channel.xml.'); @@ -164,12 +169,11 @@ public function getLatestModuleVersion(): string /** * delete the file /config/xml/$version.xml if exists. */ - public function clearXmlMd5File(string $version): bool + public function clearXmlMd5File(string $version): void { - if (file_exists(_PS_ROOT_DIR_ . '/config/xml/' . $version . '.xml')) { - return unlink(_PS_ROOT_DIR_ . '/config/xml/' . $version . '.xml'); + $fileToRemove = _PS_ROOT_DIR_ . '/config/xml/' . $version . '.xml'; + if ($this->filesystem->exists($fileToRemove)) { + $this->filesystem->remove($fileToRemove); } - - return true; } } diff --git a/classes/Workspace.php b/classes/Workspace.php index 9097c01ec3..d3afd7810a 100644 --- a/classes/Workspace.php +++ b/classes/Workspace.php @@ -29,6 +29,8 @@ use Exception; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Translator; +use Symfony\Component\Filesystem\Exception\IOException; +use Symfony\Component\Filesystem\Filesystem; class Workspace { @@ -42,23 +44,37 @@ class Workspace */ private $paths; + /** + * @var Filesystem + */ + private $filesystem; + /** * @param string[] $paths */ - public function __construct(Translator $translator, array $paths) + public function __construct(Translator $translator, Filesystem $filesystem, array $paths) { $this->translator = $translator; + $this->filesystem = $filesystem; $this->paths = $paths; } + /** + * @throws IOException + */ public function createFolders(): void { foreach ($this->paths as $path) { - if (!file_exists($path) && !@mkdir($path)) { - throw new Exception($this->translator->trans('Unable to create directory %s', [$path])); + if (!$this->filesystem->exists($path)) { + try { + $this->filesystem->mkdir($path); + } catch (IOException $e) { + throw new IOException($this->translator->trans('Unable to create directory %s: %s', [$path, $e->getMessage()])); + } } + if (!is_writable($path)) { - throw new Exception($this->translator->trans('Cannot write to the directory. Please ensure you have the necessary write permissions on "%s".', [$path])); + throw new IOException($this->translator->trans('Cannot write to the directory. Please ensure you have the necessary write permissions on "%s".', [$path])); } } } diff --git a/classes/Xml/FileLoader.php b/classes/Xml/FileLoader.php index d95894fe01..7ecc98c26b 100644 --- a/classes/Xml/FileLoader.php +++ b/classes/Xml/FileLoader.php @@ -31,6 +31,7 @@ use PrestaShop\Module\AutoUpgrade\Tools14; use PrestaShop\Module\AutoUpgrade\Upgrader; use SimpleXMLElement; +use Symfony\Component\Filesystem\Filesystem; class FileLoader { @@ -39,6 +40,13 @@ class FileLoader /** @var array */ private $version_md5 = []; + /** @var Filesystem */ + private $filesystem; + + public function __construct(Filesystem $filesystem) + { + $this->filesystem = $filesystem; + } /** * @return SimpleXMLElement|false @@ -48,17 +56,17 @@ public function getXmlFile(string $xml_localfile, string $xml_remotefile, bool $ // @TODO : this has to be moved in autoupgrade.php > install method if (!is_dir(_PS_ROOT_DIR_ . '/config/xml')) { if (is_file(_PS_ROOT_DIR_ . '/config/xml')) { - unlink(_PS_ROOT_DIR_ . '/config/xml'); + $this->filesystem->remove(_PS_ROOT_DIR_ . '/config/xml'); } - mkdir(_PS_ROOT_DIR_ . '/config/xml', 0777); + $this->filesystem->mkdir(_PS_ROOT_DIR_ . '/config/xml'); } // End TODO - if ($refresh || !file_exists($xml_localfile) || @filemtime($xml_localfile) < (time() - (3600 * Upgrader::DEFAULT_CHECK_VERSION_DELAY_HOURS))) { + if ($refresh || !$this->filesystem->exists($xml_localfile) || @filemtime($xml_localfile) < (time() - (3600 * Upgrader::DEFAULT_CHECK_VERSION_DELAY_HOURS))) { $xml_string = Tools14::file_get_contents($xml_remotefile, false, stream_context_create(['http' => ['timeout' => 10]])); $xml = @simplexml_load_string($xml_string); if ($xml !== false) { - file_put_contents($xml_localfile, $xml_string); + $this->filesystem->dumpFile($xml_localfile, $xml_string); } } else { $xml = @simplexml_load_file($xml_localfile); diff --git a/classes/ZipAction.php b/classes/ZipAction.php index 1def18f402..650eb59525 100644 --- a/classes/ZipAction.php +++ b/classes/ZipAction.php @@ -32,6 +32,7 @@ use PrestaShop\Module\AutoUpgrade\Parameters\UpgradeConfiguration; use PrestaShop\Module\AutoUpgrade\Progress\Backlog; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Translator; +use Symfony\Component\Filesystem\Exception\IOException; use Symfony\Component\Filesystem\Filesystem; use ZipArchive; @@ -56,13 +57,19 @@ class ZipAction */ private $translator; + /** + * @var Filesystem + */ + private $filesystem; + /** * @var string Path to the shop, in order to remove it from the archived file paths */ private $prodRootDir; - public function __construct(Translator $translator, LoggerInterface $logger, UpgradeConfiguration $updateConfiguration, string $prodRootDir) + public function __construct(Filesystem $filesystem, Translator $translator, LoggerInterface $logger, UpgradeConfiguration $updateConfiguration, string $prodRootDir) { + $this->filesystem = $filesystem; $this->translator = $translator; $this->logger = $logger; $this->prodRootDir = $prodRootDir; @@ -94,7 +101,7 @@ public function compress(Backlog $backlog, string $toFile): bool $error = $zip->getStatusString(); // if an error occur, it's more safe to delete the corrupted backup $zip->close(); - (new Filesystem())->remove($toFile); + $this->filesystem->remove($toFile); $this->logger->error($this->translator->trans( 'Unable to add %filename% to archive %archive%: %error%', [ @@ -147,14 +154,14 @@ public function extract(string $from_file, string $to_dir): bool return false; } - if (!file_exists($to_dir)) { - // ToDo: Use Filesystem from Symfony - if (!mkdir($to_dir)) { + if (!$this->filesystem->exists($to_dir)) { + try { + $this->filesystem->mkdir($to_dir, 0775); + } catch (IOException $exception) { $this->logger->error($this->translator->trans('Unable to create directory %s.', [$to_dir])); return false; } - chmod($to_dir, 0775); } try { @@ -197,7 +204,7 @@ public function extract(string $from_file, string $to_dir): bool */ public function listContent(string $zipFile): array { - if (!file_exists($zipFile)) { + if (!$this->filesystem->exists($zipFile)) { return []; } diff --git a/tests/unit/AnalyticsTest.php b/tests/unit/AnalyticsTest.php index ece907412a..41adf97d72 100644 --- a/tests/unit/AnalyticsTest.php +++ b/tests/unit/AnalyticsTest.php @@ -30,6 +30,7 @@ use PrestaShop\Module\AutoUpgrade\State\RestoreState; use PrestaShop\Module\AutoUpgrade\State\UpdateState; use PrestaShop\Module\AutoUpgrade\UpgradeContainer; +use Symfony\Component\Filesystem\Filesystem; class AnalyticsTest extends TestCase { @@ -43,7 +44,7 @@ protected function setUp() public function testProperties() { $fixturesDir = __DIR__ . '/../../fixtures/config/'; - $fileStorage = new FileStorage($fixturesDir); + $fileStorage = new FileStorage(new Filesystem(), $fixturesDir); $restoreState = (new RestoreState($fileStorage)) ->setRestoreName('V1.2.3_blablabla-🐶'); diff --git a/tests/unit/PrestashopConfiguration/PrestaShopConfigurationTest.php b/tests/unit/PrestashopConfiguration/PrestaShopConfigurationTest.php index 0f308a4e22..010347c8a7 100644 --- a/tests/unit/PrestashopConfiguration/PrestaShopConfigurationTest.php +++ b/tests/unit/PrestashopConfiguration/PrestaShopConfigurationTest.php @@ -25,12 +25,13 @@ */ use PHPUnit\Framework\TestCase; use PrestaShop\Module\AutoUpgrade\PrestashopConfiguration; +use Symfony\Component\Filesystem\Filesystem; class PrestaShopConfigurationTest extends TestCase { public function testPrestaShopVersionInFile() { - $class = new PrestashopConfiguration(__DIR__); + $class = new PrestashopConfiguration(new Filesystem(), __DIR__); $content = "assertSame( '1.7.6.0', $class->findPrestaShopVersionInFile( diff --git a/tests/unit/Services/PhpVersionResolverServiceTest.php b/tests/unit/Services/PhpVersionResolverServiceTest.php index 6517afca57..dcf17b8ab0 100644 --- a/tests/unit/Services/PhpVersionResolverServiceTest.php +++ b/tests/unit/Services/PhpVersionResolverServiceTest.php @@ -87,6 +87,7 @@ public function testUnknownCompatibilityRange() public function testGetLatestPrestashop17ReleaseWillReturnRelease() { $fileLoader = $this->getMockBuilder(FileLoader::class) + ->disableOriginalConstructor() ->setMethods(['getXmlChannel']) ->getMock(); @@ -123,6 +124,7 @@ public function testGetLatestPrestashop17ReleaseWillReturnRelease() public function testGetLatestPrestashop17ReleaseWillReturnNull() { $fileLoader = $this->getMockBuilder(FileLoader::class) + ->disableOriginalConstructor() ->setMethods(['getXmlChannel']) ->getMock(); @@ -148,6 +150,7 @@ public function testGetLatestPrestashop17ReleaseWillReturnNull() public function testGetPrestashopDestinationReleaseForPHP71() { $fileLoader = $this->getMockBuilder(FileLoader::class) + ->disableOriginalConstructor() ->setMethods(['getXmlChannel']) ->getMock(); @@ -185,6 +188,7 @@ public function testGetPrestashopDestinationReleaseForPHP71() public function testGetPrestashopDestinationReleaseForPHP73() { $fileLoader = $this->getMockBuilder(FileLoader::class) + ->disableOriginalConstructor() ->setMethods(['getXmlChannel']) ->getMock(); @@ -236,6 +240,7 @@ public function testGetPrestashopDestinationReleaseForPHP73() public function testGetPrestashopDestinationReleaseWithNoMatchingChannelXml() { $fileLoader = $this->getMockBuilder(FileLoader::class) + ->disableOriginalConstructor() ->setMethods(['getXmlChannel']) ->getMock(); @@ -288,6 +293,7 @@ public function testGetPrestashopDestinationReleaseWithNoMatchingChannelXml() public function testGetPrestashopDestinationReleaseWithCurrentVersionUpToDate() { $fileLoader = $this->getMockBuilder(FileLoader::class) + ->disableOriginalConstructor() ->setMethods(['getXmlChannel']) ->getMock(); @@ -339,6 +345,7 @@ public function testGetPrestashopDestinationReleaseWithCurrentVersionUpToDate() public function testGetPrestashopDestinationReleaseWhenAPIReturnEmptyResponse() { $fileLoader = $this->getMockBuilder(FileLoader::class) + ->disableOriginalConstructor() ->setMethods(['getXmlChannel']) ->getMock(); diff --git a/tests/unit/Services/PrestashopVersionServiceTest.php b/tests/unit/Services/PrestashopVersionServiceTest.php index 844b67e6d6..ecf09f5f66 100644 --- a/tests/unit/Services/PrestashopVersionServiceTest.php +++ b/tests/unit/Services/PrestashopVersionServiceTest.php @@ -4,6 +4,7 @@ use PrestaShop\Module\AutoUpgrade\Services\PrestashopVersionService; use PrestaShop\Module\AutoUpgrade\UpgradeContainer; use Symfony\Component\Filesystem\Exception\FileNotFoundException; +use Symfony\Component\Filesystem\Filesystem; class PrestashopVersionServiceTest extends TestCase { @@ -18,7 +19,7 @@ protected function setUp(): void $this->fixturePath = __DIR__ . '/../../fixtures/localChannel/'; - $this->versionService = new PrestashopVersionService($this->container->getZipAction()); + $this->versionService = new PrestashopVersionService($this->container->getZipAction(), new Filesystem()); } public function testExtractPrestashopVersionFromZipFileNotFound(): void diff --git a/tests/unit/UpgradeTools/Module/ModuleMigrationTest.php b/tests/unit/UpgradeTools/Module/ModuleMigrationTest.php index 43b158ecfb..0bc3d09264 100644 --- a/tests/unit/UpgradeTools/Module/ModuleMigrationTest.php +++ b/tests/unit/UpgradeTools/Module/ModuleMigrationTest.php @@ -29,6 +29,7 @@ use PrestaShop\Module\AutoUpgrade\UpgradeTools\Module\ModuleMigration; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Module\ModuleMigrationContext; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Translator; +use Symfony\Component\Filesystem\Filesystem; class ModuleMigrationTest extends TestCase { @@ -72,7 +73,7 @@ protected function setUp(): void }); $this->logger = $this->createMock(Logger::class); - $this->moduleMigration = new ModuleMigration($translator, $this->logger, self::$fixtureFolder); + $this->moduleMigration = new ModuleMigration(new Filesystem(), $translator, $this->logger, self::$fixtureFolder); } public function testNeedMigrationWithSameVersion() @@ -204,7 +205,7 @@ public function testRunMigrationWithBadUpgradeMethodName() $this->moduleMigration->needMigration($moduleMigrationContext); $this->expectException(\PrestaShop\Module\AutoUpgrade\Exceptions\UpgradeException::class); - $this->expectExceptionMessage('[WARNING] Method mymodule_upgrade_module_1_2_0 does not exist. Module mymodule disabled.'); + $this->expectExceptionMessage('Method mymodule_upgrade_module_1_2_0 does not exist. Module mymodule disabled.'); $this->moduleMigration->runMigration($moduleMigrationContext); } diff --git a/tests/unit/UpgradeTools/Module/Source/Provider/ComposerSourceProviderTest.php b/tests/unit/UpgradeTools/Module/Source/Provider/ComposerSourceProviderTest.php index da353c6a91..0defab4383 100644 --- a/tests/unit/UpgradeTools/Module/Source/Provider/ComposerSourceProviderTest.php +++ b/tests/unit/UpgradeTools/Module/Source/Provider/ComposerSourceProviderTest.php @@ -29,6 +29,7 @@ use PrestaShop\Module\AutoUpgrade\Services\ComposerService; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Module\Source\ModuleSource; use PrestaShop\Module\AutoUpgrade\UpgradeTools\Module\Source\Provider\ComposerSourceProvider; +use Symfony\Component\Filesystem\Filesystem; class ComposerSourceProviderTest extends TestCase { @@ -37,7 +38,7 @@ public function testCacheGenerationWithData() $prestashopContents = realpath(__DIR__ . '/../../../../../fixtures/prestashop-release'); $fileConfigurationStorageMock = $this->createMock(FileStorage::class); - $sourceProvider = new ComposerSourceProvider($prestashopContents, new ComposerService(), $fileConfigurationStorageMock); + $sourceProvider = new ComposerSourceProvider($prestashopContents, new ComposerService(new Filesystem()), $fileConfigurationStorageMock); $fileConfigurationStorageMock->expects($this->once())->method('exists'); $fileConfigurationStorageMock->expects($this->once())->method('save'); @@ -58,7 +59,7 @@ public function testCacheGenerationWithNoData() $prestashopContents = realpath(__DIR__ . '/../../../../../../'); $fileConfigurationStorageMock = $this->createMock(FileStorage::class); - $sourceProvider = new ComposerSourceProvider($prestashopContents, new ComposerService(), $fileConfigurationStorageMock); + $sourceProvider = new ComposerSourceProvider($prestashopContents, new ComposerService(new Filesystem()), $fileConfigurationStorageMock); $fileConfigurationStorageMock->expects($this->once())->method('exists'); $fileConfigurationStorageMock->expects($this->once())->method('save'); @@ -75,7 +76,7 @@ public function testCacheLoading() $fileConfigurationStorageMock->method('exists')->willReturn(true); $fileConfigurationStorageMock->method('load')->willReturn([]); - $sourceProvider = new ComposerSourceProvider($prestashopContents, new ComposerService(), $fileConfigurationStorageMock); + $sourceProvider = new ComposerSourceProvider($prestashopContents, new ComposerService(new Filesystem()), $fileConfigurationStorageMock); $fileConfigurationStorageMock->expects($this->once())->method('exists'); $fileConfigurationStorageMock->expects($this->once())->method('load');