Merge pull request #11 from mateusjunges/junges-patch-1

Apply fixes from StyleCI and refactor readme
This commit is contained in:
Jani Gyllenberg
2019-06-20 13:32:35 -04:00
committed by GitHub
14 changed files with 95 additions and 74 deletions

View File

@@ -1,8 +1,8 @@
<?php <?php
return [ return [
'path' => base_path('sync'), 'path' => base_path('sync'),
'order' => [ 'order' => [
// //
] ],
]; ];

View File

@@ -1,9 +1,30 @@
<p align="center">
<a href="https://packagist.org/packages/distinctm/laravel-data-sync" target="_blank"><img src="https://poser.pugx.org/distinctm/laravel-data-sync/d/total.svg" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/distinctm/laravel-data-sync" target="_blank"><img src="https://poser.pugx.org/distinctm/laravel-data-sync/v/stable.svg" alt="Latest Stable Version"></a>
</p>
# Laravel Data Sync # Laravel Data Sync
Laravel utility to keep records synced between environments through source control Laravel utility to keep records synced between environments through source control
## Installation & Usage ## Installation
- Via composer: `composer require distinctm/laravel-data-sync` You can install this package via composer:
```bash
composer require distinctm/laravel-data-sync
```
Or add this line in your `composer.json`, inside of the `require` section:
``` json
{
"require": {
"distinctm/laravel-data-sync": "^1.0",
}
}
```
then run ` composer install `
## Usage
- Run `php artisan vendor:publish --provider="distinctm\LaravelDataSync\DataSyncBaseServiceProvider" --tag="data-sync-config"` to publish config file. Specify directory for sync data files (default is a new sync directory in the project root) - Run `php artisan vendor:publish --provider="distinctm\LaravelDataSync\DataSyncBaseServiceProvider" --tag="data-sync-config"` to publish config file. Specify directory for sync data files (default is a new sync directory in the project root)
- Create a JSON file for each model, using the model name as the filename. Example: Product.json would update the Product model - Create a JSON file for each model, using the model name as the filename. Example: Product.json would update the Product model
- Use nested arrays in place of hardcoded IDs for relationships - Use nested arrays in place of hardcoded IDs for relationships

View File

@@ -17,9 +17,9 @@ class Sync extends Command
$model = $this->option('model'); $model = $this->option('model');
$this->info('Updating Models with sync data files'); $this->info('Updating Models with sync data files');
(new Updater($path, $model))->run(); (new Updater($path, $model))->run();
$this->comment('Data sync completed'); $this->comment('Data sync completed');
} }
} }

View File

@@ -23,7 +23,7 @@ class DataSyncBaseServiceProvider extends ServiceProvider
protected function registerPublishing() protected function registerPublishing()
{ {
$this->publishes([ $this->publishes([
__DIR__ . '/../config/data-sync.php' => config_path('data-sync.php'), __DIR__.'/../config/data-sync.php' => config_path('data-sync.php'),
], 'data-sync-config'); ], 'data-sync-config');
} }
} }

View File

@@ -7,10 +7,10 @@ use Throwable;
class ErrorUpdatingModelException extends Exception class ErrorUpdatingModelException extends Exception
{ {
public function __construct(string $message = "", int $code = 0, Throwable $previous = null) public function __construct(string $message = '', int $code = 0, Throwable $previous = null)
{ {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
$this->message = "Error updating the {$message} model."; $this->message = "Error updating the {$message} model.";
} }
} }

View File

@@ -7,4 +7,4 @@ use Exception;
class FileDirectoryNotFoundException extends Exception class FileDirectoryNotFoundException extends Exception
{ {
protected $message = 'Specified sync file directory does not exist'; protected $message = 'Specified sync file directory does not exist';
} }

View File

@@ -7,4 +7,4 @@ use Exception;
class NoCriteriaException extends Exception class NoCriteriaException extends Exception
{ {
protected $message = 'No criteria/attributes detected'; protected $message = 'No criteria/attributes detected';
} }

View File

