Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getRequiredValidatedBodyParam method #15595

Open
wants to merge 2 commits into
base: 5.x
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/web/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,48 @@ public function getRequiredBodyParam(string $name): mixed
throw new BadRequestHttpException("Request missing required body param");
}

/**
* Validates and returns the named request body parameter value, or bails on the request with a 400 error if that parameter doesn’t exist or doesn’t pass validation.
*
* ---
*
* ```php
* // get required and validated $_POST['foo']
* $foo = Craft::$app->request->getRequiredValidatedBodyParam('foo');
*
* // get required and validated $_POST['foo']['bar']
* $bar = Craft::$app->request->getRequiredValidatedBodyParam('foo.bar');
* ```
* ```twig
* {# get required and validated $_POST['foo'] #}
* {% set foo = craft.app.request.getRequiredValidatedBodyParam('foo') %}
*
* {# get required and validated $_POST['foo']['bar'] #}
* {% set bar = craft.app.request.getRequiredValidatedBodyParam('foo.bar') %}
* ```
*
* @param string $name The parameter name.
* @return mixed The parameter value
* @throws BadRequestHttpException if the request does not have the body param or if the param value doesn’t pass validation
* @see getBodyParam()
*/
public function getRequiredValidatedBodyParam(string $name): mixed
{
$value = $this->getBodyParam($name);

if ($value === null) {
throw new BadRequestHttpException("Request missing required body param");
}

$value = Craft::$app->getSecurity()->validateData($value);

if ($value === false) {
throw new BadRequestHttpException('Request contained an invalid body param');
}

return $value;
}

/**
* Validates and returns the named request body parameter value, or bails on the request with a 400 error if that parameter doesn’t pass validation.
*
Expand Down
Loading