public static function detectLineEndings($file, $contents = null)
{
if ($contents === null) {
// Determine the newline character being used in this file.
// Will be either \r, \r\n or \n.
if (is_readable($file) === false) {
$error = 'Error opening file; file no longer exists or you do not have access to read the file';
throw new PHP_CodeSniffer_Exception($error);
} else {
$handle = fopen($file, 'r');
if ($handle === false) {
$error = 'Error opening file; could not auto-detect line endings';
throw new PHP_CodeSniffer_Exception($error);
}
}
$firstLine = fgets($handle);
fclose($handle);
$eolChar = substr($firstLine, -1);
if ($eolChar === "\n") {
$secondLastChar = substr($firstLine, -2, 1);
if ($secondLastChar === "\r") {
$eolChar = "\r\n";
}
} else {
if ($eolChar !== "\r") {
// Must not be an EOL char at the end of the line.
// Probably a one-line file, so assume \n as it really
// doesn't matter considering there are no newlines.
$eolChar = "\n";
}
}
} else {
if (preg_match("/\r\n?|\n/", $contents, $matches) !== 1) {
// Assuming there are no newlines.
$eolChar = "\n";
} else {
$eolChar = $matches[0];
}
}
//end if
return $eolChar;
}