adrema/app/Mailgateway/Actions/StoreAction.php

77 lines
2.1 KiB
PHP
Raw Normal View History

2023-06-01 15:45:02 +02:00
<?php
namespace App\Mailgateway\Actions;
use App\Mailgateway\Models\Mailgateway;
2023-06-07 22:52:02 +02:00
use App\Mailgateway\Types\Type;
2023-06-01 15:45:02 +02:00
use Illuminate\Validation\Rule;
2023-06-01 17:19:24 +02:00
use Illuminate\Validation\ValidationException;
2023-06-01 15:45:02 +02:00
use Lorisleiva\Actions\ActionRequest;
use Lorisleiva\Actions\Concerns\AsAction;
class StoreAction
{
use AsAction;
2023-06-07 22:52:02 +02:00
/**
* @param array<string, mixed> $input
*/
public function handle(array $input): void
2023-06-01 15:45:02 +02:00
{
2023-06-07 22:52:02 +02:00
if (!app($input['type']['cls'])->setParams($input['type']['params'])->works()) {
throw ValidationException::withMessages(['connection' => 'Verbindung fehlgeschlagen.']);
2023-06-01 17:19:24 +02:00
}
2023-06-01 15:45:02 +02:00
Mailgateway::create($input);
}
2023-06-07 22:52:02 +02:00
/**
* @return array<string, mixed>
*/
2023-06-01 15:45:02 +02:00
public function rules(): array
{
return [
'name' => 'required|string|max:255',
'domain' => 'required|string|max:255',
2023-06-07 22:52:02 +02:00
...$this->typeValidation(),
2023-06-07 21:39:57 +02:00
'type.params' => 'present|array',
2023-06-01 17:19:24 +02:00
...collect(request()->input('type.cls')::rules('storeValidator'))->mapWithKeys(fn ($rules, $key) => ["type.params.{$key}" => $rules]),
2023-06-01 15:45:02 +02:00
];
}
2023-06-07 22:52:02 +02:00
/**
* @return array<string, mixed>
*/
public function getValidationAttributes(): array
{
return [
'type.cls' => 'Typ',
'name' => 'Beschreibung',
'domain' => 'Domain',
...collect(request()->input('type.cls')::fieldNames())->mapWithKeys(fn ($attribute, $key) => ["type.params.{$key}" => $attribute]),
];
}
/**
* @return array<string, mixed>
*/
private function typeValidation(): array
{
return [
'type.cls' => ['required', 'string', 'max:255', Rule::in(app('mail-gateways'))],
];
}
public function prepareForValidation(ActionRequest $request): void
{
if (!is_subclass_of(request()->input('type.cls'), Type::class)) {
throw ValidationException::withMessages(['type.cls' => 'Typ ist nicht valide.']);
}
}
2023-06-01 15:45:02 +02:00
public function asController(ActionRequest $request): void
{
$this->handle($request->validated());
}
}