<?php
/**
* Web Application Component Toolkit
*
* @link http://www.phpwact.org/
*
* @author Wact Development Team
* @link http://www.phpwact.org/team
*
* @copyright Copyright 2006, Jeff Moore
* @license http://opensource.org/licenses/mit-license.php MIT
*/

/**
* Collect test cases
*/
class Wact_Test_Collector {

    protected $testFiles = array();
    protected $testDirectories = array();
    protected $root;

    /**
    */
    function markDirectory($dir) {
        if (!empty($dir) && $dir != DIRECTORY_SEPARATOR && dirname($dir) != $dir) {
            if (isset($this->testDirectories[$dir])) {
                $this->testDirectories[$dir]++;
            } else {
                $this->testDirectories[$dir] = 1;
            }
            $this->markDirectory(dirname($dir));
        }
    }

    /**
    */
    function addTestFile($file) {
        $this->testFiles[] = $file;
        $this->markDirectory(dirname($file));
    }

    /**
    */
    function scanDirectoryForTests($directory) {
        $dh = opendir($directory);
        if (! is_resource($dh)) {
            trigger_error("Couldn't open {$directory}", E_USER_ERROR);
        }
        while ($file = readdir($dh)) {
            if ($file == '.' || $file == '..') {
                continue;
            }
            $file_path = $directory . DIRECTORY_SEPARATOR . $file;
            if (is_dir($file_path)) {
                $this->scanDirectoryForTests($file_path);
            } else if (strcasecmp(substr($file_path, -9, 9), '.test.php') == 0) {
                $this->addTestFile($file_path);
            } 
        }
        closedir($dh);
    }

    /**
    */
    function getDirs() {
        $dirs = array();
        foreach($this->testDirectories as $dir => $count) {
            if (strlen($dir) >= strlen($this->root)) {
                $dirs[$dir] = $count;
            }
        }
        ksort($dirs);
        return $dirs;
    }

    /**
    */
    function getTests($dir) {
        $tests = array();
        foreach($this->testFiles as $file) {
            if (strpos($file, $dir) === 0) {
                $tests[] = $file;
            }
        }
        sort($tests);
        return $tests;
    }

    /**
    */
    function getTestCaseDir() {
        return $this->root;
    }

    /**
    */
    function collect($root) {
        $this->root = realpath($root);
        $this->scanDirectoryForTests($this->root);
    }

}

?>