Completed
Push — master ( 1f65a3...0feaa6 )
by Jean-Christophe
01:28
created

RestServer   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 133
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 23
c 0
b 0
f 0
lcom 1
cbo 2
dl 0
loc 133
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A connect() 0 12 2
A isValid() 0 10 2
A _getHeaderToken() 0 13 3
A finalizeTokens() 0 6 2
A _getHeader() 0 8 2
A _addHeaderToken() 0 3 1
A _getApiTokens() 0 3 1
A _header() 0 9 3
A _setContentType() 0 6 2
A cors() 0 16 4
1
<?php
2
namespace micro\controllers\rest;
3
/**
4
 * @author jc
5
 *
6
 */
7
class RestServer {
8
	/**
9
	 * @var array
10
	 */
11
	protected $config;
12
	protected $headers;
13
	protected $tokensFolder;
14
	/**
15
	 * @var ApiTokens
16
	 */
17
	protected $apiTokens;
18
19
	public function __construct($config){
20
		$this->config=$config;
21
		$this->headers=['Access-Control-Allow-Origin'=>'http://127.0.0.1:4200',
22
						'Access-Control-Allow-Credentials'=>'true',
23
						'Access-Control-Max-Age'=>'86400',
24
						'Access-Control-Allow-Methods'=>'GET, POST, OPTIONS, PUT, DELETE, PATCH, HEAD'
25
		];
26
	}
27
28
	public function connect(RestController $controller){
29
		if(!isset($this->apiTokens)){
30
			$this->apiTokens=$this->_getApiTokens();
31
		}
32
		$token=$this->apiTokens->addToken();
33
		$this->_addHeaderToken($token);
34
		echo $controller->_format([
35
				"access_token"=>$token,
36
				"token_type"=>"Bearer",
37
				"expires_in"=>$this->apiTokens->getDuration()
38
		]);
39
	}
40
41
	/**
42
	 * Check if token is valid
43
	 * @return boolean
44
	 */
45
	public function isValid(){
46
		$this->apiTokens=$this->_getApiTokens();
47
		$key=$this->_getHeaderToken();
48
		if ($this->apiTokens->isExpired($key)){
49
			return false;
50
		}else{
51
			$this->_addHeaderToken($key);
52
			return true;
53
		}
54
	}
55
56
	public function _getHeaderToken(){
57
		$authHeader=$this->_getHeader("Authorization");
58
		if ($authHeader!==false) {
59
			list($type, $data) = explode(" ", $authHeader, 2);
60
			if (\strcasecmp($type, "Bearer") == 0) {
61
				return $data;
62
			} else {
63
				throw new \Exception("Bearer is required in authorization header.");
64
			}
65
		} else {
66
			throw new \Exception("The header Authorization is required in http headers.");
67
		}
68
	}
69
70
	public function finalizeTokens(){
71
		if(isset($this->apiTokens)){
72
			$this->apiTokens->removeExpireds();
73
			$this->apiTokens->storeToCache();
74
		}
75
	}
76
77
	public function _getHeader($header){
78
		$headers=getallheaders();
79
		if(isset($headers[$header])){
80
			return $headers[$header];
81
		}
82
		return false;
83
84
	}
85
86
	public function _addHeaderToken($token){
87
		$this->_header("Authorization", "Bearer ".$token);
88
	}
89
90
	/**
91
	 * To override for defining another ApiToken type
92
	 * @return ApiTokens
93
	 */
94
	public function _getApiTokens(){
95
		return ApiTokens::getFromCache(ROOT.$this->config["cacheDirectory"].DS);
96
	}
97
98
	/**
99
	 * @param string $headerField
100
	 * @param string $value
101
	 * @param boolean $replace
102
	 */
103
	public function _header($headerField,$value=null,$replace=null){
104
		if(!isset($value)){
105
			if(isset($this->headers[$headerField])){
106
				$value=$this->headers[$headerField];
107
			}else
108
				return;
109
		}
110
		\header(trim($headerField).": ".trim($value),$replace);
111
	}
112
	/**
113
	 * @param string $contentType default application/json
114
	 * @param string $charset default utf8
115
	 */
116
	public function _setContentType($contentType,$charset="utf-8"){
117
		$value=$contentType;
118
		if(isset($charset))
119
			$value.="; charset=".$charset;
120
			$this->_header("Content-type", $value);
121
	}
122
123
	public function cors() {
0 ignored issues
show
Coding Style introduced by
cors uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
124
		$this->_header('Access-Control-Allow-Origin');
125
		$this->_header('Access-Control-Allow-Credentials');
126
		$this->_header('Access-Control-Max-Age');
127
		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
128
			if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
129
				$this->_header('Access-Control-Allow-Methods');
130
131
			if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])){
132
				$this->_header('Access-Control-Allow-Headers',$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
133
			}else {
134
				$this->_header('Access-Control-Allow-Headers','*');
135
			}
136
			exit(0);
0 ignored issues
show
Coding Style Compatibility introduced by
The method cors() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
137
		}
138
	}
139
}
140