Swap exif-pixelydimension and exif-pixelxdimension messages
[lhc/web/wiklou.git] / includes / utils / ClassCollector.php
1 <?php
2
3 /**
4 * Reads PHP code and returns the FQCN of every class defined within it.
5 */
6 class ClassCollector {
7
8 /**
9 * @var string Current namespace
10 */
11 protected $namespace = '';
12
13 /**
14 * @var array List of FQCN detected in this pass
15 */
16 protected $classes;
17
18 /**
19 * @var array Token from token_get_all() that started an expect sequence
20 */
21 protected $startToken;
22
23 /**
24 * @var array List of tokens that are members of the current expect sequence
25 */
26 protected $tokens;
27
28 /**
29 * @var string $code PHP code (including <?php) to detect class names from
30 * @return array List of FQCN detected within the tokens
31 */
32 public function getClasses( $code ) {
33 $this->namespace = '';
34 $this->classes = [];
35 $this->startToken = null;
36 $this->tokens = [];
37
38 foreach ( token_get_all( $code ) as $token ) {
39 if ( $this->startToken === null ) {
40 $this->tryBeginExpect( $token );
41 } else {
42 $this->tryEndExpect( $token );
43 }
44 }
45
46 return $this->classes;
47 }
48
49 /**
50 * Determine if $token begins the next expect sequence.
51 *
52 * @param array $token
53 */
54 protected function tryBeginExpect( $token ) {
55 if ( is_string( $token ) ) {
56 return;
57 }
58 switch ( $token[0] ) {
59 case T_NAMESPACE:
60 case T_CLASS:
61 case T_INTERFACE:
62 case T_TRAIT:
63 case T_DOUBLE_COLON:
64 $this->startToken = $token;
65 }
66 }
67
68 /**
69 * Accepts the next token in an expect sequence
70 *
71 * @param array
72 */
73 protected function tryEndExpect( $token ) {
74 switch ( $this->startToken[0] ) {
75 case T_DOUBLE_COLON:
76 // Skip over T_CLASS after T_DOUBLE_COLON because this is something like
77 // "self::static" which accesses the class name. It doens't define a new class.
78 $this->startToken = null;
79 break;
80 case T_NAMESPACE:
81 if ( $token === ';' || $token === '{' ) {
82 $this->namespace = $this->implodeTokens() . '\\';
83 } else {
84 $this->tokens[] = $token;
85 }
86 break;
87
88 case T_CLASS:
89 case T_INTERFACE:
90 case T_TRAIT:
91 $this->tokens[] = $token;
92 if ( is_array( $token ) && $token[0] === T_STRING ) {
93 $this->classes[] = $this->namespace . $this->implodeTokens();
94 }
95 }
96 }
97
98 /**
99 * Returns the string representation of the tokens within the
100 * current expect sequence and resets the sequence.
101 *
102 * @return string
103 */
104 protected function implodeTokens() {
105 $content = [];
106 foreach ( $this->tokens as $token ) {
107 $content[] = is_string( $token ) ? $token : $token[1];
108 }
109
110 $this->tokens = [];
111 $this->startToken = null;
112
113 return trim( implode( '', $content ), " \n\t" );
114 }
115 }