From 77c2be7556cdcb2093006c449ba75e002bf9446e Mon Sep 17 00:00:00 2001 From: Rajab Natshah Date: Wed, 10 Jul 2019 21:36:33 +0300 Subject: [PATCH] Change the logic for composer project json url and use latest if it was listed in the update rule config #16 --- config/update-config.json | 12 +- scripts/update/update-varbase.sh | 4 +- scripts/update/update.php | 249 ++++++++------- scripts/update/varbase-updater.sh | 5 +- src/Commands/CommandsProvider.php | 26 +- src/Commands/RefactorComposerCommand.php | 310 ++++++++++++------- src/Commands/VersionCheckComposerCommand.php | 123 +++++--- src/Helpers/VersionHelper.php | 59 +++- src/Plugin/VarbaseUpdater.php | 186 ++++++----- 9 files changed, 611 insertions(+), 363 deletions(-) diff --git a/config/update-config.json b/config/update-config.json index b595b30..7f21181 100644 --- a/config/update-config.json +++ b/config/update-config.json @@ -1,7 +1,7 @@ { "profile": "varbase", "package": "vardot/varbase", - "8.4.*": { + "8.4.*": { "from": "8.4.*", "to": "8.4.28" }, @@ -29,6 +29,10 @@ }, "8.5.*": { "from": "8.5.*", + "to": "8.5.5" + }, + "8.5.5": { + "from": "8.5.5", "to": "8.6.3", "packages": { "crucial": { @@ -62,7 +66,7 @@ }, "8.7.*": { "from": "8.7.*", - "to": "8.7.*" - }, - "composer-project-json-url": "https://raw.githubusercontent.com/Vardot/varbase-project/8.7.x/composer.json" + "to": "8.7.*", + "composer-project-json-url": "latest" + } } diff --git a/scripts/update/update-varbase.sh b/scripts/update/update-varbase.sh index 71e5272..103a41d 100644 --- a/scripts/update/update-varbase.sh +++ b/scripts/update/update-varbase.sh @@ -1,5 +1,7 @@ #!/bin/bash +# Update Varbase + BASEDIR=$(pwd); echo "$(tput setaf 2)Checking composer version and updating if needed:$(tput sgr 0)"; @@ -7,5 +9,5 @@ composer self-update; echo "$(tput setaf 2)Checking varbase-updater version and updating if needed:$(tput sgr 0)"; composer update vardot/varbase-updater; -#running the updater; +# Running the updater. bash ${BASEDIR}/vendor/vardot/varbase-updater/scripts/update/varbase-updater.sh diff --git a/scripts/update/update.php b/scripts/update/update.php index 6abdf44..7a42661 100644 --- a/scripts/update/update.php +++ b/scripts/update/update.php @@ -1,136 +1,157 @@ "; - exit; - } +function get_file($url, $local_path, $newfilename) { + $err_msg = ''; + echo "Downloading $url"; + echo "\n"; + $out = fopen($local_path.$newfilename, "wrxb"); + if ($out == FALSE){ + print "File not opened.
"; + exit; + } - $ch = curl_init(); + $ch = curl_init(); - curl_setopt($ch, CURLOPT_FILE, $out); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); - curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_FILE, $out); + curl_setopt($ch, CURLOPT_HEADER, 0); + curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($ch, CURLOPT_URL, $url); - curl_exec($ch); + curl_exec($ch); - curl_close($ch); - //fclose($handle); + curl_close($ch); + //fclose($handle); -}//end function +} //end function -echo "Starting varbase-project updater!\n"; + echo "Starting varbase-project updater!\n"; -$path = getcwd()."/composer.json"; -if(!file_exists($path)){ - echo "\n"; - echo "Please run this command from your varbase-project root directory"; - echo "\n"; - exit; -} -$string = file_get_contents(getcwd()."/composer.json"); -$json=json_decode($string,true); - -if(isset($json["name"]) && $json["name"] != "vardot/varbase-project") { - echo "\n"; - echo "Please run this command from your varbase-project root directory"; - echo "\n"; - exit; -} + $path = getcwd()."/composer.json"; + if (!file_exists($path)) { + echo "\n"; + echo "Please run this command from your varbase-project root directory"; + echo "\n"; + exit; + } + $string = file_get_contents(getcwd()."/composer.json"); + $json=json_decode($string,true); -if(!isset($json["name"])){ - echo "\n"; - echo "Please run this command from your varbase-project root directory"; - echo "\n"; - exit; -} + if (isset($json["name"]) && $json["name"] != "vardot/varbase-project") { + echo "\n"; + echo "Please run this command from your varbase-project root directory"; + echo "\n"; + exit; + } -if(!isset($json["autoload"])){ - $json["autoload"] = [ - "psr-4" => [ + if (!isset($json["name"])) { + echo "\n"; + echo "Please run this command from your varbase-project root directory"; + echo "\n"; + exit; + } + + if (!isset($json["autoload"])) { + $json["autoload"] = [ + "psr-4" => [ + "Varbase\\composer\\" => "scripts/composer" + ] + ]; + } + else if(isset($json["autoload"]["psr-4"])) { + $json["autoload"]["psr-4"]["Varbase\\composer\\"] = "scripts/composer"; + } + else { + $json["autoload"]["psr-4"] = [ "Varbase\\composer\\" => "scripts/composer" - ] - ]; -}else if(isset($json["autoload"]["psr-4"])){ - $json["autoload"]["psr-4"]["Varbase\\composer\\"] = "scripts/composer"; -}else{ - $json["autoload"]["psr-4"] = [ - "Varbase\\composer\\" => "scripts/composer" - ]; -} - -if(!isset($json["scripts"])){ - $json["scripts"] = [ - "varbase-composer-generate" => [ + ]; + } + + if (!isset($json["scripts"])) { + $json["scripts"] = [ + "varbase-composer-generate" => [ + "Varbase\\composer\\VarbaseUpdate::generate" + ] + ]; + } + else if(isset($json["scripts"])) { + $json["scripts"]["varbase-composer-generate"]= [ "Varbase\\composer\\VarbaseUpdate::generate" - ] - ]; -}else if(isset($json["scripts"])){ - $json["scripts"]["varbase-composer-generate"]= [ - "Varbase\\composer\\VarbaseUpdate::generate" - ]; -} -$drupalPath = "docroot"; -if (file_exists(getcwd().'/web')) { - $drupalPath = "web"; -} - -echo "Drupal root set to " . $drupalPath . " if your Drupal root is different than this, please change install-path inside your composer.json under the 'extra' section.\n"; - -if(!isset($json["extra"])){ - $json["extra"] = [ - "install-path" => $drupalPath - ]; -}else{ - $json["extra"]["install-path"] = $drupalPath; -} - -$jsondata = json_encode($json, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); - - -if (!file_exists(getcwd().'/scripts/composer')) { + ]; + } + + $drupalPath = "docroot"; + if (file_exists(getcwd().'/web')) { + $drupalPath = "web"; + } + + echo "Drupal root set to " . $drupalPath . " if your Drupal root is different than this, please change install-path inside your composer.json under the 'extra' section.\n"; + + if (!isset($json["extra"])) { + $json["extra"] = [ + "install-path" => $drupalPath + ]; + } + else { + $json["extra"]["install-path"] = $drupalPath; + } + + $jsondata = json_encode($json, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); + + + if (!file_exists(getcwd().'/scripts/composer')) { mkdir(getcwd().'/scripts/composer', 0777, true); -} + } -if (!file_exists(getcwd().'/scripts/update')) { + if (!file_exists(getcwd().'/scripts/update')) { mkdir(getcwd().'/scripts/update', 0777, true); -} + } -if (!file_exists(getcwd().'/drush')) { + if (!file_exists(getcwd().'/drush')) { mkdir(getcwd().'/drush', 0777, true); -} + } -if (!file_exists(getcwd().'/bin')) { + if (!file_exists(getcwd().'/bin')) { mkdir(getcwd().'/bin', 0777, true); -} -$base_path = "https://raw.githubusercontent.com/Vardot/varbase-updater/master/"; -get_file($base_path . "scripts/composer/VarbaseUpdate.php", getcwd().'/scripts/composer/', 'VarbaseUpdate.php'); -get_file($base_path . "scripts/update/update-varbase.sh", getcwd().'/scripts/update/', 'update-varbase.sh'); -get_file($base_path . "scripts/update/version-check.php", getcwd().'/scripts/update/', 'version-check.php'); -get_file($base_path . "scripts/update/update-config.json", getcwd().'/scripts/update/', 'update-config.json'); -//only download them if they don't exist -if (!file_exists(getcwd().'/drush/policy.drush.inc')) { + } + + // Get the latest release for Varbase Updater. + $varbaseUpdaterLatestRelease = []; + $varbaseUpdaterJsonUrl = "https://api.github.com/repos/vardot/varbase-updater/releases/latest"; + $varbaseUpdaterFilename = uniqid(sys_get_temp_dir().'/') . ".json"; + get_file($varbaseUpdaterJsonUrl, $varbaseUpdaterFilename, $varbaseUpdaterFilename); + + if (file_exists($varbaseUpdaterFilename)) { + $varbaseUpdaterLatestRelease = JsonFile::parseJson(file_get_contents($varbaseUpdaterFilename), $varbaseUpdaterFilename); + } + + // Varbase Updater Latest release tag name. + $tagName = $varbaseUpdaterLatestRelease['tag_name']; + + $base_path = "https://raw.githubusercontent.com/vardot/varbase-updater/" . $tagName . "/"; + get_file($base_path . "scripts/composer/VarbaseUpdate.php", getcwd().'/scripts/composer/', 'VarbaseUpdate.php'); + get_file($base_path . "scripts/update/update-varbase.sh", getcwd().'/scripts/update/', 'update-varbase.sh'); + get_file($base_path . "scripts/update/version-check.php", getcwd().'/scripts/update/', 'version-check.php'); + get_file($base_path . "scripts/update/update-config.json", getcwd().'/scripts/update/', 'update-config.json'); + + // Only download them if they don't exist. + if (!file_exists(getcwd().'/drush/policy.drush.inc')) { get_file($base_path . "drush/policy.drush.inc", getcwd().'/drush/', 'policy.drush.inc'); -} -if (!file_exists(getcwd().'/drush/README.md')) { + } + + if (!file_exists(getcwd().'/drush/README.md')) { get_file($base_path . "drush/README.md", getcwd().'/drush/', 'README.md'); -} - -chmod(getcwd().'/scripts/update/update-varbase.sh', 0755); -chmod(getcwd().'/scripts/update/version-check.php', 0755); -chmod(getcwd().'/scripts/composer/VarbaseUpdate.php', 0755); - -if(file_put_contents($path, $jsondata)) { - echo "varbase-project successfully updated.\n"; - echo "Now you can run ./scripts/update/update-varbase.sh to update Varbase to the latest version.\n"; - echo "Enjoy!\n"; -}else{ - echo "Error while updating varbase-project.\n"; - echo ":(\n"; -} + } + + chmod(getcwd().'/scripts/update/update-varbase.sh', 0755); + chmod(getcwd().'/scripts/update/version-check.php', 0755); + chmod(getcwd().'/scripts/composer/VarbaseUpdate.php', 0755); + + if (file_put_contents($path, $jsondata)) { + echo "varbase-project successfully updated.\n"; + echo "Now you can run ./scripts/update/update-varbase.sh to update Varbase to the latest version.\n"; + echo "Enjoy!\n"; + } + else { + echo "Error while updating varbase-project.\n"; + echo ":(\n"; + } diff --git a/scripts/update/varbase-updater.sh b/scripts/update/varbase-updater.sh index f8d9df5..28285df 100644 --- a/scripts/update/varbase-updater.sh +++ b/scripts/update/varbase-updater.sh @@ -1,6 +1,9 @@ #!/bin/bash + +# Varbase Updater + function clear_stdin(){ - while read -e -t 1; do : ; done + while read -e -t 1; do : ; done } BASEDIR=$(pwd); diff --git a/src/Commands/CommandsProvider.php b/src/Commands/CommandsProvider.php index db90020..7d71bee 100644 --- a/src/Commands/CommandsProvider.php +++ b/src/Commands/CommandsProvider.php @@ -4,13 +4,21 @@ use Composer\Plugin\Capability\CommandProvider as CommandProviderCapability; -class CommandsProvider implements CommandProviderCapability -{ - public function getCommands() - { - return array( - new RefactorComposerCommand, - new VersionCheckComposerCommand - ); - } +/** + * Commands provider. + */ +class CommandsProvider implements CommandProviderCapability { + + /** + * Get Commands. + * + * @return type + */ + public function getCommands() { + return array ( + new RefactorComposerCommand, + new VersionCheckComposerCommand + ); + } + } diff --git a/src/Commands/RefactorComposerCommand.php b/src/Commands/RefactorComposerCommand.php index d5744a2..3b48964 100644 --- a/src/Commands/RefactorComposerCommand.php +++ b/src/Commands/RefactorComposerCommand.php @@ -32,21 +32,31 @@ use Composer\Util\ProcessExecutor; use vardot\Composer\Helpers\VersionHelper; +/** + * Refactor composer command. + */ class RefactorComposerCommand extends BaseCommand{ - protected function configure() - { + /** + * Configure. + */ + protected function configure() { $this->setName('varbase-refactor-composer'); $this->addArgument('file', InputArgument::REQUIRED, 'Where do you want to save the output'); $this->addArgument('drupal-path', InputArgument::REQUIRED, 'Drupal installation path'); } - protected function execute(InputInterface $input, OutputInterface $output) - { - $output->writeln('Refactoring composer.json'); - $path = $input->getArgument('file'); - $drupalPath = $input->getArgument('drupal-path'); - $this->generate($path, $drupalPath); + /** + * Execute. + * + * @param InputInterface $input + * @param OutputInterface $output + */ + protected function execute(InputInterface $input, OutputInterface $output) { + $output->writeln('Refactoring composer.json'); + $path = $input->getArgument('file'); + $drupalPath = $input->getArgument('drupal-path'); + $this->generate($path, $drupalPath); } /** @@ -62,6 +72,13 @@ protected function getDrupalRoot($project_root, $rootPath = "docroot") { return $project_root . '/' . $rootPath; } + /** + * Get Paths. + * + * @param type $package + * @param type $drupalPath + * @return string + */ protected function getPaths($package, $drupalPath = "docroot") { $paths = []; $projectExtras = $package->getExtra(); @@ -77,35 +94,43 @@ protected function getPaths($package, $drupalPath = "docroot") { $paths["librariesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/libraries/"; $paths["profilesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/profiles/"; - if(isset($projectExtras["installer-paths"])){ - foreach($projectExtras["installer-paths"] as $path => $types){ - foreach($types as $type){ - if($type == "type:drupal-module"){ + if (isset($projectExtras["installer-paths"])) { + foreach ($projectExtras["installer-paths"] as $path => $types) { + foreach ($types as $type) { + if ($type == "type:drupal-module") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["contribModulesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-custom-module"){ + + if ($type == "type:drupal-custom-module") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["customModulesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-theme"){ + + if ($type == "type:drupal-theme") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["contribThemesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-custom-theme"){ + + if ($type == "type:drupal-custom-theme") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["customThemesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-profile"){ + + if ($type == "type:drupal-profile") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["profilesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-library" || $type == "type:bower-asset" || $type == "type:npm-asset" ){ + + if ($type == "type:drupal-library" + || $type == "type:bower-asset" + || $type == "type:npm-asset" ) { + $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["librariesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; @@ -117,25 +142,44 @@ protected function getPaths($package, $drupalPath = "docroot") { return $paths; } + /** + * Array merge recursive distinct. + * + * @param array $array1 + * @param array $array2 + * @param type $drupalPath + * @return type + */ public function array_merge_recursive_distinct(array &$array1, array &$array2, $drupalPath){ $merged = $array1; foreach ($array2 as $key => &$value) { - $newKey = preg_replace('/{\$drupalPath}/', $drupalPath, $key); - $newKey = preg_replace('/docroot/', $drupalPath, $newKey); - if(!isset($merged[$newKey])){ - $merged[$newKey] = []; - } - if (is_array($value) && isset($merged[$newKey]) && is_array($merged[$newKey])) { - $merged[$newKey] = self::array_merge_recursive_distinct($merged[$newKey], $value, $drupalPath); - } else { - $newValue = preg_replace('/{\$drupalPath}/', $drupalPath, $value); - $newValue = preg_replace('/docroot/', $drupalPath, $newValue); - $merged[$newKey] = $newValue; - } + $newKey = preg_replace('/{\$drupalPath}/', $drupalPath, $key); + $newKey = preg_replace('/docroot/', $drupalPath, $newKey); + + if (!isset($merged[$newKey])) { + $merged[$newKey] = []; + } + + if (is_array($value) && isset($merged[$newKey]) && is_array($merged[$newKey])) { + $merged[$newKey] = self::array_merge_recursive_distinct($merged[$newKey], $value, $drupalPath); + } + else { + $newValue = preg_replace('/{\$drupalPath}/', $drupalPath, $value); + $newValue = preg_replace('/docroot/', $drupalPath, $newValue); + $merged[$newKey] = $newValue; + } } + return $merged; } + /** + * Generate. + * + * @param type $savePath + * @param type $drupalPath + * @return type + */ public function generate($savePath, $drupalPath) { $composer = $this->getComposer(); $latestProjectJsonPackage = null; @@ -155,9 +199,10 @@ public function generate($savePath, $drupalPath) { $updateConfigPath = $paths["pluginPath"] . "config/update-config.json"; $extraConfig = []; - if(file_exists($paths["composerPath"] . "update-config.json")){ + if (file_exists($paths["composerPath"] . "update-config.json")) { $extraConfig = json_decode(file_get_contents($paths["composerPath"] . "update-config.json"), TRUE); } + $updateConfig = json_decode(file_get_contents($updateConfigPath), TRUE); $error = json_last_error(); $updateConfig = array_replace_recursive($updateConfig, $extraConfig); @@ -168,39 +213,26 @@ public function generate($savePath, $drupalPath) { $hostname = parse_url($composerProjectJsonUrl, PHP_URL_HOST); $downloader->copy($hostname, $composerProjectJsonUrl, $filename, FALSE); - if(file_exists($filename)){ + if (file_exists($filename)) { $varbaseMetaData = JsonFile::parseJson(file_get_contents($filename), $filename); } $latestTags = VersionHelper::getLatestVersionInfo($varbaseMetaData); $versionInfo = VersionHelper::getVersionInfo($packages, $updateConfig, $latestTags); - $composerProjectJsonUrl = $updateConfig["composer-project-json-url"]; - $filename = uniqid(sys_get_temp_dir().'/') . ".json"; - $hostname = parse_url($composerProjectJsonUrl, PHP_URL_HOST); - $downloader->copy($hostname, $composerProjectJsonUrl, $filename, FALSE); - - if(file_exists($filename)){ - $latestProjectJsonConfig = JsonFile::parseJson(file_get_contents($filename), $filename); - $config = new Config(); - $config->merge($latestProjectJsonConfig); - $rootLoader = new RootPackageLoader($repositoryManager, $config); - $latestProjectJsonPackage = $rootLoader->load($latestProjectJsonConfig); - } - - if(!$versionInfo){ + if (!$versionInfo) { $continue = false; } - if(!isset($updateConfig['profile']) || !isset($updateConfig['package'])){ + if (!isset($updateConfig['profile']) || !isset($updateConfig['package'])) { $continue = false; } - if(!isset($versionInfo['next'])){ + if (!isset($versionInfo['next'])) { $continue = false; } - if(!$continue){ + if (!$continue) { $dumper = new ArrayDumper(); $json = $dumper->dump($projectPackage); $json["prefer-stable"] = true; @@ -209,8 +241,7 @@ public function generate($savePath, $drupalPath) { return; } - - if(isset($projectPackageExtras["patches"])){ + if (isset($projectPackageExtras["patches"])) { $projectPackagePatches = $projectPackageExtras["patches"]; } @@ -229,6 +260,47 @@ public function generate($savePath, $drupalPath) { foreach ($updateConfig as $key => $conf) { + + if (isset($conf["composer-project-json-url"])) { + if ($conf["composer-project-json-url"] == 'latest') { + + // Get the latest release for Varbase Updater. + $varbaseProjectTargetRelease = []; + $varbaseProjectTargetJsonUrl = "https://api.github.com/repos/vardot/varbase-project/releases/latest"; + $varbaseProjectTargetFilename = uniqid(sys_get_temp_dir().'/') . ".json"; + get_file($varbaseProjectTargetJsonUrl, $varbaseProjectTargetFilename, $varbaseProjectTargetFilename); + + if (file_exists($varbaseProjectTargetFilename)) { + $varbaseProjectTargetRelease = JsonFile::parseJson(file_get_contents($varbaseProjectTargetFilename), $varbaseProjectTargetFilename); + } + + // Varbase Project Latest release tag name. + $tagName = $varbaseProjectTargetRelease['tag_name']; + + $composerProjectJsonUrl = "https://raw.githubusercontent.com/vardot/varbase-project/" . $tagName . "/composer.json"; + } + else { + $composerProjectJsonUrl = "https://raw.githubusercontent.com/vardot/varbase-project/" . $conf["composer-project-json-url"] . "/composer.json"; + } + } + elseif (isset($conf['to'])) { + $tagNameInTo = str_replace("*","0", $conf['to']); + $composerProjectJsonUrl = "https://raw.githubusercontent.com/vardot/varbase-project/" . $tagNameInTo . "/composer.json"; + } + + $filename = uniqid(sys_get_temp_dir().'/') . ".json"; + $hostname = parse_url($composerProjectJsonUrl, PHP_URL_HOST); + $downloader->copy($hostname, $composerProjectJsonUrl, $filename, FALSE); + + if (file_exists($filename)) { + $latestProjectJsonConfig = JsonFile::parseJson(file_get_contents($filename), $filename); + $config = new Config(); + $config->merge($latestProjectJsonConfig); + $rootLoader = new RootPackageLoader($repositoryManager, $config); + $latestProjectJsonPackage = $rootLoader->load($latestProjectJsonConfig); + } + + if (isset($conf["from"]) && isset($conf["to"])) { $conf["from"] = preg_replace("/\*/", ".*", $conf["from"]); $conf["to"] = preg_replace("/\*/", ".*", $conf["to"]); @@ -240,10 +312,11 @@ public function generate($savePath, $drupalPath) { } } - if(preg_match('/' . $conf['to'] . '/', $profileVersion)){ + if (preg_match('/' . $conf['to'] . '/', $profileVersion)) { continue; } - if(preg_match('/' . $conf["from"] . '/', $profileVersion)){ + + if (preg_match('/' . $conf["from"] . '/', $profileVersion)) { $profileLinkConstraint = new Constraint(">=", $conf["to"]); $profileLinkConstraint->setPrettyString("~" . $conf["to"]); @@ -252,44 +325,47 @@ public function generate($savePath, $drupalPath) { $requiredPackageLinks = []; $requiredPackageLinks[$updateConfig['package']] = $profileLink; - if(isset($conf["packages"]["crucial"])){ + if (isset($conf["packages"]["crucial"])) { $crucialPackages = array_replace_recursive($crucialPackages, $conf["packages"]["crucial"]); } $enableAfterUpdatePath = $paths["pluginPath"] . "config/.enable-after-update"; - if(isset($conf["enable-after-update"])){ + if (isset($conf["enable-after-update"])) { $output = ""; foreach ($conf["enable-after-update"] as $key => $value) { $output .= $value . PHP_EOL; } file_put_contents($enableAfterUpdatePath, $output); - }else{ + } + else { file_put_contents($enableAfterUpdatePath, ""); } $skipUpdatePath = $paths["pluginPath"] . "config/.skip-update"; - if(isset($conf["skip"])){ + if (isset($conf["skip"])) { $output = ""; foreach ($conf["skip"] as $key => $value) { $output .= $value . PHP_EOL; } file_put_contents($skipUpdatePath, $output); - }else{ + } + else { file_put_contents($skipUpdatePath, ""); } - if(isset($conf["scripts"])){ + if (isset($conf["scripts"])) { $scripts = array_replace_recursive($scripts, $conf["scripts"]); } - if(isset($conf["repos"])){ + if (isset($conf["repos"])) { $repos = array_replace_recursive($repos, $conf["repos"]); } - if(isset($conf["extras"])){ + if (isset($conf["extras"])) { $extras = array_replace_recursive($extras, $conf["extras"]); } } - } elseif ($key == "all" && false){ - if(isset($conf["packages"]["crucial"])){ + } + elseif ($key == "all" && false) { + if (isset($conf["packages"]["crucial"])) { $crucialPackages = array_replace_recursive($crucialPackages, $conf["packages"]["crucial"]); } - if(isset($conf["enable-after-update"])){ + if (isset($conf["enable-after-update"])) { $output = ""; foreach ($conf["enable-after-update"] as $key => $value) { $output .= $value . PHP_EOL; @@ -297,7 +373,7 @@ public function generate($savePath, $drupalPath) { $enableAfterUpdatePath = $paths["pluginPath"] . "config/.enable-after-update"; file_put_contents($enableAfterUpdatePath, $output); } - if(isset($conf["skip"])){ + if (isset($conf["skip"])) { $output = ""; foreach ($conf["skip"] as $key => $value) { $output .= $value . PHP_EOL; @@ -305,13 +381,13 @@ public function generate($savePath, $drupalPath) { $skipUpdatePath = $paths["pluginPath"] . "config/.skip-update"; file_put_contents($skipUpdatePath, $output); } - if(isset($conf["scripts"])){ + if (isset($conf["scripts"])) { $scripts = array_replace_recursive($scripts, $conf["scripts"]); } - if(isset($conf["repos"])){ + if (isset($conf["repos"])) { $repos = array_replace_recursive($repos, $conf["repos"]); } - if(isset($conf["extras"])){ + if (isset($conf["extras"])) { $extras = array_replace_recursive($extras, $conf["extras"]); } } @@ -319,14 +395,18 @@ public function generate($savePath, $drupalPath) { foreach (glob($paths['contribModulesPath'] . "*/*.info.yml") as $file) { $yaml = Yaml::parse(file_get_contents($file)); - if(isset($yaml["project"]) && isset($yaml["version"]) && $yaml["project"] != $updateConfig['profile']){ + if (isset($yaml["project"]) + && isset($yaml["version"]) + && $yaml["project"] != $updateConfig['profile']) { + $composerRepo = "drupal"; $composerName = $composerRepo . "/" . $yaml["project"]; $composerVersion = str_replace("8.x-", "", $yaml["version"]); - if(isset($projectPackagePatches[$composerName])){ + if (isset($projectPackagePatches[$composerName])) { $requiredPackages[$composerName] = ["name"=> $composerName, "version" => $composerVersion, "patch" => true]; - }else if(!isset($profilePackageRequires[$composerName])){ + } + elseif (!isset($profilePackageRequires[$composerName])) { $requiredPackages[$composerName] = ["name"=> $composerName, "version" => $composerVersion]; } } @@ -334,11 +414,14 @@ public function generate($savePath, $drupalPath) { foreach (glob($paths['contribThemesPath'] . "*/*.info.yml") as $file) { $yaml = Yaml::parse(file_get_contents($file)); - if(isset($yaml["project"]) && isset($yaml["version"]) && $yaml["project"] != $updateConfig['profile']){ + if (isset($yaml["project"]) + && isset($yaml["version"]) + && $yaml["project"] != $updateConfig['profile']) { + $composerRepo = "drupal"; $composerName = $composerRepo . "/" . $yaml["project"]; $composerVersion = str_replace("8.x-", "", $yaml["version"]); - if(!isset($profilePackageRequires[$composerName])){ + if (!isset($profilePackageRequires[$composerName])) { $requiredPackages[$composerName] = ["name"=> $composerName, "version" => $composerVersion]; } } @@ -347,7 +430,7 @@ public function generate($savePath, $drupalPath) { foreach (glob($paths['contribModulesPath'] . "*/composer.json") as $file) { $pluginConfig = JsonFile::parseJson(file_get_contents($file), $file); - if(!isset($pluginConfig['version'])){ + if (!isset($pluginConfig['version'])) { $pluginConfig['version'] = "0.0.0"; } $pluginConfig = JsonFile::encode($pluginConfig); @@ -355,10 +438,10 @@ public function generate($savePath, $drupalPath) { $pluginPackageRequires = $pluginPackage->getRequires(); foreach ($requiredPackages as $name => $package) { - if(isset($projectPackagePatches[$name])){ + if (isset($projectPackagePatches[$name])) { continue; } - if(isset($pluginPackageRequires[$name])){ + if (isset($pluginPackageRequires[$name])) { unset($requiredPackages[$name]); } } @@ -366,7 +449,7 @@ public function generate($savePath, $drupalPath) { foreach (glob($paths['contribThemesPath'] . "*/composer.json") as $file) { $pluginConfig = JsonFile::parseJson(file_get_contents($file), $file); - if(!isset($pluginConfig['version'])){ + if (!isset($pluginConfig['version'])) { $pluginConfig['version'] = "0.0.0"; } $pluginConfig = JsonFile::encode($pluginConfig); @@ -374,16 +457,17 @@ public function generate($savePath, $drupalPath) { $pluginPackageRequires = $pluginPackage->getRequires(); foreach ($requiredPackages as $name => $package) { - if(isset($pluginPackageRequires[$name])){ + if (isset($pluginPackageRequires[$name])) { unset($requiredPackages[$name]); } } } foreach ($requiredPackages as $name => $package) { - if(isset($projectPackageRequires[$name])){ + if (isset($projectPackageRequires[$name])) { $requiredPackageLinks[$name] = $projectPackageRequires[$name]; - }else{ + } + else { $link = new Link($projectPackage->getName(), $package["name"], new Constraint(">=", $package["version"]), "", "^".$package["version"]); $requiredPackageLinks[$name] = $link; } @@ -400,7 +484,7 @@ public function generate($savePath, $drupalPath) { } } - if(!$projectPackageExtras){ + if (!$projectPackageExtras) { $projectPackageExtras = []; } @@ -408,7 +492,7 @@ public function generate($savePath, $drupalPath) { $mergedRepos = self::array_merge_recursive_distinct($projectPackageRepos, $repos, $paths["rootPath"]); $mergedScripts = self::array_merge_recursive_distinct($projectScripts, $scripts, $paths["rootPath"]); - if(!$latestProjectJsonPackage){ + if (!$latestProjectJsonPackage) { $projectPackage->setExtra($mergedExtras); $projectPackage->setRepositories($mergedRepos); $projectPackage->setRequires($requiredPackageLinks); @@ -419,8 +503,11 @@ public function generate($savePath, $drupalPath) { $json["prefer-stable"] = true; $json["extra"]["composer-exit-on-patch-failure"] = false; - //Fixing the position of installer path web/libraries/{$name} as it should be after slick and ace so it won't override them - if(isset($json["extra"]) && isset($json["extra"]["installer-paths"]) && isset($json["extra"]["installer-paths"][$paths["rootPath"].'/libraries/{$name}'])){ + // Fixing the position of installer path web/libraries/{$name} as it should be after slick and ace so it won't override them + if (isset($json["extra"]) + && isset($json["extra"]["installer-paths"]) + && isset($json["extra"]["installer-paths"][$paths["rootPath"].'/libraries/{$name}'])) { + $libsPathExtra = $json["extra"]["installer-paths"][$paths["rootPath"].'/libraries/{$name}']; unset($json["extra"]["installer-paths"][$paths["rootPath"].'/libraries/{$name}']); $extraLibsArray=[ @@ -429,35 +516,35 @@ public function generate($savePath, $drupalPath) { $json["extra"]["installer-paths"] = $json["extra"]["installer-paths"] + $extraLibsArray; } - if(isset($json["repositories"]["packagist.org"])){ + if (isset($json["repositories"]["packagist.org"])) { unset($json["repositories"]["packagist.org"]); } - if(isset($json["version"])){ + if (isset($json["version"])) { unset($json["version"]); } - if(isset($json["version_normalized"])){ + if (isset($json["version_normalized"])) { unset($json["version_normalized"]); } foreach ($json["repositories"] as $key => $value) { - if($key == "packagist.org"){ + if ($key == "packagist.org") { unset($json["repositories"][$key]); } - if( - isset($json["repositories"]["drupal"]) && - $key != "drupal" && - isset($value["url"]) && - $value["url"] == "https://packages.drupal.org/8" - ){ + if (isset($json["repositories"]["drupal"]) + && $key != "drupal" + && isset($value["url"]) + && $value["url"] == "https://packages.drupal.org/8") { + unset($json["repositories"][$key]); } } $projectConfig = JsonFile::encode($json); file_put_contents($savePath, $projectConfig); - }else{ + } + else { $latestExtras = $latestProjectJsonPackage->getExtra(); $latestRepos = $latestProjectJsonPackage->getRepositories(); $latestRequires = $latestProjectJsonPackage->getRequires(); @@ -466,11 +553,14 @@ public function generate($savePath, $drupalPath) { $latestMergedExtras = self::array_merge_recursive_distinct($mergedExtras, $latestExtras, $paths["rootPath"]); $latestMergedRepos = self::array_merge_recursive_distinct($mergedRepos, $latestRepos, $paths["rootPath"]); - //$latestMergedRequires = self::array_merge_recursive_distinct($requiredPackageLinks, $latestRequires, $paths["rootPath"]); + // $latestMergedRequires = self::array_merge_recursive_distinct($requiredPackageLinks, $latestRequires, $paths["rootPath"]); $latestMergedScripts = self::array_merge_recursive_distinct($mergedScripts, $latestScripts, $paths["rootPath"]); foreach ($latestRequires as $projectName => $projectPackageLink) { - if($projectName == $updateConfig['package']) continue; + if ($projectName == $updateConfig['package']) { + continue; + } + $requiredPackageLinks[$projectName] = $projectPackageLink; } @@ -490,8 +580,12 @@ public function generate($savePath, $drupalPath) { $json["prefer-stable"] = true; $json["extra"]["composer-exit-on-patch-failure"] = false; - //Fixing the position of installer path web/libraries/{$name} as it should be after slick and ace so it won't override them - if(isset($json["extra"]) && isset($json["extra"]["installer-paths"]) && isset($json["extra"]["installer-paths"][$paths["rootPath"].'/libraries/{$name}'])){ + // Fixing the position of installer path web/libraries/{$name} as it + // should be after slick and ace so it won't override them. + if (isset($json["extra"]) + && isset($json["extra"]["installer-paths"]) + && isset($json["extra"]["installer-paths"][$paths["rootPath"].'/libraries/{$name}'])) { + $libsPathExtra = $json["extra"]["installer-paths"][$paths["rootPath"].'/libraries/{$name}']; unset($json["extra"]["installer-paths"][$paths["rootPath"].'/libraries/{$name}']); $extraLibsArray=[ @@ -500,28 +594,28 @@ public function generate($savePath, $drupalPath) { $json["extra"]["installer-paths"] = $json["extra"]["installer-paths"] + $extraLibsArray; } - if(isset($json["repositories"]["packagist.org"])){ + if (isset($json["repositories"]["packagist.org"])) { unset($json["repositories"]["packagist.org"]); } - if(isset($json["version"])){ + if (isset($json["version"])) { unset($json["version"]); } - if(isset($json["version_normalized"])){ + if (isset($json["version_normalized"])) { unset($json["version_normalized"]); } foreach ($json["repositories"] as $key => $value) { - if($key == "packagist.org"){ + if ($key == "packagist.org"){ unset($json["repositories"][$key]); } - if( - isset($json["repositories"]["drupal"]) && - $key != "drupal" && - isset($value["url"]) && - $value["url"] == "https://packages.drupal.org/8" - ){ + + if (isset($json["repositories"]["drupal"]) + && $key != "drupal" + && isset($value["url"]) + && $value["url"] == "https://packages.drupal.org/8") { + unset($json["repositories"][$key]); } } diff --git a/src/Commands/VersionCheckComposerCommand.php b/src/Commands/VersionCheckComposerCommand.php index 8ecd430..4d1372a 100644 --- a/src/Commands/VersionCheckComposerCommand.php +++ b/src/Commands/VersionCheckComposerCommand.php @@ -30,18 +30,28 @@ use Composer\Util\ProcessExecutor; use vardot\Composer\Helpers\VersionHelper; -class VersionCheckComposerCommand extends BaseCommand{ +/** + * Version check composer command. + */ +class VersionCheckComposerCommand extends BaseCommand { - protected function configure() - { + /** + * Configure. + */ + protected function configure() { $this->setName('varbase-version-check'); $this->addArgument('type', InputArgument::REQUIRED, 'Version type'); } - protected function execute(InputInterface $input, OutputInterface $output) - { - $type = $input->getArgument('type'); - $this->getVersion($type); + /** + * Execute. + * + * @param InputInterface $input + * @param OutputInterface $output + */ + protected function execute(InputInterface $input, OutputInterface $output) { + $type = $input->getArgument('type'); + $this->getVersion($type); } /** @@ -57,6 +67,12 @@ protected function getDrupalRoot($project_root, $rootPath = "docroot") { return $project_root . '/' . $rootPath; } + /** + * Get Paths. + * + * @param type $package + * @return string + */ protected function getPaths($package) { $paths = []; $projectExtras = $package->getExtra(); @@ -65,9 +81,11 @@ protected function getPaths($package) { $paths["composerPath"] = $this->getDrupalRoot(getcwd(), ""); $paths["pluginPath"] = $this->getDrupalRoot($scriptPath, "../../"); $paths["rootPath"] = "docroot"; - if(isset($projectExtras["install-path"])){ + + if (isset($projectExtras["install-path"])) { $paths["rootPath"] = $projectExtras["install-path"]; } + $paths["contribModulesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/modules/contrib/"; $paths["customModulesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/modules/custom/"; $paths["contribThemesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/themes/contrib/"; @@ -75,35 +93,43 @@ protected function getPaths($package) { $paths["librariesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/libraries/"; $paths["profilesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/profiles/"; - if(isset($projectExtras["installer-paths"])){ - foreach($projectExtras["installer-paths"] as $path => $types){ - foreach($types as $type){ - if($type == "type:drupal-module"){ + if (isset($projectExtras["installer-paths"])) { + foreach ($projectExtras["installer-paths"] as $path => $types) { + foreach ($types as $type) { + if ($type == "type:drupal-module") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["contribModulesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-custom-module"){ + + if ($type == "type:drupal-custom-module") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["customModulesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-theme"){ + + if ($type == "type:drupal-theme") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["contribThemesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-custom-theme"){ + + if ($type == "type:drupal-custom-theme") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["customThemesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-profile"){ + + if ($type == "type:drupal-profile") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["profilesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-library" || $type == "type:bower-asset" || $type == "type:npm-asset" ){ + + if ($type == "type:drupal-library" + || $type == "type:bower-asset" + || $type == "type:npm-asset" ) { + $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["librariesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; @@ -115,23 +141,40 @@ protected function getPaths($package) { return $paths; } - public function array_merge_recursive_distinct(array &$array1, array &$array2, $drupalPath){ + /** + * Array merge recursive distinct. + * + * @param array $array1 + * @param array $array2 + * @param type $drupalPath + * @return type + */ + public function array_merge_recursive_distinct(array &$array1, array &$array2, $drupalPath) { $merged = $array1; foreach ($array2 as $key => &$value) { - $newKey = preg_replace('/{\$drupalPath}/', $drupalPath, $key); - if(!isset($merged[$newKey])){ - $merged[$newKey] = []; - } - if (is_array($value) && isset($merged[$newKey]) && is_array($merged[$newKey])) { - $merged[$newKey] = self::array_merge_recursive_distinct($merged[$newKey], $value, $drupalPath); - } else { - $newValue = preg_replace('/{\$drupalPath}/', $drupalPath, $value); - $merged[$newKey] = $newValue; - } + $newKey = preg_replace('/{\$drupalPath}/', $drupalPath, $key); + if (!isset($merged[$newKey])) { + $merged[$newKey] = []; + } + + if (is_array($value) && isset($merged[$newKey]) && is_array($merged[$newKey])) { + $merged[$newKey] = self::array_merge_recursive_distinct($merged[$newKey], $value, $drupalPath); + } + else { + $newValue = preg_replace('/{\$drupalPath}/', $drupalPath, $value); + $merged[$newKey] = $newValue; + } } return $merged; + } + /** + * Get version. + * + * @param type $type + * @return type + */ public function getVersion($type) { $composer = $this->getComposer(); $repositoryManager = $composer->getRepositoryManager(); @@ -141,9 +184,10 @@ public function getVersion($type) { $downloader = new RemoteFilesystem($this->getIO(), $this->getComposer()->getConfig()); $updateConfigPath = $paths["pluginPath"] . "config/update-config.json"; $extraConfig = []; - if(file_exists($paths["composerPath"] . "update-config.json")){ + if (file_exists($paths["composerPath"] . "update-config.json")) { $extraConfig = json_decode(file_get_contents($paths["composerPath"] . "update-config.json"), TRUE); } + $updateConfig = json_decode(file_get_contents($updateConfigPath), TRUE); $error = json_last_error(); $updateConfig = array_replace_recursive($updateConfig, $extraConfig); @@ -154,22 +198,23 @@ public function getVersion($type) { $hostname = parse_url($composerProjectJsonUrl, PHP_URL_HOST); $downloader->copy($hostname, $composerProjectJsonUrl, $filename, FALSE); - if(file_exists($filename)){ + if (file_exists($filename)) { $varbaseMetaData = JsonFile::parseJson(file_get_contents($filename), $filename); } $latestTags = VersionHelper::getLatestVersionInfo($varbaseMetaData); $versionInfo = VersionHelper::getVersionInfo($packages, $updateConfig, $latestTags); - if(!$versionInfo){ + if (!$versionInfo) { return; } - switch ($type){ + switch ($type) { case "composer-patches": - if(!defined('cweagans\Composer\PatchEvents::PATCH_APPLY_ERROR')){ + if (!defined('cweagans\Composer\PatchEvents::PATCH_APPLY_ERROR')) { exit(1); - }else{ + } + else { exit(0); } break; @@ -183,18 +228,20 @@ public function getVersion($type) { break; case "current-message": $profileName = $versionInfo["profileName"]; - if(isset($versionInfo['next'])){ + if (isset($versionInfo['next'])) { print "Updating $profileName (" . $versionInfo["current"] . ") to $profileName (" . $versionInfo["next"] . ")\n"; - }else{ + } + else { print "You are on the latest $profileName version. No updates are required.\n"; } break; case "next-message": $profileName = $versionInfo["profileName"]; - if(isset($versionInfo['next'])){ + if (isset($versionInfo['next'])) { print "You are on $profileName (" . $versionInfo["current"] . "). A newer version (" . $versionInfo["next"] . ") is now available.\n"; print "Please run: ./bin/update-varbase.sh to update to $profileName (" . $versionInfo["next"] . ").\n"; - }else{ + } + else { print "Congratulations! You are on the latest $profileName version now.\n"; } break; diff --git a/src/Helpers/VersionHelper.php b/src/Helpers/VersionHelper.php index 2e7d2cb..32b853d 100644 --- a/src/Helpers/VersionHelper.php +++ b/src/Helpers/VersionHelper.php @@ -2,30 +2,42 @@ namespace vardot\Composer\Helpers; -class VersionHelper{ +/** + * Version Helper. + */ +class VersionHelper { + + /** + * Get latest version info. + * + * @param type $metaData + * @return string|array + */ public static function getLatestVersionInfo($metaData) { $tags = []; $latestTags = []; $versionsArray = []; - if(isset($metaData["package"])){ + if (isset($metaData["package"])) { $versionsArray = $metaData["package"]["versions"]; - }else{ + } + else { return $latestTags; } - if($versionsArray && sizeof($versionsArray)){ + if ($versionsArray && sizeof($versionsArray)) { foreach ($versionsArray as $version => $meta) { - if(preg_match('/\d+\.\d+.\d+/', $version)){ + if (preg_match('/\d+\.\d+.\d+/', $version)) { $numbers = []; preg_match('/(\d+\.\d+).(\d+)/', $version, $numbers); - if(sizeof($numbers)){ + if (sizeof($numbers)) { $major = $numbers[1]; $minor = $numbers[2]; - if(isset($tags[$major])){ - if($tags[$major] < $minor){ + if (isset($tags[$major])) { + if($tags[$major] < $minor) { $tags[$major] = $minor; } - }else{ + } + else { $tags[$major] = $minor; } } @@ -40,21 +52,32 @@ public static function getLatestVersionInfo($metaData) { return $latestTags; } + /** + * Get Version Info. + * + * @param type $packages + * @param type $updateConfig + * @param type $latestVersions + * @return type + */ public static function getVersionInfo($packages, $updateConfig, $latestVersions) { $profile = null; if(!$updateConfig || !$packages){ return null; } + if(!isset($updateConfig['profile']) || !isset($updateConfig['package'])){ return null; } + foreach ($packages as $package) { - if($package->getName() == $updateConfig['package']){ + if ($package->getName() == $updateConfig['package']) { $profile = $package; break; } } - if(!$profile){ + + if (!$profile) { return null; } @@ -66,26 +89,30 @@ public static function getVersionInfo($packages, $updateConfig, $latestVersions) "profileName" => $profileName, "current" => $profileVersion ]; + foreach ($updateConfig as $key => $conf) { if (isset($conf["from"]) && isset($conf["to"])) { $conf["from"] = preg_replace("/\*/", ".*", $conf["from"]); $conf["to"] = preg_replace("/\*/", ".*", $conf["to"]); - foreach($latestVersions as $key => $value){ - if(preg_match('/' . $conf['to'] . '/', $key)){ + foreach ($latestVersions as $key => $value) { + if (preg_match('/' . $conf['to'] . '/', $key)){ $conf["to"] = $key; break; } } - - if(preg_match('/' . $conf['to'] . '/', $profileVersion)){ + + if (preg_match('/' . $conf['to'] . '/', $profileVersion)) { continue; } - if(preg_match('/' . $conf["from"] . '/', $profileVersion)){ + + if (preg_match('/' . $conf["from"] . '/', $profileVersion)) { $versionInfo["next"] = $conf["to"]; } } } + return $versionInfo; } + } diff --git a/src/Plugin/VarbaseUpdater.php b/src/Plugin/VarbaseUpdater.php index 6da59c5..5801205 100644 --- a/src/Plugin/VarbaseUpdater.php +++ b/src/Plugin/VarbaseUpdater.php @@ -26,8 +26,10 @@ use Composer\Util\RemoteFilesystem; use Composer\Util\ProcessExecutor; - -class VarbaseUpdater implements PluginInterface, EventSubscriberInterface, Capable{ +/** + * Varbase Updater. + */ +class VarbaseUpdater implements PluginInterface, EventSubscriberInterface, Capable { /** * @var Composer $composer @@ -40,29 +42,29 @@ class VarbaseUpdater implements PluginInterface, EventSubscriberInterface, Capab protected $io; /** - * Plugin activataion + * Plugin activate. * * @param Composer $composer * @param IOInterface $io */ - public function activate(Composer $composer, IOInterface $io) - { - $this->composer = $composer; - $this->io = $io; + public function activate(Composer $composer, IOInterface $io) { + $this->composer = $composer; + $this->io = $io; - if(!defined('cweagans\Composer\PatchEvents::PATCH_APPLY_ERROR')){ - $io->write("Please install composer-patches package from Vardot's repository to catch and handle errors when applying patches."); - } + if (!defined('cweagans\Composer\PatchEvents::PATCH_APPLY_ERROR')) { + $io->write("Please install composer-patches package from Vardot's repository to catch and handle errors when applying patches."); + } } /** + * Get subscribed events. + * * Returns an array of event names this subscriber wants to listen to. */ - public static function getSubscribedEvents() - { + public static function getSubscribedEvents() { $events = array(); - if(defined('cweagans\Composer\PatchEvents::PATCH_APPLY_ERROR')){ + if (defined('cweagans\Composer\PatchEvents::PATCH_APPLY_ERROR')) { $events[PatchEvents::PATCH_APPLY_ERROR] = array('handlePackagePatchError', 11); } @@ -71,18 +73,18 @@ public static function getSubscribedEvents() } /** + * Get Capabilities. + * * Return a list of plugin capabilities. * * @return array */ - public function getCapabilities() - { - return array( - 'Composer\Plugin\Capability\CommandProvider' => 'vardot\Composer\Commands\CommandsProvider' - ); + public function getCapabilities() { + return array( + 'Composer\Plugin\Capability\CommandProvider' => 'vardot\Composer\Commands\CommandsProvider' + ); } - /** * Get the Drupal root directory. * @@ -96,6 +98,12 @@ protected function getDrupalRoot($project_root, $rootPath = "docroot") { return $project_root . '/' . $rootPath; } + /** + * Get Paths. + * + * @param type $package + * @return string + */ protected function getPaths($package) { $paths = []; $projectExtras = $package->getExtra(); @@ -103,9 +111,11 @@ protected function getPaths($package) { $paths["composerPath"] = $this->getDrupalRoot(getcwd(), ""); $paths["pluginPath"] = $this->getDrupalRoot($scriptPath, "../../"); $paths["rootPath"] = "docroot"; - if(isset($projectExtras["install-path"])){ + + if (isset($projectExtras["install-path"])) { $paths["rootPath"] = $projectExtras["install-path"]; } + $paths["contribModulesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/modules/contrib/"; $paths["customModulesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/modules/custom/"; $paths["contribThemesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/themes/contrib/"; @@ -113,35 +123,43 @@ protected function getPaths($package) { $paths["librariesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/libraries/"; $paths["profilesPath"] = $this->getDrupalRoot(getcwd(), $paths["rootPath"]) . "/profiles/"; - if(isset($projectExtras["installer-paths"])){ - foreach($projectExtras["installer-paths"] as $path => $types){ - foreach($types as $type){ - if($type == "type:drupal-module"){ + if (isset($projectExtras["installer-paths"])) { + foreach ($projectExtras["installer-paths"] as $path => $types) { + foreach ($types as $type) { + if ($type == "type:drupal-module") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["contribModulesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-custom-module"){ + + if ($type == "type:drupal-custom-module") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["customModulesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-theme"){ + + if ($type == "type:drupal-theme") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["contribThemesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-custom-theme"){ + + if ($type == "type:drupal-custom-theme") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["customThemesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-profile"){ + + if ($type == "type:drupal-profile") { $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["profilesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; } - if($type == "type:drupal-library" || $type == "type:bower-asset" || $type == "type:npm-asset" ){ + + if ($type == "type:drupal-library" + || $type == "type:bower-asset" + || $type == "type:npm-asset" ) { + $typePath = preg_replace('/\{\$.*\}$/', "", $path); $paths["librariesPath"] = $this->getDrupalRoot(getcwd(), "") . $typePath; continue; @@ -162,16 +180,17 @@ protected function getPaths($package) { * * @todo Will this method ever get something other than an InstallOperation or UpdateOperation? */ - protected function getPackageFromOperation($operation) - { - if ($operation instanceof InstallOperation) { - $package = $operation->getPackage(); - } elseif ($operation instanceof UpdateOperation) { - $package = $operation->getTargetPackage(); - } else { - throw new \Exception('Unknown operation: ' . get_class($operation)); - } - return $package; + protected function getPackageFromOperation($operation) { + if ($operation instanceof InstallOperation) { + $package = $operation->getPackage(); + } + elseif ($operation instanceof UpdateOperation) { + $package = $operation->getTargetPackage(); + } + else { + throw new \Exception('Unknown operation: ' . get_class($operation)); + } + return $package; } /** @@ -189,9 +208,11 @@ protected function writePatchReport($packageName, $packagePath, $patchUrl, $desc } $reason = "Failed to apply patch"; - if($isApplied){ + + if ($isApplied) { $reason = "Patch already applied"; } + $output = "Patch: " . $patchUrl . "\n"; $output .= "\t Reason: " . $reason . "\n"; $output .= "\t Description: " . $description . "\n"; @@ -200,6 +221,11 @@ protected function writePatchReport($packageName, $packagePath, $patchUrl, $desc file_put_contents($logFile, $output, FILE_APPEND | LOCK_EX); } + /** + * Handle Package Patch Error. + * + * @param PatchEvent $event + */ public function handlePackagePatchError(PatchEvent $event) { $logPath = $this->getDrupalRoot(getcwd(), ""); @@ -222,7 +248,8 @@ public function handlePackagePatchError(PatchEvent $event) { if (file_exists($patchUrl)) { $filename = realpath($patchUrl); - } else { + } + else { // Generate random (but not cryptographically so) filename. $filename = uniqid(sys_get_temp_dir().'/') . ".patch"; @@ -262,7 +289,7 @@ public function handlePackagePatchError(PatchEvent $event) { } } - if($isApplied){ + if ($isApplied) { $io->write([ "Patch: " . $event->getUrl() . "", @@ -273,7 +300,7 @@ public function handlePackagePatchError(PatchEvent $event) { $answer = $io->ask("Would you like to remove it form your composer.json patches list? (yes)", "yes"); - if(preg_match("/yes/i", $answer)){ + if (preg_match("/yes/i", $answer)) { $io->write("Removing patch: " . $event->getUrl() . "", true); $patches = []; $patchesFile = ""; @@ -285,6 +312,7 @@ public function handlePackagePatchError(PatchEvent $event) { $patchesFile = file_get_contents($rootPackageExtras['patches-file']); $patchesFile = json_decode($patchesFile, TRUE); $error = json_last_error(); + if ($error != 0) { $io->write('There was an error reading the patches file.'); } @@ -292,25 +320,27 @@ public function handlePackagePatchError(PatchEvent $event) { if (isset($patchesFile['patches'])) { $patches = $patchesFile['patches']; } - }else{ + } + else { //shouldn't reach here! $io->write('Hmmm, no patches supplied!'); } $found = false; - if(isset($patches[$package->getName()])){ - foreach($patches[$package->getName()] as $key => $url){ - if($url == $event->getUrl()){ + if (isset($patches[$package->getName()])) { + foreach ($patches[$package->getName()] as $key => $url) { + if ($url == $event->getUrl()) { $found = true; unset($patches[$package->getName()][$key]); } } - if(!sizeof($patches[$package->getName()])){ + + if (!sizeof($patches[$package->getName()])) { unset($patches[$package->getName()]); } } - if($found){ + if ($found) { $io->write('Saving changes.'); if (isset($rootPackageExtras['patches'])) { $rootPackageExtras['patches'] = $patches; @@ -320,48 +350,56 @@ public function handlePackagePatchError(PatchEvent $event) { $json["prefer-stable"] = true; $json = json_encode($json, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); $rootFile = $this->getDrupalRoot(getcwd(), "") . "composer.json"; - if(file_put_contents($rootFile, $json)){ + + if (file_put_contents($rootFile, $json)) { $io->write('Root composer.json is saved successfully.'); - }else{ + } + else { $io->write('Couldn\'t save the root composer.json.'); self::writePatchReport($package->getName(), $installPath, $event->getUrl(), $event->getDescription(), $isApplied, $logPath); } - } elseif ($rootPackageExtras['patches-file']) { + } + elseif ($rootPackageExtras['patches-file']) { $patchesFile["patches"] = $patches; $patchesFile = json_encode($patchesFile, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); - if(file_put_contents($rootPackageExtras['patches-file'], $patchesFile)){ + if (file_put_contents($rootPackageExtras['patches-file'], $patchesFile)) { $io->write('Patches file is saved successfully.'); - }else{ + } + else { $io->write('Couldn\'t save the patches file.'); self::writePatchReport($package->getName(), $installPath, $event->getUrl(), $event->getDescription(), $isApplied, $logPath); } - } else { + } + else { //shouldn't reach here! $io->write("Can't save, no patches supplied!"); self::writePatchReport($package->getName(), $installPath, $event->getUrl(), $event->getDescription(), $isApplied, $logPath); } - }else{ + } + else { $io->write("Couldn't find the patch inside root composer.json or patches file, probably it's provided from dependencies?", true); $answer = $io->ask("Would you like to add this patch to the patches ignore list? (yes)", "yes"); - if(preg_match("/yes/i", $answer)){ + if (preg_match("/yes/i", $answer)) { foreach ($packages as $parentPackage) { $parentExtra = $parentPackage->getExtra(); if (isset($parentExtra['patches'])) { - if(isset($parentExtra['patches'][$package->getName()])){ - foreach($parentExtra['patches'][$package->getName()] as $key => $url){ - if($url == $event->getUrl()){ - if(isset($rootPackageExtras['patches-ignore'])) { - if(isset($rootPackageExtras['patches-ignore'][$parentPackage->getName()])){ - if(!isset($rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()])){ + if (isset($parentExtra['patches'][$package->getName()])) { + foreach ($parentExtra['patches'][$package->getName()] as $key => $url){ + if ($url == $event->getUrl()) { + if (isset($rootPackageExtras['patches-ignore'])) { + if (isset($rootPackageExtras['patches-ignore'][$parentPackage->getName()])) { + if (!isset($rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()])) { $rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()] = array(); $rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()][$key] = $url; - }elseif(isset($rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()])){ - if(!isset($rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()][$key])){ + } + elseif (isset($rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()])) { + if(!isset($rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()][$key])) { $rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()][$key] = $url; } } - }else{ + } + else { $rootPackageExtras['patches-ignore'][$parentPackage->getName()] = array(); $rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()] = array(); $rootPackageExtras['patches-ignore'][$parentPackage->getName()][$package->getName()][$key] = $url; @@ -379,23 +417,27 @@ public function handlePackagePatchError(PatchEvent $event) { $json["prefer-stable"] = true; $json = json_encode($json, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES); $rootFile = $this->getDrupalRoot(getcwd(), "") . "composer.json"; - if(file_put_contents($rootFile, $json)){ + if (file_put_contents($rootFile, $json)) { $io->write('Root composer.json is saved successfully.'); - }else{ + } + else { $io->write('Couldn\'t save the root composer.json.'); self::writePatchReport($package->getName(), $installPath, $event->getUrl(), $event->getDescription(), $isApplied, $logPath); } - }else{ + } + else { $io->write("Logging patch to the failed-patches.txt file instead of removing it.", true); self::writePatchReport($package->getName(), $installPath, $event->getUrl(), $event->getDescription(), $isApplied, $logPath); } } - }else{ - self::writePatchReport($package->getName(), $installPath, $event->getUrl(), $event->getDescription(), $isApplied, $logPath); } - }else{ + else { self::writePatchReport($package->getName(), $installPath, $event->getUrl(), $event->getDescription(), $isApplied, $logPath); + } + } + else{ + self::writePatchReport($package->getName(), $installPath, $event->getUrl(), $event->getDescription(), $isApplied, $logPath); } } }