Completed
Branch dev (9c0c80)
by Jakob
14:36
created

Server   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 174
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 8
dl 0
loc 174
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A setLogger() 0 4 1
A parseRequest() 0 19 3
B query() 0 60 8
A optionsResponse() 0 14 1
A sendResponse() 0 17 3
1
<?php declare(strict_types = 1);
2
3
namespace JSKOS;
4
5
use Psr\Http\Message\RequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Http\Message\ResponseFactory;
8
use Http\Discovery\MessageFactoryDiscovery;
9
use Psr\Log\LoggerInterface;
10
use Psr\Log\NullLogger;
11
12
/**
13
 * A JSKOS Server.
14
 */
15
class Server implements \Psr\Log\LoggerAwareInterface
16
{
17
    protected $service;
18
    protected $logger;
19
20
    public function __construct(
21
        Service $service, 
22
        ResponseFactory $responseFactory=null,
23
        LoggerInterface $logger=null 
24
    )
25
    {
26
        $this->service = $service;
27
        $this->responseFactory = $responseFactory ?: MessageFactoryDiscovery::find();
0 ignored issues
show
Bug introduced by
The property responseFactory does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
28
        $this->logger = $logger ?: new NullLogger();
29
    }
30
31
    public function setLogger(LoggerInterface $logger)
32
    {
33
        $this->logger = $logger;
34
    }
35
36
    protected function parseRequest(RequestInterface $request): array
37
    {
38
        $uri = $request->getUri();
39
        $path = $uri->getPath();
40
        $query = [];
41
        parse_str($uri->getQuery(), $query);
42
43
        $callback = null;
44
        if (isset($query['callback'])) {
45
            if (preg_match('/^[$A-Z_][0-9A-Z_$.]*$/i', $query['callback'])) {
46
                $callback = $query['callback'];
47
            }
48
            unset($query['callback']);
49
        }
50
51
        # TODO: get language parameter from headers
52
53
        return [$query, $path, $callback];
54
    }
55
56
    public function query(RequestInterface $request): ResponseInterface
57
    {    
58
        $method = $request->getMethod();
59
60
        $result = null;
61
        $callback = null;
62
63
        if ($method == 'GET' or $method == 'HEAD') {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
64
            list ($query, $path, $callback) = $this->parseRequest($request);
65
66
            # TODO: detect conflicting parameters?
67
            # if (isset($params['uri']) and isset($params['search'])) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
68
            #   $error = new Error(422, 'request_error', 'Conflicting request parameters uri & search');
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
69
            # }
70
71
            try {
72
                $result = $this->service->query($query, $path);
73
            } catch(Error $e) {
74
                $error = $e;
75
            }
76
            # TODO: catch other kinds of errors:
77
            # } catch (\Exception $e) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
78
            # $this->logger->error('Service Exception', ['exception' => $e]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
79
            # $error = new Error(500, 'Internal server error');
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
80
        } elseif ($request->getMethod() == 'OPTIONS') {            
81
            return $this->optionsResponse();
82
        } else {
83
            $error = new Error(405, 'Method not allowed');
84
        }
85
86
87
        if ($result) {
88
            $code = 200;
89
            $headers = [
90
                'Access-Control-Allow-Origin' => '*',
91
                'Content-Type' => 'application/json; charset=UTF-8',
92
                'X-Total-Count' => $result->getTotalCount()
93
            ];
94
            $body = $result->json();
95
        } else {
96
            $code = $error->code;
0 ignored issues
show
Bug introduced by
The variable $error does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
97
            $headers = [
98
                'Access-Control-Allow-Origin' => '*',
99
                'Content-Type' => 'application/json; charset=UTF-8',
100
            ];
101
            $body = $error->json();
102
        }
103
104
        $headers['Content-Length'] = strlen($body);
105
        if ($method == 'HEAD') {
106
            $body = '';
107
        }
108
109
        if ($callback) {
110
            $body = "/**/$callback($body);";
111
            $headers['Content-Type'] = 'application/javascript; charset=UTF-8';
112
        }
113
114
        return $this->responseFactory->createResponse($code, null, $headers, $body);
115
    }
116
117
118
    public function optionsResponse()
119
    {
120
        $headers = [
121
            'Access-Control-Allow-Methods' => 'GET, HEAD, OPTIONS',
122
        ];
123
124
        # TODO:
125
        # if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
126
        #    $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'GET') {
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
127
        #    $response->headers['Access-Control-Allow-Origin'] = '*';
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
128
        #    $response->headers['Acess-Control-Expose-Headers'] = 'Link, X-Total-Count';
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
129
130
        return $this->responseFactory->createResponse(200, null, $headers, '');
131
    }
132
133
    /**
134
     * TODO: Extract requested languages(s) from request.
135
    public function extractRequestLanguage($params)
136
    {
137
        $language = null;
138
139
        # get query modifier: language
140
        if (isset($params['language'])) {
141
            $language = $params['language'];
142
            unset($params['language']);
143
            # TODO: parse language
144
        } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
145
            # parse accept-language-header
146
            preg_match_all(
147
                '/([a-z]+(?:-[a-z]+)?)\s*(?:;\s*q\s*=\s*(1|0?\.[0-9]+))?/i',
148
                $_SERVER['HTTP_ACCEPT_LANGUAGE'],
149
                $match);
150
            if (count($match[1])) {
151
                foreach ($match[1] as $i => $l) {
152
                    if (isset($match[2][$i]) && $match[2][$i] != '') {
153
                        $langs[strtolower($l)] = (float) $match[2][$i];
154
                    } else {
155
                        $langs[strtolower($l)] = 1;
156
                    }
157
                }
158
                arsort($langs, SORT_NUMERIC);
159
                reset($langs);
160
                $language = key($langs); # most wanted language
161
            }
162
        }
163
        
164
        return $language;
165
    }
166
*/
167
168
	/**
169
	 * Utility function to emit a Response without additional framework.
170
	 */
171
    public static function sendResponse(ResponseInterface $response) 
172
    {
173
		$code = $response->getStatusCode();
174
		$reason = $response->getReasonPhrase();
175
		header(
176
			sprintf('HTTP/%s %s %s', $response->getProtocolVersion(), $code, $reason),
177
			true, $code 
178
		);
179
180
		foreach ($response->getHeaders() as $header => $values) {
181
			foreach ($values as $value) {
182
				header("$header: $value", false);
183
			}
184
		}
185
186
		echo $response->getBody();
187
	}
188
}
189