diff --git a/src/EnvironmentSetCommand.php b/src/EnvironmentSetCommand.php index 5f53c38..a6128f6 100644 --- a/src/EnvironmentSetCommand.php +++ b/src/EnvironmentSetCommand.php @@ -2,6 +2,7 @@ namespace ImLiam\EnvironmentSetCommand; +use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\App; use Illuminate\Support\Str; @@ -76,10 +77,16 @@ public function handle(): void */ public function setEnvVariable(string $envFileContent, string $key, string $value): array { - // For existed key. + // For existing key. $oldKeyValuePair = $this->readKeyValuePair($envFileContent, $key); + if ($oldKeyValuePair !== null) { - return [str_replace($oldKeyValuePair, $key . '=' . $value, $envFileContent), false]; + $historyString = $this->getHistoryString($oldKeyValuePair); + + $oldKeyValuePair = preg_quote($oldKeyValuePair); + $updatedContent = preg_replace("/^{$oldKeyValuePair}[^\r\n]*/m", $historyString . $key . '=' . $value, $envFileContent); + + return [$updatedContent, false]; } // For a new key. @@ -182,4 +189,22 @@ protected function writeFile(string $path, string $contents): bool { return (bool)file_put_contents($path, $contents, LOCK_EX); } + + /** + * Add history to a file. + * + * @param string $keyValuePair + * + * @return string + */ + public function getHistoryString(string $oldKeyValuePair = null): string + { + if (!env('ENVSET_HISTORY', false) || $oldKeyValuePair === null) { + return ''; + } + + $date = Carbon::now()->format('Y-m-d H:i:s'); + + return "# {$oldKeyValuePair} # Edited: {$date}\n"; + } } diff --git a/tests/Unit/EnvironmentSetCommandTest.php b/tests/Unit/EnvironmentSetCommandTest.php index 1b25eb5..42ad38c 100644 --- a/tests/Unit/EnvironmentSetCommandTest.php +++ b/tests/Unit/EnvironmentSetCommandTest.php @@ -2,6 +2,7 @@ namespace Tests\Unit; +use Carbon\Carbon; use ImLiam\EnvironmentSetCommand\EnvironmentSetCommand; use InvalidArgumentException; use PHPUnit\Framework\TestCase; @@ -85,6 +86,25 @@ public function testAssertKeyIsValid(string $key, bool $isGood): void $this->assertTrue($this->command->assertKeyIsValid($key)); } + /** + * @covers EnvironmentSetCommand::getHistoryString + */ + public function testHistoryString(): void + { + $this->assertEquals('', $this->command->getHistoryString('old_key=old_value')); + + putenv('ENVSET_HISTORY=true'); + + Carbon::setTestNow('2020-01-01 12:00:00'); + + $this->assertEquals( + "# old_key=old_value # Edited: 2020-01-01 12:00:00\n", + $this->command->getHistoryString('old_key=old_value') + ); + + putenv('ENVSET_HISTORY'); + } + /** * @return array * @see EnvironmentSetCommandTest::testSetEnvVariable