3 * This file is part of the PHP_TokenStream package.
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
12 * A stream of PHP tokens.
14 * @author Sebastian Bergmann <sebastian@phpunit.de>
15 * @copyright Sebastian Bergmann <sebastian@phpunit.de>
16 * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
17 * @link http://github.com/sebastianbergmann/php-token-stream/tree
18 * @since Class available since Release 1.0.0
20 class PHP_Token_Stream implements ArrayAccess, Countable, SeekableIterator
25 protected static $customTokens = array(
26 '(' => 'PHP_Token_OPEN_BRACKET',
27 ')' => 'PHP_Token_CLOSE_BRACKET',
28 '[' => 'PHP_Token_OPEN_SQUARE',
29 ']' => 'PHP_Token_CLOSE_SQUARE',
30 '{' => 'PHP_Token_OPEN_CURLY',
31 '}' => 'PHP_Token_CLOSE_CURLY',
32 ';' => 'PHP_Token_SEMICOLON',
33 '.' => 'PHP_Token_DOT',
34 ',' => 'PHP_Token_COMMA',
35 '=' => 'PHP_Token_EQUAL',
36 '<' => 'PHP_Token_LT',
37 '>' => 'PHP_Token_GT',
38 '+' => 'PHP_Token_PLUS',
39 '-' => 'PHP_Token_MINUS',
40 '*' => 'PHP_Token_MULT',
41 '/' => 'PHP_Token_DIV',
42 '?' => 'PHP_Token_QUESTION_MARK',
43 '!' => 'PHP_Token_EXCLAMATION_MARK',
44 ':' => 'PHP_Token_COLON',
45 '"' => 'PHP_Token_DOUBLE_QUOTES',
46 '@' => 'PHP_Token_AT',
47 '&' => 'PHP_Token_AMPERSAND',
48 '%' => 'PHP_Token_PERCENT',
49 '|' => 'PHP_Token_PIPE',
50 '$' => 'PHP_Token_DOLLAR',
51 '^' => 'PHP_Token_CARET',
52 '~' => 'PHP_Token_TILDE',
53 '`' => 'PHP_Token_BACKTICK'
64 protected $tokens = array();
69 protected $position = 0;
74 protected $linesOfCode = array('loc' => 0, 'cloc' => 0, 'ncloc' => 0);
94 protected $interfaces;
104 protected $lineToFunctionMap = array();
109 * @param string $sourceCode
111 public function __construct($sourceCode)
113 if (is_file($sourceCode)) {
114 $this->filename = $sourceCode;
115 $sourceCode = file_get_contents($sourceCode);
118 $this->scan($sourceCode);
124 public function __destruct()
126 $this->tokens = array();
132 public function __toString()
136 foreach ($this as $token) {
145 * @since Method available since Release 1.1.0
147 public function getFilename()
149 return $this->filename;
153 * Scans the source for sequences of characters and converts them into a
156 * @param string $sourceCode
158 protected function scan($sourceCode)
162 $tokens = token_get_all($sourceCode);
163 $numTokens = count($tokens);
165 $lastNonWhitespaceTokenWasDoubleColon = false;
167 for ($i = 0; $i < $numTokens; ++$i) {
168 $token = $tokens[$i];
171 if (is_array($token)) {
172 $name = substr(token_name($token[0]), 2);
175 if ($lastNonWhitespaceTokenWasDoubleColon && $name == 'CLASS') {
176 $name = 'CLASS_NAME_CONSTANT';
177 } elseif ($name == 'USE' && isset($tokens[$i+2][0]) && $tokens[$i+2][0] == T_FUNCTION) {
178 $name = 'USE_FUNCTION';
182 $tokenClass = 'PHP_Token_' . $name;
185 $tokenClass = self::$customTokens[$token];
188 $this->tokens[] = new $tokenClass($text, $line, $this, $id++);
189 $lines = substr_count($text, "\n");
192 if ($tokenClass == 'PHP_Token_HALT_COMPILER') {
194 } elseif ($tokenClass == 'PHP_Token_COMMENT' ||
195 $tokenClass == 'PHP_Token_DOC_COMMENT') {
196 $this->linesOfCode['cloc'] += $lines + 1;
199 if ($name == 'DOUBLE_COLON') {
200 $lastNonWhitespaceTokenWasDoubleColon = true;
201 } elseif ($name != 'WHITESPACE') {
202 $lastNonWhitespaceTokenWasDoubleColon = false;
208 $this->linesOfCode['loc'] = substr_count($sourceCode, "\n");
209 $this->linesOfCode['ncloc'] = $this->linesOfCode['loc'] -
210 $this->linesOfCode['cloc'];
216 public function count()
218 return count($this->tokens);
222 * @return PHP_Token[]
224 public function tokens()
226 return $this->tokens;
232 public function getClasses()
234 if ($this->classes !== null) {
235 return $this->classes;
240 return $this->classes;
246 public function getFunctions()
248 if ($this->functions !== null) {
249 return $this->functions;
254 return $this->functions;
260 public function getInterfaces()
262 if ($this->interfaces !== null) {
263 return $this->interfaces;
268 return $this->interfaces;
273 * @since Method available since Release 1.1.0
275 public function getTraits()
277 if ($this->traits !== null) {
278 return $this->traits;
283 return $this->traits;
287 * Gets the names of all files that have been included
288 * using include(), include_once(), require() or require_once().
290 * Parameter $categorize set to TRUE causing this function to return a
291 * multi-dimensional array with categories in the keys of the first dimension
292 * and constants and their values in the second dimension.
294 * Parameter $category allow to filter following specific inclusion type
296 * @param bool $categorize OPTIONAL
297 * @param string $category OPTIONAL Either 'require_once', 'require',
298 * 'include_once', 'include'.
300 * @since Method available since Release 1.1.0
302 public function getIncludes($categorize = false, $category = null)
304 if ($this->includes === null) {
305 $this->includes = array(
306 'require_once' => array(),
307 'require' => array(),
308 'include_once' => array(),
312 foreach ($this->tokens as $token) {
313 switch (get_class($token)) {
314 case 'PHP_Token_REQUIRE_ONCE':
315 case 'PHP_Token_REQUIRE':
316 case 'PHP_Token_INCLUDE_ONCE':
317 case 'PHP_Token_INCLUDE':
318 $this->includes[$token->getType()][] = $token->getName();
324 if (isset($this->includes[$category])) {
325 $includes = $this->includes[$category];
326 } elseif ($categorize === false) {
327 $includes = array_merge(
328 $this->includes['require_once'],
329 $this->includes['require'],
330 $this->includes['include_once'],
331 $this->includes['include']
334 $includes = $this->includes;
341 * Returns the name of the function or method a line belongs to.
343 * @return string or null if the line is not in a function or method
344 * @since Method available since Release 1.2.0
346 public function getFunctionForLine($line)
350 if (isset($this->lineToFunctionMap[$line])) {
351 return $this->lineToFunctionMap[$line];
355 protected function parse()
357 $this->interfaces = array();
358 $this->classes = array();
359 $this->traits = array();
360 $this->functions = array();
362 $classEndLine = array();
364 $traitEndLine = false;
366 $interfaceEndLine = false;
368 foreach ($this->tokens as $token) {
369 switch (get_class($token)) {
370 case 'PHP_Token_HALT_COMPILER':
373 case 'PHP_Token_INTERFACE':
374 $interface = $token->getName();
375 $interfaceEndLine = $token->getEndLine();
377 $this->interfaces[$interface] = array(
378 'methods' => array(),
379 'parent' => $token->getParent(),
380 'keywords' => $token->getKeywords(),
381 'docblock' => $token->getDocblock(),
382 'startLine' => $token->getLine(),
383 'endLine' => $interfaceEndLine,
384 'package' => $token->getPackage(),
385 'file' => $this->filename
389 case 'PHP_Token_CLASS':
390 case 'PHP_Token_TRAIT':
392 'methods' => array(),
393 'parent' => $token->getParent(),
394 'interfaces'=> $token->getInterfaces(),
395 'keywords' => $token->getKeywords(),
396 'docblock' => $token->getDocblock(),
397 'startLine' => $token->getLine(),
398 'endLine' => $token->getEndLine(),
399 'package' => $token->getPackage(),
400 'file' => $this->filename
403 if ($token instanceof PHP_Token_CLASS) {
404 $class[] = $token->getName();
405 $classEndLine[] = $token->getEndLine();
407 if ($class[count($class)-1] != 'anonymous class') {
408 $this->classes[$class[count($class)-1]] = $tmp;
411 $trait = $token->getName();
412 $traitEndLine = $token->getEndLine();
413 $this->traits[$trait] = $tmp;
417 case 'PHP_Token_FUNCTION':
418 $name = $token->getName();
420 'docblock' => $token->getDocblock(),
421 'keywords' => $token->getKeywords(),
422 'visibility'=> $token->getVisibility(),
423 'signature' => $token->getSignature(),
424 'startLine' => $token->getLine(),
425 'endLine' => $token->getEndLine(),
426 'ccn' => $token->getCCN(),
427 'file' => $this->filename
432 $interface === false) {
433 $this->functions[$name] = $tmp;
435 $this->addFunctionToMap(
440 } elseif (!empty($class) && $class[count($class)-1] != 'anonymous class') {
441 $this->classes[$class[count($class)-1]]['methods'][$name] = $tmp;
443 $this->addFunctionToMap(
444 $class[count($class)-1] . '::' . $name,
448 } elseif ($trait !== false) {
449 $this->traits[$trait]['methods'][$name] = $tmp;
451 $this->addFunctionToMap(
452 $trait . '::' . $name,
457 $this->interfaces[$interface]['methods'][$name] = $tmp;
461 case 'PHP_Token_CLOSE_CURLY':
462 if (!empty($classEndLine) &&
463 $classEndLine[count($classEndLine)-1] == $token->getLine()) {
464 array_pop($classEndLine);
466 } elseif ($traitEndLine !== false &&
467 $traitEndLine == $token->getLine()) {
469 $traitEndLine = false;
470 } elseif ($interfaceEndLine !== false &&
471 $interfaceEndLine == $token->getLine()) {
473 $interfaceEndLine = false;
483 public function getLinesOfCode()
485 return $this->linesOfCode;
490 public function rewind()
498 public function valid()
500 return isset($this->tokens[$this->position]);
506 public function key()
508 return $this->position;
514 public function current()
516 return $this->tokens[$this->position];
521 public function next()
527 * @param integer $offset
530 public function offsetExists($offset)
532 return isset($this->tokens[$offset]);
536 * @param integer $offset
538 * @throws OutOfBoundsException
540 public function offsetGet($offset)
542 if (!$this->offsetExists($offset)) {
543 throw new OutOfBoundsException(
545 'No token at position "%s"',
551 return $this->tokens[$offset];
555 * @param integer $offset
556 * @param mixed $value
558 public function offsetSet($offset, $value)
560 $this->tokens[$offset] = $value;
564 * @param integer $offset
565 * @throws OutOfBoundsException
567 public function offsetUnset($offset)
569 if (!$this->offsetExists($offset)) {
570 throw new OutOfBoundsException(
572 'No token at position "%s"',
578 unset($this->tokens[$offset]);
582 * Seek to an absolute position.
584 * @param integer $position
585 * @throws OutOfBoundsException
587 public function seek($position)
589 $this->position = $position;
591 if (!$this->valid()) {
592 throw new OutOfBoundsException(
594 'No token at position "%s"',
602 * @param string $name
603 * @param integer $startLine
604 * @param integer $endLine
606 private function addFunctionToMap($name, $startLine, $endLine)
608 for ($line = $startLine; $line <= $endLine; $line++) {
609 $this->lineToFunctionMap[$line] = $name;