Skip to content
This repository has been archived by the owner on Sep 10, 2021. It is now read-only.

Commit

Permalink
Update Zend RESTful Framework to 7ae983a5ca
Browse files Browse the repository at this point in the history
  • Loading branch information
Jamie Snape committed Jun 18, 2014
1 parent ba81d0b commit 8cbd95e
Show file tree
Hide file tree
Showing 6 changed files with 338 additions and 132 deletions.
2 changes: 1 addition & 1 deletion library/REST/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* REST Controller default actions
*
*/
require_once BASE_PATH.'/core/AppController.php';
require_once BASE_PATH . '/core/AppController.php';

abstract class REST_Controller extends AppController
{
Expand Down
60 changes: 28 additions & 32 deletions library/REST/Controller/Action/Helper/ContextSwitch.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class REST_Controller_Action_Helper_ContextSwitch extends Zend_Controller_Action
'json' => 'Zend_Serializer_Adapter_Json',
'xml' => 'REST_Serializer_Adapter_Xml',
'php' => 'Zend_Serializer_Adapter_PhpSerialize',
'html' => 'Zend_Serializer_Adapter_Json',
'html' => 'Zend_Serializer_Adapter_Json'
);

protected $_rest_contexts = array(
Expand Down Expand Up @@ -74,7 +74,7 @@ class REST_Controller_Action_Helper_ContextSwitch extends Zend_Controller_Action
'options' => array(
'autoDisableLayout' => false,
),

'callbacks' => array(
'init' => 'initAbstractContext',
'post' => 'restContext'
Expand Down Expand Up @@ -128,6 +128,7 @@ public function restContext()
if ($view instanceof Zend_View_Interface) {
if (method_exists($view, 'getVars')) {
$vars = $view->getVars();

if (isset($vars['apiresults'])) {
$data = $vars['apiresults'];

Expand All @@ -142,17 +143,17 @@ public function restContext()
$body = str_replace('<?xml version="1.0"?>', sprintf('<?xml version="1.0"?><?xml-stylesheet type="text/xsl" href="%s"?>', $stylesheet), $body);
}
}

if ($this->_currentContext == 'json') {
$callback = $this->getRequest()->getParam('jsonp-callback', false);

if ($callback !== false and !empty($callback)) {
$body = sprintf('%s(%s)', $callback, $body);
}
}

if ($this->_currentContext == 'html') {
$body = $this->prettyPrint($body, array("format" => "html"));
$body = self::prettyPrint($body, array('format' => 'html'));
}

$this->getResponse()->setBody($body);
Expand All @@ -172,14 +173,8 @@ public function getAutoSerialization()
{
return $this->_autoSerialization;
}



/**
* This function is based on the below Zend patches with minor customized changes
* Refs:
* http://framework.zend.com/issues/browse/ZF-9577
* http://framework.zend.com/issues/browse/ZF-10185
*
* Pretty-print JSON string
*
* Use 'format' option to select output format - currently html and txt supported, txt is default
Expand All @@ -189,58 +184,59 @@ public function getAutoSerialization()
* @param array $options Encoding options
* @return string
*/
public function prettyPrint($json, $options = array())
private static function prettyPrint($json, $options = array())
{
$tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
$result = "";
$result = '';
$indent = 0;

$format= "txt";
$format= 'txt';

$ind = "\t";

if(isset($options['format'])) {
if (isset($options['format'])) {
$format = $options['format'];
}

switch ($format):
switch ($format) {
case 'html':
$line_break = "<br />";
$line_break_length = 6;
$ind = "&nbsp;&nbsp;&nbsp;&nbsp;";
$lineBreak = '<br />';
$ind = '&nbsp;&nbsp;&nbsp;&nbsp;';
break;
default:
case 'txt':
$line_break = "\n";
$line_break_length = 2;
$lineBreak = "\n";
$ind = "\t";
break;
endswitch;
}

//override the defined indent setting with the supplied option
if(isset($options['indent'])) {
// override the defined indent setting with the supplied option
if (isset($options['indent'])) {
$ind = $options['indent'];
}
$inLiteral = false;

$inLiteral = false;
foreach($tokens as $token) {
if($token == "") continue;
if($token == '') {
continue;
}

$prefix = str_repeat($ind, $indent);
if (!$inLiteral && ($token == '{' || $token == '[')) {
$indent++;
if($result != "" && substr($result, strlen($result)-$line_break_length) == $line_break) {
if (($result != '') && ($result[(strlen($result)-1)] == $lineBreak)) {
$result .= $prefix;
}
$result .= "$token$line_break";
$result .= $token . $lineBreak;
} elseif (!$inLiteral && ($token == '}' || $token == ']')) {
$indent--;
$prefix = str_repeat($ind, $indent);
$result .= "$line_break$prefix$token";
$result .= $lineBreak . $prefix . $token;
} elseif (!$inLiteral && $token == ',') {
$result .= "$token$line_break" ;
$result .= $token . $lineBreak;
} else {
$result .= ( $inLiteral ? '' : $prefix ) . $token;

// Count # of unescaped double-quotes in token, subtract # of
// escaped double-quotes and if the result is odd then we are
// inside a string literal
Expand Down
153 changes: 71 additions & 82 deletions library/REST/Controller/Plugin/RestHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,104 +50,90 @@ class REST_Controller_Plugin_RestHandler extends Zend_Controller_Plugin_Abstract
);

public function __construct(Zend_Controller_Front $frontController)
{
$this->dispatcher = $frontController->getDispatcher();
}
{
$this->dispatcher = $frontController->getDispatcher();
}

public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
// only handle Restful WebApi URI
if(strpos($request->getPathInfo(), '/rest/') !== FALSE)
{
// send the HTTP Vary header
$this->_response->setHeader('Vary', 'Accept');
{
// only handle RESTful API URI
if (strpos($request->getPathInfo(), '/rest/') !== false) {
// send the HTTP Vary header
$this->_response->setHeader('Vary', 'Accept');

// Cross-Origin Resource Sharing (CORS)
// TODO: probably should be an environment setting?
$this->_response->setHeader('Access-Control-Max-Age', '86400');
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
$this->_response->setHeader('Access-Control-Allow-Credentials', 'true');
$this->_response->setHeader('Access-Control-Allow-Headers', 'Authorization, X-Authorization, Origin, Accept, Content-Type, X-Requested-With, X-HTTP-Method-Override');
// Cross-Origin Resource Sharing (CORS)
// TODO: probably should be an environment setting?
$this->_response->setHeader('Access-Control-Max-Age', '86400');
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
$this->_response->setHeader('Access-Control-Allow-Credentials', 'true');
$this->_response->setHeader('Access-Control-Allow-Headers', 'Authorization, X-Authorization, Origin, Accept, Content-Type, X-Requested-With, X-HTTP-Method-Override');

// process module apis
$this->handlePathInfo($request);
// process module APIs
$this->handlePathInfo($request);

$class = $this->getReflectionClass($request);
$class = $this->getReflectionClass($request);

if ($this->isRestClass($class))
{
// set config settings from application.ini
$this->setConfig();
if ($this->isRestClass($class)) {
// set config settings from application.ini
$this->setConfig();

// set response format
$this->setResponseFormat($request);
// set response format
$this->setResponseFormat($request);

// process requested action
$this->handleActions($request);
// process requested action
$this->handleActions($request);

// process request body
$this->handleRequestBody($request);
}
// process request body
$this->handleRequestBody($request);
}
}
}
}

/**
* Parse PathInfo in the orginal request and then alter the original request
* based on the valid Midas Restful URI format:
* based on the valid RESTful API URI format:
* /rest[/{moduleName}]/{controllerName}[/{methodName}][/{Id}]
* note: [] means optinal parts.
*/
private function handlePathInfo(Zend_Controller_Request_Abstract $request)
{
$tokens = preg_split('@/@', $request->getPathInfo(), NULL, PREG_SPLIT_NO_EMPTY);
array_shift($tokens); // remove 'rest' prefix
if(!empty($tokens))
{
if(in_array($tokens[0], Zend_Registry::get('modulesHaveApi')))
{
$apiModuleName = 'api' . array_shift($tokens);
$controllerName = array_shift($tokens);
$request->setParam('module', $apiModuleName);
$request->setParam('controller', $controllerName);
$request->setModuleName($apiModuleName);
$request->setControllerName($controllerName);
// remove redundant parameter generated by Zend routing
$request->setParam($controllerName, NULL);
}
else
{
array_shift($tokens); // remove controllerName
}
// handle method
if(!empty($tokens) && !is_numeric($tokens[0]))
{
$methodName = array_shift($tokens);
$request->setParam('method', $methodName);
// remove redundant parameter generated by Zend routing
$request->setParam($methodName, NULL);
$request->setParam('id', NULL);
}
// forward to index action if id is not provided
$action = $request->getActionName();
if(empty($tokens) && ($action == "get" || $action == "index"))
{
$request->setActionName("index");
}
else if(empty($tokens) && ($action == "post" || $action == "put"))
{
$request->setActionName("post");
}
else if(!empty($tokens) && is_numeric($tokens[0]))
{
$request->setParam('id', array_shift($tokens));
}
else
{
$this->_response->setHttpResponseCode(400); //400 Bad Request
throw new Exception('The Webapi ' . $request->getPathInfo() . ' is not supported.', 400);
}
{
$tokens = preg_split('@/@', $request->getPathInfo(), null, PREG_SPLIT_NO_EMPTY);
array_shift($tokens); // remove 'rest' prefix
if (!empty($tokens)) {
if (in_array($tokens[0], Zend_Registry::get('modulesHaveApi'))) {
$apiModuleName = 'api' . array_shift($tokens);
$controllerName = array_shift($tokens);
$request->setParam('module', $apiModuleName);
$request->setParam('controller', $controllerName);
$request->setModuleName($apiModuleName);
$request->setControllerName($controllerName);
// remove redundant parameter generated by Zend routing
$request->setParam($controllerName, null);
} else {
array_shift($tokens); // remove controllerName
}
// handle method
if (!empty($tokens) && !is_numeric($tokens[0])) {
$methodName = array_shift($tokens);
$request->setParam('method', $methodName);
// remove redundant parameter generated by Zend routing
$request->setParam($methodName, null);
$request->setParam('id', null);
}
// forward to index action if id is not provided
$action = $request->getActionName();
if (empty($tokens) && ($action == 'get' || $action == 'index')) {
$request->setActionName('index');
} else if (empty($tokens) && ($action == 'post' || $action == 'put')) {
$request->setActionName('post');
} else if (!empty($tokens) && is_numeric($tokens[0])) {
$request->setParam('id', array_shift($tokens));
} else {
$this->_response->setHttpResponseCode(400); // 400 Bad Request
throw new Exception('The web API ' . $request->getPathInfo() . ' is not supported.', 400);
}
}
}
}

private function setConfig()
{
Expand Down Expand Up @@ -176,7 +162,7 @@ private function setResponseFormat(Zend_Controller_Request_Abstract $request)
} else {
$bestMimeType = $this->negotiateContentType($request);

// if there's no matching MimeType, assign default json
// if there's no matching MimeType, assign default JSON
if (!$bestMimeType || $bestMimeType == '*/*') {
$bestMimeType = 'application/json';
}
Expand Down Expand Up @@ -211,7 +197,7 @@ private function handleActions(Zend_Controller_Request_Abstract $request)

if ($name == '__CALL' and $method->class != 'Zend_Controller_Action') {
$actions[] = $request->getMethod();
} elseif (substr($name, -6) == 'ACTION' and $name != 'INDEXACTION' and $name != 'CALLCOREACTION') {
} elseif (substr($name, -6) == 'ACTION' and $name != 'INDEXACTION') {
$actions[] = str_replace('ACTION', null, $name);
}
}
Expand Down Expand Up @@ -361,6 +347,9 @@ private function getReflectionClass(Zend_Controller_Request_Abstract $request)
if ($this->reflectionClass === null) {
// get the dispatcher to load the controller class
$controller = $this->dispatcher->getControllerClass($request);
// if no controller present escape silently...
if ($controller === false) return false;
// ... load controller class
$className = $this->dispatcher->loadClass($controller);

// extract the actions through reflection
Expand Down
35 changes: 18 additions & 17 deletions library/REST/LICENSE
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
Copyright (c) 2011 Code in Chaos Inc. http://www.codeinchaos.com
The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
Copyright (c) 2014 Ahmad Nassri. http://ahmadnassri.com

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading

0 comments on commit 8cbd95e

Please sign in to comment.