diff --git a/src/command_functions.php b/src/command_functions.php index a881426fb..da9252d60 100644 --- a/src/command_functions.php +++ b/src/command_functions.php @@ -409,6 +409,57 @@ function initialiseConfig( return $config; } +function update_config_file(Config $config, string $config_file_path, string $baseline_path) : void +{ + if ($config->error_baseline === $baseline_path) { + return; + } + + $configFile = Config::locateConfigFile($config_file_path); + + if (!$configFile) { + fwrite(STDERR, "Don't forget to set errorBaseline=\"{$baseline_path}\" to your config."); + + return; + } + + $configFileContents = file_get_contents($configFile); + + if ($config->error_baseline) { + $amendedConfigFileContents = preg_replace( + '/errorBaseline=".*?"/', + "errorBaseline=\"{$baseline_path}\"", + $configFileContents + ); + } else { + $endPsalmOpenTag = strpos($configFileContents, '>', (int)strpos($configFileContents, '", + $endPsalmOpenTag, + 1 + ); + } else { + $amendedConfigFileContents = substr_replace( + $configFileContents, + " errorBaseline=\"{$baseline_path}\">", + $endPsalmOpenTag, + 1 + ); + } + } + + file_put_contents($configFile, $amendedConfigFileContents); + +} + function get_path_to_config(array $options): ?string { $path_to_config = isset($options['c']) && is_string($options['c']) ? realpath($options['c']) : null; diff --git a/src/psalm.php b/src/psalm.php index 61ccbd1dc..8d82ee303 100644 --- a/src/psalm.php +++ b/src/psalm.php @@ -548,39 +548,11 @@ if (isset($options['set-baseline']) && is_string($options['set-baseline'])) { fwrite(STDERR, "Baseline saved to {$options['set-baseline']}."); - /** @var string $configFile */ - $configFile = Config::locateConfigFile($path_to_config ?? $current_dir); - $configFileContents = $amendedConfigFileContents = file_get_contents($configFile); - - if ($config->error_baseline) { - $amendedConfigFileContents = preg_replace( - '/errorBaseline=".*?"/', - "errorBaseline=\"{$options['set-baseline']}\"", - $configFileContents - ); - } else { - $endPsalmOpenTag = strpos($configFileContents, '>', (int)strpos($configFileContents, '", - $endPsalmOpenTag, - 1 - ); - } else { - $amendedConfigFileContents = substr_replace( - $configFileContents, - " errorBaseline=\"{$options['set-baseline']}\">", - $endPsalmOpenTag, - 1 - ); - } - } - - file_put_contents($configFile, $amendedConfigFileContents); + update_config_file( + $config, + $path_to_config ?? $current_dir, + $options['set-baseline'] + ); fwrite(STDERR, PHP_EOL); }