From 51d6b541e5d2c3b56eabb634d810a28d08b1169a Mon Sep 17 00:00:00 2001 From: Jan Jakes Date: Wed, 16 Feb 2022 11:00:39 +0100 Subject: [PATCH] Add check that JSON request body exists when required [MAILPOET-4135] --- mailpoet/lib/Automation/API/Request.php | 8 +++++++- mailpoet/lib/Automation/Exceptions.php | 9 +++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/mailpoet/lib/Automation/API/Request.php b/mailpoet/lib/Automation/API/Request.php index 8263a4e016..11f85201be 100644 --- a/mailpoet/lib/Automation/API/Request.php +++ b/mailpoet/lib/Automation/API/Request.php @@ -36,7 +36,13 @@ class Request { } public function getBody(): array { - return $this->wpRequest->get_json_params() ?? []; + $json = $this->wpRequest->get_json_params(); + + /* @phpstan-ignore-next-line hotfix for missing 'null' in WP annotation */ + if ($json === null) { + throw Exceptions::apiNoJsonBody(); + } + return $json; } public function getRawBody(): string { diff --git a/mailpoet/lib/Automation/Exceptions.php b/mailpoet/lib/Automation/Exceptions.php index afe9f58fb9..5312c03962 100644 --- a/mailpoet/lib/Automation/Exceptions.php +++ b/mailpoet/lib/Automation/Exceptions.php @@ -3,11 +3,20 @@ namespace MailPoet\Automation; use MailPoet\Automation\Exceptions\InvalidStateException; +use MailPoet\Automation\Exceptions\UnexpectedValueException; class Exceptions { + private const API_NO_JSON_BODY = 'mailpoet_automation_api_no_json_body'; + public function __construct() { throw new InvalidStateException( "This is a static factory class. Use it via 'Exception::someError()' factories." ); } + + public static function apiNoJsonBody(): UnexpectedValueException { + return UnexpectedValueException::create() + ->withErrorCode(self::API_NO_JSON_BODY) + ->withMessage('No JSON body passed.'); + } }