From e2d95ce49a85b3e0d3c0ede1ce3b215eb1cc2566 Mon Sep 17 00:00:00 2001 From: Remi Collet Date: Mon, 7 Jun 2010 00:08:06 +0800 Subject: create a class folder and move FedoraClient --- class/FedoraClient.php | 267 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 class/FedoraClient.php (limited to 'class') diff --git a/class/FedoraClient.php b/class/FedoraClient.php new file mode 100644 index 0000000..e003a03 --- /dev/null +++ b/class/FedoraClient.php @@ -0,0 +1,267 @@ + + * + * @category Main + * @package FedoraClient + * + * @author Remi Collet + * @author Johan Cwiklinski + * @copyright 2010 Remi Collet + * @license http://www.gnu.org/licenses/lgpl-2.1.txt LGPL License 2.1 or (at your option) any later version + * @link http://github.com/remicollet/rpmphp/ + * @since The begining of times. + */ + +define('FEDORACLIENT_VERSION', '0.1.0-dev'); + +if (!function_exists('curl_version')) { + die("curl extension required\n"); +} +require_once 'Cache/Lite.php'; + +abstract class FedoraClient +{ + private $url; + private $agent; + private $debug = 0; + protected $cache; + + function __construct ($url, array $options) + { + $dir = "/tmp/cachelite-".posix_getlogin()."/"; + @mkdir($dir); + $this->cache = new Cache_Lite( + array( + 'memoryCaching' => true, + 'cacheDir' => $dir, + 'automaticSerialization' => true + ) + ); + + $this->url = $url; + if (isset($options['agent']) && !empty($options['agent'])) { + $this->agent = $options['agent']; + } else { + $this->agent = 'Fedora PHPClient/'.FEDORACLIENT_VERSION; + } + if (isset($options['debug']) && intval($options['debug'])>0) { + $this->debug = intval($options['debug']); + } + $this->logDebug( + 3, + __CLASS__."::".__FUNCTION__.": url='$url', agent='".$this->agent."'" + ); + } + + function logDebug($level, $msg) + { + if ($this->debug>=$level) { + echo "[debug][$level] $msg\n"; + } + } + + function sendRequest($method, array $options=array()) + { + $curl = curl_init(); + // And join to make our url. + $url = $this->url.$method; + curl_setopt($curl, CURLOPT_URL, $url); + // Boilerplate so pycurl processes cookies + curl_setopt($curl, CURLOPT_COOKIEFILE, '/dev/null'); + + //# Associate with the response to accumulate data + $this->data=''; + curl_setopt($curl, CURLOPT_WRITEFUNCTION, array($this, 'receive')); + + // Follow redirect + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_MAXREDIRS, 5); + + // Set standard headers + curl_setopt( + $curl, + CURLOPT_HTTPHEADER, + array('User-agent: '.$this->agent, 'Accept: application/json') + ); + + // run the request + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__.": call '$url'" + ); + curl_exec($curl); + + + // Check for auth failures + // Note: old TG apps returned 403 Forbidden on authentication failures. + // Updated apps return 401 Unauthorized + // We need to accept both until all apps are updated to return 401. + $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); + if ($http_status==401 || $http_status==403) { + $this->logDebug( + 1, + __CLASS__."::".__FUNCTION__. + ": http_status '$http_status' Authentication failed logging in" + ); + return array(); + } else if ($http_status>=400) { + $this->logDebug( + 1, + __CLASS__."::".__FUNCTION__. + ": http_status '$http_status' Unknown HTTP Server Response" + ); + return array(); + } else { + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__.": http_status '$http_status'" + ); + } + + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__.": close connexion" + ); + + curl_close($curl); + return json_decode($this->data, true); + } + + function receive($curl, $data) + { + $this->logDebug( + 9, + __CLASS__."::".__FUNCTION__.": $data" + ); + $this->data .= $data; + return strlen($data); + } +} + + +class FedoraPkgdb extends FedoraClient +{ + + function __construct (array $options=array()) + { + parent::__construct('https://admin.fedoraproject.org/pkgdb/', $options); + $this->logDebug( + 3, + __CLASS__."::".__FUNCTION__ + ); + } + + function getBranches($refresh=false) + { + $rep = ($refresh ? false : $this->cache->get(__FUNCTION__, __CLASS__)); + if ($rep) { + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__."() get from cache" + ); + } else { + $rep =$this->sendRequest('collections'); + $this->cache->save($rep, __FUNCTION__, __CLASS__); + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__."() save to cache" + ); + } + + $branches = array(); + if (isset($rep['collections'])) { + foreach ($rep['collections'] as $coll) { + if (isset($coll[0]['branchname'])) { + $branches[$coll[0]['branchname']] = $coll[0]; + } + } + } + return $branches; + } + + function getPackageInfo($name, $refresh=false) + { + $url="acls/name/$name"; + $rep = ($refresh ? false : $this->cache->get($url, __CLASS__)); + if ($rep) { + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__."($name) get from cache" + ); + } else { + $rep =$this->sendRequest($url); + $this->cache->save($rep, $url, __CLASS__); + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__."($name) save to cache" + ); + } + + if (isset($rep['status']) && !$rep['status']) { + $this->logDebug( + 1, + __CLASS__."::".__FUNCTION__."($name) ".$rep['message'] + ); + return false; + } + $branches = array(); + foreach ($rep['packageListings'] as $pack) { + $branches[$pack['collection']['branchname']] = $pack; + } + return $branches; + } + + function getBranch($name, $refresh=false) + { + $branches = $this->getBranches($refresh); + + if (isset($branches[$name])) { + return $branches[$name]; + } + return false; + } + + function getCritPath($refresh=false) + { + $url="lists/critpath"; + $rep = ($refresh ? false : $this->cache->get($url, __CLASS__)); + if ($rep) { + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__." get from cache" + ); + } else { + $rep =$this->sendRequest($url); + $this->cache->save($rep, $url, __CLASS__); + $this->logDebug( + 2, + __CLASS__."::".__FUNCTION__." save to cache" + ); + } + return $rep['pkgs']; + } +} +?> -- cgit From d1c15227b18177ff0d3a33ce8f8ee2c563a5cf4d Mon Sep 17 00:00:00 2001 From: Remi Collet Date: Mon, 7 Jun 2010 02:35:36 +0800 Subject: Introduce CommonTable, TableIterator, TablePearRepo classes (and use it in refresh) --- class/CommonTable.php | 368 +++++++++++++++++++++++++++++++++++++++++++++++++ class/FedoraClient.php | 2 + 2 files changed, 370 insertions(+) create mode 100644 class/CommonTable.php (limited to 'class') diff --git a/class/CommonTable.php b/class/CommonTable.php new file mode 100644 index 0000000..721a224 --- /dev/null +++ b/class/CommonTable.php @@ -0,0 +1,368 @@ +. + * + * @category Main + * @package RPMPHP + * + * @author Remi Collet + * @author Johan Cwiklinski + * @copyright 2010 Remi Collet + * @license http://www.gnu.org/licenses/agpl-3.0-standalone.html AGPL License 3.0 or (at your option) any later version + * @link http://github.com/remicollet/rpmphp/ + * @since The begining of times. +*/ + +abstract class CommonTable { + + protected $db; + protected $table; + + function __construct(PDO $db, $table) { + + $this->db = $db; + $this->table = $table; + + if (!$this->existsTable($table)) { + $this->createTable($table); + } + } + + public function existsTable($table) { + $req = new TableIterator($this->db, "SHOW TABLES LIKE '$table'"); + foreach ($req as $data) { + return true; + } + return false; + } + + protected function exec($sql) { + $res = $this->db->exec($sql); + if ($res===false) { + $err = $this->db->errorInfo(); + throw new Exception($err[2]); + } + } + + protected function add(array $fields) { + $col = array(); + $val = array(); + foreach ($fields as $name => $value) { + $col[] = "`$name`"; + if (is_null($value)) { + $val[] = 'NULL'; + } else if (is_numeric($value)) { + $val[] = $value; + } else { + $val[] = "'$value'"; + } + } + $sql = "INSERT INTO `".$this->table."` (".implode(',',$col).") + VALUE (".implode(',',$val).")"; + $this->exec($sql); + } + abstract protected function createTable(); + + /** + * Instanciate a Simple DBIterator + * + * Examples = + * foreach ($DB->request("select * from glpi_states") as $data) { ... } + * foreach ($DB->request("glpi_states") as $ID => $data) { ... } + * foreach ($DB->request("glpi_states", "ID=1") as $ID => $data) { ... } + * foreach ($DB->request("glpi_states", "", "name") as $ID => $data) { ... } + * foreach ($DB->request("glpi_computers",array("name"=>"SBEI003W","entities_id"=>1),array("serial","otherserial")) { ... } + * + * @param $tableorsql table name, array of names or SQL query + * @param $crit string or array of field/values, ex array("id"=>1), if empty => all rows + * + * Examples = + * array("id"=>NULL) + * array("OR"=>array("id"=>1, "NOT"=>array("state"=>3))); + * array("AND"=>array("id"=>1, array("NOT"=>array("state"=>array(3,4,5),"toto"=>2)))) + * + * param 'FIELDS' name or array of field names + * param 'ORDER' filed name or array of field names + * param 'LIMIT' max of row to retrieve + * param 'START' first row to retrieve + * + * @return DBIterator + **/ + public function request ($crit='') { + return new TableIterator ($this->db, $this->table, $crit); + } + + public function getAllArray($fieldkey, $fieldvalue) { + $crit = array('FIELDS' => array($fieldkey, $fieldvalue), + 'ORDER' => $fieldkey); + $tab = array(); + foreach ($this->request($crit) as $data) { + $tab[$data[$fieldkey]] = $data[$fieldvalue]; + } + return $tab; + } +} + +class TablePearRepo extends CommonTable { + + function __construct($db) { + parent::__construct($db, 'pearrepo'); + } + + protected function createTable() { + + // Table schema + $sql = "CREATE TABLE `pearrepo` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `alias` varchar(30) NOT NULL, + `url` varchar(255) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `alias` (`alias`) + ) DEFAULT CHARSET=utf8"; + + $this->exec($sql); + + // Some known repo, other could be add manually + // no reply from "phpdb" => "pear.phpdb.org" + $channels = array( + "pear" => "pear.php.net" + ,"doctrine" => "pear.phpdoctrine.org" + ,"ezc" => "components.ez.no" + ,"pdepend" => "pear.pdepend.org" + ,"phing" => "pear.phing.info" + ,"phpmd" => "pear.phpmd.org" + ,"phpunit" => "pear.phpunit.de" + ,"swift" => "pear.swiftmailer.org" + ,"symphony" => "pear.symfony-project.com" + ); + + foreach ($channels as $alias => $url) { + $this->add(array('alias'=>$alias, 'url'=>$url)); + } + } + + function getAllRepo() { + return $this->getAllArray('alias', 'url'); + } +} + +/* + * Helper for simple query => see $DBmysql->requete + */ +class TableIterator implements Iterator { + + private $con; + private $sql; + private $res = false; + private $row; + private $pos; + + /** + * Constructor + * + * @param $dbconnexion Database Connnexion (must be a CommonDBTM object) + * @param $table table name + * @param $crit string or array of filed/values, ex array("id"=>1), if empty => all rows + * + **/ + function __construct (PDO $dbconnexion, $table, $crit='') { + + $this->conn = $dbconnexion; + if (is_string($table) && strpos($table, " ")) { + $this->sql = $table; + } else { + // check field, orderby, limit, start in criterias + $field=""; + $orderby=""; + $limit=0; + $start=0; + + if (is_array($crit) && count($crit)) { + foreach ($crit as $key => $val) { + if ($key==="FIELDS") { + $field = $val; + unset($crit[$key]); + } else if ($key==="ORDER") { + $orderby = $val; + unset($crit[$key]); + } else if ($key==="LIMIT") { + $limit = $val; + unset($crit[$key]); + } else if ($key==="START") { + $start = $val; + unset($crit[$key]); + } + } + } + + // SELECT field list + if (is_array($field)) { + $this->sql = ""; + foreach ($field as $t => $f) { + if (is_numeric($t)) { + $this->sql .= (empty($this->sql) ? "SELECT " : ",") . $f; + } else if (is_array($f)) { + $this->sql .= (empty($this->sql) ? "SELECT $t." : ",$t.") . implode(",$t.",$f); + } else { + $this->sql .= (empty($this->sql) ? "SELECT " : ",") . "$t.$f"; + } + } + } else if (empty($field)) { + $this->sql = "SELECT *"; + } else { + $this->sql = "SELECT `$field`"; + } + // FROM table list + if (is_array($table)) { + $this->sql .= " FROM `".implode("`, `",$table)."`"; + } else { + $this->sql .= " FROM `$table`"; + } + // WHERE criteria list + if (!empty($crit)) { + print_r($crit); + $this->sql .= " WHERE ".$this->analyseCrit($crit); + } + // ORDER BY + if (is_array($orderby)) { + $this->sql .= " ORDER BY `".implode("`, `",$orderby)."`"; + } else if (!empty($orderby)) { + $this->sql .= " ORDER BY `$orderby`"; + } + if (is_numeric($limit) && $limit>0) { + $this->sql .= " LIMIT $limit"; + if (is_numeric($start) && $start>0) { + $this->sql .= " OFFSET $start"; + } + } + } + //echo "SQL: ".$this->sql."\n"; + $this->res = $this->conn->prepare($this->sql); + if ($this->res===false) { + $err = $this->db->errorInfo(); + throw new Exception($err[2]); + } + + $this->pos = -1; + } + + function __destruct () { + + if ($this->res) { + $this->res->closeCursor(); + } + } + + private function analyseCrit ($crit, $bool="AND") { + + if (!is_array($crit)) { + return $crit; + } + $ret = ""; + foreach ($crit as $name => $value) { + if (!empty($ret)) { + $ret .= " $bool "; + } + if (is_numeric($name)) { + // No Key case => recurse. + $ret .= "(" . $this->analyseCrit($value, $bool) . ")"; + } else if ($name==="OR" || $name==="AND") { + // Binary logical operator + $ret .= "(" . $this->analyseCrit($value, $name) . ")"; + } else if ($name==="NOT") { + // Uninary logicial operator + $ret .= " NOT (" . $this->analyseCrit($value, "AND") . ")"; + } else if ($name==="FKEY") { + // Foreign Key condition + if (is_array($value) && count($value)==2) { + reset($value); + list($t1,$f1)=each($value); + list($t2,$f2)=each($value); + $ret .= (is_numeric($t1) ? "$f1" : "$t1.$f1") . "=" . + (is_numeric($t2) ? "$f2" : "$t2.$f2"); + } else { + trigger_error("BAD FOREIGN KEY", E_USER_ERROR); + } + } else if (is_array($value)) { + // Array of Value + $ret .= "$name IN ('". implode("','",$value)."')"; + } else if (is_null($value)) { + // NULL condition + $ret .= "$name IS NULL"; + } else if (is_numeric($value)) { + // Integer + $ret .= "$name=$value"; + } else { + // String + $ret .= "$name='$value'"; + } + } + return $ret; + } + + public function rewind () { + + if ($this->res && $this->pos>=0) { + $this->res->closeCursor(); + $this->pos = -1; + } + + if ($this->res && $this->pos<0) { + if (!$this->res->execute()) { + $err = $this->res->errorInfo(); + throw new Exception($err[2]); + } + } + return $this->next(); + } + + public function current() { + + return $this->row; + } + + public function key() { + + return (isset($this->row["id"]) ? $this->row["id"] : $this->pos); + } + + public function next() { + + if (!$this->res) { + return false; + } + $this->row = $this->res->fetch(PDO::FETCH_ASSOC); + $this->pos++; + return $this->row; + } + + public function valid() { + + return $this->res && $this->row; + } + + public function numrows() { + + return ($this->res ? $this->res->rowCount() : 0); + } +} +?> diff --git a/class/FedoraClient.php b/class/FedoraClient.php index e003a03..43d9dce 100644 --- a/class/FedoraClient.php +++ b/class/FedoraClient.php @@ -227,10 +227,12 @@ class FedoraPkgdb extends FedoraClient ); return false; } + $this->logDebug(8,print_r($rep,true)); $branches = array(); foreach ($rep['packageListings'] as $pack) { $branches[$pack['collection']['branchname']] = $pack; } + $this->logDebug(7,print_r($branches,true)); return $branches; } -- cgit From 597c487cb99caf6398ea98b71005ac0e43ca24a0 Mon Sep 17 00:00:00 2001 From: Remi Collet Date: Mon, 7 Jun 2010 02:57:48 +0800 Subject: add some docs --- class/CommonTable.php | 63 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 8 deletions(-) (limited to 'class') diff --git a/class/CommonTable.php b/class/CommonTable.php index 721a224..66e1c27 100644 --- a/class/CommonTable.php +++ b/class/CommonTable.php @@ -37,6 +37,12 @@ abstract class CommonTable { protected $db; protected $table; + /** + * Instanciate a CommonTable + * + * @param $db object PDO instance of the DB connection + * @param $table string with table name + */ function __construct(PDO $db, $table) { $this->db = $db; @@ -47,6 +53,13 @@ abstract class CommonTable { } } + /** + * Check if the table already exists + * + * @param $table string with table name + * + * @return boolean + */ public function existsTable($table) { $req = new TableIterator($this->db, "SHOW TABLES LIKE '$table'"); foreach ($req as $data) { @@ -55,6 +68,11 @@ abstract class CommonTable { return false; } + /** + * Execute an SQL statement (INSERT, DELETE, ...) + * + * @param $sql string + */ protected function exec($sql) { $res = $this->db->exec($sql); if ($res===false) { @@ -63,6 +81,11 @@ abstract class CommonTable { } } + /** + * Add a new row in the table + * + * @param fields hashtable of fieldname => value + */ protected function add(array $fields) { $col = array(); $val = array(); @@ -80,19 +103,21 @@ abstract class CommonTable { VALUE (".implode(',',$val).")"; $this->exec($sql); } + + /** + * Create the table + */ abstract protected function createTable(); /** - * Instanciate a Simple DBIterator + * Instanciate a Simple TableIterator on the current table * * Examples = - * foreach ($DB->request("select * from glpi_states") as $data) { ... } - * foreach ($DB->request("glpi_states") as $ID => $data) { ... } - * foreach ($DB->request("glpi_states", "ID=1") as $ID => $data) { ... } - * foreach ($DB->request("glpi_states", "", "name") as $ID => $data) { ... } - * foreach ($DB->request("glpi_computers",array("name"=>"SBEI003W","entities_id"=>1),array("serial","otherserial")) { ... } + * foreach ($DB->request() as $ID => $data) { ... } + * foreach ($DB->request("ID=1") as $ID => $data) { ... } + * foreach ($DB->request("", "name") as $ID => $data) { ... } + * foreach ($DB->request(array("name"=>"SBEI003W","entities_id"=>1),array("serial","otherserial")) { ... } * - * @param $tableorsql table name, array of names or SQL query * @param $crit string or array of field/values, ex array("id"=>1), if empty => all rows * * Examples = @@ -111,6 +136,14 @@ abstract class CommonTable { return new TableIterator ($this->db, $this->table, $crit); } + /** + * Retrieve 2 columns of all the table's row in a hashtable + * + * @param $fieldkey string name of the field to use as index + * @param $fieldvalue string name of the field to use as value + * + * @return hashtable + */ public function getAllArray($fieldkey, $fieldvalue) { $crit = array('FIELDS' => array($fieldkey, $fieldvalue), 'ORDER' => $fieldkey); @@ -124,10 +157,16 @@ abstract class CommonTable { class TablePearRepo extends CommonTable { + /** + * Instanciate a TablePearRepo to manage pearrepo table + */ function __construct($db) { parent::__construct($db, 'pearrepo'); } + /** + * Create the table and populate it with known repo + */ protected function createTable() { // Table schema @@ -160,13 +199,18 @@ class TablePearRepo extends CommonTable { } } + /** + * Retrieve all the known repository + * + * @return hastable of alias => url + */ function getAllRepo() { return $this->getAllArray('alias', 'url'); } } /* - * Helper for simple query => see $DBmysql->requete + * Helper for simple query => use directly or through CommonTable::request() */ class TableIterator implements Iterator { @@ -272,6 +316,9 @@ class TableIterator implements Iterator { } } + /** + * Build WHERE clause + */ private function analyseCrit ($crit, $bool="AND") { if (!is_array($crit)) { -- cgit From 3a855288f1b5977465a8d952cb151b27ab24e446 Mon Sep 17 00:00:00 2001 From: Remi Collet Date: Mon, 7 Jun 2010 03:21:06 +0800 Subject: missing ref to GLPI --- class/CommonTable.php | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'class') diff --git a/class/CommonTable.php b/class/CommonTable.php index 66e1c27..a913edd 100644 --- a/class/CommonTable.php +++ b/class/CommonTable.php @@ -211,6 +211,10 @@ class TablePearRepo extends CommonTable { /* * Helper for simple query => use directly or through CommonTable::request() + * + * Freely inspired from DBmysqlIterator class from GLPI + * (already written by Remi, and ported to PDO) + * See http://www.glpi-project.org/ */ class TableIterator implements Iterator { -- cgit From a68fe1f14112df3481479eb3f736cf2fd879a324 Mon Sep 17 00:00:00 2001 From: "Johan \"Papa\" Cwiklinski" Date: Mon, 7 Jun 2010 20:21:31 +0200 Subject: Begin PEAR coding standards ; refs #48 --- class/CommonTable.php | 190 ++++++++++++++++++++++++++++++++++---------------- 1 file changed, 129 insertions(+), 61 deletions(-) (limited to 'class') diff --git a/class/CommonTable.php b/class/CommonTable.php index a913edd..1ed47f8 100644 --- a/class/CommonTable.php +++ b/class/CommonTable.php @@ -32,19 +32,19 @@ * @since The begining of times. */ -abstract class CommonTable { - +abstract class CommonTable +{ protected $db; protected $table; /** * Instanciate a CommonTable * - * @param $db object PDO instance of the DB connection - * @param $table string with table name + * @param object $db PDO instance of the DB connection + * @param string $table with table name */ - function __construct(PDO $db, $table) { - + function __construct(PDO $db, $table) + { $this->db = $db; $this->table = $table; @@ -56,11 +56,12 @@ abstract class CommonTable { /** * Check if the table already exists * - * @param $table string with table name + * @param string $table with table name * * @return boolean */ - public function existsTable($table) { + public function existsTable($table) + { $req = new TableIterator($this->db, "SHOW TABLES LIKE '$table'"); foreach ($req as $data) { return true; @@ -71,9 +72,10 @@ abstract class CommonTable { /** * Execute an SQL statement (INSERT, DELETE, ...) * - * @param $sql string + * @param string $sql The SQL clause */ - protected function exec($sql) { + protected function exec($sql) + { $res = $this->db->exec($sql); if ($res===false) { $err = $this->db->errorInfo(); @@ -84,9 +86,10 @@ abstract class CommonTable { /** * Add a new row in the table * - * @param fields hashtable of fieldname => value + * @param hashtable $fields hashtable of fieldname => value */ - protected function add(array $fields) { + protected function add(array $fields) + { $col = array(); $val = array(); foreach ($fields as $name => $value) { @@ -99,8 +102,8 @@ abstract class CommonTable { $val[] = "'$value'"; } } - $sql = "INSERT INTO `".$this->table."` (".implode(',',$col).") - VALUE (".implode(',',$val).")"; + $sql = "INSERT INTO `".$this->table."` (".implode(',', $col).") + VALUE (".implode(',', $val).")"; $this->exec($sql); } @@ -118,12 +121,22 @@ abstract class CommonTable { * foreach ($DB->request("", "name") as $ID => $data) { ... } * foreach ($DB->request(array("name"=>"SBEI003W","entities_id"=>1),array("serial","otherserial")) { ... } * - * @param $crit string or array of field/values, ex array("id"=>1), if empty => all rows + * @param string|array $crit string or array of field/values, + * ex array("id"=>1), if empty => all rows * * Examples = - * array("id"=>NULL) - * array("OR"=>array("id"=>1, "NOT"=>array("state"=>3))); - * array("AND"=>array("id"=>1, array("NOT"=>array("state"=>array(3,4,5),"toto"=>2)))) + * array("id"=>NULL) + * array("OR"=>array("id"=>1, "NOT"=>array("state"=>3))); + * array( + * "AND"=>array( + * "id"=>1,array( + * "NOT"=>array( + * "state"=>array(3,4,5), + * "toto"=>2 + * ) + * ) + * ) + * ) * * param 'FIELDS' name or array of field names * param 'ORDER' filed name or array of field names @@ -132,19 +145,21 @@ abstract class CommonTable { * * @return DBIterator **/ - public function request ($crit='') { + public function request ($crit='') + { return new TableIterator ($this->db, $this->table, $crit); } /** * Retrieve 2 columns of all the table's row in a hashtable * - * @param $fieldkey string name of the field to use as index - * @param $fieldvalue string name of the field to use as value + * @param string $fieldkey name of the field to use as index + * @param string $fieldvalue name of the field to use as value * * @return hashtable */ - public function getAllArray($fieldkey, $fieldvalue) { + public function getAllArray($fieldkey, $fieldvalue) + { $crit = array('FIELDS' => array($fieldkey, $fieldvalue), 'ORDER' => $fieldkey); $tab = array(); @@ -155,19 +170,26 @@ abstract class CommonTable { } } -class TablePearRepo extends CommonTable { +class TablePearRepo extends CommonTable +{ /** * Instanciate a TablePearRepo to manage pearrepo table + * + * @param object $db PDO instance of the DB connection */ - function __construct($db) { + function __construct($db) + { parent::__construct($db, 'pearrepo'); } /** * Create the table and populate it with known repo + * + * @return void */ - protected function createTable() { + protected function createTable() + { // Table schema $sql = "CREATE TABLE `pearrepo` ( @@ -204,20 +226,21 @@ class TablePearRepo extends CommonTable { * * @return hastable of alias => url */ - function getAllRepo() { + function getAllRepo() + { return $this->getAllArray('alias', 'url'); } } -/* +/** * Helper for simple query => use directly or through CommonTable::request() * * Freely inspired from DBmysqlIterator class from GLPI * (already written by Remi, and ported to PDO) * See http://www.glpi-project.org/ */ -class TableIterator implements Iterator { - +class TableIterator implements Iterator +{ private $con; private $sql; private $res = false; @@ -227,12 +250,14 @@ class TableIterator implements Iterator { /** * Constructor * - * @param $dbconnexion Database Connnexion (must be a CommonDBTM object) - * @param $table table name - * @param $crit string or array of filed/values, ex array("id"=>1), if empty => all rows - * - **/ - function __construct (PDO $dbconnexion, $table, $crit='') { + * @param CommonDBTM $dbconnexion Database Connnexion + * (must be a CommonDBTM object) + * @param string $table table name + * @param string|array $crit string or array of filed/values, + * ex array("id"=>1), if empty => all rows + */ + function __construct (PDO $dbconnexion, $table, $crit='') + { $this->conn = $dbconnexion; if (is_string($table) && strpos($table, " ")) { @@ -267,11 +292,14 @@ class TableIterator implements Iterator { $this->sql = ""; foreach ($field as $t => $f) { if (is_numeric($t)) { - $this->sql .= (empty($this->sql) ? "SELECT " : ",") . $f; + $this->sql .= (empty($this->sql) + ? "SELECT " : ",") . $f; } else if (is_array($f)) { - $this->sql .= (empty($this->sql) ? "SELECT $t." : ",$t.") . implode(",$t.",$f); + $this->sql .= (empty($this->sql) + ? "SELECT $t." : ",$t.") . implode(",$t.", $f); } else { - $this->sql .= (empty($this->sql) ? "SELECT " : ",") . "$t.$f"; + $this->sql .= (empty($this->sql) + ? "SELECT " : ",") . "$t.$f"; } } } else if (empty($field)) { @@ -281,18 +309,18 @@ class TableIterator implements Iterator { } // FROM table list if (is_array($table)) { - $this->sql .= " FROM `".implode("`, `",$table)."`"; + $this->sql .= " FROM `".implode("`, `", $table)."`"; } else { $this->sql .= " FROM `$table`"; } // WHERE criteria list if (!empty($crit)) { print_r($crit); - $this->sql .= " WHERE ".$this->analyseCrit($crit); + $this->sql .= " WHERE ".$this->_analyseCrit($crit); } // ORDER BY if (is_array($orderby)) { - $this->sql .= " ORDER BY `".implode("`, `",$orderby)."`"; + $this->sql .= " ORDER BY `".implode("`, `", $orderby)."`"; } else if (!empty($orderby)) { $this->sql .= " ORDER BY `$orderby`"; } @@ -313,8 +341,11 @@ class TableIterator implements Iterator { $this->pos = -1; } - function __destruct () { - + /** + * Class destructor + */ + function __destruct () + { if ($this->res) { $this->res->closeCursor(); } @@ -322,8 +353,14 @@ class TableIterator implements Iterator { /** * Build WHERE clause + * + * @param TODO $crit To document + * @param TODO $bool To document + * + * @return To document */ - private function analyseCrit ($crit, $bool="AND") { + private function _analyseCrit ($crit, $bool="AND") + { if (!is_array($crit)) { return $crit; @@ -334,14 +371,14 @@ class TableIterator implements Iterator { $ret .= " $bool "; } if (is_numeric($name)) { - // No Key case => recurse. - $ret .= "(" . $this->analyseCrit($value, $bool) . ")"; + // No Key case => recurse. + $ret .= "(" . $this->_analyseCrit($value, $bool) . ")"; } else if ($name==="OR" || $name==="AND") { - // Binary logical operator - $ret .= "(" . $this->analyseCrit($value, $name) . ")"; + // Binary logical operator + $ret .= "(" . $this->_analyseCrit($value, $name) . ")"; } else if ($name==="NOT") { // Uninary logicial operator - $ret .= " NOT (" . $this->analyseCrit($value, "AND") . ")"; + $ret .= " NOT (" . $this->_analyseCrit($value, "AND") . ")"; } else if ($name==="FKEY") { // Foreign Key condition if (is_array($value) && count($value)==2) { @@ -355,7 +392,7 @@ class TableIterator implements Iterator { } } else if (is_array($value)) { // Array of Value - $ret .= "$name IN ('". implode("','",$value)."')"; + $ret .= "$name IN ('". implode("','", $value)."')"; } else if (is_null($value)) { // NULL condition $ret .= "$name IS NULL"; @@ -370,7 +407,13 @@ class TableIterator implements Iterator { return $ret; } - public function rewind () { + /** + * To document + * + * @return To document + */ + public function rewind () + { if ($this->res && $this->pos>=0) { $this->res->closeCursor(); @@ -386,18 +429,33 @@ class TableIterator implements Iterator { return $this->next(); } - public function current() { - + /** + * To document + * + * @return To document + */ + public function current() + { return $this->row; } - public function key() { - + /** + * To document + * + * @return To document + */ + public function key() + { return (isset($this->row["id"]) ? $this->row["id"] : $this->pos); } - public function next() { - + /** + * To document + * + * @return To document + */ + public function next() + { if (!$this->res) { return false; } @@ -406,13 +464,23 @@ class TableIterator implements Iterator { return $this->row; } - public function valid() { - + /** + * To document + * + * @return To document + */ + public function valid() + { return $this->res && $this->row; } - public function numrows() { - + /** + * To document + * + * @return To document + */ + public function numrows() + { return ($this->res ? $this->res->rowCount() : 0); } } -- cgit