PHP_CodeSniffer_File::detectLineEndings PHP Method

detectLineEndings() public static method

Opens a file and detects the EOL character being used.
public static detectLineEndings ( string $file, string $contents = null ) : string
$file string The full path to the file.
$contents string The contents to parse. If NULL, the content is taken from the file system.
return string
    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;
    }