Untitled

mail@pastecode.io avatar
unknown
php
a month ago
2.1 kB
6
Indexable
Never
<?php

namespace App\Http\Controllers\Api\Form;

use App\Enums\ErrorCodesEnum;
use App\Enums\HttpStatusCodesEnum;
use App\Http\Controllers\Controller;
use App\Http\Requests\FormBuilder\StoreRequest;
use App\Models\Form\Form;
use App\Services\Form\FormBuilder\FormBuilderService;
use Illuminate\Http\JsonResponse;

class FormBuilderController extends Controller
{
    /**
     * @param FormBuilderService $formBuilderService
     */
    public function __construct(
        private readonly FormBuilderService $formBuilderService
    ) {
        $this->middleware('jwt.auth');
    }

    /**
     * @return JsonResponse
     */
    public function create(): JsonResponse
    {
        return $this->apiSuccess((array)$this->formBuilderService->build());
    }

    /**
     * @param StoreRequest $request
     * @return JsonResponse
     */
    public function store(StoreRequest $request): JsonResponse
    {
        $result = $this->formBuilderService->store($request->all());

        if (!$result->success) {
            return $this->apiError(
                ErrorCodesEnum::RESOURCE_CREATE_ERROR,
                HttpStatusCodesEnum::BAD_REQUEST,
                $result->error
            );
        }

        return $this->apiSuccess((array)$result->value);
    }

    /**
     * @param Form $form
     * @return JsonResponse
     */
    public function edit(Form $form): JsonResponse
    {
        $this->authorize('view', $form);

        $result = $this->formBuilderService->build($form);

        return $this->apiSuccess((array)$result);
    }

    /**
     * @param Form $form
     * @return JsonResponse
     */
    public function update(StoreRequest $request, Form $form): JsonResponse
    {
        $this->authorize('update', $form);

        $result = $this->formBuilderService->update($form, $request->all());

        if (!$result->success) {
            return $this->apiError(
                ErrorCodesEnum::RESOURCE_UPDATE_ERROR,
                HttpStatusCodesEnum::BAD_REQUEST,
                $result->error
            );
        }

        return $this->apiSuccess((array)$result->value);
    }
}
Leave a Comment