Helper::getTokensFromString()   B
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 16
cts 16
cp 1
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 18
nc 6
nop 1
crap 4
1
<?php
2
3
  declare(strict_types=1);
4
5
  namespace Funivan\PhpTokenizer;
6
7
  use Funivan\PhpTokenizer\Exception\Exception;
8
9
  /**
10
   * @author Ivan Shcherbak <[email protected]> 11/26/13
11
   */
12
  class Helper {
13
14
    /**
15
     * Convert php code to array of tokens
16
     *
17
     * @param string $code
18
     * @return Token[]
19
     * @throws Exception
20
     */
21 465
    public static function getTokensFromString($code) {
22
      try {
23 465
        $tokens = token_get_all($code, TOKEN_PARSE);
24 72
      } catch (\ParseError $e) {
25
        // with TOKEN_PARSE flag, the function throws on invalid code
26
        // let's just ignore the error and tokenize the code without the flag
27 72
        $tokens = token_get_all($code);
28
      }
29
30 465
      foreach ($tokens as $index => $tokenData) {
31
32 465
        if (!is_array($tokenData)) {
33 444
          $previousIndex = $index - 1;
34
35
          /** @var Token $previousToken */
36 444
          $previousToken = $tokens[$previousIndex];
37 444
          $line = $previousToken->getLine() + substr_count($previousToken->getValue(), "\n");
38
          $tokenData = [
39 444
            Token::INVALID_TYPE,
40 444
            $tokenData,
41 444
            $line,
42
          ];
43
        }
44
45 465
        $token = new Token($tokenData);
46 465
        $token->setIndex($index);
47 465
        $tokens[$index] = $token;
48
49
      }
50
51 465
      return $tokens;
52
    }
53
54
55
    /**
56
     * @param Collection $collection
57
     * @return string
58
     */
59 3
    public static function dump(Collection $collection) {
60 3
      $string = '<pre>' . "\n";
61 3
      foreach ($collection as $token) {
62 3
        $string .= '[' . $token->getTypeName() . ']' . "\n" . print_r($token->getData(), true) . "\n";
63
      }
64 3
      $string .= ' </pre > ';
65 3
      return $string;
66
    }
67
68
69
  }
70