diff options
author | Volker Thiel <riker09@gmx.de> | 2013-03-12 13:57:37 +0100 |
---|---|---|
committer | Volker Thiel <riker09@gmx.de> | 2013-03-12 13:57:37 +0100 |
commit | 43cf002a0d5cb35737dab88eba976fdc44f0e772 (patch) | |
tree | 56a713a59ba5fa5b177714d9e355d9dea491da5d | |
parent | 3eafbc10c01224aaf839da92b4686042d4ae7959 (diff) | |
download | PHPixie-43cf002a0d5cb35737dab88eba976fdc44f0e772.zip PHPixie-43cf002a0d5cb35737dab88eba976fdc44f0e772.tar.gz PHPixie-43cf002a0d5cb35737dab88eba976fdc44f0e772.tar.bz2 |
Further application of coding guidelines
Done with Netbeans 7.3
Now with Tabs instead of Spaces!
50 files changed, 4574 insertions, 4350 deletions
diff --git a/application/config/core.php b/application/config/core.php index ce980fa..584a93f 100644 --- a/application/config/core.php +++ b/application/config/core.php @@ -1,12 +1,12 @@ <?php return array( - 'routes' => array( - array('default', '(/<controller>(/<action>(/<id>)))', array( - 'controller' => 'home', - 'action' => 'index' - ) - ), - ), - 'modules' => array('database', 'orm', 'cache'), + 'routes' => array( + array('default', '(/<controller>(/<action>(/<id>)))', array( + 'controller' => 'home', + 'action' => 'index' + ) + ), + ), + 'modules' => array('database', 'orm', 'cache'), ); diff --git a/application/config/database.php b/application/config/database.php index 0295f13..5201ab9 100644 --- a/application/config/database.php +++ b/application/config/database.php @@ -2,15 +2,13 @@ return array(
'default' => array(
- 'user'=>'root',
- 'password' => '',
+ 'user' => 'phpixie',
+ 'password' => 'phpixie',
'driver' => 'pdo',
-
//'Connection' is required if you use the PDO driver
- 'connection'=>'mysql:host=localhost;dbname=phpixie',
-
+ 'connection' => 'mysql:host=localhost;dbname=phpixie',
// 'db' and 'host' are required if you use Mysql driver
'db' => 'phpixie',
- 'host'=>'localhost'
+ 'host' => 'localhost'
)
);
diff --git a/modules/database/classes/database/expression.php b/modules/database/classes/database/expression.php index a041967..1d4de19 100644 --- a/modules/database/classes/database/expression.php +++ b/modules/database/classes/database/expression.php @@ -7,27 +7,29 @@ */
class Expression_Database
{
- /**
- * Part of query that should not be escaped
- * @var mixed
- * @access public
- */
- public $value;
- /**
- * Marks a part of query as a database specific expression,
- * e.g. calls to SQL functions like MAX(), SUBSTR() etc.
- * Example
- * <code>
- * $q->fields(DB::expr('COUNT(*)'));
- * </code>
- *
- * @param mixed $value Part of query that should not be escaped
- * @return Expression_Database
- * @access public
- */
- public function __construct($value)
- {
- $this->value = $value;
- }
+ /**
+ * Part of query that should not be escaped
+ * @var mixed
+ * @access public
+ */
+ public $value;
+
+ /**
+ * Marks a part of query as a database specific expression,
+ * e.g. calls to SQL functions like MAX(), SUBSTR() etc.
+ * Example
+ * <code>
+ * $q->fields(DB::expr('COUNT(*)'));
+ * </code>
+ *
+ * @param mixed $value Part of query that should not be escaped
+ * @return Expression_Database
+ * @access public
+ */
+ public function __construct($value)
+ {
+ $this->value = $value;
+ }
+
}
diff --git a/modules/database/classes/database/query.php b/modules/database/classes/database/query.php index 23b9876..e83a4bd 100644 --- a/modules/database/classes/database/query.php +++ b/modules/database/classes/database/query.php @@ -5,7 +5,7 @@ * Database drivers extend this class so that they can generate database specific queries. * The idea is to provide a database agnostic interface to query writing. * - * @method mixed table(string $table = null) Set table to query. + * @method mixed table(string $table = null) Set table to query. * Without arguments returns current table, returns self otherwise. * * @method mixed data(array $data = null) Set data for insert or update queries. @@ -29,103 +29,104 @@ */ abstract class Query_Database { - /** - * Array of conditions that rows must meet - * @var array - * @access protected - */ - protected $_conditions = array(); - - /** - * Table to query - * @var unknown - * @access protected - */ - protected $_table; - - /** - * Fields to return in the query - * @var array - * @access protected - */ - protected $_fields; - - /** - * Data for row insertion or update - * @var unknown - * @access protected - */ - protected $_data; - - /** - * Query type. Available types: select, update, insert, delete, count - * @var string - * @access protected - */ - protected $_type; - - /** - * Parameters for tables to join - * @var array - * @access protected - */ - protected $_joins = array(); - - /** - * Number of rows to return - * @var int - * @access protected - */ - protected $_limit; - - /** - * Offset of the first row - * @var int - * @access protected - */ - protected $_offset; - - /** - * Columns and directions to order by - * @var array - * @access protected - */ - protected $_orderby = array(); - - /** - * Database connection - * @var DB - * @access protected - */ - protected $_db; - - /** - * Conditions for aggregator functions - * @var array - * @access protected - */ - protected $_having = array(); - - /** - * Column to group by for aggregator functions - * @var string - * @access protected - */ - protected $_group_by; - - /** - * Last alias used on the table - * @var string - * @access protected - */ - protected $_alias = null; - - /** - * Methods and type of value they allow that are available via __call - * @var array - * @access protected - */ - protected $methods = array('data' => 'array','limit' => array('integer','NULL'),'offset' => array('integer','NULL'),'group_by' => array('string','NULL'),'type' => 'string'); + + /** + * Array of conditions that rows must meet + * @var array + * @access protected + */ + protected $_conditions = array(); + + /** + * Table to query + * @var unknown + * @access protected + */ + protected $_table; + + /** + * Fields to return in the query + * @var array + * @access protected + */ + protected $_fields; + + /** + * Data for row insertion or update + * @var unknown + * @access protected + */ + protected $_data; + + /** + * Query type. Available types: select, update, insert, delete, count + * @var string + * @access protected + */ + protected $_type; + + /** + * Parameters for tables to join + * @var array + * @access protected + */ + protected $_joins = array(); + + /** + * Number of rows to return + * @var int + * @access protected + */ + protected $_limit; + + /** + * Offset of the first row + * @var int + * @access protected + */ + protected $_offset; + + /** + * Columns and directions to order by + * @var array + * @access protected + */ + protected $_orderby = array(); + + /** + * Database connection + * @var DB + * @access protected + */ + protected $_db; + + /** + * Conditions for aggregator functions + * @var array + * @access protected + */ + protected $_having = array(); + + /** + * Column to group by for aggregator functions + * @var string + * @access protected + */ + protected $_group_by; + + /** + * Last alias used on the table + * @var string + * @access protected + */ + protected $_alias = null; + + /** + * Methods and type of value they allow that are available via __call + * @var array + * @access protected + */ + protected $methods = array('data' => 'array', 'limit' => array('integer', 'NULL'), 'offset' => array('integer', 'NULL'), 'group_by' => array('string', 'NULL'), 'type' => 'string'); /** * UNION queries @@ -133,323 +134,326 @@ abstract class Query_Database * @access protected */ protected $_union = array(); - - /** - * Generates a query in format that can be executed on current database implementation - * - * @access public - */ - public abstract function query(); - - /** - * Creates a new query - * - * @param DB $db Database connection - * @param string $type Query type. Available types: select, update, insert, delete, count - * @return void - * @access public - */ - public function __construct($db, $type) - { - $this->_db = $db; - $this->_type = $type; - } - - /** - * Sets fields to be queried from the database. You can add aliases to the fields - * by passing them as: - * - * array('field_name','alias') - * - * Example: $query->fields('id', array('name', 'fairy_name')) - * - * @param mixed $field,... Fields to be selected from the table - * @return mixed If no parameters are passed returns current array of fields, - * otherwise returns self. - * @access public - */ - public function fields() - { - $p = func_get_args(); - if (empty($p)) - { - return $this->_fields; - } - else - { - $this->_fields=$p; - } - return $this; - } /** - * Sets the table to perform operations on, also supports subqueries - * + * Generates a query in format that can be executed on current database implementation + * + * @access public + */ + public abstract function query(); + + /** + * Creates a new query + * + * @param DB $db Database connection + * @param string $type Query type. Available types: select, update, insert, delete, count + * @return void + * @access public + */ + public function __construct($db, $type) + { + $this->_db = $db; + $this->_type = $type; + } + + /** + * Sets fields to be queried from the database. You can add aliases to the fields + * by passing them as: + * + * array('field_name','alias') + * + * Example: $query->fields('id', array('name', 'fairy_name')) + * + * @param mixed $field,... Fields to be selected from the table + * @return mixed If no parameters are passed returns current array of fields, + * otherwise returns self. + * @access public + */ + public function fields() + { + $p = func_get_args(); + if (empty($p)) + { + return $this->_fields; + } + else + { + $this->_fields = $p; + } + return $this; + } + + /** + * Sets the table to perform operations on, also supports subqueries + * * @param string|Query_database|Expression_database $table table to select from * @param string $alias Alias for this table - * @return mixed Returns self if a table is passed, otherwise returns the table - * @access public - */ - public function table($table=null,$alias=null) - { + * @return mixed Returns self if a table is passed, otherwise returns the table + * @access public + */ + public function table($table = null, $alias = null) + { if ($table == null) - { - return is_array($this->_table)?$this->_table[1]:$this->_table; - } - - if (!is_string($table) && $alias==null) - { + { + return is_array($this->_table) ? $this->_table[1] : $this->_table; + } + + if (!is_string($table) && $alias == null) + { $alias = $this->add_alias(); - } - $this->_table = $alias == null?$table:array($table, $alias); - + } + $this->_table = $alias == null ? $table : array($table, $alias); + return $this; } + # - /** - * Magic methods to create methods for all generic query parts - * - * @param string $method Name of the method to call - * @param array $args Array of parameters - * @return mixed If no arguments are passed returns the current value of the property, - * otherwise returns self. - * @access public - * @throws Exception If method doesn't exist - * @throws Exception If value is of incorrect type - * @see $methods - */ - public function __call($method, $args) - { - if (isset($this->methods[$method])) - { - $property = '_'.$method; - - if (empty($args)) - { - return $this->$property; - } - $val = $args[0]; - if (is_numeric($val)) - { - $val = (int) $val; - } - $allowed_types = $this->methods[$method]; - if (!is_array($allowed_types)) - { - $allowed_types=array($allowed_types); - } - if (!in_array(gettype($val), $allowed_types)) - { - throw new Exception("Method '{$method}' only accepts values of type: ".implode(' or ',$allowed_types).", '{$val}' was passed"); - } - $this->$property = $val; - return $this; - } - throw new Exception("Method '{$method}' doesn't exist."); - } - - /** - * Executes the query - * - * @return object Executes current query on its database connection - * @access public - * @see DB - */ - public function execute() - { - $query = $this->query(); - $result = $this->_db->execute($query[0], $query[1]); - if ($this->_type == 'count') - { - return $result->get('count'); - } - return $result; - } - - /** - * Adds a joined table to the query. - * - * @param string $table Table to join - * @param array $conds Conditions to join tables on, same behavior as with where() method - * @param string $type Type of join. Defaults to 'left' - * @return Query_Database Returns self - * @access public - * @see where() - */ - public function join($table,$conds,$type='left') - { - $this->_joins[] = array($table, $type, $this->get_condition_part($conds)); - return $this; - } - - /** - * Sets conditions for aggregate functions, same behavior as with where() method - * - * @return Query_Database Returns self - * @access public - * @see where() - */ - public function having() - { - $p = func_get_args(); - $cond = $this->get_condition_part($p); - $this->_having = array_merge($this->_having, array($cond)); - return $this; - } - - /** - * Adds a column to ordering parameters. - * - * @param string $column Column to order by - * @param string $dir Ordering direction. - * @return Query_Database Returns self - * @throws Exception If ordering direction isn't DESC or ASC - * @access public - */ - public function order_by($column, $dir) - { - $dir = strtoupper($dir); - if ($dir != 'DESC' && $dir != 'ASC') - { - throw new Exception("Invalid sorting direction {$dir} specified"); - } - $this->_orderby[] = array($column,$dir); - return $this; - } - - /** - * Sets conditions for the query. - * Can be called in many ways, examples: - * Shorthand equals condition: - * <code> - * $q->where('name', 'Tinkerbell') - * </code> - * Conditions with operator: - * <code> - * $q->where('id', '>', 3) - * </code> - * OR logic: - * <code> - * $q->where('or', array('name', 'Tinkerbell')) - * </code> - * OR logic with operator - * <code> - * ->where('or', array('id', '>', 3)) - * </code> - * Arrays represent brackets. e.g - * <code> - * $q->where('name', 'Tinkerbell') - * ->where('or', array( - * array('id', '>', 7), - * array('id', '<', 15) - * ); - * //Will produce "WHERE `name`='Tinkerbell' OR (`id` > 7 AND `id` < 15)" - * </code> - * Multiple calls to where() append new conditions to previous ones - * - * @param mixed $column Column name, logic parameter 'OR' or 'AND' or an array of conditions - * @param mixed $operator Condition value, operator or an array of parameters - * @param mixed $val Condition value - * - * @return Query_Database Returns self - * @access public - */ - public function where() - { - $p = func_get_args(); - $cond = $this->get_condition_part($p); - $this->_conditions = array_merge($this->_conditions, array($cond)); - - return $this; - } - - /** - * Recursively builds condition arrays for methods like where(), having() - * - * @param array $p Parameters passed to the method - * @return array Array in condition format - * @access private - * @throws Exception If condition format is incorrect - */ - private function get_condition_part($p) - { - if (is_string($p[0]) && (strtolower($p[0]) == 'or' || strtolower($p[0]) == 'and') && isset($p[1]) && is_array($p[1])) - { - $cond = $this->get_condition_part($p[1]); - $cond['logic'] = strtolower($p[0]); - return $cond; - } - - if (is_array($p[0])) - { - if (count($p) == 1) - { - return $this->get_condition_part($p[0]); - } - $conds = array(); - foreach($p as $q) - { - $conds[] = $this->get_condition_part($q); - } - if (count($conds) == 1) - { - return $conds; - } - return array('logic' => 'and', 'conditions' => $conds); - } - - if ((is_string($p[0]) || get_class($p[0]) == 'Expression_Database') && isset($p[1])) - { - if (strpos($p[0], '.') === false) - { - $p[0]=$this->last_alias().'.'.$p[0]; - } - return array( - 'logic' => 'and', - 'conditions' => array( - 'field' => $p[0], - 'operator' => isset($p[2]) ? $p[1] : '=', - 'value' => isset($p[2]) ? $p[2] : $p[1] - ) - ); - } - - throw new Exception('Incorrect conditional statement passed'); - } - - /** - * Gets last generated alias - * - * @return string Last generated alias. If no alias were created returns table name. - * @access public - */ - public function last_alias() - { - if ($this->_alias === null) - { - return $this->_table; - } - return 'a'.$this->_alias; - } - - /** - * Generates new alias. Useful for dynamically adding aliases to joins. - * Alias is just a letter 'a' with an incremented number. - * - * @return string New alias - * @access public - */ - public function add_alias() - { - if ($this->_alias === null) - { - $this->_alias = 0; - } - else - { - $this->_alias++; - } - return $this->last_alias(); - } + /** + * Magic methods to create methods for all generic query parts + * + * @param string $method Name of the method to call + * @param array $args Array of parameters + * @return mixed If no arguments are passed returns the current value of the property, + * otherwise returns self. + * @access public + * @throws Exception If method doesn't exist + * @throws Exception If value is of incorrect type + * @see $methods + */ + + public function __call($method, $args) + { + if (isset($this->methods[$method])) + { + $property = '_'.$method; + + if (empty($args)) + { + return $this->$property; + } + $val = $args[0]; + if (is_numeric($val)) + { + $val = (int) $val; + } + $allowed_types = $this->methods[$method]; + if (!is_array($allowed_types)) + { + $allowed_types = array($allowed_types); + } + if (!in_array(gettype($val), $allowed_types)) + { + throw new Exception("Method '{$method}' only accepts values of type: ".implode(' or ', $allowed_types).", '{$val}' was passed"); + } + $this->$property = $val; + return $this; + } + throw new Exception("Method '{$method}' doesn't exist."); + } + + /** + * Executes the query + * + * @return object Executes current query on its database connection + * @access public + * @see DB + */ + public function execute() + { + $query = $this->query(); + $result = $this->_db->execute($query[0], $query[1]); + if ($this->_type == 'count') + { + return $result->get('count'); + } + return $result; + } + + /** + * Adds a joined table to the query. + * + * @param string $table Table to join + * @param array $conds Conditions to join tables on, same behavior as with where() method + * @param string $type Type of join. Defaults to 'left' + * @return Query_Database Returns self + * @access public + * @see where() + */ + public function join($table, $conds, $type = 'left') + { + $this->_joins[] = array($table, $type, $this->get_condition_part($conds)); + return $this; + } + + /** + * Sets conditions for aggregate functions, same behavior as with where() method + * + * @return Query_Database Returns self + * @access public + * @see where() + */ + public function having() + { + $p = func_get_args(); + $cond = $this->get_condition_part($p); + $this->_having = array_merge($this->_having, array($cond)); + return $this; + } + + /** + * Adds a column to ordering parameters. + * + * @param string $column Column to order by + * @param string $dir Ordering direction. + * @return Query_Database Returns self + * @throws Exception If ordering direction isn't DESC or ASC + * @access public + */ + public function order_by($column, $dir) + { + $dir = strtoupper($dir); + if ($dir != 'DESC' && $dir != 'ASC') + { + throw new Exception("Invalid sorting direction {$dir} specified"); + } + $this->_orderby[] = array($column, $dir); + return $this; + } + + /** + * Sets conditions for the query. + * Can be called in many ways, examples: + * Shorthand equals condition: + * <code> + * $q->where('name', 'Tinkerbell') + * </code> + * Conditions with operator: + * <code> + * $q->where('id', '>', 3) + * </code> + * OR logic: + * <code> + * $q->where('or', array('name', 'Tinkerbell')) + * </code> + * OR logic with operator + * <code> + * ->where('or', array('id', '>', 3)) + * </code> + * Arrays represent brackets. e.g + * <code> + * $q->where('name', 'Tinkerbell') + * ->where('or', array( + * array('id', '>', 7), + * array('id', '<', 15) + * ); + * //Will produce "WHERE `name`='Tinkerbell' OR (`id` > 7 AND `id` < 15)" + * </code> + * Multiple calls to where() append new conditions to previous ones + * + * @param mixed $column Column name, logic parameter 'OR' or 'AND' or an array of conditions + * @param mixed $operator Condition value, operator or an array of parameters + * @param mixed $val Condition value + * + * @return Query_Database Returns self + * @access public + */ + public function where() + { + $p = func_get_args(); + $cond = $this->get_condition_part($p); + $this->_conditions = array_merge($this->_conditions, array($cond)); + + return $this; + } + + /** + * Recursively builds condition arrays for methods like where(), having() + * + * @param array $p Parameters passed to the method + * @return array Array in condition format + * @access private + * @throws Exception If condition format is incorrect + */ + private function get_condition_part($p) + { + if (is_string($p[0]) && (strtolower($p[0]) == 'or' || strtolower($p[0]) == 'and') && isset($p[1]) && is_array($p[1])) + { + $cond = $this->get_condition_part($p[1]); + $cond['logic'] = strtolower($p[0]); + return $cond; + } + + if (is_array($p[0])) + { + if (count($p) == 1) + { + return $this->get_condition_part($p[0]); + } + $conds = array(); + foreach ($p as $q) + { + $conds[] = $this->get_condition_part($q); + } + if (count($conds) == 1) + { + return $conds; + } + return array('logic' => 'and', 'conditions' => $conds); + } + + if ((is_string($p[0]) || get_class($p[0]) == 'Expression_Database') && isset($p[1])) + { + if (strpos($p[0], '.') === false) + { + $p[0] = $this->last_alias().'.'.$p[0]; + } + return array( + 'logic' => 'and', + 'conditions' => array( + 'field' => $p[0], + 'operator' => isset($p[2]) ? $p[1] : '=', + 'value' => isset($p[2]) ? $p[2] : $p[1] + ) + ); + } + + throw new Exception('Incorrect conditional statement passed'); + } + + /** + * Gets last generated alias + * + * @return string Last generated alias. If no alias were created returns table name. + * @access public + */ + public function last_alias() + { + if ($this->_alias === null) + { + return $this->_table; + } + return 'a'.$this->_alias; + } + + /** + * Generates new alias. Useful for dynamically adding aliases to joins. + * Alias is just a letter 'a' with an incremented number. + * + * @return string New alias + * @access public + */ + public function add_alias() + { + if ($this->_alias === null) + { + $this->_alias = 0; + } + else + { + $this->_alias++; + } + return $this->last_alias(); + } + } diff --git a/modules/database/classes/database/result.php b/modules/database/classes/database/result.php index 1c6b9fe..db58119 100644 --- a/modules/database/classes/database/result.php +++ b/modules/database/classes/database/result.php @@ -8,114 +8,114 @@ abstract class Result_Database implements Iterator { - /** - * Current row number - * @var integer - * @access protected - */ - protected $_position = -1; + /** + * Current row number + * @var integer + * @access protected + */ + protected $_position = -1; - /** - * Database result object - * @var mixed - * @access protected - */ - protected $_result; + /** + * Database result object + * @var mixed + * @access protected + */ + protected $_result; - /** - * Current row - * @var object - * @access protected - */ - protected $_row; + /** + * Current row + * @var object + * @access protected + */ + protected $_row; - /** - * If at least one row has been fetched - * @var object - * @access protected - */ - protected $_fetched = false; + /** + * If at least one row has been fetched + * @var object + * @access protected + */ + protected $_fetched = false; - /** - * Returns current row - * - * @return object Current row in result set - * @access public - */ - public function current() - { - $this->check_fetched(); - return $this->_row; - } + /** + * Returns current row + * + * @return object Current row in result set + * @access public + */ + public function current() + { + $this->check_fetched(); + return $this->_row; + } - /** - * Gets the number of the current row - * - * @return integer Row number - * @access public - */ - public function key() - { - $this->check_fetched(); - return $this->_position; - } + /** + * Gets the number of the current row + * + * @return integer Row number + * @access public + */ + public function key() + { + $this->check_fetched(); + return $this->_position; + } - /** - * Check if current row exists. - * - * @return bool True if row exists - * @access public - */ - public function valid() - { - $this->check_fetched(); - return $this->_row != null; - } + /** + * Check if current row exists. + * + * @return bool True if row exists + * @access public + */ + public function valid() + { + $this->check_fetched(); + return $this->_row != null; + } - /** - * Returns all rows as array - * - * @return array Array of rows - * @access public - */ - public function as_array() - { - $arr = array(); - foreach ($this as $row) - { - $arr[] = $row; - } - return $arr; - } + /** + * Returns all rows as array + * + * @return array Array of rows + * @access public + */ + public function as_array() + { + $arr = array(); + foreach ($this as $row) + { + $arr[] = $row; + } + return $arr; + } - /** - * Checks if the rows from the result set have - * been fetched at least once. If not fetches first row. - * - * @access public - */ - protected function check_fetched() - { - if (!$this->_fetched) - { - $this->_fetched = true; - $this->next(); - } - } + /** + * Checks if the rows from the result set have + * been fetched at least once. If not fetches first row. + * + * @access public + */ + protected function check_fetched() + { + if (!$this->_fetched) + { + $this->_fetched = true; + $this->next(); + } + } - /** - * Gets a column from the current row in the set - * - * @param string $column Column name - * @return mixed Column value - * @access public - */ - public function get($column) - { - if ($this->valid() && isset($this->_row->$column)) - { - return $this->_row->$column; - } - } + /** + * Gets a column from the current row in the set + * + * @param string $column Column name + * @return mixed Column value + * @access public + */ + public function get($column) + { + if ($this->valid() && isset($this->_row->$column)) + { + return $this->_row->$column; + } + } }
\ No newline at end of file diff --git a/modules/database/classes/db.php b/modules/database/classes/db.php index 4979450..ee6d779 100644 --- a/modules/database/classes/db.php +++ b/modules/database/classes/db.php @@ -9,140 +9,140 @@ abstract class DB { - /** - * An associative array of connections to databases - * @var array - * @access private - * @static - */ - private static $_instances = array(); + /** + * An associative array of connections to databases + * @var array + * @access private + * @static + */ + private static $_instances = array(); - /** - * Executes a prepared statement query - * - * @param string $query A prepared statement query - * @param array $params Parameters for the query - * @return Result_Database - * @access public - * @see Result_Database - */ - public abstract function execute($query, $params = array()); + /** + * Executes a prepared statement query + * + * @param string $query A prepared statement query + * @param array $params Parameters for the query + * @return Result_Database + * @access public + * @see Result_Database + */ + public abstract function execute($query, $params = array()); - /** - * Builds a new Query to the database - * - * @param string $type Query type. Available types: select, update, insert, delete, count - * @return Result_Database - * @access public - * @see Query_Database - */ - public abstract function build_query($type); + /** + * Builds a new Query to the database + * + * @param string $type Query type. Available types: select, update, insert, delete, count + * @return Result_Database + * @access public + * @see Query_Database + */ + public abstract function build_query($type); - /** - * Gets the id of the last inserted row. - * - * @return mixed The id of the last inserted row - * @access public - */ - public abstract function get_insert_id(); + /** + * Gets the id of the last inserted row. + * + * @return mixed The id of the last inserted row + * @access public + */ + public abstract function get_insert_id(); - /** - * Gets column names for the specified table - * - * @param string $table Name of the table to get columns from - * @return array Array of column names - * @access public - */ - public abstract function list_columns($table); + /** + * Gets column names for the specified table + * + * @param string $table Name of the table to get columns from + * @return array Array of column names + * @access public + */ + public abstract function list_columns($table); - /** - * Executes a named query where parameters are passed as an associative array - * Example: - * <code> - * $result=$db->namedQuery("SELECT * FROM fairies where name = :name",array('name'=>'Tinkerbell')); - * </code> - * - * @param string $query A named query - * @param array $params Associative array of parameters - * @return Result_Database Current drivers implementation of Result_Database - * @access public - */ - public function named_query($query, $params = array()) - { - $bind = array(); - preg_match_all('#:(\w+)#is', $query, $matches, PREG_SET_ORDER); - foreach ($matches as $match) - { - if (isset($params[$match[1]])) - { - $query = preg_replace("#{$match[0]}#", '?', $query, 1); - $bind[] = $params[$match[1]]; - } - } - return $this->execute($query, $bind); - } + /** + * Executes a named query where parameters are passed as an associative array + * Example: + * <code> + * $result=$db->namedQuery("SELECT * FROM fairies where name = :name",array('name'=>'Tinkerbell')); + * </code> + * + * @param string $query A named query + * @param array $params Associative array of parameters + * @return Result_Database Current drivers implementation of Result_Database + * @access public + */ + public function named_query($query, $params = array()) + { + $bind = array(); + preg_match_all('#:(\w+)#is', $query, $matches, PREG_SET_ORDER); + foreach ($matches as $match) + { + if (isset($params[$match[1]])) + { + $query = preg_replace("#{$match[0]}#", '?', $query, 1); + $bind[] = $params[$match[1]]; + } + } + return $this->execute($query, $bind); + } - /** - * Returns an Expression_Database representation of the value. - * Values wrapped inside Expression_Database are not escaped in queries - * - * @param mixed $value Value to be wrapped - * @return Expression_Database Raw value that will not be escaped during query building - * @access public - * @static - */ - public static function expr($value) - { - return new Expression_Database($value); - } + /** + * Returns an Expression_Database representation of the value. + * Values wrapped inside Expression_Database are not escaped in queries + * + * @param mixed $value Value to be wrapped + * @return Expression_Database Raw value that will not be escaped during query building + * @access public + * @static + */ + public static function expr($value) + { + return new Expression_Database($value); + } - /** - * Builds a query for specified connection. - * - * @param string $type Query type. Available types: select,update,insert,delete,count - * @param string $config Configuration name of the connection. - * Defaults to 'default'. - * @return Query_Database Driver implementation of the Query_Database class. - * @access public - * @static - */ - public static function query($type, $config = 'default') - { - return DB::instance($config)->build_query($type); - } + /** + * Builds a query for specified connection. + * + * @param string $type Query type. Available types: select,update,insert,delete,count + * @param string $config Configuration name of the connection. + * Defaults to 'default'. + * @return Query_Database Driver implementation of the Query_Database class. + * @access public + * @static + */ + public static function query($type, $config = 'default') + { + return DB::instance($config)->build_query($type); + } - /** - * Gets the id of the last inserted row - * - * @param string $config Configuration name of the connection. - * Defaults to 'default'. - * @return mixed Id of the last inserted row - * @access public - * @static - */ - public static function insert_id($config = 'default') - { - return DB::instance($config)->get_insert_id(); - } + /** + * Gets the id of the last inserted row + * + * @param string $config Configuration name of the connection. + * Defaults to 'default'. + * @return mixed Id of the last inserted row + * @access public + * @static + */ + public static function insert_id($config = 'default') + { + return DB::instance($config)->get_insert_id(); + } - /** - * Gets an instance of a connection to the database - * - * @param string $config Configuration name of the connection. - * Defaults to 'default'. - * @return DB Driver implementation of the DB class. - * @access public - * @static - */ - public static function instance($config = 'default') - { - if (!isset(DB::$_instances[$config])) - { - $driver = Config::get("database.{$config}.driver"); - $driver = "DB_{$driver}_Driver"; - DB::$_instances[$config] = new $driver($config); - } - return DB::$_instances[$config]; - } + /** + * Gets an instance of a connection to the database + * + * @param string $config Configuration name of the connection. + * Defaults to 'default'. + * @return DB Driver implementation of the DB class. + * @access public + * @static + */ + public static function instance($config = 'default') + { + if (!isset(DB::$_instances[$config])) + { + $driver = Config::get("database.{$config}.driver"); + $driver = "DB_{$driver}_Driver"; + DB::$_instances[$config] = new $driver($config); + } + return DB::$_instances[$config]; + } } diff --git a/modules/database/classes/driver/mysql/db.php b/modules/database/classes/driver/mysql/db.php index 88df9b8..1d49acf 100644 --- a/modules/database/classes/driver/mysql/db.php +++ b/modules/database/classes/driver/mysql/db.php @@ -7,120 +7,120 @@ class DB_Mysql_Driver extends DB
{
- /**
- * Mysqli database connection object
- * @var mysqli
- * @access public
- * @link http://php.net/manual/en/class.mysqli.php
- */
- public $conn;
+ /**
+ * Mysqli database connection object
+ * @var mysqli
+ * @access public
+ * @link http://php.net/manual/en/class.mysqli.php
+ */
+ public $conn;
- /**
- * Type of the database, mysql.
- * @var string
- * @access public
- */
- public $db_type = 'mysql';
+ /**
+ * Type of the database, mysql.
+ * @var string
+ * @access public
+ */
+ public $db_type = 'mysql';
- /**
- * Initializes database connection
- *
- * @param string $config Name of the connection to initialize
- * @return void
- * @access public
- */
- public function __construct($config)
- {
- $this->conn = mysqli_connect(
- Config::get("database.{$config}.host", 'localhost'), Config::get("database.{$config}.user", ''), Config::get("database.{$config}.password", ''), Config::get("database.{$config}.db")
- );
- $this->conn->set_charset("utf8");
- }
+ /**
+ * Initializes database connection
+ *
+ * @param string $config Name of the connection to initialize
+ * @return void
+ * @access public
+ */
+ public function __construct($config)
+ {
+ $this->conn = mysqli_connect(
+ Config::get("database.{$config}.host", 'localhost'), Config::get("database.{$config}.user", ''), Config::get("database.{$config}.password", ''), Config::get("database.{$config}.db")
+ );
+ $this->conn->set_charset("utf8");
+ }
- /**
- * Gets column names for the specified table
- *
- * @param string $table Name of the table to get columns from
- * @return array Array of column names
- * @throw Exception if table doesn't exist
- * @access public
- */
- public function list_columns($table)
- {
- $columns = array();
- $table_desc = $this->execute("DESCRIBE `$table`");
- Debug::log($table_desc);
- if (!$table_desc->valid())
- {
- throw new Exception("Table '{$table}' doesn't exist");
- }
- foreach ($table_desc as $column)
- {
- $columns[] = $column->Field;
- }
+ /**
+ * Gets column names for the specified table
+ *
+ * @param string $table Name of the table to get columns from
+ * @return array Array of column names
+ * @throw Exception if table doesn't exist
+ * @access public
+ */
+ public function list_columns($table)
+ {
+ $columns = array();
+ $table_desc = $this->execute("DESCRIBE `$table`");
+ Debug::log($table_desc);
+ if (!$table_desc->valid())
+ {
+ throw new Exception("Table '{$table}' doesn't exist");
+ }
+ foreach ($table_desc as $column)
+ {
+ $columns[] = $column->Field;
+ }
- return $columns;
- }
+ return $columns;
+ }
- /**
- * Builds a new Query implementation
- *
- * @param string $type Query type. Available types: select,update,insert,delete,count
- * @return Query_Mysql_Driver Returns a Mysqli implementation of a Query.
- * @access public
- * @see Query_Database
- */
- public function build_query($type)
- {
- return new Query_Mysql_Driver($this, $type);
- }
+ /**
+ * Builds a new Query implementation
+ *
+ * @param string $type Query type. Available types: select,update,insert,delete,count
+ * @return Query_Mysql_Driver Returns a Mysqli implementation of a Query.
+ * @access public
+ * @see Query_Database
+ */
+ public function build_query($type)
+ {
+ return new Query_Mysql_Driver($this, $type);
+ }
- /**
- * Gets the id of the last inserted row.
- *
- * @return mixed Row id
- * @access public
- */
- public function get_insert_id()
- {
- return $this->conn->insert_id;
- }
+ /**
+ * Gets the id of the last inserted row.
+ *
+ * @return mixed Row id
+ * @access public
+ */
+ public function get_insert_id()
+ {
+ return $this->conn->insert_id;
+ }
- /**
- * Executes a prepared statement query
- *
- * @param string $query A prepared statement query
- * @param array $params Parameters for the query
- * @return Result_Mysql_Driver Mysqli implementation of a database result
- * @access public
- * @throws Exception If the query resulted in an error
- * @see Database_Result
- */
- public function execute($query, $params = array())
- {
- $cursor = $this->conn->prepare($query);
- if (!$cursor)
- {
- throw new Exception("Database error: {$this->conn->error} \n in query:\n{$query}");
- }
- $types = '';
- $bind = array();
- $refs = array();
- if (!empty($params))
- {
- foreach ($params as $key => $param)
- {
- $refs[$key] = is_array($param) ? $param[0] : $param;
- $bind[] = &$refs[$key];
- $types .= is_array($param) ? $param[1] : 's';
- }
- array_unshift($bind, $types);
+ /**
+ * Executes a prepared statement query
+ *
+ * @param string $query A prepared statement query
+ * @param array $params Parameters for the query
+ * @return Result_Mysql_Driver Mysqli implementation of a database result
+ * @access public
+ * @throws Exception If the query resulted in an error
+ * @see Database_Result
+ */
+ public function execute($query, $params = array())
+ {
+ $cursor = $this->conn->prepare($query);
+ if (!$cursor)
+ {
+ throw new Exception("Database error: {$this->conn->error} \n in query:\n{$query}");
+ }
+ $types = '';
+ $bind = array();
+ $refs = array();
+ if (!empty($params))
+ {
+ foreach ($params as $key => $param)
+ {
+ $refs[$key] = is_array($param) ? $param[0] : $param;
+ $bind[] = &$refs[$key];
+ $types .= is_array($param) ? $param[1] : 's';
+ }
+ array_unshift($bind, $types);
- call_user_func_array(array($cursor, 'bind_param'), $bind);
- }
- $cursor->execute();
- $res = $cursor->get_result();
- return new Result_Mysql_Driver($res);
- }
+ call_user_func_array(array($cursor, 'bind_param'), $bind);
+ }
+ $cursor->execute();
+ $res = $cursor->get_result();
+ return new Result_Mysql_Driver($res);
+ }
}
\ No newline at end of file diff --git a/modules/database/classes/driver/mysql/query.php b/modules/database/classes/driver/mysql/query.php index 803f932..b880338 100644 --- a/modules/database/classes/driver/mysql/query.php +++ b/modules/database/classes/driver/mysql/query.php @@ -4,4 +4,7 @@ * Mysqli implementation of the database Query * @package Database */ -class Query_Mysql_Driver extends Query_PDO_Driver {}
\ No newline at end of file +class Query_Mysql_Driver extends Query_PDO_Driver +{ + +} diff --git a/modules/database/classes/driver/mysql/result.php b/modules/database/classes/driver/mysql/result.php index e9de4a5..2927192 100644 --- a/modules/database/classes/driver/mysql/result.php +++ b/modules/database/classes/driver/mysql/result.php @@ -7,52 +7,52 @@ class Result_Mysql_Driver extends Result_Database { - /** - * Initializes new result object - * - * @param mysqli_result $result Mysqli Result - * @return void - * @access public - * @link http://php.net/manual/en/class.mysqli-result.php - */ - public function __construct($result) - { - $this->_result = $result; - } + /** + * Initializes new result object + * + * @param mysqli_result $result Mysqli Result + * @return void + * @access public + * @link http://php.net/manual/en/class.mysqli-result.php + */ + public function __construct($result) + { + $this->_result = $result; + } - /** - * Throws exception if rewind is attempted. - * - * @return void - * @access public - * @throws Exception If rewind is attempted - */ - public function rewind() - { - if ($this->_position > 0) - { - throw new Exception('Mysqli result cannot be rewound for unbuffered queries.'); - } - } + /** + * Throws exception if rewind is attempted. + * + * @return void + * @access public + * @throws Exception If rewind is attempted + */ + public function rewind() + { + if ($this->_position > 0) + { + throw new Exception('Mysqli result cannot be rewound for unbuffered queries.'); + } + } - /** - * Iterates to the next row in the result set - * - * @return void - * @access public - */ - public function next() - { - $this->check_fetched(); - $this->_row = $this->_result->fetch_object(); - if ($this->_row) - { - $this->_position++; - } - else - { - $this->_result->free(); - } - } + /** + * Iterates to the next row in the result set + * + * @return void + * @access public + */ + public function next() + { + $this->check_fetched(); + $this->_row = $this->_result->fetch_object(); + if ($this->_row) + { + $this->_position++; + } + else + { + $this->_result->free(); + } + } }
\ No newline at end of file diff --git a/modules/database/classes/driver/pdo/db.php b/modules/database/classes/driver/pdo/db.php index 5b81d66..5a920ec 100644 --- a/modules/database/classes/driver/pdo/db.php +++ b/modules/database/classes/driver/pdo/db.php @@ -7,125 +7,125 @@ class DB_PDO_Driver extends DB { - /** - * Connection object - * @var PDO - * @access public - * @link http://php.net/manual/en/class.pdo.php - */ - public $conn; + /** + * Connection object + * @var PDO + * @access public + * @link http://php.net/manual/en/class.pdo.php + */ + public $conn; - /** - * Type of the database, e.g. mysql, pgsql etc. - * @var string - * @access public - */ - public $db_type; + /** + * Type of the database, e.g. mysql, pgsql etc. + * @var string + * @access public + */ + public $db_type; - /** - * Initializes database connection - * - * @param string $config Name of the connection to initialize - * @return void - * @access public - */ - public function __construct($config) - { - $this->conn = new PDO( - Config::get("database.{$config}.connection"), Config::get("database.{$config}.user", ''), Config::get("database.{$config}.password", '') - ); - $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $this->db_type = strtolower(str_replace('PDO_', '', $this->conn->getAttribute(PDO::ATTR_DRIVER_NAME))); - if ($this->db_type != 'sqlite') - { - $this->conn->exec("SET NAMES utf8"); - } - } + /** + * Initializes database connection + * + * @param string $config Name of the connection to initialize + * @return void + * @access public + */ + public function __construct($config) + { + $this->conn = new PDO( + Config::get("database.{$config}.connection"), Config::get("database.{$config}.user", ''), Config::get("database.{$config}.password", '') + ); + $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $this->db_type = strtolower(str_replace('PDO_', '', $this->conn->getAttribute(PDO::ATTR_DRIVER_NAME))); + if ($this->db_type != 'sqlite') + { + $this->conn->exec("SET NAMES utf8"); + } + } - /** - * Builds a new Query implementation - * - * @param string $type Query type. Available types: select,update,insert,delete,count - * @return Query_PDO_Driver Returns a PDO implementation of a Query. - * @access public - * @see Query_Database - */ - public function build_query($type) - { - return new Query_PDO_Driver($this, $type); - } + /** + * Builds a new Query implementation + * + * @param string $type Query type. Available types: select,update,insert,delete,count + * @return Query_PDO_Driver Returns a PDO implementation of a Query. + * @access public + * @see Query_Database + */ + public function build_query($type) + { + return new Query_PDO_Driver($this, $type); + } - /** - * Gets the id of the last inserted row. - * - * @return mixed Row id - * @access public - */ - public function get_insert_id() - { - if ($this->db_type == 'pgsql') - { - return $this->execute('SELECT lastval() as id')->current()->id; - } - return $this->conn->lastInsertId(); - } + /** + * Gets the id of the last inserted row. + * + * @return mixed Row id + * @access public + */ + public function get_insert_id() + { + if ($this->db_type == 'pgsql') + { + return $this->execute('SELECT lastval() as id')->current()->id; + } + return $this->conn->lastInsertId(); + } - /** - * Gets column names for the specified table - * - * @param string $table Name of the table to get columns from - * @return array Array of column names - * @access public - */ - public function list_columns($table) - { - $columns = array(); - if ($this->db_type == 'mysql') - { - $table_desc = $this->execute("DESCRIBE `$table`"); - foreach ($table_desc as $column) - { - $columns[] = $column->Field; - } - } - if ($this->db_type == 'pgsql') - { - $table_desc = $this->execute("select column_name from information_schema.columns where table_name = '{$table}' and table_catalog=current_database();"); - foreach ($table_desc as $column) - { - $columns[] = $column->column_name; - } - } - if ($this->db_type == 'sqlite') - { - $table_desc = $this->execute("PRAGMA table_info('$table')"); - foreach ($table_desc as $column) - { - $columns[] = $column->name; - } - } - return $columns; - } + /** + * Gets column names for the specified table + * + * @param string $table Name of the table to get columns from + * @return array Array of column names + * @access public + */ + public function list_columns($table) + { + $columns = array(); + if ($this->db_type == 'mysql') + { + $table_desc = $this->execute("DESCRIBE `$table`"); + foreach ($table_desc as $column) + { + $columns[] = $column->Field; + } + } + if ($this->db_type == 'pgsql') + { + $table_desc = $this->execute("select column_name from information_schema.columns where table_name = '{$table}' and table_catalog=current_database();"); + foreach ($table_desc as $column) + { + $columns[] = $column->column_name; + } + } + if ($this->db_type == 'sqlite') + { + $table_desc = $this->execute("PRAGMA table_info('$table')"); + foreach ($table_desc as $column) + { + $columns[] = $column->name; + } + } + return $columns; + } - /** - * Executes a prepared statement query - * - * @param string $query A prepared statement query - * @param array $params Parameters for the query - * @return Result_PDO_Driver PDO implementation of a database result - * @access public - * @throws Exception If the query resulted in an error - * @see Database_Result - */ - public function execute($query, $params = array()) - { - $cursor = $this->conn->prepare($query); - if (!$cursor->execute($params)) - { - $error = $cursor->errorInfo(); - throw new Exception("Database error:\n".$error[2]." \n in query:\n{$query}"); - } - return new Result_PDO_Driver($cursor); - } + /** + * Executes a prepared statement query + * + * @param string $query A prepared statement query + * @param array $params Parameters for the query + * @return Result_PDO_Driver PDO implementation of a database result + * @access public + * @throws Exception If the query resulted in an error + * @see Database_Result + */ + public function execute($query, $params = array()) + { + $cursor = $this->conn->prepare($query); + if (!$cursor->execute($params)) + { + $error = $cursor->errorInfo(); + throw new Exception("Database error:\n".$error[2]." \n in query:\n{$query}"); + } + return new Result_PDO_Driver($cursor); + } }
\ No newline at end of file diff --git a/modules/database/classes/driver/pdo/query.php b/modules/database/classes/driver/pdo/query.php index d78316d..5d82cbf 100644 --- a/modules/database/classes/driver/pdo/query.php +++ b/modules/database/classes/driver/pdo/query.php @@ -7,96 +7,96 @@ class Query_PDO_Driver extends Query_Database { - /** - * Type of the database, e.g. mysql, pgsql etc. - * @var string - * @access public - */ - protected $_db_type; + /** + * Type of the database, e.g. mysql, pgsql etc. + * @var string + * @access public + */ + protected $_db_type; - /** - * Character to use for quoting fields - * @var string - * @access public - */ - protected $_quote; + /** + * Character to use for quoting fields + * @var string + * @access public + */ + protected $_quote; - /** - * Creates a new query object, checks which driver we are using and set the character used for quoting - * - * @param DB $db Database connection - * @param string $type Query type. Available types: select, update, insert, delete, count - * @return void - * @access public - * @see Query_Database::__construct() - */ - public function __construct($db, $type) - { - parent::__construct($db, $type); - $this->_db_type = $this->_db->db_type; - $this->_quote = $this->_db_type == 'mysql' ? '`' : '"'; - } + /** + * Creates a new query object, checks which driver we are using and set the character used for quoting + * + * @param DB $db Database connection + * @param string $type Query type. Available types: select, update, insert, delete, count + * @return void + * @access public + * @see Query_Database::__construct() + */ + public function __construct($db, $type) + { + parent::__construct($db, $type); + $this->_db_type = $this->_db->db_type; + $this->_quote = $this->_db_type == 'mysql' ? '`' : '"'; + } - /** - * Puts quotes around a string - * - * @param string $str String to be enclosed in quotes - * @return string String surrounded with quotes - * @access protected - */ - protected function quote($str) - { - return $this->_quote.$str.$this->_quote; - } + /** + * Puts quotes around a string + * + * @param string $str String to be enclosed in quotes + * @return string String surrounded with quotes + * @access protected + */ + protected function quote($str) + { + return $this->_quote.$str.$this->_quote; + } - /** - * If a string is passed escapes a field by enclosing it in specified quotes. - * If you pass an Expression_Database object the value will be inserted into the query unescaped - * - * @param mixed $field Field to be escaped or an Expression_Database object - * if the field must not be escaped - * @return string Escaped field representation - * @access public - * @see Expression_Database - */ - public function escape_field($field) - { - if (is_object($field) && get_class($field) == 'Expression_Database') - { - return $field->value; - } - $field = explode('.', $field); - if (count($field) == 1) - { - array_unshift($field, $this->last_alias()); - } - $str = $this->quote($field[0]).'.'; - if (trim($field[1]) == '*') - { - return $str.'*'; - } - return $str.$this->quote($field[1]); - } + /** + * If a string is passed escapes a field by enclosing it in specified quotes. + * If you pass an Expression_Database object the value will be inserted into the query unescaped + * + * @param mixed $field Field to be escaped or an Expression_Database object + * if the field must not be escaped + * @return string Escaped field representation + * @access public + * @see Expression_Database + */ + public function escape_field($field) + { + if (is_object($field) && get_class($field) == 'Expression_Database') + { + return $field->value; + } + $field = explode('.', $field); + if (count($field) == 1) + { + array_unshift($field, $this->last_alias()); + } + $str = $this->quote($field[0]).'.'; + if (trim($field[1]) == '*') + { + return $str.'*'; + } + return $str.$this->quote($field[1]); + } - /** - * Replaces the value with ? and appends it to the parameters array - * If you pass an Expression_Database object the value will be inserted into the query unescaped - * @param mixed $val Value to be escaped or an Expression_Database object - * if the value must not be escaped - * @param array &$params Reference to parameters array - * @return string Escaped value representation - * @access public - */ - public function escape_value($val,&$params) - { + /** + * Replaces the value with ? and appends it to the parameters array + * If you pass an Expression_Database object the value will be inserted into the query unescaped + * @param mixed $val Value to be escaped or an Expression_Database object + * if the value must not be escaped + * @param array &$params Reference to parameters array + * @return string Escaped value representation + * @access public + */ + public function escape_value($val, &$params) + { if ($val instanceof Expression_Database) - { + { return $val->value; - } + } if ($val instanceof Query_Database) - { - return $this->subquery($val,$params); - } + { + return $this->subquery($val, $params); + } $params[] = $val; return '?'; } @@ -106,295 +106,296 @@ class Query_PDO_Driver extends Query_Database * * @param Query_Database $query Query builder for the subquery * @param array &$params Reference to parameters array - * @return string Subquery SQL - * @access public + * @return string Subquery SQL + * @access public */ - protected function subquery($query, &$params) { + protected function subquery($query, &$params) + { $query = $query->query(); $params = array_merge($params, $query[1]); return "({$query[0]}) "; } - + /** * Gets the SQL for a table to select from * * @param string|Expression_Database|Query_Database|array $table Table representation * @param array &$params Reference to parameters array * @param string &alias Alias for this table - * @return string Table SQL - * @access public + * @return string Table SQL + * @access public */ - public function escape_table($table, &$params) { - $alias=null; - if (is_array($table)) { + public function escape_table($table, &$params) + { + $alias = null; + if (is_array($table)) + { $alias = $table[1]; $table = $table[0]; } - - if (is_string($table)){ + + if (is_string($table)) + { $table = $this->quote($table); if ($alias != null) $table.= " AS {$alias}"; return $table; } - + if ($alias == null) $alias = $this->last_alias(); - - if($table instanceof Query_Database) - return "{$this->subquery($table,$params)} AS {$alias}"; - - if($table instanceof Expression_Database) + + if ($table instanceof Query_Database) + return "{$this->subquery($table, $params)} AS {$alias}"; + + if ($table instanceof Expression_Database) return "({$table->value}) AS {$alias}"; - + throw new Exception("Parameter type {get_class($table)} cannot be used as a table"); } - /** - * Builds a query and fills the $params array with parameter values - * - * @return array An array with a prepared query string and an array of parameters - * @access public - */ + /** + * Builds a query and fills the $params array with parameter values + * + * @return array An array with a prepared query string and an array of parameters + * @access public + */ public function query() - { - + { + $query = ''; $params = array(); - + if ($this->_type == 'insert') - { + { $query .= "INSERT INTO {$this->quote($this->_table)} "; if (empty($this->_data) && $this->_db_type == 'pgsql') - { + { $query.= "DEFAULT VALUES "; } - else - { + else + { $columns = ''; $values = ''; $first = true; - foreach($this->_data as $key => $val) - { + foreach ($this->_data as $key => $val) + { if (!$first) - { + { $values .= ', '; $columns .= ', '; } - else - { + else + { $first = false; } $columns .= $this->quote($key); - $values .= $this->escape_value($val,$params); + $values .= $this->escape_value($val, $params); } $query .= "({$columns}) VALUES({$values})"; } - } - else - { + } + else + { if ($this->_type == 'select') - { + { $query .= "SELECT "; - if ($this->_fields==null) - { + if ($this->_fields == null) + { $query .= "* "; } - else - { + else + { $first = true; foreach ($this->_fields as $f) - { + { if (!$first) - { + { $query .= ", "; } - else - { + else + { $first = false; } if (is_array($f)) - { + { $query .= "{$this->escape_field($f[0])} AS {$f[1]} "; } - else - { + else + { $query .= "{$this->escape_field($f)} "; } } } - $query .= "FROM {$this->escape_table($this->_table,$params)} "; + $query .= "FROM {$this->escape_table($this->_table, $params)} "; } if ($this->_type == 'count') - { - $query .= "SELECT COUNT(*) as {$this->quote('count')} FROM {$this->escape_table($this->_table,$params)} "; + { + $query .= "SELECT COUNT(*) as {$this->quote('count')} FROM {$this->escape_table($this->_table, $params)} "; } - + if ($this->_type == 'delete') - { - if ($this->_db_type!='sqlite') - { + { + if ($this->_db_type != 'sqlite') + { $query .= "DELETE {$this->last_alias()}.* FROM {$this->quote($this->_table)} "; } - else - { + else + { if (!empty($this->_joins)) - { + { throw new Exception("SQLite doesn't support deleting a table with JOIN in the query"); - } + } $query .= "DELETE FROM {$this->quote($this->_table)} "; } } - if ($this->_type=='update') - { + if ($this->_type == 'update') + { $query .= "UPDATE {$this->quote($this->_table)} SET "; $first = true; - foreach ($this->_data as $key=>$val){ + foreach ($this->_data as $key => $val) + { if (!$first) - { + { $query.=", "; } - else - { - $first=false; + else + { + $first = false; } - $query .= "{$this->quote($key)} = {$this->escape_value($val,$params)}"; + $query .= "{$this->quote($key)} = {$this->escape_value($val, $params)}"; } $query .= " "; } - + foreach ($this->_joins as $join) - { + { $table = $join[0]; - $table = $this->escape_table($table,$params); - $query .= strtoupper($join[1])." JOIN {$table} ON {$this->get_condition_query($join[2],$params,true,true)} "; + $table = $this->escape_table($table, $params); + $query .= strtoupper($join[1])." JOIN {$table} ON {$this->get_condition_query($join[2], $params, true, true)} "; } if (!empty($this->_conditions)) - { - $query .= "WHERE {$this->get_condition_query($this->_conditions,$params,true)} "; + { + $query .= "WHERE {$this->get_condition_query($this->_conditions, $params, true)} "; } - if (($this->_type == 'select' || $this->_type == 'count') && $this->_group_by!=null) - { + if (($this->_type == 'select' || $this->_type == 'count') && $this->_group_by != null) + { $query .= "GROUP BY {$this->escape_field($this->_group_by)} "; } - if (($this->_type == 'select' || $this->_type == 'count') && !empty($this->_having)) - { - $query .= "HAVING {$this->get_condition_query($this->_having,$params,true)} "; + if (($this->_type == 'select' || $this->_type == 'count') && !empty($this->_having)) + { + $query .= "HAVING {$this->get_condition_query($this->_having, $params, true)} "; } - + if ($this->_type == 'select' && !empty($this->_orderby)) - { + { $query .= "ORDER BY "; $first = true; foreach ($this->_orderby as $order) - { + { if (!$first) - { + { $query .= ','; } - else - { + else + { $first = false; } $query .= $this->escape_field($order[0])." "; if (isset($order[1])) - { + { $dir = strtoupper($order[1]); $query .= $dir." "; } } } - + if (count($this->_union) > 0 && ($this->_type == 'select')) - { + { $query = "({$query}) "; foreach ($this->_union as $union) - { - $query .= $union[1]?"UNION ALL ":"UNION "; + { + $query .= $union[1] ? "UNION ALL " : "UNION "; if (is_subclass_of($union[0], 'Query_Database')) - { - $query .= $this->subquery($union[0],$params); + { + $query .= $this->subquery($union[0], $params); } - elseif(is_subclass_of($union[0], 'Expression_Database')) - { + elseif (is_subclass_of($union[0], 'Expression_Database')) + { $query .= "({$union[0]->value}) "; } - else - { + else + { throw new Exception("You can only use query builder instances or DB::expr for unions"); } } } - + if ($this->_type != 'count') - { + { if ($this->_limit != null) - { + { $query .= "LIMIT {$this->_limit} "; - } + } if ($this->_offset != null) - { + { $query .= "OFFSET {$this->_offset} "; - } + } } - } - - return array($query,$params); - } + return array($query, $params); + } - /** - * Recursively parses conditions array into a query string - * - * @param array $p Element of the cobditions array - * @param array &$params Reference to parameters array - * @param boolean $skip_first_operator Flag to skip the first logical operator in a query - * to prevent AND or OR to be at the beginning of the query - * @param boolean $value_is_field Flag if the the value in the logical operations should - * be treated as a field. E.g. for joins where the fields are - * compared between themselves and not with actual values - * @return string String representation of the conditions - * @access public - * @throws Exception If condition cannot be parsed - */ - public function get_condition_query($p,&$params,$skip_first_operator,$value_is_field = false) - { + /** + * Recursively parses conditions array into a query string + * + * @param array $p Element of the cobditions array + * @param array &$params Reference to parameters array + * @param boolean $skip_first_operator Flag to skip the first logical operator in a query + * to prevent AND or OR to be at the beginning of the query + * @param boolean $value_is_field Flag if the the value in the logical operations should + * be treated as a field. E.g. for joins where the fields are + * compared between themselves and not with actual values + * @return string String representation of the conditions + * @access public + * @throws Exception If condition cannot be parsed + */ + public function get_condition_query($p, &$params, $skip_first_operator, $value_is_field = false) + { if (isset($p['field'])) - { + { if ($value_is_field) - { + { $param = $this->escape_field($p['value']); } - else - { + else + { $param = $this->escape_value($p['value'], $params); } return $this->escape_field($p['field']).' '.$p['operator'].' '.$param; } if (isset($p['logic'])) - { + { return ($skip_first_operator ? '' : strtoupper($p['logic']).' ') - .$this->get_condition_query($p['conditions'], $params, false, $value_is_field); + .$this->get_condition_query($p['conditions'], $params, false, $value_is_field); } - + $conds = ''; $skip = $skip_first_operator || (count($p) > 1); - foreach($p as $q) - { - $conds .= $this->get_condition_query($q,$params,$skip,$value_is_field).' '; + foreach ($p as $q) + { + $conds .= $this->get_condition_query($q, $params, $skip, $value_is_field).' '; $skip = false; } if (count($p) > 1 && !$skip_first_operator) - { + { return "( ".$conds.")"; - } + } return $conds; throw new Exception("Cannot parse condition:\n".var_export($p, true)); } - - }
\ No newline at end of file diff --git a/modules/database/classes/driver/pdo/result.php b/modules/database/classes/driver/pdo/result.php index d64c479..fda813c 100644 --- a/modules/database/classes/driver/pdo/result.php +++ b/modules/database/classes/driver/pdo/result.php @@ -7,52 +7,52 @@ class Result_PDO_Driver extends Result_Database { - /** - * Initializes new result object - * - * @param PDOStatement $stmt PDO Statement - * @return void - * @access public - * @link http://php.net/manual/en/class.pdostatement.php - */ - public function __construct($stmt) - { - $this->_result = $stmt; - } + /** + * Initializes new result object + * + * @param PDOStatement $stmt PDO Statement + * @return void + * @access public + * @link http://php.net/manual/en/class.pdostatement.php + */ + public function __construct($stmt) + { + $this->_result = $stmt; + } - /** - * Throws exception if rewind is attempted. - * - * @return void - * @access public - * @throws Exception If rewind is attempted - */ - public function rewind() - { - if ($this->_position > 0) - { - throw new Exception('PDO statement cannot be rewound for unbuffered queries'); - } - } + /** + * Throws exception if rewind is attempted. + * + * @return void + * @access public + * @throws Exception If rewind is attempted + */ + public function rewind() + { + if ($this->_position > 0) + { + throw new Exception('PDO statement cannot be rewound for unbuffered queries'); + } + } - /** - * Iterates to the next row in the result set - * - * @return void - * @access public - */ - public function next() - { - $this->check_fetched(); - $this->_row = $this->_result->fetchObject(); - if ($this->_row) - { - $this->_position++; - } - else - { - $this->_result->closeCursor(); - } - } + /** + * Iterates to the next row in the result set + * + * @return void + * @access public + */ + public function next() + { + $this->check_fetched(); + $this->_row = $this->_result->fetchObject(); + if ($this->_row) + { + $this->_position++; + } + else + { + $this->_result->closeCursor(); + } + } }
\ No newline at end of file diff --git a/modules/orm/classes/orm.php b/modules/orm/classes/orm.php index 96bfd1e..f975fc1 100644 --- a/modules/orm/classes/orm.php +++ b/modules/orm/classes/orm.php @@ -22,791 +22,792 @@ class ORM { - /** - * Specifies which table the model will use, can be overridden - * @var string - * @access public - */ - public $table = null; - - /** - * Specifies which connection the model will use, can be overridden - * but a model can have relationships only with models utilizing the same connection - * @var string - * @access public - */ - public $connection = 'default'; - - /** - * Specifies which column is treated as PRIMARY KEY - * @var string - * @access public - */ - public $id_field = 'id'; - - /** - * You can define 'Belongs to' relationships buy changing this array - * @var array - * @access protected - */ - protected $belongs_to = array(); - - /** - * You can define 'Has one' relationships buy changing this array - * @var array - * @access protected - */ - protected $has_one = array(); - - /** - * You can define 'Has many' relationships buy changing this array - * @var array - * @access protected - */ - protected $has_many = array(); - - /** - * Associated query builder - * @var Query_Database - * @access public - */ - public $query; - - /** - * The name of the model - * @var string - * @access public - */ - public $model_name; - - /** - * Cached properties - * @var array - * @access public - */ - public $cached = array(); - - /** - * An instance of the database connection - * @var DB - * @access protected - */ - protected $db; - - /** - * Current row returned by the database - * @var array - * @access protected - */ - protected $_row = array(); - - /** - * A flag whether the row was loaded from the database - * @var boolean - * @access protected - */ - protected $_loaded = false; - - /** - * Relationships to be preloaded - * @var array - * @access protected - */ - protected $_with = array(); - - /** - * Cached column names for tables - * @var array - * @access protected - */ - protected static $_column_cache = array(); - - /** - * Constructs the model. To use ORM it is enough to - * just create a model like this: - * <code> - * class Fairy_Model extends ORM { } - * </code> - * By default it will assume that the name of your table - * is the plural form of the models' name, the PRIMARY KEY is id, - * and will use the 'default' connection. This behaviour is easy to be - * changed by overriding $table, $id and $db properties. - * - * @return void - * @access public - * @ see $table - * @ see $id - * @ see $db - */ - public function __construct() - { - $this->query = DB::instance($this->connection)->build_query('select'); - $this->model_name = strtolower(get_class($this)); - if (substr($this->model_name, -6) == '_model') - { - $this->model_name = substr($this->model_name, 0, -6); - } - if ($this->table == null) - { - $this->table = ORM::plural($this->model_name); - } - $this->query->table($this->table); - - foreach (array('belongs_to', 'has_one', 'has_many') as $rels) - { - $normalized = array(); - foreach ($this->$rels as $key => $rel) - { - if (!is_array($rel)) - { - $key = $rel; - $rel = array(); - } - $normalized[$key] = $rel; - if (!isset($rel['model'])) - { - $rel['model'] = $normalized[$key]['model'] = $rels == 'has_many' ? ORM::singular($key) : $key; - } - - $normalized[$key]['type'] = $rels; - if (!isset($rel['key'])) - { - $normalized[$key]['key'] = $rels != 'belongs_to' ? ($this->model_name.'_id') : $rel['model'].'_id'; - } - - if ($rels == 'has_many' && isset($rel['through'])) - { - if (!isset($rel['foreign_key'])) - { - $normalized[$key]['foreign_key'] = $rel['model'].'_id'; - } - } - - $normalized[$key]['name'] = $key; - } - $this->$rels = $normalized; - } - } - - /** - * Magic method for call Query_Database methods - * - * @param string $method Method to call - * @param array $arguments Arguments passed to the method - * @return mixed Returns self if parameters were passed. If no parameters where passed returns - * current value for the associated parameter - * @throws Exception If method doesn't exist - * @access public - */ - public function __call($method, $arguments) - { - if (!in_array($method, array('limit', 'offset', 'order_by', 'where'))) - { - throw new Exception("Method '{$method}' doesn't exist on .".get_class($this)); - } - $res = call_user_func_array(array($this->query, $method), $arguments); - if (is_subclass_of($res, 'Query_Database')) - { - return $this; - } - return $res; - } - - /** - * Finds all rows that meet set criteria. - * - * @return Result_ORM Returns Result_ORM that you can use in a 'foreach' loop. - * @throw Exception If the relationship specified using with() does not exist or is not of the belongs_to or has_one type - * @access public - */ - public function find_all() - { - $paths = array(); - if (!empty($this->_with)) - { - $fields = array(); - $this_alias = $this->query->last_alias(); - foreach ($this->columns() as $column) - { - $fields[] = array("{$this_alias}.{$column}", "{$this_alias}__{$column}"); - } - foreach ($this->_with as $target) - { - $model = $this; - $model_alias = $this_alias; - $rels = explode('.', $target); - foreach ($rels as $key => $rel_name) - { - $path = implode('.', array_slice($rels, 0, $key + 1)); - if (isset($paths[$path])) - { - $model = $paths[$path]['model']; - $model_alias = $paths[$path]['alias']; - continue; - } - $alias = $this->query->add_alias(); - $model_rels = array_merge($model->has_one, $model->has_many, $model->belongs_to); - $rel = Misc::arr($model_rels, $rel_name, false); - - if (!$rel) - { - throw new Exception("Model '{$model->model_name}' doesn't have a '{$rel_name}' relation defined"); - } - if ($rel['type'] == 'has_many') - { - throw new Exception("Relationship '{$rel_name}' is of has_many type and cannot be preloaded view with()"); - } - $rel_model = ORM::factory($rel['model']); - - if ($rel['type'] == 'belongs_to') - { - $this->query->join(array($rel_model->table, $alias), array( - $model_alias.'.'.$rel['key'], - $alias.'.'.$rel_model->id_field, - ), 'left'); - } - else - { - $this->query->join(array($rel_model->table, $alias), array( - $model_alias.'.'.$model->id_field, - $alias.'.'.$rel['key'], - ), 'left'); - } - - foreach ($rel_model->columns() as $column) - { - $fields[] = array("{$alias}.{$column}", "{$alias}__{$column}"); - } - $model = $rel_model; - $model_alias = $alias; - $paths[$path] = array('alias' => $alias, 'model' => $model); - } - } - - call_user_func_array(array($this->query, 'fields'), $fields); - } - - return new Result_ORM(get_class($this), $res = $this->query->execute(), $paths); - } - - /** - * Searches for the first row that meets set criteria. If no rows match it still returns an ORM object - * but with its loaded() flag being False. calling save() on such an object will insert a new row. - * - * @return ORM Found item or new object of the current model but with loaded() flag being False - * @access public - */ - public function find() - { - $set_limit = $this->limit(); - $res = $this->limit(1)->find_all()->current(); - $this->limit($set_limit); - return $res; - } - - /** - * Counts all rows that meet set criteria. Ignores limit and offset. - * - * @return int Number of rows - * @access public - */ - public function count_all() - { - $query = clone $this->query; - $query->type('count'); - return $query->execute(); - } - - /** - * Checks if the item is considered to be loaded from the database - * - * @return boolean Returns True if the item was loaded - * @access public - */ - public function loaded() - { - return $this->_loaded; - } - - /** - * Returns the row associated with current ORM item as an associative array - * - * @return array Associative array representing the row - * @access public - */ - public function as_array() - { - return $this->_row; - } - - /** - * Returns a clone of query builder that is being used to set conditions. - * It is useful for example if you let ORM manage building a complex query using it's relationship - * system, then you get the clone of that query and alter it to your liking, - * so there is no need to writing relationship joins yourself. - * - * @return Query_Database A clone of the current query builder - * @access public - */ - public function query() - { - return clone $this->query; - } - - /** - * You can override this method to return additional properties that you would like to use - * in your model. One advantage for using this instead of just overriding __get() is that - * in this way the properties also get cached. - * - * @param string $property The name of the property to get - * @return void - * @access public - */ - public function get($property) - { - - } - - /** - * Magic method that allows accessing row columns as properties and also facilitates - * access to relationships and custom properties defined in get() method. - * If a relationship is being accessed, it will return an ORM model of the related table - * and automatically alter its query so that all your previously set conditions will remain - - * @param string $column Name of the column, property or relationship to get - * @return mixed - * @access public - * @throws Exception If neither property nor a relationship with such name is found - */ - public function __get($column) - { - if (array_key_exists($column, $this->_row)) - { - return $this->_row[$column]; - } - if (array_key_exists($column, $this->cached)) - { - return $this->cached[$column]; - } - if (($val = $this->get($column)) !== null) - { - $this->cached[$column] = $val; - return $val; - } - $relations = array_merge($this->has_one, $this->has_many, $this->belongs_to); - if ($target = Misc::arr($relations, $column, false)) - { - $model = ORM::factory($target['model']); - $model->query = clone $this->query; - if ($this->loaded()) - { - $model->query->where($this->id_field, $this->_row[$this->id_field]); - } - if ($target['type'] == 'has_many' && isset($target['through'])) - { - $last_alias = $model->query->last_alias(); - $through_alias = $model->query->add_alias(); - $new_alias = $model->query->add_alias(); - $model->query->join(array($target['through'], $through_alias), array( - $last_alias.'.'.$this->id_field, - $through_alias.'.'.$target['key'], - ), 'inner'); - $model->query->join(array($model->table, $new_alias), array( - $through_alias.'.'.$target['foreign_key'], - $new_alias.'.'.$model->id_field, - ), 'inner'); - } - else - { - $last_alias = $model->query->last_alias(); - $new_alias = $model->query->add_alias(); - if ($target['type'] == 'belongs_to') - { - $model->query->join(array($model->table, $new_alias), array( - $last_alias.'.'.$target['key'], - $new_alias.'.'.$model->id_field, - ), 'inner'); - } - else - { - $model->query->join(array($model->table, $new_alias), array( - $last_alias.'.'.$this->id_field, - $new_alias.'.'.$target['key'], - ), 'inner'); - } - } - $model->query->fields("$new_alias.*"); - if ($target['type'] != 'has_many' && $this->loaded()) - { - $model = $model->find(); - $this->cached[$column] = $model; - } - return $model; - } - - throw new Exception("Property {$column} not found on {$this->model_name} model."); - } - - /** - * Magic method to update record values when set as properties or to add an ORM item to - * a relation. By assigning an ORM object to a relationship a relationship is created between the - * current item and the passed one Using properties this way is a shortcut to the add() method. - * - * @param string $column Column or relationship name - * @param mixed $val Column value or an ORM item to be added to a relation - * @return void - * @access public - * @see add() - */ - public function __set($column, $val) - { - $relations = array_merge($this->has_one, $this->has_many, $this->belongs_to); - if (array_key_exists($column, $relations)) - { - $this->add($column, $val); - } - else - { - $this->_row[$column] = $val; - } - $this->cached = array(); - } - - /** - * Create a relationship between current item and an other one - * - * @param string $relation Name of the relationship - * @param ORM $model ORM item to create a relationship with - * @return void - * @access public - * @throws Exception Exception If relationship is not defined - * @throws Exception Exception If current item is not in the database yet (isn't considered loaded()) - * @throws Exception Exception If passed item is not in the database yet (isn't considered loaded()) - */ - public function add($relation, $model) - { - - $rels = array_merge($this->has_one, $this->has_many, $this->belongs_to); - $rel = Misc::arr($rels, $relation, false); - if (!$rel) - { - throw new Exception("Model doesn't have a '{$relation}' relation defined"); - } - - if ($rel['type'] == 'belongs_to') - { - - if (!$model->loaded()) - { - throw new Exception("Model must be loaded before added to a belongs_to relationship. Probably you haven't saved it."); - } - - $key = $rel['key']; - $this->$key = $model->_row[$this->id_field]; - if ($this->loaded()) - { - $this->save(); - } - } - elseif (isset($rel['through'])) - { - - if (!$this->loaded()) - { - throw new Exception("Model must be loaded before you try adding 'through' relationships to it. Probably you haven't saved it."); - } - if (!$model->loaded()) - { - throw new Exception("Model must be loaded before added to a 'through' relationship. Probably you haven't saved it."); - } - - $exists = DB::instance($this->connection)->build_query('count') - ->table($rel['through']) - ->where(array( - array($rel['key'], $this->_row[$this->id_field]), - array($rel['foreign_key'], $model->_row[$model->id_field]) - )) - ->execute(); - if (!$exists) - { - DB::instance($this->connection)->build_query('insert') - ->table($rel['through']) - ->data(array( - $rel['key'] => $this->_row[$this->id_field], - $rel['foreign_key'] => $model->_row[$model->id_field] - )) - ->execute(); - } - } - else - { - - if (!$this->loaded()) - { - throw new Exception("Model must be loaded before you try adding 'has_many' relationships to it. Probably you haven't saved it."); - } - - $key = $rel['key']; - $model->$key = $this->_row[$this->id_field]; - if ($model->loaded()) - { - $model->save(); - } - } - $this->cached = array(); - } - - /** - * Removes a relationship between current item and the passed one - * - * @param string $relation Name of the relationship - * @param ORM $model ORM item to remove relationship with. Can be omitted for 'belongs_to' relationships - * @return void - * @access public - * @throws Exception Exception If realtionship is not defined - * @throws Exception Exception If current item is not in the database yet (isn't considered loaded()) - * @throws Exception Exception If passed item is not in the database yet (isn't considered loaded()) - */ - public function remove($relation, $model = null) - { - - if (!$this->loaded()) - { - throw new Exception("Model must be loaded before you try removing relationships from it."); - } - - $rels = array_merge($this->has_one, $this->has_many, $this->belongs_to); - $rel = Misc::arr($rels, $relation, false); - if (!$rel) - { - throw new Exception("Model doesn't have a '{$relation}' relation defined"); - } - - if ($rel['type'] != 'belongs_to' && (!$model || !$model->loaded())) - { - throw new Exception("Model must be loaded before being removed from a has_one or has_many relationship."); - } - if ($rel['type'] == 'belongs_to') - { - $key = $rel['key']; - $this->$key = null; - $this->save(); - } - elseif (isset($rel['through'])) - { - DB::instance($this->connection)->build_query('delete') - ->table($rel['through']) - ->where(array( - array($rel['key'], $this->_row[$this->id_field]), - array($rel['foreign_key'], $model->_row[$model->id_field]) - )) - ->execute(); - } - else - { - $key = $rel['key']; - $model->$key = null; - $model->save(); - } - $this->cached = array(); - } - - /** - * Gets name column names of the table associated with the model. - * - * @return array Array of column names - * @access public - */ - public function columns() - { - if (!isset(ORM::$_column_cache[$this->table])) - { - ORM::$_column_cache[$this->table] = DB::instance($this->connection)->list_columns($this->table); - } - return ORM::$_column_cache[$this->table]; - } - - /** - * Defines which relationships should be preloaded. You can only preload - * belongs_to and has_one relationships. You can use the dot notation to - * preload deep relationsips, e.g. 'tree.protector' will preload the tree - * that a fairy lives in and also preload the protector of that tree. - * - * @param string $relationsip,... List of relationships to preload - * @return ORM Returns itself - * @access public - */ - public function with() - { - $this->_with = func_get_args(); - return $this; - } - - /** - * Deletes current item from the database - * - * @return void - * @access public - * @throws Exception If the item is not in the database, e.g. is not loaded() - */ - public function delete() - { - if (!$this->loaded()) - { - throw new Exception("Cannot delete an item that wasn't selected from database"); - } - DB::instance($this->connection)->build_query('delete') - ->table($this->table) - ->where($this->id_field, $this->_row[$this->id_field]) - ->execute(); - $this->cached = array(); - } - - /** - * Deletes all items that meet set conditions. Use in the same way - * as you would a find_all() method. - * - * @return ORM Returns self - * @access public - */ - public function delete_all() - { - $query = clone $this->query; - $query->type('delete'); - $query->execute(); - return $this; - } - - /** - * Saves the item back to the database. If item is loaded() it will result - * in an update, otherwise a new row will be inserted - * - * @return ORM Returns self - * @access public - */ - public function save() - { - if ($this->loaded()) - { - $query = DB::instance($this->connection)->build_query('update') - ->table($this->table) - ->where($this->id_field, $this->_row[$this->id_field]); - } - else - { - $query = DB::instance($this->connection)->build_query('insert') - ->table($this->table); - } - $query->data($this->_row); - $query->execute(); - - if ($this->loaded()) - { - $id = $this->_row[$this->id_field]; - } - else - { - $id = DB::instance($this->connection)->get_insert_id(); - } - $row = (array) DB::instance($this->connection)->build_query('select') - ->table($this->table) - ->where($this->id_field, $id)->execute()->current(); - $this->values($row, true); - return $this; - } - - /** - * Batch updates item columns using an associative array - * - * @param array $row Associative array of key => value pairs - * @param boolean $set_loaded Flag to consider the ORM item loaded. Useful if you selected - * the row from the database and want to wrap it in ORM - * @return ORM Returns self - * @access public - */ - public function values($row, $set_loaded = false) - { - $this->_row = array_merge($this->_row, $row); - if ($set_loaded) - { - $this->_loaded = true; - } - $this->cached = array(); - return $this; - } - - /** - * Initializes ORM model by name, and optionally fetches an item by id - * - * @param string $name Model name - * @param mixed $id If set ORM will try to load the item with this id from the database - * @return ORM ORM model, either empty or preloaded - * @access public - * @static - */ - public static function factory($name, $id = null) - { - $model = $name.'_Model'; - $model = new $model; - if ($id != null) - { - $model = $model->where($model->id_field, $id)->find(); - $model->values(array($model->id_field => $id)); - } - return $model; - } - - /** - * Gets plural form of a noun - * - * @param string $str Noun to get a plural form of - * @return string Plural form - * @access private - * @static - */ - private static function plural($str) - { - $regexes = array( - '/^(.*?[sxz])$/i' => '\\1es', - '/^(.*?[^aeioudgkprt]h)$/i' => '\\1es', - '/^(.*?[^aeiou])y$/i' => '\\1ies', - ); - foreach ($regexes as $key => $val) - { - $str = preg_replace($key, $val, $str, -1, $count); - if ($count) - { - return $str; - } - } - return $str.'s'; - } - - /** - * Gets singular form of a noun - * - * @param string $str Noun to get singular form of - * @return string Singular form of the noun - * @access private - * @static - */ - private static function singular($str) - { - $regexes = array( - '/^(.*?us)$/i' => '\\1', - '/^(.*?[sxz])es$/i' => '\\1', - '/^(.*?[^aeioudgkprt]h)es$/i' => '\\1', - '/^(.*?[^aeiou])ies$/i' => '\\1y', - '/^(.*?)s$/' => '\\1', - ); - foreach ($regexes as $key => $val) - { - $str = preg_replace($key, $val, $str, -1, $count); - if ($count) - { - return $str; - } - } - return $str; - } + /** + * Specifies which table the model will use, can be overridden + * @var string + * @access public + */ + public $table = null; + + /** + * Specifies which connection the model will use, can be overridden + * but a model can have relationships only with models utilizing the same connection + * @var string + * @access public + */ + public $connection = 'default'; + + /** + * Specifies which column is treated as PRIMARY KEY + * @var string + * @access public + */ + public $id_field = 'id'; + + /** + * You can define 'Belongs to' relationships buy changing this array + * @var array + * @access protected + */ + protected $belongs_to = array(); + + /** + * You can define 'Has one' relationships buy changing this array + * @var array + * @access protected + */ + protected $has_one = array(); + + /** + * You can define 'Has many' relationships buy changing this array + * @var array + * @access protected + */ + protected $has_many = array(); + + /** + * Associated query builder + * @var Query_Database + * @access public + */ + public $query; + + /** + * The name of the model + * @var string + * @access public + */ + public $model_name; + + /** + * Cached properties + * @var array + * @access public + */ + public $cached = array(); + + /** + * An instance of the database connection + * @var DB + * @access protected + */ + protected $db; + + /** + * Current row returned by the database + * @var array + * @access protected + */ + protected $_row = array(); + + /** + * A flag whether the row was loaded from the database + * @var boolean + * @access protected + */ + protected $_loaded = false; + + /** + * Relationships to be preloaded + * @var array + * @access protected + */ + protected $_with = array(); + + /** + * Cached column names for tables + * @var array + * @access protected + */ + protected static $_column_cache = array(); + + /** + * Constructs the model. To use ORM it is enough to + * just create a model like this: + * <code> + * class Fairy_Model extends ORM { } + * </code> + * By default it will assume that the name of your table + * is the plural form of the models' name, the PRIMARY KEY is id, + * and will use the 'default' connection. This behaviour is easy to be + * changed by overriding $table, $id and $db properties. + * + * @return void + * @access public + * @ see $table + * @ see $id + * @ see $db + */ + public function __construct() + { + $this->query = DB::instance($this->connection)->build_query('select'); + $this->model_name = strtolower(get_class($this)); + if (substr($this->model_name, -6) == '_model') + { + $this->model_name = substr($this->model_name, 0, -6); + } + if ($this->table == null) + { + $this->table = ORM::plural($this->model_name); + } + $this->query->table($this->table); + + foreach (array('belongs_to', 'has_one', 'has_many') as $rels) + { + $normalized = array(); + foreach ($this->$rels as $key => $rel) + { + if (!is_array($rel)) + { + $key = $rel; + $rel = array(); + } + $normalized[$key] = $rel; + if (!isset($rel['model'])) + { + $rel['model'] = $normalized[$key]['model'] = $rels == 'has_many' ? ORM::singular($key) : $key; + } + + $normalized[$key]['type'] = $rels; + if (!isset($rel['key'])) + { + $normalized[$key]['key'] = $rels != 'belongs_to' ? ($this->model_name.'_id') : $rel['model'].'_id'; + } + + if ($rels == 'has_many' && isset($rel['through'])) + { + if (!isset($rel['foreign_key'])) + { + $normalized[$key]['foreign_key'] = $rel['model'].'_id'; + } + } + + $normalized[$key]['name'] = $key; + } + $this->$rels = $normalized; + } + } + + /** + * Magic method for call Query_Database methods + * + * @param string $method Method to call + * @param array $arguments Arguments passed to the method + * @return mixed Returns self if parameters were passed. If no parameters where passed returns + * current value for the associated parameter + * @throws Exception If method doesn't exist + * @access public + */ + public function __call($method, $arguments) + { + if (!in_array($method, array('limit', 'offset', 'order_by', 'where'))) + { + throw new Exception("Method '{$method}' doesn't exist on .".get_class($this)); + } + $res = call_user_func_array(array($this->query, $method), $arguments); + if (is_subclass_of($res, 'Query_Database')) + { + return $this; + } + return $res; + } + + /** + * Finds all rows that meet set criteria. + * + * @return Result_ORM Returns Result_ORM that you can use in a 'foreach' loop. + * @throw Exception If the relationship specified using with() does not exist or is not of the belongs_to or has_one type + * @access public + */ + public function find_all() + { + $paths = array(); + if (!empty($this->_with)) + { + $fields = array(); + $this_alias = $this->query->last_alias(); + foreach ($this->columns() as $column) + { + $fields[] = array("{$this_alias}.{$column}", "{$this_alias}__{$column}"); + } + foreach ($this->_with as $target) + { + $model = $this; + $model_alias = $this_alias; + $rels = explode('.', $target); + foreach ($rels as $key => $rel_name) + { + $path = implode('.', array_slice($rels, 0, $key + 1)); + if (isset($paths[$path])) + { + $model = $paths[$path]['model']; + $model_alias = $paths[$path]['alias']; + continue; + } + $alias = $this->query->add_alias(); + $model_rels = array_merge($model->has_one, $model->has_many, $model->belongs_to); + $rel = Misc::arr($model_rels, $rel_name, false); + + if (!$rel) + { + throw new Exception("Model '{$model->model_name}' doesn't have a '{$rel_name}' relation defined"); + } + if ($rel['type'] == 'has_many') + { + throw new Exception("Relationship '{$rel_name}' is of has_many type and cannot be preloaded view with()"); + } + $rel_model = ORM::factory($rel['model']); + + if ($rel['type'] == 'belongs_to') + { + $this->query->join(array($rel_model->table, $alias), array( + $model_alias.'.'.$rel['key'], + $alias.'.'.$rel_model->id_field, + ), 'left'); + } + else + { + $this->query->join(array($rel_model->table, $alias), array( + $model_alias.'.'.$model->id_field, + $alias.'.'.$rel['key'], + ), 'left'); + } + + foreach ($rel_model->columns() as $column) + { + $fields[] = array("{$alias}.{$column}", "{$alias}__{$column}"); + } + $model = $rel_model; + $model_alias = $alias; + $paths[$path] = array('alias' => $alias, 'model' => $model); + } + } + + call_user_func_array(array($this->query, 'fields'), $fields); + } + + return new Result_ORM(get_class($this), $res = $this->query->execute(), $paths); + } + + /** + * Searches for the first row that meets set criteria. If no rows match it still returns an ORM object + * but with its loaded() flag being False. calling save() on such an object will insert a new row. + * + * @return ORM Found item or new object of the current model but with loaded() flag being False + * @access public + */ + public function find() + { + $set_limit = $this->limit(); + $res = $this->limit(1)->find_all()->current(); + $this->limit($set_limit); + return $res; + } + + /** + * Counts all rows that meet set criteria. Ignores limit and offset. + * + * @return int Number of rows + * @access public + */ + public function count_all() + { + $query = clone $this->query; + $query->type('count'); + return $query->execute(); + } + + /** + * Checks if the item is considered to be loaded from the database + * + * @return boolean Returns True if the item was loaded + * @access public + */ + public function loaded() + { + return $this->_loaded; + } + + /** + * Returns the row associated with current ORM item as an associative array + * + * @return array Associative array representing the row + * @access public + */ + public function as_array() + { + return $this->_row; + } + + /** + * Returns a clone of query builder that is being used to set conditions. + * It is useful for example if you let ORM manage building a complex query using it's relationship + * system, then you get the clone of that query and alter it to your liking, + * so there is no need to writing relationship joins yourself. + * + * @return Query_Database A clone of the current query builder + * @access public + */ + public function query() + { + return clone $this->query; + } + + /** + * You can override this method to return additional properties that you would like to use + * in your model. One advantage for using this instead of just overriding __get() is that + * in this way the properties also get cached. + * + * @param string $property The name of the property to get + * @return void + * @access public + */ + public function get($property) + { + + } + + /** + * Magic method that allows accessing row columns as properties and also facilitates + * access to relationships and custom properties defined in get() method. + * If a relationship is being accessed, it will return an ORM model of the related table + * and automatically alter its query so that all your previously set conditions will remain + + * @param string $column Name of the column, property or relationship to get + * @return mixed + * @access public + * @throws Exception If neither property nor a relationship with such name is found + */ + public function __get($column) + { + if (array_key_exists($column, $this->_row)) + { + return $this->_row[$column]; + } + if (array_key_exists($column, $this->cached)) + { + return $this->cached[$column]; + } + if (($val = $this->get($column)) !== null) + { + $this->cached[$column] = $val; + return $val; + } + $relations = array_merge($this->has_one, $this->has_many, $this->belongs_to); + if ($target = Misc::arr($relations, $column, false)) + { + $model = ORM::factory($target['model']); + $model->query = clone $this->query; + if ($this->loaded()) + { + $model->query->where($this->id_field, $this->_row[$this->id_field]); + } + if ($target['type'] == 'has_many' && isset($target['through'])) + { + $last_alias = $model->query->last_alias(); + $through_alias = $model->query->add_alias(); + $new_alias = $model->query->add_alias(); + $model->query->join(array($target['through'], $through_alias), array( + $last_alias.'.'.$this->id_field, + $through_alias.'.'.$target['key'], + ), 'inner'); + $model->query->join(array($model->table, $new_alias), array( + $through_alias.'.'.$target['foreign_key'], + $new_alias.'.'.$model->id_field, + ), 'inner'); + } + else + { + $last_alias = $model->query->last_alias(); + $new_alias = $model->query->add_alias(); + if ($target['type'] == 'belongs_to') + { + $model->query->join(array($model->table, $new_alias), array( + $last_alias.'.'.$target['key'], + $new_alias.'.'.$model->id_field, + ), 'inner'); + } + else + { + $model->query->join(array($model->table, $new_alias), array( + $last_alias.'.'.$this->id_field, + $new_alias.'.'.$target['key'], + ), 'inner'); + } + } + $model->query->fields("$new_alias.*"); + if ($target['type'] != 'has_many' && $this->loaded()) + { + $model = $model->find(); + $this->cached[$column] = $model; + } + return $model; + } + + throw new Exception("Property {$column} not found on {$this->model_name} model."); + } + + /** + * Magic method to update record values when set as properties or to add an ORM item to + * a relation. By assigning an ORM object to a relationship a relationship is created between the + * current item and the passed one Using properties this way is a shortcut to the add() method. + * + * @param string $column Column or relationship name + * @param mixed $val Column value or an ORM item to be added to a relation + * @return void + * @access public + * @see add() + */ + public function __set($column, $val) + { + $relations = array_merge($this->has_one, $this->has_many, $this->belongs_to); + if (array_key_exists($column, $relations)) + { + $this->add($column, $val); + } + else + { + $this->_row[$column] = $val; + } + $this->cached = array(); + } + + /** + * Create a relationship between current item and an other one + * + * @param string $relation Name of the relationship + * @param ORM $model ORM item to create a relationship with + * @return void + * @access public + * @throws Exception Exception If relationship is not defined + * @throws Exception Exception If current item is not in the database yet (isn't considered loaded()) + * @throws Exception Exception If passed item is not in the database yet (isn't considered loaded()) + */ + public function add($relation, $model) + { + + $rels = array_merge($this->has_one, $this->has_many, $this->belongs_to); + $rel = Misc::arr($rels, $relation, false); + if (!$rel) + { + throw new Exception("Model doesn't have a '{$relation}' relation defined"); + } + + if ($rel['type'] == 'belongs_to') + { + + if (!$model->loaded()) + { + throw new Exception("Model must be loaded before added to a belongs_to relationship. Probably you haven't saved it."); + } + + $key = $rel['key']; + $this->$key = $model->_row[$this->id_field]; + if ($this->loaded()) + { + $this->save(); + } + } + elseif (isset($rel['through'])) + { + + if (!$this->loaded()) + { + throw new Exception("Model must be loaded before you try adding 'through' relationships to it. Probably you haven't saved it."); + } + if (!$model->loaded()) + { + throw new Exception("Model must be loaded before added to a 'through' relationship. Probably you haven't saved it."); + } + + $exists = DB::instance($this->connection)->build_query('count') + ->table($rel['through']) + ->where(array( + array($rel['key'], $this->_row[$this->id_field]), + array($rel['foreign_key'], $model->_row[$model->id_field]) + )) + ->execute(); + if (!$exists) + { + DB::instance($this->connection)->build_query('insert') + ->table($rel['through']) + ->data(array( + $rel['key'] => $this->_row[$this->id_field], + $rel['foreign_key'] => $model->_row[$model->id_field] + )) + ->execute(); + } + } + else + { + + if (!$this->loaded()) + { + throw new Exception("Model must be loaded before you try adding 'has_many' relationships to it. Probably you haven't saved it."); + } + + $key = $rel['key']; + $model->$key = $this->_row[$this->id_field]; + if ($model->loaded()) + { + $model->save(); + } + } + $this->cached = array(); + } + + /** + * Removes a relationship between current item and the passed one + * + * @param string $relation Name of the relationship + * @param ORM $model ORM item to remove relationship with. Can be omitted for 'belongs_to' relationships + * @return void + * @access public + * @throws Exception Exception If realtionship is not defined + * @throws Exception Exception If current item is not in the database yet (isn't considered loaded()) + * @throws Exception Exception If passed item is not in the database yet (isn't considered loaded()) + */ + public function remove($relation, $model = null) + { + + if (!$this->loaded()) + { + throw new Exception("Model must be loaded before you try removing relationships from it."); + } + + $rels = array_merge($this->has_one, $this->has_many, $this->belongs_to); + $rel = Misc::arr($rels, $relation, false); + if (!$rel) + { + throw new Exception("Model doesn't have a '{$relation}' relation defined"); + } + + if ($rel['type'] != 'belongs_to' && (!$model || !$model->loaded())) + { + throw new Exception("Model must be loaded before being removed from a has_one or has_many relationship."); + } + if ($rel['type'] == 'belongs_to') + { + $key = $rel['key']; + $this->$key = null; + $this->save(); + } + elseif (isset($rel['through'])) + { + DB::instance($this->connection)->build_query('delete') + ->table($rel['through']) + ->where(array( + array($rel['key'], $this->_row[$this->id_field]), + array($rel['foreign_key'], $model->_row[$model->id_field]) + )) + ->execute(); + } + else + { + $key = $rel['key']; + $model->$key = null; + $model->save(); + } + $this->cached = array(); + } + + /** + * Gets name column names of the table associated with the model. + * + * @return array Array of column names + * @access public + */ + public function columns() + { + if (!isset(ORM::$_column_cache[$this->table])) + { + ORM::$_column_cache[$this->table] = DB::instance($this->connection)->list_columns($this->table); + } + return ORM::$_column_cache[$this->table]; + } + + /** + * Defines which relationships should be preloaded. You can only preload + * belongs_to and has_one relationships. You can use the dot notation to + * preload deep relationsips, e.g. 'tree.protector' will preload the tree + * that a fairy lives in and also preload the protector of that tree. + * + * @param string $relationsip,... List of relationships to preload + * @return ORM Returns itself + * @access public + */ + public function with() + { + $this->_with = func_get_args(); + return $this; + } + + /** + * Deletes current item from the database + * + * @return void + * @access public + * @throws Exception If the item is not in the database, e.g. is not loaded() + */ + public function delete() + { + if (!$this->loaded()) + { + throw new Exception("Cannot delete an item that wasn't selected from database"); + } + DB::instance($this->connection)->build_query('delete') + ->table($this->table) + ->where($this->id_field, $this->_row[$this->id_field]) + ->execute(); + $this->cached = array(); + } + + /** + * Deletes all items that meet set conditions. Use in the same way + * as you would a find_all() method. + * + * @return ORM Returns self + * @access public + */ + public function delete_all() + { + $query = clone $this->query; + $query->type('delete'); + $query->execute(); + return $this; + } + + /** + * Saves the item back to the database. If item is loaded() it will result + * in an update, otherwise a new row will be inserted + * + * @return ORM Returns self + * @access public + */ + public function save() + { + if ($this->loaded()) + { + $query = DB::instance($this->connection)->build_query('update') + ->table($this->table) + ->where($this->id_field, $this->_row[$this->id_field]); + } + else + { + $query = DB::instance($this->connection)->build_query('insert') + ->table($this->table); + } + $query->data($this->_row); + $query->execute(); + + if ($this->loaded()) + { + $id = $this->_row[$this->id_field]; + } + else + { + $id = DB::instance($this->connection)->get_insert_id(); + } + $row = (array) DB::instance($this->connection)->build_query('select') + ->table($this->table) + ->where($this->id_field, $id)->execute()->current(); + $this->values($row, true); + return $this; + } + + /** + * Batch updates item columns using an associative array + * + * @param array $row Associative array of key => value pairs + * @param boolean $set_loaded Flag to consider the ORM item loaded. Useful if you selected + * the row from the database and want to wrap it in ORM + * @return ORM Returns self + * @access public + */ + public function values($row, $set_loaded = false) + { + $this->_row = array_merge($this->_row, $row); + if ($set_loaded) + { + $this->_loaded = true; + } + $this->cached = array(); + return $this; + } + + /** + * Initializes ORM model by name, and optionally fetches an item by id + * + * @param string $name Model name + * @param mixed $id If set ORM will try to load the item with this id from the database + * @return ORM ORM model, either empty or preloaded + * @access public + * @static + */ + public static function factory($name, $id = null) + { + $model = $name.'_Model'; + $model = new $model; + if ($id != null) + { + $model = $model->where($model->id_field, $id)->find(); + $model->values(array($model->id_field => $id)); + } + return $model; + } + + /** + * Gets plural form of a noun + * + * @param string $str Noun to get a plural form of + * @return string Plural form + * @access private + * @static + */ + private static function plural($str) + { + $regexes = array( + '/^(.*?[sxz])$/i' => '\\1es', + '/^(.*?[^aeioudgkprt]h)$/i' => '\\1es', + '/^(.*?[^aeiou])y$/i' => '\\1ies', + ); + foreach ($regexes as $key => $val) + { + $str = preg_replace($key, $val, $str, -1, $count); + if ($count) + { + return $str; + } + } + return $str.'s'; + } + + /** + * Gets singular form of a noun + * + * @param string $str Noun to get singular form of + * @return string Singular form of the noun + * @access private + * @static + */ + private static function singular($str) + { + $regexes = array( + '/^(.*?us)$/i' => '\\1', + '/^(.*?[sxz])es$/i' => '\\1', + '/^(.*?[^aeioudgkprt]h)es$/i' => '\\1', + '/^(.*?[^aeiou])ies$/i' => '\\1y', + '/^(.*?)s$/' => '\\1', + ); + foreach ($regexes as $key => $val) + { + $str = preg_replace($key, $val, $str, -1, $count); + if ($count) + { + return $str; + } + } + return $str; + } + }
\ No newline at end of file diff --git a/modules/orm/classes/orm/result.php b/modules/orm/classes/orm/result.php index 47757cf..cb0754c 100644 --- a/modules/orm/classes/orm/result.php +++ b/modules/orm/classes/orm/result.php @@ -12,211 +12,211 @@ class Result_ORM implements Iterator { - /** - * Name of the model that the rows belong to - * @var string - * @access private - */ - private $_model; - - /** - * Database result - * @var Result_Database - * @access private - */ - private $_dbresult; - - /** - * Rules for preloaded relationships - * @var array - * @access private - */ - private $_with = array(); - - /** - * Initialized an Result_ORM with which model to use and which result to - * iterate over - * - * @param string $model Model name - * @param Result_Database $dbresult Database result - * @param array $with Array of rules for preloaded relationships - * @return void - * @access public - */ - public function __construct($model, $dbresult, $with = array()) - { - $this->_model = $model; - $this->_dbresult = $dbresult; - foreach ($with as $path => $rel) - { - $this->_with[] = array( - 'path' => explode('.', $path), - 'path_count' => count(explode('.', $path)), - 'model' => $rel['model'], - 'columns' => $rel['model']->columns(), - ); - } - } - - /** - * Rewinds database cursor to the first row - * - * @return void - * @access public - */ - function rewind() - { - $this->_dbresult->rewind(); - } - - /** - * Gets an ORM Model of the current row - * - * @return ORM Model of the current row of the result set - * @access public - */ - function current() - { - $model = new $this->_model; - - if (!$this->_dbresult->valid()) - { - return $model; - } - - if (empty($this->_with)) - { - return $model->values((array) $this->_dbresult->current(), true); - } - - $data = (array) $this->_dbresult->current(); - - $model_data = array(); - foreach ($model->columns() as $column) - { - $model_data[$column] = array_shift($data); - } - $model->values($model_data, true); - - foreach ($this->_with as $rel) - { - $rel_data = array(); - foreach ($rel['columns'] as $column) - { - $rel_data[$column] = array_shift($data); - } - $rel['model']->values($rel_data, true); - - $owner = $model; - foreach ($rel['path'] as $key => $child) - { - if ($key == $rel['path_count'] - 1) - { - $owner->cached[$child] = $rel['model']; - } - else - { - $owner = $owner->cached[$child]; - } - } - } - - return $model; - } - - /** - * Gets current rows' index number - * - * @return int Row number - * @access public - */ - function key() - { - return $this->_dbresult->key(); - } - - /** - * Iterates to the next row in the result - * - * @return void - * @access public - */ - function next() - { - $this->_dbresult->next(); - } - - /** - * Checks if current row is valid. - * - * @return bool returns false if we reach the end of the result set. - * @access public - */ - function valid() - { - return $this->_dbresult->valid(); - } - - /** - * Returns an array of all rows as ORM objects if $rows is False, - * or just an array of result rows with each row being a standard object, - * this can be useful for functions like json_encode. - * - * @param boolean $rows Whether to return just rows and not ORM objects - * @return array Array of ORM objects or standard objects representing rows - * @access public - */ - public function as_array($rows = false) - { - if (!$rows) - { - $arr = array(); - foreach ($this as $row) - $arr[] = $row; - return $arr; - } - - if (empty($this->_with)) - { - return $this->_dbresult->as_array(); - } - - $arr = array(); - $model = new $this->_model; - foreach ($this->_dbresult as $data) - { - $row = new stdClass; - $data = (array) $data; - foreach ($model->columns() as $column) - { - $row->$column = array_shift($data); - } - - foreach ($this->_with as $rel) - { - $rel_data = new StdClass; - foreach ($rel['columns'] as $column) - { - $rel_data->$column = array_shift($data); - } - - $owner = &$row; - foreach ($rel['path'] as $key => $child) - { - if ($key == $rel['path_count'] - 1) - { - $owner->$child = $rel_data; - } - else - { - $owner = &$owner->$child; - } - } - } - $arr[] = $row; - } - - return $arr; - } + /** + * Name of the model that the rows belong to + * @var string + * @access private + */ + private $_model; + + /** + * Database result + * @var Result_Database + * @access private + */ + private $_dbresult; + + /** + * Rules for preloaded relationships + * @var array + * @access private + */ + private $_with = array(); + + /** + * Initialized an Result_ORM with which model to use and which result to + * iterate over + * + * @param string $model Model name + * @param Result_Database $dbresult Database result + * @param array $with Array of rules for preloaded relationships + * @return void + * @access public + */ + public function __construct($model, $dbresult, $with = array()) + { + $this->_model = $model; + $this->_dbresult = $dbresult; + foreach ($with as $path => $rel) + { + $this->_with[] = array( + 'path' => explode('.', $path), + 'path_count' => count(explode('.', $path)), + 'model' => $rel['model'], + 'columns' => $rel['model']->columns(), + ); + } + } + + /** + * Rewinds database cursor to the first row + * + * @return void + * @access public + */ + function rewind() + { + $this->_dbresult->rewind(); + } + + /** + * Gets an ORM Model of the current row + * + * @return ORM Model of the current row of the result set + * @access public + */ + function current() + { + $model = new $this->_model; + + if (!$this->_dbresult->valid()) + { + return $model; + } + + if (empty($this->_with)) + { + return $model->values((array) $this->_dbresult->current(), true); + } + + $data = (array) $this->_dbresult->current(); + + $model_data = array(); + foreach ($model->columns() as $column) + { + $model_data[$column] = array_shift($data); + } + $model->values($model_data, true); + + foreach ($this->_with as $rel) + { + $rel_data = array(); + foreach ($rel['columns'] as $column) + { + $rel_data[$column] = array_shift($data); + } + $rel['model']->values($rel_data, true); + + $owner = $model; + foreach ($rel['path'] as $key => $child) + { + if ($key == $rel['path_count'] - 1) + { + $owner->cached[$child] = $rel['model']; + } + else + { + $owner = $owner->cached[$child]; + } + } + } + + return $model; + } + + /** + * Gets current rows' index number + * + * @return int Row number + * @access public + */ + function key() + { + return $this->_dbresult->key(); + } + + /** + * Iterates to the next row in the result + * + * @return void + * @access public + */ + function next() + { + $this->_dbresult->next(); + } + + /** + * Checks if current row is valid. + * + * @return bool returns false if we reach the end of the result set. + * @access public + */ + function valid() + { + return $this->_dbresult->valid(); + } + + /** + * Returns an array of all rows as ORM objects if $rows is False, + * or just an array of result rows with each row being a standard object, + * this can be useful for functions like json_encode. + * + * @param boolean $rows Whether to return just rows and not ORM objects + * @return array Array of ORM objects or standard objects representing rows + * @access public + */ + public function as_array($rows = false) + { + if (!$rows) + { + $arr = array(); + foreach ($this as $row) + $arr[] = $row; + return $arr; + } + + if (empty($this->_with)) + { + return $this->_dbresult->as_array(); + } + + $arr = array(); + $model = new $this->_model; + foreach ($this->_dbresult as $data) + { + $row = new stdClass; + $data = (array) $data; + foreach ($model->columns() as $column) + { + $row->$column = array_shift($data); + } + + foreach ($this->_with as $rel) + { + $rel_data = new StdClass; + foreach ($rel['columns'] as $column) + { + $rel_data->$column = array_shift($data); + } + + $owner = &$row; + foreach ($rel['path'] as $key => $child) + { + if ($key == $rel['path_count'] - 1) + { + $owner->$child = $rel_data; + } + else + { + $owner = &$owner->$child; + } + } + } + $arr[] = $row; + } + + return $arr; + } }
\ No newline at end of file diff --git a/system/bootstrap.php b/system/bootstrap.php index 3e43dc5..f8ae016 100644 --- a/system/bootstrap.php +++ b/system/bootstrap.php @@ -4,56 +4,59 @@ * Bootstraps the system
* @package Core
*/
-class Bootstrap{
+class Bootstrap
+{
+
+ /**
+ * Autload function. Searches for the class file and includes it.
+ *
+ * @param unknown $class Class name
+ * @return void
+ * @access public
+ * @throws Exception If the class is not found
+ * @static
+ */
+ public static function autoload($class)
+ {
- /**
- * Autload function. Searches for the class file and includes it.
- *
- * @param unknown $class Class name
- * @return void
- * @access public
- * @throws Exception If the class is not found
- * @static
- */
- public static function autoload($class) {
-
$path = array_reverse(explode('_', strtolower($class)));
$file = array_pop($path);
- $path = 'classes/'.implode('/',$path);
+ $path = 'classes/'.implode('/', $path);
$file = Misc::find_file($path, $file);
-
- if($file)
+
+ if ($file)
include($file);
}
-
- /**
- * Runs the application
- *
- * @return void
- * @access public
- * @static
- */
- public static function run() {
+
+ /**
+ * Runs the application
+ *
+ * @return void
+ * @access public
+ * @static
+ */
+ public static function run()
+ {
/**
* Application folder
*/
- define('APPDIR', ROOTDIR.'application/');
+ define('APPDIR', ROOTDIR.'application/');
/**
* Modules folder
*/
- define('MODDIR', ROOTDIR.'modules/');
+ define('MODDIR', ROOTDIR.'modules/');
/**
* System folder
*/
- define('SYSDIR', ROOTDIR.'system/');
+ define('SYSDIR', ROOTDIR.'system/');
/**
* Web folder
*/
- define('WEBDIR', ROOTDIR.'web/');
+ define('WEBDIR', ROOTDIR.'web/');
/**
* Helper functions
*/
@@ -63,14 +66,15 @@ class Bootstrap{ * Configuration handler
*/
include('classes/config.php');
-
+
Config::load_group('core', 'application/config/core.php');
spl_autoload_register('Bootstrap::autoload');
Debug::init();
- if(Config::get('core.composer',false))
- include ROOTDIR.'vendor/autoload.php';
+ if (Config::get('core.composer', false))
+ include ROOTDIR.'vendor/autoload.php';
- foreach(Config::get('core.routes') as $route)
- Route::add($route[0],$route[1],$route[2]);
+ foreach (Config::get('core.routes') as $route)
+ Route::add($route[0], $route[1], $route[2]);
}
+
}
\ No newline at end of file diff --git a/system/classes/config.php b/system/classes/config.php index 27b7fa6..75152ac 100644 --- a/system/classes/config.php +++ b/system/classes/config.php @@ -6,61 +6,65 @@ * and later access them via the get() method.
* @package Core
*/
-class Config {
-
- /**
- * Array of configuration files and values loaded from them
- * @var array
- * @access protected
- * @static
- */
+class Config
+{
+
+ /**
+ * Array of configuration files and values loaded from them
+ * @var array
+ * @access protected
+ * @static
+ */
protected static $groups = array();
-
+
/**
- * Loads a group configuration file it has not been loaded before and
+ * Loads a group configuration file it has not been loaded before and
* returns its options. If the group doesn't exist creates an empty one
- *
- * @param string $name Name of the configuration group to load
- * @return array Array of options for this group
- * @access public
- * @static
- */
- public static function get_group($name) {
-
- if (!isset(Config::$groups[$name])) {
+ *
+ * @param string $name Name of the configuration group to load
+ * @return array Array of options for this group
+ * @access public
+ * @static
+ */
+ public static function get_group($name)
+ {
+
+ if (!isset(Config::$groups[$name]))
+ {
$file = Misc::find_file('config', $name);
-
+
if (!$file)
Config::$groups[$name] = array(
'file' => APPDIR.'config/'.$name.'.php',
'options' => array()
);
else
- Config::load_group($name,$file);
+ Config::load_group($name, $file);
}
-
+
return Config::$groups[$name]['options'];
}
-
+
/**
- * Loads group from file
- *
- * @param string $name Name to assign the loaded group
+ * Loads group from file
+ *
+ * @param string $name Name to assign the loaded group
* @param string $file File to load
- * @access public
- * @static
- */
- public static function load_group($name, $file) {
-
+ * @access public
+ * @static
+ */
+ public static function load_group($name, $file)
+ {
+
Config::$groups[$name] = array(
'file' => $file,
'options' => include($file)
);
}
-
- /**
- * Retrieves a configuration value. You can use a dot notation
+
+ /**
+ * Retrieves a configuration value. You can use a dot notation
* to access properties in group arrays. The first part of the key
* specifies the configuration file from which options should be loaded from
* <code>
@@ -68,80 +72,88 @@ class Config { * //from database.php configuration file
* Config::get('database.default.user');
* </code>
- *
- * @param string $key Configuration key to retrieve.
- * @param string $default Default value to return if the key is not found.
- * @return mixed Configuration value
- * @access public
- * @throws Exception If default value is not specified and the key is not found
- * @static
- */
- public static function get() {
+ *
+ * @param string $key Configuration key to retrieve.
+ * @param string $default Default value to return if the key is not found.
+ * @return mixed Configuration value
+ * @access public
+ * @throws Exception If default value is not specified and the key is not found
+ * @static
+ */
+ public static function get()
+ {
$p = func_get_args();
-
+
$keys = explode('.', $p[0]);
$group_name = array_shift($keys);
$group = Config::get_group($group_name);
if (empty($keys))
return $group;
-
- $total=count($keys);
- foreach($keys as $i => $key) {
- if (isset($group[$key])) {
+
+ $total = count($keys);
+ foreach ($keys as $i => $key)
+ {
+ if (isset($group[$key]))
+ {
if ($i == $total - 1)
return $group[$key];
- $group=&$group[$key];
- }else {
- if (array_key_exists (1,$p))
+ $group = &$group[$key];
+ }else
+ {
+ if (array_key_exists(1, $p))
return $p[1];
throw new Exception("Configuration not set for {$p[0]}.");
}
}
}
-
+
/**
- * Sets a configuration option.
- *
- * @param string $key Configuration key to set
+ * Sets a configuration option.
+ *
+ * @param string $key Configuration key to set
* @param string $value Value to set for this option
- * @access public
- * @static
- */
- public static function set($key,$value){
+ * @access public
+ * @static
+ */
+ public static function set($key, $value)
+ {
$keys = explode('.', $key);
$group_name = array_shift($keys);
$group = Config::get_group($group_name);
$subgroup = &$group;
-
- foreach($keys as $i => $key) {
-
- if ($i == count($keys) - 1) {
-
+
+ foreach ($keys as $i => $key)
+ {
+
+ if ($i == count($keys) - 1)
+ {
+
$subgroup[$key] = $value;
-
- } else {
-
- if(!isset($subgroup[$key])||!is_array($subgroup[$key]))
- $subgroup[$key]=array();
+ }
+ else
+ {
+
+ if (!isset($subgroup[$key]) || !is_array($subgroup[$key]))
+ $subgroup[$key] = array();
$subgroup = & $subgroup[$key];
-
}
}
-
+
Config::$groups[$group_name]['options'] = $group;
}
-
+
/**
- * Writes a configuration group back to the file it was loaded from
- *
- * @param string $group Name of the group to write
- * @access public
- * @static
- */
- public static function write($group){
+ * Writes a configuration group back to the file it was loaded from
+ *
+ * @param string $group Name of the group to write
+ * @access public
+ * @static
+ */
+ public static function write($group)
+ {
Config::get_group($group);
- $group=Config::$groups[$group];
- file_put_contents($group['file'],"<?php\r\nreturn ".var_export($group['options'],true).";");
+ $group = Config::$groups[$group];
+ file_put_contents($group['file'], "<?php\r\nreturn ".var_export($group['options'], true).";");
}
}
\ No newline at end of file diff --git a/system/classes/controller.php b/system/classes/controller.php index a1aff33..df0af7b 100644 --- a/system/classes/controller.php +++ b/system/classes/controller.php @@ -1,85 +1,93 @@ -<?php
+<?php
/**
* Base Controller class. Controllers contain the logic of your website,
* each action representing a reply to a particular request, e.g. a single page.
* @package Core
*/
-class Controller {
+class Controller
+{
- /**
- * Request for this controller. Holds all input data.
- * @var Request
- * @access public
- */
+ /**
+ * Request for this controller. Holds all input data.
+ * @var Request
+ * @access public
+ */
public $request;
- /**
- * Response for this controller. It will be updated with headers and
+ /**
+ * Response for this controller. It will be updated with headers and
* response body during controller execution
- * @var Response
- * @access public
- */
+ * @var Response
+ * @access public
+ */
public $response;
- /**
- * If set to False stops controller execution
- * @var boolean
- * @access public
- */
- public $execute=true;
+ /**
+ * If set to False stops controller execution
+ * @var boolean
+ * @access public
+ */
+ public $execute = true;
- /**
- * This method is called before the action.
- * You can override it if you need to,
+ /**
+ * This method is called before the action.
+ * You can override it if you need to,
* it doesn't do anything by default.
- *
- * @return void
- * @access public
- */
- public function before() {}
+ *
+ * @return void
+ * @access public
+ */
+ public function before()
+ {
- /**
- * This method is called after the action.
- * You can override it if you need to,
+ }
+
+ /**
+ * This method is called after the action.
+ * You can override it if you need to,
* it doesn't do anything by default.
- *
- * @return void
- * @access public
- */
- public function after() { }
+ *
+ * @return void
+ * @access public
+ */
+ public function after()
+ {
+
+ }
- /**
- * Creates new Controller
- *
- * @return void
- * @access public
- */
- public function __construct() {
- $this->response=new Response;
+ /**
+ * Creates new Controller
+ *
+ * @return void
+ * @access public
+ */
+ public function __construct()
+ {
+ $this->response = new Response;
}
- /**
- * Runs the appropriate action.
+ /**
+ * Runs the appropriate action.
* It will execute the before() method before the action
* and after() method after the action finishes.
- *
- * @param string $action Name of the action to execute.
- * @return void
- * @access public
- * @throws Exception If the specified action doesn't exist
- */
- public function run($action) {
+ *
+ * @param string $action Name of the action to execute.
+ * @return void
+ * @access public
+ * @throws Exception If the specified action doesn't exist
+ */
+ public function run($action)
+ {
$action = 'action_'.$action;
if (!method_exists($this, $action))
- throw new Exception("Method {$action} doesn't exist in ".get_class($this),404);
- $this->execute=true;
+ throw new Exception("Method {$action} doesn't exist in ".get_class($this), 404);
+ $this->execute = true;
$this->before();
- if($this->execute)
+ if ($this->execute)
$this->$action();
- if($this->execute)
+ if ($this->execute)
$this->after();
}
-
}
\ No newline at end of file diff --git a/system/classes/debug.php b/system/classes/debug.php index d1593e3..615ab3e 100644 --- a/system/classes/debug.php +++ b/system/classes/debug.php @@ -4,128 +4,140 @@ * Handles error reporting and debugging.
* @package Core
*/
-class Debug {
+class Debug
+{
- /**
- * An array of logged items
- * @var array
- * @access public
- * @static
- */
- public static $logged=array();
+ /**
+ * An array of logged items
+ * @var array
+ * @access public
+ * @static
+ */
+ public static $logged = array();
- /**
- * Displays the error page. If you have 'silent_errors' enabled in
+ /**
+ * Displays the error page. If you have 'silent_errors' enabled in
* core.php config file, a small message will be shown instead.
- *
- * @return void
- * @access public
- */
- public function render_error($exception) {
+ *
+ * @return void
+ * @access public
+ */
+ public function render_error($exception)
+ {
ob_end_clean();
-
- if($exception->getCode()==404){
- $status='404 Not Found';
- }else {
- $status='503 Service Temporarily Unavailable';
+
+ if ($exception->getCode() == 404)
+ {
+ $status = '404 Not Found';
+ }
+ else
+ {
+ $status = '503 Service Temporarily Unavailable';
}
-
- header($_SERVER["SERVER_PROTOCOL"].' '.$status);
+
+ header($_SERVER["SERVER_PROTOCOL"].' '.$status);
header("Status: {$status}");
-
- if (Config::get('core.errors.silent', false)) {
+
+ if (Config::get('core.errors.silent', false))
+ {
echo $status;
return;
}
-
+
$view = View::get('debug');
$view->exception = $exception;
$view->log = Debug::$logged;
echo $view->render();
}
- /**
- * Catches errors and exceptions and sends them
+ /**
+ * Catches errors and exceptions and sends them
* to the configured handler if one is present,
* otherwise render_error() will be called.
- *
- * @param Exception $exception Caught exception
- * @return void
- * @access public
- * @static
- */
- public static function onError($exception) {
+ *
+ * @param Exception $exception Caught exception
+ * @return void
+ * @access public
+ * @static
+ */
+ public static function onError($exception)
+ {
set_exception_handler(array('Debug', 'internalException'));
- set_error_handler ( array('Debug', 'internalError'), E_ALL);
+ set_error_handler(array('Debug', 'internalError'), E_ALL);
$handler = Config::get('core.errors.handler', 'Debug::render_error');
- call_user_func($handler,$exception);
+ call_user_func($handler, $exception);
}
- /**
- * Converts PHP Errors to Exceptions
- *
- * @param string $errno Error number
- * @param string $errstr Error message
- * @param string $errfile File in which the error occurred
- * @param string $errline Line at which the error occurred
- * @return void
- * @access public
- * @throws ErrorException Throws converted exception to be immediately caught
- * @static
- */
- public static function errorHandler($errno, $errstr, $errfile, $errline) {
+ /**
+ * Converts PHP Errors to Exceptions
+ *
+ * @param string $errno Error number
+ * @param string $errstr Error message
+ * @param string $errfile File in which the error occurred
+ * @param string $errline Line at which the error occurred
+ * @return void
+ * @access public
+ * @throws ErrorException Throws converted exception to be immediately caught
+ * @static
+ */
+ public static function errorHandler($errno, $errstr, $errfile, $errline)
+ {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
- /**
- * Handles exceptions that occurred while inside the error handler. Prevents recursion.
- *
- * @param Exception $exception Caught exception
- * @return void
- * @access public
- * @static
- */
- public static function internalException($exception) {
+ /**
+ * Handles exceptions that occurred while inside the error handler. Prevents recursion.
+ *
+ * @param Exception $exception Caught exception
+ * @return void
+ * @access public
+ * @static
+ */
+ public static function internalException($exception)
+ {
echo $exception->getMessage().' in '.$exception->getFile().' on line '.$exception->getLine();
}
- /**
- * Handles errors that occurred while inside the error handler. Prevents recursion.
- *
- * @param string $errno Error number
- * @param string $errstr Error message
- * @param string $errfile File in which the error occurred
- * @param string $errline Line at which the error occurred
- * @return void
- * @access public
- * @static
- */
- public static function internalError($errno, $errstr, $errfile, $errline) {
+ /**
+ * Handles errors that occurred while inside the error handler. Prevents recursion.
+ *
+ * @param string $errno Error number
+ * @param string $errstr Error message
+ * @param string $errfile File in which the error occurred
+ * @param string $errline Line at which the error occurred
+ * @return void
+ * @access public
+ * @static
+ */
+ public static function internalError($errno, $errstr, $errfile, $errline)
+ {
echo $errstr.' in '.$errfile.' on line '.$errline;
}
- /**
- * Initializes the error handler
- *
- * @return void
- * @access public
- * @static
- */
- public static function init(){
+ /**
+ * Initializes the error handler
+ *
+ * @return void
+ * @access public
+ * @static
+ */
+ public static function init()
+ {
set_exception_handler(array('Debug', 'onError'));
- set_error_handler ( array('Debug', 'errorHandler'), E_ALL);
+ set_error_handler(array('Debug', 'errorHandler'), E_ALL);
}
- /**
- * Adds an item to the log.
- *
- * @param mixed $val Item to be logged
- * @return void
- * @access public
- * @static
- */
- public static function log($val){
- array_unshift(Debug::$logged,$val);
+ /**
+ * Adds an item to the log.
+ *
+ * @param mixed $val Item to be logged
+ * @return void
+ * @access public
+ * @static
+ */
+ public static function log($val)
+ {
+ array_unshift(Debug::$logged, $val);
}
-
+
}
\ No newline at end of file diff --git a/system/classes/misc.php b/system/classes/misc.php index 65f2ec6..b14e9eb 100644 --- a/system/classes/misc.php +++ b/system/classes/misc.php @@ -6,70 +6,72 @@ */
class Misc
{
- /**
- * Retrieve value from array by key, with default value support.
- *
- * @param array $array Input array
- * @param string $key Key to retrieve from the array
- * @param mixed $default Default value to return if the key is not found
- * @return mixed An array value if it was found or default value if it is not
- * @access public
- * @static
- */
- public static function arr($array,$key,$default=null)
- {
- if (isset($array[$key]))
- {
- return $array[$key];
- }
- return $default;
- }
- /**
- * Finds full path to a specified file
- * It will search in the /application folder first, then in all enabled modules
- * and then the /system folder
- *
- * @param string $subfolder Subfolder to search in e.g. 'classes' or 'views'
- * @param string $name Name of the file without extension
- * @param string $extension File extension
- * @param boolean $return_all If 'true' returns all mathced files as array,
- * otherwise returns the first file found
- * @return mixed Full path to the file or False if it is not found
- * @access public
- * @static
- */
- public static function find_file($subfolder, $name, $extension = 'php', $return_all = false )
- {
- $folders = array(APPDIR);
+ /**
+ * Retrieve value from array by key, with default value support.
+ *
+ * @param array $array Input array
+ * @param string $key Key to retrieve from the array
+ * @param mixed $default Default value to return if the key is not found
+ * @return mixed An array value if it was found or default value if it is not
+ * @access public
+ * @static
+ */
+ public static function arr($array, $key, $default = null)
+ {
+ if (isset($array[$key]))
+ {
+ return $array[$key];
+ }
+ return $default;
+ }
- foreach(Config::get('core.modules', array()) as $module)
- {
- $folders[] = MODDIR.$module.'/';
- }
- $folders[] = SYSDIR;
+ /**
+ * Finds full path to a specified file
+ * It will search in the /application folder first, then in all enabled modules
+ * and then the /system folder
+ *
+ * @param string $subfolder Subfolder to search in e.g. 'classes' or 'views'
+ * @param string $name Name of the file without extension
+ * @param string $extension File extension
+ * @param boolean $return_all If 'true' returns all mathced files as array,
+ * otherwise returns the first file found
+ * @return mixed Full path to the file or False if it is not found
+ * @access public
+ * @static
+ */
+ public static function find_file($subfolder, $name, $extension = 'php', $return_all = false)
+ {
+ $folders = array(APPDIR);
- $fname = $name.'.'.$extension;
- $found_files = array();
+ foreach (Config::get('core.modules', array()) as $module)
+ {
+ $folders[] = MODDIR.$module.'/';
+ }
+ $folders[] = SYSDIR;
- foreach ($folders as $folder)
- {
- $file = $folder.$subfolder.'/'.$fname;
- if (file_exists($file))
- {
- if (!$return_all)
- {
- return($file);
- }
- $found_files[] = $file;
- }
- }
+ $fname = $name.'.'.$extension;
+ $found_files = array();
- if (!empty($found_files))
- {
- return $found_files;
- }
+ foreach ($folders as $folder)
+ {
+ $file = $folder.$subfolder.'/'.$fname;
+ if (file_exists($file))
+ {
+ if (!$return_all)
+ {
+ return($file);
+ }
+ $found_files[] = $file;
+ }
+ }
+
+ if (!empty($found_files))
+ {
+ return $found_files;
+ }
+
+ return false;
+ }
- return false;
- }
}
diff --git a/system/classes/request.php b/system/classes/request.php index 4105901..1b95b42 100644 --- a/system/classes/request.php +++ b/system/classes/request.php @@ -4,142 +4,150 @@ * Handles client request. * @package Core */ -class Request { +class Request +{ - /** - * Stores POST data - * @var array - * @access private - */ + /** + * Stores POST data + * @var array + * @access private + */ private $_post; - /** - * Stores GET data - * @var array - * @access private - */ + /** + * Stores GET data + * @var array + * @access private + */ private $_get; - /** - * Current Route - * @var Route - * @access public - */ + /** + * Current Route + * @var Route + * @access public + */ public $route; - /** - * Request method - * @var string - * @access public - */ + /** + * Request method + * @var string + * @access public + */ public $method; - + /** - * Creates a new request - * - * @param Route $route Route for this request - * @param string $method HTTP method for the request (e.g. GET, POST) + * Creates a new request + * + * @param Route $route Route for this request + * @param string $method HTTP method for the request (e.g. GET, POST) * @param array $post Array of POST data * @param array $get Array of GET data * @param array $server Array of SERVER data - * @return Request Initialized request + * @return Request Initialized request * - * @access public - */ - public function __construct($route, $method="GET", $post = array(), $get = array(), $server = array()) { - $this->route = $route; - $this->method = $method; - $this->_post = $post; - $this->_get = $get; + * @access public + */ + public function __construct($route, $method = "GET", $post = array(), $get = array(), $server = array()) + { + $this->route = $route; + $this->method = $method; + $this->_post = $post; + $this->_get = $get; $this->_server = $server; } - - /** - * Retrieves a GET parameter - * - * @param string $key Parameter key - * @param mixed $default Default value - * @return mixed Returns a value if a key is specified, + + /** + * Retrieves a GET parameter + * + * @param string $key Parameter key + * @param mixed $default Default value + * @return mixed Returns a value if a key is specified, * or an array of GET parameters if it isn't. - * @access public - */ - public function get($key = null, $default = null) { + * @access public + */ + public function get($key = null, $default = null) + { if ($key == null) return $this->_get; - return Misc::arr($this->_get,$key,$default); + return Misc::arr($this->_get, $key, $default); } - /** - * Retrieves a POST parameter - * - * @param string $key Parameter key - * @param mixed $default Default value - * @return mixed Returns a value if a key is specified, + /** + * Retrieves a POST parameter + * + * @param string $key Parameter key + * @param mixed $default Default value + * @return mixed Returns a value if a key is specified, * or an array of POST parameters if it isn't. - * @access public - */ - public function post($key = null, $default = null) { + * @access public + */ + public function post($key = null, $default = null) + { if ($key == null) return $this->_post; - return Misc::arr($this->_post,$key,$default); + return Misc::arr($this->_post, $key, $default); } - + /** - * Retrieves a SERVER parameter - * - * @param string $key Parameter key - * @param mixed $default Default value - * @return mixed Returns a value if a key is specified, + * Retrieves a SERVER parameter + * + * @param string $key Parameter key + * @param mixed $default Default value + * @return mixed Returns a value if a key is specified, * or an array of SERVER parameters if it isn't. - * @access public - */ - public function server($key = null, $default = null) { + * @access public + */ + public function server($key = null, $default = null) + { if ($key == null) return $this->_server; - return Misc::arr($this->_server,$key,$default); + return Misc::arr($this->_server, $key, $default); } - - /** - * Retrieves a Route parameter - * - * @param string $key Parameter key - * @param mixed $default Default value - * @return mixed Returns a value if a key is specified, + + /** + * Retrieves a Route parameter + * + * @param string $key Parameter key + * @param mixed $default Default value + * @return mixed Returns a value if a key is specified, * or an array of Route parameters if it isn't. - * @access public - */ - public function param($key = null, $default = null) { + * @access public + */ + public function param($key = null, $default = null) + { if ($key == null) return $this->route->params; - return Misc::arr($this->route->params,$key,$default); + return Misc::arr($this->route->params, $key, $default); } - /** - * Initializes the routed Controller and executes specified action - * - * @return Response A Response object with the body and headers set - * @access public - */ - public function execute() { + /** + * Initializes the routed Controller and executes specified action + * + * @return Response A Response object with the body and headers set + * @access public + */ + public function execute() + { $controller = $this->param('controller').'_Controller'; if (!class_exists($controller)) - throw new Exception("Class {$controller} doesn't exist",404); + throw new Exception("Class {$controller} doesn't exist", 404); $controller = new $controller; $controller->request = $this; $controller->run($this->param('action')); return $controller->response; } - /** - * Creates a Request representing current HTTP request. - * - * @return Request Request - * @access public - * @static - */ - public static function create() { + /** + * Creates a Request representing current HTTP request. + * + * @return Request Request + * @access public + * @static + */ + public static function create() + { $uri = $_SERVER['REQUEST_URI']; - $basepath=Config::get('core.basepath','/'); + $basepath = Config::get('core.basepath', '/'); $uri = preg_replace("#^{$basepath}(?:index\.php/)?#i", '/', $uri); $url_parts = parse_url($uri); return new Request(Route::match($url_parts['path']), $_SERVER['REQUEST_METHOD'], $_POST, $_GET, $_SERVER); diff --git a/system/classes/response.php b/system/classes/response.php index b1b38cc..a4b737e 100644 --- a/system/classes/response.php +++ b/system/classes/response.php @@ -4,67 +4,72 @@ * Handles the response that is sent back to the client.
* @package Core
*/
-class Response {
+class Response
+{
- /**
- * Headers for the response
- * @var array
- * @access public
- */
+ /**
+ * Headers for the response
+ * @var array
+ * @access public
+ */
public $headers = array(
'Content-Type: text/html; charset=utf-8'
);
- /**
- * Response body
- * @var string
- * @access public
- */
+ /**
+ * Response body
+ * @var string
+ * @access public
+ */
public $body;
- /**
- * Add header to the response
- *
- * @param string $header Header content
- * @return void
- * @access public
- */
- public function add_header($header){
- $this->headers[]=$header;
+ /**
+ * Add header to the response
+ *
+ * @param string $header Header content
+ * @return void
+ * @access public
+ */
+ public function add_header($header)
+ {
+ $this->headers[] = $header;
}
- /**
- * Add redirection header
- *
- * @param string $url URL to redirect the client to
- * @return void
- * @access public
- */
- public function redirect($url){
+ /**
+ * Add redirection header
+ *
+ * @param string $url URL to redirect the client to
+ * @return void
+ * @access public
+ */
+ public function redirect($url)
+ {
$this->add_header("Location: $url");
}
- /**
- * Sends headers to the client
- *
- * @return Response Same Response object, for method chaining
- * @access public
- */
- public function send_headers(){
- foreach($this->headers as $header)
+ /**
+ * Sends headers to the client
+ *
+ * @return Response Same Response object, for method chaining
+ * @access public
+ */
+ public function send_headers()
+ {
+ foreach ($this->headers as $header)
header($header);
return $this;
}
- /**
- * Send response body to the client
- *
- * @return object Same Response object, for method chaining
- * @access public
- */
- public function send_body(){
+ /**
+ * Send response body to the client
+ *
+ * @return object Same Response object, for method chaining
+ * @access public
+ */
+ public function send_body()
+ {
echo $this->body;
return $this;
}
-
+
}
\ No newline at end of file diff --git a/system/classes/route.php b/system/classes/route.php index 244a0c7..04b9a6c 100644 --- a/system/classes/route.php +++ b/system/classes/route.php @@ -4,198 +4,210 @@ * Routing class to extract and parse request parameters from the URL. * @package Core */ -class Route { +class Route +{ - /** - * Name of the route. - * @var string - * @access public - */ + /** + * Name of the route. + * @var string + * @access public + */ public $name; - + /** - * Rule for this route. - * @var mixed - * @access public - */ + * Rule for this route. + * @var mixed + * @access public + */ public $rule; - + /** - * Default parameters for this route. - * @var mixed - * @access public - */ + * Default parameters for this route. + * @var mixed + * @access public + */ public $defaults; - - /** - * Extracted parameters - * @var array - * @access public - */ - public $params=array(); - - /** - * Associative array of route rules. - * @var array - * @access private - * @static - */ - private static $rules=array(); - + + /** + * Extracted parameters + * @var array + * @access public + */ + public $params = array(); + + /** + * Associative array of route rules. + * @var array + * @access private + * @static + */ + private static $rules = array(); + /** - * Associative array of route instances. - * @var array - * @access private - * @static - */ + * Associative array of route instances. + * @var array + * @access private + * @static + */ private static $routes = array(); - + /** - * Constructs a route. - * - * @param string $name Name of the route + * Constructs a route. + * + * @param string $name Name of the route * @param mixed $rule Rule for this route * @param array $defaults Default parameters for the route * @return Route Initialized Route * @access protected - */ - protected function __construct($name, $rule, $defaults) { + */ + protected function __construct($name, $rule, $defaults) + { $this->name = $name; $this->rule = $rule; $this->defaults = $defaults; } - + /** - * Generates a url for a route - * - * @param array $params Parameters to substitute in the route + * Generates a url for a route + * + * @param array $params Parameters to substitute in the route * @param bool $absolute Whether to return an absolute url * @param string $protocol Protocol to use for absolute url * @return string Generated url * @access public - */ - public function url($params = array(), $absolute = false, $protocol = 'http') { + */ + public function url($params = array(), $absolute = false, $protocol = 'http') + { if (is_callable($this->rule)) throw new Exception("The rule for '{$this->name}' route is a function and cannot be reversed"); - - $url = is_array($this->rule)?$this->rule[0]:$this->rule; - + + $url = is_array($this->rule) ? $this->rule[0] : $this->rule; + $replace = array(); $params = array_merge($this->defaults, $params); - foreach($params as $key => $value) + foreach ($params as $key => $value) $replace["<{$key}>"] = $value; $url = str_replace(array_keys($replace), array_values($replace), $url); - + $count = 1; - $chars='[^\(\)]*?'; - while($count>0) + $chars = '[^\(\)]*?'; + while ($count > 0) $url = preg_replace("#\({$chars}<{$chars}>{$chars}\)#", '', $url, -1, $count); - + $url = str_replace(array('(', ')'), '', $url); - + if ($absolute) $url = $protocol.'://'.$_SERVER['HTTP_HOST'].$url; - + return $url; } - - /** - * Ads a route - * - * @param string $name Name of the route. Routes with the same name will override one another. - * @param mixed $rule Either an expression to match URI against or a function that will + + /** + * Ads a route + * + * @param string $name Name of the route. Routes with the same name will override one another. + * @param mixed $rule Either an expression to match URI against or a function that will * be passed the URI and must return either an associative array of * extracted parameters (if it matches) or False. - * @param array $defaults An associated array of default values. - * @return void - * @access public - * @static - */ - public static function add($name, $rule, $defaults = array()) { - Route::$rules[$name]=array( - 'rule'=>$rule, - 'defaults'=>$defaults + * @param array $defaults An associated array of default values. + * @return void + * @access public + * @static + */ + public static function add($name, $rule, $defaults = array()) + { + Route::$rules[$name] = array( + 'rule' => $rule, + 'defaults' => $defaults ); } - /** - * Gets route by name - * - * @param string $name Route name - * @return Route - * @access public + /** + * Gets route by name + * + * @param string $name Route name + * @return Route + * @access public * @throws Exception If specified route doesn't exist - * @static - */ - public static function get($name) { + * @static + */ + public static function get($name) + { if (!isset(Route::$rules[$name])) throw new Exception("Route {$name} not found."); - - if (!isset(Route::$routes[$name])) { + + if (!isset(Route::$routes[$name])) + { $rules = Route::$rules[$name]; Route::$routes[$name] = new static($name, $rules['rule'], $rules['defaults']); } - + return Route::$routes[$name]; } - /** - * Matches the URI against available routes to find the correct one. - * - * @param string $uri Request URI - * @return Route - * @access public - * @throws Exception If no route matches the URI - * @throws Exception If route matched but no Controller was defined for it - * @throws Exception If route matched but no action was defined for it - * @static - */ - public static function match($uri) { + /** + * Matches the URI against available routes to find the correct one. + * + * @param string $uri Request URI + * @return Route + * @access public + * @throws Exception If no route matches the URI + * @throws Exception If route matched but no Controller was defined for it + * @throws Exception If route matched but no action was defined for it + * @static + */ + public static function match($uri) + { $matched = false; - foreach(Route::$rules as $name=>$rule) { - $rule=$rule['rule']; - if (is_callable($rule)) { - if (($data = $rule($uri)) !== FALSE) { + foreach (Route::$rules as $name => $rule) + { + $rule = $rule['rule']; + if (is_callable($rule)) + { + if (($data = $rule($uri)) !== FALSE) + { $matched = $name; break; } - }else { - $pattern = is_array($rule)?$rule[0]:$rule; + } + else + { + $pattern = is_array($rule) ? $rule[0] : $rule; $pattern = str_replace(')', ')?', $pattern); - - $pattern=preg_replace_callback('/<.*?>/', - function($str) use ($rule){ - $str=$str[0]; - $regexp='[a-zA-Z0-9\-\._]+'; - if(is_array($rule)) - $regexp=Misc::arr($rule[1],str_replace(array('<','>'),'',$str),$regexp); + + $pattern = preg_replace_callback('/<.*?>/', function($str) use ($rule) { + $str = $str[0]; + $regexp = '[a-zA-Z0-9\-\._]+'; + if (is_array($rule)) + $regexp = Misc::arr($rule[1], str_replace(array('<', '>'), '', $str), $regexp); return '(?P'.$str.$regexp.')'; - },$pattern); - - preg_match('#^'.$pattern.'/?$#',$uri,$match); - if(!empty($match[0])){ - $matched=$name; - $data=array(); - foreach($match as $k=>$v) - if(!is_numeric($k)) - $data[$k]=$v; + }, $pattern); + + preg_match('#^'.$pattern.'/?$#', $uri, $match); + if (!empty($match[0])) + { + $matched = $name; + $data = array(); + foreach ($match as $k => $v) + if (!is_numeric($k)) + $data[$k] = $v; break; } } } - if($matched==false) - throw new Exception('No route matched your request',404); - $rule=Route::$rules[$matched]; - - $params=array_merge($rule['defaults'],$data); - - if(!isset($params['controller'])) - throw new Exception("Route {$matched} matched, but no controller was defined for this route",404); - if(!isset($params['action'])) - throw new Exception("Route {$matched} matched with controller {$params['controller']}, but no action was defined for this route",404); - - $route=Route::get($matched); - $route->params=$params; + if ($matched == false) + throw new Exception('No route matched your request', 404); + $rule = Route::$rules[$matched]; + + $params = array_merge($rule['defaults'], $data); + + if (!isset($params['controller'])) + throw new Exception("Route {$matched} matched, but no controller was defined for this route", 404); + if (!isset($params['action'])) + throw new Exception("Route {$matched} matched with controller {$params['controller']}, but no action was defined for this route", 404); + + $route = Route::get($matched); + $route->params = $params; return $route; } diff --git a/system/classes/session.php b/system/classes/session.php index 3749396..f08b2b7 100644 --- a/system/classes/session.php +++ b/system/classes/session.php @@ -4,100 +4,112 @@ * Simple class for accessing session data * @package Core */ -class Session{ +class Session +{ - /** - * Makes sure the session is initialized - * - * @return void - * @access private - * @static - */ - private static function check(){ - if(!session_id()){ + /** + * Makes sure the session is initialized + * + * @return void + * @access private + * @static + */ + private static function check() + { + if (!session_id()) + { session_start(); } } - /** - * Gets a session variable - * - * @param string $key Variable name - * @param mixed $default Default value - * @return mixed Session value - * @access public - * @static - */ - public static function get($key, $default = null) { + /** + * Gets a session variable + * + * @param string $key Variable name + * @param mixed $default Default value + * @return mixed Session value + * @access public + * @static + */ + public static function get($key, $default = null) + { Session::check(); - return Misc::arr($_SESSION,$key,$default); + return Misc::arr($_SESSION, $key, $default); } - /** - * Sets a session variable - * - * @param string $key Variable name - * @param mixed $val Variable value - * @return void - * @access public - * @static - */ - public static function set($key, $val) { + /** + * Sets a session variable + * + * @param string $key Variable name + * @param mixed $val Variable value + * @return void + * @access public + * @static + */ + public static function set($key, $val) + { Session::check(); - $_SESSION[$key]=$val; + $_SESSION[$key] = $val; } - + /** - * Removes a session variable - * - * @param string $key Variable name - * @return void - * @access public - * @static - */ - public static function remove($key) { + * Removes a session variable + * + * @param string $key Variable name + * @return void + * @access public + * @static + */ + public static function remove($key) + { Session::check(); - + if (!isset($_SESSION[$key])) return; - + $var = $_SESSION[$key]; unset($_SESSION[$key], $var); } - + /** - * Resets the session - * - * @return void - * @access public - * @static - */ - public static function reset() { + * Resets the session + * + * @return void + * @access public + * @static + */ + public static function reset() + { Session::check(); - $_SESSION=array(); + $_SESSION = array(); } - + /** - * Gets ot sets flash messages. + * Gets ot sets flash messages. * If the value parameter is passed the message is set, otherwise it is retrieved. * After the message is retrieved for the first time it is removed. - * + * * @param $key The name of the flash message * @param $val Flash message content - * @return mixed - * @access public - * @static - */ - public static function flash($key,$val = null) { + * @return mixed + * @access public + * @static + */ + public static function flash($key, $val = null) + { Session::check(); - $key="flash_{$key}"; - if($val != null) { - Session::set($key,$val); - }else { + $key = "flash_{$key}"; + if ($val != null) + { + Session::set($key, $val); + } + else + { $val = Session::get($key); Session::remove($key); } - + return $val; } + }
\ No newline at end of file diff --git a/system/classes/view.php b/system/classes/view.php index 7c319d0..49e9661 100644 --- a/system/classes/view.php +++ b/system/classes/view.php @@ -4,82 +4,86 @@ * Manages passing variables to templates and rendering them * @package Core */ -class View{ +class View +{ - /** - * Full path to template file - * @var string - * @access private - */ + /** + * Full path to template file + * @var string + * @access private + */ protected $path; - /** - * The name of the view. - * @var string - * @access public - */ + /** + * The name of the view. + * @var string + * @access public + */ public $name; - /** - * Stores all the variables passed to the view - * @var array - * @access protected - */ + /** + * Stores all the variables passed to the view + * @var array + * @access protected + */ protected $_data = array(); /** - * File extension of the templates - * @var string - * @access protected - */ + * File extension of the templates + * @var string + * @access protected + */ protected $_extension = 'php'; - + /** - * Constructs the view - * - * @param string $name The name of the template to use - * @return View - * @throws Exception If specified template is not found - * @access protected - */ - protected function __construct($name){ + * Constructs the view + * + * @param string $name The name of the template to use + * @return View + * @throws Exception If specified template is not found + * @access protected + */ + protected function __construct($name) + { $this->name = $name; - $file = Misc::find_file('views', $name,$this->_extension); - + $file = Misc::find_file('views', $name, $this->_extension); + if ($file == false) throw new Exception("View {$name} not found."); - - $this->path=$file; + + $this->path = $file; } - - /** - * Manages storing the data passed to the view as properties - * - * @param string $key Property name - * @param string $val Property value - * @return void - * @access public - */ - public function __set($key, $val) { - $this->_data[$key]=$val; + + /** + * Manages storing the data passed to the view as properties + * + * @param string $key Property name + * @param string $val Property value + * @return void + * @access public + */ + public function __set($key, $val) + { + $this->_data[$key] = $val; } - /** - * Manages accessing passed data as properties - * - * @param string $key Property name - * @return mixed Property value - * @access public - * @throws Exception If the property is not found - */ - public function __get($key){ + /** + * Manages accessing passed data as properties + * + * @param string $key Property name + * @return mixed Property value + * @access public + * @throws Exception If the property is not found + */ + public function __get($key) + { if (isset($this->_data[$key])) return $this->_data[$key]; - throw new Exception("Value {$key} not set for view {$this->name}"); + throw new Exception("Value {$key} not set for view {$this->name}"); } - /** - * Renders the template, all dynamically set properties + /** + * Renders the template, all dynamically set properties * will be available inside the view file as variables. * Example: * <code> @@ -87,28 +91,31 @@ class View{ * $view->title = "Page title"; * echo $view->render(); * </code> - * - * @return string Rendered template - * @access public - */ - public function render() { + * + * @return string Rendered template + * @access public + */ + public function render() + { extract($this->_data); ob_start(); include($this->path); return ob_get_clean(); } - /** - * Shorthand for constructing a view. + /** + * Shorthand for constructing a view. * - * @param string $name The name of the template to use - * @return View - * @throws Exception If specified template is not found - * @static - * @access public - */ - public static function get($name){ + * @param string $name The name of the template to use + * @return View + * @throws Exception If specified template is not found + * @static + * @access public + */ + public static function get($name) + { $class = get_called_class(); return new $class($name); } + }
\ No newline at end of file diff --git a/system/views/debug.php b/system/views/debug.php index 0d78601..374abb5 100644 --- a/system/views/debug.php +++ b/system/views/debug.php @@ -30,7 +30,7 @@ margin:10px; } .code{ - + padding:10px; } .highlight{ @@ -55,7 +55,7 @@ border-bottom: 1px solid black; } .log.odd{ - + } pre{ margin:0px; @@ -66,61 +66,63 @@ </style> </head> <body> - <?php - $rawblocks=array_merge(array(array( - 'file'=>$exception->getFile(), - 'line'=>$exception->getLine() + <?php + $rawblocks = array_merge(array(array( + 'file' => $exception->getFile(), + 'line' => $exception->getLine() )), $exception->getTrace()); - $blocks = array(); - foreach($rawblocks as $block){ - if(!isset($block['file'])) + $blocks = array(); + foreach ($rawblocks as $block) + { + if (!isset($block['file'])) + continue; + //avoid duplicates + if (count($blocks) > 0) + { + $last = $blocks[count($blocks) - 1]; + if ($block['file'] == $last['file'] && $block['line'] == $last['line']) continue; - //avoid duplicates - if(count($blocks)>0){ - $last=$blocks[count($blocks)-1]; - if($block['file']==$last['file'] && $block['line']==$last['line']) - continue; - } - $blocks[]=$block; } - - + $blocks[] = $block; + } ?> <div id="content"> - <div id="exception"><?php echo str_replace("\n",'<br/>',$exception->getMessage()); ?></div> + <div id="exception"><?php echo str_replace("\n", '<br/>', $exception->getMessage()); ?></div> <div id="blocks"> - <?php foreach($blocks as $bkey=>$block): ?> - <div class="block <?php echo (!empty($log)&&$bkey==0)?'thick':''; ?>"> - <div class="file"><?php echo $block['file'];?></div> + <?php foreach ($blocks as $bkey => $block): ?> + <div class="block <?php echo (!empty($log) && $bkey == 0) ? 'thick' : ''; ?>"> + <div class="file"><?php echo $block['file']; ?></div> <div class="code"> - <?php - $line=$block['line']-1; - $code = explode("\n", file_get_contents($block['file'])); - $start = $line - 3; - if ($start < 0) $start = 0; - $end = $line + 3; - if($end>=count($code)) $end=count($code)-1; - $code=array_slice($code,$start,$end-$start,true); + <?php + $line = $block['line'] - 1; + $code = explode("\n", file_get_contents($block['file'])); + $start = $line - 3; + if ($start < 0) + $start = 0; + $end = $line + 3; + if ($end >= count($code)) + $end = count($code) - 1; + $code = array_slice($code, $start, $end - $start, true); ?> - - <?php foreach($code as $n=>$text):?> - <pre class="line <?php echo $n==$line?'highlight':''; ?>"><?php echo ($n+1).' '.htmlspecialchars($text); ?></pre> - <?php endforeach;?> + + <?php foreach ($code as $n => $text): ?> + <pre class="line <?php echo $n == $line ? 'highlight' : ''; ?>"><?php echo ($n + 1).' '.htmlspecialchars($text); ?></pre> + <?php endforeach; ?> </div> </div> - <?php if($bkey==0&&!empty($log)):?> + <?php if ($bkey == 0 && !empty($log)): ?> <div id="debug"> <div id="log">Logged values:</div> - <?php foreach($log as $key=>$val):?> - <div class="log <?php echo $key%2?'odd':''; ?>"> - <pre><?php var_export($val);?></pre> + <?php foreach ($log as $key => $val): ?> + <div class="log <?php echo $key % 2 ? 'odd' : ''; ?>"> + <pre><?php var_export($val); ?></pre> </div> - <?php endforeach;?> + <?php endforeach; ?> </div> <div id="log">Call stack:</div> - <?php endif;?> - <?php endforeach;?> + <?php endif; ?> +<?php endforeach; ?> </div> </div> </body> -</html>
\ No newline at end of file +</html>
\ No newline at end of file diff --git a/tests/modules/database/database/expressionTest.php b/tests/modules/database/database/expressionTest.php index edb9d50..66164b2 100644 --- a/tests/modules/database/database/expressionTest.php +++ b/tests/modules/database/database/expressionTest.php @@ -1,37 +1,42 @@ <?php + require_once('/../../../../modules/database/classes/database/expression.php'); + /** * Generated by PHPUnit_SkeletonGenerator on 2013-02-07 at 10:14:10. */ class Expression_DatabaseTest extends PHPUnit_Framework_TestCase { - /** - * @var Expression_Database - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - $this->object = new Expression_Database('test'); - } - + /** - * @covers Expression_Database::__construct - */ - public function testConstruct() - { - $this->assertEquals('test',$this->object->value); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } + * @var Expression_Database + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + $this->object = new Expression_Database('test'); + } + + /** + * @covers Expression_Database::__construct + */ + public function testConstruct() + { + $this->assertEquals('test', $this->object->value); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + + } + } diff --git a/tests/modules/database/driver/mysql/queryTest.php b/tests/modules/database/driver/mysql/queryTest.php index a326434..3534048 100644 --- a/tests/modules/database/driver/mysql/queryTest.php +++ b/tests/modules/database/driver/mysql/queryTest.php @@ -1,69 +1,73 @@ <?php + require_once('/../../../../../modules/database/classes/database/query.php'); require_once('/../../../../../modules/database/classes/driver/pdo/query.php'); require_once('/../../../../../modules/database/classes/driver/mysql/query.php'); require_once('/../../../../../modules/database/classes/database/expression.php'); + /** * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-02-01 at 06:23:13. */ class Query_Mysql_DriverTest extends PHPUnit_Framework_TestCase { - /** - * @var Query_Mysql_Driver - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - $stub=(object)array('db_type'=>'mysql'); - $this->object = new Query_Mysql_Driver($stub,'select'); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - - /** - * @covers Query_Mysql_Driver::escape_field - * @todo Implement testEscape_field(). - */ - public function testEscape_field() - { + + /** + * @var Query_Mysql_Driver + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + $stub = (object) array('db_type' => 'mysql'); + $this->object = new Query_Mysql_Driver($stub, 'select'); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + + } + + /** + * @covers Query_Mysql_Driver::escape_field + * @todo Implement testEscape_field(). + */ + public function testEscape_field() + { $this->object->add_alias(); - $this->assertEquals('test', $this->object->escape_field(new Expression_Database('test'))); + $this->assertEquals('test', $this->object->escape_field(new Expression_Database('test'))); $this->assertEquals('`a0`.*', $this->object->escape_field('*')); $this->assertEquals('`a0`.`test`', $this->object->escape_field('test')); - $this->assertEquals('`test`.`test`',$this->object->escape_field('test.test')); - } - - /** - * @covers Query_Mysql_Driver::escape_value - * @todo Implement testEscape_value(). - */ - public function testEscape_value() - { - $params=array(); - $this->assertEquals('test', $this->object->escape_value(new Expression_Database('test'),$params)); + $this->assertEquals('`test`.`test`', $this->object->escape_field('test.test')); + } + + /** + * @covers Query_Mysql_Driver::escape_value + * @todo Implement testEscape_value(). + */ + public function testEscape_value() + { + $params = array(); + $this->assertEquals('test', $this->object->escape_value(new Expression_Database('test'), $params)); $this->assertEquals('?', $this->object->escape_value('korova', $params)); $this->assertArrayHasKey(0, $params); $this->assertEquals('korova', $params[0]); - } - - /** - * @covers Query_Mysql_Driver::query - * @todo Implement testQuery(). - */ - public function testQuerySelect1() - { - $query=$this->object + } + + /** + * @covers Query_Mysql_Driver::query + * @todo Implement testQuery(). + */ + public function testQuerySelect1() + { + $query = $this->object ->table('fairies') ->where('a', 7) ->where('b', '<', 8) @@ -72,13 +76,13 @@ class Query_Mysql_DriverTest extends PHPUnit_Framework_TestCase ->where(array( array('e', 9), array('or', array( - array('f', 10), - array('g', 11), - )), + array('f', 10), + array('g', 11), + )), array('or', array( - array('h', 12), - array('or',array('i', 13)), - )) + array('h', 12), + array('or', array('i', 13)), + )) )) ->order_by('id', 'desc') ->group_by('id') @@ -87,123 +91,122 @@ class Query_Mysql_DriverTest extends PHPUnit_Framework_TestCase ->having(array( array('m', 9), array('or', array( - array('n', 10), - array('o', 11), - )) + array('n', 10), + array('o', 11), + )) )) ->limit(5) ->offset(6) ->query(); - $this->assertEquals("SELECT * FROM `fairies` WHERE `fairies`.`a` = ? AND `fairies`.`b` < ? AND `fairies`.`c` > ? OR `fairies`.`d` > ? AND ( `fairies`.`e` = ? OR ( `fairies`.`f` = ? AND `fairies`.`g` = ? ) OR ( `fairies`.`h` = ? OR `fairies`.`i` = ? ) ) GROUP BY `fairies`.`id` HAVING `fairies`.`j` < korova OR `fairies`.`l` > ? AND ( `fairies`.`m` = ? OR ( `fairies`.`n` = ? AND `fairies`.`o` = ? ) ) ORDER BY `fairies`.`id` DESC LIMIT 5 OFFSET 6 ",current($query)); - - } + $this->assertEquals("SELECT * FROM `fairies` WHERE `fairies`.`a` = ? AND `fairies`.`b` < ? AND `fairies`.`c` > ? OR `fairies`.`d` > ? AND ( `fairies`.`e` = ? OR ( `fairies`.`f` = ? AND `fairies`.`g` = ? ) OR ( `fairies`.`h` = ? OR `fairies`.`i` = ? ) ) GROUP BY `fairies`.`id` HAVING `fairies`.`j` < korova OR `fairies`.`l` > ? AND ( `fairies`.`m` = ? OR ( `fairies`.`n` = ? AND `fairies`.`o` = ? ) ) ORDER BY `fairies`.`id` DESC LIMIT 5 OFFSET 6 ", current($query)); + } + /** - * @covers Query_Mysql_Driver::query - * @todo Implement testQuery(). - */ - public function testQuerySelect2() - { - $query=$this->object + * @covers Query_Mysql_Driver::query + * @todo Implement testQuery(). + */ + public function testQuerySelect2() + { + $query = $this->object ->table('fairies') ->where('a', 7) ->join('test', array('fairies.test_id', 'test.id')) ->join('test2', array( array('fairies.test2_id', 'test.test_id'), array('fairies.test3_id', 'test.id') - ),'inner') - ->order_by('id','desc') + ), 'inner') + ->order_by('id', 'desc') ->query(); - $this->assertEquals("SELECT * FROM `fairies` LEFT JOIN `test` ON `fairies`.`test_id` = `test`.`id` INNER JOIN `test2` ON ( `fairies`.`test2_id` = `test`.`test_id` AND `fairies`.`test3_id` = `test`.`id` ) WHERE `fairies`.`a` = ? ORDER BY `fairies`.`id` DESC ",current($query)); - - } - + $this->assertEquals("SELECT * FROM `fairies` LEFT JOIN `test` ON `fairies`.`test_id` = `test`.`id` INNER JOIN `test2` ON ( `fairies`.`test2_id` = `test`.`test_id` AND `fairies`.`test3_id` = `test`.`id` ) WHERE `fairies`.`a` = ? ORDER BY `fairies`.`id` DESC ", current($query)); + } + /** - * @covers Query_Mysql_Driver::query - * @todo Implement testQuery(). - */ - public function testQueryDelete() - { - $query=$this->object + * @covers Query_Mysql_Driver::query + * @todo Implement testQuery(). + */ + public function testQueryDelete() + { + $query = $this->object ->type('delete') ->table('fairies') - ->where('id',1) + ->where('id', 1) ->query(); - - $this->assertEquals("DELETE fairies.* FROM `fairies` WHERE `fairies`.`id` = ? ",current($query)); - } - + + $this->assertEquals("DELETE fairies.* FROM `fairies` WHERE `fairies`.`id` = ? ", current($query)); + } + /** - * @covers Query_Mysql_Driver::query - * @todo Implement testQuery(). - */ - public function testQueryInsert() - { - $query=$this->object + * @covers Query_Mysql_Driver::query + * @todo Implement testQuery(). + */ + public function testQueryInsert() + { + $query = $this->object ->type('insert') ->table('fairies') - ->data(array('id'=>1,'name'=>'Trixie')) + ->data(array('id' => 1, 'name' => 'Trixie')) ->query(); - - $this->assertEquals("INSERT INTO `fairies` (`id`, `name`) VALUES(?, ?)",current($query)); - } - + + $this->assertEquals("INSERT INTO `fairies` (`id`, `name`) VALUES(?, ?)", current($query)); + } + /** - * @covers Query_Mysql_Driver::query - * @todo Implement testQuery(). - */ - public function testQueryUpdate() - { - $query=$this->object + * @covers Query_Mysql_Driver::query + * @todo Implement testQuery(). + */ + public function testQueryUpdate() + { + $query = $this->object ->type('update') ->table('fairies') - ->data(array('id'=>1,'name'=>'Trixie')) + ->data(array('id' => 1, 'name' => 'Trixie')) ->query(); - - $this->assertEquals("UPDATE `fairies` SET `id` = ?, `name` = ? ",current($query)); - } - + + $this->assertEquals("UPDATE `fairies` SET `id` = ?, `name` = ? ", current($query)); + } + /** - * @covers Query_Mysql_Driver::query - * @todo Implement testQuery(). - */ + * @covers Query_Mysql_Driver::query + * @todo Implement testQuery(). + */ public function testQueryCount() - { - $query=$this->object + { + $query = $this->object ->type('count') ->table('fairies') - ->where('id',8) + ->where('id', 8) ->query(); - - $this->assertEquals("SELECT COUNT(*) as `count` FROM `fairies` WHERE `fairies`.`id` = ? ",current($query)); - } - + + $this->assertEquals("SELECT COUNT(*) as `count` FROM `fairies` WHERE `fairies`.`id` = ? ", current($query)); + } + /** - * @covers Query_Mysql_Driver::add_alias - * @todo Implement testQuery(). - */ + * @covers Query_Mysql_Driver::add_alias + * @todo Implement testQuery(). + */ public function testAlias() - { + { $this->object->table('fairies'); $this->assertEquals('fairies', $this->object->last_alias()); $this->object->add_alias(); - $this->assertEquals('a0',$this->object->last_alias()); - } - + $this->assertEquals('a0', $this->object->last_alias()); + } + /** - * @covers Query_Mysql_Driver::__call - * @todo Implement testQuery(). - */ + * @covers Query_Mysql_Driver::__call + * @todo Implement testQuery(). + */ public function testCall() - { + { $this->object->table('fairies'); $this->assertEquals('fairies', $this->object->table()); $except = false; try { $this->object->limit('fairies'); - }catch (Exception $e) { - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals(true,$except); - } - + $this->assertEquals(true, $except); + } + } diff --git a/tests/modules/database/driver/mysql/resultTest.php b/tests/modules/database/driver/mysql/resultTest.php index 5159e39..7142313 100644 --- a/tests/modules/database/driver/mysql/resultTest.php +++ b/tests/modules/database/driver/mysql/resultTest.php @@ -1,125 +1,135 @@ <?php + require_once('/../../../../../modules/database/classes/database/result.php'); require_once('/../../../../../modules/database/classes/driver/mysql/result.php'); + /** * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-02-06 at 20:48:50. */ class Result_Mysql_DriverTest extends PHPUnit_Framework_TestCase { - /** - * @var Result_Mysql_Driver - */ - protected $object; - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { + /** + * @var Result_Mysql_Driver + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { $stub = $this->getMockBuilder('mysqli_result') - ->disableOriginalConstructor() - ->getMock(); + ->disableOriginalConstructor() + ->getMock(); $stub->expects($this->any()) ->method('fetch_object') ->will($this->onConsecutiveCalls( - (object) array('id' => 1, 'name' => 'Tinkerbell'), - (object) array('id' => 2, 'name' => 'Trixie'), - null - )); + (object) array('id' => 1, 'name' => 'Tinkerbell'), (object) array('id' => 2, 'name' => 'Trixie'), null + )); - $this->object = new Result_Mysql_Driver($stub); - } + $this->object = new Result_Mysql_Driver($stub); + } - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { - /** - * @covers Result_Mysql_Driver::rewind - * @todo Implement testRewind(). - */ - public function testRewind() - { - $except = false; + } + + /** + * @covers Result_Mysql_Driver::rewind + * @todo Implement testRewind(). + */ + public function testRewind() + { + $except = false; $this->object->valid(); $this->object->rewind(); $this->object->next(); try { $this->object->rewind(); - }catch(Exception $e) { - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals(true,$except); - } + $this->assertEquals(true, $except); + } - /** - * @covers Result_Mysql_Driver::current - */ - public function testCurrent() { - $this->assertEquals($this->object->current()->name,'Tinkerbell'); + * @covers Result_Mysql_Driver::current + */ + public function testCurrent() + { + $this->assertEquals($this->object->current()->name, 'Tinkerbell'); } - + /** - * @covers Result_Mysql_Driver::valid - */ - public function testVaid() { - $this->assertEquals($this->object->valid(),true); + * @covers Result_Mysql_Driver::valid + */ + public function testVaid() + { + $this->assertEquals($this->object->valid(), true); } - + /** - * @covers Result_Mysql_Driver::key - */ - public function testKey() { - $this->assertEquals($this->object->key(),0); + * @covers Result_Mysql_Driver::key + */ + public function testKey() + { + $this->assertEquals($this->object->key(), 0); } - + /** - * @covers Result_Mysql_Driver::key - */ - public function testGet() { - $this->assertEquals($this->object->get('id'),1); + * @covers Result_Mysql_Driver::key + */ + public function testGet() + { + $this->assertEquals($this->object->get('id'), 1); } - + /** - * @covers Result_Mysql_Driver::as_array - */ - public function testAs_Array() { + * @covers Result_Mysql_Driver::as_array + */ + public function testAs_Array() + { $arr = $this->object->as_array(); $this->assertArrayHasKey(0, $arr); - $this->assertArrayHasKey('name', (array)$arr[0]); + $this->assertArrayHasKey('name', (array) $arr[0]); $this->assertEquals($arr[0]->name, 'Tinkerbell'); $this->assertArrayHasKey(1, $arr); - $this->assertArrayHasKey('id', (array)$arr[1]); + $this->assertArrayHasKey('id', (array) $arr[1]); $this->assertEquals($arr[1]->id, 2); } - - public function testIterator(){ + + public function testIterator() + { $this->assertEquals($this->object->valid(), true); $this->assertEquals($this->object->get('id'), 1); - foreach($this->object as $key => $row) { - if ($key == 0) { + foreach ($this->object as $key => $row) + { + if ($key == 0) + { $this->assertEquals($row->name, 'Tinkerbell'); $this->assertEquals($row->id, 1); } - if ($key == 1) { + if ($key == 1) + { $this->assertEquals($row->name, 'Trixie'); $this->assertEquals(2, $this->object->get('id')); $this->assertEquals($row->id, 2); } } - $this->assertEquals(false,$this->object->valid()); + $this->assertEquals(false, $this->object->valid()); $this->assertEquals(null, $this->object->get('id')); $this->assertEquals(null, $this->object->current()); $this->object->next(); $this->object->next(); $this->object->next(); - $this->assertEquals(1,$this->object->key()); - + $this->assertEquals(1, $this->object->key()); } + } diff --git a/tests/modules/database/driver/pdo/dbTest.php b/tests/modules/database/driver/pdo/dbTest.php index bf242ec..ccebedc 100644 --- a/tests/modules/database/driver/pdo/dbTest.php +++ b/tests/modules/database/driver/pdo/dbTest.php @@ -1,134 +1,137 @@ <?php + require_once('/../../../../../modules/database/classes/db.php'); require_once('/../../../../../modules/database/classes/driver/pdo/db.php'); require_once('/../../../../../modules/database/classes/database/query.php'); require_once('/../../../../../modules/database/classes/driver/pdo/query.php'); + /** * Generated by PHPUnit_SkeletonGenerator on 2013-02-07 at 12:41:50. */ class DB_PDO_DriverTest extends PHPUnit_Framework_TestCase { - /** - * @var DB_PDO_Driver - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - file_put_contents(dirname(__FILE__).'/../../files/test.sqlite',''); + + /** + * @var DB_PDO_Driver + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + file_put_contents(dirname(__FILE__).'/../../files/test.sqlite', ''); $db = new PDO('sqlite:'.dirname(__FILE__).'/../../files/test.sqlite'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->exec("CREATE TABLE fairies(id INT PRIMARY_KEY,name VARCHAR(255))"); - + Misc::$file = dirname(__FILE__).'/../../files/config.sqlite'; file_put_contents(Misc::$file, "<?php return ".var_export(array( - 'default' => array( - 'connection' => 'sqlite:'.dirname(__FILE__).'/../../files/test.sqlite', - 'driver'=>'pdo' - ) - ), true).';'); - - $this->object = new DB_PDO_Driver('default'); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - - } - - /** - * @covers DB_PDO_Driver::build_query - * @todo Implement testBuild_query(). - */ - public function testBuild_query() - { - $this->object->build_query('select'); - } - - /** - * @covers DB_PDO_Driver::get_insert_id - * @todo Implement testGet_insert_id(). - */ - public function testGet_insert_id() - { - $this->object->execute("INSERT INTO fairies(name)values('Trixie')"); - $this->assertEquals(1,$this->object->get_insert_id()); - } - - /** - * @covers DB_PDO_Driver::list_columns - * @todo Implement testList_columns(). - */ - public function testList_columns() - { - $cols = $this->object->list_columns('fairies'); - $this->assertContains('id',$cols); - $this->assertContains('name',$cols); - } - - /** - * @covers DB_PDO_Driver::execute - * @todo Implement testExecute(). - */ - public function testExecute() - { - $this->object->execute("SELECT * FROM fairies where id = ?",array(1)); - } - + 'default' => array( + 'connection' => 'sqlite:'.dirname(__FILE__).'/../../files/test.sqlite', + 'driver' => 'pdo' + ) + ), true).';'); + + $this->object = new DB_PDO_Driver('default'); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + + } + /** - * @covers DB_PDO_Driver::execute - * @todo Implement testExecute(). - */ - public function testExecuteException() - { + * @covers DB_PDO_Driver::build_query + * @todo Implement testBuild_query(). + */ + public function testBuild_query() + { + $this->object->build_query('select'); + } + + /** + * @covers DB_PDO_Driver::get_insert_id + * @todo Implement testGet_insert_id(). + */ + public function testGet_insert_id() + { + $this->object->execute("INSERT INTO fairies(name)values('Trixie')"); + $this->assertEquals(1, $this->object->get_insert_id()); + } + + /** + * @covers DB_PDO_Driver::list_columns + * @todo Implement testList_columns(). + */ + public function testList_columns() + { + $cols = $this->object->list_columns('fairies'); + $this->assertContains('id', $cols); + $this->assertContains('name', $cols); + } + + /** + * @covers DB_PDO_Driver::execute + * @todo Implement testExecute(). + */ + public function testExecute() + { + $this->object->execute("SELECT * FROM fairies where id = ?", array(1)); + } + + /** + * @covers DB_PDO_Driver::execute + * @todo Implement testExecute(). + */ + public function testExecuteException() + { $except = false; - try{ + try { $this->object->execute("SELECUT * FROM fairies where id = ?", array(1)); - }catch (Exception $e) { - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals(true,$except); - } - + $this->assertEquals(true, $except); + } + /** - * @covers DB_PDO_Driver::named_query - * @todo Implement testExecute(). - */ - public function testNamed_query() - { - $this->object->named_query("SELECT * FROM fairies where id = :id",array(array('id'=>1))); - } - + * @covers DB_PDO_Driver::named_query + * @todo Implement testExecute(). + */ + public function testNamed_query() + { + $this->object->named_query("SELECT * FROM fairies where id = :id", array(array('id' => 1))); + } + /** - * @covers DB_PDO_Driver::named_query - * @todo Implement testExecute(). - */ - public function testNamed_queryException() - { + * @covers DB_PDO_Driver::named_query + * @todo Implement testExecute(). + */ + public function testNamed_queryException() + { $except = false; - try{ - $this->object->named_query("SELsECT * FROM fairies where id = :id",array(array('id'=>1))); - }catch (Exception $e) { - $except=true; + try { + $this->object->named_query("SELsECT * FROM fairies where id = :id", array(array('id' => 1))); + } catch (Exception $e) { + $except = true; } - $this->assertEquals(true,$except); - } - + $this->assertEquals(true, $except); + } + /** - * @covers DB_PDO_Driver::instance - * @todo Implement testExecute(). - */ - public function testInstance() - { - $this->assertEquals('DB_PDO_Driver',get_class(DB::instance('default'))); - } - + * @covers DB_PDO_Driver::instance + * @todo Implement testExecute(). + */ + public function testInstance() + { + $this->assertEquals('DB_PDO_Driver', get_class(DB::instance('default'))); + } + } diff --git a/tests/modules/database/driver/pdo/queryTest.php b/tests/modules/database/driver/pdo/queryTest.php index 158a0f7..b216ec7 100644 --- a/tests/modules/database/driver/pdo/queryTest.php +++ b/tests/modules/database/driver/pdo/queryTest.php @@ -1,68 +1,72 @@ <?php + require_once('/../../../../../modules/database/classes/database/query.php'); require_once('/../../../../../modules/database/classes/driver/pdo/query.php'); require_once('/../../../../../modules/database/classes/database/expression.php'); + /** * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-02-01 at 06:23:13. */ class Query_PDO_DriverTest extends PHPUnit_Framework_TestCase { - /** - * @var Query_PDO_Driver - */ - protected $object; - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - $stub=(object)array('db_type'=>'mysql'); - $this->object = new Query_PDO_Driver($stub,'select'); - } + /** + * @var Query_PDO_Driver + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + $stub = (object) array('db_type' => 'mysql'); + $this->object = new Query_PDO_Driver($stub, 'select'); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } + } - /** - * @covers Query_PDO_Driver::escape_field - * @todo Implement testEscape_field(). - */ - public function testEscape_field() - { + /** + * @covers Query_PDO_Driver::escape_field + * @todo Implement testEscape_field(). + */ + public function testEscape_field() + { $this->object->add_alias(); - $this->assertEquals('test', $this->object->escape_field(new Expression_Database('test'))); + $this->assertEquals('test', $this->object->escape_field(new Expression_Database('test'))); $this->assertEquals('`a0`.*', $this->object->escape_field('*')); $this->assertEquals('`a0`.`test`', $this->object->escape_field('test')); - $this->assertEquals('`test`.`test`',$this->object->escape_field('test.test')); - } + $this->assertEquals('`test`.`test`', $this->object->escape_field('test.test')); + } - /** - * @covers Query_PDO_Driver::escape_value - * @todo Implement testEscape_value(). - */ - public function testEscape_value() - { - $params=array(); - $this->assertEquals('test', $this->object->escape_value(new Expression_Database('test'),$params)); + /** + * @covers Query_PDO_Driver::escape_value + * @todo Implement testEscape_value(). + */ + public function testEscape_value() + { + $params = array(); + $this->assertEquals('test', $this->object->escape_value(new Expression_Database('test'), $params)); $this->assertEquals('?', $this->object->escape_value('korova', $params)); $this->assertArrayHasKey(0, $params); $this->assertEquals('korova', $params[0]); - } + } - /** - * @covers Query_PDO_Driver::query - * @todo Implement testQuery(). - */ - public function testQuerySelect1() - { - $query=$this->object + /** + * @covers Query_PDO_Driver::query + * @todo Implement testQuery(). + */ + public function testQuerySelect1() + { + $query = $this->object ->table('fairies') ->where('a', 7) ->where('b', '<', 8) @@ -71,13 +75,13 @@ class Query_PDO_DriverTest extends PHPUnit_Framework_TestCase ->where(array( array('e', 9), array('or', array( - array('f', 10), - array('g', 11), - )), + array('f', 10), + array('g', 11), + )), array('or', array( - array('h', 12), - array('or',array('i', 13)), - )) + array('h', 12), + array('or', array('i', 13)), + )) )) ->order_by('id', 'desc') ->group_by('id') @@ -86,173 +90,172 @@ class Query_PDO_DriverTest extends PHPUnit_Framework_TestCase ->having(array( array('m', 9), array('or', array( - array('n', 10), - array('o', 11), - )) + array('n', 10), + array('o', 11), + )) )) ->limit(5) ->offset(6) ->query(); - $this->assertEquals("SELECT * FROM `fairies` WHERE `fairies`.`a` = ? AND `fairies`.`b` < ? AND `fairies`.`c` > ? OR `fairies`.`d` > ? AND ( `fairies`.`e` = ? OR ( `fairies`.`f` = ? AND `fairies`.`g` = ? ) OR ( `fairies`.`h` = ? OR `fairies`.`i` = ? ) ) GROUP BY `fairies`.`id` HAVING `fairies`.`j` < korova OR `fairies`.`l` > ? AND ( `fairies`.`m` = ? OR ( `fairies`.`n` = ? AND `fairies`.`o` = ? ) ) ORDER BY `fairies`.`id` DESC LIMIT 5 OFFSET 6 ",current($query)); - - } + $this->assertEquals("SELECT * FROM `fairies` WHERE `fairies`.`a` = ? AND `fairies`.`b` < ? AND `fairies`.`c` > ? OR `fairies`.`d` > ? AND ( `fairies`.`e` = ? OR ( `fairies`.`f` = ? AND `fairies`.`g` = ? ) OR ( `fairies`.`h` = ? OR `fairies`.`i` = ? ) ) GROUP BY `fairies`.`id` HAVING `fairies`.`j` < korova OR `fairies`.`l` > ? AND ( `fairies`.`m` = ? OR ( `fairies`.`n` = ? AND `fairies`.`o` = ? ) ) ORDER BY `fairies`.`id` DESC LIMIT 5 OFFSET 6 ", current($query)); + } + /** - * @covers Query_PDO_Driver::query - * @todo Implement testQuery(). - */ - public function testQuerySelect2() - { - $query=$this->object + * @covers Query_PDO_Driver::query + * @todo Implement testQuery(). + */ + public function testQuerySelect2() + { + $query = $this->object ->table('fairies') ->where('a', 7) ->join('test', array('fairies.test_id', 'test.id')) ->join('test2', array( array('fairies.test2_id', 'test.test_id'), array('fairies.test3_id', 'test.id') - ),'inner') - ->order_by('id','desc') + ), 'inner') + ->order_by('id', 'desc') ->query(); - $this->assertEquals("SELECT * FROM `fairies` LEFT JOIN `test` ON `fairies`.`test_id` = `test`.`id` INNER JOIN `test2` ON ( `fairies`.`test2_id` = `test`.`test_id` AND `fairies`.`test3_id` = `test`.`id` ) WHERE `fairies`.`a` = ? ORDER BY `fairies`.`id` DESC ",current($query)); - - } - + $this->assertEquals("SELECT * FROM `fairies` LEFT JOIN `test` ON `fairies`.`test_id` = `test`.`id` INNER JOIN `test2` ON ( `fairies`.`test2_id` = `test`.`test_id` AND `fairies`.`test3_id` = `test`.`id` ) WHERE `fairies`.`a` = ? ORDER BY `fairies`.`id` DESC ", current($query)); + } + /** - * @covers Query_PDO_Driver::query - * @todo Implement testQuery(). - */ - public function testQueryDelete() - { - $query=$this->object + * @covers Query_PDO_Driver::query + * @todo Implement testQuery(). + */ + public function testQueryDelete() + { + $query = $this->object ->type('delete') ->table('fairies') - ->where('id',1) + ->where('id', 1) ->query(); - - $this->assertEquals("DELETE fairies.* FROM `fairies` WHERE `fairies`.`id` = ? ",current($query)); - } - + + $this->assertEquals("DELETE fairies.* FROM `fairies` WHERE `fairies`.`id` = ? ", current($query)); + } + /** - * @covers Query_PDO_Driver::query - * @todo Implement testQuery(). - */ - public function testQueryInsert() - { - $query=$this->object + * @covers Query_PDO_Driver::query + * @todo Implement testQuery(). + */ + public function testQueryInsert() + { + $query = $this->object ->type('insert') ->table('fairies') - ->data(array('id'=>1,'name'=>'Trixie')) + ->data(array('id' => 1, 'name' => 'Trixie')) ->query(); - - $this->assertEquals("INSERT INTO `fairies` (`id`, `name`) VALUES(?, ?)",current($query)); - } - + + $this->assertEquals("INSERT INTO `fairies` (`id`, `name`) VALUES(?, ?)", current($query)); + } + /** - * @covers Query_PDO_Driver::query - * @todo Implement testQuery(). - */ - public function testQueryUpdate() - { - $query=$this->object + * @covers Query_PDO_Driver::query + * @todo Implement testQuery(). + */ + public function testQueryUpdate() + { + $query = $this->object ->type('update') ->table('fairies') - ->data(array('id'=>1,'name'=>'Trixie')) + ->data(array('id' => 1, 'name' => 'Trixie')) ->query(); - - $this->assertEquals("UPDATE `fairies` SET `id` = ?, `name` = ? ",current($query)); - } - + + $this->assertEquals("UPDATE `fairies` SET `id` = ?, `name` = ? ", current($query)); + } + /** - * @covers Query_PDO_Driver::query - * @todo Implement testQuery(). - */ + * @covers Query_PDO_Driver::query + * @todo Implement testQuery(). + */ public function testQueryCount() - { - $query=$this->object + { + $query = $this->object ->type('count') ->table('fairies') - ->where('id',8) + ->where('id', 8) ->query(); - - $this->assertEquals("SELECT COUNT(*) as `count` FROM `fairies` WHERE `fairies`.`id` = ? ",current($query)); - } - + + $this->assertEquals("SELECT COUNT(*) as `count` FROM `fairies` WHERE `fairies`.`id` = ? ", current($query)); + } + /** - * @covers Query_PDO_Driver::add_alias - * @todo Implement testQuery(). - */ + * @covers Query_PDO_Driver::add_alias + * @todo Implement testQuery(). + */ public function testAlias() - { + { $this->object->table('fairies'); $this->assertEquals('fairies', $this->object->last_alias()); $this->object->add_alias(); - $this->assertEquals('a0',$this->object->last_alias()); - } - + $this->assertEquals('a0', $this->object->last_alias()); + } + /** - * @covers Query_PDO_Driver::__call - * @todo Implement testQuery(). - */ + * @covers Query_PDO_Driver::__call + * @todo Implement testQuery(). + */ public function testCall() - { + { $this->object->table('fairies'); $this->assertEquals('fairies', $this->object->table()); $except = false; try { $this->object->limit('fairies'); - }catch (Exception $e) { - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals(true,$except); - } - + $this->assertEquals(true, $except); + } + public function testUnion() { - $stub=(object)array('db_type'=>'mysql'); + $stub = (object) array('db_type' => 'mysql'); $subquery = new Query_PDO_Driver($stub, 'select'); $subquery->table('fairies'); $this->object->table('fairies'); $this->object->where('id', '>', 7); $this->object->union($subquery); $this->object->union($subquery); - $this->assertEquals('(SELECT * FROM `fairies` WHERE `fairies`.`id` > ? ) UNION ALL (SELECT * FROM `fairies` ) UNION ALL (SELECT * FROM `fairies` ) ',current($this->object->query())); + $this->assertEquals('(SELECT * FROM `fairies` WHERE `fairies`.`id` > ? ) UNION ALL (SELECT * FROM `fairies` ) UNION ALL (SELECT * FROM `fairies` ) ', current($this->object->query())); } - + public function testSubselect() { - $stub=(object)array('db_type'=>'mysql'); + $stub = (object) array('db_type' => 'mysql'); $subquery = new Query_PDO_Driver($stub, 'select'); $subquery->fields('id')->table('fairies'); $this->object->table('fairies')->where('id', 7)->where('id', 'in', $subquery); - $this->assertEquals('SELECT * FROM `fairies` WHERE `fairies`.`id` = ? AND `fairies`.`id` in (SELECT `fairies`.`id` FROM `fairies` ) ',current($this->object->query())); + $this->assertEquals('SELECT * FROM `fairies` WHERE `fairies`.`id` = ? AND `fairies`.`id` in (SELECT `fairies`.`id` FROM `fairies` ) ', current($this->object->query())); } - + public function testSubtable() { - $stub=(object)array('db_type'=>'mysql'); + $stub = (object) array('db_type' => 'mysql'); $subquery = new Query_PDO_Driver($stub, 'select'); $subquery->fields('id')->table('fairies'); $this->object->table($subquery)->where('id', 7); - $this->assertEquals('SELECT * FROM (SELECT `fairies`.`id` FROM `fairies` ) AS a0 WHERE `a0`.`id` = ? ',current($this->object->query())); + $this->assertEquals('SELECT * FROM (SELECT `fairies`.`id` FROM `fairies` ) AS a0 WHERE `a0`.`id` = ? ', current($this->object->query())); } - + public function testJoinSubtable() { - $stub=(object)array('db_type'=>'mysql'); + $stub = (object) array('db_type' => 'mysql'); $subquery = new Query_PDO_Driver($stub, 'select'); $subquery->table('fairies'); $this->object->table($subquery); $this->object->join('pixies', array('fairies.id', '=', 'pixie.id')); $this->object->join(array('fairies', 'fae'), array('fairies.id', '=', 'fae.id')); $this->object->join(array($subquery, 'fae2'), array('fairies.id', '=', 'fae2.id')); - - - $this->assertEquals('SELECT * FROM (SELECT * FROM `fairies` ) AS a0 LEFT JOIN `pixies` ON `fairies`.`id` = `pixie`.`id` LEFT JOIN `fairies` AS fae ON `fairies`.`id` = `fae`.`id` LEFT JOIN (SELECT * FROM `fairies` ) AS fae2 ON `fairies`.`id` = `fae2`.`id` ',current($this->object->query())); + + + $this->assertEquals('SELECT * FROM (SELECT * FROM `fairies` ) AS a0 LEFT JOIN `pixies` ON `fairies`.`id` = `pixie`.`id` LEFT JOIN `fairies` AS fae ON `fairies`.`id` = `fae`.`id` LEFT JOIN (SELECT * FROM `fairies` ) AS fae2 ON `fairies`.`id` = `fae2`.`id` ', current($this->object->query())); } - + public function testExpressionSelect() { - $this->object->table('fairies')->where('id','in',DB::expr("(SELECT id from fairies)")); - $this->assertEquals('SELECT * FROM `fairies` WHERE `fairies`.`id` in (SELECT id from fairies) ',current($this->object->query())); + $this->object->table('fairies')->where('id', 'in', DB::expr("(SELECT id from fairies)")); + $this->assertEquals('SELECT * FROM `fairies` WHERE `fairies`.`id` in (SELECT id from fairies) ', current($this->object->query())); } - + } diff --git a/tests/modules/database/driver/pdo/resultTest.php b/tests/modules/database/driver/pdo/resultTest.php index 3b341b4..0a48d3a 100644 --- a/tests/modules/database/driver/pdo/resultTest.php +++ b/tests/modules/database/driver/pdo/resultTest.php @@ -1,125 +1,136 @@ <?php + require_once('/../../../../../modules/database/classes/database/result.php'); require_once('/../../../../../modules/database/classes/driver/pdo/result.php'); + /** * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-02-06 at 20:48:50. */ class Result_PDO_DriverTest extends PHPUnit_Framework_TestCase { - /** - * @var Result_PDO_Driver - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { + + /** + * @var Result_PDO_Driver + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { $db = new PDO('sqlite::memory:'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->exec("CREATE TABLE fairies(id INT,name VARCHAR(255))"); - + $db->exec("INSERT INTO fairies (id,name) VALUES (1,'Tinkerbell')"); $db->exec("INSERT INTO fairies (id,name) VALUES (2,'Trixie')"); - + $q = $db->prepare("SELECT * from fairies"); $q->execute(); - $this->object = new Result_PDO_Driver($q); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - - } - - /** - * @covers Result_PDO_Driver::rewind - * @todo Implement testRewind(). - */ - public function testRewind() - { - $except = false; + $this->object = new Result_PDO_Driver($q); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + + } + + /** + * @covers Result_PDO_Driver::rewind + * @todo Implement testRewind(). + */ + public function testRewind() + { + $except = false; $this->object->valid(); $this->object->rewind(); $this->object->next(); try { $this->object->rewind(); - }catch(Exception $e) { - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals(true,$except); - } + $this->assertEquals(true, $except); + } - /** - * @covers Result_PDO_Driver::current - */ - public function testCurrent() { - $this->assertEquals($this->object->current()->name,'Tinkerbell'); + * @covers Result_PDO_Driver::current + */ + public function testCurrent() + { + $this->assertEquals($this->object->current()->name, 'Tinkerbell'); } - + /** - * @covers Result_PDO_Driver::valid - */ - public function testVaid() { - $this->assertEquals($this->object->valid(),true); + * @covers Result_PDO_Driver::valid + */ + public function testVaid() + { + $this->assertEquals($this->object->valid(), true); } - + /** - * @covers Result_PDO_Driver::key - */ - public function testKey() { - $this->assertEquals($this->object->key(),0); + * @covers Result_PDO_Driver::key + */ + public function testKey() + { + $this->assertEquals($this->object->key(), 0); } - + /** - * @covers Result_PDO_Driver::key - */ - public function testGet() { - $this->assertEquals($this->object->get('id'),1); + * @covers Result_PDO_Driver::key + */ + public function testGet() + { + $this->assertEquals($this->object->get('id'), 1); } - + /** - * @covers Result_PDO_Driver::as_array - */ - public function testAs_Array() { + * @covers Result_PDO_Driver::as_array + */ + public function testAs_Array() + { $arr = $this->object->as_array(); $this->assertArrayHasKey(0, $arr); - $this->assertArrayHasKey('name', (array)$arr[0]); + $this->assertArrayHasKey('name', (array) $arr[0]); $this->assertEquals($arr[0]->name, 'Tinkerbell'); $this->assertArrayHasKey(1, $arr); - $this->assertArrayHasKey('id', (array)$arr[1]); + $this->assertArrayHasKey('id', (array) $arr[1]); $this->assertEquals($arr[1]->id, 2); } - - public function testIterator(){ + + public function testIterator() + { $this->assertEquals($this->object->valid(), true); $this->assertEquals($this->object->get('id'), 1); - foreach($this->object as $key => $row) { - if ($key == 0) { + foreach ($this->object as $key => $row) + { + if ($key == 0) + { $this->assertEquals($row->name, 'Tinkerbell'); $this->assertEquals($row->id, 1); } - if ($key == 1) { + if ($key == 1) + { $this->assertEquals($row->name, 'Trixie'); $this->assertEquals(2, $this->object->get('id')); $this->assertEquals($row->id, 2); } } - $this->assertEquals(false,$this->object->valid()); + $this->assertEquals(false, $this->object->valid()); $this->assertEquals(null, $this->object->get('id')); $this->assertEquals(null, $this->object->current()); $this->object->next(); $this->object->next(); $this->object->next(); - $this->assertEquals(1,$this->object->key()); - + $this->assertEquals(1, $this->object->key()); } + } diff --git a/tests/modules/database/files/config.sqlite b/tests/modules/database/files/config.sqlite index 34eea03..401e0ff 100644 --- a/tests/modules/database/files/config.sqlite +++ b/tests/modules/database/files/config.sqlite @@ -1,7 +1,9 @@ -<?php return array ( - 'default' => - array ( - 'connection' => 'sqlite:C:\\Users\\Dracony\\Documents\\GitHub\\PHPixie\\tests\\modules\\database\\driver\\pdo/../../files/test.sqlite', - 'driver' => 'pdo', - ), -);
\ No newline at end of file +<?php + +return array( + 'default' => + array( + 'connection' => 'sqlite:C:\\Users\\Dracony\\Documents\\GitHub\\PHPixie\\tests\\modules\\database\\driver\\pdo/../../files/test.sqlite', + 'driver' => 'pdo', + ), +); diff --git a/tests/modules/orm/files/config.php b/tests/modules/orm/files/config.php index 78c9a88..41f44e8 100644 --- a/tests/modules/orm/files/config.php +++ b/tests/modules/orm/files/config.php @@ -1,7 +1,9 @@ -<?php return array ( - 'orm' => - array ( - 'connection' => 'sqlite:C:\\Users\\Dracony\\Documents\\GitHub\\PHPixie\\tests\\modules\\orm./files/test.sqlite', - 'driver' => 'pdo', - ), -);
\ No newline at end of file +<?php + +return array( + 'orm' => + array( + 'connection' => 'sqlite:C:\\Users\\Dracony\\Documents\\GitHub\\PHPixie\\tests\\modules\\orm./files/test.sqlite', + 'driver' => 'pdo', + ), +); diff --git a/tests/modules/orm/files/config.sqlite b/tests/modules/orm/files/config.sqlite index 930bdd4..a1a169a 100644 --- a/tests/modules/orm/files/config.sqlite +++ b/tests/modules/orm/files/config.sqlite @@ -1,7 +1,9 @@ -<?php return array ( - 'default' => - array ( - 'connection' => 'sqlite:C:\\Users\\Dracony\\Documents\\GitHub\\PHPixie\\tests\\modules\\orm./files/test.sqlite', - 'driver' => 'pdo', - ), -);
\ No newline at end of file +<?php + +return array( + 'default' => + array( + 'connection' => 'sqlite:C:\\Users\\Dracony\\Documents\\GitHub\\PHPixie\\tests\\modules\\orm./files/test.sqlite', + 'driver' => 'pdo', + ), +); diff --git a/tests/modules/orm/files/fairy_orm.php b/tests/modules/orm/files/fairy_orm.php index 527ec88..23bc4db 100644 --- a/tests/modules/orm/files/fairy_orm.php +++ b/tests/modules/orm/files/fairy_orm.php @@ -1,13 +1,19 @@ <?php -class Fairy_Model extends ORM { + +class Fairy_Model extends ORM +{ + public $belongs_to = array('tree'); - public $connection='orm'; + public $connection = 'orm'; public $has_many = array( - 'protects'=>array('model'=>'tree','key'=>'protector_id'), - 'friends'=>array('model'=>'fairy','through'=>'friends','key'=>'fairy_id','foreign_key'=>'friend_id') + 'protects' => array('model' => 'tree', 'key' => 'protector_id'), + 'friends' => array('model' => 'fairy', 'through' => 'friends', 'key' => 'fairy_id', 'foreign_key' => 'friend_id') ); - public function get($column){ - if($column=='test') + + public function get($column) + { + if ($column == 'test') return 5; } -}
\ No newline at end of file + +} diff --git a/tests/modules/orm/files/stub_orm.php b/tests/modules/orm/files/stub_orm.php index 280b991..8c7e16e 100644 --- a/tests/modules/orm/files/stub_orm.php +++ b/tests/modules/orm/files/stub_orm.php @@ -1,16 +1,22 @@ <?php -class Stub_ORM { + +class Stub_ORM +{ + public $row; public $loaded; - public $cached = array(); - - public function values($row,$loaded){ - $this->row=$row; + + public function values($row, $loaded) + { + $this->row = $row; $this->loaded = $loaded; return $this; } - public function columns(){ - return array('id','name'); + + public function columns() + { + return array('id', 'name'); } + }
\ No newline at end of file diff --git a/tests/modules/orm/files/test_result.php b/tests/modules/orm/files/test_result.php index 090739b..11da829 100644 --- a/tests/modules/orm/files/test_result.php +++ b/tests/modules/orm/files/test_result.php @@ -1,23 +1,39 @@ <?php -Class Test_Result implements Iterator{ + +Class Test_Result implements Iterator +{ + public $pos = 0; public $data; - - public function key(){ - return $this->pos>count($this->data)-1?count($this->data)-1:$this->pos; + + public function key() + { + return $this->pos > count($this->data) - 1 ? count($this->data) - 1 : $this->pos; } - public function valid(){ - return $this->pos<count($this->data); + + public function valid() + { + return $this->pos < count($this->data); } - public function next(){ + + public function next() + { $this->pos++; } - public function current(){ + + public function current() + { return $this->data[$this->pos]; } - public function as_array(){ + + public function as_array() + { return $this->data; } - public function rewind(){} -}
\ No newline at end of file + public function rewind() + { + + } + +} diff --git a/tests/modules/orm/files/tree_orm.php b/tests/modules/orm/files/tree_orm.php index 2dff089..6806547 100644 --- a/tests/modules/orm/files/tree_orm.php +++ b/tests/modules/orm/files/tree_orm.php @@ -1,8 +1,12 @@ <?php -class Tree_Model extends ORM { + +class Tree_Model extends ORM +{ + public $has_one = array('fairy'); - public $connection='orm'; + public $connection = 'orm'; public $belongs_to = array( - 'protector'=>array('model'=>'fairy','key'=>'protector_id') + 'protector' => array('model' => 'fairy', 'key' => 'protector_id') ); -}
\ No newline at end of file + +} diff --git a/tests/modules/orm/orm/resultTest.php b/tests/modules/orm/orm/resultTest.php index cb0299e..e972d23 100644 --- a/tests/modules/orm/orm/resultTest.php +++ b/tests/modules/orm/orm/resultTest.php @@ -1,49 +1,54 @@ <?php + require_once('/../../../../modules/database/classes/database/result.php'); require_once('/../../../../modules/orm/classes/orm/result.php'); require_once('/../files/stub_orm.php'); require_once('/../files/test_result.php'); + /** * Generated by PHPUnit_SkeletonGenerator on 2013-02-08 at 13:27:44. */ class Result_ORMTest extends PHPUnit_Framework_TestCase { - /** - * @var Result_ORM - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { + + /** + * @var Result_ORM + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { $this->stub = new Test_Result; $this->stub->data = array( (object) array('id' => 1, 'name' => 'Trixie'), (object) array('id' => 2, 'name' => 'Tinkerbell') ); - $this->object = new Result_ORM('Stub_Orm',$this->stub); - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - - /** - * @covers Result_ORM::current - * @todo Implement testCurrent(). - */ - public function testCurrent() - { - - $row = $this->object->current()->row;; + $this->object = new Result_ORM('Stub_Orm', $this->stub); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + + } + + /** + * @covers Result_ORM::current + * @todo Implement testCurrent(). + */ + public function testCurrent() + { + + $row = $this->object->current()->row; + ; $this->assertArrayHasKey('id', $row); $this->assertArrayHasKey('name', $row); $this->assertEquals(1, $row['id']); @@ -53,94 +58,100 @@ class Result_ORMTest extends PHPUnit_Framework_TestCase $this->assertArrayHasKey('id', $row); $this->assertArrayHasKey('name', $row); $this->assertEquals(2, $row['id']); - $this->assertEquals('Tinkerbell',$row['name']); - } - - /** - * @covers Result_ORM::key - * @todo Implement testKey(). - */ - public function testKey() - { - $this->assertEquals(0, $this->object->key()); + $this->assertEquals('Tinkerbell', $row['name']); + } + + /** + * @covers Result_ORM::key + * @todo Implement testKey(). + */ + public function testKey() + { + $this->assertEquals(0, $this->object->key()); $this->object->next(); $this->assertEquals(1, $this->object->key()); $this->object->next(); $this->assertEquals(1, $this->object->key()); - } + } - - public function testValid() - { - $this->assertEquals(true, $this->object->valid()); + public function testValid() + { + $this->assertEquals(true, $this->object->valid()); $this->object->next(); $this->assertEquals(true, $this->object->valid()); $this->object->next(); $this->assertEquals(false, $this->object->valid()); - } - + } public function testAs_arrayArray() - { - $arr = $this->object->as_array(true); + { + $arr = $this->object->as_array(true); - foreach(array('Trixie', 'Tinkerbell') as $key=>$name) { + foreach (array('Trixie', 'Tinkerbell') as $key => $name) + { $this->assertArrayHasKey($key, $arr); - $row = (array)$arr[$key]; + $row = (array) $arr[$key]; $this->assertArrayHasKey('name', $row); - $this->assertEquals($name,$row['name']); - } - } - + $this->assertEquals($name, $row['name']); + } + } + public function testAs_arrayObject() - { + { - $arr = $this->object->as_array(); + $arr = $this->object->as_array(); - foreach(array('Trixie', 'Tinkerbell') as $key=>$name) { + foreach (array('Trixie', 'Tinkerbell') as $key => $name) + { $this->assertArrayHasKey($key, $arr); $row = $arr[$key]; $this->assertArrayHasKey('name', $row->row); - $this->assertEquals($name,$row->row['name']); - } - } - - public function test_with(){ - $this->stub->data=array( - (object) array('id' => 1, 'name' => 'Trixie','id1'=>11,'name1'=>'Trixie1','id2'=>12,'name2'=>'Trixie2'), - (object) array('id' => 1, 'name' => 'Tinkerbell','id1'=>11,'name1'=>'Tinkerbell1','id2'=>12,'name2'=>'Tinkerbell2') - ); - + $this->assertEquals($name, $row->row['name']); + } + } + + public function test_with() + { + $this->stub->data = array( + (object) array('id' => 1, 'name' => 'Trixie', 'id1' => 11, 'name1' => 'Trixie1', 'id2' => 12, 'name2' => 'Trixie2'), + (object) array('id' => 1, 'name' => 'Tinkerbell', 'id1' => 11, 'name1' => 'Tinkerbell1', 'id2' => 12, 'name2' => 'Tinkerbell2') + ); + $this->object = new Result_ORM('Stub_Orm', $this->stub, array( - 'tester' => array('model' => new Stub_Orm), - 'tester.another' => array('model' => new Stub_Orm) - )); - foreach(array('Trixie', 'Tinkerbell') as $name) { + 'tester' => array('model' => new Stub_Orm), + 'tester.another' => array('model' => new Stub_Orm) + )); + foreach (array('Trixie', 'Tinkerbell') as $name) + { $cur = $this->object->current(); $this->assertEquals($name, $cur->row['name']); $this->assertArrayHasKey('tester', $cur->cached); - + $this->assertEquals($name.'1', $cur->cached['tester']->row['name']); $this->assertArrayHasKey('another', $cur->cached['tester']->cached); $this->assertEquals($name.'2', $cur->cached['tester']->cached['another']->row['name']); $this->object->next(); } } - public function test_withArray(){ - $this->stub->data=array( - (object) array('id' => 1, 'name' => 'Trixie','id1'=>11,'name1'=>'Trixie1','id2'=>12,'name2'=>'Trixie2'), - (object) array('id' => 1, 'name' => 'Tinkerbell','id1'=>11,'name1'=>'Tinkerbell1','id2'=>12,'name2'=>'Tinkerbell2') - ); + + public function test_withArray() + { + $this->stub->data = array( + (object) array('id' => 1, 'name' => 'Trixie', 'id1' => 11, 'name1' => 'Trixie1', 'id2' => 12, 'name2' => 'Trixie2'), + (object) array('id' => 1, 'name' => 'Tinkerbell', 'id1' => 11, 'name1' => 'Tinkerbell1', 'id2' => 12, 'name2' => 'Tinkerbell2') + ); $this->object = new Result_ORM('Stub_Orm', $this->stub, array( - 'tester' => array('model' => new Stub_Orm), - 'tester.another' => array('model' => new Stub_Orm) - )); + 'tester' => array('model' => new Stub_Orm), + 'tester.another' => array('model' => new Stub_Orm) + )); $arr = $this->object->as_array(true); - foreach(array('Trixie', 'Tinkerbell') as $key=>$name) { + foreach (array('Trixie', 'Tinkerbell') as $key => $name) + { $this->assertArrayHasKey($key, $arr); $this->assertEquals($name, $arr[$key]->name); $this->assertEquals($name.'1', $arr[$key]->tester->name); $this->assertEquals($name.'2', $arr[$key]->tester->another->name); } } + } diff --git a/tests/modules/orm/ormTest.php b/tests/modules/orm/ormTest.php index f6b4b6a..ca85182 100644 --- a/tests/modules/orm/ormTest.php +++ b/tests/modules/orm/ormTest.php @@ -1,158 +1,160 @@ <?php + require_once('/../../../modules/orm/classes/orm.php'); require_once('/files/tree_orm.php'); require_once('/files/fairy_orm.php'); + /** * Generated by PHPUnit_SkeletonGenerator on 2013-02-08 at 21:28:15. */ class ORMTest extends PHPUnit_Framework_TestCase { - /** - * @var ORM - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - file_put_contents(dirname(__FILE__).'./files/test.sqlite',''); + + /** + * @var ORM + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + file_put_contents(dirname(__FILE__).'./files/test.sqlite', ''); $db = new PDO('sqlite:'.dirname(__FILE__).'./files/test.sqlite'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->exec("CREATE TABLE fairies(id INT PRIMARY_KEY,name VARCHAR(255),tree_id INT)"); $db->exec("CREATE TABLE trees(id INT PRIMARY_KEY,name VARCHAR(255),protector_id INT)"); $db->exec("CREATE TABLE friends(fairy_id INT,friend_id INT)"); - + $db->exec("INSERT INTO fairies(id,name,tree_id) VALUES (1,'Tinkerbell',1)"); $db->exec("INSERT INTO fairies(id,name,tree_id) VALUES (2,'Trixie',2)"); - + $db->exec("INSERT INTO trees(id,name,protector_id) VALUES (1,'Oak',2)"); $db->exec("INSERT INTO trees(id,name,protector_id) VALUES (2,'Willow',2)"); - + $db->exec("INSERT INTO friends(fairy_id,friend_id) VALUES (1,2)"); - - + + Misc::$file = dirname(__FILE__).'./files/config.php'; file_put_contents(Misc::$file, "<?php return ".var_export(array( - 'orm' => array( - 'connection' => 'sqlite:'.dirname(__FILE__).'./files/test.sqlite', - 'driver'=>'pdo' - ) - ), true).';'); + 'orm' => array( + 'connection' => 'sqlite:'.dirname(__FILE__).'./files/test.sqlite', + 'driver' => 'pdo' + ) + ), true).';'); Config::set('database.orm.connection', 'sqlite:'.dirname(__FILE__).'./files/test.sqlite'); - Config::set('database.orm.driver','pdo'); - - $this->fairies = new Fairy_Model; + Config::set('database.orm.driver', 'pdo'); + + $this->fairies = new Fairy_Model; $this->trees = new Tree_Model; - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - - } - - /** - * @covers ORM::__call - * @todo Implement test__call(). - */ - public function test__call() - { - $this->fairies->limit(6); - $this->fairies->offset(5); - $this->assertEquals(6, $this->fairies->limit()); - $this->assertEquals(5, $this->fairies->offset()); - $this->fairies->where('id', 8); - $this->fairies->order_by('id', 'desc'); - - } - - /** - * @covers ORM::find_all - * @todo Implement testFind_all(). - */ - public function testFind_all() - { - - $this->assertEquals('Trixie',ORM::factory('fairy')->where('id',2)->find_all()->current()->name); - } - - /** - * @covers ORM::find - * @todo Implement testFind(). - */ - public function testFind() - { - $this->assertEquals('Trixie',$this->fairies->where('id',2)->find()->name); - } - - /** - * @covers ORM::count_all - * @todo Implement testCount_all(). - */ - public function testCount_all() - { - $this->assertEquals(2, $this->fairies->count_all()); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + + } + + /** + * @covers ORM::__call + * @todo Implement test__call(). + */ + public function test__call() + { + $this->fairies->limit(6); + $this->fairies->offset(5); + $this->assertEquals(6, $this->fairies->limit()); + $this->assertEquals(5, $this->fairies->offset()); + $this->fairies->where('id', 8); + $this->fairies->order_by('id', 'desc'); + } + + /** + * @covers ORM::find_all + * @todo Implement testFind_all(). + */ + public function testFind_all() + { + + $this->assertEquals('Trixie', ORM::factory('fairy')->where('id', 2)->find_all()->current()->name); + } + + /** + * @covers ORM::find + * @todo Implement testFind(). + */ + public function testFind() + { + $this->assertEquals('Trixie', $this->fairies->where('id', 2)->find()->name); + } + + /** + * @covers ORM::count_all + * @todo Implement testCount_all(). + */ + public function testCount_all() + { + $this->assertEquals(2, $this->fairies->count_all()); $this->assertEquals(0, $this->fairies->find()->protects->count_all()); $this->assertEquals(1, $this->fairies->where('id', 2)->count_all()); $this->assertEquals(2, ORM::factory('fairy')->where('id', 2)->protects->count_all()); - } - - /** - * @covers ORM::loaded - * @todo Implement testLoaded(). - */ - public function testLoaded() - { - $this->assertEquals(false,$this->fairies->loaded()); - $this->assertEquals(true,$this->fairies->find()->loaded()); - } - - /** - * @covers ORM::as_array - * @todo Implement testAs_array(). - */ - public function testAs_array() - { - $arr = $this->fairies->find()->as_array(); - $this->assertEquals('Tinkerbell',$arr['name']); - } - - /** - * @covers ORM::query - * @todo Implement testQuery(). - */ - public function testQuery() - { - $this->fairies->limit(5); - $this->assertEquals(5,$this->fairies->query()->limit()); - } - - /** - * @covers ORM::get - * @todo Implement testGet(). - */ - public function testGet() - { + } + + /** + * @covers ORM::loaded + * @todo Implement testLoaded(). + */ + public function testLoaded() + { + $this->assertEquals(false, $this->fairies->loaded()); + $this->assertEquals(true, $this->fairies->find()->loaded()); + } + + /** + * @covers ORM::as_array + * @todo Implement testAs_array(). + */ + public function testAs_array() + { + $arr = $this->fairies->find()->as_array(); + $this->assertEquals('Tinkerbell', $arr['name']); + } + + /** + * @covers ORM::query + * @todo Implement testQuery(). + */ + public function testQuery() + { + $this->fairies->limit(5); + $this->assertEquals(5, $this->fairies->query()->limit()); + } + + /** + * @covers ORM::get + * @todo Implement testGet(). + */ + public function testGet() + { $dd = array('fff' => 44); - $fairy = $this->fairies->find(); + $fairy = $this->fairies->find(); $fairy->test; - $this->assertEquals(5,$fairy->cached['test']); - } - - /** - * @covers ORM::__get - * @todo Implement test__get(). - */ - public function test__get() - { - $this->assertEquals('Oak', $this->fairies->tree-> find_all()->current()->name); + $this->assertEquals(5, $fairy->cached['test']); + } + + /** + * @covers ORM::__get + * @todo Implement test__get(). + */ + public function test__get() + { + $this->assertEquals('Oak', $this->fairies->tree->find_all()->current()->name); $this->assertEquals('Oak', $this->fairies->find()->tree->name); $this->assertEquals('Tinkerbell', $this->trees->find()->fairy->name); $this->assertEquals('Tinkerbell', $this->trees->find()->fairy->name); @@ -163,174 +165,172 @@ class ORMTest extends PHPUnit_Framework_TestCase $this->assertEquals('Trixie', $this->trees->protector->find()->name); $this->assertEquals('Trixie', ORM::factory('fairy')->find()->friends->find()->name); - - } + } /** - * @covers ORM::add - * @todo Implement testAdd(). - */ - public function testAdd() - { - $fairy = ORM::factory('fairy')->find(); + * @covers ORM::add + * @todo Implement testAdd(). + */ + public function testAdd() + { + $fairy = ORM::factory('fairy')->find(); $fairy->add('tree', ORM::factory('tree')->where('id', 2)->find()); $fairy->save(); - $this->assertEquals('Willow', ORM::factory('fairy')->find()->tree-> name); - + $this->assertEquals('Willow', ORM::factory('fairy')->find()->tree->name); + $fairy = ORM::factory('fairy'); $fairy->add('tree', ORM::factory('tree')->where('id', 2)->find()); - $fairy->id=3; + $fairy->id = 3; $fairy->save(); $fairy = ORM::factory('fairy', 3); $this->assertEquals('Willow', $fairy->tree->name); - - $tree=ORM::factory('tree')->find(); - $fairy=ORM::factory('fairy'); - $tree-> fairy = $fairy; + + $tree = ORM::factory('tree')->find(); + $fairy = ORM::factory('fairy'); + $tree->fairy = $fairy; $fairy->id = 4; $fairy->save(); - $this->assertEquals('Oak', ORM::factory('fairy',4)->tree->name); - - - $fairy = ORM::factory('fairy')->where('id',2)->find(); - $fairy->add('friends',ORM::factory('fairy')->where('id', 1)->find()); - $this->assertEquals('Tinkerbell',ORM::factory('fairy')->where('id',2)->find()->friends->find()->name); - } - - /** - * @covers ORM::__set - * @todo Implement test__set(). - */ - public function test__set() - { - $fairy = $this->fairies->find(); + $this->assertEquals('Oak', ORM::factory('fairy', 4)->tree->name); + + + $fairy = ORM::factory('fairy')->where('id', 2)->find(); + $fairy->add('friends', ORM::factory('fairy')->where('id', 1)->find()); + $this->assertEquals('Tinkerbell', ORM::factory('fairy')->where('id', 2)->find()->friends->find()->name); + } + + /** + * @covers ORM::__set + * @todo Implement test__set(). + */ + public function test__set() + { + $fairy = $this->fairies->find(); $fairy->name = 'test'; $this->assertEquals('test', $fairy->name); - - $fairy = ORM::factory('fairy')->where('id',2)->find(); + + $fairy = ORM::factory('fairy')->where('id', 2)->find(); $fairy->friends = ORM::factory('fairy')->where('id', 1)->find(); - $this->assertEquals('Tinkerbell', ORM::factory('fairy')->where('id',2)->find()->friends->find()->name); - - ORM::factory('tree')->where('id',2)->find()->fairy = ORM::factory('fairy')->find(); + $this->assertEquals('Tinkerbell', ORM::factory('fairy')->where('id', 2)->find()->friends->find()->name); + + ORM::factory('tree')->where('id', 2)->find()->fairy = ORM::factory('fairy')->find(); ORM::factory('tree')->find()->fairy = ORM::factory('fairy')->where('id', 2)->find(); - + $this->assertEquals('Trixie', ORM::factory('tree')->find()->fairy->name); - } - - - /** - * @covers ORM::remove - * @todo Implement testRemove(). - */ - public function testRemove() - { - $fairy = ORM::factory('fairy')->find(); - $fairy->remove('tree'); - - $this->assertEquals(false, $fairy->tree->loaded()); - - $fairy->remove('friends', ORM::factory('fairy')->where('id', 2)->find()); - $this->assertEquals(false, $fairy->friends->find()->loaded()); - - $fairy = ORM::factory('fairy')->where('id',2)->find(); - $fairy->remove('protects',ORM::factory('tree')->where('id',1)->find()); - $this->assertEquals('Willow', $fairy->protects->find()->name); - - } - - /** - * @covers ORM::columns - * @todo Implement testColumns(). - */ - public function testColumns() - { - $cols=$this->fairies->columns(); - $this->assertEquals('id', $cols[0]); + } + + /** + * @covers ORM::remove + * @todo Implement testRemove(). + */ + public function testRemove() + { + $fairy = ORM::factory('fairy')->find(); + $fairy->remove('tree'); + + $this->assertEquals(false, $fairy->tree->loaded()); + + $fairy->remove('friends', ORM::factory('fairy')->where('id', 2)->find()); + $this->assertEquals(false, $fairy->friends->find()->loaded()); + + $fairy = ORM::factory('fairy')->where('id', 2)->find(); + $fairy->remove('protects', ORM::factory('tree')->where('id', 1)->find()); + $this->assertEquals('Willow', $fairy->protects->find()->name); + } + + /** + * @covers ORM::columns + * @todo Implement testColumns(). + */ + public function testColumns() + { + $cols = $this->fairies->columns(); + $this->assertEquals('id', $cols[0]); $this->assertEquals('name', $cols[1]); - $this->assertEquals('tree_id',$cols[2]); - } - - /** - * @covers ORM::with - * @todo Implement testWith(). - */ - public function testWith() - { - $res = $this->fairies->with('tree', 'tree.protector')->find(); + $this->assertEquals('tree_id', $cols[2]); + } + + /** + * @covers ORM::with + * @todo Implement testWith(). + */ + public function testWith() + { + $res = $this->fairies->with('tree', 'tree.protector')->find(); $this->assertEquals('Oak', $res->cached['tree']->name); - $this->assertEquals('Trixie',$res->cached['tree']->cached['protector']->name); - } - - /** - * @covers ORM::delete - * @todo Implement testDelete(). - */ - public function testDelete() - { - $this->fairies->find()->delete(); - $this->assertEquals('Trixie',$this->fairies->find()->name); - } - + $this->assertEquals('Trixie', $res->cached['tree']->cached['protector']->name); + } + /** - * @covers ORM::delete - * @todo Implement testDelete(). - */ - public function testDeleteException() - { + * @covers ORM::delete + * @todo Implement testDelete(). + */ + public function testDelete() + { + $this->fairies->find()->delete(); + $this->assertEquals('Trixie', $this->fairies->find()->name); + } + + /** + * @covers ORM::delete + * @todo Implement testDelete(). + */ + public function testDeleteException() + { $except = false; - try{ + try { $this->fairies->delete(); - }catch (Exception $e) { - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals(true,$except); - } - - /** - * @covers ORM::delete_all - * @todo Implement testDelete_all(). - */ - public function testDelete_all() - { - $this->fairies->delete_all(); - $this->assertEquals(false,$this->fairies->find()->loaded()); - } - - /** - * @covers ORM::save - * @todo Implement testSave(). - */ - public function testSave() - { - $fairy = $this->fairies->find(); + $this->assertEquals(true, $except); + } + + /** + * @covers ORM::delete_all + * @todo Implement testDelete_all(). + */ + public function testDelete_all() + { + $this->fairies->delete_all(); + $this->assertEquals(false, $this->fairies->find()->loaded()); + } + + /** + * @covers ORM::save + * @todo Implement testSave(). + */ + public function testSave() + { + $fairy = $this->fairies->find(); $fairy->name = 'test'; $fairy->save(); $this->assertEquals('test', $this->fairies->find()->name); - + $fairy = ORM::factory('fairy'); $fairy->name = 'test2'; $fairy->id = 3; $fairy->save(); - $this->assertEquals('test2', $this->fairies->order_by('id','desc')->find()->name); - } - - /** - * @covers ORM::values - * @todo Implement testValues(). - */ - public function testValues() - { - $fairy = $this->fairies->find(); - $fairy->values(array('id' => 1, 'name' => 'Trixie')); - $this->assertEquals('Trixie',$fairy->name); - } - - /** - * @covers ORM::factory - * @todo Implement testFactory(). - */ - public function testFactory() - { - $this->assertEquals('fairy',ORM::factory('fairy')->model_name); - } + $this->assertEquals('test2', $this->fairies->order_by('id', 'desc')->find()->name); + } + + /** + * @covers ORM::values + * @todo Implement testValues(). + */ + public function testValues() + { + $fairy = $this->fairies->find(); + $fairy->values(array('id' => 1, 'name' => 'Trixie')); + $this->assertEquals('Trixie', $fairy->name); + } + + /** + * @covers ORM::factory + * @todo Implement testFactory(). + */ + public function testFactory() + { + $this->assertEquals('fairy', ORM::factory('fairy')->model_name); + } + } diff --git a/tests/system/configTest.php b/tests/system/configTest.php index c52b727..1ea13f7 100644 --- a/tests/system/configTest.php +++ b/tests/system/configTest.php @@ -1,87 +1,90 @@ <?php -require_once("mocks/misc.php"); + +require_once("mocks/misc.php"); require_once('/../../system/classes/config.php'); + /** * Generated by PHPUnit_SkeletonGenerator on 2013-02-06 at 09:17:25. */ class configTest extends PHPUnit_Framework_TestCase { - /** - * @var Config - */ - protected $object; - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - Misc::$file = (dirname(__FILE__).'/files/config.php'); + /** + * @var Config + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + Misc::$file = (dirname(__FILE__).'/files/config.php'); file_put_contents(Misc::$file, "<?php return ".var_export(array( - 'trees' => array( - 'oak' => array( - 'fairy'=>'Tinkerbell' + 'trees' => array( + 'oak' => array( + 'fairy' => 'Tinkerbell' + ) ) - ) - ),true).';'); - } + ), true).';'); + } - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { - /** - * @covers Config::get_group - * @todo Implement testGet_group(). - */ - public function testGet_group() - { + } + + /** + * @covers Config::get_group + * @todo Implement testGet_group(). + */ + public function testGet_group() + { $group = Config::get_group('test'); $this->assertArrayHasKey('trees', $group); $this->assertArrayHasKey('oak', $group['trees']); $this->assertArrayHasKey('fairy', $group['trees']['oak']); $this->assertEquals($group['trees']['oak']['fairy'], 'Tinkerbell'); - } + } - /** - * @covers Config::get - * @todo Implement testGet(). - */ - public function testGet() - { - $this->assertEquals(Config::get('test.trees.oak.fairy'), 'Tinkerbell'); - $this->assertEquals(Config::get('test.trees.oak.fairies','default'),'default'); - } + /** + * @covers Config::get + * @todo Implement testGet(). + */ + public function testGet() + { + $this->assertEquals(Config::get('test.trees.oak.fairy'), 'Tinkerbell'); + $this->assertEquals(Config::get('test.trees.oak.fairies', 'default'), 'default'); + } - /** - * @covers Config::set - * @todo Implement testSet(). - */ - public function testSet() - { - Config::set('test.trees.oak.second_fairy', 'Trixie'); - $this->assertEquals(Config::get('test.trees.oak.second_fairy'),'Trixie'); - - } + /** + * @covers Config::set + * @todo Implement testSet(). + */ + public function testSet() + { + Config::set('test.trees.oak.second_fairy', 'Trixie'); + $this->assertEquals(Config::get('test.trees.oak.second_fairy'), 'Trixie'); + } - /** - * @covers Config::write - * @todo Implement testWrite(). - */ - public function testWrite() - { - Config::set('test.trees.oak.second_fairy', 'Trixie'); + /** + * @covers Config::write + * @todo Implement testWrite(). + */ + public function testWrite() + { + Config::set('test.trees.oak.second_fairy', 'Trixie'); Config::write('test'); $group = include(Misc::$file); $this->assertArrayHasKey('trees', $group); $this->assertArrayHasKey('oak', $group['trees']); $this->assertArrayHasKey('second_fairy', $group['trees']['oak']); $this->assertEquals($group['trees']['oak']['second_fairy'], 'Trixie'); - - } + } + } diff --git a/tests/system/controllerTest.php b/tests/system/controllerTest.php index 1a83f97..209ef06 100644 --- a/tests/system/controllerTest.php +++ b/tests/system/controllerTest.php @@ -1,42 +1,44 @@ <?php + require_once('/../../system/classes/response.php'); require_once('/../../system/classes/controller.php'); require_once('mocks/testController.php'); + /** * Generated by PHPUnit_SkeletonGenerator on 2013-02-05 at 16:39:57. */ class ControllerTest extends PHPUnit_Framework_TestCase { - /** - * @var Controller - */ - protected $object; - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - $this->object = new Test_Controller; - } + /** + * @var Controller + */ + protected $object; - - public function testRun() - { - $this->object->run('index'); - $this->assertEquals($this->object->counter,3); - } - + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + $this->object = new Test_Controller; + } + + public function testRun() + { + $this->object->run('index'); + $this->assertEquals($this->object->counter, 3); + } public function testException() - { - $except=false; - try{ + { + $except = false; + try { $this->object->run('bogus'); - }catch(Exception $e){ - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals($except,true); - } + $this->assertEquals($except, true); + } + } diff --git a/tests/system/files/config.php b/tests/system/files/config.php index d2a88aa..1361a11 100644 --- a/tests/system/files/config.php +++ b/tests/system/files/config.php @@ -1,11 +1,12 @@ <?php -return array ( - 'trees' => - array ( - 'oak' => - array ( - 'fairy' => 'Tinkerbell', - 'second_fairy' => 'Trixie', - ), - ), + +return array( + 'trees' => + array( + 'oak' => + array( + 'fairy' => 'Tinkerbell', + 'second_fairy' => 'Trixie', + ), + ), );
\ No newline at end of file diff --git a/tests/system/mocks/misc.php b/tests/system/mocks/misc.php index 12019a2..dd66b14 100644 --- a/tests/system/mocks/misc.php +++ b/tests/system/mocks/misc.php @@ -1,15 +1,23 @@ <?php + /** * Mock class for Misc */ -class Misc{ +class Misc +{ + public static $file; - public static function arr($array,$key,$default=null){ + + public static function arr($array, $key, $default = null) + { if (isset($array[$key])) return $array[$key]; return $default; } - public static function find_file(){ + + public static function find_file() + { return static::$file; } + }
\ No newline at end of file diff --git a/tests/system/mocks/testController.php b/tests/system/mocks/testController.php index 726220c..3024218 100644 --- a/tests/system/mocks/testController.php +++ b/tests/system/mocks/testController.php @@ -1,13 +1,23 @@ <?php
-class Test_Controller extends Controller {
+
+class Test_Controller extends Controller
+{
+
public $counter = 0;
- public function before() {
+
+ public function before()
+ {
$this->counter++;
}
- public function after() {
+
+ public function after()
+ {
$this->counter++;
}
- public function action_index() {
+
+ public function action_index()
+ {
$this->counter++;
}
-}
\ No newline at end of file +
+}
diff --git a/tests/system/requestTest.php b/tests/system/requestTest.php index 2193533..e202d96 100644 --- a/tests/system/requestTest.php +++ b/tests/system/requestTest.php @@ -1,117 +1,123 @@ <?php + require_once('/../../system/classes/request.php'); require_once('/../../system/classes/route.php'); + /** * Generated by PHPUnit_SkeletonGenerator on 2013-02-06 at 16:12:22. */ class requestTest extends PHPUnit_Framework_TestCase { - /** - * @var Request - */ - protected $object; - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - $route=(object)array('params'=>array('controller'=>'test','action'=>'index','fairy_param'=>'Trixie')); - $this->object = new Request($route,'GET',array('fairy_post'=>'Trixie'),array('fairy_get'=>'Trixie'),array('fairy_server'=>'Trixie')); - } + /** + * @var Request + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + $route = (object) array('params' => array('controller' => 'test', 'action' => 'index', 'fairy_param' => 'Trixie')); + $this->object = new Request($route, 'GET', array('fairy_post' => 'Trixie'), array('fairy_get' => 'Trixie'), array('fairy_server' => 'Trixie')); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + + } - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } + /** + * @covers Request::get + * @todo Implement testGet(). + */ + public function testGet() + { + $this->assertEquals($this->object->get('fairy_get'), 'Trixie'); + $this->assertEquals($this->object->get('bogus', 'default'), 'default'); + } - /** - * @covers Request::get - * @todo Implement testGet(). - */ - public function testGet() - { - $this->assertEquals($this->object->get('fairy_get'), 'Trixie'); - $this->assertEquals($this->object->get('bogus','default'),'default'); - } + /** + * @covers Request::post + * @todo Implement testPost(). + */ + public function testPost() + { + $this->assertEquals($this->object->post('fairy_post'), 'Trixie'); + $this->assertEquals($this->object->post('bogus', 'default'), 'default'); + } - /** - * @covers Request::post - * @todo Implement testPost(). - */ - public function testPost() - { - $this->assertEquals($this->object->post('fairy_post'), 'Trixie'); - $this->assertEquals($this->object->post('bogus','default'),'default'); - } + /** + * @covers Request::server + * @todo Implement testServer(). + */ + public function testServer() + { + $this->assertEquals($this->object->server('fairy_server'), 'Trixie'); + $this->assertEquals($this->object->server('bogus', 'default'), 'default'); + } - /** - * @covers Request::server - * @todo Implement testServer(). - */ - public function testServer() - { - $this->assertEquals($this->object->server('fairy_server'), 'Trixie'); - $this->assertEquals($this->object->server('bogus','default'),'default'); - } + /** + * @covers Request::param + * @todo Implement testParam(). + */ + public function testParam() + { + $this->assertEquals($this->object->param('fairy_param'), 'Trixie'); + $this->assertEquals($this->object->param('bogus', 'default'), 'default'); + } - /** - * @covers Request::param - * @todo Implement testParam(). - */ - public function testParam() - { - $this->assertEquals($this->object->param('fairy_param'), 'Trixie'); - $this->assertEquals($this->object->param('bogus','default'),'default'); - } + /** + * @covers Request::execute + * @todo Implement testExecute(). + */ + public function testExecute() + { + $this->object->execute(); + } - /** - * @covers Request::execute - * @todo Implement testExecute(). - */ - public function testExecute() - { - $this->object->execute(); - } - /** - * @covers Request::execute - * @todo Implement testExecute(). - */ - public function testExecuteException() - { - $route=(object)array('params'=>array('controller'=>'bogus','action'=>'bogus')); - $req = new Request($route); + * @covers Request::execute + * @todo Implement testExecute(). + */ + public function testExecuteException() + { + $route = (object) array('params' => array('controller' => 'bogus', 'action' => 'bogus')); + $req = new Request($route); $except = false; - try{ + try { $req->execute(); - }catch (Exception $e) { - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals($except,true); - } - /** - * @covers Request::create - * @todo Implement testGetURI(). - */ - public function testCreate() - { - Route::add('default','/<controller>/<action>'); - Config::set('core.basepath','/tester/'); + $this->assertEquals($except, true); + } + + /** + * @covers Request::create + * @todo Implement testGetURI(). + */ + public function testCreate() + { + Route::add('default', '/<controller>/<action>'); + Config::set('core.basepath', '/tester/'); $_SERVER['REQUEST_URI'] = "/tester/home/index"; $_POST['post'] = "test"; $_GET['get'] = "test"; $_SERVER['REQUEST_METHOD'] = "POST"; - $req = Request::create(); + $req = Request::create(); $this->assertEquals($req->get('get'), 'test'); $this->assertEquals($req->post('post'), 'test'); $this->assertEquals($req->server('REQUEST_METHOD'), 'POST'); $this->assertEquals($req->method, 'POST'); $this->assertEquals($req->param('controller'), 'home'); $this->assertEquals($req->param('action'), 'index'); - } + } + } diff --git a/tests/system/responseTest.php b/tests/system/responseTest.php index b80cf2e..76e4dd4 100644 --- a/tests/system/responseTest.php +++ b/tests/system/responseTest.php @@ -1,62 +1,66 @@ <?php + /** * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013 - 02 - 05 at 23:08:34. */ class ResponseTest extends PHPUnit_Framework_TestCase { - /** - * @var Response - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - $this->object = new Response; - } - - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } - - /** - * @covers Response::add_header - * @todo Implement testAdd_header(). - */ - public function testAdd_header() - { - $this->object->add_header('test'); - $this->assertEquals(end($this->object->headers),'test'); - } - - /** - * @covers Response::redirect - * @todo Implement testRedirect(). - */ - public function testRedirect() - { - $this->object->redirect('http://google.com'); - $this->assertContains('Location: http://google.com',$this->object->headers); - } - - /** - * @covers Response::send_body - * @todo Implement testSend_body(). - */ - public function testSend_body() - { - $this->object->body = 'test'; + + /** + * @var Response + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + $this->object = new Response; + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + + } + + /** + * @covers Response::add_header + * @todo Implement testAdd_header(). + */ + public function testAdd_header() + { + $this->object->add_header('test'); + $this->assertEquals(end($this->object->headers), 'test'); + } + + /** + * @covers Response::redirect + * @todo Implement testRedirect(). + */ + public function testRedirect() + { + $this->object->redirect('http://google.com'); + $this->assertContains('Location: http://google.com', $this->object->headers); + } + + /** + * @covers Response::send_body + * @todo Implement testSend_body(). + */ + public function testSend_body() + { + $this->object->body = 'test'; ob_start(); $this->object->send_body(); $out = ob_get_contents(); ob_end_clean(); - $this->assertEquals($out,'test'); - } + $this->assertEquals($out, 'test'); + } + } diff --git a/tests/system/routeTest.php b/tests/system/routeTest.php index dc22931..84e846c 100644 --- a/tests/system/routeTest.php +++ b/tests/system/routeTest.php @@ -1,124 +1,130 @@ <?php + /** * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-02-10 at 16:36:42. */ class RoteTest extends PHPUnit_Framework_TestCase { - /** - * @var Route - */ - protected $object; - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - - } + /** + * @var Route + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { - } + } - /** - * @covers Route::get - * @todo Implement testGet(). - */ - public function testGet() - { - $except = false; + /** + * @covers Route::get + * @todo Implement testGet(). + */ + public function testGet() + { + $except = false; Route::add('a', 'b', array()); try { Route::get('c'); - }catch (Exception $e) { - $except=true; + } catch (Exception $e) { + $except = true; } - $this->assertEquals(true,$except); - } + $this->assertEquals(true, $except); + } - /** - * @covers Route::match - * @todo Implement testMatch(). - */ - public function testMatchFunc() - { - Route::add('func', function() { return array('action' => 'index'); }, array('controller' => 'home')); + /** + * @covers Route::match + * @todo Implement testMatch(). + */ + public function testMatchFunc() + { + Route::add('func', function() { + return array('action' => 'index'); + }, array('controller' => 'home')); $route = Route::match('/test'); $this->assertEquals('func', $route->name); - $this->assertEquals('index', $route-> params['action']); - $this->assertEquals('home',$route->params['controller']); - } - + $this->assertEquals('index', $route->params['action']); + $this->assertEquals('home', $route->params['controller']); + } + /** - * @covers Route::match - * @todo Implement testMatch(). - */ - public function testMatchDefault() - { - Route::add('default', '(/<controller>(/<action>(/<id>)))', array( - 'controller' => 'home', - 'action' => 'index' - )); + * @covers Route::match + * @todo Implement testMatch(). + */ + public function testMatchDefault() + { + Route::add('default', '(/<controller>(/<action>(/<id>)))', array( + 'controller' => 'home', + 'action' => 'index' + )); $route = Route::match('/'); $this->assertEquals('default', $route->name); - $this->assertEquals('index', $route-> params['action']); - $this->assertEquals('home', $route-> params['controller']); - + $this->assertEquals('index', $route->params['action']); + $this->assertEquals('home', $route->params['controller']); + $route = Route::match('/test'); $this->assertEquals('default', $route->name); - $this->assertEquals('index', $route-> params['action']); - $this->assertEquals('test', $route-> params['controller']); - + $this->assertEquals('index', $route->params['action']); + $this->assertEquals('test', $route->params['controller']); + $route = Route::match('/test/act'); $this->assertEquals('default', $route->name); - $this->assertEquals('act', $route-> params['action']); - $this->assertEquals('test', $route-> params['controller']); - + $this->assertEquals('act', $route->params['action']); + $this->assertEquals('test', $route->params['controller']); + $route = Route::match('/test/act/8'); $this->assertEquals('default', $route->name); - $this->assertEquals('act', $route-> params['action']); - $this->assertEquals('test', $route-> params['controller']); - $this->assertEquals(8,$route->params['id']); - } - + $this->assertEquals('act', $route->params['action']); + $this->assertEquals('test', $route->params['controller']); + $this->assertEquals(8, $route->params['id']); + } + /** - * @covers Route::match - * @todo Implement testMatch(). - */ - public function testMatchCustom() - { - Route::add('default', array('/<alpha><num>', array( - 'alpha' => '[a-z]*', - 'num' => '[0-9]*' - )), array( - 'controller' => 'home', - 'action' => 'index' - )); + * @covers Route::match + * @todo Implement testMatch(). + */ + public function testMatchCustom() + { + Route::add('default', array('/<alpha><num>', array( + 'alpha' => '[a-z]*', + 'num' => '[0-9]*' + )), array( + 'controller' => 'home', + 'action' => 'index' + )); $route = Route::match('/test123'); $this->assertEquals('default', $route->name); - $this->assertEquals('index', $route-> params['action']); - $this->assertEquals('home', $route-> params['controller']); - $this->assertEquals('test', $route-> params['alpha']); - $this->assertEquals(123,$route->params['num']); - } - + $this->assertEquals('index', $route->params['action']); + $this->assertEquals('home', $route->params['controller']); + $this->assertEquals('test', $route->params['alpha']); + $this->assertEquals(123, $route->params['num']); + } + /** - * @covers Route::url - */ - public function testUrl() - { - Route::add('url', '(/<controller>(/<action>(/<id>)))', array( - 'controller' => 'home', - 'action' => 'index' - )); + * @covers Route::url + */ + public function testUrl() + { + Route::add('url', '(/<controller>(/<action>(/<id>)))', array( + 'controller' => 'home', + 'action' => 'index' + )); $route = Route::get('url'); - $this->assertEquals('/home/index/5', $route-> url(array('id' => 5))); + $this->assertEquals('/home/index/5', $route->url(array('id' => 5))); $this->assertEquals('/home/index', $route->url()); - } + } + } diff --git a/tests/system/sessionTest.php b/tests/system/sessionTest.php index 2656a5a..2841208 100644 --- a/tests/system/sessionTest.php +++ b/tests/system/sessionTest.php @@ -1,91 +1,95 @@ <?php -require_once("mocks/misc.php"); + +require_once("mocks/misc.php"); require_once('/../../system/classes/session.php'); + /** * Generated by PHPUnit_SkeletonGenerator on 2013 - 02 - 06 at 08:47:19. * @runTestsInSeparateProcesses */ class sessionTest extends PHPUnit_Framework_TestCase { - /** - * @var Session - */ - protected $object; - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { + /** + * @var Session + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { //if(!session_id()) - //session_start(); - } + //session_start(); + } - /** - * Tears down the fixture, for example, closes a network connection. - * This method is called after a test is executed. - */ - protected function tearDown() - { + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { session_destroy(); - } + } - /** - * @covers Session::get - * @todo Implement testGet(). - */ - public function testGet() - { - session_start(); - $_SESSION['test']='TEST'; - $this->assertEquals(Session::get('test'), 'TEST'); - $this->assertEquals(Session::get('bogus',false),false); - } + /** + * @covers Session::get + * @todo Implement testGet(). + */ + public function testGet() + { + session_start(); + $_SESSION['test'] = 'TEST'; + $this->assertEquals(Session::get('test'), 'TEST'); + $this->assertEquals(Session::get('bogus', false), false); + } - /** - * @covers Session::set - * @todo Implement testSet(). - */ - public function testSet() - { - Session::set('testSet', 'test'); - $this->assertArrayHasKey('testSet', $_SESSION); - $this->assertEquals('test',$_SESSION['testSet']); - } + /** + * @covers Session::set + * @todo Implement testSet(). + */ + public function testSet() + { + Session::set('testSet', 'test'); + $this->assertArrayHasKey('testSet', $_SESSION); + $this->assertEquals('test', $_SESSION['testSet']); + } - /** - * @covers Session::remove - * @todo Implement testRemove(). - */ - public function testRemove() - { + /** + * @covers Session::remove + * @todo Implement testRemove(). + */ + public function testRemove() + { session_start(); - $_SESSION['test'] = 'TEST'; + $_SESSION['test'] = 'TEST'; Session::remove('test'); $this->assertEquals(false, isset($_SESSION['test'])); - } + } - /** - * @covers Session::reset - * @todo Implement testReset(). - */ - public function testReset() - { + /** + * @covers Session::reset + * @todo Implement testReset(). + */ + public function testReset() + { session_start(); - $_SESSION['test'] = 'TEST'; - Session::reset(); + $_SESSION['test'] = 'TEST'; + Session::reset(); $this->assertEquals(0, count($_SESSION)); - } - + } + /** - * @covers Session::flash - */ - public function testFlash() - { + * @covers Session::flash + */ + public function testFlash() + { Session::flash('test', 'Trixie'); Session::flash('test', 'Tinkerbell'); $this->assertEquals('Tinkerbell', Session::flash('test')); - $this->assertEquals(null,Session::flash('test')); - } + $this->assertEquals(null, Session::flash('test')); + } + } diff --git a/tests/system/viewTest.php b/tests/system/viewTest.php index 9528dc8..5e1eb84 100644 --- a/tests/system/viewTest.php +++ b/tests/system/viewTest.php @@ -1,45 +1,48 @@ <?php + /** * Generated by PHPUnit_SkeletonGenerator on 2013-02-05 at 09:23:37. */ -require_once("mocks/misc.php"); +require_once("mocks/misc.php"); include('/../../system/classes/view.php'); + class ViewTest extends PHPUnit_Framework_TestCase { - /** - * @var View - */ - protected $object; - - /** - * Sets up the fixture, for example, opens a network connection. - * This method is called before a test is executed. - */ - protected function setUp() - { - Misc::$file=(dirname(__FILE__).'/files/view.php'); - $this->object = View::get('view'); - } - - - /** - * @covers View::__set and View::__get - */ - public function test__set() - { - // Remove the following lines when you implement this test. - $this->object->fairy='Tinkerbell'; - $this->assertEquals($this->object->fairy,'Tinkerbell'); - } - - /** - * @covers View::render - */ - public function testRender() - { - - $this->object->fairy = 'Tinkerbell'; + + /** + * @var View + */ + protected $object; + + /** + * Sets up the fixture, for example, opens a network connection. + * This method is called before a test is executed. + */ + protected function setUp() + { + Misc::$file = (dirname(__FILE__).'/files/view.php'); + $this->object = View::get('view'); + } + + /** + * @covers View::__set and View::__get + */ + public function test__set() + { + // Remove the following lines when you implement this test. + $this->object->fairy = 'Tinkerbell'; + $this->assertEquals($this->object->fairy, 'Tinkerbell'); + } + + /** + * @covers View::render + */ + public function testRender() + { + + $this->object->fairy = 'Tinkerbell'; $out = $this->object->render(); - $this->assertEquals($this->object->fairy,'Tinkerbell'); - } + $this->assertEquals($this->object->fairy, 'Tinkerbell'); + } + } |