Skip to content

Instantly share code, notes, and snippets.

@KennFatt
Forked from dktapps/enable_strict_types.php
Created December 29, 2017 11:33
Show Gist options
  • Save KennFatt/2a0d9f8a2b54584f938814a3e1077f11 to your computer and use it in GitHub Desktop.
Save KennFatt/2a0d9f8a2b54584f938814a3e1077f11 to your computer and use it in GitHub Desktop.
Hacked-together script to enable strict types in PHP files en masse. Primarily intended for PocketMine-MP.
<?php
declare(strict_types=1);
$startTime = microtime(true);
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__ . DIRECTORY_SEPARATOR));
foreach($iterator as $file){
if($file->getExtension() === "php"){
$path = $file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename();
if(strpos(file_get_contents($path), "declare(strict_types") !== false){
continue;
}
$lines = file($path);
$inHeader = false;
foreach($lines as $lineNum => $line){
if(strpos($line, "<?php") === 0){
continue;
}elseif(strpos($line, "/*") === 0 and !$inHeader){
$inHeader = true;
continue;
}elseif(strpos(trim($line), "*") === 0 and $inHeader){
continue;
}elseif(trim($line) === "" and !$inHeader){
continue;
}
if($inHeader and strpos(trim($line), "*/") === 0){
$inHeader = false;
continue;
}
$start = array_slice($lines, 0, $lineNum);
$start[] = "\n";
$start[] = "declare(strict_types=1);\n";
$end = array_slice($lines, $lineNum);
$lines = array_merge($start, $end);
file_put_contents($path, implode("", $lines));
break;
}
echo "Processed " . $path . PHP_EOL;
}
}
$time = ((microtime(true) - $startTime) * 1000);
echo "Done in " . $time . "ms" . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment