ldc-gen-game-web/app/Http/Controllers/Bo/SettingsController.php
2026-10-20 12:27:49 +02:00

102 lines
3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Bo;
use App\Http\Controllers\Controller;
use App\Http\Requests\Bo\Settings\UpdateSettingsRequest;
use App\Lib\Discount;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\Settings;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use RuntimeException;
use TypeError;
class SettingsController extends Controller
{
/**
* Create the controller instance.
*/
public function __construct()
{
$this->authorizeResource(Settings::class);
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Settings $settings): View
{
/** @var view-string $view */
$view = 'back::pages.settings.edit';
return view($view, [
'settingsModel' => $settings,
]);
}
/**
* Update the specified resource in storage.
*/
public function update(UpdateSettingsRequest $request, Settings $settings): RedirectResponse
{
return DB::transaction(function () use ($request, $settings) {
$data = $request->validated();
// * Assign parsed Web coupon objects
Arr::set($data, 'web_coupons', collect(Arr::get($data, 'web_coupons'))->filter()
->map(fn (array $coupon): ?\App\Lib\Discount => $this->parseWebCoupon($coupon))
->filter()->all());
$settings->fill($data);
if ($settings->saveOrFail()) {
return to_route('bo.settings.edit', $settings)
->with('success', trans(
'crud.messages.has_been_updated',
['model' => Str::singular(__('models.classes.settings'))]
));
}
return back()
->with('error', trans(
'crud.messages.cannot_be_updated',
['model' => Str::singular(__('models.classes.settings'))]
));
});
}
/**
* Try to parse webCoupon
*
* @param array<string,string> $coupon
*/
private function parseWebCoupon(array $coupon): ?Discount
{
/** @var UploadedFile|string */
$picture = Arr::get($coupon, 'picture');
if ($picture instanceof UploadedFile) {
$picture = FileStorageHelper::storeFile(
new Settings(),
$picture,
true,
'web-coupon.' . $picture->extension()
);
}
try {
return Discount::make(
$picture,
Arr::get($coupon, 'valid_on'),
Arr::get($coupon, 'face_value'),
Arr::get($coupon, 'percentage'),
Arr::get($coupon, 'web_coupon_identifiant'),
);
} catch (RuntimeException | TypeError) {
return null;
}
}
}