#30 #19 change PDO mode and the seeder from yaml to a service for mass importing

This commit is contained in:
Nabeel Shahzad
2017-06-24 12:59:07 -05:00
parent 3736e530bf
commit 2aa7cc66d5
5 changed files with 41 additions and 90 deletions

View File

@@ -1,6 +1,5 @@
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
@@ -12,35 +11,14 @@ class DatabaseSeeder extends Seeder
*/
public function run()
{
$this->seed_from_yaml(App::environment());
}
protected function seed_from_yaml($env)
{
$env = App::environment();
$path = database_path('seeds/'.$env.'.yml');
$time_fields = ['created_at', 'updated_at'];
$curr_time = Carbon::now('UTC')->format('Y-m-d H:i:s');
$yml = Yaml::parse(file_get_contents($path));
foreach ($yml as $table => $rows) {
foreach ($rows as $row) {
# encrypt any password fields
if (array_key_exists('password', $row)) {
$row['password'] = bcrypt($row['password']);
}
# if any time fields are == to "now", then insert the right time
foreach ($time_fields as $tf) {
if (array_key_exists($tf, $row) && $row[$tf] === 'now') {
$row[$tf] = $curr_time;
}
}
DB::table($table)->insert($row);
}
if(!file_exists($path)) {
return;
}
$svc = app('App\Services\DatabaseService');
$svc->seed_from_yaml($path);
}
}

View File

@@ -1,48 +0,0 @@
<?php
use Carbon\Carbon;
use Illuminate\Database\Seeder;
class DevelopmentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->seed_from_yaml();
}
protected function time(): string
{
return Carbon::now('UTC')->format('Y-m-d H:i:s');
}
protected function seed_from_yaml()
{
$time_fields = ['created_at', 'updated_at'];
$yml = Yaml::parse(file_get_contents(database_path('seeds/dev.yml')));
foreach ($yml as $table => $rows) {
foreach ($rows as $row) {
# encrypt any password fields
if(array_key_exists('password', $row)) {
$row['password'] = bcrypt($row['password']);
}
# if any time fields are == to "now", then insert the right time
foreach($time_fields as $tf) {
if(array_key_exists($tf, $row) && $row[$tf] === 'now') {
$row[$tf] = $this->time();
}
}
DB::table($table)->insert($row);
}
}
}
}