Unit tests

Instantiating class and filling arrays:$_GET iterator$_GET['myParam']$_GET['array:myParam']$_GET['id']$_GET['id_as_int']$_GET['int:id']$_GET['array:int:id']$_GET['array:float:cos:id']$_POST['escape:test']$_POST['sql:sqltest']$_GET
OKOK [Array]OK [about_us]OK [Array]OK [768]OK [768]OK [768]OK [Array]OK [Array]OK [<html>test]OK [\'\";test]OK [255/234678/1222/768/test/about_us/first?asd=rrr]
Generation time: 0.00486207008362

Instantiation example

12345678910111213141516171819202122232425262728
<?
        // Add $_POST variables
        $_POST['test'] = '<html>test';
        $_POST['sqltest'] = '\'";test';
 
        // register DB class
        superGlobal::db(new falseDB());
 
        // register Memcache class
        superGlobal::memcached(new falseMemcache(),1200);
 
        // Register predefined values set for URI param
        superGlobal::registerParam('myParam',
            array('index','about_us','production','events','publications','resources','contacts','login'));
 
        // Register param that should be numeric
        superGlobal::registerParam('id', 'is_numeric');
 
        // Register param that should be numeric and returned as integer
        superGlobal::registerParam('int:id_as_int', 'is_numeric');
 
        // Register predefined param values from SQL column
        superGlobal::registerSQLParam('sql', 'falseTable','falseField');
 
        // Inject into $_POST superglobal
        superGlobal::inject('_POST');
    
?>

Usage

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
<?
        // iterate thru $_GET
        foreach($_GET as $k => $v)
            $return['$_GET iterator']['value'][$k] = $v;
 
        // Test it
        $return['$_GET iterator']['result'] = is_array($return['$_GET iterator']['value']);
 
        // Plain myParam request from $_GET or URI
        $return['$_GET[\'myParam\']']['value'] = $_GET['myParam'];
 
        // Test it
        $return['$_GET[\'myParam\']']['result'] = is_string($_GET['myParam']);
 
        // Array of all params for myParam from $_GET and URI
        $return['$_GET[\'array:myParam\']']['value'] = $_GET['array:myParam'];
 
        // Test it
        $return['$_GET[\'array:myParam\']']['result'] = is_array($_GET['array:myParam']);
 
        // Plain $_GET or URI id request
        $return['$_GET[\'id\']']['value'] = $_GET['id'];
 
        // Test it
        $return['$_GET[\'id\']']['result'] = is_string($_GET['id']);
 
        // Pre-casted integer as plain request for $_GET|URI id
        $return['$_GET[\'id_as_int\']']['value'] = $_GET['id_as_int'];
 
        // Test it
        $return['$_GET[\'id_as_int\']']['result'] = is_int($_GET['id_as_int']);
 
        // Request $_GET id casted to integer
        $return['$_GET[\'int:id\']']['value'] = $_GET['int:id'];
 
        // Test it
        $return['$_GET[\'int:id\']']['result'] = is_int($_GET['int:id']);
 
        // Request array of URI and $_GET id casted to integer
        $return['$_GET[\'array:int:id\']']['value'] = $_GET['array:int:id'];
 
        // Test it
        $return['$_GET[\'array:int:id\']']['result'] = is_array($_GET['array:int:id']);
        if ($return['$_GET[\'array:int:id\']']['result'])
        {
            // This one is because of PHP bug, can do nothing with this
            $array = $_GET['array:int:id'];
 
            foreach ($array as $v)
            {
                if (!is_int($v))
                {
                    $return['$_GET[\'array:int:id\']']['result'] = false;
                    break;
                }
            }
        }
 
        // Request array of URI and $_GET id casted to float and then cos function applied
        $return['$_GET[\'array:float:cos:id\']']['value'] = $_GET['array:float:cos:id'];
 
        // Test it
        $return['$_GET[\'array:float:cos:id\']']['result'] = is_array($_GET['array:float:cos:id']);
        if ($return['$_GET[\'array:float:cos:id\']']['result'])
        {
            // This one is because of PHP bug, can do nothing with this
            $array = $_GET['array:float:cos:id'];
 
            foreach ($array as $v)
            {
                if (-1 >= $v && $v <= 1)
                {
                    $return['$_GET[\'array:float:cos:id\']']['result'] = false;
                    break;
                }
            }
        }
 
        // Request HTML escaped value for $_POST test variable
        $return['$_POST[\'escape:test\']']['value'] = $_POST['escape:test'];
 
        // Test it
        $return['$_POST[\'escape:test\']']['result'] = (bool)strpos($_POST['escape:test'],'&#62;');
 
        // Request SQL escaped value for $_POST test variable
        $return['$_POST[\'sql:sqltest\']']['value'] = $_POST['sql:sqltest'];
 
        // Test it
        $return['$_POST[\'sql:sqltest\']']['result'] = (bool)strpos($_POST['sql:sqltest'], "'\\\"");
 
        // Request prepared URI string for current set of $_GET and URI parameters
        $return['$_GET']['value'] = (string)$_GET;
 
        // Test it
        $return['$_GET']['result'] = (bool)strpos($_GET,'/');
        
?>

Full source

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
<?
/**
 * Unit test and usage example for superGlobals library
 *
 * @package superGlobals
 * @author Max S. Yarchevsky        max@ics.net.ua
 * @license http://ics.net.ua/license/new-bsd        New BSD License
 * @version 1.169
 */
 
// Include superGlobals library
require_once('superglobals.php');
 
// Include code highlighter (PEAR)
require_once('Text/Highlighter.php');
 
/**
 * Fake DB class for unit testing
 * implements getCol() and escape() methods required by superGlobals class
 */
class falseDB
{
    /**
     * Should return array of single column values
     *
     * @param string $sql SQL string that selects single column from DB table
     * @return array Array of all values present in column
     */
    public function getCol($sql)
    {
        return array( 'first','second','third');
    }
 
    /**
     * Should do real value escaping for current DB instance
     *
     * @param mixed $value Data to escape
     * @return string Escaped data
     */
    public function escape($value)
    {
        return mysql_escape_string($value);
    }
}
 
/**
 * Fake Memcache class (not only memchached, may be other cache server)
 * Should implement get() and set() methods
 */
class falseMemcache
{
    /**
     * Should return cached value for key or false if key not exist
     *
     * @param string $key Key for cached value
     * @return mixed|boolean Value for key or false if key not exist in cache
     */
    function get($key)
    {
        return false;
    }
 
    /**
     * Should store value in cache, optionally - for period of seconds.
     * Flag is not used.
     *
     * @param string $key Key for value
     * @param mixed $var Value
     * @param int $flag Optional flag (not used)
     * @param int $expire Cache expiration time (in seconds)
     * @return bool Returns true on success or false on failure.
     */
    function set($key, $var, $flag = null, $expire = null)
    {
        return false;
    }
}
 
 
/**
 * Unit test class for superGlobals library
 */
class superUnitTest
{
    // Unit test start microtime
    private $start;
 
    /**
     * General preparations
     *
     * @return void
     */
    public function instantiate()
    {
        // Set start time
        $this->start = microtime(true);
 
        // SPLIT
        // Add $_POST variables
        $_POST['test'] = '<html>test';
        $_POST['sqltest'] = '\'";test';
 
        // register DB class
        superGlobal::db(new falseDB());
 
        // register Memcache class
        superGlobal::memcached(new falseMemcache(),1200);
 
        // Register predefined values set for URI param
        superGlobal::registerParam('myParam',
            array('index','about_us','production','events','publications','resources','contacts','login'));
 
        // Register param that should be numeric
        superGlobal::registerParam('id', 'is_numeric');
 
        // Register param that should be numeric and returned as integer
        superGlobal::registerParam('int:id_as_int', 'is_numeric');
 
        // Register predefined param values from SQL column
        superGlobal::registerSQLParam('sql', 'falseTable','falseField');
 
        // Inject into $_POST superglobal
        superGlobal::inject('_POST');
    // SPLIT
 
        return 'OK';
    }
 
    /**
     * Perform tests
     *
     * @return array Testing results
     */
    public function test()
    {
        $return = array();
 
        // SPLIT
        // iterate thru $_GET
        foreach($_GET as $k => $v)
            $return['$_GET iterator']['value'][$k] = $v;
 
        // Test it
        $return['$_GET iterator']['result'] = is_array($return['$_GET iterator']['value']);
 
        // Plain myParam request from $_GET or URI
        $return['$_GET[\'myParam\']']['value'] = $_GET['myParam'];
 
        // Test it
        $return['$_GET[\'myParam\']']['result'] = is_string($_GET['myParam']);
 
        // Array of all params for myParam from $_GET and URI
        $return['$_GET[\'array:myParam\']']['value'] = $_GET['array:myParam'];
 
        // Test it
        $return['$_GET[\'array:myParam\']']['result'] = is_array($_GET['array:myParam']);
 
        // Plain $_GET or URI id request
        $return['$_GET[\'id\']']['value'] = $_GET['id'];
 
        // Test it
        $return['$_GET[\'id\']']['result'] = is_string($_GET['id']);
 
        // Pre-casted integer as plain request for $_GET|URI id
        $return['$_GET[\'id_as_int\']']['value'] = $_GET['id_as_int'];
 
        // Test it
        $return['$_GET[\'id_as_int\']']['result'] = is_int($_GET['id_as_int']);
 
        // Request $_GET id casted to integer
        $return['$_GET[\'int:id\']']['value'] = $_GET['int:id'];
 
        // Test it
        $return['$_GET[\'int:id\']']['result'] = is_int($_GET['int:id']);
 
        // Request array of URI and $_GET id casted to integer
        $return['$_GET[\'array:int:id\']']['value'] = $_GET['array:int:id'];
 
        // Test it
        $return['$_GET[\'array:int:id\']']['result'] = is_array($_GET['array:int:id']);
        if ($return['$_GET[\'array:int:id\']']['result'])
        {
            // This one is because of PHP bug, can do nothing with this
            $array = $_GET['array:int:id'];
 
            foreach ($array as $v)
            {
                if (!is_int($v))
                {
                    $return['$_GET[\'array:int:id\']']['result'] = false;
                    break;
                }
            }
        }
 
        // Request array of URI and $_GET id casted to float and then cos function applied
        $return['$_GET[\'array:float:cos:id\']']['value'] = $_GET['array:float:cos:id'];
 
        // Test it
        $return['$_GET[\'array:float:cos:id\']']['result'] = is_array($_GET['array:float:cos:id']);
        if ($return['$_GET[\'array:float:cos:id\']']['result'])
        {
            // This one is because of PHP bug, can do nothing with this
            $array = $_GET['array:float:cos:id'];
 
            foreach ($array as $v)
            {
                if (-1 >= $v && $v <= 1)
                {
                    $return['$_GET[\'array:float:cos:id\']']['result'] = false;
                    break;
                }
            }
        }
 
        // Request HTML escaped value for $_POST test variable
        $return['$_POST[\'escape:test\']']['value'] = $_POST['escape:test'];
 
        // Test it
        $return['$_POST[\'escape:test\']']['result'] = (bool)strpos($_POST['escape:test'],'&#62;');
 
        // Request SQL escaped value for $_POST test variable
        $return['$_POST[\'sql:sqltest\']']['value'] = $_POST['sql:sqltest'];
 
        // Test it
        $return['$_POST[\'sql:sqltest\']']['result'] = (bool)strpos($_POST['sql:sqltest'], "'\\\"");
 
        // Request prepared URI string for current set of $_GET and URI parameters
        $return['$_GET']['value'] = (string)$_GET;
 
        // Test it
        $return['$_GET']['result'] = (bool)strpos($_GET,'/');
        // SPLIT
 
        return $return;
    }
 
    public function timer()
    {
        return microtime(true) - $this->start;
    }
}
 
/**
 * Return colorized source with line numbers
 *
 * @param string $code Code to colorize
 * @param string $type Colorization type
 * @return string Colorized code with line numbers
 */
function outcode($code, $type)
{
    // Instantiate highlighter
    $highlight =& Text_Highlighter::factory($type);
 
    // Highlight library source
    $source = $highlight->highlight($code);
 
    // Generate string numbers
    $strnums = '<div class="strnums">';
    for($i = -1; $i < substr_count($source, "\n");$i++)
    {
        $strnums .= '<span>'.($i+2).'</span>';
    }
    $strnums .= '</div>';
 
    // Output source with string numbers
    return '<div class="source">'.$strnums.'<div class="listing">'.$source.'</div></div>';
}
 
// Register $_GET for site page
superGlobal::registerParam('action', array('download','source','contact','test'));
 
// Process pages
switch($_GET['action'])
{
    case 'download':
        // Package files array
        $package = array(
            'index.php', 'superglobals.php', 'license.txt', '.htaccess', 'index.html',
            'docs/ics.gif', 'docs/jquery.js', 'docs/style.css', 'docs/loading.gif'
        );
 
        $download = "superglobals.zip";
 
        // Iterate thru files to check if package was modified
        foreach ($package as $file)
        {
            // If modified - create zip again
            if (!file_exists($download) || filectime($file) > filectime($download))
            {
                // Instantiate zip archiver
                $zip = new ZipArchive();
                if ($zip->open($download, ZIPARCHIVE::CREATE) !== true) {
                    die("Cannot open <$download>.\n");
                }
 
                // Create package
                foreach ($package as $f)
                {
                    $zip->addFile($f,$f);
                }
 
                // Write and exit
                $zip->close();
                break;
            }
        }
 
        // Output zip file
        header("Content-type: application/octet-stream");
        header("Content-disposition: attachment; filename=".$download);
        die(file_get_contents($download));
    break;
 
    case 'source':
        die(outcode(file_get_contents('superglobals.php'), 'PHP'));
    break;
 
    case 'test':
        $unitTest = new superUnitTest();
 
        $tests = '';
        $results = '';
 
        // Prepare data for output
        try
        {
            // Create an instance
            $tests .= '<span>Instantiating class and filling arrays:</span>';
            $results .= '<span class="ok">'.$unitTest->instantiate().'</span>';
 
            // Perform tests
            foreach ($unitTest->test() as $test => $result)
            {
                $tests .= '<span>'.$test.'</span>';
 
                // Get formatted value
                ob_start();
                var_dump($result['value']);
                $value = htmlspecialchars(ob_get_clean());
 
                $results .= ($result['result']) ?
                    '<span class="ok">OK <a class="info" title="'.$value.'">['.$result['value'].']</a></span>' :
                    '<span class="error">ERROR</span>';
            }
            ;
        }
        catch(Exception $e)
        {
            $results .= '<span class="error">Caught exception: '.$e->getMessage().'</span>';
        }
 
        // Output testing results
        echo '<h1>Unit tests</h1>';
        echo '<div class="tests">'.$tests.'</div>';
        echo '<div class="results">'.$results.'</div>';
        echo '<div class="time">Generation time: '.$unitTest->timer().'</div>';
 
        $src = preg_split('~// SPLIT\n~', file_get_contents(__FILE__));
 
        // Output unit test source
        echo '<h1>Instantiation example</h1>';
        echo outcode("<?\r\n".$src[1]."\r\n?>",'PHP');
 
        echo '<h1>Usage</h1>';
        echo outcode("<?\r\n".$src[3]."\r\n?>",'PHP');
 
        echo '<h1>Full source</h1>';
        echo outcode(file_get_contents(__FILE__),'PHP');
    break;
 
    default:
        readfile('index.html');
    break;
}
 
?>