|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* |
|
5
|
|
|
* This file is part of the Apix Project. |
|
6
|
|
|
* |
|
7
|
|
|
* (c) Franck Cassedanne <franck at ouarz.net> |
|
8
|
|
|
* |
|
9
|
|
|
* @license http://opensource.org/licenses/BSD-3-Clause New BSD License |
|
10
|
|
|
* |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace Apix\Output; |
|
14
|
|
|
|
|
15
|
|
|
class Jsonp extends AbstractOutput |
|
16
|
|
|
{ |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* {@inheritdoc} |
|
20
|
|
|
* @see http://www.rfc-editor.org/rfc/rfc4329.txt |
|
21
|
|
|
*/ |
|
22
|
|
|
protected $content_type = 'application/javascript'; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* {@inheritdoc} |
|
26
|
|
|
*/ |
|
27
|
|
|
public function encode(array $data, $rootNode=null) |
|
|
|
|
|
|
28
|
|
|
{ |
|
29
|
|
|
$cb = isset($_REQUEST['callback']) && !empty($_REQUEST['callback']) |
|
30
|
|
|
? $_REQUEST['callback'] |
|
31
|
|
|
: $rootNode; |
|
32
|
|
|
$cb = null === $cb ? 'apix' : $cb; |
|
33
|
|
|
|
|
34
|
|
|
if (!$this->isValidIdentifier($cb)) { |
|
35
|
|
|
throw new \InvalidArgumentException( |
|
36
|
|
|
sprintf('Invalid callback name (%s) used.', $cb) |
|
37
|
|
|
); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
$json = new Json(); |
|
41
|
|
|
$str = $json->encode($data, $rootNode); |
|
42
|
|
|
|
|
43
|
|
|
return "{$cb}({$str});"; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Check wether a callback string name is a valid javascript identifier. |
|
48
|
|
|
* @see http://www.geekality.net/2011/08/03/valid-javascript-identifier/ |
|
49
|
|
|
* @see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf |
|
50
|
|
|
* |
|
51
|
|
|
* @param string $subject |
|
52
|
|
|
* @return boolean |
|
53
|
|
|
*/ |
|
54
|
|
|
public function isValidIdentifier($subject) |
|
55
|
|
|
{ |
|
56
|
|
|
$syntax = '/^[$_\p{L}][$_\p{L}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\x{200C}\x{200D}]*+$/u'; |
|
57
|
|
|
|
|
58
|
|
|
$reserved_words = array('break', 'do', 'instanceof', 'typeof', 'case', |
|
59
|
|
|
'else', 'new', 'var', 'catch', 'finally', 'return', 'void', 'continue', |
|
60
|
|
|
'for', 'switch', 'while', 'debugger', 'function', 'this', 'with', |
|
61
|
|
|
'default', 'if', 'throw', 'delete', 'in', 'try', 'class', 'enum', |
|
62
|
|
|
'extends', 'super', 'const', 'export', 'import', 'implements', 'let', |
|
63
|
|
|
'private', 'public', 'yield', 'interface', 'package', 'protected', |
|
64
|
|
|
'static', 'null', 'true', 'false'); |
|
65
|
|
|
|
|
66
|
|
|
return preg_match($syntax, $subject) |
|
67
|
|
|
&& ! in_array(strtolower($subject), $reserved_words); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
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: