new: [paramhandler] component added

- centralised handling of all things related to request parameter parsing
remotes/origin/main
iglocska 2020-06-09 15:58:11 +02:00
parent 62c9050fb2
commit 28c2ac04ea
No known key found for this signature in database
GPG Key ID: BEA224F1FEF113AC
1 changed files with 63 additions and 0 deletions

View File

@ -0,0 +1,63 @@
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Core\Configure;
class ParamHandlerComponent extends Component
{
public function initialize(array $config): void
{
$this->request = $config['request'];
}
/*
* Harvest parameters form a request
*
* Requires the request object and a list of keys to filter as input
* Order of precedence:
* ordered uri components (/foo/bar/baz) > query strings (?foo=bar) > posted data (json body {"foo": "bar"})
*/
public function harvestParams(array $filterList): array
{
$parsedParams = array();
foreach ($filterList as $k => $filter) {
if (isset($this->request->getAttribute('params')['pass'][$k])) {
$parsedParams[$filter] = $this->request->getAttribute('params')['pass'][$k];
continue;
}
if (($this->request->getQuery($filter)) !== null) {
$parsedParams[$filter] = $this->request->getQuery($filter);
continue;
}
if (($this->request->is('post') || $this->request->is('put')) && $this->request->getData($filter) !== null) {
$parsedParams[$filter] = $this->request->getData($filter);
}
}
return $parsedParams;
}
public function isRest()
{
// This method is surprisingly slow and called many times for one request, so it make sense to cache the result.
if ($this->isRest !== null) {
return $this->isRest;
}
if ($this->request->is('json')) {
if (!empty($this->request->input()) && empty($this->request->input('json_decode'))) {
throw new MethodNotAllowedException('Invalid JSON input. Make sure that the JSON input is a correctly formatted JSON string. This request has been blocked to avoid an unfiltered request.');
}
$this->isRest = true;
return true;
} else {
$this->isRest = false;
return false;
}
}
public function isJson($data)
{
return (json_decode($data) != null) ? true : false;
}
}