|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Fleetbase\Http\Middleware; |
| 4 | + |
| 5 | +use Illuminate\Http\Request; |
| 6 | +use Illuminate\Support\Facades\DB; |
| 7 | +use Illuminate\Support\Facades\Schema; |
| 8 | + |
| 9 | +class EnsureFleetbaseConfigured |
| 10 | +{ |
| 11 | + /** |
| 12 | + * Core tables required before the API can serve Fleetbase requests. |
| 13 | + * |
| 14 | + * @var array<int, string> |
| 15 | + */ |
| 16 | + protected array $requiredTables = [ |
| 17 | + 'settings', |
| 18 | + 'users', |
| 19 | + 'companies', |
| 20 | + ]; |
| 21 | + |
| 22 | + protected static bool $configured = false; |
| 23 | + |
| 24 | + public function handle(Request $request, \Closure $next) |
| 25 | + { |
| 26 | + if (!$this->shouldCheck($request)) { |
| 27 | + return $next($request); |
| 28 | + } |
| 29 | + |
| 30 | + if (!$this->isConfigured()) { |
| 31 | + return response()->json([ |
| 32 | + 'error' => 'fleetbase_not_configured', |
| 33 | + 'errors' => ['fleetbase_not_configured'], |
| 34 | + 'message' => 'Fleetbase is not installed or configured. Complete setup from the CLI or application container, then reload the console.', |
| 35 | + ], 503); |
| 36 | + } |
| 37 | + |
| 38 | + return $next($request); |
| 39 | + } |
| 40 | + |
| 41 | + protected function shouldCheck(Request $request): bool |
| 42 | + { |
| 43 | + if ($request->isMethod('OPTIONS')) { |
| 44 | + return false; |
| 45 | + } |
| 46 | + |
| 47 | + return $request->is('int/*') |
| 48 | + || $request->is('*/int/*') |
| 49 | + || $request->is('v1/*') |
| 50 | + || $request->is('*/v1/*'); |
| 51 | + } |
| 52 | + |
| 53 | + protected function isConfigured(): bool |
| 54 | + { |
| 55 | + if (static::$configured) { |
| 56 | + return true; |
| 57 | + } |
| 58 | + |
| 59 | + try { |
| 60 | + DB::connection()->getPdo(); |
| 61 | + |
| 62 | + if (!DB::connection()->getDatabaseName()) { |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + foreach ($this->requiredTables as $table) { |
| 67 | + if (!Schema::hasTable($table)) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + static::$configured = true; |
| 73 | + |
| 74 | + return true; |
| 75 | + } catch (\Throwable $e) { |
| 76 | + return false; |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments