private static function createRewrittenFile($file, $target_file)
{
if (self::$debug) {
echo "Rewriting {$file} => {$target_file}\n";
echo new \Exception();
ob_flush();
}
$contents = file_get_contents($file);
$contents = self::rewriteContents($file, $target_file, $contents);
$target_dir = dirname($target_file);
if (!($fp = fopen(self::$lock_file_path, 'a'))) {
throw new \RuntimeException("Could not create lock file " . self::$lock_file_path);
}
if (!flock($fp, LOCK_EX)) {
throw new \RuntimeException("Could not flock " . self::$lock_file_path);
}
if (!is_dir($target_dir) && !mkdir($target_dir, 0777, true)) {
throw new \RuntimeException("Could not create directory " . $target_dir);
}
$tmp_file = $target_file . ".tmp." . uniqid(getmypid());
if (file_put_contents($tmp_file, $contents) !== mb_orig_strlen($contents)) {
throw new \RuntimeException("Could not fully write {$tmp_file}");
}
if (DIRECTORY_SEPARATOR == '\\') {
// You cannot atomically replace files in Windows
if (file_exists($target_file) && !unlink($target_file)) {
throw new \RuntimeException("Could not unlink {$target_file}");
}
}
if (!rename($tmp_file, $target_file)) {
throw new \RuntimeException("Could not rename {$tmp_file} -> {$target_file}");
}
if (!fclose($fp)) {
throw new \RuntimeException("Could not fclose lock file descriptor for file " . self::$lock_file_path);
}
}