#!/usr/bin/env php
<?php

$options = getopt('h', ['help', 'output-format:']);

if (isset($options['h']) || isset($options['help'])) {
    fwrite(STDERR, <<<EOT
Usage: {$argv[0]} [--output-format=checkstyle-escapedhtml]

Reads Phan's regular output format on stdin and outputs a checkstyle file on stdout.
By default, errors in the XML are the plaintext of the issue, but those can be html escaped again by passing --output-format=checkstyle-escapedhtml.

EOT
    );
    exit(0);
}

$escape_html = false;
if (array_key_exists('output-format', $options) && $options['output-format'] === 'checkstyle-escapedhtml') {
    $escape_html = true;
}

$files = [];
while($line = trim(fgets(STDIN))) {
    $elements = explode(' ', $line, 3);

    list($file, $line) = explode(':', $elements[0]);
    $source = $elements[1];
    $message = $elements[2];

    if (empty($files[$file])) {
        $files[$file] = [];
    }

    $files[$file][] = [
        'line' => $line,
        'source' => $source,
        'message' => $message,
        'severity' => 'error',
    ];
}

$document = new \DomDocument('1.0', 'ISO-8859-15');

$checkstyle = new \DOMElement('checkstyle');
$document->appendChild($checkstyle);
$checkstyle->appendChild(new \DOMAttr('version', '6.5'));

// Write each file to the DOM
foreach ($files as $file_name => $error_list) {
    $file = new \DOMElement('file');
    $checkstyle->appendChild($file);
    $file->appendChild(new \DOMAttr('name', $file_name));

    // Write each error to the file
    foreach ($error_list as $error_map) {
        $error = new \DOMElement('error');
        $file->appendChild($error);

        // Write each element of the error as an attribute
        // of the error
        foreach ($error_map as $key => $value) {
            $string_value = $escape_html ? htmlspecialchars((string)$value, ENT_NOQUOTES, 'UTF-8') : (string)$value;
            $error->appendChild(
                new \DOMAttr($key, $string_value)
            );
        }
    }
}

print $document->saveXML();
