Skip to content

Commit

Permalink
Adds intentioned package implementation, test and readme updates
Browse files Browse the repository at this point in the history
  • Loading branch information
mtolhuys committed Jul 20, 2019
1 parent decd052 commit fd7bf60
Show file tree
Hide file tree
Showing 9 changed files with 163 additions and 73 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

All notable changes to `laravel-env-scanner` will be documented in this file

## 1.0.0 - 201X-XX-XX
## 1.0.0 - 2019-07-20

- initial release
61 changes: 56 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
# Very short description of the package
# Laravel environmental variable scanner

[![Latest Version on Packagist](https://img.shields.io/packagist/v/mtolhuys/laravel-env-scanner.svg?style=flat-square)](https://packagist.org/packages/mtolhuys/laravel-env-scanner)
[![Build Status](https://img.shields.io/travis/mtolhuys/laravel-env-scanner/master.svg?style=flat-square)](https://travis-ci.org/mtolhuys/laravel-env-scanner)
[![Quality Score](https://img.shields.io/scrutinizer/g/mtolhuys/laravel-env-scanner.svg?style=flat-square)](https://scrutinizer-ci.com/g/mtolhuys/laravel-env-scanner)
[![Total Downloads](https://img.shields.io/packagist/dt/mtolhuys/laravel-env-scanner.svg?style=flat-square)](https://packagist.org/packages/mtolhuys/laravel-env-scanner)

This is where your description should go. Try and limit it to a paragraph or two, and maybe throw in a mention of what PSRs you support to avoid any confusion with users and contributors.
This package comes with a `LaravelEnvScanner` class and artisan command which you can use to scan any folder in your app for potential .env related problems.

Example output of the command:

```bash
$ php artisan env:scan
Scanning: laravel-app/config...
+--------------+----------------+---------------------------+-------------------+
| Files (1) | Has value (4) | Depending on default (1) | No value (2) |
+--------------+----------------+---------------------------+-------------------+
| database.php | DB_CONNECTION | - | - |
| - | - | - | DATABASE_URL |
| - | DB_DATABASE | - | - |
| - | - | DB_FOREIGN_KEYS | - |
| - | - | - | DATABASE_URL |
| - | DB_HOST | - | - |
| - | DB_PORT | - | - |
+--------------+----------------+---------------------------+-------------------+
```

## Installation

Expand All @@ -16,9 +34,41 @@ composer require mtolhuys/laravel-env-scanner
```

## Usage
You can call the artisan command to start the scan:

```bash
php artisan env:scan
```

Optionally you could specify a directory to run from:

```bash
php artisan env:scan -d app/Http/Controllers
```

``` php
// Usage description here
Additionally you can use the `LaravelEnvScanner` from anywhere you want:
```php
(new LaravelEnvScanner(__DIR__))->scan()->results;

// Or

$this->scanner = new LaravelEnvScanner(__DIR__);
$this->scanner->scan();
$this->scanner->results;

// Example results
[
"files" => 1
"empty" => 0
"has_value" => 1
"depending_on_default" => 0
"data" => [
0 => [
"filename" => "database.php"
"has_value" => "DB_HOST"
"depending_on_default" => "-"
"empty" => "-"
]
```

### Testing
Expand All @@ -37,12 +87,13 @@ Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

If you discover any security related issues, please email mtolhuys@hotmail.com instead of using the issue tracker.
If you discover any security related issues, please email mtolhuys@protonmail.com instead of using the issue tracker.

## Credits

- [Maarten Tolhuijs](https://github.com/mtolhuys)
- [All Contributors](../../contributors)
- [Beyond Code](https://github.com/beyondcode) For the [boilerplate](https://laravelpackageboilerplate.com/) and having me come up with the idea for this package.

## License

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"illuminate/support": "5.8.*"
},
"require-dev": {
"orchestra/testbench": "3.8.*",
"orchestra/testbench": "^3.5",
"phpunit/phpunit": "^7.0"
},
"autoload": {
Expand Down
8 changes: 0 additions & 8 deletions config/config.php

This file was deleted.

5 changes: 4 additions & 1 deletion phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@
<logging>
<log type="tap" target="build/report.tap"/>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-html" target="build/coverage" charset="UTF-8" yui="true" highlight="true"/>
<log type="coverage-html" target="build/coverage"/>
<log type="coverage-text" target="build/coverage.txt"/>
<log type="coverage-clover" target="build/logs/clover.xml"/>
</logging>
<php>
<env name="FILLED" value="filled" force="true" />
</php>
</phpunit>
39 changes: 18 additions & 21 deletions src/Commands/EnvScan.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ class EnvScan extends Command
*/
protected $signature = '
env:scan
{ --a|app : Include app folder }
{ --t|table : Show results data in a table }
{ --d|dir= : Specify directory to scan (defaults to your config folder) }
';

private $scanner;
Expand All @@ -26,7 +25,7 @@ class EnvScan extends Command
*
* @var string
*/
protected $description = 'Check all environmental variables used in config folder';
protected $description = 'Check environmental variables used in your app';

/**
* Execute the console command.
Expand All @@ -37,27 +36,25 @@ class EnvScan extends Command
public function handle()
{
$this->scanner = new LaravelEnvScanner(
$this->option('app')
$this->option('dir')
);

$this->scanner->scan();
if (! file_exists($this->scanner->dir)) {
$this->error("{$this->scanner->dir} does not exist");
exit();
}

$this->showResults();
}
$this->output->write(
"<fg=green>Scanning:</fg=green> <fg=white>{$this->scanner->dir}...</fg=white>\n"
);

private function showResults()
{
if ($this->option('table')) {
$this->table([
'File',
"Has value ({$this->scanner->results['has_value']})",
"Depending on default ({$this->scanner->results['depending_on_default']})",
"No value ({$this->scanner->results['empty']})",
], $this->scanner->results['data']);
} else {
$this->info("{$this->scanner->results['has_value']} have a value");
$this->line("{$this->scanner->results['depending_on_default']} are depending on default");
$this->warn("{$this->scanner->results['empty']} have no value");
}
$this->scanner->scan();

$this->table([
"Files ({$this->scanner->results['files']})",
"Has value ({$this->scanner->results['has_value']})",
"Depending on default ({$this->scanner->results['depending_on_default']})",
"No value ({$this->scanner->results['empty']})",
], $this->scanner->results['data']);
}
}
45 changes: 23 additions & 22 deletions src/LaravelEnvScanner.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class LaravelEnvScanner
* @var array
*/
public $results = [
'files' => 0,
'empty' => 0,
'has_value' => 0,
'depending_on_default' => 0,
Expand All @@ -28,16 +29,16 @@ class LaravelEnvScanner
private $currentFile;

/**
* If true
* combine all config files with files in app folder
* Root directory to start recursive search for env()'s from
* Defaults to config_path()
*
* @var bool
* @var string $dir
*/
private $includeAppFolder;
public $dir;

public function __construct($includeAppFolder = false)
public function __construct(string $dir = null)
{
$this->includeAppFolder = $includeAppFolder;
$this->dir = $dir ?? config_path();
}

/**
Expand All @@ -48,19 +49,11 @@ public function __construct($includeAppFolder = false)
*/
public function scan()
{
$files = $this->recursiveGlob(config_path(), '/.*?.php/');

if ($this->includeAppFolder) {
$files = array_merge(
$this->recursiveGlob(app_path(), '/.*?.php/'), $files
);
}
$files = $this->recursiveDirSearch($this->dir, '/.*?.php/');

foreach ($files as $file) {
$values = array_filter(
preg_split(
"#[\n]+#", shell_exec("tr -d '\n' < $file | grep -oP 'env\(\K[^)]+'")
)
preg_split("#[\n]+#", shell_exec("tr -d '\n' < $file | grep -oP 'env\(\K[^)]+'"))
);

foreach ($values as $value) {
Expand All @@ -71,6 +64,8 @@ public function scan()
$this->storeResult($file, $result);
}
}

return $this;
}

/**
Expand Down Expand Up @@ -105,10 +100,10 @@ private function storeResult(string $file, $result)
}

$this->results['data'][] = [
'File' => $this->getFilename($file),
'Has value' => $result->hasValue ? $result->envVar : '-',
'Depending on default' => !$result->hasValue && $result->hasDefault ? $result->envVar : '-',
'No value' => !$result->hasValue && !$result->hasDefault ? $result->envVar : '-',
'filename' => $this->getFilename($file),
'has_value' => $result->hasValue ? $result->envVar : '-',
'depending_on_default' => !$result->hasValue && $result->hasDefault ? $result->envVar : '-',
'empty' => !$result->hasValue && !$result->hasDefault ? $result->envVar : '-',
];
}

Expand All @@ -117,14 +112,20 @@ private function getFilename(string $file)
$basename = basename($file);

if ($this->currentFile === $basename) {
return '';
return '-';
}

$this->results['files']++;

return $this->currentFile = $basename;
}

private function recursiveGlob(string $folder, string $pattern): array
private function recursiveDirSearch(string $folder, string $pattern): array
{
if (! file_exists($folder)) {
return [];
}

$files = new RegexIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($folder)
Expand Down
60 changes: 60 additions & 0 deletions tests/EnvScanTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace Mtolhuys\LaravelEnvScanner\Tests;

use Mtolhuys\LaravelEnvScanner\LaravelEnvScanner;
use Orchestra\Testbench\TestCase;

class EnvScanTest extends TestCase
{
private $scanner;

/**
* EnvScanTest constructor.
* @param null $name
* @param array $data
* @param string $dataName
* @throws \Exception
*/
public function __construct($name = null, array $data = [], $dataName = '')
{
parent::__construct($name, $data, $dataName);

env('FILLED');
env('DEPENDS', 'on_default');
env('EMPTY');

$this->scanner = new LaravelEnvScanner(__DIR__);

$this->scanner->scan();
}

/** @test
* @throws \Exception
*/
public function it_checks_if_example_env_scan_results_are_correct()
{
$this->assertTrue($this->scanner->results['files'] === 1);
$this->assertTrue($this->scanner->results['has_value'] === 1);
$this->assertTrue($this->scanner->results['depending_on_default'] === 1);
$this->assertTrue($this->scanner->results['empty'] === 1);
$this->assertTrue($this->scanner->results['data'][0]['filename'] === basename(__FILE__));

foreach ($this->scanner->results['data'] as $result) {
if ($result['has_value'] !== '-') {
$this->assertTrue($result['has_value'] === 'FILLED');
$this->assertTrue($result['depending_on_default'] === '-');
$this->assertTrue($result['empty'] === '-');
} else if ($result['depending_on_default'] !== '-') {
$this->assertTrue($result['depending_on_default'] === 'DEPENDS');
$this->assertTrue($result['has_value'] === '-');
$this->assertTrue($result['empty'] === '-');
} else if ($result['empty'] !== '-') {
$this->assertTrue($result['empty'] === 'EMPTY');
$this->assertTrue($result['depending_on_default'] === '-');
$this->assertTrue($result['has_value'] === '-');

}
}
}
}
14 changes: 0 additions & 14 deletions tests/ExampleTest.php

This file was deleted.

0 comments on commit fd7bf60

Please sign in to comment.