-
-
Save philipboomy/b5472b16a5b8498ec2a41bf2bd6000d4 to your computer and use it in GitHub Desktop.
Migrate flat-file users to Eloquent.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use App\User; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Support\Facades\File; | |
use SplFileInfo; | |
use Statamic\Facades\YAML; | |
class MigrateUsersToDatabase extends Command | |
{ | |
/** | |
* The name and signature of the console command. | |
* | |
* @var string | |
*/ | |
protected $signature = 'migrate:users'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'Migrate flat-file users to Eloquent.'; | |
/** | |
* Create a new command instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
parent::__construct(); | |
} | |
/** | |
* Execute the console command. | |
* | |
* @return int | |
*/ | |
public function handle() | |
{ | |
collect(File::allFiles(base_path('users'))) | |
->filter(function (SplFileInfo $userFile) { | |
return $userFile->getExtension() === 'yaml'; | |
}) | |
->map(function (SplFileInfo $userFile) { | |
return [ | |
'email' => str_replace('.yaml', '', $userFile->getFilename()), | |
'data' => YAML::parse(file_get_contents($userFile->getRealPath())), | |
]; | |
}) | |
->each(function ($fileData) { | |
$email = $fileData['email']; | |
$user = $fileData['data']; | |
$this->info("Migrating {$email}"); | |
$eloquentUser = User::create([ | |
'name' => isset($user['name']) ? $user['name'] : 'Name', | |
'email' => $email, | |
'password' => isset($user['password_hash']) ? $user['password_hash'] : null, | |
'super' => isset($user['super']) ? $user['super'] : false, | |
'preferences' => isset($user['preferences']) ? $user['preferences'] : null, | |
'created_at' => isset($user['created_at']) ? $user['created_at'] : now(), | |
]); | |
if (isset($user['groups'])) { | |
foreach ($user['groups'] as $group) { | |
DB::table('group_user') | |
->insert([ | |
'user_id' => $eloquentUser->id, | |
'group_id' => $group, | |
]); | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment