|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the uSilex framework. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Enrico Fagnoni <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace uSilex\Pimple; |
|
13
|
|
|
|
|
14
|
|
|
use uSilex\Api\ResponseProcessorInterface; |
|
15
|
|
|
use uSilex\Api\ResponseHandlerInterface; |
|
16
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
17
|
|
|
use TypeError; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Psr15plus trait. HTTP response post processing implementation |
|
21
|
|
|
* |
|
22
|
|
|
* @author Enrico Fagnoni <[email protected]> |
|
23
|
|
|
*/ |
|
24
|
|
|
trait ResponseHandlerTrait |
|
25
|
|
|
{ |
|
26
|
|
|
|
|
27
|
|
|
protected $responseProcessors = []; |
|
28
|
|
|
|
|
29
|
|
|
|
|
30
|
3 |
|
public function onResponse(string $serviceName) |
|
31
|
|
|
{ |
|
32
|
3 |
|
$this->responseProcessors[] = $serviceName; |
|
33
|
|
|
|
|
34
|
3 |
|
return $this; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Handles a response and produces a response |
|
40
|
|
|
* |
|
41
|
|
|
* May call other collaborating code to generate the response. |
|
42
|
|
|
*/ |
|
43
|
5 |
|
protected function handleResponseRunner (ResponseInterface $response) : ResponseInterface |
|
44
|
|
|
{ |
|
45
|
5 |
|
$responseProcessorServiceName = current($this->responseProcessors); |
|
46
|
5 |
|
if (!$responseProcessorServiceName) { |
|
47
|
2 |
|
return $response; |
|
48
|
|
|
} |
|
49
|
3 |
|
$responseProcessor = $this[$responseProcessorServiceName]; |
|
50
|
3 |
|
if( !($responseProcessor instanceof ResponseProcessorInterface)) { |
|
51
|
1 |
|
throw new TypeError("$responseProcessorServiceName is not a http response processor"); |
|
52
|
|
|
} |
|
53
|
2 |
|
next($this->responseProcessors); |
|
54
|
|
|
|
|
55
|
|
|
// execute middleware |
|
56
|
2 |
|
$result = $responseProcessor->process($response, $this); |
|
|
|
|
|
|
57
|
|
|
|
|
58
|
2 |
|
return $result; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* Handles a response and produces a response |
|
64
|
|
|
* |
|
65
|
|
|
* May call other collaborating code to generate the response. |
|
66
|
|
|
*/ |
|
67
|
5 |
|
public function handleResponse(ResponseInterface $response) : ResponseInterface |
|
68
|
|
|
{ |
|
69
|
5 |
|
reset( $this->responseProcessors); |
|
70
|
5 |
|
return $this->handleResponseRunner($response); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
} |
|
74
|
|
|
|