diff --git a/app/Actions/Application/StopApplication.php b/app/Actions/Application/StopApplication.php
index ed929573eb..642b4ba456 100644
--- a/app/Actions/Application/StopApplication.php
+++ b/app/Actions/Application/StopApplication.php
@@ -4,7 +4,6 @@
use App\Actions\Server\CleanupDocker;
use App\Models\Application;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
class StopApplication
@@ -24,7 +23,7 @@ public function handle(Application $application, bool $previewDeployments = fals
if ($server->isSwarm()) {
instant_remote_process(["docker stack rm {$application->uuid}"], $server);
- return null;
+ return;
}
$containersToStop = $application->getContainersToStop($previewDeployments);
@@ -37,10 +36,8 @@ public function handle(Application $application, bool $previewDeployments = fals
if ($dockerCleanup) {
CleanupDocker::dispatch($server, true);
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return $e->getMessage();
}
-
- return null;
}
}
diff --git a/app/Actions/Application/StopApplicationOneServer.php b/app/Actions/Application/StopApplicationOneServer.php
index a55efc3f31..b13b10efd6 100644
--- a/app/Actions/Application/StopApplicationOneServer.php
+++ b/app/Actions/Application/StopApplicationOneServer.php
@@ -4,7 +4,6 @@
use App\Models\Application;
use App\Models\Server;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
class StopApplicationOneServer
@@ -14,7 +13,7 @@ class StopApplicationOneServer
public function handle(Application $application, Server $server)
{
if ($application->destination->server->isSwarm()) {
- return null;
+ return;
}
if (! $server->isFunctional()) {
return 'Server is not functional';
@@ -32,10 +31,8 @@ public function handle(Application $application, Server $server)
}
}
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return $e->getMessage();
}
-
- return null;
}
}
diff --git a/app/Actions/CoolifyTask/PrepareCoolifyTask.php b/app/Actions/CoolifyTask/PrepareCoolifyTask.php
index fd6f697c60..3f76a2e3c7 100644
--- a/app/Actions/CoolifyTask/PrepareCoolifyTask.php
+++ b/app/Actions/CoolifyTask/PrepareCoolifyTask.php
@@ -4,7 +4,6 @@
use App\Data\CoolifyTaskArgs;
use App\Jobs\CoolifyTask;
-use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Models\Activity;
/**
@@ -18,36 +17,36 @@ class PrepareCoolifyTask
protected CoolifyTaskArgs $remoteProcessArgs;
- public function __construct(CoolifyTaskArgs $coolifyTaskArgs)
+ public function __construct(CoolifyTaskArgs $remoteProcessArgs)
{
- $this->remoteProcessArgs = $coolifyTaskArgs;
+ $this->remoteProcessArgs = $remoteProcessArgs;
- if ($coolifyTaskArgs->model instanceof Model) {
- $properties = $coolifyTaskArgs->toArray();
+ if ($remoteProcessArgs->model) {
+ $properties = $remoteProcessArgs->toArray();
unset($properties['model']);
$this->activity = activity()
->withProperties($properties)
- ->performedOn($coolifyTaskArgs->model)
- ->event($coolifyTaskArgs->type)
+ ->performedOn($remoteProcessArgs->model)
+ ->event($remoteProcessArgs->type)
->log('[]');
} else {
$this->activity = activity()
- ->withProperties($coolifyTaskArgs->toArray())
- ->event($coolifyTaskArgs->type)
+ ->withProperties($remoteProcessArgs->toArray())
+ ->event($remoteProcessArgs->type)
->log('[]');
}
}
public function __invoke(): Activity
{
- $coolifyTask = new CoolifyTask(
+ $job = new CoolifyTask(
activity: $this->activity,
ignore_errors: $this->remoteProcessArgs->ignore_errors,
call_event_on_finish: $this->remoteProcessArgs->call_event_on_finish,
call_event_data: $this->remoteProcessArgs->call_event_data,
);
- dispatch($coolifyTask);
+ dispatch($job);
$this->activity->refresh();
return $this->activity;
diff --git a/app/Actions/CoolifyTask/RunRemoteProcess.php b/app/Actions/CoolifyTask/RunRemoteProcess.php
index 78e995342c..981b81378e 100644
--- a/app/Actions/CoolifyTask/RunRemoteProcess.php
+++ b/app/Actions/CoolifyTask/RunRemoteProcess.php
@@ -11,10 +11,7 @@
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
-use JsonException;
-use RuntimeException;
use Spatie\Activitylog\Models\Activity;
-use Throwable;
class RunRemoteProcess
{
@@ -24,9 +21,9 @@ class RunRemoteProcess
public bool $ignore_errors;
- public $call_event_on_finish;
+ public $call_event_on_finish = null;
- public $call_event_data;
+ public $call_event_data = null;
protected $time_start;
@@ -44,7 +41,7 @@ class RunRemoteProcess
public function __construct(Activity $activity, bool $hide_from_output = false, bool $ignore_errors = false, $call_event_on_finish = null, $call_event_data = null)
{
if ($activity->getExtraProperty('type') !== ActivityTypes::INLINE->value && $activity->getExtraProperty('type') !== ActivityTypes::COMMAND->value) {
- throw new RuntimeException('Incompatible Activity to run a remote command.');
+ throw new \RuntimeException('Incompatible Activity to run a remote command.');
}
$this->activity = $activity;
@@ -66,7 +63,7 @@ public static function decodeOutput(?Activity $activity = null): string
associative: true,
flags: JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE
);
- } catch (JsonException $exception) {
+ } catch (\JsonException $exception) {
return '';
}
@@ -82,12 +79,12 @@ public function __invoke(): ProcessResult
$status = ProcessStatus::IN_PROGRESS;
$timeout = config('constants.ssh.command_timeout');
- $invokedProcess = Process::timeout($timeout)->start($this->getCommand(), $this->handleOutput(...));
+ $process = Process::timeout($timeout)->start($this->getCommand(), $this->handleOutput(...));
$this->activity->properties = $this->activity->properties->merge([
- 'process_id' => $invokedProcess->id(),
+ 'process_id' => $process->id(),
]);
- $processResult = $invokedProcess->wait();
+ $processResult = $process->wait();
// $processResult = Process::timeout($timeout)->run($this->getCommand(), $this->handleOutput(...));
if ($this->activity->properties->get('status') === ProcessStatus::ERROR->value) {
$status = ProcessStatus::ERROR;
@@ -114,7 +111,7 @@ public function __invoke(): ProcessResult
]);
$this->activity->save();
if ($processResult->exitCode() != 0 && ! $this->ignore_errors) {
- throw new RuntimeException($processResult->errorOutput(), $processResult->exitCode());
+ throw new \RuntimeException($processResult->errorOutput(), $processResult->exitCode());
}
if ($this->call_event_on_finish) {
try {
@@ -127,7 +124,7 @@ public function __invoke(): ProcessResult
'userId' => $this->activity->causer_id,
]));
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
Log::error('Error calling event: '.$e->getMessage());
}
}
diff --git a/app/Actions/Database/StartClickhouse.php b/app/Actions/Database/StartClickhouse.php
index 9d7114b1e6..f218fcabb0 100644
--- a/app/Actions/Database/StartClickhouse.php
+++ b/app/Actions/Database/StartClickhouse.php
@@ -16,9 +16,9 @@ class StartClickhouse
public string $configuration_dir;
- public function handle(StandaloneClickhouse $standaloneClickhouse)
+ public function handle(StandaloneClickhouse $database)
{
- $this->database = $standaloneClickhouse;
+ $this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
@@ -103,12 +103,12 @@ public function handle(StandaloneClickhouse $standaloneClickhouse)
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
- $this->commands[] = "echo 'Pulling {$standaloneClickhouse->image} image.'";
+ $this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
- return remote_process($this->commands, $standaloneClickhouse->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
+ return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
diff --git a/app/Actions/Database/StartDatabase.php b/app/Actions/Database/StartDatabase.php
index 0b2a3ce262..e2fa6fc871 100644
--- a/app/Actions/Database/StartDatabase.php
+++ b/app/Actions/Database/StartDatabase.php
@@ -25,28 +25,28 @@ public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|St
return 'Server is not functional';
}
switch ($database->getMorphClass()) {
- case StandalonePostgresql::class:
+ case \App\Models\StandalonePostgresql::class:
$activity = StartPostgresql::run($database);
break;
- case StandaloneRedis::class:
+ case \App\Models\StandaloneRedis::class:
$activity = StartRedis::run($database);
break;
- case StandaloneMongodb::class:
+ case \App\Models\StandaloneMongodb::class:
$activity = StartMongodb::run($database);
break;
- case StandaloneMysql::class:
+ case \App\Models\StandaloneMysql::class:
$activity = StartMysql::run($database);
break;
- case StandaloneMariadb::class:
+ case \App\Models\StandaloneMariadb::class:
$activity = StartMariadb::run($database);
break;
- case StandaloneKeydb::class:
+ case \App\Models\StandaloneKeydb::class:
$activity = StartKeydb::run($database);
break;
- case StandaloneDragonfly::class:
+ case \App\Models\StandaloneDragonfly::class:
$activity = StartDragonfly::run($database);
break;
- case StandaloneClickhouse::class:
+ case \App\Models\StandaloneClickhouse::class:
$activity = StartClickhouse::run($database);
break;
}
diff --git a/app/Actions/Database/StartDatabaseProxy.php b/app/Actions/Database/StartDatabaseProxy.php
index 89ed5935b7..3ddf6c036b 100644
--- a/app/Actions/Database/StartDatabaseProxy.php
+++ b/app/Actions/Database/StartDatabaseProxy.php
@@ -28,7 +28,7 @@ public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|St
$server = data_get($database, 'destination.server');
$containerName = data_get($database, 'uuid');
$proxyContainerName = "{$database->uuid}-proxy";
- if ($database->getMorphClass() === ServiceDatabase::class) {
+ if ($database->getMorphClass() === \App\Models\ServiceDatabase::class) {
$databaseType = $database->databaseType();
// $connectPredefined = data_get($database, 'service.connect_to_docker_network');
$network = $database->service->uuid;
@@ -36,54 +36,54 @@ public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|St
$proxyContainerName = "{$database->service->uuid}-proxy";
switch ($databaseType) {
case 'standalone-mariadb':
- $type = StandaloneMariadb::class;
+ $type = \App\Models\StandaloneMariadb::class;
$containerName = "mariadb-{$database->service->uuid}";
break;
case 'standalone-mongodb':
- $type = StandaloneMongodb::class;
+ $type = \App\Models\StandaloneMongodb::class;
$containerName = "mongodb-{$database->service->uuid}";
break;
case 'standalone-mysql':
- $type = StandaloneMysql::class;
+ $type = \App\Models\StandaloneMysql::class;
$containerName = "mysql-{$database->service->uuid}";
break;
case 'standalone-postgresql':
- $type = StandalonePostgresql::class;
+ $type = \App\Models\StandalonePostgresql::class;
$containerName = "postgresql-{$database->service->uuid}";
break;
case 'standalone-redis':
- $type = StandaloneRedis::class;
+ $type = \App\Models\StandaloneRedis::class;
$containerName = "redis-{$database->service->uuid}";
break;
case 'standalone-keydb':
- $type = StandaloneKeydb::class;
+ $type = \App\Models\StandaloneKeydb::class;
$containerName = "keydb-{$database->service->uuid}";
break;
case 'standalone-dragonfly':
- $type = StandaloneDragonfly::class;
+ $type = \App\Models\StandaloneDragonfly::class;
$containerName = "dragonfly-{$database->service->uuid}";
break;
case 'standalone-clickhouse':
- $type = StandaloneClickhouse::class;
+ $type = \App\Models\StandaloneClickhouse::class;
$containerName = "clickhouse-{$database->service->uuid}";
break;
}
}
- if ($type === StandaloneRedis::class) {
+ if ($type === \App\Models\StandaloneRedis::class) {
$internalPort = 6379;
- } elseif ($type === StandalonePostgresql::class) {
+ } elseif ($type === \App\Models\StandalonePostgresql::class) {
$internalPort = 5432;
- } elseif ($type === StandaloneMongodb::class) {
+ } elseif ($type === \App\Models\StandaloneMongodb::class) {
$internalPort = 27017;
- } elseif ($type === StandaloneMysql::class) {
+ } elseif ($type === \App\Models\StandaloneMysql::class) {
$internalPort = 3306;
- } elseif ($type === StandaloneMariadb::class) {
+ } elseif ($type === \App\Models\StandaloneMariadb::class) {
$internalPort = 3306;
- } elseif ($type === StandaloneKeydb::class) {
+ } elseif ($type === \App\Models\StandaloneKeydb::class) {
$internalPort = 6379;
- } elseif ($type === StandaloneDragonfly::class) {
+ } elseif ($type === \App\Models\StandaloneDragonfly::class) {
$internalPort = 6379;
- } elseif ($type === StandaloneClickhouse::class) {
+ } elseif ($type === \App\Models\StandaloneClickhouse::class) {
$internalPort = 9000;
}
$configuration_dir = database_proxy_dir($database->uuid);
diff --git a/app/Actions/Database/StartDragonfly.php b/app/Actions/Database/StartDragonfly.php
index 7ddac1c1dc..4f9f45b7c7 100644
--- a/app/Actions/Database/StartDragonfly.php
+++ b/app/Actions/Database/StartDragonfly.php
@@ -16,9 +16,9 @@ class StartDragonfly
public string $configuration_dir;
- public function handle(StandaloneDragonfly $standaloneDragonfly)
+ public function handle(StandaloneDragonfly $database)
{
- $this->database = $standaloneDragonfly;
+ $this->database = $database;
$startCommand = "dragonfly --requirepass {$this->database->dragonfly_password}";
@@ -100,12 +100,12 @@ public function handle(StandaloneDragonfly $standaloneDragonfly)
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
- $this->commands[] = "echo 'Pulling {$standaloneDragonfly->image} image.'";
+ $this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
- return remote_process($this->commands, $standaloneDragonfly->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
+ return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
diff --git a/app/Actions/Database/StartKeydb.php b/app/Actions/Database/StartKeydb.php
index 8e5da12f4f..6c733d3180 100644
--- a/app/Actions/Database/StartKeydb.php
+++ b/app/Actions/Database/StartKeydb.php
@@ -17,9 +17,9 @@ class StartKeydb
public string $configuration_dir;
- public function handle(StandaloneKeydb $standaloneKeydb)
+ public function handle(StandaloneKeydb $database)
{
- $this->database = $standaloneKeydb;
+ $this->database = $database;
$startCommand = "keydb-server --requirepass {$this->database->keydb_password} --appendonly yes";
@@ -92,7 +92,7 @@ public function handle(StandaloneKeydb $standaloneKeydb)
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
- if (! is_null($this->database->keydb_conf) || $this->database->keydb_conf !== null) {
+ if (! is_null($this->database->keydb_conf) || ! empty($this->database->keydb_conf)) {
$docker_compose['services'][$container_name]['volumes'][] = [
'type' => 'bind',
'source' => $this->configuration_dir.'/keydb.conf',
@@ -110,12 +110,12 @@ public function handle(StandaloneKeydb $standaloneKeydb)
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
- $this->commands[] = "echo 'Pulling {$standaloneKeydb->image} image.'";
+ $this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
- return remote_process($this->commands, $standaloneKeydb->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
+ return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
diff --git a/app/Actions/Database/StartMariadb.php b/app/Actions/Database/StartMariadb.php
index f161754d1f..299b07385b 100644
--- a/app/Actions/Database/StartMariadb.php
+++ b/app/Actions/Database/StartMariadb.php
@@ -16,9 +16,9 @@ class StartMariadb
public string $configuration_dir;
- public function handle(StandaloneMariadb $standaloneMariadb)
+ public function handle(StandaloneMariadb $database)
{
- $this->database = $standaloneMariadb;
+ $this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
@@ -87,7 +87,7 @@ public function handle(StandaloneMariadb $standaloneMariadb)
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
- if (! is_null($this->database->mariadb_conf) || $this->database->mariadb_conf !== null) {
+ if (! is_null($this->database->mariadb_conf) || ! empty($this->database->mariadb_conf)) {
$docker_compose['services'][$container_name]['volumes'][] = [
'type' => 'bind',
'source' => $this->configuration_dir.'/custom-config.cnf',
@@ -105,12 +105,12 @@ public function handle(StandaloneMariadb $standaloneMariadb)
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
- $this->commands[] = "echo 'Pulling {$standaloneMariadb->image} image.'";
+ $this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
- return remote_process($this->commands, $standaloneMariadb->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
+ return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
diff --git a/app/Actions/Database/StartMongodb.php b/app/Actions/Database/StartMongodb.php
index f04d3d76b5..89d35ca7b4 100644
--- a/app/Actions/Database/StartMongodb.php
+++ b/app/Actions/Database/StartMongodb.php
@@ -16,9 +16,9 @@ class StartMongodb
public string $configuration_dir;
- public function handle(StandaloneMongodb $standaloneMongodb)
+ public function handle(StandaloneMongodb $database)
{
- $this->database = $standaloneMongodb;
+ $this->database = $database;
$startCommand = 'mongod';
@@ -99,7 +99,7 @@ public function handle(StandaloneMongodb $standaloneMongodb)
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
- if (! is_null($this->database->mongo_conf) || $this->database->mongo_conf !== null) {
+ if (! is_null($this->database->mongo_conf) || ! empty($this->database->mongo_conf)) {
$docker_compose['services'][$container_name]['volumes'][] = [
'type' => 'bind',
'source' => $this->configuration_dir.'/mongod.conf',
@@ -125,12 +125,12 @@ public function handle(StandaloneMongodb $standaloneMongodb)
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
- $this->commands[] = "echo 'Pulling {$standaloneMongodb->image} image.'";
+ $this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
- return remote_process($this->commands, $standaloneMongodb->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
+ return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
diff --git a/app/Actions/Database/StartMysql.php b/app/Actions/Database/StartMysql.php
index fcdb4225f2..73db1512a3 100644
--- a/app/Actions/Database/StartMysql.php
+++ b/app/Actions/Database/StartMysql.php
@@ -16,9 +16,9 @@ class StartMysql
public string $configuration_dir;
- public function handle(StandaloneMysql $standaloneMysql)
+ public function handle(StandaloneMysql $database)
{
- $this->database = $standaloneMysql;
+ $this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
@@ -87,7 +87,7 @@ public function handle(StandaloneMysql $standaloneMysql)
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
- if (! is_null($this->database->mysql_conf) || $this->database->mysql_conf !== null) {
+ if (! is_null($this->database->mysql_conf) || ! empty($this->database->mysql_conf)) {
$docker_compose['services'][$container_name]['volumes'][] = [
'type' => 'bind',
'source' => $this->configuration_dir.'/custom-config.cnf',
@@ -105,12 +105,12 @@ public function handle(StandaloneMysql $standaloneMysql)
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
- $this->commands[] = "echo 'Pulling {$standaloneMysql->image} image.'";
+ $this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
- return remote_process($this->commands, $standaloneMysql->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
+ return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
diff --git a/app/Actions/Database/StartPostgresql.php b/app/Actions/Database/StartPostgresql.php
index a65ad24ce6..035849340d 100644
--- a/app/Actions/Database/StartPostgresql.php
+++ b/app/Actions/Database/StartPostgresql.php
@@ -18,9 +18,9 @@ class StartPostgresql
public string $configuration_dir;
- public function handle(StandalonePostgresql $standalonePostgresql)
+ public function handle(StandalonePostgresql $database)
{
- $this->database = $standalonePostgresql;
+ $this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
if (isDev()) {
@@ -97,13 +97,15 @@ public function handle(StandalonePostgresql $standalonePostgresql)
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
- foreach ($this->init_scripts as $init_script) {
- $docker_compose['services'][$container_name]['volumes'][] = [
- 'type' => 'bind',
- 'source' => $init_script,
- 'target' => '/docker-entrypoint-initdb.d/'.basename($init_script),
- 'read_only' => true,
- ];
+ if (count($this->init_scripts) > 0) {
+ foreach ($this->init_scripts as $init_script) {
+ $docker_compose['services'][$container_name]['volumes'][] = [
+ 'type' => 'bind',
+ 'source' => $init_script,
+ 'target' => '/docker-entrypoint-initdb.d/'.basename($init_script),
+ 'read_only' => true,
+ ];
+ }
}
if (filled($this->database->postgres_conf)) {
$docker_compose['services'][$container_name]['volumes'][] = [
@@ -127,12 +129,12 @@ public function handle(StandalonePostgresql $standalonePostgresql)
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
- $this->commands[] = "echo 'Pulling {$standalonePostgresql->image} image.'";
+ $this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
- return remote_process($this->commands, $standalonePostgresql->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
+ return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
diff --git a/app/Actions/Database/StartRedis.php b/app/Actions/Database/StartRedis.php
index a32af8c964..1beebd134b 100644
--- a/app/Actions/Database/StartRedis.php
+++ b/app/Actions/Database/StartRedis.php
@@ -17,9 +17,9 @@ class StartRedis
public string $configuration_dir;
- public function handle(StandaloneRedis $standaloneRedis)
+ public function handle(StandaloneRedis $database)
{
- $this->database = $standaloneRedis;
+ $this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
@@ -96,7 +96,7 @@ public function handle(StandaloneRedis $standaloneRedis)
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
- if (! is_null($this->database->redis_conf) || $this->database->redis_conf !== null) {
+ if (! is_null($this->database->redis_conf) || ! empty($this->database->redis_conf)) {
$docker_compose['services'][$container_name]['volumes'][] = [
'type' => 'bind',
'source' => $this->configuration_dir.'/redis.conf',
@@ -114,12 +114,12 @@ public function handle(StandaloneRedis $standaloneRedis)
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
- $this->commands[] = "echo 'Pulling {$standaloneRedis->image} image.'";
+ $this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
- return remote_process($this->commands, $standaloneRedis->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
+ return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
diff --git a/app/Actions/Database/StopDatabase.php b/app/Actions/Database/StopDatabase.php
index 2db2ddfc4d..e4cea7cee8 100644
--- a/app/Actions/Database/StopDatabase.php
+++ b/app/Actions/Database/StopDatabase.php
@@ -26,8 +26,10 @@ public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|St
}
$this->stopContainer($database, $database->uuid, 300);
- if (! $isDeleteOperation && $dockerCleanup) {
- CleanupDocker::dispatch($server, true);
+ if (! $isDeleteOperation) {
+ if ($dockerCleanup) {
+ CleanupDocker::dispatch($server, true);
+ }
}
if ($database->is_public) {
@@ -41,10 +43,10 @@ private function stopContainer($database, string $containerName, int $timeout =
{
$server = $database->destination->server;
- $invokedProcess = Process::timeout($timeout)->start("docker stop --time=$timeout $containerName");
+ $process = Process::timeout($timeout)->start("docker stop --time=$timeout $containerName");
$startTime = time();
- while ($invokedProcess->running()) {
+ while ($process->running()) {
if (time() - $startTime >= $timeout) {
$this->forceStopContainer($containerName, $server);
break;
@@ -64,4 +66,10 @@ private function removeContainer(string $containerName, $server): void
{
instant_remote_process(command: ["docker rm -f $containerName"], server: $server, throwError: false);
}
+
+ private function deleteConnectedNetworks($uuid, $server)
+ {
+ instant_remote_process(["docker network disconnect {$uuid} coolify-proxy"], $server, false);
+ instant_remote_process(["docker network rm {$uuid}"], $server, false);
+ }
}
diff --git a/app/Actions/Database/StopDatabaseProxy.php b/app/Actions/Database/StopDatabaseProxy.php
index 451a5d3dde..9ee7943515 100644
--- a/app/Actions/Database/StopDatabaseProxy.php
+++ b/app/Actions/Database/StopDatabaseProxy.php
@@ -24,7 +24,7 @@ public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|St
{
$server = data_get($database, 'destination.server');
$uuid = $database->uuid;
- if ($database->getMorphClass() === ServiceDatabase::class) {
+ if ($database->getMorphClass() === \App\Models\ServiceDatabase::class) {
$uuid = $database->service->uuid;
$server = data_get($database, 'service.server');
}
diff --git a/app/Actions/Docker/GetContainersStatus.php b/app/Actions/Docker/GetContainersStatus.php
index aa19d680b8..c0e0882032 100644
--- a/app/Actions/Docker/GetContainersStatus.php
+++ b/app/Actions/Docker/GetContainersStatus.php
@@ -47,20 +47,20 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
$this->applications = $this->applications->filter(function ($value, $key) use ($skip_these_applications) {
return ! $skip_these_applications->pluck('id')->contains($value->id);
});
- if (! $this->containers instanceof Collection) {
+ if ($this->containers === null) {
['containers' => $this->containers, 'containerReplicates' => $this->containerReplicates] = $this->server->getContainers();
}
if (is_null($this->containers)) {
- return null;
+ return;
}
if ($this->containerReplicates) {
- foreach ($this->containerReplicates as $containerReplicate) {
- $name = data_get($containerReplicate, 'Name');
- $this->containers = $this->containers->map(function ($container) use ($name, $containerReplicate) {
+ foreach ($this->containerReplicates as $containerReplica) {
+ $name = data_get($containerReplica, 'Name');
+ $this->containers = $this->containers->map(function ($container) use ($name, $containerReplica) {
if (data_get($container, 'Spec.Name') === $name) {
- $replicas = data_get($containerReplicate, 'Replicas');
+ $replicas = data_get($containerReplica, 'Replicas');
$running = str($replicas)->explode('/')[0];
$total = str($replicas)->explode('/')[1];
if ($running === $total) {
@@ -102,7 +102,7 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
if (str($applicationId)->contains('-')) {
$applicationId = str($applicationId)->before('-');
}
- $preview = ApplicationPreview::query()->where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();
+ $preview = ApplicationPreview::where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();
if ($preview) {
$foundApplicationPreviews[] = $preview->id;
$statusFromDb = $preview->status;
@@ -136,7 +136,7 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
if ($type === 'service') {
$database_id = data_get($labels, 'coolify.service.subId');
if ($database_id) {
- $service_db = ServiceDatabase::query()->where('id', $database_id)->first();
+ $service_db = ServiceDatabase::where('id', $database_id)->first();
if ($service_db) {
$uuid = data_get($service_db, 'service.uuid');
if ($uuid) {
@@ -145,9 +145,9 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
+ } else {
+ return data_get($value, 'Name') === "/$uuid-proxy";
}
-
- return data_get($value, 'Name') === "/$uuid-proxy";
})->first();
if (! $foundTcpProxy) {
StartDatabaseProxy::run($service_db);
@@ -173,9 +173,9 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
+ } else {
+ return data_get($value, 'Name') === "/$uuid-proxy";
}
-
- return data_get($value, 'Name') === "/$uuid-proxy";
})->first();
if (! $foundTcpProxy) {
StartDatabaseProxy::run($database);
@@ -223,14 +223,16 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
foreach ($apps as $app) {
if (in_array("$app->id-$app->name", $foundServices)) {
continue;
+ } else {
+ $exitedServices->push($app);
}
- $exitedServices->push($app);
}
foreach ($dbs as $db) {
if (in_array("$db->id-$db->name", $foundServices)) {
continue;
+ } else {
+ $exitedServices->push($db);
}
- $exitedServices->push($db);
}
}
$exitedServices = $exitedServices->unique('uuid');
@@ -241,11 +243,17 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
$name = data_get($exitedService, 'name');
$fqdn = data_get($exitedService, 'fqdn');
if ($name) {
- $containerName = $fqdn ? "$name, available at $fqdn" : $name;
- } elseif ($fqdn) {
- $containerName = $fqdn;
+ if ($fqdn) {
+ $containerName = "$name, available at $fqdn";
+ } else {
+ $containerName = $name;
+ }
} else {
- $containerName = null;
+ if ($fqdn) {
+ $containerName = $fqdn;
+ } else {
+ $containerName = null;
+ }
}
$projectUuid = data_get($service, 'environment.project.uuid');
$serviceUuid = data_get($service, 'uuid');
@@ -261,8 +269,8 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
}
$notRunningApplications = $this->applications->pluck('id')->diff($foundApplications);
- foreach ($notRunningApplications as $notRunningApplication) {
- $application = $this->applications->where('id', $notRunningApplication)->first();
+ foreach ($notRunningApplications as $applicationId) {
+ $application = $this->applications->where('id', $applicationId)->first();
if (str($application->status)->startsWith('exited')) {
continue;
}
@@ -286,8 +294,8 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
// $this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
}
$notRunningApplicationPreviews = $previews->pluck('id')->diff($foundApplicationPreviews);
- foreach ($notRunningApplicationPreviews as $notRunningApplicationPreview) {
- $preview = $previews->where('id', $notRunningApplicationPreview)->first();
+ foreach ($notRunningApplicationPreviews as $previewId) {
+ $preview = $previews->where('id', $previewId)->first();
if (str($preview->status)->startsWith('exited')) {
continue;
}
@@ -311,21 +319,21 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
// $this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
}
$notRunningDatabases = $databases->pluck('id')->diff($foundDatabases);
- foreach ($notRunningDatabases as $notRunningDatabase) {
- $notRunningDatabase = $databases->where('id', $notRunningDatabase)->first();
- if (str($notRunningDatabase->status)->startsWith('exited')) {
+ foreach ($notRunningDatabases as $database) {
+ $database = $databases->where('id', $database)->first();
+ if (str($database->status)->startsWith('exited')) {
continue;
}
- $notRunningDatabase->update(['status' => 'exited']);
+ $database->update(['status' => 'exited']);
- $name = data_get($notRunningDatabase, 'name');
- $fqdn = data_get($notRunningDatabase, 'fqdn');
+ $name = data_get($database, 'name');
+ $fqdn = data_get($database, 'fqdn');
$containerName = $name;
- $projectUuid = data_get($notRunningDatabase, 'environment.project.uuid');
- $environmentName = data_get($notRunningDatabase, 'environment.name');
- $databaseUuid = data_get($notRunningDatabase, 'uuid');
+ $projectUuid = data_get($database, 'environment.project.uuid');
+ $environmentName = data_get($database, 'environment.name');
+ $databaseUuid = data_get($database, 'uuid');
if ($projectUuid && $databaseUuid && $environmentName) {
$url = base_url().'/project/'.$projectUuid.'/'.$environmentName.'/database/'.$databaseUuid;
@@ -334,7 +342,5 @@ public function handle(Server $server, ?Collection $containers = null, ?Collecti
}
// $this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
}
-
- return null;
}
}
diff --git a/app/Actions/Fortify/CreateNewUser.php b/app/Actions/Fortify/CreateNewUser.php
index d67db2a39b..ea2befd3a8 100644
--- a/app/Actions/Fortify/CreateNewUser.php
+++ b/app/Actions/Fortify/CreateNewUser.php
@@ -34,10 +34,10 @@ public function create(array $input): User
'password' => ['required', Password::defaults(), 'confirmed'],
])->validate();
- if (User::query()->count() == 0) {
+ if (User::count() == 0) {
// If this is the first user, make them the root user
// Team is already created in the database/seeders/ProductionSeeder.php
- $user = User::query()->create([
+ $user = User::create([
'id' => 0,
'name' => $input['name'],
'email' => strtolower($input['email']),
@@ -50,7 +50,7 @@ public function create(array $input): User
$settings->is_registration_enabled = false;
$settings->save();
} else {
- $user = User::query()->create([
+ $user = User::create([
'name' => $input['name'],
'email' => strtolower($input['email']),
'password' => Hash::make($input['password']),
diff --git a/app/Actions/Proxy/CheckConfiguration.php b/app/Actions/Proxy/CheckConfiguration.php
index 70bf5a221a..bdeafd0611 100644
--- a/app/Actions/Proxy/CheckConfiguration.php
+++ b/app/Actions/Proxy/CheckConfiguration.php
@@ -3,7 +3,6 @@
namespace App\Actions\Proxy;
use App\Models\Server;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
class CheckConfiguration
@@ -26,7 +25,7 @@ public function handle(Server $server, bool $reset = false)
$proxy_configuration = str(generate_default_proxy_configuration($server))->trim()->value();
}
if (! $proxy_configuration || is_null($proxy_configuration)) {
- throw new Exception('Could not generate proxy configuration');
+ throw new \Exception('Could not generate proxy configuration');
}
return $proxy_configuration;
diff --git a/app/Actions/Proxy/CheckProxy.php b/app/Actions/Proxy/CheckProxy.php
index 1dc5540c25..6c8dd52347 100644
--- a/app/Actions/Proxy/CheckProxy.php
+++ b/app/Actions/Proxy/CheckProxy.php
@@ -4,7 +4,6 @@
use App\Enums\ProxyTypes;
use App\Models\Server;
-use Exception;
use Illuminate\Support\Facades\Log;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
@@ -33,74 +32,80 @@ public function handle(Server $server, $fromUI = false): bool
}
['uptime' => $uptime, 'error' => $error] = $server->validateConnection();
if (! $uptime) {
- throw new Exception($error);
+ throw new \Exception($error);
}
if (! $server->isProxyShouldRun()) {
if ($fromUI) {
- throw new Exception('Proxy should not run. You selected the Custom Proxy.');
+ throw new \Exception('Proxy should not run. You selected the Custom Proxy.');
+ } else {
+ return false;
}
-
- return false;
}
if ($server->isSwarm()) {
$status = getContainerStatus($server, 'coolify-proxy_traefik');
$server->proxy->set('status', $status);
$server->save();
+ if ($status === 'running') {
+ return false;
+ }
- return $status !== 'running';
- }
- $status = getContainerStatus($server, 'coolify-proxy');
- if ($status === 'running') {
- $server->proxy->set('status', 'running');
- $server->save();
+ return true;
+ } else {
+ $status = getContainerStatus($server, 'coolify-proxy');
+ if ($status === 'running') {
+ $server->proxy->set('status', 'running');
+ $server->save();
- return false;
- }
- if ($server->settings->is_cloudflare_tunnel) {
- return false;
- }
- $ip = $server->ip;
- if ($server->id === 0) {
- $ip = 'host.docker.internal';
- }
- $portsToCheck = ['80', '443'];
- try {
- if ($server->proxyType() !== ProxyTypes::NONE->value) {
- $proxyCompose = CheckConfiguration::run($server);
- if (isset($proxyCompose)) {
- $yaml = Yaml::parse($proxyCompose);
- $portsToCheck = [];
- if ($server->proxyType() === ProxyTypes::TRAEFIK->value) {
- $ports = data_get($yaml, 'services.traefik.ports');
- } elseif ($server->proxyType() === ProxyTypes::CADDY->value) {
- $ports = data_get($yaml, 'services.caddy.ports');
- }
- if (isset($ports)) {
- foreach ($ports as $port) {
- $portsToCheck[] = str($port)->before(':')->value();
+ return false;
+ }
+ if ($server->settings->is_cloudflare_tunnel) {
+ return false;
+ }
+ $ip = $server->ip;
+ if ($server->id === 0) {
+ $ip = 'host.docker.internal';
+ }
+
+ $portsToCheck = ['80', '443'];
+
+ try {
+ if ($server->proxyType() !== ProxyTypes::NONE->value) {
+ $proxyCompose = CheckConfiguration::run($server);
+ if (isset($proxyCompose)) {
+ $yaml = Yaml::parse($proxyCompose);
+ $portsToCheck = [];
+ if ($server->proxyType() === ProxyTypes::TRAEFIK->value) {
+ $ports = data_get($yaml, 'services.traefik.ports');
+ } elseif ($server->proxyType() === ProxyTypes::CADDY->value) {
+ $ports = data_get($yaml, 'services.caddy.ports');
+ }
+ if (isset($ports)) {
+ foreach ($ports as $port) {
+ $portsToCheck[] = str($port)->before(':')->value();
+ }
}
}
+ } else {
+ $portsToCheck = [];
}
- } else {
- $portsToCheck = [];
+ } catch (\Exception $e) {
+ Log::error('Error checking proxy: '.$e->getMessage());
}
- } catch (Exception $e) {
- Log::error('Error checking proxy: '.$e->getMessage());
- }
- if ($portsToCheck === []) {
- return false;
- }
- foreach ($portsToCheck as $portToCheck) {
- $connection = @fsockopen($ip, $portToCheck);
- if (is_resource($connection) && fclose($connection)) {
- if ($fromUI) {
- throw new Exception("Port {$portToCheck} is in use.
You must stop the process using this port.
Docs: https://coolify.io/docs
Discord: https://coollabs.io/discord");
- }
-
+ if (count($portsToCheck) === 0) {
return false;
}
- }
+ foreach ($portsToCheck as $port) {
+ $connection = @fsockopen($ip, $port);
+ if (is_resource($connection) && fclose($connection)) {
+ if ($fromUI) {
+ throw new \Exception("Port $port is in use.
You must stop the process using this port.
Docs: https://coolify.io/docs
Discord: https://coollabs.io/discord");
+ } else {
+ return false;
+ }
+ }
+ }
- return true;
+ return true;
+ }
}
}
diff --git a/app/Actions/Proxy/StartProxy.php b/app/Actions/Proxy/StartProxy.php
index f616f9395c..9bc506d9b5 100644
--- a/app/Actions/Proxy/StartProxy.php
+++ b/app/Actions/Proxy/StartProxy.php
@@ -5,7 +5,6 @@
use App\Enums\ProxyTypes;
use App\Events\ProxyStarted;
use App\Models\Server;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
use Spatie\Activitylog\Models\Activity;
@@ -23,7 +22,7 @@ public function handle(Server $server, bool $async = true, bool $force = false):
$proxy_path = $server->proxyPath();
$configuration = CheckConfiguration::run($server);
if (! $configuration) {
- throw new Exception('Configuration is not synced');
+ throw new \Exception('Configuration is not synced');
}
SaveConfiguration::run($server, $configuration);
$docker_compose_yml_base64 = base64_encode($configuration);
@@ -39,8 +38,10 @@ public function handle(Server $server, bool $async = true, bool $force = false):
"echo 'Successfully started coolify-proxy.'",
]);
} else {
- if (isDev() && $proxyType === ProxyTypes::CADDY->value) {
- $proxy_path = '/data/coolify/proxy/caddy';
+ if (isDev()) {
+ if ($proxyType === ProxyTypes::CADDY->value) {
+ $proxy_path = '/data/coolify/proxy/caddy';
+ }
}
$caddyfile = 'import /dynamic/*.caddy';
$commands = $commands->merge([
@@ -64,13 +65,14 @@ public function handle(Server $server, bool $async = true, bool $force = false):
if ($async) {
return remote_process($commands, $server, callEventOnFinish: 'ProxyStarted', callEventData: $server);
- }
- instant_remote_process($commands, $server);
- $server->proxy->set('status', 'running');
- $server->proxy->set('type', $proxyType);
- $server->save();
- ProxyStarted::dispatch($server);
+ } else {
+ instant_remote_process($commands, $server);
+ $server->proxy->set('status', 'running');
+ $server->proxy->set('type', $proxyType);
+ $server->save();
+ ProxyStarted::dispatch($server);
- return 'OK';
+ return 'OK';
+ }
}
}
diff --git a/app/Actions/Server/ConfigureCloudflared.php b/app/Actions/Server/ConfigureCloudflared.php
index 9364b268e0..fc04e67a45 100644
--- a/app/Actions/Server/ConfigureCloudflared.php
+++ b/app/Actions/Server/ConfigureCloudflared.php
@@ -6,7 +6,6 @@
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
-use Throwable;
class ConfigureCloudflared
{
@@ -40,7 +39,7 @@ public function handle(Server $server, string $cloudflare_token)
'docker compose up -d --remove-orphans',
]);
instant_remote_process($commands, $server);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$server->settings->is_cloudflare_tunnel = false;
$server->settings->save();
throw $e;
diff --git a/app/Actions/Server/InstallDocker.php b/app/Actions/Server/InstallDocker.php
index 4c06afa8d3..cbcb20368c 100644
--- a/app/Actions/Server/InstallDocker.php
+++ b/app/Actions/Server/InstallDocker.php
@@ -4,7 +4,6 @@
use App\Models\Server;
use App\Models\StandaloneDocker;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
class InstallDocker
@@ -16,7 +15,7 @@ public function handle(Server $server)
$dockerVersion = config('constants.docker.minimum_required_version');
$supported_os_type = $server->validateOS();
if (! $supported_os_type) {
- throw new Exception('Server OS type is not supported for automated installation. Please install Docker manually before continuing: documentation.');
+ throw new \Exception('Server OS type is not supported for automated installation. Please install Docker manually before continuing: documentation.');
}
$config = base64_encode('{
"log-driver": "json-file",
@@ -25,9 +24,9 @@ public function handle(Server $server)
"max-file": "3"
}
}');
- $builder = StandaloneDocker::query()->where('server_id', $server->id);
- if ($builder->count() == 0 && $server->id) {
- StandaloneDocker::query()->create([
+ $found = StandaloneDocker::where('server_id', $server->id);
+ if ($found->count() == 0 && $server->id) {
+ StandaloneDocker::create([
'name' => 'coolify',
'network' => 'coolify',
'server_id' => $server->id,
@@ -46,64 +45,65 @@ public function handle(Server $server)
]);
return remote_process($command, $server);
- }
- if ($supported_os_type->contains('debian')) {
- $command = $command->merge([
- "echo 'Installing Prerequisites...'",
- 'apt-get update -y',
- 'command -v curl >/dev/null || apt install -y curl',
- 'command -v wget >/dev/null || apt install -y wget',
- 'command -v git >/dev/null || apt install -y git',
- 'command -v jq >/dev/null || apt install -y jq',
- ]);
- } elseif ($supported_os_type->contains('rhel')) {
- $command = $command->merge([
- "echo 'Installing Prerequisites...'",
- 'command -v curl >/dev/null || dnf install -y curl',
- 'command -v wget >/dev/null || dnf install -y wget',
- 'command -v git >/dev/null || dnf install -y git',
- 'command -v jq >/dev/null || dnf install -y jq',
- ]);
- } elseif ($supported_os_type->contains('sles')) {
- $command = $command->merge([
- "echo 'Installing Prerequisites...'",
- 'zypper update -y',
- 'command -v curl >/dev/null || zypper install -y curl',
- 'command -v wget >/dev/null || zypper install -y wget',
- 'command -v git >/dev/null || zypper install -y git',
- 'command -v jq >/dev/null || zypper install -y jq',
- ]);
- } else {
- throw new Exception('Unsupported OS');
- }
- $command = $command->merge([
- "echo 'Installing Docker Engine...'",
- "curl https://releases.rancher.com/install-docker/{$dockerVersion}.sh | sh || curl https://get.docker.com | sh -s -- --version {$dockerVersion}",
- "echo 'Configuring Docker Engine (merging existing configuration with the required)...'",
- 'test -s /etc/docker/daemon.json && cp /etc/docker/daemon.json "/etc/docker/daemon.json.original-$(date +"%Y%m%d-%H%M%S")"',
- "test ! -s /etc/docker/daemon.json && echo '{$config}' | base64 -d | tee /etc/docker/daemon.json > /dev/null",
- "echo '{$config}' | base64 -d | tee /etc/docker/daemon.json.coolify > /dev/null",
- 'jq . /etc/docker/daemon.json.coolify | tee /etc/docker/daemon.json.coolify.pretty > /dev/null',
- 'mv /etc/docker/daemon.json.coolify.pretty /etc/docker/daemon.json.coolify',
- "jq -s '.[0] * .[1]' /etc/docker/daemon.json.coolify /etc/docker/daemon.json | tee /etc/docker/daemon.json.appended > /dev/null",
- 'mv /etc/docker/daemon.json.appended /etc/docker/daemon.json',
- "echo 'Restarting Docker Engine...'",
- 'systemctl enable docker >/dev/null 2>&1 || true',
- 'systemctl restart docker',
- ]);
- if ($server->isSwarm()) {
- $command = $command->merge([
- 'docker network create --attachable --driver overlay coolify-overlay >/dev/null 2>&1 || true',
- ]);
} else {
+ if ($supported_os_type->contains('debian')) {
+ $command = $command->merge([
+ "echo 'Installing Prerequisites...'",
+ 'apt-get update -y',
+ 'command -v curl >/dev/null || apt install -y curl',
+ 'command -v wget >/dev/null || apt install -y wget',
+ 'command -v git >/dev/null || apt install -y git',
+ 'command -v jq >/dev/null || apt install -y jq',
+ ]);
+ } elseif ($supported_os_type->contains('rhel')) {
+ $command = $command->merge([
+ "echo 'Installing Prerequisites...'",
+ 'command -v curl >/dev/null || dnf install -y curl',
+ 'command -v wget >/dev/null || dnf install -y wget',
+ 'command -v git >/dev/null || dnf install -y git',
+ 'command -v jq >/dev/null || dnf install -y jq',
+ ]);
+ } elseif ($supported_os_type->contains('sles')) {
+ $command = $command->merge([
+ "echo 'Installing Prerequisites...'",
+ 'zypper update -y',
+ 'command -v curl >/dev/null || zypper install -y curl',
+ 'command -v wget >/dev/null || zypper install -y wget',
+ 'command -v git >/dev/null || zypper install -y git',
+ 'command -v jq >/dev/null || zypper install -y jq',
+ ]);
+ } else {
+ throw new \Exception('Unsupported OS');
+ }
$command = $command->merge([
- 'docker network create --attachable coolify >/dev/null 2>&1 || true',
- ]);
- $command = $command->merge([
- "echo 'Done!'",
+ "echo 'Installing Docker Engine...'",
+ "curl https://releases.rancher.com/install-docker/{$dockerVersion}.sh | sh || curl https://get.docker.com | sh -s -- --version {$dockerVersion}",
+ "echo 'Configuring Docker Engine (merging existing configuration with the required)...'",
+ 'test -s /etc/docker/daemon.json && cp /etc/docker/daemon.json "/etc/docker/daemon.json.original-$(date +"%Y%m%d-%H%M%S")"',
+ "test ! -s /etc/docker/daemon.json && echo '{$config}' | base64 -d | tee /etc/docker/daemon.json > /dev/null",
+ "echo '{$config}' | base64 -d | tee /etc/docker/daemon.json.coolify > /dev/null",
+ 'jq . /etc/docker/daemon.json.coolify | tee /etc/docker/daemon.json.coolify.pretty > /dev/null',
+ 'mv /etc/docker/daemon.json.coolify.pretty /etc/docker/daemon.json.coolify',
+ "jq -s '.[0] * .[1]' /etc/docker/daemon.json.coolify /etc/docker/daemon.json | tee /etc/docker/daemon.json.appended > /dev/null",
+ 'mv /etc/docker/daemon.json.appended /etc/docker/daemon.json',
+ "echo 'Restarting Docker Engine...'",
+ 'systemctl enable docker >/dev/null 2>&1 || true',
+ 'systemctl restart docker',
]);
- }
+ if ($server->isSwarm()) {
+ $command = $command->merge([
+ 'docker network create --attachable --driver overlay coolify-overlay >/dev/null 2>&1 || true',
+ ]);
+ } else {
+ $command = $command->merge([
+ 'docker network create --attachable coolify >/dev/null 2>&1 || true',
+ ]);
+ $command = $command->merge([
+ "echo 'Done!'",
+ ]);
+ }
- return remote_process($command, $server);
+ return remote_process($command, $server);
+ }
}
}
diff --git a/app/Actions/Server/ResourcesCheck.php b/app/Actions/Server/ResourcesCheck.php
index dda446f130..e6b90ba380 100644
--- a/app/Actions/Server/ResourcesCheck.php
+++ b/app/Actions/Server/ResourcesCheck.php
@@ -14,7 +14,6 @@
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use Lorisleiva\Actions\Concerns\AsAction;
-use Throwable;
class ResourcesCheck
{
@@ -24,21 +23,19 @@ public function handle()
{
$seconds = 60;
try {
- Application::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- ServiceApplication::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- ServiceDatabase::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- StandalonePostgresql::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- StandaloneRedis::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- StandaloneMongodb::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- StandaloneMysql::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- StandaloneMariadb::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- StandaloneKeydb::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- StandaloneDragonfly::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- StandaloneClickhouse::query()->where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
- } catch (Throwable $e) {
+ Application::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ ServiceApplication::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ ServiceDatabase::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ StandalonePostgresql::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ StandaloneRedis::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ StandaloneMongodb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ StandaloneMysql::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ StandaloneMariadb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ StandaloneKeydb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ StandaloneDragonfly::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ StandaloneClickhouse::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
+ } catch (\Throwable $e) {
return handleError($e);
}
-
- return null;
}
}
diff --git a/app/Actions/Server/ServerCheck.php b/app/Actions/Server/ServerCheck.php
index ff3cb449cd..75b8501f32 100644
--- a/app/Actions/Server/ServerCheck.php
+++ b/app/Actions/Server/ServerCheck.php
@@ -16,7 +16,6 @@
use App\Notifications\Container\ContainerRestarted;
use Illuminate\Support\Arr;
use Lorisleiva\Actions\Concerns\AsAction;
-use Throwable;
class ServerCheck
{
@@ -62,11 +61,11 @@ public function handle(Server $server, $data = null)
}
if (isset($containerReplicates)) {
- foreach ($containerReplicates as $containerReplicate) {
- $name = data_get($containerReplicate, 'Name');
- $this->containers = $this->containers->map(function ($container) use ($name, $containerReplicate) {
+ foreach ($containerReplicates as $containerReplica) {
+ $name = data_get($containerReplica, 'Name');
+ $this->containers = $this->containers->map(function ($container) use ($name, $containerReplica) {
if (data_get($container, 'Spec.Name') === $name) {
- $replicas = data_get($containerReplicate, 'Replicas');
+ $replicas = data_get($containerReplica, 'Replicas');
$running = str($replicas)->explode('/')[0];
$total = str($replicas)->explode('/')[1];
if ($running === $total) {
@@ -96,9 +95,9 @@ public function handle(Server $server, $data = null)
$foundProxyContainer = $this->containers->filter(function ($value, $key) {
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === 'coolify-proxy_traefik';
+ } else {
+ return data_get($value, 'Name') === '/coolify-proxy';
}
-
- return data_get($value, 'Name') === '/coolify-proxy';
})->first();
if (! $foundProxyContainer) {
try {
@@ -107,7 +106,7 @@ public function handle(Server $server, $data = null)
StartProxy::run($this->server, false);
$this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server));
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
}
} else {
$this->server->proxy->status = data_get($foundProxyContainer, 'State.Status');
@@ -117,11 +116,9 @@ public function handle(Server $server, $data = null)
}
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
-
- return null;
}
private function checkLogDrainContainer()
@@ -144,10 +141,12 @@ private function checkContainers()
foreach ($this->containers as $container) {
if ($this->isSentinel) {
$labels = Arr::undot(data_get($container, 'labels'));
- } elseif ($this->server->isSwarm()) {
- $labels = Arr::undot(data_get($container, 'Spec.Labels'));
} else {
- $labels = Arr::undot(data_get($container, 'Config.Labels'));
+ if ($this->server->isSwarm()) {
+ $labels = Arr::undot(data_get($container, 'Spec.Labels'));
+ } else {
+ $labels = Arr::undot(data_get($container, 'Config.Labels'));
+ }
}
$managed = data_get($labels, 'coolify.managed');
if (! $managed) {
@@ -178,12 +177,12 @@ private function checkContainers()
if (str($applicationId)->contains('-')) {
$applicationId = str($applicationId)->before('-');
}
- $preview = ApplicationPreview::query()->where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();
+ $preview = ApplicationPreview::where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();
if ($preview) {
$preview->update(['status' => $containerStatus]);
}
} else {
- $application = Application::query()->where('id', $applicationId)->first();
+ $application = Application::where('id', $applicationId)->first();
if ($application) {
$application->update([
'status' => $containerStatus,
@@ -195,14 +194,14 @@ private function checkContainers()
// Service
$subType = data_get($labels, 'coolify.service.subType');
$subId = data_get($labels, 'coolify.service.subId');
- $service = Service::query()->where('id', $serviceId)->first();
+ $service = Service::where('id', $serviceId)->first();
if (! $service) {
continue;
}
if ($subType === 'application') {
- $service = ServiceApplication::query()->where('id', $subId)->first();
+ $service = ServiceApplication::where('id', $subId)->first();
} else {
- $service = ServiceDatabase::query()->where('id', $subId)->first();
+ $service = ServiceDatabase::where('id', $subId)->first();
}
if ($service) {
$service->update([
@@ -215,12 +214,14 @@ private function checkContainers()
$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {
if ($this->isSentinel) {
return data_get($value, 'name') === $uuid.'-proxy';
- }
- if ($this->server->isSwarm()) {
- return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
- }
+ } else {
- return data_get($value, 'Name') === "/$uuid-proxy";
+ if ($this->server->isSwarm()) {
+ return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
+ } else {
+ return data_get($value, 'Name') === "/$uuid-proxy";
+ }
+ }
})->first();
if (! $foundTcpProxy) {
StartDatabaseProxy::run($service);
@@ -245,12 +246,14 @@ private function checkContainers()
$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {
if ($this->isSentinel) {
return data_get($value, 'name') === $uuid.'-proxy';
- }
- if ($this->server->isSwarm()) {
- return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
- }
+ } else {
+ if ($this->server->isSwarm()) {
+ return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
+ } else {
- return data_get($value, 'Name') === "/$uuid-proxy";
+ return data_get($value, 'Name') === "/$uuid-proxy";
+ }
+ }
})->first();
if (! $foundTcpProxy) {
StartDatabaseProxy::run($database);
diff --git a/app/Actions/Server/StartLogDrain.php b/app/Actions/Server/StartLogDrain.php
index c3752ef16d..0d28a00994 100644
--- a/app/Actions/Server/StartLogDrain.php
+++ b/app/Actions/Server/StartLogDrain.php
@@ -3,9 +3,7 @@
namespace App\Actions\Server;
use App\Models\Server;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
-use Throwable;
class StartLogDrain
{
@@ -33,10 +31,9 @@ public function handle(Server $server)
try {
if ($type === 'none') {
return 'No log drain is enabled.';
- }
- if ($type === 'newrelic') {
+ } elseif ($type === 'newrelic') {
if (! $server->settings->is_logdrain_newrelic_enabled) {
- throw new Exception('New Relic log drain is not enabled.');
+ throw new \Exception('New Relic log drain is not enabled.');
}
$config = base64_encode("
[SERVICE]
@@ -71,7 +68,7 @@ public function handle(Server $server)
");
} elseif ($type === 'highlight') {
if (! $server->settings->is_logdrain_highlight_enabled) {
- throw new Exception('Highlight log drain is not enabled.');
+ throw new \Exception('Highlight log drain is not enabled.');
}
$config = base64_encode('
[SERVICE]
@@ -92,7 +89,7 @@ public function handle(Server $server)
');
} elseif ($type === 'axiom') {
if (! $server->settings->is_logdrain_axiom_enabled) {
- throw new Exception('Axiom log drain is not enabled.');
+ throw new \Exception('Axiom log drain is not enabled.');
}
$config = base64_encode("
[SERVICE]
@@ -132,12 +129,12 @@ public function handle(Server $server)
");
} elseif ($type === 'custom') {
if (! $server->settings->is_logdrain_custom_enabled) {
- throw new Exception('Custom log drain is not enabled.');
+ throw new \Exception('Custom log drain is not enabled.');
}
$config = base64_encode($server->settings->logdrain_custom_config);
$parsers = base64_encode($server->settings->logdrain_custom_config_parser);
} else {
- throw new Exception('Unknown log drain type.');
+ throw new \Exception('Unknown log drain type.');
}
if ($type !== 'custom') {
$parsers = base64_encode("
@@ -210,7 +207,7 @@ public function handle(Server $server)
"touch $config_path/.env",
];
} else {
- throw new Exception('Unknown log drain type.');
+ throw new \Exception('Unknown log drain type.');
}
$restart_command = [
"echo 'Starting Fluent Bit'",
@@ -219,7 +216,7 @@ public function handle(Server $server)
$command = array_merge($command, $add_envs_command, $restart_command);
return instant_remote_process($command, $server);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
}
diff --git a/app/Actions/Server/StartSentinel.php b/app/Actions/Server/StartSentinel.php
index e36ec34c24..587ac4a8db 100644
--- a/app/Actions/Server/StartSentinel.php
+++ b/app/Actions/Server/StartSentinel.php
@@ -3,7 +3,6 @@
namespace App\Actions\Server;
use App\Models\Server;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
class StartSentinel
@@ -28,7 +27,7 @@ public function handle(Server $server, bool $restart = false, ?string $latestVer
$mountDir = '/data/coolify/sentinel';
$image = "ghcr.io/coollabsio/sentinel:$version";
if (! $endpoint) {
- throw new Exception('You should set FQDN in Instance Settings.');
+ throw new \Exception('You should set FQDN in Instance Settings.');
}
$environments = [
'TOKEN' => $token,
diff --git a/app/Actions/Server/StopLogDrain.php b/app/Actions/Server/StopLogDrain.php
index 79bd8ee1cc..96c2466dec 100644
--- a/app/Actions/Server/StopLogDrain.php
+++ b/app/Actions/Server/StopLogDrain.php
@@ -4,7 +4,6 @@
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
-use Throwable;
class StopLogDrain
{
@@ -14,7 +13,7 @@ public function handle(Server $server)
{
try {
return instant_remote_process(['docker rm -f coolify-log-drain'], $server, false);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
}
diff --git a/app/Actions/Server/UpdateCoolify.php b/app/Actions/Server/UpdateCoolify.php
index add2355a8e..be9b4062c9 100644
--- a/app/Actions/Server/UpdateCoolify.php
+++ b/app/Actions/Server/UpdateCoolify.php
@@ -25,7 +25,7 @@ public function handle($manual_update = false)
return;
}
$settings = instanceSettings();
- $this->server = Server::query()->find(0);
+ $this->server = Server::find(0);
if (! $this->server) {
return;
}
diff --git a/app/Actions/Server/ValidateServer.php b/app/Actions/Server/ValidateServer.php
index 36f10711f9..55b37a77c0 100644
--- a/app/Actions/Server/ValidateServer.php
+++ b/app/Actions/Server/ValidateServer.php
@@ -3,7 +3,6 @@
namespace App\Actions\Server;
use App\Models\Server;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
class ValidateServer
@@ -35,7 +34,7 @@ public function handle(Server $server)
$server->update([
'validation_logs' => $this->error,
]);
- throw new Exception($this->error);
+ throw new \Exception($this->error);
}
$this->supported_os_type = $server->validateOS();
if (! $this->supported_os_type) {
@@ -43,7 +42,7 @@ public function handle(Server $server)
$server->update([
'validation_logs' => $this->error,
]);
- throw new Exception($this->error);
+ throw new \Exception($this->error);
}
$this->docker_installed = $server->validateDockerEngine();
@@ -53,17 +52,18 @@ public function handle(Server $server)
$server->update([
'validation_logs' => $this->error,
]);
- throw new Exception($this->error);
+ throw new \Exception($this->error);
}
$this->docker_version = $server->validateDockerEngineVersion();
if ($this->docker_version) {
return 'OK';
+ } else {
+ $this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: documentation.';
+ $server->update([
+ 'validation_logs' => $this->error,
+ ]);
+ throw new \Exception($this->error);
}
- $this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: documentation.';
- $server->update([
- 'validation_logs' => $this->error,
- ]);
- throw new Exception($this->error);
}
}
diff --git a/app/Actions/Service/DeleteService.php b/app/Actions/Service/DeleteService.php
index 65d2fdea24..9b87454dac 100644
--- a/app/Actions/Service/DeleteService.php
+++ b/app/Actions/Service/DeleteService.php
@@ -4,7 +4,6 @@
use App\Actions\Server\CleanupDocker;
use App\Models\Service;
-use Exception;
use Illuminate\Support\Facades\Log;
use Lorisleiva\Actions\Concerns\AsAction;
@@ -33,15 +32,17 @@ public function handle(Service $service, bool $deleteConfigurations, bool $delet
$storagesToDelete->push($storage);
}
}
- foreach ($storagesToDelete as $storageToDelete) {
- $commands[] = "docker volume rm -f $storageToDelete->name";
+ foreach ($storagesToDelete as $storage) {
+ $commands[] = "docker volume rm -f $storage->name";
}
// Execute volume deletion first, this must be done first otherwise volumes will not be deleted.
- foreach ($commands as $command) {
- $result = instant_remote_process([$command], $server, false);
- if ($result !== null && $result !== 0) {
- Log::error('Error deleting volumes: '.$result);
+ if (! empty($commands)) {
+ foreach ($commands as $command) {
+ $result = instant_remote_process([$command], $server, false);
+ if ($result !== null && $result !== 0) {
+ Log::error('Error deleting volumes: '.$result);
+ }
}
}
}
@@ -51,8 +52,8 @@ public function handle(Service $service, bool $deleteConfigurations, bool $delet
}
instant_remote_process(["docker rm -f $service->uuid"], $server, throwError: false);
- } catch (Exception $e) {
- throw new Exception($e->getMessage(), $e->getCode(), $e);
+ } catch (\Exception $e) {
+ throw new \Exception($e->getMessage());
} finally {
if ($deleteConfigurations) {
$service->delete_configurations();
diff --git a/app/Actions/Service/StopService.php b/app/Actions/Service/StopService.php
index b99cf190ae..95b08b4370 100644
--- a/app/Actions/Service/StopService.php
+++ b/app/Actions/Service/StopService.php
@@ -4,7 +4,6 @@
use App\Actions\Server\CleanupDocker;
use App\Models\Service;
-use Exception;
use Lorisleiva\Actions\Concerns\AsAction;
class StopService
@@ -30,10 +29,8 @@ public function handle(Service $service, bool $isDeleteOperation = false, bool $
CleanupDocker::dispatch($server, true);
}
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return $e->getMessage();
}
-
- return null;
}
}
diff --git a/app/Actions/Shared/ComplexStatusCheck.php b/app/Actions/Shared/ComplexStatusCheck.php
index 1ce30a297a..5a7ba6637c 100644
--- a/app/Actions/Shared/ComplexStatusCheck.php
+++ b/app/Actions/Shared/ComplexStatusCheck.php
@@ -20,10 +20,11 @@ public function handle(Application $application)
$application->update(['status' => 'exited:unhealthy']);
continue;
- }
- $application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited:unhealthy']);
+ } else {
+ $application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited:unhealthy']);
- continue;
+ continue;
+ }
}
$container = instant_remote_process(["docker container inspect $(docker container ls -q --filter 'label=coolify.applicationId={$application->id}' --filter 'label=coolify.pullRequestId=0') --format '{{json .}}'"], $server, false);
$container = format_docker_command_output_to_json($container);
@@ -43,14 +44,16 @@ public function handle(Application $application)
$additional_server->updateExistingPivot($server->id, ['status' => "$containerStatus:$containerHealth"]);
}
}
- } elseif ($is_main_server) {
- $application->update(['status' => 'exited:unhealthy']);
-
- continue;
} else {
- $application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited:unhealthy']);
+ if ($is_main_server) {
+ $application->update(['status' => 'exited:unhealthy']);
+
+ continue;
+ } else {
+ $application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited:unhealthy']);
- continue;
+ continue;
+ }
}
}
}
diff --git a/app/Actions/Shared/PullImage.php b/app/Actions/Shared/PullImage.php
index 38c9b47715..4bd1cf4530 100644
--- a/app/Actions/Shared/PullImage.php
+++ b/app/Actions/Shared/PullImage.php
@@ -9,20 +9,20 @@ class PullImage
{
use AsAction;
- public function handle(Service $service)
+ public function handle(Service $resource)
{
- $service->saveComposeConfigs();
+ $resource->saveComposeConfigs();
- $commands[] = 'cd '.$service->workdir();
- $commands[] = "echo 'Saved configuration files to {$service->workdir()}.'";
+ $commands[] = 'cd '.$resource->workdir();
+ $commands[] = "echo 'Saved configuration files to {$resource->workdir()}.'";
$commands[] = 'docker compose pull';
- $server = data_get($service, 'server');
+ $server = data_get($resource, 'server');
if (! $server) {
return;
}
- instant_remote_process($commands, $service->server);
+ instant_remote_process($commands, $resource->server);
}
}
diff --git a/app/Console/Commands/AdminRemoveUser.php b/app/Console/Commands/AdminRemoveUser.php
index c1b6d58283..d4534399cd 100644
--- a/app/Console/Commands/AdminRemoveUser.php
+++ b/app/Console/Commands/AdminRemoveUser.php
@@ -3,7 +3,6 @@
namespace App\Console\Commands;
use App\Models\User;
-use Exception;
use Illuminate\Console\Command;
class AdminRemoveUser extends Command
@@ -47,7 +46,7 @@ public function handle()
$team->delete();
}
$user->delete();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->error('Failed to remove user.');
$this->error($e->getMessage());
diff --git a/app/Console/Commands/CheckApplicationDeploymentQueue.php b/app/Console/Commands/CheckApplicationDeploymentQueue.php
index 1c8eb25972..e89d26f2c3 100644
--- a/app/Console/Commands/CheckApplicationDeploymentQueue.php
+++ b/app/Console/Commands/CheckApplicationDeploymentQueue.php
@@ -15,7 +15,7 @@ class CheckApplicationDeploymentQueue extends Command
public function handle()
{
$seconds = $this->option('seconds');
- $deployments = ApplicationDeploymentQueue::query()->whereIn('status', [
+ $deployments = ApplicationDeploymentQueue::whereIn('status', [
ApplicationDeploymentStatus::IN_PROGRESS,
ApplicationDeploymentStatus::QUEUED,
])->where('created_at', '<=', now()->subSeconds($seconds))->get();
@@ -40,11 +40,11 @@ public function handle()
}
}
- private function cancelDeployment(ApplicationDeploymentQueue $applicationDeploymentQueue)
+ private function cancelDeployment(ApplicationDeploymentQueue $deployment)
{
- $applicationDeploymentQueue->update(['status' => ApplicationDeploymentStatus::FAILED]);
- if ($applicationDeploymentQueue->server?->isFunctional()) {
- remote_process(['docker rm -f '.$applicationDeploymentQueue->deployment_uuid], $applicationDeploymentQueue->server, false);
+ $deployment->update(['status' => ApplicationDeploymentStatus::FAILED]);
+ if ($deployment->server?->isFunctional()) {
+ remote_process(['docker rm -f '.$deployment->deployment_uuid], $deployment->server, false);
}
}
}
diff --git a/app/Console/Commands/CleanupApplicationDeploymentQueue.php b/app/Console/Commands/CleanupApplicationDeploymentQueue.php
index badc0737a6..3aae28ae60 100644
--- a/app/Console/Commands/CleanupApplicationDeploymentQueue.php
+++ b/app/Console/Commands/CleanupApplicationDeploymentQueue.php
@@ -3,7 +3,6 @@
namespace App\Console\Commands;
use App\Models\ApplicationDeploymentQueue;
-use App\Models\Server;
use Illuminate\Console\Command;
class CleanupApplicationDeploymentQueue extends Command
@@ -15,9 +14,9 @@ class CleanupApplicationDeploymentQueue extends Command
public function handle()
{
$team_id = $this->option('team-id');
- $servers = Server::query()->where('team_id', $team_id)->get();
+ $servers = \App\Models\Server::where('team_id', $team_id)->get();
foreach ($servers as $server) {
- $deployments = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->where('server_id', $server->id)->get();
+ $deployments = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->where('server_id', $server->id)->get();
foreach ($deployments as $deployment) {
$deployment->update(['status' => 'failed']);
instant_remote_process(['docker rm -f '.$deployment->deployment_uuid], $server, false);
diff --git a/app/Console/Commands/CleanupDatabase.php b/app/Console/Commands/CleanupDatabase.php
index 7d57b8e8d5..a0adc8b36b 100644
--- a/app/Console/Commands/CleanupDatabase.php
+++ b/app/Console/Commands/CleanupDatabase.php
@@ -18,14 +18,19 @@ public function handle()
} else {
echo "Running database cleanup in dry-run mode...\n";
}
- $keep_days = isCloud() ? $this->option('keep-days') ?? 60 : $this->option('keep-days') ?? 60;
+ if (isCloud()) {
+ // Later on we can increase this to 180 days or dynamically set
+ $keep_days = $this->option('keep-days') ?? 60;
+ } else {
+ $keep_days = $this->option('keep-days') ?? 60;
+ }
echo "Keep days: $keep_days\n";
// Cleanup failed jobs table
- $builder = DB::table('failed_jobs')->where('failed_at', '<', now()->subDays(1));
- $count = $builder->count();
+ $failed_jobs = DB::table('failed_jobs')->where('failed_at', '<', now()->subDays(1));
+ $count = $failed_jobs->count();
echo "Delete $count entries from failed_jobs.\n";
if ($this->option('yes')) {
- $builder->delete();
+ $failed_jobs->delete();
}
// Cleanup sessions table
diff --git a/app/Console/Commands/CleanupStuckedResources.php b/app/Console/Commands/CleanupStuckedResources.php
index c24ec7344f..def3d5a2c5 100644
--- a/app/Console/Commands/CleanupStuckedResources.php
+++ b/app/Console/Commands/CleanupStuckedResources.php
@@ -21,7 +21,6 @@
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use Illuminate\Console\Command;
-use Throwable;
class CleanupStuckedResources extends Command
{
@@ -43,18 +42,18 @@ private function cleanup_stucked_resources()
foreach ($servers as $server) {
CleanupHelperContainersJob::dispatch($server);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stucked resources: {$e->getMessage()}\n";
}
try {
- $applicationsDeploymentQueue = ApplicationDeploymentQueue::query()->get();
+ $applicationsDeploymentQueue = ApplicationDeploymentQueue::get();
foreach ($applicationsDeploymentQueue as $applicationDeploymentQueue) {
if (is_null($applicationDeploymentQueue->application)) {
echo "Deleting stuck application deployment queue: {$applicationDeploymentQueue->id}\n";
$applicationDeploymentQueue->delete();
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck application deployment queue: {$e->getMessage()}\n";
}
try {
@@ -63,18 +62,18 @@ private function cleanup_stucked_resources()
echo "Deleting stuck application: {$application->name}\n";
$application->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck application: {$e->getMessage()}\n";
}
try {
- $applicationsPreviews = ApplicationPreview::query()->get();
+ $applicationsPreviews = ApplicationPreview::get();
foreach ($applicationsPreviews as $applicationPreview) {
if (! data_get($applicationPreview, 'application')) {
echo "Deleting stuck application preview: {$applicationPreview->uuid}\n";
$applicationPreview->delete();
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck application: {$e->getMessage()}\n";
}
try {
@@ -83,16 +82,16 @@ private function cleanup_stucked_resources()
echo "Deleting stuck postgresql: {$postgresql->name}\n";
$postgresql->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck postgresql: {$e->getMessage()}\n";
}
try {
$redis = StandaloneRedis::withTrashed()->whereNotNull('deleted_at')->get();
- foreach ($redis as $redi) {
- echo "Deleting stuck redis: {$redi->name}\n";
- $redi->forceDelete();
+ foreach ($redis as $redis) {
+ echo "Deleting stuck redis: {$redis->name}\n";
+ $redis->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck redis: {$e->getMessage()}\n";
}
try {
@@ -101,7 +100,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck keydb: {$keydb->name}\n";
$keydb->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck keydb: {$e->getMessage()}\n";
}
try {
@@ -110,7 +109,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck dragonfly: {$dragonfly->name}\n";
$dragonfly->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck dragonfly: {$e->getMessage()}\n";
}
try {
@@ -119,7 +118,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck clickhouse: {$clickhouse->name}\n";
$clickhouse->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck clickhouse: {$e->getMessage()}\n";
}
try {
@@ -128,7 +127,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck mongodb: {$mongodb->name}\n";
$mongodb->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck mongodb: {$e->getMessage()}\n";
}
try {
@@ -137,7 +136,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck mysql: {$mysql->name}\n";
$mysql->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck mysql: {$e->getMessage()}\n";
}
try {
@@ -146,7 +145,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck mariadb: {$mariadb->name}\n";
$mariadb->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck mariadb: {$e->getMessage()}\n";
}
try {
@@ -155,7 +154,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck service: {$service->name}\n";
$service->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck service: {$e->getMessage()}\n";
}
try {
@@ -164,7 +163,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck serviceapp: {$serviceApp->name}\n";
$serviceApp->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck serviceapp: {$e->getMessage()}\n";
}
try {
@@ -173,7 +172,7 @@ private function cleanup_stucked_resources()
echo "Deleting stuck serviceapp: {$serviceDb->name}\n";
$serviceDb->forceDelete();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck serviceapp: {$e->getMessage()}\n";
}
try {
@@ -184,7 +183,7 @@ private function cleanup_stucked_resources()
$scheduled_task->delete();
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck scheduledtasks: {$e->getMessage()}\n";
}
@@ -196,7 +195,7 @@ private function cleanup_stucked_resources()
$scheduled_backup->delete();
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning stuck scheduledbackups: {$e->getMessage()}\n";
}
@@ -223,7 +222,7 @@ private function cleanup_stucked_resources()
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in application: {$e->getMessage()}\n";
}
try {
@@ -248,32 +247,32 @@ private function cleanup_stucked_resources()
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in postgresql: {$e->getMessage()}\n";
}
try {
$redis = StandaloneRedis::all();
- foreach ($redis as $redi) {
- if (! data_get($redi, 'environment')) {
- echo 'Redis without environment: '.$redi->name.'\n';
- $redi->forceDelete();
+ foreach ($redis as $redis) {
+ if (! data_get($redis, 'environment')) {
+ echo 'Redis without environment: '.$redis->name.'\n';
+ $redis->forceDelete();
continue;
}
- if (! $redi->destination()) {
- echo 'Redis without destination: '.$redi->name.'\n';
- $redi->forceDelete();
+ if (! $redis->destination()) {
+ echo 'Redis without destination: '.$redis->name.'\n';
+ $redis->forceDelete();
continue;
}
- if (! data_get($redi, 'destination.server')) {
- echo 'Redis without server: '.$redi->name.'\n';
- $redi->forceDelete();
+ if (! data_get($redis, 'destination.server')) {
+ echo 'Redis without server: '.$redis->name.'\n';
+ $redis->forceDelete();
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in redis: {$e->getMessage()}\n";
}
@@ -299,7 +298,7 @@ private function cleanup_stucked_resources()
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in mongodb: {$e->getMessage()}\n";
}
@@ -325,7 +324,7 @@ private function cleanup_stucked_resources()
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in mysql: {$e->getMessage()}\n";
}
@@ -351,7 +350,7 @@ private function cleanup_stucked_resources()
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in mariadb: {$e->getMessage()}\n";
}
@@ -377,33 +376,33 @@ private function cleanup_stucked_resources()
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in service: {$e->getMessage()}\n";
}
try {
$serviceApplications = ServiceApplication::all();
- foreach ($serviceApplications as $serviceApplication) {
- if (! data_get($serviceApplication, 'service')) {
- echo 'ServiceApplication without service: '.$serviceApplication->name.'\n';
- $serviceApplication->forceDelete();
+ foreach ($serviceApplications as $service) {
+ if (! data_get($service, 'service')) {
+ echo 'ServiceApplication without service: '.$service->name.'\n';
+ $service->forceDelete();
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in serviceApplications: {$e->getMessage()}\n";
}
try {
$serviceDatabases = ServiceDatabase::all();
- foreach ($serviceDatabases as $serviceDatabase) {
- if (! data_get($serviceDatabase, 'service')) {
- echo 'ServiceDatabase without service: '.$serviceDatabase->name.'\n';
- $serviceDatabase->forceDelete();
+ foreach ($serviceDatabases as $service) {
+ if (! data_get($service, 'service')) {
+ echo 'ServiceDatabase without service: '.$service->name.'\n';
+ $service->forceDelete();
continue;
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in ServiceDatabases: {$e->getMessage()}\n";
}
}
diff --git a/app/Console/Commands/CleanupUnreachableServers.php b/app/Console/Commands/CleanupUnreachableServers.php
index 4182e46680..def01b2651 100644
--- a/app/Console/Commands/CleanupUnreachableServers.php
+++ b/app/Console/Commands/CleanupUnreachableServers.php
@@ -14,7 +14,7 @@ class CleanupUnreachableServers extends Command
public function handle()
{
echo "Running unreachable server cleanup...\n";
- $servers = Server::query()->where('unreachable_count', 3)->where('unreachable_notification_sent', true)->where('updated_at', '<', now()->subDays(7))->get();
+ $servers = Server::where('unreachable_count', 3)->where('unreachable_notification_sent', true)->where('updated_at', '<', now()->subDays(7))->get();
if ($servers->count() > 0) {
foreach ($servers as $server) {
echo "Cleanup unreachable server ($server->id) with name $server->name";
diff --git a/app/Console/Commands/CloudCheckSubscription.php b/app/Console/Commands/CloudCheckSubscription.php
index ac1d258b83..6e237e84b2 100644
--- a/app/Console/Commands/CloudCheckSubscription.php
+++ b/app/Console/Commands/CloudCheckSubscription.php
@@ -4,7 +4,6 @@
use App\Models\Team;
use Illuminate\Console\Command;
-use Stripe\StripeClient;
class CloudCheckSubscription extends Command
{
@@ -27,19 +26,19 @@ class CloudCheckSubscription extends Command
*/
public function handle()
{
- $stripeClient = new StripeClient(config('subscription.stripe_api_key'));
- $activeSubscribers = Team::query()->whereRelation('subscription', 'stripe_invoice_paid', true)->get();
- foreach ($activeSubscribers as $activeSubscriber) {
- $stripeSubscriptionId = $activeSubscriber->subscription->stripe_subscription_id;
- $stripeInvoicePaid = $activeSubscriber->subscription->stripe_invoice_paid;
- $stripeCustomerId = $activeSubscriber->subscription->stripe_customer_id;
+ $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key'));
+ $activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->get();
+ foreach ($activeSubscribers as $team) {
+ $stripeSubscriptionId = $team->subscription->stripe_subscription_id;
+ $stripeInvoicePaid = $team->subscription->stripe_invoice_paid;
+ $stripeCustomerId = $team->subscription->stripe_customer_id;
if (! $stripeSubscriptionId) {
- echo "Team {$activeSubscriber->id} has no subscription, but invoice status is: {$stripeInvoicePaid}\n";
+ echo "Team {$team->id} has no subscription, but invoice status is: {$stripeInvoicePaid}\n";
echo "Link on Stripe: https://dashboard.stripe.com/customers/{$stripeCustomerId}\n";
continue;
}
- $subscription = $stripeClient->subscriptions->retrieve($stripeSubscriptionId);
+ $subscription = $stripe->subscriptions->retrieve($stripeSubscriptionId);
if ($subscription->status === 'active') {
continue;
}
diff --git a/app/Console/Commands/CloudCleanupSubscriptions.php b/app/Console/Commands/CloudCleanupSubscriptions.php
index f6afeeadf3..9dc6e24f57 100644
--- a/app/Console/Commands/CloudCleanupSubscriptions.php
+++ b/app/Console/Commands/CloudCleanupSubscriptions.php
@@ -4,9 +4,7 @@
use App\Events\ServerReachabilityChanged;
use App\Models\Team;
-use Exception;
use Illuminate\Console\Command;
-use Stripe\StripeClient;
class CloudCleanupSubscriptions extends Command
{
@@ -23,7 +21,7 @@ public function handle()
return;
}
$this->info('Cleaning up subcriptions teams');
- $stripeClient = new StripeClient(config('subscription.stripe_api_key'));
+ $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key'));
$teams = Team::all()->filter(function ($team) {
return $team->id !== 0;
@@ -49,33 +47,34 @@ public function handle()
$this->disableServers($team);
continue;
- }
- $subscription = $stripeClient->subscriptions->retrieve(data_get($team, 'subscription.stripe_subscription_id'), []);
- $status = data_get($subscription, 'status');
- if ($status === 'active' || $status === 'past_due') {
- $team->subscription->update([
- 'stripe_invoice_paid' => true,
- 'stripe_trial_already_ended' => false,
- ]);
-
- continue;
- }
- $this->info('Subscription status: '.$status);
- $this->info('Subscription id: '.data_get($team, 'subscription.stripe_subscription_id'));
- $confirm = $this->confirm('Do you want to cancel the subscription?', true);
- if (! $confirm) {
- $this->info("Skipping team {$team->id}");
} else {
- $this->info("Cancelling subscription for team {$team->id}");
- $team->subscription->update([
- 'stripe_invoice_paid' => false,
- 'stripe_trial_already_ended' => false,
- 'stripe_subscription_id' => null,
- ]);
- $this->disableServers($team);
+ $subscription = $stripe->subscriptions->retrieve(data_get($team, 'subscription.stripe_subscription_id'), []);
+ $status = data_get($subscription, 'status');
+ if ($status === 'active' || $status === 'past_due') {
+ $team->subscription->update([
+ 'stripe_invoice_paid' => true,
+ 'stripe_trial_already_ended' => false,
+ ]);
+
+ continue;
+ }
+ $this->info('Subscription status: '.$status);
+ $this->info('Subscription id: '.data_get($team, 'subscription.stripe_subscription_id'));
+ $confirm = $this->confirm('Do you want to cancel the subscription?', true);
+ if (! $confirm) {
+ $this->info("Skipping team {$team->id}");
+ } else {
+ $this->info("Cancelling subscription for team {$team->id}");
+ $team->subscription->update([
+ 'stripe_invoice_paid' => false,
+ 'stripe_trial_already_ended' => false,
+ 'stripe_subscription_id' => null,
+ ]);
+ $this->disableServers($team);
+ }
}
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->error($e->getMessage());
return;
diff --git a/app/Console/Commands/Dev.php b/app/Console/Commands/Dev.php
index 9beb4f4b64..257de0a927 100644
--- a/app/Console/Commands/Dev.php
+++ b/app/Console/Commands/Dev.php
@@ -33,7 +33,7 @@ public function generateOpenApi()
// Generate OpenAPI documentation
echo "Generating OpenAPI documentation.\n";
// https://github.com/OAI/OpenAPI-Specification/releases
- $processResult = Process::run([
+ $process = Process::run([
'/var/www/html/vendor/bin/openapi',
'app',
'-o',
@@ -41,11 +41,11 @@ public function generateOpenApi()
'--version',
'3.1.0',
]);
- $error = $processResult->errorOutput();
+ $error = $process->errorOutput();
$error = preg_replace('/^.*an object literal,.*$/m', '', $error);
$error = preg_replace('/^\h*\v+/m', '', $error);
echo $error;
- echo $processResult->output();
+ echo $process->output();
// Convert YAML to JSON
$yaml = file_get_contents('openapi.yaml');
$json = json_encode(Yaml::parse($yaml), JSON_PRETTY_PRINT);
@@ -69,7 +69,7 @@ public function init()
}
// Seed database if it's empty
- $settings = InstanceSettings::query()->find(0);
+ $settings = InstanceSettings::find(0);
if (! $settings) {
echo "Initializing instance, seeding database.\n";
Artisan::call('migrate --seed');
diff --git a/app/Console/Commands/Emails.php b/app/Console/Commands/Emails.php
index a55c515d70..a022d54dc6 100644
--- a/app/Console/Commands/Emails.php
+++ b/app/Console/Commands/Emails.php
@@ -12,6 +12,7 @@
use App\Notifications\Application\DeploymentSuccess;
use App\Notifications\Application\StatusChanged;
use App\Notifications\Database\BackupFailed;
+use App\Notifications\Database\BackupSuccess;
use App\Notifications\Test;
use Exception;
use Illuminate\Console\Command;
@@ -42,7 +43,7 @@ class Emails extends Command
/**
* Execute the console command.
*/
- private ?MailMessage $mailMessage = null;
+ private ?MailMessage $mail = null;
private ?string $email = null;
@@ -68,13 +69,15 @@ public function handle()
$emailsGathered = ['realusers-before-trial', 'realusers-server-lost-connection'];
if (isDev()) {
$this->email = 'test@example.com';
- } elseif (! in_array($type, $emailsGathered)) {
- $this->email = text('Email Address to send to:');
+ } else {
+ if (! in_array($type, $emailsGathered)) {
+ $this->email = text('Email Address to send to:');
+ }
}
set_transanctional_email_settings();
- $this->mailMessage = new MailMessage;
- $this->mailMessage->subject('Test Email');
+ $this->mail = new MailMessage;
+ $this->mail->subject('Test Email');
switch ($type) {
case 'updates':
$teams = Team::all();
@@ -99,18 +102,18 @@ public function handle()
$confirmed = confirm('Are you sure?');
if ($confirmed) {
foreach ($emails as $email) {
- $this->mailMessage = new MailMessage;
- $this->mailMessage->subject('One-click Services, Docker Compose support');
+ $this->mail = new MailMessage;
+ $this->mail->subject('One-click Services, Docker Compose support');
$unsubscribeUrl = route('unsubscribe.marketing.emails', [
'token' => encrypt($email),
]);
- $this->mailMessage->view('emails.updates', ['unsubscribeUrl' => $unsubscribeUrl]);
+ $this->mail->view('emails.updates', ['unsubscribeUrl' => $unsubscribeUrl]);
$this->sendEmail($email);
}
}
break;
case 'emails-test':
- $this->mailMessage = (new Test)->toMail();
+ $this->mail = (new Test)->toMail();
$this->sendEmail();
break;
case 'application-deployment-success-daily':
@@ -120,41 +123,41 @@ public function handle()
if ($deployments->isEmpty()) {
continue;
}
- $this->mailMessage = (new DeploymentSuccess($application, 'test'))->toMail();
+ $this->mail = (new DeploymentSuccess($application, 'test'))->toMail();
$this->sendEmail();
}
break;
case 'application-deployment-success':
$application = Application::all()->first();
- $this->mailMessage = (new DeploymentSuccess($application, 'test'))->toMail();
+ $this->mail = (new DeploymentSuccess($application, 'test'))->toMail();
$this->sendEmail();
break;
case 'application-deployment-failed':
$application = Application::all()->first();
$preview = ApplicationPreview::all()->first();
if (! $preview) {
- $preview = ApplicationPreview::query()->create([
+ $preview = ApplicationPreview::create([
'application_id' => $application->id,
'pull_request_id' => 1,
'pull_request_html_url' => 'http://example.com',
'fqdn' => $application->fqdn,
]);
}
- $this->mailMessage = (new DeploymentFailed($application, 'test'))->toMail();
+ $this->mail = (new DeploymentFailed($application, 'test'))->toMail();
$this->sendEmail();
- $this->mailMessage = (new DeploymentFailed($application, 'test', $preview))->toMail();
+ $this->mail = (new DeploymentFailed($application, 'test', $preview))->toMail();
$this->sendEmail();
break;
case 'application-status-changed':
$application = Application::all()->first();
- $this->mailMessage = (new StatusChanged($application))->toMail();
+ $this->mail = (new StatusChanged($application))->toMail();
$this->sendEmail();
break;
case 'backup-failed':
$backup = ScheduledDatabaseBackup::all()->first();
$db = StandalonePostgresql::all()->first();
if (! $backup) {
- $backup = ScheduledDatabaseBackup::query()->create([
+ $backup = ScheduledDatabaseBackup::create([
'enabled' => true,
'frequency' => 'daily',
'save_s3' => false,
@@ -164,14 +167,14 @@ public function handle()
]);
}
$output = 'Because of an error, the backup of the database '.$db->name.' failed.';
- $this->mailMessage = (new BackupFailed($backup, $db, $output))->toMail();
+ $this->mail = (new BackupFailed($backup, $db, $output))->toMail();
$this->sendEmail();
break;
case 'backup-success':
$backup = ScheduledDatabaseBackup::all()->first();
$db = StandalonePostgresql::all()->first();
if (! $backup) {
- $backup = ScheduledDatabaseBackup::query()->create([
+ $backup = ScheduledDatabaseBackup::create([
'enabled' => true,
'frequency' => 'daily',
'save_s3' => false,
@@ -198,10 +201,10 @@ public function handle()
// $this->sendEmail();
// break;
case 'realusers-before-trial':
- $this->mailMessage = new MailMessage;
- $this->mailMessage->view('emails.before-trial-conversion');
- $this->mailMessage->subject('Trial period has been added for all subscription plans.');
- $teams = Team::query()->doesntHave('subscription')->where('id', '!=', 0)->get();
+ $this->mail = new MailMessage;
+ $this->mail->view('emails.before-trial-conversion');
+ $this->mail->subject('Trial period has been added for all subscription plans.');
+ $teams = Team::doesntHave('subscription')->where('id', '!=', 0)->get();
if (! $teams || $teams->isEmpty()) {
echo 'No teams found.'.PHP_EOL;
@@ -229,7 +232,7 @@ public function handle()
break;
case 'realusers-server-lost-connection':
$serverId = text('Server Id');
- $server = Server::query()->find($serverId);
+ $server = Server::find($serverId);
if (! $server) {
throw new Exception('Server not found');
}
@@ -244,13 +247,13 @@ public function handle()
foreach ($admins as $admin) {
$this->info($admin);
}
- $this->mailMessage = new MailMessage;
- $this->mailMessage->view('emails.server-lost-connection', [
+ $this->mail = new MailMessage;
+ $this->mail->view('emails.server-lost-connection', [
'name' => $server->name,
]);
- $this->mailMessage->subject('Action required: Server '.$server->name.' lost connection.');
- foreach ($admins as $admin) {
- $this->sendEmail($admin);
+ $this->mail->subject('Action required: Server '.$server->name.' lost connection.');
+ foreach ($admins as $email) {
+ $this->sendEmail($email);
}
break;
}
@@ -266,8 +269,8 @@ private function sendEmail(?string $email = null)
[],
fn (Message $message) => $message
->to($this->email)
- ->subject($this->mailMessage->subject)
- ->html((string) $this->mailMessage->render())
+ ->subject($this->mail->subject)
+ ->html((string) $this->mail->render())
);
$this->info("Email sent to $this->email successfully. 📧");
}
diff --git a/app/Console/Commands/Horizon.php b/app/Console/Commands/Horizon.php
index 0debcae889..d3e35ca5a1 100644
--- a/app/Console/Commands/Horizon.php
+++ b/app/Console/Commands/Horizon.php
@@ -16,7 +16,8 @@ public function handle()
$this->info('Horizon is enabled on this server.');
$this->call('horizon');
exit(0);
+ } else {
+ exit(0);
}
- exit(0);
}
}
diff --git a/app/Console/Commands/Init.php b/app/Console/Commands/Init.php
index 0197a91da9..cc9bee0a53 100644
--- a/app/Console/Commands/Init.php
+++ b/app/Console/Commands/Init.php
@@ -15,7 +15,6 @@
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
-use Throwable;
class Init extends Command
{
@@ -23,7 +22,7 @@ class Init extends Command
protected $description = 'Cleanup instance related stuffs';
- public $servers;
+ public $servers = null;
public function handle()
{
@@ -36,7 +35,8 @@ public function handle()
}
$this->servers = Server::all();
- if (! isCloud()) {
+ if (isCloud()) {
+ } else {
$this->send_alive_signal();
get_public_ips();
}
@@ -61,14 +61,14 @@ public function handle()
try {
$this->pullHelperImage();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
//
}
if (isCloud()) {
try {
$this->pullTemplatesFromCDN();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Could not pull templates from CDN: {$e->getMessage()}\n";
}
}
@@ -76,13 +76,13 @@ public function handle()
if (! isCloud()) {
try {
$this->pullTemplatesFromCDN();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Could not pull templates from CDN: {$e->getMessage()}\n";
}
try {
$localhost = $this->servers->where('id', 0)->first();
$localhost->setupDynamicProxyConfiguration();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Could not setup dynamic configuration: {$e->getMessage()}\n";
}
$settings = instanceSettings();
@@ -119,8 +119,8 @@ private function optimize()
private function update_user_emails()
{
try {
- User::query()->whereRaw('email ~ \'[A-Z]\'')->get()->each(fn (User $user) => $user->update(['email' => strtolower($user->email)]));
- } catch (Throwable $e) {
+ User::whereRaw('email ~ \'[A-Z]\'')->get()->each(fn (User $user) => $user->update(['email' => strtolower($user->email)]));
+ } catch (\Throwable $e) {
echo "Error in updating user emails: {$e->getMessage()}\n";
}
}
@@ -128,8 +128,8 @@ private function update_user_emails()
private function update_traefik_labels()
{
try {
- Server::query()->where('proxy->type', 'TRAEFIK_V2')->update(['proxy->type' => 'TRAEFIK']);
- } catch (Throwable $e) {
+ Server::where('proxy->type', 'TRAEFIK_V2')->update(['proxy->type' => 'TRAEFIK']);
+ } catch (\Throwable $e) {
echo "Error in updating traefik labels: {$e->getMessage()}\n";
}
}
@@ -149,12 +149,10 @@ private function cleanup_unnecessary_dynamic_proxy_configuration()
return instant_remote_process([
"rm -f $file",
], $server, false);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning up unnecessary dynamic proxy configuration: {$e->getMessage()}\n";
}
}
-
- return null;
}
private function cleanup_unused_network_from_coolify_proxy()
@@ -170,19 +168,19 @@ private function cleanup_unused_network_from_coolify_proxy()
['networks' => $networks, 'allNetworks' => $allNetworks] = collectDockerNetworksByServer($server);
$removeNetworks = $allNetworks->diff($networks);
$commands = collect();
- foreach ($removeNetworks as $removeNetwork) {
- $out = instant_remote_process(["docker network inspect -f json {$removeNetwork} | jq '.[].Containers | if . == {} then null else . end'"], $server, false);
- if ($out === null || $out === '' || $out === '0') {
- $commands->push("docker network disconnect {$removeNetwork} coolify-proxy >/dev/null 2>&1 || true");
- $commands->push("docker network rm {$removeNetwork} >/dev/null 2>&1 || true");
+ foreach ($removeNetworks as $network) {
+ $out = instant_remote_process(["docker network inspect -f json $network | jq '.[].Containers | if . == {} then null else . end'"], $server, false);
+ if (empty($out)) {
+ $commands->push("docker network disconnect $network coolify-proxy >/dev/null 2>&1 || true");
+ $commands->push("docker network rm $network >/dev/null 2>&1 || true");
} else {
$data = collect(json_decode($out, true));
if ($data->count() === 1) {
// If only coolify-proxy itself is connected to that network (it should not be possible, but who knows)
$isCoolifyProxyItself = data_get($data->first(), 'Name') === 'coolify-proxy';
if ($isCoolifyProxyItself) {
- $commands->push("docker network disconnect {$removeNetwork} coolify-proxy >/dev/null 2>&1 || true");
- $commands->push("docker network rm {$removeNetwork} >/dev/null 2>&1 || true");
+ $commands->push("docker network disconnect $network coolify-proxy >/dev/null 2>&1 || true");
+ $commands->push("docker network rm $network >/dev/null 2>&1 || true");
}
}
}
@@ -190,7 +188,7 @@ private function cleanup_unused_network_from_coolify_proxy()
if ($commands->isNotEmpty()) {
remote_process(command: $commands, type: ActivityTypes::INLINE->value, server: $server, ignore_errors: false);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in cleaning up unused networks from coolify proxy: {$e->getMessage()}\n";
}
}
@@ -204,20 +202,20 @@ private function restore_coolify_db_backup()
if ($database && $database->trashed()) {
echo "Restoring coolify db backup\n";
$database->restore();
- $scheduledBackup = ScheduledDatabaseBackup::query()->find(0);
+ $scheduledBackup = ScheduledDatabaseBackup::find(0);
if (! $scheduledBackup) {
- ScheduledDatabaseBackup::query()->create([
+ ScheduledDatabaseBackup::create([
'id' => 0,
'enabled' => true,
'save_s3' => false,
'frequency' => '0 0 * * *',
'database_id' => $database->id,
- 'database_type' => StandalonePostgresql::class,
+ 'database_type' => \App\Models\StandalonePostgresql::class,
'team_id' => 0,
]);
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in restoring coolify db backup: {$e->getMessage()}\n";
}
}
@@ -236,7 +234,7 @@ private function send_alive_signal()
}
try {
Http::get("https://undead.coolify.io/v4/alive?appId=$id&version=$version");
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error in sending live signal: {$e->getMessage()}\n";
}
}
@@ -248,12 +246,12 @@ private function cleanup_in_progress_application_deployments()
if (isCloud()) {
return;
}
- $queued_inprogress_deployments = ApplicationDeploymentQueue::query()->whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS->value, ApplicationDeploymentStatus::QUEUED->value])->get();
- foreach ($queued_inprogress_deployments as $queued_inprogress_deployment) {
- $queued_inprogress_deployment->status = ApplicationDeploymentStatus::FAILED->value;
- $queued_inprogress_deployment->save();
+ $queued_inprogress_deployments = ApplicationDeploymentQueue::whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS->value, ApplicationDeploymentStatus::QUEUED->value])->get();
+ foreach ($queued_inprogress_deployments as $deployment) {
+ $deployment->status = ApplicationDeploymentStatus::FAILED->value;
+ $deployment->save();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
echo "Error: {$e->getMessage()}\n";
}
}
diff --git a/app/Console/Commands/Migration.php b/app/Console/Commands/Migration.php
index 3f6e498ec3..44c17203bf 100644
--- a/app/Console/Commands/Migration.php
+++ b/app/Console/Commands/Migration.php
@@ -16,8 +16,9 @@ public function handle()
$this->info('Migration is enabled on this server.');
$this->call('migrate', ['--force' => true, '--isolated' => true]);
exit(0);
+ } else {
+ $this->info('Migration is disabled on this server.');
+ exit(0);
}
- $this->info('Migration is disabled on this server.');
- exit(0);
}
}
diff --git a/app/Console/Commands/OpenApi.php b/app/Console/Commands/OpenApi.php
index a321706998..6cbcb310c3 100644
--- a/app/Console/Commands/OpenApi.php
+++ b/app/Console/Commands/OpenApi.php
@@ -16,7 +16,7 @@ public function handle()
// Generate OpenAPI documentation
echo "Generating OpenAPI documentation.\n";
// https://github.com/OAI/OpenAPI-Specification/releases
- $processResult = Process::run([
+ $process = Process::run([
'/var/www/html/vendor/bin/openapi',
'app',
'-o',
@@ -24,10 +24,10 @@ public function handle()
'--version',
'3.1.0',
]);
- $error = $processResult->errorOutput();
+ $error = $process->errorOutput();
$error = preg_replace('/^.*an object literal,.*$/m', '', $error);
$error = preg_replace('/^\h*\v+/m', '', $error);
echo $error;
- echo $processResult->output();
+ echo $process->output();
}
}
diff --git a/app/Console/Commands/RootChangeEmail.php b/app/Console/Commands/RootChangeEmail.php
index 2027cdc493..c87a545c5b 100644
--- a/app/Console/Commands/RootChangeEmail.php
+++ b/app/Console/Commands/RootChangeEmail.php
@@ -3,7 +3,6 @@
namespace App\Console\Commands;
use App\Models\User;
-use Exception;
use Illuminate\Console\Command;
class RootChangeEmail extends Command
@@ -32,9 +31,9 @@ public function handle()
$email = $this->ask('Give me a new email for root user');
$this->info('Updating root email...');
try {
- User::query()->find(0)->update(['email' => $email]);
+ User::find(0)->update(['email' => $email]);
$this->info('Root user\'s email updated successfully.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->error('Failed to update root user\'s email.');
return;
diff --git a/app/Console/Commands/RootResetPassword.php b/app/Console/Commands/RootResetPassword.php
index 5b2210a6c4..f36c11a4f1 100644
--- a/app/Console/Commands/RootResetPassword.php
+++ b/app/Console/Commands/RootResetPassword.php
@@ -3,7 +3,6 @@
namespace App\Console\Commands;
use App\Models\User;
-use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
@@ -33,16 +32,16 @@ public function handle()
$this->info('You are about to reset the root password.');
$password = password('Give me a new password for root user: ');
$passwordAgain = password('Again');
- if ($password !== $passwordAgain) {
+ if ($password != $passwordAgain) {
$this->error('Passwords do not match.');
return;
}
$this->info('Updating root password...');
try {
- User::query()->find(0)->update(['password' => Hash::make($password)]);
+ User::find(0)->update(['password' => Hash::make($password)]);
$this->info('Root password updated successfully.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->error('Failed to update root password.');
return;
diff --git a/app/Console/Commands/Scheduler.php b/app/Console/Commands/Scheduler.php
index 90bbf29795..ee64368c3d 100644
--- a/app/Console/Commands/Scheduler.php
+++ b/app/Console/Commands/Scheduler.php
@@ -16,7 +16,8 @@ public function handle()
$this->info('Scheduler is enabled on this server.');
$this->call('schedule:work');
exit(0);
+ } else {
+ exit(0);
}
- exit(0);
}
}
diff --git a/app/Console/Commands/Seeder.php b/app/Console/Commands/Seeder.php
index 66f066515d..e37b6a9d27 100644
--- a/app/Console/Commands/Seeder.php
+++ b/app/Console/Commands/Seeder.php
@@ -16,8 +16,9 @@ public function handle()
$this->info('Seeder is enabled on this server.');
$this->call('db:seed', ['--class' => 'ProductionSeeder', '--force' => true]);
exit(0);
+ } else {
+ $this->info('Seeder is disabled on this server.');
+ exit(0);
}
- $this->info('Seeder is disabled on this server.');
- exit(0);
}
}
diff --git a/app/Console/Commands/ServicesDelete.php b/app/Console/Commands/ServicesDelete.php
index fc2dad7706..b5a74166a5 100644
--- a/app/Console/Commands/ServicesDelete.php
+++ b/app/Console/Commands/ServicesDelete.php
@@ -62,8 +62,8 @@ private function deleteServer()
options: $servers->pluck('name', 'id')->sortKeys(),
);
- foreach ($serversToDelete as $serverToDelete) {
- $toDelete = $servers->where('id', $serverToDelete)->first();
+ foreach ($serversToDelete as $server) {
+ $toDelete = $servers->where('id', $server)->first();
if ($toDelete) {
$this->info($toDelete);
$confirmed = confirm('Are you sure you want to delete all selected resources?');
@@ -88,8 +88,8 @@ private function deleteApplication()
$applications->pluck('name', 'id')->sortKeys(),
);
- foreach ($applicationsToDelete as $applicationToDelete) {
- $toDelete = $applications->where('id', $applicationToDelete)->first();
+ foreach ($applicationsToDelete as $application) {
+ $toDelete = $applications->where('id', $application)->first();
if ($toDelete) {
$this->info($toDelete);
$confirmed = confirm('Are you sure you want to delete all selected resources? ');
@@ -114,8 +114,8 @@ private function deleteDatabase()
$databases->pluck('name', 'id')->sortKeys(),
);
- foreach ($databasesToDelete as $databaseToDelete) {
- $toDelete = $databases->where('id', $databaseToDelete)->first();
+ foreach ($databasesToDelete as $database) {
+ $toDelete = $databases->where('id', $database)->first();
if ($toDelete) {
$this->info($toDelete);
$confirmed = confirm('Are you sure you want to delete all selected resources?');
@@ -140,8 +140,8 @@ private function deleteService()
$services->pluck('name', 'id')->sortKeys(),
);
- foreach ($servicesToDelete as $serviceToDelete) {
- $toDelete = $services->where('id', $serviceToDelete)->first();
+ foreach ($servicesToDelete as $service) {
+ $toDelete = $services->where('id', $service)->first();
if ($toDelete) {
$this->info($toDelete);
$confirmed = confirm('Are you sure you want to delete all selected resources?');
diff --git a/app/Console/Commands/ServicesGenerate.php b/app/Console/Commands/ServicesGenerate.php
index 208031a15b..b45707c5c0 100644
--- a/app/Console/Commands/ServicesGenerate.php
+++ b/app/Console/Commands/ServicesGenerate.php
@@ -45,7 +45,7 @@ private function processFile(string $file): false|array
$data = collect(explode(PHP_EOL, $content))->mapWithKeys(function ($line): array {
preg_match('/^#(?.*):(?.*)$/U', $line, $m);
- return $m !== [] ? [trim($m['key']) => trim($m['value'])] : [];
+ return $m ? [trim($m['key']) => trim($m['value'])] : [];
});
if (str($data->get('ignore'))->toBoolean()) {
diff --git a/app/Console/Commands/SyncBunny.php b/app/Console/Commands/SyncBunny.php
index 697808eade..df19038286 100644
--- a/app/Console/Commands/SyncBunny.php
+++ b/app/Console/Commands/SyncBunny.php
@@ -6,7 +6,6 @@
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
-use Throwable;
use function Laravel\Prompts\confirm;
@@ -115,8 +114,7 @@ public function handle()
$this->info('Service template uploaded & purged...');
return;
- }
- if ($only_version) {
+ } elseif ($only_version) {
if ($nightly) {
$this->info('About to sync NIGHLTY versions.json to BunnyCDN.');
} else {
@@ -125,6 +123,7 @@ public function handle()
$file = file_get_contents($versions_location);
$json = json_decode($file, true);
$actual_version = data_get($json, 'coolify.v4.version');
+
$confirmed = confirm("Are you sure you want to sync to {$actual_version}?");
if (! $confirmed) {
return;
@@ -153,7 +152,7 @@ public function handle()
$pool->purge("$bunny_cdn/$bunny_cdn_path/$install_script"),
]);
$this->info('All files uploaded & purged...');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->error('Error: '.$e->getMessage());
}
}
diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php
index 8f49ac8a8d..e8781b01ef 100644
--- a/app/Console/Kernel.php
+++ b/app/Console/Kernel.php
@@ -6,11 +6,13 @@
use App\Jobs\CheckForUpdatesJob;
use App\Jobs\CheckHelperImageJob;
use App\Jobs\CleanupInstanceStuffsJob;
+use App\Jobs\CleanupStaleMultiplexedConnections;
use App\Jobs\DatabaseBackupJob;
use App\Jobs\DockerCleanupJob;
use App\Jobs\PullTemplatesFromCDN;
use App\Jobs\ScheduledTaskJob;
use App\Jobs\ServerCheckJob;
+use App\Jobs\ServerCleanupMux;
use App\Jobs\ServerStorageCheckJob;
use App\Jobs\UpdateCoolifyJob;
use App\Models\InstanceSettings;
@@ -26,9 +28,9 @@ class Kernel extends ConsoleKernel
{
private $allServers;
- private Schedule $schedule;
+ private Schedule $scheduleInstance;
- private InstanceSettings $instanceSettings;
+ private InstanceSettings $settings;
private string $updateCheckFrequency;
@@ -36,13 +38,13 @@ class Kernel extends ConsoleKernel
protected function schedule(Schedule $schedule): void
{
- $this->schedule = $schedule;
- $this->allServers = Server::query()->where('ip', '!=', '1.2.3.4');
+ $this->scheduleInstance = $schedule;
+ $this->allServers = Server::where('ip', '!=', '1.2.3.4');
- $this->instanceSettings = instanceSettings();
- $this->updateCheckFrequency = $this->instanceSettings->update_check_frequency ?: '0 * * * *';
+ $this->settings = instanceSettings();
+ $this->updateCheckFrequency = $this->settings->update_check_frequency ?: '0 * * * *';
- $this->instanceTimezone = $this->instanceSettings->instance_timezone ?: config('app.timezone');
+ $this->instanceTimezone = $this->settings->instance_timezone ?: config('app.timezone');
if (validate_timezone($this->instanceTimezone) === false) {
$this->instanceTimezone = config('app.timezone');
@@ -52,9 +54,9 @@ protected function schedule(Schedule $schedule): void
if (isDev()) {
// Instance Jobs
- $this->schedule->command('horizon:snapshot')->everyMinute();
- $this->schedule->job(new CleanupInstanceStuffsJob)->everyMinute()->onOneServer();
- $this->schedule->job(new CheckHelperImageJob)->everyTenMinutes()->onOneServer();
+ $this->scheduleInstance->command('horizon:snapshot')->everyMinute();
+ $this->scheduleInstance->job(new CleanupInstanceStuffsJob)->everyMinute()->onOneServer();
+ $this->scheduleInstance->job(new CheckHelperImageJob)->everyTenMinutes()->onOneServer();
// Server Jobs
$this->checkResources();
@@ -62,16 +64,16 @@ protected function schedule(Schedule $schedule): void
$this->checkScheduledBackups();
$this->checkScheduledTasks();
- $this->schedule->command('uploads:clear')->everyTwoMinutes();
+ $this->scheduleInstance->command('uploads:clear')->everyTwoMinutes();
} else {
// Instance Jobs
- $this->schedule->command('horizon:snapshot')->everyFiveMinutes();
- $this->schedule->command('cleanup:unreachable-servers')->daily()->onOneServer();
+ $this->scheduleInstance->command('horizon:snapshot')->everyFiveMinutes();
+ $this->scheduleInstance->command('cleanup:unreachable-servers')->daily()->onOneServer();
- $this->schedule->job(new PullTemplatesFromCDN)->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();
+ $this->scheduleInstance->job(new PullTemplatesFromCDN)->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();
- $this->schedule->job(new CleanupInstanceStuffsJob)->everyTwoMinutes()->onOneServer();
+ $this->scheduleInstance->job(new CleanupInstanceStuffsJob)->everyTwoMinutes()->onOneServer();
$this->scheduleUpdates();
// Server Jobs
@@ -82,8 +84,8 @@ protected function schedule(Schedule $schedule): void
$this->checkScheduledBackups();
$this->checkScheduledTasks();
- $this->schedule->command('cleanup:database --yes')->daily();
- $this->schedule->command('uploads:clear')->everyTwoMinutes();
+ $this->scheduleInstance->command('cleanup:database --yes')->daily();
+ $this->scheduleInstance->command('uploads:clear')->everyTwoMinutes();
}
}
@@ -92,12 +94,12 @@ private function pullImages(): void
$servers = $this->allServers->whereRelation('settings', 'is_usable', true)->whereRelation('settings', 'is_reachable', true)->get();
foreach ($servers as $server) {
if ($server->isSentinelEnabled()) {
- $this->schedule->job(function () use ($server) {
+ $this->scheduleInstance->job(function () use ($server) {
CheckAndStartSentinelJob::dispatch($server);
})->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();
}
}
- $this->schedule->job(new CheckHelperImageJob)
+ $this->scheduleInstance->job(new CheckHelperImageJob)
->cron($this->updateCheckFrequency)
->timezone($this->instanceTimezone)
->onOneServer();
@@ -105,14 +107,14 @@ private function pullImages(): void
private function scheduleUpdates(): void
{
- $this->schedule->job(new CheckForUpdatesJob)
+ $this->scheduleInstance->job(new CheckForUpdatesJob)
->cron($this->updateCheckFrequency)
->timezone($this->instanceTimezone)
->onOneServer();
- if ($this->instanceSettings->is_auto_update_enabled) {
- $autoUpdateFrequency = $this->instanceSettings->auto_update_frequency;
- $this->schedule->job(new UpdateCoolifyJob)
+ if ($this->settings->is_auto_update_enabled) {
+ $autoUpdateFrequency = $this->settings->auto_update_frequency;
+ $this->scheduleInstance->job(new UpdateCoolifyJob)
->cron($autoUpdateFrequency)
->timezone($this->instanceTimezone)
->onOneServer();
@@ -123,7 +125,7 @@ private function checkResources(): void
{
if (isCloud()) {
$servers = $this->allServers->whereHas('team.subscription')->get();
- $own = Team::query()->find(0)->servers;
+ $own = Team::find(0)->servers;
$servers = $servers->merge($own);
} else {
$servers = $this->allServers->get();
@@ -140,23 +142,23 @@ private function checkResources(): void
if (Carbon::parse($lastSentinelUpdate)->isBefore(now()->subSeconds($server->waitBeforeDoingSshCheck()))) {
// Check container status every minute if Sentinel does not activated
if (isCloud()) {
- $this->schedule->job(new ServerCheckJob($server))->timezone($serverTimezone)->everyFiveMinutes()->onOneServer();
+ $this->scheduleInstance->job(new ServerCheckJob($server))->timezone($serverTimezone)->everyFiveMinutes()->onOneServer();
} else {
- $this->schedule->job(new ServerCheckJob($server))->timezone($serverTimezone)->everyMinute()->onOneServer();
+ $this->scheduleInstance->job(new ServerCheckJob($server))->timezone($serverTimezone)->everyMinute()->onOneServer();
}
// $this->scheduleInstance->job(new \App\Jobs\ServerCheckNewJob($server))->everyFiveMinutes()->onOneServer();
- $this->schedule->job(new ServerStorageCheckJob($server))->cron($server->settings->server_disk_usage_check_frequency)->timezone($serverTimezone)->onOneServer();
+ $this->scheduleInstance->job(new ServerStorageCheckJob($server))->cron($server->settings->server_disk_usage_check_frequency)->timezone($serverTimezone)->onOneServer();
}
- $this->schedule->job(new DockerCleanupJob($server))->cron($server->settings->docker_cleanup_frequency)->timezone($serverTimezone)->onOneServer();
+ $this->scheduleInstance->job(new DockerCleanupJob($server))->cron($server->settings->docker_cleanup_frequency)->timezone($serverTimezone)->onOneServer();
// Cleanup multiplexed connections every hour
// $this->scheduleInstance->job(new ServerCleanupMux($server))->hourly()->onOneServer();
// Temporary solution until we have better memory management for Sentinel
if ($server->isSentinelEnabled()) {
- $this->schedule->job(function () use ($server) {
+ $this->scheduleInstance->job(function () use ($server) {
$server->restartContainer('coolify-sentinel');
})->daily()->onOneServer();
}
@@ -165,7 +167,7 @@ private function checkResources(): void
private function checkScheduledBackups(): void
{
- $scheduled_backups = ScheduledDatabaseBackup::query()->where('enabled', true)->get();
+ $scheduled_backups = ScheduledDatabaseBackup::where('enabled', true)->get();
if ($scheduled_backups->isEmpty()) {
return;
}
@@ -185,15 +187,15 @@ private function checkScheduledBackups(): void
$scheduled_backup->frequency = VALID_CRON_STRINGS[$scheduled_backup->frequency];
}
$serverTimezone = data_get($server->settings, 'server_timezone', $this->instanceTimezone);
- $this->schedule->job(new DatabaseBackupJob(
- scheduledDatabaseBackup: $scheduled_backup
+ $this->scheduleInstance->job(new DatabaseBackupJob(
+ backup: $scheduled_backup
))->cron($scheduled_backup->frequency)->timezone($serverTimezone)->onOneServer();
}
}
private function checkScheduledTasks(): void
{
- $scheduled_tasks = ScheduledTask::query()->where('enabled', true)->get();
+ $scheduled_tasks = ScheduledTask::where('enabled', true)->get();
if ($scheduled_tasks->isEmpty()) {
return;
}
@@ -206,11 +208,15 @@ private function checkScheduledTasks(): void
continue;
}
- if ($application && str($application->status)->contains('running') === false) {
- continue;
+ if ($application) {
+ if (str($application->status)->contains('running') === false) {
+ continue;
+ }
}
- if ($service && str($service->status)->contains('running') === false) {
- continue;
+ if ($service) {
+ if (str($service->status)->contains('running') === false) {
+ continue;
+ }
}
$server = $scheduled_task->server();
@@ -222,7 +228,7 @@ private function checkScheduledTasks(): void
$scheduled_task->frequency = VALID_CRON_STRINGS[$scheduled_task->frequency];
}
$serverTimezone = data_get($server->settings, 'server_timezone', $this->instanceTimezone);
- $this->schedule->job(new ScheduledTaskJob(
+ $this->scheduleInstance->job(new ScheduledTaskJob(
task: $scheduled_task
))->cron($scheduled_task->frequency)->timezone($serverTimezone)->onOneServer();
}
diff --git a/app/Data/ServerMetadata.php b/app/Data/ServerMetadata.php
index dadba854af..d95944b15a 100644
--- a/app/Data/ServerMetadata.php
+++ b/app/Data/ServerMetadata.php
@@ -9,7 +9,7 @@
class ServerMetadata extends Data
{
public function __construct(
- public ?ProxyTypes $proxyTypes,
- public ?ProxyStatus $proxyStatus
+ public ?ProxyTypes $type,
+ public ?ProxyStatus $status
) {}
}
diff --git a/app/Events/ApplicationStatusChanged.php b/app/Events/ApplicationStatusChanged.php
index ae24aefa23..4433248aad 100644
--- a/app/Events/ApplicationStatusChanged.php
+++ b/app/Events/ApplicationStatusChanged.php
@@ -2,7 +2,6 @@
namespace App\Events;
-use Exception;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
@@ -21,7 +20,7 @@ public function __construct($teamId = null)
$teamId = auth()->user()->currentTeam()->id ?? null;
}
if (is_null($teamId)) {
- throw new Exception('Team id is null');
+ throw new \Exception('Team id is null');
}
$this->teamId = $teamId;
}
diff --git a/app/Events/BackupCreated.php b/app/Events/BackupCreated.php
index 633ac59bcf..45b2aacb7a 100644
--- a/app/Events/BackupCreated.php
+++ b/app/Events/BackupCreated.php
@@ -2,7 +2,6 @@
namespace App\Events;
-use Exception;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
@@ -21,7 +20,7 @@ public function __construct($teamId = null)
$teamId = auth()->user()->currentTeam()->id ?? null;
}
if (is_null($teamId)) {
- throw new Exception('Team id is null');
+ throw new \Exception('Team id is null');
}
$this->teamId = $teamId;
}
diff --git a/app/Events/CloudflareTunnelConfigured.php b/app/Events/CloudflareTunnelConfigured.php
index d412d332a2..3d7076d0da 100644
--- a/app/Events/CloudflareTunnelConfigured.php
+++ b/app/Events/CloudflareTunnelConfigured.php
@@ -2,7 +2,6 @@
namespace App\Events;
-use Exception;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
@@ -21,7 +20,7 @@ public function __construct($teamId = null)
$teamId = auth()->user()->currentTeam()->id ?? null;
}
if (is_null($teamId)) {
- throw new Exception('Team id is null');
+ throw new \Exception('Team id is null');
}
$this->teamId = $teamId;
}
diff --git a/app/Events/DatabaseProxyStopped.php b/app/Events/DatabaseProxyStopped.php
index 57313e5df5..96b35a5cac 100644
--- a/app/Events/DatabaseProxyStopped.php
+++ b/app/Events/DatabaseProxyStopped.php
@@ -2,7 +2,6 @@
namespace App\Events;
-use Exception;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
@@ -22,7 +21,7 @@ public function __construct($teamId = null)
$teamId = Auth::user()?->currentTeam()?->id ?? null;
}
if (is_null($teamId)) {
- throw new Exception('Team id is null');
+ throw new \Exception('Team id is null');
}
$this->teamId = $teamId;
}
diff --git a/app/Events/DatabaseStatusChanged.php b/app/Events/DatabaseStatusChanged.php
index 360592a3bd..913b21bc22 100644
--- a/app/Events/DatabaseStatusChanged.php
+++ b/app/Events/DatabaseStatusChanged.php
@@ -13,7 +13,7 @@ class DatabaseStatusChanged implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
- public $userId;
+ public $userId = null;
public function __construct($userId = null)
{
@@ -21,7 +21,7 @@ public function __construct($userId = null)
$userId = Auth::id() ?? null;
}
if (is_null($userId)) {
- return;
+ return false;
}
$this->userId = $userId;
diff --git a/app/Events/FileStorageChanged.php b/app/Events/FileStorageChanged.php
index c3b16daa1f..57004cf4c3 100644
--- a/app/Events/FileStorageChanged.php
+++ b/app/Events/FileStorageChanged.php
@@ -2,7 +2,6 @@
namespace App\Events;
-use Exception;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
@@ -18,7 +17,7 @@ class FileStorageChanged implements ShouldBroadcast
public function __construct($teamId = null)
{
if (is_null($teamId)) {
- throw new Exception('Team id is null');
+ throw new \Exception('Team id is null');
}
$this->teamId = $teamId;
}
diff --git a/app/Events/ProxyStatusChanged.php b/app/Events/ProxyStatusChanged.php
index 2c79bb9444..35eedef70e 100644
--- a/app/Events/ProxyStatusChanged.php
+++ b/app/Events/ProxyStatusChanged.php
@@ -2,7 +2,6 @@
namespace App\Events;
-use Exception;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
@@ -21,7 +20,7 @@ public function __construct($teamId = null)
$teamId = auth()->user()->currentTeam()->id ?? null;
}
if (is_null($teamId)) {
- throw new Exception('Team id is null');
+ throw new \Exception('Team id is null');
}
$this->teamId = $teamId;
}
diff --git a/app/Events/RestoreJobFinished.php b/app/Events/RestoreJobFinished.php
index 014e0f19ed..d3adb77984 100644
--- a/app/Events/RestoreJobFinished.php
+++ b/app/Events/RestoreJobFinished.php
@@ -17,15 +17,18 @@ public function __construct($data)
$tmpPath = data_get($data, 'tmpPath');
$container = data_get($data, 'container');
$serverId = data_get($data, 'serverId');
- if (filled($scriptPath) && filled($tmpPath) && filled($container) && filled($serverId) && (str($tmpPath)->startsWith('/tmp/')
- && str($scriptPath)->startsWith('/tmp/')
- && ! str($tmpPath)->contains('..')
- && ! str($scriptPath)->contains('..')
- && strlen($tmpPath) > 5 // longer than just "/tmp/"
- && strlen($scriptPath) > 5)) {
- $commands[] = "docker exec {$container} sh -c 'rm {$scriptPath}'";
- $commands[] = "docker exec {$container} sh -c 'rm {$tmpPath}'";
- instant_remote_process($commands, Server::query()->find($serverId), throwError: true);
+ if (filled($scriptPath) && filled($tmpPath) && filled($container) && filled($serverId)) {
+ if (str($tmpPath)->startsWith('/tmp/')
+ && str($scriptPath)->startsWith('/tmp/')
+ && ! str($tmpPath)->contains('..')
+ && ! str($scriptPath)->contains('..')
+ && strlen($tmpPath) > 5 // longer than just "/tmp/"
+ && strlen($scriptPath) > 5
+ ) {
+ $commands[] = "docker exec {$container} sh -c 'rm {$scriptPath}'";
+ $commands[] = "docker exec {$container} sh -c 'rm {$tmpPath}'";
+ instant_remote_process($commands, Server::find($serverId), throwError: true);
+ }
}
}
}
diff --git a/app/Events/ScheduledTaskDone.php b/app/Events/ScheduledTaskDone.php
index 5a1a8f0d5b..c8b5547f61 100644
--- a/app/Events/ScheduledTaskDone.php
+++ b/app/Events/ScheduledTaskDone.php
@@ -2,7 +2,6 @@
namespace App\Events;
-use Exception;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
@@ -21,7 +20,7 @@ public function __construct($teamId = null)
$teamId = auth()->user()->currentTeam()->id ?? null;
}
if (is_null($teamId)) {
- throw new Exception('Team id is null');
+ throw new \Exception('Team id is null');
}
$this->teamId = $teamId;
}
diff --git a/app/Events/ServiceStatusChanged.php b/app/Events/ServiceStatusChanged.php
index 2782464e1a..3950022e10 100644
--- a/app/Events/ServiceStatusChanged.php
+++ b/app/Events/ServiceStatusChanged.php
@@ -21,7 +21,7 @@ public function __construct($userId = null)
$userId = Auth::id() ?? null;
}
if (is_null($userId)) {
- return;
+ return false;
}
$this->userId = $userId;
}
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.php
index 5acba98432..8c89bb07f9 100644
--- a/app/Exceptions/Handler.php
+++ b/app/Exceptions/Handler.php
@@ -16,7 +16,7 @@ class Handler extends ExceptionHandler
/**
* A list of exception types with their corresponding custom log levels.
*
- * @var array, \Psr\Log\LogLevel::*>
+ * @var array, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
@@ -25,7 +25,7 @@ class Handler extends ExceptionHandler
/**
* A list of the exception types that are not reported.
*
- * @var array>
+ * @var array>
*/
protected $dontReport = [
ProcessException::class,
@@ -42,15 +42,15 @@ class Handler extends ExceptionHandler
'password_confirmation',
];
- private InstanceSettings $instanceSettings;
+ private InstanceSettings $settings;
- protected function unauthenticated($request, AuthenticationException $authenticationException)
+ protected function unauthenticated($request, AuthenticationException $exception)
{
- if ($request->is('api/*') || $request->expectsJson() || $this->shouldReturnJson($request, $authenticationException)) {
- return response()->json(['message' => $authenticationException->getMessage()], 401);
+ if ($request->is('api/*') || $request->expectsJson() || $this->shouldReturnJson($request, $exception)) {
+ return response()->json(['message' => $exception->getMessage()], 401);
}
- return redirect()->guest($authenticationException->redirectTo($request) ?? route('login'));
+ return redirect()->guest($exception->redirectTo($request) ?? route('login'));
}
/**
@@ -58,21 +58,21 @@ protected function unauthenticated($request, AuthenticationException $authentica
*/
public function register(): void
{
- $this->reportable(function (Throwable $throwable) {
+ $this->reportable(function (Throwable $e) {
if (isDev()) {
return;
}
- if ($throwable instanceof RuntimeException) {
+ if ($e instanceof RuntimeException) {
return;
}
- $this->instanceSettings = instanceSettings();
- if ($this->instanceSettings->do_not_track) {
+ $this->settings = instanceSettings();
+ if ($this->settings->do_not_track) {
return;
}
app('sentry')->configureScope(
function (Scope $scope) {
$email = auth()?->user() ? auth()->user()->email : 'guest';
- $instanceAdmin = User::query()->find(0)->email ?? 'admin@localhost';
+ $instanceAdmin = User::find(0)->email ?? 'admin@localhost';
$scope->setUser(
[
'email' => $email,
@@ -81,10 +81,10 @@ function (Scope $scope) {
);
}
);
- if (str($throwable->getMessage())->contains('No space left on device')) {
+ if (str($e->getMessage())->contains('No space left on device')) {
return;
}
- Integration::captureUnhandledException($throwable);
+ Integration::captureUnhandledException($e);
});
}
}
diff --git a/app/Helpers/SshMultiplexingHelper.php b/app/Helpers/SshMultiplexingHelper.php
index 1a10222bf9..8da476b9e0 100644
--- a/app/Helpers/SshMultiplexingHelper.php
+++ b/app/Helpers/SshMultiplexingHelper.php
@@ -6,13 +6,12 @@
use App\Models\Server;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Process;
-use RuntimeException;
class SshMultiplexingHelper
{
public static function serverSshConfiguration(Server $server)
{
- $privateKey = PrivateKey::query()->findOrFail($server->private_key_id);
+ $privateKey = PrivateKey::findOrFail($server->private_key_id);
$sshKeyLocation = $privateKey->getKeyLocation();
$muxFilename = '/var/www/html/storage/app/ssh/mux/mux_'.$server->uuid;
@@ -36,9 +35,9 @@ public static function ensureMultiplexedConnection(Server $server): bool
$checkCommand .= '-o ProxyCommand="cloudflared access ssh --hostname %h" ';
}
$checkCommand .= "{$server->user}@{$server->ip}";
- $processResult = Process::run($checkCommand);
+ $process = Process::run($checkCommand);
- if ($processResult->exitCode() !== 0) {
+ if ($process->exitCode() !== 0) {
return self::establishNewMultiplexedConnection($server);
}
@@ -61,9 +60,12 @@ public static function establishNewMultiplexedConnection(Server $server): bool
}
$establishCommand .= self::getCommonSshOptions($server, $sshKeyLocation, $connectionTimeout, $serverInterval);
$establishCommand .= "{$server->user}@{$server->ip}";
- $processResult = Process::run($establishCommand);
+ $establishProcess = Process::run($establishCommand);
+ if ($establishProcess->exitCode() !== 0) {
+ return false;
+ }
- return $processResult->exitCode() === 0;
+ return true;
}
public static function removeMuxFile(Server $server)
@@ -101,14 +103,15 @@ public static function generateScpCommand(Server $server, string $source, string
}
$scp_command .= self::getCommonSshOptions($server, $sshKeyLocation, config('constants.ssh.connection_timeout'), config('constants.ssh.server_interval'), isScp: true);
+ $scp_command .= "{$source} {$server->user}@{$server->ip}:{$dest}";
- return $scp_command."{$source} {$server->user}@{$server->ip}:{$dest}";
+ return $scp_command;
}
public static function generateSshCommand(Server $server, string $command)
{
if ($server->settings->force_disabled) {
- throw new RuntimeException('Server is disabled.');
+ throw new \RuntimeException('Server is disabled.');
}
$sshConfig = self::serverSshConfiguration($server);
@@ -137,9 +140,11 @@ public static function generateSshCommand(Server $server, string $command)
$delimiter = base64_encode($delimiter);
$command = str_replace($delimiter, '', $command);
- return $ssh_command.("{$server->user}@{$server->ip} 'bash -se' << \\$delimiter".PHP_EOL
+ $ssh_command .= "{$server->user}@{$server->ip} 'bash -se' << \\$delimiter".PHP_EOL
.$command.PHP_EOL
- .$delimiter);
+ .$delimiter;
+
+ return $ssh_command;
}
private static function isMultiplexingEnabled(): bool
@@ -151,9 +156,9 @@ private static function validateSshKey(PrivateKey $privateKey): void
{
$keyLocation = $privateKey->getKeyLocation();
$checkKeyCommand = "ls $keyLocation 2>/dev/null";
- $processResult = Process::run($checkKeyCommand);
+ $keyCheckProcess = Process::run($checkKeyCommand);
- if ($processResult->exitCode() !== 0) {
+ if ($keyCheckProcess->exitCode() !== 0) {
$privateKey->storeInFileSystem();
}
}
diff --git a/app/Http/Controllers/Api/ApplicationsController.php b/app/Http/Controllers/Api/ApplicationsController.php
index fa009a2deb..4df187c198 100644
--- a/app/Http/Controllers/Api/ApplicationsController.php
+++ b/app/Http/Controllers/Api/ApplicationsController.php
@@ -15,7 +15,6 @@
use App\Models\Project;
use App\Models\Server;
use App\Models\Service;
-use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use OpenApi\Attributes as OA;
@@ -90,7 +89,7 @@ public function applications(Request $request)
if (is_null($teamId)) {
return invalidTokenResponse();
}
- $projects = Project::query()->where('team_id', $teamId)->get();
+ $projects = Project::where('team_id', $teamId)->get();
$applications = collect();
$applications->push($projects->pluck('applications')->flatten());
$applications = $applications->flatten();
@@ -718,7 +717,7 @@ private function create_application(Request $request, $type)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -732,10 +731,12 @@ private function create_application(Request $request, $type)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -824,12 +825,15 @@ private function create_application(Request $request, $type)
if ($request->build_pack === 'dockercompose') {
$request->offsetSet('ports_exposes', '80');
}
+
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
+
$application = new Application;
removeUnnecessaryFieldsFromRequest($request);
+
$application->fill($request->all());
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
@@ -844,6 +848,7 @@ private function create_application(Request $request, $type)
if ($dockerComposeDomainsJson->count() > 0) {
$application->docker_compose_domains = $dockerComposeDomainsJson;
}
+
$application->fqdn = $fqdn;
$application->destination_id = $destination->id;
$application->destination_type = $destination->getMorphClass();
@@ -863,24 +868,27 @@ private function create_application(Request $request, $type)
$application->save();
}
$application->isConfigurationChanged(true);
+
if ($instantDeploy) {
$deployment_uuid = new Cuid2;
+
queue_application_deployment(
application: $application,
deployment_uuid: $deployment_uuid,
no_questions_asked: true,
is_api: true,
);
- } elseif ($application->build_pack === 'dockercompose') {
- LoadComposeFile::dispatch($application);
+ } else {
+ if ($application->build_pack === 'dockercompose') {
+ LoadComposeFile::dispatch($application);
+ }
}
return response()->json(serializeApiResponse([
'uuid' => data_get($application, 'uuid'),
'domains' => data_get($application, 'domains'),
]))->setStatusCode(201);
- }
- if ($type === 'private-gh-app') {
+ } elseif ($type === 'private-gh-app') {
$validationRules = [
'git_repository' => 'string|required',
'git_branch' => 'string|required',
@@ -892,6 +900,7 @@ private function create_application(Request $request, $type)
'docker_compose_raw' => 'string|nullable',
];
$validationRules = array_merge(sharedDataApplications(), $validationRules);
+
$validator = customApiValidator($request->all(), $validationRules);
if ($validator->fails()) {
return response()->json([
@@ -899,14 +908,16 @@ private function create_application(Request $request, $type)
'errors' => $validator->errors(),
], 422);
}
+
if (! $request->has('name')) {
$request->offsetSet('name', generate_application_name($request->git_repository, $request->git_branch));
}
if ($request->build_pack === 'dockercompose') {
$request->offsetSet('ports_exposes', '80');
}
+
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$githubApp = GithubApp::whereTeamId($teamId)->where('uuid', $githubAppUuid)->first();
@@ -919,7 +930,9 @@ private function create_application(Request $request, $type)
}
$application = new Application;
removeUnnecessaryFieldsFromRequest($request);
+
$application->fill($request->all());
+
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
$yaml = Yaml::parse($application->docker_compose_raw);
@@ -956,24 +969,28 @@ private function create_application(Request $request, $type)
$application->save();
}
$application->isConfigurationChanged(true);
+
if ($instantDeploy) {
$deployment_uuid = new Cuid2;
+
queue_application_deployment(
application: $application,
deployment_uuid: $deployment_uuid,
no_questions_asked: true,
is_api: true,
);
- } elseif ($application->build_pack === 'dockercompose') {
- LoadComposeFile::dispatch($application);
+ } else {
+ if ($application->build_pack === 'dockercompose') {
+ LoadComposeFile::dispatch($application);
+ }
}
return response()->json(serializeApiResponse([
'uuid' => data_get($application, 'uuid'),
'domains' => data_get($application, 'domains'),
]))->setStatusCode(201);
- }
- if ($type === 'private-deploy-key') {
+ } elseif ($type === 'private-deploy-key') {
+
$validationRules = [
'git_repository' => 'string|required',
'git_branch' => 'string|required',
@@ -984,8 +1001,10 @@ private function create_application(Request $request, $type)
'docker_compose_location' => 'string',
'docker_compose_raw' => 'string|nullable',
];
+
$validationRules = array_merge(sharedDataApplications(), $validationRules);
$validator = customApiValidator($request->all(), $validationRules);
+
if ($validator->fails()) {
return response()->json([
'message' => 'Validation failed.',
@@ -998,17 +1017,21 @@ private function create_application(Request $request, $type)
if ($request->build_pack === 'dockercompose') {
$request->offsetSet('ports_exposes', '80');
}
+
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$privateKey = PrivateKey::whereTeamId($teamId)->where('uuid', $request->private_key_uuid)->first();
if (! $privateKey) {
return response()->json(['message' => 'Private Key not found.'], 404);
}
+
$application = new Application;
removeUnnecessaryFieldsFromRequest($request);
+
$application->fill($request->all());
+
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
$yaml = Yaml::parse($application->docker_compose_raw);
@@ -1043,29 +1066,33 @@ private function create_application(Request $request, $type)
$application->save();
}
$application->isConfigurationChanged(true);
+
if ($instantDeploy) {
$deployment_uuid = new Cuid2;
+
queue_application_deployment(
application: $application,
deployment_uuid: $deployment_uuid,
no_questions_asked: true,
is_api: true,
);
- } elseif ($application->build_pack === 'dockercompose') {
- LoadComposeFile::dispatch($application);
+ } else {
+ if ($application->build_pack === 'dockercompose') {
+ LoadComposeFile::dispatch($application);
+ }
}
return response()->json(serializeApiResponse([
'uuid' => data_get($application, 'uuid'),
'domains' => data_get($application, 'domains'),
]))->setStatusCode(201);
- }
- if ($type === 'dockerfile') {
+ } elseif ($type === 'dockerfile') {
$validationRules = [
'dockerfile' => 'string|required',
];
$validationRules = array_merge(sharedDataApplications(), $validationRules);
$validator = customApiValidator($request->all(), $validationRules);
+
if ($validator->fails()) {
return response()->json([
'message' => 'Validation failed.',
@@ -1075,8 +1102,9 @@ private function create_application(Request $request, $type)
if (! $request->has('name')) {
$request->offsetSet('name', 'dockerfile-'.new Cuid2);
}
+
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
if (! isBase64Encoded($request->dockerfile)) {
@@ -1098,10 +1126,12 @@ private function create_application(Request $request, $type)
}
$dockerFile = base64_decode($request->dockerfile);
removeUnnecessaryFieldsFromRequest($request);
+
$port = get_port_from_dockerfile($request->dockerfile);
if (! $port) {
$port = 80;
}
+
$application = new Application;
$application->fill($request->all());
$application->fqdn = $fqdn;
@@ -1111,6 +1141,7 @@ private function create_application(Request $request, $type)
$application->destination_id = $destination->id;
$application->destination_type = $destination->getMorphClass();
$application->environment_id = $environment->id;
+
$application->git_repository = 'coollabsio/coolify';
$application->git_branch = 'main';
$application->save();
@@ -1124,6 +1155,7 @@ private function create_application(Request $request, $type)
$application->save();
}
$application->isConfigurationChanged(true);
+
if ($instantDeploy) {
$deployment_uuid = new Cuid2;
@@ -1139,8 +1171,7 @@ private function create_application(Request $request, $type)
'uuid' => data_get($application, 'uuid'),
'domains' => data_get($application, 'domains'),
]))->setStatusCode(201);
- }
- if ($type === 'dockerimage') {
+ } elseif ($type === 'dockerimage') {
$validationRules = [
'docker_registry_image_name' => 'string|required',
'docker_registry_image_tag' => 'string',
@@ -1148,6 +1179,7 @@ private function create_application(Request $request, $type)
];
$validationRules = array_merge(sharedDataApplications(), $validationRules);
$validator = customApiValidator($request->all(), $validationRules);
+
if ($validator->fails()) {
return response()->json([
'message' => 'Validation failed.',
@@ -1158,7 +1190,7 @@ private function create_application(Request $request, $type)
$request->offsetSet('name', 'docker-image-'.new Cuid2);
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
if (! $request->docker_registry_image_tag) {
@@ -1166,12 +1198,14 @@ private function create_application(Request $request, $type)
}
$application = new Application;
removeUnnecessaryFieldsFromRequest($request);
+
$application->fill($request->all());
$application->fqdn = $fqdn;
$application->build_pack = 'dockerimage';
$application->destination_id = $destination->id;
$application->destination_type = $destination->getMorphClass();
$application->environment_id = $environment->id;
+
$application->git_repository = 'coollabsio/coolify';
$application->git_branch = 'main';
$application->save();
@@ -1185,6 +1219,7 @@ private function create_application(Request $request, $type)
$application->save();
}
$application->isConfigurationChanged(true);
+
if ($instantDeploy) {
$deployment_uuid = new Cuid2;
@@ -1200,14 +1235,16 @@ private function create_application(Request $request, $type)
'uuid' => data_get($application, 'uuid'),
'domains' => data_get($application, 'domains'),
]))->setStatusCode(201);
- }
- if ($type === 'dockercompose') {
+ } elseif ($type === 'dockercompose') {
$allowedFields = ['project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'instant_deploy', 'docker_compose_raw'];
+
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1223,6 +1260,7 @@ private function create_application(Request $request, $type)
];
$validationRules = array_merge(sharedDataApplications(), $validationRules);
$validator = customApiValidator($request->all(), $validationRules);
+
if ($validator->fails()) {
return response()->json([
'message' => 'Validation failed.',
@@ -1230,7 +1268,7 @@ private function create_application(Request $request, $type)
], 422);
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
if (! isBase64Encoded($request->docker_compose_raw)) {
@@ -1252,19 +1290,23 @@ private function create_application(Request $request, $type)
}
$dockerCompose = base64_decode($request->docker_compose_raw);
$dockerComposeRaw = Yaml::dump(Yaml::parse($dockerCompose), 10, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
+
// $isValid = validateComposeFile($dockerComposeRaw, $server_id);
// if ($isValid !== 'OK') {
// return $this->dispatch('error', "Invalid docker-compose file.\n$isValid");
// }
+
$service = new Service;
removeUnnecessaryFieldsFromRequest($request);
$service->fill($request->all());
+
$service->docker_compose_raw = $dockerComposeRaw;
$service->environment_id = $environment->id;
$service->server_id = $server->id;
$service->destination_id = $destination->id;
$service->destination_type = $destination->getMorphClass();
$service->save();
+
$service->name = "service-$service->uuid";
$service->parse(isNew: true);
if ($instantDeploy) {
@@ -1404,7 +1446,7 @@ public function application_by_uuid(Request $request)
public function delete_by_uuid(Request $request)
{
$teamId = getTeamIdFromToken();
- filter_var($request->query->get('cleanup', true), FILTER_VALIDATE_BOOLEAN);
+ $cleanup = filter_var($request->query->get('cleanup', true), FILTER_VALIDATE_BOOLEAN);
if (is_null($teamId)) {
return invalidTokenResponse();
}
@@ -1559,7 +1601,7 @@ public function update_by_uuid(Request $request)
], 400);
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first();
@@ -1621,14 +1663,16 @@ public function update_by_uuid(Request $request)
}
}
$return = $this->validateDataApplications($request, $server);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1651,7 +1695,7 @@ public function update_by_uuid(Request $request)
return $domain;
});
- if ($errors !== []) {
+ if (count($errors) > 0) {
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
@@ -1710,11 +1754,11 @@ public function update_by_uuid(Request $request)
$application->save();
if ($instantDeploy) {
- $cuid2 = new Cuid2;
+ $deployment_uuid = new Cuid2;
queue_application_deployment(
application: $application,
- deployment_uuid: $cuid2,
+ deployment_uuid: $deployment_uuid,
is_api: true,
);
}
@@ -1890,7 +1934,7 @@ public function update_env_by_uuid(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first();
@@ -1911,10 +1955,12 @@ public function update_env_by_uuid(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1948,38 +1994,43 @@ public function update_env_by_uuid(Request $request)
$env->save();
return response()->json($this->removeSensitiveData($env))->setStatusCode(201);
+ } else {
+ return response()->json([
+ 'message' => 'Environment variable not found.',
+ ], 404);
}
+ } else {
+ $env = $application->environment_variables->where('key', $key)->first();
+ if ($env) {
+ $env->value = $request->value;
+ if ($env->is_build_time != $is_build_time) {
+ $env->is_build_time = $is_build_time;
+ }
+ if ($env->is_literal != $is_literal) {
+ $env->is_literal = $is_literal;
+ }
+ if ($env->is_preview != $is_preview) {
+ $env->is_preview = $is_preview;
+ }
+ if ($env->is_multiline != $request->is_multiline) {
+ $env->is_multiline = $request->is_multiline;
+ }
+ if ($env->is_shown_once != $request->is_shown_once) {
+ $env->is_shown_once = $request->is_shown_once;
+ }
+ $env->save();
- return response()->json([
- 'message' => 'Environment variable not found.',
- ], 404);
- }
- $env = $application->environment_variables->where('key', $key)->first();
- if ($env) {
- $env->value = $request->value;
- if ($env->is_build_time != $is_build_time) {
- $env->is_build_time = $is_build_time;
- }
- if ($env->is_literal != $is_literal) {
- $env->is_literal = $is_literal;
- }
- if ($env->is_preview != $is_preview) {
- $env->is_preview = $is_preview;
- }
- if ($env->is_multiline != $request->is_multiline) {
- $env->is_multiline = $request->is_multiline;
- }
- if ($env->is_shown_once != $request->is_shown_once) {
- $env->is_shown_once = $request->is_shown_once;
+ return response()->json($this->removeSensitiveData($env))->setStatusCode(201);
+ } else {
+ return response()->json([
+ 'message' => 'Environment variable not found.',
+ ], 404);
}
- $env->save();
-
- return response()->json($this->removeSensitiveData($env))->setStatusCode(201);
}
return response()->json([
- 'message' => 'Environment variable not found.',
- ], 404);
+ 'message' => 'Something is not okay. Are you okay?',
+ ], 500);
}
#[OA\Patch(
@@ -2072,7 +2123,7 @@ public function create_bulk_envs(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first();
@@ -2278,10 +2329,12 @@ public function create_env(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -2298,44 +2351,51 @@ public function create_env(Request $request)
return response()->json([
'message' => 'Environment variable already exists. Use PATCH request to update it.',
], 409);
+ } else {
+ $env = $application->environment_variables()->create([
+ 'key' => $request->key,
+ 'value' => $request->value,
+ 'is_preview' => $request->is_preview ?? false,
+ 'is_build_time' => $request->is_build_time ?? false,
+ 'is_literal' => $request->is_literal ?? false,
+ 'is_multiline' => $request->is_multiline ?? false,
+ 'is_shown_once' => $request->is_shown_once ?? false,
+ 'resourceable_type' => get_class($application),
+ 'resourceable_id' => $application->id,
+ ]);
+
+ return response()->json([
+ 'uuid' => $env->uuid,
+ ])->setStatusCode(201);
}
- $env = $application->environment_variables()->create([
- 'key' => $request->key,
- 'value' => $request->value,
- 'is_preview' => $request->is_preview ?? false,
- 'is_build_time' => $request->is_build_time ?? false,
- 'is_literal' => $request->is_literal ?? false,
- 'is_multiline' => $request->is_multiline ?? false,
- 'is_shown_once' => $request->is_shown_once ?? false,
- 'resourceable_type' => get_class($application),
- 'resourceable_id' => $application->id,
- ]);
+ } else {
+ $env = $application->environment_variables->where('key', $key)->first();
+ if ($env) {
+ return response()->json([
+ 'message' => 'Environment variable already exists. Use PATCH request to update it.',
+ ], 409);
+ } else {
+ $env = $application->environment_variables()->create([
+ 'key' => $request->key,
+ 'value' => $request->value,
+ 'is_preview' => $request->is_preview ?? false,
+ 'is_build_time' => $request->is_build_time ?? false,
+ 'is_literal' => $request->is_literal ?? false,
+ 'is_multiline' => $request->is_multiline ?? false,
+ 'is_shown_once' => $request->is_shown_once ?? false,
+ 'resourceable_type' => get_class($application),
+ 'resourceable_id' => $application->id,
+ ]);
- return response()->json([
- 'uuid' => $env->uuid,
- ])->setStatusCode(201);
+ return response()->json([
+ 'uuid' => $env->uuid,
+ ])->setStatusCode(201);
+ }
}
- $env = $application->environment_variables->where('key', $key)->first();
- if ($env) {
- return response()->json([
- 'message' => 'Environment variable already exists. Use PATCH request to update it.',
- ], 409);
- }
- $env = $application->environment_variables()->create([
- 'key' => $request->key,
- 'value' => $request->value,
- 'is_preview' => $request->is_preview ?? false,
- 'is_build_time' => $request->is_build_time ?? false,
- 'is_literal' => $request->is_literal ?? false,
- 'is_multiline' => $request->is_multiline ?? false,
- 'is_shown_once' => $request->is_shown_once ?? false,
- 'resourceable_type' => get_class($application),
- 'resourceable_id' => $application->id,
- ]);
return response()->json([
- 'uuid' => $env->uuid,
- ])->setStatusCode(201);
+ 'message' => 'Something went wrong.',
+ ], 500);
}
#[OA\Delete(
@@ -2412,7 +2472,7 @@ public function delete_env_by_uuid(Request $request)
'message' => 'Application not found.',
], 404);
}
- $found_env = EnvironmentVariable::query()->where('uuid', $request->env_uuid)
+ $found_env = EnvironmentVariable::where('uuid', $request->env_uuid)
->where('resourceable_type', Application::class)
->where('resourceable_id', $application->id)
->first();
@@ -2515,11 +2575,11 @@ public function action_deploy(Request $request)
return response()->json(['message' => 'Application not found.'], 404);
}
- $cuid2 = new Cuid2;
+ $deployment_uuid = new Cuid2;
queue_application_deployment(
application: $application,
- deployment_uuid: $cuid2,
+ deployment_uuid: $deployment_uuid,
force_rebuild: $force,
is_api: true,
no_questions_asked: $instant_deploy
@@ -2528,7 +2588,7 @@ public function action_deploy(Request $request)
return response()->json(
[
'message' => 'Deployment request queued.',
- 'deployment_uuid' => $cuid2->toString(),
+ 'deployment_uuid' => $deployment_uuid->toString(),
],
200
);
@@ -2676,11 +2736,11 @@ public function action_restart(Request $request)
return response()->json(['message' => 'Application not found.'], 404);
}
- $cuid2 = new Cuid2;
+ $deployment_uuid = new Cuid2;
queue_application_deployment(
application: $application,
- deployment_uuid: $cuid2,
+ deployment_uuid: $deployment_uuid,
restart_only: true,
is_api: true,
);
@@ -2688,7 +2748,7 @@ public function action_restart(Request $request)
return response()->json(
[
'message' => 'Restart request queued.',
- 'deployment_uuid' => $cuid2->toString(),
+ 'deployment_uuid' => $deployment_uuid->toString(),
],
);
}
@@ -2775,7 +2835,7 @@ public function execute_command_by_uuid(Request $request)
return response()->json(['message' => 'Application not found.'], 404);
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -2783,10 +2843,12 @@ public function execute_command_by_uuid(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -2869,7 +2931,7 @@ private function validateDataApplications(Request $request, Server $server)
return str($domain)->trim()->lower();
});
- if ($errors !== []) {
+ if (count($errors) > 0) {
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
@@ -2884,7 +2946,5 @@ private function validateDataApplications(Request $request, Server $server)
], 422);
}
}
-
- return null;
}
}
diff --git a/app/Http/Controllers/Api/DatabasesController.php b/app/Http/Controllers/Api/DatabasesController.php
index 74d0dd88e2..504665f6a8 100644
--- a/app/Http/Controllers/Api/DatabasesController.php
+++ b/app/Http/Controllers/Api/DatabasesController.php
@@ -12,7 +12,6 @@
use App\Jobs\DeleteResourceJob;
use App\Models\Project;
use App\Models\Server;
-use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
@@ -74,7 +73,7 @@ public function databases(Request $request)
if (is_null($teamId)) {
return invalidTokenResponse();
}
- $projects = Project::query()->where('team_id', $teamId)->get();
+ $projects = Project::where('team_id', $teamId)->get();
$databases = collect();
foreach ($projects as $project) {
$databases = $databases->merge($project->databases());
@@ -247,7 +246,7 @@ public function update_by_uuid(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -277,8 +276,10 @@ public function update_by_uuid(Request $request)
if (! $database) {
return response()->json(['message' => 'Database not found.'], 404);
}
- if ($request->is_public && $request->public_port && isPublicPortAlreadyUsed($database->destination->server, $request->public_port, $database->id)) {
- return response()->json(['message' => 'Public port already used by another database.'], 400);
+ if ($request->is_public && $request->public_port) {
+ if (isPublicPortAlreadyUsed($database->destination->server, $request->public_port, $database->id)) {
+ return response()->json(['message' => 'Public port already used by another database.'], 400);
+ }
}
switch ($database->type()) {
case 'standalone-postgresql':
@@ -471,10 +472,12 @@ public function update_by_uuid(Request $request)
break;
}
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1016,7 +1019,7 @@ public function create_database_mongodb(Request $request)
return $this->create_database($request, NewDatabaseTypes::MONGODB);
}
- public function create_database(Request $request, NewDatabaseTypes $newDatabaseTypes)
+ public function create_database(Request $request, NewDatabaseTypes $type)
{
$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf', 'clickhouse_admin_user', 'clickhouse_admin_password', 'dragonfly_password', 'redis_password', 'redis_conf', 'keydb_password', 'keydb_conf', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
@@ -1026,15 +1029,17 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($extraFields !== []) {
+ if (! empty($extraFields)) {
$errors = collect([]);
- foreach ($extraFields as $extraField) {
- $errors->add($extraField);
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1075,8 +1080,10 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
return response()->json(['message' => 'Server has multiple destinations and you do not set destination_uuid.'], 400);
}
$destination = $destinations->first();
- if ($request->has('public_port') && $request->is_public && isPublicPortAlreadyUsed($server, $request->public_port)) {
- return response()->json(['message' => 'Public port already used by another database.'], 400);
+ if ($request->has('public_port') && $request->is_public) {
+ if (isPublicPortAlreadyUsed($server, $request->public_port)) {
+ return response()->json(['message' => 'Public port already used by another database.'], 400);
+ }
}
$validator = customApiValidator($request->all(), [
'name' => 'string|max:255',
@@ -1104,15 +1111,17 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
'errors' => $validator->errors(),
], 422);
}
- if ($request->public_port && ($request->public_port < 1024 || $request->public_port > 65535)) {
- return response()->json([
- 'message' => 'Validation failed.',
- 'errors' => [
- 'public_port' => 'The public port should be between 1024 and 65535.',
- ],
- ], 422);
+ if ($request->public_port) {
+ if ($request->public_port < 1024 || $request->public_port > 65535) {
+ return response()->json([
+ 'message' => 'Validation failed.',
+ 'errors' => [
+ 'public_port' => 'The public port should be between 1024 and 65535.',
+ ],
+ ], 422);
+ }
}
- if ($newDatabaseTypes === NewDatabaseTypes::POSTGRESQL) {
+ if ($type === NewDatabaseTypes::POSTGRESQL) {
$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'postgres_user', 'postgres_password', 'postgres_db', 'postgres_initdb_args', 'postgres_host_auth_method', 'postgres_conf'];
$validator = customApiValidator($request->all(), [
'postgres_user' => 'string',
@@ -1123,10 +1132,12 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
'postgres_conf' => 'string',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1169,18 +1180,19 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
}
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
- }
- if ($newDatabaseTypes === NewDatabaseTypes::MARIADB) {
+ } elseif ($type === NewDatabaseTypes::MARIADB) {
$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mariadb_conf', 'mariadb_root_password', 'mariadb_user', 'mariadb_password', 'mariadb_database'];
$validator = customApiValidator($request->all(), [
'clickhouse_admin_user' => 'string',
'clickhouse_admin_password' => 'string',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1213,6 +1225,7 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
+
$database->refresh();
$payload = [
'uuid' => $database->uuid,
@@ -1223,8 +1236,7 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
}
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
- }
- if ($newDatabaseTypes === NewDatabaseTypes::MYSQL) {
+ } elseif ($type === NewDatabaseTypes::MYSQL) {
$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mysql_root_password', 'mysql_password', 'mysql_user', 'mysql_database', 'mysql_conf'];
$validator = customApiValidator($request->all(), [
'mysql_root_password' => 'string',
@@ -1234,10 +1246,12 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
'mysql_conf' => 'string',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1270,6 +1284,7 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
+
$database->refresh();
$payload = [
'uuid' => $database->uuid,
@@ -1280,18 +1295,19 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
}
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
- }
- if ($newDatabaseTypes === NewDatabaseTypes::REDIS) {
+ } elseif ($type === NewDatabaseTypes::REDIS) {
$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'redis_password', 'redis_conf'];
$validator = customApiValidator($request->all(), [
'redis_password' => 'string',
'redis_conf' => 'string',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1324,6 +1340,7 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
+
$database->refresh();
$payload = [
'uuid' => $database->uuid,
@@ -1334,17 +1351,19 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
}
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
- }
- if ($newDatabaseTypes === NewDatabaseTypes::DRAGONFLY) {
+ } elseif ($type === NewDatabaseTypes::DRAGONFLY) {
$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'dragonfly_password'];
$validator = customApiValidator($request->all(), [
'dragonfly_password' => 'string',
]);
+
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1352,6 +1371,7 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
'errors' => $errors,
], 422);
}
+
removeUnnecessaryFieldsFromRequest($request);
$database = create_standalone_dragonfly($environment->id, $destination->uuid, $request->all());
if ($instantDeploy) {
@@ -1361,18 +1381,19 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
return response()->json(serializeApiResponse([
'uuid' => $database->uuid,
]))->setStatusCode(201);
- }
- if ($newDatabaseTypes === NewDatabaseTypes::KEYDB) {
+ } elseif ($type === NewDatabaseTypes::KEYDB) {
$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'keydb_password', 'keydb_conf'];
$validator = customApiValidator($request->all(), [
'keydb_password' => 'string',
'keydb_conf' => 'string',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1405,6 +1426,7 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
+
$database->refresh();
$payload = [
'uuid' => $database->uuid,
@@ -1415,18 +1437,19 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
}
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
- }
- if ($newDatabaseTypes === NewDatabaseTypes::CLICKHOUSE) {
+ } elseif ($type === NewDatabaseTypes::CLICKHOUSE) {
$allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'clickhouse_admin_user', 'clickhouse_admin_password'];
$validator = customApiValidator($request->all(), [
'clickhouse_admin_user' => 'string',
'clickhouse_admin_password' => 'string',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -1439,6 +1462,7 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
if ($instantDeploy) {
StartDatabase::dispatch($database);
}
+
$database->refresh();
$payload = [
'uuid' => $database->uuid,
@@ -1449,61 +1473,67 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
}
return response()->json(serializeApiResponse($payload))->setStatusCode(201);
- }
- $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database'];
- $validator = customApiValidator($request->all(), [
- 'mongo_conf' => 'string',
- 'mongo_initdb_root_username' => 'string',
- 'mongo_initdb_root_password' => 'string',
- 'mongo_initdb_database' => 'string',
- ]);
- $extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
- $errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
- }
+ } elseif ($type === NewDatabaseTypes::MONGODB) {
+ $allowedFields = ['name', 'description', 'image', 'public_port', 'is_public', 'project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'instant_deploy', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'mongo_conf', 'mongo_initdb_root_username', 'mongo_initdb_root_password', 'mongo_initdb_database'];
+ $validator = customApiValidator($request->all(), [
+ 'mongo_conf' => 'string',
+ 'mongo_initdb_root_username' => 'string',
+ 'mongo_initdb_root_password' => 'string',
+ 'mongo_initdb_database' => 'string',
+ ]);
+ $extraFields = array_diff(array_keys($request->all()), $allowedFields);
+ if ($validator->fails() || ! empty($extraFields)) {
+ $errors = $validator->errors();
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
+ }
- return response()->json([
- 'message' => 'Validation failed.',
- 'errors' => $errors,
- ], 422);
- }
- removeUnnecessaryFieldsFromRequest($request);
- if ($request->has('mongo_conf')) {
- if (! isBase64Encoded($request->mongo_conf)) {
return response()->json([
'message' => 'Validation failed.',
- 'errors' => [
- 'mongo_conf' => 'The mongo_conf should be base64 encoded.',
- ],
+ 'errors' => $errors,
], 422);
}
- $mongoConf = base64_decode($request->mongo_conf);
- if (mb_detect_encoding($mongoConf, 'ASCII', true) === false) {
- return response()->json([
- 'message' => 'Validation failed.',
- 'errors' => [
- 'mongo_conf' => 'The mongo_conf should be base64 encoded.',
- ],
- ], 422);
+ removeUnnecessaryFieldsFromRequest($request);
+ if ($request->has('mongo_conf')) {
+ if (! isBase64Encoded($request->mongo_conf)) {
+ return response()->json([
+ 'message' => 'Validation failed.',
+ 'errors' => [
+ 'mongo_conf' => 'The mongo_conf should be base64 encoded.',
+ ],
+ ], 422);
+ }
+ $mongoConf = base64_decode($request->mongo_conf);
+ if (mb_detect_encoding($mongoConf, 'ASCII', true) === false) {
+ return response()->json([
+ 'message' => 'Validation failed.',
+ 'errors' => [
+ 'mongo_conf' => 'The mongo_conf should be base64 encoded.',
+ ],
+ ], 422);
+ }
+ $request->offsetSet('mongo_conf', $mongoConf);
}
- $request->offsetSet('mongo_conf', $mongoConf);
- }
- $database = create_standalone_mongodb($environment->id, $destination->uuid, $request->all());
- if ($instantDeploy) {
- StartDatabase::dispatch($database);
- }
- $database->refresh();
- $payload = [
- 'uuid' => $database->uuid,
- 'internal_db_url' => $database->internal_db_url,
- ];
- if ($database->is_public && $database->public_port) {
- $payload['external_db_url'] = $database->external_db_url;
+ $database = create_standalone_mongodb($environment->id, $destination->uuid, $request->all());
+ if ($instantDeploy) {
+ StartDatabase::dispatch($database);
+ }
+
+ $database->refresh();
+ $payload = [
+ 'uuid' => $database->uuid,
+ 'internal_db_url' => $database->internal_db_url,
+ ];
+ if ($database->is_public && $database->public_port) {
+ $payload['external_db_url'] = $database->external_db_url;
+ }
+
+ return response()->json(serializeApiResponse($payload))->setStatusCode(201);
}
- return response()->json(serializeApiResponse($payload))->setStatusCode(201);
+ return response()->json(['message' => 'Invalid database type requested.'], 400);
}
#[OA\Delete(
@@ -1564,7 +1594,7 @@ public function create_database(Request $request, NewDatabaseTypes $newDatabaseT
public function delete_by_uuid(Request $request)
{
$teamId = getTeamIdFromToken();
- filter_var($request->query->get('cleanup', true), FILTER_VALIDATE_BOOLEAN);
+ $cleanup = filter_var($request->query->get('cleanup', true), FILTER_VALIDATE_BOOLEAN);
if (is_null($teamId)) {
return invalidTokenResponse();
}
diff --git a/app/Http/Controllers/Api/DeployController.php b/app/Http/Controllers/Api/DeployController.php
index 2a6c37e0b6..73b452f865 100644
--- a/app/Http/Controllers/Api/DeployController.php
+++ b/app/Http/Controllers/Api/DeployController.php
@@ -5,10 +5,8 @@
use App\Actions\Database\StartDatabase;
use App\Actions\Service\StartService;
use App\Http\Controllers\Controller;
-use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Server;
-use App\Models\Service;
use App\Models\Tag;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
@@ -67,7 +65,7 @@ public function deployments(Request $request)
return invalidTokenResponse();
}
$servers = Server::whereTeamId($teamId)->get();
- $deployments_per_server = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->whereIn('server_id', $servers->pluck('id'))->get()->sortBy('id');
+ $deployments_per_server = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('server_id', $servers->pluck('id'))->get()->sortBy('id');
$deployments_per_server = $deployments_per_server->map(function ($deployment) {
return $this->removeSensitiveData($deployment);
});
@@ -123,7 +121,7 @@ public function deployment_by_uuid(Request $request)
if (! $uuid) {
return response()->json(['message' => 'UUID is required.'], 400);
}
- $deployment = ApplicationDeploymentQueue::query()->where('deployment_uuid', $uuid)->first();
+ $deployment = ApplicationDeploymentQueue::where('deployment_uuid', $uuid)->first();
if (! $deployment) {
return response()->json(['message' => 'Deployment not found.'], 404);
}
@@ -198,8 +196,7 @@ public function deploy(Request $request)
}
if ($tags) {
return $this->by_tags($tags, $teamId, $force);
- }
- if ($uuids) {
+ } elseif ($uuids) {
return $this->by_uuids($uuids, $teamId, $force);
}
@@ -248,7 +245,7 @@ public function by_tags(string $tags, int $team_id, bool $force = false)
$deployments = collect();
$payload = collect();
foreach ($tags as $tag) {
- $found_tag = Tag::query()->where(['name' => $tag, 'team_id' => $team_id])->first();
+ $found_tag = Tag::where(['name' => $tag, 'team_id' => $team_id])->first();
if (! $found_tag) {
// $message->push("Tag {$tag} not found.");
continue;
@@ -260,15 +257,15 @@ public function by_tags(string $tags, int $team_id, bool $force = false)
continue;
}
- foreach ($applications as $application) {
- ['message' => $return_message, 'deployment_uuid' => $deployment_uuid] = $this->deploy_resource($application, $force);
+ foreach ($applications as $resource) {
+ ['message' => $return_message, 'deployment_uuid' => $deployment_uuid] = $this->deploy_resource($resource, $force);
if ($deployment_uuid) {
- $deployments->push(['resource_uuid' => $application->uuid, 'deployment_uuid' => $deployment_uuid->toString()]);
+ $deployments->push(['resource_uuid' => $resource->uuid, 'deployment_uuid' => $deployment_uuid->toString()]);
}
$message = $message->merge($return_message);
}
- foreach ($services as $service) {
- ['message' => $return_message] = $this->deploy_resource($service, $force);
+ foreach ($services as $resource) {
+ ['message' => $return_message] = $this->deploy_resource($resource, $force);
$message = $message->merge($return_message);
}
}
@@ -292,7 +289,7 @@ public function deploy_resource($resource, bool $force = false): array
return ['message' => "Resource ($resource) not found.", 'deployment_uuid' => $deployment_uuid];
}
switch ($resource?->getMorphClass()) {
- case Application::class:
+ case \App\Models\Application::class:
$deployment_uuid = new Cuid2;
queue_application_deployment(
application: $resource,
@@ -301,7 +298,7 @@ public function deploy_resource($resource, bool $force = false): array
);
$message = "Application {$resource->name} deployment queued.";
break;
- case Service::class:
+ case \App\Models\Service::class:
StartService::run($resource);
$message = "Service {$resource->name} started. It could take a while, be patient.";
break;
diff --git a/app/Http/Controllers/Api/ProjectController.php b/app/Http/Controllers/Api/ProjectController.php
index c79338ac4f..b94ce9c67f 100644
--- a/app/Http/Controllers/Api/ProjectController.php
+++ b/app/Http/Controllers/Api/ProjectController.php
@@ -4,7 +4,6 @@
use App\Http\Controllers\Controller;
use App\Models\Project;
-use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
@@ -225,7 +224,7 @@ public function create_project(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -234,10 +233,12 @@ public function create_project(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -246,7 +247,7 @@ public function create_project(Request $request)
], 422);
}
- $project = Project::query()->create([
+ $project = Project::create([
'name' => $request->name,
'description' => $request->description,
'team_id' => $teamId,
@@ -321,7 +322,7 @@ public function update_project(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -330,10 +331,12 @@ public function update_project(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
diff --git a/app/Http/Controllers/Api/ResourcesController.php b/app/Http/Controllers/Api/ResourcesController.php
index f3f6b72acf..ad12c83ab8 100644
--- a/app/Http/Controllers/Api/ResourcesController.php
+++ b/app/Http/Controllers/Api/ResourcesController.php
@@ -43,7 +43,7 @@ public function resources(Request $request)
if (is_null($teamId)) {
return invalidTokenResponse();
}
- $projects = Project::query()->where('team_id', $teamId)->get();
+ $projects = Project::where('team_id', $teamId)->get();
$resources = collect();
$resources->push($projects->pluck('applications')->flatten());
$resources->push($projects->pluck('services')->flatten());
diff --git a/app/Http/Controllers/Api/SecurityController.php b/app/Http/Controllers/Api/SecurityController.php
index 27b1129c1d..a14b0da20e 100644
--- a/app/Http/Controllers/Api/SecurityController.php
+++ b/app/Http/Controllers/Api/SecurityController.php
@@ -4,7 +4,6 @@
use App\Http\Controllers\Controller;
use App\Models\PrivateKey;
-use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
@@ -59,7 +58,7 @@ public function keys(Request $request)
if (is_null($teamId)) {
return invalidTokenResponse();
}
- $keys = PrivateKey::query()->where('team_id', $teamId)->get();
+ $keys = PrivateKey::where('team_id', $teamId)->get();
return response()->json($this->removeSensitiveData($keys));
}
@@ -103,7 +102,7 @@ public function key_by_uuid(Request $request)
return invalidTokenResponse();
}
- $key = PrivateKey::query()->where('team_id', $teamId)->where('uuid', $request->uuid)->first();
+ $key = PrivateKey::where('team_id', $teamId)->where('uuid', $request->uuid)->first();
if (is_null($key)) {
return response()->json([
@@ -173,7 +172,7 @@ public function create_key(Request $request)
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -196,7 +195,7 @@ public function create_key(Request $request)
if (! $request->description) {
$request->offsetSet('description', 'Created by Coolify via API');
}
- $privateKey = PrivateKey::query()->create([
+ $key = PrivateKey::create([
'team_id' => $teamId,
'name' => $request->name,
'description' => $request->description,
@@ -204,7 +203,7 @@ public function create_key(Request $request)
]);
return response()->json(serializeApiResponse([
- 'uuid' => $privateKey->uuid,
+ 'uuid' => $key->uuid,
]))->setStatusCode(201);
}
@@ -268,7 +267,7 @@ public function update_key(Request $request)
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
@@ -279,10 +278,12 @@ public function update_key(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -290,7 +291,7 @@ public function update_key(Request $request)
'errors' => $errors,
], 422);
}
- $foundKey = PrivateKey::query()->where('team_id', $teamId)->where('uuid', $request->uuid)->first();
+ $foundKey = PrivateKey::where('team_id', $teamId)->where('uuid', $request->uuid)->first();
if (is_null($foundKey)) {
return response()->json([
'message' => 'Private Key not found.',
@@ -354,7 +355,7 @@ public function delete_key(Request $request)
return response()->json(['message' => 'UUID is required.'], 422);
}
- $key = PrivateKey::query()->where('team_id', $teamId)->where('uuid', $request->uuid)->first();
+ $key = PrivateKey::where('team_id', $teamId)->where('uuid', $request->uuid)->first();
if (is_null($key)) {
return response()->json(['message' => 'Private Key not found.'], 404);
}
diff --git a/app/Http/Controllers/Api/ServersController.php b/app/Http/Controllers/Api/ServersController.php
index a5de2a17de..b1deb53218 100644
--- a/app/Http/Controllers/Api/ServersController.php
+++ b/app/Http/Controllers/Api/ServersController.php
@@ -11,7 +11,6 @@
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\Server as ModelsServer;
-use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
use Stringable;
@@ -295,7 +294,7 @@ public function domains_by_server(Request $request)
return response()->json(serializeApiResponse($domains));
}
- $projects = Project::query()->where('team_id', $teamId)->get();
+ $projects = Project::where('team_id', $teamId)->get();
$domains = collect();
$applications = $projects->pluck('applications')->flatten();
$settings = instanceSettings();
@@ -306,8 +305,8 @@ public function domains_by_server(Request $request)
$f = str($fqdn)->replace('http://', '')->replace('https://', '')->explode('/');
return str(str($f[0])->explode(':')[0]);
- })->filter(function (Stringable $stringable) {
- return $stringable->isNotEmpty();
+ })->filter(function (Stringable $fqdn) {
+ return $fqdn->isNotEmpty();
});
if ($ip === 'host.docker.internal') {
@@ -342,13 +341,13 @@ public function domains_by_server(Request $request)
foreach ($services as $service) {
$service_applications = $service->applications;
if ($service_applications->count() > 0) {
- foreach ($service_applications as $service_application) {
- $fqdn = str($service_application->fqdn)->explode(',')->map(function ($fqdn) {
+ foreach ($service_applications as $application) {
+ $fqdn = str($application->fqdn)->explode(',')->map(function ($fqdn) {
$f = str($fqdn)->replace('http://', '')->replace('https://', '')->explode('/');
return str(str($f[0])->explode(':')[0]);
- })->filter(function (Stringable $stringable) {
- return $stringable->isNotEmpty();
+ })->filter(function (Stringable $fqdn) {
+ return $fqdn->isNotEmpty();
});
if ($ip === 'host.docker.internal') {
if ($settings->public_ipv4) {
@@ -460,7 +459,7 @@ public function create_server(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -476,10 +475,12 @@ public function create_server(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -615,7 +616,7 @@ public function update_server(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -631,10 +632,12 @@ public function update_server(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
diff --git a/app/Http/Controllers/Api/ServicesController.php b/app/Http/Controllers/Api/ServicesController.php
index 0bcb3ea974..03d9d209cc 100644
--- a/app/Http/Controllers/Api/ServicesController.php
+++ b/app/Http/Controllers/Api/ServicesController.php
@@ -11,7 +11,6 @@
use App\Models\Project;
use App\Models\Server;
use App\Models\Service;
-use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
@@ -76,7 +75,7 @@ public function services(Request $request)
if (is_null($teamId)) {
return invalidTokenResponse();
}
- $projects = Project::query()->where('team_id', $teamId)->get();
+ $projects = Project::where('team_id', $teamId)->get();
$services = collect();
foreach ($projects as $project) {
$services->push($project->services()->get());
@@ -246,7 +245,7 @@ public function create_service(Request $request)
}
$return = validateIncomingRequest($request);
- if ($return instanceof JsonResponse) {
+ if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
@@ -262,10 +261,12 @@ public function create_service(Request $request)
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
- if ($validator->fails() || $extraFields !== []) {
+ if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
- foreach ($extraFields as $extraField) {
- $errors->add($extraField, 'This field is not allowed.');
+ if (! empty($extraFields)) {
+ foreach ($extraFields as $field) {
+ $errors->add($field, 'This field is not allowed.');
+ }
}
return response()->json([
@@ -314,7 +315,7 @@ public function create_service(Request $request)
$oneClickDotEnvs = data_get($services, "$oneClickServiceName.envs", null);
if ($oneClickDotEnvs) {
$oneClickDotEnvs = str(base64_decode($oneClickDotEnvs))->split('/\r\n|\r|\n/')->filter(function ($value) {
- return $value !== '' && $value !== '0';
+ return ! empty($value);
});
}
if ($oneClickService) {
@@ -330,7 +331,7 @@ public function create_service(Request $request)
if ($oneClickServiceName === 'cloudflared') {
data_set($service_payload, 'connect_to_docker_network', true);
}
- $service = Service::query()->create($service_payload);
+ $service = Service::create($service_payload);
$service->name = "$oneClickServiceName-".$service->uuid;
$service->save();
if ($oneClickDotEnvs?->count() > 0) {
@@ -342,7 +343,7 @@ public function create_service(Request $request)
$command = $value->after('SERVICE_')->beforeLast('_');
$generatedValue = generateEnvValue($command->value(), $service);
}
- EnvironmentVariable::query()->create([
+ EnvironmentVariable::create([
'key' => $key,
'value' => $generatedValue,
'resourceable_id' => $service->id,
@@ -372,9 +373,11 @@ public function create_service(Request $request)
}
return response()->json(['message' => 'Service not found.'], 404);
+ } else {
+ return response()->json(['message' => 'Invalid service type.', 'valid_service_types' => $serviceKeys], 400);
}
- return response()->json(['message' => 'Invalid service type.', 'valid_service_types' => $serviceKeys], 400);
+ return response()->json(['message' => 'Invalid service type.'], 400);
}
#[OA\Get(
@@ -425,7 +428,7 @@ public function service_by_uuid(Request $request)
if (! $request->uuid) {
return response()->json(['message' => 'UUID is required.'], 404);
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
@@ -490,7 +493,7 @@ public function delete_by_uuid(Request $request)
if (! $request->uuid) {
return response()->json(['message' => 'UUID is required.'], 404);
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
@@ -563,7 +566,7 @@ public function envs(Request $request)
if (is_null($teamId)) {
return invalidTokenResponse();
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
@@ -667,7 +670,7 @@ public function update_env_by_uuid(Request $request)
return invalidTokenResponse();
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
@@ -788,7 +791,7 @@ public function create_bulk_envs(Request $request)
return invalidTokenResponse();
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
@@ -904,7 +907,7 @@ public function create_env(Request $request)
return invalidTokenResponse();
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
@@ -1006,12 +1009,12 @@ public function delete_env_by_uuid(Request $request)
return invalidTokenResponse();
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
- $env = EnvironmentVariable::query()->where('uuid', $request->env_uuid)
+ $env = EnvironmentVariable::where('uuid', $request->env_uuid)
->where('resourceable_type', Service::class)
->where('resourceable_id', $service->id)
->first();
@@ -1086,7 +1089,7 @@ public function action_deploy(Request $request)
if (! $uuid) {
return response()->json(['message' => 'UUID is required.'], 400);
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
@@ -1164,7 +1167,7 @@ public function action_stop(Request $request)
if (! $uuid) {
return response()->json(['message' => 'UUID is required.'], 400);
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
@@ -1242,7 +1245,7 @@ public function action_restart(Request $request)
if (! $uuid) {
return response()->json(['message' => 'UUID is required.'], 400);
}
- $service = Service::query()->whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
+ $service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index 03d78bc0dd..522683efaa 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -39,9 +39,9 @@ public function verify()
return view('auth.verify-email');
}
- public function email_verify(EmailVerificationRequest $emailVerificationRequest)
+ public function email_verify(EmailVerificationRequest $request)
{
- $emailVerificationRequest->fulfill();
+ $request->fulfill();
return redirect(RouteServiceProvider::HOME);
}
@@ -139,10 +139,9 @@ public function acceptInvitation()
refreshSession($invitation->team);
return redirect()->route('team.index');
+ } else {
+ abort(400, 'Invitation expired.');
}
- abort(400, 'Invitation expired.');
-
- return null;
}
public function revoke_invitation()
diff --git a/app/Http/Controllers/MagicController.php b/app/Http/Controllers/MagicController.php
index 3bb905dbef..59c9b8b94e 100644
--- a/app/Http/Controllers/MagicController.php
+++ b/app/Http/Controllers/MagicController.php
@@ -46,7 +46,10 @@ public function environments()
public function newProject()
{
- $project = Project::query()->firstOrCreate(['name' => request()->query('name') ?? generate_random_name()], ['team_id' => currentTeam()->id]);
+ $project = Project::firstOrCreate(
+ ['name' => request()->query('name') ?? generate_random_name()],
+ ['team_id' => currentTeam()->id]
+ );
return response()->json([
'project_uuid' => $project->uuid,
@@ -55,7 +58,10 @@ public function newProject()
public function newEnvironment()
{
- $environment = Environment::query()->firstOrCreate(['name' => request()->query('name') ?? generate_random_name()], ['project_id' => Project::ownedByCurrentTeam()->whereUuid(request()->query('project_uuid'))->firstOrFail()->id]);
+ $environment = Environment::firstOrCreate(
+ ['name' => request()->query('name') ?? generate_random_name()],
+ ['project_id' => Project::ownedByCurrentTeam()->whereUuid(request()->query('project_uuid'))->firstOrFail()->id]
+ );
return response()->json([
'environment_name' => $environment->name,
@@ -64,10 +70,12 @@ public function newEnvironment()
public function newTeam()
{
- $team = Team::query()->create([
- 'name' => request()->query('name') ?? generate_random_name(),
- 'personal_team' => false,
- ]);
+ $team = Team::create(
+ [
+ 'name' => request()->query('name') ?? generate_random_name(),
+ 'personal_team' => false,
+ ],
+ );
auth()->user()->teams()->attach($team, ['role' => 'admin']);
refreshSession();
diff --git a/app/Http/Controllers/OauthController.php b/app/Http/Controllers/OauthController.php
index b4a1806c17..3a3f18c9c4 100644
--- a/app/Http/Controllers/OauthController.php
+++ b/app/Http/Controllers/OauthController.php
@@ -3,7 +3,6 @@
namespace App\Http\Controllers;
use App\Models\User;
-use Exception;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpKernel\Exception\HttpException;
@@ -27,7 +26,7 @@ public function callback(string $provider)
abort(403, 'Registration is disabled');
}
- $user = User::query()->create([
+ $user = User::create([
'name' => $oauthUser->name,
'email' => $oauthUser->email,
]);
@@ -35,7 +34,7 @@ public function callback(string $provider)
Auth::login($user);
return redirect('/');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$errorCode = $e instanceof HttpException ? 'auth.failed' : 'auth.failed.callback';
return redirect()->route('login')->withErrors([__($errorCode)]);
diff --git a/app/Http/Controllers/UploadController.php b/app/Http/Controllers/UploadController.php
index 57a5b33030..4d34a10007 100644
--- a/app/Http/Controllers/UploadController.php
+++ b/app/Http/Controllers/UploadController.php
@@ -17,13 +17,13 @@ public function upload(Request $request)
if (is_null($resource)) {
return response()->json(['error' => 'You do not have permission for this database'], 500);
}
- $fileReceiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
+ $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
- if ($fileReceiver->isUploaded() === false) {
+ if ($receiver->isUploaded() === false) {
throw new UploadMissingFileException;
}
- $save = $fileReceiver->receive();
+ $save = $receiver->receive();
if ($save->isFinished()) {
return $this->saveFile($save->getFile(), $resource);
@@ -57,22 +57,22 @@ public function upload(Request $request)
// 'mime_type' => $mime
// ]);
// }
- protected function saveFile(UploadedFile $uploadedFile, $resource)
+ protected function saveFile(UploadedFile $file, $resource)
{
- $mime = str_replace('/', '-', $uploadedFile->getMimeType());
+ $mime = str_replace('/', '-', $file->getMimeType());
$filePath = "upload/{$resource->uuid}";
$finalPath = storage_path('app/'.$filePath);
- $uploadedFile->move($finalPath, 'restore');
+ $file->move($finalPath, 'restore');
return response()->json([
'mime_type' => $mime,
]);
}
- protected function createFilename(UploadedFile $uploadedFile)
+ protected function createFilename(UploadedFile $file)
{
- $extension = $uploadedFile->getClientOriginalExtension();
- $filename = str_replace('.'.$extension, '', $uploadedFile->getClientOriginalName()); // Filename without extension
+ $extension = $file->getClientOriginalExtension();
+ $filename = str_replace('.'.$extension, '', $file->getClientOriginalName()); // Filename without extension
$filename .= '_'.md5(time()).'.'.$extension;
diff --git a/app/Http/Controllers/Webhook/Bitbucket.php b/app/Http/Controllers/Webhook/Bitbucket.php
index 7e2b91616a..8c74f95e5c 100644
--- a/app/Http/Controllers/Webhook/Bitbucket.php
+++ b/app/Http/Controllers/Webhook/Bitbucket.php
@@ -30,7 +30,7 @@ public function manual(Request $request)
$json = json_encode($data);
Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Bitbicket::manual_bitbucket", $json);
- return null;
+ return;
}
$return_payloads = collect([]);
$payload = $request->collect();
@@ -63,7 +63,7 @@ public function manual(Request $request)
$pull_request_html_url = data_get($payload, 'pullrequest.links.html.href');
$commit = data_get($payload, 'pullrequest.source.commit.hash');
}
- $applications = Application::query()->where('git_repository', 'like', "%$full_name%");
+ $applications = Application::where('git_repository', 'like', "%$full_name%");
$applications = $applications->where('git_branch', $branch)->get();
if ($applications->isEmpty()) {
return response([
@@ -122,10 +122,10 @@ public function manual(Request $request)
if ($x_bitbucket_event === 'pullrequest:created') {
if ($application->isPRDeployable()) {
$deployment_uuid = new Cuid2;
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found) {
if ($application->build_pack === 'dockercompose') {
- $pr_app = ApplicationPreview::query()->create([
+ $pr_app = ApplicationPreview::create([
'git_type' => 'bitbucket',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -134,7 +134,7 @@ public function manual(Request $request)
]);
$pr_app->generate_preview_fqdn_compose();
} else {
- ApplicationPreview::query()->create([
+ ApplicationPreview::create([
'git_type' => 'bitbucket',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -165,7 +165,7 @@ public function manual(Request $request)
}
}
if ($x_bitbucket_event === 'pullrequest:rejected' || $x_bitbucket_event === 'pullrequest:fulfilled') {
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if ($found) {
$found->delete();
$container_name = generateApplicationContainerName($application, $pull_request_id);
diff --git a/app/Http/Controllers/Webhook/Gitea.php b/app/Http/Controllers/Webhook/Gitea.php
index 8ddea3bc37..cc53f20344 100644
--- a/app/Http/Controllers/Webhook/Gitea.php
+++ b/app/Http/Controllers/Webhook/Gitea.php
@@ -25,7 +25,7 @@ public function manual(Request $request)
return Str::contains($file, $x_gitea_delivery);
})->first();
if ($gitea_delivery_found) {
- return null;
+ return;
}
$data = [
'attributes' => $request->attributes->all(),
@@ -40,7 +40,7 @@ public function manual(Request $request)
$json = json_encode($data);
Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Gitea::manual_{$x_gitea_delivery}", $json);
- return null;
+ return;
}
$x_gitea_event = Str::lower($request->header('X-Gitea-Event'));
$x_hub_signature_256 = Str::after($request->header('X-Hub-Signature-256'), 'sha256=');
@@ -76,7 +76,7 @@ public function manual(Request $request)
if (! $branch) {
return response('Nothing to do. No branch found in the request.');
}
- $applications = Application::query()->where('git_repository', 'like', "%$full_name%");
+ $applications = Application::where('git_repository', 'like', "%$full_name%");
if ($x_gitea_event === 'push') {
$applications = $applications->where('git_branch', $branch)->get();
if ($applications->isEmpty()) {
@@ -155,10 +155,10 @@ public function manual(Request $request)
if ($action === 'opened' || $action === 'synchronize' || $action === 'reopened') {
if ($application->isPRDeployable()) {
$deployment_uuid = new Cuid2;
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found) {
if ($application->build_pack === 'dockercompose') {
- $pr_app = ApplicationPreview::query()->create([
+ $pr_app = ApplicationPreview::create([
'git_type' => 'gitea',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -167,7 +167,7 @@ public function manual(Request $request)
]);
$pr_app->generate_preview_fqdn_compose();
} else {
- ApplicationPreview::query()->create([
+ ApplicationPreview::create([
'git_type' => 'gitea',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -198,7 +198,7 @@ public function manual(Request $request)
}
}
if ($action === 'closed') {
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if ($found) {
$found->delete();
$container_name = generateApplicationContainerName($application, $pull_request_id);
diff --git a/app/Http/Controllers/Webhook/Github.php b/app/Http/Controllers/Webhook/Github.php
index d3a1234801..ac1d4ded21 100644
--- a/app/Http/Controllers/Webhook/Github.php
+++ b/app/Http/Controllers/Webhook/Github.php
@@ -31,7 +31,7 @@ public function manual(Request $request)
return Str::contains($file, $x_github_delivery);
})->first();
if ($github_delivery_found) {
- return null;
+ return;
}
$data = [
'attributes' => $request->attributes->all(),
@@ -46,7 +46,7 @@ public function manual(Request $request)
$json = json_encode($data);
Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Github::manual_{$x_github_delivery}", $json);
- return null;
+ return;
}
$x_github_event = Str::lower($request->header('X-GitHub-Event'));
$x_hub_signature_256 = Str::after($request->header('X-Hub-Signature-256'), 'sha256=');
@@ -82,7 +82,7 @@ public function manual(Request $request)
if (! $branch) {
return response('Nothing to do. No branch found in the request.');
}
- $applications = Application::query()->where('git_repository', 'like', "%$full_name%");
+ $applications = Application::where('git_repository', 'like', "%$full_name%");
if ($x_github_event === 'push') {
$applications = $applications->where('git_branch', $branch)->get();
if ($applications->isEmpty()) {
@@ -161,10 +161,10 @@ public function manual(Request $request)
if ($action === 'opened' || $action === 'synchronize' || $action === 'reopened') {
if ($application->isPRDeployable()) {
$deployment_uuid = new Cuid2;
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found) {
if ($application->build_pack === 'dockercompose') {
- $pr_app = ApplicationPreview::query()->create([
+ $pr_app = ApplicationPreview::create([
'git_type' => 'github',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -173,7 +173,7 @@ public function manual(Request $request)
]);
$pr_app->generate_preview_fqdn_compose();
} else {
- ApplicationPreview::query()->create([
+ ApplicationPreview::create([
'git_type' => 'github',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -204,7 +204,7 @@ public function manual(Request $request)
}
}
if ($action === 'closed') {
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if ($found) {
$found->delete();
$container_name = generateApplicationContainerName($application, $pull_request_id);
@@ -245,7 +245,7 @@ public function normal(Request $request)
return Str::contains($file, $x_github_delivery);
})->first();
if ($github_delivery_found) {
- return null;
+ return;
}
$data = [
'attributes' => $request->attributes->all(),
@@ -260,7 +260,7 @@ public function normal(Request $request)
$json = json_encode($data);
Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Github::normal_{$x_github_delivery}", $json);
- return null;
+ return;
}
$x_github_event = Str::lower($request->header('X-GitHub-Event'));
$x_github_hook_installation_target_id = $request->header('X-GitHub-Hook-Installation-Target-Id');
@@ -270,14 +270,16 @@ public function normal(Request $request)
// Just pong
return response('pong');
}
- $github_app = GithubApp::query()->where('app_id', $x_github_hook_installation_target_id)->first();
+ $github_app = GithubApp::where('app_id', $x_github_hook_installation_target_id)->first();
if (is_null($github_app)) {
return response('Nothing to do. No GitHub App found.');
}
$webhook_secret = data_get($github_app, 'webhook_secret');
$hmac = hash_hmac('sha256', $request->getContent(), $webhook_secret);
- if (config('app.env') !== 'local' && ! hash_equals($x_hub_signature_256, $hmac)) {
- return response('Invalid signature.');
+ if (config('app.env') !== 'local') {
+ if (! hash_equals($x_hub_signature_256, $hmac)) {
+ return response('Invalid signature.');
+ }
}
if ($x_github_event === 'installation' || $x_github_event === 'installation_repositories') {
// Installation handled by setup redirect url. Repositories queried on-demand.
@@ -310,7 +312,7 @@ public function normal(Request $request)
if (! $id || ! $branch) {
return response('Nothing to do. No id or branch found.');
}
- $applications = Application::query()->where('repository_project_id', $id)->whereRelation('source', 'is_public', false);
+ $applications = Application::where('repository_project_id', $id)->whereRelation('source', 'is_public', false);
if ($x_github_event === 'push') {
$applications = $applications->where('git_branch', $branch)->get();
if ($applications->isEmpty()) {
@@ -379,9 +381,9 @@ public function normal(Request $request)
if ($action === 'opened' || $action === 'synchronize' || $action === 'reopened') {
if ($application->isPRDeployable()) {
$deployment_uuid = new Cuid2;
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found) {
- ApplicationPreview::query()->create([
+ ApplicationPreview::create([
'git_type' => 'github',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -411,7 +413,7 @@ public function normal(Request $request)
}
}
if ($action === 'closed' || $action === 'close') {
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if ($found) {
$containers = getCurrentApplicationContainerStatus($application->destination->server, $application->id, $pull_request_id);
if ($containers->isNotEmpty()) {
@@ -451,7 +453,7 @@ public function redirect(Request $request)
try {
$code = $request->get('code');
$state = $request->get('state');
- $github_app = GithubApp::query()->where('uuid', $state)->firstOrFail();
+ $github_app = GithubApp::where('uuid', $state)->firstOrFail();
$api_url = data_get($github_app, 'api_url');
$data = Http::withBody(null)->accept('application/vnd.github+json')->post("$api_url/app-manifests/$code/conversions")->throw()->json();
$id = data_get($data, 'id');
@@ -460,7 +462,7 @@ public function redirect(Request $request)
$client_secret = data_get($data, 'client_secret');
$private_key = data_get($data, 'pem');
$webhook_secret = data_get($data, 'webhook_secret');
- $private_key = PrivateKey::query()->create([
+ $private_key = PrivateKey::create([
'name' => "github-app-{$slug}",
'private_key' => $private_key,
'team_id' => $github_app->team_id,
@@ -499,11 +501,11 @@ public function install(Request $request)
$json = json_encode($data);
Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Github::install_{$installation_id}", $json);
- return null;
+ return;
}
$source = $request->get('source');
$setup_action = $request->get('setup_action');
- $github_app = GithubApp::query()->where('uuid', $source)->firstOrFail();
+ $github_app = GithubApp::where('uuid', $source)->firstOrFail();
if ($setup_action === 'install') {
$github_app->installation_id = $installation_id;
$github_app->save();
diff --git a/app/Http/Controllers/Webhook/Gitlab.php b/app/Http/Controllers/Webhook/Gitlab.php
index e97614a6f2..d8dcc0c3ba 100644
--- a/app/Http/Controllers/Webhook/Gitlab.php
+++ b/app/Http/Controllers/Webhook/Gitlab.php
@@ -31,7 +31,7 @@ public function manual(Request $request)
$json = json_encode($data);
Storage::disk('webhooks-during-maintenance')->put("{$epoch}_Gitlab::manual_gitlab", $json);
- return null;
+ return;
}
$return_payloads = collect([]);
@@ -93,7 +93,7 @@ public function manual(Request $request)
return response($return_payloads);
}
}
- $applications = Application::query()->where('git_repository', 'like', "%$full_name%");
+ $applications = Application::where('git_repository', 'like', "%$full_name%");
if ($x_gitlab_event === 'push') {
$applications = $applications->where('git_branch', $branch)->get();
if ($applications->isEmpty()) {
@@ -181,10 +181,10 @@ public function manual(Request $request)
if ($action === 'open' || $action === 'opened' || $action === 'synchronize' || $action === 'reopened' || $action === 'reopen' || $action === 'update') {
if ($application->isPRDeployable()) {
$deployment_uuid = new Cuid2;
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found) {
if ($application->build_pack === 'dockercompose') {
- $pr_app = ApplicationPreview::query()->create([
+ $pr_app = ApplicationPreview::create([
'git_type' => 'gitlab',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -193,7 +193,7 @@ public function manual(Request $request)
]);
$pr_app->generate_preview_fqdn_compose();
} else {
- ApplicationPreview::query()->create([
+ ApplicationPreview::create([
'git_type' => 'gitlab',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
@@ -223,7 +223,7 @@ public function manual(Request $request)
]);
}
} elseif ($action === 'closed' || $action === 'close' || $action === 'merge') {
- $found = ApplicationPreview::query()->where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if ($found) {
$found->delete();
$container_name = generateApplicationContainerName($application, $pull_request_id);
diff --git a/app/Http/Controllers/Webhook/Stripe.php b/app/Http/Controllers/Webhook/Stripe.php
index 9e07ebaf9e..83ba16699a 100644
--- a/app/Http/Controllers/Webhook/Stripe.php
+++ b/app/Http/Controllers/Webhook/Stripe.php
@@ -40,7 +40,7 @@ public function events(Request $request)
return response('Webhook received. Cool cool cool cool cool.', 200);
}
- $this->webhook = Webhook::query()->create([
+ $this->webhook = Webhook::create([
'type' => 'stripe',
'payload' => $request->getContent(),
]);
diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php
index 5ba787bed9..a1ce20295b 100644
--- a/app/Http/Kernel.php
+++ b/app/Http/Kernel.php
@@ -2,35 +2,7 @@
namespace App\Http;
-use App\Http\Middleware\ApiAbility;
-use App\Http\Middleware\ApiSensitiveData;
-use App\Http\Middleware\Authenticate;
-use App\Http\Middleware\CheckForcePasswordReset;
-use App\Http\Middleware\DecideWhatToDoWithUser;
-use App\Http\Middleware\EncryptCookies;
-use App\Http\Middleware\PreventRequestsDuringMaintenance;
-use App\Http\Middleware\RedirectIfAuthenticated;
-use App\Http\Middleware\TrimStrings;
-use App\Http\Middleware\TrustProxies;
-use App\Http\Middleware\ValidateSignature;
-use App\Http\Middleware\VerifyCsrfToken;
-use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
-use Illuminate\Auth\Middleware\Authorize;
-use Illuminate\Auth\Middleware\EnsureEmailIsVerified;
-use Illuminate\Auth\Middleware\RequirePassword;
-use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
-use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
-use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
-use Illuminate\Http\Middleware\HandleCors;
-use Illuminate\Http\Middleware\SetCacheHeaders;
-use Illuminate\Routing\Middleware\SubstituteBindings;
-use Illuminate\Routing\Middleware\ThrottleRequests;
-use Illuminate\Session\Middleware\AuthenticateSession;
-use Illuminate\Session\Middleware\StartSession;
-use Illuminate\View\Middleware\ShareErrorsFromSession;
-use Laravel\Sanctum\Http\Middleware\CheckAbilities;
-use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
class Kernel extends HttpKernel
{
@@ -43,12 +15,12 @@ class Kernel extends HttpKernel
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
- TrustProxies::class,
- HandleCors::class,
- PreventRequestsDuringMaintenance::class,
- ValidatePostSize::class,
- TrimStrings::class,
- ConvertEmptyStringsToNull::class,
+ \App\Http\Middleware\TrustProxies::class,
+ \Illuminate\Http\Middleware\HandleCors::class,
+ \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
+ \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
+ \App\Http\Middleware\TrimStrings::class,
+ \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
@@ -59,21 +31,21 @@ class Kernel extends HttpKernel
*/
protected $middlewareGroups = [
'web' => [
- EncryptCookies::class,
- AddQueuedCookiesToResponse::class,
- StartSession::class,
- ShareErrorsFromSession::class,
- VerifyCsrfToken::class,
- SubstituteBindings::class,
- CheckForcePasswordReset::class,
- DecideWhatToDoWithUser::class,
+ \App\Http\Middleware\EncryptCookies::class,
+ \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
+ \Illuminate\Session\Middleware\StartSession::class,
+ \Illuminate\View\Middleware\ShareErrorsFromSession::class,
+ \App\Http\Middleware\VerifyCsrfToken::class,
+ \Illuminate\Routing\Middleware\SubstituteBindings::class,
+ \App\Http\Middleware\CheckForcePasswordReset::class,
+ \App\Http\Middleware\DecideWhatToDoWithUser::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
- ThrottleRequests::class.':api',
- SubstituteBindings::class,
+ \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
+ \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
@@ -85,19 +57,19 @@ class Kernel extends HttpKernel
* @var array
*/
protected $middlewareAliases = [
- 'auth' => Authenticate::class,
- 'auth.basic' => AuthenticateWithBasicAuth::class,
- 'auth.session' => AuthenticateSession::class,
- 'cache.headers' => SetCacheHeaders::class,
- 'can' => Authorize::class,
- 'guest' => RedirectIfAuthenticated::class,
- 'password.confirm' => RequirePassword::class,
- 'signed' => ValidateSignature::class,
- 'throttle' => ThrottleRequests::class,
- 'verified' => EnsureEmailIsVerified::class,
- 'abilities' => CheckAbilities::class,
- 'ability' => CheckForAnyAbility::class,
- 'api.ability' => ApiAbility::class,
- 'api.sensitive' => ApiSensitiveData::class,
+ 'auth' => \App\Http\Middleware\Authenticate::class,
+ 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
+ 'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
+ 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
+ 'can' => \Illuminate\Auth\Middleware\Authorize::class,
+ 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
+ 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
+ 'signed' => \App\Http\Middleware\ValidateSignature::class,
+ 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
+ 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
+ 'abilities' => \Laravel\Sanctum\Http\Middleware\CheckAbilities::class,
+ 'ability' => \Laravel\Sanctum\Http\Middleware\CheckForAnyAbility::class,
+ 'api.ability' => \App\Http\Middleware\ApiAbility::class,
+ 'api.sensitive' => \App\Http\Middleware\ApiSensitiveData::class,
];
}
diff --git a/app/Http/Middleware/ApiAbility.php b/app/Http/Middleware/ApiAbility.php
index 7ad16472ad..324eeebaa3 100644
--- a/app/Http/Middleware/ApiAbility.php
+++ b/app/Http/Middleware/ApiAbility.php
@@ -2,8 +2,6 @@
namespace App\Http\Middleware;
-use Exception;
-use Illuminate\Auth\AuthenticationException;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
class ApiAbility extends CheckForAnyAbility
@@ -16,11 +14,11 @@ public function handle($request, $next, ...$abilities)
}
return parent::handle($request, $next, ...$abilities);
- } catch (AuthenticationException $e) {
+ } catch (\Illuminate\Auth\AuthenticationException $e) {
return response()->json([
'message' => 'Unauthenticated.',
], 401);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return response()->json([
'message' => 'Missing required permissions: '.implode(', ', $abilities),
], 403);
diff --git a/app/Http/Middleware/ApiAllowed.php b/app/Http/Middleware/ApiAllowed.php
index 7c14b7921b..dc6be5da3d 100644
--- a/app/Http/Middleware/ApiAllowed.php
+++ b/app/Http/Middleware/ApiAllowed.php
@@ -18,10 +18,12 @@ public function handle(Request $request, Closure $next): Response
return response()->json(['success' => true, 'message' => 'API is disabled.'], 403);
}
- if (! isDev() && $settings->allowed_ips) {
- $allowedIps = explode(',', $settings->allowed_ips);
- if (! in_array($request->ip(), $allowedIps)) {
- return response()->json(['success' => true, 'message' => 'You are not allowed to access the API.'], 403);
+ if (! isDev()) {
+ if ($settings->allowed_ips) {
+ $allowedIps = explode(',', $settings->allowed_ips);
+ if (! in_array($request->ip(), $allowedIps)) {
+ return response()->json(['success' => true, 'message' => 'You are not allowed to access the API.'], 403);
+ }
}
}
diff --git a/app/Http/Middleware/CheckForcePasswordReset.php b/app/Http/Middleware/CheckForcePasswordReset.php
index 3e8fa9d02d..78b1f896c4 100644
--- a/app/Http/Middleware/CheckForcePasswordReset.php
+++ b/app/Http/Middleware/CheckForcePasswordReset.php
@@ -11,7 +11,7 @@ class CheckForcePasswordReset
/**
* Handle an incoming request.
*
- * @param Closure(Request):Response $next
+ * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
diff --git a/app/Http/Middleware/DecideWhatToDoWithUser.php b/app/Http/Middleware/DecideWhatToDoWithUser.php
index f9e979de74..8b1c550dfe 100644
--- a/app/Http/Middleware/DecideWhatToDoWithUser.php
+++ b/app/Http/Middleware/DecideWhatToDoWithUser.php
@@ -33,12 +33,14 @@ public function handle(Request $request, Closure $next): Response
return redirect()->route('verify.email');
}
- if (! isSubscriptionActive() && ! isSubscriptionOnGracePeriod() && ! in_array($request->path(), allowedPathsForUnsubscribedAccounts())) {
- if (Str::startsWith($request->path(), 'invitations')) {
- return $next($request);
- }
+ if (! isSubscriptionActive() && ! isSubscriptionOnGracePeriod()) {
+ if (! in_array($request->path(), allowedPathsForUnsubscribedAccounts())) {
+ if (Str::startsWith($request->path(), 'invitations')) {
+ return $next($request);
+ }
- return redirect()->route('subscription.index');
+ return redirect()->route('subscription.index');
+ }
}
if (showBoarding() && ! in_array($request->path(), allowedPathsForBoardingAccounts())) {
if (Str::startsWith($request->path(), 'invitations')) {
diff --git a/app/Http/Middleware/RedirectIfAuthenticated.php b/app/Http/Middleware/RedirectIfAuthenticated.php
index 075438ee52..afc78c4e53 100644
--- a/app/Http/Middleware/RedirectIfAuthenticated.php
+++ b/app/Http/Middleware/RedirectIfAuthenticated.php
@@ -13,11 +13,11 @@ class RedirectIfAuthenticated
/**
* Handle an incoming request.
*
- * @param Closure(Request):Response $next
+ * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string ...$guards): Response
{
- $guards = $guards === [] ? [null] : $guards;
+ $guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php
index 0aa812e12d..addaf436ae 100644
--- a/app/Jobs/ApplicationDeploymentJob.php
+++ b/app/Jobs/ApplicationDeploymentJob.php
@@ -88,7 +88,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
private bool $is_this_additional_server = false;
- private ?ApplicationPreview $applicationPreview = null;
+ private ?ApplicationPreview $preview = null;
private ?string $git_type = null;
@@ -174,8 +174,8 @@ public function __construct(int $application_deployment_queue_id)
$this->nixpacks_plan_json = collect([]);
- $this->application_deployment_queue = ApplicationDeploymentQueue::query()->find($application_deployment_queue_id);
- $this->application = Application::query()->find($this->application_deployment_queue->application_id);
+ $this->application_deployment_queue = ApplicationDeploymentQueue::find($application_deployment_queue_id);
+ $this->application = Application::find($this->application_deployment_queue->application_id);
$this->build_pack = data_get($this->application, 'build_pack');
$this->build_args = collect([]);
@@ -199,7 +199,7 @@ public function __construct(int $application_deployment_queue_id)
if ($source) {
$this->source = $source->getMorphClass()::where('id', $this->application->source->id)->first();
}
- $this->server = Server::query()->find($this->application_deployment_queue->server_id);
+ $this->server = Server::find($this->application_deployment_queue->server_id);
$this->timeout = $this->server->settings->dynamic_timeout;
$this->destination = $this->server->destinations()->where('id', $this->application_deployment_queue->destination_id)->first();
$this->server = $this->mainServer = $this->destination->server;
@@ -225,12 +225,14 @@ public function __construct(int $application_deployment_queue_id)
// Set preview fqdn
if ($this->pull_request_id !== 0) {
- $this->applicationPreview = $this->application->generate_preview_fqdn($this->pull_request_id);
+ $this->preview = $this->application->generate_preview_fqdn($this->pull_request_id);
if ($this->application->is_github_based()) {
- ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->applicationPreview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::IN_PROGRESS);
+ ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::IN_PROGRESS);
}
- if ($this->application->build_pack === 'dockerfile' && data_get($this->application, 'dockerfile_location')) {
- $this->dockerfile_location = $this->application->dockerfile_location;
+ if ($this->application->build_pack === 'dockerfile') {
+ if (data_get($this->application, 'dockerfile_location')) {
+ $this->dockerfile_location = $this->application->dockerfile_location;
+ }
}
}
}
@@ -261,15 +263,15 @@ public function handle(): void
if (count($allContainers) > 0) {
$allContainers = $allContainers[0];
$allContainers = collect($allContainers)->sort()->values();
- foreach ($allContainers as $allContainer) {
- $containerName = data_get($allContainer, 'Name');
+ foreach ($allContainers as $container) {
+ $containerName = data_get($container, 'Name');
if ($containerName === 'coolify-proxy') {
continue;
}
if (preg_match('/-(\d{12})/', $containerName)) {
continue;
}
- $containerIp = data_get($allContainer, 'IPv4Address');
+ $containerIp = data_get($container, 'IPv4Address');
if ($containerName && $containerIp) {
$containerIp = str($containerIp)->before('/');
$ips->put($containerName, $containerIp->value());
@@ -310,7 +312,7 @@ public function handle(): void
$this->decide_what_to_do();
} catch (Exception $e) {
if ($this->pull_request_id !== 0 && $this->application->is_github_based()) {
- ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->applicationPreview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::ERROR);
+ ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::ERROR);
}
$this->fail($e);
throw $e;
@@ -338,8 +340,7 @@ private function decide_what_to_do()
$this->just_restart();
return;
- }
- if ($this->pull_request_id !== 0) {
+ } elseif ($this->pull_request_id !== 0) {
$this->deploy_pull_request();
} elseif ($this->application->dockerfile) {
$this->deploy_simple_dockerfile();
@@ -363,8 +364,10 @@ private function post_deployment()
GetContainersStatus::dispatch($this->server);
}
$this->next(ApplicationDeploymentStatus::FINISHED->value);
- if ($this->pull_request_id !== 0 && $this->application->is_github_based()) {
- ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->applicationPreview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::FINISHED);
+ if ($this->pull_request_id !== 0) {
+ if ($this->application->is_github_based()) {
+ ApplicationPullRequestUpdateJob::dispatch(application: $this->application, preview: $this->preview, deployment_uuid: $this->deployment_uuid, status: ProcessStatus::FINISHED);
+ }
}
$this->run_post_deployment_command();
$this->application->isConfigurationChanged(true);
@@ -467,7 +470,7 @@ private function deploy_docker_compose_buildpack()
$yaml = $composeFile = $this->application->docker_compose_raw;
$this->save_environment_variables();
} else {
- $composeFile = $this->application->parse(pull_request_id: $this->pull_request_id, preview_id: data_get($this->applicationPreview, 'id'));
+ $composeFile = $this->application->parse(pull_request_id: $this->pull_request_id, preview_id: data_get($this->preview, 'id'));
$this->save_environment_variables();
if (! is_null($this->env_filename)) {
$services = collect(data_get($composeFile, 'services', []));
@@ -550,32 +553,34 @@ private function deploy_docker_compose_buildpack()
['command' => $command, 'hidden' => true],
);
}
- } elseif ($this->docker_compose_custom_start_command) {
- $this->write_deployment_configurations();
- $this->execute_remote_command(
- [executeInDocker($this->deployment_uuid, "cd {$this->basedir} && {$this->docker_compose_custom_start_command}"), 'hidden' => true],
- );
} else {
- $command = "{$this->coolify_variables} docker compose";
- if ($this->preserveRepository) {
- if ($this->env_filename) {
- $command .= " --env-file {$server_workdir}/{$this->env_filename}";
- }
- $command .= " --project-name {$this->application->uuid} --project-directory {$server_workdir} -f {$server_workdir}{$this->docker_compose_location} up -d";
+ if ($this->docker_compose_custom_start_command) {
$this->write_deployment_configurations();
-
$this->execute_remote_command(
- ['command' => $command, 'hidden' => true],
+ [executeInDocker($this->deployment_uuid, "cd {$this->basedir} && {$this->docker_compose_custom_start_command}"), 'hidden' => true],
);
} else {
- if ($this->env_filename) {
- $command .= " --env-file {$this->workdir}/{$this->env_filename}";
+ $command = "{$this->coolify_variables} docker compose";
+ if ($this->preserveRepository) {
+ if ($this->env_filename) {
+ $command .= " --env-file {$server_workdir}/{$this->env_filename}";
+ }
+ $command .= " --project-name {$this->application->uuid} --project-directory {$server_workdir} -f {$server_workdir}{$this->docker_compose_location} up -d";
+ $this->write_deployment_configurations();
+
+ $this->execute_remote_command(
+ ['command' => $command, 'hidden' => true],
+ );
+ } else {
+ if ($this->env_filename) {
+ $command .= " --env-file {$this->workdir}/{$this->env_filename}";
+ }
+ $command .= " --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up -d";
+ $this->execute_remote_command(
+ [executeInDocker($this->deployment_uuid, $command), 'hidden' => true],
+ );
+ $this->write_deployment_configurations();
}
- $command .= " --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up -d";
- $this->execute_remote_command(
- [executeInDocker($this->deployment_uuid, $command), 'hidden' => true],
- );
- $this->write_deployment_configurations();
}
}
@@ -683,7 +688,7 @@ private function write_deployment_configurations()
$this->server = $this->build_server;
}
}
- if ($this->docker_compose_base64 !== null) {
+ if (isset($this->docker_compose_base64)) {
if ($this->use_build_server) {
$this->server = $this->original_server;
}
@@ -768,7 +773,9 @@ private function push_to_docker_registry()
}
} catch (Exception $e) {
$this->application_deployment_queue->addLogEntry('Failed to push image to docker registry. Please check debug logs for more information.');
- throw new RuntimeException($e->getMessage(), 69420, $e);
+ if ($forceFail) {
+ throw new RuntimeException($e->getMessage(), 69420);
+ }
}
}
@@ -839,8 +846,9 @@ private function should_skip_build()
$this->rolling_update();
return true;
+ } else {
+ $this->application_deployment_queue->addLogEntry('Configuration changed. Rebuilding image.');
}
- $this->application_deployment_queue->addLogEntry('Configuration changed. Rebuilding image.');
} else {
$this->application_deployment_queue->addLogEntry("Image not found ({$this->production_image_name}). Building new image.");
}
@@ -900,11 +908,11 @@ private function save_environment_variables()
}
}
if ($this->application->environment_variables_preview->where('key', 'COOLIFY_FQDN')->isEmpty()) {
- $envs->push("COOLIFY_FQDN={$this->applicationPreview->fqdn}");
- $envs->push("COOLIFY_DOMAIN_URL={$this->applicationPreview->fqdn}");
+ $envs->push("COOLIFY_FQDN={$this->preview->fqdn}");
+ $envs->push("COOLIFY_DOMAIN_URL={$this->preview->fqdn}");
}
if ($this->application->environment_variables_preview->where('key', 'COOLIFY_URL')->isEmpty()) {
- $url = str($this->applicationPreview->fqdn)->replace('http://', '')->replace('https://', '');
+ $url = str($this->preview->fqdn)->replace('http://', '')->replace('https://', '');
$envs->push("COOLIFY_URL={$url}");
$envs->push("COOLIFY_DOMAIN_FQDN={$url}");
}
@@ -919,20 +927,24 @@ private function save_environment_variables()
add_coolify_default_environment_variables($this->application, $envs, $this->application->environment_variables_preview);
- foreach ($sorted_environment_variables_preview as $sorted_environment_variable_preview) {
- $real_value = $sorted_environment_variable_preview->real_value;
- if ($sorted_environment_variable_preview->version === '4.0.0-beta.239') {
- $real_value = $sorted_environment_variable_preview->real_value;
- } elseif ($sorted_environment_variable_preview->is_literal || $sorted_environment_variable_preview->is_multiline) {
- $real_value = '\''.$real_value.'\'';
+ foreach ($sorted_environment_variables_preview as $env) {
+ $real_value = $env->real_value;
+ if ($env->version === '4.0.0-beta.239') {
+ $real_value = $env->real_value;
} else {
- $real_value = escapeEnvVariables($sorted_environment_variable_preview->real_value);
+ if ($env->is_literal || $env->is_multiline) {
+ $real_value = '\''.$real_value.'\'';
+ } else {
+ $real_value = escapeEnvVariables($env->real_value);
+ }
}
- $envs->push($sorted_environment_variable_preview->key.'='.$real_value);
+ $envs->push($env->key.'='.$real_value);
}
// Add PORT if not exists, use the first port as default
- if ($this->build_pack !== 'dockercompose' && $this->application->environment_variables_preview->where('key', 'PORT')->isEmpty()) {
- $envs->push("PORT={$ports[0]}");
+ if ($this->build_pack !== 'dockercompose') {
+ if ($this->application->environment_variables_preview->where('key', 'PORT')->isEmpty()) {
+ $envs->push("PORT={$ports[0]}");
+ }
}
// Add HOST if not exists
if ($this->application->environment_variables_preview->where('key', 'HOST')->isEmpty()) {
@@ -974,20 +986,24 @@ private function save_environment_variables()
add_coolify_default_environment_variables($this->application, $envs, $this->application->environment_variables);
- foreach ($sorted_environment_variables as $sorted_environment_variable) {
- $real_value = $sorted_environment_variable->real_value;
- if ($sorted_environment_variable->version === '4.0.0-beta.239') {
- $real_value = $sorted_environment_variable->real_value;
- } elseif ($sorted_environment_variable->is_literal || $sorted_environment_variable->is_multiline) {
- $real_value = '\''.$real_value.'\'';
+ foreach ($sorted_environment_variables as $env) {
+ $real_value = $env->real_value;
+ if ($env->version === '4.0.0-beta.239') {
+ $real_value = $env->real_value;
} else {
- $real_value = escapeEnvVariables($sorted_environment_variable->real_value);
+ if ($env->is_literal || $env->is_multiline) {
+ $real_value = '\''.$real_value.'\'';
+ } else {
+ $real_value = escapeEnvVariables($env->real_value);
+ }
}
- $envs->push($sorted_environment_variable->key.'='.$real_value);
+ $envs->push($env->key.'='.$real_value);
}
// Add PORT if not exists, use the first port as default
- if ($this->build_pack !== 'dockercompose' && $this->application->environment_variables->where('key', 'PORT')->isEmpty()) {
- $envs->push("PORT={$ports[0]}");
+ if ($this->build_pack !== 'dockercompose') {
+ if ($this->application->environment_variables->where('key', 'PORT')->isEmpty()) {
+ $envs->push("PORT={$ports[0]}");
+ }
}
// Add HOST if not exists
if ($this->application->environment_variables->where('key', 'HOST')->isEmpty()) {
@@ -1051,7 +1067,11 @@ private function save_environment_variables()
private function elixir_finetunes()
{
- $envType = $this->pull_request_id === 0 ? 'environment_variables' : 'environment_variables_preview';
+ if ($this->pull_request_id === 0) {
+ $envType = 'environment_variables';
+ } else {
+ $envType = 'environment_variables_preview';
+ }
$mix_env = $this->application->{$envType}->where('key', 'MIX_ENV')->first();
if ($mix_env) {
if ($mix_env->is_build_time === false) {
@@ -1086,7 +1106,11 @@ private function elixir_finetunes()
private function laravel_finetunes()
{
- $envType = $this->pull_request_id === 0 ? 'environment_variables' : 'environment_variables_preview';
+ if ($this->pull_request_id === 0) {
+ $envType = 'environment_variables';
+ } else {
+ $envType = 'environment_variables_preview';
+ }
$nixpacks_php_fallback_path = $this->application->{$envType}->where('key', 'NIXPACKS_PHP_FALLBACK_PATH')->first();
$nixpacks_php_root_dir = $this->application->{$envType}->where('key', 'NIXPACKS_PHP_ROOT_DIR')->first();
@@ -1170,7 +1194,7 @@ private function health_check()
$this->application_deployment_queue->addLogEntry('Custom healthcheck found, skipping default healthcheck.');
}
// ray('New container name: ', $this->container_name);
- if ($this->container_name !== '' && $this->container_name !== '0') {
+ if ($this->container_name) {
$counter = 1;
$this->application_deployment_queue->addLogEntry('Waiting for healthcheck to pass on the new container.');
if ($this->full_healthcheck_url) {
@@ -1320,10 +1344,12 @@ private function prepare_builder_image()
throw new RuntimeException('Docker config file (~/.docker/config.json) not found on the build server. Please run "docker login" to login to the docker registry on the server.');
}
$runCommand = "docker run -d --name {$this->deployment_uuid} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
- } elseif ($this->dockerConfigFileExists === 'OK') {
- $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
} else {
- $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} --rm -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
+ if ($this->dockerConfigFileExists === 'OK') {
+ $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} --rm -v {$this->serverUserHomeDir}/.docker/config.json:/root/.docker/config.json:ro -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
+ } else {
+ $runCommand = "docker run -d --network {$this->destination->network} --name {$this->deployment_uuid} --rm -v /var/run/docker.sock:/var/run/docker.sock {$helperImage}";
+ }
}
$this->application_deployment_queue->addLogEntry("Preparing container with helper image: $helperImage.");
$this->execute_remote_command(
@@ -1363,7 +1389,7 @@ private function deploy_to_additional_destinations()
return;
}
foreach ($destination_ids as $destination_id) {
- $destination = StandaloneDocker::query()->find($destination_id);
+ $destination = StandaloneDocker::find($destination_id);
$server = $destination->server;
if ($server->team_id !== $this->mainServer->team_id) {
$this->application_deployment_queue->addLogEntry("Skipping deployment to {$server->name}. Not in the same team?!");
@@ -1391,13 +1417,17 @@ private function deploy_to_additional_destinations()
private function set_coolify_variables()
{
$this->coolify_variables = "SOURCE_COMMIT={$this->commit} ";
- $fqdn = $this->pull_request_id === 0 ? $this->application->fqdn : $this->applicationPreview->fqdn;
+ if ($this->pull_request_id === 0) {
+ $fqdn = $this->application->fqdn;
+ } else {
+ $fqdn = $this->preview->fqdn;
+ }
if (isset($fqdn)) {
$this->coolify_variables .= "COOLIFY_FQDN={$fqdn} ";
$url = str($fqdn)->replace('http://', '')->replace('https://', '');
$this->coolify_variables .= "COOLIFY_URL={$url} ";
}
- if (property_exists($this->application, 'git_branch') && $this->application->git_branch !== null) {
+ if (isset($this->application->git_branch)) {
$this->coolify_variables .= "COOLIFY_BRANCH={$this->application->git_branch} ";
}
}
@@ -1568,8 +1598,9 @@ private function nixpacks_build_cmd()
if ($this->application->install_command) {
$nixpacks_command .= " --install-cmd \"{$this->application->install_command}\"";
}
+ $nixpacks_command .= " {$this->workdir}";
- return $nixpacks_command." {$this->workdir}";
+ return $nixpacks_command;
}
private function generate_nixpacks_env_variables()
@@ -1635,7 +1666,7 @@ private function generate_compose_file()
});
if ($found_caddy_labels->count() === 0) {
if ($this->pull_request_id !== 0) {
- $domains = str(data_get($this->applicationPreview, 'fqdn'))->explode(',');
+ $domains = str(data_get($this->preview, 'fqdn'))->explode(',');
} else {
$domains = str(data_get($this->application, 'fqdn'))->explode(',');
}
@@ -1651,11 +1682,13 @@ private function generate_compose_file()
}
$this->application->custom_labels = base64_encode($labels->implode("\n"));
$this->application->save();
- } elseif (! $this->application->settings->is_container_label_readonly_enabled) {
- $labels = collect(generateLabelsApplication($this->application, $this->applicationPreview));
+ } else {
+ if (! $this->application->settings->is_container_label_readonly_enabled) {
+ $labels = collect(generateLabelsApplication($this->application, $this->preview));
+ }
}
if ($this->pull_request_id !== 0) {
- $labels = collect(generateLabelsApplication($this->application, $this->applicationPreview));
+ $labels = collect(generateLabelsApplication($this->application, $this->preview));
}
if ($this->application->settings->is_container_label_escape_enabled) {
$labels = $labels->map(function ($value, $key) {
@@ -1841,21 +1874,23 @@ private function generate_compose_file()
$docker_compose['services'][$this->application->uuid] = array_merge_recursive($docker_compose['services'][$this->application->uuid], $custom_compose);
}
}
- } elseif (count($custom_compose) > 0) {
- $ipv4 = data_get($custom_compose, 'ip.0');
- $ipv6 = data_get($custom_compose, 'ip6.0');
- data_forget($custom_compose, 'ip');
- data_forget($custom_compose, 'ip6');
- if ($ipv4 || $ipv6) {
- data_forget($docker_compose['services'][$this->container_name], 'networks');
- }
- if ($ipv4) {
- $docker_compose['services'][$this->container_name]['networks'][$this->destination->network]['ipv4_address'] = $ipv4;
- }
- if ($ipv6) {
- $docker_compose['services'][$this->container_name]['networks'][$this->destination->network]['ipv6_address'] = $ipv6;
+ } else {
+ if (count($custom_compose) > 0) {
+ $ipv4 = data_get($custom_compose, 'ip.0');
+ $ipv6 = data_get($custom_compose, 'ip6.0');
+ data_forget($custom_compose, 'ip');
+ data_forget($custom_compose, 'ip6');
+ if ($ipv4 || $ipv6) {
+ data_forget($docker_compose['services'][$this->container_name], 'networks');
+ }
+ if ($ipv4) {
+ $docker_compose['services'][$this->container_name]['networks'][$this->destination->network]['ipv4_address'] = $ipv4;
+ }
+ if ($ipv6) {
+ $docker_compose['services'][$this->container_name]['networks'][$this->destination->network]['ipv6_address'] = $ipv6;
+ }
+ $docker_compose['services'][$this->container_name] = array_merge_recursive($docker_compose['services'][$this->container_name], $custom_compose);
}
- $docker_compose['services'][$this->container_name] = array_merge_recursive($docker_compose['services'][$this->container_name], $custom_compose);
}
}
@@ -2070,82 +2105,86 @@ private function build_image()
'hidden' => true,
]
);
- } elseif ($this->application->dockerfile) {
- // Pure Dockerfile based deployment
- if ($this->force_rebuild) {
- $build_command = "docker build --no-cache --pull {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
- } else {
- $build_command = "docker build --pull {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
- }
- $base64_build_command = base64_encode($build_command);
- $this->execute_remote_command(
- [
- executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),
- 'hidden' => true,
- ],
- [
- executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),
- 'hidden' => true,
- ],
- [
- executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),
- 'hidden' => true,
- ]
- );
- } elseif ($this->application->build_pack === 'nixpacks') {
- $this->nixpacks_plan = base64_encode($this->nixpacks_plan);
- $this->execute_remote_command([executeInDocker($this->deployment_uuid, "echo '{$this->nixpacks_plan}' | base64 -d | tee /artifacts/thegameplan.json > /dev/null"), 'hidden' => true]);
- if ($this->force_rebuild) {
- $this->execute_remote_command([
- executeInDocker($this->deployment_uuid, "nixpacks build -c /artifacts/thegameplan.json --no-cache --no-error-without-start -n {$this->production_image_name} {$this->workdir} -o {$this->workdir}"),
- 'hidden' => true,
- ]);
- $build_command = "docker build --no-cache {$this->addHosts} --network host -f {$this->workdir}/.nixpacks/Dockerfile {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
- } else {
- $this->execute_remote_command([
- executeInDocker($this->deployment_uuid, "nixpacks build -c /artifacts/thegameplan.json --cache-key '{$this->application->uuid}' --no-error-without-start -n {$this->production_image_name} {$this->workdir} -o {$this->workdir}"),
- 'hidden' => true,
- ]);
- $build_command = "docker build {$this->addHosts} --network host -f {$this->workdir}/.nixpacks/Dockerfile {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
- }
- $base64_build_command = base64_encode($build_command);
- $this->execute_remote_command(
- [
- executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),
- 'hidden' => true,
- ],
- [
- executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),
- 'hidden' => true,
- ],
- [
- executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),
- 'hidden' => true,
- ]
- );
- $this->execute_remote_command([executeInDocker($this->deployment_uuid, 'rm /artifacts/thegameplan.json'), 'hidden' => true]);
} else {
- if ($this->force_rebuild) {
- $build_command = "docker build --no-cache {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
+ // Pure Dockerfile based deployment
+ if ($this->application->dockerfile) {
+ if ($this->force_rebuild) {
+ $build_command = "docker build --no-cache --pull {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
+ } else {
+ $build_command = "docker build --pull {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
+ }
$base64_build_command = base64_encode($build_command);
+ $this->execute_remote_command(
+ [
+ executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),
+ 'hidden' => true,
+ ],
+ [
+ executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),
+ 'hidden' => true,
+ ],
+ [
+ executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),
+ 'hidden' => true,
+ ]
+ );
} else {
- $build_command = "docker build {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
- $base64_build_command = base64_encode($build_command);
+ if ($this->application->build_pack === 'nixpacks') {
+ $this->nixpacks_plan = base64_encode($this->nixpacks_plan);
+ $this->execute_remote_command([executeInDocker($this->deployment_uuid, "echo '{$this->nixpacks_plan}' | base64 -d | tee /artifacts/thegameplan.json > /dev/null"), 'hidden' => true]);
+ if ($this->force_rebuild) {
+ $this->execute_remote_command([
+ executeInDocker($this->deployment_uuid, "nixpacks build -c /artifacts/thegameplan.json --no-cache --no-error-without-start -n {$this->production_image_name} {$this->workdir} -o {$this->workdir}"),
+ 'hidden' => true,
+ ]);
+ $build_command = "docker build --no-cache {$this->addHosts} --network host -f {$this->workdir}/.nixpacks/Dockerfile {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
+ } else {
+ $this->execute_remote_command([
+ executeInDocker($this->deployment_uuid, "nixpacks build -c /artifacts/thegameplan.json --cache-key '{$this->application->uuid}' --no-error-without-start -n {$this->production_image_name} {$this->workdir} -o {$this->workdir}"),
+ 'hidden' => true,
+ ]);
+ $build_command = "docker build {$this->addHosts} --network host -f {$this->workdir}/.nixpacks/Dockerfile {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
+ }
+ $base64_build_command = base64_encode($build_command);
+ $this->execute_remote_command(
+ [
+ executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),
+ 'hidden' => true,
+ ],
+ [
+ executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),
+ 'hidden' => true,
+ ],
+ [
+ executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),
+ 'hidden' => true,
+ ]
+ );
+ $this->execute_remote_command([executeInDocker($this->deployment_uuid, 'rm /artifacts/thegameplan.json'), 'hidden' => true]);
+ } else {
+ if ($this->force_rebuild) {
+ $build_command = "docker build --no-cache {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
+ $base64_build_command = base64_encode($build_command);
+ } else {
+ $build_command = "docker build {$this->buildTarget} {$this->addHosts} --network host -f {$this->workdir}{$this->dockerfile_location} {$this->build_args} --progress plain -t {$this->production_image_name} {$this->workdir}";
+ $base64_build_command = base64_encode($build_command);
+ }
+ $this->execute_remote_command(
+ [
+ executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),
+ 'hidden' => true,
+ ],
+ [
+ executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),
+ 'hidden' => true,
+ ],
+ [
+ executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),
+ 'hidden' => true,
+ ]
+ );
+ }
}
- $this->execute_remote_command(
- [
- executeInDocker($this->deployment_uuid, "echo '{$base64_build_command}' | base64 -d | tee /artifacts/build.sh > /dev/null"),
- 'hidden' => true,
- ],
- [
- executeInDocker($this->deployment_uuid, 'cat /artifacts/build.sh'),
- 'hidden' => true,
- ],
- [
- executeInDocker($this->deployment_uuid, 'bash /artifacts/build.sh'),
- 'hidden' => true,
- ]
- );
}
$this->application_deployment_queue->addLogEntry('Building docker image completed.');
}
@@ -2175,7 +2214,7 @@ private function graceful_shutdown_container(string $containerName, int $timeout
["docker kill $containerName", 'hidden' => true, 'ignore_errors' => true]
);
}
- } catch (Exception $error) {
+ } catch (\Exception $error) {
$this->application_deployment_queue->addLogEntry("Error stopping container $containerName: ".$error->getMessage(), 'stderr');
}
@@ -2228,14 +2267,16 @@ private function start_by_compose_file()
[executeInDocker($this->deployment_uuid, "docker compose --project-name {$this->application->uuid} --project-directory {$this->workdir} pull"), 'hidden' => true],
[executeInDocker($this->deployment_uuid, "{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->workdir} up --build -d"), 'hidden' => true],
);
- } elseif ($this->use_build_server) {
- $this->execute_remote_command(
- ["{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->configuration_dir} -f {$this->configuration_dir}{$this->docker_compose_location} up --build -d", 'hidden' => true],
- );
} else {
- $this->execute_remote_command(
- [executeInDocker($this->deployment_uuid, "{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up --build -d"), 'hidden' => true],
- );
+ if ($this->use_build_server) {
+ $this->execute_remote_command(
+ ["{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->configuration_dir} -f {$this->configuration_dir}{$this->docker_compose_location} up --build -d", 'hidden' => true],
+ );
+ } else {
+ $this->execute_remote_command(
+ [executeInDocker($this->deployment_uuid, "{$this->coolify_variables} docker compose --project-name {$this->application->uuid} --project-directory {$this->workdir} -f {$this->workdir}{$this->docker_compose_location} up --build -d"), 'hidden' => true],
+ );
+ }
}
$this->application_deployment_queue->addLogEntry('New container started.');
}
@@ -2357,7 +2398,7 @@ private function next(string $status)
]);
}
if ($this->application_deployment_queue->status === ApplicationDeploymentStatus::FAILED->value) {
- $this->application->environment->project->team?->notify(new DeploymentFailed($this->application, $this->deployment_uuid, $this->applicationPreview));
+ $this->application->environment->project->team?->notify(new DeploymentFailed($this->application, $this->deployment_uuid, $this->preview));
return;
}
@@ -2365,20 +2406,20 @@ private function next(string $status)
if (! $this->only_this_server) {
$this->deploy_to_additional_destinations();
}
- $this->application->environment->project->team?->notify(new DeploymentSuccess($this->application, $this->deployment_uuid, $this->applicationPreview));
+ $this->application->environment->project->team?->notify(new DeploymentSuccess($this->application, $this->deployment_uuid, $this->preview));
}
}
- public function failed(Throwable $throwable): void
+ public function failed(Throwable $exception): void
{
$this->next(ApplicationDeploymentStatus::FAILED->value);
$this->application_deployment_queue->addLogEntry('Oops something is not okay, are you okay? 😢', 'stderr');
- if (str($throwable->getMessage())->isNotEmpty()) {
- $this->application_deployment_queue->addLogEntry($throwable->getMessage(), 'stderr');
+ if (str($exception->getMessage())->isNotEmpty()) {
+ $this->application_deployment_queue->addLogEntry($exception->getMessage(), 'stderr');
}
if ($this->application->build_pack !== 'dockercompose') {
- $code = $throwable->getCode();
+ $code = $exception->getCode();
if ($code !== 69420) {
// 69420 means failed to push the image to the registry, so we don't need to remove the new version as it is the currently running one
if ($this->application->settings->is_consistent_container_name_enabled || str($this->application->settings->custom_internal_name)->isNotEmpty()) {
diff --git a/app/Jobs/ApplicationPullRequestUpdateJob.php b/app/Jobs/ApplicationPullRequestUpdateJob.php
index 195f997b61..ef8e6efb6e 100755
--- a/app/Jobs/ApplicationPullRequestUpdateJob.php
+++ b/app/Jobs/ApplicationPullRequestUpdateJob.php
@@ -11,7 +11,6 @@
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Throwable;
class ApplicationPullRequestUpdateJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -23,8 +22,8 @@ class ApplicationPullRequestUpdateJob implements ShouldBeEncrypted, ShouldQueue
public function __construct(
public Application $application,
- public ApplicationPreview $applicationPreview,
- public ProcessStatus $processStatus,
+ public ApplicationPreview $preview,
+ public ProcessStatus $status,
public ?string $deployment_uuid = null
) {
$this->onQueue('high');
@@ -34,42 +33,39 @@ public function handle()
{
try {
if ($this->application->is_public_repository()) {
- return null;
+ return;
}
- if ($this->processStatus === ProcessStatus::CLOSED) {
+ if ($this->status === ProcessStatus::CLOSED) {
$this->delete_comment();
- return null;
- }
- if ($this->processStatus === ProcessStatus::IN_PROGRESS) {
+ return;
+ } elseif ($this->status === ProcessStatus::IN_PROGRESS) {
$this->body = "The preview deployment is in progress. 🟡\n\n";
- } elseif ($this->processStatus === ProcessStatus::FINISHED) {
+ } elseif ($this->status === ProcessStatus::FINISHED) {
$this->body = "The preview deployment is ready. 🟢\n\n";
- if ($this->applicationPreview->fqdn) {
- $this->body .= "[Open Preview]({$this->applicationPreview->fqdn}) | ";
+ if ($this->preview->fqdn) {
+ $this->body .= "[Open Preview]({$this->preview->fqdn}) | ";
}
- } elseif ($this->processStatus === ProcessStatus::ERROR) {
+ } elseif ($this->status === ProcessStatus::ERROR) {
$this->body = "The preview deployment failed. 🔴\n\n";
}
$this->build_logs_url = base_url()."/project/{$this->application->environment->project->uuid}/{$this->application->environment->name}/application/{$this->application->uuid}/deployment/{$this->deployment_uuid}";
$this->body .= '[Open Build Logs]('.$this->build_logs_url.")\n\n\n";
$this->body .= 'Last updated at: '.now()->toDateTimeString().' CET';
- if ($this->applicationPreview->pull_request_issue_comment_id) {
+ if ($this->preview->pull_request_issue_comment_id) {
$this->update_comment();
} else {
$this->create_comment();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return $e;
}
-
- return null;
}
private function update_comment()
{
- ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->applicationPreview->pull_request_issue_comment_id}", method: 'patch', data: [
+ ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->preview->pull_request_issue_comment_id}", method: 'patch', data: [
'body' => $this->body,
], throwError: false);
if (data_get($data, 'message') === 'Not Found') {
@@ -79,15 +75,15 @@ private function update_comment()
private function create_comment()
{
- ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/{$this->applicationPreview->pull_request_id}/comments", method: 'post', data: [
+ ['data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/{$this->preview->pull_request_id}/comments", method: 'post', data: [
'body' => $this->body,
]);
- $this->applicationPreview->pull_request_issue_comment_id = $data['id'];
- $this->applicationPreview->save();
+ $this->preview->pull_request_issue_comment_id = $data['id'];
+ $this->preview->save();
}
private function delete_comment()
{
- githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->applicationPreview->pull_request_issue_comment_id}", method: 'delete');
+ githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/issues/comments/{$this->preview->pull_request_issue_comment_id}", method: 'delete');
}
}
diff --git a/app/Jobs/CheckAndStartSentinelJob.php b/app/Jobs/CheckAndStartSentinelJob.php
index 37d669d234..788db89eaa 100644
--- a/app/Jobs/CheckAndStartSentinelJob.php
+++ b/app/Jobs/CheckAndStartSentinelJob.php
@@ -34,18 +34,19 @@ public function handle(): void
}
// If sentinel is running, check if it needs an update
$runningVersion = instant_remote_process(['docker exec coolify-sentinel sh -c "curl http://127.0.0.1:8888/api/version"'], $this->server, false);
- if ($runningVersion === null || $runningVersion === '' || $runningVersion === '0') {
+ if (empty($runningVersion)) {
$runningVersion = '0.0.0';
}
if ($latestVersion === '0.0.0' && $runningVersion === '0.0.0') {
StartSentinel::run(server: $this->server, restart: true, latestVersion: 'latest');
return;
- }
- if (version_compare($runningVersion, $latestVersion, '<')) {
- StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion);
+ } else {
+ if (version_compare($runningVersion, $latestVersion, '<')) {
+ StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion);
- return;
+ return;
+ }
}
}
}
diff --git a/app/Jobs/CheckForUpdatesJob.php b/app/Jobs/CheckForUpdatesJob.php
index 2995dad02f..1d3a345e15 100644
--- a/app/Jobs/CheckForUpdatesJob.php
+++ b/app/Jobs/CheckForUpdatesJob.php
@@ -10,7 +10,6 @@
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
-use Throwable;
class CheckForUpdatesJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -38,7 +37,7 @@ public function handle(): void
$settings->update(['new_version_available' => false]);
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
// Consider implementing a notification to administrators
}
}
diff --git a/app/Jobs/CheckHelperImageJob.php b/app/Jobs/CheckHelperImageJob.php
index 5269e2d224..6abb8a1502 100644
--- a/app/Jobs/CheckHelperImageJob.php
+++ b/app/Jobs/CheckHelperImageJob.php
@@ -9,7 +9,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
-use Throwable;
class CheckHelperImageJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -17,6 +16,8 @@ class CheckHelperImageJob implements ShouldBeEncrypted, ShouldQueue
public $timeout = 1000;
+ public function __construct() {}
+
public function handle(): void
{
try {
@@ -30,7 +31,7 @@ public function handle(): void
$settings->update(['helper_version' => $latest_version]);
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
send_internal_notification('CheckHelperImageJob failed with: '.$e->getMessage());
throw $e;
}
diff --git a/app/Jobs/CleanupHelperContainersJob.php b/app/Jobs/CleanupHelperContainersJob.php
index f3a081d2b3..f185ab7812 100644
--- a/app/Jobs/CleanupHelperContainersJob.php
+++ b/app/Jobs/CleanupHelperContainersJob.php
@@ -10,7 +10,6 @@
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Throwable;
class CleanupHelperContainersJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue
{
@@ -28,7 +27,7 @@ public function handle(): void
instant_remote_process(['docker container rm -f '.$containerId], $this->server, false);
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
send_internal_notification('CleanupHelperContainersJob failed with error: '.$e->getMessage());
}
}
diff --git a/app/Jobs/CleanupInstanceStuffsJob.php b/app/Jobs/CleanupInstanceStuffsJob.php
index 35db942947..84f14ed02a 100644
--- a/app/Jobs/CleanupInstanceStuffsJob.php
+++ b/app/Jobs/CleanupInstanceStuffsJob.php
@@ -12,12 +12,13 @@
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
-use Throwable;
class CleanupInstanceStuffsJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+ public function __construct() {}
+
public function middleware(): array
{
return [(new WithoutOverlapping('cleanup-instance-stuffs'))->dontRelease()];
@@ -27,7 +28,7 @@ public function handle(): void
{
try {
$this->cleanupInvitationLink();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
Log::error('CleanupInstanceStuffsJob failed with error: '.$e->getMessage());
}
}
diff --git a/app/Jobs/CleanupStaleMultiplexedConnections.php b/app/Jobs/CleanupStaleMultiplexedConnections.php
index 126adf37ed..6d49bee4b0 100644
--- a/app/Jobs/CleanupStaleMultiplexedConnections.php
+++ b/app/Jobs/CleanupStaleMultiplexedConnections.php
@@ -28,7 +28,7 @@ private function cleanupStaleConnections()
foreach ($muxFiles as $muxFile) {
$serverUuid = $this->extractServerUuidFromMuxFile($muxFile);
- $server = Server::query()->where('uuid', $serverUuid)->first();
+ $server = Server::where('uuid', $serverUuid)->first();
if (! $server) {
$this->removeMultiplexFile($muxFile);
@@ -57,7 +57,7 @@ private function cleanupStaleConnections()
private function cleanupNonExistentServerConnections()
{
$muxFiles = Storage::disk('ssh-mux')->files();
- $existingServerUuids = Server::query()->pluck('uuid')->toArray();
+ $existingServerUuids = Server::pluck('uuid')->toArray();
foreach ($muxFiles as $muxFile) {
$serverUuid = $this->extractServerUuidFromMuxFile($muxFile);
diff --git a/app/Jobs/CoolifyTask.php b/app/Jobs/CoolifyTask.php
index ba63ffdc0a..49a5ba8dd2 100755
--- a/app/Jobs/CoolifyTask.php
+++ b/app/Jobs/CoolifyTask.php
@@ -33,13 +33,13 @@ public function __construct(
*/
public function handle(): void
{
- $runRemoteProcess = resolve(RunRemoteProcess::class, [
+ $remote_process = resolve(RunRemoteProcess::class, [
'activity' => $this->activity,
'ignore_errors' => $this->ignore_errors,
'call_event_on_finish' => $this->call_event_on_finish,
'call_event_data' => $this->call_event_data,
]);
- $runRemoteProcess();
+ $remote_process();
}
}
diff --git a/app/Jobs/DatabaseBackupJob.php b/app/Jobs/DatabaseBackupJob.php
index 5fc602c6e9..6730dceb72 100644
--- a/app/Jobs/DatabaseBackupJob.php
+++ b/app/Jobs/DatabaseBackupJob.php
@@ -16,7 +16,6 @@
use App\Notifications\Database\BackupFailed;
use App\Notifications\Database\BackupSuccess;
use Carbon\Carbon;
-use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -24,7 +23,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Str;
-use Throwable;
class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -58,7 +56,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue
public ?S3Storage $s3 = null;
- public function __construct(public ScheduledDatabaseBackup $scheduledDatabaseBackup)
+ public function __construct(public ScheduledDatabaseBackup $backup)
{
$this->onQueue('high');
}
@@ -68,26 +66,26 @@ public function handle(): void
try {
$databasesToBackup = null;
- $this->team = Team::query()->find($this->scheduledDatabaseBackup->team_id);
+ $this->team = Team::find($this->backup->team_id);
if (! $this->team) {
- $this->scheduledDatabaseBackup->delete();
+ $this->backup->delete();
return;
}
- if (data_get($this->scheduledDatabaseBackup, 'database_type') === ServiceDatabase::class) {
- $this->database = data_get($this->scheduledDatabaseBackup, 'database');
+ if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {
+ $this->database = data_get($this->backup, 'database');
$this->server = $this->database->service->server;
- $this->s3 = $this->scheduledDatabaseBackup->s3;
+ $this->s3 = $this->backup->s3;
} else {
- $this->database = data_get($this->scheduledDatabaseBackup, 'database');
+ $this->database = data_get($this->backup, 'database');
$this->server = $this->database->destination->server;
- $this->s3 = $this->scheduledDatabaseBackup->s3;
+ $this->s3 = $this->backup->s3;
}
if (is_null($this->server)) {
- throw new Exception('Server not found?!');
+ throw new \Exception('Server not found?!');
}
if (is_null($this->database)) {
- throw new Exception('Database not found?!');
+ throw new \Exception('Database not found?!');
}
BackupCreated::dispatch($this->team->id);
@@ -96,7 +94,7 @@ public function handle(): void
if (! $status->startsWith('running') && $this->database->id !== 0) {
return;
}
- if (data_get($this->scheduledDatabaseBackup, 'database_type') === ServiceDatabase::class) {
+ if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {
$databaseType = $this->database->databaseType();
$serviceUuid = $this->database->service->uuid;
$serviceName = str($this->database->service->name)->slug();
@@ -110,13 +108,21 @@ public function handle(): void
$user = $envs->filter(function ($env) {
return str($env)->startsWith('POSTGRES_USER=');
})->first();
- $this->database->postgres_user = $user ? str($user)->after('POSTGRES_USER=')->value() : 'postgres';
+ if ($user) {
+ $this->database->postgres_user = str($user)->after('POSTGRES_USER=')->value();
+ } else {
+ $this->database->postgres_user = 'postgres';
+ }
$db = $envs->filter(function ($env) {
return str($env)->startsWith('POSTGRES_DB=');
})->first();
- $databasesToBackup = $db ? str($db)->after('POSTGRES_DB=')->value() : $this->database->postgres_user;
+ if ($db) {
+ $databasesToBackup = str($db)->after('POSTGRES_DB=')->value();
+ } else {
+ $databasesToBackup = $this->database->postgres_user;
+ }
$this->postgres_password = $envs->filter(function ($env) {
return str($env)->startsWith('POSTGRES_PASSWORD=');
})->first();
@@ -144,7 +150,7 @@ public function handle(): void
if ($db) {
$databasesToBackup = str($db)->after('MYSQL_DATABASE=')->value();
} else {
- throw new Exception('MYSQL_DATABASE not found');
+ throw new \Exception('MYSQL_DATABASE not found');
}
} elseif (str($databaseType)->contains('mariadb')) {
$this->container_name = "{$this->database->name}-$serviceUuid";
@@ -180,7 +186,7 @@ public function handle(): void
if ($db) {
$databasesToBackup = str($db)->after('MYSQL_DATABASE=')->value();
} else {
- throw new Exception('MARIADB_DATABASE or MYSQL_DATABASE not found');
+ throw new \Exception('MARIADB_DATABASE or MYSQL_DATABASE not found');
}
}
}
@@ -189,7 +195,7 @@ public function handle(): void
$this->container_name = $this->database->uuid;
$this->directory_name = $databaseName.'-'.$this->container_name;
$databaseType = $this->database->type();
- $databasesToBackup = data_get($this->scheduledDatabaseBackup, 'databases_to_backup');
+ $databasesToBackup = data_get($this->backup, 'databases_to_backup');
}
if (blank($databasesToBackup)) {
if (str($databaseType)->contains('postgres')) {
@@ -203,24 +209,26 @@ public function handle(): void
} else {
return;
}
- } elseif (str($databaseType)->contains('postgres')) {
- // Format: db1,db2,db3
- $databasesToBackup = explode(',', $databasesToBackup);
- $databasesToBackup = array_map('trim', $databasesToBackup);
- } elseif (str($databaseType)->contains('mongodb')) {
- // Format: db1:collection1,collection2|db2:collection3,collection4
- $databasesToBackup = explode('|', $databasesToBackup);
- $databasesToBackup = array_map('trim', $databasesToBackup);
- } elseif (str($databaseType)->contains('mysql')) {
- // Format: db1,db2,db3
- $databasesToBackup = explode(',', $databasesToBackup);
- $databasesToBackup = array_map('trim', $databasesToBackup);
- } elseif (str($databaseType)->contains('mariadb')) {
- // Format: db1,db2,db3
- $databasesToBackup = explode(',', $databasesToBackup);
- $databasesToBackup = array_map('trim', $databasesToBackup);
} else {
- return;
+ if (str($databaseType)->contains('postgres')) {
+ // Format: db1,db2,db3
+ $databasesToBackup = explode(',', $databasesToBackup);
+ $databasesToBackup = array_map('trim', $databasesToBackup);
+ } elseif (str($databaseType)->contains('mongodb')) {
+ // Format: db1:collection1,collection2|db2:collection3,collection4
+ $databasesToBackup = explode('|', $databasesToBackup);
+ $databasesToBackup = array_map('trim', $databasesToBackup);
+ } elseif (str($databaseType)->contains('mysql')) {
+ // Format: db1,db2,db3
+ $databasesToBackup = explode(',', $databasesToBackup);
+ $databasesToBackup = array_map('trim', $databasesToBackup);
+ } elseif (str($databaseType)->contains('mariadb')) {
+ // Format: db1,db2,db3
+ $databasesToBackup = explode(',', $databasesToBackup);
+ $databasesToBackup = array_map('trim', $databasesToBackup);
+ } else {
+ return;
+ }
}
$this->backup_dir = backup_dir().'/databases/'.str($this->team->name)->slug().'-'.$this->team->id.'/'.$this->directory_name;
if ($this->database->name === 'coolify-db') {
@@ -229,80 +237,82 @@ public function handle(): void
$ip = Str::slug($this->server->ip);
$this->backup_dir = backup_dir().'/coolify'."/coolify-db-$ip";
}
- foreach ($databasesToBackup as $databaseToBackup) {
+ foreach ($databasesToBackup as $database) {
$size = 0;
try {
if (str($databaseType)->contains('postgres')) {
- $this->backup_file = "/pg-dump-{$databaseToBackup}-".Carbon::now()->timestamp.'.dmp';
- if ($this->scheduledDatabaseBackup->dump_all) {
+ $this->backup_file = "/pg-dump-$database-".Carbon::now()->timestamp.'.dmp';
+ if ($this->backup->dump_all) {
$this->backup_file = '/pg-dump-all-'.Carbon::now()->timestamp.'.gz';
}
$this->backup_location = $this->backup_dir.$this->backup_file;
- $this->backup_log = ScheduledDatabaseBackupExecution::query()->create([
- 'database_name' => $databaseToBackup,
+ $this->backup_log = ScheduledDatabaseBackupExecution::create([
+ 'database_name' => $database,
'filename' => $this->backup_location,
- 'scheduled_database_backup_id' => $this->scheduledDatabaseBackup->id,
+ 'scheduled_database_backup_id' => $this->backup->id,
]);
- $this->backup_standalone_postgresql($databaseToBackup);
+ $this->backup_standalone_postgresql($database);
} elseif (str($databaseType)->contains('mongodb')) {
- if ($databaseToBackup === '*') {
- $databaseToBackup = 'all';
+ if ($database === '*') {
+ $database = 'all';
$databaseName = 'all';
- } elseif (str($databaseToBackup)->contains(':')) {
- $databaseName = str($databaseToBackup)->before(':');
} else {
- $databaseName = $databaseToBackup;
+ if (str($database)->contains(':')) {
+ $databaseName = str($database)->before(':');
+ } else {
+ $databaseName = $database;
+ }
}
$this->backup_file = "/mongo-dump-$databaseName-".Carbon::now()->timestamp.'.tar.gz';
$this->backup_location = $this->backup_dir.$this->backup_file;
- $this->backup_log = ScheduledDatabaseBackupExecution::query()->create([
+ $this->backup_log = ScheduledDatabaseBackupExecution::create([
'database_name' => $databaseName,
'filename' => $this->backup_location,
- 'scheduled_database_backup_id' => $this->scheduledDatabaseBackup->id,
+ 'scheduled_database_backup_id' => $this->backup->id,
]);
- $this->backup_standalone_mongodb($databaseToBackup);
+ $this->backup_standalone_mongodb($database);
} elseif (str($databaseType)->contains('mysql')) {
- $this->backup_file = "/mysql-dump-{$databaseToBackup}-".Carbon::now()->timestamp.'.dmp';
- if ($this->scheduledDatabaseBackup->dump_all) {
+ $this->backup_file = "/mysql-dump-$database-".Carbon::now()->timestamp.'.dmp';
+ if ($this->backup->dump_all) {
$this->backup_file = '/mysql-dump-all-'.Carbon::now()->timestamp.'.gz';
}
$this->backup_location = $this->backup_dir.$this->backup_file;
- $this->backup_log = ScheduledDatabaseBackupExecution::query()->create([
- 'database_name' => $databaseToBackup,
+ $this->backup_log = ScheduledDatabaseBackupExecution::create([
+ 'database_name' => $database,
'filename' => $this->backup_location,
- 'scheduled_database_backup_id' => $this->scheduledDatabaseBackup->id,
+ 'scheduled_database_backup_id' => $this->backup->id,
]);
- $this->backup_standalone_mysql($databaseToBackup);
+ $this->backup_standalone_mysql($database);
} elseif (str($databaseType)->contains('mariadb')) {
- $this->backup_file = "/mariadb-dump-{$databaseToBackup}-".Carbon::now()->timestamp.'.dmp';
- if ($this->scheduledDatabaseBackup->dump_all) {
+ $this->backup_file = "/mariadb-dump-$database-".Carbon::now()->timestamp.'.dmp';
+ if ($this->backup->dump_all) {
$this->backup_file = '/mariadb-dump-all-'.Carbon::now()->timestamp.'.gz';
}
$this->backup_location = $this->backup_dir.$this->backup_file;
- $this->backup_log = ScheduledDatabaseBackupExecution::query()->create([
- 'database_name' => $databaseToBackup,
+ $this->backup_log = ScheduledDatabaseBackupExecution::create([
+ 'database_name' => $database,
'filename' => $this->backup_location,
- 'scheduled_database_backup_id' => $this->scheduledDatabaseBackup->id,
+ 'scheduled_database_backup_id' => $this->backup->id,
]);
- $this->backup_standalone_mariadb($databaseToBackup);
+ $this->backup_standalone_mariadb($database);
} else {
- throw new Exception('Unsupported database type');
+ throw new \Exception('Unsupported database type');
}
$size = $this->calculate_size();
$this->remove_old_backups();
- if ($this->scheduledDatabaseBackup->save_s3) {
+ if ($this->backup->save_s3) {
$this->upload_to_s3();
}
- $this->team->notify(new BackupSuccess($this->scheduledDatabaseBackup, $this->database, $databaseToBackup));
+ $this->team->notify(new BackupSuccess($this->backup, $this->database, $database));
$this->backup_log->update([
'status' => 'success',
'message' => $this->backup_output,
'size' => $size,
]);
- } catch (Throwable $e) {
- if ($this->backup_log instanceof ScheduledDatabaseBackupExecution) {
+ } catch (\Throwable $e) {
+ if ($this->backup_log) {
$this->backup_log->update([
'status' => 'failed',
'message' => $this->backup_output,
@@ -310,13 +320,13 @@ public function handle(): void
'filename' => null,
]);
}
- $this->team?->notify(new BackupFailed($this->scheduledDatabaseBackup, $this->database, $this->backup_output, $databaseToBackup));
+ $this->team?->notify(new BackupFailed($this->backup, $this->database, $this->backup_output, $database));
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
throw $e;
} finally {
- if ($this->team instanceof Team) {
+ if ($this->team) {
BackupCreated::dispatch($this->team->id);
}
}
@@ -348,10 +358,12 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi
} else {
$commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$url --db $databaseName --gzip --archive > $this->backup_location";
}
- } elseif (str($this->database->image)->startsWith('mongo:4')) {
- $commands[] = "docker exec $this->container_name mongodump --uri=$url --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";
} else {
- $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$url --db $databaseName --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";
+ if (str($this->database->image)->startsWith('mongo:4')) {
+ $commands[] = "docker exec $this->container_name mongodump --uri=$url --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";
+ } else {
+ $commands[] = "docker exec $this->container_name mongodump --authenticationDatabase=admin --uri=$url --db $databaseName --gzip --excludeCollection ".$collectionsToExclude->implode(' --excludeCollection ')." --archive > $this->backup_location";
+ }
}
}
$this->backup_output = instant_remote_process($commands, $this->server);
@@ -359,7 +371,7 @@ private function backup_standalone_mongodb(string $databaseWithCollections): voi
if ($this->backup_output === '') {
$this->backup_output = null;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->add_to_backup_output($e->getMessage());
throw $e;
}
@@ -373,7 +385,7 @@ private function backup_standalone_postgresql(string $database): void
if ($this->postgres_password) {
$backupCommand .= " -e PGPASSWORD=$this->postgres_password";
}
- if ($this->scheduledDatabaseBackup->dump_all) {
+ if ($this->backup->dump_all) {
$backupCommand .= " $this->container_name pg_dumpall --username {$this->database->postgres_user} | gzip > $this->backup_location";
} else {
$backupCommand .= " $this->container_name pg_dump --format=custom --no-acl --no-owner --username {$this->database->postgres_user} $database > $this->backup_location";
@@ -385,7 +397,7 @@ private function backup_standalone_postgresql(string $database): void
if ($this->backup_output === '') {
$this->backup_output = null;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->add_to_backup_output($e->getMessage());
throw $e;
}
@@ -395,7 +407,7 @@ private function backup_standalone_mysql(string $database): void
{
try {
$commands[] = 'mkdir -p '.$this->backup_dir;
- if ($this->scheduledDatabaseBackup->dump_all) {
+ if ($this->backup->dump_all) {
$commands[] = "docker exec $this->container_name mysqldump -u root -p{$this->database->mysql_root_password} --all-databases --single-transaction --quick --lock-tables=false --compress | gzip > $this->backup_location";
} else {
$commands[] = "docker exec $this->container_name mysqldump -u root -p{$this->database->mysql_root_password} $database > $this->backup_location";
@@ -405,7 +417,7 @@ private function backup_standalone_mysql(string $database): void
if ($this->backup_output === '') {
$this->backup_output = null;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->add_to_backup_output($e->getMessage());
throw $e;
}
@@ -415,7 +427,7 @@ private function backup_standalone_mariadb(string $database): void
{
try {
$commands[] = 'mkdir -p '.$this->backup_dir;
- if ($this->scheduledDatabaseBackup->dump_all) {
+ if ($this->backup->dump_all) {
$commands[] = "docker exec $this->container_name mariadb-dump -u root -p{$this->database->mariadb_root_password} --all-databases --single-transaction --quick --lock-tables=false --compress > $this->backup_location";
} else {
$commands[] = "docker exec $this->container_name mariadb-dump -u root -p{$this->database->mariadb_root_password} $database > $this->backup_location";
@@ -425,7 +437,7 @@ private function backup_standalone_mariadb(string $database): void
if ($this->backup_output === '') {
$this->backup_output = null;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->add_to_backup_output($e->getMessage());
throw $e;
}
@@ -433,7 +445,11 @@ private function backup_standalone_mariadb(string $database): void
private function add_to_backup_output($output): void
{
- $this->backup_output = $this->backup_output ? $this->backup_output."\n".$output : $output;
+ if ($this->backup_output) {
+ $this->backup_output = $this->backup_output."\n".$output;
+ } else {
+ $this->backup_output = $output;
+ }
}
private function calculate_size()
@@ -443,10 +459,10 @@ private function calculate_size()
private function remove_old_backups(): void
{
- if ($this->scheduledDatabaseBackup->number_of_backups_locally === 0) {
- $deletable = $this->scheduledDatabaseBackup->executions()->where('status', 'success');
+ if ($this->backup->number_of_backups_locally === 0) {
+ $deletable = $this->backup->executions()->where('status', 'success');
} else {
- $deletable = $this->scheduledDatabaseBackup->executions()->where('status', 'success')->skip($this->scheduledDatabaseBackup->number_of_backups_locally - 1);
+ $deletable = $this->backup->executions()->where('status', 'success')->skip($this->backup->number_of_backups_locally - 1);
}
foreach ($deletable->get() as $execution) {
delete_backup_locally($execution->filename, $this->server);
@@ -466,7 +482,7 @@ private function upload_to_s3(): void
$bucket = $this->s3->bucket;
$endpoint = $this->s3->endpoint;
$this->s3->testConnection(shouldSave: true);
- if (data_get($this->scheduledDatabaseBackup, 'database_type') === ServiceDatabase::class) {
+ if (data_get($this->backup, 'database_type') === \App\Models\ServiceDatabase::class) {
$network = $this->database->service->destination->network;
} else {
$network = $this->database->destination->network;
@@ -477,29 +493,29 @@ private function upload_to_s3(): void
if (isDev()) {
if ($this->database->name === 'coolify-db') {
$backup_location_from = '/var/lib/docker/volumes/coolify_dev_backups_data/_data/coolify/coolify-db-'.$this->server->ip.$this->backup_file;
- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->scheduledDatabaseBackup->uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";
+ $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup->uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";
} else {
$backup_location_from = '/var/lib/docker/volumes/coolify_dev_backups_data/_data/databases/'.str($this->team->name)->slug().'-'.$this->team->id.'/'.$this->directory_name.$this->backup_file;
- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->scheduledDatabaseBackup->uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";
+ $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup->uuid} --rm -v $backup_location_from:$this->backup_location:ro {$fullImageName}";
}
} else {
- $commands[] = "docker run -d --network {$network} --name backup-of-{$this->scheduledDatabaseBackup->uuid} --rm -v $this->backup_location:$this->backup_location:ro {$fullImageName}";
+ $commands[] = "docker run -d --network {$network} --name backup-of-{$this->backup->uuid} --rm -v $this->backup_location:$this->backup_location:ro {$fullImageName}";
}
if ($this->s3->isHetzner()) {
$endpointWithoutBucket = 'https://'.str($endpoint)->after('https://')->after('.')->value();
- $commands[] = "docker exec backup-of-{$this->scheduledDatabaseBackup->uuid} mc alias set --path=off --api=S3v4 temporary {$endpointWithoutBucket} $key $secret";
+ $commands[] = "docker exec backup-of-{$this->backup->uuid} mc alias set --path=off --api=S3v4 temporary {$endpointWithoutBucket} $key $secret";
} else {
- $commands[] = "docker exec backup-of-{$this->scheduledDatabaseBackup->uuid} mc config host add temporary {$endpoint} $key $secret";
+ $commands[] = "docker exec backup-of-{$this->backup->uuid} mc config host add temporary {$endpoint} $key $secret";
}
- $commands[] = "docker exec backup-of-{$this->scheduledDatabaseBackup->uuid} mc cp $this->backup_location temporary/$bucket{$this->backup_dir}/";
+ $commands[] = "docker exec backup-of-{$this->backup->uuid} mc cp $this->backup_location temporary/$bucket{$this->backup_dir}/";
instant_remote_process($commands, $this->server);
$this->add_to_backup_output('Uploaded to S3.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->add_to_backup_output($e->getMessage());
throw $e;
} finally {
- $command = "docker rm -f backup-of-{$this->scheduledDatabaseBackup->uuid}";
+ $command = "docker rm -f backup-of-{$this->backup->uuid}";
instant_remote_process([$command], $this->server);
}
}
diff --git a/app/Jobs/DeleteResourceJob.php b/app/Jobs/DeleteResourceJob.php
index b8fe20f68d..8b9228e5f5 100644
--- a/app/Jobs/DeleteResourceJob.php
+++ b/app/Jobs/DeleteResourceJob.php
@@ -24,7 +24,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Artisan;
-use Throwable;
class DeleteResourceJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -81,7 +80,7 @@ public function handle()
|| $this->resource instanceof StandaloneKeydb
|| $this->resource instanceof StandaloneDragonfly
|| $this->resource instanceof StandaloneClickhouse;
- $server = data_get($this->resource, 'server', data_get($this->resource, 'destination.server'));
+ $server = data_get($this->resource, 'server') ?? data_get($this->resource, 'destination.server');
if (($this->dockerCleanup || $isDatabase) && $server) {
CleanupDocker::dispatch($server, true);
}
@@ -89,7 +88,7 @@ public function handle()
if ($this->deleteConnectedNetworks && ! $isDatabase) {
$this->resource?->delete_connected_networks($this->resource->uuid);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
throw $e;
} finally {
$this->resource->forceDelete();
diff --git a/app/Jobs/DockerCleanupJob.php b/app/Jobs/DockerCleanupJob.php
index 03db120272..103c137b9f 100644
--- a/app/Jobs/DockerCleanupJob.php
+++ b/app/Jobs/DockerCleanupJob.php
@@ -13,7 +13,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
-use Throwable;
class DockerCleanupJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -67,7 +66,7 @@ public function handle(): void
} else {
$this->server->team?->notify(new DockerCleanupSuccess($this->server, 'No cleanup needed for '.$this->server->name));
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->server->team?->notify(new DockerCleanupFailed($this->server, 'Docker cleanup job failed with the following error: '.$e->getMessage()));
throw $e;
}
diff --git a/app/Jobs/GithubAppPermissionJob.php b/app/Jobs/GithubAppPermissionJob.php
index 95f4911ae7..d483fe4c2d 100644
--- a/app/Jobs/GithubAppPermissionJob.php
+++ b/app/Jobs/GithubAppPermissionJob.php
@@ -10,7 +10,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
-use Throwable;
class GithubAppPermissionJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -23,25 +22,25 @@ public function backoff(): int
return isDev() ? 1 : 3;
}
- public function __construct(public GithubApp $githubApp) {}
+ public function __construct(public GithubApp $github_app) {}
public function handle()
{
try {
- $github_access_token = generate_github_jwt_token($this->githubApp);
+ $github_access_token = generate_github_jwt_token($this->github_app);
$response = Http::withHeaders([
'Authorization' => "Bearer $github_access_token",
'Accept' => 'application/vnd.github+json',
- ])->get("{$this->githubApp->api_url}/app");
+ ])->get("{$this->github_app->api_url}/app");
$response = $response->json();
$permissions = data_get($response, 'permissions');
- $this->githubApp->contents = data_get($permissions, 'contents');
- $this->githubApp->metadata = data_get($permissions, 'metadata');
- $this->githubApp->pull_requests = data_get($permissions, 'pull_requests');
- $this->githubApp->administration = data_get($permissions, 'administration');
- $this->githubApp->save();
- $this->githubApp->makeVisible('client_secret')->makeVisible('webhook_secret');
- } catch (Throwable $e) {
+ $this->github_app->contents = data_get($permissions, 'contents');
+ $this->github_app->metadata = data_get($permissions, 'metadata');
+ $this->github_app->pull_requests = data_get($permissions, 'pull_requests');
+ $this->github_app->administration = data_get($permissions, 'administration');
+ $this->github_app->save();
+ $this->github_app->makeVisible('client_secret')->makeVisible('webhook_secret');
+ } catch (\Throwable $e) {
send_internal_notification('GithubAppPermissionJob failed with: '.$e->getMessage());
throw $e;
}
diff --git a/app/Jobs/PullTemplatesFromCDN.php b/app/Jobs/PullTemplatesFromCDN.php
index 1c82b27183..45c536e062 100644
--- a/app/Jobs/PullTemplatesFromCDN.php
+++ b/app/Jobs/PullTemplatesFromCDN.php
@@ -10,7 +10,6 @@
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
-use Throwable;
class PullTemplatesFromCDN implements ShouldBeEncrypted, ShouldQueue
{
@@ -36,7 +35,7 @@ public function handle(): void
} else {
send_internal_notification('PullTemplatesAndVersions failed with: '.$response->status().' '.$response->body());
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
send_internal_notification('PullTemplatesAndVersions failed with: '.$e->getMessage());
}
}
diff --git a/app/Jobs/PushServerUpdateJob.php b/app/Jobs/PushServerUpdateJob.php
index 7c7b39be92..24f8d1e6be 100644
--- a/app/Jobs/PushServerUpdateJob.php
+++ b/app/Jobs/PushServerUpdateJob.php
@@ -14,7 +14,6 @@
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
use App\Notifications\Container\ContainerRestarted;
-use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -22,7 +21,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
-use Throwable;
class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -94,7 +92,7 @@ public function handle()
{
// TODO: Swarm is not supported yet
if (! $this->data) {
- throw new Exception('No data provided');
+ throw new \Exception('No data provided');
}
$data = collect($this->data);
@@ -156,7 +154,7 @@ public function handle()
}
$this->updateApplicationPreviewStatus($applicationId, $containerStatus);
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
}
} elseif ($labels->has('coolify.serviceId')) {
$serviceId = $labels->get('coolify.serviceId');
@@ -175,12 +173,14 @@ public function handle()
if ($name === 'coolify-proxy' && $this->isRunning($containerStatus)) {
$this->foundProxy = true;
} elseif ($type === 'service' && $this->isRunning($containerStatus)) {
- } elseif ($this->allDatabaseUuids->contains($uuid) && $this->isRunning($containerStatus)) {
- $this->foundDatabaseUuids->push($uuid);
- if ($this->allTcpProxyUuids->contains($uuid) && $this->isRunning($containerStatus)) {
- $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: true);
- } else {
- $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: false);
+ } else {
+ if ($this->allDatabaseUuids->contains($uuid) && $this->isRunning($containerStatus)) {
+ $this->foundDatabaseUuids->push($uuid);
+ if ($this->allTcpProxyUuids->contains($uuid) && $this->isRunning($containerStatus)) {
+ $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: true);
+ } else {
+ $this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: false);
+ }
}
}
}
@@ -224,7 +224,7 @@ private function updateNotFoundApplicationStatus()
$notFoundApplicationIds = $this->allApplicationIds->diff($this->foundApplicationIds);
if ($notFoundApplicationIds->isNotEmpty()) {
$notFoundApplicationIds->each(function ($applicationId) {
- $application = Application::query()->find($applicationId);
+ $application = Application::find($applicationId);
if ($application) {
$application->status = 'exited';
$application->save();
@@ -238,7 +238,7 @@ private function updateNotFoundApplicationPreviewStatus()
$notFoundApplicationPreviewsIds = $this->allApplicationPreviewsIds->diff($this->foundApplicationPreviewsIds);
if ($notFoundApplicationPreviewsIds->isNotEmpty()) {
$notFoundApplicationPreviewsIds->each(function ($applicationPreviewId) {
- $applicationPreview = ApplicationPreview::query()->find($applicationPreviewId);
+ $applicationPreview = ApplicationPreview::find($applicationPreviewId);
if ($applicationPreview) {
$applicationPreview->status = 'exited';
$applicationPreview->save();
@@ -257,7 +257,7 @@ private function updateProxyStatus()
StartProxy::run($this->server, false);
$this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server));
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
}
} else {
$connectProxyToDockerNetworks = connectProxyToNetworks($this->server);
@@ -327,7 +327,7 @@ private function updateNotFoundServiceStatus()
$notFoundServiceDatabaseIds = $this->allServiceDatabaseIds->diff($this->foundServiceDatabaseIds);
if ($notFoundServiceApplicationIds->isNotEmpty()) {
$notFoundServiceApplicationIds->each(function ($serviceApplicationId) {
- $application = ServiceApplication::query()->find($serviceApplicationId);
+ $application = ServiceApplication::find($serviceApplicationId);
if ($application) {
$application->status = 'exited';
$application->save();
@@ -336,7 +336,7 @@ private function updateNotFoundServiceStatus()
}
if ($notFoundServiceDatabaseIds->isNotEmpty()) {
$notFoundServiceDatabaseIds->each(function ($serviceDatabaseId) {
- $database = ServiceDatabase::query()->find($serviceDatabaseId);
+ $database = ServiceDatabase::find($serviceDatabaseId);
if ($database) {
$database->status = 'exited';
$database->save();
diff --git a/app/Jobs/ScheduledTaskJob.php b/app/Jobs/ScheduledTaskJob.php
index de4b0757c5..90a10f3e99 100644
--- a/app/Jobs/ScheduledTaskJob.php
+++ b/app/Jobs/ScheduledTaskJob.php
@@ -11,14 +11,11 @@
use App\Models\Team;
use App\Notifications\ScheduledTask\TaskFailed;
use App\Notifications\ScheduledTask\TaskSuccess;
-use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use RuntimeException;
-use Throwable;
class ScheduledTaskJob implements ShouldQueue
{
@@ -52,9 +49,9 @@ public function __construct($task)
} elseif ($application = $task->application()->first()) {
$this->resource = $application;
} else {
- throw new RuntimeException('ScheduledTaskJob failed: No resource found.');
+ throw new \RuntimeException('ScheduledTaskJob failed: No resource found.');
}
- $this->team = Team::query()->findOrFail($task->team_id);
+ $this->team = Team::findOrFail($task->team_id);
$this->server_timezone = $this->getServerTimezone();
}
@@ -62,15 +59,17 @@ private function getServerTimezone(): string
{
if ($this->resource instanceof Application) {
return $this->resource->destination->server->settings->server_timezone;
+ } elseif ($this->resource instanceof Service) {
+ return $this->resource->server->settings->server_timezone;
}
- return $this->resource->server->settings->server_timezone;
+ return 'UTC';
}
public function handle(): void
{
try {
- $this->task_log = ScheduledTaskExecution::query()->create([
+ $this->task_log = ScheduledTaskExecution::create([
'scheduled_task_id' => $this->task->id,
]);
@@ -96,17 +95,17 @@ public function handle(): void
});
}
if (count($this->containers) == 0) {
- throw new Exception('ScheduledTaskJob failed: No containers running.');
+ throw new \Exception('ScheduledTaskJob failed: No containers running.');
}
if (count($this->containers) > 1 && empty($this->task->container)) {
- throw new Exception('ScheduledTaskJob failed: More than one container exists but no container name was provided.');
+ throw new \Exception('ScheduledTaskJob failed: More than one container exists but no container name was provided.');
}
- foreach ($this->containers as $container) {
- if (count($this->containers) == 1 || str_starts_with($container, $this->task->container.'-'.$this->resource->uuid)) {
+ foreach ($this->containers as $containerName) {
+ if (count($this->containers) == 1 || str_starts_with($containerName, $this->task->container.'-'.$this->resource->uuid)) {
$cmd = "sh -c '".str_replace("'", "'\''", $this->task->command)."'";
- $exec = "docker exec {$container} {$cmd}";
+ $exec = "docker exec {$containerName} {$cmd}";
$this->task_output = instant_remote_process([$exec], $this->server, true);
$this->task_log->update([
'status' => 'success',
@@ -120,9 +119,9 @@ public function handle(): void
}
// No valid container was found.
- throw new Exception('ScheduledTaskJob failed: No valid container was found. Is the container name correct?');
- } catch (Throwable $e) {
- if ($this->task_log instanceof ScheduledTaskExecution) {
+ throw new \Exception('ScheduledTaskJob failed: No valid container was found. Is the container name correct?');
+ } catch (\Throwable $e) {
+ if ($this->task_log) {
$this->task_log->update([
'status' => 'failed',
'message' => $this->task_output ?? $e->getMessage(),
diff --git a/app/Jobs/SendMessageToDiscordJob.php b/app/Jobs/SendMessageToDiscordJob.php
index 4545cfdfbf..99aeaeea27 100644
--- a/app/Jobs/SendMessageToDiscordJob.php
+++ b/app/Jobs/SendMessageToDiscordJob.php
@@ -30,7 +30,7 @@ class SendMessageToDiscordJob implements ShouldBeEncrypted, ShouldQueue
public int $maxExceptions = 5;
public function __construct(
- public DiscordMessage $discordMessage,
+ public DiscordMessage $message,
public string $webhookUrl
) {
$this->onQueue('high');
@@ -41,6 +41,6 @@ public function __construct(
*/
public function handle(): void
{
- Http::post($this->webhookUrl, $this->discordMessage->toPayload());
+ Http::post($this->webhookUrl, $this->message->toPayload());
}
}
diff --git a/app/Jobs/SendMessageToPushoverJob.php b/app/Jobs/SendMessageToPushoverJob.php
index fa1acbeb53..e2a94cdaa0 100644
--- a/app/Jobs/SendMessageToPushoverJob.php
+++ b/app/Jobs/SendMessageToPushoverJob.php
@@ -10,7 +10,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
-use RuntimeException;
class SendMessageToPushoverJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -31,7 +30,7 @@ class SendMessageToPushoverJob implements ShouldBeEncrypted, ShouldQueue
public int $maxExceptions = 5;
public function __construct(
- public PushoverMessage $pushoverMessage,
+ public PushoverMessage $message,
public string $token,
public string $user,
) {
@@ -43,9 +42,9 @@ public function __construct(
*/
public function handle(): void
{
- $response = Http::post('https://api.pushover.net/1/messages.json', $this->pushoverMessage->toPayload($this->token, $this->user));
+ $response = Http::post('https://api.pushover.net/1/messages.json', $this->message->toPayload($this->token, $this->user));
if ($response->failed()) {
- throw new RuntimeException('Pushover notification failed with '.$response->status().' status code.'.$response->body());
+ throw new \RuntimeException('Pushover notification failed with '.$response->status().' status code.'.$response->body());
}
}
}
diff --git a/app/Jobs/SendMessageToSlackJob.php b/app/Jobs/SendMessageToSlackJob.php
index c27f45ad4d..470002d233 100644
--- a/app/Jobs/SendMessageToSlackJob.php
+++ b/app/Jobs/SendMessageToSlackJob.php
@@ -15,7 +15,7 @@ class SendMessageToSlackJob implements ShouldQueue
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
- private SlackMessage $slackMessage,
+ private SlackMessage $message,
private string $webhookUrl
) {
$this->onQueue('high');
@@ -35,20 +35,20 @@ public function handle(): void
],
'attachments' => [
[
- 'color' => $this->slackMessage->color,
+ 'color' => $this->message->color,
'blocks' => [
[
'type' => 'header',
'text' => [
'type' => 'plain_text',
- 'text' => $this->slackMessage->title,
+ 'text' => $this->message->title,
],
],
[
'type' => 'section',
'text' => [
'type' => 'mrkdwn',
- 'text' => $this->slackMessage->description,
+ 'text' => $this->message->description,
],
],
],
diff --git a/app/Jobs/SendMessageToTelegramJob.php b/app/Jobs/SendMessageToTelegramJob.php
index 734e47c885..6b0a64ae39 100644
--- a/app/Jobs/SendMessageToTelegramJob.php
+++ b/app/Jobs/SendMessageToTelegramJob.php
@@ -10,7 +10,6 @@
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
-use RuntimeException;
class SendMessageToTelegramJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -45,16 +44,18 @@ public function handle(): void
{
$url = 'https://api.telegram.org/bot'.$this->token.'/sendMessage';
$inlineButtons = [];
- foreach ($this->buttons as $button) {
- $buttonUrl = data_get($button, 'url');
- $text = data_get($button, 'text', 'Click here');
- if ($buttonUrl && Str::contains($buttonUrl, 'http://localhost')) {
- $buttonUrl = str_replace('http://localhost', config('app.url'), $buttonUrl);
+ if (! empty($this->buttons)) {
+ foreach ($this->buttons as $button) {
+ $buttonUrl = data_get($button, 'url');
+ $text = data_get($button, 'text', 'Click here');
+ if ($buttonUrl && Str::contains($buttonUrl, 'http://localhost')) {
+ $buttonUrl = str_replace('http://localhost', config('app.url'), $buttonUrl);
+ }
+ $inlineButtons[] = [
+ 'text' => $text,
+ 'url' => $buttonUrl,
+ ];
}
- $inlineButtons[] = [
- 'text' => $text,
- 'url' => $buttonUrl,
- ];
}
$payload = [
// 'parse_mode' => 'markdown',
@@ -71,7 +72,7 @@ public function handle(): void
}
$response = Http::post($url, $payload);
if ($response->failed()) {
- throw new RuntimeException('Telegram notification failed with '.$response->status().' status code.'.$response->body());
+ throw new \RuntimeException('Telegram notification failed with '.$response->status().' status code.'.$response->body());
}
}
}
diff --git a/app/Jobs/ServerCheckJob.php b/app/Jobs/ServerCheckJob.php
index 847db6bb8a..9818d5c6a0 100644
--- a/app/Jobs/ServerCheckJob.php
+++ b/app/Jobs/ServerCheckJob.php
@@ -15,7 +15,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Queue\SerializesModels;
-use Throwable;
class ServerCheckJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -61,9 +60,9 @@ public function handle()
$foundProxyContainer = $this->containers->filter(function ($value, $key) {
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === 'coolify-proxy_traefik';
+ } else {
+ return data_get($value, 'Name') === '/coolify-proxy';
}
-
- return data_get($value, 'Name') === '/coolify-proxy';
})->first();
if (! $foundProxyContainer) {
try {
@@ -72,7 +71,7 @@ public function handle()
StartProxy::run($this->server, false);
$this->server->team?->notify(new ContainerRestarted('coolify-proxy', $this->server));
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
}
} else {
$this->server->proxy->status = data_get($foundProxyContainer, 'State.Status');
@@ -82,11 +81,9 @@ public function handle()
}
}
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
-
- return null;
}
private function checkLogDrainContainer()
diff --git a/app/Jobs/ServerCheckNewJob.php b/app/Jobs/ServerCheckNewJob.php
index 21114f035e..3e8e60a31d 100644
--- a/app/Jobs/ServerCheckNewJob.php
+++ b/app/Jobs/ServerCheckNewJob.php
@@ -11,7 +11,6 @@
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Throwable;
class ServerCheckNewJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -28,10 +27,8 @@ public function handle()
try {
ServerCheck::run($this->server);
ResourcesCheck::dispatch($this->server);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
-
- return null;
}
}
diff --git a/app/Jobs/ServerCleanupMux.php b/app/Jobs/ServerCleanupMux.php
index 8b00e62470..b793c3eca6 100644
--- a/app/Jobs/ServerCleanupMux.php
+++ b/app/Jobs/ServerCleanupMux.php
@@ -10,7 +10,6 @@
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Throwable;
class ServerCleanupMux implements ShouldBeEncrypted, ShouldQueue
{
@@ -34,10 +33,8 @@ public function handle()
return 'Server is not reachable or not ready.';
}
SshMultiplexingHelper::removeMuxFile($this->server);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
-
- return null;
}
}
diff --git a/app/Jobs/ServerLimitCheckJob.php b/app/Jobs/ServerLimitCheckJob.php
index ecfbf9a84f..aa82c6dade 100644
--- a/app/Jobs/ServerLimitCheckJob.php
+++ b/app/Jobs/ServerLimitCheckJob.php
@@ -11,7 +11,6 @@
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Throwable;
class ServerLimitCheckJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -47,12 +46,10 @@ public function handle()
}
});
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
send_internal_notification('ServerLimitCheckJob failed with: '.$e->getMessage());
return handleError($e);
}
-
- return null;
}
}
diff --git a/app/Jobs/ServerStorageCheckJob.php b/app/Jobs/ServerStorageCheckJob.php
index 499027f1ea..9a8d86be1e 100644
--- a/app/Jobs/ServerStorageCheckJob.php
+++ b/app/Jobs/ServerStorageCheckJob.php
@@ -11,7 +11,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\RateLimiter;
-use Throwable;
class ServerStorageCheckJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -59,10 +58,8 @@ function () use ($team, $serverDiskUsageNotificationThreshold) {
} else {
RateLimiter::hit('high-disk-usage:'.$this->server->id, 600);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
-
- return null;
}
}
diff --git a/app/Jobs/StripeProcessJob.php b/app/Jobs/StripeProcessJob.php
index 9fabc1ecfb..d61c738f4a 100644
--- a/app/Jobs/StripeProcessJob.php
+++ b/app/Jobs/StripeProcessJob.php
@@ -4,12 +4,9 @@
use App\Models\Subscription;
use App\Models\Team;
-use Exception;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Str;
-use RuntimeException;
-use Stripe\StripeClient;
class StripeProcessJob implements ShouldQueue
{
@@ -36,26 +33,26 @@ public function handle(): void
$data = data_get($this->event, 'data.object');
switch ($type) {
case 'radar.early_fraud_warning.created':
- $stripeClient = new StripeClient(config('subscription.stripe_api_key'));
+ $stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key'));
$id = data_get($data, 'id');
$charge = data_get($data, 'charge');
if ($charge) {
- $stripeClient->refunds->create(['charge' => $charge]);
+ $stripe->refunds->create(['charge' => $charge]);
}
$pi = data_get($data, 'payment_intent');
- $piData = $stripeClient->paymentIntents->retrieve($pi, []);
+ $piData = $stripe->paymentIntents->retrieve($pi, []);
$customerId = data_get($piData, 'customer');
- $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();
+ $subscription = Subscription::where('stripe_customer_id', $customerId)->first();
if ($subscription) {
$subscriptionId = data_get($subscription, 'stripe_subscription_id');
- $stripeClient->subscriptions->cancel($subscriptionId, []);
+ $stripe->subscriptions->cancel($subscriptionId, []);
$subscription->update([
'stripe_invoice_paid' => false,
]);
send_internal_notification("Early fraud warning created Refunded, subscription canceled. Charge: {$charge}, id: {$id}, pi: {$pi}");
} else {
send_internal_notification("Early fraud warning: subscription not found. Charge: {$charge}, id: {$id}, pi: {$pi}");
- throw new RuntimeException("Early fraud warning: subscription not found. Charge: {$charge}, id: {$id}, pi: {$pi}");
+ throw new \RuntimeException("Early fraud warning: subscription not found. Charge: {$charge}, id: {$id}, pi: {$pi}");
}
break;
case 'checkout.session.completed':
@@ -68,13 +65,13 @@ public function handle(): void
$teamId = Str::after($clientReferenceId, ':');
$subscriptionId = data_get($data, 'subscription');
$customerId = data_get($data, 'customer');
- $team = Team::query()->find($teamId);
+ $team = Team::find($teamId);
$found = $team->members->where('id', $userId)->first();
if (! $found->isAdmin()) {
send_internal_notification("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}.");
- throw new RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}.");
+ throw new \RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}, subscriptionid: {$subscriptionId}.");
}
- $subscription = Subscription::query()->where('team_id', $teamId)->first();
+ $subscription = Subscription::where('team_id', $teamId)->first();
if ($subscription) {
send_internal_notification('Old subscription activated for team: '.$teamId);
$subscription->update([
@@ -84,7 +81,7 @@ public function handle(): void
]);
} else {
send_internal_notification('New subscription for team: '.$teamId);
- Subscription::query()->create([
+ Subscription::create([
'team_id' => $teamId,
'stripe_subscription_id' => $subscriptionId,
'stripe_customer_id' => $customerId,
@@ -99,26 +96,26 @@ public function handle(): void
send_internal_notification('Subscription excluded.');
break;
}
- $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();
+ $subscription = Subscription::where('stripe_customer_id', $customerId)->first();
if ($subscription) {
$subscription->update([
'stripe_invoice_paid' => true,
]);
} else {
- throw new RuntimeException("No subscription found for customer: {$customerId}");
+ throw new \RuntimeException("No subscription found for customer: {$customerId}");
}
break;
case 'invoice.payment_failed':
$customerId = data_get($data, 'customer');
- $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();
+ $subscription = Subscription::where('stripe_customer_id', $customerId)->first();
if (! $subscription) {
send_internal_notification('invoice.payment_failed failed but no subscription found in Coolify for customer: '.$customerId);
- throw new RuntimeException("No subscription found for customer: {$customerId}");
+ throw new \RuntimeException("No subscription found for customer: {$customerId}");
}
$team = data_get($subscription, 'team');
if (! $team) {
send_internal_notification('invoice.payment_failed failed but no team found in Coolify for customer: '.$customerId);
- throw new RuntimeException("No team found in Coolify for customer: {$customerId}");
+ throw new \RuntimeException("No team found in Coolify for customer: {$customerId}");
}
if (! $subscription->stripe_invoice_paid) {
SubscriptionInvoiceFailedJob::dispatch($team);
@@ -129,10 +126,10 @@ public function handle(): void
break;
case 'payment_intent.payment_failed':
$customerId = data_get($data, 'customer');
- $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();
+ $subscription = Subscription::where('stripe_customer_id', $customerId)->first();
if (! $subscription) {
send_internal_notification('payment_intent.payment_failed, no subscription found in Coolify for customer: '.$customerId);
- throw new RuntimeException("No subscription found in Coolify for customer: {$customerId}");
+ throw new \RuntimeException("No subscription found in Coolify for customer: {$customerId}");
}
if ($subscription->stripe_invoice_paid) {
send_internal_notification('payment_intent.payment_failed but invoice is active for customer: '.$customerId);
@@ -147,48 +144,49 @@ public function handle(): void
$teamId = data_get($data, 'metadata.team_id');
$userId = data_get($data, 'metadata.user_id');
if (! $teamId || ! $userId) {
- $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();
+ $subscription = Subscription::where('stripe_customer_id', $customerId)->first();
if ($subscription) {
- throw new RuntimeException("Subscription already exists for customer: {$customerId}");
+ throw new \RuntimeException("Subscription already exists for customer: {$customerId}");
}
- throw new RuntimeException('No team id or user id found');
+ throw new \RuntimeException('No team id or user id found');
}
- $team = Team::query()->find($teamId);
+ $team = Team::find($teamId);
$found = $team->members->where('id', $userId)->first();
if (! $found->isAdmin()) {
send_internal_notification("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}.");
- throw new RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}.");
+ throw new \RuntimeException("User {$userId} is not an admin or owner of team {$team->id}, customerid: {$customerId}.");
}
- $subscription = Subscription::query()->where('team_id', $teamId)->first();
+ $subscription = Subscription::where('team_id', $teamId)->first();
if ($subscription) {
send_internal_notification("Subscription already exists for team: {$teamId}");
- throw new RuntimeException("Subscription already exists for team: {$teamId}");
+ throw new \RuntimeException("Subscription already exists for team: {$teamId}");
+ } else {
+ Subscription::create([
+ 'team_id' => $teamId,
+ 'stripe_subscription_id' => $subscriptionId,
+ 'stripe_customer_id' => $customerId,
+ 'stripe_invoice_paid' => false,
+ ]);
}
- Subscription::query()->create([
- 'team_id' => $teamId,
- 'stripe_subscription_id' => $subscriptionId,
- 'stripe_customer_id' => $customerId,
- 'stripe_invoice_paid' => false,
- ]);
case 'customer.subscription.updated':
$teamId = data_get($data, 'metadata.team_id');
$userId = data_get($data, 'metadata.user_id');
$customerId = data_get($data, 'customer');
$status = data_get($data, 'status');
- $subscriptionId = data_get($data, 'items.data.0.subscription', data_get($data, 'id'));
- $planId = data_get($data, 'items.data.0.plan.id', data_get($data, 'plan.id'));
+ $subscriptionId = data_get($data, 'items.data.0.subscription') ?? data_get($data, 'id');
+ $planId = data_get($data, 'items.data.0.plan.id') ?? data_get($data, 'plan.id');
if (Str::contains($excludedPlans, $planId)) {
send_internal_notification('Subscription excluded.');
break;
}
- $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->first();
+ $subscription = Subscription::where('stripe_customer_id', $customerId)->first();
if (! $subscription) {
if ($status === 'incomplete_expired') {
send_internal_notification('Subscription incomplete expired');
- throw new RuntimeException('Subscription incomplete expired');
+ throw new \RuntimeException('Subscription incomplete expired');
}
if ($teamId) {
- $subscription = Subscription::query()->create([
+ $subscription = Subscription::create([
'team_id' => $teamId,
'stripe_subscription_id' => $subscriptionId,
'stripe_customer_id' => $customerId,
@@ -196,7 +194,7 @@ public function handle(): void
]);
} else {
send_internal_notification('No subscription and team id found');
- throw new RuntimeException('No subscription and team id found');
+ throw new \RuntimeException('No subscription and team id found');
}
}
$cancelAtPeriodEnd = data_get($data, 'cancel_at_period_end');
@@ -219,15 +217,19 @@ public function handle(): void
'stripe_plan_id' => $planId,
'stripe_cancel_at_period_end' => $cancelAtPeriodEnd,
]);
- if (($status === 'paused' || $status === 'incomplete_expired') && $subscription->stripe_subscription_id === $subscriptionId) {
- $subscription->update([
- 'stripe_invoice_paid' => false,
- ]);
+ if ($status === 'paused' || $status === 'incomplete_expired') {
+ if ($subscription->stripe_subscription_id === $subscriptionId) {
+ $subscription->update([
+ 'stripe_invoice_paid' => false,
+ ]);
+ }
}
- if ($status === 'active' && $subscription->stripe_subscription_id === $subscriptionId) {
- $subscription->update([
- 'stripe_invoice_paid' => true,
- ]);
+ if ($status === 'active') {
+ if ($subscription->stripe_subscription_id === $subscriptionId) {
+ $subscription->update([
+ 'stripe_invoice_paid' => true,
+ ]);
+ }
}
if ($feedback) {
$reason = "Cancellation feedback for {$customerId}: '".$feedback."'";
@@ -240,24 +242,24 @@ public function handle(): void
case 'customer.subscription.deleted':
$customerId = data_get($data, 'customer');
$subscriptionId = data_get($data, 'id');
- $subscription = Subscription::query()->where('stripe_customer_id', $customerId)->where('stripe_subscription_id', $subscriptionId)->first();
+ $subscription = Subscription::where('stripe_customer_id', $customerId)->where('stripe_subscription_id', $subscriptionId)->first();
if ($subscription) {
$team = data_get($subscription, 'team');
if ($team) {
$team->subscriptionEnded();
} else {
send_internal_notification('Subscription deleted but no team found in Coolify for customer: '.$customerId);
- throw new RuntimeException("No team found in Coolify for customer: {$customerId}");
+ throw new \RuntimeException("No team found in Coolify for customer: {$customerId}");
}
} else {
send_internal_notification('Subscription deleted but no subscription found in Coolify for customer: '.$customerId);
- throw new RuntimeException("No subscription found in Coolify for customer: {$customerId}");
+ throw new \RuntimeException("No subscription found in Coolify for customer: {$customerId}");
}
break;
default:
- throw new RuntimeException("Unhandled event type: {$type}");
+ throw new \RuntimeException("Unhandled event type: {$type}");
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
send_internal_notification('StripeProcessJob error: '.$e->getMessage());
}
}
diff --git a/app/Jobs/SubscriptionInvoiceFailedJob.php b/app/Jobs/SubscriptionInvoiceFailedJob.php
index a425928270..dc511f4452 100755
--- a/app/Jobs/SubscriptionInvoiceFailedJob.php
+++ b/app/Jobs/SubscriptionInvoiceFailedJob.php
@@ -10,7 +10,6 @@
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
-use Throwable;
class SubscriptionInvoiceFailedJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -25,17 +24,17 @@ public function handle()
{
try {
$session = getStripeCustomerPortalSession($this->team);
- $mailMessage = new MailMessage;
- $mailMessage->view('emails.subscription-invoice-failed', [
+ $mail = new MailMessage;
+ $mail->view('emails.subscription-invoice-failed', [
'stripeCustomerPortal' => $session->url,
]);
- $mailMessage->subject('Your last payment was failed for Coolify Cloud.');
- $this->team->members()->each(function ($member) use ($mailMessage) {
+ $mail->subject('Your last payment was failed for Coolify Cloud.');
+ $this->team->members()->each(function ($member) use ($mail) {
if ($member->isAdmin()) {
- send_user_an_email($mailMessage, $member->email);
+ send_user_an_email($mail, $member->email);
}
});
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
send_internal_notification('SubscriptionInvoiceFailedJob failed with: '.$e->getMessage());
throw $e;
}
diff --git a/app/Jobs/UpdateCoolifyJob.php b/app/Jobs/UpdateCoolifyJob.php
index 958039e9e2..f0e43cbc0a 100644
--- a/app/Jobs/UpdateCoolifyJob.php
+++ b/app/Jobs/UpdateCoolifyJob.php
@@ -11,7 +11,6 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
-use Throwable;
class UpdateCoolifyJob implements ShouldBeEncrypted, ShouldQueue
{
@@ -35,7 +34,7 @@ public function handle(): void
return;
}
- $server = Server::query()->findOrFail(0);
+ $server = Server::findOrFail(0);
if (! $server) {
Log::error('Server not found. Cannot proceed with update.');
@@ -47,7 +46,7 @@ public function handle(): void
$settings->update(['new_version_available' => false]);
Log::info('Coolify update completed successfully.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
Log::error('UpdateCoolifyJob failed: '.$e->getMessage());
// Consider implementing a notification to administrators
}
diff --git a/app/Listeners/MaintenanceModeDisabledNotification.php b/app/Listeners/MaintenanceModeDisabledNotification.php
index 085dc569fe..6c3ab83d8f 100644
--- a/app/Listeners/MaintenanceModeDisabledNotification.php
+++ b/app/Listeners/MaintenanceModeDisabledNotification.php
@@ -6,11 +6,12 @@
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
-use Throwable;
class MaintenanceModeDisabledNotification
{
- public function handle(EventsMaintenanceModeDisabled $eventsMaintenanceModeDisabled): void
+ public function __construct() {}
+
+ public function handle(EventsMaintenanceModeDisabled $event): void
{
$files = Storage::disk('webhooks-during-maintenance')->files();
$files = collect($files);
@@ -38,7 +39,7 @@ public function handle(EventsMaintenanceModeDisabled $eventsMaintenanceModeDisab
try {
$instance = new $class;
$instance->$method($request);
- } catch (Throwable $th) {
+ } catch (\Throwable $th) {
} finally {
Storage::disk('webhooks-during-maintenance')->delete($file);
}
diff --git a/app/Listeners/MaintenanceModeEnabledNotification.php b/app/Listeners/MaintenanceModeEnabledNotification.php
index 37170a0341..5aab248ea8 100644
--- a/app/Listeners/MaintenanceModeEnabledNotification.php
+++ b/app/Listeners/MaintenanceModeEnabledNotification.php
@@ -17,5 +17,5 @@ public function __construct()
/**
* Handle the event.
*/
- public function handle(EventsMaintenanceModeEnabled $eventsMaintenanceModeEnabled): void {}
+ public function handle(EventsMaintenanceModeEnabled $event): void {}
}
diff --git a/app/Listeners/ProxyStartedNotification.php b/app/Listeners/ProxyStartedNotification.php
index ffd6858cfb..9045b1e5c1 100644
--- a/app/Listeners/ProxyStartedNotification.php
+++ b/app/Listeners/ProxyStartedNotification.php
@@ -9,9 +9,11 @@ class ProxyStartedNotification
{
public Server $server;
- public function handle(ProxyStarted $proxyStarted): void
+ public function __construct() {}
+
+ public function handle(ProxyStarted $event): void
{
- $this->server = data_get($proxyStarted, 'data');
+ $this->server = data_get($event, 'data');
$this->server->setupDefaultRedirect();
$this->server->setupDynamicProxyConfiguration();
$this->server->proxy->force_stop = false;
diff --git a/app/Livewire/ActivityMonitor.php b/app/Livewire/ActivityMonitor.php
index 18e1a565ea..2e36f34ee7 100644
--- a/app/Livewire/ActivityMonitor.php
+++ b/app/Livewire/ActivityMonitor.php
@@ -36,7 +36,7 @@ public function newMonitorActivity($activityId, $eventToDispatch = 'activityFini
public function hydrateActivity()
{
- $this->activity = Activity::query()->find($this->activityId);
+ $this->activity = Activity::find($this->activityId);
}
public function polling()
@@ -51,20 +51,22 @@ public function polling()
// // $this->setStatus(ProcessStatus::ERROR);
// }
$this->isPollingActive = false;
- if ($exit_code === 0 && $this->eventToDispatch !== null) {
- if (str($this->eventToDispatch)->startsWith('App\\Events\\')) {
- $causer_id = data_get($this->activity, 'causer_id');
- $user = User::query()->find($causer_id);
- if ($user) {
- foreach ($user->teams as $team) {
- $teamId = $team->id;
- $this->eventToDispatch::dispatch($teamId);
+ if ($exit_code === 0) {
+ if ($this->eventToDispatch !== null) {
+ if (str($this->eventToDispatch)->startsWith('App\\Events\\')) {
+ $causer_id = data_get($this->activity, 'causer_id');
+ $user = User::find($causer_id);
+ if ($user) {
+ foreach ($user->teams as $team) {
+ $teamId = $team->id;
+ $this->eventToDispatch::dispatch($teamId);
+ }
}
- }
- return;
+ return;
+ }
+ $this->dispatch($this->eventToDispatch);
}
- $this->dispatch($this->eventToDispatch);
}
}
}
diff --git a/app/Livewire/Admin/Index.php b/app/Livewire/Admin/Index.php
index 88fc2aa9dd..b5f6d29294 100644
--- a/app/Livewire/Admin/Index.php
+++ b/app/Livewire/Admin/Index.php
@@ -6,6 +6,7 @@
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Cache;
use Livewire\Component;
class Index extends Component
@@ -27,29 +28,25 @@ public function mount()
return redirect()->route('dashboard');
}
$this->getSubscribers();
-
- return null;
}
public function back()
{
if (session('impersonating')) {
session()->forget('impersonating');
- $user = User::query()->find(0);
+ $user = User::find(0);
$team_to_switch_to = $user->teams->first();
Auth::login($user);
refreshSession($team_to_switch_to);
return redirect(request()->header('Referer'));
}
-
- return null;
}
public function submitSearch()
{
if ($this->search !== '') {
- $this->foundUsers = User::query()->where(function ($query) {
+ $this->foundUsers = User::where(function ($query) {
$query->where('name', 'like', "%{$this->search}%")
->orWhere('email', 'like', "%{$this->search}%");
})->get();
@@ -58,8 +55,8 @@ public function submitSearch()
public function getSubscribers()
{
- $this->inactiveSubscribers = Team::query()->whereRelation('subscription', 'stripe_invoice_paid', false)->count();
- $this->activeSubscribers = Team::query()->whereRelation('subscription', 'stripe_invoice_paid', true)->count();
+ $this->inactiveSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', false)->count();
+ $this->activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->count();
}
public function switchUser(int $user_id)
@@ -68,7 +65,7 @@ public function switchUser(int $user_id)
return redirect()->route('dashboard');
}
session(['impersonating' => true]);
- $user = User::query()->find($user_id);
+ $user = User::find($user_id);
$team_to_switch_to = $user->teams->first();
// Cache::forget("team:{$user->id}");
Auth::login($user);
diff --git a/app/Livewire/Boarding/Index.php b/app/Livewire/Boarding/Index.php
index 18e8cc85b6..15eabfec57 100644
--- a/app/Livewire/Boarding/Index.php
+++ b/app/Livewire/Boarding/Index.php
@@ -7,10 +7,8 @@
use App\Models\Project;
use App\Models\Server;
use App\Models\Team;
-use Exception;
use Illuminate\Support\Collection;
use Livewire\Component;
-use Throwable;
use Visus\Cuid2\Cuid2;
class Index extends Component
@@ -92,8 +90,6 @@ public function mount()
$this->remoteServerDescription = 'Created by Coolify';
$this->remoteServerHost = 'coolify-testing-host';
}
-
- return null;
}
public function explanation()
@@ -102,8 +98,6 @@ public function explanation()
return $this->setServerType('remote');
}
$this->currentState = 'select-server-type';
-
- return null;
}
public function restartBoarding()
@@ -113,7 +107,7 @@ public function restartBoarding()
public function skipBoarding()
{
- Team::query()->find(currentTeam()->id)->update([
+ Team::find(currentTeam()->id)->update([
'show_boarding' => false,
]);
refreshSession();
@@ -125,16 +119,15 @@ public function setServerType(string $type)
{
$this->selectedServerType = $type;
if ($this->selectedServerType === 'localhost') {
- $this->createdServer = Server::query()->find(0);
+ $this->createdServer = Server::find(0);
$this->selectedExistingServer = 0;
if (! $this->createdServer) {
return $this->dispatch('error', 'Localhost server is not found. Something went wrong during installation. Please try to reinstall or contact support.');
}
$this->serverPublicKey = $this->createdServer->privateKey->getPublicKey();
- return $this->validateServer();
- }
- if ($this->selectedServerType === 'remote') {
+ return $this->validateServer('localhost');
+ } elseif ($this->selectedServerType === 'remote') {
if (isDev()) {
$this->privateKeys = PrivateKey::ownedByCurrentTeam(['name'])->get();
} else {
@@ -149,17 +142,15 @@ public function setServerType(string $type)
$this->updateServerDetails();
$this->currentState = 'select-existing-server';
- return null;
+ return;
}
$this->currentState = 'private-key';
}
-
- return null;
}
public function selectExistingServer()
{
- $this->createdServer = Server::query()->find($this->selectedExistingServer);
+ $this->createdServer = Server::find($this->selectedExistingServer);
if (! $this->createdServer) {
$this->dispatch('error', 'Server is not found.');
$this->currentState = 'private-key';
@@ -174,7 +165,7 @@ public function selectExistingServer()
private function updateServerDetails()
{
- if ($this->createdServer instanceof Server) {
+ if ($this->createdServer) {
$this->remoteServerPort = $this->createdServer->port;
$this->remoteServerUser = $this->createdServer->user;
}
@@ -193,7 +184,7 @@ public function selectExistingPrivateKey()
return;
}
- $this->createdPrivateKey = PrivateKey::query()->where('team_id', currentTeam()->id)->where('id', $this->selectedExistingPrivateKey)->first();
+ $this->createdPrivateKey = PrivateKey::where('team_id', currentTeam()->id)->where('id', $this->selectedExistingPrivateKey)->first();
$this->privateKey = $this->createdPrivateKey->private_key;
$this->currentState = 'create-server';
}
@@ -232,7 +223,7 @@ public function savePrivateKey()
$this->createdPrivateKey = $privateKey;
$this->currentState = 'create-server';
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->addError('privateKey', 'Failed to save private key: '.$e->getMessage());
}
}
@@ -251,7 +242,7 @@ public function saveServer()
if ($foundServer) {
return $this->dispatch('error', 'IP address is already in use by another team.');
}
- $this->createdServer = Server::query()->create([
+ $this->createdServer = Server::create([
'name' => $this->remoteServerName,
'ip' => $this->remoteServerHost,
'port' => $this->remoteServerPort,
@@ -265,8 +256,6 @@ public function saveServer()
$this->createdServer->settings->save();
$this->selectedExistingServer = $this->createdServer->id;
$this->currentState = 'validate-server';
-
- return null;
}
public function installServer()
@@ -286,7 +275,7 @@ public function validateServer()
'is_reachable' => true,
]);
$this->serverReachable = true;
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->serverReachable = false;
$this->createdServer->settings()->update([
'is_reachable' => false,
@@ -300,21 +289,19 @@ public function validateServer()
$dockerVersion = checkMinimumDockerEngineVersion($dockerVersion);
if (is_null($dockerVersion)) {
$this->currentState = 'validate-server';
- throw new Exception('Docker not found or old version is installed.');
+ throw new \Exception('Docker not found or old version is installed.');
}
$this->createdServer->settings()->update([
'is_usable' => true,
]);
$this->getProxyType();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->createdServer->settings()->update([
'is_usable' => false,
]);
return handleError(error: $e, livewire: $this);
}
-
- return null;
}
public function selectProxy(?string $proxyType = null)
@@ -326,13 +313,11 @@ public function selectProxy(?string $proxyType = null)
$this->createdServer->proxy->status = 'exited';
$this->createdServer->save();
$this->getProjects();
-
- return null;
}
public function getProjects()
{
- $this->projects = Project::ownedByCurrentTeam()->get();
+ $this->projects = Project::ownedByCurrentTeam(['name'])->get();
if ($this->projects->count() > 0) {
$this->selectedProject = $this->projects->first()->id;
}
@@ -341,13 +326,13 @@ public function getProjects()
public function selectExistingProject()
{
- $this->createdProject = Project::query()->find($this->selectedProject);
+ $this->createdProject = Project::find($this->selectedProject);
$this->currentState = 'create-resource';
}
public function createNewProject()
{
- $this->createdProject = Project::query()->create([
+ $this->createdProject = Project::create([
'name' => 'My first project',
'team_id' => currentTeam()->id,
'uuid' => (string) new Cuid2,
diff --git a/app/Livewire/Dashboard.php b/app/Livewire/Dashboard.php
index 7c876f1f5c..c3cb797bff 100644
--- a/app/Livewire/Dashboard.php
+++ b/app/Livewire/Dashboard.php
@@ -38,7 +38,7 @@ public function cleanupQueue()
public function loadDeployments()
{
- $this->deploymentsPerServer = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->whereIn('server_id', $this->servers->pluck('id'))->get([
+ $this->deploymentsPerServer = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('server_id', $this->servers->pluck('id'))->get([
'id',
'application_id',
'application_name',
@@ -52,7 +52,7 @@ public function loadDeployments()
public function navigateToProject($projectUuid)
{
- $project = Project::query()->where('uuid', $projectUuid)->first();
+ $project = Project::where('uuid', $projectUuid)->first();
if ($project && $project->environments->count() === 1) {
return Redirect::route('project.resource.index', [
diff --git a/app/Livewire/Destination/New/Docker.php b/app/Livewire/Destination/New/Docker.php
index ecbb063eb7..337f1d0673 100644
--- a/app/Livewire/Destination/New/Docker.php
+++ b/app/Livewire/Destination/New/Docker.php
@@ -5,11 +5,9 @@
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
-use Exception;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
use Visus\Cuid2\Cuid2;
class Docker extends Component
@@ -65,31 +63,31 @@ public function submit()
if ($this->isSwarm) {
$found = $this->selectedServer->swarmDockers()->where('network', $this->network)->first();
if ($found) {
- throw new Exception('Network already added to this server.');
+ throw new \Exception('Network already added to this server.');
+ } else {
+ $docker = SwarmDocker::create([
+ 'name' => $this->name,
+ 'network' => $this->network,
+ 'server_id' => $this->selectedServer->id,
+ ]);
}
- $docker = SwarmDocker::query()->create([
- 'name' => $this->name,
- 'network' => $this->network,
- 'server_id' => $this->selectedServer->id,
- ]);
} else {
$found = $this->selectedServer->standaloneDockers()->where('network', $this->network)->first();
if ($found) {
- throw new Exception('Network already added to this server.');
+ throw new \Exception('Network already added to this server.');
+ } else {
+ $docker = StandaloneDocker::create([
+ 'name' => $this->name,
+ 'network' => $this->network,
+ 'server_id' => $this->selectedServer->id,
+ ]);
}
- $docker = StandaloneDocker::query()->create([
- 'name' => $this->name,
- 'network' => $this->network,
- 'server_id' => $this->selectedServer->id,
- ]);
}
$connectProxyToDockerNetworks = connectProxyToNetworks($this->selectedServer);
instant_remote_process($connectProxyToDockerNetworks, $this->selectedServer, false);
$this->dispatch('reloadWindow');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Destination/Show.php b/app/Livewire/Destination/Show.php
index 6cacfd4784..5c4d6c1701 100644
--- a/app/Livewire/Destination/Show.php
+++ b/app/Livewire/Destination/Show.php
@@ -8,7 +8,6 @@
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Show extends Component
{
@@ -41,11 +40,9 @@ public function mount(string $destination_uuid)
}
$this->destination = $destination;
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -68,17 +65,15 @@ public function submit()
try {
$this->syncData(true);
$this->dispatch('success', 'Destination saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function delete()
{
try {
- if ($this->destination->getMorphClass() === StandaloneDocker::class) {
+ if ($this->destination->getMorphClass() === \App\Models\StandaloneDocker::class) {
if ($this->destination->attachedTo()) {
return $this->dispatch('error', 'You must delete all resources before deleting this destination.');
}
@@ -88,7 +83,7 @@ public function delete()
$this->destination->delete();
return redirect()->route('destination.index');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/ForcePasswordReset.php b/app/Livewire/ForcePasswordReset.php
index 09cdea8847..61a2a20e95 100644
--- a/app/Livewire/ForcePasswordReset.php
+++ b/app/Livewire/ForcePasswordReset.php
@@ -6,7 +6,6 @@
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Livewire\Component;
-use Throwable;
class ForcePasswordReset extends Component
{
@@ -32,8 +31,6 @@ public function mount()
return redirect()->route('dashboard');
}
$this->email = auth()->user()->email;
-
- return null;
}
public function render()
@@ -60,7 +57,7 @@ public function submit()
}
return redirect()->route('dashboard');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Help.php b/app/Livewire/Help.php
index 864cece058..f51527fbeb 100644
--- a/app/Livewire/Help.php
+++ b/app/Livewire/Help.php
@@ -7,7 +7,6 @@
use Illuminate\Support\Facades\Http;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Help extends Component
{
@@ -26,14 +25,14 @@ public function submit()
$this->rateLimit(3, 30);
$settings = instanceSettings();
- $mailMessage = new MailMessage;
- $mailMessage->view(
+ $mail = new MailMessage;
+ $mail->view(
'emails.help',
[
'description' => $this->description,
]
);
- $mailMessage->subject("[HELP]: {$this->subject}");
+ $mail->subject("[HELP]: {$this->subject}");
$type = set_transanctional_email_settings($settings);
// Sending feedback through Cloud API
@@ -43,15 +42,13 @@ public function submit()
'content' => 'User: `'.auth()->user()?->email.'` with subject: `'.$this->subject.'` has the following problem: `'.$this->description.'`',
]);
} else {
- send_user_an_email($mailMessage, auth()->user()?->email, 'hi@coollabs.io');
+ send_user_an_email($mail, auth()->user()?->email, 'hi@coollabs.io');
}
$this->dispatch('success', 'Feedback sent.', 'We will get in touch with you as soon as possible.');
$this->reset('description', 'subject');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/NavbarDeleteTeam.php b/app/Livewire/NavbarDeleteTeam.php
index 639a9543f9..e97cceb0da 100644
--- a/app/Livewire/NavbarDeleteTeam.php
+++ b/app/Livewire/NavbarDeleteTeam.php
@@ -19,10 +19,12 @@ public function mount()
public function delete($password)
{
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return null;
+ return;
+ }
}
$currentTeam = currentTeam();
diff --git a/app/Livewire/NewActivityMonitor.php b/app/Livewire/NewActivityMonitor.php
index bd1474c915..a9334e7108 100644
--- a/app/Livewire/NewActivityMonitor.php
+++ b/app/Livewire/NewActivityMonitor.php
@@ -14,7 +14,7 @@ class NewActivityMonitor extends Component
public $eventToDispatch = 'activityFinished';
- public $eventData;
+ public $eventData = null;
public $isPollingActive = false;
@@ -35,7 +35,7 @@ public function newMonitorActivity($activityId, $eventToDispatch = 'activityFini
public function hydrateActivity()
{
- $this->activity = Activity::query()->find($this->activityId);
+ $this->activity = Activity::find($this->activityId);
}
public function polling()
@@ -53,7 +53,7 @@ public function polling()
if ($this->eventToDispatch !== null) {
if (str($this->eventToDispatch)->startsWith('App\\Events\\')) {
$causer_id = data_get($this->activity, 'causer_id');
- $user = User::query()->find($causer_id);
+ $user = User::find($causer_id);
if ($user) {
foreach ($user->teams as $team) {
$teamId = $team->id;
diff --git a/app/Livewire/Notifications/Discord.php b/app/Livewire/Notifications/Discord.php
index 0544b75667..57007813ee 100644
--- a/app/Livewire/Notifications/Discord.php
+++ b/app/Livewire/Notifications/Discord.php
@@ -7,7 +7,6 @@
use App\Notifications\Test;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Discord extends Component
{
@@ -63,11 +62,9 @@ public function mount()
$this->team = auth()->user()->currentTeam();
$this->settings = $this->team->discordNotificationSettings;
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -120,24 +117,20 @@ public function instantSaveDiscordEnabled()
'discordWebhookUrl.required' => 'Discord Webhook URL is required.',
]);
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->discordEnabled = false;
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
{
try {
$this->syncData(true);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -146,11 +139,9 @@ public function submit()
$this->resetErrorBag();
$this->syncData(true);
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function saveModel()
@@ -165,11 +156,9 @@ public function sendTestNotification()
try {
$this->team->notify(new Test(channel: 'discord'));
$this->dispatch('success', 'Test notification sent.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Notifications/Email.php b/app/Livewire/Notifications/Email.php
index dc26bf915f..3ed20f907c 100644
--- a/app/Livewire/Notifications/Email.php
+++ b/app/Livewire/Notifications/Email.php
@@ -5,12 +5,10 @@
use App\Models\EmailNotificationSettings;
use App\Models\Team;
use App\Notifications\Test;
-use Exception;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Email extends Component
{
@@ -111,11 +109,9 @@ public function mount()
$this->settings = $this->team->emailNotificationSettings;
$this->syncData();
$this->testEmailAddress = auth()->user()->email;
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -189,11 +185,9 @@ public function submit()
try {
$this->resetErrorBag();
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function saveModel()
@@ -216,9 +210,9 @@ public function instantSave(?string $type = null)
$this->resendEnabled = false;
$this->saveModel();
- return null;
+ return;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
if ($type === 'SMTP') {
$this->smtpEnabled = false;
} elseif ($type === 'Resend') {
@@ -229,8 +223,6 @@ public function instantSave(?string $type = null)
} finally {
$this->dispatch('refresh');
}
-
- return null;
}
public function submitSmtp()
@@ -274,13 +266,11 @@ public function submitSmtp()
$this->settings->save();
$this->dispatch('success', 'SMTP settings updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->smtpEnabled = false;
return handleError($e);
}
-
- return null;
}
public function submitResend()
@@ -311,11 +301,9 @@ public function submitResend()
$this->settings->save();
$this->dispatch('success', 'Resend settings updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function sendTestEmail()
@@ -339,13 +327,11 @@ function () {
);
if (! $executed) {
- throw new Exception('Too many messages sent!');
+ throw new \Exception('Too many messages sent!');
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function copyFromInstanceSettings()
diff --git a/app/Livewire/Notifications/Pushover.php b/app/Livewire/Notifications/Pushover.php
index 0c14fa023d..f1e4c464da 100644
--- a/app/Livewire/Notifications/Pushover.php
+++ b/app/Livewire/Notifications/Pushover.php
@@ -8,7 +8,6 @@
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Pushover extends Component
{
@@ -71,11 +70,9 @@ public function mount()
$this->team = auth()->user()->currentTeam();
$this->settings = $this->team->pushoverNotificationSettings;
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -132,28 +129,24 @@ public function instantSavePushoverEnabled()
'pushoverApiToken.required' => 'Pushover API Token is required.',
]);
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->pushoverEnabled = false;
return handleError($e, $this);
} finally {
$this->dispatch('refresh');
}
-
- return null;
}
public function instantSave()
{
try {
$this->syncData(true);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->dispatch('refresh');
}
-
- return null;
}
public function submit()
@@ -162,11 +155,9 @@ public function submit()
$this->resetErrorBag();
$this->syncData(true);
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function saveModel()
@@ -181,11 +172,9 @@ public function sendTestNotification()
try {
$this->team->notify(new Test(channel: 'pushover'));
$this->dispatch('success', 'Test notification sent.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Notifications/Slack.php b/app/Livewire/Notifications/Slack.php
index 03fa171c21..f47ad8a979 100644
--- a/app/Livewire/Notifications/Slack.php
+++ b/app/Livewire/Notifications/Slack.php
@@ -8,7 +8,6 @@
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Slack extends Component
{
@@ -68,11 +67,9 @@ public function mount()
$this->team = auth()->user()->currentTeam();
$this->settings = $this->team->slackNotificationSettings;
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -125,28 +122,24 @@ public function instantSaveSlackEnabled()
'slackWebhookUrl.required' => 'Slack Webhook URL is required.',
]);
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->slackEnabled = false;
return handleError($e, $this);
} finally {
$this->dispatch('refresh');
}
-
- return null;
}
public function instantSave()
{
try {
$this->syncData(true);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->dispatch('refresh');
}
-
- return null;
}
public function submit()
@@ -155,11 +148,9 @@ public function submit()
$this->resetErrorBag();
$this->syncData(true);
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function saveModel()
@@ -174,11 +165,9 @@ public function sendTestNotification()
try {
$this->team->notify(new Test(channel: 'slack'));
$this->dispatch('success', 'Test notification sent.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Notifications/Telegram.php b/app/Livewire/Notifications/Telegram.php
index 2f6c6f3be9..01afb4ac67 100644
--- a/app/Livewire/Notifications/Telegram.php
+++ b/app/Livewire/Notifications/Telegram.php
@@ -8,7 +8,6 @@
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Telegram extends Component
{
@@ -107,11 +106,9 @@ public function mount()
$this->team = auth()->user()->currentTeam();
$this->settings = $this->team->telegramNotificationSettings;
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -186,13 +183,11 @@ public function instantSave()
{
try {
$this->syncData(true);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->dispatch('refresh');
}
-
- return null;
}
public function submit()
@@ -201,11 +196,9 @@ public function submit()
$this->resetErrorBag();
$this->syncData(true);
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSaveTelegramEnabled()
@@ -219,15 +212,13 @@ public function instantSaveTelegramEnabled()
'telegramChatId.required' => 'Telegram Chat ID is required.',
]);
$this->saveModel();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->telegramEnabled = false;
return handleError($e, $this);
} finally {
$this->dispatch('refresh');
}
-
- return null;
}
public function saveModel()
@@ -242,11 +233,9 @@ public function sendTestNotification()
try {
$this->team->notify(new Test(channel: 'telegram'));
$this->dispatch('success', 'Test notification sent.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Profile/Index.php b/app/Livewire/Profile/Index.php
index 70f82da153..53314cd5c3 100644
--- a/app/Livewire/Profile/Index.php
+++ b/app/Livewire/Profile/Index.php
@@ -7,7 +7,6 @@
use Illuminate\Validation\Rules\Password;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Index extends Component
{
@@ -42,11 +41,9 @@ public function submit()
]);
$this->dispatch('success', 'Profile updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function resetPassword()
@@ -59,12 +56,12 @@ public function resetPassword()
if (! Hash::check($this->current_password, auth()->user()->password)) {
$this->dispatch('error', 'Current password is incorrect.');
- return null;
+ return;
}
if ($this->new_password !== $this->new_password_confirmation) {
$this->dispatch('error', 'The two new passwords does not match.');
- return null;
+ return;
}
auth()->user()->update([
'password' => Hash::make($this->new_password),
@@ -73,11 +70,9 @@ public function resetPassword()
$this->current_password = '';
$this->new_password = '';
$this->new_password_confirmation = '';
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/AddEmpty.php b/app/Livewire/Project/AddEmpty.php
index f91c977c68..07873c059d 100644
--- a/app/Livewire/Project/AddEmpty.php
+++ b/app/Livewire/Project/AddEmpty.php
@@ -5,7 +5,6 @@
use App\Models\Project;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
use Visus\Cuid2\Cuid2;
class AddEmpty extends Component
@@ -20,7 +19,7 @@ public function submit()
{
try {
$this->validate();
- $project = Project::query()->create([
+ $project = Project::create([
'name' => $this->name,
'description' => $this->description,
'team_id' => currentTeam()->id,
@@ -28,7 +27,7 @@ public function submit()
]);
return redirect()->route('project.show', $project->uuid);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Project/Application/Advanced.php b/app/Livewire/Project/Application/Advanced.php
index 99b40c62d0..cb63f0e1a6 100644
--- a/app/Livewire/Project/Application/Advanced.php
+++ b/app/Livewire/Project/Application/Advanced.php
@@ -5,7 +5,6 @@
use App\Models\Application;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Advanced extends Component
{
@@ -72,11 +71,9 @@ public function mount()
{
try {
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -130,12 +127,14 @@ public function syncData(bool $toModel = false)
public function instantSave()
{
try {
- if ($this->isLogDrainEnabled && ! $this->application->destination->server->isLogDrainEnabled()) {
- $this->isLogDrainEnabled = false;
- $this->syncData(true);
- $this->dispatch('error', 'Log drain is not enabled on this server.');
-
- return null;
+ if ($this->isLogDrainEnabled) {
+ if (! $this->application->destination->server->isLogDrainEnabled()) {
+ $this->isLogDrainEnabled = false;
+ $this->syncData(true);
+ $this->dispatch('error', 'Log drain is not enabled on this server.');
+
+ return;
+ }
}
if ($this->application->isForceHttpsEnabled() !== $this->isForceHttpsEnabled ||
$this->application->isGzipEnabled() !== $this->isGzipEnabled ||
@@ -152,11 +151,9 @@ public function instantSave()
$this->syncData(true);
$this->dispatch('success', 'Settings saved.');
$this->dispatch('configurationChanged');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -168,15 +165,13 @@ public function submit()
$this->gpuDeviceIds = null;
$this->syncData(true);
- return null;
+ return;
}
$this->syncData(true);
$this->dispatch('success', 'Settings saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function saveCustomName()
diff --git a/app/Livewire/Project/Application/Deployment/Index.php b/app/Livewire/Project/Application/Deployment/Index.php
index e03a28cb53..b847c40ef1 100644
--- a/app/Livewire/Project/Application/Deployment/Index.php
+++ b/app/Livewire/Project/Application/Deployment/Index.php
@@ -49,8 +49,6 @@ public function mount()
$this->current_url = url()->current();
$this->show_pull_request_only();
$this->show_more();
-
- return null;
}
private function show_pull_request_only()
@@ -80,9 +78,9 @@ public function reload_deployments()
public function previous_page(?int $take = null)
{
if ($take) {
- $this->skip -= $take;
+ $this->skip = $this->skip - $take;
}
- $this->skip -= $this->default_take;
+ $this->skip = $this->skip - $this->default_take;
if ($this->skip < 0) {
$this->show_prev = false;
$this->skip = 0;
@@ -93,7 +91,7 @@ public function previous_page(?int $take = null)
public function next_page(?int $take = null)
{
if ($take) {
- $this->skip += $take;
+ $this->skip = $this->skip + $take;
}
$this->show_prev = true;
$this->load_deployments();
diff --git a/app/Livewire/Project/Application/Deployment/Show.php b/app/Livewire/Project/Application/Deployment/Show.php
index 3289efe26e..4e86b5c7e4 100644
--- a/app/Livewire/Project/Application/Deployment/Show.php
+++ b/app/Livewire/Project/Application/Deployment/Show.php
@@ -34,7 +34,7 @@ public function mount()
if (! $application) {
return redirect()->route('dashboard');
}
- $application_deployment_queue = ApplicationDeploymentQueue::query()->where('deployment_uuid', $deploymentUuid)->first();
+ $application_deployment_queue = ApplicationDeploymentQueue::where('deployment_uuid', $deploymentUuid)->first();
if (! $application_deployment_queue) {
return redirect()->route('project.application.deployment.index', [
'project_uuid' => $project->uuid,
@@ -45,8 +45,6 @@ public function mount()
$this->application = $application;
$this->application_deployment_queue = $application_deployment_queue;
$this->deployment_uuid = $deploymentUuid;
-
- return null;
}
public function refreshQueue()
diff --git a/app/Livewire/Project/Application/DeploymentNavbar.php b/app/Livewire/Project/Application/DeploymentNavbar.php
index b88bafbd7c..87b40d4dc1 100644
--- a/app/Livewire/Project/Application/DeploymentNavbar.php
+++ b/app/Livewire/Project/Application/DeploymentNavbar.php
@@ -8,7 +8,6 @@
use App\Models\Server;
use Illuminate\Support\Carbon;
use Livewire\Component;
-use Throwable;
class DeploymentNavbar extends Component
{
@@ -46,11 +45,9 @@ public function force_start()
{
try {
force_start_deployment($this->application_deployment_queue);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function cancel()
@@ -60,9 +57,9 @@ public function cancel()
$server_id = $this->application_deployment_queue->server_id ?? $this->application->destination->server_id;
try {
if ($this->application->settings->is_build_server_enabled) {
- $server = Server::query()->find($build_server_id);
+ $server = Server::find($build_server_id);
} else {
- $server = Server::query()->find($server_id);
+ $server = Server::find($server_id);
}
if ($this->application_deployment_queue->logs) {
$previous_logs = json_decode($this->application_deployment_queue->logs, associative: true, flags: JSON_THROW_ON_ERROR);
@@ -81,7 +78,7 @@ public function cancel()
]);
}
instant_remote_process([$kill_command], $server);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->application_deployment_queue->update([
@@ -90,7 +87,5 @@ public function cancel()
]);
next_after_cancel($server);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Application/General.php b/app/Livewire/Project/Application/General.php
index 8622055018..d1cc3476cd 100644
--- a/app/Livewire/Project/Application/General.php
+++ b/app/Livewire/Project/Application/General.php
@@ -6,9 +6,7 @@
use App\Models\Application;
use Illuminate\Support\Collection;
use Livewire\Component;
-use Livewire\Features\SupportEvents\Event;
use Spatie\Url\Url;
-use Throwable;
use Visus\Cuid2\Cuid2;
class General extends Component
@@ -143,7 +141,7 @@ public function mount()
return;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->dispatch('error', $e->getMessage());
}
if ($this->application->build_pack === 'dockercompose') {
@@ -181,11 +179,13 @@ public function instantSave()
if ($this->ports_exposes !== $this->application->ports_exposes || $this->is_container_label_escape_enabled !== $this->application->settings->is_container_label_escape_enabled) {
$this->resetDefaultLabels(false);
}
- if ($this->is_preserve_repository_enabled !== $this->application->settings->is_preserve_repository_enabled && $this->application->settings->is_preserve_repository_enabled === false) {
- $this->application->fileStorages->each(function ($storage) {
- $storage->is_based_on_git = $this->application->settings->is_preserve_repository_enabled;
- $storage->save();
- });
+ if ($this->is_preserve_repository_enabled !== $this->application->settings->is_preserve_repository_enabled) {
+ if ($this->application->settings->is_preserve_repository_enabled === false) {
+ $this->application->fileStorages->each(function ($storage) {
+ $storage->is_based_on_git = $this->application->settings->is_preserve_repository_enabled;
+ $storage->save();
+ });
+ }
}
}
@@ -193,7 +193,7 @@ public function loadComposeFile($isInit = false)
{
try {
if ($isInit && $this->application->docker_compose_raw) {
- return null;
+ return;
}
// Must reload the application to get the latest database changes
@@ -204,14 +204,14 @@ public function loadComposeFile($isInit = false)
if (is_null($this->parsedServices)) {
$this->dispatch('error', 'Failed to parse your docker-compose file. Please check the syntax and try again.');
- return null;
+ return;
}
$this->application->parse();
$this->dispatch('success', 'Docker compose file loaded.');
$this->dispatch('compose_loaded');
$this->dispatch('refreshStorages');
$this->dispatch('refreshEnvs');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->application->docker_compose_location = $this->initialDockerComposeLocation;
$this->application->save();
@@ -219,14 +219,12 @@ public function loadComposeFile($isInit = false)
} finally {
$this->initLoadingCompose = false;
}
-
- return null;
}
public function generateDomain(string $serviceName)
{
- $cuid2 = new Cuid2;
- $domain = generateFqdn($this->application->destination->server, $cuid2);
+ $uuid = new Cuid2;
+ $domain = generateFqdn($this->application->destination->server, $uuid);
$this->parsedServiceDomains[$serviceName]['domain'] = $domain;
$this->application->docker_compose_domains = json_encode($this->parsedServiceDomains);
$this->application->save();
@@ -297,7 +295,7 @@ public function resetDefaultLabels($manualReset = false)
{
try {
if ($this->application->settings->is_container_label_readonly_enabled && ! $manualReset) {
- return null;
+ return;
}
$this->customLabels = str(implode('|coolify|', generateLabelsApplication($this->application)))->replace('|coolify|', "\n");
$this->ports_exposes = $this->application->ports_exposes;
@@ -308,11 +306,9 @@ public function resetDefaultLabels($manualReset = false)
$this->loadComposeFile();
}
$this->dispatch('configurationChanged');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function checkFqdns($showToaster = true)
@@ -338,16 +334,14 @@ public function setRedirect()
if ($has_www === 0 && $this->application->redirect === 'www') {
$this->dispatch('error', 'You want to redirect to www, but you do not have a www domain set.
Please add www to your domain list and as an A DNS record (if applicable).');
- return null;
+ return;
}
$this->application->save();
$this->resetDefaultLabels();
$this->dispatch('success', 'Redirect updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit($showToaster = true)
@@ -383,8 +377,8 @@ public function submit($showToaster = true)
if ($this->application->build_pack === 'dockercompose' && $this->initialDockerComposeLocation !== $this->application->docker_compose_location) {
$compose_return = $this->loadComposeFile();
- if ($compose_return instanceof Event) {
- return null;
+ if ($compose_return instanceof \Livewire\Features\SupportEvents\Event) {
+ return;
}
}
$this->validate();
@@ -416,8 +410,8 @@ public function submit($showToaster = true)
if ($this->application->build_pack === 'dockercompose') {
$this->application->docker_compose_domains = json_encode($this->parsedServiceDomains);
- foreach ($this->parsedServiceDomains as $parsedServiceDomain) {
- $domain = data_get($parsedServiceDomain, 'domain');
+ foreach ($this->parsedServiceDomains as $serviceName => $service) {
+ $domain = data_get($service, 'domain');
if ($domain) {
if (! validate_dns_entry($domain, $this->application->destination->server)) {
$showToaster && $this->dispatch('error', 'Validating DNS failed.', "Make sure you have added the DNS records correctly.
$domain->{$this->application->destination->server->ip}
Check this documentation for further help.");
@@ -431,10 +425,8 @@ public function submit($showToaster = true)
}
$this->application->custom_labels = base64_encode($this->customLabels);
$this->application->save();
- if ($showToaster && ! $warning) {
- $this->dispatch('success', 'Application settings updated!');
- }
- } catch (Throwable $e) {
+ $showToaster && ! $warning && $this->dispatch('success', 'Application settings updated!');
+ } catch (\Throwable $e) {
$originalFqdn = $this->application->getOriginal('fqdn');
if ($originalFqdn !== $this->application->fqdn) {
$this->application->fqdn = $originalFqdn;
@@ -444,8 +436,6 @@ public function submit($showToaster = true)
} finally {
$this->dispatch('configurationChanged');
}
-
- return null;
}
public function downloadConfig()
diff --git a/app/Livewire/Project/Application/Heading.php b/app/Livewire/Project/Application/Heading.php
index 26d9275dc4..0afc9123a2 100644
--- a/app/Livewire/Project/Application/Heading.php
+++ b/app/Livewire/Project/Application/Heading.php
@@ -66,22 +66,22 @@ public function deploy(bool $force_rebuild = false)
if ($this->application->build_pack === 'dockercompose' && is_null($this->application->docker_compose_raw)) {
$this->dispatch('error', 'Failed to deploy', 'Please load a Compose file first.');
- return null;
+ return;
}
if ($this->application->destination->server->isSwarm() && str($this->application->docker_registry_image_name)->isEmpty()) {
$this->dispatch('error', 'Failed to deploy.', 'To deploy to a Swarm cluster you must set a Docker image name first.');
- return null;
+ return;
}
if (data_get($this->application, 'settings.is_build_server_enabled') && str($this->application->docker_registry_image_name)->isEmpty()) {
$this->dispatch('error', 'Failed to deploy.', 'To use a build server, you must first set a Docker image.
More information here: documentation');
- return null;
+ return;
}
if ($this->application->additional_servers->count() > 0 && str($this->application->docker_registry_image_name)->isEmpty()) {
$this->dispatch('error', 'Failed to deploy.', 'Before deploying to multiple servers, you must first set a Docker image in the General tab.
More information here: documentation');
- return null;
+ return;
}
$this->setDeploymentUuid();
queue_application_deployment(
@@ -123,7 +123,7 @@ public function restart()
if ($this->application->additional_servers->count() > 0 && str($this->application->docker_registry_image_name)->isEmpty()) {
$this->dispatch('error', 'Failed to deploy', 'Before deploying to multiple servers, you must first set a Docker image in the General tab.
More information here: documentation');
- return null;
+ return;
}
$this->setDeploymentUuid();
queue_application_deployment(
diff --git a/app/Livewire/Project/Application/Preview/Form.php b/app/Livewire/Project/Application/Preview/Form.php
index 208574de97..edcab44c88 100644
--- a/app/Livewire/Project/Application/Preview/Form.php
+++ b/app/Livewire/Project/Application/Preview/Form.php
@@ -6,7 +6,6 @@
use Livewire\Attributes\Validate;
use Livewire\Component;
use Spatie\Url\Url;
-use Throwable;
class Form extends Component
{
@@ -20,11 +19,9 @@ public function mount()
try {
$this->previewUrlTemplate = $this->application->preview_url_template;
$this->generateRealUrl();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -36,11 +33,9 @@ public function submit()
$this->application->save();
$this->dispatch('success', 'Preview url template updated.');
$this->generateRealUrl();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function resetToDefault()
@@ -51,11 +46,9 @@ public function resetToDefault()
$this->application->save();
$this->generateRealUrl();
$this->dispatch('success', 'Preview url template updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function generateRealUrl()
diff --git a/app/Livewire/Project/Application/Previews.php b/app/Livewire/Project/Application/Previews.php
index 16235e7ce5..bdf62706c3 100644
--- a/app/Livewire/Project/Application/Previews.php
+++ b/app/Livewire/Project/Application/Previews.php
@@ -6,13 +6,11 @@
use App\Models\Application;
use App\Models\ApplicationPreview;
use Carbon\Carbon;
-use Exception;
use Illuminate\Process\InvokedProcess;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Process;
use Livewire\Component;
use Spatie\Url\Url;
-use Throwable;
use Visus\Cuid2\Cuid2;
class Previews extends Component
@@ -43,13 +41,11 @@ public function load_prs()
['rate_limit_remaining' => $rate_limit_remaining, 'data' => $data] = githubApi(source: $this->application->source, endpoint: "/repos/{$this->application->git_repository}/pulls");
$this->rate_limit_remaining = $rate_limit_remaining;
$this->pull_requests = $data->sortBy('number')->values();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->rate_limit_remaining = 0;
return handleError($e, $this);
}
-
- return null;
}
public function save_preview($preview_id)
@@ -69,19 +65,13 @@ public function save_preview($preview_id)
}
if (! $preview) {
- throw new Exception('Preview not found');
- }
- if ($success) {
- $preview->save();
+ throw new \Exception('Preview not found');
}
- if ($success) {
- $this->dispatch('success', 'Preview saved.
Do not forget to redeploy the preview to apply the changes.');
- }
- } catch (Throwable $e) {
+ $success && $preview->save();
+ $success && $this->dispatch('success', 'Preview saved.
Do not forget to redeploy the preview to apply the changes.');
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function generate_preview($preview_id)
@@ -105,8 +95,8 @@ public function generate_preview($preview_id)
$template = $this->application->preview_url_template;
$host = $url->getHost();
$schema = $url->getScheme();
- $cuid2 = new Cuid2;
- $preview_fqdn = str_replace('{{random}}', $cuid2, $template);
+ $random = new Cuid2;
+ $preview_fqdn = str_replace('{{random}}', $random, $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $preview->pull_request_id, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn";
@@ -120,9 +110,9 @@ public function add(int $pull_request_id, ?string $pull_request_html_url = null)
try {
if ($this->application->build_pack === 'dockercompose') {
$this->setDeploymentUuid();
- $found = ApplicationPreview::query()->where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found && ! is_null($pull_request_html_url)) {
- $found = ApplicationPreview::query()->create([
+ $found = ApplicationPreview::create([
'application_id' => $this->application->id,
'pull_request_id' => $pull_request_id,
'pull_request_html_url' => $pull_request_html_url,
@@ -133,9 +123,9 @@ public function add(int $pull_request_id, ?string $pull_request_html_url = null)
$this->application->refresh();
} else {
$this->setDeploymentUuid();
- $found = ApplicationPreview::query()->where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found && ! is_null($pull_request_html_url)) {
- $found = ApplicationPreview::query()->create([
+ $found = ApplicationPreview::create([
'application_id' => $this->application->id,
'pull_request_id' => $pull_request_id,
'pull_request_html_url' => $pull_request_html_url,
@@ -146,11 +136,9 @@ public function add(int $pull_request_id, ?string $pull_request_html_url = null)
$this->dispatch('update_links');
$this->dispatch('success', 'Preview added.');
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function add_and_deploy(int $pull_request_id, ?string $pull_request_html_url = null)
@@ -163,9 +151,9 @@ public function deploy(int $pull_request_id, ?string $pull_request_html_url = nu
{
try {
$this->setDeploymentUuid();
- $found = ApplicationPreview::query()->where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
+ $found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
if (! $found && ! is_null($pull_request_html_url)) {
- ApplicationPreview::query()->create([
+ ApplicationPreview::create([
'application_id' => $this->application->id,
'pull_request_id' => $pull_request_id,
'pull_request_html_url' => $pull_request_html_url,
@@ -185,7 +173,7 @@ public function deploy(int $pull_request_id, ?string $pull_request_html_url = nu
'deployment_uuid' => $this->deployment_uuid,
'environment_uuid' => $this->parameters['environment_uuid'],
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
@@ -213,11 +201,9 @@ public function stop(int $pull_request_id)
$this->application->refresh();
$this->dispatch('containerStatusUpdated');
$this->dispatch('success', 'Preview Deployment stopped.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function delete(int $pull_request_id)
@@ -233,7 +219,7 @@ public function delete(int $pull_request_id)
$this->stopContainers($containers, $server, $timeout);
}
- ApplicationPreview::query()->where('application_id', $this->application->id)
+ ApplicationPreview::where('application_id', $this->application->id)
->where('pull_request_id', $pull_request_id)
->first()
->delete();
@@ -241,11 +227,9 @@ public function delete(int $pull_request_id)
$this->application->refresh();
$this->dispatch('update_links');
$this->dispatch('success', 'Preview deleted.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
private function stopContainers(array $containers, $server, int $timeout)
@@ -257,7 +241,7 @@ private function stopContainers(array $containers, $server, int $timeout)
}
$startTime = Carbon::now()->getTimestamp();
- while ($processes !== []) {
+ while (count($processes) > 0) {
$finishedProcesses = array_filter($processes, function ($process) {
return ! $process->running();
});
diff --git a/app/Livewire/Project/Application/PreviewsCompose.php b/app/Livewire/Project/Application/PreviewsCompose.php
index cc9a016c57..b3e838bb3f 100644
--- a/app/Livewire/Project/Application/PreviewsCompose.php
+++ b/app/Livewire/Project/Application/PreviewsCompose.php
@@ -44,8 +44,8 @@ public function generate()
$template = $this->preview->application->preview_url_template;
$host = $url->getHost();
$schema = $url->getScheme();
- $cuid2 = new Cuid2;
- $preview_fqdn = str_replace('{{random}}', $cuid2, $template);
+ $random = new Cuid2;
+ $preview_fqdn = str_replace('{{random}}', $random, $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $this->preview->pull_request_id, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn";
diff --git a/app/Livewire/Project/Application/Rollback.php b/app/Livewire/Project/Application/Rollback.php
index fe06912fc6..ff5db1e08c 100644
--- a/app/Livewire/Project/Application/Rollback.php
+++ b/app/Livewire/Project/Application/Rollback.php
@@ -4,7 +4,6 @@
use App\Models\Application;
use Livewire\Component;
-use Throwable;
use Visus\Cuid2\Cuid2;
class Rollback extends Component
@@ -24,11 +23,11 @@ public function mount()
public function rollbackImage($commit)
{
- $cuid2 = new Cuid2;
+ $deployment_uuid = new Cuid2;
queue_application_deployment(
application: $this->application,
- deployment_uuid: $cuid2,
+ deployment_uuid: $deployment_uuid,
commit: $commit,
rollback: true,
force_rebuild: false,
@@ -37,7 +36,7 @@ public function rollbackImage($commit)
return redirect()->route('project.application.deployment.show', [
'project_uuid' => $this->parameters['project_uuid'],
'application_uuid' => $this->parameters['application_uuid'],
- 'deployment_uuid' => $cuid2,
+ 'deployment_uuid' => $deployment_uuid,
'environment_uuid' => $this->parameters['environment_uuid'],
]);
}
@@ -74,7 +73,7 @@ public function loadImages($showToast = false)
$showToast && $this->dispatch('success', 'Images loaded.');
return [];
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Project/Application/Source.php b/app/Livewire/Project/Application/Source.php
index bd80ba0cfe..ade297d501 100644
--- a/app/Livewire/Project/Application/Source.php
+++ b/app/Livewire/Project/Application/Source.php
@@ -7,7 +7,6 @@
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Source extends Component
{
@@ -36,7 +35,7 @@ public function mount()
try {
$this->syncData();
$this->getPrivateKeys();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
handleError($e, $this);
}
}
@@ -76,11 +75,9 @@ public function setPrivateKey(int $privateKeyId)
$this->application->refresh();
$this->privateKeyName = $this->application->private_key->name;
$this->dispatch('success', 'Private key updated!');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -91,10 +88,8 @@ public function submit()
}
$this->syncData(true);
$this->dispatch('success', 'Application source updated!');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Application/Swarm.php b/app/Livewire/Project/Application/Swarm.php
index ea3c3f7c0d..197dc41ed3 100644
--- a/app/Livewire/Project/Application/Swarm.php
+++ b/app/Livewire/Project/Application/Swarm.php
@@ -5,7 +5,6 @@
use App\Models\Application;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Swarm extends Component
{
@@ -24,11 +23,9 @@ public function mount()
{
try {
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -56,11 +53,9 @@ public function instantSave()
try {
$this->syncData(true);
$this->dispatch('success', 'Swarm settings updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -68,11 +63,9 @@ public function submit()
try {
$this->syncData(true);
$this->dispatch('success', 'Swarm settings updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/CloneMe.php b/app/Livewire/Project/CloneMe.php
index 172d1860f1..593355c443 100644
--- a/app/Livewire/Project/CloneMe.php
+++ b/app/Livewire/Project/CloneMe.php
@@ -5,7 +5,6 @@
use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
-use Exception;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
@@ -44,11 +43,11 @@ class CloneMe extends Component
public function mount($project_uuid)
{
$this->project_uuid = $project_uuid;
- $this->project = Project::query()->where('uuid', $project_uuid)->firstOrFail();
+ $this->project = Project::where('uuid', $project_uuid)->firstOrFail();
$this->environment = $this->project->environments->where('uuid', $this->environment_uuid)->first();
$this->project_id = $this->project->id;
$this->servers = currentTeam()->servers;
- $this->newName = str($this->project->name.'-clone-'.new Cuid2)->slug();
+ $this->newName = str($this->project->name.'-clone-'.(string) new Cuid2)->slug();
}
public function render()
@@ -78,11 +77,11 @@ public function clone(string $type)
'newName' => 'required',
]);
if ($type === 'project') {
- $foundProject = Project::query()->where('name', $this->newName)->first();
+ $foundProject = Project::where('name', $this->newName)->first();
if ($foundProject) {
- throw new Exception('Project with the same name already exists.');
+ throw new \Exception('Project with the same name already exists.');
}
- $project = Project::query()->create([
+ $project = Project::create([
'name' => $this->newName,
'team_id' => currentTeam()->id,
'description' => $this->project->description.' (clone)',
@@ -97,7 +96,7 @@ public function clone(string $type)
} else {
$foundEnv = $this->project->environments()->where('name', $this->newName)->first();
if ($foundEnv) {
- throw new Exception('Environment with the same name already exists.');
+ throw new \Exception('Environment with the same name already exists.');
}
$project = $this->project;
$environment = $this->project->environments()->create([
@@ -127,9 +126,9 @@ public function clone(string $type)
$newEnvironmentVariable->save();
}
$persistentVolumes = $application->persistentStorages()->get();
- foreach ($persistentVolumes as $persistentVolume) {
- $newPersistentVolume = $persistentVolume->replicate()->fill([
- 'name' => $newApplication->uuid.'-'.str($persistentVolume->name)->afterLast('-'),
+ foreach ($persistentVolumes as $volume) {
+ $newPersistentVolume = $volume->replicate()->fill([
+ 'name' => $newApplication->uuid.'-'.str($volume->name)->afterLast('-'),
'resource_id' => $newApplication->id,
]);
$newPersistentVolume->save();
@@ -179,7 +178,7 @@ public function clone(string $type)
'project_uuid' => $project->uuid,
'environment_uuid' => $environment->uuid,
]);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Project/Database/Backup/Execution.php b/app/Livewire/Project/Database/Backup/Execution.php
index 35818d35c9..4ac3b2e2c5 100644
--- a/app/Livewire/Project/Database/Backup/Execution.php
+++ b/app/Livewire/Project/Database/Backup/Execution.php
@@ -39,8 +39,6 @@ public function mount()
$this->backup = $backup;
$this->executions = $executions;
$this->s3s = currentTeam()->s3s;
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Database/Backup/Index.php b/app/Livewire/Project/Database/Backup/Index.php
index 072b88a2b1..2df32ec7bf 100644
--- a/app/Livewire/Project/Database/Backup/Index.php
+++ b/app/Livewire/Project/Database/Backup/Index.php
@@ -2,10 +2,6 @@
namespace App\Livewire\Project\Database\Backup;
-use App\Models\StandaloneClickhouse;
-use App\Models\StandaloneDragonfly;
-use App\Models\StandaloneKeydb;
-use App\Models\StandaloneRedis;
use Livewire\Component;
class Index extends Component
@@ -28,10 +24,10 @@ public function mount()
}
// No backups
if (
- $database->getMorphClass() === StandaloneRedis::class ||
- $database->getMorphClass() === StandaloneKeydb::class ||
- $database->getMorphClass() === StandaloneDragonfly::class ||
- $database->getMorphClass() === StandaloneClickhouse::class
+ $database->getMorphClass() === \App\Models\StandaloneRedis::class ||
+ $database->getMorphClass() === \App\Models\StandaloneKeydb::class ||
+ $database->getMorphClass() === \App\Models\StandaloneDragonfly::class ||
+ $database->getMorphClass() === \App\Models\StandaloneClickhouse::class
) {
return redirect()->route('project.database.configuration', [
'project_uuid' => $project->uuid,
@@ -40,8 +36,6 @@ public function mount()
]);
}
$this->database = $database;
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Database/BackupEdit.php b/app/Livewire/Project/Database/BackupEdit.php
index d5b05aeda7..0dea0496ca 100644
--- a/app/Livewire/Project/Database/BackupEdit.php
+++ b/app/Livewire/Project/Database/BackupEdit.php
@@ -4,7 +4,6 @@
use App\Models\InstanceSettings;
use App\Models\ScheduledDatabaseBackup;
-use App\Models\ServiceDatabase;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
@@ -12,7 +11,6 @@
use Livewire\Attributes\Validate;
use Livewire\Component;
use Spatie\Url\Url;
-use Throwable;
class BackupEdit extends Component
{
@@ -68,8 +66,6 @@ public function mount()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -98,10 +94,12 @@ public function syncData(bool $toModel = false)
public function delete($password)
{
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return null;
+ return;
+ }
}
try {
@@ -114,7 +112,7 @@ public function delete($password)
$this->backup->delete();
- if ($this->backup->database->getMorphClass() === ServiceDatabase::class) {
+ if ($this->backup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {
$previousUrl = url()->previous();
$url = Url::fromString($previousUrl);
$url = $url->withoutQueryParameter('selectedBackupId');
@@ -122,10 +120,10 @@ public function delete($password)
$url = $url->getPath()."#{$url->getFragment()}";
return redirect($url);
+ } else {
+ return redirect()->route('project.database.backup.index', $this->parameters);
}
-
- return redirect()->route('project.database.backup.index', $this->parameters);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
@@ -135,7 +133,7 @@ public function instantSave()
try {
$this->syncData(true);
$this->dispatch('success', 'Backup updated successfully.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->dispatch('error', $e->getMessage());
}
}
@@ -147,7 +145,7 @@ private function customValidate()
}
$isValid = validate_cron_expression($this->backup->frequency);
if (! $isValid) {
- throw new Exception('Invalid Cron / Human expression');
+ throw new \Exception('Invalid Cron / Human expression');
}
$this->validate();
}
@@ -157,7 +155,7 @@ public function submit()
try {
$this->syncData(true);
$this->dispatch('success', 'Backup updated successfully.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->dispatch('error', $e->getMessage());
}
}
@@ -168,7 +166,7 @@ private function deleteAssociatedBackupsLocally()
$backupFolder = null;
foreach ($executions as $execution) {
- if ($this->backup->database->getMorphClass() === ServiceDatabase::class) {
+ if ($this->backup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {
$server = $this->backup->database->service->destination->server;
} else {
$server = $this->backup->database->destination->server;
diff --git a/app/Livewire/Project/Database/BackupExecutions.php b/app/Livewire/Project/Database/BackupExecutions.php
index 090eb25640..f91b8bfaf3 100644
--- a/app/Livewire/Project/Database/BackupExecutions.php
+++ b/app/Livewire/Project/Database/BackupExecutions.php
@@ -4,10 +4,6 @@
use App\Models\InstanceSettings;
use App\Models\ScheduledDatabaseBackup;
-use App\Models\ServiceDatabase;
-use DateTime;
-use DateTimeZone;
-use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
@@ -37,7 +33,7 @@ public function getListeners()
public function cleanupFailed()
{
- if ($this->backup instanceof ScheduledDatabaseBackup) {
+ if ($this->backup) {
$this->backup->executions()->where('status', 'failed')->delete();
$this->refreshBackupExecutions();
$this->dispatch('success', 'Failed backups cleaned up.');
@@ -46,10 +42,12 @@ public function cleanupFailed()
public function deleteBackup($executionId, $password)
{
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return;
+ return;
+ }
}
$execution = $this->backup->executions()->where('id', $executionId)->first();
@@ -59,7 +57,7 @@ public function deleteBackup($executionId, $password)
return;
}
- if ($execution->scheduledDatabaseBackup->database->getMorphClass() === ServiceDatabase::class) {
+ if ($execution->scheduledDatabaseBackup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {
delete_backup_locally($execution->filename, $execution->scheduledDatabaseBackup->database->service->destination->server);
} else {
delete_backup_locally($execution->filename, $execution->scheduledDatabaseBackup->database->destination->server);
@@ -85,15 +83,15 @@ public function download_file($exeuctionId)
public function refreshBackupExecutions(): void
{
- if ($this->backup instanceof ScheduledDatabaseBackup) {
+ if ($this->backup) {
$this->executions = $this->backup->executions()->get();
}
}
- public function mount(ScheduledDatabaseBackup $scheduledDatabaseBackup)
+ public function mount(ScheduledDatabaseBackup $backup)
{
- $this->backup = $scheduledDatabaseBackup;
- $this->database = $scheduledDatabaseBackup->database;
+ $this->backup = $backup;
+ $this->database = $backup->database;
$this->refreshBackupExecutions();
}
@@ -102,7 +100,7 @@ public function server()
if ($this->database) {
$server = null;
- if ($this->database instanceof ServiceDatabase) {
+ if ($this->database instanceof \App\Models\ServiceDatabase) {
$server = $this->database->service->destination->server;
} elseif ($this->database->destination && $this->database->destination->server) {
$server = $this->database->destination->server;
@@ -128,11 +126,11 @@ public function getServerTimezone()
public function formatDateInServerTimezone($date)
{
$serverTimezone = $this->getServerTimezone();
- $dateObj = new DateTime($date);
+ $dateObj = new \DateTime($date);
try {
- $dateObj->setTimezone(new DateTimeZone($serverTimezone));
- } catch (Exception) {
- $dateObj->setTimezone(new DateTimeZone('UTC'));
+ $dateObj->setTimezone(new \DateTimeZone($serverTimezone));
+ } catch (\Exception) {
+ $dateObj->setTimezone(new \DateTimeZone('UTC'));
}
return $dateObj->format('Y-m-d H:i:s T');
diff --git a/app/Livewire/Project/Database/Clickhouse/General.php b/app/Livewire/Project/Database/Clickhouse/General.php
index 1bbce0ac41..2d39c5151f 100644
--- a/app/Livewire/Project/Database/Clickhouse/General.php
+++ b/app/Livewire/Project/Database/Clickhouse/General.php
@@ -10,7 +10,6 @@
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class General extends Component
{
@@ -68,11 +67,9 @@ public function mount()
try {
$this->syncData();
$this->server = data_get($this->database, 'destination.server');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -116,7 +113,7 @@ public function instantSaveAdvanced()
$this->isLogDrainEnabled = false;
$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');
- return null;
+ return;
}
$this->syncData(true);
@@ -125,8 +122,6 @@ public function instantSaveAdvanced()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
@@ -136,14 +131,14 @@ public function instantSave()
$this->dispatch('error', 'Public port is required.');
$this->isPublic = false;
- return null;
+ return;
}
if ($this->isPublic) {
if (! str($this->database->status)->startsWith('running')) {
$this->dispatch('error', 'Database must be started to be publicly accessible.');
$this->isPublic = false;
- return null;
+ return;
}
StartDatabaseProxy::run($this->database);
$this->dispatch('success', 'Database is now publicly accessible.');
@@ -153,14 +148,12 @@ public function instantSave()
}
$this->dbUrlPublic = $this->database->external_db_url;
$this->syncData(true);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->isPublic = ! $this->isPublic;
$this->syncData(true);
return handleError($e, $this);
}
-
- return null;
}
public function databaseProxyStopped()
@@ -185,7 +178,5 @@ public function submit()
$this->dispatch('configurationChanged');
}
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Database/CreateScheduledBackup.php b/app/Livewire/Project/Database/CreateScheduledBackup.php
index fa7d9f4af9..01108c2900 100644
--- a/app/Livewire/Project/Database/CreateScheduledBackup.php
+++ b/app/Livewire/Project/Database/CreateScheduledBackup.php
@@ -3,12 +3,10 @@
namespace App\Livewire\Project\Database;
use App\Models\ScheduledDatabaseBackup;
-use App\Models\ServiceDatabase;
use Illuminate\Support\Collection;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class CreateScheduledBackup extends Component
{
@@ -35,11 +33,9 @@ public function mount()
if ($this->definedS3s->count() > 0) {
$this->s3StorageId = $this->definedS3s->first()->id;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -51,7 +47,7 @@ public function submit()
if (! $isValid) {
$this->dispatch('error', 'Invalid Cron / Human expression.');
- return null;
+ return;
}
$payload = [
@@ -72,19 +68,17 @@ public function submit()
$payload['databases_to_backup'] = $this->database->mariadb_database;
}
- $databaseBackup = ScheduledDatabaseBackup::query()->create($payload);
- if ($this->database->getMorphClass() === ServiceDatabase::class) {
+ $databaseBackup = ScheduledDatabaseBackup::create($payload);
+ if ($this->database->getMorphClass() === \App\Models\ServiceDatabase::class) {
$this->dispatch('refreshScheduledBackups', $databaseBackup->id);
} else {
$this->dispatch('refreshScheduledBackups');
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->frequency = '';
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Database/Dragonfly/General.php b/app/Livewire/Project/Database/Dragonfly/General.php
index b5b85fee29..ea6cd46b04 100644
--- a/app/Livewire/Project/Database/Dragonfly/General.php
+++ b/app/Livewire/Project/Database/Dragonfly/General.php
@@ -10,7 +10,6 @@
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class General extends Component
{
@@ -65,11 +64,9 @@ public function mount()
try {
$this->syncData();
$this->server = data_get($this->database, 'destination.server');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -111,7 +108,7 @@ public function instantSaveAdvanced()
$this->isLogDrainEnabled = false;
$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');
- return null;
+ return;
}
$this->syncData(true);
@@ -120,8 +117,6 @@ public function instantSaveAdvanced()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
@@ -131,14 +126,14 @@ public function instantSave()
$this->dispatch('error', 'Public port is required.');
$this->isPublic = false;
- return null;
+ return;
}
if ($this->isPublic) {
if (! str($this->database->status)->startsWith('running')) {
$this->dispatch('error', 'Database must be started to be publicly accessible.');
$this->isPublic = false;
- return null;
+ return;
}
StartDatabaseProxy::run($this->database);
$this->dispatch('success', 'Database is now publicly accessible.');
@@ -148,14 +143,12 @@ public function instantSave()
}
$this->dbUrlPublic = $this->database->external_db_url;
$this->syncData(true);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->isPublic = ! $this->isPublic;
$this->syncData(true);
return handleError($e, $this);
}
-
- return null;
}
public function databaseProxyStopped()
@@ -180,7 +173,5 @@ public function submit()
$this->dispatch('configurationChanged');
}
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Database/Import.php b/app/Livewire/Project/Database/Import.php
index 699f0be6cc..dc330b3af8 100644
--- a/app/Livewire/Project/Database/Import.php
+++ b/app/Livewire/Project/Database/Import.php
@@ -3,18 +3,9 @@
namespace App\Livewire\Project\Database;
use App\Models\Server;
-use App\Models\StandaloneClickhouse;
-use App\Models\StandaloneDragonfly;
-use App\Models\StandaloneKeydb;
-use App\Models\StandaloneMariadb;
-use App\Models\StandaloneMongodb;
-use App\Models\StandaloneMysql;
-use App\Models\StandalonePostgresql;
-use App\Models\StandaloneRedis;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
-use Throwable;
class Import extends Component
{
@@ -81,7 +72,7 @@ public function mount()
public function updatedDumpAll($value)
{
switch ($this->resource->getMorphClass()) {
- case StandaloneMariadb::class:
+ case \App\Models\StandaloneMariadb::class:
if ($value === true) {
$this->mariadbRestoreCommand = <<<'EOD'
for pid in $(mariadb -u root -p$MARIADB_ROOT_PASSWORD -N -e "SELECT id FROM information_schema.processlist WHERE user != 'root';"); do
@@ -96,7 +87,7 @@ public function updatedDumpAll($value)
$this->mariadbRestoreCommand = 'mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE';
}
break;
- case StandaloneMysql::class:
+ case \App\Models\StandaloneMysql::class:
if ($value === true) {
$this->mysqlRestoreCommand = <<<'EOD'
for pid in $(mysql -u root -p$MYSQL_ROOT_PASSWORD -N -e "SELECT id FROM information_schema.processlist WHERE user != 'root';"); do
@@ -111,7 +102,7 @@ public function updatedDumpAll($value)
$this->mysqlRestoreCommand = 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE';
}
break;
- case StandalonePostgresql::class:
+ case \App\Models\StandalonePostgresql::class:
if ($value === true) {
$this->postgresqlRestoreCommand = <<<'EOD'
psql -U $POSTGRES_USER -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IS NOT NULL AND pid <> pg_backend_pid()" && \
@@ -145,10 +136,10 @@ public function getContainers()
}
if (
- $this->resource->getMorphClass() === StandaloneRedis::class ||
- $this->resource->getMorphClass() === StandaloneKeydb::class ||
- $this->resource->getMorphClass() === StandaloneDragonfly::class ||
- $this->resource->getMorphClass() === StandaloneClickhouse::class
+ $this->resource->getMorphClass() === \App\Models\StandaloneRedis::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneKeydb::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneDragonfly::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneClickhouse::class
) {
$this->unsupported = true;
}
@@ -162,16 +153,14 @@ public function checkFile()
if (blank($result)) {
$this->dispatch('error', 'The file does not exist or has been deleted.');
- return null;
+ return;
}
$this->filename = $this->customLocation;
$this->dispatch('success', 'The file exists.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
-
- return null;
}
public function runImport()
@@ -179,7 +168,7 @@ public function runImport()
if ($this->filename === '') {
$this->dispatch('error', 'Please select a file to import.');
- return null;
+ return;
}
try {
$this->importCommands = [];
@@ -193,7 +182,7 @@ public function runImport()
if (! Storage::exists($backupFileName)) {
$this->dispatch('error', 'The file does not exist or has been deleted.');
- return null;
+ return;
}
$tmpPath = '/tmp/'.basename($backupFileName).'_'.$this->resource->uuid;
instant_scp($path, $tmpPath, $this->server);
@@ -205,7 +194,7 @@ public function runImport()
$scriptPath = "/tmp/restore_{$this->resource->uuid}.sh";
switch ($this->resource->getMorphClass()) {
- case StandaloneMariadb::class:
+ case \App\Models\StandaloneMariadb::class:
$restoreCommand = $this->mariadbRestoreCommand;
if ($this->dumpAll) {
$restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | mariadb -u root -p\$MARIADB_ROOT_PASSWORD";
@@ -213,7 +202,7 @@ public function runImport()
$restoreCommand .= " < {$tmpPath}";
}
break;
- case StandaloneMysql::class:
+ case \App\Models\StandaloneMysql::class:
$restoreCommand = $this->mysqlRestoreCommand;
if ($this->dumpAll) {
$restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | mysql -u root -p\$MYSQL_ROOT_PASSWORD";
@@ -221,7 +210,7 @@ public function runImport()
$restoreCommand .= " < {$tmpPath}";
}
break;
- case StandalonePostgresql::class:
+ case \App\Models\StandalonePostgresql::class:
$restoreCommand = $this->postgresqlRestoreCommand;
if ($this->dumpAll) {
$restoreCommand .= " && (gunzip -cf {$tmpPath} 2>/dev/null || cat {$tmpPath}) | psql -U \$POSTGRES_USER postgres";
@@ -229,7 +218,7 @@ public function runImport()
$restoreCommand .= " {$tmpPath}";
}
break;
- case StandaloneMongodb::class:
+ case \App\Models\StandaloneMongodb::class:
$restoreCommand = $this->mongodbRestoreCommand;
if ($this->dumpAll === false) {
$restoreCommand .= " {$tmpPath}";
@@ -245,7 +234,7 @@ public function runImport()
$this->importCommands[] = "docker exec {$this->container} sh -c '{$scriptPath}'";
$this->importCommands[] = "docker exec {$this->container} sh -c 'echo \"Import finished with exit code $?\"'";
- if ($this->importCommands !== []) {
+ if (! empty($this->importCommands)) {
$activity = remote_process($this->importCommands, $this->server, ignore_errors: true, callEventOnFinish: 'RestoreJobFinished', callEventData: [
'scriptPath' => $scriptPath,
'tmpPath' => $tmpPath,
@@ -254,13 +243,11 @@ public function runImport()
]);
$this->dispatch('activityMonitor', $activity->id);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->filename = null;
$this->importCommands = [];
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Database/InitScript.php b/app/Livewire/Project/Database/InitScript.php
index 06b3138c53..e3baa1c8ee 100644
--- a/app/Livewire/Project/Database/InitScript.php
+++ b/app/Livewire/Project/Database/InitScript.php
@@ -30,8 +30,6 @@ public function mount()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -45,8 +43,6 @@ public function submit()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function delete()
@@ -56,7 +52,5 @@ public function delete()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Database/Keydb/General.php b/app/Livewire/Project/Database/Keydb/General.php
index fbeb66fc4c..e768495eb8 100644
--- a/app/Livewire/Project/Database/Keydb/General.php
+++ b/app/Livewire/Project/Database/Keydb/General.php
@@ -10,7 +10,6 @@
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class General extends Component
{
@@ -68,11 +67,9 @@ public function mount()
try {
$this->syncData();
$this->server = data_get($this->database, 'destination.server');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -116,7 +113,7 @@ public function instantSaveAdvanced()
$this->isLogDrainEnabled = false;
$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');
- return null;
+ return;
}
$this->syncData(true);
@@ -125,8 +122,6 @@ public function instantSaveAdvanced()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
@@ -136,14 +131,14 @@ public function instantSave()
$this->dispatch('error', 'Public port is required.');
$this->isPublic = false;
- return null;
+ return;
}
if ($this->isPublic) {
if (! str($this->database->status)->startsWith('running')) {
$this->dispatch('error', 'Database must be started to be publicly accessible.');
$this->isPublic = false;
- return null;
+ return;
}
StartDatabaseProxy::run($this->database);
$this->dispatch('success', 'Database is now publicly accessible.');
@@ -153,14 +148,12 @@ public function instantSave()
}
$this->dbUrlPublic = $this->database->external_db_url;
$this->syncData(true);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->isPublic = ! $this->isPublic;
$this->syncData(true);
return handleError($e, $this);
}
-
- return null;
}
public function databaseProxyStopped()
@@ -185,7 +178,5 @@ public function submit()
$this->dispatch('configurationChanged');
}
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Database/Mariadb/General.php b/app/Livewire/Project/Database/Mariadb/General.php
index 38a81026b9..c9d473223f 100644
--- a/app/Livewire/Project/Database/Mariadb/General.php
+++ b/app/Livewire/Project/Database/Mariadb/General.php
@@ -8,7 +8,6 @@
use App\Models\StandaloneMariadb;
use Exception;
use Livewire\Component;
-use Throwable;
class General extends Component
{
@@ -67,7 +66,7 @@ public function instantSaveAdvanced()
$this->database->is_log_drain_enabled = false;
$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');
- return null;
+ return;
}
$this->database->save();
$this->dispatch('success', 'Database updated.');
@@ -75,8 +74,6 @@ public function instantSaveAdvanced()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -97,8 +94,6 @@ public function submit()
$this->dispatch('configurationChanged');
}
}
-
- return null;
}
public function instantSave()
@@ -108,14 +103,14 @@ public function instantSave()
$this->dispatch('error', 'Public port is required.');
$this->database->is_public = false;
- return null;
+ return;
}
if ($this->database->is_public) {
if (! str($this->database->status)->startsWith('running')) {
$this->dispatch('error', 'Database must be started to be publicly accessible.');
$this->database->is_public = false;
- return null;
+ return;
}
StartDatabaseProxy::run($this->database);
$this->dispatch('success', 'Database is now publicly accessible.');
@@ -125,13 +120,11 @@ public function instantSave()
}
$this->db_url_public = $this->database->external_db_url;
$this->database->save();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->database->is_public = ! $this->database->is_public;
return handleError($e, $this);
}
-
- return null;
}
public function refresh(): void
diff --git a/app/Livewire/Project/Database/Mongodb/General.php b/app/Livewire/Project/Database/Mongodb/General.php
index 1cc777022d..e19895dae6 100644
--- a/app/Livewire/Project/Database/Mongodb/General.php
+++ b/app/Livewire/Project/Database/Mongodb/General.php
@@ -8,7 +8,6 @@
use App\Models\StandaloneMongodb;
use Exception;
use Livewire\Component;
-use Throwable;
class General extends Component
{
@@ -65,7 +64,7 @@ public function instantSaveAdvanced()
$this->database->is_log_drain_enabled = false;
$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');
- return null;
+ return;
}
$this->database->save();
$this->dispatch('success', 'Database updated.');
@@ -73,8 +72,6 @@ public function instantSaveAdvanced()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -98,8 +95,6 @@ public function submit()
$this->dispatch('configurationChanged');
}
}
-
- return null;
}
public function instantSave()
@@ -109,14 +104,14 @@ public function instantSave()
$this->dispatch('error', 'Public port is required.');
$this->database->is_public = false;
- return null;
+ return;
}
if ($this->database->is_public) {
if (! str($this->database->status)->startsWith('running')) {
$this->dispatch('error', 'Database must be started to be publicly accessible.');
$this->database->is_public = false;
- return null;
+ return;
}
StartDatabaseProxy::run($this->database);
$this->dispatch('success', 'Database is now publicly accessible.');
@@ -126,13 +121,11 @@ public function instantSave()
}
$this->db_url_public = $this->database->external_db_url;
$this->database->save();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->database->is_public = ! $this->database->is_public;
return handleError($e, $this);
}
-
- return null;
}
public function refresh(): void
diff --git a/app/Livewire/Project/Database/Mysql/General.php b/app/Livewire/Project/Database/Mysql/General.php
index afcb8077f0..7d5270ddf5 100644
--- a/app/Livewire/Project/Database/Mysql/General.php
+++ b/app/Livewire/Project/Database/Mysql/General.php
@@ -8,7 +8,6 @@
use App\Models\StandaloneMysql;
use Exception;
use Livewire\Component;
-use Throwable;
class General extends Component
{
@@ -67,7 +66,7 @@ public function instantSaveAdvanced()
$this->database->is_log_drain_enabled = false;
$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');
- return null;
+ return;
}
$this->database->save();
$this->dispatch('success', 'Database updated.');
@@ -75,8 +74,6 @@ public function instantSaveAdvanced()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -97,8 +94,6 @@ public function submit()
$this->dispatch('configurationChanged');
}
}
-
- return null;
}
public function instantSave()
@@ -108,14 +103,14 @@ public function instantSave()
$this->dispatch('error', 'Public port is required.');
$this->database->is_public = false;
- return null;
+ return;
}
if ($this->database->is_public) {
if (! str($this->database->status)->startsWith('running')) {
$this->dispatch('error', 'Database must be started to be publicly accessible.');
$this->database->is_public = false;
- return null;
+ return;
}
StartDatabaseProxy::run($this->database);
$this->dispatch('success', 'Database is now publicly accessible.');
@@ -125,13 +120,11 @@ public function instantSave()
}
$this->db_url_public = $this->database->external_db_url;
$this->database->save();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->database->is_public = ! $this->database->is_public;
return handleError($e, $this);
}
-
- return null;
}
public function refresh(): void
diff --git a/app/Livewire/Project/Database/Postgresql/General.php b/app/Livewire/Project/Database/Postgresql/General.php
index 17502f8171..88dd5c1a86 100644
--- a/app/Livewire/Project/Database/Postgresql/General.php
+++ b/app/Livewire/Project/Database/Postgresql/General.php
@@ -8,7 +8,6 @@
use App\Models\StandalonePostgresql;
use Exception;
use Livewire\Component;
-use Throwable;
class General extends Component
{
@@ -82,7 +81,7 @@ public function instantSaveAdvanced()
$this->database->is_log_drain_enabled = false;
$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');
- return null;
+ return;
}
$this->database->save();
$this->dispatch('success', 'Database updated.');
@@ -90,8 +89,6 @@ public function instantSaveAdvanced()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
@@ -101,14 +98,14 @@ public function instantSave()
$this->dispatch('error', 'Public port is required.');
$this->database->is_public = false;
- return null;
+ return;
}
if ($this->database->is_public) {
if (! str($this->database->status)->startsWith('running')) {
$this->dispatch('error', 'Database must be started to be publicly accessible.');
$this->database->is_public = false;
- return null;
+ return;
}
StartDatabaseProxy::run($this->database);
$this->dispatch('success', 'Database is now publicly accessible.');
@@ -118,13 +115,11 @@ public function instantSave()
}
$this->db_url_public = $this->database->external_db_url;
$this->database->save();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->database->is_public = ! $this->database->is_public;
return handleError($e, $this);
}
-
- return null;
}
public function save_init_script($script)
@@ -148,7 +143,7 @@ public function save_init_script($script)
$delete_command = "rm -f $old_file_path";
try {
instant_remote_process([$delete_command], $this->server);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->dispatch('error', 'Failed to remove old init script from server: '.$e->getMessage());
return;
@@ -189,7 +184,7 @@ public function delete_init_script($script)
$command = "rm -f $file_path";
try {
instant_remote_process([$command], $this->server);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->dispatch('error', 'Failed to remove init script from server: '.$e->getMessage());
return;
@@ -228,7 +223,7 @@ public function save_new_init_script()
return;
}
- if (! property_exists($this->database, 'init_scripts') || $this->database->init_scripts === null) {
+ if (! isset($this->database->init_scripts)) {
$this->database->init_scripts = [];
}
$this->database->init_scripts = array_merge($this->database->init_scripts, [
@@ -262,7 +257,5 @@ public function submit()
$this->dispatch('configurationChanged');
}
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Database/Redis/General.php b/app/Livewire/Project/Database/Redis/General.php
index ff7e55a66f..25a96b2926 100644
--- a/app/Livewire/Project/Database/Redis/General.php
+++ b/app/Livewire/Project/Database/Redis/General.php
@@ -8,7 +8,6 @@
use App\Models\StandaloneRedis;
use Exception;
use Livewire\Component;
-use Throwable;
class General extends Component
{
@@ -71,7 +70,7 @@ public function instantSaveAdvanced()
$this->database->is_log_drain_enabled = false;
$this->dispatch('error', 'Log drain is not enabled on the server. Please enable it first.');
- return null;
+ return;
}
$this->database->save();
$this->dispatch('success', 'Database updated.');
@@ -79,8 +78,6 @@ public function instantSaveAdvanced()
} catch (Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -106,8 +103,6 @@ public function submit()
} finally {
$this->dispatch('refreshEnvs');
}
-
- return null;
}
public function instantSave()
@@ -117,14 +112,14 @@ public function instantSave()
$this->dispatch('error', 'Public port is required.');
$this->database->is_public = false;
- return null;
+ return;
}
if ($this->database->is_public) {
if (! str($this->database->status)->startsWith('running')) {
$this->dispatch('error', 'Database must be started to be publicly accessible.');
$this->database->is_public = false;
- return null;
+ return;
}
StartDatabaseProxy::run($this->database);
$this->dispatch('success', 'Database is now publicly accessible.');
@@ -134,13 +129,11 @@ public function instantSave()
}
$this->db_url_public = $this->database->external_db_url;
$this->database->save();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->database->is_public = ! $this->database->is_public;
return handleError($e, $this);
}
-
- return null;
}
public function refresh(): void
diff --git a/app/Livewire/Project/Database/ScheduledBackups.php b/app/Livewire/Project/Database/ScheduledBackups.php
index a6fa103b8d..412240bd4e 100644
--- a/app/Livewire/Project/Database/ScheduledBackups.php
+++ b/app/Livewire/Project/Database/ScheduledBackups.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Project\Database;
use App\Models\ScheduledDatabaseBackup;
-use App\Models\ServiceDatabase;
use Livewire\Component;
class ScheduledBackups extends Component
@@ -30,7 +29,11 @@ public function mount(): void
$this->setSelectedBackup($this->selectedBackupId, true);
}
$this->parameters = get_route_parameters();
- $this->type = $this->database->getMorphClass() === ServiceDatabase::class ? 'service-database' : 'database';
+ if ($this->database->getMorphClass() === \App\Models\ServiceDatabase::class) {
+ $this->type = 'service-database';
+ } else {
+ $this->type = 'database';
+ }
$this->s3s = currentTeam()->s3s;
}
diff --git a/app/Livewire/Project/DeleteEnvironment.php b/app/Livewire/Project/DeleteEnvironment.php
index e27b89be88..1ee5de2691 100644
--- a/app/Livewire/Project/DeleteEnvironment.php
+++ b/app/Livewire/Project/DeleteEnvironment.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Project;
use App\Models\Environment;
-use Exception;
use Livewire\Component;
class DeleteEnvironment extends Component
@@ -19,13 +18,11 @@ class DeleteEnvironment extends Component
public function mount()
{
try {
- $this->environmentName = Environment::query()->findOrFail($this->environment_id)->name;
+ $this->environmentName = Environment::findOrFail($this->environment_id)->name;
$this->parameters = get_route_parameters();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function delete()
@@ -33,7 +30,7 @@ public function delete()
$this->validate([
'environment_id' => 'required|int',
]);
- $environment = Environment::query()->findOrFail($this->environment_id);
+ $environment = Environment::findOrFail($this->environment_id);
if ($environment->isEmpty()) {
$environment->delete();
diff --git a/app/Livewire/Project/DeleteProject.php b/app/Livewire/Project/DeleteProject.php
index bade13e6fb..f320a19b0f 100644
--- a/app/Livewire/Project/DeleteProject.php
+++ b/app/Livewire/Project/DeleteProject.php
@@ -18,7 +18,7 @@ class DeleteProject extends Component
public function mount()
{
$this->parameters = get_route_parameters();
- $this->projectName = Project::query()->findOrFail($this->project_id)->name;
+ $this->projectName = Project::findOrFail($this->project_id)->name;
}
public function delete()
@@ -26,7 +26,7 @@ public function delete()
$this->validate([
'project_id' => 'required|int',
]);
- $project = Project::query()->findOrFail($this->project_id);
+ $project = Project::findOrFail($this->project_id);
if ($project->isEmpty()) {
$project->delete();
diff --git a/app/Livewire/Project/Edit.php b/app/Livewire/Project/Edit.php
index c9f83304b0..463febb10d 100644
--- a/app/Livewire/Project/Edit.php
+++ b/app/Livewire/Project/Edit.php
@@ -5,7 +5,6 @@
use App\Models\Project;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Edit extends Component
{
@@ -20,13 +19,11 @@ class Edit extends Component
public function mount(string $project_uuid)
{
try {
- $this->project = Project::query()->where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail();
+ $this->project = Project::where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail();
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -48,10 +45,8 @@ public function submit()
try {
$this->syncData(true);
$this->dispatch('success', 'Project updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/EnvironmentEdit.php b/app/Livewire/Project/EnvironmentEdit.php
index 7e93a5fcac..e98b088ecf 100644
--- a/app/Livewire/Project/EnvironmentEdit.php
+++ b/app/Livewire/Project/EnvironmentEdit.php
@@ -7,7 +7,6 @@
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class EnvironmentEdit extends Component
{
@@ -30,11 +29,9 @@ public function mount(string $project_uuid, string $environment_uuid)
$this->project = Project::ownedByCurrentTeam()->where('uuid', $project_uuid)->firstOrFail();
$this->environment = $this->project->environments()->where('uuid', $environment_uuid)->firstOrFail();
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -59,11 +56,9 @@ public function submit()
'environment_uuid' => $this->environment->uuid,
'project_uuid' => $this->project->uuid,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Index.php b/app/Livewire/Project/Index.php
index 75597d8f5c..06bf88219b 100644
--- a/app/Livewire/Project/Index.php
+++ b/app/Livewire/Project/Index.php
@@ -34,7 +34,7 @@ public function render()
public function navigateToProject($projectUuid)
{
- $project = Project::query()->where('uuid', $projectUuid)->first();
+ $project = Project::where('uuid', $projectUuid)->first();
if ($project && $project->environments->count() === 1) {
return Redirect::route('project.resource.index', [
diff --git a/app/Livewire/Project/New/DockerCompose.php b/app/Livewire/Project/New/DockerCompose.php
index d8425e34fe..27975eaa2b 100644
--- a/app/Livewire/Project/New/DockerCompose.php
+++ b/app/Livewire/Project/New/DockerCompose.php
@@ -7,11 +7,9 @@
use App\Models\Service;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
-use Exception;
use Illuminate\Support\Str;
use Livewire\Component;
use Symfony\Component\Yaml\Yaml;
-use Throwable;
class DockerCompose extends Component
{
@@ -60,20 +58,20 @@ public function submit()
return $this->dispatch('error', "Invalid docker-compose file.\n$isValid");
}
- $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();
+ $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
$destination_uuid = $this->query['destination'];
- $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (! $destination) {
- $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (! $destination) {
- throw new Exception('Destination not found. What?!');
+ throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
- $service = Service::query()->create([
+ $service = Service::create([
'name' => 'service'.Str::random(10),
'docker_compose_raw' => $this->dockerComposeRaw,
'environment_id' => $environment->id,
@@ -84,7 +82,7 @@ public function submit()
$variables = parseEnvFormatToArray($this->envFile);
foreach ($variables as $key => $variable) {
- EnvironmentVariable::query()->create([
+ EnvironmentVariable::create([
'key' => $key,
'value' => $variable,
'is_build_time' => false,
@@ -102,7 +100,7 @@ public function submit()
'environment_uuid' => $environment->uuid,
'project_uuid' => $project->uuid,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Project/New/DockerImage.php b/app/Livewire/Project/New/DockerImage.php
index cd8f7c4ece..9429244377 100644
--- a/app/Livewire/Project/New/DockerImage.php
+++ b/app/Livewire/Project/New/DockerImage.php
@@ -6,7 +6,6 @@
use App\Models\Project;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
-use Exception;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
@@ -29,28 +28,32 @@ public function submit()
$this->validate([
'dockerImage' => 'required',
]);
- $stringable = str($this->dockerImage)->before(':');
- $tag = str($this->dockerImage)->contains(':') ? str($this->dockerImage)->after(':') : 'latest';
+ $image = str($this->dockerImage)->before(':');
+ if (str($this->dockerImage)->contains(':')) {
+ $tag = str($this->dockerImage)->after(':');
+ } else {
+ $tag = 'latest';
+ }
$destination_uuid = $this->query['destination'];
- $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (! $destination) {
- $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (! $destination) {
- throw new Exception('Destination not found. What?!');
+ throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
- $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();
+ $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
- $application = Application::query()->create([
+ $application = Application::create([
'name' => 'docker-image-'.new Cuid2,
'repository_project_id' => 0,
'git_repository' => 'coollabsio/coolify',
'git_branch' => 'main',
'build_pack' => 'dockerimage',
'ports_exposes' => 80,
- 'docker_registry_image_name' => $stringable,
+ 'docker_registry_image_name' => $image,
'docker_registry_image_tag' => $tag,
'environment_id' => $environment->id,
'destination_id' => $destination->id,
diff --git a/app/Livewire/Project/New/EmptyProject.php b/app/Livewire/Project/New/EmptyProject.php
index 2f1eda3f7f..54cfc4b4d8 100644
--- a/app/Livewire/Project/New/EmptyProject.php
+++ b/app/Livewire/Project/New/EmptyProject.php
@@ -10,7 +10,7 @@ class EmptyProject extends Component
{
public function createEmptyProject()
{
- $project = Project::query()->create([
+ $project = Project::create([
'name' => generate_random_name(),
'team_id' => currentTeam()->id,
'uuid' => (string) new Cuid2,
diff --git a/app/Livewire/Project/New/GithubPrivateRepository.php b/app/Livewire/Project/New/GithubPrivateRepository.php
index 3363e596bd..370d005557 100644
--- a/app/Livewire/Project/New/GithubPrivateRepository.php
+++ b/app/Livewire/Project/New/GithubPrivateRepository.php
@@ -7,11 +7,9 @@
use App\Models\Project;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
-use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
-use Throwable;
class GithubPrivateRepository extends Component
{
@@ -106,7 +104,7 @@ public function loadRepositories($github_app_id)
$this->repositories = collect();
$this->page = 1;
$this->selected_github_app_id = $github_app_id;
- $this->github_app = GithubApp::query()->where('id', $github_app_id)->first();
+ $this->github_app = GithubApp::where('id', $github_app_id)->first();
$this->token = generate_github_installation_token($this->github_app);
$this->loadRepositoryByPage();
if ($this->repositories->count() < $this->total_repositories_count) {
@@ -131,12 +129,10 @@ protected function loadRepositoryByPage()
}
if ($json['total_count'] === 0) {
- return null;
+ return;
}
$this->total_repositories_count = $json['total_count'];
$this->repositories = $this->repositories->concat(collect($json['repositories']));
-
- return null;
}
public function loadBranches()
@@ -165,27 +161,25 @@ protected function loadBranchByPage()
$this->total_branches_count = count($json);
$this->branches = $this->branches->concat(collect($json));
-
- return null;
}
public function submit()
{
try {
$destination_uuid = $this->query['destination'];
- $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (! $destination) {
- $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (! $destination) {
- throw new Exception('Destination not found. What?!');
+ throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
- $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();
+ $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
- $application = Application::query()->create([
+ $application = Application::create([
'name' => generate_application_name($this->selected_repository_owner.'/'.$this->selected_repository_repo, $this->selected_branch_name),
'repository_project_id' => $this->selected_repository_id,
'git_repository' => "{$this->selected_repository_owner}/{$this->selected_repository_repo}",
@@ -220,7 +214,7 @@ public function submit()
'environment_uuid' => $environment->uuid,
'project_uuid' => $project->uuid,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php b/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php
index 74ef258734..01b0c9ae85 100644
--- a/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php
+++ b/app/Livewire/Project/New/GithubPrivateRepositoryDeployKey.php
@@ -9,11 +9,9 @@
use App\Models\Project;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
-use Exception;
use Illuminate\Support\Str;
use Livewire\Component;
use Spatie\Url\Url;
-use Throwable;
class GithubPrivateRepositoryDeployKey extends Component
{
@@ -83,9 +81,9 @@ public function mount()
$this->parameters = get_route_parameters();
$this->query = request()->query();
if (isDev()) {
- $this->private_keys = PrivateKey::query()->where('team_id', currentTeam()->id)->get();
+ $this->private_keys = PrivateKey::where('team_id', currentTeam()->id)->get();
} else {
- $this->private_keys = PrivateKey::query()->where('team_id', currentTeam()->id)->where('id', '!=', 0)->get();
+ $this->private_keys = PrivateKey::where('team_id', currentTeam()->id)->where('id', '!=', 0)->get();
}
}
@@ -126,18 +124,18 @@ public function submit()
$this->validate();
try {
$destination_uuid = $this->query['destination'];
- $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (! $destination) {
- $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (! $destination) {
- throw new Exception('Destination not found. What?!');
+ throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
$this->get_git_source();
- $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();
+ $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
if ($this->git_source === 'other') {
$application_init = [
@@ -175,7 +173,7 @@ public function submit()
$application_init['docker_compose_location'] = $this->docker_compose_location;
$application_init['base_directory'] = $this->base_directory;
}
- $application = Application::query()->create($application_init);
+ $application = Application::create($application_init);
$application->settings->is_static = $this->is_static;
$application->settings->save();
@@ -189,7 +187,7 @@ public function submit()
'environment_uuid' => $environment->uuid,
'project_uuid' => $project->uuid,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
@@ -201,7 +199,7 @@ private function get_git_source()
$this->git_repository = $this->repository_url_parsed->getSegment(1).'/'.$this->repository_url_parsed->getSegment(2);
if ($this->git_host === 'github.com') {
- $this->git_source = GithubApp::query()->where('name', 'Public GitHub')->first();
+ $this->git_source = GithubApp::where('name', 'Public GitHub')->first();
return;
}
diff --git a/app/Livewire/Project/New/PublicGitRepository.php b/app/Livewire/Project/New/PublicGitRepository.php
index 31866c936f..2f2331fc00 100644
--- a/app/Livewire/Project/New/PublicGitRepository.php
+++ b/app/Livewire/Project/New/PublicGitRepository.php
@@ -10,10 +10,8 @@
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
use Carbon\Carbon;
-use Exception;
use Livewire\Component;
use Spatie\Url\Url;
-use Throwable;
class PublicGitRepository extends Component
{
@@ -95,7 +93,7 @@ public function mount()
public function updatedBaseDirectory()
{
- if ($this->base_directory !== '' && $this->base_directory !== '0') {
+ if ($this->base_directory) {
$this->base_directory = rtrim($this->base_directory, '/');
if (! str($this->base_directory)->startsWith('/')) {
$this->base_directory = '/'.$this->base_directory;
@@ -155,12 +153,12 @@ public function loadBranch()
(! str($this->repository_url)->contains('github.com') ||
! str($this->repository_url)->contains('git.sr.ht'))
) {
- $this->repository_url .= '.git';
+ $this->repository_url = $this->repository_url.'.git';
}
if (str($this->repository_url)->contains('github.com') && str($this->repository_url)->endsWith('.git')) {
$this->repository_url = str($this->repository_url)->beforeLast('.git')->value();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
try {
@@ -168,26 +166,24 @@ public function loadBranch()
$this->getGitSource();
$this->getBranch();
$this->selectedBranch = $this->git_branch;
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
if ($this->rate_limit_remaining == 0) {
$this->selectedBranch = $this->git_branch;
$this->branchFound = true;
- return null;
+ return;
}
if (! $this->branchFound && $this->git_branch === 'main') {
try {
$this->git_branch = 'master';
$this->getBranch();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
} else {
return handleError($e, $this);
}
}
-
- return null;
}
private function getGitSource()
@@ -201,7 +197,7 @@ private function getGitSource()
$this->git_branch = 'main';
}
if ($this->git_host === 'github.com') {
- $this->git_source = GithubApp::query()->where('name', 'Public GitHub')->first();
+ $this->git_source = GithubApp::where('name', 'Public GitHub')->first();
return;
}
@@ -216,7 +212,7 @@ private function getBranch()
return;
}
- if ($this->git_source->getMorphClass() === GithubApp::class) {
+ if ($this->git_source->getMorphClass() === \App\Models\GithubApp::class) {
['rate_limit_remaining' => $this->rate_limit_remaining, 'rate_limit_reset' => $this->rate_limit_reset] = githubApi(source: $this->git_source, endpoint: "/repos/{$this->git_repository}/branches/{$this->git_branch}");
$this->rate_limit_reset = Carbon::parse((int) $this->rate_limit_reset)->format('Y-M-d H:i:s');
$this->branchFound = true;
@@ -231,16 +227,16 @@ public function submit()
$project_uuid = $this->parameters['project_uuid'];
$environment_uuid = $this->parameters['environment_uuid'];
- $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (! $destination) {
- $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (! $destination) {
- throw new Exception('Destination not found. What?!');
+ throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
- $project = Project::query()->where('uuid', $project_uuid)->first();
+ $project = Project::where('uuid', $project_uuid)->first();
$environment = $project->load(['environments'])->environments->where('uuid', $environment_uuid)->first();
if ($this->build_pack === 'dockercompose' && isDev() && $this->new_compose_services) {
@@ -260,13 +256,15 @@ public function submit()
$new_service['source_id'] = $this->git_source->id;
$new_service['source_type'] = $this->git_source->getMorphClass();
}
- $service = Service::query()->create($new_service);
+ $service = Service::create($new_service);
return redirect()->route('project.service.configuration', [
'service_uuid' => $service->uuid,
'environment_uuid' => $environment->uuid,
'project_uuid' => $project->uuid,
]);
+
+ return;
}
if ($this->git_source === 'other') {
$application_init = [
@@ -305,7 +303,7 @@ public function submit()
$application_init['docker_compose_location'] = $this->docker_compose_location;
$application_init['base_directory'] = $this->base_directory;
}
- $application = Application::query()->create($application_init);
+ $application = Application::create($application_init);
$application->settings->is_static = $this->isStatic;
$application->settings->save();
@@ -324,7 +322,7 @@ public function submit()
'environment_uuid' => $environment->uuid,
'project_uuid' => $project->uuid,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Project/New/Select.php b/app/Livewire/Project/New/Select.php
index e05f53230e..b645a89150 100644
--- a/app/Livewire/Project/New/Select.php
+++ b/app/Livewire/Project/New/Select.php
@@ -205,10 +205,12 @@ public function instantSave()
{
if ($this->includeSwarm) {
$this->servers = $this->allServers;
- } elseif ($this->allServers instanceof Collection) {
- $this->servers = $this->allServers->where('settings.is_swarm_worker', false)->where('settings.is_swarm_manager', false)->where('settings.is_build_server', false);
} else {
- $this->servers = $this->allServers;
+ if ($this->allServers instanceof Collection) {
+ $this->servers = $this->allServers->where('settings.is_swarm_worker', false)->where('settings.is_swarm_manager', false)->where('settings.is_build_server', false);
+ } else {
+ $this->servers = $this->allServers;
+ }
}
}
@@ -216,7 +218,7 @@ public function setType(string $type)
{
$type = str($type)->lower()->slug()->value();
if ($this->loading) {
- return null;
+ return;
}
$this->loading = true;
$this->type = $type;
@@ -250,7 +252,7 @@ public function setType(string $type)
if ($type === 'existing-postgresql') {
$this->current_step = $type;
- return null;
+ return;
}
if (count($this->servers) === 1) {
$server = $this->servers->first();
@@ -265,8 +267,6 @@ public function setType(string $type)
}
}
$this->current_step = 'servers';
-
- return null;
}
public function setServer(Server $server)
@@ -285,8 +285,6 @@ public function setServer(Server $server)
}
}
$this->current_step = 'destinations';
-
- return null;
}
public function setDestination(string $destination_uuid)
@@ -323,8 +321,6 @@ public function whatToDoNext()
'server_id' => $this->server_id,
]);
}
-
- return null;
}
public function loadServers()
diff --git a/app/Livewire/Project/New/SimpleDockerfile.php b/app/Livewire/Project/New/SimpleDockerfile.php
index f40c36bac1..c3ed6039a0 100644
--- a/app/Livewire/Project/New/SimpleDockerfile.php
+++ b/app/Livewire/Project/New/SimpleDockerfile.php
@@ -7,7 +7,6 @@
use App\Models\Project;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
-use Exception;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
@@ -37,23 +36,23 @@ public function submit()
'dockerfile' => 'required',
]);
$destination_uuid = $this->query['destination'];
- $destination = StandaloneDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (! $destination) {
- $destination = SwarmDocker::query()->where('uuid', $destination_uuid)->first();
+ $destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (! $destination) {
- throw new Exception('Destination not found. What?!');
+ throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
- $project = Project::query()->where('uuid', $this->parameters['project_uuid'])->first();
+ $project = Project::where('uuid', $this->parameters['project_uuid'])->first();
$environment = $project->load(['environments'])->environments->where('uuid', $this->parameters['environment_uuid'])->first();
$port = get_port_from_dockerfile($this->dockerfile);
if (! $port) {
$port = 80;
}
- $application = Application::query()->create([
+ $application = Application::create([
'name' => 'dockerfile-'.new Cuid2,
'repository_project_id' => 0,
'git_repository' => 'coollabsio/coolify',
diff --git a/app/Livewire/Project/Resource/Create.php b/app/Livewire/Project/Resource/Create.php
index ac177b0b37..0faf0b8da2 100644
--- a/app/Livewire/Project/Resource/Create.php
+++ b/app/Livewire/Project/Resource/Create.php
@@ -67,7 +67,7 @@ public function mount()
$oneClickDotEnvs = data_get($services, "$oneClickServiceName.envs", null);
if ($oneClickDotEnvs) {
$oneClickDotEnvs = str(base64_decode($oneClickDotEnvs))->split('/\r\n|\r|\n/')->filter(function ($value) {
- return $value !== '' && $value !== '0';
+ return ! empty($value);
});
}
if ($oneClickService) {
@@ -84,7 +84,7 @@ public function mount()
if ($oneClickServiceName === 'cloudflared') {
data_set($service_payload, 'connect_to_docker_network', true);
}
- $service = Service::query()->create($service_payload);
+ $service = Service::create($service_payload);
$service->name = "$oneClickServiceName-".$service->uuid;
$service->save();
if ($oneClickDotEnvs?->count() > 0) {
@@ -92,7 +92,7 @@ public function mount()
$key = str()->before($value, '=');
$value = str(str()->after($value, '='));
if ($value) {
- EnvironmentVariable::query()->create([
+ EnvironmentVariable::create([
'key' => $key,
'value' => $value,
'resourceable_id' => $service->id,
@@ -114,8 +114,6 @@ public function mount()
}
$this->type = $type->value();
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Resource/EnvironmentSelect.php b/app/Livewire/Project/Resource/EnvironmentSelect.php
index e7c2c2bd61..a38d750daa 100644
--- a/app/Livewire/Project/Resource/EnvironmentSelect.php
+++ b/app/Livewire/Project/Resource/EnvironmentSelect.php
@@ -25,11 +25,11 @@ public function updatedSelectedEnvironment($value)
return redirect()->route('project.show', [
'project_uuid' => $this->project_uuid,
]);
+ } else {
+ return redirect()->route('project.resource.index', [
+ 'project_uuid' => $this->project_uuid,
+ 'environment_uuid' => $value,
+ ]);
}
-
- return redirect()->route('project.resource.index', [
- 'project_uuid' => $this->project_uuid,
- 'environment_uuid' => $value,
- ]);
}
}
diff --git a/app/Livewire/Project/Service/Configuration.php b/app/Livewire/Project/Service/Configuration.php
index a1f1d0aa5a..4a5e8627fa 100644
--- a/app/Livewire/Project/Service/Configuration.php
+++ b/app/Livewire/Project/Service/Configuration.php
@@ -4,7 +4,6 @@
use App\Actions\Docker\GetContainersStatus;
use App\Models\Service;
-use Exception;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
@@ -72,11 +71,9 @@ public function restartApplication($id)
$application->restart();
$this->dispatch('success', 'Service application restarted successfully.');
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function restartDatabase($id)
@@ -87,11 +84,9 @@ public function restartDatabase($id)
$database->restart();
$this->dispatch('success', 'Service database restarted successfully.');
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function check_status()
@@ -105,10 +100,8 @@ public function check_status()
$database->refresh();
});
$this->dispatch('$refresh');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Service/Database.php b/app/Livewire/Project/Service/Database.php
index 88bedd3b4b..9f02db05c8 100644
--- a/app/Livewire/Project/Service/Database.php
+++ b/app/Livewire/Project/Service/Database.php
@@ -6,7 +6,6 @@
use App\Actions\Database\StopDatabaseProxy;
use App\Models\ServiceDatabase;
use Livewire\Component;
-use Throwable;
class Database extends Component
{
@@ -96,7 +95,7 @@ public function submit()
$this->database->save();
updateCompose($this->database);
$this->dispatch('success', 'Database saved.');
- } catch (Throwable) {
+ } catch (\Throwable) {
} finally {
$this->dispatch('generateDockerCompose');
}
diff --git a/app/Livewire/Project/Service/EditCompose.php b/app/Livewire/Project/Service/EditCompose.php
index 3b8b7d1556..dc043e65ad 100644
--- a/app/Livewire/Project/Service/EditCompose.php
+++ b/app/Livewire/Project/Service/EditCompose.php
@@ -31,12 +31,12 @@ public function envsUpdated()
public function refreshEnvs()
{
- $this->service = Service::query()->find($this->serviceId);
+ $this->service = Service::find($this->serviceId);
}
public function mount()
{
- $this->service = Service::query()->find($this->serviceId);
+ $this->service = Service::find($this->serviceId);
}
public function saveEditedCompose()
diff --git a/app/Livewire/Project/Service/EditDomain.php b/app/Livewire/Project/Service/EditDomain.php
index dbc5ca2ff9..e89aeda85f 100644
--- a/app/Livewire/Project/Service/EditDomain.php
+++ b/app/Livewire/Project/Service/EditDomain.php
@@ -5,7 +5,6 @@
use App\Models\ServiceApplication;
use Livewire\Component;
use Spatie\Url\Url;
-use Throwable;
class EditDomain extends Component
{
@@ -20,7 +19,7 @@ class EditDomain extends Component
public function mount()
{
- $this->application = ServiceApplication::query()->find($this->applicationId);
+ $this->application = ServiceApplication::find($this->applicationId);
}
public function submit()
@@ -44,13 +43,13 @@ public function submit()
updateCompose($this->application);
if (str($this->application->fqdn)->contains(',')) {
$this->dispatch('warning', 'Some services do not support multiple domains, which can lead to problems and is NOT RECOMMENDED.
Only use multiple domains if you know what you are doing.');
- } elseif (! $warning) {
- $this->dispatch('success', 'Service saved.');
+ } else {
+ ! $warning && $this->dispatch('success', 'Service saved.');
}
$this->application->service->parse();
$this->dispatch('refresh');
$this->dispatch('configurationChanged');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$originalFqdn = $this->application->getOriginal('fqdn');
if ($originalFqdn !== $this->application->fqdn) {
$this->application->fqdn = $originalFqdn;
@@ -58,8 +57,6 @@ public function submit()
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Service/FileStorage.php b/app/Livewire/Project/Service/FileStorage.php
index 83b05acb15..4d070bc0cc 100644
--- a/app/Livewire/Project/Service/FileStorage.php
+++ b/app/Livewire/Project/Service/FileStorage.php
@@ -18,7 +18,6 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
-use Throwable;
class FileStorage extends Component
{
@@ -62,13 +61,11 @@ public function convertToDirectory()
$this->fileStorage->is_based_on_git = false;
$this->fileStorage->save();
$this->fileStorage->saveStorageOnServer();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->dispatch('refreshStorages');
}
-
- return null;
}
public function convertToFile()
@@ -82,21 +79,21 @@ public function convertToFile()
}
$this->fileStorage->save();
$this->fileStorage->saveStorageOnServer();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->dispatch('refreshStorages');
}
-
- return null;
}
public function delete($password)
{
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return null;
+ return;
+ }
}
try {
@@ -110,13 +107,11 @@ public function delete($password)
}
$this->fileStorage->delete();
$this->dispatch('success', $message);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->dispatch('refreshStorages');
}
-
- return null;
}
public function submit()
@@ -130,14 +125,12 @@ public function submit()
$this->fileStorage->save();
$this->fileStorage->saveStorageOnServer();
$this->dispatch('success', 'File updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->fileStorage->setRawAttributes($original);
$this->fileStorage->save();
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
diff --git a/app/Livewire/Project/Service/Index.php b/app/Livewire/Project/Service/Index.php
index 38a2aad2d1..ba4ebe2fca 100644
--- a/app/Livewire/Project/Service/Index.php
+++ b/app/Livewire/Project/Service/Index.php
@@ -7,7 +7,6 @@
use App\Models\ServiceDatabase;
use Illuminate\Support\Collection;
use Livewire\Component;
-use Throwable;
class Index extends Component
{
@@ -46,11 +45,9 @@ public function mount()
$this->serviceDatabase->getFilesFromServer();
}
$this->s3s = currentTeam()->s3s;
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function generateDockerCompose()
diff --git a/app/Livewire/Project/Service/Navbar.php b/app/Livewire/Project/Service/Navbar.php
index 0fc9207795..22fc1c0d6b 100644
--- a/app/Livewire/Project/Service/Navbar.php
+++ b/app/Livewire/Project/Service/Navbar.php
@@ -10,7 +10,6 @@
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Spatie\Activitylog\Models\Activity;
-use Throwable;
class Navbar extends Component
{
@@ -71,10 +70,14 @@ public function checkDeployments()
try {
// TODO: This is a temporary solution. We need to refactor this.
// We need to delete null bytes somehow.
- $activity = Activity::query()->where('properties->type_uuid', $this->service->uuid)->latest()->first();
+ $activity = Activity::where('properties->type_uuid', $this->service->uuid)->latest()->first();
$status = data_get($activity, 'properties.status');
- $this->isDeploymentProgress = $status === 'queued' || $status === 'in_progress';
- } catch (Throwable) {
+ if ($status === 'queued' || $status === 'in_progress') {
+ $this->isDeploymentProgress = true;
+ } else {
+ $this->isDeploymentProgress = false;
+ }
+ } catch (\Throwable) {
$this->isDeploymentProgress = false;
}
}
diff --git a/app/Livewire/Project/Service/ServiceApplicationView.php b/app/Livewire/Project/Service/ServiceApplicationView.php
index a3e417567b..8324ee645c 100644
--- a/app/Livewire/Project/Service/ServiceApplicationView.php
+++ b/app/Livewire/Project/Service/ServiceApplicationView.php
@@ -8,7 +8,6 @@
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
use Spatie\Url\Url;
-use Throwable;
class ServiceApplicationView extends Component
{
@@ -51,10 +50,12 @@ public function instantSaveAdvanced()
public function delete($password)
{
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return null;
+ return;
+ }
}
try {
@@ -62,7 +63,7 @@ public function delete($password)
$this->dispatch('success', 'Application deleted.');
return redirect()->route('project.service.configuration', $this->parameters);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
@@ -93,11 +94,11 @@ public function submit()
updateCompose($this->application);
if (str($this->application->fqdn)->contains(',')) {
$this->dispatch('warning', 'Some services do not support multiple domains, which can lead to problems and is NOT RECOMMENDED.
Only use multiple domains if you know what you are doing.');
- } elseif (! $warning) {
- $this->dispatch('success', 'Service saved.');
+ } else {
+ ! $warning && $this->dispatch('success', 'Service saved.');
}
$this->dispatch('generateDockerCompose');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$originalFqdn = $this->application->getOriginal('fqdn');
if ($originalFqdn !== $this->application->fqdn) {
$this->application->fqdn = $originalFqdn;
@@ -105,8 +106,6 @@ public function submit()
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Service/StackForm.php b/app/Livewire/Project/Service/StackForm.php
index 2ee43cb578..2c751aa92a 100644
--- a/app/Livewire/Project/Service/StackForm.php
+++ b/app/Livewire/Project/Service/StackForm.php
@@ -3,10 +3,8 @@
namespace App\Livewire\Project\Service;
use App\Models\Service;
-use Exception;
use Illuminate\Support\Collection;
use Livewire\Component;
-use Throwable;
class StackForm extends Component
{
@@ -80,7 +78,7 @@ public function submit($notify = true)
$this->validate();
$isValid = validateComposeFile($this->service->docker_compose_raw, $this->service->server->id);
if ($isValid !== 'OK') {
- throw new Exception("Invalid docker-compose file.\n$isValid");
+ throw new \Exception("Invalid docker-compose file.\n$isValid");
}
$this->service->save();
$this->service->saveExtraFields($this->fields);
@@ -89,7 +87,7 @@ public function submit($notify = true)
$this->service->saveComposeConfigs();
$this->dispatch('refreshEnvs');
$notify && $this->dispatch('success', 'Service saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
if (is_null($this->service->config_hash)) {
@@ -98,8 +96,6 @@ public function submit($notify = true)
$this->dispatch('configurationChanged');
}
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Service/Storage.php b/app/Livewire/Project/Service/Storage.php
index 5fc83058d9..4b64a8b5ef 100644
--- a/app/Livewire/Project/Service/Storage.php
+++ b/app/Livewire/Project/Service/Storage.php
@@ -4,7 +4,6 @@
use App\Models\LocalPersistentVolume;
use Livewire\Component;
-use Throwable;
class Storage extends Component
{
@@ -43,7 +42,7 @@ public function refreshStorages()
public function addNewVolume($data)
{
try {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => $data['name'],
'mount_path' => $data['mount_path'],
'host_path' => $data['host_path'],
@@ -54,11 +53,9 @@ public function addNewVolume($data)
$this->dispatch('success', 'Storage added successfully');
$this->dispatch('clearAddStorage');
$this->dispatch('refreshStorages');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Shared/Danger.php b/app/Livewire/Project/Shared/Danger.php
index 014bd21afa..7da48f9fb4 100644
--- a/app/Livewire/Project/Shared/Danger.php
+++ b/app/Livewire/Project/Shared/Danger.php
@@ -10,7 +10,6 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
-use Throwable;
use Visus\Cuid2\Cuid2;
class Danger extends Component
@@ -44,10 +43,10 @@ public function mount()
if ($this->resource === null) {
if (isset($parameters['service_uuid'])) {
- $this->resource = Service::query()->where('uuid', $parameters['service_uuid'])->first();
+ $this->resource = Service::where('uuid', $parameters['service_uuid'])->first();
} elseif (isset($parameters['stack_service_uuid'])) {
- $this->resource = ServiceApplication::query()->where('uuid', $parameters['stack_service_uuid'])->first()
- ?? ServiceDatabase::query()->where('uuid', $parameters['stack_service_uuid'])->first();
+ $this->resource = ServiceApplication::where('uuid', $parameters['stack_service_uuid'])->first()
+ ?? ServiceDatabase::where('uuid', $parameters['stack_service_uuid'])->first();
}
}
@@ -82,16 +81,18 @@ public function mount()
public function delete($password)
{
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return null;
+ return;
+ }
}
if (! $this->resource) {
$this->addError('resource', 'Resource not found.');
- return null;
+ return;
}
try {
@@ -108,7 +109,7 @@ public function delete($password)
'project_uuid' => $this->projectUuid,
'environment_uuid' => $this->environmentUuid,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Project/Shared/Destination.php b/app/Livewire/Project/Shared/Destination.php
index 0096bc9896..1759fe08ac 100644
--- a/app/Livewire/Project/Shared/Destination.php
+++ b/app/Livewire/Project/Shared/Destination.php
@@ -8,7 +8,6 @@
use App\Models\InstanceSettings;
use App\Models\Server;
use App\Models\StandaloneDocker;
-use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
@@ -64,11 +63,9 @@ public function stop($serverId)
$server = Server::ownedByCurrentTeam()->findOrFail($serverId);
StopApplicationOneServer::run($this->resource, $server);
$this->refreshServers();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function redeploy(int $network_id, int $server_id)
@@ -77,13 +74,13 @@ public function redeploy(int $network_id, int $server_id)
if ($this->resource->additional_servers->count() > 0 && str($this->resource->docker_registry_image_name)->isEmpty()) {
$this->dispatch('error', 'Failed to deploy.', 'Before deploying to multiple servers, you must first set a Docker image in the General tab.
More information here: documentation');
- return null;
+ return;
}
- $cuid2 = new Cuid2;
+ $deployment_uuid = new Cuid2;
$server = Server::ownedByCurrentTeam()->findOrFail($server_id);
$destination = $server->standaloneDockers->where('id', $network_id)->firstOrFail();
queue_application_deployment(
- deployment_uuid: $cuid2,
+ deployment_uuid: $deployment_uuid,
application: $this->resource,
server: $server,
destination: $destination,
@@ -94,10 +91,10 @@ public function redeploy(int $network_id, int $server_id)
return redirect()->route('project.application.deployment.show', [
'project_uuid' => data_get($this->resource, 'environment.project.uuid'),
'application_uuid' => data_get($this->resource, 'uuid'),
- 'deployment_uuid' => $cuid2,
+ 'deployment_uuid' => $deployment_uuid,
'environment_uuid' => data_get($this->resource, 'environment.uuid'),
]);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
}
@@ -133,26 +130,26 @@ public function addServer(int $network_id, int $server_id)
public function removeServer(int $network_id, int $server_id, $password)
{
try {
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return null;
+ return;
+ }
}
if ($this->resource->destination->server->id == $server_id && $this->resource->destination->id == $network_id) {
$this->dispatch('error', 'You cannot remove this destination server.', 'You are trying to remove the main server.');
- return null;
+ return;
}
$server = Server::ownedByCurrentTeam()->findOrFail($server_id);
StopApplicationOneServer::run($this->resource, $server);
$this->resource->additional_networks()->detach($network_id, ['server_id' => $server_id]);
$this->loadData();
ApplicationStatusChanged::dispatch(data_get($this->resource, 'environment.project.team.id'));
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Shared/EnvironmentVariable/All.php b/app/Livewire/Project/Shared/EnvironmentVariable/All.php
index db9184ba4a..80156bf65a 100644
--- a/app/Livewire/Project/Shared/EnvironmentVariable/All.php
+++ b/app/Livewire/Project/Shared/EnvironmentVariable/All.php
@@ -2,10 +2,8 @@
namespace App\Livewire\Project\Shared\EnvironmentVariable;
-use App\Models\Application;
use App\Models\EnvironmentVariable;
use Livewire\Component;
-use Throwable;
class All extends Component
{
@@ -33,7 +31,7 @@ public function mount()
{
$this->is_env_sorting_enabled = data_get($this->resource, 'settings.is_env_sorting_enabled', false);
$this->resourceClass = get_class($this->resource);
- $resourceWithPreviews = [Application::class];
+ $resourceWithPreviews = [\App\Models\Application::class];
$simpleDockerfile = filled(data_get($this->resource, 'dockerfile'));
if (str($this->resourceClass)->contains($resourceWithPreviews) && ! $simpleDockerfile) {
$this->showPreview = true;
@@ -103,13 +101,11 @@ public function submit($data = null)
$this->updateOrder();
$this->sortEnvironmentVariables();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->refreshEnvs();
}
-
- return null;
}
private function updateOrder()
@@ -171,17 +167,17 @@ private function handleSingleSubmit($data)
private function createEnvironmentVariable($data)
{
- $environmentVariable = new EnvironmentVariable;
- $environmentVariable->key = $data['key'];
- $environmentVariable->value = $data['value'];
- $environmentVariable->is_build_time = $data['is_build_time'] ?? false;
- $environmentVariable->is_multiline = $data['is_multiline'] ?? false;
- $environmentVariable->is_literal = $data['is_literal'] ?? false;
- $environmentVariable->is_preview = $data['is_preview'] ?? false;
- $environmentVariable->resourceable_id = $this->resource->id;
- $environmentVariable->resourceable_type = $this->resource->getMorphClass();
-
- return $environmentVariable;
+ $environment = new EnvironmentVariable;
+ $environment->key = $data['key'];
+ $environment->value = $data['value'];
+ $environment->is_build_time = $data['is_build_time'] ?? false;
+ $environment->is_multiline = $data['is_multiline'] ?? false;
+ $environment->is_literal = $data['is_literal'] ?? false;
+ $environment->is_preview = $data['is_preview'] ?? false;
+ $environment->resourceable_id = $this->resource->id;
+ $environment->resourceable_type = $this->resource->getMorphClass();
+
+ return $environment;
}
private function deleteRemovedVariables($isPreview, $variables)
diff --git a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
index 7d588a55b1..4b66bfdcb6 100644
--- a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
+++ b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
@@ -4,7 +4,6 @@
use App\Models\EnvironmentVariable as ModelsEnvironmentVariable;
use App\Models\SharedEnvironmentVariable;
-use Exception;
use Livewire\Component;
class Show extends Component
@@ -61,7 +60,7 @@ class Show extends Component
public function mount()
{
$this->syncData();
- if ($this->env->getMorphClass() === SharedEnvironmentVariable::class) {
+ if ($this->env->getMorphClass() === \App\Models\SharedEnvironmentVariable::class) {
$this->isSharedVariable = true;
}
$this->parameters = get_route_parameters();
@@ -117,7 +116,7 @@ public function checkEnvs()
public function serialize()
{
data_forget($this->env, 'real_value');
- if ($this->env->getMorphClass() === SharedEnvironmentVariable::class) {
+ if ($this->env->getMorphClass() === \App\Models\SharedEnvironmentVariable::class) {
data_forget($this->env, 'is_build_time');
}
}
@@ -157,7 +156,7 @@ public function submit()
$this->value = $oldValue;
$this->dispatch('error', 'Required environment variable cannot be empty.');
- return null;
+ return;
}
$this->serialize();
@@ -169,11 +168,9 @@ public function submit()
$this->syncData(true);
$this->dispatch('success', 'Environment variable updated.');
$this->dispatch('envsUpdated');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
-
- return null;
}
public function delete()
@@ -182,10 +179,8 @@ public function delete()
$this->env->delete();
$this->dispatch('environmentVariableDeleted');
$this->dispatch('success', 'Environment variable deleted successfully.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Shared/ExecuteContainerCommand.php b/app/Livewire/Project/Shared/ExecuteContainerCommand.php
index 9b6610e99a..d12d8e26a9 100644
--- a/app/Livewire/Project/Shared/ExecuteContainerCommand.php
+++ b/app/Livewire/Project/Shared/ExecuteContainerCommand.php
@@ -6,11 +6,8 @@
use App\Models\Server;
use App\Models\Service;
use Illuminate\Support\Collection;
-use InvalidArgumentException;
use Livewire\Attributes\On;
use Livewire\Component;
-use RuntimeException;
-use Throwable;
class ExecuteContainerCommand extends Component
{
@@ -46,7 +43,7 @@ public function mount()
$this->servers = collect();
if (data_get($this->parameters, 'application_uuid')) {
$this->type = 'application';
- $this->resource = Application::query()->where('uuid', $this->parameters['application_uuid'])->firstOrFail();
+ $this->resource = Application::where('uuid', $this->parameters['application_uuid'])->firstOrFail();
if ($this->resource->destination->server->isFunctional()) {
$this->servers = $this->servers->push($this->resource->destination->server);
}
@@ -69,14 +66,14 @@ public function mount()
$this->loadContainers();
} elseif (data_get($this->parameters, 'service_uuid')) {
$this->type = 'service';
- $this->resource = Service::query()->where('uuid', $this->parameters['service_uuid'])->firstOrFail();
+ $this->resource = Service::where('uuid', $this->parameters['service_uuid'])->firstOrFail();
if ($this->resource->server->isFunctional()) {
$this->servers = $this->servers->push($this->resource->server);
}
$this->loadContainers();
} elseif (data_get($this->parameters, 'server_uuid')) {
$this->type = 'server';
- $this->resource = Server::query()->where('uuid', $this->parameters['server_uuid'])->firstOrFail();
+ $this->resource = Server::where('uuid', $this->parameters['server_uuid'])->firstOrFail();
$this->server = $this->resource;
}
}
@@ -149,7 +146,7 @@ public function connectToServer()
{
try {
if ($this->server->isForceDisabled()) {
- throw new RuntimeException('Server is disabled.');
+ throw new \RuntimeException('Server is disabled.');
}
$this->dispatch(
'send-terminal-command',
@@ -157,11 +154,9 @@ public function connectToServer()
data_get($this->server, 'name'),
data_get($this->server, 'uuid')
);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
#[On('connectToContainer')]
@@ -170,28 +165,28 @@ public function connectToContainer()
if ($this->selected_container === 'default') {
$this->dispatch('error', 'Please select a container.');
- return null;
+ return;
}
try {
// Validate container name format
if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $this->selected_container)) {
- throw new InvalidArgumentException('Invalid container name format');
+ throw new \InvalidArgumentException('Invalid container name format');
}
// Verify container exists in our allowed list
$container = collect($this->containers)->firstWhere('container.Names', $this->selected_container);
if (is_null($container)) {
- throw new RuntimeException('Container not found.');
+ throw new \RuntimeException('Container not found.');
}
// Verify server ownership and status
$server = data_get($container, 'server');
if (! $server || ! $server instanceof Server) {
- throw new RuntimeException('Invalid server configuration.');
+ throw new \RuntimeException('Invalid server configuration.');
}
if ($server->isForceDisabled()) {
- throw new RuntimeException('Server is disabled.');
+ throw new \RuntimeException('Server is disabled.');
}
// Additional ownership verification based on resource type
@@ -199,11 +194,11 @@ public function connectToContainer()
'application' => $this->resource->destination->server,
'database' => $this->resource->destination->server,
'service' => $this->resource->server,
- default => throw new RuntimeException('Invalid resource type.')
+ default => throw new \RuntimeException('Invalid resource type.')
};
if ($server->id !== $resourceServer->id && ! $this->resource->additional_servers->contains('id', $server->id)) {
- throw new RuntimeException('Server ownership verification failed.');
+ throw new \RuntimeException('Server ownership verification failed.');
}
$this->dispatch(
@@ -212,11 +207,9 @@ public function connectToContainer()
data_get($container, 'container.Names'),
data_get($container, 'server.uuid')
);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Shared/GetLogs.php b/app/Livewire/Project/Shared/GetLogs.php
index 992bf6619d..43fd97c341 100644
--- a/app/Livewire/Project/Shared/GetLogs.php
+++ b/app/Livewire/Project/Shared/GetLogs.php
@@ -44,15 +44,19 @@ class GetLogs extends Component
public function mount()
{
if (! is_null($this->resource)) {
- if ($this->resource->getMorphClass() === Application::class) {
+ if ($this->resource->getMorphClass() === \App\Models\Application::class) {
$this->showTimeStamps = $this->resource->settings->is_include_timestamps;
- } elseif ($this->servicesubtype) {
- $this->showTimeStamps = $this->servicesubtype->is_include_timestamps;
} else {
- $this->showTimeStamps = $this->resource->is_include_timestamps;
+ if ($this->servicesubtype) {
+ $this->showTimeStamps = $this->servicesubtype->is_include_timestamps;
+ } else {
+ $this->showTimeStamps = $this->resource->is_include_timestamps;
+ }
}
- if ($this->resource?->getMorphClass() === Application::class && str($this->container)->contains('-pr-')) {
- $this->pull_request = 'Pull Request: '.str($this->container)->afterLast('-pr-')->beforeLast('_')->value();
+ if ($this->resource?->getMorphClass() === \App\Models\Application::class) {
+ if (str($this->container)->contains('-pr-')) {
+ $this->pull_request = 'Pull Request: '.str($this->container)->afterLast('-pr-')->beforeLast('_')->value();
+ }
}
}
}
@@ -65,11 +69,11 @@ public function doSomethingWithThisChunkOfOutput($output)
public function instantSave()
{
if (! is_null($this->resource)) {
- if ($this->resource->getMorphClass() === Application::class) {
+ if ($this->resource->getMorphClass() === \App\Models\Application::class) {
$this->resource->settings->is_include_timestamps = $this->showTimeStamps;
$this->resource->settings->save();
}
- if ($this->resource->getMorphClass() === Service::class) {
+ if ($this->resource->getMorphClass() === \App\Models\Service::class) {
$serviceName = str($this->container)->beforeLast('-')->value();
$subType = $this->resource->applications()->where('name', $serviceName)->first();
if ($subType) {
@@ -91,7 +95,7 @@ public function getLogs($refresh = false)
if (! $this->server->isFunctional()) {
return;
}
- if (! $refresh && ($this->resource?->getMorphClass() === Service::class || str($this->container)->contains('-pr-'))) {
+ if (! $refresh && ($this->resource?->getMorphClass() === \App\Models\Service::class || str($this->container)->contains('-pr-'))) {
return;
}
if ($this->numberOfLines <= 0 || is_null($this->numberOfLines)) {
@@ -114,20 +118,22 @@ public function getLogs($refresh = false)
}
$sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);
}
- } elseif ($this->server->isSwarm()) {
- $command = "docker service logs -n {$this->numberOfLines} {$this->container}";
- if ($this->server->isNonRoot()) {
- $command = parseCommandsByLineForSudo(collect($command), $this->server);
- $command = $command[0];
- }
- $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);
} else {
- $command = "docker logs -n {$this->numberOfLines} {$this->container}";
- if ($this->server->isNonRoot()) {
- $command = parseCommandsByLineForSudo(collect($command), $this->server);
- $command = $command[0];
+ if ($this->server->isSwarm()) {
+ $command = "docker service logs -n {$this->numberOfLines} {$this->container}";
+ if ($this->server->isNonRoot()) {
+ $command = parseCommandsByLineForSudo(collect($command), $this->server);
+ $command = $command[0];
+ }
+ $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);
+ } else {
+ $command = "docker logs -n {$this->numberOfLines} {$this->container}";
+ if ($this->server->isNonRoot()) {
+ $command = parseCommandsByLineForSudo(collect($command), $this->server);
+ $command = $command[0];
+ }
+ $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);
}
- $sshCommand = SshMultiplexingHelper::generateSshCommand($this->server, $command);
}
if ($refresh) {
$this->outputs = '';
diff --git a/app/Livewire/Project/Shared/HealthChecks.php b/app/Livewire/Project/Shared/HealthChecks.php
index 027869f70c..83162e36a2 100644
--- a/app/Livewire/Project/Shared/HealthChecks.php
+++ b/app/Livewire/Project/Shared/HealthChecks.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Project\Shared;
use Livewire\Component;
-use Throwable;
class HealthChecks extends Component
{
@@ -38,11 +37,9 @@ public function submit()
$this->validate();
$this->resource->save();
$this->dispatch('success', 'Health check updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Shared/Logs.php b/app/Livewire/Project/Shared/Logs.php
index acc5480a53..12022b1eeb 100644
--- a/app/Livewire/Project/Shared/Logs.php
+++ b/app/Livewire/Project/Shared/Logs.php
@@ -12,7 +12,6 @@
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
-use Exception;
use Illuminate\Support\Collection;
use Livewire\Component;
@@ -43,7 +42,7 @@ public function loadContainers($server_id)
try {
$server = $this->servers->firstWhere('id', $server_id);
if (! $server->isFunctional()) {
- return null;
+ return;
}
if ($server->isSwarm()) {
$containers = collect([
@@ -55,11 +54,9 @@ public function loadContainers($server_id)
$containers = getCurrentApplicationContainerStatus($server, $this->resource->id, includePullrequests: true);
}
$server->containers = $containers->sort();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function mount()
@@ -71,7 +68,7 @@ public function mount()
$this->query = request()->query();
if (data_get($this->parameters, 'application_uuid')) {
$this->type = 'application';
- $this->resource = Application::query()->where('uuid', $this->parameters['application_uuid'])->firstOrFail();
+ $this->resource = Application::where('uuid', $this->parameters['application_uuid'])->firstOrFail();
$this->status = $this->resource->status;
if ($this->resource->destination->server->isFunctional()) {
$this->servers = $this->servers->push($this->resource->destination->server);
@@ -96,7 +93,7 @@ public function mount()
$this->containers->push($this->container);
} elseif (data_get($this->parameters, 'service_uuid')) {
$this->type = 'service';
- $this->resource = Service::query()->where('uuid', $this->parameters['service_uuid'])->firstOrFail();
+ $this->resource = Service::where('uuid', $this->parameters['service_uuid'])->firstOrFail();
$this->resource->applications()->get()->each(function ($application) {
$this->containers->push(data_get($application, 'name').'-'.data_get($this->resource, 'uuid'));
});
@@ -113,11 +110,9 @@ public function mount()
return str_contains($container, $this->query['pull_request_id']);
});
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Shared/Metrics.php b/app/Livewire/Project/Shared/Metrics.php
index 052da00f26..fdc35fc0fb 100644
--- a/app/Livewire/Project/Shared/Metrics.php
+++ b/app/Livewire/Project/Shared/Metrics.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Project\Shared;
use Livewire\Component;
-use Throwable;
class Metrics extends Component
{
@@ -40,11 +39,9 @@ public function loadData()
$this->dispatch("refreshChartData-{$this->chartId}-memory", [
'seriesData' => $memoryMetrics,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function setInterval()
diff --git a/app/Livewire/Project/Shared/ResourceLimits.php b/app/Livewire/Project/Shared/ResourceLimits.php
index e7c03f4eeb..608dfbf022 100644
--- a/app/Livewire/Project/Shared/ResourceLimits.php
+++ b/app/Livewire/Project/Shared/ResourceLimits.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Project\Shared;
use Livewire\Component;
-use Throwable;
class ResourceLimits extends Component
{
@@ -56,10 +55,8 @@ public function submit()
$this->validate();
$this->resource->save();
$this->dispatch('success', 'Resource limits updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Shared/ResourceOperations.php b/app/Livewire/Project/Shared/ResourceOperations.php
index 421e16deb7..c6a32f0c7a 100644
--- a/app/Livewire/Project/Shared/ResourceOperations.php
+++ b/app/Livewire/Project/Shared/ResourceOperations.php
@@ -2,21 +2,11 @@
namespace App\Livewire\Project\Shared;
-use App\Models\Application;
use App\Models\Environment;
use App\Models\Project;
-use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDocker;
-use App\Models\StandaloneDragonfly;
-use App\Models\StandaloneKeydb;
-use App\Models\StandaloneMariadb;
-use App\Models\StandaloneMongodb;
-use App\Models\StandaloneMysql;
-use App\Models\StandalonePostgresql;
-use App\Models\StandaloneRedis;
use App\Models\SwarmDocker;
use Livewire\Component;
-use Throwable;
use Visus\Cuid2\Cuid2;
class ResourceOperations extends Component
@@ -42,17 +32,18 @@ public function mount()
public function cloneTo($destination_id)
{
- $new_destination = StandaloneDocker::query()->find($destination_id);
+ $new_destination = StandaloneDocker::find($destination_id);
if (! $new_destination) {
- $new_destination = SwarmDocker::query()->find($destination_id);
+ $new_destination = SwarmDocker::find($destination_id);
}
if (! $new_destination) {
return $this->addError('destination_id', 'Destination not found.');
}
$uuid = (string) new Cuid2;
$server = $new_destination->server;
- if ($this->resource->getMorphClass() === Application::class) {
+ if ($this->resource->getMorphClass() === \App\Models\Application::class) {
$name = 'clone-of-'.str($this->resource->name)->limit(20).'-'.$uuid;
+
$new_resource = $this->resource->replicate()->fill([
'uuid' => $uuid,
'name' => $name,
@@ -75,12 +66,12 @@ public function cloneTo($destination_id)
$newEnvironmentVariable->save();
}
$persistentVolumes = $this->resource->persistentStorages()->get();
- foreach ($persistentVolumes as $persistentVolume) {
- $volumeName = str($persistentVolume->name)->replace($this->resource->uuid, $new_resource->uuid)->value();
- if ($volumeName === $persistentVolume->name) {
- $volumeName = $new_resource->uuid.'-'.str($persistentVolume->name)->afterLast('-');
+ foreach ($persistentVolumes as $volume) {
+ $volumeName = str($volume->name)->replace($this->resource->uuid, $new_resource->uuid)->value();
+ if ($volumeName === $volume->name) {
+ $volumeName = $new_resource->uuid.'-'.str($volume->name)->afterLast('-');
}
- $newPersistentVolume = $persistentVolume->replicate()->fill([
+ $newPersistentVolume = $volume->replicate()->fill([
'name' => $volumeName,
'resource_id' => $new_resource->id,
]);
@@ -93,15 +84,16 @@ public function cloneTo($destination_id)
]).'#resource-operations';
return redirect()->to($route);
- }
- if ($this->resource->getMorphClass() === StandalonePostgresql::class ||
- $this->resource->getMorphClass() === StandaloneMongodb::class ||
- $this->resource->getMorphClass() === StandaloneMysql::class ||
- $this->resource->getMorphClass() === StandaloneMariadb::class ||
- $this->resource->getMorphClass() === StandaloneRedis::class ||
- $this->resource->getMorphClass() === StandaloneKeydb::class ||
- $this->resource->getMorphClass() === StandaloneDragonfly::class ||
- $this->resource->getMorphClass() === StandaloneClickhouse::class) {
+ } elseif (
+ $this->resource->getMorphClass() === \App\Models\StandalonePostgresql::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneMongodb::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneMysql::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneMariadb::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneRedis::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneKeydb::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneDragonfly::class ||
+ $this->resource->getMorphClass() === \App\Models\StandaloneClickhouse::class
+ ) {
$uuid = (string) new Cuid2;
$new_resource = $this->resource->replicate()->fill([
'uuid' => $uuid,
@@ -135,8 +127,7 @@ public function cloneTo($destination_id)
]).'#resource-operations';
return redirect()->to($route);
- }
- if ($this->resource->type() === 'service') {
+ } elseif ($this->resource->type() === 'service') {
$uuid = (string) new Cuid2;
$new_resource = $this->resource->replicate()->fill([
'uuid' => $uuid,
@@ -163,14 +154,12 @@ public function cloneTo($destination_id)
return redirect()->to($route);
}
-
- return null;
}
public function moveTo($environment_id)
{
try {
- $new_environment = Environment::query()->findOrFail($environment_id);
+ $new_environment = Environment::findOrFail($environment_id);
$this->resource->update([
'environment_id' => $environment_id,
]);
@@ -182,8 +171,7 @@ public function moveTo($environment_id)
]).'#resource-operations';
return redirect()->to($route);
- }
- if (str($this->resource->type())->startsWith('standalone-')) {
+ } elseif (str($this->resource->type())->startsWith('standalone-')) {
$route = route('project.database.configuration', [
'project_uuid' => $new_environment->project->uuid,
'environment_uuid' => $new_environment->uuid,
@@ -191,8 +179,7 @@ public function moveTo($environment_id)
]).'#resource-operations';
return redirect()->to($route);
- }
- if ($this->resource->type() === 'service') {
+ } elseif ($this->resource->type() === 'service') {
$route = route('project.service.configuration', [
'project_uuid' => $new_environment->project->uuid,
'environment_uuid' => $new_environment->uuid,
@@ -201,11 +188,9 @@ public function moveTo($environment_id)
return redirect()->to($route);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Project/Shared/ScheduledTask/Add.php b/app/Livewire/Project/Shared/ScheduledTask/Add.php
index 0f378e39b2..adfd59217e 100644
--- a/app/Livewire/Project/Shared/ScheduledTask/Add.php
+++ b/app/Livewire/Project/Shared/ScheduledTask/Add.php
@@ -2,7 +2,6 @@
namespace App\Livewire\Project\Shared\ScheduledTask;
-use Exception;
use Illuminate\Support\Collection;
use Livewire\Component;
@@ -54,10 +53,12 @@ public function submit()
if (! $isValid) {
$this->dispatch('error', 'Invalid Cron / Human expression.');
- return null;
+ return;
}
- if (($this->container === null || $this->container === '' || $this->container === '0' || $this->container === 'null') && $this->type === 'service') {
- $this->container = $this->subServiceName;
+ if (empty($this->container) || $this->container === 'null') {
+ if ($this->type === 'service') {
+ $this->container = $this->subServiceName;
+ }
}
$this->dispatch('saveScheduledTask', [
'name' => $this->name,
@@ -66,11 +67,9 @@ public function submit()
'container' => $this->container,
]);
$this->clear();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function clear()
diff --git a/app/Livewire/Project/Shared/ScheduledTask/All.php b/app/Livewire/Project/Shared/ScheduledTask/All.php
index 11e7fcef60..6ab8426f39 100644
--- a/app/Livewire/Project/Shared/ScheduledTask/All.php
+++ b/app/Livewire/Project/Shared/ScheduledTask/All.php
@@ -5,7 +5,6 @@
use App\Models\ScheduledTask;
use Illuminate\Support\Collection;
use Livewire\Component;
-use Throwable;
class All extends Component
{
@@ -44,31 +43,29 @@ public function refreshTasks()
public function submit($data)
{
try {
- $scheduledTask = new ScheduledTask;
- $scheduledTask->name = $data['name'];
- $scheduledTask->command = $data['command'];
- $scheduledTask->frequency = $data['frequency'];
- $scheduledTask->container = $data['container'];
- $scheduledTask->team_id = currentTeam()->id;
+ $task = new ScheduledTask;
+ $task->name = $data['name'];
+ $task->command = $data['command'];
+ $task->frequency = $data['frequency'];
+ $task->container = $data['container'];
+ $task->team_id = currentTeam()->id;
switch ($this->resource->type()) {
case 'application':
- $scheduledTask->application_id = $this->resource->id;
+ $task->application_id = $this->resource->id;
break;
case 'standalone-postgresql':
- $scheduledTask->standalone_postgresql_id = $this->resource->id;
+ $task->standalone_postgresql_id = $this->resource->id;
break;
case 'service':
- $scheduledTask->service_id = $this->resource->id;
+ $task->service_id = $this->resource->id;
break;
}
- $scheduledTask->save();
+ $task->save();
$this->refreshTasks();
$this->dispatch('success', 'Scheduled task added.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Shared/ScheduledTask/Executions.php b/app/Livewire/Project/Shared/ScheduledTask/Executions.php
index f0f6cf7753..74eac7132e 100644
--- a/app/Livewire/Project/Shared/ScheduledTask/Executions.php
+++ b/app/Livewire/Project/Shared/ScheduledTask/Executions.php
@@ -3,9 +3,6 @@
namespace App\Livewire\Project\Shared\ScheduledTask;
use App\Models\ScheduledTask;
-use DateTime;
-use DateTimeZone;
-use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Locked;
@@ -31,7 +28,7 @@ class Executions extends Component
public $logsPerPage = 100;
- public $selectedExecution;
+ public $selectedExecution = null;
public $isPollingActive = false;
@@ -48,7 +45,7 @@ public function mount($taskId)
{
try {
$this->taskId = $taskId;
- $this->task = ScheduledTask::query()->findOrFail($taskId);
+ $this->task = ScheduledTask::findOrFail($taskId);
$this->executions = $this->task->executions()->take(20)->get();
$this->serverTimezone = data_get($this->task, 'application.destination.server.settings.server_timezone');
if (! $this->serverTimezone) {
@@ -57,11 +54,9 @@ public function mount($taskId)
if (! $this->serverTimezone) {
$this->serverTimezone = 'UTC';
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
-
- return null;
}
public function refreshExecutions(): void
@@ -129,7 +124,7 @@ public function downloadLogs(int $executionId)
{
$execution = $this->executions->firstWhere('id', $executionId);
if (! $execution) {
- return null;
+ return;
}
return response()->streamDownload(function () use ($execution) {
@@ -150,11 +145,11 @@ public function hasMoreLogs()
public function formatDateInServerTimezone($date)
{
$serverTimezone = $this->serverTimezone;
- $dateObj = new DateTime($date);
+ $dateObj = new \DateTime($date);
try {
- $dateObj->setTimezone(new DateTimeZone($serverTimezone));
- } catch (Exception) {
- $dateObj->setTimezone(new DateTimeZone('UTC'));
+ $dateObj->setTimezone(new \DateTimeZone($serverTimezone));
+ } catch (\Exception) {
+ $dateObj->setTimezone(new \DateTimeZone('UTC'));
}
return $dateObj->format('Y-m-d H:i:s T');
diff --git a/app/Livewire/Project/Shared/ScheduledTask/Show.php b/app/Livewire/Project/Shared/ScheduledTask/Show.php
index 5ea0e3cdc0..0764ab3b96 100644
--- a/app/Livewire/Project/Shared/ScheduledTask/Show.php
+++ b/app/Livewire/Project/Shared/ScheduledTask/Show.php
@@ -6,7 +6,6 @@
use App\Models\Application;
use App\Models\ScheduledTask;
use App\Models\Service;
-use Exception;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
@@ -69,11 +68,9 @@ public function mount(string $task_uuid, string $project_uuid, string $environme
$this->task = $this->resource->scheduled_tasks()->where('uuid', $task_uuid)->firstOrFail();
$this->syncData();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -101,11 +98,9 @@ public function instantSave()
$this->syncData(true);
$this->dispatch('success', 'Scheduled task updated.');
$this->refreshTasks();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
-
- return null;
}
public function submit()
@@ -113,22 +108,18 @@ public function submit()
try {
$this->syncData(true);
$this->dispatch('success', 'Scheduled task updated.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
-
- return null;
}
public function refreshTasks()
{
try {
$this->task->refresh();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
-
- return null;
}
public function delete()
@@ -138,10 +129,10 @@ public function delete()
if ($this->type === 'application') {
return redirect()->route('project.application.configuration', $this->parameters, $this->task->name);
+ } else {
+ return redirect()->route('project.service.configuration', $this->parameters, $this->task->name);
}
-
- return redirect()->route('project.service.configuration', $this->parameters, $this->task->name);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
}
@@ -151,10 +142,8 @@ public function executeNow()
try {
ScheduledTaskJob::dispatch($this->task);
$this->dispatch('success', 'Scheduled task executed.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Shared/Storages/Add.php b/app/Livewire/Project/Shared/Storages/Add.php
index 5645b28c37..6e250bd908 100644
--- a/app/Livewire/Project/Shared/Storages/Add.php
+++ b/app/Livewire/Project/Shared/Storages/Add.php
@@ -5,7 +5,6 @@
use App\Models\Application;
use App\Models\LocalFileVolume;
use Livewire\Component;
-use Throwable;
class Add extends Component
{
@@ -64,7 +63,7 @@ public function mount()
$this->parameters = get_route_parameters();
if (data_get($this->parameters, 'application_uuid')) {
$applicationUuid = $this->parameters['application_uuid'];
- $application = Application::query()->where('uuid', $applicationUuid)->first();
+ $application = Application::where('uuid', $applicationUuid)->first();
if (! $application) {
abort(404);
}
@@ -84,23 +83,23 @@ public function submitFileStorage()
]);
$this->file_storage_path = trim($this->file_storage_path);
$this->file_storage_path = str($this->file_storage_path)->start('/')->value();
- if ($this->resource->getMorphClass() === Application::class) {
+ if ($this->resource->getMorphClass() === \App\Models\Application::class) {
$fs_path = application_configuration_dir().'/'.$this->resource->uuid.$this->file_storage_path;
}
- LocalFileVolume::query()->create([
- 'fs_path' => $fs_path,
- 'mount_path' => $this->file_storage_path,
- 'content' => $this->file_storage_content,
- 'is_directory' => false,
- 'resource_id' => $this->resource->id,
- 'resource_type' => get_class($this->resource),
- ]);
+ LocalFileVolume::create(
+ [
+ 'fs_path' => $fs_path,
+ 'mount_path' => $this->file_storage_path,
+ 'content' => $this->file_storage_content,
+ 'is_directory' => false,
+ 'resource_id' => $this->resource->id,
+ 'resource_type' => get_class($this->resource),
+ ],
+ );
$this->dispatch('refreshStorages');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submitFileStorageDirectory()
@@ -114,19 +113,19 @@ public function submitFileStorageDirectory()
$this->file_storage_directory_source = str($this->file_storage_directory_source)->start('/')->value();
$this->file_storage_directory_destination = trim($this->file_storage_directory_destination);
$this->file_storage_directory_destination = str($this->file_storage_directory_destination)->start('/')->value();
- LocalFileVolume::query()->create([
- 'fs_path' => $this->file_storage_directory_source,
- 'mount_path' => $this->file_storage_directory_destination,
- 'is_directory' => true,
- 'resource_id' => $this->resource->id,
- 'resource_type' => get_class($this->resource),
- ]);
+ LocalFileVolume::create(
+ [
+ 'fs_path' => $this->file_storage_directory_source,
+ 'mount_path' => $this->file_storage_directory_destination,
+ 'is_directory' => true,
+ 'resource_id' => $this->resource->id,
+ 'resource_type' => get_class($this->resource),
+ ],
+ );
$this->dispatch('refreshStorages');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submitPersistentVolume()
@@ -143,11 +142,9 @@ public function submitPersistentVolume()
'mount_path' => $this->mount_path,
'host_path' => $this->host_path,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function clear()
diff --git a/app/Livewire/Project/Shared/Storages/Show.php b/app/Livewire/Project/Shared/Storages/Show.php
index 0451a7f925..54b1be3af5 100644
--- a/app/Livewire/Project/Shared/Storages/Show.php
+++ b/app/Livewire/Project/Shared/Storages/Show.php
@@ -41,10 +41,12 @@ public function submit()
public function delete($password)
{
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return;
+ return;
+ }
}
$this->storage->delete();
diff --git a/app/Livewire/Project/Shared/Tags.php b/app/Livewire/Project/Shared/Tags.php
index 2b22feb2a1..811859cb88 100644
--- a/app/Livewire/Project/Shared/Tags.php
+++ b/app/Livewire/Project/Shared/Tags.php
@@ -3,14 +3,13 @@
namespace App\Livewire\Project\Shared;
use App\Models\Tag;
-use Exception;
use Livewire\Attributes\Validate;
use Livewire\Component;
// Refactored ✅
class Tags extends Component
{
- public $resource;
+ public $resource = null;
#[Validate('required|string|min:2')]
public string $newTags;
@@ -51,7 +50,7 @@ public function submit()
}
$found = Tag::ownedByCurrentTeam()->where(['name' => $tag])->exists();
if (! $found) {
- $found = Tag::query()->create([
+ $found = Tag::create([
'name' => $tag,
'team_id' => currentTeam()->id,
]);
@@ -59,11 +58,9 @@ public function submit()
$this->resource->tags()->attach($found->id);
}
$this->refresh();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function addTag(string $id, string $name)
@@ -73,16 +70,14 @@ public function addTag(string $id, string $name)
if ($this->resource->tags()->where('id', $id)->exists()) {
$this->dispatch('error', 'Duplicate tags.', "Tag $name already added.");
- return null;
+ return;
}
$this->resource->tags()->attach($id);
$this->refresh();
$this->dispatch('success', 'Tag added.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function deleteTag(string $id)
@@ -95,11 +90,9 @@ public function deleteTag(string $id)
}
$this->refresh();
$this->dispatch('success', 'Tag deleted.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function refresh()
diff --git a/app/Livewire/Project/Shared/Terminal.php b/app/Livewire/Project/Shared/Terminal.php
index 375500142e..d8f1012770 100644
--- a/app/Livewire/Project/Shared/Terminal.php
+++ b/app/Livewire/Project/Shared/Terminal.php
@@ -4,7 +4,6 @@
use App\Helpers\SshMultiplexingHelper;
use App\Models\Server;
-use InvalidArgumentException;
use Livewire\Attributes\On;
use Livewire\Component;
@@ -32,7 +31,7 @@ public function sendTerminalCommand($isContainer, $identifier, $serverUuid)
if ($isContainer) {
// Validate container identifier format (alphanumeric, dashes, and underscores only)
if (! preg_match('/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/', $identifier)) {
- throw new InvalidArgumentException('Invalid container identifier format');
+ throw new \InvalidArgumentException('Invalid container identifier format');
}
// Verify container exists and belongs to the user's team
diff --git a/app/Livewire/Project/Shared/UploadConfig.php b/app/Livewire/Project/Shared/UploadConfig.php
index 9ebe045e49..1b10f588b8 100644
--- a/app/Livewire/Project/Shared/UploadConfig.php
+++ b/app/Livewire/Project/Shared/UploadConfig.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Project\Shared;
use App\Models\Application;
-use Exception;
use Livewire\Component;
class UploadConfig extends Component
@@ -30,10 +29,10 @@ public function mount()
public function uploadConfig()
{
try {
- $application = Application::query()->findOrFail($this->applicationId);
+ $application = Application::findOrFail($this->applicationId);
$application->setConfig($this->config);
$this->dispatch('success', 'Application settings updated');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
return;
diff --git a/app/Livewire/Project/Shared/Webhooks.php b/app/Livewire/Project/Shared/Webhooks.php
index f88169af2c..aab1fdc47c 100644
--- a/app/Livewire/Project/Shared/Webhooks.php
+++ b/app/Livewire/Project/Shared/Webhooks.php
@@ -2,7 +2,6 @@
namespace App\Livewire\Project\Shared;
-use Exception;
use Livewire\Component;
// Refactored ✅
@@ -58,10 +57,8 @@ public function submit()
'manual_webhook_secret_gitea' => $this->giteaManualWebhookSecret,
]);
$this->dispatch('success', 'Secret Saved.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Project/Show.php b/app/Livewire/Project/Show.php
index 4c2ed4b890..886a20218f 100644
--- a/app/Livewire/Project/Show.php
+++ b/app/Livewire/Project/Show.php
@@ -6,7 +6,6 @@
use App\Models\Project;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
use Visus\Cuid2\Cuid2;
class Show extends Component
@@ -22,19 +21,17 @@ class Show extends Component
public function mount(string $project_uuid)
{
try {
- $this->project = Project::query()->where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail();
- } catch (Throwable $e) {
+ $this->project = Project::where('team_id', currentTeam()->id)->where('uuid', $project_uuid)->firstOrFail();
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
{
try {
$this->validate();
- $environment = Environment::query()->create([
+ $environment = Environment::create([
'name' => $this->name,
'project_id' => $this->project->id,
'uuid' => (string) new Cuid2,
@@ -44,11 +41,9 @@ public function submit()
'project_uuid' => $this->project->uuid,
'environment_uuid' => $environment->uuid,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
handleError($e, $this);
}
-
- return null;
}
public function navigateToEnvironment($projectUuid, $environmentUuid)
diff --git a/app/Livewire/Security/ApiTokens.php b/app/Livewire/Security/ApiTokens.php
index ad0ad745cc..72684bdc63 100644
--- a/app/Livewire/Security/ApiTokens.php
+++ b/app/Livewire/Security/ApiTokens.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Security;
use App\Models\InstanceSettings;
-use Exception;
use Livewire\Component;
class ApiTokens extends Component
@@ -40,8 +39,10 @@ public function updatedPermissions($permissionToUpdate)
$this->permissions[] = 'read';
} elseif ($permissionToUpdate == 'deploy') {
$this->permissions = ['deploy'];
- } elseif (count($this->permissions) == 0) {
- $this->permissions = ['read'];
+ } else {
+ if (count($this->permissions) == 0) {
+ $this->permissions = ['read'];
+ }
}
sort($this->permissions);
}
@@ -55,11 +56,9 @@ public function addNewToken()
$token = auth()->user()->createToken($this->description, array_values($this->permissions));
$this->getTokens();
session()->flash('token', $token->plainTextToken);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function revoke(int $id)
@@ -68,10 +67,8 @@ public function revoke(int $id)
$token = auth()->user()->tokens()->where('id', $id)->firstOrFail();
$token->delete();
$this->getTokens();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Security/PrivateKey/Create.php b/app/Livewire/Security/PrivateKey/Create.php
index 1e52906f5e..319cec1926 100644
--- a/app/Livewire/Security/PrivateKey/Create.php
+++ b/app/Livewire/Security/PrivateKey/Create.php
@@ -4,7 +4,6 @@
use App\Models\PrivateKey;
use Livewire\Component;
-use Throwable;
class Create extends Component
{
@@ -59,7 +58,7 @@ public function createPrivateKey()
]);
return $this->redirectAfterCreation($privateKey);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Security/PrivateKey/Show.php b/app/Livewire/Security/PrivateKey/Show.php
index f21c4583bd..b9195b5430 100644
--- a/app/Livewire/Security/PrivateKey/Show.php
+++ b/app/Livewire/Security/PrivateKey/Show.php
@@ -3,9 +3,7 @@
namespace App\Livewire\Security\PrivateKey;
use App\Models\PrivateKey;
-use Exception;
use Livewire\Component;
-use Throwable;
class Show extends Component
{
@@ -30,7 +28,7 @@ public function mount()
{
try {
$this->private_key = PrivateKey::ownedByCurrentTeam(['name', 'description', 'private_key', 'is_git_related'])->whereUuid(request()->private_key_uuid)->firstOrFail();
- } catch (Throwable) {
+ } catch (\Throwable) {
abort(404);
}
}
@@ -47,16 +45,14 @@ public function delete()
{
try {
$this->private_key->safeDelete();
- currentTeam()->privateKeys = PrivateKey::query()->where('team_id', currentTeam()->id)->get();
+ currentTeam()->privateKeys = PrivateKey::where('team_id', currentTeam()->id)->get();
return redirect()->route('security.private-key.index');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function changePrivateKey()
@@ -67,10 +63,8 @@ public function changePrivateKey()
]);
refresh_server_connection($this->private_key);
$this->dispatch('success', 'Private key updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Server/Advanced.php b/app/Livewire/Server/Advanced.php
index f09c219629..577730f244 100644
--- a/app/Livewire/Server/Advanced.php
+++ b/app/Livewire/Server/Advanced.php
@@ -4,10 +4,8 @@
use App\Jobs\DockerCleanupJob;
use App\Models\Server;
-use Exception;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Advanced extends Component
{
@@ -48,11 +46,9 @@ public function mount(string $server_uuid)
$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
$this->parameters = get_route_parameters();
$this->syncData();
- } catch (Throwable) {
+ } catch (\Throwable) {
return redirect()->route('server.show');
}
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -87,11 +83,9 @@ public function instantSave()
try {
$this->syncData(true);
$this->dispatch('success', 'Server updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function manualCleanup()
@@ -99,11 +93,9 @@ public function manualCleanup()
try {
DockerCleanupJob::dispatch($this->server, true);
$this->dispatch('success', 'Manual cleanup job started. Depending on the amount of data, this might take a while.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -111,19 +103,17 @@ public function submit()
try {
if (! validate_cron_expression($this->dockerCleanupFrequency)) {
$this->dockerCleanupFrequency = $this->server->settings->getOriginal('docker_cleanup_frequency');
- throw new Exception('Invalid Cron / Human expression for Docker Cleanup Frequency.');
+ throw new \Exception('Invalid Cron / Human expression for Docker Cleanup Frequency.');
}
if (! validate_cron_expression($this->serverDiskUsageCheckFrequency)) {
$this->serverDiskUsageCheckFrequency = $this->server->settings->getOriginal('server_disk_usage_check_frequency');
- throw new Exception('Invalid Cron / Human expression for Disk Usage Check Frequency.');
+ throw new \Exception('Invalid Cron / Human expression for Disk Usage Check Frequency.');
}
$this->syncData(true);
$this->dispatch('success', 'Server updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/Charts.php b/app/Livewire/Server/Charts.php
index d322364855..d0db87f577 100644
--- a/app/Livewire/Server/Charts.php
+++ b/app/Livewire/Server/Charts.php
@@ -4,7 +4,6 @@
use App\Models\Server;
use Livewire\Component;
-use Throwable;
class Charts extends Component
{
@@ -24,11 +23,9 @@ public function mount(string $server_uuid)
{
try {
$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function pollData()
@@ -52,11 +49,9 @@ public function loadData()
$this->dispatch("refreshChartData-{$this->chartId}-memory", [
'seriesData' => $memoryMetrics,
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function setInterval()
diff --git a/app/Livewire/Server/CloudflareTunnels.php b/app/Livewire/Server/CloudflareTunnels.php
index 247cab6c2b..f69fc86557 100644
--- a/app/Livewire/Server/CloudflareTunnels.php
+++ b/app/Livewire/Server/CloudflareTunnels.php
@@ -5,7 +5,6 @@
use App\Models\Server;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class CloudflareTunnels extends Component
{
@@ -22,11 +21,9 @@ public function mount(string $server_uuid)
return redirect()->route('server.show', ['server_uuid' => $server_uuid]);
}
$this->isCloudflareTunnelsEnabled = $this->server->settings->is_cloudflare_tunnel;
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
@@ -36,11 +33,9 @@ public function instantSave()
$this->server->settings->is_cloudflare_tunnel = $this->isCloudflareTunnelsEnabled;
$this->server->settings->save();
$this->dispatch('success', 'Server updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function manualCloudflareConfig()
diff --git a/app/Livewire/Server/ConfigureCloudflareTunnels.php b/app/Livewire/Server/ConfigureCloudflareTunnels.php
index 336fe7772a..f58d7b6be6 100644
--- a/app/Livewire/Server/ConfigureCloudflareTunnels.php
+++ b/app/Livewire/Server/ConfigureCloudflareTunnels.php
@@ -5,7 +5,6 @@
use App\Actions\Server\ConfigureCloudflared;
use App\Models\Server;
use Livewire\Component;
-use Throwable;
class ConfigureCloudflareTunnels extends Component
{
@@ -23,11 +22,9 @@ public function alreadyConfigured()
$server->settings->save();
$this->dispatch('success', 'Cloudflare Tunnels configured successfully.');
$this->dispatch('refreshServerShow');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -45,11 +42,9 @@ public function submit()
$server->save();
$server->settings->save();
$this->dispatch('warning', 'Cloudflare Tunnels configuration started.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/Delete.php b/app/Livewire/Server/Delete.php
index bd1ee0901f..b9e3944b54 100644
--- a/app/Livewire/Server/Delete.php
+++ b/app/Livewire/Server/Delete.php
@@ -9,7 +9,6 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;
-use Throwable;
class Delete extends Component
{
@@ -21,32 +20,32 @@ public function mount(string $server_uuid)
{
try {
$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function delete($password)
{
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return null;
+ return;
+ }
}
try {
$this->authorize('delete', $this->server);
if ($this->server->hasDefinedResources()) {
$this->dispatch('error', 'Server has defined resources. Please delete them first.');
- return null;
+ return;
}
$this->server->delete();
DeleteServer::dispatch($this->server);
return redirect()->route('server.index');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Server/Destinations.php b/app/Livewire/Server/Destinations.php
index 26fde971f3..dbab6e03f0 100644
--- a/app/Livewire/Server/Destinations.php
+++ b/app/Livewire/Server/Destinations.php
@@ -7,7 +7,6 @@
use App\Models\SwarmDocker;
use Illuminate\Support\Collection;
use Livewire\Component;
-use Throwable;
class Destinations extends Component
{
@@ -20,11 +19,9 @@ public function mount(string $server_uuid)
try {
$this->networks = collect();
$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
private function createNetworkAndAttachToProxy()
@@ -41,31 +38,37 @@ public function add($name)
$this->dispatch('error', 'Network already added to this server.');
return;
+ } else {
+ SwarmDocker::create([
+ 'name' => $this->server->name.'-'.$name,
+ 'network' => $this->name,
+ 'server_id' => $this->server->id,
+ ]);
}
- SwarmDocker::query()->create([
- 'name' => $this->server->name.'-'.$name,
- 'network' => $this->name,
- 'server_id' => $this->server->id,
- ]);
} else {
$found = $this->server->standaloneDockers()->where('network', $name)->first();
if ($found) {
$this->dispatch('error', 'Network already added to this server.');
return;
+ } else {
+ StandaloneDocker::create([
+ 'name' => $this->server->name.'-'.$name,
+ 'network' => $name,
+ 'server_id' => $this->server->id,
+ ]);
}
- StandaloneDocker::query()->create([
- 'name' => $this->server->name.'-'.$name,
- 'network' => $name,
- 'server_id' => $this->server->id,
- ]);
$this->createNetworkAndAttachToProxy();
}
}
public function scan()
{
- $alreadyAddedNetworks = $this->server->isSwarm() ? $this->server->swarmDockers : $this->server->standaloneDockers;
+ if ($this->server->isSwarm()) {
+ $alreadyAddedNetworks = $this->server->swarmDockers;
+ } else {
+ $alreadyAddedNetworks = $this->server->standaloneDockers;
+ }
$networks = instant_remote_process(['docker network ls --format "{{json .}}"'], $this->server, false);
$this->networks = format_docker_command_output_to_json($networks)->filter(function ($network) {
return $network['Name'] !== 'bridge' && $network['Name'] !== 'host' && $network['Name'] !== 'none';
diff --git a/app/Livewire/Server/LogDrains.php b/app/Livewire/Server/LogDrains.php
index 1bad68d712..edddfc7557 100644
--- a/app/Livewire/Server/LogDrains.php
+++ b/app/Livewire/Server/LogDrains.php
@@ -7,7 +7,6 @@
use App\Models\Server;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class LogDrains extends Component
{
@@ -45,11 +44,9 @@ public function mount(string $server_uuid)
try {
$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function syncDataNewRelic(bool $toModel = false)
@@ -107,16 +104,18 @@ public function syncData(bool $toModel = false, ?string $type = null)
$this->syncDataCustom($toModel);
}
$this->server->settings->save();
- } elseif ($type === 'newrelic') {
- $this->syncDataNewRelic($toModel);
- } elseif ($type === 'axiom') {
- $this->syncDataAxiom($toModel);
- } elseif ($type === 'custom') {
- $this->syncDataCustom($toModel);
} else {
- $this->syncDataNewRelic($toModel);
- $this->syncDataAxiom($toModel);
- $this->syncDataCustom($toModel);
+ if ($type === 'newrelic') {
+ $this->syncDataNewRelic($toModel);
+ } elseif ($type === 'axiom') {
+ $this->syncDataAxiom($toModel);
+ } elseif ($type === 'custom') {
+ $this->syncDataCustom($toModel);
+ } else {
+ $this->syncDataNewRelic($toModel);
+ $this->syncDataAxiom($toModel);
+ $this->syncDataCustom($toModel);
+ }
}
}
@@ -128,7 +127,7 @@ public function customValidation()
'logDrainNewRelicLicenseKey' => ['required'],
'logDrainNewRelicBaseUri' => ['required', 'url'],
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->isLogDrainNewRelicEnabled = false;
throw $e;
@@ -139,7 +138,7 @@ public function customValidation()
'logDrainAxiomDatasetName' => ['required'],
'logDrainAxiomApiKey' => ['required'],
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->isLogDrainAxiomEnabled = false;
throw $e;
@@ -150,7 +149,7 @@ public function customValidation()
'logDrainCustomConfig' => ['required'],
'logDrainCustomConfigParser' => ['string', 'nullable'],
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->isLogDrainCustomEnabled = false;
throw $e;
@@ -169,11 +168,9 @@ public function instantSave()
StopLogDrain::run($this->server);
$this->dispatch('success', 'Log drain service stopped.');
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit(string $type)
@@ -181,11 +178,9 @@ public function submit(string $type)
try {
$this->syncData(true, $type);
$this->dispatch('success', 'Settings saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/New/ByIp.php b/app/Livewire/Server/New/ByIp.php
index 5d5169ff82..5f60c5db5e 100644
--- a/app/Livewire/Server/New/ByIp.php
+++ b/app/Livewire/Server/New/ByIp.php
@@ -9,7 +9,6 @@
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class ByIp extends Component
{
@@ -53,7 +52,7 @@ class ByIp extends Component
public bool $is_swarm_worker = false;
#[Validate('nullable|integer', as: 'Swarm Cluster')]
- public $selected_swarm_cluster;
+ public $selected_swarm_cluster = null;
#[Validate('required|boolean', as: 'Build Server')]
public bool $is_build_server = false;
@@ -85,7 +84,7 @@ public function submit()
{
$this->validate();
try {
- if (Server::query()->where('team_id', currentTeam()->id)
+ if (Server::where('team_id', currentTeam()->id)
->where('ip', $this->ip)
->exists()) {
return $this->dispatch('error', 'This IP/Domain is already in use by another server in your team.');
@@ -112,7 +111,7 @@ public function submit()
if ($this->is_build_server) {
data_forget($payload, 'proxy');
}
- $server = Server::query()->create($payload);
+ $server = Server::create($payload);
$server->proxy->set('status', 'exited');
$server->proxy->set('type', ProxyTypes::TRAEFIK->value);
$server->save();
@@ -127,7 +126,7 @@ public function submit()
$server->settings->save();
return redirect()->route('server.show', $server->uuid);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Server/PrivateKey/Show.php b/app/Livewire/Server/PrivateKey/Show.php
index 614629d8d0..64aa1884ba 100644
--- a/app/Livewire/Server/PrivateKey/Show.php
+++ b/app/Livewire/Server/PrivateKey/Show.php
@@ -4,9 +4,7 @@
use App\Models\PrivateKey;
use App\Models\Server;
-use Exception;
use Livewire\Component;
-use Throwable;
class Show extends Component
{
@@ -21,11 +19,9 @@ public function mount(string $server_uuid)
try {
$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
$this->privateKeys = PrivateKey::ownedByCurrentTeam()->get()->where('is_git_related', false);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function setPrivateKey($privateKeyId)
@@ -44,9 +40,9 @@ public function setPrivateKey($privateKeyId)
if ($uptime) {
$this->dispatch('success', 'Private key updated successfully.');
} else {
- throw new Exception($error);
+ throw new \Exception($error);
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->server->update(['private_key_id' => $originalPrivateKeyId]);
$this->server->validateConnection();
$this->dispatch('error', $e->getMessage());
@@ -62,13 +58,11 @@ public function checkConnection()
} else {
$this->dispatch('error', 'Server is not reachable.
Check this documentation for further help.
Error: '.$error);
- return null;
+ return;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/Proxy.php b/app/Livewire/Server/Proxy.php
index 97f0a76aa9..4e325c1ff6 100644
--- a/app/Livewire/Server/Proxy.php
+++ b/app/Livewire/Server/Proxy.php
@@ -6,7 +6,6 @@
use App\Actions\Proxy\SaveConfiguration;
use App\Models\Server;
use Livewire\Component;
-use Throwable;
class Proxy extends Component
{
@@ -14,7 +13,7 @@ class Proxy extends Component
public ?string $selectedProxy = null;
- public $proxy_settings;
+ public $proxy_settings = null;
public bool $redirect_enabled = true;
@@ -51,11 +50,9 @@ public function selectProxy($proxy_type)
$this->server->changeProxy($proxy_type, async: false);
$this->selectedProxy = $this->server->proxy->type;
$this->dispatch('reloadWindow');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
@@ -64,11 +61,9 @@ public function instantSave()
$this->validate();
$this->server->settings->save();
$this->dispatch('success', 'Settings saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSaveRedirect()
@@ -78,11 +73,9 @@ public function instantSaveRedirect()
$this->server->save();
$this->server->setupDefaultRedirect();
$this->dispatch('success', 'Proxy configuration saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -93,11 +86,9 @@ public function submit()
$this->server->save();
$this->server->setupDefaultRedirect();
$this->dispatch('success', 'Proxy configuration saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function reset_proxy_configuration()
@@ -107,11 +98,9 @@ public function reset_proxy_configuration()
SaveConfiguration::run($this->server, $this->proxy_settings);
$this->server->save();
$this->dispatch('success', 'Proxy configuration saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function loadProxyConfiguration()
@@ -123,10 +112,8 @@ public function loadProxyConfiguration()
} else {
$this->dispatch('traefikDashboardAvailable', false);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Server/Proxy/Deploy.php b/app/Livewire/Server/Proxy/Deploy.php
index 6188f06f34..4f9d410923 100644
--- a/app/Livewire/Server/Proxy/Deploy.php
+++ b/app/Livewire/Server/Proxy/Deploy.php
@@ -10,7 +10,6 @@
use Illuminate\Process\InvokedProcess;
use Illuminate\Support\Facades\Process;
use Livewire\Component;
-use Throwable;
class Deploy extends Component
{
@@ -39,7 +38,11 @@ public function getListeners()
public function mount()
{
- $this->serverIp = $this->server->id === 0 ? base_ip() : $this->server->ip;
+ if ($this->server->id === 0) {
+ $this->serverIp = base_ip();
+ } else {
+ $this->serverIp = $this->server->ip;
+ }
$this->currentRoute = request()->route()->getName();
}
@@ -64,11 +67,9 @@ public function restart()
try {
$this->stop();
$this->dispatch('checkProxy');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function checkProxy()
@@ -77,11 +78,9 @@ public function checkProxy()
CheckProxy::run($this->server, true);
$this->dispatch('startProxyPolling');
$this->dispatch('proxyChecked');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function startProxy()
@@ -91,11 +90,9 @@ public function startProxy()
$this->server->save();
$activity = StartProxy::run($this->server, force: true);
$this->dispatch('activityMonitor', $activity->id, ProxyStatusChanged::class);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function stop(bool $forceStop = true)
@@ -117,7 +114,7 @@ public function stop(bool $forceStop = true)
}
$this->removeContainer($containerName);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
} finally {
$this->server->proxy->force_stop = $forceStop;
@@ -125,8 +122,6 @@ public function stop(bool $forceStop = true)
$this->server->save();
$this->dispatch('proxyStatusUpdated');
}
-
- return null;
}
private function stopContainer(string $containerName, int $timeout): InvokedProcess
diff --git a/app/Livewire/Server/Proxy/DynamicConfigurations.php b/app/Livewire/Server/Proxy/DynamicConfigurations.php
index f01d666735..6277a24bd4 100644
--- a/app/Livewire/Server/Proxy/DynamicConfigurations.php
+++ b/app/Livewire/Server/Proxy/DynamicConfigurations.php
@@ -5,7 +5,6 @@
use App\Models\Server;
use Illuminate\Support\Collection;
use Livewire\Component;
-use Throwable;
class DynamicConfigurations extends Component
{
@@ -33,7 +32,7 @@ public function loadDynamicConfigurations()
{
$proxy_path = $this->server->proxyPath();
$files = instant_remote_process(["mkdir -p $proxy_path/dynamic && ls -1 {$proxy_path}/dynamic"], $this->server);
- $files = collect(explode("\n", $files))->reject(fn ($file): bool => $file === '' || $file === '0');
+ $files = collect(explode("\n", $files))->filter(fn ($file) => ! empty($file));
$files = $files->map(fn ($file) => trim($file));
$files = $files->sort();
$contents = collect([]);
@@ -53,11 +52,9 @@ public function mount()
if (is_null($this->server)) {
return redirect()->route('server.index');
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/Proxy/Logs.php b/app/Livewire/Server/Proxy/Logs.php
index e2578f1ea2..8e0f40c54e 100644
--- a/app/Livewire/Server/Proxy/Logs.php
+++ b/app/Livewire/Server/Proxy/Logs.php
@@ -4,7 +4,6 @@
use App\Models\Server;
use Livewire\Component;
-use Throwable;
class Logs extends Component
{
@@ -20,11 +19,9 @@ public function mount()
if (is_null($this->server)) {
return redirect()->route('server.index');
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/Proxy/NewDynamicConfiguration.php b/app/Livewire/Server/Proxy/NewDynamicConfiguration.php
index 096700d8e0..2155f1e82d 100644
--- a/app/Livewire/Server/Proxy/NewDynamicConfiguration.php
+++ b/app/Livewire/Server/Proxy/NewDynamicConfiguration.php
@@ -6,7 +6,6 @@
use App\Models\Server;
use Livewire\Component;
use Symfony\Component\Yaml\Yaml;
-use Throwable;
class NewDynamicConfiguration extends Component
{
@@ -54,7 +53,7 @@ public function addDynamicConfiguration()
if ($this->fileName === 'coolify.yaml') {
$this->dispatch('error', 'File name is reserved.');
- return null;
+ return;
}
} elseif ($proxy_type === 'CADDY') {
if (! str($this->fileName)->endsWith('.caddy')) {
@@ -68,7 +67,7 @@ public function addDynamicConfiguration()
if ($exists == 1) {
$this->dispatch('error', 'File already exists');
- return null;
+ return;
}
}
if ($proxy_type === ProxyTypes::TRAEFIK->value) {
@@ -86,11 +85,9 @@ public function addDynamicConfiguration()
$this->dispatch('loadDynamicConfigurations');
$this->dispatch('dynamic-configuration-added');
$this->dispatch('success', 'Dynamic configuration saved.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/Proxy/Show.php b/app/Livewire/Server/Proxy/Show.php
index 507cea7b02..5ecb56a691 100644
--- a/app/Livewire/Server/Proxy/Show.php
+++ b/app/Livewire/Server/Proxy/Show.php
@@ -4,7 +4,6 @@
use App\Models\Server;
use Livewire\Component;
-use Throwable;
class Show extends Component
{
@@ -24,11 +23,9 @@ public function mount()
$this->parameters = get_route_parameters();
try {
$this->server = Server::ownedByCurrentTeam()->whereUuid(request()->server_uuid)->firstOrFail();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/Proxy/Status.php b/app/Livewire/Server/Proxy/Status.php
index 5750a12bd4..f4f18381f8 100644
--- a/app/Livewire/Server/Proxy/Status.php
+++ b/app/Livewire/Server/Proxy/Status.php
@@ -7,7 +7,6 @@
use App\Actions\Proxy\StartProxy;
use App\Models\Server;
use Livewire\Component;
-use Throwable;
class Status extends Component
{
@@ -39,11 +38,9 @@ public function checkProxy(bool $notification = false)
if ($this->numberOfPolls >= 10) {
$this->polling = false;
$this->numberOfPolls = 0;
- if ($notification) {
- $this->dispatch('error', 'Proxy is not running.');
- }
+ $notification && $this->dispatch('error', 'Proxy is not running.');
- return null;
+ return;
}
$this->numberOfPolls++;
}
@@ -54,25 +51,17 @@ public function checkProxy(bool $notification = false)
$this->dispatch('proxyStatusUpdated');
if ($this->server->proxy->status === 'running') {
$this->polling = false;
- if ($notification) {
- $this->dispatch('success', 'Proxy is running.');
- }
- } elseif ($this->server->proxy->status === 'exited' && ! $this->server->proxy->force_stop) {
- if ($notification) {
- $this->dispatch('error', 'Proxy has exited.');
- }
+ $notification && $this->dispatch('success', 'Proxy is running.');
+ } elseif ($this->server->proxy->status === 'exited' and ! $this->server->proxy->force_stop) {
+ $notification && $this->dispatch('error', 'Proxy has exited.');
} elseif ($this->server->proxy->force_stop) {
- if ($notification) {
- $this->dispatch('error', 'Proxy is stopped manually.');
- }
- } elseif ($notification) {
- $this->dispatch('error', 'Proxy is not running.');
+ $notification && $this->dispatch('error', 'Proxy is stopped manually.');
+ } else {
+ $notification && $this->dispatch('error', 'Proxy is not running.');
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function getProxyStatus()
@@ -81,10 +70,8 @@ public function getProxyStatus()
GetContainersStatus::run($this->server);
// dispatch_sync(new ContainerStatusJob($this->server));
$this->dispatch('proxyStatusUpdated');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Server/Resources.php b/app/Livewire/Server/Resources.php
index cf3eb6c2c1..f549b43cbd 100644
--- a/app/Livewire/Server/Resources.php
+++ b/app/Livewire/Server/Resources.php
@@ -6,7 +6,6 @@
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
use Livewire\Component;
-use Throwable;
class Resources extends Component
{
@@ -66,11 +65,9 @@ public function loadManagedContainers()
try {
$this->activeTab = 'managed';
$this->containers = $this->server->refresh()->definedResources();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function loadUnmanagedContainers()
@@ -78,11 +75,9 @@ public function loadUnmanagedContainers()
$this->activeTab = 'unmanaged';
try {
$this->containers = $this->server->loadUnmanagedContainers();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function mount()
@@ -95,11 +90,9 @@ public function mount()
return redirect()->route('server.index');
}
$this->loadManagedContainers();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/Show.php b/app/Livewire/Server/Show.php
index 4e36e0e5a1..6d267b9c89 100644
--- a/app/Livewire/Server/Show.php
+++ b/app/Livewire/Server/Show.php
@@ -6,11 +6,9 @@
use App\Actions\Server\StopSentinel;
use App\Events\ServerReachabilityChanged;
use App\Models\Server;
-use Exception;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Show extends Component
{
@@ -97,11 +95,9 @@ public function mount(string $server_uuid)
try {
$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
$this->syncData();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
#[Computed]
@@ -118,12 +114,12 @@ public function syncData(bool $toModel = false)
if ($toModel) {
$this->validate();
- if (Server::query()->where('team_id', currentTeam()->id)
+ if (Server::where('team_id', currentTeam()->id)
->where('ip', $this->ip)
->where('id', '!=', $this->server->id)
->exists()) {
$this->ip = $this->server->ip;
- throw new Exception('This IP/Domain is already in use by another server in your team.');
+ throw new \Exception('This IP/Domain is already in use by another server in your team.');
}
$this->server->name = $this->name;
@@ -149,9 +145,10 @@ public function syncData(bool $toModel = false)
if (! validate_timezone($this->serverTimezone)) {
$this->serverTimezone = config('app.timezone');
- throw new Exception('Invalid timezone.');
+ throw new \Exception('Invalid timezone.');
+ } else {
+ $this->server->settings->server_timezone = $this->serverTimezone;
}
- $this->server->settings->server_timezone = $this->serverTimezone;
$this->server->settings->save();
} else {
@@ -192,11 +189,9 @@ public function validateServer($install = true)
$this->validationLogs = $this->server->validation_logs = null;
$this->server->save();
$this->dispatch('init', $install);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function checkLocalhostConnection()
@@ -253,11 +248,9 @@ public function regenerateSentinelToken()
try {
$this->server->settings->generateSentinelToken();
$this->dispatch('success', 'Token regenerated & Sentinel restarted.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
@@ -270,11 +263,9 @@ public function submit()
try {
$this->syncData(true);
$this->dispatch('success', 'Server updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Server/ValidateAndInstall.php b/app/Livewire/Server/ValidateAndInstall.php
index 1c73537a97..791ef93501 100644
--- a/app/Livewire/Server/ValidateAndInstall.php
+++ b/app/Livewire/Server/ValidateAndInstall.php
@@ -5,9 +5,7 @@
use App\Actions\Proxy\CheckProxy;
use App\Actions\Proxy\StartProxy;
use App\Models\Server;
-use Exception;
use Livewire\Component;
-use Throwable;
class ValidateAndInstall extends Component
{
@@ -19,19 +17,19 @@ class ValidateAndInstall extends Component
public bool $install = true;
- public $uptime;
+ public $uptime = null;
- public $supported_os_type;
+ public $supported_os_type = null;
- public $docker_installed;
+ public $docker_installed = null;
- public $docker_compose_installed;
+ public $docker_compose_installed = null;
- public $docker_version;
+ public $docker_version = null;
public $proxy_started = false;
- public $error;
+ public $error = null;
public bool $ask = false;
@@ -75,16 +73,14 @@ public function startProxy()
if ($proxy === 'OK') {
$this->proxy_started = true;
} else {
- throw new Exception('Proxy could not be started.');
+ throw new \Exception('Proxy could not be started.');
}
} else {
$this->proxy_started = true;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function validateConnection()
@@ -121,28 +117,30 @@ public function validateDockerEngine()
$this->docker_compose_installed = $this->server->validateDockerCompose();
if (! $this->docker_installed || ! $this->docker_compose_installed) {
if ($this->install) {
- if ($this->number_of_tries === $this->max_tries) {
+ if ($this->number_of_tries == $this->max_tries) {
$this->error = 'Docker Engine could not be installed. Please install Docker manually before continuing: documentation.';
$this->server->update([
'validation_logs' => $this->error,
]);
+ return;
+ } else {
+ if ($this->number_of_tries <= $this->max_tries) {
+ $activity = $this->server->installDocker();
+ $this->number_of_tries++;
+ $this->dispatch('newActivityMonitor', $activity->id, 'init', $this->number_of_tries);
+ }
+
return;
}
- if ($this->number_of_tries <= $this->max_tries) {
- $activity = $this->server->installDocker();
- $this->number_of_tries++;
- $this->dispatch('newActivityMonitor', $activity->id, 'init', $this->number_of_tries);
- }
+ } else {
+ $this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: documentation.';
+ $this->server->update([
+ 'validation_logs' => $this->error,
+ ]);
return;
}
- $this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: documentation.';
- $this->server->update([
- 'validation_logs' => $this->error,
- ]);
-
- return;
}
$this->dispatch('validateDockerVersion');
}
diff --git a/app/Livewire/Settings/Index.php b/app/Livewire/Settings/Index.php
index 29dc61969d..3d90024b7e 100644
--- a/app/Livewire/Settings/Index.php
+++ b/app/Livewire/Settings/Index.php
@@ -5,7 +5,6 @@
use App\Jobs\CheckForUpdatesJob;
use App\Models\InstanceSettings;
use App\Models\Server;
-use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Attributes\Computed;
@@ -78,27 +77,26 @@ public function mount()
{
if (! isInstanceAdmin()) {
return redirect()->route('dashboard');
+ } else {
+ $this->settings = instanceSettings();
+ $this->fqdn = $this->settings->fqdn;
+ $this->public_port_min = $this->settings->public_port_min;
+ $this->public_port_max = $this->settings->public_port_max;
+ $this->custom_dns_servers = $this->settings->custom_dns_servers;
+ $this->instance_name = $this->settings->instance_name;
+ $this->allowed_ips = $this->settings->allowed_ips;
+ $this->public_ipv4 = $this->settings->public_ipv4;
+ $this->public_ipv6 = $this->settings->public_ipv6;
+ $this->do_not_track = $this->settings->do_not_track;
+ $this->is_auto_update_enabled = $this->settings->is_auto_update_enabled;
+ $this->is_registration_enabled = $this->settings->is_registration_enabled;
+ $this->is_dns_validation_enabled = $this->settings->is_dns_validation_enabled;
+ $this->is_api_enabled = $this->settings->is_api_enabled;
+ $this->auto_update_frequency = $this->settings->auto_update_frequency;
+ $this->update_check_frequency = $this->settings->update_check_frequency;
+ $this->instance_timezone = $this->settings->instance_timezone;
+ $this->disable_two_step_confirmation = $this->settings->disable_two_step_confirmation;
}
- $this->settings = instanceSettings();
- $this->fqdn = $this->settings->fqdn;
- $this->public_port_min = $this->settings->public_port_min;
- $this->public_port_max = $this->settings->public_port_max;
- $this->custom_dns_servers = $this->settings->custom_dns_servers;
- $this->instance_name = $this->settings->instance_name;
- $this->allowed_ips = $this->settings->allowed_ips;
- $this->public_ipv4 = $this->settings->public_ipv4;
- $this->public_ipv6 = $this->settings->public_ipv6;
- $this->do_not_track = $this->settings->do_not_track;
- $this->is_auto_update_enabled = $this->settings->is_auto_update_enabled;
- $this->is_registration_enabled = $this->settings->is_registration_enabled;
- $this->is_dns_validation_enabled = $this->settings->is_dns_validation_enabled;
- $this->is_api_enabled = $this->settings->is_api_enabled;
- $this->auto_update_frequency = $this->settings->auto_update_frequency;
- $this->update_check_frequency = $this->settings->update_check_frequency;
- $this->instance_timezone = $this->settings->instance_timezone;
- $this->disable_two_step_confirmation = $this->settings->disable_two_step_confirmation;
-
- return null;
}
#[Computed]
@@ -146,43 +144,46 @@ public function submit()
{
try {
$error_show = false;
- $this->server = Server::query()->findOrFail(0);
+ $this->server = Server::findOrFail(0);
$this->resetErrorBag();
if (! validate_timezone($this->instance_timezone)) {
$this->instance_timezone = config('app.timezone');
- throw new Exception('Invalid timezone.');
+ throw new \Exception('Invalid timezone.');
+ } else {
+ $this->settings->instance_timezone = $this->instance_timezone;
}
- $this->settings->instance_timezone = $this->instance_timezone;
if ($this->settings->public_port_min > $this->settings->public_port_max) {
$this->addError('settings.public_port_min', 'The minimum port must be lower than the maximum port.');
- return null;
+ return;
}
$this->validate();
if ($this->is_auto_update_enabled && ! validate_cron_expression($this->auto_update_frequency)) {
$this->dispatch('error', 'Invalid Cron / Human expression for Auto Update Frequency.');
- if (! isset($this->auto_update_frequency) || ($this->auto_update_frequency === '' || $this->auto_update_frequency === '0')) {
+ if (empty($this->auto_update_frequency)) {
$this->auto_update_frequency = '0 0 * * *';
}
- return null;
+ return;
}
if (! validate_cron_expression($this->update_check_frequency)) {
$this->dispatch('error', 'Invalid Cron / Human expression for Update Check Frequency.');
- if (! isset($this->update_check_frequency) || ($this->update_check_frequency === '' || $this->update_check_frequency === '0')) {
+ if (empty($this->update_check_frequency)) {
$this->update_check_frequency = '0 * * * *';
}
- return null;
+ return;
}
- if ($this->settings->is_dns_validation_enabled && $this->settings->fqdn && ! validate_dns_entry($this->settings->fqdn, $this->server)) {
- $this->dispatch('error', "Validating DNS failed.
Make sure you have added the DNS records correctly.
{$this->settings->fqdn}->{$this->server->ip}
Check this documentation for further help.");
- $error_show = true;
+ if ($this->settings->is_dns_validation_enabled && $this->settings->fqdn) {
+ if (! validate_dns_entry($this->settings->fqdn, $this->server)) {
+ $this->dispatch('error', "Validating DNS failed.
Make sure you have added the DNS records correctly.
{$this->settings->fqdn}->{$this->server->ip}
Check this documentation for further help.");
+ $error_show = true;
+ }
}
if ($this->settings->fqdn) {
check_domain_usage(domain: $this->settings->fqdn);
@@ -208,11 +209,9 @@ public function submit()
if (! $error_show) {
$this->dispatch('success', 'Instance settings updated successfully!');
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function checkManually()
diff --git a/app/Livewire/SettingsBackup.php b/app/Livewire/SettingsBackup.php
index 275c0f4b0a..1b0599ffee 100644
--- a/app/Livewire/SettingsBackup.php
+++ b/app/Livewire/SettingsBackup.php
@@ -6,9 +6,7 @@
use App\Models\S3Storage;
use App\Models\ScheduledDatabaseBackup;
use App\Models\Server;
-use App\Models\StandaloneDocker;
use App\Models\StandalonePostgresql;
-use Exception;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
@@ -46,40 +44,39 @@ public function mount()
{
if (! isInstanceAdmin()) {
return redirect()->route('dashboard');
- }
- $settings = instanceSettings();
- $this->database = StandalonePostgresql::whereName('coolify-db')->first();
- $s3s = S3Storage::whereTeamId(0)->get() ?? [];
- if ($this->database instanceof StandalonePostgresql) {
- $this->uuid = $this->database->uuid;
- $this->name = $this->database->name;
- $this->description = $this->database->description;
- $this->postgres_user = $this->database->postgres_user;
- $this->postgres_password = $this->database->postgres_password;
-
- if ($this->database->status !== 'running') {
- $this->database->status = 'running';
- $this->database->save();
+ } else {
+ $settings = instanceSettings();
+ $this->database = StandalonePostgresql::whereName('coolify-db')->first();
+ $s3s = S3Storage::whereTeamId(0)->get() ?? [];
+ if ($this->database) {
+ $this->uuid = $this->database->uuid;
+ $this->name = $this->database->name;
+ $this->description = $this->database->description;
+ $this->postgres_user = $this->database->postgres_user;
+ $this->postgres_password = $this->database->postgres_password;
+
+ if ($this->database->status !== 'running') {
+ $this->database->status = 'running';
+ $this->database->save();
+ }
+ $this->backup = $this->database->scheduledBackups->first();
+ $this->executions = $this->backup->executions;
}
- $this->backup = $this->database->scheduledBackups->first();
- $this->executions = $this->backup->executions;
+ $this->settings = $settings;
+ $this->s3s = $s3s;
}
- $this->settings = $settings;
- $this->s3s = $s3s;
-
- return null;
}
public function addCoolifyDatabase()
{
try {
- $server = Server::query()->findOrFail(0);
+ $server = Server::findOrFail(0);
$out = instant_remote_process(['docker inspect coolify-db'], $server);
$envs = format_docker_envs_to_json($out);
$postgres_password = $envs['POSTGRES_PASSWORD'];
$postgres_user = $envs['POSTGRES_USER'];
$postgres_db = $envs['POSTGRES_DB'];
- $this->database = StandalonePostgresql::query()->create([
+ $this->database = StandalonePostgresql::create([
'id' => 0,
'name' => 'coolify-db',
'description' => 'Coolify database',
@@ -87,16 +84,16 @@ public function addCoolifyDatabase()
'postgres_password' => $postgres_password,
'postgres_db' => $postgres_db,
'status' => 'running',
- 'destination_type' => StandaloneDocker::class,
+ 'destination_type' => \App\Models\StandaloneDocker::class,
'destination_id' => 0,
]);
- $this->backup = ScheduledDatabaseBackup::query()->create([
+ $this->backup = ScheduledDatabaseBackup::create([
'id' => 0,
'enabled' => true,
'save_s3' => false,
'frequency' => '0 0 * * *',
'database_id' => $this->database->id,
- 'database_type' => StandalonePostgresql::class,
+ 'database_type' => \App\Models\StandalonePostgresql::class,
'team_id' => currentTeam()->id,
]);
$this->database->refresh();
@@ -110,11 +107,9 @@ public function addCoolifyDatabase()
$this->postgres_password = $this->database->postgres_password;
$this->executions = $this->backup->executions;
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
diff --git a/app/Livewire/SettingsEmail.php b/app/Livewire/SettingsEmail.php
index bbdc23034b..058f080e42 100644
--- a/app/Livewire/SettingsEmail.php
+++ b/app/Livewire/SettingsEmail.php
@@ -5,12 +5,10 @@
use App\Models\InstanceSettings;
use App\Models\Team;
use App\Notifications\Test;
-use Exception;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class SettingsEmail extends Component
{
@@ -67,8 +65,6 @@ public function mount()
$this->syncData();
$this->team = auth()->user()->currentTeam();
$this->testEmailAddress = auth()->user()->email;
-
- return null;
}
public function syncData(bool $toModel = false)
@@ -110,11 +106,9 @@ public function submit()
$this->resetErrorBag();
$this->syncData(true);
$this->dispatch('success', 'Transactional email settings updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave(string $type)
@@ -128,7 +122,7 @@ public function instantSave(string $type)
$this->submitResend();
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
if ($type === 'SMTP') {
$this->smtpEnabled = false;
} elseif ($type === 'Resend') {
@@ -137,8 +131,6 @@ public function instantSave(string $type)
return handleError($e, $this);
}
-
- return null;
}
public function submitSmtp()
@@ -180,13 +172,11 @@ public function submitSmtp()
$this->settings->save();
$this->dispatch('success', 'SMTP settings updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->smtpEnabled = false;
return handleError($e);
}
-
- return null;
}
public function submitResend()
@@ -215,13 +205,11 @@ public function submitResend()
$this->settings->save();
$this->dispatch('success', 'Resend settings updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->resendEnabled = false;
return handleError($e);
}
-
- return null;
}
public function sendTestEmail()
@@ -245,12 +233,10 @@ function () {
);
if (! $executed) {
- throw new Exception('Too many messages sent!');
+ throw new \Exception('Too many messages sent!');
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
-
- return null;
}
}
diff --git a/app/Livewire/SettingsOauth.php b/app/Livewire/SettingsOauth.php
index 01c76a459b..e23f94a73b 100644
--- a/app/Livewire/SettingsOauth.php
+++ b/app/Livewire/SettingsOauth.php
@@ -3,7 +3,6 @@
namespace App\Livewire;
use App\Models\OauthSetting;
-use Exception;
use Livewire\Component;
class SettingsOauth extends Component
@@ -34,8 +33,6 @@ public function mount()
return $carry;
}, []);
-
- return null;
}
private function updateOauthSettings(?string $provider = null)
@@ -44,7 +41,7 @@ private function updateOauthSettings(?string $provider = null)
$oauth = $this->oauth_settings_map[$provider];
if (! $oauth->couldBeEnabled()) {
$oauth->update(['enabled' => false]);
- throw new Exception('OAuth settings are not complete for '.$oauth->provider.'.
Please fill in all required fields.');
+ throw new \Exception('OAuth settings are not complete for '.$oauth->provider.'.
Please fill in all required fields.');
}
$oauth->save();
$this->dispatch('success', 'OAuth settings for '.$oauth->provider.' updated successfully!');
@@ -59,11 +56,9 @@ public function instantSave(string $provider)
{
try {
$this->updateOauthSettings($provider);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
diff --git a/app/Livewire/SharedVariables/Environment/Show.php b/app/Livewire/SharedVariables/Environment/Show.php
index 4495375ace..e88ac5f135 100644
--- a/app/Livewire/SharedVariables/Environment/Show.php
+++ b/app/Livewire/SharedVariables/Environment/Show.php
@@ -4,9 +4,7 @@
use App\Models\Application;
use App\Models\Project;
-use Exception;
use Livewire\Component;
-use Throwable;
class Show extends Component
{
@@ -25,7 +23,7 @@ public function saveKey($data)
try {
$found = $this->environment->environment_variables()->where('key', $data['key'])->first();
if ($found) {
- throw new Exception('Variable already exists.');
+ throw new \Exception('Variable already exists.');
}
$this->environment->environment_variables()->create([
'key' => $data['key'],
@@ -36,11 +34,9 @@ public function saveKey($data)
'team_id' => currentTeam()->id,
]);
$this->environment->refresh();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function mount()
diff --git a/app/Livewire/SharedVariables/Project/Show.php b/app/Livewire/SharedVariables/Project/Show.php
index 79d217e655..0171283c4a 100644
--- a/app/Livewire/SharedVariables/Project/Show.php
+++ b/app/Livewire/SharedVariables/Project/Show.php
@@ -3,9 +3,7 @@
namespace App\Livewire\SharedVariables\Project;
use App\Models\Project;
-use Exception;
use Livewire\Component;
-use Throwable;
class Show extends Component
{
@@ -18,7 +16,7 @@ public function saveKey($data)
try {
$found = $this->project->environment_variables()->where('key', $data['key'])->first();
if ($found) {
- throw new Exception('Variable already exists.');
+ throw new \Exception('Variable already exists.');
}
$this->project->environment_variables()->create([
'key' => $data['key'],
@@ -29,24 +27,20 @@ public function saveKey($data)
'team_id' => currentTeam()->id,
]);
$this->project->refresh();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function mount()
{
$projectUuid = request()->route('project_uuid');
$teamId = currentTeam()->id;
- $project = Project::query()->where('team_id', $teamId)->where('uuid', $projectUuid)->first();
+ $project = Project::where('team_id', $teamId)->where('uuid', $projectUuid)->first();
if (! $project) {
return redirect()->route('dashboard');
}
$this->project = $project;
-
- return null;
}
public function render()
diff --git a/app/Livewire/SharedVariables/Team/Index.php b/app/Livewire/SharedVariables/Team/Index.php
index 3de2b86faa..a76ccf58a6 100644
--- a/app/Livewire/SharedVariables/Team/Index.php
+++ b/app/Livewire/SharedVariables/Team/Index.php
@@ -3,9 +3,7 @@
namespace App\Livewire\SharedVariables\Team;
use App\Models\Team;
-use Exception;
use Livewire\Component;
-use Throwable;
class Index extends Component
{
@@ -18,7 +16,7 @@ public function saveKey($data)
try {
$found = $this->team->environment_variables()->where('key', $data['key'])->first();
if ($found) {
- throw new Exception('Variable already exists.');
+ throw new \Exception('Variable already exists.');
}
$this->team->environment_variables()->create([
'key' => $data['key'],
@@ -29,11 +27,9 @@ public function saveKey($data)
'team_id' => currentTeam()->id,
]);
$this->team->refresh();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function mount()
diff --git a/app/Livewire/Source/Github/Change.php b/app/Livewire/Source/Github/Change.php
index 851212dc77..8f4f02f70f 100644
--- a/app/Livewire/Source/Github/Change.php
+++ b/app/Livewire/Source/Github/Change.php
@@ -5,13 +5,11 @@
use App\Jobs\GithubAppPermissionJob;
use App\Models\GithubApp;
use App\Models\PrivateKey;
-use DateTimeImmutable;
use Illuminate\Support\Facades\Http;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Livewire\Component;
-use Throwable;
class Change extends Component
{
@@ -60,7 +58,7 @@ class Change extends Component
public function boot()
{
- if ($this->github_app instanceof GithubApp) {
+ if ($this->github_app) {
$this->github_app->makeVisible(['client_secret', 'webhook_secret']);
}
}
@@ -153,11 +151,9 @@ public function mount()
$this->webhook_endpoint = $this->ipv4;
$this->is_system_wide = $this->github_app->is_system_wide;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function getGithubAppNameUpdatePath()
@@ -183,8 +179,8 @@ private function generateGithubJwt($private_key, $app_id): string
->issuedBy((string) $app_id)
->permittedFor('https://api.github.com')
->identifiedBy((string) $now)
- ->issuedAt(new DateTimeImmutable("@{$now}"))
- ->expiresAt(new DateTimeImmutable('@'.($now + 600)))
+ ->issuedAt(new \DateTimeImmutable("@{$now}"))
+ ->expiresAt(new \DateTimeImmutable('@'.($now + 600)))
->getToken($configuration->signer(), $configuration->signingKey())
->toString();
}
@@ -197,7 +193,7 @@ public function updateGithubAppName()
if (! $privateKey) {
$this->dispatch('error', 'No private key found for this GitHub App.');
- return null;
+ return;
}
$jwt = $this->generateGithubJwt($privateKey->private_key, $this->github_app->app_id);
@@ -226,11 +222,9 @@ public function updateGithubAppName()
$error_message = $response->json()['message'] ?? 'Unknown error';
$this->dispatch('error', "Failed to fetch GitHub App information: {$error_message}");
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function submit()
@@ -253,11 +247,9 @@ public function submit()
]);
$this->github_app->save();
$this->dispatch('success', 'Github App updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function instantSave()
@@ -266,11 +258,9 @@ public function instantSave()
$this->github_app->makeVisible('client_secret')->makeVisible('webhook_secret');
$this->github_app->save();
$this->dispatch('success', 'Github App updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function delete()
@@ -280,12 +270,12 @@ public function delete()
$this->dispatch('error', 'This source is being used by an application. Please delete all applications first.');
$this->github_app->makeVisible('client_secret')->makeVisible('webhook_secret');
- return null;
+ return;
}
$this->github_app->delete();
return redirect()->route('source.all');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Source/Github/Create.php b/app/Livewire/Source/Github/Create.php
index 0b6ede36f5..136d3525e0 100644
--- a/app/Livewire/Source/Github/Create.php
+++ b/app/Livewire/Source/Github/Create.php
@@ -4,7 +4,6 @@
use App\Models\GithubApp;
use Livewire\Component;
-use Throwable;
class Create extends Component
{
@@ -51,13 +50,13 @@ public function createGitHubApp()
if (isCloud()) {
$payload['is_system_wide'] = $this->is_system_wide;
}
- $github_app = GithubApp::query()->create($payload);
+ $github_app = GithubApp::create($payload);
if (session('from')) {
session(['from' => session('from') + ['source_id' => $github_app->id]]);
}
return redirect()->route('source.github.show', ['github_app_uuid' => $github_app->uuid]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Storage/Create.php b/app/Livewire/Storage/Create.php
index 6e45b42114..c5250e1e3b 100644
--- a/app/Livewire/Storage/Create.php
+++ b/app/Livewire/Storage/Create.php
@@ -4,7 +4,6 @@
use App\Models\S3Storage;
use Livewire\Component;
-use Throwable;
class Create extends Component
{
@@ -69,17 +68,19 @@ public function submit()
$this->storage->key = $this->key;
$this->storage->secret = $this->secret;
$this->storage->bucket = $this->bucket;
- $this->storage->endpoint = ! isset($this->endpoint) || ($this->endpoint === '' || $this->endpoint === '0') ? "https://s3.{$this->region}.amazonaws.com" : $this->endpoint;
+ if (empty($this->endpoint)) {
+ $this->storage->endpoint = "https://s3.{$this->region}.amazonaws.com";
+ } else {
+ $this->storage->endpoint = $this->endpoint;
+ }
$this->storage->team_id = currentTeam()->id;
$this->storage->testConnection();
$this->storage->save();
return redirect()->route('storage.show', $this->storage->uuid);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->dispatch('error', 'Failed to create storage.', $e->getMessage());
// return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Storage/Form.php b/app/Livewire/Storage/Form.php
index 2deecefdd9..8ca0020c7b 100644
--- a/app/Livewire/Storage/Form.php
+++ b/app/Livewire/Storage/Form.php
@@ -4,7 +4,6 @@
use App\Models\S3Storage;
use Livewire\Component;
-use Throwable;
class Form extends Component
{
@@ -38,11 +37,9 @@ public function test_s3_connection()
$this->storage->testConnection(shouldSave: true);
return $this->dispatch('success', 'Connection is working.', 'Tested with "ListObjectsV2" action.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->dispatch('error', 'Failed to create storage.', $e->getMessage());
}
-
- return null;
}
public function delete()
@@ -51,7 +48,7 @@ public function delete()
$this->storage->delete();
return redirect()->route('storage.index');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
@@ -61,10 +58,8 @@ public function submit()
$this->validate();
try {
$this->test_s3_connection();
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Storage/Show.php b/app/Livewire/Storage/Show.php
index b473435c69..bdea9a3b04 100644
--- a/app/Livewire/Storage/Show.php
+++ b/app/Livewire/Storage/Show.php
@@ -7,7 +7,7 @@
class Show extends Component
{
- public $storage;
+ public $storage = null;
public function mount()
{
diff --git a/app/Livewire/Subscription/Index.php b/app/Livewire/Subscription/Index.php
index a6f6b19421..df450cf7ef 100644
--- a/app/Livewire/Subscription/Index.php
+++ b/app/Livewire/Subscription/Index.php
@@ -25,15 +25,13 @@ public function mount()
}
$this->settings = instanceSettings();
$this->alreadySubscribed = currentTeam()->subscription()->exists();
-
- return null;
}
public function stripeCustomerPortal()
{
$session = getStripeCustomerPortalSession(currentTeam());
if (is_null($session)) {
- return null;
+ return;
}
return redirect($session->url);
diff --git a/app/Livewire/Subscription/PricingPlans.php b/app/Livewire/Subscription/PricingPlans.php
index c3099d70d8..6b2d3fb364 100644
--- a/app/Livewire/Subscription/PricingPlans.php
+++ b/app/Livewire/Subscription/PricingPlans.php
@@ -22,7 +22,7 @@ public function subscribeStripe($type)
if (! $priceId) {
$this->dispatch('error', 'Price ID not found! Please contact the administrator.');
- return null;
+ return;
}
$payload = [
'allow_promotion_codes' => true,
diff --git a/app/Livewire/Subscription/Show.php b/app/Livewire/Subscription/Show.php
index e0c17af8ae..96258c64e0 100644
--- a/app/Livewire/Subscription/Show.php
+++ b/app/Livewire/Subscription/Show.php
@@ -17,8 +17,6 @@ public function mount()
if (! data_get(currentTeam(), 'subscription')) {
return redirect()->route('subscription.index');
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/SwitchTeam.php b/app/Livewire/SwitchTeam.php
index 7d31dd5ab3..7629c95964 100644
--- a/app/Livewire/SwitchTeam.php
+++ b/app/Livewire/SwitchTeam.php
@@ -22,11 +22,11 @@ public function updatedSelectedTeamId()
public function switch_to($team_id)
{
if (! auth()->user()->teams->contains($team_id)) {
- return null;
+ return;
}
- $team_to_switch_to = Team::query()->find($team_id);
+ $team_to_switch_to = Team::find($team_id);
if (! $team_to_switch_to) {
- return null;
+ return;
}
refreshSession($team_to_switch_to);
diff --git a/app/Livewire/Tags/Deployments.php b/app/Livewire/Tags/Deployments.php
index 932b0a4305..e4afa5b606 100644
--- a/app/Livewire/Tags/Deployments.php
+++ b/app/Livewire/Tags/Deployments.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Tags;
use App\Models\ApplicationDeploymentQueue;
-use Exception;
use Livewire\Component;
class Deployments extends Component
@@ -20,7 +19,7 @@ public function render()
public function getDeployments()
{
try {
- $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $this->resourceIds)->get([
+ $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $this->resourceIds)->get([
'id',
'application_id',
'application_name',
@@ -31,10 +30,8 @@ public function getDeployments()
'status',
])->sortBy('id')->groupBy('server_name')->toArray();
$this->dispatch('deployments', $this->deploymentsPerTagPerServer);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/Tags/Show.php b/app/Livewire/Tags/Show.php
index 9955187c0a..fc5b133749 100644
--- a/app/Livewire/Tags/Show.php
+++ b/app/Livewire/Tags/Show.php
@@ -5,7 +5,6 @@
use App\Http\Controllers\Api\DeployController;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Tag;
-use Exception;
use Illuminate\Support\Collection;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Title;
@@ -47,18 +46,16 @@ public function mount()
$this->tag = $tag;
$this->getDeployments();
}
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function getDeployments()
{
try {
$resource_ids = $this->applications->pluck('id');
- $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::query()->whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $resource_ids)->get([
+ $this->deploymentsPerTagPerServer = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->whereIn('application_id', $resource_ids)->get([
'id',
'application_id',
'application_name',
@@ -68,11 +65,9 @@ public function getDeployments()
'server_id',
'status',
])->sortBy('id')->groupBy('server_name')->toArray();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function redeployAll()
@@ -88,11 +83,9 @@ public function redeployAll()
$message->push($deploy->deploy_resource($resource));
});
$this->dispatch('success', 'Mass deployment started.');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Livewire/Team/AdminView.php b/app/Livewire/Team/AdminView.php
index 58c46d51b2..cfb47d9d83 100644
--- a/app/Livewire/Team/AdminView.php
+++ b/app/Livewire/Team/AdminView.php
@@ -25,14 +25,12 @@ public function mount()
return redirect()->route('dashboard');
}
$this->getUsers();
-
- return null;
}
public function submitSearch()
{
if ($this->search !== '') {
- $this->users = User::query()->where(function ($query) {
+ $this->users = User::where(function ($query) {
$query->where('name', 'like', "%{$this->search}%")
->orWhere('email', 'like', "%{$this->search}%");
})->get()->filter(function ($user) {
@@ -45,7 +43,7 @@ public function submitSearch()
public function getUsers()
{
- $users = User::query()->where('id', '!=', auth()->id())->get();
+ $users = User::where('id', '!=', auth()->id())->get();
if ($users->count() > $this->number_of_users_to_show) {
$this->lots_of_users = true;
$this->users = $users->take($this->number_of_users_to_show);
@@ -79,20 +77,24 @@ public function delete($id, $password)
if (! isInstanceAdmin()) {
return redirect()->route('dashboard');
}
- if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation') && ! Hash::check($password, Auth::user()->password)) {
- $this->addError('password', 'The provided password is incorrect.');
+ if (! data_get(InstanceSettings::get(), 'disable_two_step_confirmation')) {
+ if (! Hash::check($password, Auth::user()->password)) {
+ $this->addError('password', 'The provided password is incorrect.');
- return null;
+ return;
+ }
}
if (! auth()->user()->isInstanceAdmin()) {
return $this->dispatch('error', 'You are not authorized to delete users');
}
- $user = User::query()->find($id);
+ $user = User::find($id);
$teams = $user->teams;
foreach ($teams as $team) {
$user_alone_in_team = $team->members->count() === 1;
- if ($team->id === 0 && $user_alone_in_team) {
- return $this->dispatch('error', 'User is alone in the root team, cannot delete');
+ if ($team->id === 0) {
+ if ($user_alone_in_team) {
+ return $this->dispatch('error', 'User is alone in the root team, cannot delete');
+ }
}
if ($user_alone_in_team) {
$this->finalizeDeletion($user, $team);
@@ -108,26 +110,26 @@ public function delete($id, $password)
$team->members()->detach($user->id);
continue;
- }
- $found_other_member_who_is_not_owner = $team->members->filter(function ($member) {
- return $member->pivot->role === 'member';
- })->first();
- if ($found_other_member_who_is_not_owner) {
- $found_other_member_who_is_not_owner->pivot->role = 'owner';
- $found_other_member_who_is_not_owner->pivot->save();
- $team->members()->detach($user->id);
} else {
- $this->finalizeDeletion($user, $team);
- }
+ $found_other_member_who_is_not_owner = $team->members->filter(function ($member) {
+ return $member->pivot->role === 'member';
+ })->first();
+ if ($found_other_member_who_is_not_owner) {
+ $found_other_member_who_is_not_owner->pivot->role = 'owner';
+ $found_other_member_who_is_not_owner->pivot->save();
+ $team->members()->detach($user->id);
+ } else {
+ $this->finalizeDeletion($user, $team);
+ }
- continue;
+ continue;
+ }
+ } else {
+ $team->members()->detach($user->id);
}
- $team->members()->detach($user->id);
}
$user->delete();
$this->getUsers();
-
- return null;
}
public function render()
diff --git a/app/Livewire/Team/Create.php b/app/Livewire/Team/Create.php
index f5069d92db..f805d61222 100644
--- a/app/Livewire/Team/Create.php
+++ b/app/Livewire/Team/Create.php
@@ -5,7 +5,6 @@
use App\Models\Team;
use Livewire\Attributes\Validate;
use Livewire\Component;
-use Throwable;
class Create extends Component
{
@@ -19,7 +18,7 @@ public function submit()
{
try {
$this->validate();
- $team = Team::query()->create([
+ $team = Team::create([
'name' => $this->name,
'description' => $this->description,
'personal_team' => false,
@@ -28,7 +27,7 @@ public function submit()
refreshSession();
return redirect()->route('team.index');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
}
diff --git a/app/Livewire/Team/Index.php b/app/Livewire/Team/Index.php
index 0682d86aed..0972e7364f 100644
--- a/app/Livewire/Team/Index.php
+++ b/app/Livewire/Team/Index.php
@@ -7,7 +7,6 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
-use Throwable;
class Index extends Component
{
@@ -46,11 +45,9 @@ public function submit()
$this->team->save();
refreshSession();
$this->dispatch('success', 'Team updated.');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function delete()
diff --git a/app/Livewire/Team/Invitations.php b/app/Livewire/Team/Invitations.php
index 9d3ea8736a..93432efc86 100644
--- a/app/Livewire/Team/Invitations.php
+++ b/app/Livewire/Team/Invitations.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Team;
use App\Models\TeamInvitation;
-use Exception;
use Livewire\Component;
class Invitations extends Component
@@ -19,11 +18,9 @@ public function deleteInvitation(int $invitation_id)
$initiation_found->delete();
$this->refreshInvitations();
$this->dispatch('success', 'Invitation revoked.');
- } catch (Exception) {
+ } catch (\Exception) {
return $this->dispatch('error', 'Invitation not found.');
}
-
- return null;
}
public function refreshInvitations()
diff --git a/app/Livewire/Team/InviteLink.php b/app/Livewire/Team/InviteLink.php
index 50a7e302bb..25f8a1ff51 100644
--- a/app/Livewire/Team/InviteLink.php
+++ b/app/Livewire/Team/InviteLink.php
@@ -4,13 +4,11 @@
use App\Models\TeamInvitation;
use App\Models\User;
-use Exception;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Livewire\Component;
-use Throwable;
use Visus\Cuid2\Cuid2;
class InviteLink extends Component
@@ -44,19 +42,19 @@ private function generate_invite_link(bool $sendEmail = false)
try {
$this->validate();
if (auth()->user()->role() === 'admin' && $this->role === 'owner') {
- throw new Exception('Admins cannot invite owners.');
+ throw new \Exception('Admins cannot invite owners.');
}
$member_emails = currentTeam()->members()->get()->pluck('email');
if ($member_emails->contains($this->email)) {
return handleError(livewire: $this, customErrorMessage: "$this->email is already a member of ".currentTeam()->name.'.');
}
- $cuid2 = new Cuid2(32);
- $link = url('/').config('constants.invitation.link.base_url').$cuid2;
+ $uuid = new Cuid2(32);
+ $link = url('/').config('constants.invitation.link.base_url').$uuid;
$user = User::whereEmail($this->email)->first();
if (is_null($user)) {
$password = Str::password();
- $user = User::query()->create([
+ $user = User::create([
'name' => str($this->email)->before('@'),
'email' => $this->email,
'password' => Hash::make($password),
@@ -70,34 +68,36 @@ private function generate_invite_link(bool $sendEmail = false)
$invitationValid = $invitation->isValid();
if ($invitationValid) {
return handleError(livewire: $this, customErrorMessage: "Pending invitation already exists for $this->email.");
+ } else {
+ $invitation->delete();
}
- $invitation->delete();
}
- $invitation = TeamInvitation::query()->firstOrCreate([
+ $invitation = TeamInvitation::firstOrCreate([
'team_id' => currentTeam()->id,
- 'uuid' => $cuid2,
+ 'uuid' => $uuid,
'email' => $this->email,
'role' => $this->role,
'link' => $link,
'via' => $sendEmail ? 'email' : 'link',
]);
if ($sendEmail) {
- $mailMessage = new MailMessage;
- $mailMessage->view('emails.invitation-link', [
+ $mail = new MailMessage;
+ $mail->view('emails.invitation-link', [
'team' => currentTeam()->name,
'invitation_link' => $link,
]);
- $mailMessage->subject('You have been invited to '.currentTeam()->name.' on '.config('app.name').'.');
- send_user_an_email($mailMessage, $this->email);
+ $mail->subject('You have been invited to '.currentTeam()->name.' on '.config('app.name').'.');
+ send_user_an_email($mail, $this->email);
$this->dispatch('success', 'Invitation sent via email.');
$this->dispatch('refreshInvitations');
- return null;
+ return;
+ } else {
+ $this->dispatch('success', 'Invitation link generated.');
+ $this->dispatch('refreshInvitations');
}
- $this->dispatch('success', 'Invitation link generated.');
- $this->dispatch('refreshInvitations');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$error_message = $e->getMessage();
if ($e->getCode() === '23505') {
$error_message = 'Invitation already sent.';
@@ -105,7 +105,5 @@ private function generate_invite_link(bool $sendEmail = false)
return handleError(error: $e, livewire: $this, customErrorMessage: $error_message);
}
-
- return null;
}
}
diff --git a/app/Livewire/Team/Member.php b/app/Livewire/Team/Member.php
index 463d201546..890d640a07 100644
--- a/app/Livewire/Team/Member.php
+++ b/app/Livewire/Team/Member.php
@@ -4,7 +4,6 @@
use App\Enums\Role;
use App\Models\User;
-use Exception;
use Illuminate\Support\Facades\Cache;
use Livewire\Component;
@@ -17,11 +16,11 @@ public function makeAdmin()
try {
if (Role::from(auth()->user()->role())->lt(Role::ADMIN)
|| Role::from($this->getMemberRole())->gt(auth()->user()->role())) {
- throw new Exception('You are not authorized to perform this action.');
+ throw new \Exception('You are not authorized to perform this action.');
}
$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::ADMIN->value]);
$this->dispatch('reloadWindow');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
}
}
@@ -31,11 +30,11 @@ public function makeOwner()
try {
if (Role::from(auth()->user()->role())->lt(Role::OWNER)
|| Role::from($this->getMemberRole())->gt(auth()->user()->role())) {
- throw new Exception('You are not authorized to perform this action.');
+ throw new \Exception('You are not authorized to perform this action.');
}
$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::OWNER->value]);
$this->dispatch('reloadWindow');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
}
}
@@ -45,11 +44,11 @@ public function makeReadonly()
try {
if (Role::from(auth()->user()->role())->lt(Role::ADMIN)
|| Role::from($this->getMemberRole())->gt(auth()->user()->role())) {
- throw new Exception('You are not authorized to perform this action.');
+ throw new \Exception('You are not authorized to perform this action.');
}
$this->member->teams()->updateExistingPivot(currentTeam()->id, ['role' => Role::MEMBER->value]);
$this->dispatch('reloadWindow');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
}
}
@@ -59,7 +58,7 @@ public function remove()
try {
if (Role::from(auth()->user()->role())->lt(Role::ADMIN)
|| Role::from($this->getMemberRole())->gt(auth()->user()->role())) {
- throw new Exception('You are not authorized to perform this action.');
+ throw new \Exception('You are not authorized to perform this action.');
}
$this->member->teams()->detach(currentTeam());
Cache::forget("team:{$this->member->id}");
@@ -67,7 +66,7 @@ public function remove()
return $this->member->teams()->first();
});
$this->dispatch('reloadWindow');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
$this->dispatch('error', $e->getMessage());
}
}
diff --git a/app/Livewire/Team/Storage/Show.php b/app/Livewire/Team/Storage/Show.php
index f45c15c05b..d3051afd42 100644
--- a/app/Livewire/Team/Storage/Show.php
+++ b/app/Livewire/Team/Storage/Show.php
@@ -7,7 +7,7 @@
class Show extends Component
{
- public $storage;
+ public $storage = null;
public function mount()
{
diff --git a/app/Livewire/Terminal/Index.php b/app/Livewire/Terminal/Index.php
index c087a5b03e..a24a237c58 100644
--- a/app/Livewire/Terminal/Index.php
+++ b/app/Livewire/Terminal/Index.php
@@ -3,7 +3,6 @@
namespace App\Livewire\Terminal;
use App\Models\Server;
-use Exception;
use Livewire\Attributes\On;
use Livewire\Component;
@@ -29,13 +28,11 @@ public function loadContainers()
{
try {
$this->containers = $this->getAllActiveContainers();
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
} finally {
$this->isLoadingContainers = false;
}
-
- return null;
}
private function getAllActiveContainers()
@@ -46,8 +43,8 @@ private function getAllActiveContainers()
}
return $server->loadAllContainers()->map(function ($container) use ($server) {
- $stringable = data_get_str($container, 'State')->lower();
- if ($stringable->contains('running')) {
+ $state = data_get_str($container, 'State')->lower();
+ if ($state->contains('running')) {
return [
'name' => data_get($container, 'Names'),
'connection_name' => data_get($container, 'Names'),
diff --git a/app/Livewire/Upgrade.php b/app/Livewire/Upgrade.php
index 0bb3a548c3..e50085c64e 100644
--- a/app/Livewire/Upgrade.php
+++ b/app/Livewire/Upgrade.php
@@ -5,7 +5,6 @@
use App\Actions\Server\UpdateCoolify;
use App\Models\InstanceSettings;
use Livewire\Component;
-use Throwable;
class Upgrade extends Component
{
@@ -27,25 +26,21 @@ public function checkUpdate()
if (isDev()) {
$this->isUpgradeAvailable = true;
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
public function upgrade()
{
try {
if ($this->updateInProgress) {
- return null;
+ return;
}
$this->updateInProgress = true;
UpdateCoolify::run(manual_update: true);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e, $this);
}
-
- return null;
}
}
diff --git a/app/Livewire/VerifyEmail.php b/app/Livewire/VerifyEmail.php
index 39aaa1f9cd..fab3265b65 100644
--- a/app/Livewire/VerifyEmail.php
+++ b/app/Livewire/VerifyEmail.php
@@ -3,7 +3,6 @@
namespace App\Livewire;
use DanHarrin\LivewireRateLimiting\WithRateLimiting;
-use Exception;
use Livewire\Component;
class VerifyEmail extends Component
@@ -16,11 +15,9 @@ public function again()
$this->rateLimit(1, 300);
auth()->user()->sendVerificationEmail();
$this->dispatch('success', 'Email verification link sent!');
- } catch (Exception $e) {
+ } catch (\Exception $e) {
return handleError($e, $this);
}
-
- return null;
}
public function render()
diff --git a/app/Models/Application.php b/app/Models/Application.php
index 5b99cfbd0d..56faf6c311 100644
--- a/app/Models/Application.php
+++ b/app/Models/Application.php
@@ -3,7 +3,6 @@
namespace App\Models;
use App\Enums\ApplicationDeploymentStatus;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
@@ -148,15 +147,17 @@ protected static function booted()
if ($application->isDirty('status')) {
$payload['last_online_at'] = now();
}
- if ($application->isDirty('custom_nginx_configuration') && $application->custom_nginx_configuration === '') {
- $payload['custom_nginx_configuration'] = null;
+ if ($application->isDirty('custom_nginx_configuration')) {
+ if ($application->custom_nginx_configuration === '') {
+ $payload['custom_nginx_configuration'] = null;
+ }
}
- if ($payload !== []) {
+ if (count($payload) > 0) {
$application->forceFill($payload);
}
});
static::created(function ($application) {
- ApplicationSetting::query()->create([
+ ApplicationSetting::create([
'application_id' => $application->id,
]);
$application->compose_parsing_version = self::$parserVersion;
@@ -181,12 +182,12 @@ protected static function booted()
public static function ownedByCurrentTeamAPI(int $teamId)
{
- return \App\Models\Application::query()->whereRelation('environment.project.team', 'id', $teamId)->orderBy('name');
+ return Application::whereRelation('environment.project.team', 'id', $teamId)->orderBy('name');
}
public static function ownedByCurrentTeam()
{
- return \App\Models\Application::query()->whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
+ return Application::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
public function getContainersToStop(bool $previewDeployments = false): array
@@ -206,11 +207,11 @@ public function stopContainers(array $containerNames, $server, int $timeout = 60
}
$startTime = time();
- while ($processes !== []) {
+ while (count($processes) > 0) {
$finishedProcesses = array_filter($processes, function ($process) {
return ! $process->running();
});
- foreach (array_keys($finishedProcesses) as $containerName) {
+ foreach ($finishedProcesses as $containerName => $process) {
unset($processes[$containerName]);
$this->removeContainer($containerName, $server);
}
@@ -251,17 +252,17 @@ public function delete_configurations()
}
}
- public function delete_volumes(?Collection $collection)
+ public function delete_volumes(?Collection $persistentStorages)
{
if ($this->build_pack === 'dockercompose') {
$server = data_get($this, 'destination.server');
instant_remote_process(["cd {$this->dirOnServer()} && docker compose down -v"], $server, false);
} else {
- if ($collection->count() === 0) {
+ if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
- foreach ($collection as $storage) {
+ foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -288,12 +289,20 @@ public function additional_networks()
public function is_public_repository(): bool
{
- return (bool) data_get($this, 'source.is_public');
+ if (data_get($this, 'source.is_public')) {
+ return true;
+ }
+
+ return false;
}
public function is_github_based(): bool
{
- return (bool) data_get($this, 'source');
+ if (data_get($this, 'source')) {
+ return true;
+ }
+
+ return false;
}
public function isForceHttpsEnabled()
@@ -477,12 +486,13 @@ public function dockerfileLocation(): Attribute
set: function ($value) {
if (is_null($value) || $value === '') {
return '/Dockerfile';
- }
- if ($value !== '/') {
- return Str::start(Str::replaceEnd('/', '', $value), '/');
- }
+ } else {
+ if ($value !== '/') {
+ return Str::start(Str::replaceEnd('/', '', $value), '/');
+ }
- return Str::start($value, '/');
+ return Str::start($value, '/');
+ }
}
);
}
@@ -493,12 +503,13 @@ public function dockerComposeLocation(): Attribute
set: function ($value) {
if (is_null($value) || $value === '') {
return '/docker-compose.yaml';
- }
- if ($value !== '/') {
- return Str::start(Str::replaceEnd('/', '', $value), '/');
- }
+ } else {
+ if ($value !== '/') {
+ return Str::start(Str::replaceEnd('/', '', $value), '/');
+ }
- return Str::start($value, '/');
+ return Str::start($value, '/');
+ }
}
);
}
@@ -569,18 +580,33 @@ public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
- if (str($value)->contains('(')) {
- $status = str($value)->before('(')->trim()->value();
- $health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
- } elseif (str($value)->contains(':')) {
- $status = str($value)->before(':')->trim()->value();
- $health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
+ if ($this->additional_servers->count() === 0) {
+ if (str($value)->contains('(')) {
+ $status = str($value)->before('(')->trim()->value();
+ $health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
+ } elseif (str($value)->contains(':')) {
+ $status = str($value)->before(':')->trim()->value();
+ $health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
+ } else {
+ $status = $value;
+ $health = 'unhealthy';
+ }
+
+ return "$status:$health";
} else {
- $status = $value;
- $health = 'unhealthy';
- }
+ if (str($value)->contains('(')) {
+ $status = str($value)->before('(')->trim()->value();
+ $health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
+ } elseif (str($value)->contains(':')) {
+ $status = str($value)->before(':')->trim()->value();
+ $health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
+ } else {
+ $status = $value;
+ $health = 'unhealthy';
+ }
- return "$status:$health";
+ return "$status:$health";
+ }
},
get: function ($value) {
if ($this->additional_servers->count() === 0) {
@@ -597,24 +623,25 @@ public function status(): Attribute
}
return "$status:$health";
- }
- $complex_status = null;
- $complex_health = null;
- $complex_status = $main_server_status = str($value)->before(':')->value();
- $complex_health = $main_server_health = str($value)->after(':')->value() ?? 'unhealthy';
- $additional_servers_status = $this->additional_servers->pluck('pivot.status');
- foreach ($additional_servers_status as $status) {
- $server_status = str($status)->before(':')->value();
- $server_health = str($status)->after(':')->value() ?? 'unhealthy';
- if ($main_server_status !== $server_status) {
- $complex_status = 'degraded';
- }
- if ($main_server_health !== $server_health) {
- $complex_health = 'unhealthy';
+ } else {
+ $complex_status = null;
+ $complex_health = null;
+ $complex_status = $main_server_status = str($value)->before(':')->value();
+ $complex_health = $main_server_health = str($value)->after(':')->value() ?? 'unhealthy';
+ $additional_servers_status = $this->additional_servers->pluck('pivot.status');
+ foreach ($additional_servers_status as $status) {
+ $server_status = str($status)->before(':')->value();
+ $server_health = str($status)->after(':')->value() ?? 'unhealthy';
+ if ($main_server_status !== $server_status) {
+ $complex_status = 'degraded';
+ }
+ if ($main_server_health !== $server_health) {
+ $complex_health = 'unhealthy';
+ }
}
- }
- return "$complex_status:$complex_health";
+ return "$complex_status:$complex_health";
+ }
},
);
}
@@ -763,24 +790,27 @@ public function source()
public function isDeploymentInprogress()
{
- $deployments = ApplicationDeploymentQueue::query()->where('application_id', $this->id)->whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS, ApplicationDeploymentStatus::QUEUED])->count();
+ $deployments = ApplicationDeploymentQueue::where('application_id', $this->id)->whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS, ApplicationDeploymentStatus::QUEUED])->count();
+ if ($deployments > 0) {
+ return true;
+ }
- return $deployments > 0;
+ return false;
}
public function get_last_successful_deployment()
{
- return ApplicationDeploymentQueue::query()->where('application_id', $this->id)->where('status', ApplicationDeploymentStatus::FINISHED)->where('pull_request_id', 0)->orderBy('created_at', 'desc')->first();
+ return ApplicationDeploymentQueue::where('application_id', $this->id)->where('status', ApplicationDeploymentStatus::FINISHED)->where('pull_request_id', 0)->orderBy('created_at', 'desc')->first();
}
public function get_last_days_deployments()
{
- return ApplicationDeploymentQueue::query()->where('application_id', $this->id)->where('created_at', '>=', now()->subDays(7))->orderBy('created_at', 'desc')->get();
+ return ApplicationDeploymentQueue::where('application_id', $this->id)->where('created_at', '>=', now()->subDays(7))->orderBy('created_at', 'desc')->get();
}
public function deployments(int $skip = 0, int $take = 10)
{
- $deployments = ApplicationDeploymentQueue::query()->where('application_id', $this->id)->orderBy('created_at', 'desc');
+ $deployments = ApplicationDeploymentQueue::where('application_id', $this->id)->orderBy('created_at', 'desc');
$count = $deployments->count();
$deployments = $deployments->skip($skip)->take($take)->get();
@@ -792,17 +822,25 @@ public function deployments(int $skip = 0, int $take = 10)
public function get_deployment(string $deployment_uuid)
{
- return Activity::query()->where('subject_id', $this->id)->where('properties->type_uuid', '=', $deployment_uuid)->first();
+ return Activity::where('subject_id', $this->id)->where('properties->type_uuid', '=', $deployment_uuid)->first();
}
public function isDeployable(): bool
{
- return (bool) $this->settings->is_auto_deploy_enabled;
+ if ($this->settings->is_auto_deploy_enabled) {
+ return true;
+ }
+
+ return false;
}
public function isPRDeployable(): bool
{
- return (bool) $this->settings->is_preview_deployments_enabled;
+ if ($this->settings->is_preview_deployments_enabled) {
+ return true;
+ }
+
+ return false;
}
public function deploymentType()
@@ -812,17 +850,21 @@ public function deploymentType()
}
if (data_get($this, 'private_key_id')) {
return 'deploy_key';
- }
- if (data_get($this, 'source')) {
+ } elseif (data_get($this, 'source')) {
return 'source';
+ } else {
+ return 'other';
}
-
- return 'other';
+ throw new \Exception('No deployment type found');
}
public function could_set_build_commands(): bool
{
- return $this->build_pack === 'nixpacks';
+ if ($this->build_pack === 'nixpacks') {
+ return true;
+ }
+
+ return false;
}
public function git_based(): bool
@@ -830,13 +872,20 @@ public function git_based(): bool
if ($this->dockerfile) {
return false;
}
+ if ($this->build_pack === 'dockerimage') {
+ return false;
+ }
- return $this->build_pack !== 'dockerimage';
+ return true;
}
public function isHealthcheckDisabled(): bool
{
- return data_get($this, 'health_check_enabled') === false;
+ if (data_get($this, 'health_check_enabled') === false) {
+ return true;
+ }
+
+ return false;
}
public function workdir()
@@ -869,13 +918,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function customRepository()
@@ -907,7 +957,7 @@ public function setGitImportSettings(string $deployment_uuid, string $git_clone_
$git_clone_command = "{$git_clone_command} && cd {$baseDir} && GIT_SSH_COMMAND=\"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\" git submodule update --init --recursive";
}
if ($this->settings->is_git_lfs_enabled) {
- return "{$git_clone_command} && cd {$baseDir} && GIT_SSH_COMMAND=\"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\" git lfs pull";
+ $git_clone_command = "{$git_clone_command} && cd {$baseDir} && GIT_SSH_COMMAND=\"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\" git lfs pull";
}
return $git_clone_command;
@@ -923,7 +973,7 @@ public function getGitRemoteStatus(string $deployment_uuid)
'is_accessible' => true,
'error' => null,
];
- } catch (RuntimeException $ex) {
+ } catch (\RuntimeException $ex) {
return [
'is_accessible' => false,
'error' => $ex->getMessage(),
@@ -1027,8 +1077,6 @@ public function generateGitLsRemoteCommands(string $deployment_uuid, bool $exec_
'fullRepoUrl' => $fullRepoUrl,
];
}
-
- return null;
}
public function generateGitImportCommands(string $deployment_uuid, int $pull_request_id = 0, ?string $git_type = null, bool $exec_in_docker = true, bool $only_checkout = false, ?string $custom_base_dir = null, ?string $commit = null)
@@ -1050,7 +1098,7 @@ public function generateGitImportCommands(string $deployment_uuid, int $pull_req
$source_html_url_host = $url['host'];
$source_html_url_scheme = $url['scheme'];
- if ($this->source->getMorphClass() === GithubApp::class) {
+ if ($this->source->getMorphClass() === \App\Models\GithubApp::class) {
if ($this->source->is_public) {
$fullRepoUrl = "{$this->source->html_url}/{$customRepository}";
$git_clone_command = "{$git_clone_command} {$this->source->html_url}/{$customRepository} {$baseDir}";
@@ -1207,16 +1255,14 @@ public function generateGitImportCommands(string $deployment_uuid, int $pull_req
'fullRepoUrl' => $fullRepoUrl,
];
}
-
- return null;
}
public function oldRawParser()
{
try {
$yaml = Yaml::parse($this->docker_compose_raw);
- } catch (Exception $e) {
- throw new Exception($e->getMessage(), $e->getCode(), $e);
+ } catch (\Exception $e) {
+ throw new \Exception($e->getMessage());
}
$services = data_get($yaml, 'services');
@@ -1224,27 +1270,24 @@ public function oldRawParser()
$services = collect($services)->map(function ($service) use ($commands) {
$serviceVolumes = collect(data_get($service, 'volumes', []));
if ($serviceVolumes->count() > 0) {
- foreach ($serviceVolumes as $serviceVolume) {
+ foreach ($serviceVolumes as $volume) {
$workdir = $this->workdir();
$type = null;
$source = null;
- if (is_string($serviceVolume)) {
- $source = str($serviceVolume)->before(':');
+ if (is_string($volume)) {
+ $source = str($volume)->before(':');
if ($source->startsWith('./') || $source->startsWith('/') || $source->startsWith('~')) {
$type = str('bind');
}
- } elseif (is_array($serviceVolume)) {
- $type = data_get_str($serviceVolume, 'type');
- $source = data_get_str($serviceVolume, 'source');
+ } elseif (is_array($volume)) {
+ $type = data_get_str($volume, 'type');
+ $source = data_get_str($volume, 'source');
}
if ($type?->value() === 'bind') {
if ($source->value() === '/var/run/docker.sock') {
continue;
}
- if ($source->value() === '/tmp') {
- continue;
- }
- if ($source->value() === '/tmp/') {
+ if ($source->value() === '/tmp' || $source->value() === '/tmp/') {
continue;
}
if ($source->startsWith('.')) {
@@ -1279,28 +1322,27 @@ public function parse(int $pull_request_id = 0, ?int $preview_id = null)
{
if ((int) $this->compose_parsing_version >= 3) {
return newParser($this, $pull_request_id, $preview_id);
- }
- if ($this->docker_compose_raw) {
+ } elseif ($this->docker_compose_raw) {
return parseDockerComposeFile(resource: $this, isNew: false, pull_request_id: $pull_request_id, preview_id: $preview_id);
+ } else {
+ return collect([]);
}
-
- return collect([]);
}
public function loadComposeFile($isInit = false)
{
$initialDockerComposeLocation = $this->docker_compose_location;
if ($isInit && $this->docker_compose_raw) {
- return null;
+ return;
}
- $cuid2 = new Cuid2;
- ['commands' => $cloneCommand] = $this->generateGitImportCommands(deployment_uuid: $cuid2, only_checkout: true, exec_in_docker: false, custom_base_dir: '.');
+ $uuid = new Cuid2;
+ ['commands' => $cloneCommand] = $this->generateGitImportCommands(deployment_uuid: $uuid, only_checkout: true, exec_in_docker: false, custom_base_dir: '.');
$workdir = rtrim($this->base_directory, '/');
$composeFile = $this->docker_compose_location;
$fileList = collect([".$workdir$composeFile"]);
- $gitRemoteStatus = $this->getGitRemoteStatus(deployment_uuid: $cuid2);
+ $gitRemoteStatus = $this->getGitRemoteStatus(deployment_uuid: $uuid);
if (! $gitRemoteStatus['is_accessible']) {
- throw new RuntimeException("Failed to read Git source:\n\n{$gitRemoteStatus['error']}");
+ throw new \RuntimeException("Failed to read Git source:\n\n{$gitRemoteStatus['error']}");
}
$getGitVersion = instant_remote_process(['git --version'], $this->destination->server, false);
$gitVersion = str($getGitVersion)->explode(' ')->last();
@@ -1311,7 +1353,7 @@ public function loadComposeFile($isInit = false)
$paths = collect();
$currentPath = '';
foreach ($parts as $part) {
- $currentPath .= ($currentPath !== '' && $currentPath !== '0' ? '/' : '').$part;
+ $currentPath .= ($currentPath ? '/' : '').$part;
if (str($currentPath)->isNotEmpty()) {
$paths->push($currentPath);
}
@@ -1320,9 +1362,9 @@ public function loadComposeFile($isInit = false)
return $paths;
})->flatten()->unique()->values();
$commands = collect([
- "rm -rf /tmp/{$cuid2}",
- "mkdir -p /tmp/{$cuid2}",
- "cd /tmp/{$cuid2}",
+ "rm -rf /tmp/{$uuid}",
+ "mkdir -p /tmp/{$uuid}",
+ "cd /tmp/{$uuid}",
$cloneCommand,
'git sparse-checkout init',
"git sparse-checkout set {$fileList->implode(' ')}",
@@ -1331,9 +1373,9 @@ public function loadComposeFile($isInit = false)
]);
} else {
$commands = collect([
- "rm -rf /tmp/{$cuid2}",
- "mkdir -p /tmp/{$cuid2}",
- "cd /tmp/{$cuid2}",
+ "rm -rf /tmp/{$uuid}",
+ "mkdir -p /tmp/{$uuid}",
+ "cd /tmp/{$uuid}",
$cloneCommand,
'git sparse-checkout init --cone',
"git sparse-checkout set {$fileList->implode(' ')}",
@@ -1343,22 +1385,22 @@ public function loadComposeFile($isInit = false)
}
try {
$composeFileContent = instant_remote_process($commands, $this->destination->server);
- } catch (Exception $e) {
+ } catch (\Exception $e) {
if (str($e->getMessage())->contains('No such file')) {
- throw new RuntimeException("Docker Compose file not found at: $workdir$composeFile
Check if you used the right extension (.yaml or .yml) in the compose file name.", $e->getCode(), $e);
+ throw new \RuntimeException("Docker Compose file not found at: $workdir$composeFile
Check if you used the right extension (.yaml or .yml) in the compose file name.");
}
if (str($e->getMessage())->contains('fatal: repository') && str($e->getMessage())->contains('does not exist')) {
if ($this->deploymentType() === 'deploy_key') {
- throw new RuntimeException('Your deploy key does not have access to the repository. Please check your deploy key and try again.', $e->getCode(), $e);
+ throw new \RuntimeException('Your deploy key does not have access to the repository. Please check your deploy key and try again.');
}
- throw new RuntimeException('Repository does not exist. Please check your repository URL and try again.', $e->getCode(), $e);
+ throw new \RuntimeException('Repository does not exist. Please check your repository URL and try again.');
}
- throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
+ throw new \RuntimeException($e->getMessage());
} finally {
$this->docker_compose_location = $initialDockerComposeLocation;
$this->save();
$commands = collect([
- "rm -rf /tmp/{$cuid2}",
+ "rm -rf /tmp/{$uuid}",
]);
instant_remote_process($commands, $this->destination->server, false);
}
@@ -1374,7 +1416,11 @@ public function loadComposeFile($isInit = false)
$json = $json->filter(function ($value, $key) use ($diff) {
return ! in_array($key, $diff);
});
- $this->docker_compose_domains = $json ? json_encode($json) : null;
+ if ($json) {
+ $this->docker_compose_domains = json_encode($json);
+ } else {
+ $this->docker_compose_domains = null;
+ }
$this->save();
}
@@ -1382,15 +1428,16 @@ public function loadComposeFile($isInit = false)
'parsedServices' => $parsedServices,
'initialDockerComposeLocation' => $this->docker_compose_location,
];
+ } else {
+ throw new \RuntimeException("Docker Compose file not found at: $workdir$composeFile
Check if you used the right extension (.yaml or .yml) in the compose file name.");
}
- throw new RuntimeException("Docker Compose file not found at: $workdir$composeFile
Check if you used the right extension (.yaml or .yml) in the compose file name.");
}
- public function parseContainerLabels(?ApplicationPreview $applicationPreview = null)
+ public function parseContainerLabels(?ApplicationPreview $preview = null)
{
$customLabels = data_get($this, 'custom_labels');
if (! $customLabels) {
- return null;
+ return;
}
if (base64_encode(base64_decode($customLabels, true)) !== $customLabels) {
$this->custom_labels = str($customLabels)->replace(',', "\n");
@@ -1398,7 +1445,7 @@ public function parseContainerLabels(?ApplicationPreview $applicationPreview = n
}
$customLabels = base64_decode($this->custom_labels);
if (mb_detect_encoding($customLabels, 'ASCII', true) === false) {
- $customLabels = str(implode('|coolify|', generateLabelsApplication($this, $applicationPreview)))->replace('|coolify|', "\n");
+ $customLabels = str(implode('|coolify|', generateLabelsApplication($this, $preview)))->replace('|coolify|', "\n");
}
$this->custom_labels = base64_encode($customLabels);
$this->save();
@@ -1472,7 +1519,7 @@ public function parseHealthcheckFromDockerfile($dockerfile, bool $isInit = false
if (isset($healthcheckCommand) && str_contains($trimmedLine, '\\')) {
$healthcheckCommand .= ' '.trim($trimmedLine, '\\ ');
}
- if (isset($healthcheckCommand) && ! str_contains($trimmedLine, '\\') && ($healthcheckCommand !== '' && $healthcheckCommand !== '0')) {
+ if (isset($healthcheckCommand) && ! str_contains($trimmedLine, '\\') && ! empty($healthcheckCommand)) {
$healthcheckCommand .= ' '.$trimmedLine;
break;
}
@@ -1522,8 +1569,8 @@ public function generate_preview_fqdn(int $pull_request_id)
$template = $this->preview_url_template;
$host = $url->getHost();
$schema = $url->getScheme();
- $cuid2 = new Cuid2;
- $preview_fqdn = str_replace('{{random}}', $cuid2, $template);
+ $random = new Cuid2;
+ $preview_fqdn = str_replace('{{random}}', $random, $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pull_request_id, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn";
@@ -1536,7 +1583,7 @@ public function generate_preview_fqdn(int $pull_request_id)
public static function getDomainsByUuid(string $uuid): array
{
- $application = self::query()->where('uuid', $uuid)->first();
+ $application = self::where('uuid', $uuid)->first();
if ($application) {
return $application->fqdns;
@@ -1558,7 +1605,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -1567,8 +1614,6 @@ public function getCpuMetrics(int $mins = 5)
return $parsedCollection->toArray();
}
-
- return null;
}
public function getMemoryMetrics(int $mins = 5)
@@ -1584,7 +1629,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -1593,14 +1638,12 @@ public function getMemoryMetrics(int $mins = 5)
return $parsedCollection->toArray();
}
-
- return null;
}
public function generateConfig($is_json = false)
{
$config = collect([]);
- if (($this->build_pack = 'nixpacks') !== '') {
+ if ($this->build_pack = 'nixpacks') {
$config = collect([
'build_pack' => 'nixpacks',
'docker_registry_image_name' => $this->docker_registry_image_name,
@@ -1634,7 +1677,7 @@ public function setConfig($config)
'config' => 'required|json',
]);
if ($validator->fails()) {
- throw new Exception('Invalid JSON format');
+ throw new \Exception('Invalid JSON format');
}
$config = json_decode($config, true);
@@ -1646,7 +1689,7 @@ public function setConfig($config)
'config.settings.is_static' => 'required|boolean',
]);
if ($deepValidator->fails()) {
- throw new Exception('Invalid data');
+ throw new \Exception('Invalid data');
}
$config = $deepValidator->validated()['config'];
@@ -1655,8 +1698,8 @@ public function setConfig($config)
data_forget($config, 'settings');
$this->update($config);
$this->settings()->update($settings);
- } catch (Exception $e) {
- throw new Exception('Failed to update application settings', $e->getCode(), $e);
+ } catch (\Exception $e) {
+ throw new \Exception('Failed to update application settings');
}
}
}
diff --git a/app/Models/ApplicationDeploymentQueue.php b/app/Models/ApplicationDeploymentQueue.php
index 6029d08011..c261c30c65 100644
--- a/app/Models/ApplicationDeploymentQueue.php
+++ b/app/Models/ApplicationDeploymentQueue.php
@@ -43,14 +43,14 @@ class ApplicationDeploymentQueue extends Model
public function application(): Attribute
{
return Attribute::make(
- get: fn () => Application::query()->find($this->application_id),
+ get: fn () => Application::find($this->application_id),
);
}
public function server(): Attribute
{
return Attribute::make(
- get: fn () => Server::query()->find($this->server_id),
+ get: fn () => Server::find($this->server_id),
);
}
diff --git a/app/Models/ApplicationPreview.php b/app/Models/ApplicationPreview.php
index c06c32937f..bf2bf05bf1 100644
--- a/app/Models/ApplicationPreview.php
+++ b/app/Models/ApplicationPreview.php
@@ -37,7 +37,7 @@ protected static function booted()
public static function findPreviewByApplicationAndPullId(int $application_id, int $pull_request_id)
{
- return self::query()->where('application_id', $application_id)->where('pull_request_id', $pull_request_id)->firstOrFail();
+ return self::where('application_id', $application_id)->where('pull_request_id', $pull_request_id)->firstOrFail();
}
public function isRunning()
diff --git a/app/Models/DiscordNotificationSettings.php b/app/Models/DiscordNotificationSettings.php
index edd3921909..619393ddc0 100644
--- a/app/Models/DiscordNotificationSettings.php
+++ b/app/Models/DiscordNotificationSettings.php
@@ -30,6 +30,23 @@ class DiscordNotificationSettings extends Model
'server_unreachable_discord_notifications',
];
+ protected $casts = [
+ 'discord_enabled' => 'boolean',
+ 'discord_webhook_url' => 'encrypted',
+
+ 'deployment_success_discord_notifications' => 'boolean',
+ 'deployment_failure_discord_notifications' => 'boolean',
+ 'status_change_discord_notifications' => 'boolean',
+ 'backup_success_discord_notifications' => 'boolean',
+ 'backup_failure_discord_notifications' => 'boolean',
+ 'scheduled_task_success_discord_notifications' => 'boolean',
+ 'scheduled_task_failure_discord_notifications' => 'boolean',
+ 'docker_cleanup_discord_notifications' => 'boolean',
+ 'server_disk_usage_discord_notifications' => 'boolean',
+ 'server_reachable_discord_notifications' => 'boolean',
+ 'server_unreachable_discord_notifications' => 'boolean',
+ ];
+
public function team()
{
return $this->belongsTo(Team::class);
@@ -39,24 +56,4 @@ public function isEnabled()
{
return $this->discord_enabled;
}
-
- protected function casts(): array
- {
- return [
- 'discord_enabled' => 'boolean',
- 'discord_webhook_url' => 'encrypted',
-
- 'deployment_success_discord_notifications' => 'boolean',
- 'deployment_failure_discord_notifications' => 'boolean',
- 'status_change_discord_notifications' => 'boolean',
- 'backup_success_discord_notifications' => 'boolean',
- 'backup_failure_discord_notifications' => 'boolean',
- 'scheduled_task_success_discord_notifications' => 'boolean',
- 'scheduled_task_failure_discord_notifications' => 'boolean',
- 'docker_cleanup_discord_notifications' => 'boolean',
- 'server_disk_usage_discord_notifications' => 'boolean',
- 'server_reachable_discord_notifications' => 'boolean',
- 'server_unreachable_discord_notifications' => 'boolean',
- ];
- }
}
diff --git a/app/Models/EmailNotificationSettings.php b/app/Models/EmailNotificationSettings.php
index 65e459e79d..ae118986fc 100644
--- a/app/Models/EmailNotificationSettings.php
+++ b/app/Models/EmailNotificationSettings.php
@@ -37,6 +37,32 @@ class EmailNotificationSettings extends Model
'server_disk_usage_email_notifications',
];
+ protected $casts = [
+ 'smtp_enabled' => 'boolean',
+ 'smtp_from_address' => 'encrypted',
+ 'smtp_from_name' => 'encrypted',
+ 'smtp_recipients' => 'encrypted',
+ 'smtp_host' => 'encrypted',
+ 'smtp_port' => 'integer',
+ 'smtp_username' => 'encrypted',
+ 'smtp_password' => 'encrypted',
+ 'smtp_timeout' => 'integer',
+
+ 'resend_enabled' => 'boolean',
+ 'resend_api_key' => 'encrypted',
+
+ 'use_instance_email_settings' => 'boolean',
+
+ 'deployment_success_email_notifications' => 'boolean',
+ 'deployment_failure_email_notifications' => 'boolean',
+ 'status_change_email_notifications' => 'boolean',
+ 'backup_success_email_notifications' => 'boolean',
+ 'backup_failure_email_notifications' => 'boolean',
+ 'scheduled_task_success_email_notifications' => 'boolean',
+ 'scheduled_task_failure_email_notifications' => 'boolean',
+ 'server_disk_usage_email_notifications' => 'boolean',
+ ];
+
public function team()
{
return $this->belongsTo(Team::class);
@@ -50,33 +76,4 @@ public function isEnabled()
return $this->smtp_enabled || $this->resend_enabled || $this->use_instance_email_settings;
}
-
- protected function casts(): array
- {
- return [
- 'smtp_enabled' => 'boolean',
- 'smtp_from_address' => 'encrypted',
- 'smtp_from_name' => 'encrypted',
- 'smtp_recipients' => 'encrypted',
- 'smtp_host' => 'encrypted',
- 'smtp_port' => 'integer',
- 'smtp_username' => 'encrypted',
- 'smtp_password' => 'encrypted',
- 'smtp_timeout' => 'integer',
-
- 'resend_enabled' => 'boolean',
- 'resend_api_key' => 'encrypted',
-
- 'use_instance_email_settings' => 'boolean',
-
- 'deployment_success_email_notifications' => 'boolean',
- 'deployment_failure_email_notifications' => 'boolean',
- 'status_change_email_notifications' => 'boolean',
- 'backup_success_email_notifications' => 'boolean',
- 'backup_failure_email_notifications' => 'boolean',
- 'scheduled_task_success_email_notifications' => 'boolean',
- 'scheduled_task_failure_email_notifications' => 'boolean',
- 'server_disk_usage_email_notifications' => 'boolean',
- ];
- }
}
diff --git a/app/Models/EnvironmentVariable.php b/app/Models/EnvironmentVariable.php
index 2dd4019700..507ff0d7e2 100644
--- a/app/Models/EnvironmentVariable.php
+++ b/app/Models/EnvironmentVariable.php
@@ -55,30 +55,30 @@ protected static function booted()
}
});
- static::created(function (EnvironmentVariable $environmentVariable) {
- if ($environmentVariable->resourceable_type === Application::class && ! $environmentVariable->is_preview) {
- $found = ModelsEnvironmentVariable::where('key', $environmentVariable->key)
+ static::created(function (EnvironmentVariable $environment_variable) {
+ if ($environment_variable->resourceable_type === Application::class && ! $environment_variable->is_preview) {
+ $found = ModelsEnvironmentVariable::where('key', $environment_variable->key)
->where('resourceable_type', Application::class)
- ->where('resourceable_id', $environmentVariable->resourceable_id)
+ ->where('resourceable_id', $environment_variable->resourceable_id)
->where('is_preview', true)
->first();
if (! $found) {
- $application = Application::query()->find($environmentVariable->resourceable_id);
+ $application = Application::find($environment_variable->resourceable_id);
if ($application && $application->build_pack !== 'dockerfile') {
ModelsEnvironmentVariable::create([
- 'key' => $environmentVariable->key,
- 'value' => $environmentVariable->value,
- 'is_build_time' => $environmentVariable->is_build_time,
- 'is_multiline' => $environmentVariable->is_multiline ?? false,
+ 'key' => $environment_variable->key,
+ 'value' => $environment_variable->value,
+ 'is_build_time' => $environment_variable->is_build_time,
+ 'is_multiline' => $environment_variable->is_multiline ?? false,
'resourceable_type' => Application::class,
- 'resourceable_id' => $environmentVariable->resourceable_id,
+ 'resourceable_id' => $environment_variable->resourceable_id,
'is_preview' => true,
]);
}
}
}
- $environmentVariable->update([
+ $environment_variable->update([
'version' => config('constants.coolify.version'),
]);
});
@@ -143,15 +143,18 @@ protected function isShared(): Attribute
return Attribute::make(
get: function () {
$type = str($this->value)->after('{{')->before('.')->value;
+ if (str($this->value)->startsWith('{{'.$type) && str($this->value)->endsWith('}}')) {
+ return true;
+ }
- return str($this->value)->startsWith('{{'.$type) && str($this->value)->endsWith('}}');
+ return false;
}
);
}
private function get_real_environment_variables(?string $environment_variable = null, $resource = null)
{
- if (is_null($resource)) {
+ if ((is_null($environment_variable) && $environment_variable === '') || is_null($resource)) {
return null;
}
$environment_variable = trim($environment_variable);
@@ -159,12 +162,12 @@ private function get_real_environment_variables(?string $environment_variable =
if ($sharedEnvsFound->isEmpty()) {
return $environment_variable;
}
- foreach ($sharedEnvsFound as $sharedEnvFound) {
- $type = str($sharedEnvFound)->match('/(.*?)\./');
+ foreach ($sharedEnvsFound as $sharedEnv) {
+ $type = str($sharedEnv)->match('/(.*?)\./');
if (! collect(SHARED_VARIABLE_TYPES)->contains($type)) {
continue;
}
- $variable = str($sharedEnvFound)->match('/\.(.*)/');
+ $variable = str($sharedEnv)->match('/\.(.*)/');
if ($type->value() === 'environment') {
$id = $resource->environment->id;
} elseif ($type->value() === 'project') {
@@ -175,9 +178,9 @@ private function get_real_environment_variables(?string $environment_variable =
if (is_null($id)) {
continue;
}
- $environment_variable_found = SharedEnvironmentVariable::query()->where('type', $type)->where('key', $variable)->where('team_id', $resource->team()->id)->where("{$type}_id", $id)->first();
+ $environment_variable_found = SharedEnvironmentVariable::where('type', $type)->where('key', $variable)->where('team_id', $resource->team()->id)->where("{$type}_id", $id)->first();
if ($environment_variable_found) {
- $environment_variable = str($environment_variable)->replace("{{{$sharedEnvFound}}}", $environment_variable_found->value);
+ $environment_variable = str($environment_variable)->replace("{{{$sharedEnv}}}", $environment_variable_found->value);
}
}
diff --git a/app/Models/GithubApp.php b/app/Models/GithubApp.php
index f21597dfdd..0b0e93b128 100644
--- a/app/Models/GithubApp.php
+++ b/app/Models/GithubApp.php
@@ -2,7 +2,6 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
class GithubApp extends BaseModel
@@ -11,6 +10,11 @@ class GithubApp extends BaseModel
protected $appends = ['type'];
+ protected $casts = [
+ 'is_public' => 'boolean',
+ 'type' => 'string',
+ ];
+
protected $hidden = [
'client_secret',
'webhook_secret',
@@ -18,12 +22,12 @@ class GithubApp extends BaseModel
protected static function booted(): void
{
- static::deleting(function (GithubApp $githubApp) {
- $applications_count = Application::query()->where('source_id', $githubApp->id)->count();
+ static::deleting(function (GithubApp $github_app) {
+ $applications_count = Application::where('source_id', $github_app->id)->count();
if ($applications_count > 0) {
- throw new Exception('You cannot delete this GitHub App because it is in use by '.$applications_count.' application(s). Delete them first.');
+ throw new \Exception('You cannot delete this GitHub App because it is in use by '.$applications_count.' application(s). Delete them first.');
}
- $githubApp->privateKey()->delete();
+ $github_app->privateKey()->delete();
});
}
@@ -67,12 +71,4 @@ public function type(): Attribute
},
);
}
-
- protected function casts(): array
- {
- return [
- 'is_public' => 'boolean',
- 'type' => 'string',
- ];
- }
}
diff --git a/app/Models/InstanceSettings.php b/app/Models/InstanceSettings.php
index 58b243567c..5b89bb401c 100644
--- a/app/Models/InstanceSettings.php
+++ b/app/Models/InstanceSettings.php
@@ -15,11 +15,32 @@ class InstanceSettings extends Model implements SendsEmail
protected $guarded = [];
+ protected $casts = [
+ 'smtp_enabled' => 'boolean',
+ 'smtp_from_address' => 'encrypted',
+ 'smtp_from_name' => 'encrypted',
+ 'smtp_recipients' => 'encrypted',
+ 'smtp_host' => 'encrypted',
+ 'smtp_port' => 'integer',
+ 'smtp_username' => 'encrypted',
+ 'smtp_password' => 'encrypted',
+ 'smtp_timeout' => 'integer',
+
+ 'resend_enabled' => 'boolean',
+ 'resend_api_key' => 'encrypted',
+
+ 'allowed_ip_ranges' => 'array',
+ 'is_auto_update_enabled' => 'boolean',
+ 'auto_update_frequency' => 'string',
+ 'update_check_frequency' => 'string',
+ 'sentinel_token' => 'encrypted',
+ ];
+
protected static function booted(): void
{
static::updated(function ($settings) {
if ($settings->isDirty('helper_version')) {
- Server::query()->chunkById(100, function ($servers) {
+ Server::chunkById(100, function ($servers) {
foreach ($servers as $server) {
PullHelperImageJob::dispatch($server);
}
@@ -68,7 +89,7 @@ public function autoUpdateFrequency(): Attribute
public static function get()
{
- return \App\Models\InstanceSettings::query()->findOrFail(0);
+ return InstanceSettings::findOrFail(0);
}
public function getRecipients($notification)
@@ -103,27 +124,4 @@ public function getTitleDisplayName(): string
// }
// );
// }
- protected function casts(): array
- {
- return [
- 'smtp_enabled' => 'boolean',
- 'smtp_from_address' => 'encrypted',
- 'smtp_from_name' => 'encrypted',
- 'smtp_recipients' => 'encrypted',
- 'smtp_host' => 'encrypted',
- 'smtp_port' => 'integer',
- 'smtp_username' => 'encrypted',
- 'smtp_password' => 'encrypted',
- 'smtp_timeout' => 'integer',
-
- 'resend_enabled' => 'boolean',
- 'resend_api_key' => 'encrypted',
-
- 'allowed_ip_ranges' => 'array',
- 'is_auto_update_enabled' => 'boolean',
- 'auto_update_frequency' => 'string',
- 'update_check_frequency' => 'string',
- 'sentinel_token' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/LocalFileVolume.php b/app/Models/LocalFileVolume.php
index c5b5a0870f..2c223be779 100644
--- a/app/Models/LocalFileVolume.php
+++ b/app/Models/LocalFileVolume.php
@@ -3,8 +3,6 @@
namespace App\Models;
use App\Events\FileStorageChanged;
-use App\Jobs\ServerStorageSaveJob;
-use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class LocalFileVolume extends BaseModel
@@ -15,9 +13,9 @@ class LocalFileVolume extends BaseModel
protected static function booted()
{
- static::created(function (LocalFileVolume $localFileVolume) {
- $localFileVolume->load(['service']);
- dispatch(new ServerStorageSaveJob($localFileVolume));
+ static::created(function (LocalFileVolume $fileVolume) {
+ $fileVolume->load(['service']);
+ dispatch(new \App\Jobs\ServerStorageSaveJob($fileVolume));
});
}
@@ -37,7 +35,7 @@ public function loadStorageOnServer()
$workdir = $this->resource->workdir();
$server = $this->resource->destination->server;
}
- collect([]);
+ $commands = collect([]);
$path = data_get_str($this, 'fs_path');
if ($path->startsWith('.')) {
$path = $path->after('.');
@@ -82,8 +80,6 @@ public function deleteStorageOnServer()
if ($commands->count() > 0) {
return instant_remote_process($commands, $server);
}
-
- return null;
}
public function saveStorageOnServer()
@@ -122,13 +118,12 @@ public function saveStorageOnServer()
$this->content = $content;
$this->save();
FileStorageChanged::dispatch(data_get($server, 'team_id'));
- throw new Exception('The following file is a file on the server, but you are trying to mark it as a directory. Please delete the file on the server or mark it as directory.');
- }
- if ($isDir === 'OK' && ! $this->is_directory) {
+ throw new \Exception('The following file is a file on the server, but you are trying to mark it as a directory. Please delete the file on the server or mark it as directory.');
+ } elseif ($isDir === 'OK' && ! $this->is_directory) {
if ($path === '/' || $path === '.' || $path === '..' || $path === '' || str($path)->isEmpty() || is_null($path)) {
$this->is_directory = true;
$this->save();
- throw new Exception('The following file is a directory on the server, but you are trying to mark it as a file.
Please delete the directory on the server or mark it as directory.');
+ throw new \Exception('The following file is a directory on the server, but you are trying to mark it as a file.
Please delete the directory on the server or mark it as directory.');
}
instant_remote_process([
"rm -fr $path",
diff --git a/app/Models/LocalPersistentVolume.php b/app/Models/LocalPersistentVolume.php
index b3ed3c2441..68e476365a 100644
--- a/app/Models/LocalPersistentVolume.php
+++ b/app/Models/LocalPersistentVolume.php
@@ -49,9 +49,9 @@ protected function hostPath(): Attribute
set: function (?string $value) {
if ($value) {
return str($value)->trim()->start('/')->value;
+ } else {
+ return $value;
}
-
- return $value;
}
);
}
diff --git a/app/Models/OauthSetting.php b/app/Models/OauthSetting.php
index eb72d862c4..3d82e89f29 100644
--- a/app/Models/OauthSetting.php
+++ b/app/Models/OauthSetting.php
@@ -16,8 +16,8 @@ class OauthSetting extends Model
protected function clientSecret(): Attribute
{
return Attribute::make(
- get: fn (?string $value) => $value === null || $value === '' || $value === '0' ? null : Crypt::decryptString($value),
- set: fn (?string $value) => $value === null || $value === '' || $value === '0' ? null : Crypt::encryptString($value),
+ get: fn (?string $value) => empty($value) ? null : Crypt::decryptString($value),
+ set: fn (?string $value) => empty($value) ? null : Crypt::encryptString($value),
);
}
diff --git a/app/Models/PrivateKey.php b/app/Models/PrivateKey.php
index 228fb16218..80015d87f8 100644
--- a/app/Models/PrivateKey.php
+++ b/app/Models/PrivateKey.php
@@ -3,12 +3,10 @@
namespace App\Models;
use DanHarrin\LivewireRateLimiting\WithRateLimiting;
-use Exception;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use OpenApi\Attributes as OA;
use phpseclib3\Crypt\PublicKeyLoader;
-use Throwable;
#[OA\Schema(
description: 'Private Key model',
@@ -38,6 +36,10 @@ class PrivateKey extends BaseModel
'fingerprint',
];
+ protected $casts = [
+ 'private_key' => 'encrypted',
+ ];
+
protected static function booted()
{
static::saving(function ($key) {
@@ -80,7 +82,7 @@ public static function validatePrivateKey($privateKey)
PublicKeyLoader::load($privateKey);
return true;
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return false;
}
}
@@ -109,8 +111,8 @@ public static function generateNewKeyPair($type = 'rsa')
'private_key' => $keyPair['private'],
'public_key' => $keyPair['public'],
];
- } catch (Throwable $e) {
- throw new Exception("Failed to generate new {$type} key: ".$e->getMessage(), $e->getCode(), $e);
+ } catch (\Throwable $e) {
+ throw new \Exception("Failed to generate new {$type} key: ".$e->getMessage());
}
}
@@ -120,7 +122,7 @@ public static function extractPublicKeyFromPrivate($privateKey)
$key = PublicKeyLoader::load($privateKey);
return $key->getPublicKey()->toString('OpenSSH', ['comment' => '']);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return null;
}
}
@@ -185,17 +187,10 @@ public function gitlabApps()
public function isInUse()
{
- if ($this->servers()->exists()) {
- return true;
- }
- if ($this->applications()->exists()) {
- return true;
- }
- if ($this->githubApps()->exists()) {
- return true;
- }
-
- return (bool) $this->gitlabApps()->exists();
+ return $this->servers()->exists()
+ || $this->applications()->exists()
+ || $this->githubApps()->exists()
+ || $this->gitlabApps()->exists();
}
public function safeDelete()
@@ -216,22 +211,22 @@ public static function generateFingerprint($privateKey)
$publicKey = $key->getPublicKey();
return $publicKey->getFingerprint('sha256');
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return null;
}
}
private static function fingerprintExists($fingerprint, $excludeId = null)
{
- $builder = self::query()
+ $query = self::query()
->where('fingerprint', $fingerprint)
->where('id', '!=', $excludeId);
if (currentTeam()) {
- $builder->where('team_id', currentTeam()->id);
+ $query->where('team_id', currentTeam()->id);
}
- return $builder->exists();
+ return $query->exists();
}
public static function cleanupUnusedKeys()
@@ -240,11 +235,4 @@ public static function cleanupUnusedKeys()
$privateKey->safeDelete();
});
}
-
- protected function casts(): array
- {
- return [
- 'private_key' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/Project.php b/app/Models/Project.php
index d47da2b23c..3b50b9b33e 100644
--- a/app/Models/Project.php
+++ b/app/Models/Project.php
@@ -33,10 +33,10 @@ public static function ownedByCurrentTeam()
protected static function booted()
{
static::created(function ($project) {
- ProjectSetting::query()->create([
+ ProjectSetting::create([
'project_id' => $project->id,
]);
- Environment::query()->create([
+ Environment::create([
'name' => 'production',
'project_id' => $project->id,
'uuid' => (string) new Cuid2,
diff --git a/app/Models/PushoverNotificationSettings.php b/app/Models/PushoverNotificationSettings.php
index 4179057d6f..e3191dcc34 100644
--- a/app/Models/PushoverNotificationSettings.php
+++ b/app/Models/PushoverNotificationSettings.php
@@ -31,6 +31,24 @@ class PushoverNotificationSettings extends Model
'server_unreachable_pushover_notifications',
];
+ protected $casts = [
+ 'pushover_enabled' => 'boolean',
+ 'pushover_user_key' => 'encrypted',
+ 'pushover_api_token' => 'encrypted',
+
+ 'deployment_success_pushover_notifications' => 'boolean',
+ 'deployment_failure_pushover_notifications' => 'boolean',
+ 'status_change_pushover_notifications' => 'boolean',
+ 'backup_success_pushover_notifications' => 'boolean',
+ 'backup_failure_pushover_notifications' => 'boolean',
+ 'scheduled_task_success_pushover_notifications' => 'boolean',
+ 'scheduled_task_failure_pushover_notifications' => 'boolean',
+ 'docker_cleanup_pushover_notifications' => 'boolean',
+ 'server_disk_usage_pushover_notifications' => 'boolean',
+ 'server_reachable_pushover_notifications' => 'boolean',
+ 'server_unreachable_pushover_notifications' => 'boolean',
+ ];
+
public function team()
{
return $this->belongsTo(Team::class);
@@ -40,25 +58,4 @@ public function isEnabled()
{
return $this->pushover_enabled;
}
-
- protected function casts(): array
- {
- return [
- 'pushover_enabled' => 'boolean',
- 'pushover_user_key' => 'encrypted',
- 'pushover_api_token' => 'encrypted',
-
- 'deployment_success_pushover_notifications' => 'boolean',
- 'deployment_failure_pushover_notifications' => 'boolean',
- 'status_change_pushover_notifications' => 'boolean',
- 'backup_success_pushover_notifications' => 'boolean',
- 'backup_failure_pushover_notifications' => 'boolean',
- 'scheduled_task_success_pushover_notifications' => 'boolean',
- 'scheduled_task_failure_pushover_notifications' => 'boolean',
- 'docker_cleanup_pushover_notifications' => 'boolean',
- 'server_disk_usage_pushover_notifications' => 'boolean',
- 'server_reachable_pushover_notifications' => 'boolean',
- 'server_unreachable_pushover_notifications' => 'boolean',
- ];
- }
}
diff --git a/app/Models/S3Storage.php b/app/Models/S3Storage.php
index c87b7f200a..f1247e6f74 100644
--- a/app/Models/S3Storage.php
+++ b/app/Models/S3Storage.php
@@ -5,7 +5,6 @@
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Storage;
-use Throwable;
class S3Storage extends BaseModel
{
@@ -13,6 +12,12 @@ class S3Storage extends BaseModel
protected $guarded = [];
+ protected $casts = [
+ 'is_usable' => 'boolean',
+ 'key' => 'encrypted',
+ 'secret' => 'encrypted',
+ ];
+
public static function ownedByCurrentTeam(array $select = ['*'])
{
$selectArray = collect($select)->concat(['id']);
@@ -52,12 +57,12 @@ public function testConnection(bool $shouldSave = false)
Storage::disk('custom-s3')->files();
$this->unusable_email_sent = false;
$this->is_usable = true;
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->is_usable = false;
if ($this->unusable_email_sent === false && is_transactional_emails_enabled()) {
- $mailMessage = new MailMessage;
- $mailMessage->subject('Coolify: S3 Storage Connection Error');
- $mailMessage->view('emails.s3-connection-error', ['name' => $this->name, 'reason' => $e->getMessage(), 'url' => route('storage.show', ['storage_uuid' => $this->uuid])]);
+ $mail = new MailMessage;
+ $mail->subject('Coolify: S3 Storage Connection Error');
+ $mail->view('emails.s3-connection-error', ['name' => $this->name, 'reason' => $e->getMessage(), 'url' => route('storage.show', ['storage_uuid' => $this->uuid])]);
$users = collect([]);
$members = $this->team->members()->get();
foreach ($members as $user) {
@@ -66,7 +71,7 @@ public function testConnection(bool $shouldSave = false)
}
}
foreach ($users as $user) {
- send_user_an_email($mailMessage, $user->email);
+ send_user_an_email($mail, $user->email);
}
$this->unusable_email_sent = true;
}
@@ -78,13 +83,4 @@ public function testConnection(bool $shouldSave = false)
}
}
}
-
- protected function casts(): array
- {
- return [
- 'is_usable' => 'boolean',
- 'key' => 'encrypted',
- 'secret' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/Server.php b/app/Models/Server.php
index 484760096e..8d11e23a93 100644
--- a/app/Models/Server.php
+++ b/app/Models/Server.php
@@ -10,7 +10,6 @@
use App\Jobs\CheckAndStartSentinelJob;
use App\Notifications\Server\Reachable;
use App\Notifications\Server\Unreachable;
-use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -20,13 +19,11 @@
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Stringable;
-use Log;
use OpenApi\Attributes as OA;
use Spatie\SchemalessAttributes\Casts\SchemalessAttributes;
use Spatie\SchemalessAttributes\SchemalessAttributesTrait;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
-use Throwable;
#[OA\Schema(
description: 'Server model',
@@ -75,37 +72,39 @@ protected static function booted()
}
});
static::created(function ($server) {
- ServerSetting::query()->create([
+ ServerSetting::create([
'server_id' => $server->id,
]);
if ($server->id === 0) {
if ($server->isSwarm()) {
- SwarmDocker::query()->create([
+ SwarmDocker::create([
'id' => 0,
'name' => 'coolify',
'network' => 'coolify-overlay',
'server_id' => $server->id,
]);
} else {
- StandaloneDocker::query()->create([
+ StandaloneDocker::create([
'id' => 0,
'name' => 'coolify',
'network' => 'coolify',
'server_id' => $server->id,
]);
}
- } elseif ($server->isSwarm()) {
- SwarmDocker::query()->create([
- 'name' => 'coolify-overlay',
- 'network' => 'coolify-overlay',
- 'server_id' => $server->id,
- ]);
} else {
- StandaloneDocker::query()->create([
- 'name' => 'coolify',
- 'network' => 'coolify',
- 'server_id' => $server->id,
- ]);
+ if ($server->isSwarm()) {
+ SwarmDocker::create([
+ 'name' => 'coolify-overlay',
+ 'network' => 'coolify-overlay',
+ 'server_id' => $server->id,
+ ]);
+ } else {
+ StandaloneDocker::create([
+ 'name' => 'coolify',
+ 'network' => 'coolify',
+ 'server_id' => $server->id,
+ ]);
+ }
}
if (! isset($server->proxy->redirect_enabled)) {
$server->proxy->redirect_enabled = true;
@@ -125,6 +124,17 @@ protected static function booted()
});
}
+ protected $casts = [
+ 'proxy' => SchemalessAttributes::class,
+ 'logdrain_axiom_api_key' => 'encrypted',
+ 'logdrain_newrelic_license_key' => 'encrypted',
+ 'delete_unused_volumes' => 'boolean',
+ 'delete_unused_networks' => 'boolean',
+ 'unreachable_notification_sent' => 'boolean',
+ 'is_build_server' => 'boolean',
+ 'force_disabled' => 'boolean',
+ ];
+
protected $schemalessAttributes = [
'proxy',
];
@@ -192,8 +202,10 @@ public function setupDefaultRedirect()
$proxy_type = $this->proxyType();
$redirect_enabled = $this->proxy->redirect_enabled ?? true;
$redirect_url = $this->proxy->redirect_url;
- if (isDev() && $proxy_type === ProxyTypes::CADDY->value) {
- $dynamic_conf_path = '/data/coolify/proxy/caddy/dynamic';
+ if (isDev()) {
+ if ($proxy_type === ProxyTypes::CADDY->value) {
+ $dynamic_conf_path = '/data/coolify/proxy/caddy/dynamic';
+ }
}
if ($proxy_type === ProxyTypes::TRAEFIK->value) {
$default_redirect_file = "$dynamic_conf_path/default_redirect_503.yaml";
@@ -211,11 +223,15 @@ public function setupDefaultRedirect()
instant_remote_process(["rm -f $default_redirect_file"], $this);
} else {
if ($proxy_type === ProxyTypes::CADDY->value) {
- $conf = filled($redirect_url) ? ":80, :443 {
+ if (filled($redirect_url)) {
+ $conf = ":80, :443 {
redir $redirect_url
-}" : ':80, :443 {
+}";
+ } else {
+ $conf = ':80, :443 {
respond 503
}';
+ }
} elseif ($proxy_type === ProxyTypes::TRAEFIK->value) {
$dynamic_conf = [
'http' => [
@@ -458,9 +474,17 @@ public function proxyPath()
if ($proxyType === ProxyTypes::TRAEFIK->value) {
// Do nothing
} elseif ($proxyType === ProxyTypes::CADDY->value) {
- $proxy_path = isDev() ? '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/caddy' : $proxy_path.'/caddy';
+ if (isDev()) {
+ $proxy_path = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/caddy';
+ } else {
+ $proxy_path = $proxy_path.'/caddy';
+ }
} elseif ($proxyType === ProxyTypes::NGINX->value) {
- $proxy_path = isDev() ? '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/nginx' : $proxy_path.'/nginx';
+ if (isDev()) {
+ $proxy_path = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/nginx';
+ } else {
+ $proxy_path = $proxy_path.'/nginx';
+ }
}
return $proxy_path;
@@ -521,7 +545,7 @@ public function waitBeforeDoingSshCheck(): int
{
$wait = $this->settings->sentinel_push_interval_seconds * 3;
if ($wait < 120) {
- return 120;
+ $wait = 120;
}
return $wait;
@@ -563,7 +587,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$cpu = json_decode($cpu, true);
@@ -571,8 +595,6 @@ public function getCpuMetrics(int $mins = 5)
return [(int) $metric['time'], (float) $metric['percent']];
});
}
-
- return null;
}
public function getMemoryMetrics(int $mins = 5)
@@ -586,7 +608,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$memory = json_decode($memory, true);
$parsedCollection = collect($memory)->map(function ($metric) {
@@ -597,8 +619,6 @@ public function getMemoryMetrics(int $mins = 5)
return $parsedCollection->toArray();
}
-
- return null;
}
public function getDiskUsage(): ?string
@@ -641,11 +661,11 @@ public function getContainers()
$containerReplicates = instant_remote_process(["docker service ls --format '{{json .}}'"], $this, false);
if ($containerReplicates) {
$containerReplicates = format_docker_command_output_to_json($containerReplicates);
- foreach ($containerReplicates as $containerReplicate) {
- $name = data_get($containerReplicate, 'Name');
- $containers = $containers->map(function ($container) use ($name, $containerReplicate) {
+ foreach ($containerReplicates as $containerReplica) {
+ $name = data_get($containerReplica, 'Name');
+ $containers = $containers->map(function ($container) use ($name, $containerReplica) {
if (data_get($container, 'Spec.Name') === $name) {
- $replicas = data_get($containerReplicate, 'Replicas');
+ $replicas = data_get($containerReplica, 'Replicas');
$running = str($replicas)->explode('/')[0];
$total = str($replicas)->explode('/')[1];
if ($running === $total) {
@@ -717,9 +737,9 @@ public function loadUnmanagedContainers(): Collection
$containers = $containers->filter();
return collect($containers);
+ } else {
+ return collect([]);
}
-
- return collect([]);
}
public function hasDefinedResources()
@@ -727,8 +747,11 @@ public function hasDefinedResources()
$applications = $this->applications()->count() > 0;
$databases = $this->databases()->count() > 0;
$services = $this->services()->count() > 0;
+ if ($applications || $databases || $services) {
+ return true;
+ }
- return $applications || $databases || $services;
+ return false;
}
public function databases()
@@ -758,7 +781,7 @@ public function applications()
$additionalApplicationIds = collect($additionalApplicationIds)->map(function ($item) {
return $item->application_id;
});
- Application::query()->whereIn('id', $additionalApplicationIds)->get()->each(function ($application) use ($applications) {
+ Application::whereIn('id', $additionalApplicationIds)->get()->each(function ($application) use ($applications) {
$applications->push($application);
});
@@ -776,7 +799,7 @@ public function dockerComposeBasedPreviewDeployments()
{
return $this->previews()->filter(function ($preview) {
$applicationId = data_get($preview, 'application_id');
- $application = Application::query()->find($applicationId);
+ $application = Application::find($applicationId);
if (! $application) {
return false;
}
@@ -878,7 +901,11 @@ public function team()
public function isProxyShouldRun()
{
// TODO: Do we need "|| $this->proxy->force_stop" here?
- return $this->proxyType() !== ProxyTypes::NONE->value && ! $this->isBuildServer();
+ if ($this->proxyType() === ProxyTypes::NONE->value || $this->isBuildServer()) {
+ return false;
+ }
+
+ return true;
}
public function skipServer()
@@ -886,8 +913,11 @@ public function skipServer()
if ($this->ip === '1.2.3.4') {
return true;
}
+ if ($this->settings->force_disabled === true) {
+ return true;
+ }
- return $this->settings->force_disabled === true;
+ return false;
}
public function isFunctional()
@@ -911,8 +941,8 @@ public function validateOS(): bool|Stringable
$os_release = instant_remote_process(['cat /etc/os-release'], $this);
$releaseLines = collect(explode("\n", $os_release));
$collectedData = collect([]);
- foreach ($releaseLines as $releaseLine) {
- $item = str($releaseLine)->trim();
+ foreach ($releaseLines as $line) {
+ $item = str($line)->trim();
$collectedData->put($item->before('=')->value(), $item->after('=')->lower()->replace('"', '')->value());
}
$ID = data_get($collectedData, 'ID');
@@ -926,10 +956,10 @@ public function validateOS(): bool|Stringable
if ($supported->count() === 1) {
// ray('supported');
return str($supported->first());
+ } else {
+ // ray('not supported');
+ return false;
}
-
- // ray('not supported');
- return false;
}
public function isSwarm()
@@ -952,8 +982,11 @@ public function serverStatus(): bool
if ($this->status() === false) {
return false;
}
+ if ($this->isFunctional() === false) {
+ return false;
+ }
- return $this->isFunctional() !== false;
+ return true;
}
public function status(): bool
@@ -993,19 +1026,19 @@ public function isReachableChanged()
$unreachableNotificationSent = (bool) $this->unreachable_notification_sent;
$isReachable = (bool) $this->settings->is_reachable;
- Log::debug('Server reachability check', [
+ \Log::debug('Server reachability check', [
'server_id' => $this->id,
'is_reachable' => $isReachable,
'notification_sent' => $unreachableNotificationSent,
'unreachable_count' => $this->unreachable_count,
]);
- if ($isReachable) {
+ if ($isReachable === true) {
$this->unreachable_count = 0;
$this->save();
- if ($unreachableNotificationSent) {
- Log::debug('Server is now reachable, sending notification', [
+ if ($unreachableNotificationSent === true) {
+ \Log::debug('Server is now reachable, sending notification', [
'server_id' => $this->id,
]);
$this->sendReachableNotification();
@@ -1015,7 +1048,7 @@ public function isReachableChanged()
}
$this->increment('unreachable_count');
- Log::debug('Incremented unreachable count', [
+ \Log::debug('Incremented unreachable count', [
'server_id' => $this->id,
'new_count' => $this->unreachable_count,
]);
@@ -1023,7 +1056,7 @@ public function isReachableChanged()
if ($this->unreachable_count === 1) {
$this->settings->is_reachable = true;
$this->settings->save();
- Log::debug('First unreachable attempt, marking as reachable', [
+ \Log::debug('First unreachable attempt, marking as reachable', [
'server_id' => $this->id,
]);
@@ -1034,7 +1067,7 @@ public function isReachableChanged()
$failedChecks = 0;
for ($i = 0; $i < 3; $i++) {
$status = $this->serverStatus();
- Log::debug('Additional reachability check', [
+ \Log::debug('Additional reachability check', [
'server_id' => $this->id,
'attempt' => $i + 1,
'status' => $status,
@@ -1046,7 +1079,7 @@ public function isReachableChanged()
}
if ($failedChecks === 3 && ! $unreachableNotificationSent) {
- Log::debug('Server confirmed unreachable after 3 attempts, sending notification', [
+ \Log::debug('Server confirmed unreachable after 3 attempts, sending notification', [
'server_id' => $this->id,
]);
$this->sendUnreachableNotification();
@@ -1086,7 +1119,7 @@ public function validateConnection(bool $justCheckingNewKey = false)
}
return ['uptime' => true, 'error' => null];
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
if ($justCheckingNewKey) {
return ['uptime' => false, 'error' => 'This key is not valid for this server.'];
}
@@ -1112,18 +1145,18 @@ public function validateDockerEngine($throwError = false)
$this->settings->is_usable = false;
$this->settings->save();
if ($throwError) {
- throw new Exception('Server is not usable. Docker Engine is not installed.');
+ throw new \Exception('Server is not usable. Docker Engine is not installed.');
}
return false;
}
try {
instant_remote_process(['docker version'], $this);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
$this->settings->is_usable = false;
$this->settings->save();
if ($throwError) {
- throw new Exception('Server is not usable. Docker Engine is not running.', $e->getCode(), $e);
+ throw new \Exception('Server is not usable. Docker Engine is not running.');
}
return false;
@@ -1142,7 +1175,7 @@ public function validateDockerCompose($throwError = false)
$this->settings->is_usable = false;
$this->settings->save();
if ($throwError) {
- throw new Exception('Server is not usable. Docker Compose is not installed.');
+ throw new \Exception('Server is not usable. Docker Compose is not installed.');
}
return false;
@@ -1158,7 +1191,9 @@ public function validateDockerSwarm()
$swarmStatus = instant_remote_process(['docker info|grep -i swarm'], $this, false);
$swarmStatus = str($swarmStatus)->trim()->after(':')->trim();
if ($swarmStatus === 'inactive') {
- throw new Exception('Docker Swarm is not initiated. Please join the server to a swarm before continuing.');
+ throw new \Exception('Docker Swarm is not initiated. Please join the server to a swarm before continuing.');
+
+ return false;
}
$this->settings->is_usable = true;
$this->settings->save();
@@ -1190,13 +1225,13 @@ public function validateDockerEngineVersion()
public function validateCoolifyNetwork($isSwarm = false, $isBuildServer = false)
{
if ($isBuildServer) {
- return null;
+ return;
}
if ($isSwarm) {
return instant_remote_process(['docker network create --attachable --driver overlay coolify-overlay >/dev/null 2>&1 || true'], $this, false);
+ } else {
+ return instant_remote_process(['docker network create coolify --attachable >/dev/null 2>&1 || true'], $this, false);
}
-
- return instant_remote_process(['docker network create coolify --attachable >/dev/null 2>&1 || true'], $this, false);
}
public function isNonRoot()
@@ -1225,7 +1260,7 @@ public static function createWithPrivateKey(array $data, PrivateKey $privateKey)
public function updateWithPrivateKey(array $data, ?PrivateKey $privateKey = null)
{
$this->update($data);
- if ($privateKey instanceof PrivateKey) {
+ if ($privateKey) {
$this->privateKey()->associate($privateKey);
$this->save();
}
@@ -1255,11 +1290,9 @@ public function restartSentinel(bool $async = true)
} else {
StartSentinel::run($this, true);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return handleError($e);
}
-
- return null;
}
public function url()
@@ -1289,21 +1322,7 @@ public function changeProxy(string $proxyType, bool $async = true)
}
}
} else {
- throw new Exception('Invalid proxy type.');
+ throw new \Exception('Invalid proxy type.');
}
}
-
- protected function casts(): array
- {
- return [
- 'proxy' => SchemalessAttributes::class,
- 'logdrain_axiom_api_key' => 'encrypted',
- 'logdrain_newrelic_license_key' => 'encrypted',
- 'delete_unused_volumes' => 'boolean',
- 'delete_unused_networks' => 'boolean',
- 'unreachable_notification_sent' => 'boolean',
- 'is_build_server' => 'boolean',
- 'force_disabled' => 'boolean',
- ];
- }
}
diff --git a/app/Models/ServerSetting.php b/app/Models/ServerSetting.php
index 1b54e0ea5f..f4b776cca0 100644
--- a/app/Models/ServerSetting.php
+++ b/app/Models/ServerSetting.php
@@ -6,7 +6,6 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use OpenApi\Attributes as OA;
-use Throwable;
#[OA\Schema(
description: 'Server Settings model',
@@ -54,6 +53,14 @@ class ServerSetting extends Model
{
protected $guarded = [];
+ protected $casts = [
+ 'force_docker_cleanup' => 'boolean',
+ 'docker_cleanup_threshold' => 'integer',
+ 'sentinel_token' => 'encrypted',
+ 'is_reachable' => 'boolean',
+ 'is_usable' => 'boolean',
+ ];
+
protected static function booted()
{
static::creating(function ($setting) {
@@ -64,7 +71,7 @@ protected static function booted()
if (str($setting->sentinel_custom_url)->isEmpty()) {
$setting->generateSentinelUrl(save: false, ignoreEvent: true);
}
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
Log::error('Error creating server setting: '.$e->getMessage());
}
});
@@ -141,15 +148,4 @@ public function dockerCleanupFrequency(): Attribute
}
);
}
-
- protected function casts(): array
- {
- return [
- 'force_docker_cleanup' => 'boolean',
- 'docker_cleanup_threshold' => 'integer',
- 'sentinel_token' => 'encrypted',
- 'is_reachable' => 'boolean',
- 'is_usable' => 'boolean',
- ];
- }
}
diff --git a/app/Models/Service.php b/app/Models/Service.php
index c01e74bcb7..1df579802d 100644
--- a/app/Models/Service.php
+++ b/app/Models/Service.php
@@ -84,13 +84,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
protected function serverStatus(): Attribute
@@ -134,7 +135,7 @@ public function tags()
public static function ownedByCurrentTeam()
{
- return \App\Models\Service::query()->whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
+ return Service::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
public function getContainersToStop(): array
@@ -160,7 +161,7 @@ public function stopContainers(array $containerNames, $server, int $timeout = 30
}
$startTime = time();
- while ($processes !== []) {
+ while (count($processes) > 0) {
$finishedProcesses = array_filter($processes, function ($process) {
return ! $process->running();
});
@@ -230,7 +231,11 @@ public function getStatusAttribute()
continue;
}
if ($status->startsWith('running')) {
- $complexStatus = $complexStatus === 'exited' ? 'degraded' : 'running';
+ if ($complexStatus === 'exited') {
+ $complexStatus = 'degraded';
+ } else {
+ $complexStatus = 'running';
+ }
} elseif ($status->startsWith('restarting')) {
$complexStatus = 'degraded';
} elseif ($status->startsWith('exited')) {
@@ -255,7 +260,11 @@ public function getStatusAttribute()
continue;
}
if ($status->startsWith('running')) {
- $complexStatus = $complexStatus === 'exited' ? 'degraded' : 'running';
+ if ($complexStatus === 'exited') {
+ $complexStatus = 'degraded';
+ } else {
+ $complexStatus = 'running';
+ }
} elseif ($status->startsWith('restarting')) {
$complexStatus = 'degraded';
} elseif ($status->startsWith('exited')) {
@@ -1278,10 +1287,12 @@ public function saveComposeConfigs()
$real_value = $env->real_value;
if ($env->version === '4.0.0-beta.239') {
$real_value = $env->real_value;
- } elseif ($env->is_literal || $env->is_multiline) {
- $real_value = '\''.$real_value.'\'';
} else {
- $real_value = escapeEnvVariables($env->real_value);
+ if ($env->is_literal || $env->is_multiline) {
+ $real_value = '\''.$real_value.'\'';
+ } else {
+ $real_value = escapeEnvVariables($env->real_value);
+ }
}
$commands[] = "echo \"{$env->key}={$real_value}\" >> .env";
}
@@ -1296,12 +1307,11 @@ public function parse(bool $isNew = false): Collection
{
if ((int) $this->compose_parsing_version >= 3) {
return newParser($this);
- }
- if ($this->docker_compose_raw) {
+ } elseif ($this->docker_compose_raw) {
return parseDockerComposeFile($this, $isNew);
+ } else {
+ return collect([]);
}
-
- return collect([]);
}
public function networks()
diff --git a/app/Models/ServiceApplication.php b/app/Models/ServiceApplication.php
index f5c1e5f145..5cafc90422 100644
--- a/app/Models/ServiceApplication.php
+++ b/app/Models/ServiceApplication.php
@@ -34,12 +34,12 @@ public function restart()
public static function ownedByCurrentTeamAPI(int $teamId)
{
- return \App\Models\ServiceApplication::query()->whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');
+ return ServiceApplication::whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');
}
public static function ownedByCurrentTeam()
{
- return \App\Models\ServiceApplication::query()->whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');
+ return ServiceApplication::whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
public function isRunning()
diff --git a/app/Models/ServiceDatabase.php b/app/Models/ServiceDatabase.php
index 88b637cd53..5fdd52637f 100644
--- a/app/Models/ServiceDatabase.php
+++ b/app/Models/ServiceDatabase.php
@@ -26,12 +26,12 @@ protected static function booted()
public static function ownedByCurrentTeamAPI(int $teamId)
{
- return \App\Models\ServiceDatabase::query()->whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');
+ return ServiceDatabase::whereRelation('service.environment.project.team', 'id', $teamId)->orderBy('name');
}
public static function ownedByCurrentTeam()
{
- return \App\Models\ServiceDatabase::query()->whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');
+ return ServiceDatabase::whereRelation('service.environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
public function restart()
@@ -133,19 +133,10 @@ public function scheduledBackups()
public function isBackupSolutionAvailable()
{
- if (str($this->databaseType())->contains('mysql')) {
- return true;
- }
- if (str($this->databaseType())->contains('postgres')) {
- return true;
- }
- if (str($this->databaseType())->contains('postgis')) {
- return true;
- }
- if (str($this->databaseType())->contains('mariadb')) {
- return true;
- }
-
- return (bool) str($this->databaseType())->contains('mongodb');
+ return str($this->databaseType())->contains('mysql') ||
+ str($this->databaseType())->contains('postgres') ||
+ str($this->databaseType())->contains('postgis') ||
+ str($this->databaseType())->contains('mariadb') ||
+ str($this->databaseType())->contains('mongodb');
}
}
diff --git a/app/Models/SharedEnvironmentVariable.php b/app/Models/SharedEnvironmentVariable.php
index 453ff0c948..aab8b87350 100644
--- a/app/Models/SharedEnvironmentVariable.php
+++ b/app/Models/SharedEnvironmentVariable.php
@@ -8,11 +8,8 @@ class SharedEnvironmentVariable extends Model
{
protected $guarded = [];
- protected function casts(): array
- {
- return [
- 'key' => 'string',
- 'value' => 'encrypted',
- ];
- }
+ protected $casts = [
+ 'key' => 'string',
+ 'value' => 'encrypted',
+ ];
}
diff --git a/app/Models/SlackNotificationSettings.php b/app/Models/SlackNotificationSettings.php
index f14c527f4c..48153f2ea8 100644
--- a/app/Models/SlackNotificationSettings.php
+++ b/app/Models/SlackNotificationSettings.php
@@ -30,6 +30,23 @@ class SlackNotificationSettings extends Model
'server_unreachable_slack_notifications',
];
+ protected $casts = [
+ 'slack_enabled' => 'boolean',
+ 'slack_webhook_url' => 'encrypted',
+
+ 'deployment_success_slack_notifications' => 'boolean',
+ 'deployment_failure_slack_notifications' => 'boolean',
+ 'status_change_slack_notifications' => 'boolean',
+ 'backup_success_slack_notifications' => 'boolean',
+ 'backup_failure_slack_notifications' => 'boolean',
+ 'scheduled_task_success_slack_notifications' => 'boolean',
+ 'scheduled_task_failure_slack_notifications' => 'boolean',
+ 'docker_cleanup_slack_notifications' => 'boolean',
+ 'server_disk_usage_slack_notifications' => 'boolean',
+ 'server_reachable_slack_notifications' => 'boolean',
+ 'server_unreachable_slack_notifications' => 'boolean',
+ ];
+
public function team()
{
return $this->belongsTo(Team::class);
@@ -39,24 +56,4 @@ public function isEnabled()
{
return $this->slack_enabled;
}
-
- protected function casts(): array
- {
- return [
- 'slack_enabled' => 'boolean',
- 'slack_webhook_url' => 'encrypted',
-
- 'deployment_success_slack_notifications' => 'boolean',
- 'deployment_failure_slack_notifications' => 'boolean',
- 'status_change_slack_notifications' => 'boolean',
- 'backup_success_slack_notifications' => 'boolean',
- 'backup_failure_slack_notifications' => 'boolean',
- 'scheduled_task_success_slack_notifications' => 'boolean',
- 'scheduled_task_failure_slack_notifications' => 'boolean',
- 'docker_cleanup_slack_notifications' => 'boolean',
- 'server_disk_usage_slack_notifications' => 'boolean',
- 'server_reachable_slack_notifications' => 'boolean',
- 'server_unreachable_slack_notifications' => 'boolean',
- ];
- }
}
diff --git a/app/Models/StandaloneClickhouse.php b/app/Models/StandaloneClickhouse.php
index 5bd23068e1..60198115da 100644
--- a/app/Models/StandaloneClickhouse.php
+++ b/app/Models/StandaloneClickhouse.php
@@ -2,7 +2,6 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,10 +15,14 @@ class StandaloneClickhouse extends BaseModel
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
+ protected $casts = [
+ 'clickhouse_password' => 'encrypted',
+ ];
+
protected static function booted()
{
static::created(function ($database) {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'clickhouse-data-'.$database->uuid,
'mount_path' => '/bitnami/clickhouse',
'host_path' => null,
@@ -66,13 +69,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function isRunning()
@@ -105,8 +109,8 @@ public function delete_volumes(Collection $persistentStorages)
return;
}
$server = data_get($this, 'destination.server');
- foreach ($persistentStorages as $persistentStorage) {
- instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);
+ foreach ($persistentStorages as $storage) {
+ instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -279,7 +283,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -301,7 +305,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -315,11 +319,4 @@ public function isBackupSolutionAvailable()
{
return false;
}
-
- protected function casts(): array
- {
- return [
- 'clickhouse_password' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/StandaloneDocker.php b/app/Models/StandaloneDocker.php
index 3beb20d6ec..1ef6ff587a 100644
--- a/app/Models/StandaloneDocker.php
+++ b/app/Models/StandaloneDocker.php
@@ -74,10 +74,6 @@ public function databases()
public function attachedTo()
{
- if ($this->applications?->count() > 0) {
- return true;
- }
-
- return $this->databases()->count() > 0;
+ return $this->applications?->count() > 0 || $this->databases()->count() > 0;
}
}
diff --git a/app/Models/StandaloneDragonfly.php b/app/Models/StandaloneDragonfly.php
index d659e0a1bb..3c1127d8de 100644
--- a/app/Models/StandaloneDragonfly.php
+++ b/app/Models/StandaloneDragonfly.php
@@ -2,7 +2,6 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,10 +15,14 @@ class StandaloneDragonfly extends BaseModel
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
+ protected $casts = [
+ 'dragonfly_password' => 'encrypted',
+ ];
+
protected static function booted()
{
static::created(function ($database) {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'dragonfly-data-'.$database->uuid,
'mount_path' => '/data',
'host_path' => null,
@@ -66,13 +69,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function isRunning()
@@ -105,8 +109,8 @@ public function delete_volumes(Collection $persistentStorages)
return;
}
$server = data_get($this, 'destination.server');
- foreach ($persistentStorages as $persistentStorage) {
- instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);
+ foreach ($persistentStorages as $storage) {
+ instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -273,7 +277,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -295,7 +299,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -315,11 +319,4 @@ public function environment_variables()
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderBy('key', 'asc');
}
-
- protected function casts(): array
- {
- return [
- 'dragonfly_password' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/StandaloneKeydb.php b/app/Models/StandaloneKeydb.php
index 2754fa40f7..ebf1c22e95 100644
--- a/app/Models/StandaloneKeydb.php
+++ b/app/Models/StandaloneKeydb.php
@@ -2,7 +2,6 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,10 +15,14 @@ class StandaloneKeydb extends BaseModel
protected $appends = ['internal_db_url', 'external_db_url', 'server_status'];
+ protected $casts = [
+ 'keydb_password' => 'encrypted',
+ ];
+
protected static function booted()
{
static::created(function ($database) {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'keydb-data-'.$database->uuid,
'mount_path' => '/data',
'host_path' => null,
@@ -66,13 +69,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function isRunning()
@@ -105,8 +109,8 @@ public function delete_volumes(Collection $persistentStorages)
return;
}
$server = data_get($this, 'destination.server');
- foreach ($persistentStorages as $persistentStorage) {
- instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);
+ foreach ($persistentStorages as $storage) {
+ instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -273,7 +277,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -295,7 +299,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -315,11 +319,4 @@ public function environment_variables()
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderBy('key', 'asc');
}
-
- protected function casts(): array
- {
- return [
- 'keydb_password' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/StandaloneMariadb.php b/app/Models/StandaloneMariadb.php
index cdb1932717..004ead4d95 100644
--- a/app/Models/StandaloneMariadb.php
+++ b/app/Models/StandaloneMariadb.php
@@ -2,7 +2,6 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,10 +15,14 @@ class StandaloneMariadb extends BaseModel
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
+ protected $casts = [
+ 'mariadb_password' => 'encrypted',
+ ];
+
protected static function booted()
{
static::created(function ($database) {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'mariadb-data-'.$database->uuid,
'mount_path' => '/var/lib/mysql',
'host_path' => null,
@@ -66,13 +69,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function isRunning()
@@ -105,8 +109,8 @@ public function delete_volumes(Collection $persistentStorages)
return;
}
$server = data_get($this, 'destination.server');
- foreach ($persistentStorages as $persistentStorage) {
- instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);
+ foreach ($persistentStorages as $storage) {
+ instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -279,7 +283,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -301,7 +305,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -315,11 +319,4 @@ public function isBackupSolutionAvailable()
{
return true;
}
-
- protected function casts(): array
- {
- return [
- 'mariadb_password' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/StandaloneMongodb.php b/app/Models/StandaloneMongodb.php
index 76c618f804..aba0f6123e 100644
--- a/app/Models/StandaloneMongodb.php
+++ b/app/Models/StandaloneMongodb.php
@@ -2,12 +2,10 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
-use Throwable;
class StandaloneMongodb extends BaseModel
{
@@ -20,7 +18,7 @@ class StandaloneMongodb extends BaseModel
protected static function booted()
{
static::created(function ($database) {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'mongodb-configdb-'.$database->uuid,
'mount_path' => '/data/configdb',
'host_path' => null,
@@ -28,7 +26,7 @@ protected static function booted()
'resource_type' => $database->getMorphClass(),
'is_readonly' => true,
]);
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'mongodb-db-'.$database->uuid,
'mount_path' => '/data/db',
'host_path' => null,
@@ -75,13 +73,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function isRunning()
@@ -114,8 +113,8 @@ public function delete_volumes(Collection $persistentStorages)
return;
}
$server = data_get($this, 'destination.server');
- foreach ($persistentStorages as $persistentStorage) {
- instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);
+ foreach ($persistentStorages as $storage) {
+ instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -197,7 +196,7 @@ public function mongoInitdbRootPassword(): Attribute
get: function ($value) {
try {
return decrypt($value);
- } catch (Throwable $th) {
+ } catch (\Throwable $th) {
$this->mongo_initdb_root_password = encrypt($value);
$this->save();
@@ -298,7 +297,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -320,7 +319,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
diff --git a/app/Models/StandaloneMysql.php b/app/Models/StandaloneMysql.php
index 32cc016cfe..9ae0fdcaeb 100644
--- a/app/Models/StandaloneMysql.php
+++ b/app/Models/StandaloneMysql.php
@@ -2,7 +2,6 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,10 +15,15 @@ class StandaloneMysql extends BaseModel
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
+ protected $casts = [
+ 'mysql_password' => 'encrypted',
+ 'mysql_root_password' => 'encrypted',
+ ];
+
protected static function booted()
{
static::created(function ($database) {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'mysql-data-'.$database->uuid,
'mount_path' => '/var/lib/mysql',
'host_path' => null,
@@ -66,13 +70,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function isRunning()
@@ -105,8 +110,8 @@ public function delete_volumes(Collection $persistentStorages)
return;
}
$server = data_get($this, 'destination.server');
- foreach ($persistentStorages as $persistentStorage) {
- instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);
+ foreach ($persistentStorages as $storage) {
+ instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -273,7 +278,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -295,7 +300,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -315,12 +320,4 @@ public function environment_variables()
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderBy('key', 'asc');
}
-
- protected function casts(): array
- {
- return [
- 'mysql_password' => 'encrypted',
- 'mysql_root_password' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/StandalonePostgresql.php b/app/Models/StandalonePostgresql.php
index 1117848231..dd92ae7c91 100644
--- a/app/Models/StandalonePostgresql.php
+++ b/app/Models/StandalonePostgresql.php
@@ -2,7 +2,6 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,10 +15,15 @@ class StandalonePostgresql extends BaseModel
protected $appends = ['internal_db_url', 'external_db_url', 'database_type', 'server_status'];
+ protected $casts = [
+ 'init_scripts' => 'array',
+ 'postgres_password' => 'encrypted',
+ ];
+
protected static function booted()
{
static::created(function ($database) {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'postgres-data-'.$database->uuid,
'mount_path' => '/var/lib/postgresql/data',
'host_path' => null,
@@ -70,8 +74,8 @@ public function delete_volumes(Collection $persistentStorages)
return;
}
$server = data_get($this, 'destination.server');
- foreach ($persistentStorages as $persistentStorage) {
- instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);
+ foreach ($persistentStorages as $storage) {
+ instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -91,13 +95,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function isRunning()
@@ -278,7 +283,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -300,7 +305,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -315,12 +320,4 @@ public function environment_variables()
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderBy('key', 'asc');
}
-
- protected function casts(): array
- {
- return [
- 'init_scripts' => 'array',
- 'postgres_password' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/StandaloneRedis.php b/app/Models/StandaloneRedis.php
index 5ca849c987..ed5cf98708 100644
--- a/app/Models/StandaloneRedis.php
+++ b/app/Models/StandaloneRedis.php
@@ -2,7 +2,6 @@
namespace App\Models;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -19,7 +18,7 @@ class StandaloneRedis extends BaseModel
protected static function booted()
{
static::created(function ($database) {
- LocalPersistentVolume::query()->create([
+ LocalPersistentVolume::create([
'name' => 'redis-data-'.$database->uuid,
'mount_path' => '/data',
'host_path' => null,
@@ -66,13 +65,14 @@ public function isConfigurationChanged(bool $save = false)
}
if ($oldConfigHash === $newConfigHash) {
return false;
- }
- if ($save) {
- $this->config_hash = $newConfigHash;
- $this->save();
- }
+ } else {
+ if ($save) {
+ $this->config_hash = $newConfigHash;
+ $this->save();
+ }
- return true;
+ return true;
+ }
}
public function isRunning()
@@ -105,8 +105,8 @@ public function delete_volumes(Collection $persistentStorages)
return;
}
$server = data_get($this, 'destination.server');
- foreach ($persistentStorages as $persistentStorage) {
- instant_remote_process(["docker volume rm -f $persistentStorage->name"], $server, false);
+ foreach ($persistentStorages as $storage) {
+ instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
@@ -288,7 +288,7 @@ public function getCpuMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
@@ -310,7 +310,7 @@ public function getMemoryMetrics(int $mins = 5)
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
- throw new Exception($error);
+ throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
diff --git a/app/Models/Subscription.php b/app/Models/Subscription.php
index a50e39a27a..1bd84a6647 100644
--- a/app/Models/Subscription.php
+++ b/app/Models/Subscription.php
@@ -19,7 +19,7 @@ public function type()
if (! $this->stripe_plan_id) {
return 'zero';
}
- $subscription = \App\Models\Subscription::query()->where('id', $this->id)->first();
+ $subscription = Subscription::where('id', $this->id)->first();
if (! $subscription) {
return null;
}
diff --git a/app/Models/SwarmDocker.php b/app/Models/SwarmDocker.php
index 99993aba69..e0fe349c71 100644
--- a/app/Models/SwarmDocker.php
+++ b/app/Models/SwarmDocker.php
@@ -77,10 +77,6 @@ public function databases()
public function attachedTo()
{
- if ($this->applications?->count() > 0) {
- return true;
- }
-
- return $this->databases()->count() > 0;
+ return $this->applications?->count() > 0 || $this->databases()->count() > 0;
}
}
diff --git a/app/Models/Team.php b/app/Models/Team.php
index 9915918b2d..8651df3c8b 100644
--- a/app/Models/Team.php
+++ b/app/Models/Team.php
@@ -8,7 +8,6 @@
use App\Notifications\Channels\SendsPushover;
use App\Notifications\Channels\SendsSlack;
use App\Traits\HasNotificationSettings;
-use Exception;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
@@ -41,6 +40,10 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Sen
protected $guarded = [];
+ protected $casts = [
+ 'personal_team' => 'boolean',
+ ];
+
protected static function booted()
{
static::created(function ($team) {
@@ -53,7 +56,7 @@ protected static function booted()
static::saving(function ($team) {
if (auth()->user()?->isMember()) {
- throw new Exception('You are not allowed to update this team.');
+ throw new \Exception('You are not allowed to update this team.');
}
});
@@ -92,7 +95,11 @@ public static function serverLimitReached()
public function serverOverflow()
{
- return $this->serverLimit() < $this->servers->count();
+ if ($this->serverLimit() < $this->servers->count()) {
+ return true;
+ }
+
+ return false;
}
public static function serverLimit()
@@ -100,7 +107,7 @@ public static function serverLimit()
if (currentTeam()->id === 0 && isDev()) {
return 9999999;
}
- $team = \App\Models\Team::query()->find(currentTeam()->id);
+ $team = Team::find(currentTeam()->id);
if (! $team) {
return 0;
}
@@ -162,20 +169,12 @@ public function isAnyNotificationEnabled()
if (isCloud()) {
return true;
}
- if ($this->getNotificationSettings('email')?->isEnabled()) {
- return true;
- }
- if ($this->getNotificationSettings('discord')?->isEnabled()) {
- return true;
- }
- if ($this->getNotificationSettings('slack')?->isEnabled()) {
- return true;
- }
- if ($this->getNotificationSettings('telegram')?->isEnabled()) {
- return true;
- }
- return (bool) $this->getNotificationSettings('pushover')?->isEnabled();
+ return $this->getNotificationSettings('email')?->isEnabled() ||
+ $this->getNotificationSettings('discord')?->isEnabled() ||
+ $this->getNotificationSettings('slack')?->isEnabled() ||
+ $this->getNotificationSettings('telegram')?->isEnabled() ||
+ $this->getNotificationSettings('pushover')?->isEnabled();
}
public function subscriptionEnded()
@@ -223,7 +222,11 @@ public function invitations()
public function isEmpty()
{
- return $this->projects()->count() === 0 && $this->servers()->count() === 0 && $this->privateKeys()->count() === 0 && $this->sources()->count() === 0;
+ if ($this->projects()->count() === 0 && $this->servers()->count() === 0 && $this->privateKeys()->count() === 0 && $this->sources()->count() === 0) {
+ return true;
+ }
+
+ return false;
}
public function projects()
@@ -279,11 +282,4 @@ public function pushoverNotificationSettings()
{
return $this->hasOne(PushoverNotificationSettings::class);
}
-
- protected function casts(): array
- {
- return [
- 'personal_team' => 'boolean',
- ];
- }
}
diff --git a/app/Models/TeamInvitation.php b/app/Models/TeamInvitation.php
index b64b356bd0..bc1a90d586 100644
--- a/app/Models/TeamInvitation.php
+++ b/app/Models/TeamInvitation.php
@@ -31,9 +31,10 @@ public function isValid()
$diff = $createdAt->diffInDays(now());
if ($diff <= config('constants.invitation.link.expiration_days')) {
return true;
- }
- $this->delete();
+ } else {
+ $this->delete();
- return false;
+ return false;
+ }
}
}
diff --git a/app/Models/TelegramNotificationSettings.php b/app/Models/TelegramNotificationSettings.php
index ec83327aed..78bd841bd4 100644
--- a/app/Models/TelegramNotificationSettings.php
+++ b/app/Models/TelegramNotificationSettings.php
@@ -43,6 +43,36 @@ class TelegramNotificationSettings extends Model
'telegram_notifications_server_unreachable_thread_id',
];
+ protected $casts = [
+ 'telegram_enabled' => 'boolean',
+ 'telegram_token' => 'encrypted',
+ 'telegram_chat_id' => 'encrypted',
+
+ 'deployment_success_telegram_notifications' => 'boolean',
+ 'deployment_failure_telegram_notifications' => 'boolean',
+ 'status_change_telegram_notifications' => 'boolean',
+ 'backup_success_telegram_notifications' => 'boolean',
+ 'backup_failure_telegram_notifications' => 'boolean',
+ 'scheduled_task_success_telegram_notifications' => 'boolean',
+ 'scheduled_task_failure_telegram_notifications' => 'boolean',
+ 'docker_cleanup_telegram_notifications' => 'boolean',
+ 'server_disk_usage_telegram_notifications' => 'boolean',
+ 'server_reachable_telegram_notifications' => 'boolean',
+ 'server_unreachable_telegram_notifications' => 'boolean',
+
+ 'telegram_notifications_deployment_success_thread_id' => 'encrypted',
+ 'telegram_notifications_deployment_failure_thread_id' => 'encrypted',
+ 'telegram_notifications_status_change_thread_id' => 'encrypted',
+ 'telegram_notifications_backup_success_thread_id' => 'encrypted',
+ 'telegram_notifications_backup_failure_thread_id' => 'encrypted',
+ 'telegram_notifications_scheduled_task_success_thread_id' => 'encrypted',
+ 'telegram_notifications_scheduled_task_failure_thread_id' => 'encrypted',
+ 'telegram_notifications_docker_cleanup_thread_id' => 'encrypted',
+ 'telegram_notifications_server_disk_usage_thread_id' => 'encrypted',
+ 'telegram_notifications_server_reachable_thread_id' => 'encrypted',
+ 'telegram_notifications_server_unreachable_thread_id' => 'encrypted',
+ ];
+
public function team()
{
return $this->belongsTo(Team::class);
@@ -52,37 +82,4 @@ public function isEnabled()
{
return $this->telegram_enabled;
}
-
- protected function casts(): array
- {
- return [
- 'telegram_enabled' => 'boolean',
- 'telegram_token' => 'encrypted',
- 'telegram_chat_id' => 'encrypted',
-
- 'deployment_success_telegram_notifications' => 'boolean',
- 'deployment_failure_telegram_notifications' => 'boolean',
- 'status_change_telegram_notifications' => 'boolean',
- 'backup_success_telegram_notifications' => 'boolean',
- 'backup_failure_telegram_notifications' => 'boolean',
- 'scheduled_task_success_telegram_notifications' => 'boolean',
- 'scheduled_task_failure_telegram_notifications' => 'boolean',
- 'docker_cleanup_telegram_notifications' => 'boolean',
- 'server_disk_usage_telegram_notifications' => 'boolean',
- 'server_reachable_telegram_notifications' => 'boolean',
- 'server_unreachable_telegram_notifications' => 'boolean',
-
- 'telegram_notifications_deployment_success_thread_id' => 'encrypted',
- 'telegram_notifications_deployment_failure_thread_id' => 'encrypted',
- 'telegram_notifications_status_change_thread_id' => 'encrypted',
- 'telegram_notifications_backup_success_thread_id' => 'encrypted',
- 'telegram_notifications_backup_failure_thread_id' => 'encrypted',
- 'telegram_notifications_scheduled_task_success_thread_id' => 'encrypted',
- 'telegram_notifications_scheduled_task_failure_thread_id' => 'encrypted',
- 'telegram_notifications_docker_cleanup_thread_id' => 'encrypted',
- 'telegram_notifications_server_disk_usage_thread_id' => 'encrypted',
- 'telegram_notifications_server_reachable_thread_id' => 'encrypted',
- 'telegram_notifications_server_unreachable_thread_id' => 'encrypted',
- ];
- }
}
diff --git a/app/Models/User.php b/app/Models/User.php
index 054a647fba..7c23631c36 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -48,6 +48,12 @@ class User extends Authenticatable implements SendsEmail
'two_factor_secret',
];
+ protected $casts = [
+ 'email_verified_at' => 'datetime',
+ 'force_password_reset' => 'boolean',
+ 'show_boarding' => 'boolean',
+ ];
+
protected static function boot()
{
parent::boot();
@@ -61,7 +67,7 @@ protected static function boot()
$team['id'] = 0;
$team['name'] = 'Root Team';
}
- $new_team = Team::query()->create($team);
+ $new_team = Team::create($team);
$user->teams()->attach($new_team, ['role' => 'owner']);
});
}
@@ -77,7 +83,7 @@ public function recreate_personal_team()
$team['id'] = 0;
$team['name'] = 'Root Team';
}
- $new_team = Team::query()->create($team);
+ $new_team = Team::create($team);
$this->teams()->attach($new_team, ['role' => 'owner']);
return $new_team;
@@ -92,7 +98,7 @@ public function createToken(string $name, array $abilities = ['*'], ?DateTimeInt
hash('crc32b', $tokenEntropy)
);
- $personalAccessToken = $this->tokens()->create([
+ $token = $this->tokens()->create([
'name' => $name,
'token' => hash('sha256', $plainTextToken),
'abilities' => $abilities,
@@ -100,7 +106,7 @@ public function createToken(string $name, array $abilities = ['*'], ?DateTimeInt
'team_id' => session('currentTeam')->id,
]);
- return new NewAccessToken($personalAccessToken, $personalAccessToken->getKey().'|'.$plainTextToken);
+ return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
}
public function teams()
@@ -115,7 +121,7 @@ public function getRecipients($notification)
public function sendVerificationEmail()
{
- $mailMessage = new MailMessage;
+ $mail = new MailMessage;
$url = Url::temporarySignedRoute(
'verify.verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
@@ -124,11 +130,11 @@ public function sendVerificationEmail()
'hash' => sha1($this->getEmailForVerification()),
]
);
- $mailMessage->view('emails.email-verification', [
+ $mail->view('emails.email-verification', [
'url' => $url,
]);
- $mailMessage->subject('Coolify: Verify your email.');
- send_user_an_email($mailMessage, $this->email);
+ $mail->subject('Coolify: Verify your email.');
+ send_user_an_email($mail, $this->email);
}
public function sendPasswordResetNotification($token): void
@@ -138,11 +144,7 @@ public function sendPasswordResetNotification($token): void
public function isAdmin()
{
- if ($this->role() === 'admin') {
- return true;
- }
-
- return $this->role() === 'owner';
+ return $this->role() === 'admin' || $this->role() === 'owner';
}
public function isOwner()
@@ -179,7 +181,11 @@ public function isInstanceAdmin()
{
$found_root_team = Auth::user()->teams->filter(function ($team) {
if ($team->id == 0) {
- return (bool) Auth::user()->isAdmin();
+ if (! Auth::user()->isAdmin()) {
+ return false;
+ }
+
+ return true;
}
return false;
@@ -195,7 +201,7 @@ public function currentTeam()
return Auth::user()->teams[0];
}
- return Team::query()->find(session('currentTeam')->id);
+ return Team::find(session('currentTeam')->id);
});
}
@@ -215,13 +221,4 @@ public function role()
return data_get($user, 'pivot.role');
}
-
- protected function casts(): array
- {
- return [
- 'email_verified_at' => 'datetime',
- 'force_password_reset' => 'boolean',
- 'show_boarding' => 'boolean',
- ];
- }
}
diff --git a/app/Models/Webhook.php b/app/Models/Webhook.php
index f4d7c3de98..8e2b629558 100644
--- a/app/Models/Webhook.php
+++ b/app/Models/Webhook.php
@@ -8,11 +8,8 @@ class Webhook extends Model
{
protected $guarded = [];
- protected function casts(): array
- {
- return [
- 'type' => 'string',
- 'payload' => 'encrypted',
- ];
- }
+ protected $casts = [
+ 'type' => 'string',
+ 'payload' => 'encrypted',
+ ];
}
diff --git a/app/Notifications/Application/DeploymentFailed.php b/app/Notifications/Application/DeploymentFailed.php
index 37760d086a..0c09b1dbd0 100644
--- a/app/Notifications/Application/DeploymentFailed.php
+++ b/app/Notifications/Application/DeploymentFailed.php
@@ -30,12 +30,12 @@ class DeploymentFailed extends CustomEmailNotification
public ?string $fqdn = null;
- public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $applicationPreview = null)
+ public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $preview = null)
{
$this->onQueue('high');
$this->application = $application;
$this->deployment_uuid = $deployment_uuid;
- $this->preview = $applicationPreview;
+ $this->preview = $preview;
$this->application_name = data_get($application, 'name');
$this->project_uuid = data_get($application, 'environment.project.uuid');
$this->environment_uuid = data_get($application, 'environment.uuid');
@@ -54,28 +54,28 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
+ $mail = new MailMessage;
$pull_request_id = data_get($this->preview, 'pull_request_id', 0);
$fqdn = $this->fqdn;
if ($pull_request_id === 0) {
- $mailMessage->subject('Coolify: Deployment failed of '.$this->application_name.'.');
+ $mail->subject('Coolify: Deployment failed of '.$this->application_name.'.');
} else {
$fqdn = $this->preview->fqdn;
- $mailMessage->subject('Coolify: Deployment failed of pull request #'.$this->preview->pull_request_id.' of '.$this->application_name.'.');
+ $mail->subject('Coolify: Deployment failed of pull request #'.$this->preview->pull_request_id.' of '.$this->application_name.'.');
}
- $mailMessage->view('emails.application-deployment-failed', [
+ $mail->view('emails.application-deployment-failed', [
'name' => $this->application_name,
'fqdn' => $fqdn,
'deployment_url' => $this->deployment_url,
'pull_request_id' => data_get($this->preview, 'pull_request_id', 0),
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- if ($this->preview instanceof ApplicationPreview) {
+ if ($this->preview) {
$message = new DiscordMessage(
title: ':cross_mark: Deployment failed',
description: 'Pull request: '.$this->preview->pull_request_id,
@@ -92,16 +92,22 @@ public function toDiscord(): DiscordMessage
$message->addField('Domain', $this->fqdn, true);
}
} else {
- $description = $this->fqdn ? '[Open application]('.$this->fqdn.')' : '';
+ if ($this->fqdn) {
+ $description = '[Open application]('.$this->fqdn.')';
+ } else {
+ $description = '';
+ }
$message = new DiscordMessage(
title: ':cross_mark: Deployment failed',
description: $description,
color: DiscordMessage::errorColor(),
isCritical: true,
);
+
$message->addField('Project', data_get($this->application, 'environment.project.name'), true);
$message->addField('Environment', $this->environment_name, true);
$message->addField('Name', $this->application_name, true);
+
$message->addField('Deployment Logs', '[Link]('.$this->deployment_url.')');
}
@@ -110,7 +116,7 @@ public function toDiscord(): DiscordMessage
public function toTelegram(): array
{
- if ($this->preview instanceof ApplicationPreview) {
+ if ($this->preview) {
$message = 'Coolify: Pull request #'.$this->preview->pull_request_id.' of '.$this->application_name.' ('.$this->preview->fqdn.') deployment failed: ';
} else {
$message = 'Coolify: Deployment failed of '.$this->application_name.' ('.$this->fqdn.'): ';
@@ -130,7 +136,7 @@ public function toTelegram(): array
public function toPushover(): PushoverMessage
{
- if ($this->preview instanceof ApplicationPreview) {
+ if ($this->preview) {
$title = "Pull request #{$this->preview->pull_request_id} deployment failed";
$message = "Pull request deployment failed for {$this->application_name}";
} else {
@@ -155,7 +161,7 @@ public function toPushover(): PushoverMessage
public function toSlack(): SlackMessage
{
- if ($this->preview instanceof ApplicationPreview) {
+ if ($this->preview) {
$title = "Pull request #{$this->preview->pull_request_id} deployment failed";
$description = "Pull request deployment failed for {$this->application_name}";
if ($this->preview->fqdn) {
diff --git a/app/Notifications/Application/DeploymentSuccess.php b/app/Notifications/Application/DeploymentSuccess.php
index 1632988451..e1067e9bc4 100644
--- a/app/Notifications/Application/DeploymentSuccess.php
+++ b/app/Notifications/Application/DeploymentSuccess.php
@@ -30,12 +30,12 @@ class DeploymentSuccess extends CustomEmailNotification
public ?string $fqdn;
- public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $applicationPreview = null)
+ public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $preview = null)
{
$this->onQueue('high');
$this->application = $application;
$this->deployment_uuid = $deployment_uuid;
- $this->preview = $applicationPreview;
+ $this->preview = $preview;
$this->application_name = data_get($application, 'name');
$this->project_uuid = data_get($application, 'environment.project.uuid');
$this->environment_uuid = data_get($application, 'environment.uuid');
@@ -54,28 +54,28 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
+ $mail = new MailMessage;
$pull_request_id = data_get($this->preview, 'pull_request_id', 0);
$fqdn = $this->fqdn;
if ($pull_request_id === 0) {
- $mailMessage->subject("Coolify: New version is deployed of {$this->application_name}");
+ $mail->subject("Coolify: New version is deployed of {$this->application_name}");
} else {
$fqdn = $this->preview->fqdn;
- $mailMessage->subject("Coolify: Pull request #{$pull_request_id} of {$this->application_name} deployed successfully");
+ $mail->subject("Coolify: Pull request #{$pull_request_id} of {$this->application_name} deployed successfully");
}
- $mailMessage->view('emails.application-deployment-success', [
+ $mail->view('emails.application-deployment-success', [
'name' => $this->application_name,
'fqdn' => $fqdn,
'deployment_url' => $this->deployment_url,
'pull_request_id' => $pull_request_id,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- if ($this->preview instanceof ApplicationPreview) {
+ if ($this->preview) {
$message = new DiscordMessage(
title: ':white_check_mark: Preview deployment successful',
description: 'Pull request: '.$this->preview->pull_request_id,
@@ -91,7 +91,11 @@ public function toDiscord(): DiscordMessage
$message->addField('Name', $this->application_name, true);
$message->addField('Deployment logs', '[Link]('.$this->deployment_url.')');
} else {
- $description = $this->fqdn ? '[Open application]('.$this->fqdn.')' : '';
+ if ($this->fqdn) {
+ $description = '[Open application]('.$this->fqdn.')';
+ } else {
+ $description = '';
+ }
$message = new DiscordMessage(
title: ':white_check_mark: New version successfully deployed',
description: $description,
@@ -100,6 +104,7 @@ public function toDiscord(): DiscordMessage
$message->addField('Project', data_get($this->application, 'environment.project.name'), true);
$message->addField('Environment', $this->environment_name, true);
$message->addField('Name', $this->application_name, true);
+
$message->addField('Deployment logs', '[Link]('.$this->deployment_url.')');
}
@@ -108,7 +113,7 @@ public function toDiscord(): DiscordMessage
public function toTelegram(): array
{
- if ($this->preview instanceof ApplicationPreview) {
+ if ($this->preview) {
$message = 'Coolify: New PR'.$this->preview->pull_request_id.' version successfully deployed of '.$this->application_name.'';
if ($this->preview->fqdn) {
$buttons[] = [
@@ -140,7 +145,7 @@ public function toTelegram(): array
public function toPushover(): PushoverMessage
{
- if ($this->preview instanceof ApplicationPreview) {
+ if ($this->preview) {
$title = "Pull request #{$this->preview->pull_request_id} successfully deployed";
$message = 'New PR'.$this->preview->pull_request_id.' version successfully deployed of '.$this->application_name.'';
if ($this->preview->fqdn) {
@@ -176,7 +181,7 @@ public function toPushover(): PushoverMessage
public function toSlack(): SlackMessage
{
- if ($this->preview instanceof ApplicationPreview) {
+ if ($this->preview) {
$title = "Pull request #{$this->preview->pull_request_id} successfully deployed";
$description = "New version successfully deployed for {$this->application_name}";
if ($this->preview->fqdn) {
diff --git a/app/Notifications/Application/StatusChanged.php b/app/Notifications/Application/StatusChanged.php
index d9fa18e401..669f6e5842 100644
--- a/app/Notifications/Application/StatusChanged.php
+++ b/app/Notifications/Application/StatusChanged.php
@@ -23,18 +23,18 @@ class StatusChanged extends CustomEmailNotification
public ?string $fqdn;
- public function __construct(public Application $application)
+ public function __construct(public Application $resource)
{
$this->onQueue('high');
- $this->resource_name = data_get($application, 'name');
- $this->project_uuid = data_get($application, 'environment.project.uuid');
- $this->environment_uuid = data_get($application, 'environment.uuid');
- $this->environment_name = data_get($application, 'environment.name');
- $this->fqdn = data_get($application, 'fqdn', null);
+ $this->resource_name = data_get($resource, 'name');
+ $this->project_uuid = data_get($resource, 'environment.project.uuid');
+ $this->environment_uuid = data_get($resource, 'environment.uuid');
+ $this->environment_name = data_get($resource, 'environment.name');
+ $this->fqdn = data_get($resource, 'fqdn', null);
if (str($this->fqdn)->explode(',')->count() > 1) {
$this->fqdn = str($this->fqdn)->explode(',')->first();
}
- $this->resource_url = base_url()."/project/{$this->project_uuid}/environments/{$this->environment_uuid}/application/{$this->application->uuid}";
+ $this->resource_url = base_url()."/project/{$this->project_uuid}/environments/{$this->environment_uuid}/application/{$this->resource->uuid}";
}
public function via(object $notifiable): array
@@ -44,16 +44,16 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
+ $mail = new MailMessage;
$fqdn = $this->fqdn;
- $mailMessage->subject("Coolify: {$this->resource_name} has been stopped");
- $mailMessage->view('emails.application-status-changes', [
+ $mail->subject("Coolify: {$this->resource_name} has been stopped");
+ $mail->view('emails.application-status-changes', [
'name' => $this->resource_name,
'fqdn' => $fqdn,
'resource_url' => $this->resource_url,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
@@ -103,7 +103,7 @@ public function toSlack(): SlackMessage
$title = 'Application stopped';
$description = "{$this->resource_name} has been stopped";
- $description .= "\n\n**Project:** ".data_get($this->application, 'environment.project.name');
+ $description .= "\n\n**Project:** ".data_get($this->resource, 'environment.project.name');
$description .= "\n**Environment:** {$this->environment_name}";
$description .= "\n**Application URL:** {$this->resource_url}";
diff --git a/app/Notifications/Channels/DiscordChannel.php b/app/Notifications/Channels/DiscordChannel.php
index cf3613df00..362006d8ec 100644
--- a/app/Notifications/Channels/DiscordChannel.php
+++ b/app/Notifications/Channels/DiscordChannel.php
@@ -10,11 +10,11 @@ class DiscordChannel
/**
* Send the given notification.
*/
- public function send(SendsDiscord $sendsDiscord, Notification $notification): void
+ public function send(SendsDiscord $notifiable, Notification $notification): void
{
$message = $notification->toDiscord();
- $discordSettings = $sendsDiscord->discordNotificationSettings;
+ $discordSettings = $notifiable->discordNotificationSettings;
if (! $discordSettings || ! $discordSettings->isEnabled() || ! $discordSettings->discord_webhook_url) {
return;
diff --git a/app/Notifications/Channels/EmailChannel.php b/app/Notifications/Channels/EmailChannel.php
index 1289e2b572..6ffe5c4d79 100644
--- a/app/Notifications/Channels/EmailChannel.php
+++ b/app/Notifications/Channels/EmailChannel.php
@@ -9,16 +9,16 @@
class EmailChannel
{
- public function send(SendsEmail $sendsEmail, Notification $notification): void
+ public function send(SendsEmail $notifiable, Notification $notification): void
{
try {
- $this->bootConfigs($sendsEmail);
- $recipients = $sendsEmail->getRecipients($notification);
+ $this->bootConfigs($notifiable);
+ $recipients = $notifiable->getRecipients($notification);
if (count($recipients) === 0) {
throw new Exception('No email recipients found');
}
- $mailMessage = $notification->toMail($sendsEmail);
+ $mailMessage = $notification->toMail($notifiable);
Mail::send(
[],
[],
diff --git a/app/Notifications/Channels/PushoverChannel.php b/app/Notifications/Channels/PushoverChannel.php
index 663db4aa77..3d3728d01f 100644
--- a/app/Notifications/Channels/PushoverChannel.php
+++ b/app/Notifications/Channels/PushoverChannel.php
@@ -7,10 +7,10 @@
class PushoverChannel
{
- public function send(SendsPushover $sendsPushover, Notification $notification): void
+ public function send(SendsPushover $notifiable, Notification $notification): void
{
$message = $notification->toPushover();
- $pushoverSettings = $sendsPushover->pushoverNotificationSettings;
+ $pushoverSettings = $notifiable->pushoverNotificationSettings;
if (! $pushoverSettings || ! $pushoverSettings->isEnabled() || ! $pushoverSettings->pushover_user_key || ! $pushoverSettings->pushover_api_token) {
return;
diff --git a/app/Notifications/Channels/SlackChannel.php b/app/Notifications/Channels/SlackChannel.php
index f85de5c826..cddb7a5611 100644
--- a/app/Notifications/Channels/SlackChannel.php
+++ b/app/Notifications/Channels/SlackChannel.php
@@ -10,10 +10,10 @@ class SlackChannel
/**
* Send the given notification.
*/
- public function send(SendsSlack $sendsSlack, Notification $notification): void
+ public function send(SendsSlack $notifiable, Notification $notification): void
{
$message = $notification->toSlack();
- $slackSettings = $sendsSlack->slackNotificationSettings;
+ $slackSettings = $notifiable->slackNotificationSettings;
if (! $slackSettings || ! $slackSettings->isEnabled() || ! $slackSettings->slack_webhook_url) {
return;
diff --git a/app/Notifications/Channels/TelegramChannel.php b/app/Notifications/Channels/TelegramChannel.php
index 43f8fc4233..ea4ab71715 100644
--- a/app/Notifications/Channels/TelegramChannel.php
+++ b/app/Notifications/Channels/TelegramChannel.php
@@ -3,20 +3,6 @@
namespace App\Notifications\Channels;
use App\Jobs\SendMessageToTelegramJob;
-use App\Notifications\Application\DeploymentFailed;
-use App\Notifications\Application\DeploymentSuccess;
-use App\Notifications\Application\StatusChanged;
-use App\Notifications\Container\ContainerRestarted;
-use App\Notifications\Container\ContainerStopped;
-use App\Notifications\Database\BackupFailed;
-use App\Notifications\Database\BackupSuccess;
-use App\Notifications\ScheduledTask\TaskFailed;
-use App\Notifications\ScheduledTask\TaskSuccess;
-use App\Notifications\Server\DockerCleanupFailed;
-use App\Notifications\Server\DockerCleanupSuccess;
-use App\Notifications\Server\HighDiskUsage;
-use App\Notifications\Server\Reachable;
-use App\Notifications\Server\Unreachable;
class TelegramChannel
{
@@ -31,23 +17,23 @@ public function send($notifiable, $notification): void
$chatId = $settings->telegram_chat_id;
$threadId = match (get_class($notification)) {
- DeploymentSuccess::class => $settings->telegram_notifications_deployment_success_thread_id,
- DeploymentFailed::class => $settings->telegram_notifications_deployment_failure_thread_id,
- StatusChanged::class,
- ContainerRestarted::class,
- ContainerStopped::class => $settings->telegram_notifications_status_change_thread_id,
-
- BackupSuccess::class => $settings->telegram_notifications_backup_success_thread_id,
- BackupFailed::class => $settings->telegram_notifications_backup_failure_thread_id,
-
- TaskSuccess::class => $settings->telegram_notifications_scheduled_task_success_thread_id,
- TaskFailed::class => $settings->telegram_notifications_scheduled_task_failure_thread_id,
-
- DockerCleanupSuccess::class => $settings->telegram_notifications_docker_cleanup_success_thread_id,
- DockerCleanupFailed::class => $settings->telegram_notifications_docker_cleanup_failure_thread_id,
- HighDiskUsage::class => $settings->telegram_notifications_server_disk_usage_thread_id,
- Unreachable::class => $settings->telegram_notifications_server_unreachable_thread_id,
- Reachable::class => $settings->telegram_notifications_server_reachable_thread_id,
+ \App\Notifications\Application\DeploymentSuccess::class => $settings->telegram_notifications_deployment_success_thread_id,
+ \App\Notifications\Application\DeploymentFailed::class => $settings->telegram_notifications_deployment_failure_thread_id,
+ \App\Notifications\Application\StatusChanged::class,
+ \App\Notifications\Container\ContainerRestarted::class,
+ \App\Notifications\Container\ContainerStopped::class => $settings->telegram_notifications_status_change_thread_id,
+
+ \App\Notifications\Database\BackupSuccess::class => $settings->telegram_notifications_backup_success_thread_id,
+ \App\Notifications\Database\BackupFailed::class => $settings->telegram_notifications_backup_failure_thread_id,
+
+ \App\Notifications\ScheduledTask\TaskSuccess::class => $settings->telegram_notifications_scheduled_task_success_thread_id,
+ \App\Notifications\ScheduledTask\TaskFailed::class => $settings->telegram_notifications_scheduled_task_failure_thread_id,
+
+ \App\Notifications\Server\DockerCleanupSuccess::class => $settings->telegram_notifications_docker_cleanup_success_thread_id,
+ \App\Notifications\Server\DockerCleanupFailed::class => $settings->telegram_notifications_docker_cleanup_failure_thread_id,
+ \App\Notifications\Server\HighDiskUsage::class => $settings->telegram_notifications_server_disk_usage_thread_id,
+ \App\Notifications\Server\Unreachable::class => $settings->telegram_notifications_server_unreachable_thread_id,
+ \App\Notifications\Server\Reachable::class => $settings->telegram_notifications_server_reachable_thread_id,
default => null,
};
diff --git a/app/Notifications/Channels/TransactionalEmailChannel.php b/app/Notifications/Channels/TransactionalEmailChannel.php
index 91bfaa8b67..7617802313 100644
--- a/app/Notifications/Channels/TransactionalEmailChannel.php
+++ b/app/Notifications/Channels/TransactionalEmailChannel.php
@@ -10,18 +10,18 @@
class TransactionalEmailChannel
{
- public function send(User $user, Notification $notification): void
+ public function send(User $notifiable, Notification $notification): void
{
$settings = instanceSettings();
if (! data_get($settings, 'smtp_enabled') && ! data_get($settings, 'resend_enabled')) {
return;
}
- $email = $user->email;
+ $email = $notifiable->email;
if (! $email) {
return;
}
$this->bootConfigs();
- $mailMessage = $notification->toMail($user);
+ $mailMessage = $notification->toMail($notifiable);
Mail::send(
[],
[],
diff --git a/app/Notifications/Container/ContainerRestarted.php b/app/Notifications/Container/ContainerRestarted.php
index 91fdc9e2ba..68fc6b019d 100644
--- a/app/Notifications/Container/ContainerRestarted.php
+++ b/app/Notifications/Container/ContainerRestarted.php
@@ -23,30 +23,30 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: A resource ({$this->name}) has been restarted automatically on {$this->server->name}");
- $mailMessage->view('emails.container-restarted', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: A resource ({$this->name}) has been restarted automatically on {$this->server->name}");
+ $mail->view('emails.container-restarted', [
'containerName' => $this->name,
'serverName' => $this->server->name,
'url' => $this->url,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':warning: Resource restarted',
description: "{$this->name} has been restarted automatically on {$this->server->name}.",
color: DiscordMessage::infoColor(),
);
if ($this->url) {
- $discordMessage->addField('Resource', '[Link]('.$this->url.')');
+ $message->addField('Resource', '[Link]('.$this->url.')');
}
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
diff --git a/app/Notifications/Container/ContainerStopped.php b/app/Notifications/Container/ContainerStopped.php
index 01955651f1..59ad7ae4e4 100644
--- a/app/Notifications/Container/ContainerStopped.php
+++ b/app/Notifications/Container/ContainerStopped.php
@@ -23,30 +23,30 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: A resource has been stopped unexpectedly on {$this->server->name}");
- $mailMessage->view('emails.container-stopped', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: A resource has been stopped unexpectedly on {$this->server->name}");
+ $mail->view('emails.container-stopped', [
'containerName' => $this->name,
'serverName' => $this->server->name,
'url' => $this->url,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':cross_mark: Resource stopped',
description: "{$this->name} has been stopped unexpectedly on {$this->server->name}.",
color: DiscordMessage::errorColor(),
);
if ($this->url) {
- $discordMessage->addField('Resource', '[Link]('.$this->url.')');
+ $message->addField('Resource', '[Link]('.$this->url.')');
}
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
diff --git a/app/Notifications/Database/BackupFailed.php b/app/Notifications/Database/BackupFailed.php
index 4229c95582..6dcb705839 100644
--- a/app/Notifications/Database/BackupFailed.php
+++ b/app/Notifications/Database/BackupFailed.php
@@ -15,11 +15,11 @@ class BackupFailed extends CustomEmailNotification
public string $frequency;
- public function __construct(ScheduledDatabaseBackup $scheduledDatabaseBackup, public $database, public $output, public $database_name)
+ public function __construct(ScheduledDatabaseBackup $backup, public $database, public $output, public $database_name)
{
$this->onQueue('high');
$this->name = $database->name;
- $this->frequency = $scheduledDatabaseBackup->frequency;
+ $this->frequency = $backup->frequency;
}
public function via(object $notifiable): array
@@ -29,31 +29,31 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: [ACTION REQUIRED] Database Backup FAILED for {$this->database->name}");
- $mailMessage->view('emails.backup-failed', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: [ACTION REQUIRED] Database Backup FAILED for {$this->database->name}");
+ $mail->view('emails.backup-failed', [
'name' => $this->name,
'database_name' => $this->database_name,
'frequency' => $this->frequency,
'output' => $this->output,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':cross_mark: Database backup failed',
description: "Database backup for {$this->name} (db:{$this->database_name}) has FAILED.",
color: DiscordMessage::errorColor(),
isCritical: true,
);
- $discordMessage->addField('Frequency', $this->frequency, true);
- $discordMessage->addField('Output', $this->output);
+ $message->addField('Frequency', $this->frequency, true);
+ $message->addField('Output', $this->output);
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
diff --git a/app/Notifications/Database/BackupSuccess.php b/app/Notifications/Database/BackupSuccess.php
index 8696d52fc4..585f7cce19 100644
--- a/app/Notifications/Database/BackupSuccess.php
+++ b/app/Notifications/Database/BackupSuccess.php
@@ -15,12 +15,12 @@ class BackupSuccess extends CustomEmailNotification
public string $frequency;
- public function __construct(ScheduledDatabaseBackup $scheduledDatabaseBackup, public $database, public $database_name)
+ public function __construct(ScheduledDatabaseBackup $backup, public $database, public $database_name)
{
$this->onQueue('high');
$this->name = $database->name;
- $this->frequency = $scheduledDatabaseBackup->frequency;
+ $this->frequency = $backup->frequency;
}
public function via(object $notifiable): array
@@ -30,28 +30,28 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: Backup successfully done for {$this->database->name}");
- $mailMessage->view('emails.backup-success', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: Backup successfully done for {$this->database->name}");
+ $mail->view('emails.backup-success', [
'name' => $this->name,
'database_name' => $this->database_name,
'frequency' => $this->frequency,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':white_check_mark: Database backup successful',
description: "Database backup for {$this->name} (db:{$this->database_name}) was successful.",
color: DiscordMessage::successColor(),
);
- $discordMessage->addField('Frequency', $this->frequency, true);
+ $message->addField('Frequency', $this->frequency, true);
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
diff --git a/app/Notifications/ScheduledTask/TaskFailed.php b/app/Notifications/ScheduledTask/TaskFailed.php
index 9d43808c68..c4d92f2135 100644
--- a/app/Notifications/ScheduledTask/TaskFailed.php
+++ b/app/Notifications/ScheduledTask/TaskFailed.php
@@ -13,13 +13,13 @@ class TaskFailed extends CustomEmailNotification
{
public ?string $url = null;
- public function __construct(public ScheduledTask $scheduledTask, public string $output)
+ public function __construct(public ScheduledTask $task, public string $output)
{
$this->onQueue('high');
- if ($scheduledTask->application) {
- $this->url = $scheduledTask->application->taskLink($scheduledTask->uuid);
- } elseif ($scheduledTask->service) {
- $this->url = $scheduledTask->service->taskLink($scheduledTask->uuid);
+ if ($task->application) {
+ $this->url = $task->application->taskLink($task->uuid);
+ } elseif ($task->service) {
+ $this->url = $task->service->taskLink($task->uuid);
}
}
@@ -30,39 +30,39 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: [ACTION REQUIRED] Scheduled task ({$this->scheduledTask->name}) failed.");
- $mailMessage->view('emails.scheduled-task-failed', [
- 'task' => $this->scheduledTask,
+ $mail = new MailMessage;
+ $mail->subject("Coolify: [ACTION REQUIRED] Scheduled task ({$this->task->name}) failed.");
+ $mail->view('emails.scheduled-task-failed', [
+ 'task' => $this->task,
'url' => $this->url,
'output' => $this->output,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':cross_mark: Scheduled task failed',
- description: "Scheduled task ({$this->scheduledTask->name}) failed.",
+ description: "Scheduled task ({$this->task->name}) failed.",
color: DiscordMessage::errorColor(),
);
if ($this->url) {
- $discordMessage->addField('Scheduled task', '[Link]('.$this->url.')');
+ $message->addField('Scheduled task', '[Link]('.$this->url.')');
}
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
{
- $message = "Coolify: Scheduled task ({$this->scheduledTask->name}) failed with output: {$this->output}";
+ $message = "Coolify: Scheduled task ({$this->task->name}) failed with output: {$this->output}";
if ($this->url) {
$buttons[] = [
'text' => 'Open task in Coolify',
- 'url' => $this->url,
+ 'url' => (string) $this->url,
];
}
@@ -73,9 +73,9 @@ public function toTelegram(): array
public function toPushover(): PushoverMessage
{
- $message = "Scheduled task ({$this->scheduledTask->name}) failed
";
+ $message = "Scheduled task ({$this->task->name}) failed
";
- if ($this->output !== '' && $this->output !== '0') {
+ if ($this->output) {
$message .= "
Error Output:{$this->output}";
}
@@ -83,7 +83,7 @@ public function toPushover(): PushoverMessage
if ($this->url) {
$buttons[] = [
'text' => 'Open task in Coolify',
- 'url' => $this->url,
+ 'url' => (string) $this->url,
];
}
@@ -98,9 +98,9 @@ public function toPushover(): PushoverMessage
public function toSlack(): SlackMessage
{
$title = 'Scheduled task failed';
- $description = "Scheduled task ({$this->scheduledTask->name}) failed.";
+ $description = "Scheduled task ({$this->task->name}) failed.";
- if ($this->output !== '' && $this->output !== '0') {
+ if ($this->output) {
$description .= "\n\n**Error Output:**\n{$this->output}";
}
diff --git a/app/Notifications/ScheduledTask/TaskSuccess.php b/app/Notifications/ScheduledTask/TaskSuccess.php
index 4b55a389f0..5d4154e7ab 100644
--- a/app/Notifications/ScheduledTask/TaskSuccess.php
+++ b/app/Notifications/ScheduledTask/TaskSuccess.php
@@ -13,13 +13,13 @@ class TaskSuccess extends CustomEmailNotification
{
public ?string $url = null;
- public function __construct(public ScheduledTask $scheduledTask, public string $output)
+ public function __construct(public ScheduledTask $task, public string $output)
{
$this->onQueue('high');
- if ($scheduledTask->application) {
- $this->url = $scheduledTask->application->taskLink($scheduledTask->uuid);
- } elseif ($scheduledTask->service) {
- $this->url = $scheduledTask->service->taskLink($scheduledTask->uuid);
+ if ($task->application) {
+ $this->url = $task->application->taskLink($task->uuid);
+ } elseif ($task->service) {
+ $this->url = $task->service->taskLink($task->uuid);
}
}
@@ -30,39 +30,39 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: Scheduled task ({$this->scheduledTask->name}) succeeded.");
- $mailMessage->view('emails.scheduled-task-success', [
- 'task' => $this->scheduledTask,
+ $mail = new MailMessage;
+ $mail->subject("Coolify: Scheduled task ({$this->task->name}) succeeded.");
+ $mail->view('emails.scheduled-task-success', [
+ 'task' => $this->task,
'url' => $this->url,
'output' => $this->output,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':white_check_mark: Scheduled task succeeded',
- description: "Scheduled task ({$this->scheduledTask->name}) succeeded.",
+ description: "Scheduled task ({$this->task->name}) succeeded.",
color: DiscordMessage::successColor(),
);
if ($this->url) {
- $discordMessage->addField('Scheduled task', '[Link]('.$this->url.')');
+ $message->addField('Scheduled task', '[Link]('.$this->url.')');
}
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
{
- $message = "Coolify: Scheduled task ({$this->scheduledTask->name}) succeeded.";
+ $message = "Coolify: Scheduled task ({$this->task->name}) succeeded.";
if ($this->url) {
$buttons[] = [
'text' => 'Open task in Coolify',
- 'url' => $this->url,
+ 'url' => (string) $this->url,
];
}
@@ -73,12 +73,12 @@ public function toTelegram(): array
public function toPushover(): PushoverMessage
{
- $message = "Coolify: Scheduled task ({$this->scheduledTask->name}) succeeded.";
+ $message = "Coolify: Scheduled task ({$this->task->name}) succeeded.";
$buttons = [];
if ($this->url) {
$buttons[] = [
'text' => 'Open task in Coolify',
- 'url' => $this->url,
+ 'url' => (string) $this->url,
];
}
@@ -93,7 +93,7 @@ public function toPushover(): PushoverMessage
public function toSlack(): SlackMessage
{
$title = 'Scheduled task succeeded';
- $description = "Scheduled task ({$this->scheduledTask->name}) succeeded.";
+ $description = "Scheduled task ({$this->task->name}) succeeded.";
if ($this->url) {
$description .= "\n\n**Task URL:** {$this->url}";
diff --git a/app/Notifications/Server/DockerCleanupFailed.php b/app/Notifications/Server/DockerCleanupFailed.php
index ab6485dfce..0291eed19d 100644
--- a/app/Notifications/Server/DockerCleanupFailed.php
+++ b/app/Notifications/Server/DockerCleanupFailed.php
@@ -23,14 +23,14 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: [ACTION REQUIRED] Docker cleanup job failed on {$this->server->name}");
- $mailMessage->view('emails.docker-cleanup-failed', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: [ACTION REQUIRED] Docker cleanup job failed on {$this->server->name}");
+ $mail->view('emails.docker-cleanup-failed', [
'name' => $this->server->name,
'text' => $this->message,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
diff --git a/app/Notifications/Server/DockerCleanupSuccess.php b/app/Notifications/Server/DockerCleanupSuccess.php
index be0fb6dc68..1a652d1890 100644
--- a/app/Notifications/Server/DockerCleanupSuccess.php
+++ b/app/Notifications/Server/DockerCleanupSuccess.php
@@ -23,14 +23,14 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: Docker cleanup job succeeded on {$this->server->name}");
- $mailMessage->view('emails.docker-cleanup-success', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: Docker cleanup job succeeded on {$this->server->name}");
+ $mail->view('emails.docker-cleanup-success', [
'name' => $this->server->name,
'text' => $this->message,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
diff --git a/app/Notifications/Server/ForceDisabled.php b/app/Notifications/Server/ForceDisabled.php
index 3b1a1187b2..7a1f7bcbf7 100644
--- a/app/Notifications/Server/ForceDisabled.php
+++ b/app/Notifications/Server/ForceDisabled.php
@@ -23,26 +23,26 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: Server ({$this->server->name}) disabled because it is not paid!");
- $mailMessage->view('emails.server-force-disabled', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: Server ({$this->server->name}) disabled because it is not paid!");
+ $mail->view('emails.server-force-disabled', [
'name' => $this->server->name,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':cross_mark: Server disabled',
description: "Server ({$this->server->name}) disabled because it is not paid!",
color: DiscordMessage::errorColor(),
);
- $discordMessage->addField('Please update your subscription to enable the server again!', '[Link](https://app.coolify.io/subscriptions)');
+ $message->addField('Please update your subscription to enable the server again!', '[Link](https://app.coolify.io/subscriptions)');
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
diff --git a/app/Notifications/Server/ForceEnabled.php b/app/Notifications/Server/ForceEnabled.php
index dea66d3db0..36dad3c60f 100644
--- a/app/Notifications/Server/ForceEnabled.php
+++ b/app/Notifications/Server/ForceEnabled.php
@@ -23,13 +23,13 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: Server ({$this->server->name}) enabled again!");
- $mailMessage->view('emails.server-force-enabled', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: Server ({$this->server->name}) enabled again!");
+ $mail->view('emails.server-force-enabled', [
'name' => $this->server->name,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
diff --git a/app/Notifications/Server/HighDiskUsage.php b/app/Notifications/Server/HighDiskUsage.php
index 805c730eb1..4c9da12e35 100644
--- a/app/Notifications/Server/HighDiskUsage.php
+++ b/app/Notifications/Server/HighDiskUsage.php
@@ -23,32 +23,32 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: Server ({$this->server->name}) high disk usage detected!");
- $mailMessage->view('emails.high-disk-usage', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: Server ({$this->server->name}) high disk usage detected!");
+ $mail->view('emails.high-disk-usage', [
'name' => $this->server->name,
'disk_usage' => $this->disk_usage,
'threshold' => $this->server_disk_usage_notification_threshold,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':cross_mark: High disk usage detected',
description: "Server '{$this->server->name}' high disk usage detected!",
color: DiscordMessage::errorColor(),
isCritical: true,
);
- $discordMessage->addField('Disk usage', "{$this->disk_usage}%", true);
- $discordMessage->addField('Threshold', "{$this->server_disk_usage_notification_threshold}%", true);
- $discordMessage->addField('What to do?', '[Link](https://coolify.io/docs/knowledge-base/server/automated-cleanup)', true);
- $discordMessage->addField('Change Settings', '[Threshold]('.base_url().'/server/'.$this->server->uuid.'#advanced) | [Notification]('.base_url().'/notifications/discord)');
+ $message->addField('Disk usage', "{$this->disk_usage}%", true);
+ $message->addField('Threshold', "{$this->server_disk_usage_notification_threshold}%", true);
+ $message->addField('What to do?', '[Link](https://coolify.io/docs/knowledge-base/server/automated-cleanup)', true);
+ $message->addField('Change Settings', '[Threshold]('.base_url().'/server/'.$this->server->uuid.'#advanced) | [Notification]('.base_url().'/notifications/discord)');
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
diff --git a/app/Notifications/Server/Reachable.php b/app/Notifications/Server/Reachable.php
index 357d40823f..e03aef6b79 100644
--- a/app/Notifications/Server/Reachable.php
+++ b/app/Notifications/Server/Reachable.php
@@ -32,13 +32,13 @@ public function via(object $notifiable): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: Server ({$this->server->name}) revived.");
- $mailMessage->view('emails.server-revived', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: Server ({$this->server->name}) revived.");
+ $mail->view('emails.server-revived', [
'name' => $this->server->name,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
diff --git a/app/Notifications/Server/Unreachable.php b/app/Notifications/Server/Unreachable.php
index 2a2351c0be..fe90cc6105 100644
--- a/app/Notifications/Server/Unreachable.php
+++ b/app/Notifications/Server/Unreachable.php
@@ -32,26 +32,26 @@ public function via(object $notifiable): array
public function toMail(): ?MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject("Coolify: Your server ({$this->server->name}) is unreachable.");
- $mailMessage->view('emails.server-lost-connection', [
+ $mail = new MailMessage;
+ $mail->subject("Coolify: Your server ({$this->server->name}) is unreachable.");
+ $mail->view('emails.server-lost-connection', [
'name' => $this->server->name,
]);
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): ?DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':cross_mark: Server unreachable',
description: "Your server '{$this->server->name}' is unreachable.",
color: DiscordMessage::errorColor(),
);
- $discordMessage->addField('IMPORTANT', 'We automatically try to revive your server and turn on all automations & integrations.');
+ $message->addField('IMPORTANT', 'We automatically try to revive your server and turn on all automations & integrations.');
- return $discordMessage;
+ return $message;
}
public function toTelegram(): ?array
diff --git a/app/Notifications/Test.php b/app/Notifications/Test.php
index 91625ee6e7..ebb8735f53 100644
--- a/app/Notifications/Test.php
+++ b/app/Notifications/Test.php
@@ -30,7 +30,7 @@ public function __construct(public ?string $emails = null, public ?string $chann
public function via(object $notifiable): array
{
if ($this->channel) {
- return match ($this->channel) {
+ $channels = match ($this->channel) {
'email' => [EmailChannel::class],
'discord' => [DiscordChannel::class],
'telegram' => [TelegramChannel::class],
@@ -38,9 +38,11 @@ public function via(object $notifiable): array
'pushover' => [PushoverChannel::class],
default => [],
};
+ } else {
+ $channels = $notifiable->getEnabledChannels('test');
}
- return $notifiable->getEnabledChannels('test');
+ return $channels;
}
public function middleware(object $notifiable, string $channel)
@@ -53,24 +55,24 @@ public function middleware(object $notifiable, string $channel)
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject('Coolify: Test Email');
- $mailMessage->view('emails.test');
+ $mail = new MailMessage;
+ $mail->subject('Coolify: Test Email');
+ $mail->view('emails.test');
- return $mailMessage;
+ return $mail;
}
public function toDiscord(): DiscordMessage
{
- $discordMessage = new DiscordMessage(
+ $message = new DiscordMessage(
title: ':white_check_mark: Test Success',
description: 'This is a test Discord notification from Coolify. :cross_mark: :warning: :information_source:',
color: DiscordMessage::successColor(),
);
- $discordMessage->addField(name: 'Dashboard', value: '[Link]('.base_url().')', inline: true);
+ $message->addField(name: 'Dashboard', value: '[Link]('.base_url().')', inline: true);
- return $discordMessage;
+ return $message;
}
public function toTelegram(): array
diff --git a/app/Notifications/TransactionalEmails/InvitationLink.php b/app/Notifications/TransactionalEmails/InvitationLink.php
index 5bf143434a..30ace99dcb 100644
--- a/app/Notifications/TransactionalEmails/InvitationLink.php
+++ b/app/Notifications/TransactionalEmails/InvitationLink.php
@@ -24,16 +24,16 @@ public function __construct(public User $user)
public function toMail(): MailMessage
{
$invitation = TeamInvitation::whereEmail($this->user->email)->first();
- $invitation_team = Team::query()->find($invitation->team->id);
+ $invitation_team = Team::find($invitation->team->id);
- $mailMessage = new MailMessage;
- $mailMessage->subject('Coolify: Invitation for '.$invitation_team->name);
- $mailMessage->view('emails.invitation-link', [
+ $mail = new MailMessage;
+ $mail->subject('Coolify: Invitation for '.$invitation_team->name);
+ $mail->view('emails.invitation-link', [
'team' => $invitation_team->name,
'email' => $this->user->email,
'invitation_link' => $invitation->link,
]);
- return $mailMessage;
+ return $mail;
}
}
diff --git a/app/Notifications/TransactionalEmails/ResetPassword.php b/app/Notifications/TransactionalEmails/ResetPassword.php
index ffb66940ff..3938a8da79 100644
--- a/app/Notifications/TransactionalEmails/ResetPassword.php
+++ b/app/Notifications/TransactionalEmails/ResetPassword.php
@@ -3,7 +3,6 @@
namespace App\Notifications\TransactionalEmails;
use App\Models\InstanceSettings;
-use Exception;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
@@ -37,7 +36,7 @@ public function via($notifiable)
{
$type = set_transanctional_email_settings();
if (! $type) {
- throw new Exception('No email settings found.');
+ throw new \Exception('No email settings found.');
}
return ['mail'];
@@ -54,11 +53,11 @@ public function toMail($notifiable)
protected function buildMailMessage($url)
{
- $mailMessage = new MailMessage;
- $mailMessage->subject('Coolify: Reset Password');
- $mailMessage->view('emails.reset-password', ['url' => $url, 'count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]);
+ $mail = new MailMessage;
+ $mail->subject('Coolify: Reset Password');
+ $mail->view('emails.reset-password', ['url' => $url, 'count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]);
- return $mailMessage;
+ return $mail;
}
protected function resetUrl($notifiable)
diff --git a/app/Notifications/TransactionalEmails/Test.php b/app/Notifications/TransactionalEmails/Test.php
index 96b1c8be49..eeb32a2545 100644
--- a/app/Notifications/TransactionalEmails/Test.php
+++ b/app/Notifications/TransactionalEmails/Test.php
@@ -20,10 +20,10 @@ public function via(): array
public function toMail(): MailMessage
{
- $mailMessage = new MailMessage;
- $mailMessage->subject('Coolify: Test Email');
- $mailMessage->view('emails.test');
+ $mail = new MailMessage;
+ $mail->subject('Coolify: Test Email');
+ $mail->view('emails.test');
- return $mailMessage;
+ return $mail;
}
}
diff --git a/app/Policies/ApplicationPolicy.php b/app/Policies/ApplicationPolicy.php
index e7fed03b13..05fc289b8b 100644
--- a/app/Policies/ApplicationPolicy.php
+++ b/app/Policies/ApplicationPolicy.php
@@ -44,7 +44,11 @@ public function update(User $user, Application $application): bool
*/
public function delete(User $user, Application $application): bool
{
- return (bool) $user->isAdmin();
+ if ($user->isAdmin()) {
+ return true;
+ }
+
+ return false;
}
/**
diff --git a/app/Policies/ServicePolicy.php b/app/Policies/ServicePolicy.php
index 5a764a25c4..51a6d81168 100644
--- a/app/Policies/ServicePolicy.php
+++ b/app/Policies/ServicePolicy.php
@@ -44,7 +44,11 @@ public function update(User $user, Service $service): bool
*/
public function delete(User $user, Service $service): bool
{
- return (bool) $user->isAdmin();
+ if ($user->isAdmin()) {
+ return true;
+ }
+
+ return false;
}
/**
@@ -60,11 +64,19 @@ public function restore(User $user, Service $service): bool
*/
public function forceDelete(User $user, Service $service): bool
{
- return (bool) $user->isAdmin();
+ if ($user->isAdmin()) {
+ return true;
+ }
+
+ return false;
}
public function stop(User $user, Service $service): bool
{
- return (bool) $user->isAdmin();
+ if ($user->isAdmin()) {
+ return true;
+ }
+
+ return false;
}
}
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index d1b5b99b0b..2ce94201ca 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -8,32 +8,29 @@
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Laravel\Sanctum\Sanctum;
-use Laravel\Telescope\TelescopeServiceProvider;
-use SocialiteProviders\Authentik\Provider;
-use SocialiteProviders\Manager\SocialiteWasCalled;
class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
if ($this->app->environment('local')) {
- $this->app->register(TelescopeServiceProvider::class);
+ $this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class);
}
}
public function boot(): void
{
- Event::listen(function (SocialiteWasCalled $socialiteWasCalled) {
- $socialiteWasCalled->extendSocialite('authentik', Provider::class);
+ Event::listen(function (\SocialiteProviders\Manager\SocialiteWasCalled $event) {
+ $event->extendSocialite('authentik', \SocialiteProviders\Authentik\Provider::class);
});
Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);
Password::defaults(function () {
- $password = Password::min(8);
+ $rule = Password::min(8);
return $this->app->isProduction()
- ? $password->mixedCase()->letters()->numbers()->symbols()
- : $password;
+ ? $rule->mixedCase()->letters()->numbers()->symbols()
+ : $rule;
});
Http::macro('github', function (string $api_url, ?string $github_access_token = null) {
@@ -43,11 +40,11 @@ public function boot(): void
'Accept' => 'application/vnd.github.v3+json',
'Authorization' => "Bearer $github_access_token",
])->baseUrl($api_url);
+ } else {
+ return Http::withHeaders([
+ 'Accept' => 'application/vnd.github.v3+json',
+ ])->baseUrl($api_url);
}
-
- return Http::withHeaders([
- 'Accept' => 'application/vnd.github.v3+json',
- ])->baseUrl($api_url);
});
}
}
diff --git a/app/Providers/DuskServiceProvider.php b/app/Providers/DuskServiceProvider.php
index 02c06d4dc3..07e0e8709f 100644
--- a/app/Providers/DuskServiceProvider.php
+++ b/app/Providers/DuskServiceProvider.php
@@ -3,7 +3,6 @@
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
-use Laravel\Dusk\Browser;
class DuskServiceProvider extends ServiceProvider
{
@@ -12,7 +11,7 @@ class DuskServiceProvider extends ServiceProvider
*/
public function boot(): void
{
- Browser::macro('loginWithRootUser', function () {
+ \Laravel\Dusk\Browser::macro('loginWithRootUser', function () {
return $this->visit('/login')
->type('email', 'test@example.com')
->type('password', 'password')
diff --git a/app/Providers/FortifyServiceProvider.php b/app/Providers/FortifyServiceProvider.php
index 960d0794ee..ed27a158a1 100644
--- a/app/Providers/FortifyServiceProvider.php
+++ b/app/Providers/FortifyServiceProvider.php
@@ -8,7 +8,6 @@
use App\Actions\Fortify\UpdateUserProfileInformation;
use App\Models\OauthSetting;
use App\Models\User;
-use Illuminate\Auth\Events\Login;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
@@ -45,7 +44,7 @@ public function boot(): void
{
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::registerView(function () {
- $isFirstUser = User::query()->count() === 0;
+ $isFirstUser = User::count() === 0;
$settings = instanceSettings();
if (! $settings->is_registration_enabled) {
@@ -59,14 +58,14 @@ public function boot(): void
Fortify::loginView(function () {
$settings = instanceSettings();
- $enabled_oauth_providers = OauthSetting::query()->where('enabled', true)->get();
- $users = User::query()->count();
+ $enabled_oauth_providers = OauthSetting::where('enabled', true)->get();
+ $users = User::count();
if ($users == 0) {
// If there are no users, redirect to registration
return redirect()->route('register');
}
- return view(Login::class, [
+ return view('auth.login', [
'is_registration_enabled' => $settings->is_registration_enabled,
'enabled_oauth_providers' => $enabled_oauth_providers,
]);
@@ -74,7 +73,7 @@ public function boot(): void
Fortify::authenticateUsing(function (Request $request) {
$email = strtolower($request->email);
- $user = User::query()->where('email', $email)->with('teams')->first();
+ $user = User::where('email', $email)->with('teams')->first();
if (
$user &&
Hash::check($request->password, $user->password)
diff --git a/app/Providers/HorizonServiceProvider.php b/app/Providers/HorizonServiceProvider.php
index 55f949ae34..2e2b79a597 100644
--- a/app/Providers/HorizonServiceProvider.php
+++ b/app/Providers/HorizonServiceProvider.php
@@ -31,9 +31,11 @@ public function boot(): void
protected function gate(): void
{
Gate::define('viewHorizon', function ($user) {
- $root_user = User::query()->find(0);
+ $root_user = User::find(0);
- return $user->email == $root_user->email;
+ return in_array($user->email, [
+ $root_user->email,
+ ]);
});
}
}
diff --git a/app/Providers/TelescopeServiceProvider.php b/app/Providers/TelescopeServiceProvider.php
index 1e185251e5..b7a3366314 100644
--- a/app/Providers/TelescopeServiceProvider.php
+++ b/app/Providers/TelescopeServiceProvider.php
@@ -21,24 +21,13 @@ public function register(): void
$isLocal = $this->app->environment('local');
- Telescope::filter(function (IncomingEntry $incomingEntry) use ($isLocal) {
- if ($isLocal) {
- return true;
- }
- if ($incomingEntry->isReportableException()) {
- return true;
- }
- if ($incomingEntry->isFailedRequest()) {
- return true;
- }
- if ($incomingEntry->isFailedJob()) {
- return true;
- }
- if ($incomingEntry->isScheduledTask()) {
- return true;
- }
-
- return $incomingEntry->hasMonitoredTag();
+ Telescope::filter(function (IncomingEntry $entry) use ($isLocal) {
+ return $isLocal ||
+ $entry->isReportableException() ||
+ $entry->isFailedRequest() ||
+ $entry->isFailedJob() ||
+ $entry->isScheduledTask() ||
+ $entry->hasMonitoredTag();
});
}
@@ -68,9 +57,11 @@ protected function hideSensitiveRequestDetails(): void
protected function gate(): void
{
Gate::define('viewTelescope', function ($user) {
- $root_user = User::query()->find(0);
+ $root_user = User::find(0);
- return $user->email == $root_user->email;
+ return in_array($user->email, [
+ $root_user->email,
+ ]);
});
}
}
diff --git a/app/Traits/ExecuteRemoteCommand.php b/app/Traits/ExecuteRemoteCommand.php
index 5b5f6c37a4..f8ccee9db7 100644
--- a/app/Traits/ExecuteRemoteCommand.php
+++ b/app/Traits/ExecuteRemoteCommand.php
@@ -8,7 +8,6 @@
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Process;
-use RuntimeException;
trait ExecuteRemoteCommand
{
@@ -19,14 +18,18 @@ trait ExecuteRemoteCommand
public function execute_remote_command(...$commands)
{
static::$batch_counter++;
- $commandsText = $commands instanceof Collection ? $commands : collect($commands);
+ if ($commands instanceof Collection) {
+ $commandsText = $commands;
+ } else {
+ $commandsText = collect($commands);
+ }
if ($this->server instanceof Server === false) {
- throw new RuntimeException('Server is not set or is not an instance of Server model');
+ throw new \RuntimeException('Server is not set or is not an instance of Server model');
}
$commandsText->each(function ($single_command) {
- $command = data_get($single_command, 'command', $single_command[0] ?? null);
+ $command = data_get($single_command, 'command') ?? $single_command[0] ?? null;
if ($command === null) {
- throw new RuntimeException('Command is not set');
+ throw new \RuntimeException('Command is not set');
}
$hidden = data_get($single_command, 'hidden', false);
$customType = data_get($single_command, 'type');
@@ -41,7 +44,7 @@ public function execute_remote_command(...$commands)
}
}
$remote_command = SshMultiplexingHelper::generateSshCommand($this->server, $command);
- $invokedProcess = Process::timeout(3600)->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) {
+ $process = Process::timeout(3600)->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) {
$output = str($output)->trim();
if ($output->startsWith('╔')) {
$output = "\n".$output;
@@ -77,14 +80,16 @@ public function execute_remote_command(...$commands)
}
});
$this->application_deployment_queue->update([
- 'current_process_id' => $invokedProcess->id(),
+ 'current_process_id' => $process->id(),
]);
- $processResult = $invokedProcess->wait();
- if ($processResult->exitCode() !== 0 && ! $ignore_errors) {
- $this->application_deployment_queue->status = ApplicationDeploymentStatus::FAILED->value;
- $this->application_deployment_queue->save();
- throw new RuntimeException($processResult->errorOutput());
+ $process_result = $process->wait();
+ if ($process_result->exitCode() !== 0) {
+ if (! $ignore_errors) {
+ $this->application_deployment_queue->status = ApplicationDeploymentStatus::FAILED->value;
+ $this->application_deployment_queue->save();
+ throw new \RuntimeException($process_result->errorOutput());
+ }
}
});
}
diff --git a/app/Traits/SaveFromRedirect.php b/app/Traits/SaveFromRedirect.php
index 189e08d253..166c16a4bc 100644
--- a/app/Traits/SaveFromRedirect.php
+++ b/app/Traits/SaveFromRedirect.php
@@ -6,19 +6,19 @@
trait SaveFromRedirect
{
- public function saveFromRedirect(string $route, ?Collection $collection = null)
+ public function saveFromRedirect(string $route, ?Collection $parameters = null)
{
session()->forget('from');
- if (! $collection || $collection->count() === 0) {
- $collection = $this->parameters;
+ if (! $parameters || $parameters->count() === 0) {
+ $parameters = $this->parameters;
}
- $collection = collect($collection) ?? collect([]);
+ $parameters = collect($parameters) ?? collect([]);
$queries = collect($this->query) ?? collect([]);
- $collection = $collection->merge($queries);
+ $parameters = $parameters->merge($queries);
session(['from' => [
'back' => $this->currentRoute,
'route' => $route,
- 'parameters' => $collection,
+ 'parameters' => $parameters,
]]);
return redirect()->route($route);
diff --git a/app/View/Components/Forms/Input.php b/app/View/Components/Forms/Input.php
index e08459e89f..7283ef20f8 100644
--- a/app/View/Components/Forms/Input.php
+++ b/app/View/Components/Forms/Input.php
@@ -36,7 +36,7 @@ public function render(): View|Closure|string
$this->name = $this->id;
}
if ($this->type === 'password') {
- $this->defaultClass .= ' pr-[2.8rem]';
+ $this->defaultClass = $this->defaultClass.' pr-[2.8rem]';
}
// $this->label = Str::title($this->label);
diff --git a/app/View/Components/Services/Links.php b/app/View/Components/Services/Links.php
index c14832b451..0497aebae2 100644
--- a/app/View/Components/Services/Links.php
+++ b/app/View/Components/Services/Links.php
@@ -33,7 +33,11 @@ public function __construct(public Service $service)
if ($application->ports) {
$portsCollection = collect(str($application->ports)->explode(','));
$portsCollection->map(function ($port) {
- $hostPort = str($port)->contains(':') ? str($port)->before(':') : $port;
+ if (str($port)->contains(':')) {
+ $hostPort = str($port)->before(':');
+ } else {
+ $hostPort = $port;
+ }
$this->links->push(base_url(withPort: false).":{$hostPort}");
});
}
diff --git a/config/app.php b/config/app.php
index a8b28a6c87..371ac44ecc 100644
--- a/config/app.php
+++ b/config/app.php
@@ -1,34 +1,6 @@
[
'users' => [
'driver' => 'eloquent',
- 'model' => User::class,
+ 'model' => App\Models\User::class,
],
// 'users' => [
diff --git a/config/sanctum.php b/config/sanctum.php
index 5dfd3f266a..f1e5fc0e51 100644
--- a/config/sanctum.php
+++ b/config/sanctum.php
@@ -1,8 +1,5 @@
[
- 'authenticate_session' => AuthenticateSession::class,
- 'encrypt_cookies' => EncryptCookies::class,
- 'validate_csrf_token' => ValidateCsrfToken::class,
+ 'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
+ 'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
+ 'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],
];
diff --git a/config/telescope.php b/config/telescope.php
index 85589ee755..c940bec8a8 100644
--- a/config/telescope.php
+++ b/config/telescope.php
@@ -1,24 +1,7 @@
[
- BatchWatcher::class => env('TELESCOPE_BATCH_WATCHER', true),
+ Watchers\BatchWatcher::class => env('TELESCOPE_BATCH_WATCHER', true),
- CacheWatcher::class => [
+ Watchers\CacheWatcher::class => [
'enabled' => env('TELESCOPE_CACHE_WATCHER', true),
'hidden' => [],
],
- ClientRequestWatcher::class => env('TELESCOPE_CLIENT_REQUEST_WATCHER', true),
+ Watchers\ClientRequestWatcher::class => env('TELESCOPE_CLIENT_REQUEST_WATCHER', true),
- CommandWatcher::class => [
+ Watchers\CommandWatcher::class => [
'enabled' => env('TELESCOPE_COMMAND_WATCHER', true),
'ignore' => [],
],
- DumpWatcher::class => [
+ Watchers\DumpWatcher::class => [
'enabled' => env('TELESCOPE_DUMP_WATCHER', true),
'always' => env('TELESCOPE_DUMP_WATCHER_ALWAYS', false),
],
- EventWatcher::class => [
+ Watchers\EventWatcher::class => [
'enabled' => env('TELESCOPE_EVENT_WATCHER', true),
'ignore' => [],
],
- ExceptionWatcher::class => env('TELESCOPE_EXCEPTION_WATCHER', true),
+ Watchers\ExceptionWatcher::class => env('TELESCOPE_EXCEPTION_WATCHER', true),
- GateWatcher::class => [
+ Watchers\GateWatcher::class => [
'enabled' => env('TELESCOPE_GATE_WATCHER', true),
'ignore_abilities' => [],
'ignore_packages' => true,
'ignore_paths' => [],
],
- JobWatcher::class => env('TELESCOPE_JOB_WATCHER', true),
+ Watchers\JobWatcher::class => env('TELESCOPE_JOB_WATCHER', true),
- LogWatcher::class => [
+ Watchers\LogWatcher::class => [
'enabled' => env('TELESCOPE_LOG_WATCHER', true),
'level' => 'error',
],
- MailWatcher::class => env('TELESCOPE_MAIL_WATCHER', true),
+ Watchers\MailWatcher::class => env('TELESCOPE_MAIL_WATCHER', true),
- ModelWatcher::class => [
+ Watchers\ModelWatcher::class => [
'enabled' => env('TELESCOPE_MODEL_WATCHER', true),
'events' => ['eloquent.*'],
'hydrations' => true,
],
- NotificationWatcher::class => env('TELESCOPE_NOTIFICATION_WATCHER', true),
+ Watchers\NotificationWatcher::class => env('TELESCOPE_NOTIFICATION_WATCHER', true),
- QueryWatcher::class => [
+ Watchers\QueryWatcher::class => [
'enabled' => env('TELESCOPE_QUERY_WATCHER', true),
'ignore_packages' => true,
'ignore_paths' => [],
'slow' => 100,
],
- RedisWatcher::class => env('TELESCOPE_REDIS_WATCHER', true),
+ Watchers\RedisWatcher::class => env('TELESCOPE_REDIS_WATCHER', true),
- RequestWatcher::class => [
+ Watchers\RequestWatcher::class => [
'enabled' => env('TELESCOPE_REQUEST_WATCHER', true),
'size_limit' => env('TELESCOPE_RESPONSE_SIZE_LIMIT', 64),
'ignore_http_methods' => [],
'ignore_status_codes' => [],
],
- ScheduleWatcher::class => env('TELESCOPE_SCHEDULE_WATCHER', true),
- ViewWatcher::class => env('TELESCOPE_VIEW_WATCHER', true),
+ Watchers\ScheduleWatcher::class => env('TELESCOPE_SCHEDULE_WATCHER', true),
+ Watchers\ViewWatcher::class => env('TELESCOPE_VIEW_WATCHER', true),
],
];
diff --git a/rector.php b/rector.php
index 94e1a99f3f..cffbb9f536 100644
--- a/rector.php
+++ b/rector.php
@@ -11,6 +11,7 @@
__DIR__.'/app',
__DIR__.'/routes',
__DIR__.'/config',
+
])
->withSets([
LaravelLevelSetList::UP_TO_LARAVEL_110,
@@ -23,13 +24,11 @@
->withRules([
TypedPropertyFromStrictConstructorRector::class,
])
- ->withImportNames(
- removeUnusedImports: true,
- )
->withPreparedSets(
deadCode: true,
codeQuality: true,
naming: true,
privatization: true,
earlyReturn: true,
+
);
diff --git a/routes/api.php b/routes/api.php
index 84722c61b3..c3f7a8f269 100644
--- a/routes/api.php
+++ b/routes/api.php
@@ -141,7 +141,7 @@
$decrypted = decrypt($naked_token);
$decrypted_token = json_decode($decrypted, true);
$server_uuid = data_get($decrypted_token, 'server_uuid');
- $server = Server::query()->where('uuid', $server_uuid)->first();
+ $server = Server::where('uuid', $server_uuid)->first();
if (! $server) {
return response()->json(['message' => 'Server not found'], 404);
}
diff --git a/routes/channels.php b/routes/channels.php
index 72a8c2c9a0..f75c30d0f1 100644
--- a/routes/channels.php
+++ b/routes/channels.php
@@ -16,9 +16,17 @@
use Illuminate\Support\Facades\Broadcast;
Broadcast::channel('team.{teamId}', function (User $user, int $teamId) {
- return (bool) $user->teams->pluck('id')->contains($teamId);
+ if ($user->teams->pluck('id')->contains($teamId)) {
+ return true;
+ }
+
+ return false;
});
Broadcast::channel('user.{userId}', function (User $user) {
- return $user->id === Auth::id();
+ if ($user->id === Auth::id()) {
+ return true;
+ }
+
+ return false;
});
diff --git a/routes/web.php b/routes/web.php
index 0050796b69..ec49239415 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -72,7 +72,6 @@
use App\Livewire\Terminal\Index as TerminalIndex;
use App\Models\GitlabApp;
use App\Models\ScheduledDatabaseBackupExecution;
-use App\Models\ServiceDatabase;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
@@ -296,7 +295,7 @@
return response()->json(['message' => 'Team not found.'], 404);
}
$exeuctionId = request()->route('executionId');
- $execution = ScheduledDatabaseBackupExecution::query()->where('id', $exeuctionId)->firstOrFail();
+ $execution = ScheduledDatabaseBackupExecution::where('id', $exeuctionId)->firstOrFail();
$execution_team_id = $execution->scheduledDatabaseBackup->database->team()?->id;
if ($team->id !== 0) {
if (is_null($execution_team_id)) {
@@ -310,7 +309,7 @@
}
}
$filename = data_get($execution, 'filename');
- if ($execution->scheduledDatabaseBackup->database->getMorphClass() === ServiceDatabase::class) {
+ if ($execution->scheduledDatabaseBackup->database->getMorphClass() === \App\Models\ServiceDatabase::class) {
$server = $execution->scheduledDatabaseBackup->database->service->destination->server;
} else {
$server = $execution->scheduledDatabaseBackup->database->destination->server;
@@ -330,7 +329,7 @@
}
return new StreamedResponse(function () use ($disk, $filename) {
- if (ob_get_level() !== 0) {
+ if (ob_get_level()) {
ob_end_clean();
}
$stream = $disk->readStream($filename);
@@ -347,7 +346,7 @@
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment; filename="'.basename($filename).'"',
]);
- } catch (Throwable $e) {
+ } catch (\Throwable $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
})->name('download.backup');