Server.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Json
  17. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * @see Zend_Server_Abstract
  23. */
  24. require_once 'Zend/Server/Abstract.php';
  25. /**
  26. * @category Zend
  27. * @package Zend_Json
  28. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  29. * @license http://framework.zend.com/license/new-bsd New BSD License
  30. */
  31. class Zend_Json_Server extends Zend_Server_Abstract
  32. {
  33. /**#@+
  34. * Version Constants
  35. * @const string
  36. */
  37. const VERSION_1 = '1.0';
  38. const VERSION_2 = '2.0';
  39. /**#@-*/
  40. /**
  41. * Flag: whether or not to auto-emit the response
  42. * @var bool
  43. */
  44. protected $_autoEmitResponse = true;
  45. /**
  46. * @var bool Flag; allow overwriting existing methods when creating server definition
  47. */
  48. protected $_overwriteExistingMethods = true;
  49. /**
  50. * Request object
  51. * @var Zend_Json_Server_Request
  52. */
  53. protected $_request;
  54. /**
  55. * Response object
  56. * @var Zend_Json_Server_Response
  57. */
  58. protected $_response;
  59. /**
  60. * SMD object
  61. * @var Zend_Json_Server_Smd
  62. */
  63. protected $_serviceMap;
  64. /**
  65. * SMD class accessors
  66. * @var array
  67. */
  68. protected $_smdMethods;
  69. /**
  70. * @var Zend_Server_Description
  71. */
  72. protected $_table;
  73. /**
  74. * Attach a function or callback to the server
  75. *
  76. * @param string|array $function Valid PHP callback
  77. * @param string $namespace Ignored
  78. * @return Zend_Json_Server
  79. */
  80. public function addFunction($function, $namespace = '')
  81. {
  82. if (!is_string($function) && (!is_array($function) || (2 > count($function)))) {
  83. require_once 'Zend/Json/Server/Exception.php';
  84. throw new Zend_Json_Server_Exception('Unable to attach function; invalid');
  85. }
  86. if (!is_callable($function)) {
  87. require_once 'Zend/Json/Server/Exception.php';
  88. throw new Zend_Json_Server_Exception('Unable to attach function; does not exist');
  89. }
  90. $argv = null;
  91. if (2 < func_num_args()) {
  92. $argv = func_get_args();
  93. $argv = array_slice($argv, 2);
  94. }
  95. require_once 'Zend/Server/Reflection.php';
  96. if (is_string($function)) {
  97. $method = Zend_Server_Reflection::reflectFunction($function, $argv, $namespace);
  98. } else {
  99. $class = array_shift($function);
  100. $action = array_shift($function);
  101. $reflection = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
  102. $methods = $reflection->getMethods();
  103. $found = false;
  104. foreach ($methods as $method) {
  105. if ($action == $method->getName()) {
  106. $found = true;
  107. break;
  108. }
  109. }
  110. if (!$found) {
  111. $this->fault('Method not found', -32601);
  112. return $this;
  113. }
  114. }
  115. $definition = $this->_buildSignature($method);
  116. $this->_addMethodServiceMap($definition);
  117. return $this;
  118. }
  119. /**
  120. * Register a class with the server
  121. *
  122. * @param string $class
  123. * @param string $namespace Ignored
  124. * @param mixed $argv Ignored
  125. * @return Zend_Json_Server
  126. */
  127. public function setClass($class, $namespace = '', $argv = null)
  128. {
  129. $argv = null;
  130. if (3 < func_num_args()) {
  131. $argv = func_get_args();
  132. $argv = array_slice($argv, 3);
  133. }
  134. require_once 'Zend/Server/Reflection.php';
  135. $reflection = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
  136. foreach ($reflection->getMethods() as $method) {
  137. $definition = $this->_buildSignature($method, $class);
  138. $this->_addMethodServiceMap($definition);
  139. }
  140. return $this;
  141. }
  142. /**
  143. * Indicate fault response
  144. *
  145. * @param string $fault
  146. * @param int $code
  147. * @return false
  148. */
  149. public function fault($fault = null, $code = 404, $data = null)
  150. {
  151. require_once 'Zend/Json/Server/Error.php';
  152. $error = new Zend_Json_Server_Error($fault, $code, $data);
  153. $this->getResponse()->setError($error);
  154. return $error;
  155. }
  156. /**
  157. * Handle request
  158. *
  159. * @param Zend_Json_Server_Request $request
  160. * @return null|Zend_Json_Server_Response
  161. */
  162. public function handle($request = false)
  163. {
  164. if ((false !== $request) && (!$request instanceof Zend_Json_Server_Request)) {
  165. require_once 'Zend/Json/Server/Exception.php';
  166. throw new Zend_Json_Server_Exception('Invalid request type provided; cannot handle');
  167. } elseif ($request) {
  168. $this->setRequest($request);
  169. }
  170. // Handle request
  171. $this->_handle();
  172. // Get response
  173. $response = $this->_getReadyResponse();
  174. // Emit response?
  175. if ($this->autoEmitResponse()) {
  176. echo $response;
  177. return;
  178. }
  179. // or return it?
  180. return $response;
  181. }
  182. /**
  183. * Load function definitions
  184. *
  185. * @param array|Zend_Server_Definition $definition
  186. * @return void
  187. */
  188. public function loadFunctions($definition)
  189. {
  190. if (!is_array($definition) && (!$definition instanceof Zend_Server_Definition)) {
  191. require_once 'Zend/Json/Server/Exception.php';
  192. throw new Zend_Json_Server_Exception('Invalid definition provided to loadFunctions()');
  193. }
  194. foreach ($definition as $key => $method) {
  195. $this->_table->addMethod($method, $key);
  196. $this->_addMethodServiceMap($method);
  197. }
  198. }
  199. public function setPersistence($mode)
  200. {
  201. }
  202. /**
  203. * Set request object
  204. *
  205. * @param Zend_Json_Server_Request $request
  206. * @return Zend_Json_Server
  207. */
  208. public function setRequest(Zend_Json_Server_Request $request)
  209. {
  210. $this->_request = $request;
  211. return $this;
  212. }
  213. /**
  214. * Get JSON-RPC request object
  215. *
  216. * @return Zend_Json_Server_Request
  217. */
  218. public function getRequest()
  219. {
  220. if (null === ($request = $this->_request)) {
  221. require_once 'Zend/Json/Server/Request/Http.php';
  222. $this->setRequest(new Zend_Json_Server_Request_Http());
  223. }
  224. return $this->_request;
  225. }
  226. /**
  227. * Set response object
  228. *
  229. * @param Zend_Json_Server_Response $response
  230. * @return Zend_Json_Server
  231. */
  232. public function setResponse(Zend_Json_Server_Response $response)
  233. {
  234. $this->_response = $response;
  235. return $this;
  236. }
  237. /**
  238. * Get response object
  239. *
  240. * @return Zend_Json_Server_Response
  241. */
  242. public function getResponse()
  243. {
  244. if (null === ($response = $this->_response)) {
  245. require_once 'Zend/Json/Server/Response/Http.php';
  246. $this->setResponse(new Zend_Json_Server_Response_Http());
  247. }
  248. return $this->_response;
  249. }
  250. /**
  251. * Set flag indicating whether or not to auto-emit response
  252. *
  253. * @param bool $flag
  254. * @return Zend_Json_Server
  255. */
  256. public function setAutoEmitResponse($flag)
  257. {
  258. $this->_autoEmitResponse = (bool) $flag;
  259. return $this;
  260. }
  261. /**
  262. * Will we auto-emit the response?
  263. *
  264. * @return bool
  265. */
  266. public function autoEmitResponse()
  267. {
  268. return $this->_autoEmitResponse;
  269. }
  270. // overloading for SMD metadata
  271. /**
  272. * Overload to accessors of SMD object
  273. *
  274. * @param string $method
  275. * @param array $args
  276. * @return mixed
  277. */
  278. public function __call($method, $args)
  279. {
  280. if (preg_match('/^(set|get)/', $method, $matches)) {
  281. if (in_array($method, $this->_getSmdMethods())) {
  282. if ('set' == $matches[1]) {
  283. $value = array_shift($args);
  284. $this->getServiceMap()->$method($value);
  285. return $this;
  286. } else {
  287. return $this->getServiceMap()->$method();
  288. }
  289. }
  290. }
  291. return null;
  292. }
  293. /**
  294. * Retrieve SMD object
  295. *
  296. * @return Zend_Json_Server_Smd
  297. */
  298. public function getServiceMap()
  299. {
  300. if (null === $this->_serviceMap) {
  301. require_once 'Zend/Json/Server/Smd.php';
  302. $this->_serviceMap = new Zend_Json_Server_Smd();
  303. }
  304. return $this->_serviceMap;
  305. }
  306. /**
  307. * Add service method to service map
  308. *
  309. * @param Zend_Server_Reflection_Function $method
  310. * @return void
  311. */
  312. protected function _addMethodServiceMap(Zend_Server_Method_Definition $method)
  313. {
  314. $serviceInfo = array(
  315. 'name' => $method->getName(),
  316. 'return' => $this->_getReturnType($method),
  317. );
  318. $params = $this->_getParams($method);
  319. $serviceInfo['params'] = $params;
  320. $serviceMap = $this->getServiceMap();
  321. if (false !== $serviceMap->getService($serviceInfo['name'])) {
  322. $serviceMap->removeService($serviceInfo['name']);
  323. }
  324. $serviceMap->addService($serviceInfo);
  325. }
  326. /**
  327. * Translate PHP type to JSON type
  328. *
  329. * @param string $type
  330. * @return string
  331. */
  332. protected function _fixType($type)
  333. {
  334. return $type;
  335. }
  336. /**
  337. * Get default params from signature
  338. *
  339. * @param array $args
  340. * @param array $params
  341. * @return array
  342. */
  343. protected function _getDefaultParams(array $args, array $params)
  344. {
  345. $defaultParams = array_slice($params, count($args));
  346. foreach ($defaultParams as $param) {
  347. $value = null;
  348. if (array_key_exists('default', $param)) {
  349. $value = $param['default'];
  350. }
  351. array_push($args, $value);
  352. }
  353. return $args;
  354. }
  355. /**
  356. * Get method param type
  357. *
  358. * @param Zend_Server_Reflection_Function_Abstract $method
  359. * @return string|array
  360. */
  361. protected function _getParams(Zend_Server_Method_Definition $method)
  362. {
  363. $params = array();
  364. foreach ($method->getPrototypes() as $prototype) {
  365. foreach ($prototype->getParameterObjects() as $key => $parameter) {
  366. if (!isset($params[$key])) {
  367. $params[$key] = array(
  368. 'type' => $parameter->getType(),
  369. 'name' => $parameter->getName(),
  370. 'optional' => $parameter->isOptional(),
  371. );
  372. if (null !== ($default = $parameter->getDefaultValue())) {
  373. $params[$key]['default'] = $default;
  374. }
  375. $description = $parameter->getDescription();
  376. if (!empty($description)) {
  377. $params[$key]['description'] = $description;
  378. }
  379. continue;
  380. }
  381. $newType = $parameter->getType();
  382. if (!is_array($params[$key]['type'])) {
  383. if ($params[$key]['type'] == $newType) {
  384. continue;
  385. }
  386. $params[$key]['type'] = (array) $params[$key]['type'];
  387. } elseif (in_array($newType, $params[$key]['type'])) {
  388. continue;
  389. }
  390. array_push($params[$key]['type'], $parameter->getType());
  391. }
  392. }
  393. return $params;
  394. }
  395. /**
  396. * Set response state
  397. *
  398. * @return Zend_Json_Server_Response
  399. */
  400. protected function _getReadyResponse()
  401. {
  402. $request = $this->getRequest();
  403. $response = $this->getResponse();
  404. $response->setServiceMap($this->getServiceMap());
  405. if (null !== ($id = $request->getId())) {
  406. $response->setId($id);
  407. }
  408. if (null !== ($version = $request->getVersion())) {
  409. $response->setVersion($version);
  410. }
  411. return $response;
  412. }
  413. /**
  414. * Get method return type
  415. *
  416. * @param Zend_Server_Reflection_Function_Abstract $method
  417. * @return string|array
  418. */
  419. protected function _getReturnType(Zend_Server_Method_Definition $method)
  420. {
  421. $return = array();
  422. foreach ($method->getPrototypes() as $prototype) {
  423. $return[] = $prototype->getReturnType();
  424. }
  425. if (1 == count($return)) {
  426. return $return[0];
  427. }
  428. return $return;
  429. }
  430. /**
  431. * Retrieve list of allowed SMD methods for proxying
  432. *
  433. * @return array
  434. */
  435. protected function _getSmdMethods()
  436. {
  437. if (null === $this->_smdMethods) {
  438. $this->_smdMethods = array();
  439. require_once 'Zend/Json/Server/Smd.php';
  440. $methods = get_class_methods('Zend_Json_Server_Smd');
  441. foreach ($methods as $key => $method) {
  442. if (!preg_match('/^(set|get)/', $method)) {
  443. continue;
  444. }
  445. if (strstr($method, 'Service')) {
  446. continue;
  447. }
  448. $this->_smdMethods[] = $method;
  449. }
  450. }
  451. return $this->_smdMethods;
  452. }
  453. /**
  454. * Internal method for handling request
  455. *
  456. * @return void
  457. */
  458. protected function _handle()
  459. {
  460. $request = $this->getRequest();
  461. if (!$request->isMethodError() && (null === $request->getMethod())) {
  462. return $this->fault('Invalid Request', -32600);
  463. }
  464. if ($request->isMethodError()) {
  465. return $this->fault('Invalid Request', -32600);
  466. }
  467. $method = $request->getMethod();
  468. if (!$this->_table->hasMethod($method)) {
  469. return $this->fault('Method not found', -32601);
  470. }
  471. $params = $request->getParams();
  472. $invocable = $this->_table->getMethod($method);
  473. $serviceMap = $this->getServiceMap();
  474. $service = $serviceMap->getService($method);
  475. $serviceParams = $service->getParams();
  476. if (count($params) < count($serviceParams)) {
  477. $params = $this->_getDefaultParams($params, $serviceParams);
  478. }
  479. try {
  480. $result = $this->_dispatch($invocable, $params);
  481. } catch (Exception $e) {
  482. return $this->fault($e->getMessage(), $e->getCode());
  483. }
  484. $this->getResponse()->setResult($result);
  485. }
  486. }