Completed
Push — master ( 06ade8...5dbfe3 )
by Patrick
02:29
created

SerializationMiddleware   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 121
Duplicated Lines 9.92 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 12
loc 121
rs 9.2
c 1
b 0
f 0
wmc 34
lcom 1
cbo 1

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getFormatFromHeader() 0 13 3
A getParamFromArrayIfSet() 0 8 2
B getFormat() 0 23 5
A reserializeBody() 0 11 1
C __invoke() 12 57 23

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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