Skip to content

Record historic values #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
29 changes: 27 additions & 2 deletions src/EnvironmentSetCommand.php
Original file line number Diff line number Diff line change
@@ -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";
}
}
20 changes: 20 additions & 0 deletions tests/Unit/EnvironmentSetCommandTest.php
Original file line number Diff line number Diff line change
@@ -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