Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement TestSwarmContext (issue #127) #131

Merged
merged 5 commits into from Mar 22, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 12 additions & 7 deletions content/home.php
Expand Up @@ -61,11 +61,13 @@

/** @return bool: Whether the current user was found in the swarm */
function loadBrowsers($headingTitle, $mobile) {
global $swarmBrowser, $swarmDB;
global $swarmContext;
$bi = $swarmContext->getBrowserInfo();
$db = $swarmContext->getDB();

$foundSelf = false;

$rows = $swarmDB->getRows(str_queryf(
$rows = $db->getRows(str_queryf(
"SELECT
useragents.engine as engine,
useragents.name as name,
Expand All @@ -82,8 +84,8 @@ function loadBrowsers($headingTitle, $mobile) {
AND mobile = %s
ORDER BY engine, name;",
swarmdb_dateformat( strtotime( '1 minute ago' ) ),
$swarmBrowser->getBrowserCodename(),
$swarmBrowser->getBrowserVersion(),
$bi->getBrowserCodename(),
$bi->getBrowserVersion(),
$mobile
));

Expand Down Expand Up @@ -116,23 +118,26 @@ function loadBrowsers($headingTitle, $mobile) {
return $foundSelf;
}

$request = $swarmContext->getRequest();
$bi = $swarmContext->getBrowserInfo();

if ( $found ) { ?>
<div class="join">
<p><strong>TestSwarm Needs Your Help!</strong> You have a browser that we need to test against, you should join the swarm to help us out.</p>
<?php if ( !$swarmRequest->getSessionData( "username" ) ) { ?>
<?php if ( !$request->getSessionData( "username" ) ) { ?>
<form action="" method="get">
<input type="hidden" name="state" value="run"/>
<br/><strong>Username:</strong><br/>
<input type="text" name="user" value=""/>
<input type="submit" value="Join the Swarm"/>
</form>
<?php } else { ?>
<br/><p><strong>&raquo; <?php echo $swarmRequest->getSessionData( "username" ); ?></strong> <a href="<?php echo swarmpath("run/{$swarmRequest->getSessionData( "username" )}/" ); ?>">Start Running Tests</a></p>
<br/><p><strong>&raquo; <?php echo $request->getSessionData( "username" ); ?></strong> <a href="<?php echo swarmpath("run/{$request->getSessionData( "username" )}/" ); ?>">Start Running Tests</a></p>
<?php } ?>
</div>
<?php } else { ?>
<div class="join">
<p>TestSwarm doesn't need your help at this time. If you wish to help run tests you should load up one of the below browsers.</p>
<p>If you feel that this may be a mistake, copy the following information (<?php echo $swarmBrowser->getBrowserCodename(); ?> <?php echo $swarmBrowser->getBrowserVersion(); ?> <?php echo $swarmBrowser->getOsCodename(); ?>) and your <a href="http://useragentstring.com/">useragent string</a>, and post it to the <a href="//groups.google.com/group/testswarm">discussion group</a>.</a>
<p>If you feel that this may be a mistake, copy the following information (<?php echo $bi->getBrowserCodename(); ?> <?php echo $bi->getBrowserVersion(); ?> <?php echo $bi->getOsCodename(); ?>) and your <a href="http://useragentstring.com/">useragent string</a>, and post it to the <a href="//groups.google.com/group/testswarm">discussion group</a>.</a>
</div>
<?php }
7 changes: 5 additions & 2 deletions content/run.php
@@ -1,7 +1,10 @@
<?php
$bi = $swarmContext->getBrowserInfo();
?>
<div class="userinfo">
<div class="browser you">
<img src="<?php echo swarmpath( "images/{$swarmBrowser->getBrowserCodename()}.sm.png" ); ?>" class="browser-icon <?php echo $swarmBrowser->getBrowserCodename(); ?>" alt="<?php echo $swarmBrowser->getSwarmUserAgentName(); ?>" title="<?php echo $swarmBrowser->getSwarmUserAgentName(); ?>"/>
<span class="browser-name"><?php echo preg_replace('/\w+ /', "", $swarmBrowser->getSwarmUserAgentName()); ?></span>
<img src="<?php echo swarmpath( "images/{$bi->getBrowserCodename()}.sm.png" ); ?>" class="browser-icon <?php echo $bi->getBrowserCodename(); ?>" alt="<?php echo $bi->getSwarmUserAgentName(); ?>" title="<?php echo $bi->getSwarmUserAgentName(); ?>"/>
<span class="browser-name"><?php echo preg_replace('/\w+ /', "", $bi->getSwarmUserAgentName()); ?></span>
</div>

<h3><?php echo $username; ?></h3>
Expand Down
2 changes: 1 addition & 1 deletion content/tinder.php
Expand Up @@ -98,7 +98,7 @@ function get_status2($num, $fail, $error, $total){

}

$job_search = preg_replace( "/[^a-zA-Z ]/", "", $swarmRequest->getVal( "job", "" ) );
$job_search = preg_replace( "/[^a-zA-Z ]/", "", $swarmContext->getRequest()->getVal( "job", "" ) );
$job_search .= "%";

$search_result = mysql_queryf(
Expand Down
55 changes: 22 additions & 33 deletions inc/BrowserInfo.php
Expand Up @@ -7,8 +7,7 @@
* @package TestSwarm
*/
class BrowserInfo {

protected static $cache = array();
private $context;

protected $userAgent = "";
protected $browserCodename;
Expand All @@ -19,38 +18,15 @@ class BrowserInfo {
protected $swarmUserAgentName;

/**
* @param $context TestSwarmContext
* @param $userAgent string
* @return BrowserInfo
*/
public static function newFromUA( $userAgent ) {
// Cached already?
if ( isset( self::$cache[$userAgent] ) ) {
return self::$cache[$userAgent];
}

$bi = new self( $userAgent );
return self::$cache[$userAgent] = $bi;
}

/**
* Get information from the TestSwarm useragents table.
* @param $bi BrowserInfo
* @return array|false Database row or false if no matches.
*/
public static function findSwarmUAFromBI( BrowserInfo $bi ) {
global $swarmDB;

return $swarmDB->getRow(str_queryf(
"SELECT
id,
name
FROM
useragents
WHERE engine = %s
AND %s REGEXP version;",
$bi->getBrowserCodename(),
$bi->getBrowserVersion()
));
public static function newFromContext( TestSwarmContext $context, $userAgent ) {
$bi = new self();
$bi->context = $context;
$bi->parseUserAgent( $userAgent );
return $bi;
}

/** @return string */
Expand Down Expand Up @@ -94,7 +70,17 @@ public function isKnownInTestSwarm() {
}

public function loadSwarmUserAgentData() {
$uaRow = self::findSwarmUAFromBI( $this );
$uaRow = $this->context->getDB()->getRow(str_queryf(
"SELECT
id,
name
FROM
useragents
WHERE engine = %s
AND %s REGEXP version;",
$this->getBrowserCodename(),
$this->getBrowserVersion()
));
if ( $uaRow ) {
$this->swarmUserAgentID = $uaRow->id ? intval( $uaRow->id ) : null;
$this->swarmUserAgentName = $uaRow->name ? (string)$uaRow->name : null;
Expand All @@ -107,7 +93,7 @@ public function loadSwarmUserAgentData() {
* Instances may not be created directly, use the static newFromUA method instead
* @param $userAgent string
*/
private function __construct( $userAgent ) {
private function parseUserAgent( $userAgent ) {
$lcUA = strtolower( $userAgent );

// Version
Expand Down Expand Up @@ -202,4 +188,7 @@ private function __construct( $userAgent ) {

return $this;
}

/** Don't allow direct instantiations of this class, use newFromContext instead */
private function __construct() {}
}
38 changes: 31 additions & 7 deletions inc/Database.php
Expand Up @@ -7,24 +7,40 @@
* @package TestSwarm
*/
class Database {
private $context;

protected $host, $username, $password, $dbname;
protected $conn;
protected $isOpen = false;

public function __construct( $host, $username, $password, $dbname = false ) {
$this->checkEnvironment();
/**
* Creates a Database object, opens the connection and returns the instance.
*
* @param context TestSwarmContext
* @param $connType int: [optional]
*/

$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
return $this;
public static function newFromContext( TestSwarmContext $context, $connType = DBCON_DEFAULT ) {
$dbConf = $context->getConf()->database;
$db = new self();

$db->context = $context;
$db->host = $dbConf->host;
$db->username = $dbConf->username;
$db->password = $dbConf->password;
$db->dbname = $dbConf->database;

$db->open( $connType );

return $db;
}

/**
* @param $connType int: DBCON_DEFAULT or DBCON_PERSISTENT.
*/
public function open( $connType = DBCON_DEFAULT ) {
$this->close();

switch ( $connType ) {
case DBCON_DEFAULT:
$this->conn = mysql_connect( $this->host, $this->username, $this->password, /*force_new=*/true );
Expand All @@ -35,9 +51,11 @@ public function open( $connType = DBCON_DEFAULT ) {
default:
throw new SwarmException( "Invalid connection type." );
}

if ( !$this->conn ) {
throw new SwarmException( "Connection to {$this->host} failed.\nMySQL Error " . $this->lastErrNo() . ": " . $this->lastErrMsg() );
}

if ( $this->dbname ) {
$isOK = mysql_select_db( $this->dbname, $this->conn );
if ( !$isOK ) {
Expand All @@ -46,6 +64,7 @@ public function open( $connType = DBCON_DEFAULT ) {
} else {
$isOK = (bool)$this->conn;
}

$this->isOpen = $isOK;
return $this;
}
Expand Down Expand Up @@ -91,6 +110,7 @@ public function getNumRows( $res ) {

/**
* Queries other than SELECT, such as DELETE, UPDATE and INSERT.
* @return resource|false
*/
public function query( $sql ) {
return $this->doQuery( $sql );
Expand Down Expand Up @@ -142,4 +162,8 @@ protected function checkEnvironment() {
throw new SwarmException( "MySQL functions missing." );
}
}

private function __construct() {
$this->checkEnvironment();
}
}
66 changes: 66 additions & 0 deletions inc/TestSwarm.php
@@ -0,0 +1,66 @@
<?php
/**
* Wrapper class containing various request-specific objects.
* Each of these objects is created only once for the context.
* The creation happends on-demand and is put in a private cache.
*
* @author Timo Tijhof, 2012
* @since 0.3.0
* @package TestSwarm
*/
class TestSwarmContext {
private $browserInfo, $conf, $db, $request;

/**
* The context is self-initializing. The only thing it
* needs to be passed is an array with all setting keys from testswarm.ini
* (including ones commented out in the sample file, it has to contain them all)
* Population of default values of optional settings happens in init.php
* @param $config array
*/
public function __construct( Array $config ) {
$conf = new stdClass;
foreach ( $config as $key => $val ) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this makes sense? Checking for an array and casting it to an object?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, conf is a 2-level deep object (an object with objects). The variable given is a fresh ini parse, which will be an array of arrays. Casting the main variable to an object will only cast the root level, so I'm looping instead. Although right now all settings are in a subgroup, there may be root settings in the future, hence the check for an array first.

If it's a group, cast the array to an object. Otherwise keep it (a string, number or boolean) as is. See also ./config/testswarm-sample.ini and init.php

$conf->$key = is_array( $val ) ? (object)$val : $val;
}
$this->conf = $conf;
}

public function getBrowserInfo() {
if ( $this->browserInfo === null ) {
$ua = isset( $_SERVER["HTTP_USER_AGENT"] ) ? $_SERVER["HTTP_USER_AGENT"] : "";
$this->browserInfo = BrowserInfo::newFromContext( $this, $ua );
}
return $this->browserInfo;
}

/**
* Get the configuration object
* @return stdClass
*/
public function getConf() {
return $this->conf;
}

/**
* Get the Database object
* @return Database
*/
public function getDB() {
if ( $this->db === null ) {
$this->db = Database::newFromContext( $this );
}
return $this->db;
}

/**
* Get the WebRequest object
* @return WebRequest
*/
public function getRequest() {
if ( $this->request === null ) {
$this->request = new WebRequest( $this );
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe also use a static factory method to be consistent... "newFromContext"

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}
return $this->request;
}
}
5 changes: 4 additions & 1 deletion inc/WebRequest.php
Expand Up @@ -11,10 +11,13 @@
*/

class WebRequest {
private $context;

protected $raw;
private $ip;

function __construct() {
function __construct( TestSwarmContext $context ) {
$this->context = $context;
$this->checkMagicQuotes();

// POST overrides GET data
Expand Down