Skip to content

Commit

Permalink
Merge pull request #637 from pelican-dev/lance/enforce-di
Browse files Browse the repository at this point in the history
Enforce Dependency Injection
  • Loading branch information
lancepioch authored Oct 20, 2024
2 parents 465a372 + 54ea55d commit 2be8168
Show file tree
Hide file tree
Showing 25 changed files with 128 additions and 69 deletions.
5 changes: 1 addition & 4 deletions app/Console/Commands/Egg/CheckEggUpdatesCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,8 @@ class CheckEggUpdatesCommand extends Command
{
protected $signature = 'p:egg:check-updates';

public function handle(): void
public function handle(EggExporterService $exporterService): void
{
/** @var EggExporterService $exporterService */
$exporterService = app(EggExporterService::class);

$eggs = Egg::all();
foreach ($eggs as $egg) {
try {
Expand Down
1 change: 1 addition & 0 deletions app/Exceptions/DisplayException.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ public function render(Request $request)
return response()->json(Handler::toArray($this), $this->getStatusCode(), $this->getHeaders());
}

// @phpstan-ignore-next-line
app(AlertsMessageBag::class)->danger($this->getMessage())->flash();

return redirect()->back()->withInput();
Expand Down
1 change: 1 addition & 0 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ protected function extractPrevious(\Throwable $e): array
*/
public static function toArray(\Throwable $e): array
{
// @phpstan-ignore-next-line
return (new self(app()))->convertExceptionToArray($e);
}
}
18 changes: 11 additions & 7 deletions app/Filament/Pages/Dashboard.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,20 @@ public function getTitle(): string

public string $activeTab = 'nodes';

public function getViewData(): array
private SoftwareVersionService $softwareVersionService;

public function mount(SoftwareVersionService $softwareVersionService): void
{
/** @var SoftwareVersionService $softwareVersionService */
$softwareVersionService = app(SoftwareVersionService::class);
$this->softwareVersionService = $softwareVersionService;
}

public function getViewData(): array
{
return [
'inDevelopment' => config('app.version') === 'canary',
'version' => $softwareVersionService->versionData()['version'],
'latestVersion' => $softwareVersionService->getPanel(),
'isLatest' => $softwareVersionService->isLatestPanel(),
'version' => $this->softwareVersionService->versionData()['version'],
'latestVersion' => $this->softwareVersionService->getPanel(),
'isLatest' => $this->softwareVersionService->isLatestPanel(),
'eggsCount' => Egg::query()->count(),
'nodesList' => ListNodes::getUrl(),
'nodesCount' => Node::query()->count(),
Expand Down Expand Up @@ -67,7 +71,7 @@ public function getViewData(): array
CreateAction::make()
->label(trans('dashboard/index.sections.intro-support.button_donate'))
->icon('tabler-cash')
->url($softwareVersionService->getDonations(), true)
->url($this->softwareVersionService->getDonations(), true)
->color('success'),
],
'helpActions' => [
Expand Down
4 changes: 2 additions & 2 deletions app/Filament/Pages/Installer/PanelInstaller.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,12 +159,12 @@ public function runMigrations(string $driver): void
}
}

public function createAdminUser(): void
public function createAdminUser(UserCreationService $userCreationService): void
{
try {
$userData = array_get($this->data, 'user');
$userData['root_admin'] = true;
$this->user = app(UserCreationService::class)->handle($userData);
$this->user = $userCreationService->handle($userData);
} catch (Exception $exception) {
report($exception);

Expand Down
3 changes: 2 additions & 1 deletion app/Filament/Pages/Installer/Steps/AdminUserStep.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Filament\Pages\Installer\Steps;

use App\Filament\Pages\Installer\PanelInstaller;
use App\Services\Users\UserCreationService;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Wizard\Step;

Expand All @@ -28,6 +29,6 @@ public static function make(PanelInstaller $installer): Step
->password()
->revealable(),
])
->afterValidation(fn () => $installer->createAdminUser());
->afterValidation(fn (UserCreationService $service) => $installer->createAdminUser($service));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

class CreateDatabaseHost extends CreateRecord
{
private HostCreationService $service;

protected static string $resource = DatabaseHostResource::class;

protected ?string $heading = 'Database Hosts';
Expand All @@ -24,6 +26,11 @@ class CreateDatabaseHost extends CreateRecord

protected ?string $subheading = '(database servers that can have individual databases)';

public function boot(HostCreationService $service)
{
$this->service = $service;
}

public function form(Form $form): Form
{
return $form
Expand Down Expand Up @@ -94,7 +101,7 @@ protected function getFormActions(): array

protected function handleRecordCreation(array $data): Model
{
return resolve(HostCreationService::class)->handle($data);
return $this->service->handle($data);
}

public function exception($e, $stopPropagation): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ class EditDatabaseHost extends EditRecord
{
protected static string $resource = DatabaseHostResource::class;

private HostUpdateService $hostUpdateService;

public function boot(HostUpdateService $hostUpdateService)
{
$this->hostUpdateService = $hostUpdateService;
}

public function form(Form $form): Form
{
return $form
Expand Down Expand Up @@ -99,7 +106,7 @@ public function getRelationManagers(): array

protected function handleRecordUpdate($record, array $data): Model
{
return resolve(HostUpdateService::class)->handle($record->id, $data);
return $this->hostUpdateService->handle($record->id, $data);
}

public function exception($e, $stopPropagation): void
Expand Down
5 changes: 1 addition & 4 deletions app/Filament/Resources/EggResource/Pages/EditEgg.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,10 +280,7 @@ protected function getHeaderActions(): array
->contained(false),

])
->action(function (array $data, Egg $egg): void {
/** @var EggImporterService $eggImportService */
$eggImportService = resolve(EggImporterService::class);

->action(function (array $data, Egg $egg, EggImporterService $eggImportService): void {
if (!empty($data['egg'])) {
try {
$eggImportService->fromFile($data['egg'], $egg);
Expand Down
10 changes: 4 additions & 6 deletions app/Filament/Resources/EggResource/Pages/ListEggs.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,10 @@ public function table(Table $table): Table
->modalDescription('If you made any changes to the egg they will be overwritten!')
->modalIconColor('danger')
->modalSubmitAction(fn (Actions\StaticAction $action) => $action->color('danger'))
->action(function (Egg $egg) {
->action(function (Egg $egg, EggImporterService $eggImporterService) {
try {
app(EggImporterService::class)->fromUrl($egg->update_url, $egg);
$eggImporterService->fromUrl($egg->update_url, $egg);

cache()->forget("eggs.{$egg->uuid}.update");
} catch (Exception $exception) {
Notification::make()
Expand Down Expand Up @@ -129,10 +130,7 @@ protected function getHeaderActions(): array
->contained(false),

])
->action(function (array $data): void {
/** @var EggImporterService $eggImportService */
$eggImportService = resolve(EggImporterService::class);

->action(function (array $data, EggImporterService $eggImportService): void {
if (!empty($data['egg'])) {
/** @var TemporaryUploadedFile[] $eggFile */
$eggFile = $data['egg'];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public function table(Table $table): Table
->splitKeys(['Tab', ' ', ','])
->required(),
])
->action(fn (array $data) => resolve(AssignmentService::class)->handle($this->getOwnerRecord(), $data)),
->action(fn (array $data, AssignmentService $service) => $service->handle($this->getOwnerRecord(), $data)),
])
->bulkActions([
BulkActionGroup::make([
Expand Down
21 changes: 13 additions & 8 deletions app/Filament/Resources/ServerResource/Pages/CreateServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ class CreateServer extends CreateRecord

public ?Node $node = null;

private ServerCreationService $serverCreationService;

public function boot(ServerCreationService $serverCreationService)
{
$this->serverCreationService = $serverCreationService;
}

public function form(Form $form): Form
{
return $form
Expand Down Expand Up @@ -118,8 +125,9 @@ public function form(Form $form): Form
->hintIconTooltip('Providing a user password is optional. New user email will prompt users to create a password the first time they login.')
->password(),
])
->createOptionUsing(function ($data) {
resolve(UserCreationService::class)->handle($data);
->createOptionUsing(function ($data, UserCreationService $service) {
$service->handle($data);

$this->refreshForm();
})
->required(),
Expand Down Expand Up @@ -262,9 +270,9 @@ public function form(Form $form): Form
->splitKeys(['Tab', ' ', ','])
->required(),
])
->createOptionUsing(function (array $data, Get $get): int {
->createOptionUsing(function (array $data, Get $get, AssignmentService $assignmentService): int {
return collect(
resolve(AssignmentService::class)->handle(Node::find($get('node_id')), $data)
$assignmentService->handle(Node::find($get('node_id')), $data)
)->first();
})
->required(),
Expand Down Expand Up @@ -825,10 +833,7 @@ protected function handleRecordCreation(array $data): Model
{
$data['allocation_additional'] = collect($data['allocation_additional'])->filter()->all();

/** @var ServerCreationService $service */
$service = resolve(ServerCreationService::class);

return $service->handle($data);
return $this->serverCreationService->handle($data);
}

private function shouldHideComponent(Get $get, Component $component): bool
Expand Down
4 changes: 2 additions & 2 deletions app/Filament/Resources/ServerResource/Pages/EditServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -749,8 +749,8 @@ protected function getHeaderActions(): array
->color('danger')
->label('Delete')
->requiresConfirmation()
->action(function (Server $server) {
resolve(ServerDeletionService::class)->handle($server);
->action(function (Server $server, ServerDeletionService $service) {
$service->handle($server);

return redirect(ListServers::getUrl());
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public function table(Table $table): Table
->splitKeys(['Tab', ' ', ','])
->required(),
])
->action(fn (array $data) => resolve(AssignmentService::class)->handle($this->getOwnerRecord()->node, $data, $this->getOwnerRecord())),
->action(fn (array $data, AssignmentService $service) => $service->handle($this->getOwnerRecord()->node, $data, $this->getOwnerRecord())),
AssociateAction::make()
->multiple()
->associateAnother(false)
Expand Down
21 changes: 10 additions & 11 deletions app/Filament/Resources/UserResource/Pages/EditProfile.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@
*/
class EditProfile extends \Filament\Pages\Auth\EditProfile
{
private ToggleTwoFactorService $toggleTwoFactorService;

public function boot(ToggleTwoFactorService $toggleTwoFactorService): void
{
$this->toggleTwoFactorService = $toggleTwoFactorService;
}

protected function getForms(): array
{
return [
Expand Down Expand Up @@ -106,7 +113,7 @@ protected function getForms(): array

Tab::make('2FA')
->icon('tabler-shield-lock')
->schema(function () {
->schema(function (TwoFactorSetupService $setupService) {
if ($this->getUser()->use_totp) {
return [
Placeholder::make('2fa-already-enabled')
Expand All @@ -124,8 +131,6 @@ protected function getForms(): array
->helperText('Enter your current 2FA code to disable Two Factor Authentication'),
];
}
/** @var TwoFactorSetupService */
$setupService = app(TwoFactorSetupService::class);

['image_url_data' => $url, 'secret' => $secret] = cache()->remember(
"users.{$this->getUser()->id}.2fa.state",
Expand Down Expand Up @@ -277,20 +282,14 @@ protected function getForms(): array
protected function handleRecordUpdate($record, $data): Model
{
if ($token = $data['2facode'] ?? null) {
/** @var ToggleTwoFactorService $service */
$service = resolve(ToggleTwoFactorService::class);

$tokens = $service->handle($record, $token, true);
$tokens = $this->toggleTwoFactorService->handle($record, $token, true);
cache()->set("users.$record->id.2fa.tokens", implode("\n", $tokens), now()->addSeconds(15));

$this->redirectRoute('filament.admin.auth.profile', ['tab' => '-2fa-tab']);
}

if ($token = $data['2fa-disable-code'] ?? null) {
/** @var ToggleTwoFactorService $service */
$service = resolve(ToggleTwoFactorService::class);

$service->handle($record, $token, false);
$this->toggleTwoFactorService->handle($record, $token, false);

cache()->forget("users.$record->id.2fa.state");
}
Expand Down
4 changes: 1 addition & 3 deletions app/Filament/Resources/UserResource/Pages/ListUsers.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,11 @@ protected function getHeaderActions(): array
]),
])
->successRedirectUrl(route('filament.admin.resources.users.index'))
->action(function (array $data) {
->action(function (array $data, UserCreationService $creationService) {
$roles = $data['roles'];
$roles = collect($roles)->map(fn ($role) => Role::findById($role));
unset($data['roles']);

/** @var UserCreationService $creationService */
$creationService = resolve(UserCreationService::class);
$user = $creationService->handle($data);

$user->syncRoles($roles);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,18 @@ public function table(Table $table): Table
)
->label('Suspend All Servers')
->color('warning')
->action(function () use ($user) {
->action(function (SuspensionService $suspensionService) use ($user) {
foreach ($user->servers()->whereNot('status', ServerState::Suspended)->get() as $server) {
resolve(SuspensionService::class)->toggle($server);
$suspensionService->toggle($server);
}
}),
Actions\Action::make('toggleUnsuspend')
->hidden(fn () => $user->servers()->where('status', ServerState::Suspended)->count() === 0)
->label('Unsuspend All Servers')
->color('primary')
->action(function () use ($user) {
->action(function (SuspensionService $suspensionService) use ($user) {
foreach ($user->servers()->where('status', ServerState::Suspended)->get() as $server) {
resolve(SuspensionService::class)->toggle($server, SuspensionService::ACTION_UNSUSPEND);
$suspensionService->toggle($server, SuspensionService::ACTION_UNSUSPEND);
}
}),
])
Expand Down
13 changes: 8 additions & 5 deletions app/Http/Middleware/VerifyReCaptcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,26 @@
namespace App\Http\Middleware;

use GuzzleHttp\Client;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Events\Auth\FailedCaptcha;
use Symfony\Component\HttpKernel\Exception\HttpException;

class VerifyReCaptcha
readonly class VerifyReCaptcha
{
/**
* Handle an incoming request.
*/
public function __construct(private Application $app)
{

}

public function handle(Request $request, \Closure $next): mixed
{
if (!config('recaptcha.enabled')) {
return $next($request);
}

if (app()->isLocal()) {
if ($this->app->isLocal()) {
return $next($request);
}

Expand Down
1 change: 1 addition & 0 deletions app/Models/Node.php
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ public function systemInformation(): array
{
return once(function () {
try {
// @phpstan-ignore-next-line
return resolve(DaemonConfigurationRepository::class)
->setNode($this)
->getSystemInformation(connectTimeout: 3);
Expand Down
Loading

0 comments on commit 2be8168

Please sign in to comment.