Files
2026-10-09 08:21:06 +02:00

93 lines
1.9 KiB
PHP

<?php
namespace Tests\Setup;
use App\Models\Role;
use App\Models\User;
use App\Support\Enum\UserStatus;
use Facades\Tests\Setup\RoleFactory;
class UserFactory
{
protected $params = [];
protected $role;
public function withCredentials($username, $password)
{
$this->params['username'] = $username;
$this->params['password'] = $password;
return $this;
}
public function banned()
{
$this->params['status'] = UserStatus::BANNED;
return $this;
}
public function unconfirmed()
{
$this->params['status'] = UserStatus::UNCONFIRMED;
return $this;
}
public function unverified()
{
$this->params['email_verified_at'] = null;
return $this;
}
public function role(Role $role)
{
$this->role = $role;
return $this;
}
public function admin()
{
return $this->role(Role::where('name', 'Admin')->first());
}
public function user()
{
return $this->role(Role::where('name', 'User')->first());
}
public function email($email)
{
$this->params['email'] = $email;
return $this;
}
public function withPermissions($permissions)
{
$permissions = func_get_args();
// Spread, because RoleFactory::withPermissions() also reads
// func_get_args(). Passing the array whole nested it one level deeper,
// and Permission::where('name', $nested) then quietly matched only the
// first entry, so a two permission user came out with one.
$this->role(
RoleFactory::withPermissions(...$permissions)->create()
);
return $this;
}
public function create(array $overrides = [])
{
if ($this->role) {
$this->params['role_id'] = $this->role;
}
return User::factory()->create(array_merge($this->params, $overrides));
}
}