PhpCsFixer\Tokenizer\Tokens::fromCode PHP Method

fromCode() public static method

Create token collection directly from code.
public static fromCode ( string $code ) : Tokens
$code string PHP code
return Tokens
    public static function fromCode($code)
    {
        $codeHash = self::calculateCodeHash($code);
        if (self::hasCache($codeHash)) {
            $tokens = self::getCache($codeHash);
            // generate the code to recalculate the hash
            $tokens->generateCode();
            if ($codeHash === $tokens->codeHash) {
                $tokens->clearEmptyTokens();
                $tokens->clearChanged();
                return $tokens;
            }
        }
        $tokens = new self();
        $tokens->setCode($code);
        $tokens->clearChanged();
        return $tokens;
    }

Usage Example

 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $tokensAnalyzer = new TokensAnalyzer($tokens);
     $uses = array_reverse($tokensAnalyzer->getImportUseIndexes());
     foreach ($uses as $index) {
         $endIndex = $tokens->getNextTokenOfKind($index, array(';'));
         $declarationContent = $tokens->generatePartialCode($index + 1, $endIndex - 1);
         $declarationParts = explode(',', $declarationContent);
         if (1 === count($declarationParts)) {
             continue;
         }
         $declarationContent = array();
         foreach ($declarationParts as $declarationPart) {
             $declarationContent[] = 'use ' . trim($declarationPart) . ';';
         }
         $declarationContent = implode("\n" . $this->detectIndent($tokens, $index), $declarationContent);
         for ($i = $index; $i <= $endIndex; ++$i) {
             $tokens[$i]->clear();
         }
         $declarationTokens = Tokens::fromCode('<?php ' . $declarationContent);
         $declarationTokens[0]->clear();
         $declarationTokens->clearEmptyTokens();
         $tokens->insertAt($index, $declarationTokens);
     }
 }
All Usage Examples Of PhpCsFixer\Tokenizer\Tokens::fromCode