|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Created by PhpStorm. |
| 4 | + * User: inhere |
| 5 | + * Date: 2019-01-06 |
| 6 | + * Time: 00:09 |
| 7 | + */ |
| 8 | + |
| 9 | +namespace Toolkit\PhpUtil; |
| 10 | + |
| 11 | +/** |
| 12 | + * Class PhpDoc |
| 13 | + * @package Toolkit\PhpUtil |
| 14 | + */ |
| 15 | +class PhpDoc |
| 16 | +{ |
| 17 | + /** |
| 18 | + * 以下三个方法来自 yii2 console/Controller.php 做了一些调整 |
| 19 | + */ |
| 20 | + |
| 21 | + /** |
| 22 | + * Parses the comment block into tags. |
| 23 | + * @param string $comment The comment block text |
| 24 | + * @param array $ignored |
| 25 | + * @return array The parsed tags |
| 26 | + */ |
| 27 | + public static function getTags(string $comment, array $ignored = ['param', 'return']): array |
| 28 | + { |
| 29 | + $comment = (string)\str_replace("\r\n", "\n", \trim($comment, "/ \n")); |
| 30 | + $comment = "@description \n" . \str_replace("\r", '', |
| 31 | + \trim(\preg_replace('/^\s*\**( |\t)?/m', '', $comment)) |
| 32 | + ); |
| 33 | + |
| 34 | + $tags = []; |
| 35 | + $parts = \preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY); |
| 36 | + |
| 37 | + foreach ($parts as $part) { |
| 38 | + if (\preg_match('/^(\w+)(.*)/ms', \trim($part), $matches)) { |
| 39 | + $name = $matches[1]; |
| 40 | + if (\in_array($name, $ignored, true)) { |
| 41 | + continue; |
| 42 | + } |
| 43 | + |
| 44 | + if (!isset($tags[$name])) { |
| 45 | + $tags[$name] = \trim($matches[2]); |
| 46 | + } elseif (\is_array($tags[$name])) { |
| 47 | + $tags[$name][] = \trim($matches[2]); |
| 48 | + } else { |
| 49 | + $tags[$name] = [$tags[$name], \trim($matches[2])]; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return $tags; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Returns the first line of docBlock. |
| 59 | + * |
| 60 | + * @param string $comment |
| 61 | + * @return string |
| 62 | + */ |
| 63 | + public static function firstLine(string $comment): string |
| 64 | + { |
| 65 | + $docLines = \preg_split('~\R~u', $comment); |
| 66 | + |
| 67 | + if (isset($docLines[1])) { |
| 68 | + return \trim($docLines[1], "/\t *"); |
| 69 | + } |
| 70 | + |
| 71 | + return ''; |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * Returns full description from the doc-block. |
| 76 | + * If have multi line text, will return multi line. |
| 77 | + * |
| 78 | + * @param string $comment |
| 79 | + * @return string |
| 80 | + */ |
| 81 | + public static function description(string $comment): string |
| 82 | + { |
| 83 | + $comment = (string)\str_replace("\r", '', \trim(\preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/')))); |
| 84 | + |
| 85 | + if (\preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) { |
| 86 | + $comment = \trim(\substr($comment, 0, $matches[0][1])); |
| 87 | + } |
| 88 | + |
| 89 | + return $comment; |
| 90 | + } |
| 91 | +} |
0 commit comments