Completed
Push — master ( f4afa6...28cdc3 )
by Jean-Christophe
01:27
created

RestServer::getRestNamespace()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
namespace micro\controllers\rest;
3
use micro\controllers\Startup;
4
use micro\cache\ClassUtils;
5
6
/**
7
 * @author jc
8
 *
9
 */
10
class RestServer {
11
	/**
12
	 * @var array
13
	 */
14
	protected $config;
15
	protected $headers;
16
	protected $tokensFolder;
17
	protected $tokensCacheKey="_apiTokens";
18
	/**
19
	 * @var ApiTokens
20
	 */
21
	protected $apiTokens;
22
23
	public function __construct($config){
24
		$this->config=$config;
25
		$this->headers=['Access-Control-Allow-Origin'=>'http://127.0.0.1:4200',
26
						'Access-Control-Allow-Credentials'=>'true',
27
						'Access-Control-Max-Age'=>'86400',
28
						'Access-Control-Allow-Methods'=>'GET, POST, OPTIONS, PUT, DELETE, PATCH, HEAD'
29
		];
30
	}
31
32
	public function connect(RestController $controller){
33
		if(!isset($this->apiTokens)){
34
			$this->apiTokens=$this->_getApiTokens();
35
		}
36
		$token=$this->apiTokens->addToken();
37
		$this->_addHeaderToken($token);
38
		echo $controller->_format([
39
				"access_token"=>$token,
40
				"token_type"=>"Bearer",
41
				"expires_in"=>$this->apiTokens->getDuration()
42
		]);
43
	}
44
45
	/**
46
	 * Check if token is valid
47
	 * @return boolean
48
	 */
49
	public function isValid(){
50
		$this->apiTokens=$this->_getApiTokens();
51
		$key=$this->_getHeaderToken();
52
		if ($this->apiTokens->isExpired($key)){
53
			return false;
54
		}else{
55
			$this->_addHeaderToken($key);
56
			return true;
57
		}
58
	}
59
60
	public function _getHeaderToken(){
61
		$authHeader=$this->_getHeader("Authorization");
62
		if ($authHeader!==false) {
63
			list($type, $data) = explode(" ", $authHeader, 2);
64
			if (\strcasecmp($type, "Bearer") == 0) {
65
				return $data;
66
			} else {
67
				throw new \Exception("Bearer is required in authorization header.");
68
			}
69
		} else {
70
			throw new \Exception("The header Authorization is required in http headers.");
71
		}
72
	}
73
74
	public function finalizeTokens(){
75
		if(isset($this->apiTokens)){
76
			$this->apiTokens->removeExpireds();
77
			$this->apiTokens->storeToCache();
78
		}
79
	}
80
81
	public function _getHeader($header){
82
		$headers=getallheaders();
83
		if(isset($headers[$header])){
84
			return $headers[$header];
85
		}
86
		return false;
87
88
	}
89
90
	public function _addHeaderToken($token){
91
		$this->_header("Authorization", "Bearer ".$token);
92
	}
93
94
	/**
95
	 * To override for defining another ApiToken type
96
	 * @return ApiTokens
97
	 */
98
	public function _getApiTokens(){
99
		return ApiTokens::getFromCache(ROOT.$this->config["cacheDirectory"].DS,$this->tokensCacheKey);
100
	}
101
102
	/**
103
	 * @param string $headerField
104
	 * @param string $value
105
	 * @param boolean $replace
106
	 */
107
	public function _header($headerField,$value=null,$replace=null){
108
		if(!isset($value)){
109
			if(isset($this->headers[$headerField])){
110
				$value=$this->headers[$headerField];
111
			}else
112
				return;
113
		}
114
		\header(trim($headerField).": ".trim($value),$replace);
115
	}
116
	/**
117
	 * @param string $contentType default application/json
118
	 * @param string $charset default utf8
119
	 */
120
	public function _setContentType($contentType,$charset="utf-8"){
121
		$value=$contentType;
122
		if(isset($charset))
123
			$value.="; charset=".$charset;
124
			$this->_header("Content-type", $value);
125
	}
126
127
	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...
128
		$this->_header('Access-Control-Allow-Origin');
129
		$this->_header('Access-Control-Allow-Credentials');
130
		$this->_header('Access-Control-Max-Age');
131
		if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
132
			if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
133
				$this->_header('Access-Control-Allow-Methods');
134
135
			if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])){
136
				$this->_header('Access-Control-Allow-Headers',$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
137
			}else {
138
				$this->_header('Access-Control-Allow-Headers','*');
139
			}
140
			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...
141
		}
142
	}
143
144
	public static function getRestNamespace(){
145
		$config=Startup::getConfig();
146
		$controllerNS=$config["mvcNS"]["controllers"];
147
		$restNS="";
148
		if(isset($config["mvcNS"]["rest"])){
149
			$restNS=$config["mvcNS"]["rest"];
150
		}
151
		return ClassUtils::getNamespaceFromParts([$controllerNS,$restNS]);
152
	}
153
}
154