Files
crewli/api/app/Models/Scopes/OrganisationScope.php

91 lines
2.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models\Scopes;
use App\Models\Event;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
/**
* Global scope that filters models by organisation_id.
*
* Resolution order:
* 1. Explicitly provided organisation ID (constructor)
* 2. Route parameter 'organisation' (object or string)
* 3. Skip scope if no context (CLI, queue jobs, unauthenticated)
*
* Models declare their scoping strategy via the $organisationScopeColumn property:
* - 'organisation_id' (default) — model has a direct organisation_id column
* - 'event_id' — model is scoped through events.organisation_id
* - 'festival_section_id' — model is scoped through festival_sections.event_id → events.organisation_id
*/
final class OrganisationScope implements Scope
{
public function __construct(
private readonly ?string $organisationId = null,
) {}
public function apply(Builder $builder, Model $model): void
{
$id = $this->resolveOrganisationId();
if ($id === null) {
return;
}
$column = $model->organisationScopeColumn ?? 'organisation_id';
match ($column) {
'organisation_id' => $builder->where($model->getTable() . '.organisation_id', $id),
'event_id' => $builder->whereIn(
$model->getTable() . '.event_id',
Event::withoutGlobalScope(self::class)
->where('organisation_id', $id)
->select('id')
),
'festival_section_id' => $builder->whereIn(
$model->getTable() . '.festival_section_id',
\App\Models\FestivalSection::withoutGlobalScope(self::class)
->whereIn('event_id', Event::withoutGlobalScope(self::class)
->where('organisation_id', $id)
->select('id'))
->select('id')
),
default => null,
};
}
private function resolveOrganisationId(): ?string
{
if ($this->organisationId !== null) {
return $this->organisationId;
}
$route = request()->route();
if ($route === null) {
return null;
}
$org = $route->parameter('organisation');
if ($org instanceof \App\Models\Organisation) {
return $org->id;
}
if (is_string($org) && $org !== '') {
return $org;
}
// Fall back to the event's organisation if we're on an event route
$event = $route->parameter('event');
if ($event instanceof Event) {
return $event->organisation_id;
}
return null;
}
}