77 lines
1.7 KiB
PHP
77 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace Modules\Sites\Services;
|
|
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Modules\Sites\Models\Site;
|
|
|
|
final class SiteManager
|
|
{
|
|
private ?Site $current = null;
|
|
|
|
public function current(): ?Site
|
|
{
|
|
return $this->current;
|
|
}
|
|
|
|
public function setCurrent(?Site $site): void
|
|
{
|
|
$this->current = $site;
|
|
|
|
if ($site) {
|
|
app()->instance(Site::class, $site);
|
|
app()->instance('currentSite', $site);
|
|
}
|
|
}
|
|
|
|
public function all(): Collection
|
|
{
|
|
if (! $this->tablesExist()) {
|
|
return collect();
|
|
}
|
|
|
|
return Site::query()
|
|
->active()
|
|
->orderByDesc('is_default')
|
|
->orderBy('name')
|
|
->get();
|
|
}
|
|
|
|
public function resolve(Request $request): ?Site
|
|
{
|
|
if (! $this->tablesExist()) {
|
|
$this->setCurrent(null);
|
|
|
|
return null;
|
|
}
|
|
|
|
$host = strtolower(preg_replace('/:\d+$/', '', $request->getHost()));
|
|
|
|
$site = Site::query()
|
|
->with(['domains', 'settings'])
|
|
->whereHas('domains', fn ($query) => $query
|
|
->where('domain', $host)
|
|
->where('is_active', true))
|
|
->first();
|
|
|
|
if (! $site && config('sites.fallback_to_default')) {
|
|
$site = Site::query()
|
|
->with(['domains', 'settings'])
|
|
->active()
|
|
->where('is_default', true)
|
|
->first();
|
|
}
|
|
|
|
$this->setCurrent($site);
|
|
|
|
return $site;
|
|
}
|
|
|
|
private function tablesExist(): bool
|
|
{
|
|
return Schema::hasTable('sites') && Schema::hasTable('site_domains');
|
|
}
|
|
}
|