@@ -3,9 +3,13 @@
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Collection as SupportCollection;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
use Laravel\Cashier\Subscription;
|
||||
|
||||
/**
|
||||
* @extends Factory<User>
|
||||
@@ -17,6 +21,14 @@ class UserFactory extends Factory
|
||||
*/
|
||||
protected static ?string $password;
|
||||
|
||||
/**
|
||||
* Whether created users are given an active subscription.
|
||||
*
|
||||
* A factory user defaults to being entitled so that tests can focus on the
|
||||
* behaviour they are covering. Call unsubscribed() to opt out.
|
||||
*/
|
||||
protected bool $subscribed = true;
|
||||
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
@@ -36,6 +48,43 @@ class UserFactory extends Factory
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the model and, unless opted out, give it an active subscription on
|
||||
* the personal organization the model's created hook just made.
|
||||
*
|
||||
* The flag is read here rather than in an afterCreating callback because
|
||||
* afterCreating() hands back a new factory instance, so a closure registered
|
||||
* there would close over a copy that unsubscribed() never reaches.
|
||||
*
|
||||
* @param array<string, mixed> $attributes
|
||||
* @return Collection<int, User>|User
|
||||
*/
|
||||
public function create($attributes = [], ?Model $parent = null): Collection|User
|
||||
{
|
||||
$result = parent::create($attributes, $parent);
|
||||
|
||||
if (! $this->subscribed) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$users = $result instanceof SupportCollection ? $result : collect([$result]);
|
||||
|
||||
$users->each(fn (User $user) => $this->subscribe($user));
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the model does not have an active subscription, as a newly
|
||||
* registered account that has not been through checkout.
|
||||
*/
|
||||
public function unsubscribed(): static
|
||||
{
|
||||
$this->subscribed = false;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the model's email address should be unverified.
|
||||
*/
|
||||
@@ -77,4 +126,18 @@ class UserFactory extends Factory
|
||||
'two_factor_confirmed_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach an active subscription to the user's current organization.
|
||||
*/
|
||||
protected function subscribe(User $user): void
|
||||
{
|
||||
$organization = $user->currentOrganization()->first();
|
||||
|
||||
if ($organization === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Subscription::factory()->create(['organization_id' => $organization->id]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user