Skip to content

Commit

Permalink
Merge pull request #35 from JackieDo/1.0
Browse files Browse the repository at this point in the history
Add new feature
  • Loading branch information
JackieDo authored Apr 12, 2020
2 parents 189ec00 + 1c5d480 commit 519f4c1
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 50 deletions.
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ php:
- 5.4
- 5.5
- 5.6
- 7.1
- 7.2
- 7.3

before_script:
- travis_retry composer self-update
Expand Down
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,20 +64,25 @@ $ composer update

> **Note:** Instead of performing the above two steps, it may be faster to use the command line `$ composer require jackiedo/dotenv-editor:1.*`.
- Once the update operation completes, the third step is to add the service provider. Open `config/app.php`, and add a new item to the providers array:
Since Laravel 5.5, [service providers and aliases are automatically registered](https://laravel.com/docs/5.5/packages#package-discovery). But if you are using Laravel 5.4 or earlier, you must perform these two steps:

- The third step is to register the service provider. Open `config/app.php`, and add a new item to the providers array:

```php
...
'providers' => array(
'providers' => [
...
Jackiedo\DotenvEditor\DotenvEditorServiceProvider::class,
),
],
```

- The next step is to add the following line to the section `aliases` in the file `config/app.php`:
- The fourth step is to register the facade. Add the following line to the section `aliases` in the file `config/app.php`:

```php
'DotenvEditor' => Jackiedo\DotenvEditor\Facades\DotenvEditor::class,
'aliases' => [
...
'DotenvEditor' => Jackiedo\DotenvEditor\Facades\DotenvEditor::class,
],
```

## Configuration
Expand All @@ -95,6 +100,9 @@ The option `autoBackup` determines if your orignal file will be backed up before
#### Backup location
The option `backupPath` specifies where your file is backed up to. This value is a sub path (sub-folder) from the root folder of the project application.

#### Always create backup folder
The option `alwaysCreateBackupFolder` specifies always creating a backup directory, whether or not the backup is performed.

## Usage

#### Working with facade
Expand Down
98 changes: 65 additions & 33 deletions src/Jackiedo/DotenvEditor/DotenvEditor.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,29 +90,27 @@ class DotenvEditor
*/
public function __construct(Container $app, Config $config)
{
$this->app = $app;
$this->config = $config;
$this->formatter = new DotenvFormatter;
$this->reader = new DotenvReader($this->formatter);
$this->writer = new DotenvWriter($this->formatter);

$backupPath = $this->config->get('dotenv-editor.backupPath');
$this->app = $app;
$this->config = $config;
$this->formatter = new DotenvFormatter;
$this->reader = new DotenvReader($this->formatter);
$this->writer = new DotenvWriter($this->formatter);
$this->autoBackup = $this->config->get('dotenv-editor.autoBackup', true);
$this->backupPath = $this->config->get('dotenv-editor.backupPath');

if (is_null($backupPath)) {
if (is_null($this->backupPath)) {
if (function_exists('base_path')) {
$backupPath = base_path('storage/dotenv-editor/backups/');
$this->backupPath = base_path('storage/dotenv-editor/backups/');
} else {
$backupPath = __DIR__.'/../../../../../../storage/dotenv-editor/backups/';
$this->backupPath = __DIR__.'/../../../../../../storage/dotenv-editor/backups/';
}
}

if (!is_dir($backupPath)) {
mkdir($backupPath, 0777, true);
copy(__DIR__ . '/../../stubs/gitignore.txt', $backupPath . '../.gitignore');
}
$this->backupPath = rtrim($this->backupPath, '\\/') . '/';

$this->backupPath = $backupPath;
$this->autoBackup = $this->config->get('dotenv-editor.autoBackup', true);
if ($this->config->get('dotenv-editor.alwaysCreateBackupFolder', false)) {
$this->createBackupFolder();
}

$this->load();
}
Expand Down Expand Up @@ -144,12 +142,15 @@ public function load($filePath = null, $restoreIfNotFound = false, $restorePath

if (file_exists($this->filePath)) {
$this->writer->setBuffer($this->getContent());

return $this;
} elseif ($restoreIfNotFound) {
}

if ($restoreIfNotFound) {
return $this->restore($restorePath);
} else {
return $this;
}

return $this;
}

/**
Expand All @@ -160,10 +161,24 @@ public function load($filePath = null, $restoreIfNotFound = false, $restorePath
protected function resetContent()
{
$this->filePath = null;

$this->reader->load(null);
$this->writer->setBuffer(null);
}

/**
* Create backup folder if not exists
*
* @return void
*/
protected function createBackupFolder()
{
if (! is_dir($this->backupPath)) {
mkdir($this->backupPath, 0777, true);
copy(__DIR__ . '/../../stubs/gitignore.txt', $this->backupPath . '../.gitignore');
}
}

/*
|--------------------------------------------------------------------------
| Working with reading
Expand Down Expand Up @@ -212,6 +227,7 @@ public function getKeys($keys = [])
if (!empty($keys)) {
return in_array($key, $keys);
}

return true;
}, ARRAY_FILTER_USE_KEY);
}
Expand All @@ -226,10 +242,8 @@ public function getKeys($keys = [])
public function keyExists($key)
{
$allKeys = $this->getKeys();
if (array_key_exists($key, $allKeys)) {
return true;
}
return false;

return array_key_exists($key, $allKeys);
}

/**
Expand All @@ -244,9 +258,11 @@ public function keyExists($key)
public function getValue($key)
{
$allKeys = $this->getKeys([$key]);

if (array_key_exists($key, $allKeys)) {
return $allKeys[$key]['value'];
}

throw new KeyNotFoundException('Requested key not found in your file.');
}

Expand Down Expand Up @@ -284,17 +300,21 @@ public function getBuffer()
public function addEmpty()
{
$this->writer->appendEmptyLine();

return $this;
}

/**
* Add comment line to buffer
*
* @param object
*
* @return DotenvEditor
*/
public function addComment($comment)
{
$this->writer->appendCommentLine($comment);

return $this;
}

Expand All @@ -319,6 +339,7 @@ public function setKeys($data)
} else {
$oldInfo = $this->getKeys([$key]);
$comment = is_null($comment) ? $oldInfo[$key]['comment'] : $comment;

$this->writer->updateSetter($key, $value, $comment, $export);
}
}
Expand Down Expand Up @@ -386,6 +407,7 @@ public function save()
}

