coder_format_file($filename, $undo = FALSE)Reads, backups, processes and writes the source code from and to a file.
$filename Path to a file to process or restore. Pass original filename to restore an already processed file.
$undo Whether to restore a processed file. Always restores the last backup.
TRUE on success.
sites/all/modules/coder/scripts/coder_format/coder_format.inc, line 43
<?php
function coder_format_file($filename, $undo = FALSE) {
// Restore a processed file.
if ($undo) {
// Do nothing if no backup file exists at all.
if (!file_exists($filename .'.coder.orig')) {
return;
}
// Save original filename.
$original = $filename;
// Retrieve the file's directory.
$basename = file_check_path($filename);
// Find all backups.
$mask = '^'. preg_quote($basename) .'(\.coder\.orig)+$';
$nomask = array('.', '..', 'CVS', '.svn');
$backups = file_scan_directory($filename, $mask, $nomask, 0, FALSE);
// Find the latest backup to restore.
ksort($backups);
$latest = array_pop($backups);
// Restore latest backup.
if (file_move($latest->filename, $original, FILE_EXISTS_REPLACE)) {
drupal_set_message(t('%file restored.', array('%file' => $original)));
return TRUE;
}
else {
drupal_set_message(t('%file could not be restored.', array('%file' => $original)), 'error');
return FALSE;
}
}
// Backup original file.
// file_copy() replaces source filepath with target filepath.
$sourcefile = $filename;
if (!file_copy($filename, $filename .'.coder.orig', FILE_EXISTS_RENAME)) {
drupal_set_message(t('%file could not be backup.', array('%file' => $filename)), 'error');
return FALSE;
}
// Read source code from source file.
$fd = fopen($sourcefile, 'r');
$code = fread($fd, filesize($sourcefile));
fclose($fd);
if ($code !== false) {
$code = coder_format_string_all($code);
if ($code !== false) {
// Write formatted source code to target file.
$fd = fopen($sourcefile, 'w');
$status = fwrite($fd, $code);
fclose($fd);
drupal_set_message(t('%file processed.', array('%file' => $sourcefile)));
return $status;
}
else {
drupal_set_message(t('An error occurred while processing %file.', array('%file' => $sourcefile)), 'error');
return FALSE;
}
}
else {
drupal_set_message(t('%file could not be opened.', array('%file' => $sourcefile)), 'error');
return FALSE;
}
}
?>