Completed
Push — master ( 166484...24c373 )
by Patrick
02:36
created

SerializationMiddleware::__invoke()   C

Complexity

Conditions 25
Paths 25

Size

Total Lines 60
Code Lines 49

Duplication

Lines 12
Ratio 20 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 25
eloc 49
c 1
b 0
f 0
nc 25
nop 3
dl 12
loc 60
rs 6.1226

How to fix   Long Method    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->getHeaderLine('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
            else if($this->format === 'json')
48
            {
49
                //OData json is different from notmal json
50
                $this->format = 'odata-json';
51
            }
52
        }
53
        if(strstr($this->format, 'odata.streaming=true'))
54
        {
55
            return $response->withStatus(406);
56
        }
57
        return $response;
58
    }
59
60
    protected function reserializeBody($response, $serializer)
61
    {
62
        $body = $response->getBody();
63
        $body->rewind();
64
        $data = json_decode($body->getContents());
65
        $serializer = new $serializer();
66
        $res = $serializer->serializeData($this->format, $data);
67
        $response = $response->withBody(new \Slim\Http\Body(fopen('php://temp', 'r+')));
68
        $response->getBody()->write($res);
69
        return $response->withHeader('Content-Type', $this->format);
70
    }
71
72
    public function __invoke($request, $response, $next)
73
    {
74
        $response = $this->getFormat($request, $response);
75
        if($response->getStatusCode() !== 200)
76
        {
77
            return $response;
78
        }
79
        $request = $request->withAttribute('format', $this->format);
80
        $response = $next($request, $response);
81
        if($response->getHeaderLine('Content-Type') !== 'application/json;charset=utf-8')
82
        {
83
            //The underlying API call gave us back a different content type. Just pass that on...
84
            return $response;
85
        }
86
        switch($this->format)
87
        {
88
            case 'application/json':
89
            case 'application/x-javascript':
90
            case 'text/javascript':
91
            case 'text/x-javascript':
92
            case 'text/x-json':
93
            case 'json':
94
                return $response;
95
            case 'json-ss':
96
            case 'json-ss-dt':
97
                return $this->reserializeBody($response, '\Serialize\JsonSpreadSheet');
98 View Code Duplication
            case 'data-table':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
99
                //This is a special case for json...
100
                $body = $response->getBody();
101
                $body->rewind();
102
                $data = json_decode($body->getContents());
103
                return $response->withJson(array('data'=>$data));
104 View Code Duplication
            case 'odata-json':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
                //This is a special case for json...
106
                $body = $response->getBody();
107
                $body->rewind();
108
                $data = json_decode($body->getContents());
109
                return $response->withJson(array('value'=>$data));
110
            case 'xml':
111
            case 'application/xml':
112
            case 'text/xml':
113
                return $this->reserializeBody($response, '\Serialize\XMLSerializer');
114
            case 'csv':
115
            case 'text/csv':
116
                return $this->reserializeBody($response, '\Serialize\CSVSerializer');
117
            case 'xlsx':
118
            case 'xls':
119
            case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
120
            case 'application/vnd.ms-excel':
121
                return $this->reserializeBody($response, '\Serialize\ExcelSerializer');
122
            case 'yaml':
123
            case 'application/x-yaml':
124
            case 'text/x-yaml':
125
                return $this->reserializeBody($response, '\Serialize\YAMLSerializer');
126
            default:
127
                print_r($this->format); die();
128
                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...
129
        }
130
        return $response;
131
    }
132
}
133