-
-
Save pbowyer/1485534 to your computer and use it in GitHub Desktop.
symfony 1.4 api action class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Extended action class for adding json rendering functionality. | |
* | |
* @author Phil Moorhouse <[email protected]> | |
* @package tlv4 | |
* @subpackage api | |
*/ | |
class tlApiActions extends sfActions | |
{ | |
/** | |
* Forwards the request to the correct api method action based on method param | |
*/ | |
public function executeMethodSwitch(sfWebRequest $request) | |
{ | |
if(!$method = $request->getParameter('method')) | |
{ | |
return $this->renderError("param 'method' is required", 400, $request); | |
} | |
$moduleName = $this->getModuleName(); | |
if(!$this->getController()->actionExists($moduleName, $method)) | |
{ | |
return $this->renderError("method '$moduleName?method=$method' does not exist", 404, $request); | |
} | |
$this->forward($this->getModuleName(), $method); | |
} | |
/** | |
* If the action is accessed directly in dev env then the json will be | |
* dumped to the screen. Otherwise data is returned as JSON or JSONP | |
* with correct headers. | |
*/ | |
public function renderJson($data, $request) | |
{ | |
if(sfConfig::get('sf_environment') == 'dev' && !$this->getRequest()->isXmlHttpRequest()) | |
{ | |
$this->data = $data; | |
$this->setTemplate('debug'); | |
} | |
else | |
{ | |
$this->setLayout(false); | |
if($callback = $request->getParameter('callback')) | |
{ | |
// request is JSONP (cross-domain) so wrap JSON in callback function | |
$this->getResponse()->setHttpHeader('Content-type','text/javascript'); | |
return $this->renderText($callback.'('.json_encode($data).');'); | |
} | |
else | |
{ | |
// request is for pure-JSON | |
$this->getResponse()->setHttpHeader('Content-type','application/json'); | |
return $this->renderText(json_encode($data)); | |
} | |
} | |
} | |
/** | |
* Respond with an error message / status code | |
* | |
* @param string $errorMsg The error message to return | |
* @param int $httpStatusCode The http status code for the response header | |
*/ | |
public function renderError($errorMsg, $httpStatusCode = 500, $request) | |
{ | |
$this->getResponse()->setStatusCode($httpStatusCode); | |
return $this->renderJson(array('error' => $errorMsg), $request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment