PHP_CodeSniffer_Fixer::generateDiff PHP Method

generateDiff() public method

Generates a text diff of the original file and the new content.
public generateDiff ( string $filePath = null, boolean $colors = true ) : string
$filePath string Optional file path to diff the file against. If not specified, the original version of the file will be used.
$colors boolean Print colored output or not.
return string
    public function generateDiff($filePath = null, $colors = true)
    {
        if ($filePath === null) {
            $filePath = $this->_currentFile->getFilename();
        }
        $cwd = getcwd() . DIRECTORY_SEPARATOR;
        $filename = str_replace($cwd, '', $filePath);
        $contents = $this->getContents();
        if (function_exists('sys_get_temp_dir') === true) {
            // This is needed for HHVM support, but only available from 5.2.1.
            $tempName = tempnam(sys_get_temp_dir(), 'phpcs-fixer');
            $fixedFile = fopen($tempName, 'w');
        } else {
            $fixedFile = tmpfile();
            $data = stream_get_meta_data($fixedFile);
            $tempName = $data['uri'];
        }
        fwrite($fixedFile, $contents);
        // We must use something like shell_exec() because whitespace at the end
        // of lines is critical to diff files.
        $cmd = "diff -u -L\"{$filename}\" -LPHP_CodeSniffer \"{$filename}\" \"{$tempName}\"";
        $diff = shell_exec($cmd);
        fclose($fixedFile);
        if (is_file($tempName) === true) {
            unlink($tempName);
        }
        if ($colors === false) {
            return $diff;
        }
        $diffLines = explode(PHP_EOL, $diff);
        if (count($diffLines) === 1) {
            // Seems to be required for cygwin.
            $diffLines = explode("\n", $diff);
        }
        $diff = array();
        foreach ($diffLines as $line) {
            if (isset($line[0]) === true) {
                switch ($line[0]) {
                    case '-':
                        $diff[] = "{$line}";
                        break;
                    case '+':
                        $diff[] = "{$line}";
                        break;
                    default:
                        $diff[] = $line;
                }
            }
        }
        $diff = implode(PHP_EOL, $diff);
        return $diff;
    }