1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the silex-annotation-provider package. |
4
|
|
|
* For the full copyright and license information, please view the LICENSE |
5
|
|
|
* file that was distributed with this source code. |
6
|
|
|
* |
7
|
|
|
* @license MIT License |
8
|
|
|
* @copyright (c) 2018, Dana Desrosiers <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
declare(strict_types=1); |
12
|
|
|
|
13
|
|
|
namespace DDesrosiers\SilexAnnotations\AnnotationReader; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class DocBlock parses doc block annotations into an array representation. |
17
|
|
|
* |
18
|
|
|
* @author Dana Desrosiers <[email protected]> |
19
|
|
|
*/ |
20
|
|
|
class DocBlock |
21
|
|
|
{ |
22
|
|
|
const LINE_ENDINGS = ["\r\n","\n\r","\r"]; |
23
|
|
|
|
24
|
|
|
private $docBlockString; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param string $docBlockString |
28
|
|
|
*/ |
29
|
|
|
public function __construct(string $docBlockString) |
30
|
|
|
{ |
31
|
|
|
$this->docBlockString = $docBlockString; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param $annotationName |
36
|
|
|
* @return array|null |
37
|
|
|
*/ |
38
|
|
|
public function parseAnnotation($annotationName): ?array |
39
|
|
|
{ |
40
|
|
|
$annotation = explode("@$annotationName(", $this->docBlockString)[1]; |
41
|
|
|
|
42
|
|
|
if ($annotation === null) { |
43
|
|
|
return null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$def = []; |
47
|
|
|
foreach ($this->splitLines($annotation) as $line) { |
48
|
|
|
$tokens = $this->tokenizeLine($line); |
49
|
|
|
if (strlen($tokens[0]) > 0) { |
50
|
|
|
$def[$tokens[0]][] = (count($tokens) === 1) ? [] : explode(', ', $tokens[1]); |
51
|
|
|
} |
52
|
|
|
if ($this->endsWith($line, ')')) { |
53
|
|
|
break; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
return $def; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param string $str |
62
|
|
|
* @return array |
63
|
|
|
*/ |
64
|
|
|
private function splitLines(string $str): array |
65
|
|
|
{ |
66
|
|
|
return explode("\n", str_replace(self::LINE_ENDINGS,"\n", trim($str))); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param string $str |
71
|
|
|
* @return array |
72
|
|
|
*/ |
73
|
|
|
private function tokenizeLine(string $str): array |
74
|
|
|
{ |
75
|
|
|
$trimmedLine = trim($str, " \t*)"); |
76
|
|
|
|
77
|
|
|
return explode(' => ', $trimmedLine); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @param string $str |
82
|
|
|
* @param string $endsWith (last character) |
83
|
|
|
* @return bool |
84
|
|
|
*/ |
85
|
|
|
private function endsWith(string $str, string $endsWith): bool |
86
|
|
|
{ |
87
|
|
|
$str = trim($str); |
88
|
|
|
return $str[strlen($str)-1] === $endsWith; |
89
|
|
|
} |
90
|
|
|
} |