| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\DonationForms\Routes; |
| 4 |
|
| 5 |
|
| 6 |
use Exception; |
| 7 |
use Give\DonationForms\DataTransferObjects\DonateRouteData; |
| 8 |
use Give\DonationForms\DataTransferObjects\ValidationRouteData; |
| 9 |
use Give\DonationForms\Exceptions\DonationFormFieldErrorsException; |
| 10 |
use Give\DonationForms\Exceptions\DonationFormForbidden; |
| 11 |
use Give\DonationForms\ValueObjects\DonationFormErrorTypes; |
| 12 |
use Give\Framework\PaymentGateways\Traits\HandleHttpResponses; |
| 13 |
use Give\Log\Log; |
| 14 |
use WP_Error; |
| 15 |
|
| 16 |
/** |
| 17 |
* @since 3.0.0 |
| 18 |
*/ |
| 19 |
class ValidationRoute |
| 20 |
{ |
| 21 |
use HandleHttpResponses; |
| 22 |
|
| 23 |
/** |
| 24 |
* @since 3.22.0 added additional catch statements for forbidden and unknown errors |
| 25 |
* @since 3.0.0 |
| 26 |
*/ |
| 27 |
public function __invoke(array $request): bool |
| 28 |
{ |
| 29 |
// create DTO from GET request |
| 30 |
$routeData = DonateRouteData::fromRequest(give_clean($_GET)); |
| 31 |
|
| 32 |
// validate signature |
| 33 |
$routeData->validateSignature(); |
| 34 |
|
| 35 |
// create DTO from POST request |
| 36 |
$formData = ValidationRouteData::fromRequest($request); |
| 37 |
|
| 38 |
try { |
| 39 |
$response = $formData->validate(); |
| 40 |
|
| 41 |
$this->handleResponse($response); |
| 42 |
} catch (DonationFormFieldErrorsException $exception) { |
| 43 |
$type = DonationFormErrorTypes::VALIDATION; |
| 44 |
$this->logError($type, $exception->getMessage(), $formData); |
| 45 |
$this->sendJsonError($type, $exception->getError()); |
| 46 |
} catch (DonationFormForbidden $exception) { |
| 47 |
wp_die($exception->getMessage(), 403); |
| 48 |
} catch (Exception $exception) { |
| 49 |
$type = DonationFormErrorTypes::UNKNOWN; |
| 50 |
$this->logError($type, $exception->getMessage(), $formData); |
| 51 |
$this->sendJsonError($type, new WP_Error($type, $exception->getMessage())); |
| 52 |
} |
| 53 |
|
| 54 |
exit; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* @since 3.0.0 |
| 59 |
*/ |
| 60 |
private function logError( |
| 61 |
string $type, |
| 62 |
string $exceptionMessage, |
| 63 |
ValidationRouteData $formData |
| 64 |
) { |
| 65 |
Log::error( |
| 66 |
"Donation Route Error: $type", |
| 67 |
[ |
| 68 |
'error_type' => $type, |
| 69 |
'exceptionMessage' => $exceptionMessage, |
| 70 |
'formData' => $formData->toArray(), |
| 71 |
] |
| 72 |
); |
| 73 |
} |
| 74 |
|
| 75 |
/** |
| 76 |
* @param string $type |
| 77 |
* @param array|string|WP_Error $errors |
| 78 |
* @return void |
| 79 |
*/ |
| 80 |
protected function sendJsonError(string $type, WP_Error $errors) |
| 81 |
{ |
| 82 |
wp_send_json_error([ |
| 83 |
'type' => $type, |
| 84 |
'errors' => $errors, |
| 85 |
]); |
| 86 |
} |
| 87 |
} |
| 88 |
|