Skip to content

Commit

Permalink
added gzip compression to REST server responses
Browse files Browse the repository at this point in the history
  • Loading branch information
michael-graute committed Jan 9, 2021
1 parent 31228e2 commit 4eda9b5
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 1 deletion.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"ext-pdo": "*",
"ext-readline": "*",
"ext-mbstring": "*",
"ext-gd": "*"
"ext-gd": "*",
"ext-zlib": "*"
},
"autoload": {
"psr-4": {
Expand Down
8 changes: 8 additions & 0 deletions src/Pressmind/MVC/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,14 @@ public function getHeaders()
return $this->_headers;
}

/**
* @param $name
* @return string
*/
public function getHeader($name) {
return isset($this->_headers[$name]) ? $this->_headers[$name] : null;
}

/**
* @return string
*/
Expand Down
4 changes: 4 additions & 0 deletions src/Pressmind/MVC/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ public function send()
if($this->_content_type == 'application/json') {
$this->_body = json_encode($this->_body);
}
if(isset($this->_headers['Content-Encoding']) && in_array('gzip', array_map('trim', explode(',', $this->_headers['Content-Encoding'])))) {
$this->_body = gzencode(trim( preg_replace( '/\s+/', ' ', $this->_body )), 9);
}
header('Content-Length: '.strlen($this->_body));
echo $this->_body;
}
}
3 changes: 3 additions & 0 deletions src/Pressmind/REST/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ public function handle() {
$this->_response->addHeader('Access-Control-Allow-Methods', implode(',', array_merge($this->_output_methods, $this->_header_methods)));
$this->_response->addHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token, Authorization, Cache-Control, Pragma, Expires');
$this->_response->addHeader('Cache-Control', 'no-cache');
if(in_array('gzip', array_map('trim', explode(',', $this->_request->getHeader('Accept-Encoding'))))) {
$this->_response->addHeader('Content-Encoding', 'gzip');
}
if ($route_match = $this->_router->handle($this->_request)) {
$classname = $route_match['module'] . '\\' . $route_match['controller'];
if (class_exists($classname)) {
Expand Down

0 comments on commit 4eda9b5

Please sign in to comment.