simedkom/app/Console/Commands/MigrateUserCommand.php

117 lines
3.5 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Enums\IsActive;
use App\Enums\RoleEnum;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
class MigrateUserCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrate:user';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Migrate users from legacy database';
/**
* Execute the console command.
*/
public function handle()
{
$this->info('Starting user migration...');
$legacyConn = DB::connection('mysql_second');
$legacyUsers = $legacyConn->table('users')->get();
if ($legacyUsers->isEmpty()) {
$this->warn('No users found in legacy database.');
return;
}
$this->withProgressBar($legacyUsers, function ($legacy) {
// Skip if user already exists with same email, but ensure role is synced if needed
$user = User::where('email', $legacy->email)->first();
if (! $user) {
$username = $this->generateUniqueUsername($legacy->name, $legacy->email);
// Using DB facade directly to insert ensures the legacy password hash
// is NOT double-hashed by the model's "hashed" cast.
$userId = DB::table('users')->insertGetId([
'name' => Str::limit($legacy->name, 100),
'email' => $legacy->email,
'username' => $username,
'password' => $legacy->password, // Preserving legacy hash
'is_active' => $legacy->status == '1' ? IsActive::ACTIVE->value : IsActive::INACTIVE->value,
'email_verified_at' => now(),
'created_at' => $legacy->created_at ?? now(),
'updated_at' => $legacy->updated_at ?? now(),
]);
$user = User::find($userId);
}
// Map and Assign Role
$roleName = $this->mapRole($legacy->role);
if ($roleName && $user) {
$user->syncRoles([$roleName]);
}
});
$this->newLine();
$this->info('User migration completed successfully!');
}
private function generateUniqueUsername($name, $email)
{
// Try name first
$base = Str::limit(Str::slug($name, ''), 10, '');
if (empty($base)) {
$base = Str::limit(explode('@', $email)[0], 10, '');
}
$username = $base;
$counter = 1;
// Ensure unique within 10 chars
while (User::where('username', $username)->exists()) {
$suffix = (string) $counter;
$maxBaseLength = 10 - strlen($suffix);
$username = substr($base, 0, $maxBaseLength).$suffix;
$counter++;
if ($counter > 999) {
break;
} // Safety
}
return $username;
}
private function mapRole($legacyRole): ?string
{
return match ((int) $legacyRole) {
1 => RoleEnum::ADMINISTRATOR->value,
2 => RoleEnum::ADMIN_MONITORING->value,
3 => RoleEnum::PERUSAHAAN->value,
4 => RoleEnum::ADMIN_KONTEN->value,
5 => RoleEnum::ADMIN_KEUANGAN->value,
default => null,
};
}
}