PageRenderTime 22ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/webservice/classes/rest/reflection/function/Abstract.php

https://github.com/jpbauer/knowledgetree
PHP | 479 lines | 247 code | 54 blank | 178 comment | 36 complexity | 1d1a2308328cc1c9dc331e3d2664d053 MD5 | raw file
Possible License(s): GPL-3.0, Apache-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Rest_Reflection_Node
  4. */
  5. require_once 'classes/rest/reflection/Node.php';
  6. /**
  7. * Rest_Reflection_Parameter
  8. */
  9. require_once 'classes/rest/reflection/Parameter.php';
  10. /**
  11. * Rest_Reflection_Prototype
  12. */
  13. require_once 'classes/rest/reflection/Prototype.php';
  14. /**
  15. * Function/Method Reflection
  16. *
  17. * Decorates a ReflectionFunction. Allows setting and retrieving an alternate
  18. * 'service' name (i.e., the name to be used when calling via a service),
  19. * setting and retrieving the description (originally set using the docblock
  20. * contents), retrieving the callback and callback type, retrieving additional
  21. * method invocation arguments, and retrieving the
  22. * method
  23. *
  24. */
  25. abstract class Rest_Reflection_Function_Abstract
  26. {
  27. /**
  28. * @var ReflectionFunction
  29. */
  30. protected $_reflection;
  31. /**
  32. * Additional arguments to pass to method on invocation
  33. * @var array
  34. */
  35. protected $_argv = array();
  36. /**
  37. * Used to store extra configuration for the method (typically done by the
  38. * server class, e.g., to indicate whether or not to instantiate a class).
  39. * Associative array; access is as properties via {@link __get()} and
  40. * {@link __set()}
  41. * @var array
  42. */
  43. protected $_config = array();
  44. /**
  45. * Declaring class (needed for when serialization occurs)
  46. * @var string
  47. */
  48. protected $_class;
  49. /**
  50. * Function/method description
  51. * @var string
  52. */
  53. protected $_description = '';
  54. /**
  55. * Namespace with which to prefix function/method name
  56. * @var string
  57. */
  58. protected $_namespace;
  59. /**
  60. * Prototypes
  61. * @var array
  62. */
  63. protected $_prototypes = array();
  64. private $_return;
  65. private $_returnDesc;
  66. private $_paramDesc;
  67. private $_sigParams;
  68. private $_sigParamsDepth;
  69. /**
  70. * Constructor
  71. *
  72. * @param ReflectionFunction $r
  73. */
  74. public function __construct(Reflector $r, $namespace = null, $argv = array())
  75. {
  76. // In PHP 5.1.x, ReflectionMethod extends ReflectionFunction. In 5.2.x,
  77. // both extend ReflectionFunctionAbstract. So, we can't do normal type
  78. // hinting in the prototype, but instead need to do some explicit
  79. // testing here.
  80. if ((!$r instanceof ReflectionFunction)
  81. && (!$r instanceof ReflectionMethod)) {
  82. require_once 'classes/rest/Exception.php';
  83. throw new Rest_Exception('Invalid reflection class');
  84. }
  85. $this->_reflection = $r;
  86. // Determine namespace
  87. if (null !== $namespace){
  88. $this->setNamespace($namespace);
  89. }
  90. // Determine arguments
  91. if (is_array($argv)) {
  92. $this->_argv = $argv;
  93. }
  94. // If method call, need to store some info on the class
  95. if ($r instanceof ReflectionMethod) {
  96. $this->_class = $r->getDeclaringClass()->getName();
  97. }
  98. // Perform some introspection
  99. $this->_reflect();
  100. }
  101. /**
  102. * Create signature node tree
  103. *
  104. * Recursive method to build the signature node tree. Increments through
  105. * each array in {@link $_sigParams}, adding every value of the next level
  106. * to the current value (unless the current value is null).
  107. *
  108. * @param Rest_Reflection_Node $parent
  109. * @param int $level
  110. * @return void
  111. */
  112. protected function _addTree(Rest_Reflection_Node $parent, $level = 0)
  113. {
  114. if ($level >= $this->_sigParamsDepth) {
  115. return;
  116. }
  117. foreach ($this->_sigParams[$level] as $value) {
  118. $node = new Rest_Reflection_Node($value, $parent);
  119. if ((null !== $value) && ($this->_sigParamsDepth > $level + 1)) {
  120. $this->_addTree($node, $level + 1);
  121. }
  122. }
  123. }
  124. /**
  125. * Build the signature tree
  126. *
  127. * Builds a signature tree starting at the return values and descending
  128. * through each method argument. Returns an array of
  129. * {@link Rest_Reflection_Node}s.
  130. *
  131. * @return array
  132. */
  133. protected function _buildTree()
  134. {
  135. $returnTree = array();
  136. foreach ((array) $this->_return as $value) {
  137. $node = new Rest_Reflection_Node($value);
  138. $this->_addTree($node);
  139. $returnTree[] = $node;
  140. }
  141. return $returnTree;
  142. }
  143. /**
  144. * Build method signatures
  145. *
  146. * Builds method signatures using the array of return types and the array of
  147. * parameters types
  148. *
  149. * @param array $return Array of return types
  150. * @param string $returnDesc Return value description
  151. * @param array $params Array of arguments (each an array of types)
  152. * @param array $paramDesc Array of parameter descriptions
  153. * @return array
  154. */
  155. protected function _buildSignatures($return, $returnDesc, $paramTypes, $paramDesc)
  156. {
  157. $this->_return = $return;
  158. $this->_returnDesc = $returnDesc;
  159. $this->_paramDesc = $paramDesc;
  160. $this->_sigParams = $paramTypes;
  161. $this->_sigParamsDepth = count($paramTypes);
  162. $signatureTrees = $this->_buildTree();
  163. $signatures = array();
  164. $endPoints = array();
  165. foreach ($signatureTrees as $root) {
  166. $tmp = $root->getEndPoints();
  167. if (empty($tmp)) {
  168. $endPoints = array_merge($endPoints, array($root));
  169. } else {
  170. $endPoints = array_merge($endPoints, $tmp);
  171. }
  172. }
  173. foreach ($endPoints as $node) {
  174. if (!$node instanceof Rest_Reflection_Node) {
  175. continue;
  176. }
  177. $signature = array();
  178. do {
  179. array_unshift($signature, $node->getValue());
  180. $node = $node->getParent();
  181. } while ($node instanceof Rest_Reflection_Node);
  182. $signatures[] = $signature;
  183. }
  184. // Build prototypes
  185. $params = $this->_reflection->getParameters();
  186. foreach ($signatures as $signature) {
  187. $return = new Rest_Reflection_ReturnValue(array_shift($signature), $this->_returnDesc);
  188. $tmp = array();
  189. foreach ($signature as $key => $type) {
  190. $param = new Rest_Reflection_Parameter($params[$key], $type, $this->_paramDesc[$key]);
  191. $param->setPosition($key);
  192. $tmp[] = $param;
  193. }
  194. $this->_prototypes[] = new Rest_Reflection_Prototype($return, $tmp);
  195. }
  196. }
  197. /**
  198. * Use code reflection to create method signatures
  199. *
  200. * Determines the method help/description text from the function DocBlock
  201. * comment. Determines method signatures using a combination of
  202. * ReflectionFunction and parsing of DocBlock @param and @return values.
  203. *
  204. * @param ReflectionFunction $function
  205. * @return array
  206. */
  207. protected function _reflect()
  208. {
  209. $function = $this->_reflection;
  210. $helpText = '';
  211. $signatures = array();
  212. $returnDesc = '';
  213. $paramCount = $function->getNumberOfParameters();
  214. $paramCountRequired = $function->getNumberOfRequiredParameters();
  215. $parameters = $function->getParameters();
  216. $docBlock = $function->getDocComment();
  217. if (!empty($docBlock)) {
  218. // Get help text
  219. if (preg_match(':/\*\*\s*\r?\n\s*\*\s(.*?)\r?\n\s*\*(\s@|/):s', $docBlock, $matches))
  220. {
  221. $helpText = $matches[1];
  222. $helpText = preg_replace('/(^\s*\*\s)/m', '', $helpText);
  223. $helpText = preg_replace('/\r?\n\s*\*\s*(\r?\n)*/s', "\n", $helpText);
  224. $helpText = trim($helpText);
  225. }
  226. // Get return type(s) and description
  227. $return = 'void';
  228. if (preg_match('/@return\s+(\S+)/', $docBlock, $matches)) {
  229. $return = explode('|', $matches[1]);
  230. if (preg_match('/@return\s+\S+\s+(.*?)(@|\*\/)/s', $docBlock, $matches))
  231. {
  232. $value = $matches[1];
  233. $value = preg_replace('/\s?\*\s/m', '', $value);
  234. $value = preg_replace('/\s{2,}/', ' ', $value);
  235. $returnDesc = trim($value);
  236. }
  237. }
  238. // Get param types and description
  239. if (preg_match_all('/@param\s+([^\s]+)/m', $docBlock, $matches)) {
  240. $paramTypesTmp = $matches[1];
  241. if (preg_match_all('/@param\s+\S+\s+(\$^\S+)\s+(.*?)(@|\*\/)/s', $docBlock, $matches))
  242. {
  243. $paramDesc = $matches[2];
  244. foreach ($paramDesc as $key => $value) {
  245. $value = preg_replace('/\s?\*\s/m', '', $value);
  246. $value = preg_replace('/\s{2,}/', ' ', $value);
  247. $paramDesc[$key] = trim($value);
  248. }
  249. }
  250. }
  251. } else {
  252. $helpText = $function->getName();
  253. $return = 'void';
  254. }
  255. // Set method description
  256. $this->setDescription($helpText);
  257. // Get all param types as arrays
  258. if (!isset($paramTypesTmp) && (0 < $paramCount)) {
  259. $paramTypesTmp = array_fill(0, $paramCount, 'mixed');
  260. } elseif (!isset($paramTypesTmp)) {
  261. $paramTypesTmp = array();
  262. } elseif (count($paramTypesTmp) < $paramCount) {
  263. $start = $paramCount - count($paramTypesTmp);
  264. for ($i = $start; $i < $paramCount; ++$i) {
  265. $paramTypesTmp[$i] = 'mixed';
  266. }
  267. }
  268. // Get all param descriptions as arrays
  269. if (!isset($paramDesc) && (0 < $paramCount)) {
  270. $paramDesc = array_fill(0, $paramCount, '');
  271. } elseif (!isset($paramDesc)) {
  272. $paramDesc = array();
  273. } elseif (count($paramDesc) < $paramCount) {
  274. $start = $paramCount - count($paramDesc);
  275. for ($i = $start; $i < $paramCount; ++$i) {
  276. $paramDesc[$i] = '';
  277. }
  278. }
  279. if (count($paramTypesTmp) != $paramCount) {
  280. require_once 'classes/rest/Exception.php';
  281. throw new Rest_Exception(
  282. 'Variable number of arguments is not supported for services (except optional parameters). '
  283. . 'Number of function arguments must currespond to actual number of arguments described in a docblock.');
  284. }
  285. $paramTypes = array();
  286. foreach ($paramTypesTmp as $i => $param) {
  287. $tmp = explode('|', $param);
  288. if ($parameters[$i]->isOptional()) {
  289. array_unshift($tmp, null);
  290. }
  291. $paramTypes[] = $tmp;
  292. }
  293. $this->_buildSignatures($return, $returnDesc, $paramTypes, $paramDesc);
  294. }
  295. /**
  296. * Proxy reflection calls
  297. *
  298. * @param string $method
  299. * @param array $args
  300. * @return mixed
  301. */
  302. public function __call($method, $args)
  303. {
  304. if (method_exists($this->_reflection, $method)) {
  305. return call_user_func_array(array($this->_reflection, $method), $args);
  306. }
  307. require_once 'classes/rest/Exception.php';
  308. throw new Rest_Exception('Invalid reflection method ("' .$method. '")');
  309. }
  310. /**
  311. * Retrieve configuration parameters
  312. *
  313. * Values are retrieved by key from {@link $_config}. Returns null if no
  314. * value found.
  315. *
  316. * @param string $key
  317. * @return mixed
  318. */
  319. public function __get($key)
  320. {
  321. if (isset($this->_config[$key])) {
  322. return $this->_config[$key];
  323. }
  324. return null;
  325. }
  326. /**
  327. * Set configuration parameters
  328. *
  329. * Values are stored by $key in {@link $_config}.
  330. *
  331. * @param string $key
  332. * @param mixed $value
  333. * @return void
  334. */
  335. public function __set($key, $value)
  336. {
  337. $this->_config[$key] = $value;
  338. }
  339. /**
  340. * Set method's namespace
  341. *
  342. * @param string $namespace
  343. * @return void
  344. */
  345. public function setNamespace($namespace)
  346. {
  347. if (empty($namespace)) {
  348. $this->_namespace = '';
  349. return;
  350. }
  351. if (!is_string($namespace) || !preg_match('/[a-z0-9_\.]+/i', $namespace)) {
  352. require_once 'classes/rest/Exception.php';
  353. throw new Rest_Exception('Invalid namespace');
  354. }
  355. $this->_namespace = $namespace;
  356. }
  357. /**
  358. * Return method's namespace
  359. *
  360. * @return string
  361. */
  362. public function getNamespace()
  363. {
  364. return $this->_namespace;
  365. }
  366. /**
  367. * Set the description
  368. *
  369. * @param string $string
  370. * @return void
  371. */
  372. public function setDescription($string)
  373. {
  374. if (!is_string($string)) {
  375. require_once 'classes/rest/Exception.php';
  376. throw new Rest_Exception('Invalid description');
  377. }
  378. $this->_description = $string;
  379. }
  380. /**
  381. * Retrieve the description
  382. *
  383. * @return void
  384. */
  385. public function getDescription()
  386. {
  387. return $this->_description;
  388. }
  389. /**
  390. * Retrieve all prototypes as array of
  391. * {@link Rest_Reflection_Prototype Rest_Reflection_Prototypes}
  392. *
  393. * @return array
  394. */
  395. public function getPrototypes()
  396. {
  397. return $this->_prototypes;
  398. }
  399. /**
  400. * Retrieve additional invocation arguments
  401. *
  402. * @return array
  403. */
  404. public function getInvokeArguments()
  405. {
  406. return $this->_argv;
  407. }
  408. /**
  409. * Wakeup from serialization
  410. *
  411. * Reflection needs explicit instantiation to work correctly. Re-instantiate
  412. * reflection object on wakeup.
  413. *
  414. * @return void
  415. */
  416. public function __wakeup()
  417. {
  418. if ($this->_reflection instanceof ReflectionMethod) {
  419. $class = new ReflectionClass($this->_class);
  420. $this->_reflection = new ReflectionMethod($class->newInstance(), $this->getName());
  421. } else {
  422. $this->_reflection = new ReflectionFunction($this->getName());
  423. }
  424. }
  425. }