You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DocBlock.php 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: robin
  5. * Date: 10/22/15
  6. * Time: 9:59 PM
  7. */
  8. namespace Luticate\Doc\Business;
  9. use Exception;
  10. class DocBlock {
  11. public $docblock;
  12. public $description = null;
  13. public $all_params = array();
  14. /**
  15. * Parses a docblock;
  16. */
  17. function __construct($docblock)
  18. {
  19. if (!is_string($docblock)) {
  20. throw new Exception("DocBlock expects first parameter to be a string");
  21. }
  22. $this->docblock = $docblock;
  23. $this->parse_block();
  24. }
  25. /**
  26. * An alias to __call();
  27. * allows a better DSL
  28. *
  29. * @param string $param_name
  30. * @return mixed
  31. */
  32. public function __get($param_name) {
  33. return $this->$param_name();
  34. }
  35. /**
  36. * Checks if the param exists
  37. *
  38. * @param string $param_name
  39. * @return mixed
  40. */
  41. public function __call($param_name, $values = null)
  42. {
  43. if ($param_name == "description") {
  44. return $this->description;
  45. }
  46. else if (isset($this->all_params[$param_name])) {
  47. $params = $this->all_params[$param_name];
  48. if (count($params) == 1) {
  49. return $params[0];
  50. }
  51. else {
  52. return $params;
  53. }
  54. }
  55. return null;
  56. }
  57. /**
  58. * Parse each line in the docblock
  59. * and store the params in `$this->all_params`
  60. * and the rest in `$this->description`
  61. */
  62. private function parse_block() {
  63. foreach(preg_split("/(\r?\n)/", $this->docblock) as $line) {
  64. if (preg_match('/^(?=\s+?\*[^\/])(.+)/', $line, $matches)) {
  65. $info = $matches[1];
  66. $info = trim($info);
  67. $info = preg_replace('/^(\*\s+?)/', '', $info);
  68. if ($info[0] !== "@") {
  69. $this->description .= "\n$info";
  70. }
  71. else if (preg_match('/@param +([^ ]+) +([^ ]+) +(.*)$/', $info, $matches) == 1) {
  72. if ($matches[1][0] == "$") {
  73. $param_name = $matches[1];
  74. $param_type = $matches[2];
  75. }
  76. else {
  77. $param_name = $matches[2];
  78. $param_type = $matches[1];
  79. }
  80. $value = $matches[3];
  81. $param_name = substr($param_name, 1);
  82. $this->all_params[$param_name] = [
  83. "name" => $param_name,
  84. "type" => $param_type,
  85. "description" => $value
  86. ];
  87. }
  88. }
  89. }
  90. }
  91. }