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

// Traversing up the directory tree to find composer.json
$workingDir = $projectDir = getcwd();

while(!file_exists($projectDir . '/composer.json')) {

    $projectDir = dirname($projectDir);

    if ($projectDir === '/') {
        fwrite(STDERR, "Could not find composer.json in the current directory or any parent\n");
        exit(1);
    }

}

$composer = $projectDir . '/composer.json';

// Parsing composer.json and find vendor-dir
$composerConfig = json_decode(file_get_contents($composer), true);
if (isset($composerConfig['config']['vendor-dir'])) {
    $vendorDir = $composerConfig['config']['vendor-dir'];
} else {
    $vendorDir = 'vendor';
}

$phpUnitBin = realpath($projectDir . '/' . $vendorDir) . '/phpunit/phpunit/phpunit';

if (!file_exists($phpUnitBin)) {
    fwrite(STDERR, "Could not find the phpunit executable at $phpUnitBin\n");
    exit(1);
}



// Next step is to find phpunit.xml.dist or phpunit.xml
$testDirs = [
   'phpunit.xml',
   'phpunit.xml.dist',
   'test/phpunit.xml',
   'test/phpunit.xml.dist',
   'tests/phpunit.xml',
   'tests/phpunit.xml.dist',
];

$phpUnitFile = null;

foreach($testDirs as $testDir) {

    if (file_exists($workingDir . '/' . $testDir)) {

        $phpUnitFile = $workingDir . '/' . $testDir;
        break;

    }

    if (file_exists($projectDir . '/' . $testDir)) {

        $phpUnitFile = $projectDir . '/' . $testDir;
        break;

    }

}

// Setting the current directory to where we found phpunit.xml
if ($phpUnitFile) {
    chdir(dirname($phpUnitFile));
}

require $projectDir.'/'.$vendorDir.'/autoload.php';
if (class_exists('PHPUnit_TextUI_Command')) {
    // start PHPUnit directly bypassing the binary as including the binary outputs the shebang line
    PHPUnit_TextUI_Command::main();
} else {
    // future-proofing
    require $phpUnitBin;
}
