Created
July 11, 2012 14:21
-
-
Save pjbeardsley/3090673 to your computer and use it in GitHub Desktop.
fJSONP.php
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 | |
/** | |
* Extension to Flourish fJSON class to provide methods for JSONP support. | |
* | |
* @package Flourish | |
*/ | |
class fJSONP extends fJSON { | |
/** | |
* Overrides fJSON::sendHeader() to send a text/javascript response instead. | |
* | |
* @return void | |
*/ | |
public static function sendHeader() { | |
header('Content-Type: text/javascript'); | |
} | |
/** | |
* Validate a callback name is not a reserved word in JavaScript and does not have | |
* invalid characters. | |
* | |
* @credit http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/ | |
* | |
* @param string $subject The callback name. | |
* @return boolean TRUE if the callback can be used, FALSE otherwise. | |
*/ | |
private static function isValidCallback($subject) { | |
$identifier_syntax = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*+$/u'; | |
$reserved_words = array( | |
'break', | |
'do', | |
'instanceof', | |
'typeof', | |
'case', | |
'else', | |
'new', | |
'var', | |
'catch', | |
'finally', | |
'return', | |
'void', | |
'continue', | |
'for', | |
'switch', | |
'while', | |
'debugger', | |
'function', | |
'this', | |
'with', | |
'default', | |
'if', | |
'throw', | |
'delete', | |
'in', | |
'try', | |
'class', | |
'enum', | |
'extends', | |
'super', | |
'const', | |
'export', | |
'import', | |
'implements', | |
'let', | |
'private', | |
'public', | |
'yield', | |
'interface', | |
'package', | |
'protected', | |
'static', | |
'null', | |
'true', | |
'false', | |
); | |
return preg_match($identifier_syntax, $subject) && !in_array(fUTF8::lower($subject), $reserved_words); | |
} | |
/** | |
* Overrides fJSON::encode() method to wrap around the callback received. | |
* | |
* @throws fValidationException If the callback is invalid. | |
* | |
* @param mixed $data Data to encode. | |
* @param string $callback_name Optional. If not passed, will be retrieved from GET | |
* paramater 'callback'. If no such parameter is found, 'fn' will be used. | |
* @return string Encoded JSONP data. | |
*/ | |
public static function encode($data, $callback = NULL) { | |
if (is_null($callback)) { | |
$callback = fRequest::get('callback', 'string', 'fn'); | |
} | |
if (!self::isValidCallback($callback)) { | |
throw new fValidationException('Invalid callback "'.$callback.'" passed.'); | |
} | |
return $callback.'('.parent::encode($data).');'; | |
} | |
/** | |
* Force use as a static class. | |
* | |
* @return fJSONP | |
*/ | |
private function __construct() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment