#!/usr/bin/env php
<?php
/**
 * Run PHPCS tests against a push.
 *
 * The only argument is for the commit, which a list of changed files is retrieved from. The PHPCS tests are only run
 * against these changed files, to speed up the tests.
 */
if (empty($argv[1])) {
    fwrite(STDERR, 'You must provide a commit SHA to check.');
    fwrite(STDERR, "\n");
    exit(1);
}

// Get a changelist of files from Git for this push.
$fileList = shell_exec('git show --name-only --pretty="" --diff-filter=ACMR ' . $argv[1]);
$files = array_filter(explode("\n", $fileList));

foreach ($files as &$file) {
    if (strpos($file, ' ') !== false) {
        $file = str_replace(' ', '\\ ', $file);
    }
}

// no changes found in diff, early exit
if (!count($files)) {
    fwrite(STDOUT, "\e[0;32mFound no changed files.\e[0m");
    fwrite(STDOUT, "\n");
    exit(0);
}

// Run all changed files through the PHPCS code sniffer and generate a CSV report
$csv = shell_exec('phpcs --colors -nq --report="csv" --extensions="php" ' . implode(' ', $files));
$lines = array_map(function ($row) {
    return array_map(function ($column) {
        return trim($column, '"');
    }, explode(',', $row));
}, array_filter(explode("\n", $csv)));

// Remove header row
array_shift($lines);

if (!count($lines)) {
    fwrite(STDOUT, "\e[0;32mFound no issues with code quality.\e[0m");
    fwrite(STDOUT, "\n");
    exit(0);
}

// Group errors by file
$files = [];

foreach ($lines as $line) {
    $filename = str_replace(dirname(dirname(dirname(__DIR__))), '', $line[0]);

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

    $files[$filename][] = [
        'warning' => (($line[3] ?? 'err') === 'warning'),
        'message' => $line[4] ?? 'unknown',
        'line' => $line[1] ?? '0',
    ];
}

// Render report
fwrite(STDERR, "\e[0;31mFound "
    . ((count($lines) === 1)
        ? '1 issue'
        : count($lines) . ' issues')
    . " with code quality.\e[0m");
fwrite(STDERR,  "\n");

foreach ($files as $file => $errors) {
    fwrite(STDERR, "\n");
    fwrite(STDERR, "\e[1;37m" . str_replace('"', '', $file) . "\e[0m");
    fwrite(STDERR, "\n\n");

    foreach ($errors as $error) {
        fwrite(STDERR, "\e[2m" . str_pad('  L' . $error['line'], 7) . " | \e[0m");
        fwrite(STDERR, $error['warning'] ? "\e[1;33mWARN:\e[0m " : "\e[0;31mERR:\e[0m  ");
        fwrite(STDERR, $error['message']);
        fwrite(STDERR, "\n");
    }
}
exit(1);

