PhpCsFixer\Tokenizer\Tokens::setCode PHP Method

setCode() public method

Set code. Clear all current content and replace it by new Token items generated from code directly.
public setCode ( string $code )
$code string PHP code
    public function setCode($code)
    {
        // No need to work when the code is the same.
        // That is how we avoid a lot of work and setting changed flag.
        if ($code === $this->generateCode()) {
            return;
        }
        // clear memory
        $this->setSize(0);
        $tokens = defined('TOKEN_PARSE') ? token_get_all($code, TOKEN_PARSE) : token_get_all($code);
        $this->setSize(count($tokens));
        foreach ($tokens as $index => $token) {
            $this[$index] = new Token($token);
        }
        $transformers = Transformers::create();
        $transformers->transform($this);
        $this->foundTokenKinds = array();
        foreach ($this as $index => $token) {
            $this->registerFoundToken($token);
        }
        $this->rewind();
        $this->changeCodeHash(self::calculateCodeHash($code));
        $this->changed = true;
    }

Usage Example

 /**
  * {@inheritdoc}
  */
 public function fix(\SplFileInfo $file, Tokens $tokens)
 {
     $this->deepestLevel = 0;
     // This fixer works partially on Tokens and partially on string representation of code.
     // During the process of fixing internal state of single Token may be affected by injecting ALIGNABLE_PLACEHOLDER to its content.
     // The placeholder will be resolved by `replacePlaceholder` method by removing placeholder or changing it into spaces.
     // That way of fixing the code causes disturbances in marking Token as changed - if code is perfectly valid then placeholder
     // still be injected and removed, which will cause the `changed` flag to be set.
     // To handle that unwanted behavior we work on clone of Tokens collection and then override original collection with fixed collection.
     $tokensClone = clone $tokens;
     $this->injectAlignmentPlaceholders($tokensClone);
     $content = $this->replacePlaceholder($tokensClone);
     $tokens->setCode($content);
 }
All Usage Examples Of PhpCsFixer\Tokenizer\Tokens::setCode