Skip to content

Commit

Permalink
set backup count and clear old backups
Browse files Browse the repository at this point in the history
  • Loading branch information
iRaziul committed Feb 4, 2024
1 parent 19a1d21 commit 65681e1
Showing 1 changed file with 60 additions and 9 deletions.
69 changes: 60 additions & 9 deletions src/DotEnvEditor.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ class DotEnvEditor

protected ?string $backupDirectory = null;

protected int $backupCount = 5;

/**
* DotEnvEditor constructor.
*
Expand Down Expand Up @@ -51,6 +53,29 @@ public function setBackupDir(string $dir): self
return $this;
}

/**
* Path to the backup directory
*/
public function backupDir(): string
{
if ($this->backupDirectory) {
return rtrim($this->backupDirectory, '/');
}

// default to the same directory as the .env file
return dirname($this->envFilePath);
}

/**
* Set the number of backups to keep
*/
public function setBackupCount(int $count): self
{
$this->backupCount = $count;

return $this;
}

/**
* Load the .env file
*/
Expand Down Expand Up @@ -165,6 +190,32 @@ private function parseEnv(string $rawData): array
return $env;
}

/**
* Clear old backups
*/
public function clearOldBackups(): void
{
if (! $this->backupDirectory) {
return;
}

$backups = glob($this->backupDir().'/*');

if (count($backups) < $this->backupCount) {
return;
}

// sort by last modified
usort($backups, fn ($a, $b) => filemtime($b) - filemtime($a));

// keep latest backups
array_splice($backups, $this->backupCount);

foreach ($backups as $backup) {
unlink($backup);
}
}

/**
* Keep a backup of the .env file
*/
Expand All @@ -174,15 +225,15 @@ private function keepBackup(): void
return;
}

if (! $this->backupDirectory) {
$path = $this->envFilePath;
} else {
$path = rtrim($this->backupDirectory, '/').'/'.basename($this->envFilePath);
}

copy(
$this->envFilePath,
$path.'.'.date('Y-m-d-H-i-s')
$path = sprintf(
'%s/%s.%s',
$this->backupDir(),
basename($this->envFilePath),
date('Y-m-d-H-i-s')
);

copy($this->envFilePath, $path);

$this->clearOldBackups();
}
}

0 comments on commit 65681e1

Please sign in to comment.