59 lines
2.1 KiB
PHP
59 lines
2.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\ProductInquiry\Controller\Index;
|
|
|
|
use Esun\ProductInquiry\Model\SubmissionService;
|
|
use Magento\Framework\App\Action\HttpPostActionInterface;
|
|
use Magento\Framework\App\RequestInterface;
|
|
use Magento\Framework\Controller\Result\Json;
|
|
use Magento\Framework\Controller\Result\JsonFactory;
|
|
use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;
|
|
use Magento\Framework\Exception\LocalizedException;
|
|
use Psr\Log\LoggerInterface;
|
|
|
|
class Post implements HttpPostActionInterface
|
|
{
|
|
public function __construct(
|
|
private readonly RequestInterface $request,
|
|
private readonly JsonFactory $jsonFactory,
|
|
private readonly FormKeyValidator $formKeyValidator,
|
|
private readonly SubmissionService $submissionService,
|
|
private readonly LoggerInterface $logger
|
|
) {
|
|
}
|
|
|
|
public function execute(): Json
|
|
{
|
|
$result = $this->jsonFactory->create();
|
|
if (!$this->formKeyValidator->validate($this->request)) {
|
|
return $this->error($result, __('Your session has expired. Refresh the page and try again.'), 400);
|
|
}
|
|
|
|
try {
|
|
$submission = $this->submissionService->submit($this->request);
|
|
} catch (LocalizedException $exception) {
|
|
return $this->error($result, $exception->getMessage(), 422);
|
|
} catch (\Throwable $exception) {
|
|
$this->logger->critical($exception);
|
|
return $this->error($result, __('Unable to submit your inquiry. Please try again later.'), 500);
|
|
}
|
|
|
|
return $result->setData([
|
|
'success' => true,
|
|
'duplicate' => (bool)$submission['duplicate'],
|
|
'message' => (string)($submission['duplicate']
|
|
? __('This inquiry has already been submitted. We will contact you as soon as possible.')
|
|
: __('Thank you. Your inquiry has been submitted.')),
|
|
]);
|
|
}
|
|
|
|
private function error(Json $result, \Stringable|string $message, int $statusCode): Json
|
|
{
|
|
return $result->setHttpResponseCode($statusCode)->setData([
|
|
'success' => false,
|
|
'message' => (string)$message,
|
|
]);
|
|
}
|
|
}
|