$this->writer->save($this->filePath);

return $this;
}

Expand Down Expand Up @@ -414,6 +436,7 @@ public function save()
public function autoBackup($on = true)
{
$this->autoBackup = $on;

return $this;
}

Expand All @@ -426,9 +449,13 @@ public function backup()
{
if (!is_file($this->filePath)) {
throw new FileNotFoundException("File does not exist at path {$this->filePath}");

return false;
}

// Make sure the backup directory exists
$this->createBackupFolder();

copy(
$this->filePath,
$this->backupPath . self::BACKUP_FILENAME_PREFIX . date('Y_m_d_His') . self::BACKUP_FILENAME_SUFFIX
Expand All @@ -444,23 +471,23 @@ public function backup()
*/
public function getBackups()
{
$filenameRegex = '/^' .preg_quote(self::BACKUP_FILENAME_PREFIX, '/'). '(\d{4})_(\d{2})_(\d{2})_(\d{2})(\d{2})(\d{2})' .preg_quote(self::BACKUP_FILENAME_SUFFIX, '/'). '$/';
$backups = array_filter(array_diff(scandir($this->backupPath), array('..', '.')), function($backup) use ($filenameRegex) {
return preg_match($filenameRegex, $backup);
});
$output = [];

foreach ($backups as $backup) {
if (! is_dir($this->backupPath)) {
return $output;
}

$datetime = preg_replace($filenameRegex, '$1-$2-$3 $4:$5:$6', $backup);
$filenameRegex = '/^' .preg_quote(self::BACKUP_FILENAME_PREFIX, '/'). '(\d{4})_(\d{2})_(\d{2})_(\d{2})(\d{2})(\d{2})' .preg_quote(self::BACKUP_FILENAME_SUFFIX, '/'). '$/';
$backups = array_filter(array_diff(scandir($this->backupPath), array('..', '.')), function($backup) use ($filenameRegex) {
return preg_match($filenameRegex, $backup);
});

$data = [
foreach ($backups as $backup) {
$output[] = [
'filename' => $backup,
'filepath' => $this->backupPath . $backup,
'created_at' => $datetime,
'created_at' => preg_replace($filenameRegex, '$1-$2-$3 $4:$5:$6', $backup)
];

$output[] = $data;
}

return $output;
Expand All @@ -480,8 +507,10 @@ public function getLatestBackup()
}

$latestBackup = 0;

foreach ($backups as $backup) {
$timestamp = strtotime($backup['created_at']);

if ($timestamp > $latestBackup) {
$latestBackup = $timestamp;
}
Expand Down Expand Up @@ -511,9 +540,11 @@ public function restore($filePath = null)
{
if (is_null($filePath)) {
$latestBackup = $this->getLatestBackup();

if (is_null($latestBackup)) {
throw new NoBackupAvailableException("There are no available backups!");
}

$filePath = $latestBackup['filepath'];
}

Expand All @@ -538,6 +569,7 @@ public function deleteBackups($filePaths = [])
{
if (empty($filePaths)) {
$allBackups = $this->getBackups();

foreach ($allBackups as $backup) {
$filePaths[] = $backup['filepath'];
}
Expand Down
9 changes: 5 additions & 4 deletions src/Jackiedo/DotenvEditor/DotenvFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ public function formatSetterLine($key, $value = null, $comment = null, $export =
$key = $this->formatKey($key);
$comment = $this->formatComment($comment);
$export = $export ? 'export ' : '';

$line = "{$export}{$key}={$value}{$comment}";
$line = "{$export}{$key}={$value}{$comment}";

return $line;
}
Expand Down Expand Up @@ -109,6 +108,7 @@ public function normaliseValue($value, $quote = '')

$value = str_replace("\\$quote", $quote, $value);
$value = str_replace('\\\\', '\\', $value);

return $value;
}

Expand Down Expand Up @@ -179,11 +179,10 @@ public function parseLine($line)
$value = preg_replace($regexPattern, '$1', $data);
$extant = preg_replace($regexPattern, '$2', $data);

$value = $this->normaliseValue($value, $quote);
$value = $this->normaliseValue($value, $quote);
$comment = ($this->isComment($extant)) ? $this->normaliseComment($extant) : '';
} else {
$parts = explode(' #', $data, 2);

$value = $this->normaliseValue($parts[0]);
$comment = (isset($parts[1])) ? $this->normaliseComment($parts[1]) : '';

Expand Down Expand Up @@ -252,9 +251,11 @@ protected function looksLikeSetter($line)
protected function isExportKey($key)
{
$pattern = '/^export\h.*$/';

if (preg_match($pattern, trim($key))) {
return true;
}

return false;
}

Expand Down
2 changes: 2 additions & 0 deletions src/Jackiedo/DotenvEditor/DotenvReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public function __construct(DotenvFormatterContract $formatter)
public function load($filePath)
{
$this->filePath = $filePath;

return $this;
}

Expand Down Expand Up @@ -110,6 +111,7 @@ public function keys()

foreach ($lines as $row => $line) {
$data = $this->formatter->parseLine($line);

if ($data['type'] == 'setter') {
$content[$data['key']] = [
'line' => $row+1,
Expand Down
11 changes: 4 additions & 7 deletions src/Jackiedo/DotenvEditor/DotenvWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,8 @@ protected function ensureFileIsWritable($filePath)
*/
public function setBuffer($content)
{
if ($content !== '' && substr($content, -1) !== PHP_EOL) {
$content .= PHP_EOL;
}
$this->buffer = trim($content) . PHP_EOL;

$this->buffer = $content;
return $this;
}

Expand Down Expand Up @@ -142,8 +139,8 @@ public function appendSetter($key, $value = null, $comment = null, $export = fal
*/
public function updateSetter($key, $value = null, $comment = null, $export = false)
{
$pattern = "/^(export\h)?\h*{$key}=.*/m";
$line = $this->formatter->formatSetterLine($key, $value, $comment, $export);
$pattern = "/^(export\h)?\h*{$key}=.*/m";
$line = $this->formatter->formatSetterLine($key, $value, $comment, $export);
$this->buffer = preg_replace_callback($pattern, function () use ($line) {
return $line;
}, $this->buffer);
Expand All @@ -160,7 +157,7 @@ public function updateSetter($key, $value = null, $comment = null, $export = fal
*/
public function deleteSetter($key)
{
$pattern = "/^(export\h)?\h*{$key}=.*\n/m";
$pattern = "/^(export\h)?\h*{$key}=.*\n/m";
$this->buffer = preg_replace($pattern, null, $this->buffer);

return $this;
Expand Down
Loading

0 comments on commit 519f4c1

Please sign in to comment.