77 lines
2.5 KiB
PHP
77 lines
2.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Services\Onboarding;
|
|
|
|
use App\Models\TenantOnboardingSession;
|
|
use App\Models\User;
|
|
use App\Models\Workspace;
|
|
use Illuminate\Auth\Access\AuthorizationException;
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
use Illuminate\Support\Facades\Gate;
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
|
|
|
class OnboardingDraftResolver
|
|
{
|
|
public function __construct(
|
|
private readonly OnboardingLifecycleService $lifecycleService,
|
|
) {}
|
|
|
|
/**
|
|
* @throws AuthorizationException
|
|
* @throws NotFoundHttpException
|
|
*/
|
|
public function resolve(TenantOnboardingSession|int|string $draft, User $user, Workspace $workspace): TenantOnboardingSession
|
|
{
|
|
$draftId = $draft instanceof TenantOnboardingSession
|
|
? (int) $draft->getKey()
|
|
: (int) $draft;
|
|
|
|
$resolvedDraft = TenantOnboardingSession::query()
|
|
->with(['tenant', 'startedByUser', 'updatedByUser'])
|
|
->whereKey($draftId)
|
|
->first();
|
|
|
|
if (! $resolvedDraft instanceof TenantOnboardingSession) {
|
|
throw new NotFoundHttpException;
|
|
}
|
|
|
|
if ((int) $resolvedDraft->workspace_id !== (int) $workspace->getKey()) {
|
|
throw new NotFoundHttpException;
|
|
}
|
|
|
|
Gate::forUser($user)->authorize('view', $resolvedDraft);
|
|
|
|
return $this->lifecycleService
|
|
->syncPersistedLifecycle($resolvedDraft)
|
|
->loadMissing(['tenant', 'startedByUser', 'updatedByUser']);
|
|
}
|
|
|
|
/**
|
|
* @return Collection<int, TenantOnboardingSession>
|
|
*/
|
|
public function resumableDraftsFor(User $user, Workspace $workspace): Collection
|
|
{
|
|
$drafts = TenantOnboardingSession::query()
|
|
->with(['tenant', 'startedByUser', 'updatedByUser'])
|
|
->where('workspace_id', (int) $workspace->getKey())
|
|
->resumable()
|
|
->orderByDesc('updated_at')
|
|
->get();
|
|
|
|
return $drafts->filter(function (TenantOnboardingSession $draft) use ($user): bool {
|
|
try {
|
|
Gate::forUser($user)->authorize('view', $draft);
|
|
} catch (AuthorizationException) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
})->map(fn (TenantOnboardingSession $draft): TenantOnboardingSession => $this->lifecycleService
|
|
->syncPersistedLifecycle($draft)
|
|
->loadMissing(['tenant', 'startedByUser', 'updatedByUser']))
|
|
->values();
|
|
}
|
|
}
|