*/ use HasFactory; use HasHashid; /** * The resource name for this model when it is transformed into an * API representation using fractal. */ public const string RESOURCE_NAME = 'allocation'; /** * @return array */ protected function casts(): array { return [ 'node_id' => 'integer', 'port' => 'integer', 'server_id' => 'integer', ]; } public function getRouteKeyName(): string { return $this->getKeyName(); } public function toString(): string { return sprintf('%s:%s', $this->ip, $this->port); } /** * Gets information for the server associated with this allocation. * * @return BelongsTo */ public function server(): BelongsTo { return $this->belongsTo(Server::class); } /** * Return the Node model associated with this allocation. * * @return BelongsTo */ public function node(): BelongsTo { return $this->belongsTo(Node::class); } /** * Accessor to automatically provide the IP alias if defined. * * @return Attribute */ protected function alias(): Attribute { return Attribute::make(get: fn (): string => $this->ip_alias ?? $this->ip); } /** * Accessor to quickly determine if this allocation has an alias. * * @return Attribute */ protected function hasAlias(): Attribute { return Attribute::make(get: fn (): bool => $this->ip_alias !== null); } /** * Allocations not yet assigned to a server. * * @param Builder $query */ #[Scope] protected function unassigned(Builder $query): void { $query->whereNull('server_id'); } /** * Allocations on any of the given nodes; an empty list leaves the query unrestricted. * * @param Builder $query * @param list $nodes */ #[Scope] protected function onNodes(Builder $query, array $nodes): void { $query->when($nodes !== [], fn (Builder $q) => $q->whereIn('node_id', $nodes)); } /** * Allocations whose port is one of the given ports or falls inside one of the * given [start, end] ranges; with neither given the query is unrestricted. * * @param Builder $query * @param list $ports * @param list $ranges */ #[Scope] protected function onPorts(Builder $query, array $ports, array $ranges = []): void { if ($ports === [] && $ranges === []) { return; } $query->where(function (Builder $inner) use ($ports, $ranges): void { if ($ports !== []) { $inner->orWhereIn('port', $ports); } foreach ($ranges as $range) { $inner->orWhereBetween('port', $range); } }); } /** * Allocations on node/IP pairs that no server uses yet. * * @param Builder $query * @param list $nodes restrict the occupied-IP lookup to these nodes */ #[Scope] protected function onDedicatedIp(Builder $query, array $nodes = []): void { $occupied = self::query() ->selectRaw('CONCAT_WS("-", node_id, ip)') ->whereNotNull('server_id') ->onNodes($nodes); $query->whereNotIn($query->raw('CONCAT_WS("-", node_id, ip)'), $occupied); } }