Skip to content

Instantly share code, notes, and snippets.

@SnowCait
Created May 9, 2020 04:54
Show Gist options
  • Save SnowCait/b1b1bd98da508cfdd62aa63e966259da to your computer and use it in GitHub Desktop.
Save SnowCait/b1b1bd98da508cfdd62aa63e966259da to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
$files = []; // glob か何かでファイルのリストを取得
foreach ($files as $file) {
$source = file_get_contents($file);
$refactoring = new Refactoring($source);
$refactoring->addDeclare();
file_put_contents($file, $refactoring->toString());
}
class Refactoring {
private $tokens;
public function __construct(string $source) {
$this->tokens = token_get_all($source);
}
public function addDeclare(): void {
$open_tag = current($this->tokens);
if ($open_tag[0] !== T_OPEN_TAG) {
throw new Exception('Open tag is invalid.');
}
while (next($this->tokens)[0] === T_WHITESPACE) {
// nop
}
$declare = current($this->tokens);
if ($declare[0] !== T_DECLARE) {
$declare_tokens = token_get_all("declare(strict_types=1);" . PHP_EOL);
array_splice($this->tokens, 1, 0, $declare_tokens);
}
reset($this->tokens);
}
public function toString(): string {
$source = '';
foreach ($this->tokens as $token) {
if (is_array($token)) {
[, $string, ] = $token;
$source .= $string;
} else { // 記号
$source .= $token;
}
}
return $source;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment