Helper   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 1
dl 0
loc 58
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getTokensFromString() 0 32 4
A dump() 0 8 2
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