1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace SlayerBirden\DataFlowServer\Zend\InputFilter\Middleware; |
5
|
|
|
|
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
9
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
10
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\Request\Parser; |
11
|
|
|
use SlayerBirden\DataFlowServer\Stdlib\Validation\ValidationResponseFactory; |
12
|
|
|
use Zend\InputFilter\InputFilterInterface; |
13
|
|
|
|
14
|
|
|
final class InputFilterMiddleware implements MiddlewareInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var InputFilterInterface |
18
|
|
|
*/ |
19
|
|
|
private $inputFilter; |
20
|
|
|
/** |
21
|
|
|
* @var string |
22
|
|
|
*/ |
23
|
|
|
private $refName; |
24
|
|
|
|
25
|
30 |
|
public function __construct(InputFilterInterface $inputFilter, string $refName) |
26
|
|
|
{ |
27
|
30 |
|
$this->inputFilter = $inputFilter; |
28
|
30 |
|
$this->refName = $refName; |
29
|
30 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @inheritDoc |
33
|
|
|
*/ |
34
|
30 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
35
|
|
|
{ |
36
|
30 |
|
$data = Parser::getRequestBody($request); |
37
|
30 |
|
$this->inputFilter->setData($data); |
38
|
|
|
|
39
|
30 |
|
if (!$this->inputFilter->isValid()) { |
40
|
6 |
|
return (new ValidationResponseFactory())($this->refName, $this->inputFilter); |
41
|
|
|
} |
42
|
|
|
|
43
|
24 |
|
$values = $this->inputFilter->getValues(); |
44
|
|
|
// only pass values that exist in data |
45
|
|
|
$toPass = array_filter($values, function ($key) use ($data) { |
46
|
24 |
|
return array_key_exists($key, $data); |
47
|
24 |
|
}, ARRAY_FILTER_USE_KEY); |
48
|
|
|
|
49
|
24 |
|
return $handler->handle($request->withParsedBody($toPass)); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|