@@ -7,10 +7,10 @@ use Throwable;
class NoRecordsInvalidJSONException extends Exception class NoRecordsInvalidJSONException extends Exception
{ {
public function __construct(string $message = "", int $code = 0, Throwable $previous = null) public function __construct(string $message = '', int $code = 0, Throwable $previous = null)
{ {
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
$this->message = "No records or invalid JSON for {$message} model."; $this->message = "No records or invalid JSON for {$message} model.";
} }
} }

View File

@@ -2,17 +2,17 @@
namespace distinctm\LaravelDataSync; namespace distinctm\LaravelDataSync;
use distinctm\LaravelDataSync\Exceptions\ErrorUpdatingModelException;
use distinctm\LaravelDataSync\Exceptions\FileDirectoryNotFoundException; use distinctm\LaravelDataSync\Exceptions\FileDirectoryNotFoundException;
use distinctm\LaravelDataSync\Exceptions\NoCriteriaException; use distinctm\LaravelDataSync\Exceptions\NoCriteriaException;
use distinctm\LaravelDataSync\Exceptions\NoRecordsInvalidJSONException; use distinctm\LaravelDataSync\Exceptions\NoRecordsInvalidJSONException;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\File;
use distinctm\LaravelDataSync\Exceptions\ErrorUpdatingModelException;
class Updater class Updater
{ {
/** /**
* Get files in sync directory * Get files in sync directory.
* *
* @param string|null $path * @param string|null $path
* @param string|null $model * @param string|null $model
@@ -26,7 +26,7 @@ class Updater
} }
/** /**
* Execute syncModel for each file * Execute syncModel for each file.
* *
* @return mixed * @return mixed
*/ */
@@ -46,12 +46,13 @@ class Updater
} }
/** /**
* Parse each record for criteria/values and update/create model * Parse each record for criteria/values and update/create model.
* *
* @param string $file * @param string $file
* *
* @return \Illuminate\Support\Collection
* @throws \distinctm\LaravelDataSync\Exceptions\NoRecordsInvalidJSONException * @throws \distinctm\LaravelDataSync\Exceptions\NoRecordsInvalidJSONException
*
* @return \Illuminate\Support\Collection
*/ */
protected function syncModel(string $file) protected function syncModel(string $file)
{ {
@@ -74,28 +75,29 @@ class Updater
} }
/** /**
* Get directory path for sync files * Get directory path for sync files.
* *
* @param $path * @param $path
* *
* @return string
* @throws \distinctm\LaravelDataSync\Exceptions\FileDirectoryNotFoundException * @throws \distinctm\LaravelDataSync\Exceptions\FileDirectoryNotFoundException
*
* @return string
*/ */
protected function getDirectory($path) protected function getDirectory($path)
{ {
$directory = $path ?? config('data-sync.path', base_path('sync')); $directory = $path ?? config('data-sync.path', base_path('sync'));
if (!file_exists($directory)) { if (!file_exists($directory)) {
throw new FileDirectoryNotFoundException; throw new FileDirectoryNotFoundException();
} }
return $directory; return $directory;
} }
/** /**
* Get list of files in directory * Get list of files in directory.
* *
* @param string $directory * @param string $directory
* @param string|null $model * @param string|null $model
* *
* @return \Illuminate\Support\Collection * @return \Illuminate\Support\Collection
@@ -103,11 +105,11 @@ class Updater
protected function getFiles(string $directory, $model = null) protected function getFiles(string $directory, $model = null)
{ {
if ($model) { if ($model) {
return Collection::wrap($directory . '/' . $model . '.json'); return Collection::wrap($directory.'/'.$model.'.json');
} }
return collect(File::files($directory)) return collect(File::files($directory))
->filter(function($file) { ->filter(function ($file) {
return pathinfo($file, PATHINFO_EXTENSION) == 'json'; return pathinfo($file, PATHINFO_EXTENSION) == 'json';
})->map(function ($path) { })->map(function ($path) {
return $path->getPathname(); return $path->getPathname();
@@ -115,36 +117,38 @@ class Updater
} }
/** /**
* Sort Models by pre-configured order * Sort Models by pre-configured order.
* *
* @param \Illuminate\Support\Collection $files * @param \Illuminate\Support\Collection $files
*
* @return \Illuminate\Support\Collection * @return \Illuminate\Support\Collection
*/ */
protected function sortModels(\Illuminate\Support\Collection $files) protected function sortModels(\Illuminate\Support\Collection $files)
{ {
if(empty(config('data-sync.order'))) { if (empty(config('data-sync.order'))) {
return $files; return $files;
} }
return $files->sortBy(function($file) use ($files) { return $files->sortBy(function ($file) use ($files) {
$filename = pathinfo($file, PATHINFO_FILENAME); $filename = pathinfo($file, PATHINFO_FILENAME);
$order = array_search( $order = array_search(
studly_case($filename), studly_case($filename),
config('data-sync.order') config('data-sync.order')
); );
return $order !== false ? $order : (count($files) + 1); return $order !== false ? $order : (count($files) + 1);
}); });
} }
/** /**
* Filter record criteria * Filter record criteria.
* *
* @param object $record * @param object $record
* *
* @return \Illuminate\Support\Collection
* @throws \distinctm\LaravelDataSync\Exceptions\NoCriteriaException * @throws \distinctm\LaravelDataSync\Exceptions\NoCriteriaException
*
* @return \Illuminate\Support\Collection
*/ */
protected function getCriteria(object $record) protected function getCriteria(object $record)
{ {
@@ -153,7 +157,7 @@ class Updater
}); });
if ($criteria->count() == 0) { if ($criteria->count() == 0) {
throw new NoCriteriaException; throw new NoCriteriaException();
} }
return $criteria->mapWithKeys(function ($value, $key) { return $criteria->mapWithKeys(function ($value, $key) {
@@ -162,7 +166,7 @@ class Updater
} }
/** /**
* Filter record values * Filter record values.
* *
* @param object $record * @param object $record
* *
@@ -184,7 +188,7 @@ class Updater
} }
/** /**
* Returns model name for file * Returns model name for file.
* *
* @param string $name * @param string $name
* *
@@ -192,16 +196,17 @@ class Updater
*/ */
protected function getModel(string $name) protected function getModel(string $name)
{ {
return '\\App\\' . studly_case(pathinfo($name, PATHINFO_FILENAME)); return '\\App\\'.studly_case(pathinfo($name, PATHINFO_FILENAME));
} }
/** /**
* Parses JSON from file and returns collection * Parses JSON from file and returns collection.
* *
* @param string $file * @param string $file
* *
* @return \Illuminate\Support\Collection
* @throws \distinctm\LaravelDataSync\Exceptions\NoRecordsInvalidJSONException * @throws \distinctm\LaravelDataSync\Exceptions\NoRecordsInvalidJSONException
*
* @return \Illuminate\Support\Collection
*/ */
protected function getRecords(string $file) protected function getRecords(string $file)
{ {
@@ -215,11 +220,11 @@ class Updater
} }
/** /**
* Check if column is criteria for a condition match * Check if column is criteria for a condition match.
* *
* @param string $key * @param string $key
* *
* @return boolean * @return bool
*/ */
protected function isCriteria($key) protected function isCriteria($key)
{ {
@@ -227,7 +232,7 @@ class Updater
} }
/** /**
* Return ID for nested key-value pairs * Return ID for nested key-value pairs.
* *
* @param string $key * @param string $key
* @param object $values * @param object $values
@@ -239,7 +244,6 @@ class Updater
$model = $this->getModel($key); $model = $this->getModel($key);
$values = collect($values)->mapWithKeys(function ($value, $column) { $values = collect($values)->mapWithKeys(function ($value, $column) {
if (is_object($value)) { if (is_object($value)) {
return $this->resolveId($column, $value); return $this->resolveId($column, $value);
} }
@@ -247,11 +251,11 @@ class Updater
return [$column => $value]; return [$column => $value];
})->toArray(); })->toArray();
return [$key . '_id' => $model::where($values)->first()->id]; return [$key.'_id' => $model::where($values)->first()->id];
} }
/** /**
* Detect nested objects and resolve them * Detect nested objects and resolve them.
* *
* @param \Illuminate\Support\Collection $record * @param \Illuminate\Support\Collection $record
* *
@@ -267,5 +271,4 @@ class Updater
return [$key => $value]; return [$key => $value];
})->toArray(); })->toArray();
} }
} }

View File

@@ -14,4 +14,4 @@ class Roles extends Model
{ {
return $this->belongsTo(Supervisor::class); return $this->belongsTo(Supervisor::class);
} }
} }

View File

@@ -14,4 +14,4 @@ class Supervisor extends Model
{ {
return $this->hasMany(Roles::class); return $this->hasMany(Roles::class);
} }
} }

View File

@@ -11,8 +11,8 @@ class TestCase extends \Orchestra\Testbench\TestCase
{ {
$app['config']->set('database.default', 'testdb'); $app['config']->set('database.default', 'testdb');
$app['config']->set('database.connections.testdb', [ $app['config']->set('database.connections.testdb', [
'driver' => 'sqlite', 'driver' => 'sqlite',
'database' => ':memory:' 'database' => ':memory:',
]); ]);
} }
@@ -32,4 +32,4 @@ class TestCase extends \Orchestra\Testbench\TestCase
$table->string('category')->nullable(); $table->string('category')->nullable();
}); });
} }
} }

View File

@@ -2,16 +2,16 @@
namespace distinctm\LaravelDataSync\Tests; namespace distinctm\LaravelDataSync\Tests;
use distinctm\LaravelDataSync\Exceptions\ErrorUpdatingModelException;
use distinctm\LaravelDataSync\Tests\Fakes\UpdaterFake; use distinctm\LaravelDataSync\Tests\Fakes\UpdaterFake;
use Exception; use Exception;
use distinctm\LaravelDataSync\Exceptions\ErrorUpdatingModelException;
class UpdaterTest extends TestCase class UpdaterTest extends TestCase
{ {
/** @test */ /** @test */
public function it_adds_roles_to_the_database() public function it_adds_roles_to_the_database()
{ {
$updater = new UpdaterFake(__DIR__ . '/../test-data', 'roles'); $updater = new UpdaterFake(__DIR__.'/../test-data', 'roles');
$updater->run(); $updater->run();
@@ -23,7 +23,7 @@ class UpdaterTest extends TestCase
/** @test */ /** @test */
public function it_can_default_to_configuration() public function it_can_default_to_configuration()
{ {
config()->set('data-sync.path', __DIR__ . '/../test-data'); config()->set('data-sync.path', __DIR__.'/../test-data');
$updater = new UpdaterFake(); $updater = new UpdaterFake();
@@ -37,10 +37,10 @@ class UpdaterTest extends TestCase
/** @test */ /** @test */
public function it_can_update_an_existing_record() public function it_can_update_an_existing_record()
{ {
config()->set('data-sync.path', __DIR__ . '/../test-data'); config()->set('data-sync.path', __DIR__.'/../test-data');
(new UpdaterFake())->run(); (new UpdaterFake())->run();
config()->set('data-sync.path', __DIR__ . '/../test-data/valid'); config()->set('data-sync.path', __DIR__.'/../test-data/valid');
(new UpdaterFake())->run(); (new UpdaterFake())->run();
$this->assertDatabaseHas('roles', ['category' => 'changed']); $this->assertDatabaseHas('roles', ['category' => 'changed']);
@@ -55,7 +55,7 @@ class UpdaterTest extends TestCase
'name' => 'CEO', 'name' => 'CEO',
]); ]);
config()->set('data-sync.path', __DIR__ . '/../test-data/relationship', 'roles'); config()->set('data-sync.path', __DIR__.'/../test-data/relationship', 'roles');
(new UpdaterFake())->run(); (new UpdaterFake())->run();
$this->assertEquals($supervisor->id, Roles::first()->supervisor_id); $this->assertEquals($supervisor->id, Roles::first()->supervisor_id);
@@ -69,21 +69,19 @@ class UpdaterTest extends TestCase
new UpdaterFake(); new UpdaterFake();
$this->fail('exception was thrown'); $this->fail('exception was thrown');
} catch (Exception $e) { } catch (Exception $e) {
$this->assertEquals('Specified sync file directory does not exist', $e->getMessage()); $this->assertEquals('Specified sync file directory does not exist', $e->getMessage());
} }
} }
/** @test */ /** @test */
public function invalid_json_throws_an_exception() public function invalid_json_throws_an_exception()
{ {
try { try {
$updater = new UpdaterFake(__DIR__ . '/../test-data/invalid-json'); $updater = new UpdaterFake(__DIR__.'/../test-data/invalid-json');
$updater->run(); $updater->run();
$this->fail('exception was thrown'); $this->fail('exception was thrown');
} catch (Exception $e) { } catch (Exception $e) {
$this->assertContains('No records or invalid JSON for', $e->getMessage()); $this->assertContains('No records or invalid JSON for', $e->getMessage());
} }
@@ -93,13 +91,12 @@ class UpdaterTest extends TestCase
public function the_json_must_contain_a_key_with_an_underscore() public function the_json_must_contain_a_key_with_an_underscore()
{ {
try { try {
$updater = new UpdaterFake(__DIR__ . '/../test-data/no-criteria'); $updater = new UpdaterFake(__DIR__.'/../test-data/no-criteria');
$updater->run(); $updater->run();
$this->fail('exception was thrown'); $this->fail('exception was thrown');
} catch (Exception $e) { } catch (Exception $e) {
$this->assertEquals('No criteria/attributes detected', $e->getMessage()); $this->assertEquals('No criteria/attributes detected', $e->getMessage());
} }
} }
@@ -108,10 +105,10 @@ class UpdaterTest extends TestCase
{ {
config()->set('data-sync.order', [ config()->set('data-sync.order', [
'Supervisor', 'Supervisor',
'Roles' 'Roles',
]); ]);
$updater = new UpdaterFake(__DIR__ . '/../test-data/ordered'); $updater = new UpdaterFake(__DIR__.'/../test-data/ordered');
$updater->run(); $updater->run();
$this->assertDatabaseHas('roles', ['slug' => 'update-student-records']); $this->assertDatabaseHas('roles', ['slug' => 'update-student-records']);
@@ -123,21 +120,21 @@ class UpdaterTest extends TestCase
{ {
config()->set('data-sync.order', [ config()->set('data-sync.order', [
'Roles', 'Roles',
'Supervisor' 'Supervisor',
]); ]);
$this->expectException(ErrorUpdatingModelException::class); $this->expectException(ErrorUpdatingModelException::class);
$updater = new UpdaterFake(__DIR__ . '/../test-data/ordered'); $updater = new UpdaterFake(__DIR__.'/../test-data/ordered');
$updater->run(); $updater->run();
} }
/** @test */ /** @test */
public function it_ignores_non_json_files() public function it_ignores_non_json_files()
{ {
$updater = new UpdaterFake(__DIR__ . '/../test-data/not-json'); $updater = new UpdaterFake(__DIR__.'/../test-data/not-json');
$updater->run(); $updater->run();
$this->assertDatabaseMissing('roles', ['slug' => 'update-student-records']); $this->assertDatabaseMissing('roles', ['slug' => 'update-student-records']);
} }
} }

View File

@@ -8,8 +8,8 @@ class UpdaterFake extends Updater
{ {
protected function getModel(string $name) protected function getModel(string $name)
{ {
return '\\distinctm\\LaravelDataSync\\Tests\\' . studly_case( return '\\distinctm\\LaravelDataSync\\Tests\\'.studly_case(
pathinfo($name, PATHINFO_FILENAME) pathinfo($name, PATHINFO_FILENAME)
); );
} }
} }