From 9389284209ff0c48a8deae858cf70ac6a3157332 Mon Sep 17 00:00:00 2001 From: Luke Rodgers Date: Sat, 5 Nov 2022 19:43:44 +0000 Subject: [PATCH] Add PSR12 code styling --- .gitignore | 1 + .travis.yml | 4 +- composer.json | 8 +- composer.lock | 58 +++++- dev/phpcs.xml | 20 +++ dev/phpunit/bootstrap.php | 1 + dev/phpunit/functional/FunctionalTests.php | 3 +- .../PatchHelper/Command/AnalyseCommand.php | 131 ++++++++++---- .../Exception/PluginDetectionException.php | 1 + .../Exception/VirtualTypeException.php | 1 + .../PatchHelper/Helper/Magento2Instance.php | 11 +- .../Helper/PatchOverrideValidator.php | 168 ++++++++++-------- src/Ampersand/PatchHelper/Patchfile/Entry.php | 15 +- .../PatchHelper/Patchfile/Reader.php | 1 + src/functions.php | 13 ++ 15 files changed, 312 insertions(+), 124 deletions(-) create mode 100644 dev/phpcs.xml diff --git a/.gitignore b/.gitignore index 198dc0aa..8575c0b1 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ dev/instances/magento* .php_cs.cache dev/vendor/ dev/phpunit/functional/.phpunit.result.cache +dev/phpunit/unit/.phpunit.result.cache diff --git a/.travis.yml b/.travis.yml index d59ad2ba..4095a3e8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,9 +17,9 @@ install: - composer validate - composer install # Run static analysis tests before trying to install the modules in magento - - vendor/bin/php-cs-fixer fix --diff --dry-run + - test:static # Run unit tests before trying to install magento - - vendor/bin/phpunit -c dev/phpunit/unit/phpunit.xml --verbose; + - composer test:unit - if [[ $TEST_GROUP = m22 ]]; then rm -rf composer.lock ./vendor/ ; fi # todo ensure all 22 test cases are covered in 24 - cd dev - docker --version diff --git a/composer.json b/composer.json index cb958417..b4205f44 100644 --- a/composer.json +++ b/composer.json @@ -20,6 +20,12 @@ "license": "LGPL-3.0-only", "require-dev": { "phpunit/phpunit": "^8.5|^9.5", - "friendsofphp/php-cs-fixer": "^3.0" + "friendsofphp/php-cs-fixer": "^3.0", + "squizlabs/php_codesniffer": "^3.7" + }, + "scripts": { + "test:static:fix": " vendor/bin/phpcbf --standard=dev/phpcs.xml && vendor/bin/php-cs-fixer fix --diff", + "test:static": "vendor/bin/phpcs --standard=dev/phpcs.xml -s && vendor/bin/php-cs-fixer fix --diff --dry-run", + "test:unit": "vendor/bin/phpunit -c dev/phpunit/unit/phpunit.xml --verbose" } } diff --git a/composer.lock b/composer.lock index db77f242..c0e48551 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "6de2e3219f3d44ca99197f75e32c4d6a", + "content-hash": "7dcd1e844a8f7ca35c227e609ba418c6", "packages": [ { "name": "psr/container", @@ -3056,6 +3056,62 @@ ], "time": "2020-09-28T06:39:44+00:00" }, + { + "name": "squizlabs/php_codesniffer", + "version": "3.7.1", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "1359e176e9307e906dc3d890bcc9603ff6d90619" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/1359e176e9307e906dc3d890bcc9603ff6d90619", + "reference": "1359e176e9307e906dc3d890bcc9603ff6d90619", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "bin": [ + "bin/phpcs", + "bin/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/squizlabs/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards" + ], + "support": { + "issues": "https://github.com/squizlabs/PHP_CodeSniffer/issues", + "source": "https://github.com/squizlabs/PHP_CodeSniffer", + "wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki" + }, + "time": "2022-06-18T07:21:10+00:00" + }, { "name": "symfony/event-dispatcher", "version": "v4.4.42", diff --git a/dev/phpcs.xml b/dev/phpcs.xml new file mode 100644 index 00000000..7a7b9b5b --- /dev/null +++ b/dev/phpcs.xml @@ -0,0 +1,20 @@ + + + PHPCS configuration file. + ../src + ./phpunit + + + */phpunit/*/resources/* + + src/functions.php + + + */phpunit/* + + + + */phpunit/* + + + diff --git a/dev/phpunit/bootstrap.php b/dev/phpunit/bootstrap.php index 4e08e746..29982e12 100644 --- a/dev/phpunit/bootstrap.php +++ b/dev/phpunit/bootstrap.php @@ -1,2 +1,3 @@ setName('analyse') - ->addArgument('project', InputArgument::REQUIRED, 'The path to the magento2 project') + ->addArgument( + 'project', + InputArgument::REQUIRED, + 'The path to the magento2 project' + ) ->addOption( 'auto-theme-update', 'a', InputOption::VALUE_OPTIONAL, 'Fuzz factor for automatically applying changes to local theme' ) - ->addOption('sort-by-type', null, InputOption::VALUE_NONE, 'Sort the output by override type') - ->addOption('phpstorm-threeway-diff-commands', null, InputOption::VALUE_NONE, 'Output phpstorm threeway diff commands') - ->addOption('vendor-namespaces', null, InputOption::VALUE_OPTIONAL, 'Only show custom modules with these namespaces (comma separated list)') - ->addOption('pad-table-columns', null, InputOption::VALUE_REQUIRED, 'Pad the table column width') - ->addOption('php-strict-errors', null, InputOption::VALUE_NONE, 'Any php errors/warnings/notices will throw an exception') - ->addOption('show-info', null, InputOption::VALUE_NONE, 'Show all INFO level reports') + ->addOption( + 'sort-by-type', + null, + InputOption::VALUE_NONE, + 'Sort the output by override type' + ) + ->addOption( + 'phpstorm-threeway-diff-commands', + null, + InputOption::VALUE_NONE, + 'Output phpstorm threeway diff commands' + ) + ->addOption( + 'vendor-namespaces', + null, + InputOption::VALUE_OPTIONAL, + 'Only show custom modules with these namespaces (comma separated list)' + ) + ->addOption( + 'pad-table-columns', + null, + InputOption::VALUE_REQUIRED, + 'Pad the table column width' + ) + ->addOption( + 'php-strict-errors', + null, + InputOption::VALUE_NONE, + 'Any php errors/warnings/notices will throw an exception' + ) + ->addOption( + 'show-info', + null, + InputOption::VALUE_NONE, + 'Show all INFO level reports' + ) ->setDescription('Analyse a magento2 project which has had a ./vendor.patch file manually created'); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, Output $output) { $exitCode = 0; if ($input->getOption('php-strict-errors')) { @@ -49,7 +86,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if (!(is_string($projectDir) && is_dir($projectDir))) { throw new \Exception("Invalid project directory specified"); } - $patchDiffFilePath = $projectDir . DIRECTORY_SEPARATOR . 'vendor.patch'; + $patchDiffFilePath = $projectDir . DS . 'vendor.patch'; if (!(is_string($patchDiffFilePath) && is_file($patchDiffFilePath))) { throw new \Exception("$patchDiffFilePath does not exist, see README.md"); } @@ -60,7 +97,10 @@ protected function execute(InputInterface $input, OutputInterface $output) } $vendorNamespaces = []; - if ($input->getOption('vendor-namespaces') && $vendorNamespaces = $input->getOption('vendor-namespaces')) { + if ( + $input->getOption('vendor-namespaces') && + $vendorNamespaces = $input->getOption('vendor-namespaces') + ) { $vendorNamespaces = explode(',', str_replace(' ', '', $vendorNamespaces)); } @@ -71,7 +111,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $magento2 = new Helper\Magento2Instance($projectDir); foreach ($magento2->getBootErrors() as $bootError) { - $output->writeln( + $errOutput->writeln( sprintf( 'Magento boot error, could not work out db schema files: %s %s', $bootError->getMessage(), @@ -80,9 +120,9 @@ protected function execute(InputInterface $input, OutputInterface $output) ); $exitCode = 2; } - $output->writeln('Magento has been instantiated', OutputInterface::VERBOSITY_VERBOSE); + $output->writeln('Magento has been instantiated', Output::VERBOSITY_VERBOSE); $patchFile = new Patchfile\Reader($patchDiffFilePath); - $output->writeln('Patch file has been parsed', OutputInterface::VERBOSITY_VERBOSE); + $output->writeln('Patch file has been parsed', Output::VERBOSITY_VERBOSE); $pluginPatchExceptions = []; $threeWayDiff = []; @@ -90,18 +130,20 @@ protected function execute(InputInterface $input, OutputInterface $output) $patchFilesToOutput = []; $patchFiles = $patchFile->getFiles(); if (empty($patchFiles)) { - $errOutput->writeln("The patch file could not be parsed, are you sure its a unified diff? "); + $errOutput->writeln( + "The patch file could not be parsed, are you sure its a unified diff? " + ); return 1; } foreach ($patchFiles as $patchFile) { $file = $patchFile->getPath(); try { - $patchOverrideValidator = new PatchOverrideValidator($magento2, $patchFile); + $patchOverrideValidator = new Validator($magento2, $patchFile); if (!$patchOverrideValidator->canValidate()) { - $output->writeln("Skipping $file", OutputInterface::VERBOSITY_VERY_VERBOSE); + $output->writeln("Skipping $file", Output::VERBOSITY_VERBOSE); continue; } - $output->writeln("Validating $file", OutputInterface::VERBOSITY_VERBOSE); + $output->writeln("Validating $file", Output::VERBOSITY_VERBOSE); $patchOverrideValidator->validate($vendorNamespaces); if ($patchOverrideValidator->hasWarnings()) { @@ -112,27 +154,35 @@ protected function execute(InputInterface $input, OutputInterface $output) } foreach ($patchOverrideValidator->getWarnings() as $warnType => $warnings) { foreach ($warnings as $warning) { - $summaryOutputData[] = [PatchOverrideValidator::LEVEL_WARN, $warnType, $file, ltrim(str_replace(realpath($projectDir), '', $warning), '/')]; - if ($warnType === PatchOverrideValidator::TYPE_FILE_OVERRIDE && $autoApplyThemeFuzz) { + $summaryOutputData[] + = [Validator::LEVEL_WARN, $warnType, $file, sanitize_filepath($projectDir, $warning)]; + if ($warnType === Validator::TYPE_FILE_OVERRIDE && $autoApplyThemeFuzz) { $patchFile->applyToTheme($projectDir, $warning, $autoApplyThemeFuzz); } } } foreach ($patchOverrideValidator->getInfos() as $infoType => $infos) { foreach ($infos as $info) { - $summaryOutputData[] = [PatchOverrideValidator::LEVEL_INFO, $infoType, $file, ltrim(str_replace(realpath($projectDir), '', $info), '/')]; + $summaryOutputData[] + = [Validator::LEVEL_INFO, $infoType, $file, sanitize_filepath($projectDir, $info)]; } } if ($input->getOption('phpstorm-threeway-diff-commands')) { $threeWayDiff = array_merge($threeWayDiff, $patchOverrideValidator->getThreeWayDiffData()); } } catch (VirtualTypeException $e) { - $output->writeln("Could not understand $file: {$e->getMessage()}", OutputInterface::VERBOSITY_VERY_VERBOSE); + $output->writeln( + "Could not understand $file: {$e->getMessage()}", + Output::VERBOSITY_VERBOSE + ); } catch (\InvalidArgumentException $e) { if ($input->getOption('php-strict-errors')) { throw $e; } - $output->writeln("Could not understand $file: {$e->getMessage()}", OutputInterface::VERBOSITY_VERY_VERBOSE); + $output->writeln( + "Could not understand $file: {$e->getMessage()}", + Output::VERBOSITY_VERBOSE + ); } catch (PluginDetectionException $e) { if ($input->getOption('php-strict-errors')) { throw $e; @@ -142,14 +192,14 @@ protected function execute(InputInterface $input, OutputInterface $output) } $infoLevelCount = count(array_filter($summaryOutputData, function ($row) { - return $row[0] === PatchOverrideValidator::LEVEL_INFO; + return $row[0] === Validator::LEVEL_INFO; })); $warnLevelCount = count(array_filter($summaryOutputData, function ($row) { - return $row[0] === PatchOverrideValidator::LEVEL_WARN; + return $row[0] === Validator::LEVEL_WARN; })); if (!$input->getOption('show-info')) { $summaryOutputData = array_filter($summaryOutputData, function ($row) { - return $row[0] !== PatchOverrideValidator::LEVEL_INFO; + return $row[0] !== Validator::LEVEL_INFO; }); } @@ -182,15 +232,18 @@ protected function execute(InputInterface $input, OutputInterface $output) } if (!empty($pluginPatchExceptions)) { - $errOutput->writeln("Could not detect plugins for the following files", OutputInterface::VERBOSITY_NORMAL); + $errOutput->writeln("Could not detect plugins for the following files"); $logicExceptionsPatchString = ''; foreach ($pluginPatchExceptions as $logicExceptionData) { $logicExceptionsPatchString .= $logicExceptionData['patch'] . PHP_EOL; - $errOutput->writeln("{$logicExceptionData['message']}", OutputInterface::VERBOSITY_NORMAL); + $errOutput->writeln("{$logicExceptionData['message']}"); } - $vendorFilesErrorPatchFile = rtrim($projectDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'vendor_files_error.patch'; + $vendorFilesErrorPatchFile = rtrim($projectDir, DS) . DS . 'vendor_files_error.patch'; file_put_contents($vendorFilesErrorPatchFile, $logicExceptionsPatchString); - $errOutput->writeln("Please raise a github issue with the above error information and the contents of $vendorFilesErrorPatchFile" . PHP_EOL); + $errOutput->writeln( + "Please raise a github issue with the above" . + " error information and the contents of $vendorFilesErrorPatchFile" . PHP_EOL + ); } $outputTable = new Table($output); @@ -201,21 +254,27 @@ protected function execute(InputInterface $input, OutputInterface $output) if (!empty($threeWayDiff)) { $output->writeln("Outputting diff commands below"); foreach ($threeWayDiff as $outputDatum) { - $output->writeln("phpstorm diff {$outputDatum[0]} {$outputDatum[1]} {$outputDatum[2]}"); + $output->writeln( + "phpstorm diff {$outputDatum[0]} {$outputDatum[1]} {$outputDatum[2]}" + ); } } $countToCheck = count($summaryOutputData); - $newPatchFilePath = rtrim($projectDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'vendor_files_to_check.patch'; + $newPatchFilePath = rtrim($projectDir, DS) . DS . 'vendor_files_to_check.patch'; $output->writeln("WARN count: $warnLevelCount"); $infoMessage = "INFO count: $infoLevelCount"; - if (!$input->getOption('show-info') && $infoLevelCount >=0) { + if (!$input->getOption('show-info') && $infoLevelCount >= 0) { $infoMessage .= " (to view re-run this tool with --show-info)"; } $output->writeln("$infoMessage"); - $output->writeln("For docs on each check see https://github.com/AmpersandHQ/ampersand-magento2-upgrade-patch-helper/blob/master/docs/CHECKS_AVAILABLE.md"); - $output->writeln("You should review the above $countToCheck items alongside $newPatchFilePath"); + $output->writeln( + "For docs on each check see " . self::DOCS_URL . "" + ); + $output->writeln( + "You should review the above $countToCheck items alongside $newPatchFilePath" + ); file_put_contents($newPatchFilePath, implode(PHP_EOL, $patchFilesToOutput)); return $exitCode; diff --git a/src/Ampersand/PatchHelper/Exception/PluginDetectionException.php b/src/Ampersand/PatchHelper/Exception/PluginDetectionException.php index aec95b99..efd410f3 100644 --- a/src/Ampersand/PatchHelper/Exception/PluginDetectionException.php +++ b/src/Ampersand/PatchHelper/Exception/PluginDetectionException.php @@ -1,4 +1,5 @@ getArea()) { case Area::AREA_FRONTEND: $this->customFrontendThemes[] = $theme; - break; + break; case Area::AREA_ADMINHTML: $this->customAdminThemes[] = $theme; - break; + break; } } @@ -107,7 +108,7 @@ public function __construct($path) // List of modules and their relative paths foreach ($objectManager->get(\Magento\Framework\Module\FullModuleList::class)->getNames() as $moduleName) { $dir = $objectManager->get(\Magento\Framework\Module\Dir::class)->getDir($moduleName); - $dir = ltrim(str_replace($dirList->getRoot(), '', $dir), '/') . '/'; + $dir = sanitize_filepath($dirList->getRoot(), $dir) . '/'; $this->listOfPathsToModules[$dir] = $moduleName; } @@ -115,7 +116,7 @@ public function __construct($path) $componentRegistrar = $objectManager->get(ComponentRegistrar::class); foreach ($componentRegistrar->getPaths(ComponentRegistrar::LIBRARY) as $lib => $libPath) { - $libPath = ltrim(str_replace($dirList->getRoot(), '', $libPath), '/') . '/'; + $libPath = sanitize_filepath($dirList->getRoot(), $libPath) . '/'; $this->listOfPathsToLibrarys[$libPath] = $lib; } } @@ -183,7 +184,7 @@ private function prepareDbSchemaXmlData() $tableName = (string) $table->attributes()->name; $tablesAndTheirSchemas[$tableName][] = [ - 'file' => ltrim(str_replace($rootDir, '', $dbSchemaFile), '/'), + 'file' => sanitize_filepath($rootDir, $dbSchemaFile), 'definition' => $tableXml, 'is_primary' => (str_contains(strtolower($tableXml), 'xsi:type="primary"')) ]; diff --git a/src/Ampersand/PatchHelper/Helper/PatchOverrideValidator.php b/src/Ampersand/PatchHelper/Helper/PatchOverrideValidator.php index ea8f10e7..e4493b88 100644 --- a/src/Ampersand/PatchHelper/Helper/PatchOverrideValidator.php +++ b/src/Ampersand/PatchHelper/Helper/PatchOverrideValidator.php @@ -7,20 +7,20 @@ class PatchOverrideValidator { - const LEVEL_INFO = 'INFO'; - const LEVEL_WARN = 'WARN'; - - const TYPE_PREFERENCE = 'Preference'; - const TYPE_METHOD_PLUGIN = 'Plugin'; - const TYPE_FILE_OVERRIDE = 'Override (phtml/js/html)'; - const TYPE_LAYOUT_OVERRIDE = 'Override/extended (layout xml)'; - const TYPE_QUEUE_CONSUMER_ADDED = 'Queue consumer added'; - const TYPE_QUEUE_CONSUMER_REMOVED = 'Queue consumer removed'; - const TYPE_QUEUE_CONSUMER_CHANGED = 'Queue consumer changed'; - const TYPE_DB_SCHEMA_ADDED = 'DB schema added'; - const TYPE_DB_SCHEMA_CHANGED = 'DB schema changed'; - const TYPE_DB_SCHEMA_REMOVED = 'DB schema removed'; - const TYPE_DB_SCHEMA_TARGET_CHANGED = 'DB schema target changed'; + public const LEVEL_INFO = 'INFO'; + public const LEVEL_WARN = 'WARN'; + + public const TYPE_PREFERENCE = 'Preference'; + public const TYPE_METHOD_PLUGIN = 'Plugin'; + public const TYPE_FILE_OVERRIDE = 'Override (phtml/js/html)'; + public const TYPE_LAYOUT_OVERRIDE = 'Override/extended (layout xml)'; + public const TYPE_QUEUE_CONSUMER_ADDED = 'Queue consumer added'; + public const TYPE_QUEUE_CONSUMER_REMOVED = 'Queue consumer removed'; + public const TYPE_QUEUE_CONSUMER_CHANGED = 'Queue consumer changed'; + public const TYPE_DB_SCHEMA_ADDED = 'DB schema added'; + public const TYPE_DB_SCHEMA_CHANGED = 'DB schema changed'; + public const TYPE_DB_SCHEMA_REMOVED = 'DB schema removed'; + public const TYPE_DB_SCHEMA_TARGET_CHANGED = 'DB schema target changed'; /** * @var string @@ -253,7 +253,7 @@ public function getThreeWayDiffData() list($toCheckFileOrClass, ) = explode(':', $toCheckFileOrClass); $toCheckFileOrClass = $this->getFilenameFromPhpClass($toCheckFileOrClass); } - $toCheckFileOrClass = ltrim(str_replace(realpath($projectDir), '', $toCheckFileOrClass), '/'); + $toCheckFileOrClass = sanitize_filepath($projectDir, $toCheckFileOrClass); $threeWayCompareVals = [$this->vendorFilepath, $toCheckFileOrClass, $this->origVendorPath]; $threeWayDiffData[md5(\serialize($threeWayCompareVals))] = $threeWayCompareVals; } @@ -332,9 +332,11 @@ private function validatePhpFileForPlugins($vendorNamespaces = []) $pluginClass = $pluginConf['instance']; $pluginClass = ltrim($pluginClass, '\\'); - if (!class_exists($pluginClass) && + if ( + !class_exists($pluginClass) && isset($areaConfig[$area][$pluginClass]['type']) && - class_exists($areaConfig[$area][$pluginClass]['type'])) { + class_exists($areaConfig[$area][$pluginClass]['type']) + ) { /* * The class doesn't exist but there is another reference to it in the area config * This is very likely a virtual type @@ -342,7 +344,8 @@ class_exists($areaConfig[$area][$pluginClass]['type'])) { * In our test case it is like this * * $pluginClass = somethingVirtualPlugin - * $areaConfig['global']['somethingVirtualPlugin']['type'] = Ampersand\Test\Block\Plugin\OrderViewHistoryPlugin + * $areaConfig['global']['somethingVirtualPlugin']['type'] = + * Ampersand\Test\Block\Plugin\OrderViewHistoryPlugin */ $pluginClass = $areaConfig[$area][$pluginClass]['type']; } @@ -514,18 +517,23 @@ private function validateFrontendFile($type) */ $path = $this->m2->getMinificationResolver()->resolve($type, $name, $area, $theme, null, $module); if (!is_file($path)) { - throw new \InvalidArgumentException("Could not resolve $file (attempted to resolve to $path) using the minification resolver"); + throw new \InvalidArgumentException( + "Could not resolve $file (attempted to resolve to $path) using the minification resolver" + ); } } catch (\Exception $exception) { $path = $this->m2->getSimpleResolver()->resolve($type, $name, $area, $theme, null, $module); if (!is_file($path)) { - throw new \InvalidArgumentException("Could not resolve $file (attempted to resolve to $path) using the simple resolver"); + throw new \InvalidArgumentException( + "Could not resolve $file (attempted to resolve to $path) using the simple resolver" + ); } } if ($path && strpos($path, '/vendor/magento/') === false) { // don't output the exact same file more than once - // (can happen when you have multiple custom theme inheritance and when you don't overwrite a certain file in the deepest theme) + // (can happen when you have multiple custom theme inheritance and when you don't overwrite a certain + // file in the deepest theme) if (!in_array($path, $this->warnings[self::TYPE_FILE_OVERRIDE], true)) { if (!str_ends_with($path, $this->vendorFilepath)) { $this->warnings[self::TYPE_FILE_OVERRIDE][] = $path; @@ -549,23 +557,26 @@ private function validateWebTemplateHtml() */ $templatePart = ltrim(preg_replace('#^.+/web/templates?/#i', '', $file), '/'); - $potentialOverrides = array_filter($this->m2->getListOfHtmlFiles(), function ($potentialFilePath) use ($module, $templatePart) { - $validFile = true; + $potentialOverrides = array_filter( + $this->m2->getListOfHtmlFiles(), + function ($potentialFilePath) use ($module, $templatePart) { + $validFile = true; - if (!str_ends_with($potentialFilePath, $templatePart)) { - // This is not the same file name as our layout file - $validFile = false; - } - if (!str_contains($potentialFilePath, $module)) { - // This file path does not contain the module name, so not an override - $validFile = false; - } - if (str_contains($potentialFilePath, 'vendor/magento/')) { - // This file path is a magento core override, not looking at core<->core modifications - $validFile = false; + if (!str_ends_with($potentialFilePath, $templatePart)) { + // This is not the same file name as our layout file + $validFile = false; + } + if (!str_contains($potentialFilePath, $module)) { + // This file path does not contain the module name, so not an override + $validFile = false; + } + if (str_contains($potentialFilePath, 'vendor/magento/')) { + // This file path is a magento core override, not looking at core<->core modifications + $validFile = false; + } + return $validFile; } - return $validFile; - }); + ); foreach ($potentialOverrides as $override) { if (!str_ends_with($override, $this->vendorFilepath)) { @@ -585,23 +596,26 @@ private function validateEmailTemplateHtml() $templatePart = ltrim(substr($file, stripos($file, '/email/')), '/'); - $potentialOverrides = array_filter($this->m2->getListOfHtmlFiles(), function ($potentialFilePath) use ($module, $templatePart) { - $validFile = true; + $potentialOverrides = array_filter( + $this->m2->getListOfHtmlFiles(), + function ($potentialFilePath) use ($module, $templatePart) { + $validFile = true; - if (!str_ends_with($potentialFilePath, $templatePart)) { - // This is not the same file name as our layout file - $validFile = false; - } - if (!str_contains($potentialFilePath, $module)) { - // This file path does not contain the module name, so not an override - $validFile = false; - } - if (str_contains($potentialFilePath, 'vendor/magento/')) { - // This file path is a magento core override, not looking at core<->core modifications - $validFile = false; + if (!str_ends_with($potentialFilePath, $templatePart)) { + // This is not the same file name as our layout file + $validFile = false; + } + if (!str_contains($potentialFilePath, $module)) { + // This file path does not contain the module name, so not an override + $validFile = false; + } + if (str_contains($potentialFilePath, 'vendor/magento/')) { + // This file path is a magento core override, not looking at core<->core modifications + $validFile = false; + } + return $validFile; } - return $validFile; - }); + ); foreach ($potentialOverrides as $override) { if (!str_ends_with($override, $this->vendorFilepath)) { @@ -688,7 +702,8 @@ private function validateDbSchemaFile() if ( empty($this->infos[self::TYPE_DB_SCHEMA_CHANGED]) && empty($this->infos[self::TYPE_DB_SCHEMA_ADDED]) && - empty($this->infos[self::TYPE_DB_SCHEMA_REMOVED])) { + empty($this->infos[self::TYPE_DB_SCHEMA_REMOVED]) + ) { throw new \InvalidArgumentException("$vendorFile could not work out db schema changes for this diff"); } @@ -713,7 +728,10 @@ private function validateDbSchemaFile() if ($primaryTableToFile[$tableName] === $this->vendorFilepath) { $primaryDefinitionsInThisFile[$tableName] = $tableName; } - if ($primaryTableToFile[$tableName] !== $this->vendorFilepath && !str_starts_with($this->vendorFilepath, 'vendor/magento/')) { + if ( + $primaryTableToFile[$tableName] !== $this->vendorFilepath + && !str_starts_with($this->vendorFilepath, 'vendor/magento/') + ) { $this->warnings[$dbSchemaType][$tableName] = $tableName; unset($this->infos[$dbSchemaType][$tableName]); } @@ -738,7 +756,8 @@ private function validateDbSchemaFile() continue; } foreach ($dbSchemaAlterations[$primaryTableBeingModified] as $thirdPartyDbSchemaModifyingTable) { - $this->warnings[self::TYPE_DB_SCHEMA_TARGET_CHANGED][] = "$thirdPartyDbSchemaModifyingTable ($primaryTableBeingModified)"; + $this->warnings[self::TYPE_DB_SCHEMA_TARGET_CHANGED][] + = "$thirdPartyDbSchemaModifyingTable ($primaryTableBeingModified)"; } } unset($primaryTableBeingModified, $thirdPartyDbSchemaModifyingTable); @@ -759,27 +778,30 @@ private function validateLayoutFile() $layoutFile = end($parts); - $potentialOverrides = array_filter($this->m2->getListOfXmlFiles(), function ($potentialFilePath) use ($module, $area, $layoutFile) { - $validFile = true; + $potentialOverrides = array_filter( + $this->m2->getListOfXmlFiles(), + function ($potentialFilePath) use ($module, $area, $layoutFile) { + $validFile = true; - if (!str_contains($potentialFilePath, $area)) { - // This is not in the same area - $validFile = false; - } - if (!str_ends_with($potentialFilePath, $layoutFile)) { - // This is not the same file name as our layout file - $validFile = false; - } - if (!str_contains($potentialFilePath, $module)) { - // This file path does not contain the module name, so not an override - $validFile = false; - } - if (str_contains($potentialFilePath, 'vendor/magento/')) { - // This file path is a magento core override, not looking at core<->core modifications - $validFile = false; + if (!str_contains($potentialFilePath, $area)) { + // This is not in the same area + $validFile = false; + } + if (!str_ends_with($potentialFilePath, $layoutFile)) { + // This is not the same file name as our layout file + $validFile = false; + } + if (!str_contains($potentialFilePath, $module)) { + // This file path does not contain the module name, so not an override + $validFile = false; + } + if (str_contains($potentialFilePath, 'vendor/magento/')) { + // This file path is a magento core override, not looking at core<->core modifications + $validFile = false; + } + return $validFile; } - return $validFile; - }); + ); foreach ($potentialOverrides as $override) { if (!str_ends_with($override, $this->vendorFilepath)) { diff --git a/src/Ampersand/PatchHelper/Patchfile/Entry.php b/src/Ampersand/PatchHelper/Patchfile/Entry.php index 4c514302..61028f1d 100644 --- a/src/Ampersand/PatchHelper/Patchfile/Entry.php +++ b/src/Ampersand/PatchHelper/Patchfile/Entry.php @@ -1,4 +1,5 @@ lines, function ($line) { - return !((strlen($line)>12 && substr($line, 0, 2) === '\ ')); + return !((strlen($line) > 12 && substr($line, 0, 2) === '\ ')); }); $hunks = []; @@ -251,7 +254,9 @@ private function getAffectedFunction($lineNumber, $fileContents, $expectedLineCo $actualLine = $fileContents[$lineNumber - 1]; if (strcmp($expectedLineContents, $actualLine) !== 0) { - throw new PluginDetectionException("$this->newFilePath - on line $lineNumber - $expectedLineContents does not equal $actualLine"); + throw new PluginDetectionException( + "$this->newFilePath - on line $lineNumber - $expectedLineContents does not equal $actualLine" + ); } return $this->scanAboveForFunctionDeclaration($fileContents, $lineNumber - 1); @@ -282,7 +287,7 @@ private function scanAboveForFunctionDeclaration($fileContents, $lineNumber) } } - for ($i=$lineNumber; $i>=0; $i--) { + for ($i = $lineNumber; $i >= 0; $i--) { $potentialFunctionDeclaration = trim($fileContents[$i]); if (str_contains($potentialFunctionDeclaration, 'function')) { foreach ($phpLinesToSkip as $lineToSkip) { @@ -322,7 +327,7 @@ public function __toString() public function applyToTheme($projectDir, $overrideFile, $fuzzFactor) { - $overrideFilePathRelative = ltrim(str_replace($projectDir, '', $overrideFile), '/'); + $overrideFilePathRelative = sanitize_filepath($projectDir, $overrideFile); if (substr($overrideFilePathRelative, 0, 7) === "vendor/") { return; // Only attempt to patch local files not vendor overrides which will be in .gitignore diff --git a/src/Ampersand/PatchHelper/Patchfile/Reader.php b/src/Ampersand/PatchHelper/Patchfile/Reader.php index fc5670b5..168c4b3f 100644 --- a/src/Ampersand/PatchHelper/Patchfile/Reader.php +++ b/src/Ampersand/PatchHelper/Patchfile/Reader.php @@ -1,4 +1,5 @@