LegacyResponderMiddleware::extract()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
namespace hiapi\middlewares;
4
5
use hiapi\commands\error\CommandError;
6
use League\Tactician\Middleware;
7
use Psr\Http\Message\ResponseInterface;
8
use Zend\Hydrator\HydratorInterface;
9
10
class LegacyResponderMiddleware implements Middleware
11
{
12
    /**
13
     * @var ResponseInterface
14
     */
15
    private $response;
16
    /**
17
     * @var HydratorInterface
18
     */
19
    private $extractor;
20
21
    public function __construct(
22
        ResponseInterface $response,
23
        HydratorInterface $extractor
24
    ) {
25
        $this->response = $response;
26
        $this->extractor = $extractor;
27
    }
28
29
    /**
30
     * @param object $command
31
     * @param callable $next
32
     *
33
     * @return mixed
34
     */
35
    public function execute($command, callable $next)
36
    {
37
        $result = $next($command);
38
39
        $data = $this->extract($result);
40
41
        return $this->createResponseFor($data);
42
    }
43
44
    private function extract($result)
45
    {
46
        if ($result instanceof CommandError) {
47
            return ['_error' => $result->getException()->getMessage()];
48
        }
49
50
        if (is_array($result)) {
51
            return array_map(function ($item) {
52
                return $this->extractOne($item);
53
            }, $result);
54
        }
55
56
        return $this->extractOne($result);
57
    }
58
59
    private function extractOne($result)
60
    {
61
        return is_object($result) ? $this->extractor->extract($result) : $result;
62
    }
63
64
    private function createResponseFor($data)
65
    {
66
        $response = $this->response
67
            ->withStatus(200)
68
            ->withHeader("Content-Type", "application/json");
69
70
        if ($response->getBody()->isSeekable()) {
71
            $response->getBody()->rewind();
72
        }
73
74
        $response->getBody()->write(json_encode($data));
75
76
        return $response;
77
    }
78
}
79