Completed
Pull Request — develop (#53)
by Patrick
03:17
created

SerializationMiddleware::__invoke()   D

Complexity

Conditions 19
Paths 19

Size

Total Lines 47
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 19
eloc 37
c 1
b 0
f 0
nc 19
nop 3
dl 0
loc 47
rs 4.8871

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Http\Rest;
3
4
use \Psr\Http\Message\ServerRequestInterface as Request;
5
use \Psr\Http\Message\ResponseInterface as Response;
6
7
require 'vendor/autoload.php';
8
9
class SerializationMiddleware
10
{
11
    protected $format = null;
12
13
    private function getFormatFromHeader($request)
14
    {
15
        $mimeType = $request->getHeader('Accept');
16
        switch($mimeType)
17
        {
18
            case 'text/csv':
19
                return 'csv';
20
            case 'text/x-vCard':
21
                return 'vcard';
22
            default:
23
                return 'json';
24
        }
25
    }
26
27
    private function getParamFromArrayIfSet($array, $param, $default = null)
28
    {
29
        if(isset($array[$param]))
30
        {
31
            return $array[$param];
32
        }
33
        return $default;
34
    }
35
36
    private function getFormat($request, $response)
37
    {
38
        $params = $request->getQueryParams();
39
        $this->format = $this->getParamFromArrayIfSet($params, 'fmt');
40
        if($this->format === null)
41
        {
42
            $this->format = $this->getParamFromArrayIfSet($params, '$format');
43
            if($this->format === null)
44
            {
45
                $this->format = $this->getFormatFromHeader($request);
46
            }
47
        }
48
        if(strstr($this->format, 'odata.streaming=true'))
49
        {
50
            return $response->withStatus(406);
51
        }
52
        return $response;
53
    }
54
55
    protected function reserializeBody($response, $serializer)
56
    {
57
        $body = $response->getBody();
58
        $body->rewind();
59
        $data = json_decode($body->getContents());
60
        $serializer = new $serializer();
61
        $res = $serializer->serializeData($this->format, $data);
62
        $response = $response->withBody(new \Slim\Http\Body(fopen('php://temp', 'r+')));
63
        $response->getBody()->write($res);
64
        return $response->withHeader('Content-Type', $this->format);
65
    }
66
67
    public function __invoke($request, $response, $next)
68
    {
69
        $response = $this->getFormat($request, $response);
70
        if($response->getStatusCode() !== 200)
71
        {
72
            return $response;
73
        }
74
        $request = $request->withAttribute('format', $this->format);
75
        $response = $next($request, $response);
76
        if($response->getHeaderLine('Content-Type') !== 'application/json;charset=utf-8')
77
        {
78
            //The underlying API call gave us back a different content type. Just pass that on...
79
            return $response;
80
        }
81
        switch($this->format)
82
        {
83
            case 'application/json':
84
            case 'application/x-javascript':
85
            case 'text/javascript':
86
            case 'text/x-javascript':
87
            case 'text/x-json':
88
            case 'json':
89
                return $response;
90
            case 'data-table':
91
                //This is a special case for json...
92
                $body = $response->getBody();
93
                $body->rewind();
94
                $data = json_decode($body->getContents());
95
                return $response->withJson(array('data'=>$data));
96
            case 'xml':
97
            case 'application/xml':
98
            case 'text/xml':
99
                return $this->reserializeBody($response, '\Serialize\XMLSerializer');
100
            case 'csv':
101
            case 'text/csv':
102
                return $this->reserializeBody($response, '\Serialize\CSVSerializer');
103
            case 'xlsx':
104
            case 'xls':
105
            case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
106
            case 'application/vnd.ms-excel':
107
                return $this->reserializeBody($response, '\Serialize\ExcelSerializer');
108
            default:
109
                print_r($this->format); die();
110
                break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
111
        }
112
        return $response;
113
    }
114
}
115