diff --git a/lib/Doctrine/Access.php b/lib/Doctrine/Access.php index f066e7f4a..91ca06d9e 100644 --- a/lib/Doctrine/Access.php +++ b/lib/Doctrine/Access.php @@ -20,23 +20,25 @@ */ /** - * Provides array access and property overload interface for Doctrine subclasses + * Provides array access and property overload interface for Doctrine subclasses. * - * @package Doctrine - * @subpackage Access * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Access extends Doctrine_Locator_Injectable implements ArrayAccess { /** - * Set an entire aray to the data + * Set an entire aray to the data. + * + * @param array $array An array of key => value pairs * - * @param array $array An array of key => value pairs - * @return Doctrine_Access + * @return Doctrine_Access */ public function setArray(array $array) { @@ -48,12 +50,9 @@ public function setArray(array $array) } /** - * Set key and value to data + * Set key and value to data. * * @see set, offsetSet - * @param $name - * @param $value - * @return void */ public function __set($name, $value) { @@ -61,11 +60,9 @@ public function __set($name, $value) } /** - * Get key from data + * Get key from data. * * @see get, offsetGet - * @param mixed $name - * @return mixed */ public function __get($name) { @@ -73,10 +70,11 @@ public function __get($name) } /** - * Check if key exists in data + * Check if key exists in data. * - * @param string $name - * @return boolean whether or not this object contains $name + * @param string $name + * + * @return bool whether or not this object contains $name */ public function __isset($name) { @@ -84,12 +82,11 @@ public function __isset($name) } /** - * Remove key from data + * Remove key from data. * - * @param string $name - * @return void + * @param string $name */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function __unset($name) { return $this->remove($name); @@ -98,16 +95,13 @@ public function __unset($name) /** * @return bool */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetExists($offset) { return $this->contains($offset); } - /** - * @return mixed - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetGet($offset) { // array notation with no index was causing 'undefined variable: $offset' notices in php7, @@ -116,84 +110,78 @@ public function offsetGet($offset) if (!isset($offset)) { return $this->get(null); } + return $this->get($offset); } - /** - * @return void - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetSet($offset, $value) { - if ( ! isset($offset)) { + if (!isset($offset)) { $this->add($value); } else { $this->set($offset, $value); } } - /** - * @return void - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetUnset($offset) { $this->remove($offset); } /** - * Remove the element with the specified offset + * Remove the element with the specified offset. * * @param mixed $offset The offset to remove + * * @return bool True if removed otherwise false */ public function remove($offset) { - throw new Doctrine_Exception('Remove is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Remove is not supported for '.get_class($this)); } /** - * Return the element with the specified offset + * Return the element with the specified offset. * - * @param mixed $offset The offset to return - * @return mixed + * @param mixed $offset The offset to return */ public function get($offset) { - throw new Doctrine_Exception('Get is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Get is not supported for '.get_class($this)); } /** - * Set the offset to the value + * Set the offset to the value. * * @param mixed $offset The offset to set - * @param mixed $value The value to set the offset to - * + * @param mixed $value The value to set the offset to */ public function set($offset, $value) { - throw new Doctrine_Exception('Set is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Set is not supported for '.get_class($this)); } /** - * Check if the specified offset exists + * Check if the specified offset exists. * * @param mixed $offset The offset to check - * @return boolean True if exists otherwise false + * + * @return bool True if exists otherwise false */ public function contains($offset) { - throw new Doctrine_Exception('Contains is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Contains is not supported for '.get_class($this)); } /** - * Add the value + * Add the value. * * @param mixed $value The value to add - * @return void */ public function add($value) { - throw new Doctrine_Exception('Add is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Add is not supported for '.get_class($this)); } } diff --git a/lib/Doctrine/Adapter/Exception.php b/lib/Doctrine/Adapter/Exception.php index 9fed8319c..f13ef4860 100644 --- a/lib/Doctrine/Adapter/Exception.php +++ b/lib/Doctrine/Adapter/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Adapter exception class + * Doctrine_Adapter exception class. * - * @package Doctrine - * @subpackage Adapter * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Adapter_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Adapter/Interface.php b/lib/Doctrine/Adapter/Interface.php index 73c322f1e..b79c46701 100644 --- a/lib/Doctrine/Adapter/Interface.php +++ b/lib/Doctrine/Adapter/Interface.php @@ -20,28 +20,39 @@ */ /** - * This adapter interface should be implemented by all custom adapters + * This adapter interface should be implemented by all custom adapters. * * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Adapter - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ interface Doctrine_Adapter_Interface { public function prepare($prepareString); + public function query($queryString); + public function quote($input); + public function exec($statement); + public function lastInsertId(); + public function beginTransaction(); + public function commit(); + public function rollBack(); + public function errorCode(); + public function errorInfo(); + public function setAttribute($attribute, $value); + public function getAttribute($attribute); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Adapter/Mock.php b/lib/Doctrine/Adapter/Mock.php index fddce61df..c1640d9fb 100644 --- a/lib/Doctrine/Adapter/Mock.php +++ b/lib/Doctrine/Adapter/Mock.php @@ -22,53 +22,52 @@ /** * Doctrine mock connection adapter. This class is used for special testing purposes. * - * @package Doctrine - * @subpackage Adapter * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Adapter_Mock implements Doctrine_Adapter_Interface, Countable { /** - * Name of the dbms to mock + * Name of the dbms to mock. * * @var string */ private $_name; /** - * Array of queries executed through this instance of the mock adapter + * Array of queries executed through this instance of the mock adapter. * - * @var array $queries + * @var array */ private $_queries = array(); /** - * Array of exceptions thrown + * Array of exceptions thrown. * - * @var array $exceptions + * @var array */ private $_exception = array(); /** - * Bool true/false variable for whether or not the last insert failed + * Bool true/false variable for whether or not the last insert failed. * - * @var boolean $lastInsertIdFail + * @var bool */ private $_lastInsertIdFail = false; /** - * Doctrine mock adapter constructor + * Doctrine mock adapter constructor. * * * $conn = new Doctrine_Adapter_Mock('mysql'); * * - * @param string $name - * @return void + * @param string $name */ public function __construct($name = null) { @@ -76,7 +75,7 @@ public function __construct($name = null) } /** - * Get the name of the dbms used in this instance of the mock adapter + * Get the name of the dbms used in this instance of the mock adapter. * * @return string $name Name of the dbms */ @@ -86,7 +85,7 @@ public function getName() } /** - * Pop the last executed query from the array of executed queries and return it + * Pop the last executed query from the array of executed queries and return it. * * @return string $sql Last executed sql string */ @@ -96,12 +95,11 @@ public function pop() } /** - * Force an exception in to the array of exceptions + * Force an exception in to the array of exceptions. * - * @param string $name Name of exception - * @param string $message Message for the exception - * @param integer $code Code of the exception - * @return void + * @param string $name Name of exception + * @param string $message Message for the exception + * @param int $code Code of the exception */ public function forceException($name, $message = '', $code = 0) { @@ -109,9 +107,10 @@ public function forceException($name, $message = '', $code = 0) } /** - * Prepare a query statement + * Prepare a query statement. + * + * @param string $query Query to prepare * - * @param string $query Query to prepare * @return Doctrine_Adapter_Statement_Mock $mock Mock prepared statement */ public function prepare($query) @@ -123,10 +122,9 @@ public function prepare($query) } /** - * Add query to the stack of executed queries + * Add query to the stack of executed queries. * - * @param string $query - * @return void + * @param string $query */ public function addQuery($query) { @@ -134,18 +132,19 @@ public function addQuery($query) } /** - * Fake the execution of query and add it to the stack of executed queries + * Fake the execution of query and add it to the stack of executed queries. + * + * @param string $query * - * @param string $query * @return Doctrine_Adapter_Statement_Mock $stmt */ public function query($query) { $this->_queries[] = $query; - $e = $this->_exception; + $e = $this->_exception; - if ( ! empty($e)) { + if (!empty($e)) { $name = $e[0]; $this->_exception = array(); @@ -160,7 +159,7 @@ public function query($query) } /** - * Get all the executed queries + * Get all the executed queries. * * @return array $queries Array of all executed queries */ @@ -170,29 +169,29 @@ public function getAll() } /** - * Quote a value for the dbms + * Quote a value for the dbms. + * + * @param string $input * - * @param string $input * @return string $quoted */ public function quote($input) { - return "'" . addslashes($input) . "'"; + return "'".addslashes($input)."'"; } /** - * Execute a raw sql statement + * Execute a raw sql statement. * - * @param string $statement - * @return void + * @param string $statement */ public function exec($statement) { $this->_queries[] = $statement; - $e = $this->_exception; + $e = $this->_exception; - if ( ! empty($e)) { + if (!empty($e)) { $name = $e[0]; $this->_exception = array(); @@ -204,10 +203,9 @@ public function exec($statement) } /** - * Force last insert to be failed + * Force last insert to be failed. * - * @param boolean $fail - * @return void + * @param bool $fail */ public function forceLastInsertIdFail($fail = true) { @@ -219,35 +217,33 @@ public function forceLastInsertIdFail($fail = true) } /** - * Get the id of the last inserted record + * Get the id of the last inserted record. * - * @return integer $id + * @return int $id */ public function lastInsertId() { $this->_queries[] = 'LAST_INSERT_ID()'; if ($this->_lastInsertIdFail) { return null; - } else { - return 1; } + + return 1; } /** - * Get the number of queries executed + * Get the number of queries executed. * - * @return integer $count + * @return int $count */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_queries); } /** - * Begin a transaction - * - * @return void + * Begin a transaction. */ public function beginTransaction() { @@ -255,9 +251,7 @@ public function beginTransaction() } /** - * Commit a transaction - * - * @return void + * Commit a transaction. */ public function commit() { @@ -265,9 +259,7 @@ public function commit() } /** - * Rollback a transaction - * - * @return void + * Rollback a transaction. */ public function rollBack() { @@ -276,20 +268,24 @@ public function rollBack() public function getAttribute($attribute) { - if ($attribute == Doctrine_Core::ATTR_DRIVER_NAME) { + if (Doctrine_Core::ATTR_DRIVER_NAME == $attribute) { return strtolower($this->_name); } } public function errorCode() - { } + { + } public function errorInfo() - { } + { + } public function setAttribute($attribute, $value) - { } + { + } public function sqliteCreateFunction() - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Adapter/Oracle.php b/lib/Doctrine/Adapter/Oracle.php index a820bec0c..40c014f88 100644 --- a/lib/Doctrine/Adapter/Oracle.php +++ b/lib/Doctrine/Adapter/Oracle.php @@ -20,34 +20,32 @@ */ /** - * Custom Doctrine connection adapter for oracle + * Custom Doctrine connection adapter for oracle. * - * @package Doctrine - * @subpackage Adapter * @author Konsta Vesterinen * @author vadik56 * @author Miloslav Kmet * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ - class Doctrine_Adapter_Oracle implements Doctrine_Adapter_Interface { /** - * execution mode + * execution mode. */ protected $executeMode = OCI_COMMIT_ON_SUCCESS; /** - * Resource representing connection to database + * Resource representing connection to database. */ protected $connection = false; - - protected $attributes = array(Doctrine_Core::ATTR_DRIVER_NAME => "oci8", - Doctrine_Core::ATTR_ERRMODE => Doctrine_Core::ERRMODE_SILENT); + protected $attributes = array(Doctrine_Core::ATTR_DRIVER_NAME => 'oci8', + Doctrine_Core::ATTR_ERRMODE => Doctrine_Core::ERRMODE_SILENT); /** * User-provided configuration. @@ -62,15 +60,15 @@ class Doctrine_Adapter_Oracle implements Doctrine_Adapter_Interface * @var array */ protected $config = array( - 'dbname' => null, - 'username' => null, - 'password' => null, - 'charset' => null, - 'persistent' => false + 'dbname' => null, + 'username' => null, + 'password' => null, + 'charset' => null, + 'persistent' => false, ); /** - * Doctrine Oracle adapter constructor + * Doctrine Oracle adapter constructor. * * * $conn = new Doctrine_Adapter_Oracle(array('dbname'=>'db','username'=>'usr','password'=>'pass')); @@ -82,17 +80,16 @@ class Doctrine_Adapter_Oracle implements Doctrine_Adapter_Interface * Doctrine_Manager::connection(array('oracle:dbname=SID;charset=NLS_CHARACTERSET;persistent=true','usr', 'pass'),"doctrine_connection_name") * * - * @param string $name - * @return void + * @param mixed|null $username + * @param mixed|null $password */ public function __construct($config = array(), $username = null, $password = null) { - if (is_string($config)) - { - $config = str_replace("oracle:","",$config); - $parts = explode(";", $config); - foreach($parts as $part) { - $e = explode("=", $part); + if (is_string($config)) { + $config = str_replace('oracle:', '', $config); + $parts = explode(';', $config); + foreach ($parts as $part) { + $e = explode('=', $part); $key = array_shift($e); $this->config[$key] = implode('=', $e); } @@ -104,54 +101,53 @@ public function __construct($config = array(), $username = null, $password = nul $this->config['password'] = $password; } } else { - if ( ! isset($config['password']) || ! isset($config['username'])) { + if (!isset($config['password']) || !isset($config['username'])) { throw new Doctrine_Adapter_Exception('config array must have at least a username and a password'); } $this->config['username'] = $config['username']; $this->config['password'] = $config['password']; - $this->config['dbname'] = $config['dbname']; - - if (isset($config['charset'])) { - $this->config['charset'] = $config['charset']; - } - - if (isset($config['persistent'])) { - $this->config['persistent'] = $config['persistent']; + $this->config['dbname'] = $config['dbname']; + + if (isset($config['charset'])) { + $this->config['charset'] = $config['charset']; } - } + if (isset($config['persistent'])) { + $this->config['persistent'] = $config['persistent']; + } + } - if ($this->config['persistent'] == 'true'){ - $this->connection = @oci_pconnect($this->config['username'], $this->config['password'], - $this->config['dbname'], $this->config['charset']); - } else { - $this->connection = @oci_new_connect($this->config['username'], $this->config['password'], - $this->config['dbname'], $this->config['charset']); + if ('true' == $this->config['persistent']) { + $this->connection = @oci_pconnect($this->config['username'], $this->config['password'], + $this->config['dbname'], $this->config['charset']); + } else { + $this->connection = @oci_new_connect($this->config['username'], $this->config['password'], + $this->config['dbname'], $this->config['charset']); } - if ($this->connection === false) { + if (false === $this->connection) { throw new Doctrine_Adapter_Exception(sprintf("Unable to Connect to :'%s' as '%s'", $this->config['dbname'], $this->config['username'])); } } /** - * Prepare a query statement + * Prepare a query statement. * * @param string $query Query to prepare + * * @return Doctrine_Adapter_Statement_Oracle $stmt prepared statement */ public function prepare($query) { - $stmt = new Doctrine_Adapter_Statement_Oracle($this, $query, $this->executeMode); - - return $stmt; + return new Doctrine_Adapter_Statement_Oracle($this, $query, $this->executeMode); } /** - * Execute query and return results as statement object + * Execute query and return results as statement object. * * @param string $query + * * @return Doctrine_Adapter_Statement_Oracle $stmt */ public function query($query) @@ -163,56 +159,54 @@ public function query($query) } /** - * Quote a value for the dbms + * Quote a value for the dbms. * * @param string $input + * * @return string $quoted */ public function quote($input) { - return "'" . str_replace("'","''",$input) . "'"; + return "'".str_replace("'", "''", $input)."'"; } /** - * Execute a raw sql statement + * Execute a raw sql statement. * * @param string $statement - * @return void */ public function exec($statement) { $stmt = new Doctrine_Adapter_Statement_Oracle($this, $statement, $this->executeMode); $stmt->execute(); - $count = $stmt->rowCount(); - return $count; + return $stmt->rowCount(); } /** - * Get the id of the last inserted record + * Get the id of the last inserted record. * - * @return integer $id + * @return int $id */ public function lastInsertId() { - throw new Doctrine_Adapter_Exception("unsupported"); + throw new Doctrine_Adapter_Exception('unsupported'); } /** - * Begin a transaction + * Begin a transaction. * - * @return boolean + * @return bool */ public function beginTransaction() { - $this->executeMode = OCI_DEFAULT; - return true; + $this->executeMode = OCI_DEFAULT; + + return true; } /** - * Commit a transaction - * - * @return void + * Commit a transaction. */ public function commit() { @@ -220,9 +214,9 @@ public function commit() } /** - * Rollback a transaction + * Rollback a transaction. * - * @return boolean + * @return bool */ public function rollBack() { @@ -230,39 +224,43 @@ public function rollBack() } /** - * Set connection attribute + * Set connection attribute. + * + * @param int $attribute + * @param mixed $value the value of given attribute * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value) { switch ($attribute) { case Doctrine_Core::ATTR_DRIVER_NAME: - //TODO throw an error since driver name can not be changed + // TODO throw an error since driver name can not be changed case Doctrine_Core::ATTR_ERRMODE: - break; + break; case Doctrine_Core::ATTR_CASE: - if ($value == Doctrine_Core::CASE_NATURAL) { + if (Doctrine_Core::CASE_NATURAL == $value) { break; - } else { - throw new Doctrine_Adapter_Exception("Unsupported Option for ATTR_CASE: $value"); } + throw new Doctrine_Adapter_Exception("Unsupported Option for ATTR_CASE: {$value}"); default: - throw new Doctrine_Adapter_Exception("Unsupported Attribute: $attribute"); + throw new Doctrine_Adapter_Exception("Unsupported Attribute: {$attribute}"); + return false; } $this->attributes[$attribute] = $value; + return true; } /** - * Retrieve a statement attribute + * Retrieve a statement attribute. + * + * @param int $attribute * - * @param integer $attribute * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute) { @@ -270,7 +268,7 @@ public function getAttribute($attribute) } /** - * Returns established OCI connection handler + * Returns established OCI connection handler. * * @return resource OCI connection handler */ @@ -278,15 +276,15 @@ public function getConnection() { return $this->connection; } - + /** - * Returns current user name - * + * Returns current user name. + * * @return string current user name */ public function getUserName() { - return $this->config['username']; + return $this->config['username']; } public function errorCode() @@ -296,6 +294,7 @@ public function errorCode() } else { $error = @oci_error(); } + return $error['code']; } @@ -306,14 +305,15 @@ public function errorInfo() } else { $error = @oci_error(); } + return $error['message']; } - public function __destruct() - { - if (is_resource($this->connection)) { - @oci_rollback($this->connection); - @oci_close($this->connection); - } + public function __destruct() + { + if (is_resource($this->connection)) { + @oci_rollback($this->connection); + @oci_close($this->connection); + } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Adapter/Statement.php b/lib/Doctrine/Adapter/Statement.php index 19cf96d9c..e4197c678 100644 --- a/lib/Doctrine/Adapter/Statement.php +++ b/lib/Doctrine/Adapter/Statement.php @@ -20,112 +20,85 @@ */ /** - * Doctrine_Adapter_Statement + * Doctrine_Adapter_Statement. * * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Adapter - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ abstract class Doctrine_Adapter_Statement { /** - * bindValue + * bindValue. * - * @param string $no - * @param string $value - * @return void + * @param string $no + * @param string $value */ public function bindValue($no, $value) - { } + { + } /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. - * - * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for - * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value - * specifies the row to fetch relative to the cursor position before - * Doctrine_Adapter_Statement_Interface->fetch() was called. - * - * @return mixed */ public function fetch() - { } + { + } /** - * nextRowSet - * - * @return void + * nextRowSet. */ public function nextRowset() - { } + { + } /** - * execute() - * - * @return void + * execute(). */ public function execute() - { } + { + } /** - * errorCode - * - * @return void + * errorCode. */ public function errorCode() - { } + { + } /** - * errorInfo - * - * @return void + * errorInfo. */ public function errorInfo() - { } + { + } /** - * rowCount - * - * @return void + * rowCount. */ public function rowCount() - { } + { + } /** - * setFetchMode + * setFetchMode. * - * @param string $mode - * @return void + * @param string $mode */ public function setFetchMode($mode) - { } + { + } /** - * columnCount - * - * @return void + * columnCount. */ public function columnCount() - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Adapter/Statement/Interface.php b/lib/Doctrine/Adapter/Statement/Interface.php index e35fd5687..885f316fe 100644 --- a/lib/Doctrine/Adapter/Statement/Interface.php +++ b/lib/Doctrine/Adapter/Statement/Interface.php @@ -20,107 +20,103 @@ */ /** - * Interface for Doctrine adapter statements + * Interface for Doctrine adapter statements. * * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Adapter - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ interface Doctrine_Adapter_Statement_Interface { /** - * Bind a column to a PHP variable - * - * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. - * If using the column name, be aware that the name should match - * the case of the column, as returned by the driver. - * @param string $param Name of the PHP variable to which the column will be bound. - * @param integer $type Data type of the parameter, specified by the Doctrine_Core::PARAM_* constants. - * @return boolean Returns TRUE on success or FALSE on failure + * Bind a column to a PHP variable. + * + * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. + * If using the column name, be aware that the name should match + * the case of the column, as returned by the driver. + * @param string $param name of the PHP variable to which the column will be bound + * @param int $type data type of the parameter, specified by the Doctrine_Core::PARAM_* constants + * + * @return bool Returns TRUE on success or FALSE on failure */ public function bindColumn($column, $param, $type = null); /** - * Binds a value to a corresponding named or question mark + * Binds a value to a corresponding named or question mark * placeholder in the SQL statement that was use to prepare the statement. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter - * - * @param mixed $value The value to bind to the parameter. - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. + * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, + * this will be a parameter name of the form :name. For a prepared statement + * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $value the value to bind to the parameter + * @param int $type explicit data type for the parameter using the Doctrine_Core::PARAM_* constants * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindValue($param, $value, $type = null); /** - * Binds a PHP variable to a corresponding named or question mark placeholder in the + * Binds a PHP variable to a corresponding named or question mark placeholder in the * SQL statement that was use to prepare the statement. Unlike Doctrine_Adapter_Statement_Interface->bindValue(), - * the variable is bound as a reference and will only be evaluated at the time + * the variable is bound as a reference and will only be evaluated at the time * that Doctrine_Adapter_Statement_Interface->execute() is called. * - * Most parameters are input parameters, that is, parameters that are - * used in a read-only fashion to build up the query. Some drivers support the invocation + * Most parameters are input parameters, that is, parameters that are + * used in a read-only fashion to build up the query. Some drivers support the invocation * of stored procedures that return data as output parameters, and some also as input/output * parameters that both send in data and are updated to receive it. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $variable name of the PHP variable to bind to the SQL statement parameter + * @param int $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return + * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the + * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. + * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter + * from a stored procedure, you must explicitly set the length. * - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. - * - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return - * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the - * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. - * - * @param integer $length Length of the data type. To indicate that a parameter is an OUT parameter - * from a stored procedure, you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array()); /** * Closes the cursor, enabling the statement to be executed again. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function closeCursor(); - /** - * Returns the number of columns in the result set + /** + * Returns the number of columns in the result set. * - * @return integer Returns the number of columns in the result set represented - * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, - * this method should return 0. + * @return int Returns the number of columns in the result set represented + * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, + * this method should return 0. */ public function columnCount(); /** - * Fetch the SQLSTATE associated with the last operation on the statement handle + * Fetch the SQLSTATE associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorCode() - * @return string error code string + * + * @return string error code string */ public function errorCode(); /** - * Fetch extended error information associated with the last operation on the statement handle + * Fetch extended error information associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorInfo() - * @return array error info array + * + * @return array error info array */ public function errorInfo(); /** - * Executes a prepared statement + * Executes a prepared statement. * * If the prepared statement included parameter markers, you must either: * call PDOStatement->bindParam() to bind PHP variables to the parameter markers: @@ -128,53 +124,47 @@ public function errorInfo(); * if any, of their associated parameter markers or pass an array of input-only * parameter values * + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed * - * @param array $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = null); /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. - * - * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for - * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value - * specifies the row to fetch relative to the cursor position before - * Doctrine_Adapter_Statement_Interface->fetch() was called. * - * @return mixed + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH + * @param int $cursorOrientation For a PDOStatement object representing a scrollable cursor, + * this value determines which row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to + * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your + * Doctrine_Adapter_Statement_Interface object, + * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you + * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). + * @param int $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the + * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies + * the absolute number of the row in the result set that shall be fetched. + * + * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for + * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value + * specifies the row to fetch relative to the cursor position before + * Doctrine_Adapter_Statement_Interface->fetch() was called. */ public function fetch($fetchStyle = Doctrine_Core::FETCH_BOTH, - $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, - $cursorOffset = null); + $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, + $cursorOffset = null); /** - * Returns an array containing all of the result set rows + * Returns an array containing all of the result set rows. * - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is - * Doctrine_Core::FETCH_COLUMN. Defaults to 0. + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH * * @return array */ @@ -184,43 +174,45 @@ public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH); * Returns a single column from the next row of a * result set or FALSE if there are no more rows. * - * @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no - * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() - * fetches the first column. + * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no + * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() + * fetches the first column. * - * @return string returns a single column in the next row of a result set. + * @return string returns a single column in the next row of a result set */ public function fetchColumn($columnIndex = 0); /** * Fetches the next row and returns it as an object. * - * Fetches the next row and returns it as an object. This function is an alternative to + * Fetches the next row and returns it as an object. This function is an alternative to * Doctrine_Adapter_Statement_Interface->fetch() with Doctrine_Core::FETCH_CLASS or Doctrine_Core::FETCH_OBJ style. * - * @param string $className Name of the created class, defaults to stdClass. - * @param array $args Elements of this array are passed to the constructor. + * @param string $className name of the created class, defaults to stdClass + * @param array $args elements of this array are passed to the constructor * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @return mixed an instance of the required class with property names that correspond + * to the column names or FALSE in case of an error */ public function fetchObject($className = 'stdClass', $args = array()); /** - * Retrieve a statement attribute + * Retrieve a statement attribute. + * + * @param int $attribute * - * @param integer $attribute * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute); /** - * Returns metadata for a column in a result set + * Returns metadata for a column in a result set. * - * @param integer $column The 0-indexed column in the result set. + * @param int $column the 0-indexed column in the result set * - * @return array Associative meta data array with the following structure: + * @return array Associative meta data array with the following structure: * * native_type The PHP native type used to represent the column value. * driver:decl_ type The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta(). @@ -233,44 +225,48 @@ public function getAttribute($attribute); public function getColumnMeta($column); /** - * Advances to the next rowset in a multi-rowset statement handle - * - * Some database servers support stored procedures that return more than one rowset - * (also known as a result set). The nextRowset() method enables you to access the second - * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a + * Advances to the next rowset in a multi-rowset statement handle. + * + * Some database servers support stored procedures that return more than one rowset + * (also known as a result set). The nextRowset() method enables you to access the second + * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a * different set of columns from the preceding rowset. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function nextRowset(); /** - * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement + * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement * executed by the corresponding object. * - * If the last SQL statement executed by the associated Statement object was a SELECT statement, - * some databases may return the number of rows returned by that statement. However, - * this behaviour is not guaranteed for all databases and should not be + * If the last SQL statement executed by the associated Statement object was a SELECT statement, + * some databases may return the number of rows returned by that statement. However, + * this behaviour is not guaranteed for all databases and should not be * relied on for portable applications. * - * @return integer Returns the number of rows. + * @return int returns the number of rows */ public function rowCount(); /** - * Set a statement attribute + * Set a statement attribute. * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @param int $attribute + * @param mixed $value the value of given attribute + * + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value); /** - * Set the default fetch mode for this statement + * Set the default fetch mode for this statement. + * + * @param int $mode the fetch mode must be one of the Doctrine_Core::FETCH_* constants + * @param mixed|null $arg1 + * @param mixed|null $arg2 * - * @param integer $mode The fetch mode must be one of the Doctrine_Core::FETCH_* constants. - * @return boolean Returns 1 on success or FALSE on failure. + * @return bool returns 1 on success or FALSE on failure */ public function setFetchMode($mode, $arg1 = null, $arg2 = null); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Adapter/Statement/Mock.php b/lib/Doctrine/Adapter/Statement/Mock.php index 3b7a2ac49..4891870fa 100644 --- a/lib/Doctrine/Adapter/Statement/Mock.php +++ b/lib/Doctrine/Adapter/Statement/Mock.php @@ -20,77 +20,79 @@ */ /** - * Mock connection adapter statement class. Used for special testing purposes + * Mock connection adapter statement class. Used for special testing purposes. * - * @package Doctrine - * @subpackage Adapter * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Adapter_Statement_Mock implements Doctrine_Adapter_Statement_Interface { /** - * Variable which stores instance of Doctrine_Adapter_Mock + * Variable which stores instance of Doctrine_Adapter_Mock. * * @var Doctrine_Adapter_Mock */ private $_mock; /** - * queryString + * queryString. * * @var string */ public $queryString; /** - * Constructor for mock adapter statements. Accepts instance of Doctrine_Adapter_Mock + * Constructor for mock adapter statements. Accepts instance of Doctrine_Adapter_Mock. * * @param Doctrine_Adapter_Mock $mock */ public function __construct($mock) { - $this->_mock = $mock; + $this->_mock = $mock; } /** - * bindColumn + * bindColumn. * * Bind a column to a PHP variable * - * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. - * If using the column name, be aware that the name should match - * the case of the column, as returned by the driver. - * @param string $param Name of the PHP variable to which the column will be bound. - * @param integer $type Data type of the parameter, specified by the Doctrine_Core::PARAM_* constants. - * @return boolean Returns TRUE on success or FALSE on failure + * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. + * If using the column name, be aware that the name should match + * the case of the column, as returned by the driver. + * @param string $param name of the PHP variable to which the column will be bound + * @param int $type data type of the parameter, specified by the Doctrine_Core::PARAM_* constants + * + * @return bool Returns TRUE on success or FALSE on failure */ public function bindColumn($column, $param, $type = null) - { } + { + } /** - * bindValue + * bindValue. * * Binds a value to a corresponding named or question mark * placeholder in the SQL statement that was use to prepare the statement. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter - * - * @param mixed $value The value to bind to the parameter. - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. + * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, + * this will be a parameter name of the form :name. For a prepared statement + * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $value the value to bind to the parameter + * @param int $type explicit data type for the parameter using the Doctrine_Core::PARAM_* constants * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindValue($param, $value, $type = null) - { } + { + } /** - * bindParam + * bindParam. * * Binds a PHP variable to a corresponding named or question mark placeholder in the * SQL statement that was use to prepare the statement. Unlike Doctrine_Adapter_Statement_Interface->bindValue(), @@ -102,32 +104,25 @@ public function bindValue($param, $value, $type = null) * of stored procedures that return data as output parameters, and some also as input/output * parameters that both send in data and are updated to receive it. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $variable name of the PHP variable to bind to the SQL statement parameter + * @param int $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return + * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the + * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. + * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter + * from a stored procedure, you must explicitly set the length. * - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. - * - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return - * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the - * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. - * - * @param integer $length Length of the data type. To indicate that a parameter is an OUT parameter - * from a stored procedure, you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array()) { - } /** - * closeCursor + * closeCursor. * * Closes the cursor, enabling the statement to be executed again. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function closeCursor() { @@ -135,13 +130,13 @@ public function closeCursor() } /** - * columnCount + * columnCount. * * Returns the number of columns in the result set * - * @return integer Returns the number of columns in the result set represented - * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, - * this method should return 0. + * @return int Returns the number of columns in the result set represented + * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, + * this method should return 0. */ public function columnCount() { @@ -149,12 +144,13 @@ public function columnCount() } /** - * errorCode + * errorCode. * * Fetch the SQLSTATE associated with the last operation on the statement handle * * @see Doctrine_Adapter_Interface::errorCode() - * @return string error code string + * + * @return string error code string */ public function errorCode() { @@ -162,12 +158,13 @@ public function errorCode() } /** - * errorInfo + * errorInfo. * * Fetch extended error information associated with the last operation on the statement handle * * @see Doctrine_Adapter_Interface::errorInfo() - * @return array error info array + * + * @return array error info array */ public function errorInfo() { @@ -175,51 +172,41 @@ public function errorInfo() } /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. + * + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH + * @param int $cursorOrientation For a PDOStatement object representing a scrollable cursor, + * this value determines which row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to + * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your + * Doctrine_Adapter_Statement_Interface object, + * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you + * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). + * @param int $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the + * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies + * the absolute number of the row in the result set that shall be fetched. * * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value * specifies the row to fetch relative to the cursor position before * Doctrine_Adapter_Statement_Interface->fetch() was called. - * - * @return mixed */ public function fetch($fetchStyle = Doctrine_Core::FETCH_BOTH, - $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, - $cursorOffset = null) + $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, + $cursorOffset = null) { return array(); } /** - * fetchAll + * fetchAll. * * Returns an array containing all of the result set rows * - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is - * Doctrine_Core::FETCH_COLUMN. Defaults to 0. - * * @return array */ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH) @@ -228,7 +215,7 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH) } /** - * execute + * execute. * * Executes a prepared statement * @@ -238,30 +225,31 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH) * if any, of their associated parameter markers or pass an array of input-only * parameter values * + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed * - * @param array $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = null) { if (is_object($this->_mock)) { $this->_mock->addQuery($this->queryString); } + return true; } /** - * fetchColumn + * fetchColumn. * * Returns a single column from the next row of a * result set or FALSE if there are no more rows. * - * @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no - * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() - * fetches the first column. + * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no + * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() + * fetches the first column. * - * @return string returns a single column in the next row of a result set. + * @return string returns a single column in the next row of a result set */ public function fetchColumn($columnIndex = 0) { @@ -269,18 +257,18 @@ public function fetchColumn($columnIndex = 0) } /** - * fetchObject + * fetchObject. * * Fetches the next row and returns it as an object. * * Fetches the next row and returns it as an object. This function is an alternative to * Doctrine_Adapter_Statement_Interface->fetch() with Doctrine_Core::FETCH_CLASS or Doctrine_Core::FETCH_OBJ style. * - * @param string $className Name of the created class, defaults to stdClass. - * @param array $args Elements of this array are passed to the constructor. + * @param string $className name of the created class, defaults to stdClass + * @param array $args elements of this array are passed to the constructor * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @return mixed an instance of the required class with property names that correspond + * to the column names or FALSE in case of an error */ public function fetchObject($className = 'stdClass', $args = array()) { @@ -288,7 +276,7 @@ public function fetchObject($className = 'stdClass', $args = array()) } /** - * nextRowset + * nextRowset. * * Advances to the next rowset in a multi-rowset statement handle * @@ -297,7 +285,7 @@ public function fetchObject($className = 'stdClass', $args = array()) * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a * different set of columns from the preceding rowset. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function nextRowset() { @@ -305,7 +293,7 @@ public function nextRowset() } /** - * rowCount + * rowCount. * * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement * executed by the corresponding object. @@ -315,7 +303,7 @@ public function nextRowset() * this behaviour is not guaranteed for all databases and should not be * relied on for portable applications. * - * @return integer Returns the number of rows. + * @return int returns the number of rows */ public function rowCount() { @@ -323,13 +311,13 @@ public function rowCount() } /** - * getColumnMeta + * getColumnMeta. * * Returns metadata for a column in a result set * - * @param integer $column The 0-indexed column in the result set. + * @param int $column the 0-indexed column in the result set * - * @return array Associative meta data array with the following structure: + * @return array Associative meta data array with the following structure: * * native_type The PHP native type used to represent the column value. * driver:decl_ type The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta(). @@ -340,40 +328,50 @@ public function rowCount() * pdo_type The type of this column as represented by the PDO::PARAM_* constants. */ public function getColumnMeta($column) - { } + { + } /** - * getAttribute + * getAttribute. * * Retrieve a statement attribute * - * @param integer $attribute + * @param int $attribute + * * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute) - { } + { + } /** - * setAttribute + * setAttribute. * * Set a statement attribute * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @param int $attribute + * @param mixed $value the value of given attribute + * + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value) - { } + { + } /** - * setFetchMode + * setFetchMode. * * Set the default fetch mode for this statement * - * @param integer $mode The fetch mode must be one of the Doctrine_Core::FETCH_* constants. - * @return boolean Returns 1 on success or FALSE on failure. + * @param int $mode the fetch mode must be one of the Doctrine_Core::FETCH_* constants + * @param mixed|null $arg1 + * @param mixed|null $arg2 + * + * @return bool returns 1 on success or FALSE on failure */ public function setFetchMode($mode, $arg1 = null, $arg2 = null) - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Adapter/Statement/Oracle.php b/lib/Doctrine/Adapter/Statement/Oracle.php index 0198f78f1..e6f70185c 100644 --- a/lib/Doctrine/Adapter/Statement/Oracle.php +++ b/lib/Doctrine/Adapter/Statement/Oracle.php @@ -22,64 +22,63 @@ /** * Oracle connection adapter statement class. * - * @package Doctrine - * @subpackage Adapter * @author Konsta Vesterinen * @author vadik56 * @author Miloslav Kmet * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Rev$ */ class Doctrine_Adapter_Statement_Oracle implements Doctrine_Adapter_Statement_Interface { /** - * @var string $queryString actual query string + * @var string actual query string */ public $queryString; - + /** - * @var resource $connection OCI connection handler + * @var resource OCI connection handler */ protected $connection; - + /** - * @var resource $statement OCI prepared statement + * @var resource OCI prepared statement */ protected $statement; - + /** - * @var integer $executeMode OCI statement execution mode + * @var int OCI statement execution mode */ protected $executeMode = OCI_COMMIT_ON_SUCCESS; /** - * @var array $bindParams Array of parameters bounded to a statement + * @var array Array of parameters bounded to a statement */ protected $bindParams = array(); /** - * @var array $attributes Array of attributes + * @var array Array of attributes */ protected $attributes = array(); /** - * @var array $ociErrors Array of errors + * @var array Array of errors */ protected $ociErrors = array(); - + /** - * the constructor - * - * @param Doctrine_Adapter_Oracle $connection - * @param string $query Query string to be executed - * @param integer $executeMode OCI execute mode + * the constructor. + * + * @param string $query Query string to be executed + * @param int $executeMode OCI execute mode */ - public function __construct( Doctrine_Adapter_Oracle $connection, $query, $executeMode) + public function __construct(Doctrine_Adapter_Oracle $connection, $query, $executeMode) { - $this->connection = $connection->getConnection(); - $this->queryString = $query; + $this->connection = $connection->getConnection(); + $this->queryString = $query; $this->executeMode = $executeMode; $this->attributes[Doctrine_Core::ATTR_ERRMODE] = $connection->getAttribute(Doctrine_Core::ATTR_ERRMODE); @@ -87,36 +86,36 @@ public function __construct( Doctrine_Adapter_Oracle $connection, $query, $execu } /** - * Bind a column to a PHP variable - * - * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. - * If using the column name, be aware that the name should match - * the case of the column, as returned by the driver. - * @param string $param Name of the PHP variable to which the column will be bound. - * @param integer $type Data type of the parameter, specified by the Doctrine_Core::PARAM_* constants. - * @return boolean Returns TRUE on success or FALSE on failure + * Bind a column to a PHP variable. + * + * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. + * If using the column name, be aware that the name should match + * the case of the column, as returned by the driver. + * @param string $param name of the PHP variable to which the column will be bound + * @param int $type data type of the parameter, specified by the Doctrine_Core::PARAM_* constants + * + * @return bool Returns TRUE on success or FALSE on failure */ public function bindColumn($column, $param, $type = null) { - throw new Doctrine_Adapter_Exception("Unsupported"); + throw new Doctrine_Adapter_Exception('Unsupported'); } /** - * Binds a value to a corresponding named or question mark + * Binds a value to a corresponding named or question mark * placeholder in the SQL statement that was use to prepare the statement. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter - * - * @param mixed $value The value to bind to the parameter. - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. + * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, + * this will be a parameter name of the form :name. For a prepared statement + * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $value the value to bind to the parameter + * @param int $type explicit data type for the parameter using the Doctrine_Core::PARAM_* constants * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindValue($param, $value, $type = null) { - /** + /* * need to store the value internally since binding is done by reference */ $this->bindParams[] = $value; @@ -124,38 +123,32 @@ public function bindValue($param, $value, $type = null) } /** - * Binds a PHP variable to a corresponding named or question mark placeholder in the + * Binds a PHP variable to a corresponding named or question mark placeholder in the * SQL statement that was use to prepare the statement. Unlike Doctrine_Adapter_Statement_Interface->bindValue(), - * the variable is bound as a reference and will only be evaluated at the time + * the variable is bound as a reference and will only be evaluated at the time * that Doctrine_Adapter_Statement_Interface->execute() is called. * - * Most parameters are input parameters, that is, parameters that are - * used in a read-only fashion to build up the query. Some drivers support the invocation + * Most parameters are input parameters, that is, parameters that are + * used in a read-only fashion to build up the query. Some drivers support the invocation * of stored procedures that return data as output parameters, and some also as input/output * parameters that both send in data and are updated to receive it. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $variable name of the PHP variable to bind to the SQL statement parameter + * @param int $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return + * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the + * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. + * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter + * from a stored procedure, you must explicitly set the length. * - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. - * - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return - * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the - * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. - * - * @param integer $length Length of the data type. To indicate that a parameter is an OUT parameter - * from a stored procedure, you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array()) { - if ($driverOptions || $length ) { + if ($driverOptions || $length) { throw new Doctrine_Adapter_Exception('Unsupported parameters:$length, $driverOptions'); } - if ($length === null) { + if (null === $length) { $oci_length = -1; } $oci_type = SQLT_CHR; @@ -163,26 +156,27 @@ public function bindParam($column, &$variable, $type = null, $length = null, $dr switch ($type) { case Doctrine_Core::PARAM_STR: $oci_type = SQLT_CHR; - break; + break; } if (is_integer($column)) { - $variable_name = ":oci_b_var_$column"; + $variable_name = ":oci_b_var_{$column}"; } else { $variable_name = $column; } - //print "Binding $variable to $variable_name".PHP_EOL; + // print "Binding $variable to $variable_name".PHP_EOL; $status = @oci_bind_by_name($this->statement, $variable_name, $variable, $oci_length, $oci_type); - if ($status === false) { - $this->handleError(); + if (false === $status) { + $this->handleError(); } + return $status; } /** * Closes the cursor, enabling the statement to be executed again. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function closeCursor() { @@ -190,64 +184,70 @@ public function closeCursor() if (is_resource($this->statement)) { return oci_free_statement($this->statement); } + return true; } - /** - * Returns the number of columns in the result set + /** + * Returns the number of columns in the result set. * - * @return integer Returns the number of columns in the result set represented - * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, - * this method should return 0. + * @return int Returns the number of columns in the result set represented + * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, + * this method should return 0. */ public function columnCount() { - return oci_num_fields ( $this->statement ); + return oci_num_fields($this->statement); } /** - * Fetch the SQLSTATE associated with the last operation on the statement handle + * Fetch the SQLSTATE associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorCode() - * @return string error code string + * + * @return string error code string */ public function errorCode() { $oci_error = $this->getOciError(); + return $oci_error['code']; } /** - * Fetch extended error information associated with the last operation on the statement handle + * Fetch extended error information associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorInfo() - * @return array error info array + * + * @return array error info array */ public function errorInfo() { $oci_error = $this->getOciError(); - return $oci_error['message'] . " : " . $oci_error['sqltext']; + + return $oci_error['message'].' : '.$oci_error['sqltext']; } private function getOciError() { if (is_resource($this->statement)) { - $oci_error = oci_error ($this->statement); + $oci_error = oci_error($this->statement); } else { - $oci_error = oci_error (); + $oci_error = oci_error(); } if ($oci_error) { - //store the error + // store the error $this->oci_errors[] = $oci_error; - } else if (count($this->ociErrors) > 0) { - $oci_error = $this->ociErrors[count($this->ociErrors)-1]; + } elseif (count($this->ociErrors) > 0) { + $oci_error = $this->ociErrors[count($this->ociErrors) - 1]; } + return $oci_error; } /** - * Executes a prepared statement + * Executes a prepared statement. * * If the prepared statement included parameter markers, you must either: * call PDOStatement->bindParam() to bind PHP variables to the parameter markers: @@ -255,107 +255,103 @@ private function getOciError() * if any, of their associated parameter markers or pass an array of input-only * parameter values * + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed * - * @param array $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = null) { if (is_array($params)) { foreach ($params as $var => $value) { - $this->bindValue($var+1, $value); + $this->bindValue($var + 1, $value); } } - $result = @oci_execute($this->statement , $this->executeMode ); + $result = @oci_execute($this->statement, $this->executeMode); - if ($result === false) { + if (false === $result) { $this->handleError(); + return false; - } + } + return true; } /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. - * - * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for - * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value - * specifies the row to fetch relative to the cursor position before - * Doctrine_Adapter_Statement_Interface->fetch() was called. * - * @return mixed + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH + * @param int $cursorOrientation For a PDOStatement object representing a scrollable cursor, + * this value determines which row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to + * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your + * Doctrine_Adapter_Statement_Interface object, + * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you + * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). + * @param int $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the + * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies + * the absolute number of the row in the result set that shall be fetched. + * + * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for + * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value + * specifies the row to fetch relative to the cursor position before + * Doctrine_Adapter_Statement_Interface->fetch() was called. */ public function fetch($fetchStyle = Doctrine_Core::FETCH_BOTH, $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, $cursorOffset = null) { switch ($fetchStyle) { case Doctrine_Core::FETCH_BOTH : return oci_fetch_array($this->statement, OCI_BOTH + OCI_RETURN_NULLS + OCI_RETURN_LOBS); - break; + break; case Doctrine_Core::FETCH_ASSOC : return oci_fetch_array($this->statement, OCI_ASSOC + OCI_RETURN_NULLS + OCI_RETURN_LOBS); - break; + break; case Doctrine_Core::FETCH_NUM : return oci_fetch_array($this->statement, OCI_NUM + OCI_RETURN_NULLS + OCI_RETURN_LOBS); - break; + break; case Doctrine_Core::FETCH_OBJ: return oci_fetch_object($this->statement, OCI_NUM + OCI_RETURN_NULLS + OCI_RETURN_LOBS); - break; + break; default: - throw new Doctrine_Adapter_Exception("This type of fetch is not supported: ".$fetchStyle); -/* - case Doctrine_Core::FETCH_BOUND: - case Doctrine_Core::FETCH_CLASS: - case FETCH_CLASSTYPE: - case FETCH_COLUMN: - case FETCH_FUNC: - case FETCH_GROUP: - case FETCH_INTO: - case FETCH_LAZY: - case FETCH_NAMED: - case FETCH_SERIALIZE: - case FETCH_UNIQUE: - case FETCH_ORI_ABS: - case FETCH_ORI_FIRST: - case FETCH_ORI_LAST: - case FETCH_ORI_NEXT: - case FETCH_ORI_PRIOR: - case FETCH_ORI_REL: -*/ + throw new Doctrine_Adapter_Exception('This type of fetch is not supported: '.$fetchStyle); + /* + case Doctrine_Core::FETCH_BOUND: + case Doctrine_Core::FETCH_CLASS: + case FETCH_CLASSTYPE: + case FETCH_COLUMN: + case FETCH_FUNC: + case FETCH_GROUP: + case FETCH_INTO: + case FETCH_LAZY: + case FETCH_NAMED: + case FETCH_SERIALIZE: + case FETCH_UNIQUE: + case FETCH_ORI_ABS: + case FETCH_ORI_FIRST: + case FETCH_ORI_LAST: + case FETCH_ORI_NEXT: + case FETCH_ORI_PRIOR: + case FETCH_ORI_REL: + */ } } /** - * Returns an array containing all of the result set rows + * Returns an array containing all of the result set rows. * - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is - * Doctrine_Core::FETCH_COLUMN. Defaults to 0. + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH * * @return array */ - public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH, $colnum=0) + public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH, $colnum = 0) { $fetchColumn = false; $skip = 0; @@ -365,19 +361,19 @@ public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH, $colnum=0) $int = $fetchStyle & Doctrine_Core::FETCH_COLUMN; - if ($fetchStyle == Doctrine_Core::FETCH_BOTH) { + if (Doctrine_Core::FETCH_BOTH == $fetchStyle) { $flags = OCI_BOTH; $numberOfRows = @oci_fetch_all($this->statement, $data, $skip, $maxrows, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC + OCI_RETURN_LOBS); - } else if ($fetchStyle == Doctrine_Core::FETCH_ASSOC) { + } elseif (Doctrine_Core::FETCH_ASSOC == $fetchStyle) { $numberOfRows = @oci_fetch_all($this->statement, $data, $skip, $maxrows, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC + OCI_RETURN_LOBS); - } else if ($fetchStyle == Doctrine_Core::FETCH_NUM) { + } elseif (Doctrine_Core::FETCH_NUM == $fetchStyle) { $numberOfRows = @oci_fetch_all($this->statement, $data, $skip, $maxrows, OCI_FETCHSTATEMENT_BY_ROW + OCI_NUM + OCI_RETURN_LOBS); - } else if ($fetchStyle == Doctrine_Core::FETCH_COLUMN) { - while ($row = @oci_fetch_array ($this->statement, OCI_NUM+OCI_RETURN_LOBS)) { + } elseif (Doctrine_Core::FETCH_COLUMN == $fetchStyle) { + while ($row = @oci_fetch_array($this->statement, OCI_NUM + OCI_RETURN_LOBS)) { $data[] = $row[$colnum]; } } else { - throw new Doctrine_Adapter_Exception("Unsupported mode: '" . $fetchStyle . "' "); + throw new Doctrine_Adapter_Exception("Unsupported mode: '".$fetchStyle."' "); } return $data; @@ -387,75 +383,76 @@ public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH, $colnum=0) * Returns a single column from the next row of a * result set or FALSE if there are no more rows. * - * @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no - * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() - * fetches the first column. + * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no + * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() + * fetches the first column. * - * @return string returns a single column in the next row of a result set. + * @return string returns a single column in the next row of a result set */ public function fetchColumn($columnIndex = 0) { - if ( ! is_integer($columnIndex)) { - $this->handleError(array('message'=>"columnIndex parameter should be numeric")); + if (!is_integer($columnIndex)) { + $this->handleError(array('message' => 'columnIndex parameter should be numeric')); return false; } $row = $this->fetch(Doctrine_Core::FETCH_NUM); + return isset($row[$columnIndex]) ? $row[$columnIndex] : false; } /** * Fetches the next row and returns it as an object. * - * Fetches the next row and returns it as an object. This function is an alternative to + * Fetches the next row and returns it as an object. This function is an alternative to * Doctrine_Adapter_Statement_Interface->fetch() with Doctrine_Core::FETCH_CLASS or Doctrine_Core::FETCH_OBJ style. * - * @param string $className Name of the created class, defaults to stdClass. - * @param array $args Elements of this array are passed to the constructor. + * @param string $className name of the created class, defaults to stdClass + * @param array $args elements of this array are passed to the constructor * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @return mixed an instance of the required class with property names that correspond + * to the column names or FALSE in case of an error */ public function fetchObject($className = 'stdClass', $args = array()) { $row = $this->fetch(Doctrine_Core::FETCH_ASSOC); - if ($row === false) { + if (false === $row) { return false; } - $instantiation_code = "\$object = new $className("; - $firstParam=true; - foreach ($args as $index=>$value) { - if ( ! $firstParam ) { - $instantiation_code = $instantiation_code . ","; + $instantiation_code = "\$object = new {$className}("; + $firstParam = true; + foreach ($args as $index => $value) { + if (!$firstParam) { + $instantiation_code = $instantiation_code.','; } else { - $firstParam= false; + $firstParam = false; } - if ( is_string($index)) { - $instantiation_code = $instantiation_code . " \$args['$index']"; + if (is_string($index)) { + $instantiation_code = $instantiation_code." \$args['{$index}']"; } else { - $instantiation_code = $instantiation_code . "\$args[$index]"; + $instantiation_code = $instantiation_code."\$args[{$index}]"; } } - $instantiation_code = $instantiation_code . ");"; + $instantiation_code = $instantiation_code.');'; eval($instantiation_code); - //initialize instance of $className class + // initialize instance of $className class foreach ($row as $col => $value) { - $object->$col = $value; + $object->{$col} = $value; } return $object; } /** - * Returns metadata for a column in a result set + * Returns metadata for a column in a result set. * - * @param integer $column The 0-indexed column in the result set. + * @param int $column the 0-indexed column in the result set * - * @return array Associative meta data array with the following structure: + * @return array Associative meta data array with the following structure: * * native_type The PHP native type used to represent the column value. * driver:decl_ type The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta(). @@ -468,14 +465,14 @@ public function fetchObject($className = 'stdClass', $args = array()) public function getColumnMeta($column) { if (is_integer($column)) { - $internal_column = $column +1; + $internal_column = $column + 1; } else { $internal_column = $column; } $data = array(); $data['native_type'] = oci_field_type($this->statement, $internal_column); - $data['flags'] = ""; + $data['flags'] = ''; $data['len'] = oci_field_size($this->statement, $internal_column); $data['name'] = oci_field_name($this->statement, $internal_column); $data['precision'] = oci_field_precision($this->statement, $internal_column); @@ -484,30 +481,30 @@ public function getColumnMeta($column) } /** - * Advances to the next rowset in a multi-rowset statement handle - * - * Some database servers support stored procedures that return more than one rowset - * (also known as a result set). The nextRowset() method enables you to access the second - * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a + * Advances to the next rowset in a multi-rowset statement handle. + * + * Some database servers support stored procedures that return more than one rowset + * (also known as a result set). The nextRowset() method enables you to access the second + * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a * different set of columns from the preceding rowset. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function nextRowset() { - throw new Doctrine_Adapter_Exception("Unsupported"); + throw new Doctrine_Adapter_Exception('Unsupported'); } /** - * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement + * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement * executed by the corresponding object. * - * If the last SQL statement executed by the associated Statement object was a SELECT statement, - * some databases may return the number of rows returned by that statement. However, - * this behaviour is not guaranteed for all databases and should not be + * If the last SQL statement executed by the associated Statement object was a SELECT statement, + * some databases may return the number of rows returned by that statement. However, + * this behaviour is not guaranteed for all databases and should not be * relied on for portable applications. * - * @return integer Returns the number of rows. + * @return int returns the number of rows */ public function rowCount() { @@ -515,29 +512,32 @@ public function rowCount() } /** - * Set a statement attribute + * Set a statement attribute. + * + * @param int $attribute + * @param mixed $value the value of given attribute * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value) { switch ($attribute) { - case Doctrine_Core::ATTR_ERRMODE; - break; + case Doctrine_Core::ATTR_ERRMODE: + break; default: - throw new Doctrine_Adapter_Exception("Unsupported Attribute: $attribute"); + throw new Doctrine_Adapter_Exception("Unsupported Attribute: {$attribute}"); } $this->attributes[$attribute] = $value; } /** - * Retrieve a statement attribute + * Retrieve a statement attribute. + * + * @param int $attribute * - * @param integer $attribute * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute) { @@ -545,53 +545,54 @@ public function getAttribute($attribute) } /** - * Set the default fetch mode for this statement + * Set the default fetch mode for this statement. + * + * @param int $mode the fetch mode must be one of the Doctrine_Core::FETCH_* constants + * @param mixed|null $arg1 + * @param mixed|null $arg2 * - * @param integer $mode The fetch mode must be one of the Doctrine_Core::FETCH_* constants. - * @return boolean Returns 1 on success or FALSE on failure. + * @return bool returns 1 on success or FALSE on failure */ public function setFetchMode($mode, $arg1 = null, $arg2 = null) { - throw new Doctrine_Adapter_Exception("Unsupported"); + throw new Doctrine_Adapter_Exception('Unsupported'); } - private function handleError($params=array()) + private function handleError($params = array()) { - switch ($this->attributes[Doctrine_Core::ATTR_ERRMODE]) { case Doctrine_Core::ERRMODE_EXCEPTION: if (isset($params['message'])) { throw new Doctrine_Adapter_Exception($params['message']); - } else { - throw new Doctrine_Adapter_Exception($this->errorInfo()); } - - break; + throw new Doctrine_Adapter_Exception($this->errorInfo()); + break; case Doctrine_Core::ERRMODE_WARNING: case Doctrine_Core::ERRMODE_SILENT: - break; + break; } } /** - * Parse actual query from queryString and returns OCI statement handler + * Parse actual query from queryString and returns OCI statement handler. + * * @param string Query string to parse, if NULL, $this->queryString is used - * - * @return resource OCI statement handler + * @param mixed|null $query + * + * @return resource OCI statement handler */ - private function parseQuery($query=null) + private function parseQuery($query = null) { if (is_null($query)) { $query = $this->queryString; } $bind_index = 1; // Replace ? bind-placeholders with :oci_b_var_ variables - $query = preg_replace_callback("/(\?)/", function($m) use(&$bind_index) { return ":oci_b_var_". $bind_index++; } , $query); + $query = preg_replace_callback('/(\\?)/', function ($m) use (&$bind_index) { return ':oci_b_var_'.$bind_index++; }, $query); - $this->statement = @oci_parse($this->connection, $query); + $this->statement = @oci_parse($this->connection, $query); - if ( $this->statement == false ) - { + if (false == $this->statement) { throw new Doctrine_Adapter_Exception($this->getOciError()); } diff --git a/lib/Doctrine/AuditLog.php b/lib/Doctrine/AuditLog.php index 763b882c7..fc8a65fce 100644 --- a/lib/Doctrine/AuditLog.php +++ b/lib/Doctrine/AuditLog.php @@ -20,45 +20,45 @@ */ /** - * Doctrine_AuditLog + * Doctrine_AuditLog. * - * @package Doctrine - * @subpackage AuditLog * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_AuditLog extends Doctrine_Record_Generator { /** - * Array of AuditLog Options + * Array of AuditLog Options. * * @var array */ - protected $_options = array('className' => '%CLASS%Version', - 'version' => array('name' => 'version', - 'alias' => null, - 'type' => 'integer', - 'length' => 8, - 'options' => array('primary' => true)), - 'tableName' => false, - 'generateFiles' => false, - 'table' => false, - 'pluginTable' => false, - 'children' => array(), - 'auditLog' => true, - 'deleteVersions' => true, - 'cascadeDelete' => true, - 'excludeFields' => array(), - 'appLevelDelete' => false); + protected $_options = array('className' => '%CLASS%Version', + 'version' => array('name' => 'version', + 'alias' => null, + 'type' => 'integer', + 'length' => 8, + 'options' => array('primary' => true)), + 'tableName' => false, + 'generateFiles' => false, + 'table' => false, + 'pluginTable' => false, + 'children' => array(), + 'auditLog' => true, + 'deleteVersions' => true, + 'cascadeDelete' => true, + 'excludeFields' => array(), + 'appLevelDelete' => false); /** - * Accepts array of options to configure the AuditLog + * Accepts array of options to configure the AuditLog. * - * @param array $options An array of options - * @return void + * @param array $options An array of options */ public function __construct(array $options = array()) { @@ -72,9 +72,7 @@ public function buildRelation() } /** - * Set the table definition for the audit log table - * - * @return void + * Set the table definition for the audit log table. */ public function setTableDefinition() { @@ -88,13 +86,11 @@ public function setTableDefinition() if (in_array($column, $this->_options['excludeFields'])) { continue; } - unset($definition['autoincrement']); - unset($definition['sequence']); - unset($definition['unique']); + unset($definition['autoincrement'], $definition['sequence'], $definition['unique']); $fieldName = $this->_options['table']->getFieldName($column); if ($fieldName != $column) { - $name = $column . ' as ' . $fieldName; + $name = $column.' as '.$fieldName; } else { $name = $fieldName; } @@ -104,67 +100,68 @@ public function setTableDefinition() // the version column should be part of the primary key definition $this->hasColumn( - $this->_options['version']['name'], + $this->_options['version']['name'], $this->_options['version']['type'], $this->_options['version']['length'], $this->_options['version']['options']); } /** - * Get array of information for the passed record and the specified version + * Get array of information for the passed record and the specified version. + * + * @param int $version + * @param int $hydrationMode + * @param bool $asCollection * - * @param Doctrine_Record $record - * @param integer $version - * @param integer $hydrationMode - * @param boolean $asCollection - * @return array An array or Doctrine_Collection or a Doctrine_Record + * @return array An array or Doctrine_Collection or a Doctrine_Record */ public function getVersion(Doctrine_Record $record, $version, $hydrationMode = Doctrine_Core::HYDRATE_ARRAY, $asCollection = true) { $className = $this->_options['className']; - $method = ($asCollection) ? 'execute' : 'fetchOne'; + $method = ($asCollection) ? 'execute' : 'fetchOne'; $q = Doctrine_Core::getTable($className) - ->createQuery(); + ->createQuery() + ; $values = array(); foreach ((array) $this->_options['table']->getIdentifier() as $id) { - $conditions[] = $className . '.' . $id . ' = ?'; + $conditions[] = $className.'.'.$id.' = ?'; $values[] = $record->get($id); } - $where = implode(' AND ', $conditions) . ' AND ' . $className . '.' . $this->_options['version']['name'] . ' = ?'; + $where = implode(' AND ', $conditions).' AND '.$className.'.'.$this->_options['version']['name'].' = ?'; $values[] = $version; $q->where($where); - return $q->$method($values, $hydrationMode); + return $q->{$method}($values, $hydrationMode); } /** - * Get the max version number for a given Doctrine_Record + * Get the max version number for a given Doctrine_Record. * - * @param Doctrine_Record $record - * @return Integer $versionnumber + * @return int $versionnumber */ public function getMaxVersion(Doctrine_Record $record) { $className = $this->_options['className']; - $select = 'MAX(' . $className . '.' . $this->_options['version']['name'] . ') max_version'; + $select = 'MAX('.$className.'.'.$this->_options['version']['name'].') max_version'; foreach ((array) $this->_options['table']->getIdentifier() as $id) { - $conditions[] = $className . '.' . $id . ' = ?'; + $conditions[] = $className.'.'.$id.' = ?'; $values[] = $record->get($id); } $q = Doctrine_Core::getTable($className) ->createQuery() ->select($select) - ->where(implode(' AND ',$conditions)); + ->where(implode(' AND ', $conditions)) + ; $result = $q->execute($values, Doctrine_Core::HYDRATE_ARRAY); - return isset($result[0]['max_version']) ? $result[0]['max_version']:0; + return isset($result[0]['max_version']) ? $result[0]['max_version'] : 0; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/AuditLog/Listener.php b/lib/Doctrine/AuditLog/Listener.php index d2631e7a3..6b745428a 100644 --- a/lib/Doctrine/AuditLog/Listener.php +++ b/lib/Doctrine/AuditLog/Listener.php @@ -20,46 +20,41 @@ */ /** - * Doctrine_AuditLog_Listener + * Doctrine_AuditLog_Listener. * - * @package Doctrine - * @subpackage AuditLog * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_AuditLog_Listener extends Doctrine_Record_Listener { /** - * Instance of Doctrine_Auditlog + * Instance of Doctrine_Auditlog. * * @var Doctrine_AuditLog */ protected $_auditLog; /** - * Instantiate AuditLog listener and set the Doctrine_AuditLog instance to the class - * - * @param Doctrine_AuditLog $auditLog - * @return void + * Instantiate AuditLog listener and set the Doctrine_AuditLog instance to the class. */ - public function __construct(Doctrine_AuditLog $auditLog) + public function __construct(Doctrine_AuditLog $auditLog) { $this->_auditLog = $auditLog; } /** - * Pre insert event hook for incrementing version number - * - * @param Doctrine_Event $event - * @return void + * Pre insert event hook for incrementing version number. */ public function preInsert(Doctrine_Event $event) { $version = $this->_auditLog->getOption('version'); - $name = $version['alias'] === null ? $version['name'] : $version['alias']; + $name = null === $version['alias'] ? $version['name'] : $version['alias']; $record = $event->getInvoker(); $record->set($name, $this->_getInitialVersion($record)); @@ -67,17 +62,14 @@ public function preInsert(Doctrine_Event $event) /** * Post insert event hook which creates the new version record - * This will only insert a version record if the auditLog is enabled - * - * @param Doctrine_Event $event - * @return void + * This will only insert a version record if the auditLog is enabled. */ - public function postInsert(Doctrine_Event $event) + public function postInsert(Doctrine_Event $event) { if ($this->_auditLog->getOption('auditLog')) { $class = $this->_auditLog->getOption('className'); - $record = $event->getInvoker(); + $record = $event->getInvoker(); $version = new $class(); $version->merge($record->toArray(), false); $version->save(); @@ -86,49 +78,45 @@ public function postInsert(Doctrine_Event $event) /** * Pre delete event hook deletes all related versions - * This will only delete version records if the auditLog is enabled - * - * @param Doctrine_Event $event - * @return void + * This will only delete version records if the auditLog is enabled. */ public function preDelete(Doctrine_Event $event) { if ($this->_auditLog->getOption('auditLog')) { - $className = $this->_auditLog->getOption('className'); + $className = $this->_auditLog->getOption('className'); $version = $this->_auditLog->getOption('version'); - $name = $version['alias'] === null ? $version['name'] : $version['alias']; - $event->getInvoker()->set($name, null); + $name = null === $version['alias'] ? $version['name'] : $version['alias']; + $event->getInvoker()->set($name, null); if ($this->_auditLog->getOption('deleteVersions')) { - $q = Doctrine_Core::getTable($className) - ->createQuery('obj') - ->delete(); - foreach ((array) $this->_auditLog->getOption('table')->getIdentifier() as $id) { - $conditions[] = 'obj.' . $id . ' = ?'; - $values[] = $event->getInvoker()->get($id); - } + $q = Doctrine_Core::getTable($className) + ->createQuery('obj') + ->delete() + ; + foreach ((array) $this->_auditLog->getOption('table')->getIdentifier() as $id) { + $conditions[] = 'obj.'.$id.' = ?'; + $values[] = $event->getInvoker()->get($id); + } - $rows = $q->where(implode(' AND ', $conditions)) - ->execute($values); - } + $rows = $q->where(implode(' AND ', $conditions)) + ->execute($values) + ; + } } } /** * Pre update event hook for inserting new version record - * This will only insert a version record if the auditLog is enabled - * - * @param Doctrine_Event $event - * @return void + * This will only insert a version record if the auditLog is enabled. */ public function preUpdate(Doctrine_Event $event) { if ($this->_auditLog->getOption('auditLog')) { - $class = $this->_auditLog->getOption('className'); + $class = $this->_auditLog->getOption('className'); $record = $event->getInvoker(); $version = $this->_auditLog->getOption('version'); - $name = $version['alias'] === null ? $version['name'] : $version['alias']; + $name = null === $version['alias'] ? $version['name'] : $version['alias']; $record->set($name, $this->_getNextVersion($record)); @@ -139,10 +127,9 @@ public function preUpdate(Doctrine_Event $event) } /** - * Get the initial version number for the audit log + * Get the initial version number for the audit log. * - * @param Doctrine_Record $record - * @return integer $initialVersion + * @return int $initialVersion */ protected function _getInitialVersion(Doctrine_Record $record) { @@ -150,15 +137,14 @@ protected function _getInitialVersion(Doctrine_Record $record) } /** - * Get the next version number for the audit log + * Get the next version number for the audit log. * - * @param Doctrine_Record $record - * @return integer $nextVersion + * @return int $nextVersion */ protected function _getNextVersion(Doctrine_Record $record) { - if ($this->_auditLog->getOption('auditLog')) { - return ($this->_auditLog->getMaxVersion($record) + 1); - } + if ($this->_auditLog->getOption('auditLog')) { + return $this->_auditLog->getMaxVersion($record) + 1; + } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/AuditLog/Listener/Microtime.php b/lib/Doctrine/AuditLog/Listener/Microtime.php index 081a27fff..65f7871e2 100644 --- a/lib/Doctrine/AuditLog/Listener/Microtime.php +++ b/lib/Doctrine/AuditLog/Listener/Microtime.php @@ -20,30 +20,28 @@ */ /** - * Doctrine_AuditLog_Listener + * Doctrine_AuditLog_Listener. * - * @package Doctrine - * @subpackage AuditLog * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Lukas Smith */ class Doctrine_AuditLog_Listener_Microtime extends Doctrine_AuditLog_Listener { /** - * The numher of digits to use from the float microtime value + * The numher of digits to use from the float microtime value. * * @var int */ protected $accuracy = 10; /** - * Instantiate AuditLog listener and set the Doctrine_AuditLog instance to the class - * - * @param Doctrine_AuditLog $auditLog - * @return void + * Instantiate AuditLog listener and set the Doctrine_AuditLog instance to the class. */ public function __construct(Doctrine_AuditLog $auditLog) { @@ -55,10 +53,9 @@ public function __construct(Doctrine_AuditLog $auditLog) } /** - * Get the initial version number for the audit log + * Get the initial version number for the audit log. * - * @param Doctrine_Record $record - * @return integer $initialVersion + * @return int $initialVersion */ protected function _getInitialVersion(Doctrine_Record $record) { @@ -66,10 +63,9 @@ protected function _getInitialVersion(Doctrine_Record $record) } /** - * Get the next version number for the audit log + * Get the next version number for the audit log. * - * @param Doctrine_Record $record - * @return integer $nextVersion + * @return int $nextVersion */ protected function _getNextVersion(Doctrine_Record $record) { @@ -77,15 +73,15 @@ protected function _getNextVersion(Doctrine_Record $record) } /** - * Compute a version out of microtime(true) + * Compute a version out of microtime(true). * * @return string $version */ protected function _microtime() { $version = microtime(true) - 1073741824; // 31 bits - $version = str_replace('.', '', (string)$version); + $version = str_replace('.', '', (string) $version); + return substr($version, 0, $this->accuracy); } - -} \ No newline at end of file +} diff --git a/lib/Doctrine/Builder.php b/lib/Doctrine/Builder.php index 9f6ac88a7..c566b54fc 100644 --- a/lib/Doctrine/Builder.php +++ b/lib/Doctrine/Builder.php @@ -20,14 +20,16 @@ */ /** - * Base class for any code builders/generators for Doctrine + * Base class for any code builders/generators for Doctrine. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Builder - * @link www.doctrine-project.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 4593 $ + * * @author Jonathan H. Wage */ class Doctrine_Builder @@ -35,22 +37,20 @@ class Doctrine_Builder /** * Special function for var_export() * The normal code which is returned is malformed and does not follow Doctrine standards - * So we do some string replacing to clean it up + * So we do some string replacing to clean it up. * * @param string $var - * @return void */ public function varExport($var) { $export = var_export($var, true); - $export = str_replace("\n", PHP_EOL . str_repeat(' ', 50), $export); + $export = str_replace("\n", PHP_EOL.str_repeat(' ', 50), $export); $export = str_replace(' ', ' ', $export); $export = str_replace('array (', 'array(', $export); $export = str_replace('array( ', 'array(', $export); $export = str_replace(',)', ')', $export); $export = str_replace(', )', ')', $export); - $export = str_replace(' ', ' ', $export); - return $export; + return str_replace(' ', ' ', $export); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Apc.php b/lib/Doctrine/Cache/Apc.php index 079676da4..50244fd65 100644 --- a/lib/Doctrine/Cache/Apc.php +++ b/lib/Doctrine/Cache/Apc.php @@ -20,38 +20,40 @@ */ /** - * APC Cache Driver + * APC Cache Driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Cache_Apc extends Doctrine_Cache_Driver { /** - * constructor + * constructor. * - * @param array $options associative array of cache driver options + * @param array $options associative array of cache driver options */ public function __construct($options = array()) { - if ( ! extension_loaded('apc')) { + if (!extension_loaded('apc')) { throw new Doctrine_Cache_Exception('The apc extension must be loaded for using this backend !'); } parent::__construct($options); } /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { @@ -59,26 +61,29 @@ protected function _doFetch($id, $testCacheValidity = true) } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) { $found = false; apc_fetch($id, $found); + return $found; } /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false) { @@ -87,10 +92,11 @@ protected function _doSave($id, $data, $lifeTime = false) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { @@ -98,7 +104,7 @@ protected function _doDelete($id) } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ @@ -108,8 +114,9 @@ protected function _getCacheKeys() $keys = array(); foreach ($ci['cache_list'] as $entry) { - $keys[] = $entry['info']; + $keys[] = $entry['info']; } + return $keys; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Array.php b/lib/Doctrine/Cache/Array.php index 50188e892..26e9aa976 100644 --- a/lib/Doctrine/Cache/Array.php +++ b/lib/Doctrine/Cache/Array.php @@ -20,43 +20,47 @@ */ /** - * Array cache driver + * Array cache driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Cache_Array extends Doctrine_Cache_Driver { /** - * @var array $data an array of cached data + * @var array an array of cached data */ protected $data = array(); /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { if (isset($this->data[$id])) { return $this->data[$id]; } + return false; } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) @@ -66,12 +70,13 @@ protected function _doContains($id) /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) + * + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false) { @@ -82,10 +87,11 @@ protected function _doSave($id, $data, $lifeTime = false) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { @@ -97,7 +103,7 @@ protected function _doDelete($id) } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ @@ -105,4 +111,4 @@ protected function _getCacheKeys() { return array_keys($this->data); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Db.php b/lib/Doctrine/Cache/Db.php index 4fa89c54b..36275b72c 100644 --- a/lib/Doctrine/Cache/Db.php +++ b/lib/Doctrine/Cache/Db.php @@ -20,14 +20,15 @@ */ /** - * Database cache driver + * Database cache driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ @@ -35,30 +36,25 @@ class Doctrine_Cache_Db extends Doctrine_Cache_Driver { /** * Configure Database cache driver. Specify instance of Doctrine_Connection - * and tableName to store cache in - * - * @param array $_options an array of options + * and tableName to store cache in. */ public function __construct($options = array()) { - if ( ! isset($options['connection']) || - ! ($options['connection'] instanceof Doctrine_Connection)) { - + if (!isset($options['connection']) + || !($options['connection'] instanceof Doctrine_Connection)) { throw new Doctrine_Cache_Exception('Connection option not set.'); } - if ( ! isset($options['tableName']) || - ! is_string($options['tableName'])) { - - throw new Doctrine_Cache_Exception('Table name option not set.'); + if (!isset($options['tableName']) + || !is_string($options['tableName'])) { + throw new Doctrine_Cache_Exception('Table name option not set.'); } - $this->_options = $options; } /** - * Get the connection object associated with this cache driver + * Get the connection object associated with this cache driver. * * @return Doctrine_Connection $connection */ @@ -68,24 +64,25 @@ public function getConnection() } /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { - $sql = 'SELECT data, expire FROM ' . $this->_options['tableName'] - . ' WHERE id = ?'; + $sql = 'SELECT data, expire FROM '.$this->_options['tableName'] + .' WHERE id = ?'; if ($testCacheValidity) { - $sql .= " AND (expire is null OR expire > '" . date('Y-m-d H:i:s') . "')"; + $sql .= " AND (expire is null OR expire > '".date('Y-m-d H:i:s')."')"; } $result = $this->getConnection()->execute($sql, array($id))->fetchAll(Doctrine_Core::FETCH_NUM); - if ( ! isset($result[0])) { + if (!isset($result[0])) { return false; } @@ -93,57 +90,60 @@ protected function _doFetch($id, $testCacheValidity = true) } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) { - $sql = 'SELECT id, expire FROM ' . $this->_options['tableName'] - . ' WHERE id = ?'; + $sql = 'SELECT id, expire FROM '.$this->_options['tableName'] + .' WHERE id = ?'; $result = $this->getConnection()->fetchOne($sql, array($id)); - if (isset($result[0] )) { + if (isset($result[0])) { return time(); } + return false; } /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false, $saveKey = true) { if ($this->contains($id)) { - //record is in database, do update - $sql = 'UPDATE ' . $this->_options['tableName'] - . ' SET data = ?, expire=? ' - . ' WHERE id = ?'; + // record is in database, do update + $sql = 'UPDATE '.$this->_options['tableName'] + .' SET data = ?, expire=? ' + .' WHERE id = ?'; if ($lifeTime) { $expire = date('Y-m-d H:i:s', time() + $lifeTime); } else { - $expire = NULL; + $expire = null; } $params = array(bin2hex(serialize($data)), $expire, $id); } else { - //record is not in database, do insert - $sql = 'INSERT INTO ' . $this->_options['tableName'] - . ' (id, data, expire) VALUES (?, ?, ?)'; + // record is not in database, do insert + $sql = 'INSERT INTO '.$this->_options['tableName'] + .' (id, data, expire) VALUES (?, ?, ?)'; if ($lifeTime) { $expire = date('Y-m-d H:i:s', time() + $lifeTime); } else { - $expire = NULL; + $expire = null; } $params = array($id, bin2hex(serialize($data)), $expire); @@ -154,21 +154,21 @@ protected function _doSave($id, $data, $lifeTime = false, $saveKey = true) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { - $sql = 'DELETE FROM ' . $this->_options['tableName'] . ' WHERE id = ?'; + $sql = 'DELETE FROM '.$this->_options['tableName'].' WHERE id = ?'; + return $this->getConnection()->exec($sql, array($id)); } /** - * Create the cache table - * - * @return void + * Create the cache table. */ public function createTable() { @@ -176,19 +176,19 @@ public function createTable() $fields = array( 'id' => array( - 'type' => 'string', - 'length' => 255 + 'type' => 'string', + 'length' => 255, ), 'data' => array( - 'type' => 'blob' + 'type' => 'blob', ), 'expire' => array( - 'type' => 'timestamp' - ) + 'type' => 'timestamp', + ), ); $options = array( - 'primary' => array('id') + 'primary' => array('id'), ); $this->getConnection()->export->createTable($name, $fields, $options); @@ -199,34 +199,36 @@ public function createTable() * it is returned as is. * * @param string $hex + * * @return string $binary */ protected function _hex2bin($hex) { - if ( ! is_string($hex)) { + if (!is_string($hex)) { return null; } - if ( ! ctype_xdigit($hex)) { + if (!ctype_xdigit($hex)) { return $hex; } - return pack("H*", $hex); + return pack('H*', $hex); } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ protected function _getCacheKeys() { - $sql = 'SELECT id FROM ' . $this->_options['tableName']; + $sql = 'SELECT id FROM '.$this->_options['tableName']; $keys = array(); $results = $this->getConnection()->execute($sql)->fetchAll(Doctrine_Core::FETCH_NUM); - for ($i = 0, $count = count($results); $i < $count; $i++) { + for ($i = 0, $count = count($results); $i < $count; ++$i) { $keys[] = $results[$i][0]; } + return $keys; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Driver.php b/lib/Doctrine/Cache/Driver.php index 5bbf61d7b..7b74998d2 100644 --- a/lib/Doctrine/Cache/Driver.php +++ b/lib/Doctrine/Cache/Driver.php @@ -20,28 +20,27 @@ */ /** - * Abstract cache driver class + * Abstract cache driver class. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ abstract class Doctrine_Cache_Driver implements Doctrine_Cache_Interface { /** - * @var array $_options an array of options + * @var array an array of options */ protected $_options = array(); /** - * Configure cache driver with an array of options - * - * @param array $_options an array of options + * Configure cache driver with an array of options. */ public function __construct($options = array()) { @@ -49,30 +48,34 @@ public function __construct($options = array()) } /** - * Set option name and value + * Set option name and value. * - * @param mixed $option the option name - * @param mixed $value option value - * @return boolean TRUE on success, FALSE on failure + * @param mixed $option the option name + * @param mixed $value option value + * + * @return bool TRUE on success, FALSE on failure */ public function setOption($option, $value) { if (isset($this->_options[$option])) { $this->_options[$option] = $value; + return true; } + return false; } /** - * Get value of option + * Get value of option. + * + * @param mixed $option the option name * - * @param mixed $option the option name - * @return mixed option value + * @return mixed option value */ public function getOption($option) { - if ( ! isset($this->_options[$option])) { + if (!isset($this->_options[$option])) { return null; } @@ -80,68 +83,76 @@ public function getOption($option) } /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ public function fetch($id, $testCacheValidity = true) { $key = $this->_getKey($id); + return $this->_doFetch($key, $testCacheValidity); } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ public function contains($id) { $key = $this->_getKey($id); + return $this->_doContains($key); } /** - * Save some string datas into a cache record + * Save some string datas into a cache record. + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ public function save($id, $data, $lifeTime = false) { $key = $this->_getKey($id); + return $this->_doSave($key, $data, $lifeTime); } /** - * Remove a cache record + * Remove a cache record. * * Note: This method accepts wildcards with the * character * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ public function delete($id) { $key = $this->_getKey($id); - if (strpos($key, '*') !== false) { - return $this->deleteByRegex('/' . str_replace('*', '.*', $key) . '/'); + if (false !== strpos($key, '*')) { + return $this->deleteByRegex('/'.str_replace('*', '.*', $key).'/'); } return $this->_doDelete($key); } /** - * Delete cache entries where the key matches a PHP regular expressions + * Delete cache entries where the key matches a PHP regular expressions. * * @param string $regex - * @return integer $count The number of deleted cache entries + * + * @return int $count The number of deleted cache entries */ public function deleteByRegex($regex) { @@ -150,19 +161,21 @@ public function deleteByRegex($regex) if (is_array($keys)) { foreach ($keys as $key) { if (preg_match($regex, $key)) { - $count++; + ++$count; $this->delete($key); } } } + return $count; } /** - * Delete cache entries where the key has the passed prefix + * Delete cache entries where the key has the passed prefix. * * @param string $prefix - * @return integer $count The number of deleted cache entries + * + * @return int $count The number of deleted cache entries */ public function deleteByPrefix($prefix) { @@ -170,20 +183,22 @@ public function deleteByPrefix($prefix) $keys = $this->_getCacheKeys(); if (is_array($keys)) { foreach ($keys as $key) { - if (strpos($key, $prefix) === 0) { - $count++; + if (0 === strpos($key, $prefix)) { + ++$count; $this->delete($key); } } } + return $count; } /** - * Delete cache entries where the key has the passed suffix + * Delete cache entries where the key has the passed suffix. * * @param string $suffix - * @return integer $count The number of deleted cache entries + * + * @return int $count The number of deleted cache entries */ public function deleteBySuffix($suffix) { @@ -192,89 +207,96 @@ public function deleteBySuffix($suffix) if (is_array($keys)) { foreach ($keys as $key) { if (substr($key, -1 * strlen($suffix)) == $suffix) { - $count++; + ++$count; $this->delete($key); } } } + return $count; } /** - * Delete all cache entries from the cache driver - * - * @return integer $count The number of deleted cache entries + * Delete all cache entries from the cache driver. + * + * @return int $count The number of deleted cache entries */ - public function deleteAll() + public function deleteAll() { $count = 0; if (is_array($keys = $this->_getCacheKeys())) { foreach ($keys as $key) { - $count++; + ++$count; $this->delete($key); } } + return $count; } /** - * Get the hash key passing its suffix + * Get the hash key passing its suffix. * - * @param string $id The hash key suffix - * @return string Hash key to be used by drivers + * @param string $id The hash key suffix + * + * @return string Hash key to be used by drivers */ protected function _getKey($id) { $prefix = isset($this->_options['prefix']) ? $this->_options['prefix'] : ''; - if ( ! $prefix || strpos($id, $prefix) === 0) { + if (!$prefix || 0 === strpos($id, $prefix)) { return $id; - } else { - return $prefix . $id; } + + return $prefix.$id; } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ abstract protected function _getCacheKeys(); /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ abstract protected function _doFetch($id, $testCacheValidity = true); /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ abstract protected function _doContains($id); /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ abstract protected function _doSave($id, $data, $lifeTime = false); /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ abstract protected function _doDelete($id); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Exception.php b/lib/Doctrine/Cache/Exception.php index 1fa224e8d..998a51710 100644 --- a/lib/Doctrine/Cache/Exception.php +++ b/lib/Doctrine/Cache/Exception.php @@ -20,17 +20,18 @@ */ /** - * Doctrine cache exception class + * Doctrine cache exception class. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Cache_Exception extends Doctrine_Exception { -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Interface.php b/lib/Doctrine/Cache/Interface.php index d6e103f49..1274cf75f 100644 --- a/lib/Doctrine/Cache/Interface.php +++ b/lib/Doctrine/Cache/Interface.php @@ -20,51 +20,56 @@ */ /** - * Doctrine cache driver interface + * Doctrine cache driver interface. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ interface Doctrine_Cache_Interface { /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ public function fetch($id, $testCacheValidity = true); /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ public function contains($id); /** - * Save a cache record and add the key to the index of cached keys + * Save a cache record and add the key to the index of cached keys. * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) + * + * @return bool true if no problem */ public function save($id, $data, $lifeTime = false); /** - * Remove a cache record + * Remove a cache record. * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ public function delete($id); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Memcache.php b/lib/Doctrine/Cache/Memcache.php index f366c204d..ab0afa8cf 100644 --- a/lib/Doctrine/Cache/Memcache.php +++ b/lib/Doctrine/Cache/Memcache.php @@ -20,38 +20,39 @@ */ /** - * Memcache cache driver + * Memcache cache driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Cache_Memcache extends Doctrine_Cache_Driver { /** - * @var Memcache $_memcache memcache object + * @var Memcache memcache object */ - protected $_memcache = null; + protected $_memcache; /** - * constructor + * constructor. * - * @param array $options associative array of cache driver options + * @param array $options associative array of cache driver options */ public function __construct($options = array()) { - if ( ! extension_loaded('memcache')) { + if (!extension_loaded('memcache')) { throw new Doctrine_Cache_Exception('In order to use Memcache driver, the memcache extension must be loaded.'); } parent::__construct($options); if (isset($options['servers'])) { - $value= $options['servers']; + $value = $options['servers']; if (isset($value['host'])) { // in this case, $value seems to be a simple associative array (one server only) $value = array(0 => $value); // let's transform it into a classical array of associative arrays @@ -59,13 +60,13 @@ public function __construct($options = array()) $this->setOption('servers', $value); } - $this->_memcache = new Memcache; + $this->_memcache = new Memcache(); foreach ($this->_options['servers'] as $server) { - if ( ! array_key_exists('persistent', $server)) { + if (!array_key_exists('persistent', $server)) { $server['persistent'] = true; } - if ( ! array_key_exists('port', $server)) { + if (!array_key_exists('port', $server)) { $server['port'] = 11211; } $this->_memcache->addServer($server['host'], $server['port'], $server['persistent']); @@ -73,10 +74,11 @@ public function __construct($options = array()) } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id - * @return mixed Returns either the cached data or false + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { @@ -84,9 +86,10 @@ protected function _doFetch($id, $testCacheValidity = true) } /** - * Test if a cache is available or not (for the given id) + * Test if a cache is available or not (for the given id). * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) @@ -96,12 +99,13 @@ protected function _doContains($id) /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false) { @@ -116,10 +120,11 @@ protected function _doSave($id, $data, $lifeTime = false) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { @@ -127,7 +132,7 @@ protected function _doDelete($id) } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ @@ -146,6 +151,7 @@ protected function _getCacheKeys() } } } + return $keys; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Xcache.php b/lib/Doctrine/Cache/Xcache.php index 6415277e3..a24161e29 100644 --- a/lib/Doctrine/Cache/Xcache.php +++ b/lib/Doctrine/Cache/Xcache.php @@ -20,14 +20,15 @@ */ /** - * Xcache cache driver + * Xcache cache driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: $ + * * @author Dmitry Bakaleinik (dima@snaiper.net) * @author Konsta Vesterinen * @author Jonathan H. Wage @@ -35,13 +36,13 @@ class Doctrine_Cache_Xcache extends Doctrine_Cache_Driver { /** - * constructor + * constructor. * - * @param array $options associative array of cache driver options + * @param array $options associative array of cache driver options */ public function __construct($options = array()) { - if ( ! extension_loaded('xcache') ) { + if (!extension_loaded('xcache')) { throw new Doctrine_Cache_Exception('In order to use Xcache driver, the xcache extension must be loaded.'); } @@ -49,10 +50,11 @@ public function __construct($options = array()) } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id - * @return mixed Returns either the cached data or false + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { @@ -60,9 +62,10 @@ protected function _doFetch($id, $testCacheValidity = true) } /** - * Test if a cache is available or not (for the given id) + * Test if a cache is available or not (for the given id). * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) @@ -72,12 +75,13 @@ protected function _doContains($id) /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false) { @@ -86,10 +90,11 @@ protected function _doSave($id, $data, $lifeTime = false) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { @@ -97,7 +102,7 @@ protected function _doDelete($id) } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ @@ -105,7 +110,7 @@ protected function _getCacheKeys() { $this->checkAuth(); $keys = array(); - for ($i = 0, $count = xcache_count(XC_TYPE_VAR); $i < $count; $i++) { + for ($i = 0, $count = xcache_count(XC_TYPE_VAR); $i < $count; ++$i) { $entries = xcache_list(XC_TYPE_VAR, $i); if (is_array($entries['cache_list'])) { foreach ($entries['cache_list'] as $entry) { @@ -113,14 +118,14 @@ protected function _getCacheKeys() } } } + return $keys; } /** - * Checks that xcache.admin.enable_auth is Off + * Checks that xcache.admin.enable_auth is Off. * * @throws Doctrine_Cache_Exception When xcache.admin.enable_auth is On - * @return void */ protected function checkAuth() { @@ -128,4 +133,4 @@ protected function checkAuth() throw new Doctrine_Cache_Exception('To use all features of Doctrine_Cache_Xcache, you must set "xcache.admin.enable_auth" to "Off" in your php.ini.'); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cli.php b/lib/Doctrine/Cli.php index f6cd3dd4f..93ca97ab3 100644 --- a/lib/Doctrine/Cli.php +++ b/lib/Doctrine/Cli.php @@ -20,31 +20,32 @@ */ /** - * Command line interface class - * + * Command line interface class. + * * Interface for easily executing Doctrine_Task classes from a command line interface * - * @package Doctrine - * @subpackage Cli * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Cli { /** - * The name of the Doctrine Task base class - * + * The name of the Doctrine Task base class. + * * @var string */ - const TASK_BASE_CLASS = 'Doctrine_Task'; + public const TASK_BASE_CLASS = 'Doctrine_Task'; /** * @var string */ - protected $_scriptName = null; + protected $_scriptName; /** * @var array @@ -57,8 +58,8 @@ class Doctrine_Cli private $_formatter; /** - * An array, keyed on class name, containing task instances - * + * An array, keyed on class name, containing task instances. + * * @var array */ private $_registeredTask = array(); @@ -69,7 +70,7 @@ class Doctrine_Cli private $_taskInstance; /** - * __construct + * __construct. * * @param array [$config=array()] * @param object|null [$formatter=null] Doctrine_Cli_Formatter @@ -81,9 +82,6 @@ public function __construct(array $config = array(), Doctrine_Cli_Formatter $for $this->includeAndRegisterTaskClasses(); } - /** - * @param array $config - */ public function setConfig(array $config) { $this->_config = $config; @@ -114,15 +112,15 @@ public function getFormatter() } /** - * Returns the specified value from the config, or the default value, if specified - * + * Returns the specified value from the config, or the default value, if specified. + * * @param string $name - * @return mixed + * * @throws OutOfBoundsException If the element does not exist in the config */ - public function getConfigValue($name/*, $defaultValue*/) + public function getConfigValue($name/* , $defaultValue */) { - if (! isset($this->_config[$name])) { + if (!isset($this->_config[$name])) { if (func_num_args() > 1) { return func_get_arg(1); } @@ -134,16 +132,17 @@ public function getConfigValue($name/*, $defaultValue*/) } /** - * Returns TRUE if the element in the config has the specified value, or FALSE otherwise - * + * Returns TRUE if the element in the config has the specified value, or FALSE otherwise. + * * If $value is not passed, this method will return TRUE if the specified element has _any_ value, or FALSE if the * element is not set - * + * * For strict checking, set $strict to TRUE - the default is FALSE - * + * * @param string $name * @param mixed [$value=null] * @param bool [$strict=false] + * * @return bool */ public function hasConfigValue($name, $value = null, $strict = false) @@ -164,9 +163,7 @@ public function hasConfigValue($name, $value = null, $strict = false) } /** - * Sets the array of registered tasks - * - * @param array $registeredTask + * Sets the array of registered tasks. */ public function setRegisteredTasks(array $registeredTask) { @@ -174,8 +171,8 @@ public function setRegisteredTasks(array $registeredTask) } /** - * Returns an array containing the registered tasks - * + * Returns an array containing the registered tasks. + * * @return array */ public function getRegisteredTasks() @@ -184,9 +181,10 @@ public function getRegisteredTasks() } /** - * Returns TRUE if the specified Task-class is registered, or FALSE otherwise - * + * Returns TRUE if the specified Task-class is registered, or FALSE otherwise. + * * @param string $className + * * @return bool */ public function taskClassIsRegistered($className) @@ -195,12 +193,13 @@ public function taskClassIsRegistered($className) } /** - * Returns TRUE if a task with the specified name is registered, or FALSE otherwise - * + * Returns TRUE if a task with the specified name is registered, or FALSE otherwise. + * * If a matching task is found, $className is set with the name of the implementing class - * + * * @param string $taskName * @param string|null [&$className=null] + * * @return bool */ public function taskNameIsRegistered($taskName, &$className = null) @@ -208,6 +207,7 @@ public function taskNameIsRegistered($taskName, &$className = null) foreach ($this->getRegisteredTasks() as $currClassName => $task) { if ($task->getTaskName() == $taskName) { $className = $currClassName; + return true; } } @@ -233,8 +233,8 @@ public function getTaskInstance() /** * Called by the constructor, this method includes and registers Doctrine core Tasks and then registers all other - * loaded Task classes - * + * loaded Task classes. + * * The second round of registering will pick-up loaded custom Tasks. Methods are provided that will allow users to * register Tasks loaded after creating an instance of Doctrine_Cli. */ @@ -242,23 +242,23 @@ protected function includeAndRegisterTaskClasses() { $this->includeAndRegisterDoctrineTaskClasses(); - //Always autoregister custom tasks _unless_ we've been explicitly asked not to + // Always autoregister custom tasks _unless_ we've been explicitly asked not to if ($this->getConfigValue('autoregister_custom_tasks', true)) { $this->registerIncludedTaskClasses(); } } /** - * Includes and registers Doctrine-style tasks from the specified directory / directories - * + * Includes and registers Doctrine-style tasks from the specified directory / directories. + * * If no directory is given it looks in the default Doctrine/Task folder for the core tasks - * + * * @param mixed [$directories=null] Can be a string path or array of paths */ protected function includeAndRegisterDoctrineTaskClasses($directories = null) { if (is_null($directories)) { - $directories = Doctrine_Core::getPath() . DIRECTORY_SEPARATOR . 'Doctrine' . DIRECTORY_SEPARATOR . 'Task'; + $directories = Doctrine_Core::getPath().DIRECTORY_SEPARATOR.'Doctrine'.DIRECTORY_SEPARATOR.'Task'; } foreach ((array) $directories as $directory) { @@ -269,24 +269,26 @@ protected function includeAndRegisterDoctrineTaskClasses($directories = null) } /** - * Attempts to include Doctrine-style Task-classes from the specified directory - and nothing more besides - * + * Attempts to include Doctrine-style Task-classes from the specified directory - and nothing more besides. + * * Returns an array containing the names of Task classes included - * + * * This method effectively makes two assumptions: * - The directory contains only _Task_ class-files * - The class files, and the class in each, follow the Doctrine naming conventions - * + * * This means that a file called "Foo.php", say, will be expected to contain a Task class called * "Doctrine_Task_Foo". Hence the method's name, "include*Doctrine*TaskClasses". - * + * * @param string $directory + * * @return array $taskClassesIncluded + * * @throws InvalidArgumentException If the directory does not exist */ protected function includeDoctrineTaskClasses($directory) { - if (! is_dir($directory)) { + if (!is_dir($directory)) { throw new InvalidArgumentException("The directory \"{$directory}\" does not exist"); } @@ -306,17 +308,17 @@ protected function includeDoctrineTaskClasses($directory) */ $matched = (bool) preg_match('/^([A-Z].*?)\.php$/', $baseName, $matches); - if ( ! ($matched && (strpos($baseName, '.inc') === false))) { + if (!($matched && (false === strpos($baseName, '.inc')))) { continue; } - $expectedClassName = self::TASK_BASE_CLASS . '_' . $matches[1]; + $expectedClassName = self::TASK_BASE_CLASS.'_'.$matches[1]; - if ( ! class_exists($expectedClassName)) { - require_once($file->getPathName()); + if (!class_exists($expectedClassName)) { + require_once $file->getPathName(); } - //So was the expected class included, and is it a task? If so, we'll let the calling function know. + // So was the expected class included, and is it a task? If so, we'll let the calling function know. if (class_exists($expectedClassName, false) && $this->classIsTask($expectedClassName)) { $taskClassesIncluded[] = $expectedClassName; } @@ -326,24 +328,25 @@ protected function includeDoctrineTaskClasses($directory) } /** - * Registers the specified _included_ task-class - * + * Registers the specified _included_ task-class. + * * @param string $className + * * @throws InvalidArgumentException If the class does not exist or the task-name is blank - * @throws DomainException If the class is not a Doctrine Task + * @throws DomainException If the class is not a Doctrine Task */ public function registerTaskClass($className) { - //Simply ignore registered classes + // Simply ignore registered classes if ($this->taskClassIsRegistered($className)) { return; } - if ( ! class_exists($className/*, false*/)) { + if (!class_exists($className/* , false */)) { throw new InvalidArgumentException("The task class \"{$className}\" does not exist"); } - if ( ! $this->classIsTask($className)) { + if (!$this->classIsTask($className)) { throw new DomainException("The class \"{$className}\" is not a Doctrine Task"); } @@ -351,24 +354,27 @@ public function registerTaskClass($className) } /** - * Returns TRUE if the specified class is a Task, or FALSE otherwise - * + * Returns TRUE if the specified class is a Task, or FALSE otherwise. + * * @param string $className + * * @return bool */ protected function classIsTask($className) { $reflectionClass = new ReflectionClass($className); + return (bool) $reflectionClass->isSubclassOf(self::TASK_BASE_CLASS); } /** - * Creates, and returns, a new instance of the specified Task class - * + * Creates, and returns, a new instance of the specified Task class. + * * Displays a message, and returns FALSE, if there were problems instantiating the class - * + * * @param string $className - * @param object $cli Doctrine_Cli + * @param object $cli Doctrine_Cli + * * @return object Doctrine_Task */ protected function createTaskInstance($className, Doctrine_Cli $cli) @@ -377,8 +383,8 @@ protected function createTaskInstance($className, Doctrine_Cli $cli) } /** - * Registers all loaded classes - by default - or the specified loaded Task classes - * + * Registers all loaded classes - by default - or the specified loaded Task classes. + * * This method will skip registered task classes, so it can be safely called many times over */ public function registerIncludedTaskClasses() @@ -391,26 +397,23 @@ public function registerIncludedTaskClasses() } /** - * Notify the formatter of a message + * Notify the formatter of a message. * - * @param string $notification The notification message - * @param string $style Style to format the notification with(INFO, ERROR) - * @return void + * @param string $notification The notification message + * @param string $style Style to format the notification with(INFO, ERROR) */ public function notify($notification = null, $style = 'HEADER') { $formatter = $this->getFormatter(); - echo( - $formatter->format($this->getTaskInstance()->getTaskName(), 'INFO') . ' - ' . - $formatter->format($notification, $style) . "\n" - ); + echo + $formatter->format($this->getTaskInstance()->getTaskName(), 'INFO').' - '. + $formatter->format($notification, $style)."\n"; } /** - * Formats, and then returns, the message in the specified exception + * Formats, and then returns, the message in the specified exception. * - * @param Exception $exception * @return string */ protected function formatExceptionMessage(Exception $exception) @@ -418,20 +421,17 @@ protected function formatExceptionMessage(Exception $exception) $message = $exception->getMessage(); if (Doctrine_Core::debug()) { - $message .= "\n" . $exception->getTraceAsString(); + $message .= "\n".$exception->getTraceAsString(); } - return $this->getFormatter()->format($message, 'ERROR') . "\n"; + return $this->getFormatter()->format($message, 'ERROR')."\n"; } /** - * Notify the formatter of an exception - * + * Notify the formatter of an exception. + * * N.B. This should really only be called by Doctrine_Cli::run(). Exceptions should be thrown when errors occur: * it's up to Doctrine_Cli::run() to determine how those exceptions are reported. - * - * @param Exception $exception - * @return void */ protected function notifyException(Exception $exception) { @@ -439,11 +439,10 @@ protected function notifyException(Exception $exception) } /** - * Public function to run the loaded task with the passed arguments + * Public function to run the loaded task with the passed arguments. * - * @param array $args - * @return void * @throws Doctrine_Cli_Exception + * * @todo Should know more about what we're attempting to run so feedback can be improved. Continue refactoring. */ public function run(array $args) @@ -451,14 +450,14 @@ public function run(array $args) try { $this->_run($args); } catch (Exception $exception) { - //Do not rethrow exceptions by default + // Do not rethrow exceptions by default if ($this->getConfigValue('rethrow_exceptions', false)) { throw new $exception($this->formatExceptionMessage($exception)); } $this->notifyException($exception); - //User error + // User error if ($exception instanceof Doctrine_Cli_Exception) { $this->printTasks(); } @@ -466,30 +465,33 @@ public function run(array $args) } /** - * Run the actual task execution with the passed arguments + * Run the actual task execution with the passed arguments. + * + * @param array $args Array of arguments for this task being executed * - * @param array $args Array of arguments for this task being executed - * @return void * @throws Doctrine_Cli_Exception If the requested task has not been registered or if required arguments are missing + * * @todo Continue refactoring for testing */ protected function _run(array $args) - { + { $this->_scriptName = $args[0]; - + $requestedTaskName = isset($args[1]) ? $args[1] : null; - - if ( ! $requestedTaskName || $requestedTaskName == 'help') { - $this->printTasks(null, $requestedTaskName == 'help' ? true : false); + + if (!$requestedTaskName || 'help' == $requestedTaskName) { + $this->printTasks(null, 'help' == $requestedTaskName ? true : false); + return; } - - if ($requestedTaskName && isset($args[2]) && $args[2] === 'help') { + + if ($requestedTaskName && isset($args[2]) && 'help' === $args[2]) { $this->printTasks($requestedTaskName, true); + return; } - if (! $this->taskNameIsRegistered($requestedTaskName, $taskClassName)) { + if (!$this->taskNameIsRegistered($requestedTaskName, $taskClassName)) { throw new Doctrine_Cli_Exception("The task \"{$requestedTaskName}\" has not been registered"); } @@ -499,17 +501,17 @@ protected function _run(array $args) } /** - * Executes the task with the specified _prepared_ arguments - * + * Executes the task with the specified _prepared_ arguments. + * * @param object $task Doctrine_Task - * @param array $preparedArguments + * * @throws Doctrine_Cli_Exception If required arguments are missing */ protected function executeTask(Doctrine_Task $task, array $preparedArguments) { $task->setArguments($preparedArguments); - if (! $task->validate()) { + if (!$task->validate()) { throw new Doctrine_Cli_Exception('Required arguments missing'); } @@ -518,56 +520,59 @@ protected function executeTask(Doctrine_Task $task, array $preparedArguments) /** * Prepare the raw arguments for execution. Combines with the required and optional argument - * list in order to determine a complete array of arguments for the task + * list in order to determine a complete array of arguments for the task. + * + * @param array $args Array of raw arguments * - * @param array $args Array of raw arguments * @return array $prepared Array of prepared arguments + * * @todo Continue refactoring for testing */ protected function prepareArgs(array $args) { $taskInstance = $this->getTaskInstance(); - + $args = array_values($args); - + // First lets load populate an array with all the possible arguments. required and optional $prepared = array(); - + $requiredArguments = $taskInstance->getRequiredArguments(); foreach ($requiredArguments as $key => $arg) { $prepared[$arg] = null; } - + $optionalArguments = $taskInstance->getOptionalArguments(); foreach ($optionalArguments as $key => $arg) { $prepared[$arg] = null; } - + // If we have a config array then lets try and fill some of the arguments with the config values foreach ($this->getConfig() as $key => $value) { if (array_key_exists($key, $prepared)) { $prepared[$key] = $value; } } - + // Now lets fill in the entered arguments to the prepared array $copy = $args; foreach ($prepared as $key => $value) { - if ( ! $value && !empty($copy)) { + if (!$value && !empty($copy)) { $prepared[$key] = $copy[0]; unset($copy[0]); $copy = array_values($copy); } } - + return $prepared; } /** - * Prints an index of all the available tasks in the CLI instance - * + * Prints an index of all the available tasks in the CLI instance. + * * @param string|null [$taskName=null] * @param bool [$full=false] + * * @todo Continue refactoring for testing */ public function printTasks($taskName = null, $full = false) @@ -575,27 +580,27 @@ public function printTasks($taskName = null, $full = false) $formatter = $this->getFormatter(); $config = $this->getConfig(); - $taskIndex = $formatter->format('Doctrine Command Line Interface', 'HEADER') . "\n\n"; + $taskIndex = $formatter->format('Doctrine Command Line Interface', 'HEADER')."\n\n"; foreach ($this->getRegisteredTasks() as $task) { if ($taskName && (strtolower($taskName) != strtolower($task->getTaskName()))) { continue; } - $taskIndex .= $formatter->format($this->_scriptName . ' ' . $task->getTaskName(), 'INFO'); + $taskIndex .= $formatter->format($this->_scriptName.' '.$task->getTaskName(), 'INFO'); if ($full) { - $taskIndex .= ' - ' . $task->getDescription() . "\n"; + $taskIndex .= ' - '.$task->getDescription()."\n"; $args = ''; $args .= $this->assembleArgumentList($task->getRequiredArgumentsDescriptions(), $config, $formatter); $args .= $this->assembleArgumentList($task->getOptionalArgumentsDescriptions(), $config, $formatter); if ($args) { - $taskIndex .= "\n" . $formatter->format('Arguments:', 'HEADER') . "\n" . $args; + $taskIndex .= "\n".$formatter->format('Arguments:', 'HEADER')."\n".$args; } } - + $taskIndex .= "\n"; } @@ -603,9 +608,8 @@ public function printTasks($taskName = null, $full = false) } /** - * @param array $argumentsDescriptions - * @param array $config * @param object $formatter Doctrine_Cli_Formatter + * * @return string */ protected function assembleArgumentList(array $argumentsDescriptions, array $config, Doctrine_Cli_Formatter $formatter) @@ -613,8 +617,8 @@ protected function assembleArgumentList(array $argumentsDescriptions, array $con $argumentList = ''; foreach ($argumentsDescriptions as $name => $description) { - $argumentList .= $formatter->format($name, 'ERROR') . ' - '; - + $argumentList .= $formatter->format($name, 'ERROR').' - '; + if (isset($config[$name])) { $argumentList .= $formatter->format($config[$name], 'COMMENT'); } else { @@ -628,10 +632,10 @@ protected function assembleArgumentList(array $argumentsDescriptions, array $con } /** - * Used by Doctrine_Cli::loadTasks() and Doctrine_Cli::getLoadedTasks() to re-create their pre-refactoring behaviour - * + * Used by Doctrine_Cli::loadTasks() and Doctrine_Cli::getLoadedTasks() to re-create their pre-refactoring behaviour. + * * @ignore - * @param array $registeredTask + * * @return array */ private function createOldStyleTaskList(array $registeredTask) @@ -647,33 +651,36 @@ private function createOldStyleTaskList(array $registeredTask) } /** - * Old method retained for backwards compatibility - * + * Old method retained for backwards compatibility. + * * @deprecated + * + * @param mixed|null $directory */ public function loadTasks($directory = null) { $this->includeAndRegisterDoctrineTaskClasses($directory); + return $this->createOldStyleTaskList($this->getRegisteredTasks()); } /** - * Old method retained for backwards compatibility - * + * Old method retained for backwards compatibility. + * * @deprecated */ protected function _getTaskClassFromArgs(array $args) { - return self::TASK_BASE_CLASS . '_' . Doctrine_Inflector::classify(str_replace('-', '_', $args[1])); + return self::TASK_BASE_CLASS.'_'.Doctrine_Inflector::classify(str_replace('-', '_', $args[1])); } /** - * Old method retained for backwards compatibility - * + * Old method retained for backwards compatibility. + * * @deprecated */ public function getLoadedTasks() { return $this->createOldStyleTaskList($this->getRegisteredTasks()); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cli/AnsiColorFormatter.php b/lib/Doctrine/Cli/AnsiColorFormatter.php index cca3afb7d..a443baa5a 100644 --- a/lib/Doctrine/Cli/AnsiColorFormatter.php +++ b/lib/Doctrine/Cli/AnsiColorFormatter.php @@ -29,29 +29,28 @@ /** * Doctrine_AnsiColorFormatter provides methods to colorize text to be displayed on a console. - * This class was taken from the symfony-project source + * This class was taken from the symfony-project source. * - * @package Doctrine - * @subpackage Cli * @author Fabien Potencier * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 4252 $ */ class Doctrine_Cli_AnsiColorFormatter extends Doctrine_Cli_Formatter { - protected - $_styles = array( - 'HEADER' => array('fg' => 'black', 'bold' => true), - 'ERROR' => array('bg' => 'red', 'fg' => 'white', 'bold' => true), - 'INFO' => array('fg' => 'green', 'bold' => true), - 'COMMENT' => array('fg' => 'yellow'), - ), - $_options = array('bold' => 1, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, 'conceal' => 8), - $_foreground = array('black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'white' => 37), - $_background = array('black' => 40, 'red' => 41, 'green' => 42, 'yellow' => 43, 'blue' => 44, 'magenta' => 45, 'cyan' => 46, 'white' => 47); + protected $_styles = array( + 'HEADER' => array('fg' => 'black', 'bold' => true), + 'ERROR' => array('bg' => 'red', 'fg' => 'white', 'bold' => true), + 'INFO' => array('fg' => 'green', 'bold' => true), + 'COMMENT' => array('fg' => 'yellow'), + ); + protected $_options = array('bold' => 1, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, 'conceal' => 8); + protected $_foreground = array('black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'white' => 37); + protected $_background = array('black' => 40, 'red' => 41, 'green' => 42, 'yellow' => 43, 'blue' => 44, 'magenta' => 45, 'cyan' => 46, 'white' => 47); /** * Sets a new style. @@ -74,15 +73,15 @@ public function setStyle($name, $options = array()) */ public function format($text = '', $parameters = array(), $stream = STDOUT) { - if ( ! $this->supportsColors($stream)) { + if (!$this->supportsColors($stream)) { return $text; } - if ( ! is_array($parameters) && 'NONE' == $parameters) { + if (!is_array($parameters) && 'NONE' == $parameters) { return $text; } - if ( ! is_array($parameters) && isset($this->_styles[$parameters])) { + if (!is_array($parameters) && isset($this->_styles[$parameters])) { $parameters = $this->_styles[$parameters]; } @@ -90,11 +89,11 @@ public function format($text = '', $parameters = array(), $stream = STDOUT) if (isset($parameters['fg'])) { $codes[] = $this->_foreground[$parameters['fg']]; } - + if (isset($parameters['bg'])) { $codes[] = $this->_background[$parameters['bg']]; } - + foreach ($this->_options as $option => $value) { if (isset($parameters[$option]) && $parameters[$option]) { $codes[] = $value; @@ -109,7 +108,8 @@ public function format($text = '', $parameters = array(), $stream = STDOUT) * * @param string The section name * @param string The text message - * @param integer The maximum size allowed for a line (65 by default) + * @param int The maximum size allowed for a line (65 by default) + * @param mixed|null $size */ public function formatSection($section, $text, $size = null) { @@ -122,13 +122,14 @@ public function formatSection($section, $text, $size = null) * Truncates a line. * * @param string The text - * @param integer The maximum size of the returned string (65 by default) + * @param int The maximum size of the returned string (65 by default) + * @param mixed|null $size * * @return string The truncated string */ public function excerpt($text, $size = null) { - if ( ! $size) { + if (!$size) { $size = $this->size; } @@ -138,7 +139,7 @@ public function excerpt($text, $size = null) $subsize = floor(($size - 3) / 2); - return substr($text, 0, $subsize) . $this->format('...', 'INFO').substr($text, -$subsize); + return substr($text, 0, $subsize).$this->format('...', 'INFO').substr($text, -$subsize); } /** @@ -151,10 +152,10 @@ public function excerpt($text, $size = null) * * @param mixed A stream * - * @return Boolean true if the stream supports colorization, false otherwise + * @return bool true if the stream supports colorization, false otherwise */ public function supportsColors($stream) { return DIRECTORY_SEPARATOR != '\\' && function_exists('posix_isatty') && @posix_isatty($stream); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cli/Exception.php b/lib/Doctrine/Cli/Exception.php index a8c441072..2f12ddf21 100644 --- a/lib/Doctrine/Cli/Exception.php +++ b/lib/Doctrine/Cli/Exception.php @@ -20,15 +20,17 @@ */ /** - * Cli exception class + * Cli exception class. * - * @package Doctrine - * @subpackage Cli * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Cli_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Cli/Formatter.php b/lib/Doctrine/Cli/Formatter.php index 4ba794505..486729ff3 100644 --- a/lib/Doctrine/Cli/Formatter.php +++ b/lib/Doctrine/Cli/Formatter.php @@ -29,15 +29,15 @@ /** * Doctrine_Cli_Formatter provides methods to format text to be displayed on a console. - * This class was taken from the symfony-project source + * This class was taken from the symfony-project source. * - * @package Doctrine - * @subpackage Cli * @author Fabien Potencier * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ */ class Doctrine_Cli_Formatter @@ -45,12 +45,11 @@ class Doctrine_Cli_Formatter protected $_size = 65; /** - * __construct + * __construct. * - * @param string $maxLineSize - * @return void + * @param string $maxLineSize */ - function __construct($maxLineSize = 65) + public function __construct($maxLineSize = 65) { $this->_size = $maxLineSize; } @@ -74,24 +73,26 @@ public function format($text = '', $parameters = array(), $stream = STDOUT) * * @param string The section name * @param string The text message - * @param integer The maximum size allowed for a line (65 by default) + * @param int The maximum size allowed for a line (65 by default) + * @param mixed|null $size */ public function formatSection($section, $text, $size = null) { - return sprintf(">> %-$9s %s", $section, $this->excerpt($text, $size)); + return sprintf('>> %-$9s %s', $section, $this->excerpt($text, $size)); } /** * Truncates a line. * * @param string The text - * @param integer The maximum size of the returned string (65 by default) + * @param int The maximum size of the returned string (65 by default) + * @param mixed|null $size * * @return string The truncated string */ public function excerpt($text, $size = null) { - if ( ! $size) { + if (!$size) { $size = $this->_size; } @@ -107,10 +108,10 @@ public function excerpt($text, $size = null) /** * Sets the maximum line size. * - * @param integer The maximum line size for a message + * @param int The maximum line size for a message */ public function setMaxLineSize($size) { $this->_size = $size; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Collection.php b/lib/Doctrine/Collection.php index 25b7ca441..8095b7d19 100644 --- a/lib/Doctrine/Collection.php +++ b/lib/Doctrine/Collection.php @@ -23,86 +23,86 @@ * Doctrine_Collection * Collection of Doctrine_Record objects. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7686 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection extends Doctrine_Access implements Countable, IteratorAggregate, Serializable { /** - * @var array $data an array containing the records of this collection + * @var array an array containing the records of this collection */ protected $data = array(); /** - * @var Doctrine_Table $table each collection has only records of specified table + * @var Doctrine_Table each collection has only records of specified table */ protected $_table; /** - * @var array $_snapshot a snapshot of the fetched data + * @var array a snapshot of the fetched data */ protected $_snapshot = array(); /** - * @var Doctrine_Record $reference collection can belong to a record + * @var Doctrine_Record collection can belong to a record */ protected $reference; /** - * @var string $referenceField the reference field of the collection + * @var string the reference field of the collection */ protected $referenceField; /** - * @var Doctrine_Relation the record this collection is related to, if any + * @var Doctrine_Relation the record this collection is related to, if any */ protected $relation; /** - * @var string $keyColumn the name of the column that is used for collection key mapping + * @var string the name of the column that is used for collection key mapping */ protected $keyColumn; /** - * @var Doctrine_Null $null used for extremely fast null value testing + * @var Doctrine_Null used for extremely fast null value testing */ protected static $null; /** - * constructor + * constructor. * * @param Doctrine_Table|string $table + * @param mixed|null $keyColumn */ public function __construct($table, $keyColumn = null) { - if ( ! ($table instanceof Doctrine_Table)) { + if (!($table instanceof Doctrine_Table)) { $table = Doctrine_Core::getTable($table); } $this->_table = $table; - if ($keyColumn === null) { + if (null === $keyColumn) { $keyColumn = $table->getBoundQueryPart('indexBy'); } - if ($keyColumn === null) { - $keyColumn = $table->getAttribute(Doctrine_Core::ATTR_COLL_KEY); + if (null === $keyColumn) { + $keyColumn = $table->getAttribute(Doctrine_Core::ATTR_COLL_KEY); } - if ($keyColumn !== null) { + if (null !== $keyColumn) { $this->keyColumn = $keyColumn; } } /** - * Initializes the null object for this collection - * - * @return void + * Initializes the null object for this collection. */ public static function initNullObject(Doctrine_Null $null) { @@ -112,7 +112,7 @@ public static function initNullObject(Doctrine_Null $null) public static function create($table, $keyColumn = null, $class = null) { if (is_null($class)) { - if ( ! $table instanceof Doctrine_Table) { + if (!$table instanceof Doctrine_Table) { $table = Doctrine_Core::getTable($table); } $class = $table->getAttribute(Doctrine_Core::ATTR_COLLECTION_CLASS); @@ -122,7 +122,7 @@ public static function create($table, $keyColumn = null, $class = null) } /** - * Get the table this collection belongs to + * Get the table this collection belongs to. * * @return Doctrine_Table */ @@ -132,9 +132,8 @@ public function getTable() } /** - * Set the data for the Doctrin_Collection instance + * Set the data for the Doctrin_Collection instance. * - * @param array $data * @return Doctrine_Collection */ public function setData(array $data) @@ -142,9 +141,8 @@ public function setData(array $data) $this->data = $data; } - /** - * This method is automatically called when this Doctrine_Collection is serialized + * This method is automatically called when this Doctrine_Collection is serialized. * * @return string */ @@ -156,9 +154,7 @@ public function serialize() } /** - * This method is automatically called everytime a Doctrine_Collection object is unserialized - * - * @return void + * This method is automatically called everytime a Doctrine_Collection object is unserialized. */ public function unserialize($serialized) { @@ -168,20 +164,15 @@ public function unserialize($serialized) } /** - * Serializes the current instance for php 7.4+ + * Serializes the current instance for php 7.4+. * * @return array */ - public function __serialize() { - + public function __serialize() + { $vars = get_object_vars($this); - unset($vars['reference']); - unset($vars['referenceField']); - unset($vars['relation']); - unset($vars['expandable']); - unset($vars['expanded']); - unset($vars['generator']); + unset($vars['reference'], $vars['referenceField'], $vars['relation'], $vars['expandable'], $vars['expanded'], $vars['generator']); $vars['_table'] = $vars['_table']->getComponentName(); @@ -189,36 +180,34 @@ public function __serialize() { } /** - * Unserializes a Doctrine_Collection instance for php 7.4+ - * - * @param string $serialized A serialized Doctrine_Collection instance + * Unserializes a Doctrine_Collection instance for php 7.4+. */ public function __unserialize($data) { - $manager = Doctrine_Manager::getInstance(); - $connection = $manager->getCurrentConnection(); - + $manager = Doctrine_Manager::getInstance(); + $connection = $manager->getCurrentConnection(); foreach ($data as $name => $values) { - $this->$name = $values; + $this->{$name} = $values; } $this->_table = $connection->getTable($this->_table); $keyColumn = isset($array['keyColumn']) ? $array['keyColumn'] : null; - if ($keyColumn === null) { + if (null === $keyColumn) { $keyColumn = $this->_table->getBoundQueryPart('indexBy'); } - if ($keyColumn !== null) { + if (null !== $keyColumn) { $this->keyColumn = $keyColumn; } } /** - * Sets the key column for this collection + * Sets the key column for this collection. * * @param string $column + * * @return Doctrine_Collection $this */ public function setKeyColumn($column) @@ -229,7 +218,7 @@ public function setKeyColumn($column) } /** - * Get the name of the key column + * Get the name of the key column. * * @return string */ @@ -239,7 +228,7 @@ public function getKeyColumn() } /** - * Get all the records as an array + * Get all the records as an array. * * @return array */ @@ -249,7 +238,7 @@ public function getData() } /** - * Get the first record in the collection + * Get the first record in the collection. * * @return Doctrine_Record */ @@ -259,7 +248,7 @@ public function getFirst() } /** - * Get the last record in the collection + * Get the last record in the collection. * * @return Doctrine_Record */ @@ -269,7 +258,7 @@ public function getLast() } /** - * Get the last record in the collection + * Get the last record in the collection. * * @return Doctrine_Record */ @@ -279,7 +268,7 @@ public function end() } /** - * Get the current key + * Get the current key. * * @return Doctrine_Record */ @@ -289,7 +278,7 @@ public function key() } /** - * Sort by key + * Sort by key. * * @return Doctrine_Collection */ @@ -301,35 +290,32 @@ public function ksort() } /** - * Sets a reference pointer - * - * @return void + * Sets a reference pointer. */ public function setReference(Doctrine_Record $record, Doctrine_Relation $relation) { $this->reference = $record; - $this->relation = $relation; + $this->relation = $relation; - if ($relation instanceof Doctrine_Relation_ForeignKey || - $relation instanceof Doctrine_Relation_LocalKey) { + if ($relation instanceof Doctrine_Relation_ForeignKey + || $relation instanceof Doctrine_Relation_LocalKey) { $this->referenceField = $relation->getForeignFieldName(); $value = $record->get($relation->getLocalFieldName()); foreach ($this->data as $record) { - if ($value !== null) { + if (null !== $value) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); } } } elseif ($relation instanceof Doctrine_Relation_Association) { - } } /** - * Get reference to Doctrine_Record instance + * Get reference to Doctrine_Record instance. * * @return Doctrine_Record $reference */ @@ -339,24 +325,25 @@ public function getReference() } /** - * Removes a specified collection element + * Removes a specified collection element. * - * @param mixed $key - * @return boolean + * @return bool */ public function remove($key) { $removed = $this->data[$key]; unset($this->data[$key]); + return $removed; } /** - * Whether or not this collection contains a specified element + * Whether or not this collection contains a specified element. + * + * @param mixed $key the key of the element * - * @param mixed $key the key of the element - * @return boolean + * @return bool */ public function contains($key) { @@ -364,10 +351,7 @@ public function contains($key) } /** - * Search a Doctrine_Record instance - * - * @param string $Doctrine_Record - * @return void + * Search a Doctrine_Record instance. */ public function search(Doctrine_Record $record) { @@ -375,7 +359,7 @@ public function search(Doctrine_Record $record) } /** - * Gets a record for given key + * Gets a record for given key. * * There are two special cases: * @@ -387,24 +371,25 @@ public function search(Doctrine_Record $record) * * Collection also maps referential information to newly created records * - * @param mixed $key the key of the element - * @return Doctrine_Record return a specified record + * @param mixed $key the key of the element + * + * @return Doctrine_Record return a specified record */ public function get($key) { - if ( ! isset($this->data[$key])) { + if (!isset($this->data[$key])) { $record = $this->_table->create(); if (isset($this->referenceField)) { $value = $this->reference->get($this->relation->getLocalFieldName()); - if ($value !== null) { + if (null !== $value) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); } } - if ($key === null) { + if (null === $key) { $this->data[] = $record; } else { $this->data[$key] = $record; @@ -421,9 +406,9 @@ public function get($key) } /** - * Get array of primary keys for all the records in the collection + * Get array of primary keys for all the records in the collection. * - * @return array an array containing all primary keys + * @return array an array containing all primary keys */ public function getPrimaryKeys() { @@ -437,11 +422,12 @@ public function getPrimaryKeys() $list[] = $record->getIncremented(); } } + return $list; } /** - * Get all keys of the data in the collection + * Get all keys of the data in the collection. * * @return array */ @@ -452,22 +438,21 @@ public function getKeys() /** * Gets the number of records in this collection - * This class implements interface countable + * This class implements interface countable. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->data); } /** - * Set a Doctrine_Record instance to the collection + * Set a Doctrine_Record instance to the collection. * - * @param integer $key + * @param int $key * @param Doctrine_Record $record - * @return void */ public function set($key, $record) { @@ -479,17 +464,18 @@ public function set($key, $record) } /** - * Adds a record to collection + * Adds a record to collection. + * + * @param Doctrine_Record $record record to be added + * @param string $key optional key for the record * - * @param Doctrine_Record $record record to be added - * @param string $key optional key for the record - * @return boolean + * @return bool */ public function add($record, $key = null) { if (isset($this->referenceField)) { $value = $this->reference->get($this->relation->getLocalFieldName()); - if ($value !== null) { + if (null !== $value) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); @@ -502,7 +488,7 @@ public function add($record, $key = null) } } } - /** + /* * for some weird reason in_array cannot be used here (php bug ?) * * if used it results in fatal error : [ nesting level too deep ] @@ -518,12 +504,13 @@ public function add($record, $key = null) return false; } $this->data[$key] = $record; + return true; } if (isset($this->keyColumn)) { $value = $record->get($this->keyColumn); - if ($value === null) { + if (null === $value) { throw new Doctrine_Collection_Exception("Couldn't create collection index. Record field '".$this->keyColumn."' was null."); } $this->data[$value] = $record; @@ -535,9 +522,8 @@ public function add($record, $key = null) } /** - * Merges collection into $this and returns merged collection + * Merges collection into $this and returns merged collection. * - * @param Doctrine_Collection $coll * @return Doctrine_Collection */ public function merge(Doctrine_Collection $coll) @@ -545,7 +531,7 @@ public function merge(Doctrine_Collection $coll) $localBase = $this->getTable()->getComponentName(); $otherBase = $coll->getTable()->getComponentName(); - if ($otherBase != $localBase && !is_subclass_of($otherBase, $localBase) ) { + if ($otherBase != $localBase && !is_subclass_of($otherBase, $localBase)) { throw new Doctrine_Collection_Exception("Can't merge collections with incompatible record types"); } @@ -557,32 +543,31 @@ public function merge(Doctrine_Collection $coll) } /** - * Load all relationships or the named relationship passed + * Load all relationships or the named relationship passed. * - * @param mixed $name - * @return boolean + * @return bool */ public function loadRelated($name = null) { $list = array(); $query = $this->_table->createQuery(); - if ( ! isset($name)) { + if (!isset($name)) { foreach ($this->data as $record) { $value = $record->getIncremented(); - if ($value !== null) { + if (null !== $value) { $list[] = $value; } } - $query->where($this->_table->getComponentName() . '.id IN (' . substr(str_repeat("?, ", count($list)),0,-2) . ')'); - if ( ! $list) { - $query->where($this->_table->getComponentName() . '.id IN (' . substr(str_repeat("?, ", count($list)),0,-2) . ')', $list); + $query->where($this->_table->getComponentName().'.id IN ('.substr(str_repeat('?, ', count($list)), 0, -2).')'); + if (!$list) { + $query->where($this->_table->getComponentName().'.id IN ('.substr(str_repeat('?, ', count($list)), 0, -2).')', $list); } return $query; } - $rel = $this->_table->getRelation($name); + $rel = $this->_table->getRelation($name); if ($rel instanceof Doctrine_Relation_LocalKey || $rel instanceof Doctrine_Relation_ForeignKey) { foreach ($this->data as $record) { @@ -591,36 +576,34 @@ public function loadRelated($name = null) } else { foreach ($this->data as $record) { $value = $record->getIncremented(); - if ($value !== null) { + if (null !== $value) { $list[] = $value; } } } - if ( ! $list) { + if (!$list) { return; } - $dql = $rel->getRelationDql(count($list), 'collection'); + $dql = $rel->getRelationDql(count($list), 'collection'); - $coll = $query->query($dql, $list); + $coll = $query->query($dql, $list); $this->populateRelated($name, $coll); } /** - * Populate the relationship $name for all records in the passed collection + * Populate the relationship $name for all records in the passed collection. * * @param string $name - * @param Doctrine_Collection $coll - * @return void */ public function populateRelated($name, Doctrine_Collection $coll) { - $rel = $this->_table->getRelation($name); - $table = $rel->getTable(); + $rel = $this->_table->getRelation($name); + $table = $rel->getTable(); $foreign = $rel->getForeign(); - $local = $rel->getLocal(); + $local = $rel->getLocal(); if ($rel instanceof Doctrine_Relation_LocalKey) { foreach ($this->data as $key => $record) { @@ -632,7 +615,7 @@ public function populateRelated($name, Doctrine_Collection $coll) } } elseif ($rel instanceof Doctrine_Relation_ForeignKey) { foreach ($this->data as $key => $record) { - if ( ! $record->exists()) { + if (!$record->exists()) { continue; } $sub = Doctrine_Collection::create($table); @@ -648,11 +631,11 @@ public function populateRelated($name, Doctrine_Collection $coll) } } elseif ($rel instanceof Doctrine_Relation_Association) { $identifier = $this->_table->getIdentifier(); - $asf = $rel->getAssociationFactory(); - $name = $table->getComponentName(); + $asf = $rel->getAssociationFactory(); + $name = $table->getComponentName(); foreach ($this->data as $key => $record) { - if ( ! $record->exists()) { + if (!$record->exists()) { continue; } $sub = Doctrine_Collection::create($table); @@ -662,13 +645,12 @@ public function populateRelated($name, Doctrine_Collection $coll) } } $this->data[$key]->setRelated($name, $sub); - } } } /** - * Get normal iterator - an iterator that will not expand this collection + * Get normal iterator - an iterator that will not expand this collection. * * @return Doctrine_Iterator_Normal $iterator */ @@ -678,7 +660,7 @@ public function getNormalIterator() } /** - * Takes a snapshot from this collection + * Takes a snapshot from this collection. * * snapshots are used for diff processing, for example * when a fetched collection has three elements, then two of those @@ -697,9 +679,9 @@ public function takeSnapshot() } /** - * Gets the data of the last snapshot + * Gets the data of the last snapshot. * - * @return array returns the data in last snapshot + * @return array returns the data in last snapshot */ public function getSnapshot() { @@ -707,7 +689,7 @@ public function getSnapshot() } /** - * Processes the difference of the last snapshot and the current data + * Processes the difference of the last snapshot and the current data. * * an example: * Snapshot with the objects 1, 2 and 4 @@ -719,7 +701,7 @@ public function getSnapshot() */ public function processDiff() { - foreach (array_udiff($this->_snapshot, $this->data, array($this, "compareRecords")) as $record) { + foreach (array_udiff($this->_snapshot, $this->data, array($this, 'compareRecords')) as $record) { $record->delete(); } @@ -727,16 +709,15 @@ public function processDiff() } /** - * Mimics the result of a $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + * Mimics the result of a $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY);. * - * @param boolean $deep + * @param bool $deep */ public function toArray($deep = true, $prefixKey = false) { $data = array(); foreach ($this as $key => $record) { - - $key = $prefixKey ? get_class($record) . '_' .$key:$key; + $key = $prefixKey ? get_class($record).'_'.$key : $key; $data[$key] = $record->toArray($deep, $prefixKey); } @@ -745,18 +726,20 @@ public function toArray($deep = true, $prefixKey = false) } /** - * Build an array made up of the values from the 2 specified columns + * Build an array made up of the values from the 2 specified columns. * * @param string $key * @param string $value + * * @return array $result */ public function toKeyValueArray($key, $value) { $result = array(); foreach ($this as $record) { - $result[$record->$key] = $record->$value; + $result[$record->{$key}] = $record->{$value}; } + return $result; } @@ -765,7 +748,7 @@ public function toHierarchy() $collection = $this; $table = $collection->getTable(); - if ( ! $table->isTree() || ! $table->hasColumn('level')) { + if (!$table->isTree() || !$table->hasColumn('level')) { throw new Doctrine_Exception('Cannot hydrate model that does not implements Tree behavior with `level` column'); } @@ -786,13 +769,13 @@ public function toHierarchy() $l = count($stack); // Check if we're dealing with different levels - while($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { + while ($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { array_pop($stack->data); - $l--; + --$l; } // Stack is empty (we are inspecting the root) - if ($l == 0) { + if (0 == $l) { // Assigning the root child $i = count($trees); $trees[$i] = $item; @@ -805,14 +788,14 @@ public function toHierarchy() } } } + return $trees; } /** - * Populate a Doctrine_Collection from an array of data + * Populate a Doctrine_Collection from an array of data. * * @param string $array - * @return void */ public function fromArray($array, $deep = true) { @@ -823,7 +806,7 @@ public function fromArray($array, $deep = true) } /** - * synchronizes a Doctrine_Collection with data from an array + * synchronizes a Doctrine_Collection with data from an array. * * it expects an array representation of a Doctrine_Collection similar to the return * value of the toArray() method. It will create Dectrine_Records that don't exist @@ -854,39 +837,37 @@ public function synchronizeFromArray(array $array) } /** - * Export a Doctrine_Collection to one of the supported Doctrine_Parser formats + * Export a Doctrine_Collection to one of the supported Doctrine_Parser formats. * * @param string $type * @param string $deep - * @return void */ public function exportTo($type, $deep = true) { - if ($type == 'array') { + if ('array' == $type) { return $this->toArray($deep); - } else { - return Doctrine_Parser::dump($this->toArray($deep, true), $type); } + + return Doctrine_Parser::dump($this->toArray($deep, true), $type); } /** - * Import data to a Doctrine_Collection from one of the supported Doctrine_Parser formats + * Import data to a Doctrine_Collection from one of the supported Doctrine_Parser formats. * * @param string $type * @param string $data - * @return void */ public function importFrom($type, $data) { - if ($type == 'array') { + if ('array' == $type) { return $this->fromArray($data); - } else { - return $this->fromArray(Doctrine_Parser::load($data, $type)); } + + return $this->fromArray(Doctrine_Parser::load($data, $type)); } /** - * Perform a delete diff between the last snapshot and the current data + * Perform a delete diff between the last snapshot and the current data. * * @return array $diff */ @@ -896,21 +877,22 @@ public function getDeleteDiff() } /** - * Perform a insert diff between the last snapshot and the current data + * Perform a insert diff between the last snapshot and the current data. * * @return array $diff */ public function getInsertDiff() { - return array_udiff($this->data, $this->_snapshot, array($this, "compareRecords")); + return array_udiff($this->data, $this->_snapshot, array($this, 'compareRecords')); } /** - * Compares two records. To be used on _snapshot diffs using array_udiff + * Compares two records. To be used on _snapshot diffs using array_udiff. * * @param Doctrine_Record $a * @param Doctrine_Record $b - * @return integer + * + * @return int */ protected function compareRecords($a, $b) { @@ -923,14 +905,15 @@ protected function compareRecords($a, $b) /** * Saves all records of this collection and processes the - * difference of the last snapshot and the current data + * difference of the last snapshot and the current data. + * + * @param Doctrine_Connection $conn optional connection parameter * - * @param Doctrine_Connection $conn optional connection parameter * @return Doctrine_Collection */ public function save(Doctrine_Connection $conn = null, $processDiff = true) { - if ($conn == null) { + if (null == $conn) { $conn = $this->_table->getConnection(); } @@ -958,14 +941,15 @@ public function save(Doctrine_Connection $conn = null, $processDiff = true) /** * Replaces all records of this collection and processes the - * difference of the last snapshot and the current data + * difference of the last snapshot and the current data. + * + * @param Doctrine_Connection $conn optional connection parameter * - * @param Doctrine_Connection $conn optional connection parameter * @return Doctrine_Collection */ public function replace(Doctrine_Connection $conn = null, $processDiff = true) { - if ($conn == null) { + if (null == $conn) { $conn = $this->_table->getConnection(); } @@ -992,13 +976,13 @@ public function replace(Doctrine_Connection $conn = null, $processDiff = true) } /** - * Deletes all records from this collection + * Deletes all records from this collection. * * @return Doctrine_Collection */ public function delete(Doctrine_Connection $conn = null, $clearColl = true) { - if ($conn == null) { + if (null == $conn) { $conn = $this->_table->getConnection(); } @@ -1025,8 +1009,6 @@ public function delete(Doctrine_Connection $conn = null, $clearColl = true) /** * Clears the collection. - * - * @return void */ public function clear() { @@ -1037,13 +1019,11 @@ public function clear() * Frees the resources used by the collection. * WARNING: After invoking free() the collection is no longer considered to * be in a useable state. Subsequent usage may result in unexpected behavior. - * - * @return void */ public function free($deep = false) { foreach ($this->getData() as $key => $record) { - if ( ! ($record instanceof Doctrine_Null)) { + if (!($record instanceof Doctrine_Null)) { $record->free($deep); } } @@ -1057,19 +1037,20 @@ public function free($deep = false) } /** - * Get collection data iterator + * Get collection data iterator. * * @return Iterator */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { $data = $this->data; + return new ArrayIterator($data); } /** - * Returns a string representation of this object + * Returns a string representation of this object. * * @return string $string */ @@ -1079,7 +1060,7 @@ public function __toString() } /** - * Returns the relation object + * Returns the relation object. * * @return Doctrine_Relation */ @@ -1090,19 +1071,21 @@ public function getRelation() /** * checks if one of the containing records is modified - * returns true if modified, false otherwise + * returns true if modified, false otherwise. * - * @return boolean + * @return bool */ - final public function isModified() { + final public function isModified() + { $dirty = (count($this->getInsertDiff()) > 0 || count($this->getDeleteDiff()) > 0); - if ( ! $dirty) { - foreach($this as $record) { + if (!$dirty) { + foreach ($this as $record) { if ($dirty = $record->isModified()) { break; } } } + return $dirty; } } diff --git a/lib/Doctrine/Collection/Exception.php b/lib/Doctrine/Collection/Exception.php index 5b217fb21..e71bc9a3c 100644 --- a/lib/Doctrine/Collection/Exception.php +++ b/lib/Doctrine/Collection/Exception.php @@ -20,15 +20,17 @@ */ /** - * Collection exception class + * Collection exception class. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Collection/Iterator.php b/lib/Doctrine/Collection/Iterator.php index 3fdc79cd0..9b3287a1d 100644 --- a/lib/Doctrine/Collection/Iterator.php +++ b/lib/Doctrine/Collection/Iterator.php @@ -21,72 +21,69 @@ /** * Doctrine_Collection_Iterator - * iterates through Doctrine_Collection + * iterates through Doctrine_Collection. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Collection_Iterator implements Iterator { /** - * @var Doctrine_Collection $collection + * @var Doctrine_Collection */ protected $collection; /** - * @var array $keys + * @var array */ protected $keys; - /** - * @var mixed $key - */ protected $key; /** - * @var integer $index + * @var int */ protected $index; /** - * @var integer $count + * @var int */ protected $count; /** - * constructor - * @var Doctrine_Collection $collection + * constructor. + * + * @var Doctrine_Collection */ public function __construct($collection) { $this->collection = $collection; - $this->keys = $this->collection->getKeys(); - $this->count = $this->collection->count(); + $this->keys = $this->collection->getKeys(); + $this->count = $this->collection->count(); } /** - * rewinds the iterator - * - * @return void + * rewinds the iterator. */ public function rewind() { $this->index = 0; $i = $this->index; if (isset($this->keys[$i])) { - $this->key = $this->keys[$i]; + $this->key = $this->keys[$i]; } } /** - * returns the current key + * returns the current key. * - * @return integer + * @return int */ public function key() { @@ -94,7 +91,7 @@ public function key() } /** - * returns the current record + * returns the current record. * * @return Doctrine_Record */ @@ -104,16 +101,14 @@ public function current() } /** - * advances the internal pointer - * - * @return void + * advances the internal pointer. */ public function next() { - $this->index++; + ++$this->index; $i = $this->index; if (isset($this->keys[$i])) { - $this->key = $this->keys[$i]; + $this->key = $this->keys[$i]; } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Collection/Iterator/Expandable.php b/lib/Doctrine/Collection/Iterator/Expandable.php index 7c18c5c58..1fbb941fb 100644 --- a/lib/Doctrine/Collection/Iterator/Expandable.php +++ b/lib/Doctrine/Collection/Iterator/Expandable.php @@ -20,14 +20,15 @@ */ /** - * Expandable collection iterator class + * Expandable collection iterator class. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Iterator_Expandable extends Doctrine_Collection_Iterator @@ -36,14 +37,16 @@ public function valid() { if ($this->index < $this->count) { return true; - } elseif ($this->index == $this->count) { - $coll = $this->collection->expand($this->index); + } + if ($this->index == $this->count) { + $coll = $this->collection->expand($this->index); if ($coll instanceof Doctrine_Collection) { $count = count($coll); if ($count > 0) { - $this->keys = array_merge($this->keys, $coll->getKeys()); + $this->keys = array_merge($this->keys, $coll->getKeys()); $this->count += $count; + return true; } } @@ -51,4 +54,4 @@ public function valid() return false; } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Collection/Iterator/Normal.php b/lib/Doctrine/Collection/Iterator/Normal.php index 540bdad63..498bc490d 100644 --- a/lib/Doctrine/Collection/Iterator/Normal.php +++ b/lib/Doctrine/Collection/Iterator/Normal.php @@ -20,23 +20,24 @@ */ /** - * Doctrine_Collection_Iterator_Normal + * Doctrine_Collection_Iterator_Normal. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Iterator_Normal extends Doctrine_Collection_Iterator { /** - * @return boolean whether or not the iteration will continue + * @return bool whether or not the iteration will continue */ public function valid() { - return ($this->index < $this->count); + return $this->index < $this->count; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Collection/Iterator/Offset.php b/lib/Doctrine/Collection/Iterator/Offset.php index 181b73f21..8b8a16bfc 100644 --- a/lib/Doctrine/Collection/Iterator/Offset.php +++ b/lib/Doctrine/Collection/Iterator/Offset.php @@ -20,18 +20,20 @@ */ /** - * Doctrine_Collection_Iterator_Normal + * Doctrine_Collection_Iterator_Normal. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Iterator_Offset extends Doctrine_Collection_Iterator { public function valid() - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Collection/Offset.php b/lib/Doctrine/Collection/Offset.php index d8516a8f1..51b332104 100644 --- a/lib/Doctrine/Collection/Offset.php +++ b/lib/Doctrine/Collection/Offset.php @@ -23,24 +23,22 @@ * Doctrine_Collection_Offset * Collection of Doctrine_Record objects. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Offset extends Doctrine_Collection { /** - * @var integer $limit + * @var int */ private $limit; - /** - * @param Doctrine_Table $table - */ public function __construct(Doctrine_Table $table) { parent::__construct($table); @@ -48,7 +46,7 @@ public function __construct(Doctrine_Table $table) } /** - * @return integer + * @return int */ public function getLimit() { diff --git a/lib/Doctrine/Collection/OnDemand.php b/lib/Doctrine/Collection/OnDemand.php index ab2e81134..272eb0bdf 100644 --- a/lib/Doctrine/Collection/OnDemand.php +++ b/lib/Doctrine/Collection/OnDemand.php @@ -21,14 +21,15 @@ /** * Doctrine_Collection_OnDemand - * iterates through Doctrine_Records hydrating one at a time + * iterates through Doctrine_Records hydrating one at a time. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * * @author Geoff Davis */ class Doctrine_Collection_OnDemand implements Iterator @@ -55,16 +56,16 @@ private function _hydrateCurrent() $record = $this->_hydrator->hydrateResultSet($this->_stmt); if ($record instanceof Doctrine_Collection) { $this->_current = $record->getFirst(); - } else if (is_array($record) && count($record) == 0) { + } elseif (is_array($record) && 0 == count($record)) { $this->_current = null; - } else if (is_array($record) && isset($record[0])) { + } elseif (is_array($record) && isset($record[0])) { $this->_current = $record[0]; } else { $this->_current = $record; } } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function rewind() { $this->index = 0; @@ -74,32 +75,33 @@ public function rewind() $this->_hydrateCurrent(); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function key() { return $this->index; } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function current() { return $this->_current; } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function next() { $this->_current = null; - $this->index++; + ++$this->index; $this->_hydrateCurrent(); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function valid() { - if ( ! is_null($this->_current) && $this->_current !== false) { + if (!is_null($this->_current) && false !== $this->_current) { return true; } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Column.php b/lib/Doctrine/Column.php index fafb97adb..fde9d7206 100644 --- a/lib/Doctrine/Column.php +++ b/lib/Doctrine/Column.php @@ -21,28 +21,28 @@ /** * Doctrine_Column - * This class represents a database column + * This class represents a database column. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Column * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision: 7663 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Column extends Doctrine_Access implements IteratorAggregate, Countable { /** - * @var array $_definition @see getDefinition() + * @var array @see getDefinition() */ protected $_definition = array( - 'type' => null, - 'length' => 0, - ); + 'type' => null, + 'length' => 0, + ); /** - * @var array $definition @see getDefinition() + * @var array @see getDefinition() */ public function __construct(array $definition = array()) { @@ -52,10 +52,11 @@ public function __construct(array $definition = array()) /** * Returns the definition of the column. * - * Keys can be: + * Keys can be: * string type, * integer length, * array values (only for enum fields, maps integer indexes to mixed values), + * * @return array */ public function getDefinition() @@ -64,35 +65,33 @@ public function getDefinition() } /** - * contains + * contains. * - * @return boolean + * @return bool */ - public function contains($name) + public function contains($name) { return isset($this->_definition[$name]); } /** - * get + * get. * * @param string $name - * @return mixed */ public function get($name) { - if ( ! isset($this->_definition[$name])) { + if (!isset($this->_definition[$name])) { return null; } - + return $this->_definition[$name]; } /** - * set + * set. * * @param string $name - * @return void */ public function set($name, $value) { @@ -100,23 +99,23 @@ public function set($name, $value) } /** - * @param string $field * @return array */ public function getEnumValues() { if (isset($this->_definition['values'])) { return $this->_definition['values']; - } else { - return array(); } + + return array(); } /** * Retrieves an enum value. * - * @param integer $index - * @return string integer ($index) if not present + * @param int $index + * + * @return string integer ($index) if not present */ public function enumValue($index) { @@ -128,11 +127,9 @@ public function enumValue($index) } /** - * enumIndex + * enumIndex. * * @param string $field - * @param mixed $value - * @return mixed */ public function enumIndex($field, $value) { @@ -142,23 +139,23 @@ public function enumIndex($field, $value) } /** - * count + * count. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_definition); } /** - * getIterator + * getIterator. * * @return ArrayIterator */ - #[\ReturnTypeWillChange] - public function getIterator() + #[ReturnTypeWillChange] + public function getIterator() { return new ArrayIterator($this->_definition); } diff --git a/lib/Doctrine/Compiler.php b/lib/Doctrine/Compiler.php index 9379316ea..07b5fec54 100644 --- a/lib/Doctrine/Compiler.php +++ b/lib/Doctrine/Compiler.php @@ -21,14 +21,14 @@ /** * Doctrine_Compiler - * This class can be used for compiling the entire Doctrine framework into a single file + * This class can be used for compiling the entire Doctrine framework into a single file. * - * @package Doctrine - * @subpackage Compiler * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpllicense.php LGPL - * @link www.phpdoctrine. + * + * @see www.phpdoctrine. * @since 1.0 + * * @version $Revision: 7677 $ */ class Doctrine_Compiler @@ -36,103 +36,106 @@ class Doctrine_Compiler /** * method for making a single file of most used doctrine runtime components * including the compiled file instead of multiple files (in worst - * cases dozens of files) can improve performance by an order of magnitude + * cases dozens of files) can improve performance by an order of magnitude. + * + * @param mixed|null $target * - * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation * @return $target Path the compiled file was written to + * + * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation */ public static function compile($target = null, $includedDrivers = array()) { - if ( ! is_array($includedDrivers)) { + if (!is_array($includedDrivers)) { $includedDrivers = array($includedDrivers); } - + $excludedDrivers = array(); - + // If we have an array of specified drivers then lets determine which drivers we should exclude - if ( ! empty($includedDrivers)) { + if (!empty($includedDrivers)) { $drivers = array('db2', - 'mssql', - 'mysql', - 'oracle', - 'pgsql', - 'sqlite'); - + 'mssql', + 'mysql', + 'oracle', + 'pgsql', + 'sqlite'); + $excludedDrivers = array_diff($drivers, $includedDrivers); } - + $path = Doctrine_Core::getPath(); - $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path . '/Doctrine'), RecursiveIteratorIterator::LEAVES_ONLY); + $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path.'/Doctrine'), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $e = explode('.', $file->getFileName()); - - //@todo what is a versioning file? do we have these anymore? None - //exists in my version of doctrine from svn. + + // @todo what is a versioning file? do we have these anymore? None + // exists in my version of doctrine from svn. // we don't want to require versioning files - if (end($e) === 'php' && strpos($file->getFileName(), '.inc') === false - && strpos($file->getFileName(), 'sfYaml') === false) { + if ('php' === end($e) && false === strpos($file->getFileName(), '.inc') + && false === strpos($file->getFileName(), 'sfYaml')) { require_once $file->getPathName(); } } $classes = array_merge(get_declared_classes(), get_declared_interfaces()); - $ret = array(); + $ret = array(); foreach ($classes as $class) { $e = explode('_', $class); - if ($e[0] !== 'Doctrine') { + if ('Doctrine' !== $e[0]) { continue; } - + // Exclude drivers - if ( ! empty($excludedDrivers)) { + if (!empty($excludedDrivers)) { foreach ($excludedDrivers as $excludedDriver) { $excludedDriver = ucfirst($excludedDriver); - + if (in_array($excludedDriver, $e)) { - continue(2); + continue 2; } } } - - $refl = new ReflectionClass($class); - $file = $refl->getFileName(); - + + $refl = new ReflectionClass($class); + $file = $refl->getFileName(); + $lines = file($file); $start = $refl->getStartLine() - 1; - $end = $refl->getEndLine(); + $end = $refl->getEndLine(); - $ret = array_merge($ret, array_slice($lines, $start, ($end - $start))); + $ret = array_merge($ret, array_slice($lines, $start, $end - $start)); } - if ($target == null) { - $target = $path . DIRECTORY_SEPARATOR . 'Doctrine.compiled.php'; + if (null == $target) { + $target = $path.DIRECTORY_SEPARATOR.'Doctrine.compiled.php'; } // first write the 'compiled' data to a text file, so // that we can use php_strip_whitespace (which only works on files) $fp = @fopen($target, 'w'); - if ($fp === false) { - throw new Doctrine_Compiler_Exception("Couldn't write compiled data. Failed to open $target"); + if (false === $fp) { + throw new Doctrine_Compiler_Exception("Couldn't write compiled data. Failed to open {$target}"); } - - fwrite($fp, " * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Compiler_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Configurable.php b/lib/Doctrine/Configurable.php index 5a3493e81..992745423 100644 --- a/lib/Doctrine/Configurable.php +++ b/lib/Doctrine/Configurable.php @@ -21,54 +21,56 @@ /** * Doctrine_Configurable - * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection + * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection. * - * @package Doctrine - * @subpackage Configurable * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ abstract class Doctrine_Configurable extends Doctrine_Locator_Injectable { /** - * @var array $attributes an array of containing all attributes + * @var array an array of containing all attributes */ protected $attributes = array(); /** - * @var Doctrine_Configurable $parent the parent of this component + * @var Doctrine_Configurable the parent of this component */ protected $parent; /** - * @var array $_impl an array containing concrete implementations for class templates - * keys as template names and values as names of the concrete - * implementation classes + * @var array an array containing concrete implementations for class templates + * keys as template names and values as names of the concrete + * implementation classes */ protected $_impl = array(); /** - * @var array $_params an array of user defined parameters + * @var array an array of user defined parameters */ protected $_params = array(); /** * setAttribute - * sets a given attribute + * sets a given attribute. * * * $manager->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL); * * - * @param mixed $attribute either a Doctrine_Core::ATTR_* integer constant or a string - * corresponding to a constant - * @param mixed $value the value of the attribute + * @param mixed $attribute either a Doctrine_Core::ATTR_* integer constant or a string + * corresponding to a constant + * @param mixed $value the value of the attribute + * * @see Doctrine_Core::ATTR_* constants - * @throws Doctrine_Exception if the value is invalid - * @return void + * + * @throws Doctrine_Exception if the value is invalid */ public function setAttribute($attribute, $value) { @@ -77,39 +79,39 @@ public function setAttribute($attribute, $value) $this->setEventListener($value); break; case Doctrine_Core::ATTR_COLL_KEY: - if ( ! ($this instanceof Doctrine_Table)) { - throw new Doctrine_Exception("This attribute can only be set at table level."); + if (!($this instanceof Doctrine_Table)) { + throw new Doctrine_Exception('This attribute can only be set at table level.'); } - if ($value !== null && ! $this->hasField($value)) { - throw new Doctrine_Exception("Couldn't set collection key attribute. No such field '$value'."); + if (null !== $value && !$this->hasField($value)) { + throw new Doctrine_Exception("Couldn't set collection key attribute. No such field '{$value}'."); } break; case Doctrine_Core::ATTR_CACHE: case Doctrine_Core::ATTR_RESULT_CACHE: case Doctrine_Core::ATTR_QUERY_CACHE: case Doctrine_Core::ATTR_TABLE_CACHE: - if ($value !== null) { - if ( ! ($value instanceof Doctrine_Cache_Interface)) { + if (null !== $value) { + if (!($value instanceof Doctrine_Cache_Interface)) { throw new Doctrine_Exception('Cache driver should implement Doctrine_Cache_Interface'); } } break; case Doctrine_Core::ATTR_SEQCOL_NAME: - if ( ! is_string($value)) { + if (!is_string($value)) { throw new Doctrine_Exception('Sequence column name attribute only accepts string values'); } break; case Doctrine_Core::ATTR_FIELD_CASE: - if ($value != 0 && $value != CASE_LOWER && $value != CASE_UPPER) + if (0 != $value && CASE_LOWER != $value && CASE_UPPER != $value) { throw new Doctrine_Exception('Field case attribute should be either 0, CASE_LOWER or CASE_UPPER constant.'); + } break; case Doctrine_Core::ATTR_SEQNAME_FORMAT: case Doctrine_Core::ATTR_IDXNAME_FORMAT: case Doctrine_Core::ATTR_TBLNAME_FORMAT: case Doctrine_Core::ATTR_FKNAME_FORMAT: if ($this instanceof Doctrine_Table) { - throw new Doctrine_Exception('Sequence / index name format attributes cannot be set' - . 'at table level (only at connection or global level).'); + throw new Doctrine_Exception('Sequence / index name format attributes cannot be setat table level (only at connection or global level).'); } break; } @@ -119,13 +121,13 @@ public function setAttribute($attribute, $value) public function getParams($namespace = null) { - if ($namespace == null) { - $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); - } + if (null == $namespace) { + $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); + } - if ( ! isset($this->_params[$namespace])) { - return null; - } + if (!isset($this->_params[$namespace])) { + return null; + } return $this->_params[$namespace]; } @@ -137,25 +139,26 @@ public function getParamNamespaces() public function setParam($name, $value, $namespace = null) { - if ($namespace == null) { - $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); - } + if (null == $namespace) { + $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); + } - $this->_params[$namespace][$name] = $value; + $this->_params[$namespace][$name] = $value; - return $this; + return $this; } public function getParam($name, $namespace = null) { - if ($namespace == null) { - $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); - } + if (null == $namespace) { + $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); + } - if ( ! isset($this->_params[$namespace][$name])) { + if (!isset($this->_params[$namespace][$name])) { if (isset($this->parent)) { return $this->parent->getParam($name, $namespace); } + return null; } @@ -164,13 +167,14 @@ public function getParam($name, $namespace = null) /** * setImpl - * binds given class to given template name + * binds given class to given template name. * * this method is the base of Doctrine dependency injection * - * @param string $template name of the class template - * @param string $class name of the class to be bound - * @return Doctrine_Configurable this object + * @param string $template name of the class template + * @param string $class name of the class to be bound + * + * @return Doctrine_Configurable this object */ public function setImpl($template, $class) { @@ -181,36 +185,38 @@ public function setImpl($template, $class) /** * getImpl - * returns the implementation for given class + * returns the implementation for given class. * - * @return string name of the concrete implementation + * @return string name of the concrete implementation */ public function getImpl($template) { - if ( ! isset($this->_impl[$template])) { + if (!isset($this->_impl[$template])) { if (isset($this->parent)) { return $this->parent->getImpl($template); } + return null; } + return $this->_impl[$template]; } - public function hasImpl($template) { - if ( ! isset($this->_impl[$template])) { + if (!isset($this->_impl[$template])) { if (isset($this->parent)) { return $this->parent->hasImpl($template); } + return false; } + return true; } /** * @param Doctrine_EventListener $listener - * @return void */ public function setEventListener($listener) { @@ -218,16 +224,17 @@ public function setEventListener($listener) } /** - * addRecordListener + * addRecordListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * @param mixed|null $name + * + * @return Doctrine_Configurable this object */ public function addRecordListener($listener, $name = null) { - if ( ! isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]) || - ! ($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] instanceof Doctrine_Record_Listener_Chain)) { - + if (!isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]) + || !($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] instanceof Doctrine_Record_Listener_Chain)) { $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] = new Doctrine_Record_Listener_Chain(); } $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]->add($listener, $name); @@ -236,31 +243,34 @@ public function addRecordListener($listener, $name = null) } /** - * getListener + * getListener. * * @return Doctrine_EventListener_Interface|Doctrine_Overloadable */ public function getRecordListener() { - if ( ! isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER])) { + if (!isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER])) { if (isset($this->parent)) { return $this->parent->getRecordListener(); } + return null; } + return $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]; } /** - * setListener + * setListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * + * @return Doctrine_Configurable this object */ public function setRecordListener($listener) { - if ( ! ($listener instanceof Doctrine_Record_Listener_Interface) - && ! ($listener instanceof Doctrine_Overloadable) + if (!($listener instanceof Doctrine_Record_Listener_Interface) + && !($listener instanceof Doctrine_Overloadable) ) { throw new Doctrine_Exception("Couldn't set eventlistener. Record listeners should implement either Doctrine_Record_Listener_Interface or Doctrine_Overloadable"); } @@ -270,16 +280,17 @@ public function setRecordListener($listener) } /** - * addListener + * addListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * @param mixed|null $name + * + * @return Doctrine_Configurable this object */ public function addListener($listener, $name = null) { - if ( ! isset($this->attributes[Doctrine_Core::ATTR_LISTENER]) || - ! ($this->attributes[Doctrine_Core::ATTR_LISTENER] instanceof Doctrine_EventListener_Chain)) { - + if (!isset($this->attributes[Doctrine_Core::ATTR_LISTENER]) + || !($this->attributes[Doctrine_Core::ATTR_LISTENER] instanceof Doctrine_EventListener_Chain)) { $this->attributes[Doctrine_Core::ATTR_LISTENER] = new Doctrine_EventListener_Chain(); } $this->attributes[Doctrine_Core::ATTR_LISTENER]->add($listener, $name); @@ -288,31 +299,34 @@ public function addListener($listener, $name = null) } /** - * getListener + * getListener. * * @return Doctrine_EventListener_Interface|Doctrine_Overloadable */ public function getListener() { - if ( ! isset($this->attributes[Doctrine_Core::ATTR_LISTENER])) { + if (!isset($this->attributes[Doctrine_Core::ATTR_LISTENER])) { if (isset($this->parent)) { return $this->parent->getListener(); } + return null; } + return $this->attributes[Doctrine_Core::ATTR_LISTENER]; } /** - * setListener + * setListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * + * @return Doctrine_Configurable this object */ public function setListener($listener) { - if ( ! ($listener instanceof Doctrine_EventListener_Interface) - && ! ($listener instanceof Doctrine_Overloadable) + if (!($listener instanceof Doctrine_EventListener_Interface) + && !($listener instanceof Doctrine_Overloadable) ) { throw new Doctrine_EventListener_Exception("Couldn't set eventlistener. EventListeners should implement either Doctrine_EventListener_Interface or Doctrine_Overloadable"); } @@ -322,10 +336,9 @@ public function setListener($listener) } /** - * returns the value of an attribute + * returns the value of an attribute. * - * @param integer $attribute - * @return mixed + * @param int $attribute */ public function getAttribute($attribute) { @@ -336,14 +349,14 @@ public function getAttribute($attribute) if (isset($this->parent)) { return $this->parent->getAttribute($attribute); } + return null; } /** - * Unset an attribute from this levels attributes + * Unset an attribute from this levels attributes. * - * @param integer $attribute - * @return void + * @param int $attribute */ public function unsetAttribute($attribute) { @@ -354,7 +367,7 @@ public function unsetAttribute($attribute) /** * getAttributes - * returns all attributes as an array + * returns all attributes as an array. * * @return array */ @@ -364,7 +377,7 @@ public function getAttributes() } /** - * Set the charset + * Set the charset. * * @param string $charset */ @@ -374,9 +387,7 @@ public function setCharset($charset) } /** - * Get the charset - * - * @return mixed + * Get the charset. */ public function getCharset() { @@ -384,7 +395,7 @@ public function getCharset() } /** - * Set the collate + * Set the collate. * * @param string $collate */ @@ -394,7 +405,7 @@ public function setCollate($collate) } /** - * Get the collate + * Get the collate. * * @return mixed $collate */ @@ -405,10 +416,7 @@ public function getCollate() /** * sets a parent for this configurable component - * the parent must be configurable component itself - * - * @param Doctrine_Configurable $component - * @return void + * the parent must be configurable component itself. */ public function setParent(Doctrine_Configurable $component) { @@ -417,7 +425,7 @@ public function setParent(Doctrine_Configurable $component) /** * getParent - * returns the parent of this component + * returns the parent of this component. * * @return Doctrine_Configurable */ diff --git a/lib/Doctrine/Connection.php b/lib/Doctrine/Connection.php index 73a7e5fa7..c262f26a6 100644 --- a/lib/Doctrine/Connection.php +++ b/lib/Doctrine/Connection.php @@ -20,7 +20,7 @@ */ /** - * Doctrine_Connection + * Doctrine_Connection. * * A wrapper layer on top of PDO / Doctrine_Adapter * @@ -44,66 +44,67 @@ * is divided into modules. For a full list of connection modules see * Doctrine_Connection::$_modules * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Lukas Smith (MDB2 library) */ abstract class Doctrine_Connection extends Doctrine_Configurable implements Countable, IteratorAggregate, Serializable { /** - * @var $dbh the database handler + * @var the database handler */ protected $dbh; /** - * @var array $tables an array containing all the initialized Doctrine_Table objects - * keys representing Doctrine_Table component names and values as Doctrine_Table objects + * @var array an array containing all the initialized Doctrine_Table objects + * keys representing Doctrine_Table component names and values as Doctrine_Table objects */ - protected $tables = array(); + protected $tables = array(); /** - * $_name + * $_name. * * Name of the connection * - * @var string $_name + * @var string */ protected $_name; /** * The name of this connection driver. * - * @var string $driverName + * @var string */ protected $driverName; /** - * @var boolean $isConnected whether or not a connection has been established + * @var bool whether or not a connection has been established */ - protected $isConnected = false; + protected $isConnected = false; /** - * @var array $supported an array containing all features this driver supports, - * keys representing feature names and values as - * one of the following (true, false, 'emulated') + * @var array an array containing all features this driver supports, + * keys representing feature names and values as + * one of the following (true, false, 'emulated') */ - protected $supported = array(); + protected $supported = array(); /** - * @var array $pendingAttributes An array of pending attributes. When setting attributes - * no connection is needed. When connected all the pending - * attributes are passed to the underlying adapter (usually PDO) instance. + * @var array An array of pending attributes. When setting attributes + * no connection is needed. When connected all the pending + * attributes are passed to the underlying adapter (usually PDO) instance. */ - protected $pendingAttributes = array(); + protected $pendingAttributes = array(); /** - * @var array $modules an array containing all modules - * transaction Doctrine_Transaction driver, handles savepoint and transaction isolation abstraction + * @var array an array containing all modules + * transaction Doctrine_Transaction driver, handles savepoint and transaction isolation abstraction * * expression Doctrine_Expression_Driver, handles expression abstraction * @@ -130,86 +131,87 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @see Doctrine_Formatter */ private $modules = array('transaction' => false, - 'expression' => false, - 'dataDict' => false, - 'export' => false, - 'import' => false, - 'sequence' => false, - 'unitOfWork' => false, - 'formatter' => false, - 'util' => false, - ); - - /** - * @var array $properties an array of connection properties - */ - protected $properties = array('sql_comments' => array(array('start' => '--', 'end' => "\n", 'escape' => false), - array('start' => '/*', 'end' => '*/', 'escape' => false)), - 'identifier_quoting' => array('start' => '"', 'end' => '"','escape' => '"'), - 'string_quoting' => array('start' => "'", - 'end' => "'", - 'escape' => false, - 'escape_pattern' => false), - 'wildcards' => array('%', '_'), - 'varchar_max_length' => 255, - 'sql_file_delimiter' => ";\n", - 'max_identifier_length' => 64, - ); - - /** - * @var array $serverInfo + 'expression' => false, + 'dataDict' => false, + 'export' => false, + 'import' => false, + 'sequence' => false, + 'unitOfWork' => false, + 'formatter' => false, + 'util' => false, + ); + + /** + * @var array an array of connection properties + */ + protected $properties = array('sql_comments' => array(array('start' => '--', 'end' => "\n", 'escape' => false), + array('start' => '/*', 'end' => '*/', 'escape' => false)), + 'identifier_quoting' => array('start' => '"', 'end' => '"', 'escape' => '"'), + 'string_quoting' => array('start' => "'", + 'end' => "'", + 'escape' => false, + 'escape_pattern' => false), + 'wildcards' => array('%', '_'), + 'varchar_max_length' => 255, + 'sql_file_delimiter' => ";\n", + 'max_identifier_length' => 64, + ); + + /** + * @var array */ protected $serverInfo = array(); - protected $options = array(); + protected $options = array(); /** - * @var array $supportedDrivers an array containing all supported drivers + * @var array an array containing all supported drivers */ - private static $supportedDrivers = array( - 'Mysql', - 'Pgsql', - 'Oracle', - 'Mssql', - 'Sqlite', - ); + private static $supportedDrivers = array( + 'Mysql', + 'Pgsql', + 'Oracle', + 'Mssql', + 'Sqlite', + ); protected $_count = 0; /** - * @var array $_userFkNames array of foreign key names that have been used + * @var array array of foreign key names that have been used */ protected $_usedNames = array( 'foreign_keys' => array(), - 'indexes' => array() + 'indexes' => array(), ); /** - * @var Doctrine_Cache_Interface The cache driver used for caching tables. + * @var Doctrine_Cache_Interface the cache driver used for caching tables */ protected $_tableCache; protected $_tableCacheTTL; protected $exported; /** - * the constructor + * the constructor. * - * @param Doctrine_Manager $manager the manager object - * @param PDO|Doctrine_Adapter_Interface $adapter database driver + * @param Doctrine_Manager $manager the manager object + * @param PDO|Doctrine_Adapter_Interface $adapter database driver + * @param mixed|null $user + * @param mixed|null $pass */ public function __construct(Doctrine_Manager $manager, $adapter, $user = null, $pass = null) { if (is_object($adapter)) { - if ( ! ($adapter instanceof PDO) && ! in_array('Doctrine_Adapter_Interface', class_implements($adapter))) { + if (!($adapter instanceof PDO) && !in_array('Doctrine_Adapter_Interface', class_implements($adapter))) { throw new Doctrine_Connection_Exception('First argument should be an instance of PDO or implement Doctrine_Adapter_Interface'); } $this->dbh = $adapter; $this->isConnected = true; - - } else if (is_array($adapter)) { + } elseif (is_array($adapter)) { $this->pendingAttributes[Doctrine_Core::ATTR_DRIVER_NAME] = $adapter['scheme']; - $this->options['dsn'] = $adapter['dsn']; + $this->options['dsn'] = $adapter['dsn']; $this->options['username'] = $adapter['user']; $this->options['password'] = $adapter['pass']; @@ -217,7 +219,6 @@ public function __construct(Doctrine_Manager $manager, $adapter, $user = null, $ if (isset($adapter['other'])) { $this->options['other'] = array(Doctrine_Core::ATTR_PERSISTENT => $adapter['persistent']); } - } $this->setParent($manager); @@ -231,9 +232,9 @@ public function __construct(Doctrine_Manager $manager, $adapter, $user = null, $ } /** - * Check wherther the connection to the database has been made yet + * Check wherther the connection to the database has been made yet. * - * @return boolean + * @return bool */ public function isConnected() { @@ -241,24 +242,21 @@ public function isConnected() } /** - * getOptions + * getOptions. * * Get array of all options - * - * @return void */ public function getOptions() { - return $this->options; + return $this->options; } /** - * getOption + * getOption. * * Retrieves option * * @param string $option - * @return void */ public function getOption($option) { @@ -268,31 +266,30 @@ public function getOption($option) } /** - * setOption + * setOption. * * Set option value * * @param string $option - * @return void */ public function setOption($option, $value) { - return $this->options[$option] = $value; + return $this->options[$option] = $value; } /** * getAttribute - * retrieves a database connection attribute + * retrieves a database connection attribute. * - * @param integer $attribute - * @return mixed + * @param int $attribute */ public function getAttribute($attribute) { if ($attribute >= 100 && $attribute < 1000) { - if ( ! isset($this->attributes[$attribute])) { + if (!isset($this->attributes[$attribute])) { return parent::getAttribute($attribute); } + return $this->attributes[$attribute]; } @@ -300,10 +297,10 @@ public function getAttribute($attribute) try { return $this->dbh->getAttribute($attribute); } catch (Exception $e) { - throw new Doctrine_Connection_Exception('Attribute ' . $attribute . ' not found.'); + throw new Doctrine_Connection_Exception('Attribute '.$attribute.' not found.'); } } else { - if ( ! isset($this->pendingAttributes[$attribute])) { + if (!isset($this->pendingAttributes[$attribute])) { $this->connect(); $this->getAttribute($attribute); } @@ -313,7 +310,7 @@ public function getAttribute($attribute) } /** - * returns an array of available PDO drivers + * returns an array of available PDO drivers. */ public static function getAvailableDrivers() { @@ -321,7 +318,7 @@ public static function getAvailableDrivers() } /** - * Returns an array of supported drivers by Doctrine + * Returns an array of supported drivers by Doctrine. * * @return array $supportedDrivers */ @@ -332,14 +329,14 @@ public static function getSupportedDrivers() /** * setAttribute - * sets an attribute + * sets an attribute. * * @todo why check for >= 100? has this any special meaning when creating * attributes? * - * @param integer $attribute - * @param mixed $value - * @return boolean + * @param int $attribute + * + * @return bool */ public function setAttribute($attribute, $value) { @@ -358,9 +355,9 @@ public function setAttribute($attribute, $value) /** * getName - * returns the name of this driver + * returns the name of this driver. * - * @return string the name of this driver + * @return string the name of this driver */ public function getName() { @@ -368,12 +365,11 @@ public function getName() } /** - * setName + * setName. * * Sets the name of the connection * * @param string $name - * @return void */ public function setName($name) { @@ -381,11 +377,9 @@ public function setName($name) } /** - * getDriverName + * getDriverName. * * Gets the name of the instance driver - * - * @return void */ public function getDriverName() { @@ -394,16 +388,19 @@ public function getDriverName() /** * __get - * lazy loads given module and returns it + * lazy loads given module and returns it. * * @see Doctrine_DataDict * @see Doctrine_Expression_Driver * @see Doctrine_Export * @see Doctrine_Transaction * @see Doctrine_Connection::$modules all availible modules - * @param string $name the name of the module to get - * @throws Doctrine_Connection_Exception if trying to get an unknown module - * @return Doctrine_Connection_Module connection module + * + * @param string $name the name of the module to get + * + * @return Doctrine_Connection_Module connection module + * + * @throws Doctrine_Connection_Exception if trying to get an unknown module */ public function __get($name) { @@ -411,10 +408,10 @@ public function __get($name) return $this->properties[$name]; } - if ( ! isset($this->modules[$name])) { - throw new Doctrine_Connection_Exception('Unknown module / property ' . $name); + if (!isset($this->modules[$name])) { + throw new Doctrine_Connection_Exception('Unknown module / property '.$name); } - if ($this->modules[$name] === false) { + if (false === $this->modules[$name]) { switch ($name) { case 'unitOfWork': $this->modules[$name] = new Doctrine_Connection_UnitOfWork($this); @@ -423,16 +420,16 @@ public function __get($name) $this->modules[$name] = new Doctrine_Formatter($this); break; default: - $class = 'Doctrine_' . ucwords($name) . '_' . $this->getDriverName(); + $class = 'Doctrine_'.ucwords($name).'_'.$this->getDriverName(); $this->modules[$name] = new $class($this); - } + } } return $this->modules[$name]; } /** - * returns the manager that created this connection + * returns the manager that created this connection. * * @return Doctrine_Manager */ @@ -442,9 +439,9 @@ public function getManager() } /** - * returns the database handler of which this connection uses + * returns the database handler of which this connection uses. * - * @return PDO the database handler + * @return PDO the database handler */ public function getDbh() { @@ -455,9 +452,9 @@ public function getDbh() /** * connect - * connects into database + * connects into database. * - * @return boolean + * @return bool */ public function connect() { @@ -469,37 +466,37 @@ public function connect() $this->getListener()->preConnect($event); - $e = explode(':', $this->options['dsn']); + $e = explode(':', $this->options['dsn']); $found = false; if (extension_loaded('pdo')) { if (in_array($e[0], self::getAvailableDrivers())) { try { $this->dbh = new PDO($this->options['dsn'], $this->options['username'], - (!$this->options['password'] ? '':$this->options['password']), $this->options['other']); + !$this->options['password'] ? '' : $this->options['password'], $this->options['other']); $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { - throw new Doctrine_Connection_Exception('PDO Connection Error: ' . $e->getMessage()); + throw new Doctrine_Connection_Exception('PDO Connection Error: '.$e->getMessage()); } $found = true; } } - if ( ! $found) { - $class = 'Doctrine_Adapter_' . ucwords($e[0]); + if (!$found) { + $class = 'Doctrine_Adapter_'.ucwords($e[0]); if (class_exists($class)) { $this->dbh = new $class($this->options['dsn'], $this->options['username'], $this->options['password'], $this->options); } else { - throw new Doctrine_Connection_Exception("Couldn't locate driver named " . $e[0]); + throw new Doctrine_Connection_Exception("Couldn't locate driver named ".$e[0]); } } // attach the pending attributes to adapter - foreach($this->pendingAttributes as $attr => $value) { + foreach ($this->pendingAttributes as $attr => $value) { // some drivers don't support setting this so we just skip it - if ($attr == Doctrine_Core::ATTR_DRIVER_NAME) { + if (Doctrine_Core::ATTR_DRIVER_NAME == $attr) { continue; } $this->dbh->setAttribute($attr, $value); @@ -508,34 +505,34 @@ public function connect() $this->isConnected = true; $this->getListener()->postConnect($event); + return true; } public function incrementQueryCount() { - $this->_count++; + ++$this->_count; } /** - * converts given driver name - * - * @param + * converts given driver name. */ public function driverName($name) { } /** - * supports + * supports. + * + * @param string $feature the name of the feature * - * @param string $feature the name of the feature - * @return boolean whether or not this drivers supports given feature + * @return bool whether or not this drivers supports given feature */ public function supports($feature) { - return (isset($this->supported[$feature]) - && ($this->supported[$feature] === 'emulated' - || $this->supported[$feature])); + return isset($this->supported[$feature]) + && ('emulated' === $this->supported[$feature] + || $this->supported[$feature]); } /** @@ -550,26 +547,25 @@ public function supports($feature) * of queries inside a transaction to assure the atomicity of the operation. * * @param string name of the table on which the REPLACE query will - * be executed. - * + * be executed * @param array an associative array that describes the fields and the * values that will be inserted or updated in the specified table. The * indexes of the array are the names of all the fields of the table. * * The values of the array are values to be assigned to the specified field. - * - * @param array $keys an array containing all key fields (primary key fields - * or unique index fields) for this table + * @param array $keys an array containing all key fields (primary key fields + * or unique index fields) for this table * * the uniqueness of a row will be determined according to * the provided key fields * * this method will fail if no key fields are specified * - * @throws Doctrine_Connection_Exception if this driver doesn't support replace - * @throws Doctrine_Connection_Exception if some of the key values was null - * @throws Doctrine_Connection_Exception if there were no key fields - * @throws PDOException if something fails at PDO level + * @throws Doctrine_Connection_Exception if this driver doesn't support replace + * @throws Doctrine_Connection_Exception if some of the key values was null + * @throws Doctrine_Connection_Exception if there were no key fields + * @throws PDOException if something fails at PDO level + * * @ return integer number of rows affected */ public function replace(Doctrine_Table $table, array $fields, array $keys) @@ -582,47 +578,49 @@ public function replace(Doctrine_Table $table, array $fields, array $keys) foreach ($fields as $fieldName => $value) { if (in_array($fieldName, $keys)) { - if ($value !== null) { - $condition[] = $table->getColumnName($fieldName) . ' = ?'; + if (null !== $value) { + $condition[] = $table->getColumnName($fieldName).' = ?'; $conditionValues[] = $value; } } } $affectedRows = 0; - if ( ! empty($condition) && ! empty($conditionValues)) { - $query = 'DELETE FROM ' . $this->quoteIdentifier($table->getTableName()) - . ' WHERE ' . implode(' AND ', $condition); + if (!empty($condition) && !empty($conditionValues)) { + $query = 'DELETE FROM '.$this->quoteIdentifier($table->getTableName()) + .' WHERE '.implode(' AND ', $condition); $affectedRows = $this->exec($query, $conditionValues); } $this->insert($table, $fields); - $affectedRows++; + ++$affectedRows; return $affectedRows; } /** - * deletes table row(s) matching the specified identifier + * deletes table row(s) matching the specified identifier. + * + * @param string $table The table to delete data from + * @param array $identifier an associateve array containing identifier column-value pairs * - * @throws Doctrine_Connection_Exception if something went wrong at the database level - * @param string $table The table to delete data from - * @param array $identifier An associateve array containing identifier column-value pairs. - * @return integer The number of affected rows + * @return int The number of affected rows + * + * @throws Doctrine_Connection_Exception if something went wrong at the database level */ public function delete(Doctrine_Table $table, array $identifier) { $tmp = array(); foreach (array_keys($identifier) as $id) { - $tmp[] = $this->quoteIdentifier($table->getColumnName($id)) . ' = ?'; + $tmp[] = $this->quoteIdentifier($table->getColumnName($id)).' = ?'; } $query = 'DELETE FROM ' - . $this->quoteIdentifier($table->getTableName()) - . ' WHERE ' . implode(' AND ', $tmp); + .$this->quoteIdentifier($table->getTableName()) + .' WHERE '.implode(' AND ', $tmp); return $this->exec($query, array_values($identifier)); } @@ -630,11 +628,11 @@ public function delete(Doctrine_Table $table, array $identifier) /** * Updates table row(s) with specified data. * - * @throws Doctrine_Connection_Exception if something went wrong at the database level - * @param Doctrine_Table $table The table to insert data into - * @param array $values An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param Doctrine_Table $table The table to insert data into + * + * @return int the number of affected rows. Boolean false if empty value array was given, + * + * @throws Doctrine_Connection_Exception if something went wrong at the database level */ public function update(Doctrine_Table $table, array $fields, array $identifier) { @@ -645,19 +643,19 @@ public function update(Doctrine_Table $table, array $fields, array $identifier) $set = array(); foreach ($fields as $fieldName => $value) { if ($value instanceof Doctrine_Expression) { - $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)) . ' = ' . $value->getSql(); + $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)).' = '.$value->getSql(); unset($fields[$fieldName]); } else { - $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)) . ' = ?'; + $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)).' = ?'; } } $params = array_merge(array_values($fields), array_values($identifier)); - $sql = 'UPDATE ' . $this->quoteIdentifier($table->getTableName()) - . ' SET ' . implode(', ', $set) - . ' WHERE ' . implode(' = ? AND ', $this->quoteMultipleIdentifier($table->getIdentifierColumnNames())) - . ' = ?'; + $sql = 'UPDATE '.$this->quoteIdentifier($table->getTableName()) + .' SET '.implode(', ', $set) + .' WHERE '.implode(' = ? AND ', $this->quoteMultipleIdentifier($table->getIdentifierColumnNames())) + .' = ?'; return $this->exec($sql, $params); } @@ -665,10 +663,9 @@ public function update(Doctrine_Table $table, array $fields, array $identifier) /** * Inserts a table row with specified data. * - * @param Doctrine_Table $table The table to insert data into. - * @param array $values An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param Doctrine_Table $table the table to insert data into + * + * @return int the number of affected rows. Boolean false if empty value array was given, */ public function insert(Doctrine_Table $table, array $fields) { @@ -689,15 +686,15 @@ public function insert(Doctrine_Table $table, array $fields) } // build the statement - $query = 'INSERT INTO ' . $this->quoteIdentifier($tableName) - . ' (' . implode(', ', $cols) . ')' - . ' VALUES (' . implode(', ', $a) . ')'; + $query = 'INSERT INTO '.$this->quoteIdentifier($tableName) + .' ('.implode(', ', $cols).')' + .' VALUES ('.implode(', ', $a).')'; return $this->exec($query, array_values($fields)); } /** - * Quote a string so it can be safely used as a table or column name + * Quote a string so it can be safely used as a table or column name. * * Delimiting style depends on which database driver is being used. * @@ -723,10 +720,10 @@ public function insert(Doctrine_Table $table, array $fields) * InterBase doesn't seem to be able to use delimited identifiers * via PHP 4. They work fine under PHP 5. * - * @param string $str identifier name to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param string $str identifier name to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteIdentifier($str, $checkOption = true) { @@ -734,20 +731,21 @@ public function quoteIdentifier($str, $checkOption = true) if (strpos($str, '.')) { $e = explode('.', $str); - return $this->formatter->quoteIdentifier($e[0], $checkOption) . '.' - . $this->formatter->quoteIdentifier($e[1], $checkOption); + return $this->formatter->quoteIdentifier($e[0], $checkOption).'.' + .$this->formatter->quoteIdentifier($e[1], $checkOption); } + return $this->formatter->quoteIdentifier($str, $checkOption); } /** * quoteMultipleIdentifier - * Quotes multiple identifier strings + * Quotes multiple identifier strings. * - * @param array $arr identifiers array to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param array $arr identifiers array to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteMultipleIdentifier($arr, $checkOption = true) { @@ -761,12 +759,11 @@ public function quoteMultipleIdentifier($arr, $checkOption = true) /** * convertBooleans * some drivers need the boolean values to be converted into integers - * when using DQL API + * when using DQL API. * * This method takes care of that conversion * * @param array $item - * @return void */ public function convertBooleans($item) { @@ -775,10 +772,11 @@ public function convertBooleans($item) /** * quote - * quotes given input parameter + * quotes given input parameter. * - * @param mixed $input parameter to be quoted + * @param mixed $input parameter to be quoted * @param string $type + * * @return string */ public function quote($input, $type = null) @@ -787,21 +785,21 @@ public function quote($input, $type = null) } /** - * Set the date/time format for the current connection + * Set the date/time format for the current connection. * * @param string time format - * - * @return void + * @param mixed|null $format */ public function setDateFormat($format = null) { } /** - * fetchAll + * fetchAll. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchAll($statement, array $params = array()) @@ -810,12 +808,11 @@ public function fetchAll($statement, array $params = array()) } /** - * fetchOne + * fetchOne. * - * @param string $statement sql query to be executed - * @param array $params prepared statement params - * @param int $colnum 0-indexed column number to retrieve - * @return mixed + * @param string $statement sql query to be executed + * @param array $params prepared statement params + * @param int $colnum 0-indexed column number to retrieve */ public function fetchOne($statement, array $params = array(), $colnum = 0) { @@ -823,10 +820,11 @@ public function fetchOne($statement, array $params = array(), $colnum = 0) } /** - * fetchRow + * fetchRow. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchRow($statement, array $params = array()) @@ -835,10 +833,11 @@ public function fetchRow($statement, array $params = array()) } /** - * fetchArray + * fetchArray. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchArray($statement, array $params = array()) @@ -847,11 +846,12 @@ public function fetchArray($statement, array $params = array()) } /** - * fetchColumn + * fetchColumn. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params + * @param int $colnum 0-indexed column number to retrieve * - * @param string $statement sql query to be executed - * @param array $params prepared statement params - * @param int $colnum 0-indexed column number to retrieve * @return array */ public function fetchColumn($statement, array $params = array(), $colnum = 0) @@ -860,10 +860,11 @@ public function fetchColumn($statement, array $params = array(), $colnum = 0) } /** - * fetchAssoc + * fetchAssoc. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchAssoc($statement, array $params = array()) @@ -872,10 +873,11 @@ public function fetchAssoc($statement, array $params = array()) } /** - * fetchBoth + * fetchBoth. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchBoth($statement, array $params = array()) @@ -886,7 +888,7 @@ public function fetchBoth($statement, array $params = array()) /** * query * queries the database using Doctrine Query Language - * returns a collection of Doctrine_Record objects + * returns a collection of Doctrine_Record objects. * * * $users = $conn->query('SELECT u.* FROM User u'); @@ -894,11 +896,13 @@ public function fetchBoth($statement, array $params = array()) * $users = $conn->query('SELECT u.* FROM User u WHERE u.name LIKE ?', array('someone')); * * - * @param string $query DQL query - * @param array $params query parameters - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string $query DQL query + * @param array $params query parameters + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @see Doctrine_Query - * @return Doctrine_Collection Collection of Doctrine_Record objects + * + * @return Doctrine_Collection Collection of Doctrine_Record objects */ public function query($query, array $params = array(), $hydrationMode = null) { @@ -910,7 +914,7 @@ public function query($query, array $params = array(), $hydrationMode = null) } /** - * prepare + * prepare. * * @param string $statement */ @@ -925,15 +929,16 @@ public function prepare($statement) $stmt = false; - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $stmt = $this->dbh->prepare($statement); } $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postPrepare($event); return new Doctrine_Connection_Statement($this, $stmt); - } catch(Doctrine_Adapter_Exception $e) { - } catch(PDOException $e) { } + } catch (Doctrine_Adapter_Exception $e) { + } catch (PDOException $e) { + } $this->rethrowException($e, $this, $statement); } @@ -941,7 +946,7 @@ public function prepare($statement) /** * query * queries the database using Doctrine Query Language and returns - * the first record found + * the first record found. * * * $user = $conn->queryOne('SELECT u.* FROM User u WHERE u.id = ?', array(1)); @@ -951,30 +956,34 @@ public function prepare($statement) * ); * * - * @param string $query DQL query - * @param array $params query parameters + * @param string $query DQL query + * @param array $params query parameters + * * @see Doctrine_Query - * @return Doctrine_Record|false Doctrine_Record object on success, - * boolean false on failure + * + * @return Doctrine_Record|false Doctrine_Record object on success, + * boolean false on failure */ public function queryOne($query, array $params = array()) { $parser = Doctrine_Query::create(); $coll = $parser->query($query, $params); - if ( ! $coll->contains(0)) { + if (!$coll->contains(0)) { return false; } + return $coll[0]; } /** * queries the database with limit and offset - * added to the query and returns a Doctrine_Connection_Statement object + * added to the query and returns a Doctrine_Connection_Statement object. * * @param string $query - * @param integer $limit - * @param integer $offset + * @param int $limit + * @param int $offset + * * @return Doctrine_Connection_Statement */ public function select($query, $limit = 0, $offset = 0) @@ -982,14 +991,15 @@ public function select($query, $limit = 0, $offset = 0) if ($limit > 0 || $offset > 0) { $query = $this->modifyLimitQuery($query, $limit, $offset); } + return $this->execute($query); } /** - * standaloneQuery + * standaloneQuery. * - * @param string $query sql query - * @param array $params query parameters + * @param string $query sql query + * @param array $params query parameters * * @return PDOStatement|Doctrine_Adapter_Statement */ @@ -999,9 +1009,10 @@ public function standaloneQuery($query, $params = array()) } /** - * execute - * @param string $query sql query - * @param array $params query parameters + * execute. + * + * @param string $query sql query + * @param array $params query parameters * * @return PDOStatement|Doctrine_Adapter_Statement */ @@ -1010,68 +1021,71 @@ public function execute($query, array $params = array()) $this->connect(); try { - if ( ! empty($params)) { + if (!empty($params)) { $stmt = $this->prepare($query); $stmt->execute($params); return $stmt; - } else { - $event = new Doctrine_Event($this, Doctrine_Event::CONN_QUERY, $query, $params); - - $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->preQuery($event); + } + $event = new Doctrine_Event($this, Doctrine_Event::CONN_QUERY, $query, $params); - if ( ! $event->skipOperation) { - $stmt = $this->dbh->query($query); - $this->_count++; - } - $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postQuery($event); + $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->preQuery($event); - return $stmt; + if (!$event->skipOperation) { + $stmt = $this->dbh->query($query); + ++$this->_count; } + $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postQuery($event); + + return $stmt; } catch (Doctrine_Adapter_Exception $e) { - } catch (PDOException $e) { } + } catch (PDOException $e) { + } $this->rethrowException($e, $this, $query); } /** - * exec - * @param string $query sql query - * @param array $params query parameters + * exec. * - * @return integer + * @param string $query sql query + * @param array $params query parameters + * + * @return int */ public function exec($query, array $params = array()) { $this->connect(); try { - if ( ! empty($params)) { + if (!empty($params)) { $stmt = $this->prepare($query); $stmt->execute($params); return $stmt->rowCount(); - } else { - $event = new Doctrine_Event($this, Doctrine_Event::CONN_EXEC, $query, $params); - - $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->preExec($event); - if ( ! $event->skipOperation) { - $count = $this->dbh->exec($query); + } + $event = new Doctrine_Event($this, Doctrine_Event::CONN_EXEC, $query, $params); - $this->_count++; - } - $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postExec($event); + $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->preExec($event); + if (!$event->skipOperation) { + $count = $this->dbh->exec($query); - return $count; + ++$this->_count; } + $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postExec($event); + + return $count; } catch (Doctrine_Adapter_Exception $e) { - } catch (PDOException $e) { } + } catch (PDOException $e) { + } $this->rethrowException($e, $this, $query); } /** - * rethrowException + * rethrowException. + * + * @param mixed|null $query * * @throws Doctrine_Connection_Exception */ @@ -1081,20 +1095,20 @@ public function rethrowException(Exception $e, $invoker, $query = null) $this->getListener()->preError($event); - $name = 'Doctrine_Connection_' . $this->driverName . '_Exception'; + $name = 'Doctrine_Connection_'.$this->driverName.'_Exception'; $message = $e->getMessage(); if ($query) { $message .= sprintf('. Failing Query: "%s"', $query); } - $exc = new $name($message, (int) $e->getCode()); - if ( ! isset($e->errorInfo) || ! is_array($e->errorInfo)) { + $exc = new $name($message, (int) $e->getCode()); + if (!isset($e->errorInfo) || !is_array($e->errorInfo)) { $e->errorInfo = array(null, null, null, null); } $exc->processErrorInfo($e->errorInfo); - if ($this->getAttribute(Doctrine_Core::ATTR_THROW_EXCEPTIONS)) { + if ($this->getAttribute(Doctrine_Core::ATTR_THROW_EXCEPTIONS)) { throw $exc; } @@ -1103,10 +1117,9 @@ public function rethrowException(Exception $e, $invoker, $query = null) /** * hasTable - * whether or not this connection has table $name initialized + * whether or not this connection has table $name initialized. * - * @param mixed $name - * @return boolean + * @return bool */ public function hasTable($name) { @@ -1114,9 +1127,10 @@ public function hasTable($name) } /** - * returns a table object for given component name + * returns a table object for given component name. + * + * @param string $name component name * - * @param string $name component name * @return Doctrine_Table */ public function getTable($name) @@ -1125,10 +1139,10 @@ public function getTable($name) return $this->tables[$name]; } - $hasTableCache = $this->_tableCache !== false && ($this->_tableCache || $this->getAttribute(Doctrine_Core::ATTR_TABLE_CACHE)); + $hasTableCache = false !== $this->_tableCache && ($this->_tableCache || $this->getAttribute(Doctrine_Core::ATTR_TABLE_CACHE)); if ($hasTableCache) { $tableCacheDriver = $this->getTableCacheDriver(); - $hash = md5($name . 'DOCTRINE_TABLE_CACHE_SALT'); + $hash = md5($name.'DOCTRINE_TABLE_CACHE_SALT'); $cached = $tableCacheDriver->fetch($hash); if ($cached) { @@ -1141,8 +1155,8 @@ public function getTable($name) $class = sprintf($this->getAttribute(Doctrine_Core::ATTR_TABLE_CLASS_FORMAT), $name); - if (class_exists($class, $this->getAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES)) && - in_array('Doctrine_Table', class_parents($class))) { + if (class_exists($class, $this->getAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES)) + && in_array('Doctrine_Table', class_parents($class))) { $table = new $class($name, $this, true); } else { $tableClass = $this->getAttribute(Doctrine_Core::ATTR_TABLE_CLASS); @@ -1158,7 +1172,7 @@ public function getTable($name) } /** - * returns an array of all initialized tables + * returns an array of all initialized tables. * * @return array */ @@ -1169,7 +1183,7 @@ public function getTables() /** * returns an iterator that iterators through all - * initialized table objects + * initialized table objects. * * * foreach ($conn as $index => $table) { @@ -1177,20 +1191,20 @@ public function getTables() * } * * - * @return ArrayIterator SPL ArrayIterator object + * @return ArrayIterator SPL ArrayIterator object */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->tables); } /** - * returns the count of initialized table objects + * returns the count of initialized table objects. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return $this->_count; @@ -1198,10 +1212,11 @@ public function count() /** * addTable - * adds a Doctrine_Table object into connection registry + * adds a Doctrine_Table object into connection registry. + * + * @param $table a Doctrine_Table object to be added into registry * - * @param $table a Doctrine_Table object to be added into registry - * @return boolean + * @return bool */ public function addTable(Doctrine_Table $table) { @@ -1217,11 +1232,13 @@ public function addTable(Doctrine_Table $table) /** * create - * creates a record + * creates a record. * * create creates a record - * @param string $name component name - * @return Doctrine_Record Doctrine_Record object + * + * @param string $name component name + * + * @return Doctrine_Record Doctrine_Record object */ public function create($name) { @@ -1241,10 +1258,9 @@ public function createQuery() /** * flush * saves all the records from all tables - * this operation is isolated using a transaction + * this operation is isolated using a transaction. * - * @throws PDOException if something went wrong at database level - * @return void + * @throws PDOException if something went wrong at database level */ public function flush() { @@ -1260,9 +1276,7 @@ public function flush() /** * clear - * clears all repositories - * - * @return void + * clears all repositories. */ public function clear() { @@ -1274,9 +1288,7 @@ public function clear() /** * evictTables - * evicts all tables - * - * @return void + * evicts all tables. */ public function evictTables() { @@ -1286,9 +1298,7 @@ public function evictTables() /** * close - * closes the connection - * - * @return void + * closes the connection. */ public function close() { @@ -1305,9 +1315,9 @@ public function close() } /** - * get the current transaction nesting level + * get the current transaction nesting level. * - * @return integer + * @return int */ public function getTransactionLevel() { @@ -1316,9 +1326,9 @@ public function getTransactionLevel() /** * errorCode - * Fetch the SQLSTATE associated with the last operation on the database handle + * Fetch the SQLSTATE associated with the last operation on the database handle. * - * @return integer + * @return int */ public function errorCode() { @@ -1329,7 +1339,7 @@ public function errorCode() /** * errorInfo - * Fetch extended error information associated with the last operation on the database handle + * Fetch extended error information associated with the last operation on the database handle. * * @return array */ @@ -1341,13 +1351,13 @@ public function errorInfo() } /** - * getResultCacheDriver + * getResultCacheDriver. * * @return Doctrine_Cache_Interface */ public function getResultCacheDriver() { - if ( ! $this->getAttribute(Doctrine_Core::ATTR_RESULT_CACHE)) { + if (!$this->getAttribute(Doctrine_Core::ATTR_RESULT_CACHE)) { throw new Doctrine_Exception('Result Cache driver not initialized.'); } @@ -1355,13 +1365,13 @@ public function getResultCacheDriver() } /** - * getQueryCacheDriver + * getQueryCacheDriver. * * @return Doctrine_Cache_Interface */ public function getQueryCacheDriver() { - if ( ! $this->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE)) { + if (!$this->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE)) { throw new Doctrine_Exception('Query Cache driver not initialized.'); } @@ -1369,13 +1379,13 @@ public function getQueryCacheDriver() } /** - * getQueryCacheDriver + * getQueryCacheDriver. * * @return Doctrine_Cache_Interface */ public function getTableCacheDriver() { - if ( ! $this->getAttribute(Doctrine_Core::ATTR_TABLE_CACHE)) { + if (!$this->getAttribute(Doctrine_Core::ATTR_TABLE_CACHE)) { throw new Doctrine_Exception('Query Cache driver not initialized.'); } @@ -1385,7 +1395,7 @@ public function getTableCacheDriver() /** * Gets the life span of the table cache the Query object is using. * - * @return integer The life span in seconds. + * @return int the life span in seconds */ public function getTableCacheLifeSpan() { @@ -1393,7 +1403,7 @@ public function getTableCacheLifeSpan() } /** - * lastInsertId + * lastInsertId. * * Returns the ID of the last inserted row, or the last value from a sequence object, * depending on the underlying driver. @@ -1401,8 +1411,8 @@ public function getTableCacheLifeSpan() * Note: This method may not return a meaningful or consistent result across different drivers, * because the underlying database may not even support the notion of auto-increment fields or sequences. * - * @param string $table name of the table into which a new row was inserted - * @param string $field name of the field into which a new row was inserted + * @param string $table name of the table into which a new row was inserted + * @param string $field name of the field into which a new row was inserted */ public function lastInsertId($table = null, $field = null) { @@ -1418,9 +1428,11 @@ public function lastInsertId($table = null, $field = null) * * Listeners: onPreTransactionBegin, onTransactionBegin * - * @param string $savepoint name of a savepoint to set - * @throws Doctrine_Transaction_Exception if the transaction fails at database level - * @return integer current transaction nesting level + * @param string $savepoint name of a savepoint to set + * + * @return int current transaction nesting level + * + * @throws Doctrine_Transaction_Exception if the transaction fails at database level */ public function beginTransaction($savepoint = null) { @@ -1440,10 +1452,12 @@ public function beginInternalTransaction($savepoint = null) * * Listeners: onPreTransactionCommit, onTransactionCommit * - * @param string $savepoint name of a savepoint to release - * @throws Doctrine_Transaction_Exception if the transaction fails at PDO level - * @throws Doctrine_Validator_Exception if the transaction fails due to record validations - * @return boolean false if commit couldn't be performed, true otherwise + * @param string $savepoint name of a savepoint to release + * + * @return bool false if commit couldn't be performed, true otherwise + * + * @throws Doctrine_Transaction_Exception if the transaction fails at PDO level + * @throws Doctrine_Validator_Exception if the transaction fails due to record validations */ public function commit($savepoint = null) { @@ -1460,9 +1474,11 @@ public function commit($savepoint = null) * this method can be listened with onPreTransactionRollback and onTransactionRollback * eventlistener methods * - * @param string $savepoint name of a savepoint to rollback to - * @throws Doctrine_Transaction_Exception if the rollback operation fails at database level - * @return boolean false if rollback couldn't be performed, true otherwise + * @param string $savepoint name of a savepoint to rollback to + * + * @return bool false if rollback couldn't be performed, true otherwise + * + * @throws Doctrine_Transaction_Exception if the rollback operation fails at database level */ public function rollback($savepoint = null) { @@ -1470,15 +1486,15 @@ public function rollback($savepoint = null) } /** - * createDatabase + * createDatabase. * * Issue create database command for this instance of Doctrine_Connection * - * @return string Doctrine_Exception catched in case of failure + * @return string Doctrine_Exception catched in case of failure */ public function createDatabase() { - if ( ! $dsn = $this->getOption('dsn')) { + if (!$dsn = $this->getOption('dsn')) { throw new Doctrine_Connection_Exception('You must create your Doctrine_Connection by using a valid Doctrine style dsn in order to use the create/drop database functionality'); } @@ -1492,7 +1508,8 @@ public function createDatabase() // the tmp connection try { $tmpConnection->export->createDatabase($info['dbname']); - } catch (Exception $e) {} + } catch (Exception $e) { + } // Close the temporary connection used to issue the drop database command $this->getManager()->closeConnection($tmpConnection); @@ -1503,15 +1520,15 @@ public function createDatabase() } /** - * dropDatabase + * dropDatabase. * * Issue drop database command for this instance of Doctrine_Connection * - * @return string success string. Doctrine_Exception if operation failed + * @return string success string. Doctrine_Exception if operation failed */ public function dropDatabase() { - if ( ! $dsn = $this->getOption('dsn')) { + if (!$dsn = $this->getOption('dsn')) { throw new Doctrine_Connection_Exception('You must create your Doctrine_Connection by using a valid Doctrine style dsn in order to use the create/drop database functionality'); } @@ -1525,19 +1542,19 @@ public function dropDatabase() // the tmp connection try { $tmpConnection->export->dropDatabase($info['dbname']); - } catch (Exception $e) {} + } catch (Exception $e) { + } // Close the temporary connection used to issue the drop database command $this->getManager()->closeConnection($tmpConnection); - if (isset($e)) { throw $e; } } /** - * getTmpConnection + * getTmpConnection. * * Create a temporary connection to the database with the user credentials. * This is so the user can make a connection to a db server. Some dbms allow @@ -1546,24 +1563,23 @@ public function dropDatabase() * This value is set in the Doctrine_Export_{DRIVER} classes if required * * @param string $info - * @return void */ public function getTmpConnection($info) { - $pdoDsn = $info['scheme'] . ':'; + $pdoDsn = $info['scheme'].':'; if ($info['unix_socket']) { - $pdoDsn .= 'unix_socket=' . $info['unix_socket'] . ';'; + $pdoDsn .= 'unix_socket='.$info['unix_socket'].';'; } - $pdoDsn .= 'host=' . $info['host']; + $pdoDsn .= 'host='.$info['host']; if ($info['port']) { - $pdoDsn .= ';port=' . $info['port']; + $pdoDsn .= ';port='.$info['port']; } if (isset($this->export->tmpConnectionDatabase) && $this->export->tmpConnectionDatabase) { - $pdoDsn .= ';dbname=' . $this->export->tmpConnectionDatabase; + $pdoDsn .= ';dbname='.$this->export->tmpConnectionDatabase; } $username = $this->getOption('username'); @@ -1577,7 +1593,7 @@ public function getTmpConnection($info) } /** - * modifyLimitQuery + * modifyLimitQuery. * * Some dbms require specific functionality for this. Check the other connection adapters for examples * @@ -1595,13 +1611,14 @@ public function modifyLimitQuery($query, $limit = false, $offset = false, $isMan * @return string */ public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = false, - $offset = false, $isManip = false) + $offset = false, $isManip = false) { return $this->modifyLimitQuery($query, $limit, $offset, $isManip); } /** - * returns a string representation of this object + * returns a string representation of this object. + * * @return string */ public function __toString() @@ -1609,9 +1626,8 @@ public function __toString() return Doctrine_Lib::getConnectionAsString($this); } - /** - * Serialize. Remove database connection(pdo) since it cannot be serialized + * Serialize. Remove database connection(pdo) since it cannot be serialized. * * @return string $serialized */ @@ -1623,10 +1639,9 @@ public function serialize() } /** - * Unserialize. Recreate connection from serialized content + * Unserialize. Recreate connection from serialized content. * * @param string $serialized - * @return void */ public function unserialize($serialized) { @@ -1636,7 +1651,7 @@ public function unserialize($serialized) } /** - * Serialize. Remove database connection(pdo) since it cannot be serialized for PHP 7.4+ + * Serialize. Remove database connection(pdo) since it cannot be serialized for PHP 7.4+. * * @return array */ @@ -1650,22 +1665,22 @@ public function __serialize() } /** - * Unserialize. Recreate connection from serialized content PHP 7.4+ + * Unserialize. Recreate connection from serialized content PHP 7.4+. * * @param array $data - * @return void */ public function __unserialize($data) { foreach ($data as $name => $values) { - $this->$name = $values; + $this->{$name} = $values; } } /** - * Get/generate a unique foreign key name for a relationship + * Get/generate a unique foreign key name for a relationship. + * + * @param Doctrine_Relation $relation Relation object to generate the foreign key name for * - * @param Doctrine_Relation $relation Relation object to generate the foreign key name for * @return string $fkName */ public function generateUniqueRelationForeignKeyName(Doctrine_Relation $relation) @@ -1683,10 +1698,11 @@ public function generateUniqueRelationForeignKeyName(Doctrine_Relation $relation } /** - * Get/generate unique index name for a table name and set of fields + * Get/generate unique index name for a table name and set of fields. + * + * @param string $tableName The name of the table the index exists + * @param string $fields The fields that makes up the index * - * @param string $tableName The name of the table the index exists - * @param string $fields The fields that makes up the index * @return string $indexName The name of the generated index */ public function generateUniqueIndexName($tableName, $fields) @@ -1705,8 +1721,8 @@ protected function _generateUniqueName($type, $parts, $key, $format = '%s', $max if (isset($this->_usedNames[$type][$key])) { return $this->_usedNames[$type][$key]; } - if ($maxLength === null) { - $maxLength = $this->properties['max_identifier_length']; + if (null === $maxLength) { + $maxLength = $this->properties['max_identifier_length']; } $generated = implode('_', $parts); @@ -1731,7 +1747,7 @@ protected function _generateUniqueName($type, $parts, $key, $format = '%s', $max if (is_numeric($end)) { unset($e[count($e) - 1]); $fkName = implode('_', $e); - $name = $fkName . '_' . ++$end; + $name = $fkName.'_'.++$end; } else { $name .= '_1'; } diff --git a/lib/Doctrine/Connection/Common.php b/lib/Doctrine/Connection/Common.php index 36f7e286c..d63e53d7c 100644 --- a/lib/Doctrine/Connection/Common.php +++ b/lib/Doctrine/Connection/Common.php @@ -20,37 +20,38 @@ */ /** - * standard connection, the parent of pgsql, mysql and sqlite + * standard connection, the parent of pgsql, mysql and sqlite. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Connection - * @link www.doctrine-project.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Common extends Doctrine_Connection { /** - * Adds an driver-specific LIMIT clause to the query + * Adds an driver-specific LIMIT clause to the query. * * @param string $query - * @param mixed $limit - * @param mixed $offset + * * @return string */ - public function modifyLimitQuery($query, $limit = false,$offset = false,$isManip=false) + public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { $limit = (int) $limit; $offset = (int) $offset; if ($limit && $offset) { - $query .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } elseif ($limit && ! $offset) { - $query .= ' LIMIT ' . $limit; - } elseif ( ! $limit && $offset) { - $query .= ' LIMIT 999999999999 OFFSET ' . $offset; + $query .= ' LIMIT '.$limit.' OFFSET '.$offset; + } elseif ($limit && !$offset) { + $query .= ' LIMIT '.$limit; + } elseif (!$limit && $offset) { + $query .= ' LIMIT 999999999999 OFFSET '.$offset; } return $query; diff --git a/lib/Doctrine/Connection/Db2.php b/lib/Doctrine/Connection/Db2.php index ad9d1505d..dee23d4bc 100644 --- a/lib/Doctrine/Connection/Db2.php +++ b/lib/Doctrine/Connection/Db2.php @@ -20,45 +20,46 @@ */ /** - * Doctrine_Connection_Db2 + * Doctrine_Connection_Db2. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Db2 extends Doctrine_Connection_Common { /** - * Adds an driver-specific LIMIT clause to the query + * Adds an driver-specific LIMIT clause to the query. + * + * @param string $query query to modify + * @param int $limit limit the number of rows + * @param int $offset start reading from given offset * - * @param string $query query to modify - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string the modified query + * @return string the modified query */ public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { - if ($limit <= 0) + if ($limit <= 0) { return $query; + } - if ($offset == 0) { - return $query . ' FETCH FIRST '. (int)$limit .' ROWS ONLY'; - } else { - $sqlPieces = explode('from', $query); - $select = $sqlPieces[0]; - $table = $sqlPieces[1]; + if (0 == $offset) { + return $query.' FETCH FIRST '.(int) $limit.' ROWS ONLY'; + } + $sqlPieces = explode('from', $query); + $select = $sqlPieces[0]; + $table = $sqlPieces[1]; - $col = explode('select', $select); + $col = explode('select', $select); - $sql = 'WITH OFFSET AS(' . $select . ', ROW_NUMBER() ' . - 'OVER(ORDER BY ' . $col[1] . ') AS doctrine_rownum FROM ' . $table . ')' . - $select . 'FROM OFFSET WHERE doctrine_rownum BETWEEN ' . (int)$offset . - 'AND ' . ((int)$offset + (int)$limit - 1); - return $sql; - } + return 'WITH OFFSET AS('.$select.', ROW_NUMBER() '. + 'OVER(ORDER BY '.$col[1].') AS doctrine_rownum FROM '.$table.')'. + $select.'FROM OFFSET WHERE doctrine_rownum BETWEEN '.(int) $offset. + 'AND '.((int) $offset + (int) $limit - 1); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Exception.php b/lib/Doctrine/Connection/Exception.php index 43e6161db..796a4b6f8 100644 --- a/lib/Doctrine/Connection/Exception.php +++ b/lib/Doctrine/Connection/Exception.php @@ -20,68 +20,70 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Exception extends Doctrine_Exception { /** - * @var array $errorMessages an array containing messages for portable error codes + * @var array an array containing messages for portable error codes */ - static protected $errorMessages = array( - Doctrine_Core::ERR => 'unknown error', - Doctrine_Core::ERR_ALREADY_EXISTS => 'already exists', - Doctrine_Core::ERR_CANNOT_CREATE => 'can not create', - Doctrine_Core::ERR_CANNOT_ALTER => 'can not alter', - Doctrine_Core::ERR_CANNOT_REPLACE => 'can not replace', - Doctrine_Core::ERR_CANNOT_DELETE => 'can not delete', - Doctrine_Core::ERR_CANNOT_DROP => 'can not drop', - Doctrine_Core::ERR_CONSTRAINT => 'constraint violation', - Doctrine_Core::ERR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint', - Doctrine_Core::ERR_DIVZERO => 'division by zero', - Doctrine_Core::ERR_INVALID => 'invalid', - Doctrine_Core::ERR_INVALID_DATE => 'invalid date or time', - Doctrine_Core::ERR_INVALID_NUMBER => 'invalid number', - Doctrine_Core::ERR_MISMATCH => 'mismatch', - Doctrine_Core::ERR_NODBSELECTED => 'no database selected', - Doctrine_Core::ERR_NOSUCHFIELD => 'no such field', - Doctrine_Core::ERR_NOSUCHTABLE => 'no such table', - Doctrine_Core::ERR_NOT_CAPABLE => 'Doctrine backend not capable', - Doctrine_Core::ERR_NOT_FOUND => 'not found', - Doctrine_Core::ERR_NOT_LOCKED => 'not locked', - Doctrine_Core::ERR_SYNTAX => 'syntax error', - Doctrine_Core::ERR_UNSUPPORTED => 'not supported', - Doctrine_Core::ERR_VALUE_COUNT_ON_ROW => 'value count on row', - Doctrine_Core::ERR_INVALID_DSN => 'invalid DSN', - Doctrine_Core::ERR_CONNECT_FAILED => 'connect failed', - Doctrine_Core::ERR_NEED_MORE_DATA => 'insufficient data supplied', - Doctrine_Core::ERR_EXTENSION_NOT_FOUND=> 'extension not found', - Doctrine_Core::ERR_NOSUCHDB => 'no such database', - Doctrine_Core::ERR_ACCESS_VIOLATION => 'insufficient permissions', - Doctrine_Core::ERR_LOADMODULE => 'error while including on demand module', - Doctrine_Core::ERR_TRUNCATED => 'truncated', - Doctrine_Core::ERR_DEADLOCK => 'deadlock detected', - ); + protected static $errorMessages = array( + Doctrine_Core::ERR => 'unknown error', + Doctrine_Core::ERR_ALREADY_EXISTS => 'already exists', + Doctrine_Core::ERR_CANNOT_CREATE => 'can not create', + Doctrine_Core::ERR_CANNOT_ALTER => 'can not alter', + Doctrine_Core::ERR_CANNOT_REPLACE => 'can not replace', + Doctrine_Core::ERR_CANNOT_DELETE => 'can not delete', + Doctrine_Core::ERR_CANNOT_DROP => 'can not drop', + Doctrine_Core::ERR_CONSTRAINT => 'constraint violation', + Doctrine_Core::ERR_CONSTRAINT_NOT_NULL => 'null value violates not-null constraint', + Doctrine_Core::ERR_DIVZERO => 'division by zero', + Doctrine_Core::ERR_INVALID => 'invalid', + Doctrine_Core::ERR_INVALID_DATE => 'invalid date or time', + Doctrine_Core::ERR_INVALID_NUMBER => 'invalid number', + Doctrine_Core::ERR_MISMATCH => 'mismatch', + Doctrine_Core::ERR_NODBSELECTED => 'no database selected', + Doctrine_Core::ERR_NOSUCHFIELD => 'no such field', + Doctrine_Core::ERR_NOSUCHTABLE => 'no such table', + Doctrine_Core::ERR_NOT_CAPABLE => 'Doctrine backend not capable', + Doctrine_Core::ERR_NOT_FOUND => 'not found', + Doctrine_Core::ERR_NOT_LOCKED => 'not locked', + Doctrine_Core::ERR_SYNTAX => 'syntax error', + Doctrine_Core::ERR_UNSUPPORTED => 'not supported', + Doctrine_Core::ERR_VALUE_COUNT_ON_ROW => 'value count on row', + Doctrine_Core::ERR_INVALID_DSN => 'invalid DSN', + Doctrine_Core::ERR_CONNECT_FAILED => 'connect failed', + Doctrine_Core::ERR_NEED_MORE_DATA => 'insufficient data supplied', + Doctrine_Core::ERR_EXTENSION_NOT_FOUND => 'extension not found', + Doctrine_Core::ERR_NOSUCHDB => 'no such database', + Doctrine_Core::ERR_ACCESS_VIOLATION => 'insufficient permissions', + Doctrine_Core::ERR_LOADMODULE => 'error while including on demand module', + Doctrine_Core::ERR_TRUNCATED => 'truncated', + Doctrine_Core::ERR_DEADLOCK => 'deadlock detected', + ); /** * @see Doctrine_Core::ERR_* constants * @since 1.0 - * @var integer $portableCode portable error code + * + * @var int portable error code */ protected $portableCode; /** * getPortableCode - * returns portable error code + * returns portable error code. * - * @return integer portable error code + * @return int portable error code */ public function getPortableCode() { @@ -90,9 +92,9 @@ public function getPortableCode() /** * getPortableMessage - * returns portable error message + * returns portable error message. * - * @return string portable error message + * @return string portable error message */ public function getPortableMessage() { @@ -100,14 +102,15 @@ public function getPortableMessage() } /** - * Return a textual error message for a Doctrine error code + * Return a textual error message for a Doctrine error code. * * @param int|array integer error code, * null to get the current error code-message map, * or an array with a new error code-message map + * @param mixed|null $value * - * @return string error message, or false if the error code was - * not recognized + * @return string error message, or false if the error code was + * not recognized */ public function errorMessage($value = null) { @@ -118,13 +121,16 @@ public function errorMessage($value = null) /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Connection/Mock.php b/lib/Doctrine/Connection/Mock.php index e101a2dc4..220059754 100644 --- a/lib/Doctrine/Connection/Mock.php +++ b/lib/Doctrine/Connection/Mock.php @@ -20,32 +20,30 @@ */ /** - * Doctrine_Connection_Mysql + * Doctrine_Connection_Mysql. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Mock extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Mock'; /** - * the constructor + * the constructor. * - * @param Doctrine_Manager $manager - * @param PDO|Doctrine_Adapter $adapter database handler + * @param PDO|Doctrine_Adapter $adapter database handler */ public function __construct(Doctrine_Manager $manager, $adapter) { - } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Module.php b/lib/Doctrine/Connection/Module.php index a6c27a917..d8b572c84 100644 --- a/lib/Doctrine/Connection/Module.php +++ b/lib/Doctrine/Connection/Module.php @@ -20,36 +20,37 @@ */ /** - * Doctrine_Connection_Module + * Doctrine_Connection_Module. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Module { /** - * @var Doctrine_Connection $conn Doctrine_Connection object, every connection - * module holds an instance of Doctrine_Connection + * @var Doctrine_Connection Doctrine_Connection object, every connection + * module holds an instance of Doctrine_Connection */ protected $conn; /** - * @var string $moduleName the name of this module + * @var string the name of this module */ protected $moduleName; /** - * @param Doctrine_Connection $conn Doctrine_Connection object, every connection - * module holds an instance of Doctrine_Connection + * @param Doctrine_Connection $conn Doctrine_Connection object, every connection + * module holds an instance of Doctrine_Connection */ public function __construct($conn = null) { - if ( ! ($conn instanceof Doctrine_Connection)) { + if (!($conn instanceof Doctrine_Connection)) { $conn = Doctrine_Manager::getInstance()->getCurrentConnection(); } $this->conn = $conn; @@ -61,7 +62,7 @@ public function __construct($conn = null) /** * getConnection - * returns the connection object this module uses + * returns the connection object this module uses. * * @return Doctrine_Connection */ @@ -72,12 +73,12 @@ public function getConnection() /** * getModuleName - * returns the name of this module + * returns the name of this module. * - * @return string the name of this module + * @return string the name of this module */ public function getModuleName() { return $this->moduleName; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Mssql.php b/lib/Doctrine/Connection/Mssql.php index ecce33f10..f83458983 100644 --- a/lib/Doctrine/Connection/Mssql.php +++ b/lib/Doctrine/Connection/Mssql.php @@ -20,50 +20,47 @@ */ /** - * Doctrine_Connection_Mssql + * Doctrine_Connection_Mssql. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7690 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Mssql extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Mssql'; /** - * the constructor - * - * @param Doctrine_Manager $manager - * @param PDO $pdo database handle + * the constructor. */ public function __construct(Doctrine_Manager $manager, $adapter) { // initialize all driver options $this->supported = array( - 'sequences' => 'emulated', - 'indexes' => true, - 'affected_rows' => true, - 'transactions' => true, - 'summary_functions' => true, - 'order_by_text' => true, - 'current_id' => 'emulated', - 'limit_queries' => 'emulated', - 'LOBs' => true, - 'replace' => 'emulated', - 'sub_selects' => true, - 'auto_increment' => true, - 'primary_key' => true, - 'result_introspection' => true, - 'prepared_statements' => 'emulated', - ); + 'sequences' => 'emulated', + 'indexes' => true, + 'affected_rows' => true, + 'transactions' => true, + 'summary_functions' => true, + 'order_by_text' => true, + 'current_id' => 'emulated', + 'limit_queries' => 'emulated', + 'LOBs' => true, + 'replace' => 'emulated', + 'sub_selects' => true, + 'auto_increment' => true, + 'primary_key' => true, + 'result_introspection' => true, + 'prepared_statements' => 'emulated', + ); $this->properties['varchar_max_length'] = 8000; @@ -72,22 +69,22 @@ public function __construct(Doctrine_Manager $manager, $adapter) /** * quoteIdentifier - * Quote a string so it can be safely used as a table / column name + * Quote a string so it can be safely used as a table / column name. * * Quoting style depends on which database driver is being used. * - * @param string $identifier identifier name to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param string $identifier identifier name to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteIdentifier($identifier, $checkOption = false) { - if ($checkOption && ! $this->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { + if ($checkOption && !$this->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { return $identifier; } - if (strpos($identifier, '.') !== false) { + if (false !== strpos($identifier, '.')) { $parts = explode('.', $identifier); $quotedParts = array(); foreach ($parts as $p) { @@ -97,43 +94,42 @@ public function quoteIdentifier($identifier, $checkOption = false) return implode('.', $quotedParts); } - return '[' . trim($identifier, '[]') . ']'; + return '['.trim($identifier, '[]').']'; } /** * Adds an adapter-specific LIMIT clause to the SELECT statement. - * Inspired by Doctrine2 DBAL + * Inspired by Doctrine2 DBAL. * * @param string $query - * @param mixed $limit - * @param mixed $offset - * @param boolean $isSubQuery - * @param Doctrine_Query $queryOrigin - * @link https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Platforms/MsSqlPlatform.php#L607 - * @link http://www.toosweettobesour.com/2010/09/16/doctrine-1-2-mssql-alternative-limitpaging/ + * @param bool $isSubQuery + * + * @see https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Platforms/MsSqlPlatform.php#L607 + * @see http://www.toosweettobesour.com/2010/09/16/doctrine-1-2-mssql-alternative-limitpaging/ + * * @return string */ public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false, $isSubQuery = false, Doctrine_Query $queryOrigin = null) { - if ($limit === false || !($limit > 0)) { + if (false === $limit || !($limit > 0)) { return $query; } $orderby = stristr($query, 'ORDER BY'); - if ($offset !== false && $orderby === false) { - throw new Doctrine_Connection_Exception("OFFSET cannot be used in MSSQL without ORDER BY due to emulation reasons."); + if (false !== $offset && false === $orderby) { + throw new Doctrine_Connection_Exception('OFFSET cannot be used in MSSQL without ORDER BY due to emulation reasons.'); } $limit = intval($limit); $offset = intval($offset); if ($offset < 0) { - throw new Doctrine_Connection_Exception("LIMIT argument offset=$offset is not valid"); + throw new Doctrine_Connection_Exception("LIMIT argument offset={$offset} is not valid"); } - if ($offset == 0) { - $query = preg_replace('/^SELECT( DISTINCT)?\s/i', 'SELECT\1 TOP ' . $limit . ' ', $query); + if (0 == $offset) { + $query = preg_replace('/^SELECT( DISTINCT)?\s/i', 'SELECT\1 TOP '.$limit.' ', $query); } else { $over = stristr($query, 'ORDER BY'); @@ -148,33 +144,31 @@ public function modifyLimitQuery($query, $limit = false, $offset = false, $isMan $query = substr($query, strlen('SELECT ')); $select = 'SELECT'; - if (0 === strpos($query, 'DISTINCT')) - { - $query = substr($query, strlen('DISTINCT ')); - $select .= ' DISTINCT'; + if (0 === strpos($query, 'DISTINCT')) { + $query = substr($query, strlen('DISTINCT ')); + $select .= ' DISTINCT'; } $start = $offset + 1; $end = $offset + $limit; - $query = "SELECT * FROM ($select ROW_NUMBER() OVER ($over) AS [DOCTRINE_ROWNUM], $query) AS [doctrine_tbl] WHERE [DOCTRINE_ROWNUM] BETWEEN $start AND $end"; + $query = "SELECT * FROM ({$select} ROW_NUMBER() OVER ({$over}) AS [DOCTRINE_ROWNUM], {$query}) AS [doctrine_tbl] WHERE [DOCTRINE_ROWNUM] BETWEEN {$start} AND {$end}"; } return $query; } - /** - * Parse an OrderBy-Statement into chunks + * Parse an OrderBy-Statement into chunks. * * @param string $orderby */ private function parseOrderBy($orderby) { $matches = array(); - $chunks = array(); - $tokens = array(); - $parsed = str_ireplace('ORDER BY', '', $orderby); + $chunks = array(); + $tokens = array(); + $parsed = str_ireplace('ORDER BY', '', $orderby); preg_match_all('/(\w+\(.+?\)\s+(ASC|DESC)),?/', $orderby, $matches); @@ -182,13 +176,13 @@ private function parseOrderBy($orderby) foreach ($matchesWithExpressions as $match) { $chunks[] = $match; - $parsed = str_replace($match, '##' . (count($chunks) - 1) . '##', $parsed); + $parsed = str_replace($match, '##'.(count($chunks) - 1).'##', $parsed); } $tokens = preg_split('/,/', $parsed); - for ($i = 0, $iMax = count($tokens); $i < $iMax; $i++) { - $tokens[$i] = trim(preg_replace_callback('/##(\d+)##/', function($m) { return $chunks[$m[1]]; }, $tokens[$i])); + for ($i = 0, $iMax = count($tokens); $i < $iMax; ++$i) { + $tokens[$i] = trim(preg_replace_callback('/##(\d+)##/', function ($m) { return $chunks[$m[1]]; }, $tokens[$i])); } return $tokens; @@ -199,17 +193,18 @@ private function parseOrderBy($orderby) * This method fix this issue by wrap the given term (column) into a CAST directive. * * @see DC-828 - * @param Doctrine_Table $table + * * @param string $field - * @param string $term The term which will changed if it's necessary, depending to the field type. + * @param string $term the term which will changed if it's necessary, depending to the field type + * * @return string */ public function modifyOrderByColumn(Doctrine_Table $table, $field, $term) { $def = $table->getDefinitionOf($field); - if ($def['type'] == 'string' && $def['length'] === NULL) { - $term = 'CAST(' . $term . ' AS varchar(8000))'; + if ('string' == $def['type'] && null === $def['length']) { + $term = 'CAST('.$term.' AS varchar(8000))'; } return $term; @@ -227,22 +222,23 @@ public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = } /** - * return version information about the server + * return version information about the server. + * + * @param bool $native determines if the raw version string should be returned * - * @param bool $native determines if the raw version string should be returned - * @return array version information + * @return array version information */ public function getServerVersion($native = false) { if ($this->serverInfo) { $serverInfo = $this->serverInfo; } else { - $query = 'SELECT @@VERSION'; + $query = 'SELECT @@VERSION'; $serverInfo = $this->fetchOne($query); } // cache server_info $this->serverInfo = $serverInfo; - if ( ! $native) { + if (!$native) { if (preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $serverInfo, $tmp)) { $serverInfo = array( 'major' => $tmp[1], @@ -261,40 +257,42 @@ public function getServerVersion($native = false) ); } } + return $serverInfo; } /** * Checks if there's a sequence that exists. * - * @param string $seq_name The sequence name to verify. - * @return boolean The value if the table exists or not + * @return bool The value if the table exists or not */ public function checkSequence($seqName) { - $query = 'SELECT * FROM ' . $seqName; + $query = 'SELECT * FROM '.$seqName; try { $this->exec($query); - } catch(Doctrine_Connection_Exception $e) { - if ($e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if (Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { return false; } throw $e; } + return true; } /** - * execute - * @param string $query sql query - * @param array $params query parameters + * execute. + * + * @param string $query sql query + * @param array $params query parameters * * @return PDOStatement|Doctrine_Adapter_Statement */ public function execute($query, array $params = array()) { - if(! empty($params)) { + if (!empty($params)) { $query = $this->replaceBoundParamsWithInlineValuesInQuery($query, $params); } @@ -302,15 +300,16 @@ public function execute($query, array $params = array()) } /** - * execute - * @param string $query sql query - * @param array $params query parameters + * execute. + * + * @param string $query sql query + * @param array $params query parameters * * @return PDOStatement|Doctrine_Adapter_Statement */ public function exec($query, array $params = array()) { - if(! empty($params)) { + if (!empty($params)) { $query = $this->replaceBoundParamsWithInlineValuesInQuery($query, $params); } @@ -323,30 +322,27 @@ public function exec($query, array $params = array()) * Workaround for http://bugs.php.net/36561 * * @param string $query - * @param array $params */ protected function replaceBoundParamsWithInlineValuesInQuery($query, array $params) { - foreach($params as $key => $value) { + foreach ($params as $key => $value) { $re = '/(?<=WHERE|VALUES|SET|JOIN)(.*?)(\?)/'; $query = preg_replace($re, "\\1##{$key}##", $query, 1); } $self = $this; - $query = preg_replace_callback('/##(\d+)##/', function($m) use ($params, $self) { + + return preg_replace_callback('/##(\d+)##/', function ($m) use ($params, $self) { return (null === $params[$m[1]]) ? 'NULL' : $self->quote($params[$m[1]]); }, $query); - - return $query; } /** * Inserts a table row with specified data. * - * @param Doctrine_Table $table The table to insert data into. - * @param array $values An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param Doctrine_Table $table the table to insert data into + * + * @return int the number of affected rows. Boolean false if empty value array was given, */ public function insert(Doctrine_Table $table, array $fields) { @@ -354,11 +350,11 @@ public function insert(Doctrine_Table $table, array $fields) $settingNullIdentifier = false; $fields = array_change_key_case($fields); - foreach($identifiers as $identifier) { + foreach ($identifiers as $identifier) { $lcIdentifier = strtolower($identifier); - if(array_key_exists($lcIdentifier, $fields)) { - if(is_null($fields[$lcIdentifier])) { + if (array_key_exists($lcIdentifier, $fields)) { + if (is_null($fields[$lcIdentifier])) { $settingNullIdentifier = true; unset($fields[$lcIdentifier]); } @@ -367,9 +363,9 @@ public function insert(Doctrine_Table $table, array $fields) // MSSQL won't allow the setting of identifier columns to null, so insert a default record and then update it if ($settingNullIdentifier) { - $count = $this->exec('INSERT INTO ' . $this->quoteIdentifier($table->getTableName()) . ' DEFAULT VALUES'); + $count = $this->exec('INSERT INTO '.$this->quoteIdentifier($table->getTableName()).' DEFAULT VALUES'); - if(! $count) { + if (!$count) { return $count; } diff --git a/lib/Doctrine/Connection/Mssql/Exception.php b/lib/Doctrine/Connection/Mssql/Exception.php index f961f2dcc..992713b30 100644 --- a/lib/Doctrine/Connection/Mssql/Exception.php +++ b/lib/Doctrine/Connection/Mssql/Exception.php @@ -20,56 +20,61 @@ */ /** - * Doctrine_Connection_Mssql_Exception + * Doctrine_Connection_Mssql_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Connection_Mssql_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorCodeMap an array that is used for determining portable - * error code from a native database error code + * @var array an array that is used for determining portable + * error code from a native database error code */ protected static $errorCodeMap = array( - 110 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - 155 => Doctrine_Core::ERR_NOSUCHFIELD, - 170 => Doctrine_Core::ERR_SYNTAX, - 207 => Doctrine_Core::ERR_NOSUCHFIELD, - 208 => Doctrine_Core::ERR_NOSUCHTABLE, - 245 => Doctrine_Core::ERR_INVALID_NUMBER, - 515 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - 547 => Doctrine_Core::ERR_CONSTRAINT, - 1913 => Doctrine_Core::ERR_ALREADY_EXISTS, - 2627 => Doctrine_Core::ERR_CONSTRAINT, - 2714 => Doctrine_Core::ERR_ALREADY_EXISTS, - 3701 => Doctrine_Core::ERR_NOSUCHTABLE, - 8134 => Doctrine_Core::ERR_DIVZERO, - ); + 110 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + 155 => Doctrine_Core::ERR_NOSUCHFIELD, + 170 => Doctrine_Core::ERR_SYNTAX, + 207 => Doctrine_Core::ERR_NOSUCHFIELD, + 208 => Doctrine_Core::ERR_NOSUCHTABLE, + 245 => Doctrine_Core::ERR_INVALID_NUMBER, + 515 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + 547 => Doctrine_Core::ERR_CONSTRAINT, + 1913 => Doctrine_Core::ERR_ALREADY_EXISTS, + 2627 => Doctrine_Core::ERR_CONSTRAINT, + 2714 => Doctrine_Core::ERR_ALREADY_EXISTS, + 3701 => Doctrine_Core::ERR_NOSUCHTABLE, + 8134 => Doctrine_Core::ERR_DIVZERO, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { $code = $errorInfo[1]; if (isset(self::$errorCodeMap[$code])) { $this->portableCode = self::$errorCodeMap[$code]; + return true; } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Mysql.php b/lib/Doctrine/Connection/Mysql.php index 7a7e59c16..89b22e5b0 100644 --- a/lib/Doctrine/Connection/Mysql.php +++ b/lib/Doctrine/Connection/Mysql.php @@ -20,68 +20,67 @@ */ /** - * Doctrine_Connection_Mysql + * Doctrine_Connection_Mysql. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Mysql extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Mysql'; /** - * the constructor + * the constructor. * - * @param Doctrine_Manager $manager - * @param PDO|Doctrine_Adapter $adapter database handler + * @param PDO|Doctrine_Adapter $adapter database handler */ public function __construct(Doctrine_Manager $manager, $adapter) { $this->setAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_TYPE, 'INNODB'); $this->supported = array( - 'sequences' => 'emulated', - 'indexes' => true, - 'affected_rows' => true, - 'transactions' => true, - 'savepoints' => false, - 'summary_functions' => true, - 'order_by_text' => true, - 'current_id' => 'emulated', - 'limit_queries' => true, - 'LOBs' => true, - 'replace' => true, - 'sub_selects' => true, - 'auto_increment' => true, - 'primary_key' => true, - 'result_introspection' => true, - 'prepared_statements' => 'emulated', - 'identifier_quoting' => true, - 'pattern_escaping' => true - ); + 'sequences' => 'emulated', + 'indexes' => true, + 'affected_rows' => true, + 'transactions' => true, + 'savepoints' => false, + 'summary_functions' => true, + 'order_by_text' => true, + 'current_id' => 'emulated', + 'limit_queries' => true, + 'LOBs' => true, + 'replace' => true, + 'sub_selects' => true, + 'auto_increment' => true, + 'primary_key' => true, + 'result_introspection' => true, + 'prepared_statements' => 'emulated', + 'identifier_quoting' => true, + 'pattern_escaping' => true, + ); $this->properties['string_quoting'] = array('start' => "'", - 'end' => "'", - 'escape' => '\\', - 'escape_pattern' => '\\'); + 'end' => "'", + 'escape' => '\\', + 'escape_pattern' => '\\'); $this->properties['identifier_quoting'] = array('start' => '`', - 'end' => '`', - 'escape' => '`'); + 'end' => '`', + 'escape' => '`'); $this->properties['sql_comments'] = array( - array('start' => '-- ', 'end' => "\n", 'escape' => false), - array('start' => '#', 'end' => "\n", 'escape' => false), - array('start' => '/*', 'end' => '*/', 'escape' => false), - ); + array('start' => '-- ', 'end' => "\n", 'escape' => false), + array('start' => '#', 'end' => "\n", 'escape' => false), + array('start' => '/*', 'end' => '*/', 'escape' => false), + ); $this->properties['varchar_max_length'] = 255; @@ -96,22 +95,22 @@ public function __construct(Doctrine_Manager $manager, $adapter) /** * Overrides connect Method, to add specific attributes * PDO emulate prepares is required to avoid bugs on mysql < 5.1 - * when trying to prepare DROP DATABASE or CREATE DATABASE statements + * when trying to prepare DROP DATABASE or CREATE DATABASE statements. * * @see Doctrine_Connection :: connect(); - * @return boolean connected + * + * @return bool connected */ - public function connect() - { - $connected = parent::connect(); - $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); - - return $connected; - } - - + public function connect() + { + $connected = parent::connect(); + $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); + + return $connected; + } + /** - * returns the name of the connected database + * returns the name of the connected database. * * @return string */ @@ -121,13 +120,13 @@ public function getDatabaseName() } /** - * Set the charset on the current connection + * Set the charset on the current connection. * * @param string charset */ public function setCharset($charset) { - $query = 'SET NAMES ' . $this->quote($charset); + $query = 'SET NAMES '.$this->quote($charset); $this->exec($query); parent::setCharset($charset); } @@ -143,15 +142,13 @@ public function setCharset($charset) * emulated through this method for other DBMS using standard types of * queries inside a transaction to assure the atomicity of the operation. * - * @access public - * - * @param string $table name of the table on which the REPLACE query will - * be executed. - * @param array $fields associative array that describes the fields and the - * values that will be inserted or updated in the specified table. The - * indexes of the array are the names of all the fields of the table. The - * values of the array are also associative arrays that describe the - * values and other properties of the table fields. + * @param string $table name of the table on which the REPLACE query will + * be executed + * @param array $fields associative array that describes the fields and the + * values that will be inserted or updated in the specified table. The + * indexes of the array are the names of all the fields of the table. The + * values of the array are also associative arrays that describe the + * values and other properties of the table fields. * * Here follows a list of field properties that need to be specified: * @@ -194,7 +191,7 @@ public function setCharset($charset) * * Default: 0 * - * @return integer the number of affected rows + * @return int the number of affected rows */ public function replace(Doctrine_Table $table, array $fields, array $keys) { @@ -211,8 +208,8 @@ public function replace(Doctrine_Table $table, array $fields, array $keys) $params[] = $value; } - $query = 'REPLACE INTO ' . $this->quoteIdentifier($table->getTableName()) . ' (' . implode(',', $columns) . ') VALUES (' . implode(',', $values) . ')'; + $query = 'REPLACE INTO '.$this->quoteIdentifier($table->getTableName()).' ('.implode(',', $columns).') VALUES ('.implode(',', $values).')'; return $this->exec($query, $params); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Mysql/Exception.php b/lib/Doctrine/Connection/Mysql/Exception.php index 65412b6b7..a4b2b7b3f 100644 --- a/lib/Doctrine/Connection/Mysql/Exception.php +++ b/lib/Doctrine/Connection/Mysql/Exception.php @@ -20,67 +20,72 @@ */ /** - * Doctrine_Connection_Mysql_Exception + * Doctrine_Connection_Mysql_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Connection_Mysql_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorCodeMap an array that is used for determining portable - * error code from a native database error code + * @var array an array that is used for determining portable + * error code from a native database error code */ protected static $errorCodeMap = array( - 1004 => Doctrine_Core::ERR_CANNOT_CREATE, - 1005 => Doctrine_Core::ERR_CANNOT_CREATE, - 1006 => Doctrine_Core::ERR_CANNOT_CREATE, - 1007 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1008 => Doctrine_Core::ERR_CANNOT_DROP, - 1022 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1044 => Doctrine_Core::ERR_ACCESS_VIOLATION, - 1046 => Doctrine_Core::ERR_NODBSELECTED, - 1048 => Doctrine_Core::ERR_CONSTRAINT, - 1049 => Doctrine_Core::ERR_NOSUCHDB, - 1050 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1051 => Doctrine_Core::ERR_NOSUCHTABLE, - 1054 => Doctrine_Core::ERR_NOSUCHFIELD, - 1061 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1062 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1064 => Doctrine_Core::ERR_SYNTAX, - 1091 => Doctrine_Core::ERR_NOT_FOUND, - 1100 => Doctrine_Core::ERR_NOT_LOCKED, - 1136 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - 1142 => Doctrine_Core::ERR_ACCESS_VIOLATION, - 1146 => Doctrine_Core::ERR_NOSUCHTABLE, - 1216 => Doctrine_Core::ERR_CONSTRAINT, - 1217 => Doctrine_Core::ERR_CONSTRAINT, - 1451 => Doctrine_Core::ERR_CONSTRAINT, - ); + 1004 => Doctrine_Core::ERR_CANNOT_CREATE, + 1005 => Doctrine_Core::ERR_CANNOT_CREATE, + 1006 => Doctrine_Core::ERR_CANNOT_CREATE, + 1007 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1008 => Doctrine_Core::ERR_CANNOT_DROP, + 1022 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1044 => Doctrine_Core::ERR_ACCESS_VIOLATION, + 1046 => Doctrine_Core::ERR_NODBSELECTED, + 1048 => Doctrine_Core::ERR_CONSTRAINT, + 1049 => Doctrine_Core::ERR_NOSUCHDB, + 1050 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1051 => Doctrine_Core::ERR_NOSUCHTABLE, + 1054 => Doctrine_Core::ERR_NOSUCHFIELD, + 1061 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1062 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1064 => Doctrine_Core::ERR_SYNTAX, + 1091 => Doctrine_Core::ERR_NOT_FOUND, + 1100 => Doctrine_Core::ERR_NOT_LOCKED, + 1136 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + 1142 => Doctrine_Core::ERR_ACCESS_VIOLATION, + 1146 => Doctrine_Core::ERR_NOSUCHTABLE, + 1216 => Doctrine_Core::ERR_CONSTRAINT, + 1217 => Doctrine_Core::ERR_CONSTRAINT, + 1451 => Doctrine_Core::ERR_CONSTRAINT, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { $code = $errorInfo[1]; if (isset(self::$errorCodeMap[$code])) { $this->portableCode = self::$errorCodeMap[$code]; + return true; } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Oracle.php b/lib/Doctrine/Connection/Oracle.php index 6649abfb6..478ba7d54 100644 --- a/lib/Doctrine/Connection/Oracle.php +++ b/lib/Doctrine/Connection/Oracle.php @@ -20,121 +20,123 @@ */ /** - * Doctrine_Connection_Oracle + * Doctrine_Connection_Oracle. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7664 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Oracle extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Oracle'; public function __construct(Doctrine_Manager $manager, $adapter) { $this->supported = array( - 'sequences' => true, - 'indexes' => true, - 'summary_functions' => true, - 'order_by_text' => true, - 'current_id' => true, - 'affected_rows' => true, - 'transactions' => true, - 'savepoints' => true, - 'limit_queries' => true, - 'LOBs' => true, - 'replace' => 'emulated', - 'sub_selects' => true, - 'auto_increment' => false, // implementation is broken - 'primary_key' => true, - 'result_introspection' => true, - 'prepared_statements' => true, - 'identifier_quoting' => true, - 'pattern_escaping' => true, - ); - - $this->properties['sql_file_delimiter'] = "\n/\n"; - $this->properties['number_max_precision'] = 38; + 'sequences' => true, + 'indexes' => true, + 'summary_functions' => true, + 'order_by_text' => true, + 'current_id' => true, + 'affected_rows' => true, + 'transactions' => true, + 'savepoints' => true, + 'limit_queries' => true, + 'LOBs' => true, + 'replace' => 'emulated', + 'sub_selects' => true, + 'auto_increment' => false, // implementation is broken + 'primary_key' => true, + 'result_introspection' => true, + 'prepared_statements' => true, + 'identifier_quoting' => true, + 'pattern_escaping' => true, + ); + + $this->properties['sql_file_delimiter'] = "\n/\n"; + $this->properties['number_max_precision'] = 38; $this->properties['max_identifier_length'] = 30; parent::__construct($manager, $adapter); - + // moving properties to params to make them changeable by user - // VARCHAR2 allowed length is 4000 BYTE. For UTF8 strings is better to use 1000 CHAR + // VARCHAR2 allowed length is 4000 BYTE. For UTF8 strings is better to use 1000 CHAR $this->setParam('varchar2_max_length', 4000); // Oracle's default unit for char data types is BYTE. For UTF8 string it is better to use CHAR $this->setParam('char_unit', null); } /** - * Sets up the date/time format - * + * Sets up the date/time format. */ public function setDateFormat($format = 'YYYY-MM-DD HH24:MI:SS') { - $this->exec('ALTER SESSION SET NLS_DATE_FORMAT = "' . $format . '"'); + $this->exec('ALTER SESSION SET NLS_DATE_FORMAT = "'.$format.'"'); } /** - * Adds an driver-specific LIMIT clause to the query + * Adds an driver-specific LIMIT clause to the query. + * + * @param string $query query to modify + * @param int $limit limit the number of rows + * @param int $offset start reading from given offset * - * @param string $query query to modify - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string the modified query + * @return string the modified query */ public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { return $this->_createLimitSubquery($query, $limit, $offset); } - + private function _createLimitSubquery($query, $limit, $offset, $column = null) { $limit = (int) $limit; $offset = (int) $offset; if (preg_match('/^\s*SELECT/i', $query)) { - if ( ! preg_match('/\sFROM\s/i', $query)) { - $query .= " FROM dual"; + if (!preg_match('/\sFROM\s/i', $query)) { + $query .= ' FROM dual'; } if ($limit > 0) { $max = $offset + $limit; - $column = $column === null ? '*' : $this->quoteIdentifier($column); + $column = null === $column ? '*' : $this->quoteIdentifier($column); if ($offset > 0) { $min = $offset + 1; $query = 'SELECT '.$this->quoteIdentifier('b').'.'.$column.' FROM ( '. 'SELECT '.$this->quoteIdentifier('a').'.*, ROWNUM AS doctrine_rownum FROM ( ' - . $query . ' ) ' . $this->quoteIdentifier('a') . ' '. - ' ) ' . $this->quoteIdentifier('b') . ' '. - 'WHERE doctrine_rownum BETWEEN ' . $min . ' AND ' . $max; + .$query.' ) '.$this->quoteIdentifier('a').' '. + ' ) '.$this->quoteIdentifier('b').' '. + 'WHERE doctrine_rownum BETWEEN '.$min.' AND '.$max; } else { - $query = 'SELECT a.'.$column.' FROM ( ' . $query .' ) a WHERE ROWNUM <= ' . $max; + $query = 'SELECT a.'.$column.' FROM ( '.$query.' ) a WHERE ROWNUM <= '.$max; } } } + return $query; } - + /** * Creates the SQL for Oracle that can be used in the subquery for the limit-subquery * algorithm. */ public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = false, - $offset = false, $isManip = false) + $offset = false, $isManip = false) { // NOTE: no composite key support $columnNames = $rootTable->getIdentifierColumnNames(); if (count($columnNames) > 1) { - throw new Doctrine_Connection_Exception("Composite keys in LIMIT queries are " - . "currently not supported."); + throw new Doctrine_Connection_Exception('Composite keys in LIMIT queries are currently not supported.'); } $column = $columnNames[0]; + return $this->_createLimitSubquery($query, $limit, $offset, $column); } @@ -146,17 +148,19 @@ public function getTmpConnection($info) /** * Override quote behaviour for boolean to fix issues with quoting of * boolean values. + * + * @param mixed|null $type */ public function quote($input, $type = null) { - if ($type === 'boolean') { - if ($input === null) { + if ('boolean' === $type) { + if (null === $input) { return null; - } else { - return $input ? 1 : 0; } - } else { - return parent::quote($input, $type); + + return $input ? 1 : 0; } + + return parent::quote($input, $type); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Oracle/Exception.php b/lib/Doctrine/Connection/Oracle/Exception.php index 9a8721ca8..77c1577f2 100644 --- a/lib/Doctrine/Connection/Oracle/Exception.php +++ b/lib/Doctrine/Connection/Oracle/Exception.php @@ -20,61 +20,66 @@ */ /** - * Doctrine_Connection_Oracle_Exception + * Doctrine_Connection_Oracle_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Connection_Oracle_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorCodeMap an array that is used for determining portable - * error code from a native database error code + * @var array an array that is used for determining portable + * error code from a native database error code */ protected static $errorCodeMap = array( - 1 => Doctrine_Core::ERR_CONSTRAINT, - 900 => Doctrine_Core::ERR_SYNTAX, - 904 => Doctrine_Core::ERR_NOSUCHFIELD, - 913 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - 921 => Doctrine_Core::ERR_SYNTAX, - 923 => Doctrine_Core::ERR_SYNTAX, - 942 => Doctrine_Core::ERR_NOSUCHTABLE, - 955 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1400 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - 1401 => Doctrine_Core::ERR_INVALID, - 1407 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - 1418 => Doctrine_Core::ERR_NOT_FOUND, - 1476 => Doctrine_Core::ERR_DIVZERO, - 1722 => Doctrine_Core::ERR_INVALID_NUMBER, - 2289 => Doctrine_Core::ERR_NOSUCHTABLE, - 2291 => Doctrine_Core::ERR_CONSTRAINT, - 2292 => Doctrine_Core::ERR_CONSTRAINT, - 2449 => Doctrine_Core::ERR_CONSTRAINT, - ); + 1 => Doctrine_Core::ERR_CONSTRAINT, + 900 => Doctrine_Core::ERR_SYNTAX, + 904 => Doctrine_Core::ERR_NOSUCHFIELD, + 913 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + 921 => Doctrine_Core::ERR_SYNTAX, + 923 => Doctrine_Core::ERR_SYNTAX, + 942 => Doctrine_Core::ERR_NOSUCHTABLE, + 955 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1400 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + 1401 => Doctrine_Core::ERR_INVALID, + 1407 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + 1418 => Doctrine_Core::ERR_NOT_FOUND, + 1476 => Doctrine_Core::ERR_DIVZERO, + 1722 => Doctrine_Core::ERR_INVALID_NUMBER, + 2289 => Doctrine_Core::ERR_NOSUCHTABLE, + 2291 => Doctrine_Core::ERR_CONSTRAINT, + 2292 => Doctrine_Core::ERR_CONSTRAINT, + 2449 => Doctrine_Core::ERR_CONSTRAINT, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { $code = $errorInfo[1]; if (isset(self::$errorCodeMap[$code])) { $this->portableCode = self::$errorCodeMap[$code]; + return true; } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Pgsql.php b/lib/Doctrine/Connection/Pgsql.php index 2fbc19d86..0fa53589c 100644 --- a/lib/Doctrine/Connection/Pgsql.php +++ b/lib/Doctrine/Connection/Pgsql.php @@ -20,71 +20,66 @@ */ /** - * Doctrine_Connection_Pgsql + * Doctrine_Connection_Pgsql. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Pgsql extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Pgsql'; /** - * the constructor - * - * @param Doctrine_Manager $manager - * @param PDO $pdo database handle + * the constructor. */ public function __construct(Doctrine_Manager $manager, $adapter) { // initialize all driver options $this->supported = array( - 'sequences' => true, - 'indexes' => true, - 'affected_rows' => true, - 'summary_functions' => true, - 'order_by_text' => true, - 'transactions' => true, - 'savepoints' => true, - 'current_id' => true, - 'limit_queries' => true, - 'LOBs' => true, - 'replace' => 'emulated', - 'sub_selects' => true, - 'auto_increment' => 'emulated', - 'primary_key' => true, - 'result_introspection' => true, - 'prepared_statements' => true, - 'identifier_quoting' => true, - 'pattern_escaping' => true, - ); + 'sequences' => true, + 'indexes' => true, + 'affected_rows' => true, + 'summary_functions' => true, + 'order_by_text' => true, + 'transactions' => true, + 'savepoints' => true, + 'current_id' => true, + 'limit_queries' => true, + 'LOBs' => true, + 'replace' => 'emulated', + 'sub_selects' => true, + 'auto_increment' => 'emulated', + 'primary_key' => true, + 'result_introspection' => true, + 'prepared_statements' => true, + 'identifier_quoting' => true, + 'pattern_escaping' => true, + ); $this->properties['string_quoting'] = array('start' => "'", - 'end' => "'", - 'escape' => "'", - 'escape_pattern' => '\\'); + 'end' => "'", + 'escape' => "'", + 'escape_pattern' => '\\'); $this->properties['identifier_quoting'] = array('start' => '"', - 'end' => '"', - 'escape' => '"'); + 'end' => '"', + 'escape' => '"'); parent::__construct($manager, $adapter); } /** - * Set the charset on the current connection + * Set the charset on the current connection. * * @param string charset - * - * @return void */ public function setCharset($charset) { @@ -96,12 +91,11 @@ public function setCharset($charset) /** * convertBoolean * some drivers need the boolean values to be converted into integers - * when using DQL API + * when using DQL API. * * This method takes care of that conversion * * @param array $item - * @return void */ public function convertBooleans($item) { @@ -112,55 +106,58 @@ public function convertBooleans($item) } } } else { - if (is_bool($item) || is_numeric($item)) { - $item = ($item) ? 'true' : 'false'; - } + if (is_bool($item) || is_numeric($item)) { + $item = ($item) ? 'true' : 'false'; + } } + return $item; } /** - * Changes a query string for various DBMS specific reasons + * Changes a query string for various DBMS specific reasons. + * + * @param string $query query to modify + * @param int $limit limit the number of rows + * @param int $offset start reading from given offset + * @param bool $isManip if the query is a DML query * - * @param string $query query to modify - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @param boolean $isManip if the query is a DML query - * @return string modified query + * @return string modified query */ public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { if ($limit > 0) { $query = rtrim($query); - if (substr($query, -1) == ';') { + if (';' == substr($query, -1)) { $query = substr($query, 0, -1); } if ($isManip) { $manip = preg_replace('/^(DELETE FROM|UPDATE).*$/', '\\1', $query); - $from = $match[2]; + $from = $match[2]; $where = $match[3]; - $query = $manip . ' ' . $from . ' WHERE ctid=(SELECT ctid FROM ' - . $from . ' ' . $where . ' LIMIT ' . (int)$limit . ')'; - + $query = $manip.' '.$from.' WHERE ctid=(SELECT ctid FROM ' + .$from.' '.$where.' LIMIT '.(int) $limit.')'; } else { - if ( ! empty($limit)) { - $query .= ' LIMIT ' . (int)$limit; + if (!empty($limit)) { + $query .= ' LIMIT '.(int) $limit; } - if ( ! empty($offset)) { - $query .= ' OFFSET ' . (int)$offset; + if (!empty($offset)) { + $query .= ' OFFSET '.(int) $offset; } } } + return $query; } /** - * return version information about the server + * return version information about the server. * - * @param string $native determines if the raw version string should be returned - * @return array|string an array or string with version information + * @param string $native determines if the raw version string should be returned + * + * @return array|string an array or string with version information */ public function getServerVersion($native = false) { @@ -168,7 +165,7 @@ public function getServerVersion($native = false) $serverInfo = $this->fetchOne($query); - if ( ! $native) { + if (!$native) { $tmp = explode('.', $serverInfo, 3); if (empty($tmp[2]) && isset($tmp[1]) @@ -191,16 +188,16 @@ public function getServerVersion($native = false) ); } } + return $serverInfo; } /** * Inserts a table row with specified data. * - * @param Doctrine_Table $table The table to insert data into. - * @param array $values An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param Doctrine_Table $table the table to insert data into + * + * @return int the number of affected rows. Boolean false if empty value array was given, */ public function insert(Doctrine_Table $table, array $fields) { @@ -210,16 +207,16 @@ public function insert(Doctrine_Table $table, array $fields) $cols = array(); // the query VALUES will contain either expresions (eg 'NOW()') or ? $a = array(); - + foreach ($fields as $fieldName => $value) { - if ($table->isIdentifier($fieldName) - && $table->isIdentifierAutoincrement() - && $value == null) { - // Autoincrement fields should not be added to the insert statement - // if their value is null - unset($fields[$fieldName]); - continue; - } + if ($table->isIdentifier($fieldName) + && $table->isIdentifierAutoincrement() + && null == $value) { + // Autoincrement fields should not be added to the insert statement + // if their value is null + unset($fields[$fieldName]); + continue; + } $cols[] = $this->quoteIdentifier($table->getColumnName($fieldName)); if ($value instanceof Doctrine_Expression) { $a[] = $value->getSql(); @@ -228,19 +225,19 @@ public function insert(Doctrine_Table $table, array $fields) $a[] = '?'; } } - - if (count($fields) == 0) { - // Real fix #1786 and #2327 (default values when table is just 'id' as PK) - return $this->exec('INSERT INTO ' . $this->quoteIdentifier($tableName) - . ' ' - . ' VALUES (DEFAULT)'); + + if (0 == count($fields)) { + // Real fix #1786 and #2327 (default values when table is just 'id' as PK) + return $this->exec('INSERT INTO '.$this->quoteIdentifier($tableName) + .' ' + .' VALUES (DEFAULT)'); } // build the statement - $query = 'INSERT INTO ' . $this->quoteIdentifier($tableName) - . ' (' . implode(', ', $cols) . ')' - . ' VALUES (' . implode(', ', $a) . ')'; + $query = 'INSERT INTO '.$this->quoteIdentifier($tableName) + .' ('.implode(', ', $cols).')' + .' VALUES ('.implode(', ', $a).')'; return $this->exec($query, array_values($fields)); - } + } } diff --git a/lib/Doctrine/Connection/Pgsql/Exception.php b/lib/Doctrine/Connection/Pgsql/Exception.php index 46e366b84..011c2804e 100644 --- a/lib/Doctrine/Connection/Pgsql/Exception.php +++ b/lib/Doctrine/Connection/Pgsql/Exception.php @@ -20,89 +20,75 @@ */ /** - * Doctrine_Connection_Pgsql_Exception + * Doctrine_Connection_Pgsql_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org + * * @author Konsta Vesterinen * @author Paul Cooper (PEAR MDB2 Pgsql driver) * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Connection_Pgsql_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorRegexps an array that is used for determining portable - * error code from a native database error message + * @var array an array that is used for determining portable + * error code from a native database error message */ protected static $errorRegexps = array( - '/parser: parse error at or near/i' - => Doctrine_Core::ERR_SYNTAX, - '/syntax error at/' - => Doctrine_Core::ERR_SYNTAX, - '/column reference .* is ambiguous/i' - => Doctrine_Core::ERR_SYNTAX, - '/column .* (of relation .*)?does not exist/i' - => Doctrine_Core::ERR_NOSUCHFIELD, - '/attribute .* not found|relation .* does not have attribute/i' - => Doctrine_Core::ERR_NOSUCHFIELD, - '/column .* specified in USING clause does not exist in (left|right) table/i' - => Doctrine_Core::ERR_NOSUCHFIELD, - '/(relation|sequence|table).*does not exist|class .* not found/i' - => Doctrine_Core::ERR_NOSUCHTABLE, - '/index .* does not exist/' - => Doctrine_Core::ERR_NOT_FOUND, - '/relation .* already exists/i' - => Doctrine_Core::ERR_ALREADY_EXISTS, - '/(divide|division) by zero$/i' - => Doctrine_Core::ERR_DIVZERO, - '/pg_atoi: error in .*: can\'t parse /i' - => Doctrine_Core::ERR_INVALID_NUMBER, - '/invalid input syntax for( type)? (integer|numeric)/i' - => Doctrine_Core::ERR_INVALID_NUMBER, - '/value .* is out of range for type \w*int/i' - => Doctrine_Core::ERR_INVALID_NUMBER, - '/integer out of range/i' - => Doctrine_Core::ERR_INVALID_NUMBER, - '/value too long for type character/i' - => Doctrine_Core::ERR_INVALID, - '/permission denied/' - => Doctrine_Core::ERR_ACCESS_VIOLATION, - '/violates [\w ]+ constraint/' - => Doctrine_Core::ERR_CONSTRAINT, - '/referential integrity violation/' - => Doctrine_Core::ERR_CONSTRAINT, - '/violates not-null constraint/' - => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - '/more expressions than target columns/i' - => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - ); + '/parser: parse error at or near/i' => Doctrine_Core::ERR_SYNTAX, + '/syntax error at/' => Doctrine_Core::ERR_SYNTAX, + '/column reference .* is ambiguous/i' => Doctrine_Core::ERR_SYNTAX, + '/column .* (of relation .*)?does not exist/i' => Doctrine_Core::ERR_NOSUCHFIELD, + '/attribute .* not found|relation .* does not have attribute/i' => Doctrine_Core::ERR_NOSUCHFIELD, + '/column .* specified in USING clause does not exist in (left|right) table/i' => Doctrine_Core::ERR_NOSUCHFIELD, + '/(relation|sequence|table).*does not exist|class .* not found/i' => Doctrine_Core::ERR_NOSUCHTABLE, + '/index .* does not exist/' => Doctrine_Core::ERR_NOT_FOUND, + '/relation .* already exists/i' => Doctrine_Core::ERR_ALREADY_EXISTS, + '/(divide|division) by zero$/i' => Doctrine_Core::ERR_DIVZERO, + '/pg_atoi: error in .*: can\'t parse /i' => Doctrine_Core::ERR_INVALID_NUMBER, + '/invalid input syntax for( type)? (integer|numeric)/i' => Doctrine_Core::ERR_INVALID_NUMBER, + '/value .* is out of range for type \w*int/i' => Doctrine_Core::ERR_INVALID_NUMBER, + '/integer out of range/i' => Doctrine_Core::ERR_INVALID_NUMBER, + '/value too long for type character/i' => Doctrine_Core::ERR_INVALID, + '/permission denied/' => Doctrine_Core::ERR_ACCESS_VIOLATION, + '/violates [\w ]+ constraint/' => Doctrine_Core::ERR_CONSTRAINT, + '/referential integrity violation/' => Doctrine_Core::ERR_CONSTRAINT, + '/violates not-null constraint/' => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + '/more expressions than target columns/i' => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. * * the portable error code is added at the end of array * - * @param array $errorInfo error info array + * @param array $errorInfo error info array + * * @since 1.0 * @see Doctrine_Core::ERR_* constants * @see Doctrine_Connection::$portableCode - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { foreach (self::$errorRegexps as $regexp => $code) { if (preg_match($regexp, $errorInfo[2])) { $this->portableCode = $code; + return true; } } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Profiler.php b/lib/Doctrine/Connection/Profiler.php index 4f1d7cd5c..db4aec2aa 100644 --- a/lib/Doctrine/Connection/Profiler.php +++ b/lib/Doctrine/Connection/Profiler.php @@ -20,80 +20,81 @@ */ /** - * Doctrine_Connection_Profiler + * Doctrine_Connection_Profiler. * - * @package Doctrine - * @subpackage Connection * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Connection_Profiler implements Doctrine_Overloadable, IteratorAggregate, Countable { /** - * @param array $listeners an array containing all availible listeners + * @param array $listeners an array containing all availible listeners */ - private $listeners = array('query', - 'prepare', - 'commit', - 'rollback', - 'connect', - 'begintransaction', - 'exec', - 'execute'); + private $listeners = array('query', + 'prepare', + 'commit', + 'rollback', + 'connect', + 'begintransaction', + 'exec', + 'execute'); /** - * @param array $events an array containing all listened events + * @param array $events an array containing all listened events */ - private $events = array(); + private $events = array(); /** - * @param array $eventSequences an array containing sequences of all listened events as keys + * @param array $eventSequences an array containing sequences of all listened events as keys */ private $eventSequences = array(); /** - * constructor + * constructor. */ - public function __construct() { - + public function __construct() + { } /** - * setFilterQueryType + * setFilterQueryType. * - * @param integer $filter - * @return boolean + * @return bool */ - public function setFilterQueryType() { - + public function setFilterQueryType() + { } + /** * method overloader * this method is used for invoking different listeners, for the full - * list of availible listeners, see Doctrine_EventListener + * list of availible listeners, see Doctrine_EventListener. + * + * @param string $m the name of the method + * @param array $a method arguments * - * @param string $m the name of the method - * @param array $a method arguments * @see Doctrine_EventListener - * @return boolean + * + * @return bool */ public function __call($m, $a) { // first argument should be an instance of Doctrine_Event - if ( ! ($a[0] instanceof Doctrine_Event)) { + if (!($a[0] instanceof Doctrine_Event)) { throw new Doctrine_Connection_Profiler_Exception("Couldn't listen event. Event should be an instance of Doctrine_Event."); } - - if (substr($m, 0, 3) === 'pre') { + if ('pre' === substr($m, 0, 3)) { // pre-event listener found $a[0]->start(); $eventSequence = $a[0]->getSequence(); - if ( ! isset($this->eventSequences[$eventSequence])) { + if (!isset($this->eventSequences[$eventSequence])) { $this->events[] = $a[0]; $this->eventSequences[$eventSequence] = true; } @@ -104,9 +105,8 @@ public function __call($m, $a) } /** - * get + * get. * - * @param mixed $key * @return Doctrine_Event|null */ public function get($key) @@ -114,12 +114,13 @@ public function get($key) if (isset($this->events[$key])) { return $this->events[$key]; } + return null; } /** * getAll - * returns all profiled events as an array + * returns all profiled events as an array. * * @return Doctrine_Event[] All events in an array */ @@ -130,39 +131,39 @@ public function getAll() /** * getIterator - * returns an iterator that iterates through the logged events + * returns an iterator that iterates through the logged events. * * @return ArrayIterator */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->events); } /** - * count + * count. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->events); } /** - * pop the last event from the event stack + * pop the last event from the event stack. * * @return Doctrine_Event|null */ public function pop() { $event = array_pop($this->events); - if ($event !== null) - { + if (null !== $event) { unset($this->eventSequences[$event->getSequence()]); } + return $event; } @@ -179,6 +180,7 @@ public function lastEvent() } end($this->events); + return current($this->events); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Profiler/Exception.php b/lib/Doctrine/Connection/Profiler/Exception.php index 75809c793..d446f08b1 100644 --- a/lib/Doctrine/Connection/Profiler/Exception.php +++ b/lib/Doctrine/Connection/Profiler/Exception.php @@ -20,16 +20,17 @@ */ /** - * Doctrine_Connection_Profiler_Exception + * Doctrine_Connection_Profiler_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1345 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Profiler_Exception extends Doctrine_Exception { -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Sqlite.php b/lib/Doctrine/Connection/Sqlite.php index 6a29b654e..1eb38a57b 100644 --- a/lib/Doctrine/Connection/Sqlite.php +++ b/lib/Doctrine/Connection/Sqlite.php @@ -20,61 +20,57 @@ */ /** - * Doctrine_Connection_Sqlite + * Doctrine_Connection_Sqlite. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Sqlite extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Sqlite'; /** - * the constructor - * - * @param Doctrine_Manager $manager - * @param PDO $pdo database handle + * the constructor. */ public function __construct(Doctrine_Manager $manager, $adapter) { - $this->supported = array('sequences' => 'emulated', - 'indexes' => true, - 'affected_rows' => true, - 'summary_functions' => true, - 'order_by_text' => true, - 'current_id' => 'emulated', - 'limit_queries' => true, - 'LOBs' => true, - 'replace' => true, - 'transactions' => true, - 'savepoints' => false, - 'sub_selects' => true, - 'auto_increment' => true, - 'primary_key' => true, - 'result_introspection' => false, // not implemented - 'prepared_statements' => 'emulated', - 'identifier_quoting' => true, - 'pattern_escaping' => false, - ); + $this->supported = array('sequences' => 'emulated', + 'indexes' => true, + 'affected_rows' => true, + 'summary_functions' => true, + 'order_by_text' => true, + 'current_id' => 'emulated', + 'limit_queries' => true, + 'LOBs' => true, + 'replace' => true, + 'transactions' => true, + 'savepoints' => false, + 'sub_selects' => true, + 'auto_increment' => true, + 'primary_key' => true, + 'result_introspection' => false, // not implemented + 'prepared_statements' => 'emulated', + 'identifier_quoting' => true, + 'pattern_escaping' => false, + ); parent::__construct($manager, $adapter); if ($this->isConnected) { - // PHP8.1 require default to true to keep BC // https://www.php.net/manual/en/migration81.incompatible.php#migration81.incompatible.pdo.sqlite // Can be overwritten by user later $this->dbh->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true); - $this->dbh->sqliteCreateFunction('mod', array('Doctrine_Expression_Sqlite', 'modImpl'), 2); + $this->dbh->sqliteCreateFunction('mod', array('Doctrine_Expression_Sqlite', 'modImpl'), 2); $this->dbh->sqliteCreateFunction('concat', array('Doctrine_Expression_Sqlite', 'concatImpl')); $this->dbh->sqliteCreateFunction('md5', 'md5', 1); $this->dbh->sqliteCreateFunction('now', array('Doctrine_Expression_Sqlite', 'nowImpl'), 0); @@ -82,12 +78,13 @@ public function __construct(Doctrine_Manager $manager, $adapter) } /** - * initializes database functions missing in sqlite + * initializes database functions missing in sqlite. * * @see Doctrine_Expression - * @return boolean + * + * @return bool */ - public function connect() + public function connect() { if ($this->isConnected) { return; @@ -98,14 +95,14 @@ public function connect() $connected = parent::connect(); - if(!$hasConfigureStringify) { + if (!$hasConfigureStringify) { // PHP8.1 require default to true to keep BC // https://www.php.net/manual/en/migration81.incompatible.php#migration81.incompatible.pdo.sqlite // Can be overwritten by user later $this->dbh->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true); } - $this->dbh->sqliteCreateFunction('mod', array('Doctrine_Expression_Sqlite', 'modImpl'), 2); + $this->dbh->sqliteCreateFunction('mod', array('Doctrine_Expression_Sqlite', 'modImpl'), 2); $this->dbh->sqliteCreateFunction('concat', array('Doctrine_Expression_Sqlite', 'concatImpl')); $this->dbh->sqliteCreateFunction('md5', 'md5', 1); $this->dbh->sqliteCreateFunction('now', array('Doctrine_Expression_Sqlite', 'nowImpl'), 0); @@ -114,13 +111,11 @@ public function connect() } /** - * createDatabase - * - * @return void + * createDatabase. */ public function createDatabase() { - if ( ! $dsn = $this->getOption('dsn')) { + if (!$dsn = $this->getOption('dsn')) { throw new Doctrine_Connection_Exception('You must create your Doctrine_Connection by using a valid Doctrine style dsn in order to use the create/drop database functionality'); } @@ -130,18 +125,16 @@ public function createDatabase() } /** - * dropDatabase - * - * @return void + * dropDatabase. */ public function dropDatabase() { - if ( ! $dsn = $this->getOption('dsn')) { + if (!$dsn = $this->getOption('dsn')) { throw new Doctrine_Connection_Exception('You must create your Doctrine_Connection by using a valid Doctrine style dsn in order to use the create/drop database functionality'); } - + $info = $this->getManager()->parseDsn($dsn); $this->export->dropDatabase($info['database']); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Sqlite/Exception.php b/lib/Doctrine/Connection/Sqlite/Exception.php index cf4838e29..658c7c2ad 100644 --- a/lib/Doctrine/Connection/Sqlite/Exception.php +++ b/lib/Doctrine/Connection/Sqlite/Exception.php @@ -20,59 +20,63 @@ */ /** - * Doctrine_Connection_Sqlite_Exception + * Doctrine_Connection_Sqlite_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Connection_Sqlite_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorRegexps an array that is used for determining portable - * error code from a native database error message + * @var array an array that is used for determining portable + * error code from a native database error message */ protected static $errorRegexps = array( - '/^no such table:/' => Doctrine_Core::ERR_NOSUCHTABLE, - '/^no such index:/' => Doctrine_Core::ERR_NOT_FOUND, - '/^(table|index) .* already exists$/' => Doctrine_Core::ERR_ALREADY_EXISTS, - '/PRIMARY KEY must be unique/i' => Doctrine_Core::ERR_CONSTRAINT, - '/is not unique/' => Doctrine_Core::ERR_CONSTRAINT, - '/columns .* are not unique/i' => Doctrine_Core::ERR_CONSTRAINT, - '/uniqueness constraint failed/' => Doctrine_Core::ERR_CONSTRAINT, - '/may not be NULL/' => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - '/^no such column:/' => Doctrine_Core::ERR_NOSUCHFIELD, - '/column not present in both tables/i' => Doctrine_Core::ERR_NOSUCHFIELD, - '/^near ".*": syntax error$/' => Doctrine_Core::ERR_SYNTAX, - '/[0-9]+ values for [0-9]+ columns/i' => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - ); + '/^no such table:/' => Doctrine_Core::ERR_NOSUCHTABLE, + '/^no such index:/' => Doctrine_Core::ERR_NOT_FOUND, + '/^(table|index) .* already exists$/' => Doctrine_Core::ERR_ALREADY_EXISTS, + '/PRIMARY KEY must be unique/i' => Doctrine_Core::ERR_CONSTRAINT, + '/is not unique/' => Doctrine_Core::ERR_CONSTRAINT, + '/columns .* are not unique/i' => Doctrine_Core::ERR_CONSTRAINT, + '/uniqueness constraint failed/' => Doctrine_Core::ERR_CONSTRAINT, + '/may not be NULL/' => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + '/^no such column:/' => Doctrine_Core::ERR_NOSUCHFIELD, + '/column not present in both tables/i' => Doctrine_Core::ERR_NOSUCHFIELD, + '/^near ".*": syntax error$/' => Doctrine_Core::ERR_SYNTAX, + '/[0-9]+ values for [0-9]+ columns/i' => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 * @see Doctrine_Core::ERR_* constants * @see Doctrine_Connection::$portableCode - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { foreach (self::$errorRegexps as $regexp => $code) { if (preg_match($regexp, $errorInfo[2])) { - $this->portableCode = $code; + return true; } } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Statement.php b/lib/Doctrine/Connection/Statement.php index 4c0e86fac..9f3d75dfd 100644 --- a/lib/Doctrine/Connection/Statement.php +++ b/lib/Doctrine/Connection/Statement.php @@ -20,58 +20,58 @@ */ /** - * Doctrine_Connection_Statement + * Doctrine_Connection_Statement. * - * @package Doctrine - * @subpackage Connection * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1532 $ */ class Doctrine_Connection_Statement implements Doctrine_Adapter_Statement_Interface { /** - * @var Doctrine_Connection $conn Doctrine_Connection object, every connection - * statement holds an instance of Doctrine_Connection + * @var Doctrine_Connection Doctrine_Connection object, every connection + * statement holds an instance of Doctrine_Connection */ protected $_conn; /** - * @var mixed $_stmt PDOStatement object, boolean false or Doctrine_Adapter_Statement object + * @var mixed PDOStatement object, boolean false or Doctrine_Adapter_Statement object */ protected $_stmt; /** - * constructor + * constructor. * - * @param Doctrine_Connection $conn Doctrine_Connection object, every connection - * statement holds an instance of Doctrine_Connection - * @param mixed $stmt + * @param Doctrine_Connection $conn Doctrine_Connection object, every connection + * statement holds an instance of Doctrine_Connection */ public function __construct(Doctrine_Connection $conn, $stmt) { $this->_conn = $conn; $this->_stmt = $stmt; - if ($stmt === false) { + if (false === $stmt) { throw new Doctrine_Exception('Unknown statement object given.'); } } + /** - * destructor + * destructor. * * make sure that the cursor is closed - * */ public function __destruct() { $this->closeCursor(); } + /** * getConnection - * returns the connection object this statement uses + * returns the connection object this statement uses. * * @return Doctrine_Connection */ @@ -92,23 +92,23 @@ public function getQuery() /** * bindColumn - * Bind a column to a PHP variable + * Bind a column to a PHP variable. * - * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. - * If using the column name, be aware that the name should match - * the case of the column, as returned by the driver. + * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. + * If using the column name, be aware that the name should match + * the case of the column, as returned by the driver. + * @param string $param name of the PHP variable to which the column will be bound + * @param int $type data type of the parameter, specified by the Doctrine_Core::PARAM_* constants * - * @param string $param Name of the PHP variable to which the column will be bound. - * @param integer $type Data type of the parameter, specified by the Doctrine_Core::PARAM_* constants. - * @return boolean Returns TRUE on success or FALSE on failure + * @return bool Returns TRUE on success or FALSE on failure */ public function bindColumn($column, $param, $type = null) { - if ($type === null) { + if (null === $type) { return $this->_stmt->bindColumn($column, $param); - } else { - return $this->_stmt->bindColumn($column, $param, $type); } + + return $this->_stmt->bindColumn($column, $param, $type); } /** @@ -116,22 +116,21 @@ public function bindColumn($column, $param, $type = null) * Binds a value to a corresponding named or question mark * placeholder in the SQL statement that was use to prepare the statement. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, + * this will be a parameter name of the form :name. For a prepared statement + * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $value the value to bind to the parameter + * @param int $type explicit data type for the parameter using the Doctrine_Core::PARAM_* constants * - * @param mixed $value The value to bind to the parameter. - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. - * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindValue($param, $value, $type = null) { - if ($type === null) { + if (null === $type) { return $this->_stmt->bindValue($param, $value); - } else { - return $this->_stmt->bindValue($param, $value, $type); } + + return $this->_stmt->bindValue($param, $value, $type); } /** @@ -146,35 +145,29 @@ public function bindValue($param, $value, $type = null) * of stored procedures that return data as output parameters, and some also as input/output * parameters that both send in data and are updated to receive it. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter - * - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. + * @param mixed $variable name of the PHP variable to bind to the SQL statement parameter + * @param int $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return + * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the + * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. + * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter + * from a stored procedure, you must explicitly set the length. * - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return - * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the - * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. - * - * @param integer $length Length of the data type. To indicate that a parameter is an OUT parameter - * from a stored procedure, you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array()) { - if ($type === null) { + if (null === $type) { return $this->_stmt->bindParam($column, $variable); - } else { - return $this->_stmt->bindParam($column, $variable, $type, $length, $driverOptions); } + + return $this->_stmt->bindParam($column, $variable, $type, $length, $driverOptions); } /** * closeCursor * Closes the cursor, enabling the statement to be executed again. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function closeCursor() { @@ -183,11 +176,11 @@ public function closeCursor() /** * columnCount - * Returns the number of columns in the result set + * Returns the number of columns in the result set. * - * @return integer Returns the number of columns in the result set represented - * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, - * this method should return 0. + * @return int Returns the number of columns in the result set represented + * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, + * this method should return 0. */ public function columnCount() { @@ -196,10 +189,11 @@ public function columnCount() /** * errorCode - * Fetch the SQLSTATE associated with the last operation on the statement handle + * Fetch the SQLSTATE associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorCode() - * @return string error code string + * + * @return string error code string */ public function errorCode() { @@ -208,10 +202,11 @@ public function errorCode() /** * errorInfo - * Fetch extended error information associated with the last operation on the statement handle + * Fetch extended error information associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorInfo() - * @return array error info array + * + * @return array error info array */ public function errorInfo() { @@ -220,7 +215,7 @@ public function errorInfo() /** * execute - * Executes a prepared statement + * Executes a prepared statement. * * If the prepared statement included parameter markers, you must either: * call PDOStatement->bindParam() to bind PHP variables to the parameter markers: @@ -228,10 +223,10 @@ public function errorInfo() * if any, of their associated parameter markers or pass an array of input-only * parameter values * + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed * - * @param array $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = array()) { @@ -240,11 +235,10 @@ public function execute($params = array()) $this->_conn->getListener()->preStmtExecute($event); $result = true; - if ( ! $event->skipOperation) { - + if (!$event->skipOperation) { if ($this->_conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL) { foreach ($params as $key => $value) { - if ($value === '') { + if ('' === $value) { $params[$key] = null; } } @@ -253,8 +247,8 @@ public function execute($params = array()) if ($params) { $pos = 0; foreach ($params as $key => $value) { - $pos++; - $param = is_numeric($key) ? $pos : $key; + ++$pos; + $param = is_numeric($key) ? $pos : $key; if (is_resource($value)) { $this->_stmt->bindParam($param, $params[$key], Doctrine_Core::PARAM_LOB); } else { @@ -270,10 +264,10 @@ public function execute($params = array()) $this->_conn->getListener()->postStmtExecute($event); - //fix a possible "ORA-01000: maximum open cursors exceeded" when many non-SELECTs are executed and the profiling is enabled + // fix a possible "ORA-01000: maximum open cursors exceeded" when many non-SELECTs are executed and the profiling is enabled if ('Oracle' == $this->getConnection()->getDriverName()) { $queryBeginningSubstring = strtoupper(substr(ltrim($this->_stmt->queryString), 0, 6)); - if ($queryBeginningSubstring != 'SELECT' && substr($queryBeginningSubstring, 0, 4) != 'WITH' ){ + if ('SELECT' != $queryBeginningSubstring && 'WITH' != substr($queryBeginningSubstring, 0, 4)) { $this->closeCursor(); } } @@ -289,40 +283,34 @@ public function execute($params = array()) } /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. + * + * @param int $cursorOrientation For a PDOStatement object representing a scrollable cursor, + * this value determines which row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to + * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your + * Doctrine_Adapter_Statement_Interface object, + * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you + * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). + * @param int $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the + * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies + * the absolute number of the row in the result set that shall be fetched. * * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value * specifies the row to fetch relative to the cursor position before * Doctrine_Adapter_Statement_Interface->fetch() was called. - * - * @return mixed */ public function fetch($fetchMode = Doctrine_Core::FETCH_BOTH, - $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, - $cursorOffset = null) + $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, + $cursorOffset = null) { $event = new Doctrine_Event($this, Doctrine_Event::STMT_FETCH, $this->getQuery()); // null value is not an integer - if(null === $cursorOffset) { + if (null === $cursorOffset) { $cursorOffset = 0; } @@ -332,7 +320,7 @@ public function fetch($fetchMode = Doctrine_Core::FETCH_BOTH, $data = $this->_conn->getListener()->preFetch($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $data = $this->_stmt->fetch($fetchMode, $cursorOrientation, $cursorOffset); } @@ -343,19 +331,18 @@ public function fetch($fetchMode = Doctrine_Core::FETCH_BOTH, /** * fetchAll - * Returns an array containing all of the result set rows + * Returns an array containing all of the result set rows. * - * @param integer $fetchMode Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is - * Doctrine_Core::FETCH_COLUMN. Defaults to 0. + * @param int $fetchMode Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH + * @param int $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is + * Doctrine_Core::FETCH_COLUMN. Defaults to 0. * * @return array */ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH, - $columnIndex = null) + $columnIndex = null) { $event = new Doctrine_Event($this, Doctrine_Event::STMT_FETCHALL, $this->getQuery()); $event->fetchMode = $fetchMode; @@ -363,8 +350,8 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH, $this->_conn->getListener()->preFetchAll($event); - if ( ! $event->skipOperation) { - if ($columnIndex !== null) { + if (!$event->skipOperation) { + if (null !== $columnIndex) { $data = $this->_stmt->fetchAll($fetchMode, $columnIndex); } else { $data = $this->_stmt->fetchAll($fetchMode); @@ -383,11 +370,11 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH, * Returns a single column from the next row of a * result set or FALSE if there are no more rows. * - * @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no - * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() - * fetches the first column. + * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no + * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() + * fetches the first column. * - * @return string returns a single column in the next row of a result set. + * @return string returns a single column in the next row of a result set */ public function fetchColumn($columnIndex = 0) { @@ -401,11 +388,11 @@ public function fetchColumn($columnIndex = 0) * Fetches the next row and returns it as an object. This function is an alternative to * Doctrine_Adapter_Statement_Interface->fetch() with Doctrine_Core::FETCH_CLASS or Doctrine_Core::FETCH_OBJ style. * - * @param string $className Name of the created class, defaults to stdClass. - * @param array $args Elements of this array are passed to the constructor. + * @param string $className name of the created class, defaults to stdClass + * @param array $args elements of this array are passed to the constructor * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @return mixed an instance of the required class with property names that correspond + * to the column names or FALSE in case of an error */ public function fetchObject($className = 'stdClass', $args = array()) { @@ -414,11 +401,13 @@ public function fetchObject($className = 'stdClass', $args = array()) /** * getAttribute - * Retrieve a statement attribute + * Retrieve a statement attribute. + * + * @param int $attribute * - * @param integer $attribute * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute) { @@ -427,11 +416,11 @@ public function getAttribute($attribute) /** * getColumnMeta - * Returns metadata for a column in a result set + * Returns metadata for a column in a result set. * - * @param integer $column The 0-indexed column in the result set. + * @param int $column the 0-indexed column in the result set * - * @return array Associative meta data array with the following structure: + * @return array Associative meta data array with the following structure: * * native_type The PHP native type used to represent the column value. * driver:decl_ type The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta(). @@ -448,14 +437,14 @@ public function getColumnMeta($column) /** * nextRowset - * Advances to the next rowset in a multi-rowset statement handle + * Advances to the next rowset in a multi-rowset statement handle. * * Some database servers support stored procedures that return more than one rowset * (also known as a result set). The nextRowset() method enables you to access the second * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a * different set of columns from the preceding rowset. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function nextRowset() { @@ -472,7 +461,7 @@ public function nextRowset() * this behaviour is not guaranteed for all databases and should not be * relied on for portable applications. * - * @return integer Returns the number of rows. + * @return int returns the number of rows */ public function rowCount() { @@ -481,11 +470,12 @@ public function rowCount() /** * setAttribute - * Set a statement attribute + * Set a statement attribute. * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @param int $attribute + * @param mixed $value the value of given attribute + * + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value) { @@ -494,10 +484,13 @@ public function setAttribute($attribute, $value) /** * setFetchMode - * Set the default fetch mode for this statement + * Set the default fetch mode for this statement. + * + * @param int $mode the fetch mode must be one of the Doctrine_Core::FETCH_* constants + * @param mixed|null $arg1 + * @param mixed|null $arg2 * - * @param integer $mode The fetch mode must be one of the Doctrine_Core::FETCH_* constants. - * @return boolean Returns 1 on success or FALSE on failure. + * @return bool returns 1 on success or FALSE on failure */ public function setFetchMode($mode, $arg1 = null, $arg2 = null) { diff --git a/lib/Doctrine/Connection/UnitOfWork.php b/lib/Doctrine/Connection/UnitOfWork.php index 9627d6d19..bdda47b5e 100644 --- a/lib/Doctrine/Connection/UnitOfWork.php +++ b/lib/Doctrine/Connection/UnitOfWork.php @@ -20,7 +20,7 @@ */ /** - * Doctrine_Connection_UnitOfWork + * Doctrine_Connection_UnitOfWork. * * Note: This class does not have the semantics of a real "Unit of Work" in 0.10/1.0. * Database operations are not queued. All changes to objects are immediately written @@ -28,12 +28,13 @@ * * Referential integrity is currently not always ensured. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7684 $ + * * @author Konsta Vesterinen * @author Roman Borschel */ @@ -42,9 +43,6 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module /** * Saves the given record and all associated records. * (The save() operation is always cascaded in 0.10/1.0). - * - * @param Doctrine_Record $record - * @return void */ public function saveGraph(Doctrine_Record $record, $replace = false) { @@ -54,7 +52,7 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $conn->connect(); $state = $record->state(); - if ($state === Doctrine_Record::STATE_LOCKED || $state === Doctrine_Record::STATE_TLOCKED) { + if (Doctrine_Record::STATE_LOCKED === $state || Doctrine_Record::STATE_TLOCKED === $state) { return false; } @@ -69,7 +67,7 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $isValid = true; - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->saveRelatedLocalKeys($record); switch ($state) { @@ -101,12 +99,12 @@ public function saveGraph(Doctrine_Record $record, $replace = false) foreach ($record->getPendingDeletes() as $pendingDelete) { $pendingDelete->delete(); } - + foreach ($record->getPendingUnlinks() as $alias => $ids) { - if ($ids === false) { + if (false === $ids) { $record->unlinkInDb($alias, array()); $aliasesUnlinkInDb[] = $alias; - } else if ($ids) { + } elseif ($ids) { $record->unlinkInDb($alias, array_keys($ids)); $aliasesUnlinkInDb[] = $alias; } @@ -128,10 +126,10 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $alias = $fk->getAlias(); if ($record->hasReference($alias)) { - $obj = $record->$alias; + $obj = $record->{$alias}; // check that the related object is not an instance of Doctrine_Null - if ($obj && ! ($obj instanceof Doctrine_Null)) { + if ($obj && !($obj instanceof Doctrine_Null)) { $processDiff = !in_array($alias, $aliasesUnlinkInDb); $obj->save($conn, $processDiff); } @@ -148,7 +146,7 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $conn->commit(); } catch (Exception $e) { // Make sure we roll back our internal transaction - //$record->state($state); + // $record->state($state); $conn->rollback(); throw $e; } @@ -164,12 +162,13 @@ public function saveGraph(Doctrine_Record $record, $replace = false) * * this event can be listened by the onPreDelete and onDelete listeners * - * @return boolean true on success, false on failure + * @return bool true on success, false on failure */ public function delete(Doctrine_Record $record) { $deletions = array(); $this->_collectDeletions($record, $deletions); + return $this->_executeDeletions($deletions); } @@ -177,11 +176,11 @@ public function delete(Doctrine_Record $record) * Collects all records that need to be deleted by applying defined * application-level delete cascades. * - * @param array $deletions Map of the records to delete. Keys=Oids Values=Records. + * @param array $deletions Map of the records to delete. Keys=Oids Values=Records. */ private function _collectDeletions(Doctrine_Record $record, array &$deletions) { - if ( ! $record->exists()) { + if (!$record->exists()) { return; } @@ -193,7 +192,7 @@ private function _collectDeletions(Doctrine_Record $record, array &$deletions) * Executes the deletions for all collected records during a delete operation * (usually triggered through $record->delete()). * - * @param array $deletions Map of the records to delete. Keys=Oids Values=Records. + * @param array $deletions Map of the records to delete. Keys=Oids Values=Records. */ private function _executeDeletions(array $deletions) { @@ -211,7 +210,7 @@ private function _executeDeletions(array $deletions) try { $this->conn->beginInternalTransaction(); - for ($i = count($executionOrder) - 1; $i >= 0; $i--) { + for ($i = count($executionOrder) - 1; $i >= 0; --$i) { $className = $executionOrder[$i]; $table = $this->conn->getTable($className); @@ -221,7 +220,7 @@ private function _executeDeletions(array $deletions) foreach ($deletions as $oid => $record) { if ($record->getTable()->getComponentName() == $className) { $veto = $this->_preDelete($record); - if ( ! $veto) { + if (!$veto) { $identifierMaps[] = $record->identifier(); $deletedRecords[] = $record; unset($deletions[$oid]); @@ -237,7 +236,7 @@ private function _executeDeletions(array $deletions) $params = array(); $columnNames = array(); foreach ($identifierMaps as $idMap) { - foreach($idMap as $fieldName => $value) { + foreach ($idMap as $fieldName => $value) { $params[] = $value; $columnNames[] = $table->getColumnName($fieldName); } @@ -246,7 +245,7 @@ private function _executeDeletions(array $deletions) // delete $tableName = $table->getTableName(); - $sql = "DELETE FROM " . $this->conn->quoteIdentifier($tableName) . " WHERE "; + $sql = 'DELETE FROM '.$this->conn->quoteIdentifier($tableName).' WHERE '; if ($table->isIdentifierComposite()) { $sql .= $this->_buildSqlCompositeKeyCondition($columnNames, count($identifierMaps)); @@ -260,7 +259,7 @@ private function _executeDeletions(array $deletions) foreach ($deletedRecords as $record) { // currently just for bc! $this->_deleteCTIParents($table, $record); - //-- + // -- $record->state(Doctrine_Record::STATE_TCLEAN); $record->getTable()->removeRecord($record); $this->_postDelete($record); @@ -285,38 +284,38 @@ private function _executeDeletions(array $deletions) * Builds the SQL condition to target multiple records who have a single-column * primary key. * - * @param Doctrine_Table $table The table from which the records are going to be deleted. - * @param integer $numRecords The number of records that are going to be deleted. - * @return string The SQL condition "pk = ? OR pk = ? OR pk = ? ..." + * @param int $numRecords the number of records that are going to be deleted + * + * @return string The SQL condition "pk = ? OR pk = ? OR pk = ? ..." */ private function _buildSqlSingleKeyCondition($columnNames, $numRecords) { $idColumn = $this->conn->quoteIdentifier($columnNames[0]); - return implode(' OR ', array_fill(0, $numRecords, "$idColumn = ?")); + + return implode(' OR ', array_fill(0, $numRecords, "{$idColumn} = ?")); } /** * Builds the SQL condition to target multiple records who have a composite primary key. * - * @param Doctrine_Table $table The table from which the records are going to be deleted. - * @param integer $numRecords The number of records that are going to be deleted. - * @return string The SQL condition "(pk1 = ? AND pk2 = ?) OR (pk1 = ? AND pk2 = ?) ..." + * @param int $numRecords the number of records that are going to be deleted + * + * @return string The SQL condition "(pk1 = ? AND pk2 = ?) OR (pk1 = ? AND pk2 = ?) ..." */ private function _buildSqlCompositeKeyCondition($columnNames, $numRecords) { - $singleCondition = ""; + $singleCondition = ''; foreach ($columnNames as $columnName) { $columnName = $this->conn->quoteIdentifier($columnName); - if ($singleCondition === "") { - $singleCondition .= "($columnName = ?"; + if ('' === $singleCondition) { + $singleCondition .= "({$columnName} = ?"; } else { - $singleCondition .= " AND $columnName = ?"; + $singleCondition .= " AND {$columnName} = ?"; } } - $singleCondition .= ")"; - $fullCondition = implode(' OR ', array_fill(0, $numRecords, $singleCondition)); + $singleCondition .= ')'; - return $fullCondition; + return implode(' OR ', array_fill(0, $numRecords, $singleCondition)); } /** @@ -327,42 +326,41 @@ private function _buildSqlCompositeKeyCondition($columnNames, $numRecords) * Exception: many-valued relations are always (re-)fetched from the database to * make sure we have all of them. * - * @param Doctrine_Record The record for which the delete operation will be cascaded. - * @throws PDOException If something went wrong at database level - * @return void + * @param Doctrine_Record the record for which the delete operation will be cascaded + * + * @throws PDOException If something went wrong at database level */ - protected function _cascadeDelete(Doctrine_Record $record, array &$deletions) - { - foreach ($record->getTable()->getRelations() as $relation) { - if ($relation->isCascadeDelete()) { - $fieldName = $relation->getAlias(); - // if it's a xToOne relation and the related object is already loaded - // we don't need to refresh. - if ( ! ($relation->getType() == Doctrine_Relation::ONE && isset($record->$fieldName))) { - $record->refreshRelated($relation->getAlias()); - } - $relatedObjects = $record->get($relation->getAlias()); - if ($relatedObjects instanceof Doctrine_Record && $relatedObjects->exists() - && ! isset($deletions[$relatedObjects->getOid()])) { - $this->_collectDeletions($relatedObjects, $deletions); - } else if ($relatedObjects instanceof Doctrine_Collection && count($relatedObjects) > 0) { - // cascade the delete to the other objects - foreach ($relatedObjects as $object) { - if ( ! isset($deletions[$object->getOid()])) { - $this->_collectDeletions($object, $deletions); - } - } - } - } - } - } + protected function _cascadeDelete(Doctrine_Record $record, array &$deletions) + { + foreach ($record->getTable()->getRelations() as $relation) { + if ($relation->isCascadeDelete()) { + $fieldName = $relation->getAlias(); + // if it's a xToOne relation and the related object is already loaded + // we don't need to refresh. + if (!(Doctrine_Relation::ONE == $relation->getType() && isset($record->{$fieldName}))) { + $record->refreshRelated($relation->getAlias()); + } + $relatedObjects = $record->get($relation->getAlias()); + if ($relatedObjects instanceof Doctrine_Record && $relatedObjects->exists() + && !isset($deletions[$relatedObjects->getOid()])) { + $this->_collectDeletions($relatedObjects, $deletions); + } elseif ($relatedObjects instanceof Doctrine_Collection && count($relatedObjects) > 0) { + // cascade the delete to the other objects + foreach ($relatedObjects as $object) { + if (!isset($deletions[$object->getOid()])) { + $this->_collectDeletions($object, $deletions); + } + } + } + } + } + } /** * saveRelatedForeignKeys - * saves all related (through ForeignKey) records to $record + * saves all related (through ForeignKey) records to $record. * - * @throws PDOException if something went wrong at database level - * @param Doctrine_Record $record + * @throws PDOException if something went wrong at database level */ public function saveRelatedForeignKeys(Doctrine_Record $record) { @@ -376,13 +374,12 @@ public function saveRelatedForeignKeys(Doctrine_Record $record) return $saveLater; } - + /** * saveRelatedLocalKeys - * saves all related (through LocalKey) records to $record + * saves all related (through LocalKey) records to $record. * - * @throws PDOException if something went wrong at database level - * @param Doctrine_Record $record + * @throws PDOException if something went wrong at database level */ public function saveRelatedLocalKeys(Doctrine_Record $record) { @@ -391,7 +388,7 @@ public function saveRelatedLocalKeys(Doctrine_Record $record) foreach ($record->getReferences() as $k => $v) { $rel = $record->getTable()->getRelation($k); - + $local = $rel->getLocal(); $foreign = $rel->getForeign(); @@ -405,10 +402,10 @@ public function saveRelatedLocalKeys(Doctrine_Record $record) $id = array_values($obj->identifier()); - if ( ! empty($id)) { + if (!empty($id)) { foreach ((array) $rel->getLocal() as $k => $columnName) { $field = $record->getTable()->getFieldName($columnName); - + if (isset($id[$k]) && $id[$k] && $record->getTable()->hasField($field)) { $record->set($field, $id[$k]); } @@ -421,7 +418,7 @@ public function saveRelatedLocalKeys(Doctrine_Record $record) } /** - * saveAssociations + * saveAssociations. * * this method takes a diff of one-to-many / many-to-many original and * current collections and applies the changes @@ -431,9 +428,7 @@ public function saveRelatedLocalKeys(Doctrine_Record $record) * 3, 4 and 5, this method would first destroy the associations to 1 and 2 and then * save new associations to 4 and 5 * - * @throws Doctrine_Connection_Exception if something went wrong at database level - * @param Doctrine_Record $record - * @return void + * @throws Doctrine_Connection_Exception if something went wrong at database level */ public function saveAssociations(Doctrine_Record $record) { @@ -447,9 +442,9 @@ public function saveAssociations(Doctrine_Record $record) $assocTable = $rel->getAssociationTable(); foreach ($v->getDeleteDiff() as $r) { - $query = 'DELETE FROM ' . $assocTable->getTableName() - . ' WHERE ' . $rel->getForeignRefColumnName() . ' = ?' - . ' AND ' . $rel->getLocalRefColumnName() . ' = ?'; + $query = 'DELETE FROM '.$assocTable->getTableName() + .' WHERE '.$rel->getForeignRefColumnName().' = ?' + .' AND '.$rel->getLocalRefColumnName().' = ?'; $this->conn->execute($query, array($r->getIncremented(), $record->getIncremented())); } @@ -469,7 +464,7 @@ public function saveAssociations(Doctrine_Record $record) /** * Invokes preDelete event listeners. * - * @return boolean Whether a listener has used it's veto (don't delete!). + * @return bool whether a listener has used it's veto (don't delete!) */ private function _preDelete(Doctrine_Record $record) { @@ -492,10 +487,9 @@ private function _postDelete(Doctrine_Record $record) /** * saveAll - * persists all the pending records from all tables + * persists all the pending records from all tables. * - * @throws PDOException if something went wrong at database level - * @return void + * @throws PDOException if something went wrong at database level */ public function saveAll() { @@ -512,10 +506,11 @@ public function saveAll() } /** - * updates given record + * updates given record. * - * @param Doctrine_Record $record record to be updated - * @return boolean whether or not the update was successful + * @param Doctrine_Record $record record to be updated + * + * @return bool whether or not the update was successful */ public function update(Doctrine_Record $record) { @@ -523,12 +518,12 @@ public function update(Doctrine_Record $record) if ($record->isValid(false, false)) { $table = $record->getTable(); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $identifier = $record->identifier(); if ($table->getOption('joinedParents')) { // currrently just for bc! $this->_updateCTIRecord($table, $record); - //-- + // -- } else { $array = $record->getPrepared(); $this->conn->update($table, $array, $identifier); @@ -548,12 +543,11 @@ public function update(Doctrine_Record $record) * Inserts a record into database. * * This method inserts a transient record in the database, and adds it - * to the identity map of its correspondent table. It proxies to @see + * to the identity map of its correspondent table. It proxies to @see * processSingleInsert(), trigger insert hooks and validation of data * if required. * - * @param Doctrine_Record $record - * @return boolean false if record is not valid + * @return bool false if record is not valid */ public function insert(Doctrine_Record $record) { @@ -562,11 +556,11 @@ public function insert(Doctrine_Record $record) if ($record->isValid(false, false)) { $table = $record->getTable(); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { if ($table->getOption('joinedParents')) { // just for bc! $this->_insertCTIRecord($table, $record); - //-- + // -- } else { $this->processSingleInsert($record); } @@ -584,52 +578,47 @@ public function insert(Doctrine_Record $record) /** * Replaces a record into database. * - * @param Doctrine_Record $record - * @return boolean false if record is not valid + * @return bool false if record is not valid */ public function replace(Doctrine_Record $record) { if ($record->exists()) { return $this->update($record); - } else { - if ($record->isValid()) { - $this->_assignSequence($record); + } + if ($record->isValid()) { + $this->_assignSequence($record); - $saveEvent = $record->invokeSaveHooks('pre', 'save'); - $insertEvent = $record->invokeSaveHooks('pre', 'insert'); + $saveEvent = $record->invokeSaveHooks('pre', 'save'); + $insertEvent = $record->invokeSaveHooks('pre', 'insert'); - $table = $record->getTable(); - $identifier = (array) $table->getIdentifier(); - $data = $record->getPrepared(); + $table = $record->getTable(); + $identifier = (array) $table->getIdentifier(); + $data = $record->getPrepared(); - foreach ($data as $key => $value) { - if ($value instanceof Doctrine_Expression) { - $data[$key] = $value->getSql(); - } + foreach ($data as $key => $value) { + if ($value instanceof Doctrine_Expression) { + $data[$key] = $value->getSql(); } + } - $result = $this->conn->replace($table, $data, $identifier); + $result = $this->conn->replace($table, $data, $identifier); - $record->invokeSaveHooks('post', 'insert', $insertEvent); - $record->invokeSaveHooks('post', 'save', $saveEvent); + $record->invokeSaveHooks('post', 'insert', $insertEvent); + $record->invokeSaveHooks('post', 'save', $saveEvent); - $this->_assignIdentifier($record); + $this->_assignIdentifier($record); - return true; - } else { - return false; - } + return true; } + + return false; } /** * Inserts a transient record in its table. * - * This method inserts the data of a single record in its assigned table, + * This method inserts the data of a single record in its assigned table, * assigning to it the autoincrement primary key (if any is defined). - * - * @param Doctrine_Record $record - * @return void */ public function processSingleInsert(Doctrine_Record $record) { @@ -650,14 +639,15 @@ public function processSingleInsert(Doctrine_Record $record) /** * buildFlushTree - * builds a flush tree that is used in transactions + * builds a flush tree that is used in transactions. * * The returned array has all the initialized components in * 'correct' order. Basically this means that the records of those * components can be saved safely in the order specified by the returned array. * - * @param array $tables an array of Doctrine_Table objects or component names - * @return array an array of component names in flushing order + * @param array $tables an array of Doctrine_Table objects or component names + * + * @return array an array of component names in flushing order */ public function buildFlushTree(array $tables) { @@ -665,7 +655,7 @@ public function buildFlushTree(array $tables) // can contain strings or table objects... $classesToOrder = array(); foreach ($tables as $table) { - if ( ! ($table instanceof Doctrine_Table)) { + if (!($table instanceof Doctrine_Table)) { $table = $this->conn->getTable($table, false); } $classesToOrder[] = $table->getComponentName(); @@ -684,8 +674,8 @@ public function buildFlushTree(array $tables) $index = array_search($currentClass, $flushList); - if ($index === false) { - //echo "adding $currentClass to flushlist"; + if (false === $index) { + // echo "adding $currentClass to flushlist"; $flushList[] = $currentClass; $index = max(array_keys($flushList)); } @@ -703,7 +693,7 @@ public function buildFlushTree(array $tables) foreach ($rels as $rel) { $relatedClassName = $rel->getTable()->getComponentName(); - if ( ! in_array($relatedClassName, $classesToOrder)) { + if (!in_array($relatedClassName, $classesToOrder)) { continue; } @@ -719,7 +709,7 @@ public function buildFlushTree(array $tables) // the related component needs to come after this component in // the list (since it holds the fk) - if ($relatedCompIndex !== false) { + if (false !== $relatedCompIndex) { // the component is already in the list if ($relatedCompIndex >= $index) { // it's already in the right place @@ -734,12 +724,11 @@ public function buildFlushTree(array $tables) } else { $flushList[] = $relatedClassName; } - - } else if ($rel instanceof Doctrine_Relation_LocalKey) { + } elseif ($rel instanceof Doctrine_Relation_LocalKey) { // the related component needs to come before the current component // in the list (since this component holds the fk). - if ($relatedCompIndex !== false) { + if (false !== $relatedCompIndex) { // already in flush list if ($relatedCompIndex <= $index) { // it's in the right place @@ -752,9 +741,9 @@ public function buildFlushTree(array $tables) array_splice($flushList, $index, 0, $relatedClassName); } else { array_unshift($flushList, $relatedClassName); - $index++; + ++$index; } - } else if ($rel instanceof Doctrine_Relation_Association) { + } elseif ($rel instanceof Doctrine_Relation_Association) { // the association class needs to come after both classes // that are connected through it in the list (since it holds // both fks) @@ -762,16 +751,16 @@ public function buildFlushTree(array $tables) $assocTable = $rel->getAssociationFactory(); $assocClassName = $assocTable->getComponentName(); - if ($relatedCompIndex !== false) { + if (false !== $relatedCompIndex) { unset($flushList[$relatedCompIndex]); } array_splice($flushList, $index, 0, $relatedClassName); - $index++; + ++$index; $index3 = array_search($assocClassName, $flushList); - if ($index3 !== false) { + if (false !== $index3) { if ($index3 >= $index) { continue; } @@ -789,7 +778,6 @@ public function buildFlushTree(array $tables) return array_values($flushList); } - /* The following is all the Class Table Inheritance specific code. Support dropped for 0.10/1.0. */ @@ -822,7 +810,7 @@ private function _insertCTIRecord(Doctrine_Table $table, Doctrine_Record $record $classes[] = $component; foreach ($classes as $k => $parent) { - if ($k === 0) { + if (0 === $k) { $rootRecord = new $parent(); $rootRecord->merge($dataSet[$parent]); $this->processSingleInsert($rootRecord); @@ -853,7 +841,7 @@ private function _updateCTIRecord(Doctrine_Table $table, Doctrine_Record $record foreach ($record as $field => $value) { if ($value instanceof Doctrine_Record) { - if ( ! $value->exists()) { + if (!$value->exists()) { $value->save(); } $record->set($field, $value->getIncremented()); @@ -863,7 +851,7 @@ private function _updateCTIRecord(Doctrine_Table $table, Doctrine_Record $record foreach ($classes as $class) { $parentTable = $this->conn->getTable($class); - if ( ! array_key_exists($class, $dataSet)) { + if (!array_key_exists($class, $dataSet)) { continue; } @@ -883,11 +871,11 @@ private function _formatDataSet(Doctrine_Record $record) $array = $record->getPrepared(); foreach ($table->getColumns() as $columnName => $definition) { - if ( ! isset($dataSet[$component])) { + if (!isset($dataSet[$component])) { $dataSet[$component] = array(); } - if ( isset($definition['owner']) && ! isset($dataSet[$definition['owner']])) { + if (isset($definition['owner']) && !isset($dataSet[$definition['owner']])) { $dataSet[$definition['owner']] = array(); } @@ -896,7 +884,7 @@ private function _formatDataSet(Doctrine_Record $record) continue; } - if ( ! array_key_exists($fieldName, $array)) { + if (!array_key_exists($fieldName, $array)) { continue; } @@ -915,7 +903,7 @@ protected function _assignSequence(Doctrine_Record $record, &$fields = null) $table = $record->getTable(); $seq = $table->sequenceName; - if ( ! empty($seq)) { + if (!empty($seq)) { $id = $this->conn->sequence->nextId($seq); $seqName = $table->getIdentifier(); if ($fields) { @@ -934,22 +922,22 @@ protected function _assignIdentifier(Doctrine_Record $record) $identifier = $table->getIdentifier(); $seq = $table->sequenceName; - if (empty($seq) && !is_array($identifier) && - $table->getIdentifierType() != Doctrine_Core::IDENTIFIER_NATURAL) { + if (empty($seq) && !is_array($identifier) + && Doctrine_Core::IDENTIFIER_NATURAL != $table->getIdentifierType()) { $id = false; - if ($record->$identifier == null) { + if (null == $record->{$identifier}) { if (($driver = strtolower($this->conn->getDriverName())) == 'pgsql') { - $seq = $table->getTableName() . '_' . $table->getColumnName($identifier); - } elseif ($driver == 'oracle' || $driver == 'mssql') { + $seq = $table->getTableName().'_'.$table->getColumnName($identifier); + } elseif ('oracle' == $driver || 'mssql' == $driver) { $seq = $table->getTableName(); } - + $id = $this->conn->sequence->lastInsertId($seq); } else { - $id = $record->$identifier; + $id = $record->{$identifier}; } - if ( ! $id) { + if (!$id) { throw new Doctrine_Connection_Exception("Couldn't get last insert identifier."); } $record->assignIdentifier($id); diff --git a/lib/Doctrine/Core.php b/lib/Doctrine/Core.php index 382bf9510..bebfba2e9 100644 --- a/lib/Doctrine/Core.php +++ b/lib/Doctrine/Core.php @@ -20,499 +20,505 @@ */ /** - * The base core class of Doctrine + * The base core class of Doctrine. * - * @package Doctrine * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Core { /** - * VERSION - */ - const VERSION = '1.2.4'; - - /** - * ERROR CONSTANTS - */ - const ERR = -1; - const ERR_SYNTAX = -2; - const ERR_CONSTRAINT = -3; - const ERR_NOT_FOUND = -4; - const ERR_ALREADY_EXISTS = -5; - const ERR_UNSUPPORTED = -6; - const ERR_MISMATCH = -7; - const ERR_INVALID = -8; - const ERR_NOT_CAPABLE = -9; - const ERR_TRUNCATED = -10; - const ERR_INVALID_NUMBER = -11; - const ERR_INVALID_DATE = -12; - const ERR_DIVZERO = -13; - const ERR_NODBSELECTED = -14; - const ERR_CANNOT_CREATE = -15; - const ERR_CANNOT_DELETE = -16; - const ERR_CANNOT_DROP = -17; - const ERR_NOSUCHTABLE = -18; - const ERR_NOSUCHFIELD = -19; - const ERR_NEED_MORE_DATA = -20; - const ERR_NOT_LOCKED = -21; - const ERR_VALUE_COUNT_ON_ROW = -22; - const ERR_INVALID_DSN = -23; - const ERR_CONNECT_FAILED = -24; - const ERR_EXTENSION_NOT_FOUND = -25; - const ERR_NOSUCHDB = -26; - const ERR_ACCESS_VIOLATION = -27; - const ERR_CANNOT_REPLACE = -28; - const ERR_CONSTRAINT_NOT_NULL = -29; - const ERR_DEADLOCK = -30; - const ERR_CANNOT_ALTER = -31; - const ERR_MANAGER = -32; - const ERR_MANAGER_PARSE = -33; - const ERR_LOADMODULE = -34; - const ERR_INSUFFICIENT_DATA = -35; - const ERR_CLASS_NAME = -36; - - /** - * PDO derived constants - */ - const CASE_LOWER = 2; - const CASE_NATURAL = 0; - const CASE_UPPER = 1; - const CURSOR_FWDONLY = 0; - const CURSOR_SCROLL = 1; - const ERRMODE_EXCEPTION = 2; - const ERRMODE_SILENT = 0; - const ERRMODE_WARNING = 1; - const FETCH_ASSOC = 2; - const FETCH_BOTH = 4; - const FETCH_BOUND = 6; - const FETCH_CLASS = 8; - const FETCH_CLASSTYPE = 262144; - const FETCH_COLUMN = 7; - const FETCH_FUNC = 10; - const FETCH_GROUP = 65536; - const FETCH_INTO = 9; - const FETCH_LAZY = 1; - const FETCH_NAMED = 11; - const FETCH_NUM = 3; - const FETCH_OBJ = 5; - const FETCH_ORI_ABS = 4; - const FETCH_ORI_FIRST = 2; - const FETCH_ORI_LAST = 3; - const FETCH_ORI_NEXT = 0; - const FETCH_ORI_PRIOR = 1; - const FETCH_ORI_REL = 5; - const FETCH_SERIALIZE = 524288; - const FETCH_UNIQUE = 196608; - const NULL_EMPTY_STRING = 1; - const NULL_NATURAL = 0; - const NULL_TO_STRING = NULL; - const PARAM_BOOL = 5; - const PARAM_INPUT_OUTPUT = -2147483648; - const PARAM_INT = 1; - const PARAM_LOB = 3; - const PARAM_NULL = 0; - const PARAM_STMT = 4; - const PARAM_STR = 2; - - /** - * ATTRIBUTE CONSTANTS - */ - - /** - * PDO derived attributes - */ - const ATTR_AUTOCOMMIT = 0; - const ATTR_PREFETCH = 1; - const ATTR_TIMEOUT = 2; - const ATTR_ERRMODE = 3; - const ATTR_SERVER_VERSION = 4; - const ATTR_CLIENT_VERSION = 5; - const ATTR_SERVER_INFO = 6; - const ATTR_CONNECTION_STATUS = 7; - const ATTR_CASE = 8; - const ATTR_CURSOR_NAME = 9; - const ATTR_CURSOR = 10; - const ATTR_ORACLE_NULLS = 11; - const ATTR_PERSISTENT = 12; - const ATTR_STATEMENT_CLASS = 13; - const ATTR_FETCH_TABLE_NAMES = 14; - const ATTR_FETCH_CATALOG_NAMES = 15; - const ATTR_DRIVER_NAME = 16; - const ATTR_STRINGIFY_FETCHES = 17; - const ATTR_MAX_COLUMN_LEN = 18; - - /** - * Doctrine constants - */ - const ATTR_LISTENER = 100; - const ATTR_QUOTE_IDENTIFIER = 101; - const ATTR_FIELD_CASE = 102; - const ATTR_IDXNAME_FORMAT = 103; - const ATTR_SEQNAME_FORMAT = 104; - const ATTR_SEQCOL_NAME = 105; - const ATTR_CMPNAME_FORMAT = 118; - const ATTR_DBNAME_FORMAT = 117; - const ATTR_TBLCLASS_FORMAT = 119; - const ATTR_TBLNAME_FORMAT = 120; - const ATTR_FKNAME_FORMAT = 171; - const ATTR_EXPORT = 140; - const ATTR_DECIMAL_PLACES = 141; - - const ATTR_PORTABILITY = 106; - const ATTR_VALIDATE = 107; - const ATTR_COLL_KEY = 108; - const ATTR_QUERY_LIMIT = 109; - const ATTR_DEFAULT_TABLE_TYPE = 112; - const ATTR_DEF_TEXT_LENGTH = 113; - const ATTR_DEF_VARCHAR_LENGTH = 114; - const ATTR_DEF_TABLESPACE = 115; - const ATTR_EMULATE_DATABASE = 116; - const ATTR_USE_NATIVE_ENUM = 117; - const ATTR_DEFAULT_SEQUENCE = 133; - - const ATTR_FETCHMODE = 118; - const ATTR_NAME_PREFIX = 121; - const ATTR_CREATE_TABLES = 122; - const ATTR_COLL_LIMIT = 123; - - const ATTR_CACHE = 150; - const ATTR_RESULT_CACHE = 150; - const ATTR_CACHE_LIFESPAN = 151; - const ATTR_RESULT_CACHE_LIFESPAN = 151; - const ATTR_LOAD_REFERENCES = 153; - const ATTR_RECORD_LISTENER = 154; - const ATTR_THROW_EXCEPTIONS = 155; - const ATTR_DEFAULT_PARAM_NAMESPACE = 156; - const ATTR_QUERY_CACHE = 157; - const ATTR_QUERY_CACHE_LIFESPAN = 158; - const ATTR_AUTOLOAD_TABLE_CLASSES = 160; - const ATTR_MODEL_LOADING = 161; - const ATTR_RECURSIVE_MERGE_FIXTURES = 162; - const ATTR_USE_DQL_CALLBACKS = 164; - const ATTR_AUTO_ACCESSOR_OVERRIDE = 165; - const ATTR_AUTO_FREE_QUERY_OBJECTS = 166; - const ATTR_DEFAULT_TABLE_CHARSET = 167; - const ATTR_DEFAULT_TABLE_COLLATE = 168; - const ATTR_DEFAULT_IDENTIFIER_OPTIONS = 169; - const ATTR_DEFAULT_COLUMN_OPTIONS = 170; - const ATTR_HYDRATE_OVERWRITE = 172; - const ATTR_QUERY_CLASS = 173; - const ATTR_CASCADE_SAVES = 174; - const ATTR_COLLECTION_CLASS = 175; - const ATTR_TABLE_CLASS = 176; - const ATTR_USE_NATIVE_SET = 177; - const ATTR_MODEL_CLASS_PREFIX = 178; - const ATTR_TABLE_CLASS_FORMAT = 179; - const ATTR_MAX_IDENTIFIER_LENGTH = 180; - const ATTR_USE_TABLE_REPOSITORY = 181; - const ATTR_USE_TABLE_IDENTITY_MAP = 182; - const ATTR_TABLE_CACHE = 183; - const ATTR_TABLE_CACHE_LIFESPAN = 184; - - - /** - * LIMIT CONSTANTS - */ - - /** - * constant for row limiting - */ - const LIMIT_ROWS = 1; - const QUERY_LIMIT_ROWS = 1; - - /** - * constant for record limiting - */ - const LIMIT_RECORDS = 2; - const QUERY_LIMIT_RECORDS = 2; - - /** - * FETCHMODE CONSTANTS - */ - - - /** - * PORTABILITY CONSTANTS + * VERSION. + */ + public const VERSION = '1.2.4'; + + /** + * ERROR CONSTANTS. + */ + public const ERR = -1; + public const ERR_SYNTAX = -2; + public const ERR_CONSTRAINT = -3; + public const ERR_NOT_FOUND = -4; + public const ERR_ALREADY_EXISTS = -5; + public const ERR_UNSUPPORTED = -6; + public const ERR_MISMATCH = -7; + public const ERR_INVALID = -8; + public const ERR_NOT_CAPABLE = -9; + public const ERR_TRUNCATED = -10; + public const ERR_INVALID_NUMBER = -11; + public const ERR_INVALID_DATE = -12; + public const ERR_DIVZERO = -13; + public const ERR_NODBSELECTED = -14; + public const ERR_CANNOT_CREATE = -15; + public const ERR_CANNOT_DELETE = -16; + public const ERR_CANNOT_DROP = -17; + public const ERR_NOSUCHTABLE = -18; + public const ERR_NOSUCHFIELD = -19; + public const ERR_NEED_MORE_DATA = -20; + public const ERR_NOT_LOCKED = -21; + public const ERR_VALUE_COUNT_ON_ROW = -22; + public const ERR_INVALID_DSN = -23; + public const ERR_CONNECT_FAILED = -24; + public const ERR_EXTENSION_NOT_FOUND = -25; + public const ERR_NOSUCHDB = -26; + public const ERR_ACCESS_VIOLATION = -27; + public const ERR_CANNOT_REPLACE = -28; + public const ERR_CONSTRAINT_NOT_NULL = -29; + public const ERR_DEADLOCK = -30; + public const ERR_CANNOT_ALTER = -31; + public const ERR_MANAGER = -32; + public const ERR_MANAGER_PARSE = -33; + public const ERR_LOADMODULE = -34; + public const ERR_INSUFFICIENT_DATA = -35; + public const ERR_CLASS_NAME = -36; + + /** + * PDO derived constants. + */ + public const CASE_LOWER = 2; + public const CASE_NATURAL = 0; + public const CASE_UPPER = 1; + public const CURSOR_FWDONLY = 0; + public const CURSOR_SCROLL = 1; + public const ERRMODE_EXCEPTION = 2; + public const ERRMODE_SILENT = 0; + public const ERRMODE_WARNING = 1; + public const FETCH_ASSOC = 2; + public const FETCH_BOTH = 4; + public const FETCH_BOUND = 6; + public const FETCH_CLASS = 8; + public const FETCH_CLASSTYPE = 262144; + public const FETCH_COLUMN = 7; + public const FETCH_FUNC = 10; + public const FETCH_GROUP = 65536; + public const FETCH_INTO = 9; + public const FETCH_LAZY = 1; + public const FETCH_NAMED = 11; + public const FETCH_NUM = 3; + public const FETCH_OBJ = 5; + public const FETCH_ORI_ABS = 4; + public const FETCH_ORI_FIRST = 2; + public const FETCH_ORI_LAST = 3; + public const FETCH_ORI_NEXT = 0; + public const FETCH_ORI_PRIOR = 1; + public const FETCH_ORI_REL = 5; + public const FETCH_SERIALIZE = 524288; + public const FETCH_UNIQUE = 196608; + public const NULL_EMPTY_STRING = 1; + public const NULL_NATURAL = 0; + public const NULL_TO_STRING = null; + public const PARAM_BOOL = 5; + public const PARAM_INPUT_OUTPUT = -2147483648; + public const PARAM_INT = 1; + public const PARAM_LOB = 3; + public const PARAM_NULL = 0; + public const PARAM_STMT = 4; + public const PARAM_STR = 2; + + /** + * ATTRIBUTE CONSTANTS. + */ + + /** + * PDO derived attributes. + */ + public const ATTR_AUTOCOMMIT = 0; + public const ATTR_PREFETCH = 1; + public const ATTR_TIMEOUT = 2; + public const ATTR_ERRMODE = 3; + public const ATTR_SERVER_VERSION = 4; + public const ATTR_CLIENT_VERSION = 5; + public const ATTR_SERVER_INFO = 6; + public const ATTR_CONNECTION_STATUS = 7; + public const ATTR_CASE = 8; + public const ATTR_CURSOR_NAME = 9; + public const ATTR_CURSOR = 10; + public const ATTR_ORACLE_NULLS = 11; + public const ATTR_PERSISTENT = 12; + public const ATTR_STATEMENT_CLASS = 13; + public const ATTR_FETCH_TABLE_NAMES = 14; + public const ATTR_FETCH_CATALOG_NAMES = 15; + public const ATTR_DRIVER_NAME = 16; + public const ATTR_STRINGIFY_FETCHES = 17; + public const ATTR_MAX_COLUMN_LEN = 18; + + /** + * Doctrine constants. + */ + public const ATTR_LISTENER = 100; + public const ATTR_QUOTE_IDENTIFIER = 101; + public const ATTR_FIELD_CASE = 102; + public const ATTR_IDXNAME_FORMAT = 103; + public const ATTR_SEQNAME_FORMAT = 104; + public const ATTR_SEQCOL_NAME = 105; + public const ATTR_CMPNAME_FORMAT = 118; + public const ATTR_DBNAME_FORMAT = 117; + public const ATTR_TBLCLASS_FORMAT = 119; + public const ATTR_TBLNAME_FORMAT = 120; + public const ATTR_FKNAME_FORMAT = 171; + public const ATTR_EXPORT = 140; + public const ATTR_DECIMAL_PLACES = 141; + + public const ATTR_PORTABILITY = 106; + public const ATTR_VALIDATE = 107; + public const ATTR_COLL_KEY = 108; + public const ATTR_QUERY_LIMIT = 109; + public const ATTR_DEFAULT_TABLE_TYPE = 112; + public const ATTR_DEF_TEXT_LENGTH = 113; + public const ATTR_DEF_VARCHAR_LENGTH = 114; + public const ATTR_DEF_TABLESPACE = 115; + public const ATTR_EMULATE_DATABASE = 116; + public const ATTR_USE_NATIVE_ENUM = 117; + public const ATTR_DEFAULT_SEQUENCE = 133; + + public const ATTR_FETCHMODE = 118; + public const ATTR_NAME_PREFIX = 121; + public const ATTR_CREATE_TABLES = 122; + public const ATTR_COLL_LIMIT = 123; + + public const ATTR_CACHE = 150; + public const ATTR_RESULT_CACHE = 150; + public const ATTR_CACHE_LIFESPAN = 151; + public const ATTR_RESULT_CACHE_LIFESPAN = 151; + public const ATTR_LOAD_REFERENCES = 153; + public const ATTR_RECORD_LISTENER = 154; + public const ATTR_THROW_EXCEPTIONS = 155; + public const ATTR_DEFAULT_PARAM_NAMESPACE = 156; + public const ATTR_QUERY_CACHE = 157; + public const ATTR_QUERY_CACHE_LIFESPAN = 158; + public const ATTR_AUTOLOAD_TABLE_CLASSES = 160; + public const ATTR_MODEL_LOADING = 161; + public const ATTR_RECURSIVE_MERGE_FIXTURES = 162; + public const ATTR_USE_DQL_CALLBACKS = 164; + public const ATTR_AUTO_ACCESSOR_OVERRIDE = 165; + public const ATTR_AUTO_FREE_QUERY_OBJECTS = 166; + public const ATTR_DEFAULT_TABLE_CHARSET = 167; + public const ATTR_DEFAULT_TABLE_COLLATE = 168; + public const ATTR_DEFAULT_IDENTIFIER_OPTIONS = 169; + public const ATTR_DEFAULT_COLUMN_OPTIONS = 170; + public const ATTR_HYDRATE_OVERWRITE = 172; + public const ATTR_QUERY_CLASS = 173; + public const ATTR_CASCADE_SAVES = 174; + public const ATTR_COLLECTION_CLASS = 175; + public const ATTR_TABLE_CLASS = 176; + public const ATTR_USE_NATIVE_SET = 177; + public const ATTR_MODEL_CLASS_PREFIX = 178; + public const ATTR_TABLE_CLASS_FORMAT = 179; + public const ATTR_MAX_IDENTIFIER_LENGTH = 180; + public const ATTR_USE_TABLE_REPOSITORY = 181; + public const ATTR_USE_TABLE_IDENTITY_MAP = 182; + public const ATTR_TABLE_CACHE = 183; + public const ATTR_TABLE_CACHE_LIFESPAN = 184; + + /** + * LIMIT CONSTANTS. + */ + + /** + * constant for row limiting. + */ + public const LIMIT_ROWS = 1; + public const QUERY_LIMIT_ROWS = 1; + + /** + * constant for record limiting. + */ + public const LIMIT_RECORDS = 2; + public const QUERY_LIMIT_RECORDS = 2; + + /** + * FETCHMODE CONSTANTS. + */ + + /** + * PORTABILITY CONSTANTS. */ /** * Portability: turn off all portability features. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_NONE = 0; + public const PORTABILITY_NONE = 0; /** * Portability: convert names of tables and fields to case defined in the * "field_case" option when using the query*(), fetch*() methods. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_FIX_CASE = 1; + public const PORTABILITY_FIX_CASE = 1; /** * Portability: right trim the data output by query*() and fetch*(). + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_RTRIM = 2; + public const PORTABILITY_RTRIM = 2; /** * Portability: force reporting the number of rows deleted. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_DELETE_COUNT = 4; + public const PORTABILITY_DELETE_COUNT = 4; /** * Portability: convert empty values to null strings in data output by * query*() and fetch*(). + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_EMPTY_TO_NULL = 8; + public const PORTABILITY_EMPTY_TO_NULL = 8; /** - * Portability: removes database/table qualifiers from associative indexes + * Portability: removes database/table qualifiers from associative indexes. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_FIX_ASSOC_FIELD_NAMES = 16; + public const PORTABILITY_FIX_ASSOC_FIELD_NAMES = 16; /** - * Portability: makes Doctrine_Expression throw exception for unportable RDBMS expressions + * Portability: makes Doctrine_Expression throw exception for unportable RDBMS expressions. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_EXPR = 32; + public const PORTABILITY_EXPR = 32; /** * Portability: turn on all portability features. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_ALL = 63; + public const PORTABILITY_ALL = 63; /** - * LOCKMODE CONSTANTS + * LOCKMODE CONSTANTS. */ /** - * mode for optimistic locking + * mode for optimistic locking. */ - const LOCK_OPTIMISTIC = 0; + public const LOCK_OPTIMISTIC = 0; /** - * mode for pessimistic locking + * mode for pessimistic locking. */ - const LOCK_PESSIMISTIC = 1; + public const LOCK_PESSIMISTIC = 1; /** - * EXPORT CONSTANTS + * EXPORT CONSTANTS. */ /** - * EXPORT_NONE + * EXPORT_NONE. */ - const EXPORT_NONE = 0; + public const EXPORT_NONE = 0; /** - * EXPORT_TABLES + * EXPORT_TABLES. */ - const EXPORT_TABLES = 1; + public const EXPORT_TABLES = 1; /** - * EXPORT_CONSTRAINTS + * EXPORT_CONSTRAINTS. */ - const EXPORT_CONSTRAINTS = 2; + public const EXPORT_CONSTRAINTS = 2; /** - * EXPORT_PLUGINS + * EXPORT_PLUGINS. */ - const EXPORT_PLUGINS = 4; + public const EXPORT_PLUGINS = 4; /** - * EXPORT_ALL + * EXPORT_ALL. */ - const EXPORT_ALL = 7; + public const EXPORT_ALL = 7; /** - * HYDRATION CONSTANTS + * HYDRATION CONSTANTS. */ /** - * HYDRATE_RECORD + * HYDRATE_RECORD. */ - const HYDRATE_RECORD = 2; + public const HYDRATE_RECORD = 2; /** - * HYDRATE_ARRAY + * HYDRATE_ARRAY. */ - const HYDRATE_ARRAY = 3; + public const HYDRATE_ARRAY = 3; /** - * HYDRATE_NONE + * HYDRATE_NONE. */ - const HYDRATE_NONE = 4; + public const HYDRATE_NONE = 4; /** - * HYDRATE_SCALAR + * HYDRATE_SCALAR. */ - const HYDRATE_SCALAR = 5; + public const HYDRATE_SCALAR = 5; /** - * HYDRATE_SINGLE_SCALAR + * HYDRATE_SINGLE_SCALAR. */ - const HYDRATE_SINGLE_SCALAR = 6; + public const HYDRATE_SINGLE_SCALAR = 6; /** - * HYDRATE_ON_DEMAND + * HYDRATE_ON_DEMAND. */ - const HYDRATE_ON_DEMAND = 7; + public const HYDRATE_ON_DEMAND = 7; /** - * HYDRATE_ARRAY_HIERARCHY + * HYDRATE_ARRAY_HIERARCHY. */ - const HYDRATE_ARRAY_HIERARCHY = 8; + public const HYDRATE_ARRAY_HIERARCHY = 8; /** - * HYDRATE_RECORD_HIERARCHY + * HYDRATE_RECORD_HIERARCHY. */ - const HYDRATE_RECORD_HIERARCHY = 9; + public const HYDRATE_RECORD_HIERARCHY = 9; /** - * HYDRATE_ARRAY_SHALLOW + * HYDRATE_ARRAY_SHALLOW. */ - const HYDRATE_ARRAY_SHALLOW = 10; + public const HYDRATE_ARRAY_SHALLOW = 10; /** - * VALIDATION CONSTANTS + * VALIDATION CONSTANTS. */ - const VALIDATE_NONE = 0; + public const VALIDATE_NONE = 0; /** - * VALIDATE_LENGTHS + * VALIDATE_LENGTHS. */ - const VALIDATE_LENGTHS = 1; + public const VALIDATE_LENGTHS = 1; /** - * VALIDATE_TYPES + * VALIDATE_TYPES. */ - const VALIDATE_TYPES = 2; + public const VALIDATE_TYPES = 2; /** - * VALIDATE_CONSTRAINTS + * VALIDATE_CONSTRAINTS. */ - const VALIDATE_CONSTRAINTS = 4; + public const VALIDATE_CONSTRAINTS = 4; /** - * VALIDATE_ALL + * VALIDATE_ALL. */ - const VALIDATE_ALL = 7; + public const VALIDATE_ALL = 7; /** - * VALIDATE_USER + * VALIDATE_USER. */ - const VALIDATE_USER = 8; + public const VALIDATE_USER = 8; /** - * IDENTIFIER_AUTOINC + * IDENTIFIER_AUTOINC. * * constant for auto_increment identifier */ - const IDENTIFIER_AUTOINC = 1; + public const IDENTIFIER_AUTOINC = 1; /** - * IDENTIFIER_SEQUENCE + * IDENTIFIER_SEQUENCE. * * constant for sequence identifier */ - const IDENTIFIER_SEQUENCE = 2; + public const IDENTIFIER_SEQUENCE = 2; /** - * IDENTIFIER_NATURAL + * IDENTIFIER_NATURAL. * * constant for normal identifier */ - const IDENTIFIER_NATURAL = 3; + public const IDENTIFIER_NATURAL = 3; /** - * IDENTIFIER_COMPOSITE + * IDENTIFIER_COMPOSITE. * * constant for composite identifier */ - const IDENTIFIER_COMPOSITE = 4; + public const IDENTIFIER_COMPOSITE = 4; /** - * MODEL_LOADING_AGGRESSIVE + * MODEL_LOADING_AGGRESSIVE. * * Constant for agressive model loading * Will require_once() all found model files */ - const MODEL_LOADING_AGGRESSIVE = 1; + public const MODEL_LOADING_AGGRESSIVE = 1; /** - * MODEL_LOADING_CONSERVATIVE + * MODEL_LOADING_CONSERVATIVE. * * Constant for conservative model loading * Will not require_once() found model files inititally instead it will build an array * and reference it in autoload() when a class is needed it will require_once() it */ - const MODEL_LOADING_CONSERVATIVE = 2; + public const MODEL_LOADING_CONSERVATIVE = 2; /** - * MODEL_LOADING_PEAR + * MODEL_LOADING_PEAR. * * Constant for pear model loading * Will simply store the path passed to Doctrine_Core::loadModels() * and Doctrine_Core::autoload() will check there */ - const MODEL_LOADING_PEAR = 3; + public const MODEL_LOADING_PEAR = 3; /** - * Path to Doctrine root + * Path to Doctrine root. * - * @var string $path doctrine root directory + * @var string doctrine root directory */ private static $_path; /** - * Path to the Doctrine extensions directory + * Path to the Doctrine extensions directory. * - * @var string $extensionsPath + * @var string */ private static $_extensionsPath; /** - * Debug bool true/false option + * Debug bool true/false option. * - * @var boolean $_debug + * @var bool */ private static $_debug = false; /** - * Array of all the loaded models and the path to each one for autoloading + * Array of all the loaded models and the path to each one for autoloading. * * @var array */ private static $_loadedModelFiles = array(); /** - * Array of all the loaded validators + * Array of all the loaded validators. * * @var array */ private static $_validators = array(); /** - * Path to the models directory + * Path to the models directory. * * @var string */ private static $_modelsDirectory; /** - * __construct + * __construct. * - * @return void * @throws Doctrine_Exception */ public function __construct() @@ -521,7 +527,7 @@ public function __construct() } /** - * Returns an array of all the loaded models and the path where each of them exists + * Returns an array of all the loaded models and the path where each of them exists. * * @return array */ @@ -531,14 +537,13 @@ public static function getLoadedModelFiles() } /** - * Turn on/off the debugging setting + * Turn on/off the debugging setting. * * @param string $bool - * @return void */ public static function debug($bool = null) { - if ($bool !== null) { + if (null !== $bool) { self::$_debug = (bool) $bool; } @@ -546,10 +551,9 @@ public static function debug($bool = null) } /** - * Set the path to your core Doctrine libraries + * Set the path to your core Doctrine libraries. * * @param string $path The path to your Doctrine libraries - * @return void */ public static function setPath($path) { @@ -557,24 +561,23 @@ public static function setPath($path) } /** - * Get the root path to Doctrine + * Get the root path to Doctrine. * * @return string */ public static function getPath() { - if ( ! self::$_path) { - self::$_path = realpath(dirname(__FILE__) . '/..'); + if (!self::$_path) { + self::$_path = realpath(dirname(__FILE__).'/..'); } return self::$_path; } /** - * Set the path to autoload extension classes from + * Set the path to autoload extension classes from. * * @param string $extensionsPath - * @return void */ public static function setExtensionsPath($extensionsPath) { @@ -582,7 +585,7 @@ public static function setExtensionsPath($extensionsPath) } /** - * Get the path to load extension classes from + * Get the path to load extension classes from. * * @return string $extensionsPath */ @@ -592,9 +595,9 @@ public static function getExtensionsPath() } /** - * Load an individual model name and path in to the model loading registry + * Load an individual model name and path in to the model loading registry. * - * @return null + * @param mixed|null $path */ public static function loadModel($className, $path = null) { @@ -606,7 +609,6 @@ public static function loadModel($className, $path = null) * naming convention autoloading. * * @param string $directory - * @return void */ public static function setModelsDirectory($directory) { @@ -615,9 +617,8 @@ public static function setModelsDirectory($directory) /** * Get the directory where your models are located for PEAR style naming - * convention autoloading + * convention autoloading. * - * @return void * @author Jonathan Wage */ public static function getModelsDirectory() @@ -626,38 +627,38 @@ public static function getModelsDirectory() } /** - * Recursively load all models from a directory or array of directories + * Recursively load all models from a directory or array of directories. * - * @param string $directory Path to directory of models or array of directory paths - * @param integer $modelLoading Pass value of Doctrine_Core::ATTR_MODEL_LOADING to force a certain style of model loading - * Allowed Doctrine_Core::MODEL_LOADING_AGGRESSIVE(default) or Doctrine_Core::MODEL_LOADING_CONSERVATIVE - * @param string $classPrefix The class prefix of the models to load. This is useful if the class name and file name are not the same + * @param string $directory Path to directory of models or array of directory paths + * @param int $modelLoading Pass value of Doctrine_Core::ATTR_MODEL_LOADING to force a certain style of model loading + * Allowed Doctrine_Core::MODEL_LOADING_AGGRESSIVE(default) or Doctrine_Core::MODEL_LOADING_CONSERVATIVE + * @param string $classPrefix The class prefix of the models to load. This is useful if the class name and file name are not the same */ public static function loadModels($directory, $modelLoading = null, $classPrefix = null) { $manager = Doctrine_Manager::getInstance(); - $modelLoading = $modelLoading === null ? $manager->getAttribute(Doctrine_Core::ATTR_MODEL_LOADING) : $modelLoading; - $classPrefix = $classPrefix === null ? $manager->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) : $classPrefix; + $modelLoading = null === $modelLoading ? $manager->getAttribute(Doctrine_Core::ATTR_MODEL_LOADING) : $modelLoading; + $classPrefix = null === $classPrefix ? $manager->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) : $classPrefix; $loadedModels = array(); - if ($directory !== null) { + if (null !== $directory) { foreach ((array) $directory as $dir) { $dir = rtrim($dir, '/'); - if ( ! is_dir($dir)) { + if (!is_dir($dir)) { throw new Doctrine_Exception('You must pass a valid path to a directory containing Doctrine models'); } $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), - RecursiveIteratorIterator::LEAVES_ONLY); + RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $e = explode('.', $file->getFileName()); - if (end($e) === 'php' && strpos($file->getFileName(), '.inc') === false) { - if ($modelLoading == Doctrine_Core::MODEL_LOADING_PEAR) { - $className = str_replace($dir . DIRECTORY_SEPARATOR, null, $file->getPathName()); + if ('php' === end($e) && false === strpos($file->getFileName(), '.inc')) { + if (Doctrine_Core::MODEL_LOADING_PEAR == $modelLoading) { + $className = str_replace($dir.DIRECTORY_SEPARATOR, null, $file->getPathName()); $className = str_replace(DIRECTORY_SEPARATOR, '_', $className); $className = substr($className, 0, strpos($className, '.')); } else { @@ -665,17 +666,17 @@ public static function loadModels($directory, $modelLoading = null, $classPrefix } if ($classPrefix && $classPrefix != substr($className, 0, strlen($classPrefix))) { - $className = $classPrefix . $className; + $className = $classPrefix.$className; } - if ( ! class_exists($className, false)) { - if ($modelLoading == Doctrine_Core::MODEL_LOADING_CONSERVATIVE || $modelLoading == Doctrine_Core::MODEL_LOADING_PEAR) { + if (!class_exists($className, false)) { + if (Doctrine_Core::MODEL_LOADING_CONSERVATIVE == $modelLoading || Doctrine_Core::MODEL_LOADING_PEAR == $modelLoading) { self::loadModel($className, $file->getPathName()); $loadedModels[$className] = $className; } else { $declaredBefore = get_declared_classes(); - require_once($file->getPathName()); + require_once $file->getPathName(); $declaredAfter = get_declared_classes(); if (defined('HHVM_VERSION')) { @@ -699,12 +700,12 @@ public static function loadModels($directory, $modelLoading = null, $classPrefix $previouslyLoaded = array_keys(self::$_loadedModelFiles, $file->getPathName()); - if ( ! empty($previouslyLoaded)) { + if (!empty($previouslyLoaded)) { $previouslyLoaded = array_combine(array_values($previouslyLoaded), array_values($previouslyLoaded)); $loadedModels = array_merge($loadedModels, $previouslyLoaded); } } - } else if (self::isValidModelClass($className)) { + } elseif (self::isValidModelClass($className)) { $loadedModels[$className] = $className; } } @@ -718,17 +719,19 @@ public static function loadModels($directory, $modelLoading = null, $classPrefix } /** - * Get all the loaded models, you can provide an array of classes or it will use get_declared_classes() + * Get all the loaded models, you can provide an array of classes or it will use get_declared_classes(). * * Will filter through an array of classes and return the Doctrine_Records out of them. * If you do not specify $classes it will return all of the currently loaded Doctrine_Records * * @param classes Array of classes to filter through, otherwise uses get_declared_classes() - * @return array $loadedModels + * @param mixed|null $classes + * + * @return array $loadedModels */ public static function getLoadedModels($classes = null) { - if ($classes === null) { + if (null === $classes) { $classes = get_declared_classes(); $classes = array_merge($classes, array_keys(self::$_loadedModelFiles)); } @@ -740,9 +743,10 @@ public static function getLoadedModels($classes = null) * Initialize all models so everything is present and loaded in to memory * This will also inheritently initialize any model behaviors and add * the models generated by Doctrine generators and add them to the $models - * array + * array. * * @param string $models + * * @return array $models */ public static function initializeModels($models) @@ -769,9 +773,7 @@ public static function initializeModels($models) } } - $models = self::filterInvalidModels($models); - - return $models; + return self::filterInvalidModels($models); } /** @@ -779,14 +781,15 @@ public static function initializeModels($models) * This will inflect the class, causing it to be loaded in to memory. * * @param classes Array of classes to filter through, otherwise uses get_declared_classes() - * @return array $loadedModels + * + * @return array $loadedModels */ public static function filterInvalidModels($classes) { $validModels = array(); foreach ((array) $classes as $name) { - if (self::isValidModelClass($name) && ! in_array($name, $validModels)) { + if (self::isValidModelClass($name) && !in_array($name, $validModels)) { $validModels[] = $name; } } @@ -796,10 +799,11 @@ public static function filterInvalidModels($classes) /** * Checks if what is passed is a valid Doctrine_Record - * Will load class in to memory in order to inflect it and find out information about the class + * Will load class in to memory in order to inflect it and find out information about the class. + * + * @param mixed $class Can be a string named after the class, an instance of the class, or an instance of the class reflected * - * @param mixed $class Can be a string named after the class, an instance of the class, or an instance of the class reflected - * @return boolean + * @return bool */ public static function isValidModelClass($class) { @@ -815,8 +819,7 @@ public static function isValidModelClass($class) // Skip the following classes // - abstract classes // - not a subclass of Doctrine_Record - if ( ! $class->isAbstract() && $class->isSubclassOf('Doctrine_Record')) { - + if (!$class->isAbstract() && $class->isSubclassOf('Doctrine_Record')) { return true; } } @@ -826,9 +829,10 @@ public static function isValidModelClass($class) /** * Get the connection object for a table by the actual table name - * FIXME: I think this method is flawed because a individual connections could have the same table name + * FIXME: I think this method is flawed because a individual connections could have the same table name. * * @param string $tableName + * * @return Doctrine_Connection */ public static function getConnectionByTableName($tableName) @@ -839,7 +843,7 @@ public static function getConnectionByTableName($tableName) $table = Doctrine_Core::getTable($name); if ($table->getTableName() == $tableName) { - return $table->getConnection(); + return $table->getConnection(); } } @@ -847,12 +851,14 @@ public static function getConnectionByTableName($tableName) } /** - * Method for importing existing schema to Doctrine_Record classes + * Method for importing existing schema to Doctrine_Record classes. + * + * @param string $directory Directory to write your models to + * @param array $connections Array of connection names to generate models for + * @param array $options Array of options + * + * @return bool * - * @param string $directory Directory to write your models to - * @param array $connections Array of connection names to generate models for - * @param array $options Array of options - * @return boolean * @throws Exception */ public static function generateModelsFromDb($directory, array $connections = array(), array $options = array()) @@ -864,19 +870,18 @@ public static function generateModelsFromDb($directory, array $connections = arr * Generates models from database to temporary location then uses those models to generate a yaml schema file. * This should probably be fixed. We should write something to generate a yaml schema file directly from the database. * - * @param string $yamlPath Path to write oyur yaml schema file to - * @param array $connections Array of connection names to generate yaml for - * @param array $options Array of options - * @return void + * @param string $yamlPath Path to write oyur yaml schema file to + * @param array $connections Array of connection names to generate yaml for + * @param array $options Array of options */ public static function generateYamlFromDb($yamlPath, array $connections = array(), array $options = array()) { - $directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'tmp_doctrine_models'; + $directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'tmp_doctrine_models'; - $options['generateBaseClasses'] = isset($options['generateBaseClasses']) ? $options['generateBaseClasses']:false; + $options['generateBaseClasses'] = isset($options['generateBaseClasses']) ? $options['generateBaseClasses'] : false; $result = Doctrine_Core::generateModelsFromDb($directory, $connections, $options); - if ( empty($result) && ! is_dir($directory)) { + if (empty($result) && !is_dir($directory)) { throw new Doctrine_Exception('No models generated from your databases'); } @@ -890,12 +895,11 @@ public static function generateYamlFromDb($yamlPath, array $connections = array( } /** - * Generate a yaml schema file from an existing directory of models + * Generate a yaml schema file from an existing directory of models. * - * @param string $yamlPath Path to your yaml schema files + * @param string $yamlPath Path to your yaml schema files * @param string $directory Directory to generate your models in - * @param array $options Array of options to pass to the schema importer - * @return void + * @param array $options Array of options to pass to the schema importer */ public static function generateModelsFromYaml($yamlPath, $directory, $options = array()) { @@ -906,10 +910,9 @@ public static function generateModelsFromYaml($yamlPath, $directory, $options = } /** - * Creates database tables for the models in the specified directory + * Creates database tables for the models in the specified directory. * * @param string $directory Directory containing your models - * @return void */ public static function createTablesFromModels($directory = null) { @@ -917,10 +920,9 @@ public static function createTablesFromModels($directory = null) } /** - * Creates database tables for the models in the supplied array + * Creates database tables for the models in the supplied array. * * @param array $array An array of models to be exported - * @return void */ public static function createTablesFromArray($array) { @@ -928,9 +930,10 @@ public static function createTablesFromArray($array) } /** - * Generate a array of sql for the passed array of models + * Generate a array of sql for the passed array of models. + * + * @param array $array * - * @param array $array * @return array $sql */ public static function generateSqlFromArray($array) @@ -942,7 +945,8 @@ public static function generateSqlFromArray($array) * Generate a sql string to create the tables from all loaded models * or the models found in the passed directory. * - * @param string $directory + * @param string $directory + * * @return string $build String of sql queries. One query per line */ public static function generateSqlFromModels($directory = null) @@ -959,11 +963,10 @@ public static function generateSqlFromModels($directory = null) } /** - * Generate yaml schema file for the models in the specified directory + * Generate yaml schema file for the models in the specified directory. * - * @param string $yamlPath Path to your yaml schema files + * @param string $yamlPath Path to your yaml schema files * @param string $directory Directory to generate your models in - * @return void */ public static function generateYamlFromModels($yamlPath, $directory) { @@ -973,10 +976,9 @@ public static function generateYamlFromModels($yamlPath, $directory) } /** - * Creates databases for connections + * Creates databases for connections. * * @param string $specifiedConnections Array of connections you wish to create the database for - * @return void */ public static function createDatabases($specifiedConnections = array()) { @@ -984,10 +986,9 @@ public static function createDatabases($specifiedConnections = array()) } /** - * Drops databases for connections + * Drops databases for connections. * * @param string $specifiedConnections Array of connections you wish to drop the database for - * @return void */ public static function dropDatabases($specifiedConnections = array()) { @@ -995,11 +996,10 @@ public static function dropDatabases($specifiedConnections = array()) } /** - * Dump data to a yaml fixtures file + * Dump data to a yaml fixtures file. * - * @param string $yamlPath Path to write the yaml data fixtures to + * @param string $yamlPath Path to write the yaml data fixtures to * @param string $individualFiles Whether or not to dump data to individual fixtures files - * @return void */ public static function dumpData($yamlPath, $individualFiles = false) { @@ -1010,11 +1010,10 @@ public static function dumpData($yamlPath, $individualFiles = false) /** * Load data from a yaml fixtures file. - * The output of dumpData can be fed to loadData + * The output of dumpData can be fed to loadData. * * @param string $yamlPath Path to your yaml data fixtures - * @param string $append Whether or not to append the data - * @return void + * @param string $append Whether or not to append the data */ public static function loadData($yamlPath, $append = false, $charset = 'UTF-8') { @@ -1027,8 +1026,10 @@ public static function loadData($yamlPath, $append = false, $charset = 'UTF-8') * Migrate database to specified $to version. Migrates from current to latest if you do not specify. * * @param string $migrationsPath Path to migrations directory which contains your migration classes - * @param string $to Version you wish to migrate to. + * @param string $to version you wish to migrate to + * * @return bool true + * * @throws new Doctrine_Migration_Exception */ public static function migrate($migrationsPath, $to = null) @@ -1039,9 +1040,9 @@ public static function migrate($migrationsPath, $to = null) } /** - * Generate new migration class skeleton + * Generate new migration class skeleton. * - * @param string $className Name of the Migration class to generate + * @param string $className Name of the Migration class to generate * @param string $migrationsPath Path to directory which contains your migration classes */ public static function generateMigrationClass($className, $migrationsPath) @@ -1052,10 +1053,10 @@ public static function generateMigrationClass($className, $migrationsPath) } /** - * Generate a set of migration classes from an existing database + * Generate a set of migration classes from an existing database. * * @param string $migrationsPath - * @return void + * * @throws new Doctrine_Migration_Exception */ public static function generateMigrationsFromDb($migrationsPath) @@ -1066,12 +1067,11 @@ public static function generateMigrationsFromDb($migrationsPath) } /** - * Generate a set of migration classes from an existing set of models + * Generate a set of migration classes from an existing set of models. * - * @param string $migrationsPath Path to your Doctrine migration classes - * @param string $modelsPath Path to your Doctrine model classes - * @param integer $modelLoading Style of model loading to use for loading the models in order to generate migrations - * @return void + * @param string $migrationsPath Path to your Doctrine migration classes + * @param string $modelsPath Path to your Doctrine model classes + * @param int $modelLoading Style of model loading to use for loading the models in order to generate migrations */ public static function generateMigrationsFromModels($migrationsPath, $modelsPath = null, $modelLoading = null) { @@ -1082,11 +1082,12 @@ public static function generateMigrationsFromModels($migrationsPath, $modelsPath /** * Generate a set of migration classes by generating differences between two sets - * of schema information + * of schema information. + * + * @param string $migrationsPath Path to your Doctrine migration classes + * @param string $from From schema information + * @param string $to To schema information * - * @param string $migrationsPath Path to your Doctrine migration classes - * @param string $from From schema information - * @param string $to To schema information * @return array $changes */ public static function generateMigrationsFromDiff($migrationsPath, $from, $to) @@ -1097,9 +1098,10 @@ public static function generateMigrationsFromDiff($migrationsPath, $from, $to) } /** - * Get the Doctrine_Table object for the passed model + * Get the Doctrine_Table object for the passed model. * * @param string $componentName + * * @return Doctrine_Table */ public static function getTable($componentName) @@ -1110,12 +1112,12 @@ public static function getTable($componentName) /** * Method for making a single file of most used doctrine runtime components * including the compiled file instead of multiple files (in worst - * cases dozens of files) can improve performance by an order of magnitude + * cases dozens of files) can improve performance by an order of magnitude. * * @param string $target * @param array $includedDrivers + * * @throws Doctrine_Exception - * @return void */ public static function compile($target = null, $includedDrivers = array()) { @@ -1124,15 +1126,16 @@ public static function compile($target = null, $includedDrivers = array()) /** * simple autoload function - * returns true if the class was loaded, otherwise false + * returns true if the class was loaded, otherwise false. * * @param string $className - * @return boolean + * + * @return bool */ public static function autoload($className) { - if (strpos($className, 'sfYaml') === 0) { - require dirname(__FILE__) . '/Parser/sfYaml/' . $className . '.php'; + if (0 === strpos($className, 'sfYaml')) { + require dirname(__FILE__).'/Parser/sfYaml/'.$className.'.php'; return true; } @@ -1141,7 +1144,7 @@ public static function autoload($className) return false; } - $class = self::getPath() . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; + $class = self::getPath().DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $className).'.php'; if (file_exists($class)) { require $class; @@ -1158,7 +1161,7 @@ public static function modelsAutoload($className) return false; } - if ( ! self::$_modelsDirectory) { + if (!self::$_modelsDirectory) { $loadedModels = self::$_loadedModelFiles; if (isset($loadedModels[$className]) && file_exists($loadedModels[$className])) { @@ -1167,7 +1170,7 @@ public static function modelsAutoload($className) return true; } } else { - $class = self::$_modelsDirectory . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; + $class = self::$_modelsDirectory.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $className).'.php'; if (file_exists($class)) { require $class; @@ -1180,10 +1183,11 @@ public static function modelsAutoload($className) } /** - * Load classes from the Doctrine extensions directory/path + * Load classes from the Doctrine extensions directory/path. * * @param string $className - * @return boolean + * + * @return bool */ public static function extensionsAutoload($className) { @@ -1192,10 +1196,11 @@ public static function extensionsAutoload($className) } $extensions = Doctrine_Manager::getInstance() - ->getExtensions(); + ->getExtensions() + ; foreach ($extensions as $name => $path) { - $class = $path . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; + $class = $path.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $className).'.php'; if (file_exists($class)) { require $class; @@ -1208,36 +1213,36 @@ public static function extensionsAutoload($className) } /** - * dumps a given variable + * dumps a given variable. + * + * @param mixed $var a variable of any type + * @param bool $output whether to output the content + * @param string $indent indention string * - * @param mixed $var a variable of any type - * @param boolean $output whether to output the content - * @param string $indent indention string * @return void|string */ - public static function dump($var, $output = true, $indent = "") + public static function dump($var, $output = true, $indent = '') { $ret = array(); switch (gettype($var)) { case 'array': $ret[] = 'Array('; - $indent .= " "; + $indent .= ' '; foreach ($var as $k => $v) { - - $ret[] = $indent . $k . ' : ' . self::dump($v, false, $indent); + $ret[] = $indent.$k.' : '.self::dump($v, false, $indent); } - $indent = substr($indent,0, -4); - $ret[] = $indent . ")"; + $indent = substr($indent, 0, -4); + $ret[] = $indent.')'; break; case 'object': - $ret[] = 'Object(' . get_class($var) . ')'; + $ret[] = 'Object('.get_class($var).')'; break; default: $ret[] = var_export($var, true); } if ($output) { - print implode("\n", $ret); + echo implode("\n", $ret); } return implode("\n", $ret); diff --git a/lib/Doctrine/Data.php b/lib/Doctrine/Data.php index b9bcd118d..46cc8d210 100644 --- a/lib/Doctrine/Data.php +++ b/lib/Doctrine/Data.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Data + * Doctrine_Data. * * Base Doctrine_Data class for dumping and loading data to and from fixtures files. * Support formats are based on what formats are available in Doctrine_Parser such as yaml, xml, json, etc. * - * @package Doctrine - * @subpackage Data * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2552 $ */ class Doctrine_Data { /** - * formats + * formats. * * array of formats data can be in * @@ -45,7 +45,7 @@ class Doctrine_Data protected $_formats = array('csv', 'yml', 'xml'); /** - * format + * format. * * the default and current format we are working with * @@ -54,16 +54,16 @@ class Doctrine_Data protected $_format = 'yml'; /** - * directory + * directory. * * array of directory/yml paths or single directory/yml file * * @var string */ - protected $_directory = null; + protected $_directory; /** - * models + * models. * * specified array of models to use * @@ -72,7 +72,7 @@ class Doctrine_Data protected $_models = array(); /** - * _exportIndividualFiles + * _exportIndividualFiles. * * whether or not to export data to individual files instead of 1 * @@ -83,12 +83,11 @@ class Doctrine_Data protected $_charset = 'UTF-8'; /** - * setFormat + * setFormat. * * Set the current format we are working with * * @param string $format - * @return void */ public function setFormat($format) { @@ -96,11 +95,9 @@ public function setFormat($format) } /** - * getFormat + * getFormat. * * Get the current format we are working with - * - * @return void */ public function getFormat() { @@ -108,11 +105,9 @@ public function getFormat() } /** - * getFormats + * getFormats. * * Get array of available formats - * - * @return void */ public function getFormats() { @@ -120,11 +115,9 @@ public function getFormats() } /** - * setDirectory + * setDirectory. * * Set the array/string of directories or yml file paths - * - * @return void */ public function setDirectory($directory) { @@ -132,11 +125,9 @@ public function setDirectory($directory) } /** - * getDirectory + * getDirectory. * * Get directory for dumping/loading data from and to - * - * @return void */ public function getDirectory() { @@ -144,12 +135,11 @@ public function getDirectory() } /** - * setModels + * setModels. * * Set the array of specified models to work with * * @param string $models - * @return void */ public function setModels($models) { @@ -157,11 +147,9 @@ public function setModels($models) } /** - * getModels + * getModels. * * Get the array of specified models to work with - * - * @return void */ public function getModels() { @@ -169,15 +157,17 @@ public function getModels() } /** - * _exportIndividualFiles + * _exportIndividualFiles. * * Set/Get whether or not to export individual files * + * @param mixed|null $bool + * * @return bool $_exportIndividualFiles */ public function exportIndividualFiles($bool = null) { - if ($bool !== null) { + if (null !== $bool) { $this->_exportIndividualFiles = $bool; } @@ -195,7 +185,7 @@ public function getCharset() } /** - * exportData + * exportData. * * Interface for exporting data to fixtures files from Doctrine models * @@ -203,7 +193,6 @@ public function getCharset() * @param string $format * @param string $models * @param string $_exportIndividualFiles - * @return void */ public function exportData($directory, $format = 'yml', $models = array(), $_exportIndividualFiles = false) { @@ -216,14 +205,13 @@ public function exportData($directory, $format = 'yml', $models = array(), $_exp } /** - * importData + * importData. * * Interface for importing data from fixture files to Doctrine models * * @param string $directory * @param string $format * @param string $models - * @return void */ public function importData($directory, $format = 'yml', $models = array(), $append = false, $charset = 'UTF-8') { @@ -236,13 +224,11 @@ public function importData($directory, $format = 'yml', $models = array(), $appe } /** - * isRelation + * isRelation. * * Check if a fieldName on a Doctrine_Record is a relation, if it is we return that relationData * - * @param string $Doctrine_Record * @param string $fieldName - * @return void */ public function isRelation(Doctrine_Record $record, $fieldName) { @@ -254,19 +240,17 @@ public function isRelation(Doctrine_Record $record, $fieldName) if ($relationData['local'] === $fieldName) { return $relationData; } - } return false; } /** - * purge + * purge. * * Purge all data for loaded models or for the passed array of Doctrine_Records * * @param string $models - * @return void */ public function purge($models = null) { @@ -278,7 +262,7 @@ public function purge($models = null) $connections = array(); foreach ($models as $model) { - $connections[Doctrine_Core::getTable($model)->getConnection()->getName()][] = $model; + $connections[Doctrine_Core::getTable($model)->getConnection()->getName()][] = $model; } foreach ($connections as $connection => $models) { diff --git a/lib/Doctrine/Data/Exception.php b/lib/Doctrine/Data/Exception.php index a59755781..42cc76309 100644 --- a/lib/Doctrine/Data/Exception.php +++ b/lib/Doctrine/Data/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Data_Exception + * Doctrine_Data_Exception. * - * @package Doctrine - * @subpackage Data * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2552 $ */ class Doctrine_Data_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Data/Export.php b/lib/Doctrine/Data/Export.php index 41dedfa82..9966c05c1 100644 --- a/lib/Doctrine/Data/Export.php +++ b/lib/Doctrine/Data/Export.php @@ -20,23 +20,22 @@ */ /** - * Doctrine_Data_Export + * Doctrine_Data_Export. * - * @package Doctrine - * @subpackage Data * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2552 $ */ class Doctrine_Data_Export extends Doctrine_Data { /** - * constructor + * constructor. * - * @param string $directory - * @return void + * @param string $directory */ public function __construct($directory) { @@ -44,18 +43,16 @@ public function __construct($directory) } /** - * doExport + * doExport. * - * FIXME: This function has ugly hacks in it for temporarily disabling INDEXBY query parts of tables + * FIXME: This function has ugly hacks in it for temporarily disabling INDEXBY query parts of tables * to export. * * Update from jwage: I am not sure if their is any other better solution for this. It may be the correct - * solution to disable the indexBy settings for tables when exporting data fixtures. Maybe a better idea - * would be to extract this functionality to a pair of functions to enable/disable the index by settings - * so simply turn them on and off when they need to query for the translations standalone and don't need + * solution to disable the indexBy settings for tables when exporting data fixtures. Maybe a better idea + * would be to extract this functionality to a pair of functions to enable/disable the index by settings + * so simply turn them on and off when they need to query for the translations standalone and don't need * it to be indexed by the lang. - * - * @return void */ public function doExport() { @@ -64,25 +61,25 @@ public function doExport() $data = array(); - // for situation when the $models array is empty, but the $specifiedModels array isn't + // for situation when the $models array is empty, but the $specifiedModels array isn't if (empty($models)) { - $models = $specifiedModels; + $models = $specifiedModels; } $models = Doctrine_Core::initializeModels($models); // temporarily disable indexBy query parts of selected and related tables $originalIndexBy = array(); - foreach ($models AS $name) { - $table = Doctrine_Core::getTable($name); - if ( !is_null($indexBy = $table->getBoundQueryPart('indexBy'))) { - $originalIndexBy[$name] = $indexBy; - $table->bindQueryPart('indexBy', null); - } + foreach ($models as $name) { + $table = Doctrine_Core::getTable($name); + if (!is_null($indexBy = $table->getBoundQueryPart('indexBy'))) { + $originalIndexBy[$name] = $indexBy; + $table->bindQueryPart('indexBy', null); + } } - foreach ($models AS $name) { - if ( ! empty($specifiedModels) AND ! in_array($name, $specifiedModels)) { + foreach ($models as $name) { + if (!empty($specifiedModels) and !in_array($name, $specifiedModels)) { continue; } @@ -94,7 +91,7 @@ public function doExport() } // Restore the temporarily disabled indexBy query parts - foreach($originalIndexBy AS $name => $indexBy) { + foreach ($originalIndexBy as $name => $indexBy) { Doctrine_Core::getTable($name)->bindQueryPart('indexBy', $indexBy); } @@ -104,12 +101,9 @@ public function doExport() } /** - * dumpData + * dumpData. * * Dump the prepared data to the fixtures files - * - * @param string $array - * @return void */ public function dumpData(array $data) { @@ -119,44 +113,46 @@ public function dumpData(array $data) if ($this->exportIndividualFiles()) { if (is_array($directory)) { throw new Doctrine_Data_Exception('You must specify a single path to a folder in order to export individual files.'); - } else if ( ! is_dir($directory) && is_file($directory)) { + } + if (!is_dir($directory) && is_file($directory)) { $directory = dirname($directory); } foreach ($data as $className => $classData) { - if ( ! empty($classData)) { + if (!empty($classData)) { Doctrine_Parser::dump(array($className => $classData), $format, $directory.DIRECTORY_SEPARATOR.$className.'.'.$format); } } } else { if (is_dir($directory)) { - $directory .= DIRECTORY_SEPARATOR . 'data.' . $format; + $directory .= DIRECTORY_SEPARATOR.'data.'.$format; } - if ( ! empty($data)) { + if (!empty($data)) { return Doctrine_Parser::dump($data, $format, $directory); } } } /** - * prepareData + * prepareData. * * Prepare the raw data to be exported with the parser * - * @param string $data + * @param string $data + * * @return array */ public function prepareData($data) { $preparedData = array(); - foreach ($data AS $className => $classData) { + foreach ($data as $className => $classData) { $preparedData[$className] = array(); $keyType = $classData->getTable()->getIdentifierType(); foreach ($classData as $record) { $className = get_class($record); - $recordKey = $className . '_' . implode('_', $record->identifier()); + $recordKey = $className.'_'.implode('_', $record->identifier()); $preparedData[$className][$recordKey] = array(); // skip single primary keys, we need to maintain composite primary keys @@ -165,11 +161,11 @@ public function prepareData($data) $recordData = $record->toArray(false); foreach ($recordData as $key => $value) { - if ( ! is_array($keys)) { - $keys = array($keys); + if (!is_array($keys)) { + $keys = array($keys); } - if ($keyType !== Doctrine_Core::IDENTIFIER_NATURAL && count($keys) <= 1 && in_array($key, $keys)) { + if (Doctrine_Core::IDENTIFIER_NATURAL !== $keyType && count($keys) <= 1 && in_array($key, $keys)) { continue; } @@ -179,11 +175,11 @@ public function prepareData($data) } if ($relation = $this->isRelation($record, $key)) { - if ( ! $value) { + if (!$value) { continue; } $relationAlias = $relation['alias']; - $relationRecord = $record->$relationAlias; + $relationRecord = $record->{$relationAlias}; // If collection then get first so we have an instance of the related record if ($relationRecord instanceof Doctrine_Collection) { @@ -191,23 +187,23 @@ public function prepareData($data) } // If relation is null or does not exist then continue - if ($relationRecord instanceof Doctrine_Null || ! $relationRecord) { + if ($relationRecord instanceof Doctrine_Null || !$relationRecord) { continue; } // Get class name for relation $relationClassName = get_class($relationRecord); - $relationValue = $relationClassName . '_' . $value; + $relationValue = $relationClassName.'_'.$value; $preparedData[$className][$recordKey][$relationAlias] = $relationValue; - } else if ($record->getTable()->hasField($key)) { + } elseif ($record->getTable()->hasField($key)) { $preparedData[$className][$recordKey][$key] = $value; } } } } - + return $preparedData; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Data/Import.php b/lib/Doctrine/Data/Import.php index 23d0f6079..20fc08f6c 100644 --- a/lib/Doctrine/Data/Import.php +++ b/lib/Doctrine/Data/Import.php @@ -20,69 +20,68 @@ */ /** - * Doctrine_Data_Import + * Doctrine_Data_Import. * - * @package Doctrine - * @package Data * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2552 $ */ class Doctrine_Data_Import extends Doctrine_Data { /** - * Array of imported objects for processing and saving + * Array of imported objects for processing and saving. * * @var array */ protected $_importedObjects = array(); /** - * Array of the raw data parsed from yaml + * Array of the raw data parsed from yaml. * * @var array */ protected $_rows = array(); /** - * Optionally pass the directory/path to the yaml for importing + * Optionally pass the directory/path to the yaml for importing. * * @param string $directory - * @return void */ public function __construct($directory = null) { - if ($directory !== null) { + if (null !== $directory) { $this->setDirectory($directory); } } /** - * Do the parsing of the yaml files and return the final parsed array + * Do the parsing of the yaml files and return the final parsed array. * * @return array $array */ public function doParsing() { $recursiveMerge = Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_RECURSIVE_MERGE_FIXTURES); - $mergeFunction = $recursiveMerge === true ? 'array_merge_recursive':'array_merge'; + $mergeFunction = true === $recursiveMerge ? 'array_merge_recursive' : 'array_merge'; $directory = $this->getDirectory(); $array = array(); - if ($directory !== null) { + if (null !== $directory) { foreach ((array) $directory as $dir) { $e = explode('.', $dir); // If they specified a specific yml file - if (end($e) == 'yml') { + if ('yml' == end($e)) { $array = $mergeFunction($array, Doctrine_Parser::load($dir, $this->getFormat(), $this->getCharset())); // If they specified a directory - } else if (is_dir($dir)) { + } elseif (is_dir($dir)) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), - RecursiveIteratorIterator::LEAVES_ONLY); + RecursiveIteratorIterator::LEAVES_ONLY); $filesOrdered = array(); foreach ($it as $file) { $filesOrdered[] = $file; @@ -103,15 +102,13 @@ public function doParsing() } /** - * Do the importing of the data parsed from the fixtures - * - * @return void + * Do the importing of the data parsed from the fixtures. */ public function doImport($append = false) { $array = $this->doParsing(); - if ( ! $append) { + if (!$append) { $this->purge(array_reverse(array_keys($array))); } @@ -119,9 +116,7 @@ public function doImport($append = false) } /** - * Recursively loop over all data fixtures and build the array of className rows - * - * @return void + * Recursively loop over all data fixtures and build the array of className rows. */ protected function _buildRows($className, $data) { @@ -132,14 +127,14 @@ protected function _buildRows($className, $data) $this->_rows[$className][$rowKey] = $row; foreach ((array) $row as $key => $value) { - if ($table->hasRelation($key) && is_array($value) && ! $table->hasTemplate('Doctrine_Template_I18n')) { + if ($table->hasRelation($key) && is_array($value) && !$table->hasTemplate('Doctrine_Template_I18n')) { // Skip associative arrays defining keys to relationships - if ( ! isset($value[0]) || (isset($value[0]) && is_array($value[0]))) { + if (!isset($value[0]) || (isset($value[0]) && is_array($value[0]))) { $rel = $table->getRelation($key); $relClassName = $rel->getTable()->getOption('name'); - $relRowKey = $rowKey . '_' . $relClassName; + $relRowKey = $rowKey.'_'.$relClassName; - if ($rel->getType() == Doctrine_Relation::ONE) { + if (Doctrine_Relation::ONE == $rel->getType()) { $val = array($relRowKey => $value); $this->_rows[$className][$rowKey][$key] = $relRowKey; } else { @@ -155,14 +150,12 @@ protected function _buildRows($className, $data) } /** - * Build the rows for nested set models - * - * @return void + * Build the rows for nested set models. */ protected function _buildNestedSetRows($className, $data) { foreach ($data as $rowKey => $row) { - $children = isset($row['children']) ? $row['children']:array(); + $children = isset($row['children']) ? $row['children'] : array(); unset($row['children']); $this->_rows[$className][$rowKey] = $row; @@ -172,123 +165,116 @@ protected function _buildNestedSetRows($className, $data) /** * Get the unsaved object for a specified row key and validate that it is the valid object class - * for the passed record and relation name + * for the passed record and relation name. + * + * @param string $rowKey + * @param string $relationName + * @param string $referringRowKey * - * @param string $rowKey - * @param Doctrine_Record $record - * @param string $relationName - * @param string $referringRowKey * @return Doctrine_Record + * * @throws Doctrine_Data_Exception */ protected function _getImportedObject($rowKey, Doctrine_Record $record, $relationName, $referringRowKey) { $relation = $record->getTable()->getRelation($relationName); - $rowKey = $this->_getRowKeyPrefix($relation->getTable()) . $rowKey; + $rowKey = $this->_getRowKeyPrefix($relation->getTable()).$rowKey; - if ( ! isset($this->_importedObjects[$rowKey])) { - throw new Doctrine_Data_Exception( - sprintf('Invalid row key specified: %s, referred to in %s', $rowKey, $referringRowKey) - ); + if (!isset($this->_importedObjects[$rowKey])) { + throw new Doctrine_Data_Exception(sprintf('Invalid row key specified: %s, referred to in %s', $rowKey, $referringRowKey)); } $relatedRowKeyObject = $this->_importedObjects[$rowKey]; $relationClass = $relation->getClass(); - if ( ! $relatedRowKeyObject instanceof $relationClass) { - throw new Doctrine_Data_Exception(sprintf( - 'Class referred to in "%s" is expected to be "%s" and "%s" was given', - $referringRowKey, $relation->getClass(), get_class($relatedRowKeyObject) - )); + if (!$relatedRowKeyObject instanceof $relationClass) { + throw new Doctrine_Data_Exception(sprintf('Class referred to in "%s" is expected to be "%s" and "%s" was given', $referringRowKey, $relation->getClass(), get_class($relatedRowKeyObject))); } return $relatedRowKeyObject; } /** - * Process a row and make all the appropriate relations between the imported data + * Process a row and make all the appropriate relations between the imported data. * * @param string $rowKey * @param string $row - * @return void */ protected function _processRow($rowKey, $row) { $obj = $this->_importedObjects[$rowKey]; foreach ((array) $row as $key => $value) { - if (method_exists($obj, 'set' . Doctrine_Inflector::classify($key))) { - $func = 'set' . Doctrine_Inflector::classify($key); - $obj->$func($value); - } else if ($obj->getTable()->hasField($key)) { - if ($obj->getTable()->getTypeOf($key) == 'object') { + if (method_exists($obj, 'set'.Doctrine_Inflector::classify($key))) { + $func = 'set'.Doctrine_Inflector::classify($key); + $obj->{$func}($value); + } elseif ($obj->getTable()->hasField($key)) { + if ('object' == $obj->getTable()->getTypeOf($key)) { $value = unserialize($value); } $obj->set($key, $value); - } else if ($obj->getTable()->hasRelation($key)) { + } elseif ($obj->getTable()->hasRelation($key)) { if (is_array($value)) { - if (isset($value[0]) && ! is_array($value[0])) { + if (isset($value[0]) && !is_array($value[0])) { foreach ($value as $link) { - if ($obj->getTable()->getRelation($key)->getType() === Doctrine_Relation::ONE) { + if (Doctrine_Relation::ONE === $obj->getTable()->getRelation($key)->getType()) { $obj->set($key, $this->_getImportedObject($link, $obj, $key, $rowKey)); - } else if ($obj->getTable()->getRelation($key)->getType() === Doctrine_Relation::MANY) { - $relation = $obj->$key; + } elseif (Doctrine_Relation::MANY === $obj->getTable()->getRelation($key)->getType()) { + $relation = $obj->{$key}; $relation[] = $this->_getImportedObject($link, $obj, $key, $rowKey); } } } else { - $obj->$key->fromArray($value); + $obj->{$key}->fromArray($value); } } else { $obj->set($key, $this->_getImportedObject($value, $obj, $key, $rowKey)); } } else { try { - $obj->$key = $value; + $obj->{$key} = $value; } catch (Exception $e) { // used for Doctrine plugin methods (Doctrine_Template) - if (is_callable(array($obj, 'set' . Doctrine_Inflector::classify($key)))) { - $func = 'set' . Doctrine_Inflector::classify($key); - $obj->$func($value); + if (is_callable(array($obj, 'set'.Doctrine_Inflector::classify($key)))) { + $func = 'set'.Doctrine_Inflector::classify($key); + $obj->{$func}($value); } else { - throw new Doctrine_Data_Exception('Invalid fixture element "'. $key . '" under "' . $rowKey . '"'); + throw new Doctrine_Data_Exception('Invalid fixture element "'.$key.'" under "'.$rowKey.'"'); } } } } } - /** - * NestedSet fixtures may come in a 'natural' format with nested children listed under a 'children' - * key or in a raw, non-nested format with lft/rgt values. - * - * This method returns true if the given $data is a nested set in 'natural' form. - * - * @param $className - * @param $data - * @return boolean - */ + /** + * NestedSet fixtures may come in a 'natural' format with nested children listed under a 'children' + * key or in a raw, non-nested format with lft/rgt values. + * + * This method returns true if the given $data is a nested set in 'natural' form. + * + * @return bool + */ protected function _hasNaturalNestedSetFormat($className, array &$data) { if (Doctrine_Core::getTable($className)->isTree()) { - if (isset($data['NestedSet']) && $data['NestedSet'] == true) { + if (isset($data['NestedSet']) && true == $data['NestedSet']) { unset($data['NestedSet']); + return true; - } else { - $first = current($data); - return array_key_exists('children', $first); } - } else { - return false; + $first = current($data); + + return array_key_exists('children', $first); } + + return false; } /** - * Perform the loading of the data from the passed array + * Perform the loading of the data from the passed array. * * @param string $array - * @return void */ protected function _loadData(array $array) { @@ -298,7 +284,7 @@ protected function _loadData(array $array) $rows = array(); foreach ($array as $className => $data) { - if ( ! empty($specifiedModels) && !in_array($className, $specifiedModels)) { + if (!empty($specifiedModels) && !in_array($className, $specifiedModels)) { continue; } @@ -316,14 +302,14 @@ protected function _loadData(array $array) foreach ($this->_rows as $className => $classRows) { $rowKeyPrefix = $this->_getRowKeyPrefix(Doctrine_Core::getTable($className)); foreach ($classRows as $rowKey => $row) { - $rowKey = $rowKeyPrefix . $rowKey; + $rowKey = $rowKeyPrefix.$rowKey; $buildRows[$rowKey] = $row; $this->_importedObjects[$rowKey] = new $className(); $this->_importedObjects[$rowKey]->state('TDIRTY'); } } - foreach($buildRows as $rowKey => $row) { + foreach ($buildRows as $rowKey => $row) { $this->_processRow($rowKey, $row); } @@ -341,7 +327,6 @@ protected function _loadData(array $array) $connection->beginTransaction(); foreach ($tree as $model) { foreach ($this->_importedObjects as $obj) { - if ($obj instanceof $model) { $obj->save(); } @@ -352,18 +337,17 @@ protected function _loadData(array $array) } /** - * Load nested set data for models with nested set enabled + * Load nested set data for models with nested set enabled. * * @param string $model * @param string $nestedSetData * @param string $parent - * @return void */ protected function _loadNestedSetData($model, $nestedSetData, $parent = null) { - foreach($nestedSetData AS $rowKey => $nestedSet) { + foreach ($nestedSetData as $rowKey => $nestedSet) { $children = array(); - $data = array(); + $data = array(); if (array_key_exists('children', $nestedSet)) { $children = (array) $nestedSet['children']; @@ -371,20 +355,20 @@ protected function _loadNestedSetData($model, $nestedSetData, $parent = null) unset($nestedSet['children']); } - $rowKey = $this->_getRowKeyPrefix(Doctrine_Core::getTable($model)) . $rowKey; + $rowKey = $this->_getRowKeyPrefix(Doctrine_Core::getTable($model)).$rowKey; $record = $this->_importedObjects[$rowKey]; // remove this nested set from _importedObjects so it's not processed in the save routine for normal objects unset($this->_importedObjects[$rowKey]); - if ( ! $parent) { + if (!$parent) { $record->save(); // save, so that createRoot can do: root id = id Doctrine_Core::getTable($model)->getTree()->createRoot($record); } else { $parent->getNode()->addChild($record); } - if (is_array($children) AND !empty($children)) { + if (is_array($children) and !empty($children)) { $this->_loadNestedSetData($model, $children, $record); } } @@ -393,7 +377,6 @@ protected function _loadNestedSetData($model, $nestedSetData, $parent = null) /** * Returns the prefix to use when indexing an object from the supplied table. * - * @param Doctrine_Table $table * @return string */ protected function _getRowKeyPrefix(Doctrine_Table $table) diff --git a/lib/Doctrine/DataDict.php b/lib/Doctrine/DataDict.php index 6b759259e..25bca80a8 100644 --- a/lib/Doctrine/DataDict.php +++ b/lib/Doctrine/DataDict.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_DataDict + * Doctrine_DataDict. * - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) */ @@ -35,20 +36,22 @@ class Doctrine_DataDict extends Doctrine_Connection_Module { /** * parseBoolean - * parses a literal boolean value and returns - * proper sql equivalent + * parses a literal boolean value and returns + * proper sql equivalent. * - * @param string $value boolean value to be parsed - * @return string parsed boolean value + * @param string $value boolean value to be parsed + * + * @return string parsed boolean value */ public function parseBoolean($value) { // parse booleans - if ($value == 'true') { + if ('true' == $value) { $value = 1; - } elseif ($value == 'false') { + } elseif ('false' == $value) { $value = 0; } + return $value; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/DataDict/Exception.php b/lib/Doctrine/DataDict/Exception.php index 41d07b4f6..edfad298c 100644 --- a/lib/Doctrine/DataDict/Exception.php +++ b/lib/Doctrine/DataDict/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_DataDict_Exception + * Doctrine_DataDict_Exception. * - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_DataDict_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/DataDict/Mssql.php b/lib/Doctrine/DataDict/Mssql.php index 59220b3a1..762badac8 100644 --- a/lib/Doctrine/DataDict/Mssql.php +++ b/lib/Doctrine/DataDict/Mssql.php @@ -20,15 +20,15 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @author Frank M. Kromann (PEAR MDB2 Mssql driver) * @author David Coallier (PEAR MDB2 Mssql driver) + * * @version $Revision: 7660 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Mssql extends Doctrine_DataDict @@ -37,9 +37,9 @@ class Doctrine_DataDict_Mssql extends Doctrine_DataDict * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -53,17 +53,18 @@ class Doctrine_DataDict_Mssql extends Doctrine_DataDict * Boolean flag that indicates whether this field is constrained * to not be set to null. * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration($field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } switch ($field['type']) { case 'enum': - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + // no break case 'array': case 'object': case 'text': @@ -74,25 +75,27 @@ public function getNativeDeclaration($field) $length = !empty($field['length']) ? $field['length'] : false; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || 'char' == $field['type']) ? true : false; return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$this->conn->varchar_max_length.')') : (($length && $length <= $this->conn->varchar_max_length) ? 'VARCHAR('.$length.')' : 'TEXT'); case 'clob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 8000) { return 'VARCHAR('.$length.')'; } - } - return 'TEXT'; + } + + return 'TEXT'; case 'blob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 8000) { - return "VARBINARY($length)"; + return "VARBINARY({$length})"; } } + return 'IMAGE'; case 'integer': case 'int': @@ -100,79 +103,84 @@ public function getNativeDeclaration($field) case 'boolean': return 'BIT'; case 'date': - return 'CHAR(' . strlen('YYYY-MM-DD') . ')'; + return 'CHAR('.strlen('YYYY-MM-DD').')'; case 'time': - return 'CHAR(' . strlen('HH:MM:SS') . ')'; + return 'CHAR('.strlen('HH:MM:SS').')'; case 'timestamp': - return 'CHAR(' . strlen('YYYY-MM-DD HH:MM:SS') . ')'; + return 'CHAR('.strlen('YYYY-MM-DD HH:MM:SS').')'; case 'float': return 'FLOAT'; case 'decimal': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'DECIMAL('.$length.','.$scale.')'; } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to a MDB2 datatype and length + * Maps a native array description of a field to a MDB2 datatype and length. + * + * @param array $field native field description * - * @param array $field native field description - * @return array containing the various possible types, length, sign, fixed + * @return array containing the various possible types, length, sign, fixed */ public function getPortableDeclaration($field) { - $db_type = preg_replace('/[\d\(\)]/','', strtolower($field['type']) ); - $length = (isset($field['length']) && $field['length'] > 0) ? $field['length'] : null; + $db_type = preg_replace('/[\d\(\)]/', '', strtolower($field['type'])); + $length = (isset($field['length']) && $field['length'] > 0) ? $field['length'] : null; $type = array(); // todo: unsigned handling seems to be missing $unsigned = $fixed = null; - if ( ! isset($field['name'])) + if (!isset($field['name'])) { $field['name'] = ''; + } switch ($db_type) { case 'bit': $type[0] = 'boolean'; - break; + break; case 'tinyint': case 'smallint': case 'bigint': case 'int': $type[0] = 'integer'; - if ($length == 1) { + if (1 == $length) { $type[] = 'boolean'; } - break; - case 'date': - $type[0] = 'date'; - break; + break; + case 'date': + $type[0] = 'date'; + break; case 'datetime': case 'timestamp': case 'smalldatetime': $type[0] = 'timestamp'; - break; + break; case 'float': case 'real': case 'numeric': $type[0] = 'float'; - break; + break; case 'decimal': case 'money': case 'smallmoney': $type[0] = 'decimal'; - break; + break; case 'text': case 'varchar': case 'ntext': case 'nvarchar': $fixed = false; + // no break case 'char': case 'nchar': $type[0] = 'string'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^[is|has]/', $field['name'])) { $type = array_reverse($type); @@ -180,45 +188,45 @@ public function getPortableDeclaration($field) } elseif (strstr($db_type, 'text')) { $type[] = 'clob'; } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } - break; + break; case 'image': case 'varbinary': $type[] = 'blob'; $length = null; - break; + break; case 'uniqueidentifier': $type[] = 'string'; $length = 36; - break; + break; case 'sql_variant': case 'sysname': case 'binary': $type[] = 'string'; $length = null; - break; + break; default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - return array('type' => $type, - 'length' => $length, - 'unsigned' => $unsigned, - 'fixed' => $fixed); + return array('type' => $type, + 'length' => $length, + 'unsigned' => $unsigned, + 'fixed' => $fixed); } /** * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param string $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: + * @param string $name name the field to be declared + * @param string $field associative array with the name of the properties + * of the field being declared as array indexes. + * Currently, the types of supported field + * properties are as follows: * * unsigned * Boolean flag that indicates whether the field @@ -232,16 +240,17 @@ public function getPortableDeclaration($field) * notnull * Boolean flag that indicates whether this field is * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getIntegerDeclaration($name, $field) { $default = $autoinc = ''; - if ( ! empty($field['autoincrement'])) { + if (!empty($field['autoincrement'])) { $autoinc = ' identity'; } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : 0; } @@ -251,23 +260,22 @@ public function getIntegerDeclaration($name, $field) // Name the constraint if a name has been supplied if (array_key_exists('defaultConstraintName', $field)) { - $default .= ' CONSTRAINT ' . $field['defaultConstraintName']; + $default .= ' CONSTRAINT '.$field['defaultConstraintName']; } - $default .= ' DEFAULT ' . $value; + $default .= ' DEFAULT '.$value; } - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ' NULL'; - //$unsigned = (isset($field['unsigned']) && $field['unsigned']) ? ' UNSIGNED' : ''; + // $unsigned = (isset($field['unsigned']) && $field['unsigned']) ? ' UNSIGNED' : ''; // MSSQL does not support the UNSIGNED keyword $unsigned = ''; - $comment = (isset($field['comment']) && $field['comment']) - ? " COMMENT " . $this->conn->quote($field['comment'], 'text') : ''; + $comment = (isset($field['comment']) && $field['comment']) + ? ' COMMENT '.$this->conn->quote($field['comment'], 'text') : ''; $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $this->getNativeDeclaration($field) . $unsigned - . $default . $notnull . $autoinc . $comment; + return $name.' '.$this->getNativeDeclaration($field).$unsigned + .$default.$notnull.$autoinc.$comment; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/DataDict/Mysql.php b/lib/Doctrine/DataDict/Mysql.php index 3bb9d26cc..067a26171 100644 --- a/lib/Doctrine/DataDict/Mysql.php +++ b/lib/Doctrine/DataDict/Mysql.php @@ -20,101 +20,101 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7635 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Mysql extends Doctrine_DataDict { protected $keywords = array( - 'ADD', 'ALL', 'ALTER', - 'ANALYZE', 'AND', 'AS', - 'ASC', 'ASENSITIVE', 'BEFORE', - 'BETWEEN', 'BIGINT', 'BINARY', - 'BLOB', 'BOTH', 'BY', 'BIT', - 'CALL', 'CASCADE', 'CASE', - 'CHANGE', 'CHAR', 'CHARACTER', - 'CHECK', 'COLLATE', 'COLUMN', - 'CONDITION', 'CONNECTION', 'CONSTRAINT', - 'CONTINUE', 'CONVERT', 'CREATE', - 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', - 'DATABASE', 'DATABASES', 'DAY_HOUR', - 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', - 'DEC', 'DECIMAL', 'DECLARE', - 'DEFAULT', 'DELAYED', 'DELETE', - 'DESC', 'DESCRIBE', 'DETERMINISTIC', - 'DISTINCT', 'DISTINCTROW', 'DIV', - 'DOUBLE', 'DROP', 'DUAL', - 'EACH', 'ELSE', 'ELSEIF', - 'ENCLOSED', 'ESCAPED', 'EXISTS', - 'EXIT', 'EXPLAIN', 'FALSE', - 'FETCH', 'FLOAT', 'FLOAT4', - 'FLOAT8', 'FOR', 'FORCE', - 'FOREIGN', 'FROM', 'FULLTEXT', - 'GRANT', 'GROUP', 'HAVING', - 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', - 'HOUR_SECOND', 'IF', 'IGNORE', - 'IN', 'INDEX', 'INFILE', - 'INNER', 'INOUT', 'INSENSITIVE', - 'INSERT', 'INT', 'INT1', - 'INT2', 'INT3', 'INT4', - 'INT8', 'INTEGER', 'INTERVAL', - 'INTO', 'IS', 'ITERATE', - 'JOIN', 'KEY', 'KEYS', - 'KILL', 'LEADING', 'LEAVE', - 'LEFT', 'LIKE', 'LIMIT', - 'LINES', 'LOAD', 'LOCALTIME', - 'LOCALTIMESTAMP', 'LOCK', 'LONG', - 'LONGBLOB', 'LONGTEXT', 'LOOP', - 'LOW_PRIORITY', 'MATCH', 'MEDIUMBLOB', - 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', - 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', - 'MODIFIES', 'NATURAL', 'NOT', - 'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC', - 'ON', 'OPTIMIZE', 'OPTION', - 'OPTIONALLY', 'OR', 'ORDER', - 'OUT', 'OUTER', 'OUTFILE', - 'PRECISION', 'PRIMARY', 'PROCEDURE', - 'PURGE', 'RAID0', 'READ', - 'READS', 'REAL', 'REFERENCES', - 'REGEXP', 'RELEASE', 'RENAME', - 'REPEAT', 'REPLACE', 'REQUIRE', - 'RESTRICT', 'RETURN', 'REVOKE', - 'RIGHT', 'RLIKE', 'SCHEMA', - 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', - 'SENSITIVE', 'SEPARATOR', 'SET', - 'SHOW', 'SMALLINT', 'SONAME', - 'SPATIAL', 'SPECIFIC', 'SQL', - 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', - 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', - 'SSL', 'STARTING', 'STRAIGHT_JOIN', - 'TABLE', 'TERMINATED', 'THEN', - 'TINYBLOB', 'TINYINT', 'TINYTEXT', - 'TO', 'TRAILING', 'TRIGGER', - 'TRUE', 'UNDO', 'UNION', - 'UNIQUE', 'UNLOCK', 'UNSIGNED', - 'UPDATE', 'USAGE', 'USE', - 'USING', 'UTC_DATE', 'UTC_TIME', - 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', - 'VARCHAR', 'VARCHARACTER', 'VARYING', - 'WHEN', 'WHERE', 'WHILE', - 'WITH', 'WRITE', 'X509', - 'XOR', 'YEAR_MONTH', 'ZEROFILL' - ); + 'ADD', 'ALL', 'ALTER', + 'ANALYZE', 'AND', 'AS', + 'ASC', 'ASENSITIVE', 'BEFORE', + 'BETWEEN', 'BIGINT', 'BINARY', + 'BLOB', 'BOTH', 'BY', 'BIT', + 'CALL', 'CASCADE', 'CASE', + 'CHANGE', 'CHAR', 'CHARACTER', + 'CHECK', 'COLLATE', 'COLUMN', + 'CONDITION', 'CONNECTION', 'CONSTRAINT', + 'CONTINUE', 'CONVERT', 'CREATE', + 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', + 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', + 'DATABASE', 'DATABASES', 'DAY_HOUR', + 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', + 'DEC', 'DECIMAL', 'DECLARE', + 'DEFAULT', 'DELAYED', 'DELETE', + 'DESC', 'DESCRIBE', 'DETERMINISTIC', + 'DISTINCT', 'DISTINCTROW', 'DIV', + 'DOUBLE', 'DROP', 'DUAL', + 'EACH', 'ELSE', 'ELSEIF', + 'ENCLOSED', 'ESCAPED', 'EXISTS', + 'EXIT', 'EXPLAIN', 'FALSE', + 'FETCH', 'FLOAT', 'FLOAT4', + 'FLOAT8', 'FOR', 'FORCE', + 'FOREIGN', 'FROM', 'FULLTEXT', + 'GRANT', 'GROUP', 'HAVING', + 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', + 'HOUR_SECOND', 'IF', 'IGNORE', + 'IN', 'INDEX', 'INFILE', + 'INNER', 'INOUT', 'INSENSITIVE', + 'INSERT', 'INT', 'INT1', + 'INT2', 'INT3', 'INT4', + 'INT8', 'INTEGER', 'INTERVAL', + 'INTO', 'IS', 'ITERATE', + 'JOIN', 'KEY', 'KEYS', + 'KILL', 'LEADING', 'LEAVE', + 'LEFT', 'LIKE', 'LIMIT', + 'LINES', 'LOAD', 'LOCALTIME', + 'LOCALTIMESTAMP', 'LOCK', 'LONG', + 'LONGBLOB', 'LONGTEXT', 'LOOP', + 'LOW_PRIORITY', 'MATCH', 'MEDIUMBLOB', + 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', + 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', + 'MODIFIES', 'NATURAL', 'NOT', + 'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC', + 'ON', 'OPTIMIZE', 'OPTION', + 'OPTIONALLY', 'OR', 'ORDER', + 'OUT', 'OUTER', 'OUTFILE', + 'PRECISION', 'PRIMARY', 'PROCEDURE', + 'PURGE', 'RAID0', 'READ', + 'READS', 'REAL', 'REFERENCES', + 'REGEXP', 'RELEASE', 'RENAME', + 'REPEAT', 'REPLACE', 'REQUIRE', + 'RESTRICT', 'RETURN', 'REVOKE', + 'RIGHT', 'RLIKE', 'SCHEMA', + 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', + 'SENSITIVE', 'SEPARATOR', 'SET', + 'SHOW', 'SMALLINT', 'SONAME', + 'SPATIAL', 'SPECIFIC', 'SQL', + 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', + 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', + 'SSL', 'STARTING', 'STRAIGHT_JOIN', + 'TABLE', 'TERMINATED', 'THEN', + 'TINYBLOB', 'TINYINT', 'TINYTEXT', + 'TO', 'TRAILING', 'TRIGGER', + 'TRUE', 'UNDO', 'UNION', + 'UNIQUE', 'UNLOCK', 'UNSIGNED', + 'UPDATE', 'USAGE', 'USE', + 'USING', 'UTC_DATE', 'UTC_TIME', + 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', + 'VARCHAR', 'VARCHARACTER', 'VARYING', + 'WHEN', 'WHERE', 'WHILE', + 'WITH', 'WRITE', 'X509', + 'XOR', 'YEAR_MONTH', 'ZEROFILL', + ); /** * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -128,44 +128,48 @@ class Doctrine_DataDict_Mysql extends Doctrine_DataDict * Boolean flag that indicates whether this field is constrained * to not be set to null. * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration($field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } switch ($field['type']) { case 'char': - $length = ( ! empty($field['length'])) ? $field['length'] : false; + $length = (!empty($field['length'])) ? $field['length'] : false; return $length ? 'CHAR('.$length.')' : 'CHAR(255)'; case 'enum': if ($this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) { $values = array(); foreach ($field['values'] as $value) { - $values[] = $this->conn->quote($value, 'varchar'); + $values[] = $this->conn->quote($value, 'varchar'); } + return 'ENUM('.implode(', ', $values).')'; - } else { - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; } + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + + // no break case 'set': if ($this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_SET)) { $values = array(); foreach ($field['values'] as $value) { $values[] = $this->conn->quote($value, 'varchar'); } + return 'SET('.implode(', ', $values).')'; - } else { - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; } + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + + // no break case 'varchar': case 'string': case 'gzip': - if ( ! isset($field['length'])) { + if (!isset($field['length'])) { if (array_key_exists('default', $field)) { $field['length'] = $this->conn->varchar_max_length; } else { @@ -174,52 +178,63 @@ public function getNativeDeclaration($field) } $length = ($field['length'] <= $this->conn->varchar_max_length) ? $field['length'] : false; - $fixed = (isset($field['fixed'])) ? $field['fixed'] : false; + $fixed = (isset($field['fixed'])) ? $field['fixed'] : false; - return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)') - : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT'); + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)') + : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); case 'array': case 'object': case 'clob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 255) { return 'TINYTEXT'; - } elseif ($length <= 65532) { + } + if ($length <= 65532) { return 'TEXT'; - } elseif ($length <= 16777215) { + } + if ($length <= 16777215) { return 'MEDIUMTEXT'; } } + return 'LONGTEXT'; case 'blob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 255) { return 'TINYBLOB'; - } elseif ($length <= 65532) { + } + if ($length <= 65532) { return 'BLOB'; - } elseif ($length <= 16777215) { + } + if ($length <= 16777215) { return 'MEDIUMBLOB'; } } + return 'LONGBLOB'; case 'integer': case 'int': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 1) { return 'TINYINT'; - } elseif ($length == 2) { + } + if (2 == $length) { return 'SMALLINT'; - } elseif ($length == 3) { + } + if (3 == $length) { return 'MEDIUMINT'; - } elseif ($length == 4) { + } + if (4 == $length) { return 'INT'; - } elseif ($length > 4) { + } + if ($length > 4) { return 'BIGINT'; } } + return 'INT'; case 'boolean': return 'TINYINT(1)'; @@ -232,32 +247,37 @@ public function getNativeDeclaration($field) case 'float': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'FLOAT('.$length.', '.$scale.')'; case 'double': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'DOUBLE('.$length.', '.$scale.')'; case 'decimal': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'DECIMAL('.$length.', '.$scale.')'; case 'bit': return 'BIT'; } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to a MDB2 datatype and length + * Maps a native array description of a field to a MDB2 datatype and length. + * + * @param array $field native field description * - * @param array $field native field description * @return array containing the various possible types, length, sign, fixed */ public function getPortableDeclaration(array $field) { $dbType = strtolower($field['type']); $dbType = strtok($dbType, '(), '); - if ($dbType == 'national') { + if ('national' == $dbType) { $dbType = strtok('(), '); } if (isset($field['length'])) { @@ -266,14 +286,14 @@ public function getPortableDeclaration(array $field) } else { $length = strtok('(), '); $decimal = strtok('(), '); - if ( ! $decimal ) { + if (!$decimal) { $decimal = null; } } $type = array(); $unsigned = $fixed = null; - if ( ! isset($field['name'])) { + if (!isset($field['name'])) { $field['name'] = ''; } @@ -289,28 +309,28 @@ public function getPortableDeclaration(array $field) } $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 1; - break; + break; case 'smallint': $type[] = 'integer'; $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 2; - break; + break; case 'mediumint': $type[] = 'integer'; $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 3; - break; + break; case 'int': case 'integer': $type[] = 'integer'; $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 4; - break; + break; case 'bigint': $type[] = 'integer'; $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 8; - break; + break; case 'tinytext': case 'mediumtext': case 'longtext': @@ -318,24 +338,25 @@ public function getPortableDeclaration(array $field) case 'text': case 'varchar': $fixed = false; + // no break case 'string': case 'char': $type[] = 'string'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); } } elseif (strstr($dbType, 'text')) { $type[] = 'clob'; - if ($decimal == 'binary') { + if ('binary' == $decimal) { $type[] = 'blob'; } } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } - break; + break; case 'enum': $type[] = 'enum'; preg_match_all('/\'((?:\'\'|[^\'])*)\'/', $field['type'], $matches); @@ -346,7 +367,7 @@ public function getPortableDeclaration(array $field) $value = str_replace('\'\'', '\'', $value); $length = max($length, strlen($value)); } - if ($length == '1' && count($matches[1]) == 2) { + if ('1' == $length && 2 == count($matches[1])) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); @@ -361,35 +382,36 @@ public function getPortableDeclaration(array $field) $fixed = false; $type[] = 'text'; $type[] = 'integer'; - break; + break; case 'date': $type[] = 'date'; $length = null; - break; + break; case 'datetime': case 'timestamp': $type[] = 'timestamp'; $length = null; - break; + break; case 'time': $type[] = 'time'; $length = null; - break; + break; case 'float': case 'double': case 'real': $type[] = 'float'; $unsigned = preg_match('/ unsigned/i', $field['type']); - break; + break; case 'unknown': case 'decimal': - if ($decimal !== null) { + if (null !== $decimal) { $scale = $decimal; } + // no break case 'numeric': $type[] = 'decimal'; $unsigned = preg_match('/ unsigned/i', $field['type']); - break; + break; case 'tinyblob': case 'mediumblob': case 'longblob': @@ -398,15 +420,15 @@ public function getPortableDeclaration(array $field) case 'varbinary': $type[] = 'blob'; $length = null; - break; + break; case 'year': $type[] = 'integer'; $type[] = 'date'; $length = null; - break; + break; case 'bit': $type[] = 'bit'; - break; + break; case 'geometry': case 'geometrycollection': case 'point': @@ -417,20 +439,21 @@ public function getPortableDeclaration(array $field) case 'multipolygon': $type[] = 'blob'; $length = null; - break; + break; default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - $length = ((int) $length == 0) ? null : (int) $length; - $def = array('type' => $type, 'length' => $length, 'unsigned' => $unsigned, 'fixed' => $fixed); - if ($values !== null) { + $length = (0 == (int) $length) ? null : (int) $length; + $def = array('type' => $type, 'length' => $length, 'unsigned' => $unsigned, 'fixed' => $fixed); + if (null !== $values) { $def['values'] = $values; } - if ($scale !== null) { + if (null !== $scale) { $def['scale'] = $scale; } + return $def; } @@ -438,37 +461,39 @@ public function getPortableDeclaration(array $field) * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET * of a field declaration to be used in statements like CREATE TABLE. * - * @param string $charset name of the charset - * @return string DBMS specific SQL code portion needed to set the CHARACTER SET - * of a field declaration. + * @param string $charset name of the charset + * + * @return string DBMS specific SQL code portion needed to set the CHARACTER SET + * of a field declaration */ public function getCharsetFieldDeclaration($charset) { - return 'CHARACTER SET ' . $charset; + return 'CHARACTER SET '.$charset; } /** * Obtain DBMS specific SQL code portion needed to set the COLLATION * of a field declaration to be used in statements like CREATE TABLE. * - * @param string $collation name of the collation - * @return string DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration. + * @param string $collation name of the collation + * + * @return string DBMS specific SQL code portion needed to set the COLLATION + * of a field declaration */ public function getCollationFieldDeclaration($collation) { - return 'COLLATE ' . $collation; + return 'COLLATE '.$collation; } /** * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param string $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: + * @param string $name name the field to be declared + * @param string $field associative array with the name of the properties + * of the field being declared as array indexes. + * Currently, the types of supported field + * properties are as follows: * * unsigned * Boolean flag that indicates whether the field @@ -482,33 +507,34 @@ public function getCollationFieldDeclaration($collation) * notnull * Boolean flag that indicates whether this field is * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getIntegerDeclaration($name, $field) { $unique = (isset($field['unique']) && $field['unique']) ? ' UNIQUE' : ''; $default = $autoinc = ''; - if ( ! empty($field['autoincrement'])) { + if (!empty($field['autoincrement'])) { $autoinc = ' AUTO_INCREMENT'; } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : 0; } - $default = ' DEFAULT ' . (is_null($field['default']) + $default = ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'])); } - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; + $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; $unsigned = (isset($field['unsigned']) && $field['unsigned']) ? ' UNSIGNED' : ''; - $comment = (isset($field['comment']) && $field['comment']) - ? " COMMENT " . $this->conn->quote($field['comment'], 'text') : ''; + $comment = (isset($field['comment']) && $field['comment']) + ? ' COMMENT '.$this->conn->quote($field['comment'], 'text') : ''; $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $this->getNativeDeclaration($field) . $unsigned - . $default . $unique . $notnull . $autoinc . $comment; + return $name.' '.$this->getNativeDeclaration($field).$unsigned + .$default.$unique.$notnull.$autoinc.$comment; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/DataDict/Oracle.php b/lib/Doctrine/DataDict/Oracle.php index c47a296d4..b7efae5f9 100644 --- a/lib/Doctrine/DataDict/Oracle.php +++ b/lib/Doctrine/DataDict/Oracle.php @@ -20,12 +20,12 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Oracle extends Doctrine_DataDict @@ -34,9 +34,9 @@ class Doctrine_DataDict_Oracle extends Doctrine_DataDict * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -49,17 +49,19 @@ class Doctrine_DataDict_Oracle extends Doctrine_DataDict * notnull * Boolean flag that indicates whether this field is constrained * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration(array $field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } switch ($field['type']) { case 'enum': - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + // no break case 'string': case 'array': case 'object': @@ -68,36 +70,42 @@ public function getNativeDeclaration(array $field) case 'varchar': $length = !empty($field['length']) ? $field['length'] : false; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; - + $fixed = ((isset($field['fixed']) && $field['fixed']) || 'char' == $field['type']) ? true : false; + $unit = $this->conn->getParam('char_unit'); - $unit = ! is_null($unit) ? ' '.$unit : ''; + $unit = !is_null($unit) ? ' '.$unit : ''; if ($length && $length <= $this->conn->getParam('varchar2_max_length')) { return $fixed ? 'CHAR('.$length.$unit.')' : 'VARCHAR2('.$length.$unit.')'; } + // no break case 'clob': return 'CLOB'; case 'blob': return 'BLOB'; case 'integer': case 'int': - $length = (!empty($field['length'])) ? $field['length'] : false; - if ( $length && $length <= $this->conn->number_max_precision) { - if ($length <= 1) { - return 'NUMBER(3)'; // TINYINT, unsigned max. 256 - } elseif ($length == 2) { - return 'NUMBER(5)'; // SMALLINT, unsigend max. 65.536 - } elseif ($length == 3) { - return 'NUMBER(8)'; // MEDIUMINT, unsigned max. 16.777.216 - } elseif ($length == 4) { - return 'NUMBER(10)'; // INTEGER, unsigend max. 4.294.967.296 - } elseif ($length <= 8) { - return 'NUMBER(20)'; // BIGINT, unsigend max. 18.446.744.073.709.551.616 - } else { - return 'INTEGER'; - } - } + $length = (!empty($field['length'])) ? $field['length'] : false; + if ($length && $length <= $this->conn->number_max_precision) { + if ($length <= 1) { + return 'NUMBER(3)'; // TINYINT, unsigned max. 256 + } + if (2 == $length) { + return 'NUMBER(5)'; // SMALLINT, unsigend max. 65.536 + } + if (3 == $length) { + return 'NUMBER(8)'; // MEDIUMINT, unsigned max. 16.777.216 + } + if (4 == $length) { + return 'NUMBER(10)'; // INTEGER, unsigend max. 4.294.967.296 + } + if ($length <= 8) { + return 'NUMBER(20)'; // BIGINT, unsigend max. 18.446.744.073.709.551.616 + } + + return 'INTEGER'; + } + return 'INTEGER'; case 'boolean': return 'NUMBER(1)'; @@ -110,33 +118,37 @@ public function getNativeDeclaration(array $field) return 'NUMBER'; case 'decimal': $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'NUMBER(*,'.$scale.')'; default: } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to a doctrine datatype and length + * Maps a native array description of a field to a doctrine datatype and length. + * + * @param array $field native field description * - * @param array $field native field description * @return array containing the various possible types, length, sign, fixed + * * @throws Doctrine_DataDict_Oracle_Exception */ public function getPortableDeclaration(array $field) { - if ( ! isset($field['data_type'])) { + if (!isset($field['data_type'])) { throw new Doctrine_DataDict_Exception('Native oracle definition must have a data_type key specified'); } - + $dbType = strtolower($field['data_type']); $type = array(); $length = $unsigned = $fixed = null; - if ( ! empty($field['data_length'])) { - $length = (int)$field['data_length']; + if (!empty($field['data_length'])) { + $length = (int) $field['data_length']; } - if ( ! isset($field['column_name'])) { + if (!isset($field['column_name'])) { $field['column_name'] = ''; } @@ -145,7 +157,7 @@ public function getPortableDeclaration(array $field) case 'pls_integer': case 'binary_integer': $type[] = 'integer'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/i', $field['column_name'])) { $type = array_reverse($type); @@ -156,16 +168,17 @@ public function getPortableDeclaration(array $field) case 'varchar2': case 'nvarchar2': $fixed = false; + // no break case 'char': case 'nchar': $type[] = 'string'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/i', $field['column_name'])) { $type = array_reverse($type); } } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } break; @@ -178,32 +191,33 @@ public function getPortableDeclaration(array $field) $type[] = 'float'; break; case 'number': - if ( ! empty($field['data_scale'])) { + if (!empty($field['data_scale'])) { $type[] = 'decimal'; } else { $type[] = 'integer'; - if ((int)$length == '1') { + if ('1' == (int) $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/i', $field['column_name'])) { $type = array_reverse($type); } else { - $length = 1; //TINYINT + $length = 1; // TINYINT } - } elseif ( ! is_null($length) && (int)$length <= 3) { // TINYINT + } elseif (!is_null($length) && (int) $length <= 3) { // TINYINT $length = 1; - } elseif ( ! is_null($length) && (int)$length <= 5) { // SMALLINT + } elseif (!is_null($length) && (int) $length <= 5) { // SMALLINT $length = 2; - } elseif ( ! is_null($length) && (int)$length <= 8) { // MEDIUMINT + } elseif (!is_null($length) && (int) $length <= 8) { // MEDIUMINT $length = 3; - } elseif ( ! is_null($length) && (int)$length <= 10) { // INT + } elseif (!is_null($length) && (int) $length <= 10) { // INT $length = 4; - } elseif ( ! is_null($length) && (int)$length <= 20) { //BIGINT + } elseif (!is_null($length) && (int) $length <= 20) { // BIGINT $length = 8; } } break; case 'long': $type[] = 'string'; + // no break case 'clob': case 'nclob': $type[] = 'clob'; @@ -214,17 +228,17 @@ public function getPortableDeclaration(array $field) case 'bfile': $type[] = 'blob'; $length = null; - break; + break; case 'rowid': case 'urowid': default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - return array('type' => $type, - 'length' => $length, - 'unsigned' => $unsigned, - 'fixed' => $fixed); + return array('type' => $type, + 'length' => $length, + 'unsigned' => $unsigned, + 'fixed' => $fixed); } } diff --git a/lib/Doctrine/DataDict/Pgsql.php b/lib/Doctrine/DataDict/Pgsql.php index da1cc9e54..c8a554bc5 100644 --- a/lib/Doctrine/DataDict/Pgsql.php +++ b/lib/Doctrine/DataDict/Pgsql.php @@ -20,327 +20,327 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Paul Cooper * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7641 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Pgsql extends Doctrine_DataDict { /** - * @param array $reservedKeyWords an array of reserved keywords by pgsql + * @param array $reservedKeyWords an array of reserved keywords by pgsql */ protected static $reservedKeyWords = array( - 'abort', - 'absolute', - 'access', - 'action', - 'add', - 'after', - 'aggregate', - 'all', - 'alter', - 'analyse', - 'analyze', - 'and', - 'any', - 'as', - 'asc', - 'assertion', - 'assignment', - 'at', - 'authorization', - 'backward', - 'before', - 'begin', - 'between', - 'bigint', - 'binary', - 'bit', - 'boolean', - 'both', - 'by', - 'cache', - 'called', - 'cascade', - 'case', - 'cast', - 'chain', - 'char', - 'character', - 'characteristics', - 'check', - 'checkpoint', - 'class', - 'close', - 'cluster', - 'coalesce', - 'collate', - 'column', - 'comment', - 'commit', - 'committed', - 'constraint', - 'constraints', - 'conversion', - 'convert', - 'copy', - 'create', - 'createdb', - 'createuser', - 'cross', - 'current_date', - 'current_time', - 'current_timestamp', - 'current_user', - 'cursor', - 'cycle', - 'database', - 'day', - 'deallocate', - 'dec', - 'decimal', - 'declare', - 'default', - 'deferrable', - 'deferred', - 'definer', - 'delete', - 'delimiter', - 'delimiters', - 'desc', - 'distinct', - 'do', - 'domain', - 'double', - 'drop', - 'each', - 'else', - 'encoding', - 'encrypted', - 'end', - 'escape', - 'except', - 'exclusive', - 'execute', - 'exists', - 'explain', - 'external', - 'extract', - 'false', - 'fetch', - 'float', - 'for', - 'force', - 'foreign', - 'forward', - 'freeze', - 'from', - 'full', - 'function', - 'get', - 'global', - 'grant', - 'group', - 'handler', - 'having', - 'hour', - 'ilike', - 'immediate', - 'immutable', - 'implicit', - 'in', - 'increment', - 'index', - 'inherits', - 'initially', - 'inner', - 'inout', - 'input', - 'insensitive', - 'insert', - 'instead', - 'int', - 'integer', - 'intersect', - 'interval', - 'into', - 'invoker', - 'is', - 'isnull', - 'isolation', - 'join', - 'key', - 'lancompiler', - 'language', - 'leading', - 'left', - 'level', - 'like', - 'limit', - 'listen', - 'load', - 'local', - 'localtime', - 'localtimestamp', - 'location', - 'lock', - 'match', - 'maxvalue', - 'minute', - 'minvalue', - 'mode', - 'month', - 'move', - 'names', - 'national', - 'natural', - 'nchar', - 'new', - 'next', - 'no', - 'nocreatedb', - 'nocreateuser', - 'none', - 'not', - 'nothing', - 'notify', - 'notnull', - 'null', - 'nullif', - 'numeric', - 'of', - 'off', - 'offset', - 'oids', - 'old', - 'on', - 'only', - 'operator', - 'option', - 'or', - 'order', - 'out', - 'outer', - 'overlaps', - 'overlay', - 'owner', - 'partial', - 'password', - 'path', - 'pendant', - 'placing', - 'position', - 'precision', - 'prepare', - 'primary', - 'prior', - 'privileges', - 'procedural', - 'procedure', - 'read', - 'real', - 'recheck', - 'references', - 'reindex', - 'relative', - 'rename', - 'replace', - 'reset', - 'restrict', - 'returns', - 'revoke', - 'right', - 'rollback', - 'row', - 'rule', - 'schema', - 'scroll', - 'second', - 'security', - 'select', - 'sequence', - 'serializable', - 'session', - 'session_user', - 'set', - 'setof', - 'share', - 'show', - 'similar', - 'simple', - 'smallint', - 'some', - 'stable', - 'start', - 'statement', - 'statistics', - 'stdin', - 'stdout', - 'storage', - 'strict', - 'substring', - 'sysid', - 'table', - 'temp', - 'template', - 'temporary', - 'then', - 'time', - 'timestamp', - 'to', - 'toast', - 'trailing', - 'transaction', - 'treat', - 'trigger', - 'trim', - 'true', - 'truncate', - 'trusted', - 'type', - 'unencrypted', - 'union', - 'unique', - 'unknown', - 'unlisten', - 'until', - 'update', - 'usage', - 'user', - 'using', - 'vacuum', - 'valid', - 'validator', - 'values', - 'varchar', - 'varying', - 'verbose', - 'version', - 'view', - 'volatile', - 'when', - 'where', - 'with', - 'without', - 'work', - 'write', - 'year', - 'zone' - ); + 'abort', + 'absolute', + 'access', + 'action', + 'add', + 'after', + 'aggregate', + 'all', + 'alter', + 'analyse', + 'analyze', + 'and', + 'any', + 'as', + 'asc', + 'assertion', + 'assignment', + 'at', + 'authorization', + 'backward', + 'before', + 'begin', + 'between', + 'bigint', + 'binary', + 'bit', + 'boolean', + 'both', + 'by', + 'cache', + 'called', + 'cascade', + 'case', + 'cast', + 'chain', + 'char', + 'character', + 'characteristics', + 'check', + 'checkpoint', + 'class', + 'close', + 'cluster', + 'coalesce', + 'collate', + 'column', + 'comment', + 'commit', + 'committed', + 'constraint', + 'constraints', + 'conversion', + 'convert', + 'copy', + 'create', + 'createdb', + 'createuser', + 'cross', + 'current_date', + 'current_time', + 'current_timestamp', + 'current_user', + 'cursor', + 'cycle', + 'database', + 'day', + 'deallocate', + 'dec', + 'decimal', + 'declare', + 'default', + 'deferrable', + 'deferred', + 'definer', + 'delete', + 'delimiter', + 'delimiters', + 'desc', + 'distinct', + 'do', + 'domain', + 'double', + 'drop', + 'each', + 'else', + 'encoding', + 'encrypted', + 'end', + 'escape', + 'except', + 'exclusive', + 'execute', + 'exists', + 'explain', + 'external', + 'extract', + 'false', + 'fetch', + 'float', + 'for', + 'force', + 'foreign', + 'forward', + 'freeze', + 'from', + 'full', + 'function', + 'get', + 'global', + 'grant', + 'group', + 'handler', + 'having', + 'hour', + 'ilike', + 'immediate', + 'immutable', + 'implicit', + 'in', + 'increment', + 'index', + 'inherits', + 'initially', + 'inner', + 'inout', + 'input', + 'insensitive', + 'insert', + 'instead', + 'int', + 'integer', + 'intersect', + 'interval', + 'into', + 'invoker', + 'is', + 'isnull', + 'isolation', + 'join', + 'key', + 'lancompiler', + 'language', + 'leading', + 'left', + 'level', + 'like', + 'limit', + 'listen', + 'load', + 'local', + 'localtime', + 'localtimestamp', + 'location', + 'lock', + 'match', + 'maxvalue', + 'minute', + 'minvalue', + 'mode', + 'month', + 'move', + 'names', + 'national', + 'natural', + 'nchar', + 'new', + 'next', + 'no', + 'nocreatedb', + 'nocreateuser', + 'none', + 'not', + 'nothing', + 'notify', + 'notnull', + 'null', + 'nullif', + 'numeric', + 'of', + 'off', + 'offset', + 'oids', + 'old', + 'on', + 'only', + 'operator', + 'option', + 'or', + 'order', + 'out', + 'outer', + 'overlaps', + 'overlay', + 'owner', + 'partial', + 'password', + 'path', + 'pendant', + 'placing', + 'position', + 'precision', + 'prepare', + 'primary', + 'prior', + 'privileges', + 'procedural', + 'procedure', + 'read', + 'real', + 'recheck', + 'references', + 'reindex', + 'relative', + 'rename', + 'replace', + 'reset', + 'restrict', + 'returns', + 'revoke', + 'right', + 'rollback', + 'row', + 'rule', + 'schema', + 'scroll', + 'second', + 'security', + 'select', + 'sequence', + 'serializable', + 'session', + 'session_user', + 'set', + 'setof', + 'share', + 'show', + 'similar', + 'simple', + 'smallint', + 'some', + 'stable', + 'start', + 'statement', + 'statistics', + 'stdin', + 'stdout', + 'storage', + 'strict', + 'substring', + 'sysid', + 'table', + 'temp', + 'template', + 'temporary', + 'then', + 'time', + 'timestamp', + 'to', + 'toast', + 'trailing', + 'transaction', + 'treat', + 'trigger', + 'trim', + 'true', + 'truncate', + 'trusted', + 'type', + 'unencrypted', + 'union', + 'unique', + 'unknown', + 'unlisten', + 'until', + 'update', + 'usage', + 'user', + 'using', + 'vacuum', + 'valid', + 'validator', + 'values', + 'varchar', + 'varying', + 'verbose', + 'version', + 'view', + 'volatile', + 'when', + 'where', + 'with', + 'without', + 'work', + 'write', + 'year', + 'zone', + ); /** * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -354,23 +354,24 @@ class Doctrine_DataDict_Pgsql extends Doctrine_DataDict * Boolean flag that indicates whether this field is constrained * to not be set to null. * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration(array $field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } // Postgres enum type by name containing enum - if (strpos($field['type'], 'enum') !== false){ - $field['type'] = 'enum'; + if (false !== strpos($field['type'], 'enum')) { + $field['type'] = 'enum'; } switch ($field['type']) { case 'enum': - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + // no break case 'char': case 'string': case 'array': @@ -380,10 +381,10 @@ public function getNativeDeclaration(array $field) // TODO: what is the maximum VARCHAR length in pgsql ? $length = (isset($field['length']) && $field['length'] && $field['length'] < 10000) ? $field['length'] : null; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || 'char' == $field['type']) ? true : false; - return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR('.$this->conn->varchar_max_length.')') - : ($length ? 'VARCHAR(' .$length . ')' : 'TEXT'); + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$this->conn->varchar_max_length.')') + : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); case 'clob': return 'TEXT'; @@ -391,31 +392,35 @@ public function getNativeDeclaration(array $field) return 'BYTEA'; case 'integer': case 'int': - if ( ! empty($field['autoincrement'])) { - if ( ! empty($field['length'])) { + if (!empty($field['autoincrement'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length > 4) { return 'BIGSERIAL'; } } + return 'SERIAL'; } - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 2) { return 'SMALLINT'; - } elseif ($length == 3 || $length == 4) { + } + if (3 == $length || 4 == $length) { return 'INT'; - } elseif ($length > 4) { + } + if ($length > 4) { return 'BIGINT'; } } + return 'INT'; - case 'inet': - return 'INET'; + case 'inet': + return 'INET'; case 'bit': case 'varbit': - return 'VARBIT'; + return 'VARBIT'; case 'boolean': return 'BOOLEAN'; case 'date': @@ -430,31 +435,33 @@ public function getNativeDeclaration(array $field) case 'decimal': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'NUMERIC('.$length.','.$scale.')'; } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to a portable Doctrine datatype and length + * Maps a native array description of a field to a portable Doctrine datatype and length. * - * @param array $field native field description + * @param array $field native field description * * @return array containing the various possible types, length, sign, fixed */ public function getPortableDeclaration(array $field) { $length = (isset($field['length'])) ? $field['length'] : null; - if ($length == '-1' && isset($field['atttypmod'])) { + if ('-1' == $length && isset($field['atttypmod'])) { $length = $field['atttypmod'] - 4; } - if ((int)$length <= 0) { + if ((int) $length <= 0) { $length = null; } $type = array(); $unsigned = $fixed = null; - if ( ! isset($field['name'])) { + if (!isset($field['name'])) { $field['name'] = ''; } @@ -463,25 +470,25 @@ public function getPortableDeclaration(array $field) // Default from field for enum support $default = isset($field['default']) ? $field['default'] : null; $enumName = null; - if (strpos($dbType, 'enum') !== false){ + if (false !== strpos($dbType, 'enum')) { $enumName = $dbType; $dbType = 'enum'; } switch ($dbType) { - case 'inet': - $type[] = 'inet'; - break; - case 'bit': - case 'varbit': - $type[] = 'bit'; - break; + case 'inet': + $type[] = 'inet'; + break; + case 'bit': + case 'varbit': + $type[] = 'bit'; + break; case 'smallint': case 'int2': $type[] = 'integer'; $unsigned = false; $length = 2; - if ($length == '2') { + if ('2' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); @@ -515,13 +522,14 @@ public function getPortableDeclaration(array $field) case 'interval': case '_varchar': $fixed = false; + // no break case 'tsvector': case 'unknown': case 'char': case 'character': case 'bpchar': $type[] = 'string'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); @@ -529,14 +537,14 @@ public function getPortableDeclaration(array $field) } elseif (strstr($dbType, 'text')) { $type[] = 'clob'; } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } break; case 'enum': $type[] = 'enum'; - $length = $length ? $length :255; - if($default) { + $length = $length ? $length : 255; + if ($default) { $default = preg_replace('/\'(\w+)\'.*/', '${1}', $default); } break; @@ -596,21 +604,22 @@ public function getPortableDeclaration(array $field) break; default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - $ret = array('type' => $type, - 'length' => $length, - 'unsigned' => $unsigned, - 'fixed' => $fixed); + $ret = array('type' => $type, + 'length' => $length, + 'unsigned' => $unsigned, + 'fixed' => $fixed); // If this is postgresql enum type we will have non-null values here - if ($default !== null) { + if (null !== $default) { $ret['default'] = $default; } - if ($enumName !== null) { + if (null !== $enumName) { $ret['enumName'] = $enumName; } + return $ret; } @@ -618,10 +627,10 @@ public function getPortableDeclaration(array $field) * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param string $name name the field to be declared + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * unsigned * Boolean flag that indicates whether the field should be @@ -633,51 +642,53 @@ public function getPortableDeclaration(array $field) * notnull * Boolean flag that indicates whether this field is constrained * to not be set to null. + * * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * declare the specified field */ public function getIntegerDeclaration($name, $field) { /** - if ( ! empty($field['unsigned'])) { - $this->conn->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer"; - } - */ - - if ( ! empty($field['autoincrement'])) { + * if ( ! empty($field['unsigned'])) { + * $this->conn->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer"; + * }. + */ + if (!empty($field['autoincrement'])) { $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $this->getNativeDeclaration($field); + + return $name.' '.$this->getNativeDeclaration($field); } $default = ''; if (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : 0; } - $default = ' DEFAULT ' . (is_null($field['default']) + $default = ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'], $field['type'])); } /** - TODO: is this needed ? - elseif (empty($field['notnull'])) { - $default = ' DEFAULT NULL'; - } - */ - + * TODO: is this needed ? + * elseif (empty($field['notnull'])) { + * $default = ' DEFAULT NULL'; + * }. + */ $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $this->getNativeDeclaration($field) . $default . $notnull; + + return $name.' '.$this->getNativeDeclaration($field).$default.$notnull; } /** * parseBoolean * parses a literal boolean value and returns - * proper sql equivalent + * proper sql equivalent. + * + * @param string $value boolean value to be parsed * - * @param string $value boolean value to be parsed - * @return string parsed boolean value + * @return string parsed boolean value */ public function parseBoolean($value) { diff --git a/lib/Doctrine/DataDict/Sqlite.php b/lib/Doctrine/DataDict/Sqlite.php index 8bb7caeaa..1d525db68 100644 --- a/lib/Doctrine/DataDict/Sqlite.php +++ b/lib/Doctrine/DataDict/Sqlite.php @@ -20,13 +20,13 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict @@ -35,9 +35,9 @@ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -50,18 +50,21 @@ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict * notnull * Boolean flag that indicates whether this field is constrained * to not be set to null. + * * @author Lukas Smith (PEAR MDB2 library) - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration(array $field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } switch ($field['type']) { case 'enum': - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + // no break case 'text': case 'object': case 'array': @@ -71,33 +74,39 @@ public function getNativeDeclaration(array $field) case 'varchar': $length = (isset($field['length']) && $field['length']) ? $field['length'] : null; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || 'char' == $field['type']) ? true : false; return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$this->conn->varchar_max_length.')') : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); case 'clob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 255) { return 'TINYTEXT'; - } elseif ($length <= 65535) { + } + if ($length <= 65535) { return 'TEXT'; - } elseif ($length <= 16777215) { + } + if ($length <= 16777215) { return 'MEDIUMTEXT'; } } + return 'LONGTEXT'; case 'blob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 255) { return 'TINYBLOB'; - } elseif ($length <= 65535) { + } + if ($length <= 65535) { return 'BLOB'; - } elseif ($length <= 16777215) { + } + if ($length <= 16777215) { return 'MEDIUMBLOB'; } } + return 'LONGBLOB'; case 'integer': case 'boolean': @@ -111,20 +120,23 @@ public function getNativeDeclaration(array $field) return 'DATETIME'; case 'float': case 'double': - return 'DOUBLE';//($this->conn->options['fixed_float'] ? '('. - //($this->conn->options['fixed_float']+2).','.$this->conn->options['fixed_float'].')' : ''); + return 'DOUBLE'; // ($this->conn->options['fixed_float'] ? '('. + // ($this->conn->options['fixed_float']+2).','.$this->conn->options['fixed_float'].')' : ''); case 'decimal': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'DECIMAL('.$length.','.$scale.')'; } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to Doctrine datatype and length + * Maps a native array description of a field to Doctrine datatype and length. + * + * @param array $field native field description * - * @param array $field native field description * @return array containing the various possible types, length, sign, fixed */ public function getPortableDeclaration(array $field) @@ -138,7 +150,7 @@ public function getPortableDeclaration(array $field) $dbType = strtolower($field['type']); - if ( ! $dbType) { + if (!$dbType) { throw new Doctrine_DataDict_Exception('Missing "type" from field definition'); } @@ -147,7 +159,7 @@ public function getPortableDeclaration(array $field) $fixed = null; $type = array(); - if ( ! isset($field['name'])) { + if (!isset($field['name'])) { $field['name'] = ''; } @@ -199,9 +211,10 @@ public function getPortableDeclaration(array $field) case 'image': case 'nchar': $fixed = false; + // no break case 'char': $type[] = 'text'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); @@ -209,7 +222,7 @@ public function getPortableDeclaration(array $field) } elseif (strstr($dbType, 'text')) { $type[] = 'clob'; } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } break; @@ -251,24 +264,24 @@ public function getPortableDeclaration(array $field) break; default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - return array('type' => $type, - 'length' => $length, - 'unsigned' => $unsigned, - 'fixed' => $fixed); + return array('type' => $type, + 'length' => $length, + 'unsigned' => $unsigned, + 'fixed' => $fixed); } /** * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: + * @param string $name name the field to be declared + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. + * Currently, the types of supported field + * properties are as follows: * * unsigned * Boolean flag that indicates whether the field @@ -282,40 +295,40 @@ public function getPortableDeclaration(array $field) * notnull * Boolean flag that indicates whether this field is * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getIntegerDeclaration($name, array $field) { $default = $autoinc = ''; - $type = $this->getNativeDeclaration($field); + $type = $this->getNativeDeclaration($field); $autoincrement = isset($field['autoincrement']) && $field['autoincrement']; if ($autoincrement) { $autoinc = ' PRIMARY KEY AUTOINCREMENT'; - $type = 'INTEGER'; + $type = 'INTEGER'; } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : 0; } - $default = ' DEFAULT ' . (is_null($field['default']) + $default = ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'], $field['type'])); - }/** + } /** elseif (empty($field['notnull'])) { $default = ' DEFAULT NULL'; } - */ + */ + $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; + // sqlite does not support unsigned attribute for autoinremented fields + $unsigned = (isset($field['unsigned']) && $field['unsigned'] && !$autoincrement) ? ' UNSIGNED' : ''; - // sqlite does not support unsigned attribute for autoinremented fields - $unsigned = (isset($field['unsigned']) && $field['unsigned'] && !$autoincrement) ? ' UNSIGNED' : ''; + $name = $this->conn->quoteIdentifier($name, true); - $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $type . $unsigned . $default . $notnull . $autoinc; + return $name.' '.$type.$unsigned.$default.$notnull.$autoinc; + } } -} \ No newline at end of file diff --git a/lib/Doctrine/Event.php b/lib/Doctrine/Event.php index 408d8ba13..af5a32faa 100644 --- a/lib/Doctrine/Event.php +++ b/lib/Doctrine/Event.php @@ -20,122 +20,123 @@ */ /** - * Doctrine_Event + * Doctrine_Event. * * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Event - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Event { /** - * CONNECTION EVENT CODES + * CONNECTION EVENT CODES. */ - const CONN_QUERY = 1; - const CONN_EXEC = 2; - const CONN_PREPARE = 3; - const CONN_CONNECT = 4; - const CONN_CLOSE = 5; - const CONN_ERROR = 6; - - const STMT_EXECUTE = 10; - const STMT_FETCH = 11; - const STMT_FETCHALL = 12; - - const TX_BEGIN = 31; - const TX_COMMIT = 32; - const TX_ROLLBACK = 33; - const SAVEPOINT_CREATE = 34; - const SAVEPOINT_ROLLBACK = 35; - const SAVEPOINT_COMMIT = 36; - - const HYDRATE = 40; + public const CONN_QUERY = 1; + public const CONN_EXEC = 2; + public const CONN_PREPARE = 3; + public const CONN_CONNECT = 4; + public const CONN_CLOSE = 5; + public const CONN_ERROR = 6; + + public const STMT_EXECUTE = 10; + public const STMT_FETCH = 11; + public const STMT_FETCHALL = 12; + + public const TX_BEGIN = 31; + public const TX_COMMIT = 32; + public const TX_ROLLBACK = 33; + public const SAVEPOINT_CREATE = 34; + public const SAVEPOINT_ROLLBACK = 35; + public const SAVEPOINT_COMMIT = 36; + + public const HYDRATE = 40; /* * RECORD EVENT CODES */ - const RECORD_DELETE = 21; - const RECORD_SAVE = 22; - const RECORD_UPDATE = 23; - const RECORD_INSERT = 24; - const RECORD_SERIALIZE = 25; - const RECORD_UNSERIALIZE = 26; - const RECORD_DQL_DELETE = 27; - const RECORD_DQL_SELECT = 28; - const RECORD_DQL_UPDATE = 29; - const RECORD_VALIDATE = 30; + public const RECORD_DELETE = 21; + public const RECORD_SAVE = 22; + public const RECORD_UPDATE = 23; + public const RECORD_INSERT = 24; + public const RECORD_SERIALIZE = 25; + public const RECORD_UNSERIALIZE = 26; + public const RECORD_DQL_DELETE = 27; + public const RECORD_DQL_SELECT = 28; + public const RECORD_DQL_UPDATE = 29; + public const RECORD_VALIDATE = 30; /** - * @var mixed $_nextSequence the sequence of the next event that will be created + * @var mixed the sequence of the next event that will be created */ - static protected $_nextSequence = 0; + protected static $_nextSequence = 0; /** - * @var mixed $_sequence the sequence of this event + * @var mixed the sequence of this event */ protected $_sequence; /** - * @var mixed $_invoker the handler which invoked this event + * @var mixed the handler which invoked this event */ protected $_invoker; /** - * @var string $_query the sql query associated with this event (if any) + * @var string the sql query associated with this event (if any) */ protected $_query; /** - * @var string $_params the parameters associated with the query (if any) + * @var string the parameters associated with the query (if any) */ protected $_params; /** * @see Doctrine_Event constants - * @var integer $_code the event code + * + * @var int the event code */ protected $_code; /** - * @var integer $_startedMicrotime the time point in which this event was started + * @var int the time point in which this event was started */ protected $_startedMicrotime; /** - * @var integer $_endedMicrotime the time point in which this event was ended + * @var int the time point in which this event was ended */ protected $_endedMicrotime; /** - * @var array $_options an array of options + * @var array an array of options */ protected $_options = array(); /** - * constructor + * constructor. * * @param Doctrine_Connection|Doctrine_Connection_Statement| - Doctrine_Connection_UnitOfWork|Doctrine_Transaction $invoker the handler which invoked this event - * @param integer $code the event code - * @param string $query the sql query associated with this event (if any) + * Doctrine_Connection_UnitOfWork|Doctrine_Transaction $invoker the handler which invoked this event + * @param int $code the event code + * @param string $query the sql query associated with this event (if any) */ public function __construct($invoker, $code, $query = null, $params = array()) { $this->_sequence = self::$_nextSequence++; - $this->_invoker = $invoker; - $this->_code = $code; - $this->_query = $query; - $this->_params = $params; + $this->_invoker = $invoker; + $this->_code = $code; + $this->_query = $query; + $this->_params = $params; } /** - * getQuery + * getQuery. * - * @return Doctrine_Query returns the query associated with this event (if any) + * @return Doctrine_Query returns the query associated with this event (if any) */ public function getQuery() { @@ -144,9 +145,9 @@ public function getQuery() /** * getName - * returns the name of this event + * returns the name of this event. * - * @return string the name of this event + * @return string the name of this event */ public function getName() { @@ -209,9 +210,9 @@ public function getName() } /** - * getCode + * getCode. * - * @return integer returns the code associated with this event + * @return int returns the code associated with this event */ public function getCode() { @@ -220,14 +221,13 @@ public function getCode() /** * getOption - * returns the value of an option + * returns the value of an option. * - * @param string $option the name of the option - * @return mixed + * @param string $option the name of the option */ public function __get($option) { - if ( ! isset($this->_options[$option])) { + if (!isset($this->_options[$option])) { return null; } @@ -237,9 +237,9 @@ public function __get($option) /** * skipOperation * skips the next operation - * an alias for __set('skipOperation', true) + * an alias for __set('skipOperation', true). * - * @return Doctrine_Event this object + * @return Doctrine_Event this object */ public function skipOperation() { @@ -250,11 +250,12 @@ public function skipOperation() /** * setOption - * sets the value of an option + * sets the value of an option. * - * @param string $option the name of the option - * @param mixed $value the value of the given option - * @return Doctrine_Event this object + * @param string $option the name of the option + * @param mixed $value the value of the given option + * + * @return Doctrine_Event this object */ public function __set($option, $value) { @@ -265,24 +266,25 @@ public function __set($option, $value) /** * setOption - * sets the value of an option by reference + * sets the value of an option by reference. + * + * @param string $option the name of the option + * @param mixed $value the value of the given option * - * @param string $option the name of the option - * @param mixed $value the value of the given option - * @return Doctrine_Event this object + * @return Doctrine_Event this object */ public function set($option, &$value) { - $this->_options[$option] =& $value; + $this->_options[$option] = &$value; return $this; } /** * start - * starts the internal timer of this event + * starts the internal timer of this event. * - * @return Doctrine_Event this object + * @return Doctrine_Event this object */ public function start() { @@ -291,20 +293,20 @@ public function start() /** * hasEnded - * whether or not this event has ended + * whether or not this event has ended. * - * @return boolean + * @return bool */ public function hasEnded() { - return ($this->_endedMicrotime != null); + return null != $this->_endedMicrotime; } /** * end - * ends the internal timer of this event + * ends the internal timer of this event. * - * @return Doctrine_Event this object + * @return Doctrine_Event this object */ public function end() { @@ -315,9 +317,9 @@ public function end() /** * getSequence - * returns the sequence of this event + * returns the sequence of this event. * - * @return integer + * @return int */ public function getSequence() { @@ -326,7 +328,7 @@ public function getSequence() /** * getInvoker - * returns the handler that invoked this event + * returns the handler that invoked this event. * * @return Doctrine_Record|Doctrine_Connection|Doctrine_Connection_Statement| * Doctrine_Connection_UnitOfWork|Doctrine_Transaction the handler that invoked this event @@ -338,10 +340,7 @@ public function getInvoker() /** * setInvoker - * Defines new invoker (used in Hydrator) - * - * @param mixed $invoker - * @return void + * Defines new invoker (used in Hydrator). */ public function setInvoker($invoker) { @@ -350,9 +349,9 @@ public function setInvoker($invoker) /** * getParams - * returns the parameters of the query + * returns the parameters of the query. * - * @return array parameters of the query + * @return array parameters of the query */ public function getParams() { @@ -363,13 +362,14 @@ public function getParams() * Get the elapsed time (in microseconds) that the event ran. If the event has * not yet ended, return false. * - * @return integer + * @return int */ public function getElapsedSecs() { if (is_null($this->_endedMicrotime)) { return false; } - return ($this->_endedMicrotime - $this->_startedMicrotime); + + return $this->_endedMicrotime - $this->_startedMicrotime; } } diff --git a/lib/Doctrine/EventListener.php b/lib/Doctrine/EventListener.php index bffea6e3b..5b15e0c29 100644 --- a/lib/Doctrine/EventListener.php +++ b/lib/Doctrine/EventListener.php @@ -21,99 +21,147 @@ /** * Doctrine_EventListener all event listeners extend this base class - * the empty methods allow child classes to only implement the methods they need to implement + * the empty methods allow child classes to only implement the methods they need to implement. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage EventListener * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_EventListener implements Doctrine_EventListener_Interface { public function preClose(Doctrine_Event $event) - { } + { + } + public function postClose(Doctrine_Event $event) - { } + { + } public function onCollectionDelete(Doctrine_Collection $collection) - { } + { + } + public function onPreCollectionDelete(Doctrine_Collection $collection) - { } + { + } public function onOpen(Doctrine_Connection $connection) - { } + { + } public function preTransactionCommit(Doctrine_Event $event) - { } + { + } + public function postTransactionCommit(Doctrine_Event $event) - { } + { + } public function preTransactionRollback(Doctrine_Event $event) - { } + { + } + public function postTransactionRollback(Doctrine_Event $event) - { } + { + } public function preTransactionBegin(Doctrine_Event $event) - { } - public function postTransactionBegin(Doctrine_Event $event) - { } + { + } + public function postTransactionBegin(Doctrine_Event $event) + { + } public function preSavepointCommit(Doctrine_Event $event) - { } + { + } + public function postSavepointCommit(Doctrine_Event $event) - { } + { + } public function preSavepointRollback(Doctrine_Event $event) - { } + { + } + public function postSavepointRollback(Doctrine_Event $event) - { } + { + } public function preSavepointCreate(Doctrine_Event $event) - { } + { + } + public function postSavepointCreate(Doctrine_Event $event) - { } + { + } public function postConnect(Doctrine_Event $event) - { } + { + } + public function preConnect(Doctrine_Event $event) - { } + { + } public function preQuery(Doctrine_Event $event) - { } + { + } + public function postQuery(Doctrine_Event $event) - { } + { + } public function prePrepare(Doctrine_Event $event) - { } + { + } + public function postPrepare(Doctrine_Event $event) - { } + { + } public function preExec(Doctrine_Event $event) - { } + { + } + public function postExec(Doctrine_Event $event) - { } + { + } public function preError(Doctrine_Event $event) - { } + { + } + public function postError(Doctrine_Event $event) - { } + { + } public function preFetch(Doctrine_Event $event) - { } + { + } + public function postFetch(Doctrine_Event $event) - { } + { + } public function preFetchAll(Doctrine_Event $event) - { } + { + } + public function postFetchAll(Doctrine_Event $event) - { } + { + } public function preStmtExecute(Doctrine_Event $event) - { } + { + } + public function postStmtExecute(Doctrine_Event $event) - { } + { + } } diff --git a/lib/Doctrine/EventListener/Chain.php b/lib/Doctrine/EventListener/Chain.php index f7191c0a4..468b9796d 100644 --- a/lib/Doctrine/EventListener/Chain.php +++ b/lib/Doctrine/EventListener/Chain.php @@ -22,39 +22,37 @@ /** * Doctrine_EventListener_Chain * this class represents a chain of different listeners, - * useful for having multiple listeners listening the events at the same time + * useful for having multiple listeners listening the events at the same time. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage EventListener * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_EventListener_Interface { /** - * @var array $listeners an array containing all listeners + * @var array an array containing all listeners */ protected $_listeners = array(); /** * add - * adds a listener to the chain of listeners + * adds a listener to the chain of listeners. * * @param object $listener * @param string $name - * @return void */ public function add($listener, $name = null) { - if ( ! ($listener instanceof Doctrine_EventListener_Interface) && - ! ($listener instanceof Doctrine_Overloadable)) { - + if (!($listener instanceof Doctrine_EventListener_Interface) + && !($listener instanceof Doctrine_Overloadable)) { throw new Doctrine_EventListener_Exception("Couldn't add eventlistener. EventListeners should implement either Doctrine_EventListener_Interface or Doctrine_Overloadable"); } - if ($name === null) { + if (null === $name) { $this->_listeners[] = $listener; } else { $this->_listeners[$name] = $listener; @@ -63,25 +61,21 @@ public function add($listener, $name = null) /** * returns a Doctrine_EventListener on success - * and null on failure - * - * @param mixed $key - * @return mixed + * and null on failure. */ public function get($key) { - if ( ! isset($this->_listeners[$key])) { + if (!isset($this->_listeners[$key])) { return null; } + return $this->_listeners[$key]; } /** - * set + * set. * - * @param mixed $key * @param Doctrine_EventListener $listener - * @return void */ public function set($key, $listener) { @@ -90,10 +84,7 @@ public function set($key, $listener) /** * onLoad - * an event invoked when Doctrine_Record is being loaded from database - * - * @param Doctrine_Record $record - * @return void + * an event invoked when Doctrine_Record is being loaded from database. */ public function onLoad(Doctrine_Record $record) { @@ -105,10 +96,7 @@ public function onLoad(Doctrine_Record $record) /** * onPreLoad * an event invoked when Doctrine_Record is being loaded - * from database but not yet initialized - * - * @param Doctrine_Record $record - * @return void + * from database but not yet initialized. */ public function onPreLoad(Doctrine_Record $record) { @@ -119,10 +107,7 @@ public function onPreLoad(Doctrine_Record $record) /** * onSleep - * an event invoked when Doctrine_Record is serialized - * - * @param Doctrine_Record $record - * @return void + * an event invoked when Doctrine_Record is serialized. */ public function onSleep(Doctrine_Record $record) { @@ -133,10 +118,7 @@ public function onSleep(Doctrine_Record $record) /** * onWakeUp - * an event invoked when Doctrine_Record is unserialized - * - * @param Doctrine_Record $record - * @return void + * an event invoked when Doctrine_Record is unserialized. */ public function onWakeUp(Doctrine_Record $record) { @@ -147,10 +129,7 @@ public function onWakeUp(Doctrine_Record $record) /** * postClose - * an event invoked after Doctrine_Connection is closed - * - * @param Doctrine_Event $event - * @return void + * an event invoked after Doctrine_Connection is closed. */ public function postClose(Doctrine_Event $event) { @@ -161,10 +140,7 @@ public function postClose(Doctrine_Event $event) /** * preClose - * an event invoked before Doctrine_Connection is closed - * - * @param Doctrine_Event $event - * @return void + * an event invoked before Doctrine_Connection is closed. */ public function preClose(Doctrine_Event $event) { @@ -175,10 +151,7 @@ public function preClose(Doctrine_Event $event) /** * onOpen - * an event invoked after Doctrine_Connection is opened - * - * @param Doctrine_Connection $connection - * @return void + * an event invoked after Doctrine_Connection is opened. */ public function onOpen(Doctrine_Connection $connection) { @@ -189,10 +162,7 @@ public function onOpen(Doctrine_Connection $connection) /** * onTransactionCommit - * an event invoked after a Doctrine_Connection transaction is committed - * - * @param Doctrine_Event $event - * @return void + * an event invoked after a Doctrine_Connection transaction is committed. */ public function postTransactionCommit(Doctrine_Event $event) { @@ -203,10 +173,7 @@ public function postTransactionCommit(Doctrine_Event $event) /** * onPreTransactionCommit - * an event invoked before a Doctrine_Connection transaction is committed - * - * @param Doctrine_Event $event - * @return void + * an event invoked before a Doctrine_Connection transaction is committed. */ public function preTransactionCommit(Doctrine_Event $event) { @@ -217,10 +184,7 @@ public function preTransactionCommit(Doctrine_Event $event) /** * onTransactionRollback - * an event invoked after a Doctrine_Connection transaction is being rolled back - * - * @param Doctrine_Event $event - * @return void + * an event invoked after a Doctrine_Connection transaction is being rolled back. */ public function postTransactionRollback(Doctrine_Event $event) { @@ -231,10 +195,7 @@ public function postTransactionRollback(Doctrine_Event $event) /** * onPreTransactionRollback - * an event invoked before a Doctrine_Connection transaction is being rolled back - * - * @param Doctrine_Event $event - * @return void + * an event invoked before a Doctrine_Connection transaction is being rolled back. */ public function preTransactionRollback(Doctrine_Event $event) { @@ -245,10 +206,7 @@ public function preTransactionRollback(Doctrine_Event $event) /** * onTransactionBegin - * an event invoked after a Doctrine_Connection transaction has been started - * - * @param Doctrine_Event $event - * @return void + * an event invoked after a Doctrine_Connection transaction has been started. */ public function postTransactionBegin(Doctrine_Event $event) { @@ -259,10 +217,7 @@ public function postTransactionBegin(Doctrine_Event $event) /** * onTransactionBegin - * an event invoked before a Doctrine_Connection transaction is being started - * - * @param Doctrine_Event $event - * @return void + * an event invoked before a Doctrine_Connection transaction is being started. */ public function preTransactionBegin(Doctrine_Event $event) { @@ -274,10 +229,7 @@ public function preTransactionBegin(Doctrine_Event $event) /** * postSavepointCommit * an event invoked after a Doctrine_Connection transaction with savepoint - * is committed - * - * @param Doctrine_Event $event - * @return void + * is committed. */ public function postSavepointCommit(Doctrine_Event $event) { @@ -289,10 +241,7 @@ public function postSavepointCommit(Doctrine_Event $event) /** * preSavepointCommit * an event invoked before a Doctrine_Connection transaction with savepoint - * is committed - * - * @param Doctrine_Event $event - * @return void + * is committed. */ public function preSavepointCommit(Doctrine_Event $event) { @@ -304,10 +253,7 @@ public function preSavepointCommit(Doctrine_Event $event) /** * postSavepointRollback * an event invoked after a Doctrine_Connection transaction with savepoint - * is being rolled back - * - * @param Doctrine_Event $event - * @return void + * is being rolled back. */ public function postSavepointRollback(Doctrine_Event $event) { @@ -319,10 +265,7 @@ public function postSavepointRollback(Doctrine_Event $event) /** * preSavepointRollback * an event invoked before a Doctrine_Connection transaction with savepoint - * is being rolled back - * - * @param Doctrine_Event $event - * @return void + * is being rolled back. */ public function preSavepointRollback(Doctrine_Event $event) { @@ -334,10 +277,7 @@ public function preSavepointRollback(Doctrine_Event $event) /** * postSavepointCreate * an event invoked after a Doctrine_Connection transaction with savepoint - * has been started - * - * @param Doctrine_Event $event - * @return void + * has been started. */ public function postSavepointCreate(Doctrine_Event $event) { @@ -349,10 +289,7 @@ public function postSavepointCreate(Doctrine_Event $event) /** * preSavepointCreate * an event invoked before a Doctrine_Connection transaction with savepoint - * is being started - * - * @param Doctrine_Event $event - * @return void + * is being started. */ public function preSavepointCreate(Doctrine_Event $event) { @@ -364,10 +301,7 @@ public function preSavepointCreate(Doctrine_Event $event) /** * onCollectionDelete - * an event invoked after a Doctrine_Collection is being deleted - * - * @param Doctrine_Collection $collection - * @return void + * an event invoked after a Doctrine_Collection is being deleted. */ public function onCollectionDelete(Doctrine_Collection $collection) { @@ -378,10 +312,7 @@ public function onCollectionDelete(Doctrine_Collection $collection) /** * onCollectionDelete - * an event invoked after a Doctrine_Collection is being deleted - * - * @param Doctrine_Collection $collection - * @return void + * an event invoked after a Doctrine_Collection is being deleted. */ public function onPreCollectionDelete(Doctrine_Collection $collection) { @@ -405,7 +336,7 @@ public function preConnect(Doctrine_Event $event) } public function preQuery(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preQuery($event); } @@ -419,7 +350,7 @@ public function postQuery(Doctrine_Event $event) } public function prePrepare(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->prePrepare($event); } @@ -447,7 +378,7 @@ public function postExec(Doctrine_Event $event) } public function preError(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preError($event); } @@ -461,7 +392,7 @@ public function postError(Doctrine_Event $event) } public function preFetch(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preFetch($event); } @@ -475,7 +406,7 @@ public function postFetch(Doctrine_Event $event) } public function preFetchAll(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preFetchAll($event); } @@ -501,4 +432,4 @@ public function postStmtExecute(Doctrine_Event $event) $listener->postStmtExecute($event); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/EventListener/Exception.php b/lib/Doctrine/EventListener/Exception.php index a0c10cb4a..4c463e852 100644 --- a/lib/Doctrine/EventListener/Exception.php +++ b/lib/Doctrine/EventListener/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_EventListener_Exception + * Doctrine_EventListener_Exception. * - * @package Doctrine - * @subpackage EventListener * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1344 $ + * * @author Konsta Vesterinen */ class Doctrine_EventListener_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/EventListener/Interface.php b/lib/Doctrine/EventListener/Interface.php index 6a3c12e87..bc8488f18 100644 --- a/lib/Doctrine/EventListener/Interface.php +++ b/lib/Doctrine/EventListener/Interface.php @@ -21,48 +21,59 @@ /** * Doctrine_EventListener all event listeners extend this base class - * the empty methods allow child classes to only implement the methods they need to implement + * the empty methods allow child classes to only implement the methods they need to implement. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage EventListener * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ interface Doctrine_EventListener_Interface { public function preTransactionCommit(Doctrine_Event $event); + public function postTransactionCommit(Doctrine_Event $event); public function preTransactionRollback(Doctrine_Event $event); + public function postTransactionRollback(Doctrine_Event $event); public function preTransactionBegin(Doctrine_Event $event); + public function postTransactionBegin(Doctrine_Event $event); public function postConnect(Doctrine_Event $event); + public function preConnect(Doctrine_Event $event); public function preQuery(Doctrine_Event $event); + public function postQuery(Doctrine_Event $event); public function prePrepare(Doctrine_Event $event); + public function postPrepare(Doctrine_Event $event); public function preExec(Doctrine_Event $event); + public function postExec(Doctrine_Event $event); public function preError(Doctrine_Event $event); + public function postError(Doctrine_Event $event); public function preFetch(Doctrine_Event $event); + public function postFetch(Doctrine_Event $event); public function preFetchAll(Doctrine_Event $event); + public function postFetchAll(Doctrine_Event $event); public function preStmtExecute(Doctrine_Event $event); + public function postStmtExecute(Doctrine_Event $event); } diff --git a/lib/Doctrine/Exception.php b/lib/Doctrine/Exception.php index 6db70250d..84c10f097 100644 --- a/lib/Doctrine/Exception.php +++ b/lib/Doctrine/Exception.php @@ -20,64 +20,66 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. * - * @package Doctrine - * @subpackage Exception * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Exception extends Exception -{ +{ /** - * @var array $_errorMessages an array of error messages + * @var array an array of error messages */ protected static $_errorMessages = array( - Doctrine_Core::ERR => 'unknown error', - Doctrine_Core::ERR_ALREADY_EXISTS => 'already exists', - Doctrine_Core::ERR_CANNOT_CREATE => 'can not create', - Doctrine_Core::ERR_CANNOT_ALTER => 'can not alter', - Doctrine_Core::ERR_CANNOT_REPLACE => 'can not replace', - Doctrine_Core::ERR_CANNOT_DELETE => 'can not delete', - Doctrine_Core::ERR_CANNOT_DROP => 'can not drop', - Doctrine_Core::ERR_CONSTRAINT => 'constraint violation', - Doctrine_Core::ERR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint', - Doctrine_Core::ERR_DIVZERO => 'division by zero', - Doctrine_Core::ERR_INVALID => 'invalid', - Doctrine_Core::ERR_INVALID_DATE => 'invalid date or time', - Doctrine_Core::ERR_INVALID_NUMBER => 'invalid number', - Doctrine_Core::ERR_MISMATCH => 'mismatch', - Doctrine_Core::ERR_NODBSELECTED => 'no database selected', - Doctrine_Core::ERR_NOSUCHFIELD => 'no such field', - Doctrine_Core::ERR_NOSUCHTABLE => 'no such table', - Doctrine_Core::ERR_NOT_CAPABLE => 'Doctrine backend not capable', - Doctrine_Core::ERR_NOT_FOUND => 'not found', - Doctrine_Core::ERR_NOT_LOCKED => 'not locked', - Doctrine_Core::ERR_SYNTAX => 'syntax error', - Doctrine_Core::ERR_UNSUPPORTED => 'not supported', - Doctrine_Core::ERR_VALUE_COUNT_ON_ROW => 'value count on row', - Doctrine_Core::ERR_INVALID_DSN => 'invalid DSN', - Doctrine_Core::ERR_CONNECT_FAILED => 'connect failed', - Doctrine_Core::ERR_NEED_MORE_DATA => 'insufficient data supplied', - Doctrine_Core::ERR_EXTENSION_NOT_FOUND=> 'extension not found', - Doctrine_Core::ERR_NOSUCHDB => 'no such database', - Doctrine_Core::ERR_ACCESS_VIOLATION => 'insufficient permissions', - Doctrine_Core::ERR_LOADMODULE => 'error while including on demand module', - Doctrine_Core::ERR_TRUNCATED => 'truncated', - Doctrine_Core::ERR_DEADLOCK => 'deadlock detected', - ); + Doctrine_Core::ERR => 'unknown error', + Doctrine_Core::ERR_ALREADY_EXISTS => 'already exists', + Doctrine_Core::ERR_CANNOT_CREATE => 'can not create', + Doctrine_Core::ERR_CANNOT_ALTER => 'can not alter', + Doctrine_Core::ERR_CANNOT_REPLACE => 'can not replace', + Doctrine_Core::ERR_CANNOT_DELETE => 'can not delete', + Doctrine_Core::ERR_CANNOT_DROP => 'can not drop', + Doctrine_Core::ERR_CONSTRAINT => 'constraint violation', + Doctrine_Core::ERR_CONSTRAINT_NOT_NULL => 'null value violates not-null constraint', + Doctrine_Core::ERR_DIVZERO => 'division by zero', + Doctrine_Core::ERR_INVALID => 'invalid', + Doctrine_Core::ERR_INVALID_DATE => 'invalid date or time', + Doctrine_Core::ERR_INVALID_NUMBER => 'invalid number', + Doctrine_Core::ERR_MISMATCH => 'mismatch', + Doctrine_Core::ERR_NODBSELECTED => 'no database selected', + Doctrine_Core::ERR_NOSUCHFIELD => 'no such field', + Doctrine_Core::ERR_NOSUCHTABLE => 'no such table', + Doctrine_Core::ERR_NOT_CAPABLE => 'Doctrine backend not capable', + Doctrine_Core::ERR_NOT_FOUND => 'not found', + Doctrine_Core::ERR_NOT_LOCKED => 'not locked', + Doctrine_Core::ERR_SYNTAX => 'syntax error', + Doctrine_Core::ERR_UNSUPPORTED => 'not supported', + Doctrine_Core::ERR_VALUE_COUNT_ON_ROW => 'value count on row', + Doctrine_Core::ERR_INVALID_DSN => 'invalid DSN', + Doctrine_Core::ERR_CONNECT_FAILED => 'connect failed', + Doctrine_Core::ERR_NEED_MORE_DATA => 'insufficient data supplied', + Doctrine_Core::ERR_EXTENSION_NOT_FOUND => 'extension not found', + Doctrine_Core::ERR_NOSUCHDB => 'no such database', + Doctrine_Core::ERR_ACCESS_VIOLATION => 'insufficient permissions', + Doctrine_Core::ERR_LOADMODULE => 'error while including on demand module', + Doctrine_Core::ERR_TRUNCATED => 'truncated', + Doctrine_Core::ERR_DEADLOCK => 'deadlock detected', + ); /** - * Return a textual error message for a Doctrine error code + * Return a textual error message for a Doctrine error code. * * @param int|array integer error code, * null to get the current error code-message map, * or an array with a new error code-message map + * @param mixed|null $value * - * @return string error message + * @return string error message */ public function errorMessage($value = null) { @@ -88,5 +90,4 @@ public function errorMessage($value = null) return isset(self::$_errorMessages[$value]) ? self::$_errorMessages[$value] : self::$_errorMessages[Doctrine_Core::ERR]; } - } diff --git a/lib/Doctrine/Export.php b/lib/Doctrine/Export.php index ab56d6620..68d6b591a 100644 --- a/lib/Doctrine/Export.php +++ b/lib/Doctrine/Export.php @@ -20,39 +20,36 @@ */ /** - * Doctrine_Export + * Doctrine_Export. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7653 $ */ class Doctrine_Export extends Doctrine_Connection_Module { protected $valid_default_values = array( - 'text' => '', - 'boolean' => true, - 'integer' => 0, - 'decimal' => 0.0, - 'float' => 0.0, + 'text' => '', + 'boolean' => true, + 'integer' => 0, + 'decimal' => 0.0, + 'float' => 0.0, 'timestamp' => '1970-01-01 00:00:00', - 'time' => '00:00:00', - 'date' => '1970-01-01', - 'clob' => '', - 'blob' => '', - 'string' => '' + 'time' => '00:00:00', + 'date' => '1970-01-01', + 'clob' => '', + 'blob' => '', + 'string' => '', ); /** * drop an existing database - * (this method is implemented by the drivers) - * - * @param string $name name of the database that should be dropped - * @return void + * (this method is implemented by the drivers). */ public function dropDatabase($database) { @@ -63,10 +60,7 @@ public function dropDatabase($database) /** * drop an existing database - * (this method is implemented by the drivers) - * - * @param string $name name of the database that should be dropped - * @return void + * (this method is implemented by the drivers). */ public function dropDatabaseSql($database) { @@ -75,22 +69,22 @@ public function dropDatabaseSql($database) /** * dropTableSql - * drop an existing table + * drop an existing table. + * + * @param string $table name of table that should be dropped from the database * - * @param string $table name of table that should be dropped from the database * @return string */ public function dropTableSql($table) { - return 'DROP TABLE ' . $this->conn->quoteIdentifier($table); + return 'DROP TABLE '.$this->conn->quoteIdentifier($table); } /** * dropTable - * drop an existing table + * drop an existing table. * - * @param string $table name of table that should be dropped from the database - * @return void + * @param string $table name of table that should be dropped from the database */ public function dropTable($table) { @@ -98,11 +92,10 @@ public function dropTable($table) } /** - * drop existing index + * drop existing index. * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the index to be dropped */ public function dropIndex($table, $name) { @@ -110,41 +103,40 @@ public function dropIndex($table, $name) } /** - * dropIndexSql + * dropIndexSql. + * + * @param string $table name of table that should be used in method + * @param string $name name of the index to be dropped * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return string SQL that is used for dropping an index + * @return string SQL that is used for dropping an index */ public function dropIndexSql($table, $name) { $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name)); - - return 'DROP INDEX ' . $name; + + return 'DROP INDEX '.$name; } /** - * drop existing constraint + * drop existing constraint. * - * @param string $table name of table that should be used in method - * @param string $name name of the constraint to be dropped - * @param string $primary hint if the constraint is primary - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the constraint to be dropped + * @param string $primary hint if the constraint is primary */ public function dropConstraint($table, $name, $primary = false) { $table = $this->conn->quoteIdentifier($table); - $name = $this->conn->quoteIdentifier($name); - - return $this->conn->exec('ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $name); + $name = $this->conn->quoteIdentifier($name); + + return $this->conn->exec('ALTER TABLE '.$table.' DROP CONSTRAINT '.$name); } /** - * drop existing foreign key + * drop existing foreign key. * - * @param string $table name of table that should be used in method - * @param string $name name of the foreign key to be dropped - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the foreign key to be dropped */ public function dropForeignKey($table, $name) { @@ -154,11 +146,11 @@ public function dropForeignKey($table, $name) /** * dropSequenceSql * drop existing sequence - * (this method is implemented by the drivers) + * (this method is implemented by the drivers). * - * @throws Doctrine_Connection_Exception if something fails at database level - * @param string $sequenceName name of the sequence to be dropped - * @return void + * @param string $sequenceName name of the sequence to be dropped + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function dropSequence($sequenceName) { @@ -167,11 +159,11 @@ public function dropSequence($sequenceName) /** * dropSequenceSql - * drop existing sequence + * drop existing sequence. * - * @throws Doctrine_Connection_Exception if something fails at database level * @param string $sequenceName name of the sequence to be dropped - * @return void + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function dropSequenceSql($sequenceName) { @@ -180,10 +172,7 @@ public function dropSequenceSql($sequenceName) /** * create a new database - * (this method is implemented by the drivers) - * - * @param string $name name of the database that should be created - * @return void + * (this method is implemented by the drivers). */ public function createDatabase($database) { @@ -192,9 +181,8 @@ public function createDatabase($database) /** * create a new database - * (this method is implemented by the drivers) + * (this method is implemented by the drivers). * - * @param string $name name of the database that should be created * @return string */ public function createDatabaseSql($database) @@ -203,67 +191,66 @@ public function createDatabaseSql($database) } /** - * create a new table - * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: + * create a new table. + * + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. + * array( + * 'id' => array( + * 'type' => 'integer', + * 'unsigned' => 1 + * 'notnull' => 1 + * 'default' => 0 + * ), + * 'name' => array( + * 'type' => 'text', + * 'length' => 12 + * ), + * 'password' => array( + * 'type' => 'text', + * 'length' => 12 + * ) + * ); + * @param array $options An associative array of table options: * * @return string */ public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } if (empty($fields)) { - throw new Doctrine_Export_Exception('no fields specified for table ' . $name); + throw new Doctrine_Export_Exception('no fields specified for table '.$name); } $queryFields = $this->getFieldDeclarationList($fields); - - if (isset($options['primary']) && ! empty($options['primary'])) { + if (isset($options['primary']) && !empty($options['primary'])) { $primaryKeys = array_map(array($this->conn, 'quoteIdentifier'), array_values($options['primary'])); - $queryFields .= ', PRIMARY KEY(' . implode(', ', $primaryKeys) . ')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $primaryKeys).')'; } - if (isset($options['indexes']) && ! empty($options['indexes'])) { - foreach($options['indexes'] as $index => $definition) { + if (isset($options['indexes']) && !empty($options['indexes'])) { + foreach ($options['indexes'] as $index => $definition) { $indexDeclaration = $this->getIndexDeclaration($index, $definition); // append only created index declarations - if ( ! is_null($indexDeclaration)) { + if (!is_null($indexDeclaration)) { $queryFields .= ', '.$indexDeclaration; - } + } } } - $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields; - + $query = 'CREATE TABLE '.$this->conn->quoteIdentifier($name, true).' ('.$queryFields; + $check = $this->getCheckDeclaration($fields); - if ( ! empty($check)) { - $query .= ', ' . $check; + if (!empty($check)) { + $query .= ', '.$check; } $query .= ')'; @@ -271,25 +258,24 @@ public function createTableSql($name, array $fields, array $options = array()) $sql[] = $query; if (isset($options['foreignKeys'])) { - foreach ((array) $options['foreignKeys'] as $k => $definition) { if (is_array($definition)) { $sql[] = $this->createForeignKeySql($name, $definition); } } } + return $sql; } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * @param array $options An associative array of table options: - * @see Doctrine_Export::createTableSql() + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * @param array $options An associative array of table options: * - * @return void + * @see Doctrine_Export::createTableSql() */ public function createTable($name, array $fields, array $options = array()) { @@ -298,10 +284,10 @@ public function createTable($name, array $fields, array $options = array()) $count = 0; foreach ($fields as $fieldName => $field) { if (isset($field['primary']) && $field['primary']) { - if ($count == 0) { + if (0 == $count) { $options['primary'] = array(); } - $count++; + ++$count; $options['primary'][] = $fieldName; } } @@ -314,18 +300,18 @@ public function createTable($name, array $fields, array $options = array()) } /** - * create sequence - * - * @throws Doctrine_Connection_Exception if something fails at database level - * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); - * @return void + * create sequence. + * + * @param string $seqName name of the sequence to be created + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function createSequence($seqName, $start = 1, array $options = array()) { @@ -334,18 +320,20 @@ public function createSequence($seqName, $start = 1, array $options = array()) /** * return RDBMS specific create sequence statement - * (this method is implemented by the drivers) - * - * @throws Doctrine_Connection_Exception if something fails at database level - * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); + * (this method is implemented by the drivers). + * + * @param string $seqName name of the sequence to be created + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); + * * @return string + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function createSequenceSql($seqName, $start = 1, array $options = array()) { @@ -353,16 +341,16 @@ public function createSequenceSql($seqName, $start = 1, array $options = array() } /** - * create a constraint on a table + * create a constraint on a table. * - * @param string $table name of the table on which the constraint is to be created - * @param string $name name of the constraint to be created - * @param array $definition associative array that defines properties of the constraint to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the constraint fields as array - * constraints. Each entry of this array is set to another type of associative - * array that specifies properties of the constraint that are specific to - * each field. + * @param string $table name of the table on which the constraint is to be created + * @param string $name name of the constraint to be created + * @param array $definition associative array that defines properties of the constraint to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the constraint fields as array + * constraints. Each entry of this array is set to another type of associative + * array that specifies properties of the constraint that are specific to + * each field. * * Example * array( @@ -371,26 +359,25 @@ public function createSequenceSql($seqName, $start = 1, array $options = array() * 'last_login' => array() * ) * ) - * @return void */ public function createConstraint($table, $name, $definition) { $sql = $this->createConstraintSql($table, $name, $definition); - + return $this->conn->exec($sql); } /** - * create a constraint on a table + * create a constraint on a table. * - * @param string $table name of the table on which the constraint is to be created - * @param string $name name of the constraint to be created - * @param array $definition associative array that defines properties of the constraint to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the constraint fields as array - * constraints. Each entry of this array is set to another type of associative - * array that specifies properties of the constraint that are specific to - * each field. + * @param string $table name of the table on which the constraint is to be created + * @param string $name name of the constraint to be created + * @param array $definition associative array that defines properties of the constraint to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the constraint fields as array + * constraints. Each entry of this array is set to another type of associative + * array that specifies properties of the constraint that are specific to + * each field. * * Example * array( @@ -399,13 +386,12 @@ public function createConstraint($table, $name, $definition) * 'last_login' => array() * ) * ) - * @return void */ public function createConstraintSql($table, $name, $definition) { $table = $this->conn->quoteIdentifier($table); - $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name)); - $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $name; + $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name)); + $query = 'ALTER TABLE '.$table.' ADD CONSTRAINT '.$name; if (isset($definition['primary']) && $definition['primary']) { $query .= ' PRIMARY KEY'; @@ -417,22 +403,22 @@ public function createConstraintSql($table, $name, $definition) foreach (array_keys($definition['fields']) as $field) { $fields[] = $this->conn->quoteIdentifier($field, true); } - $query .= ' ('. implode(', ', $fields) . ')'; + $query .= ' ('.implode(', ', $fields).')'; return $query; } /** - * Get the stucture of a field into an array + * Get the stucture of a field into an array. * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the index fields as array + * indexes. Each entry of this array is set to another type of associative + * array that specifies properties of the index that are specific to + * each field. * * Currently, only the sorting property is supported. It should be used * to define the sorting direction of the index. It may be set to either @@ -451,7 +437,6 @@ public function createConstraintSql($table, $name, $definition) * 'last_login' => array() * ) * ) - * @return void */ public function createIndex($table, $name, array $definition) { @@ -459,79 +444,81 @@ public function createIndex($table, $name, array $definition) } /** - * Get the stucture of a field into an array + * Get the stucture of a field into an array. + * + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. * @see Doctrine_Export::createIndex() + * * @return string */ public function createIndexSql($table, $name, array $definition) { - $table = $this->conn->quoteIdentifier($table); - $name = $this->conn->quoteIdentifier($name); - $type = ''; - + $table = $this->conn->quoteIdentifier($table); + $name = $this->conn->quoteIdentifier($name); + $type = ''; + if (isset($definition['type'])) { switch (strtolower($definition['type'])) { case 'unique': - $type = strtoupper($definition['type']) . ' '; - break; + $type = strtoupper($definition['type']).' '; + break; default: - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name . ' in table ' . $table - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name.' in table '.$table); } } - $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table; + $query = 'CREATE '.$type.'INDEX '.$name.' ON '.$table; $fields = array(); foreach ($definition['fields'] as $field) { $fields[] = $this->conn->quoteIdentifier($field); } - $query .= ' (' . implode(', ', $fields) . ')'; + $query .= ' ('.implode(', ', $fields).')'; return $query; - } + } + /** - * createForeignKeySql + * createForeignKeySql. + * + * @param string $table name of the table on which the foreign key is to be created + * @param array $definition associative array that defines properties of the foreign key to be created * - * @param string $table name of the table on which the foreign key is to be created - * @param array $definition associative array that defines properties of the foreign key to be created. * @return string */ public function createForeignKeySql($table, array $definition) { $table = $this->conn->quoteIdentifier($table); - $query = 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclaration($definition); - return $query; + return 'ALTER TABLE '.$table.' ADD '.$this->getForeignKeyDeclaration($definition); } /** - * createForeignKey + * createForeignKey. + * + * @param string $table name of the table on which the foreign key is to be created + * @param array $definition associative array that defines properties of the foreign key to be created * - * @param string $table name of the table on which the foreign key is to be created - * @param array $definition associative array that defines properties of the foreign key to be created. * @return string */ public function createForeignKey($table, array $definition) { $sql = $this->createForeignKeySql($table, $definition); - + return $this->conn->execute($sql); } /** * alter an existing table - * (this method is implemented by the drivers) + * (this method is implemented by the drivers). * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -544,79 +531,14 @@ public function createForeignKey($table, array $definition) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the MDB2 parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the MDB2 parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @return void + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise */ public function alterTable($name, array $changes, $check = false) { $sql = $this->alterTableSql($name, $changes, $check); - + if (is_string($sql) && $sql) { $this->conn->execute($sql); } @@ -624,14 +546,16 @@ public function alterTable($name, array $changes, $check = false) /** * generates the sql for altering an existing table - * (this method is implemented by the drivers) + * (this method is implemented by the drivers). + * + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type * + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. * @see Doctrine_Export::alterTable() + * * @return string */ public function alterTableSql($name, array $changes, $check = false) @@ -640,13 +564,13 @@ public function alterTableSql($name, array $changes, $check = false) } /** - * Get declaration of a number of field in bulk + * Get declaration of a number of field in bulk. * - * @param array $fields a multidimensional associative array. - * The first dimension determines the field name, while the second - * dimension is keyed with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $fields a multidimensional associative array. + * The first dimension determines the field name, while the second + * dimension is keyed with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -675,6 +599,7 @@ public function getFieldDeclarationList(array $fields) $queryFields[] = $query; } + return implode(', ', $queryFields); } @@ -682,10 +607,10 @@ public function getFieldDeclarationList(array $fields) * Obtain DBMS specific SQL code portion needed to declare a generic type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param string $name name the field to be declared + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -711,43 +636,40 @@ public function getFieldDeclarationList(array $fields) * check * column check constraint * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getDeclaration($name, array $field) { + $default = $this->getDefaultFieldDeclaration($field); - $default = $this->getDefaultFieldDeclaration($field); - - $charset = (isset($field['charset']) && $field['charset']) ? - ' ' . $this->getCharsetFieldDeclaration($field['charset']) : ''; + $charset = (isset($field['charset']) && $field['charset']) ? + ' '.$this->getCharsetFieldDeclaration($field['charset']) : ''; $collation = (isset($field['collation']) && $field['collation']) ? - ' ' . $this->getCollationFieldDeclaration($field['collation']) : ''; + ' '.$this->getCollationFieldDeclaration($field['collation']) : ''; - $notnull = $this->getNotNullFieldDeclaration($field); + $notnull = $this->getNotNullFieldDeclaration($field); - $unique = (isset($field['unique']) && $field['unique']) ? - ' ' . $this->getUniqueFieldDeclaration() : ''; + $unique = (isset($field['unique']) && $field['unique']) ? + ' '.$this->getUniqueFieldDeclaration() : ''; - $check = (isset($field['check']) && $field['check']) ? - ' ' . $field['check'] : ''; + $check = (isset($field['check']) && $field['check']) ? + ' '.$field['check'] : ''; - $method = 'get' . $field['type'] . 'Declaration'; + $method = 'get'.$field['type'].'Declaration'; try { if (method_exists($this->conn->dataDict, $method)) { - return $this->conn->dataDict->$method($name, $field); - } else { - $dec = $this->conn->dataDict->getNativeDeclaration($field); + return $this->conn->dataDict->{$method}($name, $field); } + $dec = $this->conn->dataDict->getNativeDeclaration($field); return $this->conn->quoteIdentifier($name, true) - . ' ' . $dec . $charset . $default . $notnull . $unique . $check . $collation; + .' '.$dec.$charset.$default.$notnull.$unique.$check.$collation; } catch (Exception $e) { - throw new Doctrine_Exception('Around field ' . $name . ': ' . $e->getMessage()); + throw new Doctrine_Exception('Around field '.$name.': '.$e->getMessage()); } - } /** @@ -755,70 +677,69 @@ public function getDeclaration($name, array $field) * Obtain DBMS specific SQL code portion needed to set a default value * declaration to be used in statements like CREATE TABLE. * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @param array $field field definition array + * + * @return string DBMS specific SQL code portion needed to set a default value */ public function getDefaultFieldDeclaration($field) { $default = ''; if (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : $this->valid_default_values[$field['type']]; - if ($field['default'] === '' && - ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL)) { + if ('' === $field['default'] + && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL)) { $field['default'] = null; } } - if ($field['type'] === 'boolean') { + if ('boolean' === $field['type']) { $field['default'] = $this->conn->convertBooleans($field['default']); } - $default = ' DEFAULT ' . (is_null($field['default']) + $default = ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'], $field['type'])); } return $default; } - /** * getNotNullFieldDeclaration * Obtain DBMS specific SQL code portion needed to set a NOT NULL * declaration to be used in statements like CREATE TABLE. * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @return string DBMS specific SQL code portion needed to set a default value */ public function getNotNullFieldDeclaration(array $definition) { return (isset($definition['notnull']) && $definition['notnull']) ? ' NOT NULL' : ''; } - /** * Obtain DBMS specific SQL code portion needed to set a CHECK constraint * declaration to be used in statements like CREATE TABLE. * - * @param array $definition check definition - * @return string DBMS specific SQL code portion needed to set a CHECK constraint + * @param array $definition check definition + * + * @return string DBMS specific SQL code portion needed to set a CHECK constraint */ public function getCheckDeclaration(array $definition) { $constraints = array(); foreach ($definition as $field => $def) { if (is_string($def)) { - $constraints[] = 'CHECK (' . $def . ')'; + $constraints[] = 'CHECK ('.$def.')'; } else { if (isset($def['min'])) { - $constraints[] = 'CHECK (' . $field . ' >= ' . $def['min'] . ')'; + $constraints[] = 'CHECK ('.$field.' >= '.$def['min'].')'; } if (isset($def['max'])) { - $constraints[] = 'CHECK (' . $field . ' <= ' . $def['max'] . ')'; + $constraints[] = 'CHECK ('.$field.' <= '.$def['max'].')'; } } } @@ -830,32 +751,31 @@ public function getCheckDeclaration(array $definition) * Obtain DBMS specific SQL code portion needed to set an index * declaration to be used in statements like CREATE TABLE. * - * @param string $name name of the index - * @param array $definition index definition - * @return string DBMS specific SQL code portion needed to set an index + * @param string $name name of the index + * @param array $definition index definition + * + * @return string DBMS specific SQL code portion needed to set an index */ public function getIndexDeclaration($name, array $definition) { - $name = $this->conn->quoteIdentifier($name); - $type = ''; + $name = $this->conn->quoteIdentifier($name); + $type = ''; if (isset($definition['type'])) { - if (strtolower($definition['type']) == 'unique') { - $type = strtoupper($definition['type']) . ' '; + if ('unique' == strtolower($definition['type'])) { + $type = strtoupper($definition['type']).' '; } else { - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name); } } - if ( ! isset($definition['fields']) || ! is_array($definition['fields'])) { - throw new Doctrine_Export_Exception('No columns given for index ' . $name); + if (!isset($definition['fields']) || !is_array($definition['fields'])) { + throw new Doctrine_Export_Exception('No columns given for index '.$name); } - $query = $type . 'INDEX ' . $name; + $query = $type.'INDEX '.$name; - $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')'; + $query .= ' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; return $query; } @@ -877,6 +797,7 @@ public function getIndexFieldDeclarationList(array $fields) $ret[] = $this->conn->quoteIdentifier($definition); } } + return implode(', ', $ret); } @@ -891,8 +812,8 @@ public function getIndexFieldDeclarationList(array $fields) * SQL error for any database that does not support temporary tables, or that * requires a different SQL command from "CREATE TEMPORARY TABLE". * - * @return string The string required to be placed between "CREATE" and "TABLE" - * to generate a temporary table, if possible. + * @return string the string required to be placed between "CREATE" and "TABLE" + * to generate a temporary table, if possible */ public function getTemporaryTableQuery() { @@ -904,8 +825,8 @@ public function getTemporaryTableQuery() * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint * of a field declaration to be used in statements like CREATE TABLE. * - * @param array $definition an associative array with the following structure: - * name optional constraint name + * @param array $definition an associative array with the following structure: + * name optional constraint name * * local the local field(s) * @@ -938,12 +859,12 @@ public function getTemporaryTableQuery() * * SET DEFAULT * - * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint - * of a field declaration. + * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint + * of a field declaration */ public function getForeignKeyDeclaration(array $definition) { - $sql = $this->getForeignKeyBaseDeclaration($definition); + $sql = $this->getForeignKeyBaseDeclaration($definition); $sql .= $this->getAdvancedForeignKeyOptions($definition); return $sql; @@ -954,30 +875,33 @@ public function getForeignKeyDeclaration(array $definition) * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition foreign key definition + * @param array $definition foreign key definition + * * @return string */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; - if ( ! empty($definition['onUpdate'])) { - $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialAction($definition['onUpdate']); + if (!empty($definition['onUpdate'])) { + $query .= ' ON UPDATE '.$this->getForeignKeyReferentialAction($definition['onUpdate']); } - if ( ! empty($definition['onDelete'])) { - $query .= ' ON DELETE ' . $this->getForeignKeyReferentialAction($definition['onDelete']); + if (!empty($definition['onDelete'])) { + $query .= ' ON DELETE '.$this->getForeignKeyReferentialAction($definition['onDelete']); } + return $query; } /** - * getForeignKeyReferentialAction + * getForeignKeyReferentialAction. * * returns given referential action in uppercase if valid, otherwise throws * an exception * - * @throws Doctrine_Exception_Exception if unknown referential action given - * @param string $action foreign key referential action + * @param string $action foreign key referential action * @param string foreign key referential action in uppercase + * + * @throws Doctrine_Exception_Exception if unknown referential action given */ public function getForeignKeyReferentialAction($action) { @@ -989,9 +913,9 @@ public function getForeignKeyReferentialAction($action) case 'RESTRICT': case 'SET DEFAULT': return $upper; - break; + break; default: - throw new Doctrine_Export_Exception('Unknown foreign key referential action \'' . $upper . '\' given.'); + throw new Doctrine_Export_Exception('Unknown foreign key referential action \''.$upper.'\' given.'); } } @@ -1000,38 +924,37 @@ public function getForeignKeyReferentialAction($action) * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint * of a field declaration to be used in statements like CREATE TABLE. * - * @param array $definition * @return string */ public function getForeignKeyBaseDeclaration(array $definition) { $sql = ''; if (isset($definition['name'])) { - $sql .= 'CONSTRAINT ' . $this->conn->quoteIdentifier($this->conn->formatter->getForeignKeyName($definition['name'])) . ' '; + $sql .= 'CONSTRAINT '.$this->conn->quoteIdentifier($this->conn->formatter->getForeignKeyName($definition['name'])).' '; } $sql .= 'FOREIGN KEY ('; - if ( ! isset($definition['local'])) { + if (!isset($definition['local'])) { throw new Doctrine_Export_Exception('Local reference field missing from definition.'); } - if ( ! isset($definition['foreign'])) { + if (!isset($definition['foreign'])) { throw new Doctrine_Export_Exception('Foreign reference field missing from definition.'); } - if ( ! isset($definition['foreignTable'])) { + if (!isset($definition['foreignTable'])) { throw new Doctrine_Export_Exception('Foreign reference table missing from definition.'); } - if ( ! is_array($definition['local'])) { + if (!is_array($definition['local'])) { $definition['local'] = array($definition['local']); } - if ( ! is_array($definition['foreign'])) { + if (!is_array($definition['foreign'])) { $definition['foreign'] = array($definition['foreign']); } $sql .= implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['local'])) - . ') REFERENCES ' - . $this->conn->quoteIdentifier($definition['foreignTable']) . '(' - . implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['foreign'])) . ')'; + .') REFERENCES ' + .$this->conn->quoteIdentifier($definition['foreignTable']).'(' + .implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['foreign'])).')'; return $sql; } @@ -1040,8 +963,8 @@ public function getForeignKeyBaseDeclaration(array $definition) * Obtain DBMS specific SQL code portion needed to set the UNIQUE constraint * of a field declaration to be used in statements like CREATE TABLE. * - * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint - * of a field declaration. + * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint + * of a field declaration */ public function getUniqueFieldDeclaration() { @@ -1052,9 +975,10 @@ public function getUniqueFieldDeclaration() * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET * of a field declaration to be used in statements like CREATE TABLE. * - * @param string $charset name of the charset - * @return string DBMS specific SQL code portion needed to set the CHARACTER SET - * of a field declaration. + * @param string $charset name of the charset + * + * @return string DBMS specific SQL code portion needed to set the CHARACTER SET + * of a field declaration */ public function getCharsetFieldDeclaration($charset) { @@ -1065,9 +989,10 @@ public function getCharsetFieldDeclaration($charset) * Obtain DBMS specific SQL code portion needed to set the COLLATION * of a field declaration to be used in statements like CREATE TABLE. * - * @param string $collation name of the collation - * @return string DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration. + * @param string $collation name of the collation + * + * @return string DBMS specific SQL code portion needed to set the COLLATION + * of a field declaration */ public function getCollationFieldDeclaration($collation) { @@ -1076,7 +1001,7 @@ public function getCollationFieldDeclaration($collation) /** * exportSchema - * method for exporting Doctrine_Record classes to a schema + * method for exporting Doctrine_Record classes to a schema. * * if the directory parameter is given this method first iterates * recursively trhough the given directory in order to find any model classes @@ -1084,14 +1009,14 @@ public function getCollationFieldDeclaration($collation) * Then it iterates through all declared classes and creates tables for the ones * that extend Doctrine_Record and are not abstract classes * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @param string $directory optional directory parameter - * @return void + * @param string $directory optional directory parameter + * + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function exportSchema($directory = null) { - if ($directory !== null) { + if (null !== $directory) { $models = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($directory)); } else { $models = Doctrine_Core::getLoadedModels(); @@ -1102,151 +1027,148 @@ public function exportSchema($directory = null) public function exportSortedClassesSql($classes, $groupByConnection = true) { - $connections = array(); - foreach ($classes as $class) { - $connection = Doctrine_Manager::getInstance()->getConnectionForComponent($class); - $connectionName = $connection->getName(); - - if ( ! isset($connections[$connectionName])) { - $connections[$connectionName] = array( - 'create_tables' => array(), - 'create_sequences' => array(), - 'create_indexes' => array(), - 'alters' => array(), - 'create_triggers' => array(), - ); - } - - $sql = $connection->export->exportClassesSql(array($class)); - - // Build array of all the creates - // We need these to happen first - foreach ($sql as $key => $query) { - // If create table statement - if (substr($query, 0, strlen('CREATE TABLE')) == 'CREATE TABLE') { - $connections[$connectionName]['create_tables'][] = $query; - - unset($sql[$key]); - continue; - } - - // If create sequence statement - if (substr($query, 0, strlen('CREATE SEQUENCE')) == 'CREATE SEQUENCE') { - $connections[$connectionName]['create_sequences'][] = $query; - - unset($sql[$key]); - continue; - } - - // If create index statement - if (preg_grep("/CREATE ([^ ]* )?INDEX/", array($query))) { - $connections[$connectionName]['create_indexes'][] = $query; - - unset($sql[$key]); - continue; - } - - // If alter table statement or oracle anonymous block enclosing alter - if (substr($query, 0, strlen('ALTER TABLE')) == 'ALTER TABLE' - || substr($query, 0, strlen('DECLARE')) == 'DECLARE') { - $connections[$connectionName]['alters'][] = $query; - - unset($sql[$key]); - continue; - } - - // If create trgger statement - if (substr($query, 0, strlen('CREATE TRIGGER')) == 'CREATE TRIGGER') { - $connections[$connectionName]['create_triggers'][] = $query; - - unset($sql[$key]); - continue; - } - - // If comment statement - if (substr($query, 0, strlen('COMMENT ON')) == 'COMMENT ON') { - $connections[$connectionName]['comments'][] = $query; - - unset($sql[$key]); - continue; - } - } - } - - // Loop over all the sql again to merge everything together so it is in the correct order - $build = array(); - foreach ($connections as $connectionName => $sql) { - $build[$connectionName] = array_unique(array_merge($sql['create_tables'], $sql['create_sequences'], $sql['create_indexes'], $sql['alters'], $sql['create_triggers'])); - } - - if ( ! $groupByConnection) { - $new = array(); - foreach($build as $connectionname => $sql) { - $new = array_unique(array_merge($new, $sql)); - } - $build = $new; - } - return $build; + $connections = array(); + foreach ($classes as $class) { + $connection = Doctrine_Manager::getInstance()->getConnectionForComponent($class); + $connectionName = $connection->getName(); + + if (!isset($connections[$connectionName])) { + $connections[$connectionName] = array( + 'create_tables' => array(), + 'create_sequences' => array(), + 'create_indexes' => array(), + 'alters' => array(), + 'create_triggers' => array(), + ); + } + + $sql = $connection->export->exportClassesSql(array($class)); + + // Build array of all the creates + // We need these to happen first + foreach ($sql as $key => $query) { + // If create table statement + if ('CREATE TABLE' == substr($query, 0, strlen('CREATE TABLE'))) { + $connections[$connectionName]['create_tables'][] = $query; + + unset($sql[$key]); + continue; + } + + // If create sequence statement + if ('CREATE SEQUENCE' == substr($query, 0, strlen('CREATE SEQUENCE'))) { + $connections[$connectionName]['create_sequences'][] = $query; + + unset($sql[$key]); + continue; + } + + // If create index statement + if (preg_grep('/CREATE ([^ ]* )?INDEX/', array($query))) { + $connections[$connectionName]['create_indexes'][] = $query; + + unset($sql[$key]); + continue; + } + + // If alter table statement or oracle anonymous block enclosing alter + if ('ALTER TABLE' == substr($query, 0, strlen('ALTER TABLE')) + || 'DECLARE' == substr($query, 0, strlen('DECLARE'))) { + $connections[$connectionName]['alters'][] = $query; + + unset($sql[$key]); + continue; + } + + // If create trgger statement + if ('CREATE TRIGGER' == substr($query, 0, strlen('CREATE TRIGGER'))) { + $connections[$connectionName]['create_triggers'][] = $query; + + unset($sql[$key]); + continue; + } + + // If comment statement + if ('COMMENT ON' == substr($query, 0, strlen('COMMENT ON'))) { + $connections[$connectionName]['comments'][] = $query; + + unset($sql[$key]); + continue; + } + } + } + + // Loop over all the sql again to merge everything together so it is in the correct order + $build = array(); + foreach ($connections as $connectionName => $sql) { + $build[$connectionName] = array_unique(array_merge($sql['create_tables'], $sql['create_sequences'], $sql['create_indexes'], $sql['alters'], $sql['create_triggers'])); + } + + if (!$groupByConnection) { + $new = array(); + foreach ($build as $connectionname => $sql) { + $new = array_unique(array_merge($new, $sql)); + } + $build = $new; + } + + return $build; } /** * exportClasses - * method for exporting Doctrine_Record classes to a schema + * method for exporting Doctrine_Record classes to a schema. * * FIXME: This function has ugly hacks in it to make sure sql is inserted in the correct order. * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @param array $classes - * @return void + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ - public function exportClasses(array $classes) - { - $queries = $this->exportSortedClassesSql($classes); - - foreach ($queries as $connectionName => $sql) { - $connection = Doctrine_Manager::getInstance()->getConnection($connectionName); - - $connection->beginTransaction(); - - foreach ($sql as $query) { - try { - $connection->exec($query); - } catch (Doctrine_Connection_Exception $e) { - // we only want to silence table already exists errors - if ($e->getPortableCode() !== Doctrine_Core::ERR_ALREADY_EXISTS) { - $connection->rollback(); - throw new Doctrine_Export_Exception($e->getMessage() . '. Failing Query: ' . $query); - } - } - } - - $connection->commit(); - } - } + public function exportClasses(array $classes) + { + $queries = $this->exportSortedClassesSql($classes); + + foreach ($queries as $connectionName => $sql) { + $connection = Doctrine_Manager::getInstance()->getConnection($connectionName); + + $connection->beginTransaction(); + + foreach ($sql as $query) { + try { + $connection->exec($query); + } catch (Doctrine_Connection_Exception $e) { + // we only want to silence table already exists errors + if (Doctrine_Core::ERR_ALREADY_EXISTS !== $e->getPortableCode()) { + $connection->rollback(); + throw new Doctrine_Export_Exception($e->getMessage().'. Failing Query: '.$query); + } + } + } + + $connection->commit(); + } + } /** * exportClassesSql - * method for exporting Doctrine_Record classes to a schema + * method for exporting Doctrine_Record classes to a schema. * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @param array $classes - * @return void + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function exportClassesSql(array $classes) { $models = Doctrine_Core::filterInvalidModels($classes); - + $sql = array(); - + foreach ($models as $name) { $record = new $name(); $table = $record->getTable(); $parents = $table->getOption('joinedParents'); foreach ($parents as $parent) { - $data = $table->getConnection()->getTable($parent)->getExportableFormat(); + $data = $table->getConnection()->getTable($parent)->getExportableFormat(); $query = $this->conn->export->createTableSql($data['tableName'], $data['columns'], $data['options']); @@ -1254,7 +1176,7 @@ public function exportClassesSql(array $classes) } // Don't export the tables with attribute EXPORT_NONE' - if ($table->getAttribute(Doctrine_Core::ATTR_EXPORT) === Doctrine_Core::EXPORT_NONE) { + if (Doctrine_Core::EXPORT_NONE === $table->getAttribute(Doctrine_Core::ATTR_EXPORT)) { continue; } @@ -1271,38 +1193,39 @@ public function exportClassesSql(array $classes) if ($table->getAttribute(Doctrine_Core::ATTR_EXPORT) & Doctrine_Core::EXPORT_PLUGINS) { $sql = array_merge($sql, $this->exportGeneratorsSql($table)); } - + // DC-474: Remove dummy $record from repository to not pollute it during export $table->getRepository()->evict($record->getOid()); unset($record); } - + $sql = array_unique($sql); - + rsort($sql); return $sql; } /** - * fetches all generators recursively for given table + * fetches all generators recursively for given table. * - * @param Doctrine_Table $table table object to retrieve the generators from - * @return array an array of Doctrine_Record_Generator objects + * @param Doctrine_Table $table table object to retrieve the generators from + * + * @return array an array of Doctrine_Record_Generator objects */ public function getAllGenerators(Doctrine_Table $table) { $generators = array(); foreach ($table->getGenerators() as $name => $generator) { - if ($generator === null) { - continue; + if (null === $generator) { + continue; } $generators[] = $generator; $generatorTable = $generator->getTable(); - + if ($generatorTable instanceof Doctrine_Table) { $generators = array_merge($generators, $this->getAllGenerators($generatorTable)); } @@ -1313,18 +1236,19 @@ public function getAllGenerators(Doctrine_Table $table) /** * exportGeneratorsSql - * exports plugin tables for given table + * exports plugin tables for given table. + * + * @param Doctrine_Table $table the table in which the generators belong to * - * @param Doctrine_Table $table the table in which the generators belong to - * @return array an array of sql strings + * @return array an array of sql strings */ public function exportGeneratorsSql(Doctrine_Table $table) { - $sql = array(); + $sql = array(); foreach ($this->getAllGenerators($table) as $name => $generator) { $table = $generator->getTable(); - + // Make sure plugin has a valid table if ($table instanceof Doctrine_Table) { $data = $table->getExportableFormat(); @@ -1340,7 +1264,7 @@ public function exportGeneratorsSql(Doctrine_Table $table) /** * exportSql - * returns the sql for exporting Doctrine_Record classes to a schema + * returns the sql for exporting Doctrine_Record classes to a schema. * * if the directory parameter is given this method first iterates * recursively trhough the given directory in order to find any model classes @@ -1348,30 +1272,31 @@ public function exportGeneratorsSql(Doctrine_Table $table) * Then it iterates through all declared classes and creates tables for the ones * that extend Doctrine_Record and are not abstract classes * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @param string $directory optional directory parameter - * @return void + * @param string $directory optional directory parameter + * + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function exportSql($directory = null) { - if ($directory !== null) { + if (null !== $directory) { $models = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($directory)); } else { $models = Doctrine_Core::getLoadedModels(); } - + return $this->exportSortedClassesSql($models, false); } /** * exportTable - * exports given table into database based on column and option definitions + * exports given table into database based on column and option definitions. + * + * @return bool whether or not the export operation was successful + * false if table already existed in the database * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @return boolean whether or not the export operation was successful - * false if table already existed in the database + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function exportTable(Doctrine_Table $table) { @@ -1379,9 +1304,9 @@ public function exportTable(Doctrine_Table $table) $data = $table->getExportableFormat(); $this->conn->export->createTable($data['tableName'], $data['columns'], $data['options']); - } catch(Doctrine_Connection_Exception $e) { + } catch (Doctrine_Connection_Exception $e) { // we only want to silence table already exists errors - if ($e->getPortableCode() !== Doctrine_Core::ERR_ALREADY_EXISTS) { + if (Doctrine_Core::ERR_ALREADY_EXISTS !== $e->getPortableCode()) { throw $e; } } diff --git a/lib/Doctrine/Export/Exception.php b/lib/Doctrine/Export/Exception.php index cb27a7595..7a3926ac7 100644 --- a/lib/Doctrine/Export/Exception.php +++ b/lib/Doctrine/Export/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Export_Exception + * Doctrine_Export_Exception. * - * @package Doctrine - * @subpackage Export * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Export_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Export/Mssql.php b/lib/Doctrine/Export/Mssql.php index 30db562fa..521813f18 100644 --- a/lib/Doctrine/Export/Mssql.php +++ b/lib/Doctrine/Export/Mssql.php @@ -20,77 +20,77 @@ */ /** - * Doctrine_Export_Mssql + * Doctrine_Export_Mssql. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @author Frank M. Kromann (PEAR MDB2 Mssql driver) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7660 $ */ class Doctrine_Export_Mssql extends Doctrine_Export { - /** - * create a new database + /** + * create a new database. * * @param string $name name of the database that should be created - * @return void */ public function createDatabase($name) { $name = $this->conn->quoteIdentifier($name, true); - $query = "CREATE DATABASE $name"; + $query = "CREATE DATABASE {$name}"; $options = $this->conn->getOptions(); if (isset($options['database_device']) && $options['database_device']) { - $query.= ' ON '.$this->conn->options['database_device']; - $query.= $this->conn->options['database_size'] ? '=' . + $query .= ' ON '.$this->conn->options['database_device']; + $query .= $this->conn->options['database_size'] ? '='. $this->conn->options['database_size'] : ''; } + return $this->conn->standaloneQuery($query, array(), true); } /** - * drop an existing database + * drop an existing database. * * @param string $name name of the database that should be dropped - * @return void */ public function dropDatabase($name) { $name = $this->conn->quoteIdentifier($name, true); - return $this->conn->standaloneQuery('DROP DATABASE ' . $name, array(), true); + + return $this->conn->standaloneQuery('DROP DATABASE '.$name, array(), true); } /** * Override the parent method. * - * @return string The string required to be placed between "CREATE" and "TABLE" - * to generate a temporary table, if possible. + * @return string the string required to be placed between "CREATE" and "TABLE" + * to generate a temporary table, if possible */ public function getTemporaryTableQuery() { return ''; - } + } public function dropIndexSql($table, $name) { $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name)); $table = $this->conn->quoteIdentifier($table); - return 'DROP INDEX ' . $name . ' ON ' . $table; + return 'DROP INDEX '.$name.' ON '.$table; } /** - * alter an existing table + * alter an existing table. * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -103,78 +103,13 @@ public function dropIndexSql($table, $name) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the Metabase parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the Metabase parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @return void + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise */ public function alterTable($name, array $changes, $check = false) { - if ( !$name ) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } @@ -187,7 +122,7 @@ public function alterTable($name, array $changes, $check = false) case 'change': break; default: - throw new Doctrine_Export_Exception('alterTable: change type "' . $changeName . '" not yet supported'); + throw new Doctrine_Export_Exception('alterTable: change type "'.$changeName.'" not yet supported'); } } @@ -195,11 +130,10 @@ public function alterTable($name, array $changes, $check = false) return true; } - $query = ''; - $postQueries = ''; //SQL Server uses a stored procedure to rename objects + $postQueries = ''; // SQL Server uses a stored procedure to rename objects - if ( ! empty($changes['name'])) { + if (!empty($changes['name'])) { $changeName = $this->conn->quoteIdentifier($changes['name'], true); $postQueries .= sprintf( @@ -209,47 +143,46 @@ public function alterTable($name, array $changes, $check = false) ); } - //ADD TABLE - if ( ! empty($changes['add']) && is_array($changes['add'])) { + // ADD TABLE + if (!empty($changes['add']) && is_array($changes['add'])) { foreach ($changes['add'] as $fieldName => $field) { if ($query) { $query .= ', '; } - $query .= 'ADD ' . $this->getDeclaration($fieldName, $field); + $query .= 'ADD '.$this->getDeclaration($fieldName, $field); } } - //REMOVE TABLE - if ( ! empty($changes['remove']) && is_array($changes['remove'])) { - if ($query) { - $query .= ', '; - } + // REMOVE TABLE + if (!empty($changes['remove']) && is_array($changes['remove'])) { + if ($query) { + $query .= ', '; + } $query .= 'DROP COLUMN '; $dropped = array(); foreach ($changes['remove'] as $fieldName => $field) { - $fieldName = $this->conn->quoteIdentifier($fieldName, true); $dropped[] = $fieldName; } - $query .= implode(', ', $dropped) . ' '; + $query .= implode(', ', $dropped).' '; } $rename = array(); - if ( ! empty($changes['rename']) && is_array($changes['rename'])) { + if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { $rename[$field['name']] = $fieldName; } } - //CHANGE (COLUMN DEFINITION) - if ( ! empty($changes['change']) && is_array($changes['change'])) { + // CHANGE (COLUMN DEFINITION) + if (!empty($changes['change']) && is_array($changes['change'])) { if ($query) { - $query.= ', '; + $query .= ', '; } - $query .= "ALTER COLUMN "; + $query .= 'ALTER COLUMN '; $altered = array(); foreach ($changes['change'] as $fieldName => $field) { @@ -267,9 +200,9 @@ public function alterTable($name, array $changes, $check = false) // Remove the default constraint declaration from the statement $altered[] = str_replace($matches[0], '', $declaration); - if (count($matches) === 6) { + if (6 === count($matches)) { // No constraint name provided. Try to make sure it's unique - $defaultName = 'DF__' . $name . '__' . $fieldName . '__' . mt_rand(); + $defaultName = 'DF__'.$name.'__'.$fieldName.'__'.mt_rand(); $defaultValue = $matches[5]; } else { $defaultName = $matches[2]; @@ -289,15 +222,14 @@ public function alterTable($name, array $changes, $check = false) } $query .= implode(sprintf( - "; ALTER TABLE %s ALTER COLUMN ", + '; ALTER TABLE %s ALTER COLUMN ', $this->conn->quoteIdentifier($name, true) - ), $altered) . ' '; + ), $altered).' '; } - //RENAME (COLUMN) - if ( ! empty($rename) && is_array($rename)) { + // RENAME (COLUMN) + if (!empty($rename) && is_array($rename)) { foreach ($rename as $renameName => $renamedField) { - $field = $changes['rename'][$renamedField]; $renamedField = $this->conn->quoteIdentifier($renamedField); @@ -310,7 +242,7 @@ public function alterTable($name, array $changes, $check = false) } } - if ( ! $query && ! $postQueries) { + if (!$query && !$postQueries) { return false; } @@ -318,7 +250,7 @@ public function alterTable($name, array $changes, $check = false) $finalQuery = ''; if ($query) { - $finalQuery .= 'ALTER TABLE ' . $name . ' ' . trim($query) . ';'; + $finalQuery .= 'ALTER TABLE '.$name.' '.trim($query).';'; } if ($postQueries) { @@ -329,93 +261,95 @@ public function alterTable($name, array $changes, $check = false) } /** - * create sequence + * create sequence. * * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); + * * @return string */ public function createSequence($seqName, $start = 1, array $options = array()) { $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($seqName), true); $seqcolName = $this->conn->quoteIdentifier($this->conn->options['seqcol_name'], true); - $query = 'CREATE TABLE ' . $sequenceName . ' (' . $seqcolName . - ' INT PRIMARY KEY CLUSTERED IDENTITY(' . $start . ', 1) NOT NULL)'; + $query = 'CREATE TABLE '.$sequenceName.' ('.$seqcolName. + ' INT PRIMARY KEY CLUSTERED IDENTITY('.$start.', 1) NOT NULL)'; $res = $this->conn->exec($query); - if ($start == 1) { + if (1 == $start) { return true; } try { - $query = 'SET IDENTITY_INSERT ' . $sequenceName . ' ON ' . - 'INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES ( ' . $start . ')'; + $query = 'SET IDENTITY_INSERT '.$sequenceName.' ON '. + 'INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES ( '.$start.')'; $res = $this->conn->exec($query); } catch (Exception $e) { - $result = $this->conn->exec('DROP TABLE ' . $sequenceName); + $result = $this->conn->exec('DROP TABLE '.$sequenceName); } + return true; } /** - * This function drops an existing sequence + * This function drops an existing sequence. * - * @param string $seqName name of the sequence to be dropped - * @return void + * @param string $seqName name of the sequence to be dropped */ public function dropSequenceSql($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($seqName), true); - return 'DROP TABLE ' . $sequenceName; + + return 'DROP TABLE '.$sequenceName; } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. + * array( + * 'id' => array( + * 'type' => 'integer', + * 'unsigned' => 1 + * 'notnull' => 1 + * 'default' => 0 + * ), + * 'name' => array( + * 'type' => 'text', + * 'length' => 12 + * ), + * 'password' => array( + * 'type' => 'text', + * 'length' => 12 + * ) + * ); + * @param array $options An associative array of table options: * * @return string */ public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } if (empty($fields)) { - throw new Doctrine_Export_Exception('no fields specified for table ' . $name); + throw new Doctrine_Export_Exception('no fields specified for table '.$name); } // Use field declaration of primary if the primary option not set - if ( ! isset($options['primary'])) { + if (!isset($options['primary'])) { foreach ($fields as $fieldName => $fieldData) { if (isset($fieldData['primary']) && $fieldData['primary']) { $options['primary'][$fieldName] = $fieldName; @@ -426,38 +360,38 @@ public function createTableSql($name, array $fields, array $options = array()) if (isset($options['primary'])) { foreach ($options['primary'] as $fieldName) { if (isset($fields[$fieldName])) { - $fields[$fieldName]['notnull'] = true; //Silently forcing NOT NULL as MSSQL will kill a query that has a nullable PK + $fields[$fieldName]['notnull'] = true; // Silently forcing NOT NULL as MSSQL will kill a query that has a nullable PK } } } $queryFields = $this->getFieldDeclarationList($fields); - if (isset($options['primary']) && ! empty($options['primary'])) { + if (isset($options['primary']) && !empty($options['primary'])) { $primaryKeys = array_map(array($this->conn, 'quoteIdentifier'), array_values($options['primary'])); - $queryFields .= ', PRIMARY KEY(' . implode(', ', $primaryKeys) . ')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $primaryKeys).')'; } - $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields; - + $query = 'CREATE TABLE '.$this->conn->quoteIdentifier($name, true).' ('.$queryFields; + $check = $this->getCheckDeclaration($fields); - if ( ! empty($check)) { - $query .= ', ' . $check; + if (!empty($check)) { + $query .= ', '.$check; } $query .= ')'; $sql[] = $query; - - if (isset($options['indexes']) && ! empty($options['indexes'])) { - foreach($options['indexes'] as $index => $definition) { + + if (isset($options['indexes']) && !empty($options['indexes'])) { + foreach ($options['indexes'] as $index => $definition) { if (is_array($definition)) { - $sql[] = $this->createIndexSql($name,$index, $definition); + $sql[] = $this->createIndexSql($name, $index, $definition); } } } - + if (isset($options['foreignKeys'])) { foreach ((array) $options['foreignKeys'] as $k => $definition) { if (is_array($definition)) { @@ -474,51 +408,51 @@ public function createTableSql($name, array $fields, array $options = array()) * Obtain DBMS specific SQL code portion needed to set a NOT NULL * declaration to be used in statements like CREATE TABLE. * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @return string DBMS specific SQL code portion needed to set a default value */ public function getNotNullFieldDeclaration(array $definition) { return ( - (isset($definition['notnull']) && $definition['notnull']) || - (isset($definition['primary']) && $definition['primary']) + (isset($definition['notnull']) && $definition['notnull']) + || (isset($definition['primary']) && $definition['primary']) ) ? ' NOT NULL' : ' NULL'; } /** * @see Doctrine_Export::getDefaultFieldDeclaration * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @param array $field field definition array + * + * @return string DBMS specific SQL code portion needed to set a default value */ public function getDefaultFieldDeclaration($field) { $default = ''; if (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : $this->valid_default_values[$field['type']]; - if ($field['default'] === '' && - ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL)) { + if ('' === $field['default'] + && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL)) { $field['default'] = null; } } - if ($field['type'] === 'boolean') { + if ('boolean' === $field['type']) { $field['default'] = $this->conn->convertBooleans($field['default']); } if (array_key_exists('defaultConstraintName', $field)) { - $default .= ' CONSTRAINT ' . $field['defaultConstraintName']; + $default .= ' CONSTRAINT '.$field['defaultConstraintName']; } - $default .= ' DEFAULT ' . (is_null($field['default']) + $default .= ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'], $field['type'])); } - + return $default; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Export/Mysql.php b/lib/Doctrine/Export/Mysql.php index 097f68776..c7be961f8 100644 --- a/lib/Doctrine/Export/Mysql.php +++ b/lib/Doctrine/Export/Mysql.php @@ -20,104 +20,102 @@ */ /** - * Doctrine_Export_Mysql + * Doctrine_Export_Mysql. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7653 $ */ class Doctrine_Export_Mysql extends Doctrine_Export { /** - * drop existing constraint + * drop existing constraint. * - * @param string $table name of table that should be used in method - * @param string $name name of the constraint to be dropped - * @param string $primary hint if the constraint is primary - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the constraint to be dropped + * @param string $primary hint if the constraint is primary */ public function dropConstraint($table, $name, $primary = false) { $table = $this->conn->quoteIdentifier($table); - if ( ! $primary) { - $name = 'CONSTRAINT ' . $this->conn->quoteIdentifier($name); + if (!$primary) { + $name = 'CONSTRAINT '.$this->conn->quoteIdentifier($name); } else { $name = 'PRIMARY KEY'; } - return $this->conn->exec('ALTER TABLE ' . $table . ' DROP ' . $name); + return $this->conn->exec('ALTER TABLE '.$table.' DROP '.$name); } /** - * createDatabaseSql + * createDatabaseSql. * - * @param string $name - * @return void + * @param string $name */ public function createDatabaseSql($name) { - return 'CREATE DATABASE ' . $this->conn->quoteIdentifier($name, true); + return 'CREATE DATABASE '.$this->conn->quoteIdentifier($name, true); } /** - * drop an existing database + * drop an existing database. * * @param string $name name of the database that should be dropped + * * @return string */ public function dropDatabaseSql($name) { return array( 'SET FOREIGN_KEY_CHECKS = 0', - 'DROP DATABASE ' . $this->conn->quoteIdentifier($name), - 'SET FOREIGN_KEY_CHECKS = 1' + 'DROP DATABASE '.$this->conn->quoteIdentifier($name), + 'SET FOREIGN_KEY_CHECKS = 1', ); } /** - * create a new table - * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * 'type' => 'innodb', - * ); - * - * @return void + * create a new table. + * + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. + * array( + * 'id' => array( + * 'type' => 'integer', + * 'unsigned' => 1 + * 'notnull' => 1 + * 'default' => 0 + * ), + * 'name' => array( + * 'type' => 'text', + * 'length' => 12 + * ), + * 'password' => array( + * 'type' => 'text', + * 'length' => 12 + * ) + * ); + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * 'type' => 'innodb', + * ); */ - public function createTableSql($name, array $fields, array $options = array()) + public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); + } if (empty($fields)) { throw new Doctrine_Export_Exception('no fields specified for table "'.$name.'"'); @@ -132,34 +130,34 @@ public function createTableSql($name, array $fields, array $options = array()) if (isset($options['indexes'])) { foreach ($options['indexes'] as $definition) { if (is_string($definition['fields'])) { - // Check if index already exists on the column - $found = $found || ($local == $definition['fields']); - } else if (in_array($local, $definition['fields']) && count($definition['fields']) === 1) { + // Check if index already exists on the column + $found = $found || ($local == $definition['fields']); + } elseif (in_array($local, $definition['fields']) && 1 === count($definition['fields'])) { // Index already exists on the column $found = true; } } } - if (isset($options['primary']) && !empty($options['primary']) && - in_array($local, $options['primary'])) { + if (isset($options['primary']) && !empty($options['primary']) + && in_array($local, $options['primary'])) { // field is part of the PK and therefore already indexed $found = true; } - - if ( ! $found) { + + if (!$found) { if (is_array($local)) { - foreach($local as $localidx) { - $options['indexes'][$localidx] = array('fields' => array($localidx => array())); - } + foreach ($local as $localidx) { + $options['indexes'][$localidx] = array('fields' => array($localidx => array())); + } } else { - $options['indexes'][$local] = array('fields' => array($local => array())); + $options['indexes'][$local] = array('fields' => array($local => array())); } } } } // add all indexes - if (isset($options['indexes']) && ! empty($options['indexes'])) { + if (isset($options['indexes']) && !empty($options['indexes'])) { // Case Insensitive checking for duplicate indexes... $dupes = array(); foreach ($options['indexes'] as $key => $index) { @@ -171,30 +169,30 @@ public function createTableSql($name, array $fields, array $options = array()) } unset($dupes); - foreach($options['indexes'] as $index => $definition) { - $queryFields .= ', ' . $this->getIndexDeclaration($index, $definition); + foreach ($options['indexes'] as $index => $definition) { + $queryFields .= ', '.$this->getIndexDeclaration($index, $definition); } } // attach all primary keys - if (isset($options['primary']) && ! empty($options['primary'])) { + if (isset($options['primary']) && !empty($options['primary'])) { $keyColumns = array_values($options['primary']); $keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns); - $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $keyColumns).')'; } - $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields . ')'; + $query = 'CREATE TABLE '.$this->conn->quoteIdentifier($name, true).' ('.$queryFields.')'; $optionStrings = array(); if (isset($options['comment'])) { - $optionStrings['comment'] = 'COMMENT = ' . $this->conn->quote($options['comment'], 'text'); + $optionStrings['comment'] = 'COMMENT = '.$this->conn->quote($options['comment'], 'text'); } if (isset($options['charset'])) { - $optionStrings['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset']; + $optionStrings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; } if (isset($options['collate'])) { - $optionStrings['collate'] = 'COLLATE ' . $options['collate']; + $optionStrings['collate'] = 'COLLATE '.$options['collate']; } $type = false; @@ -207,22 +205,22 @@ public function createTableSql($name, array $fields, array $options = array()) } if ($type) { - $optionStrings[] = 'ENGINE = ' . $type; + $optionStrings[] = 'ENGINE = '.$type; } - if ( ! empty($optionStrings)) { - $query.= ' '.implode(' ', $optionStrings); + if (!empty($optionStrings)) { + $query .= ' '.implode(' ', $optionStrings); } $sql[] = $query; if (isset($options['foreignKeys'])) { - foreach ((array) $options['foreignKeys'] as $k => $definition) { if (is_array($definition)) { $sql[] = $this->createForeignKeySql($name, $definition); } } } + return $sql; } @@ -230,10 +228,10 @@ public function createTableSql($name, array $fields, array $options = array()) * Obtain DBMS specific SQL code portion needed to declare a generic type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param string $name name the field to be declared + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -255,54 +253,52 @@ public function createTableSql($name, array $fields, array $options = array()) * check * column check constraint * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getDeclaration($name, array $field) { + $default = $this->getDefaultFieldDeclaration($field); - $default = $this->getDefaultFieldDeclaration($field); - - $charset = (isset($field['charset']) && $field['charset']) ? - ' ' . $this->getCharsetFieldDeclaration($field['charset']) : ''; + $charset = (isset($field['charset']) && $field['charset']) ? + ' '.$this->getCharsetFieldDeclaration($field['charset']) : ''; $collation = (isset($field['collation']) && $field['collation']) ? - ' ' . $this->getCollationFieldDeclaration($field['collation']) : ''; + ' '.$this->getCollationFieldDeclaration($field['collation']) : ''; - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; + $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; - $unique = (isset($field['unique']) && $field['unique']) ? - ' ' . $this->getUniqueFieldDeclaration() : ''; + $unique = (isset($field['unique']) && $field['unique']) ? + ' '.$this->getUniqueFieldDeclaration() : ''; - $check = (isset($field['check']) && $field['check']) ? - ' ' . $field['check'] : ''; + $check = (isset($field['check']) && $field['check']) ? + ' '.$field['check'] : ''; - $comment = (isset($field['comment']) && $field['comment']) ? - " COMMENT " . $this->conn->quote($field['comment'], 'text') : ''; + $comment = (isset($field['comment']) && $field['comment']) ? + ' COMMENT '.$this->conn->quote($field['comment'], 'text') : ''; - $method = 'get' . $field['type'] . 'Declaration'; + $method = 'get'.$field['type'].'Declaration'; try { if (method_exists($this->conn->dataDict, $method)) { - return $this->conn->dataDict->$method($name, $field); - } else { - $dec = $this->conn->dataDict->getNativeDeclaration($field); + return $this->conn->dataDict->{$method}($name, $field); } - - return $this->conn->quoteIdentifier($name, true) - . ' ' . $dec . $charset . $default . $notnull . $comment . $unique . $check . $collation; + $dec = $this->conn->dataDict->getNativeDeclaration($field); + + return $this->conn->quoteIdentifier($name, true) + .' '.$dec.$charset.$default.$notnull.$comment.$unique.$check.$collation; } catch (Exception $e) { - throw new Doctrine_Exception('Around field ' . $name . ': ' . $e->getMessage() . "\n\n" . $e->getTraceAsString() . "\n\n"); + throw new Doctrine_Exception('Around field '.$name.': '.$e->getMessage()."\n\n".$e->getTraceAsString()."\n\n"); } } /** - * alter an existing table + * alter an existing table. * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -315,78 +311,15 @@ public function getDeclaration($name, array $field) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the Metabase parser. + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the Metabase parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @return boolean + * @return bool */ public function alterTableSql($name, array $changes, $check = false) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } foreach ($changes as $changeName => $change) { @@ -398,7 +331,7 @@ public function alterTableSql($name, array $changes, $check = false) case 'name': break; default: - throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported'); + throw new Doctrine_Export_Exception('change type "'.$changeName.'" not yet supported'); } } @@ -407,41 +340,41 @@ public function alterTableSql($name, array $changes, $check = false) } $query = ''; - if ( ! empty($changes['name'])) { + if (!empty($changes['name'])) { $change_name = $this->conn->quoteIdentifier($changes['name']); - $query .= 'RENAME TO ' . $change_name; + $query .= 'RENAME TO '.$change_name; } - if ( ! empty($changes['add']) && is_array($changes['add'])) { + if (!empty($changes['add']) && is_array($changes['add'])) { foreach ($changes['add'] as $fieldName => $field) { if ($query) { - $query.= ', '; + $query .= ', '; } - $query.= 'ADD ' . $this->getDeclaration($fieldName, $field); + $query .= 'ADD '.$this->getDeclaration($fieldName, $field); } } - if ( ! empty($changes['remove']) && is_array($changes['remove'])) { + if (!empty($changes['remove']) && is_array($changes['remove'])) { foreach ($changes['remove'] as $fieldName => $field) { if ($query) { $query .= ', '; } $fieldName = $this->conn->quoteIdentifier($fieldName); - $query .= 'DROP ' . $fieldName; + $query .= 'DROP '.$fieldName; } } $rename = array(); - if ( ! empty($changes['rename']) && is_array($changes['rename'])) { + if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { $rename[$field['name']] = $fieldName; } } - if ( ! empty($changes['change']) && is_array($changes['change'])) { + if (!empty($changes['change']) && is_array($changes['change'])) { foreach ($changes['change'] as $fieldName => $field) { if ($query) { - $query.= ', '; + $query .= ', '; } if (isset($rename[$fieldName])) { $oldFieldName = $rename[$fieldName]; @@ -450,62 +383,63 @@ public function alterTableSql($name, array $changes, $check = false) $oldFieldName = $fieldName; } $oldFieldName = $this->conn->quoteIdentifier($oldFieldName, true); - $query .= 'CHANGE ' . $oldFieldName . ' ' - . $this->getDeclaration($fieldName, $field['definition']); + $query .= 'CHANGE '.$oldFieldName.' ' + .$this->getDeclaration($fieldName, $field['definition']); } } - if ( ! empty($rename) && is_array($rename)) { + if (!empty($rename) && is_array($rename)) { foreach ($rename as $renameName => $renamedField) { if ($query) { - $query.= ', '; + $query .= ', '; } $field = $changes['rename'][$renamedField]; $renamedField = $this->conn->quoteIdentifier($renamedField, true); - $query .= 'CHANGE ' . $renamedField . ' ' - . $this->getDeclaration($field['name'], $field['definition']); + $query .= 'CHANGE '.$renamedField.' ' + .$this->getDeclaration($field['name'], $field['definition']); } } - if ( ! $query) { + if (!$query) { return false; } $name = $this->conn->quoteIdentifier($name, true); - - return 'ALTER TABLE ' . $name . ' ' . $query; + + return 'ALTER TABLE '.$name.' '.$query; } /** - * create sequence - * - * @param string $sequenceName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * 'type' => 'innodb', - * ); - * @return boolean + * create sequence. + * + * @param string $sequenceName name of the sequence to be created + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * 'type' => 'innodb', + * ); + * + * @return bool */ public function createSequence($sequenceName, $start = 1, array $options = array()) { - $sequenceName = $this->conn->quoteIdentifier($sequenceName, true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $sequenceName = $this->conn->quoteIdentifier($sequenceName, true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); $optionsStrings = array(); - if (isset($options['comment']) && ! empty($options['comment'])) { - $optionsStrings['comment'] = 'COMMENT = ' . $this->conn->quote($options['comment'], 'string'); + if (isset($options['comment']) && !empty($options['comment'])) { + $optionsStrings['comment'] = 'COMMENT = '.$this->conn->quote($options['comment'], 'string'); } - if (isset($options['charset']) && ! empty($options['charset'])) { - $optionsStrings['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset']; + if (isset($options['charset']) && !empty($options['charset'])) { + $optionsStrings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; if (isset($options['collate'])) { - $optionsStrings['charset'] .= ' COLLATE ' . $options['collate']; + $optionsStrings['charset'] .= ' COLLATE '.$options['collate']; } } @@ -517,53 +451,53 @@ public function createSequence($sequenceName, $start = 1, array $options = array $type = $this->conn->getAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_TYPE); } if ($type) { - $optionsStrings[] = 'ENGINE = ' . $type; + $optionsStrings[] = 'ENGINE = '.$type; } - try { - $query = 'CREATE TABLE ' . $sequenceName - . ' (' . $seqcolName . ' BIGINT NOT NULL AUTO_INCREMENT, PRIMARY KEY (' - . $seqcolName . ')) ' . implode(' ', $optionsStrings); + $query = 'CREATE TABLE '.$sequenceName + .' ('.$seqcolName.' BIGINT NOT NULL AUTO_INCREMENT, PRIMARY KEY (' + .$seqcolName.')) '.implode(' ', $optionsStrings); - $res = $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { + $res = $this->conn->exec($query); + } catch (Doctrine_Connection_Exception $e) { throw new Doctrine_Export_Exception('could not create sequence table'); } - if ($start == 1 && $res == 1) + if (1 == $start && 1 == $res) { return true; + } - $query = 'INSERT INTO ' . $sequenceName - . ' (' . $seqcolName . ') VALUES (' . ($start - 1) . ')'; + $query = 'INSERT INTO '.$sequenceName + .' ('.$seqcolName.') VALUES ('.($start - 1).')'; - $res = $this->conn->exec($query); + $res = $this->conn->exec($query); - if ($res == 1) + if (1 == $res) { return true; + } // Handle error try { - $result = $this->conn->exec('DROP TABLE ' . $sequenceName); - } catch(Doctrine_Connection_Exception $e) { + $result = $this->conn->exec('DROP TABLE '.$sequenceName); + } catch (Doctrine_Connection_Exception $e) { throw new Doctrine_Export_Exception('could not drop inconsistent sequence table'); } - - } /** - * Get the stucture of a field into an array + * Get the stucture of a field into an array. * * @author Leoncx - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. + * + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the index fields as array + * indexes. Each entry of this array is set to another type of associative + * array that specifies properties of the index that are specific to + * each field. * * Currently, only the sorting property is supported. It should be used * to define the sorting direction of the index. It may be set to either @@ -583,110 +517,107 @@ public function createSequence($sequenceName, $start = 1, array $options = array * 'last_login' => array() * ) * ) + * * @throws PDOException - * @return void */ public function createIndexSql($table, $name, array $definition) { - $table = $table; - $table = $this->conn->quoteIdentifier($table, true); + $table = $table; + $table = $this->conn->quoteIdentifier($table, true); - $name = $this->conn->formatter->getIndexName($name); - $name = $this->conn->quoteIdentifier($name); - $type = ''; + $name = $this->conn->formatter->getIndexName($name); + $name = $this->conn->quoteIdentifier($name); + $type = ''; if (isset($definition['type'])) { switch (strtolower($definition['type'])) { case 'fulltext': case 'unique': - $type = strtoupper($definition['type']) . ' '; - break; + $type = strtoupper($definition['type']).' '; + break; default: - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name . ' in table ' . $table - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name.' in table '.$table); } } - $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table; - $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')'; + $query = 'CREATE '.$type.'INDEX '.$name.' ON '.$table; + $query .= ' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; return $query; } - /** + /** * getDefaultDeclaration * Obtain DBMS specific SQL code portion needed to set a default value * declaration to be used in statements like CREATE TABLE. * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @param array $field field definition array + * + * @return string DBMS specific SQL code portion needed to set a default value */ public function getDefaultFieldDeclaration($field) { $default = ''; - if (isset($field['default']) && ( ! isset($field['length']) || $field['length'] <= 255)) { - if ($field['default'] === '') { + if (isset($field['default']) && (!isset($field['length']) || $field['length'] <= 255)) { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : $this->valid_default_values[$field['type']]; - if ($field['default'] === '' + if ('' === $field['default'] && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL) ) { $field['default'] = ' '; } } - + // Proposed patch: - if ($field['type'] == 'enum' && $this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) { + if ('enum' == $field['type'] && $this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) { $fieldType = 'varchar'; } else { $fieldType = $field['type']; } - - $default = ' DEFAULT ' . (is_null($field['default']) - ? 'NULL' + + $default = ' DEFAULT '.(is_null($field['default']) + ? 'NULL' : $this->conn->quote($field['default'], $fieldType)); - //$default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']); + // $default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']); } - + return $default; } /** - * Obtain DBMS specific SQL code portion needed to set an index + * Obtain DBMS specific SQL code portion needed to set an index * declaration to be used in statements like CREATE TABLE. * - * @param string $charset name of the index - * @param array $definition index definition - * @return string DBMS specific SQL code portion needed to set an index + * @param array $definition index definition + * + * @return string DBMS specific SQL code portion needed to set an index */ public function getIndexDeclaration($name, array $definition) { - $name = $this->conn->formatter->getIndexName($name); - $type = ''; + $name = $this->conn->formatter->getIndexName($name); + $type = ''; if (isset($definition['type'])) { switch (strtolower($definition['type'])) { case 'fulltext': case 'unique': - $type = strtoupper($definition['type']) . ' '; - break; + $type = strtoupper($definition['type']).' '; + break; default: - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name); } } - - if ( ! isset($definition['fields'])) { - throw new Doctrine_Export_Exception('No columns given for index ' . $name); + + if (!isset($definition['fields'])) { + throw new Doctrine_Export_Exception('No columns given for index '.$name); } - if ( ! is_array($definition['fields'])) { + if (!is_array($definition['fields'])) { $definition['fields'] = array($definition['fields']); } - $query = $type . 'INDEX ' . $this->conn->quoteIdentifier($name); + $query = $type.'INDEX '.$this->conn->quoteIdentifier($name); + + $query .= ' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; - $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')'; - return $query; } @@ -706,7 +637,7 @@ public function getIndexFieldDeclarationList(array $fields) if (is_array($field)) { if (isset($field['length'])) { - $fieldString .= '(' . $field['length'] . ')'; + $fieldString .= '('.$field['length'].')'; } if (isset($field['sorting'])) { @@ -714,7 +645,7 @@ public function getIndexFieldDeclarationList(array $fields) switch ($sort) { case 'ASC': case 'DESC': - $fieldString .= ' ' . $sort; + $fieldString .= ' '.$sort; break; default: throw new Doctrine_Export_Exception('Unknown index sorting option given.'); @@ -725,6 +656,7 @@ public function getIndexFieldDeclarationList(array $fields) } $declFields[] = $fieldString; } + return implode(', ', $declFields); } @@ -757,63 +689,63 @@ public function getCollationFieldDeclaration($collation) * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition * @return string */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; - if ( ! empty($definition['match'])) { - $query .= ' MATCH ' . $definition['match']; + if (!empty($definition['match'])) { + $query .= ' MATCH '.$definition['match']; } - if ( ! empty($definition['onUpdate'])) { - $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialAction($definition['onUpdate']); + if (!empty($definition['onUpdate'])) { + $query .= ' ON UPDATE '.$this->getForeignKeyReferentialAction($definition['onUpdate']); } - if ( ! empty($definition['onDelete'])) { - $query .= ' ON DELETE ' . $this->getForeignKeyReferentialAction($definition['onDelete']); + if (!empty($definition['onDelete'])) { + $query .= ' ON DELETE '.$this->getForeignKeyReferentialAction($definition['onDelete']); } + return $query; } /** - * drop existing index + * drop existing index. * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the index to be dropped */ public function dropIndexSql($table, $name) { - $table = $this->conn->quoteIdentifier($table, true); - $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name), true); - return 'DROP INDEX ' . $name . ' ON ' . $table; + $table = $this->conn->quoteIdentifier($table, true); + $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name), true); + + return 'DROP INDEX '.$name.' ON '.$table; } /** - * dropTable + * dropTable. + * + * @param string $table name of table that should be dropped from the database * - * @param string $table name of table that should be dropped from the database * @throws PDOException - * @return void */ public function dropTableSql($table) { - $table = $this->conn->quoteIdentifier($table, true); - return 'DROP TABLE ' . $table; + $table = $this->conn->quoteIdentifier($table, true); + + return 'DROP TABLE '.$table; } /** - * drop existing foreign key + * drop existing foreign key. * - * @param string $table name of table that should be used in method - * @param string $name name of the foreign key to be dropped - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the foreign key to be dropped */ public function dropForeignKey($table, $name) { $table = $this->conn->quoteIdentifier($table); - $name = $this->conn->quoteIdentifier($this->conn->formatter->getForeignKeyName($name)); + $name = $this->conn->quoteIdentifier($this->conn->formatter->getForeignKeyName($name)); - return $this->conn->exec('ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $name); + return $this->conn->exec('ALTER TABLE '.$table.' DROP FOREIGN KEY '.$name); } } diff --git a/lib/Doctrine/Export/Oracle.php b/lib/Doctrine/Export/Oracle.php index 0fea53d35..53a8802e4 100644 --- a/lib/Doctrine/Export/Oracle.php +++ b/lib/Doctrine/Export/Oracle.php @@ -20,59 +20,59 @@ */ /** - * Doctrine_Export_Oracle + * Doctrine_Export_Oracle. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Export_Oracle extends Doctrine_Export { /** - * create a new database + * create a new database. * - * @param object $db database object that is extended by this class * @param string $name name of the database that should be created - * @return boolean success of operation + * + * @return bool success of operation */ public function createDatabase($name) { if ($this->conn->getAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE)) { - $username = $name; - $password = $this->conn->dsn['password'] ? $this->conn->dsn['password'] : $name; + $username = $name; + $password = $this->conn->dsn['password'] ? $this->conn->dsn['password'] : $name; $tablespace = $this->conn->options['default_tablespace'] ? ' DEFAULT TABLESPACE '.$this->conn->options['default_tablespace'] : ''; - $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password . $tablespace; + $query = 'CREATE USER '.$username.' IDENTIFIED BY '.$password.$tablespace; $result = $this->conn->exec($query); try { - $query = 'GRANT CREATE SESSION, CREATE TABLE, UNLIMITED TABLESPACE, CREATE SEQUENCE, CREATE TRIGGER TO ' . $username; + $query = 'GRANT CREATE SESSION, CREATE TABLE, UNLIMITED TABLESPACE, CREATE SEQUENCE, CREATE TRIGGER TO '.$username; $result = $this->conn->exec($query); } catch (Exception $e) { $this->dropDatabase($username); } } + return true; } /** - * drop an existing database + * drop an existing database. * - * @param object $this->conn database object that is extended by this class * @param string $name name of the database that should be dropped - * @return boolean success of operation - * @access public + * + * @return bool success of operation */ public function dropDatabase($name) { - $sql = <<conn->getAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE)) { $username = $name; - $this->conn->exec('DROP USER ' . $username . ' CASCADE'); + $this->conn->exec('DROP USER '.$username.' CASCADE'); } } /** - * add an autoincrement sequence + trigger + * add an autoincrement sequence + trigger. * * @param string $name name of the PK field * @param string $table name of the table * @param string $start start value for the sequence - * @return string Sql code - * @access private + * + * @return string Sql code */ public function _makeAutoincrement($name, $table, $start = 1) { - $sql = array(); + $sql = array(); - if ( ! $this->conn->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { - $table = strtoupper($table); + if (!$this->conn->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { + $table = strtoupper($table); } - $indexName = $table . '_AI_PK'; + $indexName = $table.'_AI_PK'; $definition = array( 'primary' => true, 'fields' => array($name => true), ); - + $sql[] = 'DECLARE constraints_Count NUMBER; BEGIN @@ -125,10 +125,10 @@ public function _makeAutoincrement($name, $table, $start = 1) IF constraints_Count = 0 THEN EXECUTE IMMEDIATE \''.$this->createConstraintSql($table, $indexName, $definition).'\'; END IF; -END;'; - +END;'; + if (is_null($start)) { - $query = 'SELECT MAX(' . $this->conn->quoteIdentifier($name, true) . ') FROM ' . $this->conn->quoteIdentifier($table, true); + $query = 'SELECT MAX('.$this->conn->quoteIdentifier($name, true).') FROM '.$this->conn->quoteIdentifier($table, true); $start = $this->conn->fetchOne($query); ++$start; @@ -137,50 +137,50 @@ public function _makeAutoincrement($name, $table, $start = 1) $sql[] = $this->createSequenceSql($table, $start); $sequenceName = $this->conn->formatter->getSequenceName($table); - $triggerName = $this->conn->quoteIdentifier($table . '_AI_PK', true); + $triggerName = $this->conn->quoteIdentifier($table.'_AI_PK', true); $table = $this->conn->quoteIdentifier($table, true); - $name = $this->conn->quoteIdentifier($name, true); - $sql[] = 'CREATE TRIGGER ' . $triggerName . ' + $name = $this->conn->quoteIdentifier($name, true); + $sql[] = 'CREATE TRIGGER '.$triggerName.' BEFORE INSERT - ON ' . $table . ' + ON '.$table.' FOR EACH ROW DECLARE last_Sequence NUMBER; last_InsertID NUMBER; BEGIN - IF (:NEW.' . $name . ' IS NULL OR :NEW.'.$name.' = 0) THEN - SELECT ' . $this->conn->quoteIdentifier($sequenceName) . '.NEXTVAL INTO :NEW.' . $name . ' FROM DUAL; + IF (:NEW.'.$name.' IS NULL OR :NEW.'.$name.' = 0) THEN + SELECT '.$this->conn->quoteIdentifier($sequenceName).'.NEXTVAL INTO :NEW.'.$name.' FROM DUAL; ELSE SELECT NVL(Last_Number, 0) INTO last_Sequence FROM User_Sequences - WHERE UPPER(Sequence_Name) = UPPER(\'' . $sequenceName . '\'); - SELECT :NEW.' . $name . ' INTO last_InsertID FROM DUAL; + WHERE UPPER(Sequence_Name) = UPPER(\''.$sequenceName.'\'); + SELECT :NEW.'.$name.' INTO last_InsertID FROM DUAL; WHILE (last_InsertID > last_Sequence) LOOP - SELECT ' . $this->conn->quoteIdentifier($sequenceName) . '.NEXTVAL INTO last_Sequence FROM DUAL; + SELECT '.$this->conn->quoteIdentifier($sequenceName).'.NEXTVAL INTO last_Sequence FROM DUAL; END LOOP; END IF; END;'; + return $sql; } /** - * drop an existing autoincrement sequence + trigger + * drop an existing autoincrement sequence + trigger. * * @param string $table name of the table - * @return void */ public function dropAutoincrement($table) { $table = strtoupper($table); - $triggerName = $table . '_AI_PK'; + $triggerName = $table.'_AI_PK'; $trigger_name_quoted = $this->conn->quote($triggerName); $query = 'SELECT trigger_name FROM user_triggers'; - $query.= ' WHERE trigger_name='.$trigger_name_quoted.' OR trigger_name='.strtoupper($trigger_name_quoted); + $query .= ' WHERE trigger_name='.$trigger_name_quoted.' OR trigger_name='.strtoupper($trigger_name_quoted); $trigger = $this->conn->fetchOne($query); if ($trigger) { - $trigger_name = $this->conn->quoteIdentifier($table . '_AI_PK', true); - $trigger_sql = 'DROP TRIGGER ' . $trigger_name; + $trigger_name = $this->conn->quoteIdentifier($table.'_AI_PK', true); + $trigger_sql = 'DROP TRIGGER '.$trigger_name; // if throws exception, trigger for autoincrement PK could not be dropped $this->conn->exec($trigger_sql); @@ -188,18 +188,19 @@ public function dropAutoincrement($table) // if throws exception, sequence for autoincrement PK could not be dropped $this->dropSequence($table); - $indexName = $table . '_AI_PK'; + $indexName = $table.'_AI_PK'; // if throws exception, primary key for autoincrement PK could not be dropped $this->dropConstraint($table, $indexName); } } - /** + + /** * A method to return the required SQL string that fits between CREATE ... TABLE * to create the table as a temporary table. * - * @return string The string required to be placed between "CREATE" and "TABLE" - * to generate a temporary table, if possible. + * @return string the string required to be placed between "CREATE" and "TABLE" + * to generate a temporary table, if possible */ public function getTemporaryTableQuery() { @@ -211,15 +212,15 @@ public function getTemporaryTableQuery() * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition foreign key definition + * @param array $definition foreign key definition + * * @return string - * @access protected */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; - if (isset($definition['onDelete']) && strtoupper(trim($definition['onDelete'])) != 'NO ACTION') { - $query .= ' ON DELETE ' . $definition['onDelete']; + if (isset($definition['onDelete']) && 'NO ACTION' != strtoupper(trim($definition['onDelete']))) { + $query .= ' ON DELETE '.$definition['onDelete']; } if (isset($definition['deferrable'])) { $query .= ' DEFERRABLE'; @@ -231,17 +232,18 @@ public function getAdvancedForeignKeyOptions(array $definition) } else { $query .= ' INITIALLY IMMEDIATE'; } + return $query; } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. * * Example * array( @@ -261,9 +263,7 @@ public function getAdvancedForeignKeyOptions(array $definition) * 'length' => 12 * ) * ); - * @param array $options An associative array of table options: - * - * @return void + * @param array $options An associative array of table options: */ public function createTable($name, array $fields, array $options = array()) { @@ -277,13 +277,13 @@ public function createTable($name, array $fields, array $options = array()) } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. * * Example * array( @@ -303,95 +303,92 @@ public function createTable($name, array $fields, array $options = array()) * 'length' => 12 * ) * ); - * @param array $options An associative array of table options: - * - * @return void + * @param array $options An associative array of table options: */ public function createTableSql($name, array $fields, array $options = array()) { $sql = parent::createTableSql($name, $fields, $options); - if (isset($options['comment']) && ! empty($options['comment'])) { - $sql[] = $this->_createTableCommentSql($name, $options['comment']); - } + if (isset($options['comment']) && !empty($options['comment'])) { + $sql[] = $this->_createTableCommentSql($name, $options['comment']); + } foreach ($fields as $fieldName => $field) { if (isset($field['sequence'])) { - $sql[] = $this->createSequenceSql($field['sequence'], 1); + $sql[] = $this->createSequenceSql($field['sequence'], 1); } - if (isset($field['autoincrement']) && $field['autoincrement'] || - (isset($field['autoinc']) && $fields['autoinc'])) { + if (isset($field['autoincrement']) && $field['autoincrement'] + || (isset($field['autoinc']) && $fields['autoinc'])) { $sql = array_merge($sql, $this->_makeAutoincrement($fieldName, $name)); } - if (isset($field['comment']) && ! empty($field['comment'])){ - $sql[] = $this->_createColumnCommentSql($name,$fieldName,$field['comment']); + if (isset($field['comment']) && !empty($field['comment'])) { + $sql[] = $this->_createColumnCommentSql($name, $fieldName, $field['comment']); } } - - if (isset($options['indexes']) && ! empty($options['indexes'])) { + + if (isset($options['indexes']) && !empty($options['indexes'])) { foreach ($options['indexes'] as $indexName => $definition) { // create nonunique indexes, as they are a part od CREATE TABLE DDL - if ( ! isset($definition['type']) || - (isset($definition['type']) && strtolower($definition['type']) != 'unique')) { + if (!isset($definition['type']) + || (isset($definition['type']) && 'unique' != strtolower($definition['type']))) { $sql[] = $this->createIndexSql($name, $indexName, $definition); } } } - + return $sql; } /** - * create a comment on a table + * create a comment on a table. * - * @param string $table Name of the table we are commenting - * @param string $comment The comment for the table + * @param string $table Name of the table we are commenting + * @param string $comment The comment for the table * * @return string */ - public function _createTableCommentSql($table,$comment) + public function _createTableCommentSql($table, $comment) { - return 'COMMENT ON TABLE '. $this->conn->quoteIdentifier($table, true). ' IS '.$this->conn->quote($comment, 'text').''; + return 'COMMENT ON TABLE '.$this->conn->quoteIdentifier($table, true).' IS '.$this->conn->quote($comment, 'text').''; } /** - * create a comment on a column + * create a comment on a column. * - * @param string $table Name of the table - * @param string $column Name of the column we are commenting - * @param string $comment The comment for the table + * @param string $table Name of the table + * @param string $column Name of the column we are commenting + * @param string $comment The comment for the table * * @return string */ - public function _createColumnCommentSql($table,$column, $comment) + public function _createColumnCommentSql($table, $column, $comment) { - return 'COMMENT ON COLUMN '. $this->conn->quoteIdentifier($table, true). '.'. $this->conn->quoteIdentifier($column, true). ' IS '.$this->conn->quote($comment, 'text').''; + return 'COMMENT ON COLUMN '.$this->conn->quoteIdentifier($table, true).'.'.$this->conn->quoteIdentifier($column, true).' IS '.$this->conn->quote($comment, 'text').''; } /** - * drop an existing table + * drop an existing table. * * @param string $name name of the table that should be dropped - * @return void */ public function dropTable($name) { - //$this->conn->beginNestedTransaction(); + // $this->conn->beginNestedTransaction(); $result = $this->dropAutoincrement($name); - $result = parent::dropTable($name); - //$this->conn->completeNestedTransaction(); - return $result; + + return parent::dropTable($name); + // $this->conn->completeNestedTransaction(); } /** - * alter an existing table + * alter an existing table. * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -404,78 +401,12 @@ public function dropTable($name) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the MDB2 parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the MDB2 parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @return void + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise */ public function alterTable($name, array $changes, $check = false) { - foreach ($changes as $changeName => $change) { switch ($changeName) { case 'add': @@ -485,7 +416,7 @@ public function alterTable($name, array $changes, $check = false) case 'rename': break; default: - throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported'); + throw new Doctrine_Export_Exception('change type "'.$changeName.'" not yet supported'); } } @@ -495,112 +426,111 @@ public function alterTable($name, array $changes, $check = false) $name = $this->conn->quoteIdentifier($name, true); - if ( ! empty($changes['add']) && is_array($changes['add'])) { + if (!empty($changes['add']) && is_array($changes['add'])) { $fields = array(); foreach ($changes['add'] as $fieldName => $field) { - $fields[] = $this->getDeclaration($fieldName, $field); + $fields[] = $this->getDeclaration($fieldName, $field); } - $result = $this->conn->exec('ALTER TABLE ' . $name . ' ADD (' . implode(', ', $fields) . ')'); + $result = $this->conn->exec('ALTER TABLE '.$name.' ADD ('.implode(', ', $fields).')'); } - if ( ! empty($changes['change']) && is_array($changes['change'])) { + if (!empty($changes['change']) && is_array($changes['change'])) { $fields = array(); foreach ($changes['change'] as $fieldName => $field) { - $fields[] = $fieldName. ' ' . $this->getDeclaration('', $field['definition']); + $fields[] = $fieldName.' '.$this->getDeclaration('', $field['definition']); } - $result = $this->conn->exec('ALTER TABLE ' . $name . ' MODIFY (' . implode(', ', $fields) . ')'); + $result = $this->conn->exec('ALTER TABLE '.$name.' MODIFY ('.implode(', ', $fields).')'); } - if ( ! empty($changes['rename']) && is_array($changes['rename'])) { + if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { - $query = 'ALTER TABLE ' . $name . ' RENAME COLUMN ' . $this->conn->quoteIdentifier($fieldName, true) - . ' TO ' . $this->conn->quoteIdentifier($field['name']); + $query = 'ALTER TABLE '.$name.' RENAME COLUMN '.$this->conn->quoteIdentifier($fieldName, true) + .' TO '.$this->conn->quoteIdentifier($field['name']); $result = $this->conn->exec($query); } } - if ( ! empty($changes['remove']) && is_array($changes['remove'])) { + if (!empty($changes['remove']) && is_array($changes['remove'])) { $fields = array(); foreach ($changes['remove'] as $fieldName => $field) { $fields[] = $this->conn->quoteIdentifier($fieldName, true); } - $result = $this->conn->exec('ALTER TABLE ' . $name . ' DROP COLUMN ' . implode(', ', $fields)); + $result = $this->conn->exec('ALTER TABLE '.$name.' DROP COLUMN '.implode(', ', $fields)); } - if ( ! empty($changes['name'])) { + if (!empty($changes['name'])) { $changeName = $this->conn->quoteIdentifier($changes['name'], true); - $result = $this->conn->exec('ALTER TABLE ' . $name . ' RENAME TO ' . $changeName); + $result = $this->conn->exec('ALTER TABLE '.$name.' RENAME TO '.$changeName); } } /** - * create sequence + * create sequence. * * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); + * * @return string */ public function createSequenceSql($seqName, $start = 1, array $options = array()) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = 'CREATE SEQUENCE ' . $sequenceName . ' START WITH ' . $start . ' INCREMENT BY 1 NOCACHE'; - $query .= ($start < 1 ? ' MINVALUE ' . $start : ''); + $query = 'CREATE SEQUENCE '.$sequenceName.' START WITH '.$start.' INCREMENT BY 1 NOCACHE'; + $query .= ($start < 1 ? ' MINVALUE '.$start : ''); + return $query; } /** - * drop existing sequence + * drop existing sequence. * - * @param object $this->conn database object that is extended by this class * @param string $seqName name of the sequence to be dropped + * * @return string */ public function dropSequenceSql($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - return 'DROP SEQUENCE ' . $sequenceName; + + return 'DROP SEQUENCE '.$sequenceName; } /** * return Oracle's SQL code portion needed to set an index * declaration to be unsed in statements like CREATE TABLE. - * - * @param string $name name of the index - * @param array $definition index definition - * @return string Oracle's SQL code portion needed to set an index - */ + * + * @param string $name name of the index + * @param array $definition index definition + * + * @return string Oracle's SQL code portion needed to set an index + */ public function getIndexDeclaration($name, array $definition) { $name = $this->conn->quoteIdentifier($name); $type = ''; - - if ( isset($definition['type'])) - { - if (strtolower($definition['type']) == 'unique') { + + if (isset($definition['type'])) { + if ('unique' == strtolower($definition['type'])) { $type = strtoupper($definition['type']); } else { - throw new Doctrine_Export_Exception( - 'Unknown type '.$definition['type'] .' for index '.$name - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name); } } else { // only unique indexes should be defined in create table statement return null; } - - if ( !isset($definition['fields']) || !is_array($definition['fields'])) { + + if (!isset($definition['fields']) || !is_array($definition['fields'])) { throw new Doctrine_Export_Exception('No columns given for index '.$name); } - - $query = 'CONSTRAINT '.$name.' '.$type.' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; - - return $query; + + return 'CONSTRAINT '.$name.' '.$type.' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; } } diff --git a/lib/Doctrine/Export/Pgsql.php b/lib/Doctrine/Export/Pgsql.php index 6f1b106cf..6afbba5a5 100644 --- a/lib/Doctrine/Export/Pgsql.php +++ b/lib/Doctrine/Export/Pgsql.php @@ -20,15 +20,15 @@ */ /** - * Doctrine_Export_Pgsql + * Doctrine_Export_Pgsql. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7680 $ */ class Doctrine_Export_Pgsql extends Doctrine_Export @@ -36,30 +36,25 @@ class Doctrine_Export_Pgsql extends Doctrine_Export public $tmpConnectionDatabase = 'postgres'; /** - * createDatabaseSql + * createDatabaseSql. * - * @param string $name - * @return void + * @param string $name */ public function createDatabaseSql($name) { - $query = 'CREATE DATABASE ' . $this->conn->quoteIdentifier($name); - - return $query; + return 'CREATE DATABASE '.$this->conn->quoteIdentifier($name); } /** - * drop an existing database + * drop an existing database. * * @param string $name name of the database that should be dropped + * * @throws PDOException - * @access public */ public function dropDatabaseSql($name) { - $query = 'DROP DATABASE ' . $this->conn->quoteIdentifier($name); - - return $query; + return 'DROP DATABASE '.$this->conn->quoteIdentifier($name); } /** @@ -67,21 +62,21 @@ public function dropDatabaseSql($name) * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition foreign key definition + * @param array $definition foreign key definition + * * @return string - * @access protected */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; if (isset($definition['match'])) { - $query .= ' MATCH ' . $definition['match']; + $query .= ' MATCH '.$definition['match']; } if (isset($definition['onUpdate'])) { - $query .= ' ON UPDATE ' . $definition['onUpdate']; + $query .= ' ON UPDATE '.$definition['onUpdate']; } if (isset($definition['onDelete'])) { - $query .= ' ON DELETE ' . $definition['onDelete']; + $query .= ' ON DELETE '.$definition['onDelete']; } if (isset($definition['deferrable'])) { $query .= ' DEFERRABLE'; @@ -93,18 +88,21 @@ public function getAdvancedForeignKeyOptions(array $definition) } else { $query .= ' INITIALLY IMMEDIATE'; } + return $query; } /** - * generates the sql for altering an existing table on postgresql + * generates the sql for altering an existing table on postgresql. + * + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type * + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. * @see Doctrine_Export::alterTable() + * * @return array */ public function alterTableSql($name, array $changes, $check = false) @@ -118,28 +116,28 @@ public function alterTableSql($name, array $changes, $check = false) case 'rename': break; default: - throw new Doctrine_Export_Exception('change type "' . $changeName . '\" not yet supported'); + throw new Doctrine_Export_Exception('change type "'.$changeName.'\" not yet supported'); } } if ($check) { return true; } - + $sql = array(); if (isset($changes['add']) && is_array($changes['add'])) { foreach ($changes['add'] as $fieldName => $field) { - $query = 'ADD ' . $this->getDeclaration($fieldName, $field); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + $query = 'ADD '.$this->getDeclaration($fieldName, $field); + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } } if (isset($changes['remove']) && is_array($changes['remove'])) { foreach ($changes['remove'] as $fieldName => $field) { $fieldName = $this->conn->quoteIdentifier($fieldName, true); - $query = 'DROP ' . $fieldName; - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + $query = 'DROP '.$fieldName; + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } } @@ -152,16 +150,16 @@ public function alterTableSql($name, array $changes, $check = false) if (is_array($serverInfo) && $serverInfo['major'] < 8) { throw new Doctrine_Export_Exception('changing column type for "'.$field['type'].'\" requires PostgreSQL 8.0 or above'); } - $query = 'ALTER ' . $fieldName . ' TYPE ' . $this->conn->dataDict->getNativeDeclaration($field['definition']); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + $query = 'ALTER '.$fieldName.' TYPE '.$this->conn->dataDict->getNativeDeclaration($field['definition']); + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } if (array_key_exists('default', $field['definition'])) { - $query = 'ALTER ' . $fieldName . ' SET DEFAULT ' . $this->conn->quote($field['definition']['default'], $field['definition']['type']); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + $query = 'ALTER '.$fieldName.' SET DEFAULT '.$this->conn->quote($field['definition']['default'], $field['definition']['type']); + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } - if ( isset($field['definition']['notnull'])) { - $query = 'ALTER ' . $fieldName . ' ' . ($field['definition']['notnull'] ? 'SET' : 'DROP') . ' NOT NULL'; - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + if (isset($field['definition']['notnull'])) { + $query = 'ALTER '.$fieldName.' '.($field['definition']['notnull'] ? 'SET' : 'DROP').' NOT NULL'; + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } } } @@ -169,26 +167,26 @@ public function alterTableSql($name, array $changes, $check = false) if (isset($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { $fieldName = $this->conn->quoteIdentifier($fieldName, true); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' RENAME COLUMN ' . $fieldName . ' TO ' . $this->conn->quoteIdentifier($field['name'], true); + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' RENAME COLUMN '.$fieldName.' TO '.$this->conn->quoteIdentifier($field['name'], true); } } $name = $this->conn->quoteIdentifier($name, true); if (isset($changes['name'])) { $changeName = $this->conn->quoteIdentifier($changes['name'], true); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' RENAME TO ' . $changeName; + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' RENAME TO '.$changeName; } - + return $sql; } - + /** - * alter an existing table + * alter an existing table. * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -201,75 +199,13 @@ public function alterTableSql($name, array $changes, $check = false) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the Metabase parser. + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise * + * @return bool * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the Metabase parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. * @throws Doctrine_Connection_Exception - * @return boolean */ public function alterTable($name, array $changes, $check = false) { @@ -277,90 +213,91 @@ public function alterTable($name, array $changes, $check = false) foreach ($sql as $query) { $this->conn->exec($query); } - return true; + + return true; } /** - * return RDBMS specific create sequence statement + * return RDBMS specific create sequence statement. + * + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); * - * @throws Doctrine_Connection_Exception if something fails at database level - * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); * @return string + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function createSequenceSql($sequenceName, $start = 1, array $options = array()) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true); - return 'CREATE SEQUENCE ' . $sequenceName . ' INCREMENT 1' . - ($start < 1 ? ' MINVALUE ' . $start : '') . ' START ' . $start; + + return 'CREATE SEQUENCE '.$sequenceName.' INCREMENT 1'. + ($start < 1 ? ' MINVALUE '.$start : '').' START '.$start; } /** - * drop existing sequence + * drop existing sequence. * * @param string $sequenceName name of the sequence to be dropped */ public function dropSequenceSql($sequenceName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true); - return 'DROP SEQUENCE ' . $sequenceName; + + return 'DROP SEQUENCE '.$sequenceName; } /** * Creates a table. * * @param unknown_type $name - * @param array $fields - * @param array $options + * * @return unknown */ public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } - + if (empty($fields)) { - throw new Doctrine_Export_Exception('no fields specified for table ' . $name); + throw new Doctrine_Export_Exception('no fields specified for table '.$name); } $queryFields = $this->getFieldDeclarationList($fields); - - if (isset($options['primary']) && ! empty($options['primary'])) { + if (isset($options['primary']) && !empty($options['primary'])) { $keyColumns = array_values($options['primary']); $keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns); - $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $keyColumns).')'; } - $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields; + $query = 'CREATE TABLE '.$this->conn->quoteIdentifier($name, true).' ('.$queryFields; if ($check = $this->getCheckDeclaration($fields)) { - $query .= ', ' . $check; + $query .= ', '.$check; } if (isset($options['checks']) && $check = $this->getCheckDeclaration($options['checks'])) { - $query .= ', ' . $check; + $query .= ', '.$check; } $query .= ')'; $sql[] = $query; - if (isset($options['indexes']) && ! empty($options['indexes'])) { - foreach($options['indexes'] as $index => $definition) { + if (isset($options['indexes']) && !empty($options['indexes'])) { + foreach ($options['indexes'] as $index => $definition) { $sql[] = $this->createIndexSql($name, $index, $definition); } } - - if (isset($options['foreignKeys'])) { + if (isset($options['foreignKeys'])) { foreach ((array) $options['foreignKeys'] as $k => $definition) { if (is_array($definition)) { $sql[] = $this->createForeignKeySql($name, $definition); @@ -370,24 +307,28 @@ public function createTableSql($name, array $fields, array $options = array()) if (isset($options['sequenceName'])) { $sql[] = $this->createSequenceSql($options['sequenceName']); } + return $sql; } - /** + /** * Get the stucture of a field into an array. - * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. + * + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created + * * @see Doctrine_Export::createIndex() + * * @return string */ public function createIndexSql($table, $name, array $definition) { - $query = parent::createIndexSql($table, $name, $definition); - if (isset($definition['where'])) { - return $query . ' WHERE ' . $definition['where']; - } + $query = parent::createIndexSql($table, $name, $definition); + if (isset($definition['where'])) { + return $query.' WHERE '.$definition['where']; + } + return $query; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Export/Reporter.php b/lib/Doctrine/Export/Reporter.php index 742f39fac..fc0b6c037 100644 --- a/lib/Doctrine/Export/Reporter.php +++ b/lib/Doctrine/Export/Reporter.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Export_Reporter + * Doctrine_Export_Reporter. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Export_Reporter implements IteratorAggregate @@ -44,9 +44,9 @@ public function pop() return array_pop($this->messages); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->messages); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Export/Schema.php b/lib/Doctrine/Export/Schema.php index 9e67bf437..17436b3fd 100644 --- a/lib/Doctrine/Export/Schema.php +++ b/lib/Doctrine/Export/Schema.php @@ -20,40 +20,40 @@ */ /** - * Doctrine_Export_Schema - * + * Doctrine_Export_Schema. + * * Used for exporting a schema to a yaml file * - * @package Doctrine - * @subpackage Export - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision: 1838 $ + * * @author Nicolas Bérard-Nault * @author Jonathan H. Wage */ class Doctrine_Export_Schema -{ +{ /** - * buildSchema - * + * buildSchema. + * * Build schema array that can be dumped to file * - * @param string $directory The directory of models to build the schema from - * @param array $models The array of model names to build the schema for - * @param integer $modelLoading The model loading strategy to use to load the models from the passed directory - * @return void + * @param string $directory The directory of models to build the schema from + * @param array $models The array of model names to build the schema for + * @param int $modelLoading The model loading strategy to use to load the models from the passed directory */ public function buildSchema($directory = null, $models = array(), $modelLoading = null) { - if ($directory !== null) { + if (null !== $directory) { $loadedModels = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($directory, $modelLoading)); } else { $loadedModels = Doctrine_Core::getLoadedModels(); } - + $array = array(); - + $parent = new ReflectionClass('Doctrine_Record'); $sql = array(); @@ -62,24 +62,24 @@ public function buildSchema($directory = null, $models = array(), $modelLoading // we iterate through the diff of previously declared classes // and currently declared classes foreach ($loadedModels as $className) { - if ( ! empty($models) && !in_array($className, $models)) { + if (!empty($models) && !in_array($className, $models)) { continue; } $recordTable = Doctrine_Core::getTable($className); - + $data = $recordTable->getExportableFormat(); - + $table = array(); $table['connection'] = $recordTable->getConnection()->getName(); $remove = array('ptype', 'ntype', 'alltypes'); // Fix explicit length in schema, concat it to type in this format: type(length) - foreach ($data['columns'] AS $name => $column) { + foreach ($data['columns'] as $name => $column) { if (isset($column['length']) && $column['length'] && isset($column['scale']) && $column['scale']) { - $data['columns'][$name]['type'] = $column['type'] . '(' . $column['length'] . ', ' . $column['scale'] . ')'; + $data['columns'][$name]['type'] = $column['type'].'('.$column['length'].', '.$column['scale'].')'; unset($data['columns'][$name]['length'], $data['columns'][$name]['scale']); } else { - $data['columns'][$name]['type'] = $column['type'] . '(' . $column['length'] . ')'; + $data['columns'][$name]['type'] = $column['type'].'('.$column['length'].')'; unset($data['columns'][$name]['length']); } // Strip out schema information which is not necessary to be dumped to the yaml schema file @@ -88,10 +88,10 @@ public function buildSchema($directory = null, $models = array(), $modelLoading unset($data['columns'][$name][$value]); } } - + // If type is the only property of the column then lets abbreviate the syntax // columns: { name: string(255) } - if (count($data['columns'][$name]) === 1 && isset($data['columns'][$name]['type'])) { + if (1 === count($data['columns'][$name]) && isset($data['columns'][$name]['type'])) { $type = $data['columns'][$name]['type']; unset($data['columns'][$name]); $data['columns'][$name] = $type; @@ -99,56 +99,54 @@ public function buildSchema($directory = null, $models = array(), $modelLoading } $table['tableName'] = $data['tableName']; $table['columns'] = $data['columns']; - + $relations = $recordTable->getRelations(); foreach ($relations as $key => $relation) { $relationData = $relation->toArray(); - + $relationKey = $relationData['alias']; - + if (isset($relationData['refTable']) && $relationData['refTable']) { $table['relations'][$relationKey]['refClass'] = $relationData['refTable']->getComponentName(); } - + if (isset($relationData['class']) && $relationData['class'] && $relation['class'] != $relationKey) { $table['relations'][$relationKey]['class'] = $relationData['class']; } - + $table['relations'][$relationKey]['local'] = $relationData['local']; $table['relations'][$relationKey]['foreign'] = $relationData['foreign']; - - if ($relationData['type'] === Doctrine_Relation::ONE) { + + if (Doctrine_Relation::ONE === $relationData['type']) { $table['relations'][$relationKey]['type'] = 'one'; - } else if ($relationData['type'] === Doctrine_Relation::MANY) { + } elseif (Doctrine_Relation::MANY === $relationData['type']) { $table['relations'][$relationKey]['type'] = 'many'; } else { $table['relations'][$relationKey]['type'] = 'one'; } } - + $array[$className] = $table; } - + return $array; } /** - * exportSchema + * exportSchema. * - * @param string $schema - * @param string $directory - * @param string $string of data in the specified format - * @param integer $modelLoading The model loading strategy to use to load the models from the passed directory - * @return void + * @param string $schema + * @param string $directory + * @param int $modelLoading The model loading strategy to use to load the models from the passed directory */ public function exportSchema($schema, $format = 'yml', $directory = null, $models = array(), $modelLoading = null) { $array = $this->buildSchema($directory, $models, $modelLoading); - + if (is_dir($schema)) { - $schema = $schema . DIRECTORY_SEPARATOR . 'schema.' . $format; + $schema = $schema.DIRECTORY_SEPARATOR.'schema.'.$format; } - + return Doctrine_Parser::dump($array, $format, $schema); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Export/Sqlite.php b/lib/Doctrine/Export/Sqlite.php index f9b50580e..acaf5b3a7 100644 --- a/lib/Doctrine/Export/Sqlite.php +++ b/lib/Doctrine/Export/Sqlite.php @@ -20,66 +20,65 @@ */ /** - * Doctrine_Export_Sqlite + * Doctrine_Export_Sqlite. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Export_Sqlite extends Doctrine_Export { /** - * dropDatabase + * dropDatabase. * * drop an existing database * - * @param string $databaseFile Path of the database that should be dropped - * @throws Doctrine_Export_Exception if the database file does not exist - * @throws Doctrine_Export_Exception if something failed during the removal of the database file - * @return void + * @param string $databaseFile Path of the database that should be dropped + * + * @throws Doctrine_Export_Exception if the database file does not exist + * @throws Doctrine_Export_Exception if something failed during the removal of the database file */ public function dropDatabase($databaseFile) { - if ( ! @file_exists($databaseFile)) { + if (!@file_exists($databaseFile)) { throw new Doctrine_Export_Exception('database does not exist'); } $result = @unlink($databaseFile); - if ( ! $result) { + if (!$result) { throw new Doctrine_Export_Exception('could not remove the database file'); } } /** - * createDatabase + * createDatabase. * * Create sqlite database file * - * @param string $databaseFile Path of the database that should be dropped - * @return void + * @param string $databaseFile Path of the database that should be dropped */ public function createDatabase($databaseFile) { - return new PDO('sqlite:' . $databaseFile); + return new PDO('sqlite:'.$databaseFile); } /** - * Get the stucture of a field into an array + * Get the stucture of a field into an array. * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the index fields as array + * indexes. Each entry of this array is set to another type of associative + * array that specifies properties of the index that are specific to + * each field. * * Currently, only the sorting property is supported. It should be used * to define the sorting direction of the index. It may be set to either @@ -97,29 +96,27 @@ public function createDatabase($databaseFile) * 'last_login' => array() * ) * ) + * * @throws PDOException - * @return void */ public function createIndexSql($table, $name, array $definition) { - $name = $this->conn->formatter->getIndexName($name); - $name = $this->conn->quoteIdentifier($name); - $type = ''; + $name = $this->conn->formatter->getIndexName($name); + $name = $this->conn->quoteIdentifier($name); + $type = ''; if (isset($definition['type'])) { switch (strtolower($definition['type'])) { case 'unique': - $type = strtoupper($definition['type']) . ' '; - break; + $type = strtoupper($definition['type']).' '; + break; default: - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name . ' in table ' . $table - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name.' in table '.$table); } } - $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table; - $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')'; + $query = 'CREATE '.$type.'INDEX '.$name.' ON '.$table; + $query .= ' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; return $query; } @@ -129,7 +126,7 @@ public function createIndexSql($table, $name, array $definition) * Obtain DBMS specific SQL code portion needed to set an index * declaration to be used in statements like CREATE TABLE. * - * @return string + * @return string */ public function getIndexFieldDeclarationList(array $fields) { @@ -144,7 +141,7 @@ public function getIndexFieldDeclarationList(array $fields) switch ($sort) { case 'ASC': case 'DESC': - $fieldString .= ' ' . $sort; + $fieldString .= ' '.$sort; break; default: throw new Doctrine_Export_Exception('Unknown index sorting option given.'); @@ -155,79 +152,78 @@ public function getIndexFieldDeclarationList(array $fields) } $declFields[] = $fieldString; } + return implode(', ', $declFields); } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: - * - * @return void + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. + * array( + * 'id' => array( + * 'type' => 'integer', + * 'unsigned' => 1 + * 'notnull' => 1 + * 'default' => 0 + * ), + * 'name' => array( + * 'type' => 'text', + * 'length' => 12 + * ), + * 'password' => array( + * 'type' => 'text', + * 'length' => 12 + * ) + * ); + * @param array $options An associative array of table options: */ public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } - + if (empty($fields)) { throw new Doctrine_Export_Exception('no fields specified for table '.$name); } $queryFields = $this->getFieldDeclarationList($fields); - + $autoinc = false; - foreach($fields as $field) { - if (isset($field['autoincrement']) && $field['autoincrement'] || - (isset($field['autoinc']) && $field['autoinc'])) { + foreach ($fields as $field) { + if (isset($field['autoincrement']) && $field['autoincrement'] + || (isset($field['autoinc']) && $field['autoinc'])) { $autoinc = true; break; } } - if ( ! $autoinc && isset($options['primary']) && ! empty($options['primary'])) { + if (!$autoinc && isset($options['primary']) && !empty($options['primary'])) { $keyColumns = array_values($options['primary']); $keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns); - $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $keyColumns).')'; } - $name = $this->conn->quoteIdentifier($name, true); - $sql = 'CREATE TABLE ' . $name . ' (' . $queryFields; + $name = $this->conn->quoteIdentifier($name, true); + $sql = 'CREATE TABLE '.$name.' ('.$queryFields; if ($check = $this->getCheckDeclaration($fields)) { - $sql .= ', ' . $check; + $sql .= ', '.$check; } if (isset($options['checks']) && $check = $this->getCheckDeclaration($options['checks'])) { - $sql .= ', ' . $check; + $sql .= ', '.$check; } $sql .= ')'; $query[] = $sql; - if (isset($options['indexes']) && ! empty($options['indexes'])) { + if (isset($options['indexes']) && !empty($options['indexes'])) { foreach ($options['indexes'] as $index => $definition) { $query[] = $this->createIndexSql($name, $index, $definition); } @@ -241,21 +237,21 @@ public function createTableSql($name, array $fields, array $options = array()) * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition foreign key definition + * @param array $definition foreign key definition + * * @return string - * @access protected */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; if (isset($definition['match'])) { - $query .= ' MATCH ' . $definition['match']; + $query .= ' MATCH '.$definition['match']; } if (isset($definition['onUpdate'])) { - $query .= ' ON UPDATE ' . $definition['onUpdate']; + $query .= ' ON UPDATE '.$definition['onUpdate']; } if (isset($definition['onDelete'])) { - $query .= ' ON DELETE ' . $definition['onDelete']; + $query .= ' ON DELETE '.$definition['onDelete']; } if (isset($definition['deferrable'])) { $query .= ' DEFERRABLE'; @@ -267,43 +263,46 @@ public function getAdvancedForeignKeyOptions(array $definition) } else { $query .= ' INITIALLY IMMEDIATE'; } + return $query; } /** - * create sequence + * create sequence. + * + * @param string $seqName name of the sequence to be created + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); * - * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); - * @return boolean + * @return bool */ public function createSequence($seqName, $start = 1, array $options = array()) { - $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'CREATE TABLE ' . $sequenceName . ' (' . $seqcolName . ' INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)'; + $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $query = 'CREATE TABLE '.$sequenceName.' ('.$seqcolName.' INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)'; $this->conn->exec($query); - if ($start == 1) { + if (1 == $start) { return true; } try { - $this->conn->exec('INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (' . ($start-1) . ')'); + $this->conn->exec('INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES ('.($start - 1).')'); + return true; - } catch(Doctrine_Connection_Exception $e) { - // Handle error + } catch (Doctrine_Connection_Exception $e) { + // Handle error try { - $result = $db->exec('DROP TABLE ' . $sequenceName); - } catch(Doctrine_Connection_Exception $e) { + $result = $db->exec('DROP TABLE '.$sequenceName); + } catch (Doctrine_Connection_Exception $e) { throw new Doctrine_Export_Exception('could not drop inconsistent sequence table'); } } @@ -311,21 +310,22 @@ public function createSequence($seqName, $start = 1, array $options = array()) } /** - * drop existing sequence + * drop existing sequence. + * + * @param string $sequenceName name of the sequence to be dropped * - * @param string $sequenceName name of the sequence to be dropped * @return string */ public function dropSequenceSql($sequenceName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true); - return 'DROP TABLE ' . $sequenceName; + return 'DROP TABLE '.$sequenceName; } - + public function alterTableSql($name, array $changes, $check = false) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } foreach ($changes as $changeName => $change) { @@ -336,7 +336,7 @@ public function alterTableSql($name, array $changes, $check = false) case 'name': break; default: - throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported'); + throw new Doctrine_Export_Exception('change type "'.$changeName.'" not yet supported'); } } @@ -345,31 +345,31 @@ public function alterTableSql($name, array $changes, $check = false) } $query = ''; - if ( ! empty($changes['name'])) { + if (!empty($changes['name'])) { $change_name = $this->conn->quoteIdentifier($changes['name']); - $query .= 'RENAME TO ' . $change_name; + $query .= 'RENAME TO '.$change_name; } - if ( ! empty($changes['add']) && is_array($changes['add'])) { + if (!empty($changes['add']) && is_array($changes['add'])) { foreach ($changes['add'] as $fieldName => $field) { if ($query) { - $query.= ', '; + $query .= ', '; } - $query.= 'ADD ' . $this->getDeclaration($fieldName, $field); + $query .= 'ADD '.$this->getDeclaration($fieldName, $field); } } $rename = array(); - if ( ! empty($changes['rename']) && is_array($changes['rename'])) { + if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { $rename[$field['name']] = $fieldName; } } - if ( ! empty($changes['change']) && is_array($changes['change'])) { + if (!empty($changes['change']) && is_array($changes['change'])) { foreach ($changes['change'] as $fieldName => $field) { if ($query) { - $query.= ', '; + $query .= ', '; } if (isset($rename[$fieldName])) { $oldFieldName = $rename[$fieldName]; @@ -378,44 +378,45 @@ public function alterTableSql($name, array $changes, $check = false) $oldFieldName = $fieldName; } $oldFieldName = $this->conn->quoteIdentifier($oldFieldName, true); - $query .= 'CHANGE ' . $oldFieldName . ' ' - . $this->getDeclaration($fieldName, $field['definition']); + $query .= 'CHANGE '.$oldFieldName.' ' + .$this->getDeclaration($fieldName, $field['definition']); } } - if ( ! empty($rename) && is_array($rename)) { + if (!empty($rename) && is_array($rename)) { foreach ($rename as $renameName => $renamedField) { if ($query) { - $query.= ', '; + $query .= ', '; } $field = $changes['rename'][$renamedField]; $renamedField = $this->conn->quoteIdentifier($renamedField, true); - $query .= 'CHANGE ' . $renamedField . ' ' - . $this->getDeclaration($field['name'], $field['definition']); + $query .= 'CHANGE '.$renamedField.' ' + .$this->getDeclaration($field['name'], $field['definition']); } } - if ( ! $query) { + if (!$query) { return false; } $name = $this->conn->quoteIdentifier($name, true); - - return 'ALTER TABLE ' . $name . ' ' . $query; + + return 'ALTER TABLE '.$name.' '.$query; } /** - * createForeignKey + * createForeignKey. * * Sqlite does not support foreign keys so we are not even going to do anything if this function is called * to avoid any sql errors if a user tries to use this on sqlite * - * @param string $table name of the table on which the foreign key is to be created - * @param array $definition associative array that defines properties of the foreign key to be created. + * @param string $table name of the table on which the foreign key is to be created + * @param array $definition associative array that defines properties of the foreign key to be created + * * @return string */ public function createForeignKey($table, array $definition) { return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression.php b/lib/Doctrine/Expression.php index e2bdd2f39..8c54606ce 100644 --- a/lib/Doctrine/Expression.php +++ b/lib/Doctrine/Expression.php @@ -22,15 +22,16 @@ /** * Doctrine_Expression memorizes a dql expression that use a db function. * - * This class manages abstractions of dql expressions like query parts + * This class manages abstractions of dql expressions like query parts * that use CONCAT(), MIN(), SUM(). * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression @@ -42,18 +43,18 @@ class Doctrine_Expression /** * Creates an expression. * - * The constructor needs the dql fragment that contains one or more dbms + * The constructor needs the dql fragment that contains one or more dbms * functions. * * $e = new Doctrine_Expression("CONCAT('some', 'one')"); * - * - * @param string $expr sql fragment - * @param Doctrine_Connection $conn the connection (optional) + * + * @param string $expr sql fragment + * @param Doctrine_Connection $conn the connection (optional) */ public function __construct($expr, $conn = null) { - if ($conn !== null) { + if (null !== $conn) { $this->_conn = $conn; } $this->_tokenizer = new Doctrine_Query_Tokenizer(); @@ -62,13 +63,13 @@ public function __construct($expr, $conn = null) /** * Retrieves the connection associated to this expression at creation, - * or the current connection used if it was not specified. - * + * or the current connection used if it was not specified. + * * @return Doctrine_Connection The connection */ public function getConnection() { - if ( ! isset($this->_conn)) { + if (!isset($this->_conn)) { return Doctrine_Manager::connection(); } @@ -79,10 +80,9 @@ public function getConnection() * Sets the contained expression assuring that it is parsed. * * $e->setExpression("CONCAT('some', 'one')"); - * - * + * . + * * @param string $clause The expression to set - * @return void */ public function setExpression($clause) { @@ -90,38 +90,41 @@ public function setExpression($clause) } /** - * Parses a single expressions and substitutes dql abstract functions + * Parses a single expressions and substitutes dql abstract functions * with their concrete sql counterparts for the given connection. * * @param string $expr The expression to parse + * * @return string */ public function parseExpression($expr) { - $pos = strpos($expr, '('); - $quoted = (substr($expr, 0, 1) === "'" && substr($expr, -1) === "'"); - if ($pos === false || $quoted) { + $pos = strpos($expr, '('); + $quoted = ("'" === substr($expr, 0, 1) && "'" === substr($expr, -1)); + if (false === $pos || $quoted) { return $expr; } // get the name of the function - $name = substr($expr, 0, $pos); - $argStr = substr($expr, ($pos + 1), -1); + $name = substr($expr, 0, $pos); + $argStr = substr($expr, $pos + 1, -1); // parse args foreach ($this->_tokenizer->bracketExplode($argStr, ',') as $arg) { - $args[] = $this->parseClause($arg); + $args[] = $this->parseClause($arg); } return call_user_func_array(array($this->getConnection()->expression, $name), $args); } /** - * Parses a set of expressions at once. + * Parses a set of expressions at once. + * * @see parseExpression() - * - * @param string $clause The clause. Can be complex and parenthesised. - * @return string The parsed clause. + * + * @param string $clause The clause. Can be complex and parenthesised. + * + * @return string the parsed clause */ public function parseClause($clause) { @@ -130,13 +133,13 @@ public function parseClause($clause) foreach ($e as $k => $expr) { $e[$k] = $this->parseExpression($expr); } - + return implode(' ', $e); } /** * Gets the sql fragment represented. - * + * * @return string */ public function getSql() @@ -146,13 +149,13 @@ public function getSql() /** * Magic method. - * + * * Returns a string representation of this object. Proxies to @see getSql(). - * + * * @return string */ public function __toString() { return $this->getSql(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Driver.php b/lib/Doctrine/Expression/Driver.php index b97aef287..49d2b440e 100644 --- a/lib/Doctrine/Expression/Driver.php +++ b/lib/Doctrine/Expression/Driver.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Expression_Driver + * Doctrine_Expression_Driver. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Driver extends Doctrine_Connection_Module @@ -44,7 +45,7 @@ public function getIdentifiers($columns) /** * regexp - * returns the regular expression operator + * returns the regular expression operator. * * @return string */ @@ -54,66 +55,76 @@ public function regexp() } /** - * Returns the average value of a column + * Returns the average value of a column. + * + * @param string $column the column to use * - * @param string $column the column to use - * @return string generated sql including an AVG aggregate function + * @return string generated sql including an AVG aggregate function */ public function avg($column) { $column = $this->getIdentifier($column); - return 'AVG(' . $column . ')'; + + return 'AVG('.$column.')'; } /** - * Returns the number of rows (without a NULL value) of a column + * Returns the number of rows (without a NULL value) of a column. * * If a '*' is used instead of a column the number of selected rows * is returned. * - * @param string|integer $column the column to use - * @return string generated sql including a COUNT aggregate function + * @param string|int $column the column to use + * + * @return string generated sql including a COUNT aggregate function */ public function count($column) { $column = $this->getIdentifier($column); - return 'COUNT(' . $column . ')'; + + return 'COUNT('.$column.')'; } /** - * Returns the highest value of a column + * Returns the highest value of a column. * - * @param string $column the column to use - * @return string generated sql including a MAX aggregate function + * @param string $column the column to use + * + * @return string generated sql including a MAX aggregate function */ public function max($column) { $column = $this->getIdentifier($column); - return 'MAX(' . $column . ')'; + + return 'MAX('.$column.')'; } /** - * Returns the lowest value of a column + * Returns the lowest value of a column. * * @param string $column the column to use + * * @return string */ public function min($column) { $column = $this->getIdentifier($column); - return 'MIN(' . $column . ')'; + + return 'MIN('.$column.')'; } /** - * Returns the total sum of a column + * Returns the total sum of a column. * * @param string $column the column to use + * * @return string */ public function sum($column) { $column = $this->getIdentifier($column); - return 'SUM(' . $column . ')'; + + return 'SUM('.$column.')'; } // scalar functions @@ -128,34 +139,32 @@ public function sum($column) public function md5($column) { $column = $this->getIdentifier($column); - return 'MD5(' . $column . ')'; + + return 'MD5('.$column.')'; } /** * Returns the length of a text field. * - * @param string $expression1 - * @param string $expression2 * @return string */ public function length($column) { $column = $this->getIdentifier($column); - return 'LENGTH(' . $column . ')'; + + return 'LENGTH('.$column.')'; } /** * Rounds a numeric field to the number of decimals specified. * - * @param string $expression1 - * @param string $expression2 * @return string */ public function round($column, $decimals = 0) { $column = $this->getIdentifier($column); - return 'ROUND(' . $column . ', ' . $decimals . ')'; + return 'ROUND('.$column.', '.$decimals.')'; } /** @@ -164,49 +173,54 @@ public function round($column, $decimals = 0) * * @param string $expression1 * @param string $expression2 + * * @return string */ public function mod($expression1, $expression2) { $expression1 = $this->getIdentifier($expression1); $expression2 = $this->getIdentifier($expression2); - return 'MOD(' . $expression1 . ', ' . $expression2 . ')'; + + return 'MOD('.$expression1.', '.$expression2.')'; } /** * trim - * returns the string $str with leading and proceeding space characters removed + * returns the string $str with leading and proceeding space characters removed. + * + * @param string $str literal string or column name * - * @param string $str literal string or column name * @return string */ public function trim($str) { - return 'TRIM(' . $str . ')'; + return 'TRIM('.$str.')'; } /** * rtrim - * returns the string $str with proceeding space characters removed + * returns the string $str with proceeding space characters removed. + * + * @param string $str literal string or column name * - * @param string $str literal string or column name * @return string */ public function rtrim($str) { - return 'RTRIM(' . $str . ')'; + return 'RTRIM('.$str.')'; } /** * ltrim - * returns the string $str with leading space characters removed + * returns the string $str with leading space characters removed. + * + * @param string $str literal string or column name * - * @param string $str literal string or column name * @return string */ public function ltrim($str) { - return 'LTRIM(' . $str . ')'; + return 'LTRIM('.$str.')'; } /** @@ -214,12 +228,13 @@ public function ltrim($str) * Returns the string $str with all characters changed to * uppercase according to the current character set mapping. * - * @param string $str literal string or column name + * @param string $str literal string or column name + * * @return string */ public function upper($str) { - return 'UPPER(' . $str . ')'; + return 'UPPER('.$str.')'; } /** @@ -227,25 +242,27 @@ public function upper($str) * Returns the string $str with all characters changed to * lowercase according to the current character set mapping. * - * @param string $str literal string or column name + * @param string $str literal string or column name + * * @return string */ public function lower($str) { - return 'LOWER(' . $str . ')'; + return 'LOWER('.$str.')'; } /** * locate - * returns the position of the first occurrence of substring $substr in string $str + * returns the position of the first occurrence of substring $substr in string $str. * - * @param string $substr literal string to find - * @param string $str literal string - * @return integer + * @param string $substr literal string to find + * @param string $str literal string + * + * @return int */ public function locate($str, $substr) { - return 'LOCATE(' . $str . ', ' . $substr . ')'; + return 'LOCATE('.$str.', '.$substr.')'; } /** @@ -261,12 +278,13 @@ public function now() /** * soundex * Returns a string to call a function to compute the - * soundex encoding of a string + * soundex encoding of a string. * * The string "?000" is returned if the argument is NULL. * * @param string $value - * @return string SQL soundex function with given parameter + * + * @return string SQL soundex function with given parameter */ public function soundex($value) { @@ -274,41 +292,42 @@ public function soundex($value) } /** - * return string to call a function to get a substring inside an SQL statement + * return string to call a function to get a substring inside an SQL statement. * * Note: Not SQL92, but common functionality. * * SQLite only supports the 2 parameter variant of this function * - * @param string $value an sql string literal or column name/alias - * @param integer $position where to start the substring portion - * @param integer $length the substring portion length - * @return string SQL substring function with given parameters + * @param string $value an sql string literal or column name/alias + * @param mixed|null $len + * + * @return string SQL substring function with given parameters */ public function substring($value, $from, $len = null) { $value = $this->getIdentifier($value); - if ($len === null) - return 'SUBSTRING(' . $value . ' FROM ' . $from . ')'; - else { - $len = $this->getIdentifier($len); - return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $len . ')'; + if (null === $len) { + return 'SUBSTRING('.$value.' FROM '.$from.')'; } + + $len = $this->getIdentifier($len); + + return 'SUBSTRING('.$value.' FROM '.$from.' FOR '.$len.')'; } /** - * Returns a series of strings concatinated + * Returns a series of strings concatinated. * * concat() accepts an arbitrary number of parameters. Each parameter * must contain an expression or an array with expressions. * - * @param string|array(string) strings that will be concatinated. + * @param string|array(string) strings that will be concatinated */ public function concat() { $args = func_get_args(); - return 'CONCAT(' . join(', ', (array) $args) . ')'; + return 'CONCAT('.join(', ', (array) $args).')'; } /** @@ -319,7 +338,8 @@ public function concat() public function not($expression) { $expression = $this->getIdentifier($expression); - return 'NOT(' . $expression . ')'; + + return 'NOT('.$expression.')'; } /** @@ -330,8 +350,9 @@ public function not($expression) * must contain a value or an expression or an array with values or * expressions. * - * @param string $type the type of operation, can be '+', '-', '*' or '/'. + * @param string $type the type of operation, can be '+', '-', '*' or '/' * @param string|array(string) + * * @return string an expression */ private function basicMath($type, array $args) @@ -340,11 +361,11 @@ private function basicMath($type, array $args) if (count($elements) < 1) { return ''; } - if (count($elements) == 1) { + if (1 == count($elements)) { return $elements[0]; - } else { - return '(' . implode(' ' . $type . ' ', $elements) . ')'; } + + return '('.implode(' '.$type.' ', $elements).')'; } /** @@ -355,6 +376,7 @@ private function basicMath($type, array $args) * expressions. * * @param string|array(string) + * * @return string an expression */ public function add(array $args) @@ -370,11 +392,12 @@ public function add(array $args) * expressions. * * @param string|array(string) + * * @return string an expression */ public function sub(array $args) { - return $this->basicMath('-', $args ); + return $this->basicMath('-', $args); } /** @@ -385,6 +408,7 @@ public function sub(array $args) * expressions. * * @param string|array(string) + * * @return string an expression */ public function mul(array $args) @@ -400,6 +424,7 @@ public function mul(array $args) * expressions. * * @param string|array(string) + * * @return string an expression */ public function div(array $args) @@ -412,13 +437,15 @@ public function div(array $args) * * @param string $value1 logical expression to compare * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function eq($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' = ' . $value2; + + return $value1.' = '.$value2; } /** @@ -426,13 +453,15 @@ public function eq($value1, $value2) * * @param string $value1 logical expression to compare * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function neq($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' <> ' . $value2; + + return $value1.' <> '.$value2; } /** @@ -440,13 +469,15 @@ public function neq($value1, $value2) * * @param string $value1 logical expression to compare * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function gt($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' > ' . $value2; + + return $value1.' > '.$value2; } /** @@ -455,42 +486,48 @@ public function gt($value1, $value2) * * @param string $value1 logical expression to compare * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function gte($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' >= ' . $value2; + + return $value1.' >= '.$value2; } /** * Returns the SQL to check if one value is less than another value. * - * @param string $value1 logical expression to compare - * @param string $value2 logical expression to compare with + * @param string $value1 logical expression to compare + * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function lt($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' < ' . $value2; + + return $value1.' < '.$value2; } /** * Returns the SQL to check if one value is less than or equal to * another value. * - * @param string $value1 logical expression to compare - * @param string $value2 logical expression to compare with + * @param string $value1 logical expression to compare + * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function lte($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' <= ' . $value2; + + return $value1.' <= '.$value2; } /** @@ -502,46 +539,52 @@ public function lte($value1, $value2) * must contain a logical expression or an array with logical expressions. * These expressions will be matched against the first parameter. * - * @param string $column the value that should be matched against + * @param string $column the value that should be matched against * @param string|array(string) values that will be matched against $column + * * @return string logical expression */ public function in($column, $values) { - if ( ! is_array($values)) { + if (!is_array($values)) { $values = array($values); } $values = $this->getIdentifiers($values); $column = $this->getIdentifier($column); - if (count($values) == 0) { + if (0 == count($values)) { throw new Doctrine_Expression_Exception('Values array for IN operator should not be empty.'); } - return $column . ' IN (' . implode(', ', $values) . ')'; + + return $column.' IN ('.implode(', ', $values).')'; } /** * Returns SQL that checks if a expression is null. * * @param string $expression the expression that should be compared to null + * * @return string logical expression */ public function isNull($expression) { $expression = $this->getIdentifier($expression); - return $expression . ' IS NULL'; + + return $expression.' IS NULL'; } /** * Returns SQL that checks if a expression is not null. * * @param string $expression the expression that should be compared to null + * * @return string logical expression */ public function isNotNull($expression) { $expression = $this->getIdentifier($expression); - return $expression . ' IS NOT NULL'; + + return $expression.' IS NOT NULL'; } /** @@ -555,8 +598,9 @@ public function isNotNull($expression) * independence you should avoid using between(). * * @param string $expression the value to compare to - * @param string $value1 the lower value to compare with - * @param string $value2 the higher value to compare with + * @param string $value1 the lower value to compare with + * @param string $value2 the higher value to compare with + * * @return string logical expression */ public function between($expression, $value1, $value2) @@ -564,11 +608,12 @@ public function between($expression, $value1, $value2) $expression = $this->getIdentifier($expression); $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $expression . ' BETWEEN ' .$value1 . ' AND ' . $value2; + + return $expression.' BETWEEN '.$value1.' AND '.$value2; } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -578,30 +623,27 @@ public function guid() } /** - * returns arcus cosine SQL string + * returns arcus cosine SQL string. * * @return string */ public function acos($value) { - return 'ACOS(' . $value . ')'; + return 'ACOS('.$value.')'; } /** - * sin + * sin. * - * @param string $value - * @return void + * @param string $value */ public function sin($value) { - return 'SIN(' . $value . ')'; + return 'SIN('.$value.')'; } /** - * pi - * - * @return void + * pi. */ public function pi() { @@ -609,18 +651,17 @@ public function pi() } /** - * cos + * cos. * - * @param string $value - * @return void + * @param string $value */ public function cos($value) { - return 'COS(' . $value . ')'; + return 'COS('.$value.')'; } /** - * coalesce + * coalesce. * * @return string */ @@ -628,20 +669,20 @@ public function coalesce() { $args = func_get_args(); - return 'COALESCE(' . join(', ', (array) $args) . ')'; + return 'COALESCE('.join(', ', (array) $args).')'; } /** - * __call + * __call. * * for all native RDBMS functions the function name itself is returned */ - public function __call($m, $a) + public function __call($m, $a) { if ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EXPR) { - throw new Doctrine_Expression_Exception('Unknown expression: ' . $m); + throw new Doctrine_Expression_Exception('Unknown expression: '.$m); } - return $m . '(' . implode(', ', $a) . ')'; + return $m.'('.implode(', ', $a).')'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Exception.php b/lib/Doctrine/Expression/Exception.php index 7815ddb5f..f5d432931 100644 --- a/lib/Doctrine/Expression/Exception.php +++ b/lib/Doctrine/Expression/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Expression_Exception + * Doctrine_Expression_Exception. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Expression/Mock.php b/lib/Doctrine/Expression/Mock.php index f792a45c9..9e995aee1 100644 --- a/lib/Doctrine/Expression/Mock.php +++ b/lib/Doctrine/Expression/Mock.php @@ -21,15 +21,17 @@ /** * Doctrine_Expression_Mock - * Mock driver that is used for testing purposes + * Mock driver that is used for testing purposes. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Mock extends Doctrine_Expression_Driver -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Expression/Mssql.php b/lib/Doctrine/Expression/Mssql.php index dc4f49437..b46e93e80 100644 --- a/lib/Doctrine/Expression/Mssql.php +++ b/lib/Doctrine/Expression/Mssql.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Expression_Mssql + * Doctrine_Expression_Mssql. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Mssql extends Doctrine_Expression_Driver @@ -37,10 +38,9 @@ class Doctrine_Expression_Mssql extends Doctrine_Expression_Driver * There are three special variables for current date and time: * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type) * - CURRENT_DATE (date, DATE type) - * - CURRENT_TIME (time, TIME type) + * - CURRENT_TIME (time, TIME type). * * @return string to call a variable with the current timestamp - * @access public */ public function now($type = 'timestamp') { @@ -54,34 +54,35 @@ public function now($type = 'timestamp') } /** - * return string to call a function to get a substring inside an SQL statement + * return string to call a function to get a substring inside an SQL statement. + * + * @param mixed|null $length * * @return string to call a function to get a substring */ public function substring($value, $position, $length = null) { - if ( ! is_null($length)) { - return 'SUBSTRING(' . $value . ', ' . $position . ', ' . $length . ')'; + if (!is_null($length)) { + return 'SUBSTRING('.$value.', '.$position.', '.$length.')'; } - return 'SUBSTRING(' . $value . ', ' . $position . ', LEN(' . $value . ') - ' . $position . ' + 1)'; + + return 'SUBSTRING('.$value.', '.$position.', LEN('.$value.') - '.$position.' + 1)'; } /** - * Returns string to concatenate two or more string parameters + * Returns string to concatenate two or more string parameters. * - * @param string $arg1 - * @param string $arg2 - * @param string $values... * @return string to concatenate two strings */ public function concat() { $args = func_get_args(); - return '(' . implode(' + ', $args) . ')'; + + return '('.implode(' + ', $args).')'; } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -91,7 +92,7 @@ public function guid() } /** - * Returns the length of a text field + * Returns the length of a text field. * * @param string $column * @@ -99,7 +100,7 @@ public function guid() */ public function length($column) { - return 'LEN (' . $column . ')'; + return 'LEN ('.$column.')'; } /** @@ -121,15 +122,12 @@ public function length($column) * minute mi, n * second ss, s * millisecond ms - * - * @param $datepart - * @param $date */ public function date_part($datepart, $date) { // remove ' and " from datepart for dblib $datepart = str_replace(array('\'', '"'), '', $datepart); - return 'DATEPART(' . $datepart . ', ' . $date . ')'; + return 'DATEPART('.$datepart.', '.$date.')'; } } diff --git a/lib/Doctrine/Expression/Mysql.php b/lib/Doctrine/Expression/Mysql.php index 165f558a5..8ed42e2ff 100644 --- a/lib/Doctrine/Expression/Mysql.php +++ b/lib/Doctrine/Expression/Mysql.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Expression_Mysql + * Doctrine_Expression_Mysql. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Mysql extends Doctrine_Expression_Driver { /** - * returns the regular expression operator + * returns the regular expression operator. * * @return string */ @@ -43,7 +44,7 @@ public function regexp() } /** - * return string to call a function to get random value inside an SQL statement + * return string to call a function to get random value inside an SQL statement. * * @return string to generate float between 0 and 1 */ @@ -53,26 +54,24 @@ public function random() } /** - * build a pattern matching string + * build a pattern matching string. * * EXPERIMENTAL * * WARNING: this function is experimental and may change signature at * any time until labelled as non-experimental * - * @access public - * - * @param array $pattern even keys are strings, odd are patterns (% and _) + * @param array $pattern even keys are strings, odd are patterns (% and _) * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future) - * @param string $field optional field name that is being matched against - * (might be required when emulating ILIKE) + * @param string $field optional field name that is being matched against + * (might be required when emulating ILIKE) * * @return string SQL pattern */ public function matchPattern($pattern, $operator = null, $field = null) { $match = ''; - if ( ! is_null($operator)) { + if (!is_null($operator)) { $field = is_null($field) ? '' : $field.' '; $operator = strtoupper($operator); switch ($operator) { @@ -80,15 +79,15 @@ public function matchPattern($pattern, $operator = null, $field = null) case 'ILIKE': $match = $field.'LIKE '; break; - // case sensitive + // case sensitive case 'LIKE': $match = $field.'LIKE BINARY '; break; default: - throw new Doctrine_Expression_Mysql_Exception('not a supported operator type:'. $operator); + throw new Doctrine_Expression_Mysql_Exception('not a supported operator type:'.$operator); } } - $match.= "'"; + $match .= "'"; foreach ($pattern as $key => $value) { if ($key % 2) { $match .= $value; @@ -96,13 +95,14 @@ public function matchPattern($pattern, $operator = null, $field = null) $match .= $this->conn->escapePattern($this->conn->escape($value)); } } - $match.= "'"; - $match.= $this->patternEscapeString(); + $match .= "'"; + $match .= $this->patternEscapeString(); + return $match; } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -112,49 +112,56 @@ public function guid() } /** - * Returns the year from dbms + * Returns the year from dbms. + * + * @param string $column * - * @param string $column * @return string to get year from dbms */ public function year($column) { $column = $this->getIdentifier($column); - return 'YEAR(' . $column . ')'; + + return 'YEAR('.$column.')'; } /** - * Returns the month from dbms + * Returns the month from dbms. + * + * @param string $column * - * @param string $column * @return string to get month from dbms */ public function month($column) { $column = $this->getIdentifier($column); - return 'MONTH(' . $column . ')'; + + return 'MONTH('.$column.')'; } /** - * Returns day from dbms + * Returns day from dbms. + * + * @param string $column * - * @param string $column * @return string to get day from dbms */ public function day($column) { $column = $this->getIdentifier($column); - return 'DAY(' . $column . ')'; + + return 'DAY('.$column.')'; } /** - * Returns soundex from dbms + * Returns soundex from dbms. * * @param string $column + * * @return string to get soundex from dbms */ public function soundex($column) { - return 'SOUNDEX(' . $column . ')'; + return 'SOUNDEX('.$column.')'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Oracle.php b/lib/Doctrine/Expression/Oracle.php index dd0a8387c..266181e57 100644 --- a/lib/Doctrine/Expression/Oracle.php +++ b/lib/Doctrine/Expression/Oracle.php @@ -20,50 +20,52 @@ */ /** - * Doctrine_Expression_Sqlite + * Doctrine_Expression_Sqlite. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Oracle extends Doctrine_Expression_Driver { /** - * Returns a series of strings concatinated + * Returns a series of strings concatinated. * * concat() accepts an arbitrary number of parameters. Each parameter * must contain an expression * - * @param string $arg1, $arg2 ... $argN strings that will be concatinated. * @return string */ public function concat() { $args = func_get_args(); - return join(' || ' , $args); + return join(' || ', $args); } /** - * return string to call a function to get a substring inside an SQL statement + * return string to call a function to get a substring inside an SQL statement. * * Note: Not SQL92, but common functionality. * - * @param string $value an sql string literal or column name/alias - * @param integer $position where to start the substring portion - * @param integer $length the substring portion length - * @return string SQL substring function with given parameters + * @param string $value an sql string literal or column name/alias + * @param int $position where to start the substring portion + * @param int $length the substring portion length + * + * @return string SQL substring function with given parameters */ public function substring($value, $position, $length = null) { - if ($length !== null) - return "SUBSTR($value, $position, $length)"; + if (null !== $length) { + return "SUBSTR({$value}, {$position}, {$length})"; + } - return "SUBSTR($value, $position)"; + return "SUBSTR({$value}, {$position})"; } /** @@ -71,7 +73,7 @@ public function substring($value, $position, $length = null) * There are three special variables for current date and time: * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type) * - CURRENT_DATE (date, DATE type) - * - CURRENT_TIME (time, TIME type) + * - CURRENT_TIME (time, TIME type). * * @return string to call a variable with the current timestamp */ @@ -87,9 +89,9 @@ public function now($type = 'timestamp') } /** - * random + * random. * - * @return string an oracle SQL string that generates a float between 0 and 1 + * @return string an oracle SQL string that generates a float between 0 and 1 */ public function random() { @@ -97,7 +99,7 @@ public function random() } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -105,4 +107,4 @@ public function guid() { return 'SYS_GUID()'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Pgsql.php b/lib/Doctrine/Expression/Pgsql.php index f447b1e10..e3c1a68fe 100644 --- a/lib/Doctrine/Expression/Pgsql.php +++ b/lib/Doctrine/Expression/Pgsql.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Expression_Pgsql + * Doctrine_Expression_Pgsql. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7685 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Pgsql extends Doctrine_Expression_Driver @@ -54,7 +55,7 @@ public function md5($column) { $column = $this->getIdentifier($column); - return 'MD5(' . $column . ')'; + return 'MD5('.$column.')'; } /** @@ -62,46 +63,52 @@ public function md5($column) * * Note: Not SQL92, but common functionality. * - * @param string $value the target $value the string or the string column. - * @param int $from extract from this characeter. - * @param int $len extract this amount of characters. - * @return string sql that extracts part of a string. + * @param string $value the target $value the string or the string column + * @param int $from extract from this characeter + * @param int $len extract this amount of characters + * + * @return string sql that extracts part of a string */ public function substring($value, $from, $len = null) { $value = $this->getIdentifier($value); - if ($len === null) { + if (null === $len) { $len = $this->getIdentifier($len); - return 'SUBSTR(' . $value . ', ' . $from . ')'; - } else { - return 'SUBSTR(' . $value . ', ' . $from . ', ' . $len . ')'; + + return 'SUBSTR('.$value.', '.$from.')'; } + + return 'SUBSTR('.$value.', '.$from.', '.$len.')'; } /** - * Returns a series of strings concatinated + * Returns a series of strings concatinated. * * concat() accepts an arbitrary number of parameters. Each parameter * must contain an expression or an array with expressions. * - * @param string|array(string) strings that will be concatinated. + * @param string|array(string) strings that will be concatinated + * @param mixed|null $timestamp2 + * * @return string */ - /** * PostgreSQLs AGE( [, ]) function. * * @param string $timestamp1 timestamp to subtract from NOW() * @param string $timestamp2 optional; if given: subtract arguments + * * @return string */ - public function age($timestamp1, $timestamp2 = null) { - if ( $timestamp2 == null ) { - return 'AGE(' . $timestamp1 . ')'; + public function age($timestamp1, $timestamp2 = null) + { + if (null == $timestamp2) { + return 'AGE('.$timestamp1.')'; } - return 'AGE(' . $timestamp1 . ', ' . $timestamp2 . ')'; + + return 'AGE('.$timestamp1.', '.$timestamp2.')'; } /** @@ -109,11 +116,12 @@ public function age($timestamp1, $timestamp2 = null) { * * @param string $text what to extract * @param string $time timestamp or interval to extract from + * * @return string */ public function date_part($text, $time) { - return 'DATE_PART(' . $text . ', ' . $time . ')'; + return 'DATE_PART('.$text.', '.$time.')'; } /** @@ -121,23 +129,26 @@ public function date_part($text, $time) * * @param string $time timestamp or interval * @param string $text how to the format the output + * * @return string */ - public function to_char($time, $text) { - return 'TO_CHAR(' . $time . ', ' . $text . ')'; + public function to_char($time, $text) + { + return 'TO_CHAR('.$time.', '.$text.')'; } /** - * PostgreSQLs CONCAT() function + * PostgreSQLs CONCAT() function. * * @param an array of values + * * @return string */ public function concat() { $args = func_get_args(); - return join(' || ' , $args); + return join(' || ', $args); } /** @@ -151,9 +162,9 @@ public function now() } /** - * regexp + * regexp. * - * @return string the regular expression operator + * @return string the regular expression operator */ public function regexp() { @@ -161,10 +172,9 @@ public function regexp() } /** - * return string to call a function to get random value inside an SQL statement + * return string to call a function to get random value inside an SQL statement. * * @return return string to generate float between 0 and 1 - * @access public */ public function random() { @@ -172,89 +182,89 @@ public function random() } /** - * build a pattern matching string + * build a pattern matching string. * * EXPERIMENTAL * * WARNING: this function is experimental and may change signature at * any time until labelled as non-experimental * - * @access public - * - * @param array $pattern even keys are strings, odd are patterns (% and _) + * @param array $pattern even keys are strings, odd are patterns (% and _) * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future) - * @param string $field optional field name that is being matched against - * (might be required when emulating ILIKE) + * @param string $field optional field name that is being matched against + * (might be required when emulating ILIKE) * * @return string SQL pattern */ public function matchPattern($pattern, $operator = null, $field = null) { $match = ''; - if ( ! is_null($operator)) { + if (!is_null($operator)) { $field = is_null($field) ? '' : $field.' '; $operator = strtoupper($operator); switch ($operator) { // case insensitive - case 'ILIKE': - $match = $field.'ILIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE '; - break; - default: - throw new Doctrine_Expression_Pgsql_Exception('not a supported operator type:'. $operator); + case 'ILIKE': + $match = $field.'ILIKE '; + break; + // case sensitive + case 'LIKE': + $match = $field.'LIKE '; + break; + default: + throw new Doctrine_Expression_Pgsql_Exception('not a supported operator type:'.$operator); } } - $match.= "'"; + $match .= "'"; foreach ($pattern as $key => $value) { if ($key % 2) { - $match.= $value; + $match .= $value; } else { - $match.= $this->conn->escapePattern($this->conn->escape($value)); + $match .= $this->conn->escapePattern($this->conn->escape($value)); } } - $match.= "'"; - $match.= $this->patternEscapeString(); + $match .= "'"; + $match .= $this->patternEscapeString(); + return $match; } /** - * return syntax for pgsql TRANSLATE() dbms function + * return syntax for pgsql TRANSLATE() dbms function. * * @return string $sql */ public function translate($string, $from, $to) { - $translate = 'TRANSLATE(' . $string . ', ' . $from . ', ' . $to . ')'; - return $translate; + return 'TRANSLATE('.$string.', '.$from.', '.$to.')'; } /** - * transform locate to position + * transform locate to position. * * @param string $substr string to find - * @param string $str to find where + * @param string $str to find where + * * @return string */ public function locate($substr, $str) { return $this->position($substr, $str); } - + /** - * position + * position. * * @param string $substr string to find - * @param string $str to find where + * @param string $str to find where + * * @return string */ public function position($substr, $str) { $substr = $this->getIdentifier($substr); $str = $this->getIdentifier($str); - + return sprintf('POSITION(%s IN %s)', $substr, $str); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Sqlite.php b/lib/Doctrine/Expression/Sqlite.php index d4ffcf3ed..35de55a36 100644 --- a/lib/Doctrine/Expression/Sqlite.php +++ b/lib/Doctrine/Expression/Sqlite.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Expression_Sqlite + * Doctrine_Expression_Sqlite. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Sqlite extends Doctrine_Expression_Driver @@ -35,7 +36,6 @@ class Doctrine_Expression_Sqlite extends Doctrine_Expression_Driver /** * Returns the md5 sum of the data that SQLite's md5() function receives. * - * @param mixed $data * @return string */ public static function md5Impl($data) @@ -46,8 +46,9 @@ public static function md5Impl($data) /** * Returns the modules of the data that SQLite's mod() function receives. * - * @param integer $dividend - * @param integer $divisor + * @param int $dividend + * @param int $divisor + * * @return string */ public static function modImpl($dividend, $divisor) @@ -63,16 +64,18 @@ public static function modImpl($dividend, $divisor) public static function concatImpl() { $args = func_get_args(); + return join('', $args); } /** * locate * returns the position of the first occurrence of substring $substr in string $str that - * SQLite's locate() function receives + * SQLite's locate() function receives. + * + * @param string $substr literal string to find + * @param string $str literal string * - * @param string $substr literal string to find - * @param string $str literal string * @return string */ public static function locateImpl($substr, $str) @@ -99,13 +102,14 @@ public static function trimImpl($str) { return trim($str); } + public static function nowImpl() { return date('Y-m-d h:i:s'); } /** - * returns the regular expression operator + * returns the regular expression operator. * * @return string */ @@ -117,23 +121,24 @@ public function regexp() /** * soundex * Returns a string to call a function to compute the - * soundex encoding of a string + * soundex encoding of a string. * * The string "?000" is returned if the argument is NULL. * * @param string $value - * @return string SQL soundex function with given parameter + * + * @return string SQL soundex function with given parameter */ public function soundex($value) { - return 'SOUNDEX(' . $value . ')'; + return 'SOUNDEX('.$value.')'; } /** * Return string to call a variable with the current timestamp inside an SQL statement * There are three special variables for current date and time. * - * @return string sqlite function as string + * @return string sqlite function as string */ public function now($type = 'timestamp') { @@ -149,7 +154,7 @@ public function now($type = 'timestamp') } /** - * return string to call a function to get random value inside an SQL statement + * return string to call a function to get random value inside an SQL statement. * * @return string to generate float between 0 and 1 */ @@ -159,22 +164,24 @@ public function random() } /** - * return string to call a function to get a substring inside an SQL statement + * return string to call a function to get a substring inside an SQL statement. * * Note: Not SQL92, but common functionality. * * SQLite only supports the 2 parameter variant of this function * - * @param string $value an sql string literal or column name/alias - * @param integer $position where to start the substring portion - * @param integer $length the substring portion length - * @return string SQL substring function with given parameters + * @param string $value an sql string literal or column name/alias + * @param int $position where to start the substring portion + * @param int $length the substring portion length + * + * @return string SQL substring function with given parameters */ public function substring($value, $position, $length = null) { - if ($length !== null) { - return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')'; + if (null !== $length) { + return 'SUBSTR('.$value.', '.$position.', '.$length.')'; } - return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))'; + + return 'SUBSTR('.$value.', '.$position.', LENGTH('.$value.'))'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/File.php b/lib/Doctrine/File.php index 1d0cfe7ec..c9a6346c7 100644 --- a/lib/Doctrine/File.php +++ b/lib/Doctrine/File.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_File + * Doctrine_File. * - * @package Doctrine - * @subpackage File * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_File extends Doctrine_Record @@ -40,16 +40,17 @@ public function setTableDefinition() public function setUp() { $this->actAs('Searchable', array('className' => 'Doctrine_File_Index', - 'fields' => array('url', 'content'))); - + 'fields' => array('url', 'content'))); + $this->index('url', array('fields' => array('url'))); } public function get($name, $load = true) { - if ($name === 'content') { + if ('content' === $name) { return file_get_contents(parent::get('url')); } + return parent::get($name, $load); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/File/Index.php b/lib/Doctrine/File/Index.php index d97983696..07d49c660 100644 --- a/lib/Doctrine/File/Index.php +++ b/lib/Doctrine/File/Index.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_File_Index + * Doctrine_File_Index. * - * @package Doctrine - * @subpackage File * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_File_Index extends Doctrine_Record @@ -35,23 +35,23 @@ class Doctrine_File_Index extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('keyword', 'string', 255, array('notnull' => true, - 'primary' => true)); - + 'primary' => true)); + $this->hasColumn('field', 'string', 50, array('notnull' => true, - 'primary' => true)); + 'primary' => true)); $this->hasColumn('position', 'string', 255, array('notnull' => true, - 'primary' => true)); - + 'primary' => true)); + $this->hasColumn('file_id', 'integer', 8, array('notnull' => true, - 'primary' => true)); + 'primary' => true)); } public function setUp() { $this->hasOne('Doctrine_File', array('local' => 'file_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE', - 'onUpdate' => 'CASCADE')); + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + 'onUpdate' => 'CASCADE')); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Formatter.php b/lib/Doctrine/Formatter.php index d942b73b8..55b36f4db 100644 --- a/lib/Doctrine/Formatter.php +++ b/lib/Doctrine/Formatter.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Formatter + * Doctrine_Formatter. * - * @package Doctrine - * @subpackage Formatter * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Formatter extends Doctrine_Connection_Module { /** - * Quotes pattern (% and _) characters in a string) + * Quotes pattern (% and _) characters in a string). * * EXPERIMENTAL * @@ -42,34 +43,34 @@ class Doctrine_Formatter extends Doctrine_Connection_Module * * @param string the input string to quote * - * @return string quoted string + * @return string quoted string */ public function escapePattern($text) { - if ( ! $this->string_quoting['escape_pattern']) { + if (!$this->string_quoting['escape_pattern']) { return $text; } $tmp = $this->conn->string_quoting; - $text = str_replace($tmp['escape_pattern'], - $tmp['escape_pattern'] . + $text = str_replace($tmp['escape_pattern'], + $tmp['escape_pattern']. $tmp['escape_pattern'], $text); foreach ($this->wildcards as $wildcard) { - $text = str_replace($wildcard, $tmp['escape_pattern'] . $wildcard, $text); + $text = str_replace($wildcard, $tmp['escape_pattern'].$wildcard, $text); } + return $text; } /** * convertBooleans * some drivers need the boolean values to be converted into integers - * when using DQL API + * when using DQL API. * * This method takes care of that conversion * * @param array $item - * @return void */ public function convertBooleans($item) { @@ -84,11 +85,12 @@ public function convertBooleans($item) $item = (int) $item; } } + return $item; } /** - * Quote a string so it can be safely used as a table or column name + * Quote a string so it can be safely used as a table or column name. * * Delimiting style depends on which database driver is being used. * @@ -114,33 +116,32 @@ public function convertBooleans($item) * InterBase doesn't seem to be able to use delimited identifiers * via PHP 4. They work fine under PHP 5. * - * @param string $str identifier name to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param string $str identifier name to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteIdentifier($str, $checkOption = true) { - if ($checkOption && ! $this->conn->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { + if ($checkOption && !$this->conn->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { return $str; } $tmp = $this->conn->identifier_quoting; $str = str_replace($tmp['end'], - $tmp['escape'] . + $tmp['escape']. $tmp['end'], $str); - return $tmp['start'] . $str . $tmp['end']; + return $tmp['start'].$str.$tmp['end']; } - - + /** * quoteMultipleIdentifier - * Quotes multiple identifier strings + * Quotes multiple identifier strings. * - * @param array $arr identifiers array to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param array $arr identifiers array to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteMultipleIdentifier($arr, $checkOption = true) { @@ -148,88 +149,95 @@ public function quoteMultipleIdentifier($arr, $checkOption = true) $arr[$k] = $this->quoteIdentifier($v, $checkOption); } - return $arr; + return $arr; } /** * quote - * quotes given input parameter + * quotes given input parameter. * - * @param mixed $input parameter to be quoted + * @param mixed $input parameter to be quoted * @param string $type + * * @return string */ public function quote($input, $type = null) { - if ($type == null) { + if (null == $type) { $type = gettype($input); } switch ($type) { - case 'integer': - case 'double': - case 'float': - case 'bool': - case 'decimal': - case 'int': - return $input; - case 'array': - case 'object': - $input = serialize($input); - case 'date': - case 'time': - case 'timestamp': - case 'string': - case 'char': - case 'varchar': - case 'text': - case 'gzip': - case 'blob': - case 'clob': - case 'enum': - case 'set': - case 'boolean': - return "'" . str_replace("'","''",$input) . "'"; + case 'integer': + case 'double': + case 'float': + case 'bool': + case 'decimal': + case 'int': + return $input; + case 'array': + case 'object': + $input = serialize($input); + // no break + case 'date': + case 'time': + case 'timestamp': + case 'string': + case 'char': + case 'varchar': + case 'text': + case 'gzip': + case 'blob': + case 'clob': + case 'enum': + case 'set': + case 'boolean': + return "'".str_replace("'", "''", $input)."'"; } } /** - * Removes any formatting in an sequence name using the 'seqname_format' option + * Removes any formatting in an sequence name using the 'seqname_format' option. * * @param string $sqn string that containts name of a potential sequence + * * @return string name of the sequence with possible formatting removed */ public function fixSequenceName($sqn) { - $seqPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->getAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT)).'$/i'; - $seqName = preg_replace($seqPattern, '\\1', $sqn); + $seqPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->getAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT)).'$/i'; + $seqName = preg_replace($seqPattern, '\\1', $sqn); - if ($seqName && ! strcasecmp($sqn, $this->getSequenceName($seqName))) { + if ($seqName && !strcasecmp($sqn, $this->getSequenceName($seqName))) { return $seqName; } + return $sqn; } /** - * Removes any formatting in an index name using the 'idxname_format' option + * Removes any formatting in an index name using the 'idxname_format' option. * * @param string $idx string that containts name of anl index + * * @return string name of the index with possible formatting removed */ public function fixIndexName($idx) { - $indexPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->getAttribute(Doctrine_Core::ATTR_IDXNAME_FORMAT)).'$/i'; - $indexName = preg_replace($indexPattern, '\\1', $idx); - if ($indexName && ! strcasecmp($idx, $this->getIndexName($indexName))) { + $indexPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->getAttribute(Doctrine_Core::ATTR_IDXNAME_FORMAT)).'$/i'; + $indexName = preg_replace($indexPattern, '\\1', $idx); + if ($indexName && !strcasecmp($idx, $this->getIndexName($indexName))) { return $indexName; } + return $idx; } /** - * adds sequence name formatting to a sequence name + * adds sequence name formatting to a sequence name. * * @param string name of the sequence - * @return string formatted sequence name + * + * @return string formatted sequence name */ public function getSequenceName($sqn) { @@ -238,22 +246,24 @@ public function getSequenceName($sqn) } /** - * adds index name formatting to a index name + * adds index name formatting to a index name. * * @param string name of the index - * @return string formatted index name + * + * @return string formatted index name */ public function getIndexName($idx) { return sprintf($this->conn->getAttribute(Doctrine_Core::ATTR_IDXNAME_FORMAT), preg_replace('/[^a-z0-9_\$]/i', '_', $idx)); } - + /** - * Formatting a foreign Key name + * Formatting a foreign Key name. * * @param string name of the foreign key - * @return string formatted foreign key name + * + * @return string formatted foreign key name */ public function getForeignKeyName($fkey) { @@ -262,14 +272,16 @@ public function getForeignKeyName($fkey) } /** - * adds table name formatting to a table name + * adds table name formatting to a table name. * * @param string name of the table - * @return string formatted table name + * + * @return string formatted table name */ public function getTableName($table) { $format = $this->conn->getAttribute(Doctrine_Core::ATTR_TBLNAME_FORMAT); + return sprintf($format, str_replace(sprintf($format, null), '', $table)); } } diff --git a/lib/Doctrine/Hook.php b/lib/Doctrine/Hook.php index 8d07492d7..3203c6bc7 100644 --- a/lib/Doctrine/Hook.php +++ b/lib/Doctrine/Hook.php @@ -20,61 +20,62 @@ */ /** - * Doctrine_Hook + * Doctrine_Hook. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Hook { /** - * @var Doctrine_Query $query the base query + * @var Doctrine_Query the base query */ protected $query; /** - * @var array $joins the optional joins of the base query + * @var array the optional joins of the base query */ protected $joins; /** - * @var array $hooks hooks array + * @var array hooks array */ - protected $hooks = array( - 'where', - 'orderby', - 'limit', - 'offset' - ); + protected $hooks = array( + 'where', + 'orderby', + 'limit', + 'offset', + ); /** - * @var array $fieldParsers custom field parsers array - * keys as field names in the format componentAlias.FieldName - * values as parser names / objects + * @var array custom field parsers array + * keys as field names in the format componentAlias.FieldName + * values as parser names / objects */ protected $fieldParsers = array(); /** - * @var array $typeParsers type parsers array - * keys as type names and values as parser names / objects + * @var array type parsers array + * keys as type names and values as parser names / objects */ - protected $typeParsers = array( - 'char' => 'Doctrine_Hook_WordLike', - 'string' => 'Doctrine_Hook_WordLike', - 'varchar' => 'Doctrine_Hook_WordLike', - 'integer' => 'Doctrine_Hook_Integer', - 'enum' => 'Doctrine_Hook_Integer', - 'time' => 'Doctrine_Hook_Time', - 'date' => 'Doctrine_Hook_Date', - ); + protected $typeParsers = array( + 'char' => 'Doctrine_Hook_WordLike', + 'string' => 'Doctrine_Hook_WordLike', + 'varchar' => 'Doctrine_Hook_WordLike', + 'integer' => 'Doctrine_Hook_Integer', + 'enum' => 'Doctrine_Hook_Integer', + 'time' => 'Doctrine_Hook_Time', + 'date' => 'Doctrine_Hook_Date', + ); /** - * @param Doctrine_Query $query the base query + * @param Doctrine_Query $query the base query */ public function __construct($query) { @@ -84,16 +85,16 @@ public function __construct($query) } elseif ($query instanceof Doctrine_Query) { $this->query = $query; } else { - throw new Doctrine_Exception('Constructor argument should be either Doctrine_Query object or valid DQL query'); + throw new Doctrine_Exception('Constructor argument should be either Doctrine_Query object or valid DQL query'); } - + $this->query->getSqlQuery(); } /** - * getQuery + * getQuery. * - * @return Doctrine_Query returns the query object associated with this hook + * @return Doctrine_Query returns the query object associated with this hook */ public function getQuery() { @@ -101,21 +102,21 @@ public function getQuery() } /** - * setTypeParser + * setTypeParser. * - * @param string $type type name - * @param string|object $parser parser name or custom parser object + * @param string $type type name + * @param string|object $parser parser name or custom parser object */ - public function setTypeParser($type, $parser) + public function setTypeParser($type, $parser) { $this->typeParsers[$type] = $parser; } /** - * setFieldParser + * setFieldParser. * - * @param string $field field name - * @param string|object $parser parser name or custom parser object + * @param string $field field name + * @param string|object $parser parser name or custom parser object */ public function setFieldParser($field, $parser) { @@ -124,39 +125,39 @@ public function setFieldParser($field, $parser) /** * hookWhere - * builds DQL query where part from given parameter array + * builds DQL query where part from given parameter array. + * + * @param array $params an associative array containing field + * names and their values * - * @param array $params an associative array containing field - * names and their values - * @return boolean whether or not the hooking was + * @return bool whether or not the hooking was */ public function hookWhere($params) { - if ( ! is_array($params)) { + if (!is_array($params)) { return false; } foreach ($params as $name => $value) { - if ($value === '' || $value === '-') { + if ('' === $value || '-' === $value) { continue; } $e = explode('.', $name); - if (count($e) == 2) { + if (2 == count($e)) { list($alias, $column) = $e; - $map = $this->query->getQueryComponent($alias); + $map = $this->query->getQueryComponent($alias); $table = $map['table']; - if ( ! $table) { - throw new Doctrine_Exception('Unknown alias ' . $alias); + if (!$table) { + throw new Doctrine_Exception('Unknown alias '.$alias); } if ($def = $table->getDefinitionOf($column)) { - - $def[0] = gettype($value); + $def[0] = gettype($value); if (isset($this->typeParsers[$def[0]])) { - $name = $this->typeParsers[$def[0]]; - $parser = new $name; + $name = $this->typeParsers[$def[0]]; + $parser = new $name(); } $parser->parse($alias, $column, $value); @@ -171,15 +172,16 @@ public function hookWhere($params) /** * hookOrderBy - * builds DQL query orderby part from given parameter array + * builds DQL query orderby part from given parameter array. + * + * @param array $params an array containing all fields which the built query + * should be ordered by * - * @param array $params an array containing all fields which the built query - * should be ordered by - * @return boolean whether or not the hooking was successful + * @return bool whether or not the hooking was successful */ public function hookOrderby($params) { - if ( ! is_array($params)) { + if (!is_array($params)) { return false; } foreach ($params as $name) { @@ -188,30 +190,30 @@ public function hookOrderby($params) $order = 'ASC'; if (count($e) > 1) { - $order = ($e[1] == 'DESC') ? 'DESC' : 'ASC'; + $order = ('DESC' == $e[1]) ? 'DESC' : 'ASC'; } $e = explode('.', $e[0]); - if (count($e) == 2) { + if (2 == count($e)) { list($alias, $column) = $e; - $map = $this->query->getQueryComponent($alias); + $map = $this->query->getQueryComponent($alias); $table = $map['table']; - if ($def = $table->getDefinitionOf($column)) { - $this->query->addOrderBy($alias . '.' . $column . ' ' . $order); + if ($def = $table->getDefinitionOf($column)) { + $this->query->addOrderBy($alias.'.'.$column.' '.$order); } } } + return true; } /** - * set the hook limit - * - * @param integer $limit - * @return void + * set the hook limit. + * + * @param int $limit */ public function hookLimit($limit) { @@ -219,9 +221,9 @@ public function hookLimit($limit) } /** - * set the hook offset + * set the hook offset. * - * @param integer $offset + * @param int $offset */ public function hookOffset($offset) { diff --git a/lib/Doctrine/Hook/Equal.php b/lib/Doctrine/Hook/Equal.php index 144f769ab..14da3f000 100644 --- a/lib/Doctrine/Hook/Equal.php +++ b/lib/Doctrine/Hook/Equal.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Hook_Equal + * Doctrine_Hook_Equal. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Hook_Equal extends Doctrine_Hook_Parser @@ -39,14 +40,13 @@ class Doctrine_Hook_Equal extends Doctrine_Hook_Parser * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parse($alias, $field, $value) { - $this->params = (array) $value; - $this->condition = $alias . '.' . $field . ' = ?'; + $this->params = (array) $value; + $this->condition = $alias.'.'.$field.' = ?'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hook/Integer.php b/lib/Doctrine/Hook/Integer.php index 20cf14dc2..06c58b463 100644 --- a/lib/Doctrine/Hook/Integer.php +++ b/lib/Doctrine/Hook/Integer.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Hook_Integer + * Doctrine_Hook_Integer. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Hook_Integer extends Doctrine_Hook_Parser_Complex @@ -39,37 +40,36 @@ class Doctrine_Hook_Integer extends Doctrine_Hook_Parser_Complex * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parseSingle($alias, $field, $value) { $e = explode(' ', $value); foreach ($e as $v) { - $v = trim($v); + $v = trim($v); - $e2 = explode('-', $v); + $e2 = explode('-', $v); - $name = $alias. '.' . $field; + $name = $alias.'.'.$field; - if (count($e2) == 1) { - // one '-' found + if (1 == count($e2)) { + // one '-' found - $a[] = $name . ' = ?'; + $a[] = $name.' = ?'; $this->params[] = $v; } else { // more than one '-' found - $a[] = '(' . $name . ' > ? AND ' . $name . ' < ?)'; + $a[] = '('.$name.' > ? AND '.$name.' < ?)'; $this->params += array($e2[0], $e2[1]); } - } + return implode(' OR ', $a); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hook/Parser.php b/lib/Doctrine/Hook/Parser.php index acb145780..f995ed365 100644 --- a/lib/Doctrine/Hook/Parser.php +++ b/lib/Doctrine/Hook/Parser.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Hook_Parser + * Doctrine_Hook_Parser. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Hook_Parser @@ -42,7 +43,7 @@ public function getCondition() /** * getParams - * returns the parameters associated with this parser + * returns the parameters associated with this parser. * * @return array */ @@ -58,10 +59,9 @@ public function getParams() * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ abstract public function parse($alias, $field, $value); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hook/Parser/Complex.php b/lib/Doctrine/Hook/Parser/Complex.php index 2e4671f09..774796696 100644 --- a/lib/Doctrine/Hook/Parser/Complex.php +++ b/lib/Doctrine/Hook/Parser/Complex.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Hook_Parser_Complex + * Doctrine_Hook_Parser_Complex. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Hook_Parser_Complex extends Doctrine_Hook_Parser { protected $_tokenizer; - + /** * Constructor. */ @@ -41,7 +42,7 @@ public function __construct() { $this->_tokenizer = new Doctrine_Query_Tokenizer(); } - + /** * parse * Parses given field and field value to DQL condition @@ -49,10 +50,9 @@ public function __construct() * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parse($alias, $field, $value) { @@ -60,12 +60,11 @@ public function parse($alias, $field, $value) } /** - * parseClause + * parseClause. * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parseClause($alias, $field, $value) { @@ -88,20 +87,19 @@ public function parseClause($alias, $field, $value) $r = implode(' OR ', $ret); } else { - $ret = $this->parseSingle($alias, $field, $parts[0]); - return $ret; + return $this->parseSingle($alias, $field, $parts[0]); } } - return '(' . $r . ')'; + + return '('.$r.')'; } /** - * parseSingle + * parseSingle. * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ abstract public function parseSingle($alias, $field, $value); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hook/WordLike.php b/lib/Doctrine/Hook/WordLike.php index ee1ff0680..2894e3470 100644 --- a/lib/Doctrine/Hook/WordLike.php +++ b/lib/Doctrine/Hook/WordLike.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Hook_WordLike + * Doctrine_Hook_WordLike. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Hook_WordLike extends Doctrine_Hook_Parser_Complex @@ -39,28 +40,27 @@ class Doctrine_Hook_WordLike extends Doctrine_Hook_Parser_Complex * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parseSingle($alias, $field, $value) { - if (strpos($value, "'") !== false) { + if (false !== strpos($value, "'")) { $value = $this->_tokenizer->bracketTrim($value, "'", "'"); - - $a[] = $alias . '.' . $field . ' LIKE ?'; - $this->params[] = '%' . $value . '%'; + $a[] = $alias.'.'.$field.' LIKE ?'; + $this->params[] = '%'.$value.'%'; } else { - $e2 = explode(' ',$value); - + $e2 = explode(' ', $value); + foreach ($e2 as $v) { $v = trim($v); - $a[] = $alias . '.' . $field . ' LIKE ?'; - $this->params[] = '%' . $v . '%'; + $a[] = $alias.'.'.$field.' LIKE ?'; + $this->params[] = '%'.$v.'%'; } } + return implode(' OR ', $a); } } diff --git a/lib/Doctrine/Hydrator.php b/lib/Doctrine/Hydrator.php index 129743e32..0595bd0bc 100644 --- a/lib/Doctrine/Hydrator.php +++ b/lib/Doctrine/Hydrator.php @@ -22,26 +22,24 @@ /** * Its purpose is to populate object graphs. * - * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3192 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Hydrator { - protected static - $_totalHydrationTime = 0; + protected static $_totalHydrationTime = 0; - protected - $_hydrators, - $_rootAlias = null, - $_hydrationMode = Doctrine_Core::HYDRATE_RECORD, - $_queryComponents = array(); + protected $_hydrators; + protected $_rootAlias; + protected $_hydrationMode = Doctrine_Core::HYDRATE_RECORD; + protected $_queryComponents = array(); public function __construct() { @@ -49,11 +47,11 @@ public function __construct() } /** - * Set the hydration mode + * Set the hydration mode. * - * @param mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants or - * a string representing the name of the hydration mode or - * or an instance of the hydration class + * @param mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants or + * a string representing the name of the hydration mode or + * or an instance of the hydration class */ public function setHydrationMode($hydrationMode) { @@ -61,7 +59,7 @@ public function setHydrationMode($hydrationMode) } /** - * Get the hydration mode + * Get the hydration mode. * * @return mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants */ @@ -71,9 +69,7 @@ public function getHydrationMode() } /** - * Set the array of query components - * - * @param array $queryComponents + * Set the array of query components. */ public function setQueryComponents(array $queryComponents) { @@ -81,7 +77,7 @@ public function setQueryComponents(array $queryComponents) } /** - * Get the array of query components + * Get the array of query components. * * @return array $queryComponents */ @@ -91,18 +87,19 @@ public function getQueryComponents() } /** - * Get the name of the driver class for the passed hydration mode + * Get the name of the driver class for the passed hydration mode. * * @param string $mode + * * @return string $className */ public function getHydratorDriverClassName($mode = null) { - if ($mode === null) { + if (null === $mode) { $mode = $this->_hydrationMode; } - if ( ! isset($this->_hydrators[$mode])) { + if (!isset($this->_hydrators[$mode])) { throw new Doctrine_Hydrator_Exception('Invalid hydration mode specified: '.$this->_hydrationMode); } @@ -110,17 +107,18 @@ public function getHydratorDriverClassName($mode = null) } /** - * Get an instance of the hydration driver for the passed hydration mode + * Get an instance of the hydration driver for the passed hydration mode. * * @param string $mode - * @param array $tableAliases + * @param array $tableAliases + * * @return Doctrine_Hydrator_Abstract */ public function getHydratorDriver($mode, $tableAliases) { $driverClass = $this->getHydratorDriverClassName($mode); if (is_object($driverClass)) { - if (!$driverClass instanceOf Doctrine_Hydrator_Abstract) { + if (!$driverClass instanceof Doctrine_Hydrator_Abstract) { throw new Doctrine_Hydrator_Exception('Invalid hydration class specified: '.get_class($driverClass)); } $driver = $driverClass; @@ -139,14 +137,14 @@ public function getHydratorDriver($mode, $tableAliases) * hydration drivers. * * @param object $stmt - * @param array $tableAliases + * @param array $tableAliases + * * @return mixed $result */ public function hydrateResultSet($stmt, $tableAliases) { $driver = $this->getHydratorDriver($this->_hydrationMode, $tableAliases); - $result = $driver->hydrateResultSet($stmt); - return $result; + return $driver->hydrateResultSet($stmt); } } diff --git a/lib/Doctrine/Hydrator/Abstract.php b/lib/Doctrine/Hydrator/Abstract.php index 3a4dc7dc4..af95fbf1c 100644 --- a/lib/Doctrine/Hydrator/Abstract.php +++ b/lib/Doctrine/Hydrator/Abstract.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Hydrator_Abstract + * Doctrine_Hydrator_Abstract. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3192 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Hydrator_Abstract extends Doctrine_Locator_Injectable { - protected - $_queryComponents = array(), - $_tableAliases = array(), - $_priorRow, - $_hydrationMode; + protected $_queryComponents = array(); + protected $_tableAliases = array(); + protected $_priorRow; + protected $_hydrationMode; public function __construct($queryComponents = null, $tableAliases = null, $hydrationMode = null) { @@ -46,10 +46,9 @@ public function __construct($queryComponents = null, $tableAliases = null, $hydr } /** - * Set the query components (structure and query instructions) + * Set the query components (structure and query instructions). * * @param array $queryComponents - * @return void */ public function setQueryComponents($queryComponents) { @@ -57,10 +56,9 @@ public function setQueryComponents($queryComponents) } /** - * Set the table aliases for this query + * Set the table aliases for this query. * * @param array $tableAliases - * @return void */ public function setTableAliases($tableAliases) { @@ -68,12 +66,11 @@ public function setTableAliases($tableAliases) } /** - * Set the hydration mode + * Set the hydration mode. * - * @param mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants or - * a string representing the name of the hydration mode or - * or an instance of the hydration class - * @return void + * @param mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants or + * a string representing the name of the hydration mode or + * or an instance of the hydration class */ public function setHydrationMode($hydrationMode) { @@ -83,6 +80,7 @@ public function setHydrationMode($hydrationMode) public function getRootComponent() { $queryComponents = array_values($this->_queryComponents); + return $queryComponents[0]['table']; } @@ -97,24 +95,23 @@ public function onDemandReset() * (I.e. ORACLE limit/offset emulation adds doctrine_rownum to the result set). * * @param string $name + * * @return bool */ protected function _isIgnoredName($name) { - return $name === 'DOCTRINE_ROWNUM'; + return 'DOCTRINE_ROWNUM' === $name; } /** * hydrateResultSet - * parses the data returned by statement object + * parses the data returned by statement object. * * This is method defines the core of Doctrine object population algorithm * hence this method strives to be as fast as possible * * The key idea is the loop over the rowset only once doing all the needed operations * within this massive loop. - * - * @return mixed */ abstract public function hydrateResultSet($stmt); } diff --git a/lib/Doctrine/Hydrator/ArrayDriver.php b/lib/Doctrine/Hydrator/ArrayDriver.php index 0850ed0e2..cd878a9b6 100644 --- a/lib/Doctrine/Hydrator/ArrayDriver.php +++ b/lib/Doctrine/Hydrator/ArrayDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to the object graph using php arrays + * Builds result sets in to the object graph using php arrays. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Hydrator_ArrayDriver extends Doctrine_Hydrator_Graph @@ -44,49 +45,52 @@ public function getElement(array $data, $component) public function registerCollection($coll) { - } public function initRelated(&$record, $name, $keyColumn = null) { - if ( ! isset($record[$name])) { + if (!isset($record[$name])) { $record[$name] = array(); } + return true; } - public function getNullPointer() + public function getNullPointer() { - return null; + return null; } public function getLastKey(&$coll) { end($coll); + return key($coll); } public function setLastElement(&$prev, &$coll, $index, $dqlAlias, $oneToOne) { - if ($coll === null) { + if (null === $coll) { unset($prev[$dqlAlias]); // Ticket #1228 + return; } - if ($index !== false) { + if (false !== $index) { // Link element at $index to previous element for the component // identified by the DQL alias $alias - $prev[$dqlAlias] =& $coll[$index]; + $prev[$dqlAlias] = &$coll[$index]; + return; } - + if ($coll) { if ($oneToOne) { - $prev[$dqlAlias] =& $coll; + $prev[$dqlAlias] = &$coll; } else { end($coll); - $prev[$dqlAlias] =& $coll[key($coll)]; + $prev[$dqlAlias] = &$coll[key($coll)]; } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hydrator/ArrayHierarchyDriver.php b/lib/Doctrine/Hydrator/ArrayHierarchyDriver.php index 731ad0090..128ca7558 100644 --- a/lib/Doctrine/Hydrator/ArrayHierarchyDriver.php +++ b/lib/Doctrine/Hydrator/ArrayHierarchyDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to the hierarchy graph using php arrays + * Builds result sets in to the hierarchy graph using php arrays. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision$ + * * @author Guilherme Blanco */ class Doctrine_Hydrator_ArrayHierarchyDriver extends Doctrine_Hydrator_ArrayDriver @@ -41,7 +42,7 @@ public function hydrateResultSet($stmt) $table = $this->getRootComponent(); - if ( ! $table->isTree() || ! $table->hasColumn('level')) { + if (!$table->isTree() || !$table->hasColumn('level')) { throw new Doctrine_Exception('Cannot hydrate model that does not implements Tree behavior with `level` column'); } @@ -62,25 +63,26 @@ public function hydrateResultSet($stmt) $l = count($stack); // Check if we're dealing with different levels - while($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { + while ($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { array_pop($stack); - $l--; + --$l; } // Stack is empty (we are inspecting the root) - if ($l == 0) { + if (0 == $l) { // Assigning the root child $i = count($trees); $trees[$i] = $item; - $stack[] = & $trees[$i]; + $stack[] = &$trees[$i]; } else { // Add child to parent $i = count($stack[$l - 1]['__children']); $stack[$l - 1]['__children'][$i] = $item; - $stack[] = & $stack[$l - 1]['__children'][$i]; + $stack[] = &$stack[$l - 1]['__children'][$i]; } } } + return $trees; } } diff --git a/lib/Doctrine/Hydrator/ArrayShallowDriver.php b/lib/Doctrine/Hydrator/ArrayShallowDriver.php index b595122b6..392b815cc 100644 --- a/lib/Doctrine/Hydrator/ArrayShallowDriver.php +++ b/lib/Doctrine/Hydrator/ArrayShallowDriver.php @@ -22,12 +22,14 @@ /** * Extended version of Doctrine_Hydrator_ScalarDriver, passes its _gatherRowData function a value of false for $aliasPrefix in order to cause it to generate the sorts of array keys one would see in a HYDRATE_ARRAY type return. * Note: This hydrator will have issues with fields in the return that have the same name (such as 2 fields each called id) -- the second field value will overwrite the first field. - * @package Doctrine - * @subpackage Hydrate + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2.3 + * * @version $Revision$ + * * @author Will Ferrer */ class Doctrine_Hydrator_ArrayShallowDriver extends Doctrine_Hydrator_ScalarDriver @@ -42,6 +44,7 @@ public function hydrateResultSet($stmt) while ($data = $stmt->fetch(Doctrine_Core::FETCH_ASSOC)) { $result[] = $this->_gatherRowData($data, $cache, false); } + return $result; } } diff --git a/lib/Doctrine/Hydrator/Exception.php b/lib/Doctrine/Hydrator/Exception.php index 571eba4af..7c5d1f441 100644 --- a/lib/Doctrine/Hydrator/Exception.php +++ b/lib/Doctrine/Hydrator/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Hydrator_Exception + * Doctrine_Hydrator_Exception. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Hydrator_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Hydrator/Graph.php b/lib/Doctrine/Hydrator/Graph.php index b227f3874..e80785d80 100644 --- a/lib/Doctrine/Hydrator/Graph.php +++ b/lib/Doctrine/Hydrator/Graph.php @@ -21,29 +21,29 @@ /** * Abstract base class for child drivers to hydrate the object graph in to - * various data types. For example Doctrine_Record instances or PHP arrays + * various data types. For example Doctrine_Record instances or PHP arrays. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Roman Borschel * @author Jonathan H. Wage */ abstract class Doctrine_Hydrator_Graph extends Doctrine_Hydrator_Abstract { - protected - $_tables = array(), - $_rootAlias = null; + protected $_tables = array(); + protected $_rootAlias; /** * Gets the custom field used for indexing for the specified component alias. * - * @return string The field name of the field used for indexing or NULL - * if the component does not use any custom field indices. + * @return string the field name of the field used for indexing or NULL + * if the component does not use any custom field indices */ protected function _getCustomIndexField($alias) { @@ -94,7 +94,7 @@ public function hydrateResultSet($stmt) if ($result instanceof Doctrine_Collection && $indexField = $this->_getCustomIndexField($rootAlias)) { $result->setKeyColumn($indexField); } - if ($stmt === false || $stmt === 0) { + if (false === $stmt || 0 === $stmt) { return $result; } @@ -103,21 +103,22 @@ public function hydrateResultSet($stmt) $event = new Doctrine_Event(null, Doctrine_Event::HYDRATE, null); - if ($this->_hydrationMode == Doctrine_Core::HYDRATE_ON_DEMAND) { - if ( ! is_null($this->_priorRow)) { + if (Doctrine_Core::HYDRATE_ON_DEMAND == $this->_hydrationMode) { + if (!is_null($this->_priorRow)) { $data = $this->_priorRow; $this->_priorRow = null; } else { $data = $stmt->fetch(Doctrine_Core::FETCH_ASSOC); - if ( ! $data) { + if (!$data) { return $result; } } $activeRootIdentifier = null; } else { $data = $stmt->fetch(Doctrine_Core::FETCH_ASSOC); - if ( ! $data) { + if (!$data) { $stmt->closeCursor(); + return $result; } } @@ -126,7 +127,7 @@ public function hydrateResultSet($stmt) $table = $this->_queryComponents[$rootAlias]['table']; if ($table->getConnection()->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_RTRIM) { - foreach($data as $key => $foo) { + foreach ($data as $key => $foo) { $data[$key] = (is_string($foo)) ? rtrim($foo) : $foo; } } @@ -135,13 +136,14 @@ public function hydrateResultSet($stmt) $nonemptyComponents = array(); $rowData = $this->_gatherRowData($data, $cache, $id, $nonemptyComponents); - if ($this->_hydrationMode == Doctrine_Core::HYDRATE_ON_DEMAND) { + if (Doctrine_Core::HYDRATE_ON_DEMAND == $this->_hydrationMode) { if (is_null($activeRootIdentifier)) { // first row for this record $activeRootIdentifier = $id[$rootAlias]; - } else if ($activeRootIdentifier != $id[$rootAlias]) { + } elseif ($activeRootIdentifier != $id[$rootAlias]) { // first row for the next record $this->_priorRow = $data; + return $result; } } @@ -159,7 +161,7 @@ public function hydrateResultSet($stmt) $index = false; // Check for an existing element - if ($isSimpleQuery || ! isset($identifierMap[$rootAlias][$id[$rootAlias]])) { + if ($isSimpleQuery || !isset($identifierMap[$rootAlias][$id[$rootAlias]])) { $element = $this->getElement($rowData[$rootAlias], $componentName); $event->set('data', $element); $listeners[$componentName]->postHydrate($event); @@ -167,10 +169,11 @@ public function hydrateResultSet($stmt) // do we need to index by a custom field? if ($field = $this->_getCustomIndexField($rootAlias)) { - if ( ! isset($element[$field])) { - throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key named '$field'."); - } else if (isset($result[$element[$field]])) { - throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping named '{$element[$field]}' for the field named '$field'."); + if (!isset($element[$field])) { + throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key named '{$field}'."); + } + if (isset($result[$element[$field]])) { + throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping named '{$element[$field]}' for the field named '{$field}'."); } $result[$element[$field]] = $element; } else { @@ -201,20 +204,17 @@ public function hydrateResultSet($stmt) $instances[$componentName]->preHydrate($event); // It would be nice if this could be moved to the query parser but I could not find a good place to implement it - if ( ! isset($map['parent'])) { - throw new Doctrine_Hydrator_Exception( - '"' . $componentName . '" with an alias of "' . $dqlAlias . '"' . - ' in your query does not reference the parent component it is related to.' - ); + if (!isset($map['parent'])) { + throw new Doctrine_Hydrator_Exception('"'.$componentName.'" with an alias of "'.$dqlAlias.'" in your query does not reference the parent component it is related to.'); } $parent = $map['parent']; $relation = $map['relation']; $relationAlias = $map['relation']->getAlias(); - $path = $parent . '.' . $dqlAlias; + $path = $parent.'.'.$dqlAlias; - if ( ! isset($prev[$parent])) { + if (!isset($prev[$parent])) { unset($prev[$dqlAlias]); // Ticket #1228 continue; } @@ -222,24 +222,25 @@ public function hydrateResultSet($stmt) $indexField = $this->_getCustomIndexField($dqlAlias); // check the type of the relation - if ( ! $relation->isOneToOne() && $this->initRelated($prev[$parent], $relationAlias, $indexField)) { + if (!$relation->isOneToOne() && $this->initRelated($prev[$parent], $relationAlias, $indexField)) { $oneToOne = false; // append element if (isset($nonemptyComponents[$dqlAlias])) { $indexExists = isset($identifierMap[$path][$id[$parent]][$id[$dqlAlias]]); $index = $indexExists ? $identifierMap[$path][$id[$parent]][$id[$dqlAlias]] : false; - $indexIsValid = $index !== false ? isset($prev[$parent][$relationAlias][$index]) : false; - if ( ! $indexExists || ! $indexIsValid) { + $indexIsValid = false !== $index ? isset($prev[$parent][$relationAlias][$index]) : false; + if (!$indexExists || !$indexIsValid) { $element = $this->getElement($data, $componentName); $event->set('data', $element); $listeners[$componentName]->postHydrate($event); $instances[$componentName]->postHydrate($event); if ($field = $this->_getCustomIndexField($dqlAlias)) { - if ( ! isset($element[$field])) { - throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key named '$field'."); - } else if (isset($prev[$parent][$relationAlias][$element[$field]])) { - throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping named '$field'."); + if (!isset($element[$field])) { + throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key named '{$field}'."); + } + if (isset($prev[$parent][$relationAlias][$element[$field]])) { + throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping named '{$field}'."); } $prev[$parent][$relationAlias][$element[$field]] = $element; } else { @@ -258,9 +259,9 @@ public function hydrateResultSet($stmt) } else { // 1-1 relation $oneToOne = true; - if ( ! isset($nonemptyComponents[$dqlAlias]) && ! isset($prev[$parent][$relationAlias])) { + if (!isset($nonemptyComponents[$dqlAlias]) && !isset($prev[$parent][$relationAlias])) { $prev[$parent][$relationAlias] = $this->getNullPointer(); - } else if ( ! isset($prev[$parent][$relationAlias])) { + } elseif (!isset($prev[$parent][$relationAlias])) { $element = $this->getElement($data, $componentName); // [FIX] Tickets #1205 and #1237 @@ -271,8 +272,8 @@ public function hydrateResultSet($stmt) $prev[$parent][$relationAlias] = $element; } } - if ($prev[$parent][$relationAlias] !== null && !$prev[$parent][$relationAlias] instanceof Doctrine_Null) { - $coll =& $prev[$parent][$relationAlias]; + if (null !== $prev[$parent][$relationAlias] && !$prev[$parent][$relationAlias] instanceof Doctrine_Null) { + $coll = &$prev[$parent][$relationAlias]; $this->setLastElement($prev, $coll, $index, $dqlAlias, $oneToOne); } } @@ -289,8 +290,8 @@ public function hydrateResultSet($stmt) * they belong to. The column names in the result set are mapped to their * field names during this procedure. * - * @return array An array with all the fields (name => value) of the data row, - * grouped by their component (alias). + * @return array an array with all the fields (name => value) of the data row, + * grouped by their component (alias) */ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) { @@ -298,7 +299,7 @@ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) foreach ($data as $key => $value) { // Parse each column name only once. Cache the results. - if ( ! isset($cache[$key])) { + if (!isset($cache[$key])) { // check ignored names. fastest solution for now. if we get more we'll start // to introduce a list. if ($this->_isIgnoredName($key)) { @@ -319,11 +320,11 @@ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) if ($table->isIdentifier($fieldName)) { $cache[$key]['isIdentifier'] = true; } else { - $cache[$key]['isIdentifier'] = false; + $cache[$key]['isIdentifier'] = false; } $type = $table->getTypeOfColumn($last); - if ($type == 'integer' || $type == 'string') { + if ('integer' == $type || 'string' == $type) { $cache[$key]['isSimpleType'] = true; } else { $cache[$key]['type'] = $type; @@ -342,7 +343,7 @@ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) } if ($cache[$key]['isIdentifier']) { - $id[$dqlAlias] .= '|' . $value; + $id[$dqlAlias] .= '|'.$value; } if ($cache[$key]['isSimpleType']) { @@ -363,7 +364,7 @@ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) $rowData[$dqlAlias][$fieldName] = $preparedValue; } - if ( ! isset($nonemptyComponents[$dqlAlias]) && $value !== null) { + if (!isset($nonemptyComponents[$dqlAlias]) && null !== $value) { $nonemptyComponents[$dqlAlias] = true; } } @@ -387,11 +388,10 @@ abstract public function setLastElement(&$prev, &$coll, $index, $dqlAlias, $oneT public function flush() { - } /** - * Get the classname to return. Most often this is just the options['name'] + * Get the classname to return. Most often this is just the options['name']. * * Check the subclasses option and the inheritanceMap for each subclass to see * if all the maps in a subclass is met. If this is the case return that @@ -402,15 +402,14 @@ public function flush() * if the subclassing option is not set. * * @return string The name of the class to create - * */ protected function _getClassnameToReturn(array &$data, $component) { - if ( ! isset($this->_tables[$component])) { + if (!isset($this->_tables[$component])) { $this->_tables[$component] = Doctrine_Core::getTable($component); } - if ( ! ($subclasses = $this->_tables[$component]->getOption('subclasses'))) { + if (!($subclasses = $this->_tables[$component]->getOption('subclasses'))) { return $component; } @@ -426,7 +425,7 @@ protected function _getClassnameToReturn(array &$data, $component) --$needMatches; } } - if ($needMatches == 0) { + if (0 == $needMatches) { $matchedComponents[] = $table->getComponentName(); } } else { @@ -434,16 +433,15 @@ protected function _getClassnameToReturn(array &$data, $component) $key = $this->_tables[$component]->getFieldName($key); if (!isset($data[$key]) || $data[$key] != $value) { continue; - } else { - $matchedComponents[] = $table->getComponentName(); } + $matchedComponents[] = $table->getComponentName(); } } } - $matchedComponent = $matchedComponents[count($matchedComponents)-1]; + $matchedComponent = $matchedComponents[count($matchedComponents) - 1]; - if ( ! isset($this->_tables[$matchedComponent])) { + if (!isset($this->_tables[$matchedComponent])) { $this->_tables[$matchedComponent] = Doctrine_Core::getTable($matchedComponent); } diff --git a/lib/Doctrine/Hydrator/NoneDriver.php b/lib/Doctrine/Hydrator/NoneDriver.php index 6da15a6d6..924b7706b 100644 --- a/lib/Doctrine/Hydrator/NoneDriver.php +++ b/lib/Doctrine/Hydrator/NoneDriver.php @@ -20,22 +20,19 @@ */ /** - * Get results directly and skip hydration. Uses PDO::FETCH_NUM + * Get results directly and skip hydration. Uses PDO::FETCH_NUM. * - * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision: 3192 $ + * * @author Jonathan H. Wage */ class Doctrine_Hydrator_NoneDriver extends Doctrine_Hydrator_Abstract { - /** - * @return mixed - */ public function hydrateResultSet($stmt) { return $stmt->fetchAll(PDO::FETCH_NUM); diff --git a/lib/Doctrine/Hydrator/RecordDriver.php b/lib/Doctrine/Hydrator/RecordDriver.php index a028645d4..5b510c53f 100644 --- a/lib/Doctrine/Hydrator/RecordDriver.php +++ b/lib/Doctrine/Hydrator/RecordDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to the object graph using Doctrine_Record instances + * Builds result sets in to the object graph using Doctrine_Record instances. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Roman Borschel * @author Jonathan H. Wage @@ -44,68 +45,70 @@ public function getElementCollection($component) return $coll; } - + public function initRelated(&$record, $name, $keyColumn = null) { - if ( ! isset($this->_initializedRelations[$record->getOid()][$name])) { + if (!isset($this->_initializedRelations[$record->getOid()][$name])) { $relation = $record->getTable()->getRelation($name); $coll = Doctrine_Collection::create($relation->getTable()->getComponentName(), $keyColumn); $coll->setReference($record, $relation); $record[$name] = $coll; $this->_initializedRelations[$record->getOid()][$name] = true; } + return true; } - + public function registerCollection($coll) { $this->_collections[] = $coll; } - - public function getNullPointer() + + public function getNullPointer() { return self::$_null; } - + public function getElement(array $data, $component) { $component = $this->_getClassNameToReturn($data, $component); $this->_tables[$component]->setData($data); - $record = $this->_tables[$component]->getRecord(); - return $record; + return $this->_tables[$component]->getRecord(); } - public function getLastKey(&$coll) + public function getLastKey(&$coll) { $coll->end(); - + return $coll->key(); } /** * sets the last element of given data array / collection - * as previous element + * as previous element. + * + * @param bool|int $index * - * @param boolean|integer $index - * @return void * @todo Detailed documentation */ public function setLastElement(&$prev, &$coll, $index, $dqlAlias, $oneToOne) { if ($coll === self::$_null) { unset($prev[$dqlAlias]); // Ticket #1228 + return; } - if ($index !== false) { + if (false !== $index) { // Link element at $index to previous element for the component // identified by the DQL alias $alias $prev[$dqlAlias] = $coll[$index]; + return; } - + if (count($coll) > 0) { $prev[$dqlAlias] = $coll->getLast(); } @@ -121,4 +124,4 @@ public function flush() $this->_collections = array(); $this->_tables = null; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hydrator/RecordHierarchyDriver.php b/lib/Doctrine/Hydrator/RecordHierarchyDriver.php index 28c54e20e..63266ea0d 100644 --- a/lib/Doctrine/Hydrator/RecordHierarchyDriver.php +++ b/lib/Doctrine/Hydrator/RecordHierarchyDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to the hierarchy graph using php arrays + * Builds result sets in to the hierarchy graph using php arrays. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision$ + * * @author Guilherme Blanco */ class Doctrine_Hydrator_RecordHierarchyDriver extends Doctrine_Hydrator_RecordDriver diff --git a/lib/Doctrine/Hydrator/ScalarDriver.php b/lib/Doctrine/Hydrator/ScalarDriver.php index d3ce87e66..8a315e166 100644 --- a/lib/Doctrine/Hydrator/ScalarDriver.php +++ b/lib/Doctrine/Hydrator/ScalarDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to a scalar php array + * Builds result sets in to a scalar php array. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Hydrator_ScalarDriver extends Doctrine_Hydrator_Abstract @@ -52,8 +53,8 @@ protected function _gatherRowData($data, &$cache, $aliasPrefix = true) $rowData = array(); foreach ($data as $key => $value) { // Parse each column name only once. Cache the results. - if ( ! isset($cache[$key])) { - if ($key == 'DOCTRINE_ROWNUM') { + if (!isset($cache[$key])) { + if ('DOCTRINE_ROWNUM' == $key) { continue; } // cache general information like the column name <-> field name mapping @@ -74,7 +75,7 @@ protected function _gatherRowData($data, &$cache, $aliasPrefix = true) // cache type information $type = $table->getTypeOfColumn($columnName); - if ($type == 'integer' || $type == 'string') { + if ('integer' == $type || 'string' == $type) { $cache[$key]['isSimpleType'] = true; } else { $cache[$key]['type'] = $type; @@ -86,15 +87,16 @@ protected function _gatherRowData($data, &$cache, $aliasPrefix = true) $dqlAlias = $cache[$key]['dqlAlias']; $fieldName = $cache[$key]['fieldName']; - $rowDataKey = $aliasPrefix ? $dqlAlias . '_' . $fieldName:$fieldName; + $rowDataKey = $aliasPrefix ? $dqlAlias.'_'.$fieldName : $fieldName; if ($cache[$key]['isSimpleType'] || $cache[$key]['isAgg']) { $rowData[$rowDataKey] = $value; } else { $rowData[$rowDataKey] = $table->prepareValue( - $fieldName, $value, $cache[$key]['type']); + $fieldName, $value, $cache[$key]['type']); } } + return $rowData; } } diff --git a/lib/Doctrine/Hydrator/SingleScalarDriver.php b/lib/Doctrine/Hydrator/SingleScalarDriver.php index bf7589522..8b7fcd398 100644 --- a/lib/Doctrine/Hydrator/SingleScalarDriver.php +++ b/lib/Doctrine/Hydrator/SingleScalarDriver.php @@ -20,20 +20,20 @@ */ /** - * Returns the first row and first column single scalar value + * Returns the first row and first column single scalar value. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Hydrator_SingleScalarDriver extends Doctrine_Hydrator_Abstract { /** - * @param mixed $stmt * @return array|mixed */ public function hydrateResultSet($stmt) @@ -42,10 +42,10 @@ public function hydrateResultSet($stmt) while (($val = $stmt->fetchColumn()) !== false) { $result[] = $val; } - if (count($result) === 1) { + if (1 === count($result)) { return $result[0]; - } else { - return $result; } + + return $result; } } diff --git a/lib/Doctrine/I18n.php b/lib/Doctrine/I18n.php index e520fe50d..ca6d4caba 100644 --- a/lib/Doctrine/I18n.php +++ b/lib/Doctrine/I18n.php @@ -20,39 +20,39 @@ */ /** - * Doctrine_I18n + * Doctrine_I18n. * - * @package Doctrine - * @subpackage I18n * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_I18n extends Doctrine_Record_Generator { protected $_options = array( - 'className' => '%CLASS%Translation', - 'tableName' => '%TABLE%_translation', - 'fields' => array(), - 'generateFiles' => false, - 'table' => false, - 'pluginTable' => false, - 'children' => array(), - 'i18nField' => 'lang', - 'type' => 'string', - 'length' => 2, - 'options' => array(), - 'cascadeDelete' => true, - 'appLevelDelete'=> false - ); + 'className' => '%CLASS%Translation', + 'tableName' => '%TABLE%_translation', + 'fields' => array(), + 'generateFiles' => false, + 'table' => false, + 'pluginTable' => false, + 'children' => array(), + 'i18nField' => 'lang', + 'type' => 'string', + 'length' => 2, + 'options' => array(), + 'cascadeDelete' => true, + 'appLevelDelete' => false, + ); /** - * __construct + * __construct. * - * @param string $options - * @return void + * @param string $options */ public function __construct($options) { @@ -66,16 +66,13 @@ public function buildRelation() } /** - * buildDefinition - * - * @param object $Doctrine_Table - * @return void + * buildDefinition. */ public function setTableDefinition() { - if (empty($this->_options['fields'])) { - throw new Doctrine_I18n_Exception('Fields not set.'); - } + if (empty($this->_options['fields'])) { + throw new Doctrine_I18n_Exception('Fields not set.'); + } $options = array('className' => $this->_options['className']); @@ -86,7 +83,7 @@ public function setTableDefinition() $fieldName = $this->_options['table']->getFieldName($column); if (in_array($fieldName, $this->_options['fields'])) { if ($column != $fieldName) { - $column .= ' as ' . $fieldName; + $column .= ' as '.$fieldName; } $columns[$column] = $definition; $this->_options['table']->removeColumn($fieldName); @@ -97,27 +94,27 @@ public function setTableDefinition() $defaultOptions = array( 'fixed' => true, - 'primary' => true + 'primary' => true, ); $options = array_merge($defaultOptions, $this->_options['options']); $this->hasColumn($this->_options['i18nField'], $this->_options['type'], $this->_options['length'], $options); $this->bindQueryParts(array('indexBy' => $this->_options['i18nField'])); - + // Rewrite any relations to our original table $originalName = $this->_options['table']->getClassnameToReturn(); $relations = $this->_options['table']->getRelationParser()->getPendingRelations(); - foreach($relations as $table => $relation) { - if ($table != $this->_table->getTableName() ) { + foreach ($relations as $table => $relation) { + if ($table != $this->_table->getTableName()) { // check that the localColumn is part of the moved col if (isset($relation['local']) && in_array($relation['local'], $this->_options['fields'])) { // found one, let's rewrite it $this->_options['table']->getRelationParser()->unsetPendingRelations($table); - + // and bind the rewritten one $this->_table->getRelationParser()->bind($table, $relation); - + // now try to get the reverse relation, to rewrite it $rp = Doctrine_Core::getTable($table)->getRelationParser(); $others = $rp->getPendingRelation($originalName); @@ -125,10 +122,10 @@ public function setTableDefinition() $others['class'] = $this->_table->getClassnameToReturn(); $others['alias'] = $this->_table->getClassnameToReturn(); $rp->unsetPendingRelations($originalName); - $rp->bind($this->_table->getClassnameToReturn() ,$others); + $rp->bind($this->_table->getClassnameToReturn(), $others); } } } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/I18n/Exception.php b/lib/Doctrine/I18n/Exception.php index cd1845a15..553f17515 100644 --- a/lib/Doctrine/I18n/Exception.php +++ b/lib/Doctrine/I18n/Exception.php @@ -18,17 +18,19 @@ * and is licensed under the LGPL. For more information, see * . */ - + /** - * Doctrine_I18n_Exception + * Doctrine_I18n_Exception. * - * @package Doctrine - * @subpackage I18n * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_I18n_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Import.php b/lib/Doctrine/Import.php index 928c1dd26..8dbe68c20 100644 --- a/lib/Doctrine/Import.php +++ b/lib/Doctrine/Import.php @@ -25,12 +25,14 @@ * reading to a reader object and passes the result to a builder object which * builds a Doctrine data model. * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jukka Hassinen */ @@ -39,74 +41,77 @@ class Doctrine_Import extends Doctrine_Connection_Module protected $sql = array(); /** - * lists all databases + * lists all databases. * * @return array */ public function listDatabases() { - if ( ! isset($this->sql['listDatabases'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listDatabases'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listDatabases']); } /** - * lists all availible database functions + * lists all availible database functions. * * @return array */ public function listFunctions() { - if ( ! isset($this->sql['listFunctions'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listFunctions'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listFunctions']); } /** - * lists all database triggers + * lists all database triggers. * * @param string|null $database + * * @return array */ public function listTriggers($database = null) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) { - if ( ! isset($this->sql['listSequences'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listSequences'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listSequences']); } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table relations + * lists table relations. * - * Expects an array of this format to be returned with all the relationships in it where the key is + * Expects an array of this format to be returned with all the relationships in it where the key is * the name of the foreign table, and the value is an array containing the local and foreign column * name * @@ -119,103 +124,111 @@ public function listTableConstraints($table) * ) * ) * - * @param string $table database table name + * @param string $table database table name + * * @return array */ public function listTableRelations($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table views + * lists table views. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists database users + * lists database users. * * @return array */ public function listUsers() { - if ( ! isset($this->sql['listUsers'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listUsers'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listUsers']); } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) { - if ( ! isset($this->sql['listViews'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listViews'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listViews']); } /** - * checks if a database exists + * checks if a database exists. * * @param string $database - * @return boolean + * + * @return bool */ public function databaseExists($database) { @@ -223,10 +236,11 @@ public function databaseExists($database) } /** - * checks if a function exists + * checks if a function exists. * * @param string $function - * @return boolean + * + * @return bool */ public function functionExists($function) { @@ -234,11 +248,12 @@ public function functionExists($function) } /** - * checks if a trigger exists + * checks if a trigger exists. * - * @param string $trigger + * @param string $trigger * @param string|null $database - * @return boolean + * + * @return bool */ public function triggerExists($trigger, $database = null) { @@ -246,11 +261,12 @@ public function triggerExists($trigger, $database = null) } /** - * checks if a sequence exists + * checks if a sequence exists. * - * @param string $sequence + * @param string $sequence * @param string|null $database - * @return boolean + * + * @return bool */ public function sequenceExists($sequence, $database = null) { @@ -258,11 +274,12 @@ public function sequenceExists($sequence, $database = null) } /** - * checks if a table constraint exists + * checks if a table constraint exists. * * @param string $constraint - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableConstraintExists($constraint, $table) { @@ -270,11 +287,12 @@ public function tableConstraintExists($constraint, $table) } /** - * checks if a table column exists + * checks if a table column exists. * * @param string $column - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableColumnExists($column, $table) { @@ -282,11 +300,12 @@ public function tableColumnExists($column, $table) } /** - * checks if a table index exists + * checks if a table index exists. * * @param string $index - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableIndexExists($index, $table) { @@ -294,11 +313,12 @@ public function tableIndexExists($index, $table) } /** - * checks if a table exists + * checks if a table exists. * - * @param string $table + * @param string $table * @param string|null $database - * @return boolean + * + * @return bool */ public function tableExists($table, $database = null) { @@ -306,11 +326,12 @@ public function tableExists($table, $database = null) } /** - * checks if a table trigger exists + * checks if a table trigger exists. * * @param string $trigger - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableTriggerExists($trigger, $table) { @@ -318,11 +339,12 @@ public function tableTriggerExists($trigger, $table) } /** - * checks if a table view exists + * checks if a table view exists. * * @param string $view - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableViewExists($view, $table) { @@ -330,10 +352,11 @@ public function tableViewExists($view, $table) } /** - * checks if a user exists + * checks if a user exists. * * @param string $user - * @return boolean + * + * @return bool */ public function userExists($user) { @@ -341,25 +364,27 @@ public function userExists($user) } /** - * checks if a view exists + * checks if a view exists. * - * @param string $view + * @param string $view * @param string|null $database - * @return boolean + * + * @return bool */ public function viewExists($view, $database = null) { - return in_array($view, $this->listViews($database)); + return in_array($view, $this->listViews($database)); } /** - * importSchema + * importSchema. * * method for importing existing schema to Doctrine_Record classes * * @param string $directory - * @param array $connections Array of connection names to generate models for - * @return array the names of the imported classes + * @param array $connections Array of connection names to generate models for + * + * @return array the names of the imported classes */ public function importSchema($directory, array $connections = array(), array $options = array()) { @@ -367,79 +392,80 @@ public function importSchema($directory, array $connections = array(), array $op $manager = Doctrine_Manager::getInstance(); foreach ($manager as $name => $connection) { - // Limit the databases to the ones specified by $connections. - // Check only happens if array is not empty - if ( ! empty($connections) && ! in_array($name, $connections)) { - continue; - } - - $builder = new Doctrine_Import_Builder(); - $builder->setTargetPath($directory); - $builder->setOptions($options); - - $definitions = array(); - - foreach ($connection->import->listTables() as $table) { - $definition = array(); - $definition['tableName'] = $table; - $definition['className'] = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); - $definition['columns'] = $connection->import->listTableColumns($table); - $definition['connection'] = $connection->getName(); - $definition['connectionClassName'] = $definition['className']; - - try { - $definition['relations'] = array(); - $relations = $connection->import->listTableRelations($table); - $relClasses = array(); - foreach ($relations as $relation) { - $table = $relation['table']; - $class = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); - if (in_array($class, $relClasses)) { - $alias = $class . '_' . (count($relClasses) + 1); - } else { - $alias = $class; - } - $relClasses[] = $class; - $definition['relations'][$alias] = array( - 'alias' => $alias, - 'class' => $class, - 'local' => $relation['local'], - 'foreign' => $relation['foreign'] - ); - } - } catch (Exception $e) {} - - $definitions[strtolower($definition['className'])] = $definition; - $classes[] = $definition['className']; - } - - // Build opposite end of relationships - foreach ($definitions as $definition) { - $className = $definition['className']; - $relClasses = array(); - foreach ($definition['relations'] as $alias => $relation) { - if (in_array($relation['class'], $relClasses) || isset($definitions[$relation['class']]['relations'][$className])) { - $alias = $className . '_' . (count($relClasses) + 1); - } else { - $alias = $className; - } - $relClasses[] = $relation['class']; - $definitions[strtolower($relation['class'])]['relations'][$alias] = array( - 'type' => Doctrine_Relation::MANY, - 'alias' => $alias, - 'class' => $className, - 'local' => $relation['foreign'], - 'foreign' => $relation['local'] - ); - } - } - - // Build records - foreach ($definitions as $definition) { - $builder->buildRecord($definition); - } + // Limit the databases to the ones specified by $connections. + // Check only happens if array is not empty + if (!empty($connections) && !in_array($name, $connections)) { + continue; + } + + $builder = new Doctrine_Import_Builder(); + $builder->setTargetPath($directory); + $builder->setOptions($options); + + $definitions = array(); + + foreach ($connection->import->listTables() as $table) { + $definition = array(); + $definition['tableName'] = $table; + $definition['className'] = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); + $definition['columns'] = $connection->import->listTableColumns($table); + $definition['connection'] = $connection->getName(); + $definition['connectionClassName'] = $definition['className']; + + try { + $definition['relations'] = array(); + $relations = $connection->import->listTableRelations($table); + $relClasses = array(); + foreach ($relations as $relation) { + $table = $relation['table']; + $class = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); + if (in_array($class, $relClasses)) { + $alias = $class.'_'.(count($relClasses) + 1); + } else { + $alias = $class; + } + $relClasses[] = $class; + $definition['relations'][$alias] = array( + 'alias' => $alias, + 'class' => $class, + 'local' => $relation['local'], + 'foreign' => $relation['foreign'], + ); + } + } catch (Exception $e) { + } + + $definitions[strtolower($definition['className'])] = $definition; + $classes[] = $definition['className']; + } + + // Build opposite end of relationships + foreach ($definitions as $definition) { + $className = $definition['className']; + $relClasses = array(); + foreach ($definition['relations'] as $alias => $relation) { + if (in_array($relation['class'], $relClasses) || isset($definitions[$relation['class']]['relations'][$className])) { + $alias = $className.'_'.(count($relClasses) + 1); + } else { + $alias = $className; + } + $relClasses[] = $relation['class']; + $definitions[strtolower($relation['class'])]['relations'][$alias] = array( + 'type' => Doctrine_Relation::MANY, + 'alias' => $alias, + 'class' => $className, + 'local' => $relation['foreign'], + 'foreign' => $relation['local'], + ); + } + } + + // Build records + foreach ($definitions as $definition) { + $builder->buildRecord($definition); + } } return $classes; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Builder.php b/lib/Doctrine/Import/Builder.php index 7dc64d4ab..1267b9e4c 100644 --- a/lib/Doctrine/Import/Builder.php +++ b/lib/Doctrine/Import/Builder.php @@ -20,178 +20,176 @@ */ /** - * Doctrine_Import_Builder + * Doctrine_Import_Builder. * * Import builder is responsible of building Doctrine_Record classes * based on a database schema. * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jukka Hassinen * @author Nicolas Bérard-Nault * @author Jonathan H. Wage */ -#[\AllowDynamicProperties] +#[AllowDynamicProperties] class Doctrine_Import_Builder extends Doctrine_Builder { /** - * Path where to generated files + * Path where to generated files. * - * @var string $_path + * @var string */ protected $_path = ''; /** - * Class prefix for generated packages + * Class prefix for generated packages. * * @var string */ protected $_packagesPrefix = 'Package'; /** - * Path to generate packages + * Path to generate packages. * * @var string */ protected $_packagesPath = ''; /** - * Name of folder to generate packages in + * Name of folder to generate packages in. * * @var string */ protected $_packagesFolderName = 'packages'; /** - * File suffix to use when writing class definitions + * File suffix to use when writing class definitions. * - * @var string $suffix + * @var string */ protected $_suffix = '.php'; /** - * Bool true/false for whether or not to generate base classes + * Bool true/false for whether or not to generate base classes. * - * @var boolean $generateBaseClasses + * @var bool */ protected $_generateBaseClasses = true; /** - * Bool true/false for whether or not to generate child table classes + * Bool true/false for whether or not to generate child table classes. * - * @var boolean $generateTableClasses + * @var bool */ protected $_generateTableClasses = false; /** - * Prefix to use for generated base classes + * Prefix to use for generated base classes. * * @var string */ protected $_baseClassPrefix = 'Base'; /** - * Directory to put the generate base classes in + * Directory to put the generate base classes in. * - * @var string $suffix + * @var string */ protected $_baseClassesDirectory = 'generated'; /** - * Base class name for generated classes + * Base class name for generated classes. * * @var string */ protected $_baseClassName = 'Doctrine_Record'; /** - * Base table class name for generated classes + * Base table class name for generated classes. * * @var string */ protected $_baseTableClassName = 'Doctrine_Table'; /** - * Format to use for generating the model table classes + * Format to use for generating the model table classes. * * @var string */ protected $_tableClassFormat = '%sTable'; /** - * Prefix to all generated classes + * Prefix to all generated classes. * * @var string */ - protected $_classPrefix = null; + protected $_classPrefix; /** - * Whether to use the class prefix for the filenames too + * Whether to use the class prefix for the filenames too. * - * @var boolean - **/ + * @var bool + */ protected $_classPrefixFiles = true; /** - * Whether or not to generate PEAR style directories and files + * Whether or not to generate PEAR style directories and files. * - * @var boolean + * @var bool */ protected $_pearStyle = false; /** - * Allows to force a line-ending style, by default PHP_EOL will be used + * Allows to force a line-ending style, by default PHP_EOL will be used. * * @var string */ - protected $_eolStyle = null; + protected $_eolStyle; /** - * The package name to use for the generated php docs + * The package name to use for the generated php docs. * * @var string */ protected $_phpDocPackage = '##PACKAGE##'; /** - * The subpackage name to use for the generated php docs + * The subpackage name to use for the generated php docs. * * @var string */ protected $_phpDocSubpackage = '##SUBPACKAGE##'; /** - * Full name of the author to use for the generated php docs + * Full name of the author to use for the generated php docs. * * @var string */ protected $_phpDocName = '##NAME##'; /** - * Email of the author to use for the generated php docs + * Email of the author to use for the generated php docs. * * @var string */ protected $_phpDocEmail = '##EMAIL##'; /** - * _tpl + * _tpl. * * Class template used for writing classes - * - * @var $_tpl */ protected static $_tpl; /** - * __construct - * - * @return void + * __construct. */ public function __construct() { @@ -209,16 +207,15 @@ public function __construct() } /** - * setTargetPath + * setTargetPath. * * @param string path the path where imported files are being generated - * @return */ public function setTargetPath($path) { if ($path) { - if ( ! $this->_packagesPath) { - $this->setOption('packagesPath', $path . DIRECTORY_SEPARATOR . $this->_packagesFolderName); + if (!$this->_packagesPath) { + $this->setOption('packagesPath', $path.DIRECTORY_SEPARATOR.$this->_packagesFolderName); } $this->_path = $path; @@ -226,16 +223,17 @@ public function setTargetPath($path) } /** - * generateBaseClasses + * generateBaseClasses. * * Specify whether or not to generate classes which extend from generated base classes * - * @param boolean $bool - * @return boolean $bool + * @param bool $bool + * + * @return bool $bool */ public function generateBaseClasses($bool = null) { - if ($bool !== null) { + if (null !== $bool) { $this->_generateBaseClasses = $bool; } @@ -243,16 +241,17 @@ public function generateBaseClasses($bool = null) } /** - * generateTableClasses + * generateTableClasses. * * Specify whether or not to generate children table classes * - * @param boolean $bool - * @return boolean $bool + * @param bool $bool + * + * @return bool $bool */ public function generateTableClasses($bool = null) { - if ($bool !== null) { + if (null !== $bool) { $this->_generateTableClasses = $bool; } @@ -260,9 +259,9 @@ public function generateTableClasses($bool = null) } /** - * getTargetPath + * getTargetPath. * - * @return string the path where imported files are being generated + * @return string the path where imported files are being generated */ public function getTargetPath() { @@ -270,14 +269,13 @@ public function getTargetPath() } /** - * setOptions + * setOptions. * * @param string $options - * @return void */ public function setOptions($options) { - if ( ! empty($options)) { + if (!empty($options)) { foreach ($options as $key => $value) { $this->setOption($key, $value); } @@ -285,30 +283,27 @@ public function setOptions($options) } /** - * setOption + * setOption. * * @param string $key * @param string $value - * @return void */ public function setOption($key, $value) { - $name = 'set' . Doctrine_Inflector::classify($key); + $name = 'set'.Doctrine_Inflector::classify($key); if (method_exists($this, $name)) { - $this->$name($value); + $this->{$name}($value); } else { - $key = '_' . $key; - $this->$key = $value; + $key = '_'.$key; + $this->{$key} = $value; } } /** - * loadTemplate + * loadTemplate. * * Loads the class template used for generating classes - * - * @return void */ public function loadTemplate() { @@ -317,13 +312,13 @@ public function loadTemplate() } self::$_tpl = '/**' - . '%s' . PHP_EOL - . ' */' . PHP_EOL - . '%sclass %s extends %s' . PHP_EOL - . '{' - . '%s' . PHP_EOL - . '%s' . PHP_EOL - . '}'; + .'%s'.PHP_EOL + .' */'.PHP_EOL + .'%sclass %s extends %s'.PHP_EOL + .'{' + .'%s'.PHP_EOL + .'%s'.PHP_EOL + .'}'; } /* @@ -334,7 +329,7 @@ public function loadTemplate() */ public function buildTableDefinition(array $definition) { - if (isset($definition['inheritance']['type']) && ($definition['inheritance']['type'] == 'simple' || $definition['inheritance']['type'] == 'column_aggregation')) { + if (isset($definition['inheritance']['type']) && ('simple' == $definition['inheritance']['type'] || 'column_aggregation' == $definition['inheritance']['type'])) { return; } @@ -342,63 +337,60 @@ public function buildTableDefinition(array $definition) $i = 0; - if (isset($definition['inheritance']['type']) && $definition['inheritance']['type'] == 'concrete') { - $ret[$i] = " parent::setTableDefinition();"; - $i++; + if (isset($definition['inheritance']['type']) && 'concrete' == $definition['inheritance']['type']) { + $ret[$i] = ' parent::setTableDefinition();'; + ++$i; } if (isset($definition['tableName']) && !empty($definition['tableName'])) { - $ret[$i] = " ".'$this->setTableName(\''. $definition['tableName'].'\');'; - $i++; + $ret[$i] = ' $this->setTableName(\''.$definition['tableName'].'\');'; + ++$i; } if (isset($definition['columns']) && is_array($definition['columns']) && !empty($definition['columns'])) { $ret[$i] = $this->buildColumns($definition['columns']); - $i++; + ++$i; } if (isset($definition['indexes']) && is_array($definition['indexes']) && !empty($definition['indexes'])) { $ret[$i] = $this->buildIndexes($definition['indexes']); - $i++; + ++$i; } if (isset($definition['attributes']) && is_array($definition['attributes']) && !empty($definition['attributes'])) { $ret[$i] = $this->buildAttributes($definition['attributes']); - $i++; + ++$i; } if (isset($definition['options']) && is_array($definition['options']) && !empty($definition['options'])) { $ret[$i] = $this->buildOptions($definition['options']); - $i++; + ++$i; } if (isset($definition['checks']) && is_array($definition['checks']) && !empty($definition['checks'])) { $ret[$i] = $this->buildChecks($definition['checks']); - $i++; + ++$i; } - if (isset($definition['inheritance']['subclasses']) && ! empty($definition['inheritance']['subclasses'])) { + if (isset($definition['inheritance']['subclasses']) && !empty($definition['inheritance']['subclasses'])) { $subClasses = array(); foreach ($definition['inheritance']['subclasses'] as $className => $def) { - $className = $this->_classPrefix . $className; + $className = $this->_classPrefix.$className; $subClasses[$className] = $def; } - $ret[$i] = " ".'$this->setSubClasses('. $this->varExport($subClasses).');'; - $i++; + $ret[$i] = ' $this->setSubClasses('.$this->varExport($subClasses).');'; + ++$i; } $code = implode(PHP_EOL, $ret); $code = trim($code); - return PHP_EOL . " public function setTableDefinition()" . PHP_EOL . ' {' . PHP_EOL . ' ' . $code . PHP_EOL . ' }'; + return PHP_EOL.' public function setTableDefinition()'.PHP_EOL.' {'.PHP_EOL.' '.$code.PHP_EOL.' }'; } /** - * buildSetUp + * buildSetUp. * - * @param array $options - * @param array $columns - * @param array $relations * @return string */ public function buildSetUp(array $definition) @@ -406,123 +398,122 @@ public function buildSetUp(array $definition) $ret = array(); $i = 0; - if (isset($definition['relations']) && is_array($definition['relations']) && ! empty($definition['relations'])) { + if (isset($definition['relations']) && is_array($definition['relations']) && !empty($definition['relations'])) { foreach ($definition['relations'] as $name => $relation) { - $class = isset($relation['class']) ? $relation['class']:$name; - $alias = (isset($relation['alias']) && $relation['alias'] !== $this->_classPrefix . $relation['class']) ? ' as ' . $relation['alias'] : ''; + $class = isset($relation['class']) ? $relation['class'] : $name; + $alias = (isset($relation['alias']) && $relation['alias'] !== $this->_classPrefix.$relation['class']) ? ' as '.$relation['alias'] : ''; - if ( ! isset($relation['type'])) { + if (!isset($relation['type'])) { $relation['type'] = Doctrine_Relation::ONE; } - if ($relation['type'] === Doctrine_Relation::ONE) { - $ret[$i] = " ".'$this->hasOne(\'' . $class . $alias . '\''; + if (Doctrine_Relation::ONE === $relation['type']) { + $ret[$i] = ' $this->hasOne(\''.$class.$alias.'\''; } else { - $ret[$i] = " ".'$this->hasMany(\'' . $class . $alias . '\''; + $ret[$i] = ' $this->hasMany(\''.$class.$alias.'\''; } $a = array(); if (isset($relation['refClass'])) { - $a[] = '\'refClass\' => ' . $this->varExport($relation['refClass']); + $a[] = '\'refClass\' => '.$this->varExport($relation['refClass']); } if (isset($relation['refClassRelationAlias'])) { - $a[] = '\'refClassRelationAlias\' => ' . $this->varExport($relation['refClassRelationAlias']); + $a[] = '\'refClassRelationAlias\' => '.$this->varExport($relation['refClassRelationAlias']); } if (isset($relation['deferred']) && $relation['deferred']) { - $a[] = '\'default\' => ' . $this->varExport($relation['deferred']); + $a[] = '\'default\' => '.$this->varExport($relation['deferred']); } if (isset($relation['local']) && $relation['local']) { - $a[] = '\'local\' => ' . $this->varExport($relation['local']); + $a[] = '\'local\' => '.$this->varExport($relation['local']); } if (isset($relation['foreign']) && $relation['foreign']) { - $a[] = '\'foreign\' => ' . $this->varExport($relation['foreign']); + $a[] = '\'foreign\' => '.$this->varExport($relation['foreign']); } if (isset($relation['onDelete']) && $relation['onDelete']) { - $a[] = '\'onDelete\' => ' . $this->varExport($relation['onDelete']); + $a[] = '\'onDelete\' => '.$this->varExport($relation['onDelete']); } if (isset($relation['onUpdate']) && $relation['onUpdate']) { - $a[] = '\'onUpdate\' => ' . $this->varExport($relation['onUpdate']); + $a[] = '\'onUpdate\' => '.$this->varExport($relation['onUpdate']); } if (isset($relation['cascade']) && $relation['cascade']) { - $a[] = '\'cascade\' => ' . $this->varExport($relation['cascade']); + $a[] = '\'cascade\' => '.$this->varExport($relation['cascade']); } if (isset($relation['equal']) && $relation['equal']) { - $a[] = '\'equal\' => ' . $this->varExport($relation['equal']); + $a[] = '\'equal\' => '.$this->varExport($relation['equal']); } if (isset($relation['owningSide']) && $relation['owningSide']) { - $a[] = '\'owningSide\' => ' . $this->varExport($relation['owningSide']); + $a[] = '\'owningSide\' => '.$this->varExport($relation['owningSide']); } if (isset($relation['foreignKeyName']) && $relation['foreignKeyName']) { - $a[] = '\'foreignKeyName\' => ' . $this->varExport($relation['foreignKeyName']); + $a[] = '\'foreignKeyName\' => '.$this->varExport($relation['foreignKeyName']); } if (isset($relation['orderBy']) && $relation['orderBy']) { - $a[] = '\'orderBy\' => ' . $this->varExport($relation['orderBy']); + $a[] = '\'orderBy\' => '.$this->varExport($relation['orderBy']); } - if ( ! empty($a)) { - $ret[$i] .= ', ' . 'array(' . PHP_EOL . str_repeat(' ', 13); + if (!empty($a)) { + $ret[$i] .= ', array('.PHP_EOL.str_repeat(' ', 13); $length = strlen($ret[$i]); - $ret[$i] .= implode(',' . PHP_EOL . str_repeat(' ', 13), $a) . ')'; + $ret[$i] .= implode(','.PHP_EOL.str_repeat(' ', 13), $a).')'; } $ret[$i] .= ');'.PHP_EOL; - $i++; + ++$i; } } if (isset($definition['actAs']) && is_array($definition['actAs']) && !empty($definition['actAs'])) { $ret[$i] = $this->buildActAs($definition['actAs']); - $i++; + ++$i; } if (isset($definition['listeners']) && is_array($definition['listeners']) && !empty($definition['listeners'])) { $ret[$i] = $this->buildListeners($definition['listeners']); - $i++; + ++$i; } $code = implode(PHP_EOL, $ret); $code = trim($code); - $code = "parent::setUp();" . PHP_EOL . ' ' . $code; + $code = 'parent::setUp();'.PHP_EOL.' '.$code; // If we have some code for the function then lets define it and return it if ($code) { - return ' public function setUp()' . PHP_EOL . ' {' . PHP_EOL . ' ' . $code . PHP_EOL . ' }'; + return ' public function setUp()'.PHP_EOL.' {'.PHP_EOL.' '.$code.PHP_EOL.' }'; } } /** - * Build php code for record checks + * Build php code for record checks. * * @param array $checks + * * @return string $build */ public function buildChecks($checks) { $build = ''; foreach ($checks as $check) { - $build .= " \$this->check('" . $check . "');" . PHP_EOL; + $build .= " \$this->check('".$check."');".PHP_EOL; } + return $build; } /** - * buildColumns - * - * @param string $array - * @return void + * buildColumns. */ public function buildColumns(array $columns) { @@ -533,34 +524,30 @@ public function buildColumns(array $columns) foreach ($columns as $name => $column) { // An alias cannot passed via column name and column alias definition if (isset($column['name']) && stripos($column['name'], ' as ') && isset($column['alias'])) { - throw new Doctrine_Import_Exception( - sprintf('When using a column alias you cannot pass it via column name and column alias definition (column: %s).', $column['name']) - ); + throw new Doctrine_Import_Exception(sprintf('When using a column alias you cannot pass it via column name and column alias definition (column: %s).', $column['name'])); } // Update column name if an alias is provided if (isset($column['alias']) && !isset($column['name'])) { - $column['name'] = $name . ' as ' . $column['alias']; + $column['name'] = $name.' as '.$column['alias']; } - $columnName = isset($column['name']) ? $column['name']:$name; + $columnName = isset($column['name']) ? $column['name'] : $name; if ($manager->getAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE)) { $e = explode(' as ', $columnName); $fieldName = isset($e[1]) ? $e[1] : $e[0]; $classified = Doctrine_Inflector::classify($fieldName); - $getter = 'get' . $classified; - $setter = 'set' . $classified; + $getter = 'get'.$classified; + $setter = 'set'.$classified; if ($refl->hasMethod($getter) || $refl->hasMethod($setter)) { - throw new Doctrine_Import_Exception( - sprintf('When using the attribute ATTR_AUTO_ACCESSOR_OVERRIDE you cannot use the field name "%s" because it is reserved by Doctrine. You must choose another field name.', $fieldName) - ); + throw new Doctrine_Import_Exception(sprintf('When using the attribute ATTR_AUTO_ACCESSOR_OVERRIDE you cannot use the field name "%s" because it is reserved by Doctrine. You must choose another field name.', $fieldName)); } } - $build .= " ".'$this->hasColumn(\'' . $columnName . '\', \'' . $column['type'] . '\''; + $build .= ' $this->hasColumn(\''.$columnName.'\', \''.$column['type'].'\''; if ($column['length']) { - $build .= ', ' . $column['length']; + $build .= ', '.$column['length']; } else { $build .= ', null'; } @@ -568,19 +555,17 @@ public function buildColumns(array $columns) $options = $column; // Remove name, alltypes, ntype. They are not needed in options array - unset($options['name']); - unset($options['alltypes']); - unset($options['ntype']); + unset($options['name'], $options['alltypes'], $options['ntype']); // Remove notnull => true if the column is primary // Primary columns are implied to be notnull in Doctrine - if (isset($options['primary']) && $options['primary'] == true && (isset($options['notnull']) && $options['notnull'] == true)) { + if (isset($options['primary']) && true == $options['primary'] && (isset($options['notnull']) && true == $options['notnull'])) { unset($options['notnull']); } // Remove default if the value is 0 and the column is a primary key // Doctrine defaults to 0 if it is a primary key - if (isset($options['primary']) && $options['primary'] == true && (isset($options['default']) && $options['default'] == 0)) { + if (isset($options['primary']) && true == $options['primary'] && (isset($options['default']) && 0 == $options['default'])) { unset($options['default']); } @@ -592,10 +577,10 @@ public function buildColumns(array $columns) } if (is_array($options) && !empty($options)) { - $build .= ', ' . $this->varExport($options); + $build .= ', '.$this->varExport($options); } - $build .= ');' . PHP_EOL; + $build .= ');'.PHP_EOL; } return $build; @@ -621,16 +606,16 @@ public function buildAccessors(array $definition) $ret = ''; foreach ($accessors as $name) { // getters - $ret .= PHP_EOL . ' public function get' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . "(\$load = true)" . PHP_EOL; - $ret .= " {" . PHP_EOL; - $ret .= " return \$this->get('{$name}', \$load);" . PHP_EOL; - $ret .= " }" . PHP_EOL; + $ret .= PHP_EOL.' public function get'.Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)).'($load = true)'.PHP_EOL; + $ret .= ' {'.PHP_EOL; + $ret .= " return \$this->get('{$name}', \$load);".PHP_EOL; + $ret .= ' }'.PHP_EOL; // setters - $ret .= PHP_EOL . ' public function set' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . "(\${$name}, \$load = true)" . PHP_EOL; - $ret .= " {" . PHP_EOL; - $ret .= " return \$this->set('{$name}', \${$name}, \$load);" . PHP_EOL; - $ret .= " }" . PHP_EOL; + $ret .= PHP_EOL.' public function set'.Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name))."(\${$name}, \$load = true)".PHP_EOL; + $ret .= ' {'.PHP_EOL; + $ret .= " return \$this->set('{$name}', \${$name}, \$load);".PHP_EOL; + $ret .= ' }'.PHP_EOL; } return $ret; @@ -650,127 +635,107 @@ public function buildPhpDocs(array $definition) $ret[] = ''; $properties = array(); - $getters = array(); - $setters = array(); + $getters = array(); + $setters = array(); - if ((isset($definition['is_base_class']) && $definition['is_base_class']) || ! $this->generateBaseClasses()) { + if ((isset($definition['is_base_class']) && $definition['is_base_class']) || !$this->generateBaseClasses()) { foreach ($definition['columns'] as $name => $column) { - $name = isset($column['name']) ? $column['name']:$name; + $name = isset($column['name']) ? $column['name'] : $name; // extract column name & field name - if (stripos($name, ' as ')) - { + if (stripos($name, ' as ')) { if (strpos($name, ' as')) { $parts = explode(' as ', $name); - } - else - { + } else { $parts = explode(' AS ', $name); } if (count($parts) > 1) { $fieldName = $parts[1]; - } - else - { + } else { $fieldName = $parts[0]; } $name = $parts[0]; - } - else - { + } else { $fieldName = $name; $name = $name; } $phpTypeMap = array( - "enum" => "string", - "datetime" => "string", - "timestamp" => "string", - "clob" => "string", - "date" => "string", - "time" => "string", - "varchar" => "string", - "char" => "string", - "decimal" => "float", - "blob" => "object", - "gzip" => "object", - "bit" => "binary", - "varbit" => "binary", - "inet" => "string", - "boolean" => "bool", - "integer" => "int", - "string" => "string" + 'enum' => 'string', + 'datetime' => 'string', + 'timestamp' => 'string', + 'clob' => 'string', + 'date' => 'string', + 'time' => 'string', + 'varchar' => 'string', + 'char' => 'string', + 'decimal' => 'float', + 'blob' => 'object', + 'gzip' => 'object', + 'bit' => 'binary', + 'varbit' => 'binary', + 'inet' => 'string', + 'boolean' => 'bool', + 'integer' => 'int', + 'string' => 'string', ); /** - * @var double $phpCommentMap; + * @var float $phpCommentMap; */ $phpCommentMap = array( - "time" => "Time in ISO-8601 format (HH:MI:SS)", - "date" => "Date in ISO-8601 format (YYYY-MM-DD)", - "datetime" => "Date and time in ISO-8601 format (YYYY-MM-DD HH:MI)", - "timestamp" => "Timestamp in ISO-8601 format (YYYY-MM-DD HH:MI:SS)", - "gzip" => "A gzipped object", - "object" => "A doctrine serialized object", - "enum" => "Possible values (%s)" + 'time' => 'Time in ISO-8601 format (HH:MI:SS)', + 'date' => 'Date in ISO-8601 format (YYYY-MM-DD)', + 'datetime' => 'Date and time in ISO-8601 format (YYYY-MM-DD HH:MI)', + 'timestamp' => 'Timestamp in ISO-8601 format (YYYY-MM-DD HH:MI:SS)', + 'gzip' => 'A gzipped object', + 'object' => 'A doctrine serialized object', + 'enum' => 'Possible values (%s)', ); - $phpType = $column["type"]; - if (isset($phpTypeMap[$column["type"]])) - { - $phpType = $phpTypeMap[$column["type"]]; + $phpType = $column['type']; + if (isset($phpTypeMap[$column['type']])) { + $phpType = $phpTypeMap[$column['type']]; } $commentOptions = array(); - if (isset($column["length"]) && $column["length"] != null) - { - if (isset($column["fixed"]) && $column["fixed"] == true) - { - $commentOptions[] = sprintf("Type: %s(%s) fixed-size", $column["type"], $column["length"]); - } - else - { - $commentOptions[] = sprintf("Type: %s(%s)", $column["type"], $column["length"]); + if (isset($column['length']) && null != $column['length']) { + if (isset($column['fixed']) && true == $column['fixed']) { + $commentOptions[] = sprintf('Type: %s(%s) fixed-size', $column['type'], $column['length']); + } else { + $commentOptions[] = sprintf('Type: %s(%s)', $column['type'], $column['length']); } - } - else - { - $commentOptions[] = sprintf("Type: %s", $column["type"]); + } else { + $commentOptions[] = sprintf('Type: %s', $column['type']); } - if (isset($column["unique"]) && $column["unique"] == true) - { - $commentOptions[] = sprintf("unique"); + if (isset($column['unique']) && true == $column['unique']) { + $commentOptions[] = sprintf('unique'); } - if (isset($column["primary"]) && $column["primary"] == true) - { - $commentOptions[] = sprintf("primary key"); + if (isset($column['primary']) && true == $column['primary']) { + $commentOptions[] = sprintf('primary key'); } - if (isset($column["notblank"]) && $column["notblank"] == true) - { - $commentOptions[] = "required"; + if (isset($column['notblank']) && true == $column['notblank']) { + $commentOptions[] = 'required'; } - if (isset($column["default"]) && $column["default"] != null) - { - $commentOptions[] = sprintf('default "%s"', $column["default"]); + if (isset($column['default']) && null != $column['default']) { + $commentOptions[] = sprintf('default "%s"', $column['default']); } - if (isset($phpCommentMap[$column["type"]])) { - $comment = $phpCommentMap[$column["type"]]; - if ($column['type'] == "enum") - { - $comment = sprintf($comment, strtoupper(join(", ",$column["values"]))); + if (isset($phpCommentMap[$column['type']])) { + $comment = $phpCommentMap[$column['type']]; + if ('enum' == $column['type']) { + $comment = sprintf($comment, strtoupper(join(', ', $column['values']))); } $commentOptions[] = $comment; } - - $comment = join(", ",$commentOptions); + $comment = join(', ', $commentOptions); $fieldName = trim($fieldName); @@ -779,149 +744,142 @@ public function buildPhpDocs(array $definition) $setters[] = array($definition['topLevelClassName'], Doctrine_Inflector::classify($fieldName), $phpType, $comment); } - - if (isset($definition['relations']) && ! empty($definition['relations'])) { + if (isset($definition['relations']) && !empty($definition['relations'])) { foreach ($definition['relations'] as $relation) { - $type = (isset($relation['type']) && $relation['type'] == Doctrine_Relation::MANY) ? 'Doctrine_Collection' : $this->_classPrefix . $relation['class']; + $type = (isset($relation['type']) && Doctrine_Relation::MANY == $relation['type']) ? 'Doctrine_Collection' : $this->_classPrefix.$relation['class']; if ((isset($relation['type']) ? $relation['type'] : null) == Doctrine_Relation::ONE) { - $properties[] = array($relation['class'], $relation['alias'], ""); - $getters[] = array($relation['class'], $relation['alias'], ""); - $setters[] = array($definition['topLevelClassName'], $relation['alias'], $relation['class'], ""); - } - else - { + $properties[] = array($relation['class'], $relation['alias'], ''); + $getters[] = array($relation['class'], $relation['alias'], ''); + $setters[] = array($definition['topLevelClassName'], $relation['alias'], $relation['class'], ''); + } else { // MANY - $properties[] = array($type . "|". $relation['class'] . "[]", $relation['alias'] , ""); - $getters[] = array($type . "|". $relation['class'] . "[]", $relation['alias'], ""); - $setters[] = array($definition['topLevelClassName'], $relation["alias"], $type, ""); + $properties[] = array($type.'|'.$relation['class'].'[]', $relation['alias'], ''); + $getters[] = array($type.'|'.$relation['class'].'[]', $relation['alias'], ''); + $setters[] = array($definition['topLevelClassName'], $relation['alias'], $type, ''); } } } - $maxTypeSize = 0; $maxNameSize = 0; - foreach ($properties as $propItem) - { + foreach ($properties as $propItem) { $maxTypeSize = max($maxTypeSize, strlen($propItem[0])); - $maxNameSize = max($maxNameSize, strlen($propItem[1])+1); + $maxNameSize = max($maxNameSize, strlen($propItem[1]) + 1); } - foreach ($getters as $getterItem) - { + foreach ($getters as $getterItem) { $maxTypeSize = max($maxTypeSize, strlen($getterItem[0])); - $maxNameSize = max($maxNameSize, strlen($getterItem[1])+5); + $maxNameSize = max($maxNameSize, strlen($getterItem[1]) + 5); } - foreach ($setters as $setterItem) - { + foreach ($setters as $setterItem) { $maxTypeSize = max($maxTypeSize, strlen($setterItem[0])); - $maxNameSize = max($maxNameSize, strlen($setterItem[1])+strlen($setterItem[2])+9); + $maxNameSize = max($maxNameSize, strlen($setterItem[1]) + strlen($setterItem[2]) + 9); } - $maxNameSize+=1; - $maxTypeSize+=1; + ++$maxNameSize; + ++$maxTypeSize; - - foreach ($properties as $propItem) - { - $ret[] = sprintf("@property %s $%s %s", str_pad($propItem[0], $maxTypeSize, " "), str_pad($propItem[1], $maxNameSize-1, " "), $propItem[2]); + foreach ($properties as $propItem) { + $ret[] = sprintf('@property %s $%s %s', str_pad($propItem[0], $maxTypeSize, ' '), str_pad($propItem[1], $maxNameSize - 1, ' '), $propItem[2]); } - $ret[] = " "; + $ret[] = ' '; - foreach ($getters as $getterItem) - { - $methodName = sprintf("get%s()",ucfirst($getterItem[1])); - $ret[] = sprintf("@method %s %s %s", str_pad($getterItem[0], $maxTypeSize+2, " "), str_pad(($methodName), $maxNameSize, " "), $getterItem[2]); + foreach ($getters as $getterItem) { + $methodName = sprintf('get%s()', ucfirst($getterItem[1])); + $ret[] = sprintf('@method %s %s %s', str_pad($getterItem[0], $maxTypeSize + 2, ' '), str_pad($methodName, $maxNameSize, ' '), $getterItem[2]); } - $ret[] = " "; + $ret[] = ' '; - foreach ($setters as $setterItem) - { - $methodName = sprintf('set%s(%s $val)',ucfirst($setterItem[1]), $setterItem[2]); - $ret[] = sprintf("@method %s %s %s", str_pad($setterItem[0], $maxTypeSize+2, " "), str_pad(($methodName), $maxNameSize, " "), $setterItem[3]); + foreach ($setters as $setterItem) { + $methodName = sprintf('set%s(%s $val)', ucfirst($setterItem[1]), $setterItem[2]); + $ret[] = sprintf('@method %s %s %s', str_pad($setterItem[0], $maxTypeSize + 2, ' '), str_pad($methodName, $maxNameSize, ' '), $setterItem[3]); } - //$ret = array_merge($ret, $getter, $setter); + // $ret = array_merge($ret, $getter, $setter); } - $ret[] = " "; + $ret[] = ' '; - $ret[] = '@package ' . $this->_phpDocPackage; - $ret[] = '@subpackage ' . $this->_phpDocSubpackage; - $ret[] = '@author ' . $this->_phpDocName . ' <' . $this->_phpDocEmail . '>'; + $ret[] = '@package '.$this->_phpDocPackage; + $ret[] = '@subpackage '.$this->_phpDocSubpackage; + $ret[] = '@author '.$this->_phpDocName.' <'.$this->_phpDocEmail.'>'; $ret[] = '@version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $'; - $ret = ' * ' . implode(PHP_EOL . ' * ', $ret); - $ret = ' ' . trim($ret); + $ret = ' * '.implode(PHP_EOL.' * ', $ret); - return $ret; + return ' '.trim($ret); } /** - * emit a behavior assign + * emit a behavior assign. * - * @param int $level + * @param int $level * @param string $name * @param string $option + * * @return string assignation code */ private function emitAssign($level, $name, $option) { // find class matching $name $classname = $name; - if (class_exists("Doctrine_Template_$name", true)) { - $classname = "Doctrine_Template_$name"; + if (class_exists("Doctrine_Template_{$name}", true)) { + $classname = "Doctrine_Template_{$name}"; } - return " \$" . strtolower($name) . "$level = new $classname($option);". PHP_EOL; + + return ' $'.strtolower($name)."{$level} = new {$classname}({$option});".PHP_EOL; } /** - * emit an addChild + * emit an addChild. * - * @param int $level + * @param int $level * @param string $name - * @param string $option + * * @return string addChild code */ private function emitAddChild($level, $parent, $name) { - return " \$" . strtolower($parent) . ($level - 1) . "->addChild(\$" . strtolower($name) . "$level);" . PHP_EOL; + return ' $'.strtolower($parent).($level - 1).'->addChild($'.strtolower($name)."{$level});".PHP_EOL; } /** - * emit an indented actAs + * emit an indented actAs. * - * @param int $level + * @param int $level * @param string $name - * @param string $option + * * @return string actAs code */ private function emitActAs($level, $name) { - return " \$this->actAs(\$" . strtolower($name) . "$level);" . PHP_EOL; + return ' $this->actAs($'.strtolower($name)."{$level});".PHP_EOL; } /** - * buildActAs: builds a complete actAs code. It supports hierarchy of plugins + * buildActAs: builds a complete actAs code. It supports hierarchy of plugins. + * * @param array $actAs array of plugin definitions and options */ public function buildActAs($actAs) { $emittedActAs = array(); $build = $this->innerBuildActAs($actAs, 0, null, $emittedActAs); - foreach($emittedActAs as $str) { + foreach ($emittedActAs as $str) { $build .= $str; } + return $build; } /** - * innerBuildActAs: build a complete actAs code that handles hierarchy of plugins + * innerBuildActAs: build a complete actAs code that handles hierarchy of plugins. * - * @param array $actAs array of plugin definitions and options - * @param int $level current indentation level - * @param string $parent name of the parent template/plugin + * @param array $actAs array of plugin definitions and options + * @param int $level current indentation level + * @param string $parent name of the parent template/plugin * @param array $emittedActAs contains on output an array of actAs command to be appended to output + * * @return string actAs full definition */ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emittedActAs = array()) @@ -931,7 +889,7 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi $tmp = array(); foreach ($actAs as $key => $value) { if (is_numeric($key)) { - $tmp[(string)$value] = null; + $tmp[(string) $value] = null; } else { $tmp[$key] = $value; } @@ -942,16 +900,16 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi $build = ''; $currentParent = $parent; if (is_array($actAs)) { - foreach($actAs as $template => $options) { - if ($template == 'actAs') { + foreach ($actAs as $template => $options) { + if ('actAs' == $template) { // found another actAs $build .= $this->innerBuildActAs($options, $level + 1, $parent, $emittedActAs); - } else if (is_array($options)) { + } elseif (is_array($options)) { // remove actAs from options $realOptions = array(); $leftActAs = array(); - foreach($options as $name => $value) { - if ($name != 'actAs') { + foreach ($options as $name => $value) { + if ('actAs' != $name) { $realOptions[$name] = $options[$name]; } else { $leftActAs[$name] = $options[$name]; @@ -960,7 +918,7 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi $optionPHP = $this->varExport($realOptions); $build .= $this->emitAssign($level, $template, $optionPHP); - if ($level == 0) { + if (0 == $level) { $emittedActAs[] = $this->emitActAs($level, $template); } else { $build .= $this->emitAddChild($level, $currentParent, $template); @@ -970,7 +928,7 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi $build .= $this->innerBuildActAs($leftActAs, $level, $template, $emittedActAs); } else { $build .= $this->emitAssign($level, $template, null); - if ($level == 0) { + if (0 == $level) { $emittedActAs[] = $this->emitActAs($level, $template); } else { $build .= $this->emitAddChild($level, $currentParent, $template); @@ -980,7 +938,7 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi } } else { $build .= $this->emitAssign($level, $actAs, null); - if ($level == 0) { + if (0 == $level) { $emittedActAs[] = $this->emitActAs($level, $actAs); } else { $build .= $this->emitAddChild($level, $currentParent, $actAs); @@ -991,97 +949,87 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi } /** - * Build php code for adding record listeners + * Build php code for adding record listeners. * * @param string $listeners + * * @return string $build */ public function buildListeners($listeners) { $build = ''; - foreach($listeners as $name => $options) { - if ( ! is_array($options) && $options !== null) { + foreach ($listeners as $name => $options) { + if (!is_array($options) && null !== $options) { $name = $options; $options = null; } - $useOptions = ( ! empty($options) && isset($options['useOptions']) && $options['useOptions'] == true) + $useOptions = (!empty($options) && isset($options['useOptions']) && true == $options['useOptions']) ? '$this->getTable()->getOptions()' : 'array()'; - $class = ( ! empty($options) && isset($options['class'])) ? $options['class'] : $name; + $class = (!empty($options) && isset($options['class'])) ? $options['class'] : $name; - $build .= " \$this->addListener(new " . $class . "(" . $useOptions . "), '" . $name . "');" . PHP_EOL; + $build .= ' $this->addListener(new '.$class.'('.$useOptions."), '".$name."');".PHP_EOL; } return $build; } /** - * buildAttributes - * - * @param string $array - * @return void + * buildAttributes. */ public function buildAttributes(array $attributes) { $build = PHP_EOL; foreach ($attributes as $key => $value) { - $values = array(); - if (is_bool($value)) - { - $values[] = $value ? 'true':'false'; + if (is_bool($value)) { + $values[] = $value ? 'true' : 'false'; } else { - if ( ! is_array($value)) { + if (!is_array($value)) { $value = array($value); } foreach ($value as $attr) { - $const = "Doctrine_Core::" . strtoupper($key) . "_" . strtoupper($attr); + $const = 'Doctrine_Core::'.strtoupper($key).'_'.strtoupper($attr); if (defined($const)) { $values[] = $const; } else { - $values[] = "'" . $attr . "'"; + $values[] = "'".$attr."'"; } } } $string = implode(' ^ ', $values); - $build .= " \$this->setAttribute(Doctrine_Core::ATTR_" . strtoupper($key) . ", " . $string . ");" . PHP_EOL; + $build .= ' $this->setAttribute(Doctrine_Core::ATTR_'.strtoupper($key).', '.$string.');'.PHP_EOL; } return $build; } /** - * buildTableOptions - * - * @param string $array - * @return void + * buildTableOptions. */ public function buildOptions(array $options) { $build = ''; foreach ($options as $name => $value) { - $build .= " \$this->option('$name', " . $this->varExport($value) . ");" . PHP_EOL; + $build .= " \$this->option('{$name}', ".$this->varExport($value).');'.PHP_EOL; } return $build; } /** - * buildIndexes - * - * @param string $array - * @return void + * buildIndexes. */ public function buildIndexes(array $indexes) { $build = ''; foreach ($indexes as $indexName => $definitions) { - $build .= PHP_EOL . " \$this->index('" . $indexName . "'"; - $build .= ', ' . $this->varExport($definitions); + $build .= PHP_EOL." \$this->index('".$indexName."'"; + $build .= ', '.$this->varExport($definitions); $build .= ');'; } @@ -1089,40 +1037,39 @@ public function buildIndexes(array $indexes) } /** - * buildToString + * buildToString. * - * @param array $definition * @return string */ public function buildToString(array $definition) { - if ( empty($definition['toString'])) { + if (empty($definition['toString'])) { return ''; } - $ret = PHP_EOL . PHP_EOL . ' public function __toString()' . PHP_EOL; - $ret .= " {" . PHP_EOL; - $ret .= " return (string) \$this->".$definition['toString'].";" . PHP_EOL; - $ret .= " }"; + $ret = PHP_EOL.PHP_EOL.' public function __toString()'.PHP_EOL; + $ret .= ' {'.PHP_EOL; + $ret .= ' return (string) $this->'.$definition['toString'].';'.PHP_EOL; + $ret .= ' }'; + return $ret; } /** - * buildDefinition + * buildDefinition. * - * @param array $definition * @return string */ public function buildDefinition(array $definition) { - if ( ! isset($definition['className'])) { + if (!isset($definition['className'])) { throw new Doctrine_Import_Builder_Exception('Missing class name.'); } - $abstract = isset($definition['abstract']) && $definition['abstract'] === true ? 'abstract ':null; + $abstract = isset($definition['abstract']) && true === $definition['abstract'] ? 'abstract ' : null; $className = $definition['className']; - $extends = isset($definition['inheritance']['extends']) ? $definition['inheritance']['extends']:$this->_baseClassName; + $extends = isset($definition['inheritance']['extends']) ? $definition['inheritance']['extends'] : $this->_baseClassName; - if ( ! (isset($definition['no_definition']) && $definition['no_definition'] === true)) { + if (!(isset($definition['no_definition']) && true === $definition['no_definition'])) { $tableDefinitionCode = $this->buildTableDefinition($definition); $setUpCode = $this->buildSetUp($definition); } else { @@ -1131,50 +1078,41 @@ public function buildDefinition(array $definition) } if ($tableDefinitionCode && $setUpCode) { - $setUpCode = PHP_EOL . $setUpCode; + $setUpCode = PHP_EOL.$setUpCode; } - $setUpCode.= $this->buildToString($definition); + $setUpCode .= $this->buildToString($definition); - $docs = PHP_EOL . $this->buildPhpDocs($definition); + $docs = PHP_EOL.$this->buildPhpDocs($definition); - $content = sprintf(self::$_tpl, $docs, $abstract, + return sprintf(self::$_tpl, $docs, $abstract, $className, $extends, $tableDefinitionCode, $setUpCode); - - return $content; } /** - * buildRecord + * buildRecord. * - * @param array $options - * @param array $columns - * @param array $relations - * @param array $indexes - * @param array $attributes - * @param array $templates - * @param array $actAs * @return void= */ public function buildRecord(array $definition) { - if ( ! isset($definition['className'])) { + if (!isset($definition['className'])) { throw new Doctrine_Import_Builder_Exception('Missing class name.'); } $definition['topLevelClassName'] = $definition['className']; if ($this->generateBaseClasses()) { - $definition['is_package'] = (isset($definition['package']) && $definition['package']) ? true:false; + $definition['is_package'] = (isset($definition['package']) && $definition['package']) ? true : false; if ($definition['is_package']) { $e = explode('.', trim($definition['package'])); $definition['package_name'] = $e[0]; - $definition['package_path'] = ! empty($e) ? implode(DIRECTORY_SEPARATOR, $e):$definition['package_name']; + $definition['package_path'] = !empty($e) ? implode(DIRECTORY_SEPARATOR, $e) : $definition['package_name']; } // Top level definition that extends from all the others $topLevel = $definition; @@ -1182,7 +1120,7 @@ public function buildRecord(array $definition) // If we have a package then we need to make this extend the package definition and not the base definition // The package definition will then extends the base definition - $topLevel['inheritance']['extends'] = (isset($topLevel['package']) && $topLevel['package']) ? $this->_packagesPrefix . $topLevel['className']:$this->_baseClassPrefix . $topLevel['className']; + $topLevel['inheritance']['extends'] = (isset($topLevel['package']) && $topLevel['package']) ? $this->_packagesPrefix.$topLevel['className'] : $this->_baseClassPrefix.$topLevel['className']; $topLevel['no_definition'] = true; $topLevel['generate_once'] = true; $topLevel['is_main_class'] = true; @@ -1190,10 +1128,9 @@ public function buildRecord(array $definition) // Package level definition that extends from the base definition if (isset($definition['package'])) { - $packageLevel = $definition; $packageLevel['className'] = $topLevel['inheritance']['extends']; - $packageLevel['inheritance']['extends'] = $this->_baseClassPrefix . $topLevel['className']; + $packageLevel['inheritance']['extends'] = $this->_baseClassPrefix.$topLevel['className']; $packageLevel['no_definition'] = true; $packageLevel['abstract'] = true; $packageLevel['override_parent'] = true; @@ -1202,13 +1139,13 @@ public function buildRecord(array $definition) unset($packageLevel['connection']); $packageLevel['tableClassName'] = sprintf($this->_tableClassFormat, $packageLevel['className']); - $packageLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? sprintf($this->_tableClassFormat, $definition['inheritance']['extends']):$this->_baseTableClassName; + $packageLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? sprintf($this->_tableClassFormat, $definition['inheritance']['extends']) : $this->_baseTableClassName; $topLevel['tableClassName'] = sprintf($this->_tableClassFormat, $topLevel['topLevelClassName']); $topLevel['inheritance']['tableExtends'] = sprintf($this->_tableClassFormat, $packageLevel['className']); } else { $topLevel['tableClassName'] = sprintf($this->_tableClassFormat, $topLevel['className']); - $topLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? sprintf($this->_tableClassFormat, $definition['inheritance']['extends']):$this->_baseTableClassName; + $topLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? sprintf($this->_tableClassFormat, $definition['inheritance']['extends']) : $this->_baseTableClassName; } $baseClass = $definition; @@ -1219,7 +1156,7 @@ public function buildRecord(array $definition) $this->writeDefinition($baseClass); - if ( ! empty($packageLevel)) { + if (!empty($packageLevel)) { $this->writeDefinition($packageLevel); } @@ -1231,14 +1168,14 @@ public function buildRecord(array $definition) protected function _getBaseClassName($className) { - return $this->_baseClassPrefix . $className; + return $this->_baseClassPrefix.$className; } public function buildTableClassDefinition($className, $definition, $options = array()) { - $extends = isset($options['extends']) ? $options['extends']:$this->_baseTableClassName; + $extends = isset($options['extends']) ? $options['extends'] : $this->_baseTableClassName; if ($extends !== $this->_baseTableClassName) { - $extends = $this->_classPrefix . $extends; + $extends = $this->_classPrefix.$extends; } $code = sprintf(" /** @@ -1255,9 +1192,9 @@ public static function getInstance() $docBlock[] = $className; $docBlock[] = ''; $docBlock[] = 'This class has been auto-generated by the Doctrine ORM Framework'; - $docBlock = PHP_EOL.' * ' . implode(PHP_EOL . ' * ', $docBlock); + $docBlock = PHP_EOL.' * '.implode(PHP_EOL.' * ', $docBlock); - $content = '_classPrefix) { - $className = $prefix . $definition['tableClassName']; + $className = $prefix.$definition['tableClassName']; if ($this->_classPrefixFiles) { - $fileName = $className . $this->_suffix; + $fileName = $className.$this->_suffix; } else { - $fileName = $definition['tableClassName'] . $this->_suffix; + $fileName = $definition['tableClassName'].$this->_suffix; } - $writePath = $path . DIRECTORY_SEPARATOR . $fileName; + $writePath = $path.DIRECTORY_SEPARATOR.$fileName; } else { $className = $definition['tableClassName']; - $fileName = $className . $this->_suffix; + $fileName = $className.$this->_suffix; } if ($this->_pearStyle) { - $writePath = $path . DIRECTORY_SEPARATOR . str_replace('_', '/', $fileName); + $writePath = $path.DIRECTORY_SEPARATOR.str_replace('_', '/', $fileName); } else { - $writePath = $path . DIRECTORY_SEPARATOR . $fileName; + $writePath = $path.DIRECTORY_SEPARATOR.$fileName; } $content = $this->buildTableClassDefinition($className, $definition, $options); @@ -1307,7 +1242,7 @@ public function writeTableClassDefinition(array $definition, $path, $options = a Doctrine_Core::loadModel($className, $writePath); - if ( ! file_exists($writePath)) { + if (!file_exists($writePath)) { file_put_contents($writePath, $content); } } @@ -1316,15 +1251,16 @@ public function writeTableClassDefinition(array $definition, $path, $options = a * Return the file name of the class to be generated. * * @param string $originalClassName - * @param array $definition + * @param array $definition + * * @return string */ protected function _getFileName($originalClassName, $definition) { if ($this->_classPrefixFiles) { - $fileName = $definition['className'] . $this->_suffix; + $fileName = $definition['className'].$this->_suffix; } else { - $fileName = $originalClassName . $this->_suffix; + $fileName = $originalClassName.$this->_suffix; } if ($this->_pearStyle) { @@ -1335,49 +1271,40 @@ protected function _getFileName($originalClassName, $definition) } /** - * writeDefinition - * - * @param array $options - * @param array $columns - * @param array $relations - * @param array $indexes - * @param array $attributes - * @param array $templates - * @param array $actAs - * @return void + * writeDefinition. */ public function writeDefinition(array $definition) { $originalClassName = $definition['className']; if ($prefix = $this->_classPrefix) { - $definition['className'] = $prefix . $definition['className']; + $definition['className'] = $prefix.$definition['className']; if (isset($definition['connectionClassName'])) { - $definition['connectionClassName'] = $prefix . $definition['connectionClassName']; + $definition['connectionClassName'] = $prefix.$definition['connectionClassName']; } - $definition['topLevelClassName'] = $prefix . $definition['topLevelClassName']; + $definition['topLevelClassName'] = $prefix.$definition['topLevelClassName']; if (isset($definition['inheritance']['extends'])) { - $definition['inheritance']['extends'] = $prefix . $definition['inheritance']['extends']; + $definition['inheritance']['extends'] = $prefix.$definition['inheritance']['extends']; } } $definitionCode = $this->buildDefinition($definition); if ($prefix) { - $definitionCode = str_replace("this->hasOne('", "this->hasOne('$prefix", $definitionCode); - $definitionCode = str_replace("this->hasMany('", "this->hasMany('$prefix", $definitionCode); - $definitionCode = str_replace("'refClass' => '", "'refClass' => '$prefix", $definitionCode); + $definitionCode = str_replace("this->hasOne('", "this->hasOne('{$prefix}", $definitionCode); + $definitionCode = str_replace("this->hasMany('", "this->hasMany('{$prefix}", $definitionCode); + $definitionCode = str_replace("'refClass' => '", "'refClass' => '{$prefix}", $definitionCode); } $fileName = $this->_getFileName($originalClassName, $definition); - $packagesPath = $this->_packagesPath ? $this->_packagesPath:$this->_path; + $packagesPath = $this->_packagesPath ? $this->_packagesPath : $this->_path; // If this is a main class that either extends from Base or Package class if (isset($definition['is_main_class']) && $definition['is_main_class']) { // If is package then we need to put it in a package subfolder if (isset($definition['is_package']) && $definition['is_package']) { - $writePath = $this->_path . DIRECTORY_SEPARATOR . $definition['package_name']; - // Otherwise lets just put it in the root of the path + $writePath = $this->_path.DIRECTORY_SEPARATOR.$definition['package_name']; + // Otherwise lets just put it in the root of the path } else { $writePath = $this->_path; } @@ -1387,11 +1314,11 @@ public function writeDefinition(array $definition) } } // If is the package class then we need to make the path to the complete package - else if (isset($definition['is_package_class']) && $definition['is_package_class']) { + elseif (isset($definition['is_package_class']) && $definition['is_package_class']) { if (isset($definition['package_custom_path'])) { $writePath = $definition['package_custom_path']; } else { - $writePath = $packagesPath . DIRECTORY_SEPARATOR . $definition['package_path']; + $writePath = $packagesPath.DIRECTORY_SEPARATOR.$definition['package_path']; } if ($this->generateTableClasses()) { @@ -1399,14 +1326,14 @@ public function writeDefinition(array $definition) } } // If it is the base class of the doctrine record definition - else if (isset($definition['is_base_class']) && $definition['is_base_class']) { + elseif (isset($definition['is_base_class']) && $definition['is_base_class']) { // If it is a part of a package then we need to put it in a package subfolder if (isset($definition['is_package']) && $definition['is_package']) { - $basePath = $this->_path . DIRECTORY_SEPARATOR . $definition['package_name']; - $writePath = $basePath . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory; - // Otherwise lets just put it in the root generated folder + $basePath = $this->_path.DIRECTORY_SEPARATOR.$definition['package_name']; + $writePath = $basePath.DIRECTORY_SEPARATOR.$this->_baseClassesDirectory; + // Otherwise lets just put it in the root generated folder } else { - $writePath = $this->_path . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory; + $writePath = $this->_path.DIRECTORY_SEPARATOR.$this->_baseClassesDirectory; } } @@ -1414,22 +1341,22 @@ public function writeDefinition(array $definition) if (isset($writePath)) { Doctrine_Lib::makeDirectories($writePath); - $writePath .= DIRECTORY_SEPARATOR . $fileName; - // Otherwise none of the conditions were met and we aren't generating base classes + $writePath .= DIRECTORY_SEPARATOR.$fileName; + // Otherwise none of the conditions were met and we aren't generating base classes } else { Doctrine_Lib::makeDirectories($this->_path); - $writePath = $this->_path . DIRECTORY_SEPARATOR . $fileName; + $writePath = $this->_path.DIRECTORY_SEPARATOR.$fileName; } - $code = "bindComponent('" . $definition['connectionClassName'] . "', '" . $definition['connection'] . "');" . PHP_EOL; + $code .= '// Connection Component Binding'.PHP_EOL; + $code .= "Doctrine_Manager::getInstance()->bindComponent('".$definition['connectionClassName']."', '".$definition['connection']."');".PHP_EOL; } - $code .= PHP_EOL . $definitionCode; + $code .= PHP_EOL.$definitionCode; if ($this->_eolStyle) { $code = str_replace(PHP_EOL, $this->_eolStyle, $code); @@ -1437,16 +1364,16 @@ public function writeDefinition(array $definition) Doctrine_Lib::makeDirectories(dirname($writePath)); - if (isset($definition['generate_once']) && $definition['generate_once'] === true) { - if ( ! file_exists($writePath)) { + if (isset($definition['generate_once']) && true === $definition['generate_once']) { + if (!file_exists($writePath)) { $bytes = file_put_contents($writePath, $code); } } else { $bytes = file_put_contents($writePath, $code); } - if (isset($bytes) && $bytes === false) { - throw new Doctrine_Import_Builder_Exception("Couldn't write file " . $writePath); + if (isset($bytes) && false === $bytes) { + throw new Doctrine_Import_Builder_Exception("Couldn't write file ".$writePath); } Doctrine_Core::loadModel($definition['className'], $writePath); diff --git a/lib/Doctrine/Import/Builder/Exception.php b/lib/Doctrine/Import/Builder/Exception.php index b754732e4..23bffc5ae 100644 --- a/lib/Doctrine/Import/Builder/Exception.php +++ b/lib/Doctrine/Import/Builder/Exception.php @@ -20,15 +20,18 @@ */ /** - * Doctrine_Import_Builder_Exception + * Doctrine_Import_Builder_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Import_Builder_Exception extends Doctrine_Import_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Import/Exception.php b/lib/Doctrine/Import/Exception.php index 92640bbc2..13f697844 100644 --- a/lib/Doctrine/Import/Exception.php +++ b/lib/Doctrine/Import/Exception.php @@ -20,15 +20,18 @@ */ /** - * class Doctrine_Import_Exception + * class Doctrine_Import_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Import_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Import/Mssql.php b/lib/Doctrine/Import/Mssql.php index 2e1c63de0..2b0776aa4 100644 --- a/lib/Doctrine/Import/Mssql.php +++ b/lib/Doctrine/Import/Mssql.php @@ -20,23 +20,24 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @author Frank M. Kromann (PEAR MDB2 Mssql driver) * @author David Coallier (PEAR MDB2 Mssql driver) + * * @version $Revision: 7675 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Mssql extends Doctrine_Import { /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) @@ -48,9 +49,9 @@ public function listSequences($database = null) } /** - * lists table relations + * lists table relations. * - * Expects an array of this format to be returned with all the relationships in it where the key is + * Expects an array of this format to be returned with all the relationships in it where the key is * the name of the foreign table, and the value is an array containing the local and foreign column * name * @@ -63,41 +64,41 @@ public function listSequences($database = null) * ) * ) * - * @param string $table database table name * @return array */ public function listTableRelations($tableName) { $relations = array(); - $sql = 'SELECT o1.name as table_name, c1.name as column_name, o2.name as referenced_table_name, c2.name as referenced_column_name, s.name as constraint_name FROM sysforeignkeys fk inner join sysobjects o1 on fk.fkeyid = o1.id inner join sysobjects o2 on fk.rkeyid = o2.id inner join syscolumns c1 on c1.id = o1.id and c1.colid = fk.fkey inner join syscolumns c2 on c2.id = o2.id and c2.colid = fk.rkey inner join sysobjects s on fk.constid = s.id AND o1.name = \'' . $tableName . '\''; + $sql = 'SELECT o1.name as table_name, c1.name as column_name, o2.name as referenced_table_name, c2.name as referenced_column_name, s.name as constraint_name FROM sysforeignkeys fk inner join sysobjects o1 on fk.fkeyid = o1.id inner join sysobjects o2 on fk.rkeyid = o2.id inner join syscolumns c1 on c1.id = o1.id and c1.colid = fk.fkey inner join syscolumns c2 on c2.id = o2.id and c2.colid = fk.rkey inner join sysobjects s on fk.constid = s.id AND o1.name = \''.$tableName.'\''; $results = $this->conn->fetchAssoc($sql); - foreach ($results as $result) - { + foreach ($results as $result) { $result = array_change_key_case($result, CASE_LOWER); - $relations[] = array('table' => $result['referenced_table_name'], - 'local' => $result['column_name'], - 'foreign' => $result['referenced_column_name']); + $relations[] = array('table' => $result['referenced_table_name'], + 'local' => $result['column_name'], + 'foreign' => $result['referenced_column_name']); } + return $relations; } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - $sql = 'EXEC sp_primary_keys_rowset @table_name = ' . $this->conn->quoteIdentifier($table, true); + $sql = 'EXEC sp_primary_keys_rowset @table_name = '.$this->conn->quoteIdentifier($table, true); $result = $this->conn->fetchAssoc($sql); $primary = array(); foreach ($result as $key => $val) { $primary[] = $val['COLUMN_NAME']; } - $sql = 'EXEC sp_columns @table_name = ' . $this->conn->quoteIdentifier($table, true); - $result = $this->conn->fetchAssoc($sql); + $sql = 'EXEC sp_columns @table_name = '.$this->conn->quoteIdentifier($table, true); + $result = $this->conn->fetchAssoc($sql); $columns = array(); foreach ($result as $key => $val) { @@ -110,29 +111,29 @@ public function listTableColumns($table) $identity = ''; } - if ($type == 'varchar') { - $type .= '(' . $val['length'] . ')'; + if ('varchar' == $type) { + $type .= '('.$val['length'].')'; } $val['type'] = $type; $val['identity'] = $identity; $decl = $this->conn->dataDict->getPortableDeclaration($val); - $isIdentity = (bool) (strtoupper(trim($identity)) == 'IDENTITY'); - $isNullable = (bool) (strtoupper(trim($val['is_nullable'])) == 'NO'); + $isIdentity = (bool) ('IDENTITY' == strtoupper(trim($identity))); + $isNullable = (bool) ('NO' == strtoupper(trim($val['is_nullable']))); $isPrimary = in_array($val['column_name'], $primary); - $description = array( - 'name' => $val['column_name'], - 'ntype' => $type, - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'length' => $decl['length'], - 'fixed' => (bool) $decl['fixed'], - 'unsigned' => (bool) $decl['unsigned'], - 'notnull' => $isIdentity ? true : $isNullable, - 'default' => $val['column_def'], - 'primary' => $isPrimary, + $description = array( + 'name' => $val['column_name'], + 'ntype' => $type, + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'length' => $decl['length'], + 'fixed' => (bool) $decl['fixed'], + 'unsigned' => (bool) $decl['unsigned'], + 'notnull' => $isIdentity ? true : $isNullable, + 'default' => $val['column_def'], + 'primary' => $isPrimary, 'autoincrement' => $isIdentity, ); @@ -143,20 +144,21 @@ public function listTableColumns($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) { - } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) @@ -167,7 +169,9 @@ public function listTables($database = null) } /** - * lists all triggers + * lists all triggers. + * + * @param mixed|null $database * * @return array */ @@ -175,31 +179,29 @@ public function listTriggers($database = null) { $query = "SELECT name FROM sysobjects WHERE xtype = 'TR'"; - $result = $this->conn->fetchColumn($query); - - return $result; + return $this->conn->fetchColumn($query); } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) { $table = $this->conn->quote($table, 'text'); - $query = "SELECT name FROM sysobjects WHERE xtype = 'TR' AND object_name(parent_obj) = " . $this->conn->quoteIdentifier($table, true); - - $result = $this->conn->fetchColumn($query); + $query = "SELECT name FROM sysobjects WHERE xtype = 'TR' AND object_name(parent_obj) = ".$this->conn->quoteIdentifier($table, true); - return $result; + return $this->conn->fetchColumn($query); } /** - * lists table views + * lists table views. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) @@ -207,25 +209,25 @@ public function listTableViews($table) $keyName = 'INDEX_NAME'; $pkName = 'PK_NAME'; if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) == CASE_LOWER) { + if (CASE_LOWER == $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE)) { $keyName = strtolower($keyName); - $pkName = strtolower($pkName); + $pkName = strtolower($pkName); } else { $keyName = strtoupper($keyName); - $pkName = strtoupper($pkName); + $pkName = strtoupper($pkName); } } $table = $this->conn->quote($table, 'text'); - $query = 'EXEC sp_statistics @table_name = ' . $this->conn->quoteIdentifier($table, true); + $query = 'EXEC sp_statistics @table_name = '.$this->conn->quoteIdentifier($table, true); $indexes = $this->conn->fetchColumn($query, $keyName); - $query = 'EXEC sp_pkeys @table_name = ' . $this->conn->quoteIdentifier($table, true); + $query = 'EXEC sp_pkeys @table_name = '.$this->conn->quoteIdentifier($table, true); $pkAll = $this->conn->fetchColumn($query, $pkName); $result = array(); foreach ($indexes as $index) { - if ( ! in_array($index, $pkAll) && $index != null) { + if (!in_array($index, $pkAll) && null != $index) { $result[] = $this->conn->formatter->fixIndexName($index); } } @@ -234,9 +236,10 @@ public function listTableViews($table) } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) @@ -245,4 +248,4 @@ public function listViews($database = null) return $this->conn->fetchColumn($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Mysql.php b/lib/Doctrine/Import/Mysql.php index da3244ebc..cfe2accde 100644 --- a/lib/Doctrine/Import/Mysql.php +++ b/lib/Doctrine/Import/Mysql.php @@ -20,37 +20,38 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7644 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Mysql extends Doctrine_Import { - protected $sql = array( - 'listDatabases' => 'SHOW DATABASES', - 'listTableFields' => 'DESCRIBE %s', - 'listSequences' => 'SHOW TABLES', - 'listTables' => 'SHOW TABLES', - 'listUsers' => 'SELECT DISTINCT USER FROM USER', - 'listViews' => "SHOW FULL TABLES %s WHERE Table_type = 'VIEW'", - ); + protected $sql = array( + 'listDatabases' => 'SHOW DATABASES', + 'listTableFields' => 'DESCRIBE %s', + 'listSequences' => 'SHOW TABLES', + 'listTables' => 'SHOW TABLES', + 'listUsers' => 'SELECT DISTINCT USER FROM USER', + 'listViews' => "SHOW FULL TABLES %s WHERE Table_type = 'VIEW'", + ); /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) { $query = 'SHOW TABLES'; - if ( ! is_null($database)) { - $query .= ' FROM ' . $database; + if (!is_null($database)) { + $query .= ' FROM '.$database; } $tableNames = $this->conn->fetchColumn($query); @@ -58,9 +59,10 @@ public function listSequences($database = null) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) @@ -68,7 +70,7 @@ public function listTableConstraints($table) $keyName = 'Key_name'; $nonUnique = 'Non_unique'; if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) == CASE_LOWER) { + if (CASE_LOWER == $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE)) { $keyName = strtolower($keyName); $nonUnique = strtolower($nonUnique); } else { @@ -78,29 +80,30 @@ public function listTableConstraints($table) } $table = $this->conn->quoteIdentifier($table, true); - $query = 'SHOW INDEX FROM ' . $table; + $query = 'SHOW INDEX FROM '.$table; $indexes = $this->conn->fetchAssoc($query); $result = array(); foreach ($indexes as $indexData) { - if ( ! $indexData[$nonUnique]) { - if ($indexData[$keyName] !== 'PRIMARY') { + if (!$indexData[$nonUnique]) { + if ('PRIMARY' !== $indexData[$keyName]) { $index = $this->conn->formatter->fixIndexName($indexData[$keyName]); } else { $index = 'PRIMARY'; } - if ( ! empty($index)) { + if (!empty($index)) { $result[] = $index; } } } + return $result; } /** - * lists table relations + * lists table relations. * - * Expects an array of this format to be returned with all the relationships in it where the key is + * Expects an array of this format to be returned with all the relationships in it where the key is * the name of the foreign table, and the value is an array containing the local and foreign column * name * @@ -113,60 +116,59 @@ public function listTableConstraints($table) * ) * ) * - * @param string $table database table name * @return array */ public function listTableRelations($tableName) { $relations = array(); - $sql = "SELECT column_name, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.key_column_usage WHERE table_name = '" . $tableName . "' AND table_schema = '" . $this->conn->getDatabaseName() . "' and REFERENCED_COLUMN_NAME is not NULL"; + $sql = "SELECT column_name, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.key_column_usage WHERE table_name = '".$tableName."' AND table_schema = '".$this->conn->getDatabaseName()."' and REFERENCED_COLUMN_NAME is not NULL"; $results = $this->conn->fetchAssoc($sql); - foreach ($results as $result) - { + foreach ($results as $result) { $result = array_change_key_case($result, CASE_LOWER); - $relations[] = array('table' => $result['referenced_table_name'], - 'local' => $result['column_name'], - 'foreign' => $result['referenced_column_name']); + $relations[] = array('table' => $result['referenced_table_name'], + 'local' => $result['column_name'], + 'foreign' => $result['referenced_column_name']); } + return $relations; } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - $sql = 'DESCRIBE ' . $this->conn->quoteIdentifier($table, true); + $sql = 'DESCRIBE '.$this->conn->quoteIdentifier($table, true); $result = $this->conn->fetchAssoc($sql); $description = array(); $columns = array(); foreach ($result as $key => $val) { - $val = array_change_key_case($val, CASE_LOWER); $decl = $this->conn->dataDict->getPortableDeclaration($val); $values = isset($decl['values']) ? $decl['values'] : array(); - $val['default'] = $val['default'] == 'CURRENT_TIMESTAMP' ? null : $val['default']; + $val['default'] = 'CURRENT_TIMESTAMP' == $val['default'] ? null : $val['default']; $description = array( - 'name' => $val['field'], - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'ntype' => $val['type'], - 'length' => $decl['length'], - 'fixed' => (bool) $decl['fixed'], - 'unsigned' => (bool) $decl['unsigned'], - 'values' => $values, - 'primary' => (strtolower($val['key']) == 'pri'), - 'default' => $val['default'], - 'notnull' => (bool) ($val['null'] != 'YES'), - 'autoincrement' => (bool) (strpos($val['extra'], 'auto_increment') !== false), - ); + 'name' => $val['field'], + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'ntype' => $val['type'], + 'length' => $decl['length'], + 'fixed' => (bool) $decl['fixed'], + 'unsigned' => (bool) $decl['unsigned'], + 'values' => $values, + 'primary' => ('pri' == strtolower($val['key'])), + 'default' => $val['default'], + 'notnull' => (bool) ('YES' != $val['null']), + 'autoincrement' => (bool) (false !== strpos($val['extra'], 'auto_increment')), + ); if (isset($decl['scale'])) { $description['scale'] = $decl['scale']; } @@ -177,9 +179,10 @@ public function listTableColumns($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) @@ -187,7 +190,7 @@ public function listTableIndexes($table) $keyName = 'Key_name'; $nonUnique = 'Non_unique'; if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) == CASE_LOWER) { + if (CASE_LOWER == $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE)) { $keyName = strtolower($keyName); $nonUnique = strtolower($nonUnique); } else { @@ -197,23 +200,24 @@ public function listTableIndexes($table) } $table = $this->conn->quoteIdentifier($table, true); - $query = 'SHOW INDEX FROM ' . $table; + $query = 'SHOW INDEX FROM '.$table; $indexes = $this->conn->fetchAssoc($query); - $result = array(); foreach ($indexes as $indexData) { if ($indexData[$nonUnique] && ($index = $this->conn->formatter->fixIndexName($indexData[$keyName]))) { $result[] = $index; } } + return $result; } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) @@ -222,9 +226,10 @@ public function listTables($database = null) } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) @@ -232,9 +237,9 @@ public function listViews($database = null) if (is_null($database)) { $query = 'SELECT table_name FROM information_schema.VIEWS'; } else { - $query = sprintf($this->sql['listViews'], ' FROM ' . $database); + $query = sprintf($this->sql['listViews'], ' FROM '.$database); } return $this->conn->fetchColumn($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Oracle.php b/lib/Doctrine/Import/Oracle.php index 3800cc595..ce1aa2388 100644 --- a/lib/Doctrine/Import/Oracle.php +++ b/lib/Doctrine/Import/Oracle.php @@ -20,37 +20,36 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Oracle extends Doctrine_Import { /** - * lists all databases + * lists all databases. * * @return array */ public function listDatabases() { - if ( ! $this->conn->getAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE)) { + if (!$this->conn->getAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE)) { throw new Doctrine_Import_Exception('database listing is only supported if the "emulate_database" option is enabled'); } - $query = 'SELECT username FROM sys.user_users'; + $query = 'SELECT username FROM sys.user_users'; $result2 = $this->conn->standaloneQuery($query); - $result = $result2->fetchColumn(); - return $result; + return $result2->fetchColumn(); } /** - * lists all availible database functions + * lists all availible database functions. * * @return array */ @@ -62,26 +61,29 @@ public function listFunctions() } /** - * lists all database triggers + * lists all database triggers. * * @param string|null $database + * * @return array */ public function listTriggers($database = null) { - $query = "SELECT trigger_name FROM sys.user_triggers"; + $query = 'SELECT trigger_name FROM sys.user_triggers'; + return $this->conn->fetchColumn($query); } /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) { - $query = "SELECT sequence_name FROM sys.user_sequences"; + $query = 'SELECT sequence_name FROM sys.user_sequences'; $tableNames = $this->conn->fetchColumn($query); @@ -89,9 +91,10 @@ public function listSequences($database = null) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) @@ -99,7 +102,7 @@ public function listTableConstraints($table) $table = $this->conn->quote($table, 'text'); $query = 'SELECT index_name name FROM user_constraints' - . ' WHERE table_name = ' . $table . ' OR table_name = ' . strtoupper($table); + .' WHERE table_name = '.$table.' OR table_name = '.strtoupper($table); $constraints = $this->conn->fetchColumn($query); @@ -107,14 +110,15 @@ public function listTableConstraints($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - $sql = <<conn->dataDict->getPortableDeclaration($val); $descr[$val['column_name']] = array( - 'name' => $val['column_name'], - 'notnull' => (bool) ($val['nullable'] === 'N'), - 'ntype' => $val['data_type'], - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'fixed' => (bool) $decl['fixed'], - 'unsigned' => (bool) $decl['unsigned'], - 'default' => $val['data_default'], - 'length' => $val['data_length'], - 'primary' => (bool) $val['primary'], - 'scale' => isset($val['scale']) ? $val['scale']:null, + 'name' => $val['column_name'], + 'notnull' => (bool) ('N' === $val['nullable']), + 'ntype' => $val['data_type'], + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'fixed' => (bool) $decl['fixed'], + 'unsigned' => (bool) $decl['unsigned'], + 'default' => $val['data_default'], + 'length' => $val['data_length'], + 'primary' => (bool) $val['primary'], + 'scale' => isset($val['scale']) ? $val['scale'] : null, ); } @@ -153,84 +157,88 @@ public function listTableColumns($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) { $table = $this->conn->quote($table, 'text'); $query = 'SELECT index_name name FROM user_indexes' - . ' WHERE table_name = ' . $table . ' OR table_name = ' . strtoupper($table) - . ' AND generated = ' . $this->conn->quote('N', 'text'); + .' WHERE table_name = '.$table.' OR table_name = '.strtoupper($table) + .' AND generated = '.$this->conn->quote('N', 'text'); $indexes = $this->conn->fetchColumn($query); return array_map(array($this->conn->formatter, 'fixIndexName'), $indexes); } - + /** - * list table relations + * list table relations. */ public function listTableRelations($table) { $relations = array(); $sql = 'SELECT ' - . 'rcc.table_name AS referenced_table_name, ' - . 'lcc.column_name AS local_column_name, ' - . 'rcc.column_name AS referenced_column_name ' - . 'FROM user_constraints ac ' - . 'JOIN user_cons_columns rcc ON ac.r_constraint_name = rcc.constraint_name ' - . 'JOIN user_cons_columns lcc ON ac.constraint_name = lcc.constraint_name ' - . "WHERE ac.constraint_type = 'R' AND ac.table_name = :tableName"; + .'rcc.table_name AS referenced_table_name, ' + .'lcc.column_name AS local_column_name, ' + .'rcc.column_name AS referenced_column_name ' + .'FROM user_constraints ac ' + .'JOIN user_cons_columns rcc ON ac.r_constraint_name = rcc.constraint_name ' + .'JOIN user_cons_columns lcc ON ac.constraint_name = lcc.constraint_name ' + ."WHERE ac.constraint_type = 'R' AND ac.table_name = :tableName"; $results = $this->conn->fetchAssoc($sql, array(':tableName' => $table)); foreach ($results as $result) { $result = array_change_key_case($result, CASE_LOWER); - $relations[] = array('table' => $result['referenced_table_name'], - 'local' => $result['local_column_name'], - 'foreign' => $result['referenced_column_name']); + $relations[] = array('table' => $result['referenced_table_name'], + 'local' => $result['local_column_name'], + 'foreign' => $result['referenced_column_name']); } + return $relations; } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) { $query = "SELECT * FROM user_objects WHERE object_type = 'TABLE' and object_name in (select table_name from user_tables)"; + return $this->conn->fetchColumn($query); } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) { - } /** - * lists table views + * lists table views. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) { - } /** - * lists database users + * lists database users. * * @return array */ @@ -242,14 +250,16 @@ public function listUsers() } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) { $query = 'SELECT view_name FROM sys.user_views'; + return $this->conn->fetchColumn($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Pgsql.php b/lib/Doctrine/Import/Pgsql.php index bdef1d00b..2eb2a1af3 100644 --- a/lib/Doctrine/Import/Pgsql.php +++ b/lib/Doctrine/Import/Pgsql.php @@ -20,22 +20,21 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Paul Cooper * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7689 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Pgsql extends Doctrine_Import { - protected $sql = array( - 'listDatabases' => 'SELECT datname FROM pg_database', - 'listFunctions' => "SELECT + 'listDatabases' => 'SELECT datname FROM pg_database', + 'listFunctions' => "SELECT proname FROM pg_proc pr, @@ -47,14 +46,14 @@ class Doctrine_Import_Pgsql extends Doctrine_Import AND pr.pronamespace IN (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema'", - 'listSequences' => "SELECT + 'listSequences' => "SELECT regexp_replace(relname, '_seq$', '') FROM pg_class WHERE relkind = 'S' AND relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')", - 'listTables' => "SELECT + 'listTables' => "SELECT c.relname AS table_name FROM pg_class c, pg_user u WHERE c.relowner = u.usesysid @@ -68,9 +67,9 @@ class Doctrine_Import_Pgsql extends Doctrine_Import AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) AND c.relname !~ '^pg_'", - 'listViews' => 'SELECT viewname FROM pg_views', - 'listUsers' => 'SELECT usename FROM pg_user', - 'listTableConstraints' => "SELECT + 'listViews' => 'SELECT viewname FROM pg_views', + 'listUsers' => 'SELECT usename FROM pg_user', + 'listTableConstraints' => "SELECT relname FROM pg_class @@ -81,7 +80,7 @@ class Doctrine_Import_Pgsql extends Doctrine_Import AND pg_class.oid = pg_index.indrelid AND (indisunique = 't' OR indisprimary = 't') )", - 'listTableIndexes' => "SELECT + 'listTableIndexes' => "SELECT relname FROM pg_class @@ -93,7 +92,7 @@ class Doctrine_Import_Pgsql extends Doctrine_Import AND indisunique != 't' AND indisprimary != 't' )", - 'listTableColumns' => "SELECT + 'listTableColumns' => "SELECT ordinal_position as attnum, column_name as field, udt_name as type, @@ -112,7 +111,7 @@ class Doctrine_Import_Pgsql extends Doctrine_Import FROM information_schema.COLUMNS WHERE table_name = %s ORDER BY ordinal_position", - 'listTableRelations' => "SELECT pg_catalog.pg_get_constraintdef(oid, true) as condef + 'listTableRelations' => "SELECT pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_catalog.pg_constraint r WHERE r.conrelid = ( @@ -121,24 +120,25 @@ class Doctrine_Import_Pgsql extends Doctrine_Import LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ ? AND pg_catalog.pg_table_is_visible(c.oid) ) - AND r.contype = 'f'" - ); + AND r.contype = 'f'", + ); /** - * lists all database triggers + * lists all database triggers. * * @param string|null $database + * * @return array */ public function listTriggers($database = null) { - } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) @@ -150,9 +150,10 @@ public function listTableConstraints($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) @@ -161,75 +162,76 @@ public function listTableColumns($table) $query = sprintf($this->sql['listTableColumns'], $table); $result = $this->conn->fetchAssoc($query); - $columns = array(); + $columns = array(); foreach ($result as $key => $val) { $val = array_change_key_case($val, CASE_LOWER); - if ($val['type'] == 'character varying') { + if ('character varying' == $val['type']) { // get length from varchar definition $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $val['complete_type']); $val['length'] = $length; - } else if (strpos($val['complete_type'], 'character varying') !== false) { + } elseif (false !== strpos($val['complete_type'], 'character varying')) { // get length from varchar definition $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $val['complete_type']); $val['length'] = $length; } - + $decl = $this->conn->dataDict->getPortableDeclaration($val); $description = array( - 'name' => $val['field'], - 'ntype' => $val['type'], - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'length' => $decl['length'], - 'fixed' => (bool) $decl['fixed'], - 'unsigned' => (bool) $decl['unsigned'], - 'notnull' => ($val['isnotnull'] == 'NO'), - 'default' => $val['default'], - 'primary' => ($val['pri'] == 't'), + 'name' => $val['field'], + 'ntype' => $val['type'], + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'length' => $decl['length'], + 'fixed' => (bool) $decl['fixed'], + 'unsigned' => (bool) $decl['unsigned'], + 'notnull' => ('NO' == $val['isnotnull']), + 'default' => $val['default'], + 'primary' => ('t' == $val['pri']), ); - // If postgres enum type - if ($val['type'] == 'e'){ + // If postgres enum type + if ('e' == $val['type']) { $description['default'] = isset($decl['default']) ? $decl['default'] : null; - $t_result = $this->conn->fetchAssoc(sprintf('select enum_range(null::%s) as range ', $decl['enum_name'])); - if (isset($t_result[0])){ - $range = $t_result[0]['range']; - $range = str_replace('{','',$range); - $range = str_replace('}','',$range); - $range = explode(',',$range); + $t_result = $this->conn->fetchAssoc(sprintf('select enum_range(null::%s) as range ', $decl['enum_name'])); + if (isset($t_result[0])) { + $range = $t_result[0]['range']; + $range = str_replace('{', '', $range); + $range = str_replace('}', '', $range); + $range = explode(',', $range); $description['values'] = $range; } } - $matches = array(); + $matches = array(); - if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $description['default'], $matches)) { - $description['sequence'] = $this->conn->formatter->fixSequenceName($matches[1]); - $description['default'] = null; - } else if (preg_match("/^'(.*)'::character varying$/", $description['default'], $matches)) { + if (preg_match("/^nextval\\('(.*)'(::.*)?\\)$/", $description['default'], $matches)) { + $description['sequence'] = $this->conn->formatter->fixSequenceName($matches[1]); + $description['default'] = null; + } elseif (preg_match("/^'(.*)'::character varying$/", $description['default'], $matches)) { $description['default'] = $matches[1]; - } else if (preg_match("/^(.*)::character varying$/", $description['default'], $matches)) { + } elseif (preg_match('/^(.*)::character varying$/', $description['default'], $matches)) { $description['default'] = $matches[1]; - } else if ($description['type'] == 'boolean') { - if ($description['default'] === 'true') { - $description['default'] = true; - } else if ($description['default'] === 'false') { - $description['default'] = false; + } elseif ('boolean' == $description['type']) { + if ('true' === $description['default']) { + $description['default'] = true; + } elseif ('false' === $description['default']) { + $description['default'] = false; } } $columns[$val['field']] = $description; } - + return $columns; } /** - * list all indexes in a table + * list all indexes in a table. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) @@ -241,9 +243,10 @@ public function listTableIndexes($table) } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) @@ -252,9 +255,10 @@ public function listTables($database = null) } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) @@ -263,17 +267,19 @@ public function listTableTriggers($table) FROM pg_trigger trg, pg_class tbl WHERE trg.tgrelid = tbl.oid'; - if ($table !== null) { + if (null !== $table) { $table = $this->conn->quote(strtoupper($table), 'string'); - $query .= " AND tbl.relname = $table"; + $query .= " AND tbl.relname = {$table}"; } + return $this->conn->fetchColumn($query); } /** - * list the views in the database that reference a given table + * list the views in the database that reference a given table. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) @@ -284,21 +290,21 @@ public function listTableViews($table) public function listTableRelations($table) { $sql = $this->sql['listTableRelations']; - $param = array('^(' . $table . ')$'); + $param = array('^('.$table.')$'); $relations = array(); $results = $this->conn->fetchAssoc($sql, $param); foreach ($results as $result) { preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $result['condef'], $values); - if ((strpos($values[1], ',') === false) && (strpos($values[3], ',') === false)) { + if ((false === strpos($values[1], ',')) && (false === strpos($values[3], ','))) { $tableName = trim($values[2], '"'); - $relations[] = array('table' => $tableName, - 'local' => $values[1], - 'foreign' => $values[3]); + $relations[] = array('table' => $tableName, + 'local' => $values[1], + 'foreign' => $values[3]); } } return $relations; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Schema.php b/lib/Doctrine/Import/Schema.php index 65ea075d5..c51904660 100644 --- a/lib/Doctrine/Import/Schema.php +++ b/lib/Doctrine/Import/Schema.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Import_Schema + * Doctrine_Import_Schema. * * Class for importing Doctrine_Record classes from a yaml schema definition * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision: 1838 $ + * * @author Nicolas Bérard-Nault * @author Jonathan H. Wage */ @@ -51,7 +52,7 @@ class Doctrine_Import_Schema 'detect_relations'); /** - * _relations + * _relations. * * Array of all relationships parsed from all schema files * @@ -60,101 +61,101 @@ class Doctrine_Import_Schema protected $_relations = array(); /** - * _options + * _options. * * Array of options used to configure the model generation from the parsed schema files * This array is forwarded to Doctrine_Import_Builder * * @var array */ - protected $_options = array('packagesPrefix' => 'Package', - 'packagesPath' => '', - 'packagesFolderName' => 'packages', - 'suffix' => '.php', - 'generateBaseClasses' => true, - 'generateTableClasses' => false, - 'generateAccessors' => false, - 'baseClassPrefix' => 'Base', - 'baseClassesDirectory' => 'generated', - 'baseClassName' => 'Doctrine_Record'); + protected $_options = array('packagesPrefix' => 'Package', + 'packagesPath' => '', + 'packagesFolderName' => 'packages', + 'suffix' => '.php', + 'generateBaseClasses' => true, + 'generateTableClasses' => false, + 'generateAccessors' => false, + 'baseClassPrefix' => 'Base', + 'baseClassesDirectory' => 'generated', + 'baseClassName' => 'Doctrine_Record'); /** - * _validation + * _validation. * * Array used to validate schema element. * See: _validateSchemaElement * * @var array */ - protected $_validation = array('root' => array('abstract', - 'connection', - 'className', - 'tableName', - 'connection', - 'relations', - 'columns', - 'indexes', - 'attributes', - 'templates', - 'actAs', - 'options', - 'package', - 'package_custom_path', - 'inheritance', - 'detect_relations', - 'listeners', - 'checks', - 'comment'), - - 'column' => array('name', - 'format', - 'fixed', - 'primary', - 'autoincrement', - 'type', - 'length', - 'size', - 'default', - 'scale', - 'values', - 'comment', - 'sequence', - 'protected', - 'zerofill', - 'owner', - 'extra', - 'comment', - 'charset', - 'collation'), - - 'relation' => array('key', - 'class', - 'alias', - 'type', - 'refClass', - 'local', - 'foreign', - 'foreignClass', - 'foreignAlias', - 'foreignType', - 'autoComplete', - 'cascade', - 'onDelete', - 'onUpdate', - 'equal', - 'owningSide', - 'refClassRelationAlias', - 'foreignKeyName', - 'orderBy'), - - 'inheritance'=> array('type', - 'extends', - 'keyField', - 'keyValue')); + protected $_validation = array('root' => array('abstract', + 'connection', + 'className', + 'tableName', + 'connection', + 'relations', + 'columns', + 'indexes', + 'attributes', + 'templates', + 'actAs', + 'options', + 'package', + 'package_custom_path', + 'inheritance', + 'detect_relations', + 'listeners', + 'checks', + 'comment'), + + 'column' => array('name', + 'format', + 'fixed', + 'primary', + 'autoincrement', + 'type', + 'length', + 'size', + 'default', + 'scale', + 'values', + 'comment', + 'sequence', + 'protected', + 'zerofill', + 'owner', + 'extra', + 'comment', + 'charset', + 'collation'), + + 'relation' => array('key', + 'class', + 'alias', + 'type', + 'refClass', + 'local', + 'foreign', + 'foreignClass', + 'foreignAlias', + 'foreignType', + 'autoComplete', + 'cascade', + 'onDelete', + 'onUpdate', + 'equal', + 'owningSide', + 'refClassRelationAlias', + 'foreignKeyName', + 'orderBy'), + + 'inheritance' => array('type', + 'extends', + 'keyField', + 'keyValue')); /** * Returns an array of definition keys that can be applied at the global level. - * + * * @return array */ public static function getGlobalDefinitionKeys() @@ -163,22 +164,19 @@ public static function getGlobalDefinitionKeys() } /** - * getOption + * getOption. * - * @param string $name - * @return void + * @param string $name */ public function getOption($name) { - if (isset($this->_options[$name])) { + if (isset($this->_options[$name])) { return $this->_options[$name]; } } /** - * getOptions - * - * @return void + * getOptions. */ public function getOptions() { @@ -186,11 +184,10 @@ public function getOptions() } /** - * setOption + * setOption. * - * @param string $name - * @param string $value - * @return void + * @param string $name + * @param string $value */ public function setOption($name, $value) { @@ -198,42 +195,42 @@ public function setOption($name, $value) $this->_options[$name] = $value; } } - + /** - * setOptions + * setOptions. * - * @param string $options - * @return void + * @param string $options */ public function setOptions($options) { - if ( ! empty($options)) { - $this->_options = $options; + if (!empty($options)) { + $this->_options = $options; } } /** - * buildSchema + * buildSchema. * * Loop throug directories of schema files and parse them all in to one complete array of schema information * - * @param string $schema Array of schema files or single schema file. Array of directories with schema files or single directory - * @param string $format Format of the files we are parsing and building from - * @return array $array + * @param string $schema Array of schema files or single schema file. Array of directories with schema files or single directory + * @param string $format Format of the files we are parsing and building from + * + * @return array $array */ public function buildSchema($schema, $format) { $array = array(); - foreach ((array) $schema AS $s) { + foreach ((array) $schema as $s) { if (is_file($s)) { $e = explode('.', $s); if (end($e) === $format) { $array = array_merge($array, $this->parseSchema($s, $format)); - } - } else if (is_dir($s)) { + } + } elseif (is_dir($s)) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($s), - RecursiveIteratorIterator::LEAVES_ONLY); + RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $e = explode('.', $file->getFileName()); @@ -242,27 +239,24 @@ public function buildSchema($schema, $format) } } } else { - $array = array_merge($array, $this->parseSchema($s, $format)); + $array = array_merge($array, $this->parseSchema($s, $format)); } } $array = $this->_buildRelationships($array); - $array = $this->_processInheritance($array); - return $array; + return $this->_processInheritance($array); } /** - * importSchema + * importSchema. * * A method to import a Schema and translate it into a Doctrine_Record object * - * @param string $schema The file containing the XML schema - * @param string $format Format of the schema file - * @param string $directory The directory where the Doctrine_Record class will be written - * @param array $models Optional array of models to import - * - * @return void + * @param string $schema The file containing the XML schema + * @param string $format Format of the schema file + * @param string $directory The directory where the Doctrine_Record class will be written + * @param array $models Optional array of models to import */ public function importSchema($schema, $format = 'yml', $directory = null, $models = array()) { @@ -270,50 +264,49 @@ public function importSchema($schema, $format = 'yml', $directory = null, $model $builder = new Doctrine_Import_Builder(); $builder->setTargetPath($directory); $builder->setOptions($this->getOptions()); - + $array = $this->buildSchema($schema, $format); - if (count($array) == 0) { - throw new Doctrine_Import_Exception( - sprintf('No ' . $format . ' schema found in ' . implode(", ", $schema)) - ); + if (0 == count($array)) { + throw new Doctrine_Import_Exception(sprintf('No '.$format.' schema found in '.implode(', ', $schema))); } foreach ($array as $name => $definition) { - if ( ! empty($models) && !in_array($definition['className'], $models)) { + if (!empty($models) && !in_array($definition['className'], $models)) { continue; } - + $builder->buildRecord($definition); } } /** - * parseSchema + * parseSchema. * * A method to parse a Schema and translate it into a property array. * The function returns that property array. * - * @param string $schema Path to the file containing the schema - * @param string $type Format type of the schema we are parsing - * @return array $build Built array of schema information + * @param string $schema Path to the file containing the schema + * @param string $type Format type of the schema we are parsing + * + * @return array $build Built array of schema information */ public function parseSchema($schema, $type) { - $defaults = array('abstract' => false, - 'className' => null, - 'tableName' => null, - 'connection' => null, - 'relations' => array(), - 'indexes' => array(), - 'attributes' => array(), - 'templates' => array(), - 'actAs' => array(), - 'options' => array(), - 'package' => null, - 'inheritance' => array(), - 'detect_relations' => false); - + $defaults = array('abstract' => false, + 'className' => null, + 'tableName' => null, + 'connection' => null, + 'relations' => array(), + 'indexes' => array(), + 'attributes' => array(), + 'templates' => array(), + 'actAs' => array(), + 'options' => array(), + 'package' => null, + 'inheritance' => array(), + 'detect_relations' => false); + $array = Doctrine_Parser::load($schema, $type); // Loop over and build up all the global values and remove them from the array @@ -338,7 +331,7 @@ public function parseSchema($schema, $type) $columns = array(); - $className = isset($table['className']) ? (string) $table['className']:(string) $className; + $className = isset($table['className']) ? (string) $table['className'] : (string) $className; if (isset($table['inheritance']['keyField']) || isset($table['inheritance']['keyValue'])) { $table['inheritance']['type'] = 'column_aggregation'; @@ -347,22 +340,21 @@ public function parseSchema($schema, $type) if (isset($table['tableName']) && $table['tableName']) { $tableName = $table['tableName']; } else { - if (isset($table['inheritance']['type']) && ($table['inheritance']['type'] == 'column_aggregation')) { + if (isset($table['inheritance']['type']) && ('column_aggregation' == $table['inheritance']['type'])) { $tableName = null; } else { $tableName = Doctrine_Inflector::tableize($className); } } - $connection = isset($table['connection']) ? $table['connection']:'current'; + $connection = isset($table['connection']) ? $table['connection'] : 'current'; - $columns = isset($table['columns']) ? $table['columns']:array(); + $columns = isset($table['columns']) ? $table['columns'] : array(); - if ( ! empty($columns)) { + if (!empty($columns)) { foreach ($columns as $columnName => $field) { - // Support short syntax: my_column: integer(4) - if ( ! is_array($field)) { + if (!is_array($field)) { $original = $field; $field = array(); $field['type'] = $original; @@ -375,11 +367,11 @@ public function parseSchema($schema, $type) $colDesc['name'] = $columnName; } - $this->_validateSchemaElement('column', array_keys($field), $className . '->columns->' . $colDesc['name']); + $this->_validateSchemaElement('column', array_keys($field), $className.'->columns->'.$colDesc['name']); // Support short type(length) syntax: my_column: { type: integer(4) } $e = explode('(', $field['type']); - if (isset($e[0]) && isset($e[1])) { + if (isset($e[0], $e[1])) { $colDesc['type'] = $e[0]; $value = substr($e[1], 0, strlen($e[1]) - 1); $e = explode(',', $value); @@ -388,15 +380,15 @@ public function parseSchema($schema, $type) $colDesc['scale'] = $e[1]; } } else { - $colDesc['type'] = isset($field['type']) ? (string) $field['type']:null; - $colDesc['length'] = isset($field['length']) ? (int) $field['length']:null; - $colDesc['length'] = isset($field['size']) ? (int) $field['size']:$colDesc['length']; + $colDesc['type'] = isset($field['type']) ? (string) $field['type'] : null; + $colDesc['length'] = isset($field['length']) ? (int) $field['length'] : null; + $colDesc['length'] = isset($field['size']) ? (int) $field['size'] : $colDesc['length']; } - $colDesc['fixed'] = isset($field['fixed']) ? (int) $field['fixed']:null; - $colDesc['primary'] = isset($field['primary']) ? (bool) (isset($field['primary']) && $field['primary']):null; - $colDesc['default'] = isset($field['default']) ? $field['default']:null; - $colDesc['autoincrement'] = isset($field['autoincrement']) ? (bool) (isset($field['autoincrement']) && $field['autoincrement']):null; + $colDesc['fixed'] = isset($field['fixed']) ? (int) $field['fixed'] : null; + $colDesc['primary'] = isset($field['primary']) ? (bool) (isset($field['primary']) && $field['primary']) : null; + $colDesc['default'] = isset($field['default']) ? $field['default'] : null; + $colDesc['autoincrement'] = isset($field['autoincrement']) ? (bool) (isset($field['autoincrement']) && $field['autoincrement']) : null; if (isset($field['sequence'])) { if (true === $field['sequence']) { @@ -408,7 +400,7 @@ public function parseSchema($schema, $type) $colDesc['sequence'] = null; } - $colDesc['values'] = isset($field['values']) ? (array) $field['values']:null; + $colDesc['values'] = isset($field['values']) ? (array) $field['values'] : null; // Include all the specified and valid validators in the colDesc $validators = Doctrine_Manager::getInstance()->getValidators(); @@ -425,20 +417,20 @@ public function parseSchema($schema, $type) // Apply the default values foreach ($defaults as $key => $defaultValue) { - if (isset($table[$key]) && ! isset($build[$className][$key])) { + if (isset($table[$key]) && !isset($build[$className][$key])) { $build[$className][$key] = $table[$key]; } else { - $build[$className][$key] = isset($build[$className][$key]) ? $build[$className][$key]:$defaultValue; + $build[$className][$key] = isset($build[$className][$key]) ? $build[$className][$key] : $defaultValue; } } - + $build[$className]['className'] = $className; $build[$className]['tableName'] = $tableName; $build[$className]['columns'] = $columns; - + // Make sure that anything else that is specified in the schema makes it to the final array $build[$className] = Doctrine_Lib::arrayDeepMerge($table, $build[$className]); - + // We need to keep track of the className for the connection $build[$className]['connectionClassName'] = $build[$className]['className']; } @@ -447,42 +439,41 @@ public function parseSchema($schema, $type) } /** - * _processInheritance - * + * _processInheritance. + * * Perform some processing on inheritance. * Sets the default type and sets some default values for certain types * - * @param string $array - * @return void + * @param string $array */ protected function _processInheritance($array) { // Apply default inheritance configuration foreach ($array as $className => $definition) { - if ( ! empty($array[$className]['inheritance'])) { - $this->_validateSchemaElement('inheritance', array_keys($definition['inheritance']), $className . '->inheritance'); + if (!empty($array[$className]['inheritance'])) { + $this->_validateSchemaElement('inheritance', array_keys($definition['inheritance']), $className.'->inheritance'); // Default inheritance to concrete inheritance - if ( ! isset($array[$className]['inheritance']['type'])) { + if (!isset($array[$className]['inheritance']['type'])) { $array[$className]['inheritance']['type'] = 'concrete'; } // Some magic for setting up the keyField and keyValue column aggregation options // Adds keyField to the parent class automatically - if ($array[$className]['inheritance']['type'] == 'column_aggregation') { + if ('column_aggregation' == $array[$className]['inheritance']['type']) { // Set the keyField to 'type' by default - if ( ! isset($array[$className]['inheritance']['keyField'])) { - $array[$className]['inheritance']['keyField'] = 'type'; + if (!isset($array[$className]['inheritance']['keyField'])) { + $array[$className]['inheritance']['keyField'] = 'type'; } - + // Set the keyValue to the name of the child class if it does not exist - if ( ! isset($array[$className]['inheritance']['keyValue'])) { + if (!isset($array[$className]['inheritance']['keyValue'])) { $array[$className]['inheritance']['keyValue'] = $className; } $parent = $this->_findBaseSuperClass($array, $definition['className']); // Add the keyType column to the parent if a definition does not already exist - if ( ! isset($array[$parent]['columns'][$array[$className]['inheritance']['keyField']])) { + if (!isset($array[$parent]['columns'][$array[$className]['inheritance']['keyField']])) { $array[$parent]['columns'][$array[$className]['inheritance']['keyField']] = array('name' => $array[$className]['inheritance']['keyField'], 'type' => 'string', 'length' => 255); } } @@ -492,40 +483,40 @@ protected function _processInheritance($array) // Array of the array keys to move to the parent, and the value to default the child definition to // after moving it. Will also populate the subclasses array for the inheritance parent $moves = array('columns' => array(), - 'indexes' => array(), - 'attributes' => array(), - 'options' => array(), - 'checks' => array()); + 'indexes' => array(), + 'attributes' => array(), + 'options' => array(), + 'checks' => array()); foreach ($array as $className => $definition) { // Move any definitions on the schema to the parent - if (isset($definition['inheritance']['extends']) && isset($definition['inheritance']['type']) && ($definition['inheritance']['type'] == 'simple' || $definition['inheritance']['type'] == 'column_aggregation')) { + if (isset($definition['inheritance']['extends'], $definition['inheritance']['type']) && ('simple' == $definition['inheritance']['type'] || 'column_aggregation' == $definition['inheritance']['type'])) { $parent = $this->_findBaseSuperClass($array, $definition['className']); foreach ($moves as $move => $resetValue) { - if (isset($array[$parent][$move]) && isset($definition[$move])) { + if (isset($array[$parent][$move], $definition[$move])) { $array[$parent][$move] = Doctrine_Lib::arrayDeepMerge($array[$parent][$move], $definition[$move]); $array[$definition['className']][$move] = $resetValue; } } // Populate the parents subclasses - if ($definition['inheritance']['type'] == 'column_aggregation') { - // Fix for 2015: loop through superclasses' inheritance to the base-superclass to - // make sure we collect all keyFields needed (and not only the first) - $inheritanceFields = array($definition['inheritance']['keyField'] => $definition['inheritance']['keyValue']); + if ('column_aggregation' == $definition['inheritance']['type']) { + // Fix for 2015: loop through superclasses' inheritance to the base-superclass to + // make sure we collect all keyFields needed (and not only the first) + $inheritanceFields = array($definition['inheritance']['keyField'] => $definition['inheritance']['keyValue']); - $superClass = $definition['inheritance']['extends']; - $multiInheritanceDef = $array[$superClass]; + $superClass = $definition['inheritance']['extends']; + $multiInheritanceDef = $array[$superClass]; - while (count($multiInheritanceDef['inheritance']) > 0 && array_key_exists('extends', $multiInheritanceDef['inheritance']) && $multiInheritanceDef['inheritance']['type'] == 'column_aggregation') { + while (count($multiInheritanceDef['inheritance']) > 0 && array_key_exists('extends', $multiInheritanceDef['inheritance']) && 'column_aggregation' == $multiInheritanceDef['inheritance']['type']) { $superClass = $multiInheritanceDef['inheritance']['extends']; - + // keep original keyField with it's keyValue - if ( ! isset($inheritanceFields[$multiInheritanceDef['inheritance']['keyField']])) { + if (!isset($inheritanceFields[$multiInheritanceDef['inheritance']['keyField']])) { $inheritanceFields[$multiInheritanceDef['inheritance']['keyField']] = $multiInheritanceDef['inheritance']['keyValue']; - } - $multiInheritanceDef = $array[$superClass]; - } + } + $multiInheritanceDef = $array[$superClass]; + } $array[$parent]['inheritance']['subclasses'][$definition['className']] = $inheritanceFields; } @@ -539,34 +530,34 @@ protected function _processInheritance($array) * Find the base super class for this inheritance child. We need to move all levels of children to the * top most parent. * - * @param array $array Array of schema information + * @param array $array Array of schema information + * * @return string $class Class to get find the parent for */ protected function _findBaseSuperClass($array, $class) { - if (isset($array[$class]['inheritance']['extends']) && isset($array[$class]['inheritance']['type']) && ($array[$class]['inheritance']['type'] == 'simple' || $array[$class]['inheritance']['type'] == 'column_aggregation')) { + if (isset($array[$class]['inheritance']['extends'], $array[$class]['inheritance']['type']) && ('simple' == $array[$class]['inheritance']['type'] || 'column_aggregation' == $array[$class]['inheritance']['type'])) { return $this->_findBaseSuperClass($array, $array[$class]['inheritance']['extends']); - } else { - return $class; } + + return $class; } /** - * buildRelationships + * buildRelationships. * * Loop through an array of schema information and build all the necessary relationship information - * Will attempt to auto complete relationships and simplify the amount of information required + * Will attempt to auto complete relationships and simplify the amount of information required * for defining a relationship * - * @param string $array - * @return void + * @param string $array */ protected function _buildRelationships($array) { // Handle auto detecting relations by the names of columns // User.contact_id will automatically create User hasOne Contact local => contact_id, foreign => id foreach ($array as $className => $properties) { - if (isset($properties['columns']) && ! empty($properties['columns']) && isset($properties['detect_relations']) && $properties['detect_relations']) { + if (isset($properties['columns']) && !empty($properties['columns']) && isset($properties['detect_relations']) && $properties['detect_relations']) { foreach ($properties['columns'] as $column) { // Check if the column we are inflecting has a _id on the end of it before trying to inflect it and find // the class name for the column @@ -577,8 +568,8 @@ protected function _buildRelationships($array) // Set the detected foreign key type and length to the same as the primary key // of the related table - $type = isset($array[$columnClassName]['columns']['id']['type']) ? $array[$columnClassName]['columns']['id']['type']:'integer'; - $length = isset($array[$columnClassName]['columns']['id']['length']) ? $array[$columnClassName]['columns']['id']['length']:8; + $type = isset($array[$columnClassName]['columns']['id']['type']) ? $array[$columnClassName]['columns']['id']['type'] : 'integer'; + $length = isset($array[$columnClassName]['columns']['id']['length']) ? $array[$columnClassName]['columns']['id']['length'] : 8; $array[$className]['columns'][$column['name']]['type'] = $type; $array[$className]['columns'][$column['name']]['length'] = $length; } @@ -588,55 +579,55 @@ protected function _buildRelationships($array) } foreach ($array as $name => $properties) { - if ( ! isset($properties['relations'])) { + if (!isset($properties['relations'])) { continue; } - + $className = $properties['className']; $relations = $properties['relations']; - + foreach ($relations as $alias => $relation) { - $class = isset($relation['class']) ? $relation['class']:$alias; - if ( ! isset($array[$class])) { + $class = isset($relation['class']) ? $relation['class'] : $alias; + if (!isset($array[$class])) { continue; } $relation['class'] = $class; $relation['alias'] = isset($relation['alias']) ? $relation['alias'] : $alias; - + // Attempt to guess the local and foreign if (isset($relation['refClass'])) { - $relation['local'] = isset($relation['local']) ? $relation['local']:Doctrine_Inflector::tableize($name) . '_id'; - $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign']:Doctrine_Inflector::tableize($class) . '_id'; + $relation['local'] = isset($relation['local']) ? $relation['local'] : Doctrine_Inflector::tableize($name).'_id'; + $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign'] : Doctrine_Inflector::tableize($class).'_id'; } else { - $relation['local'] = isset($relation['local']) ? $relation['local']:Doctrine_Inflector::tableize($relation['class']) . '_id'; - $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign']:'id'; + $relation['local'] = isset($relation['local']) ? $relation['local'] : Doctrine_Inflector::tableize($relation['class']).'_id'; + $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign'] : 'id'; } - + if (isset($relation['refClass'])) { $relation['type'] = 'many'; } - + if (isset($relation['type']) && $relation['type']) { - $relation['type'] = $relation['type'] === 'one' ? Doctrine_Relation::ONE:Doctrine_Relation::MANY; + $relation['type'] = 'one' === $relation['type'] ? Doctrine_Relation::ONE : Doctrine_Relation::MANY; } else { $relation['type'] = Doctrine_Relation::ONE; } if (isset($relation['foreignType']) && $relation['foreignType']) { - $relation['foreignType'] = $relation['foreignType'] === 'one' ? Doctrine_Relation::ONE:Doctrine_Relation::MANY; + $relation['foreignType'] = 'one' === $relation['foreignType'] ? Doctrine_Relation::ONE : Doctrine_Relation::MANY; } - + $relation['key'] = $this->_buildUniqueRelationKey($relation); - - $this->_validateSchemaElement('relation', array_keys($relation), $className . '->relation->' . $relation['alias']); - + + $this->_validateSchemaElement('relation', array_keys($relation), $className.'->relation->'.$relation['alias']); + $this->_relations[$className][$alias] = $relation; } } - + // Now we auto-complete opposite ends of relationships $this->_autoCompleteOppositeRelations(); - + // Make sure we do not have any duplicate relations $this->_fixDuplicateRelations(); @@ -644,50 +635,48 @@ protected function _buildRelationships($array) foreach ($this->_relations as $className => $relations) { $array[$className]['relations'] = $relations; } - + return $array; } /** - * fixRelationships + * fixRelationships. * * Loop through all relationships building the opposite ends of each relationship * and make sure no duplicate relations exist - * - * @return void */ protected function _autoCompleteOppositeRelations() { - foreach($this->_relations as $className => $relations) { - foreach ($relations AS $alias => $relation) { - if ((isset($relation['equal']) && $relation['equal']) || (isset($relation['autoComplete']) && $relation['autoComplete'] === false)) { + foreach ($this->_relations as $className => $relations) { + foreach ($relations as $alias => $relation) { + if ((isset($relation['equal']) && $relation['equal']) || (isset($relation['autoComplete']) && false === $relation['autoComplete'])) { continue; } - + $newRelation = array(); $newRelation['foreign'] = $relation['local']; $newRelation['local'] = $relation['foreign']; - $newRelation['class'] = isset($relation['foreignClass']) ? $relation['foreignClass']:$className; - $newRelation['alias'] = isset($relation['foreignAlias']) ? $relation['foreignAlias']:$className; + $newRelation['class'] = isset($relation['foreignClass']) ? $relation['foreignClass'] : $className; + $newRelation['alias'] = isset($relation['foreignAlias']) ? $relation['foreignAlias'] : $className; $newRelation['foreignAlias'] = $alias; - + // this is so that we know that this relation was autogenerated and // that we do not need to include it if it is explicitly declared in the schema by the users. - $newRelation['autogenerated'] = true; - + $newRelation['autogenerated'] = true; + if (isset($relation['refClass'])) { $newRelation['refClass'] = $relation['refClass']; - $newRelation['type'] = isset($relation['foreignType']) ? $relation['foreignType']:$relation['type']; - } else { + $newRelation['type'] = isset($relation['foreignType']) ? $relation['foreignType'] : $relation['type']; + } else { if (isset($relation['foreignType'])) { $newRelation['type'] = $relation['foreignType']; } else { - $newRelation['type'] = $relation['type'] === Doctrine_Relation::ONE ? Doctrine_Relation::MANY:Doctrine_Relation::ONE; + $newRelation['type'] = Doctrine_Relation::ONE === $relation['type'] ? Doctrine_Relation::MANY : Doctrine_Relation::ONE; } } // Make sure it doesn't already exist - if ( ! isset($this->_relations[$relation['class']][$newRelation['alias']])) { + if (!isset($this->_relations[$relation['class']][$newRelation['alias']])) { $newRelation['key'] = $this->_buildUniqueRelationKey($newRelation); $this->_relations[$relation['class']][$newRelation['alias']] = $newRelation; } @@ -696,55 +685,50 @@ protected function _autoCompleteOppositeRelations() } /** - * _fixDuplicateRelations + * _fixDuplicateRelations. * * Ensure the relations for each class are unique and that no duplicated relations exist from the auto generated relations * and the user explicitely defining the opposite end - * - * @return void */ protected function _fixDuplicateRelations() { - foreach($this->_relations as $className => $relations) { + foreach ($this->_relations as $className => $relations) { // This is for checking for duplicates between alias-relations and a auto-generated relations to ensure the result set of unique relations $existingRelations = array(); $uniqueRelations = array(); foreach ($relations as $relation) { - if ( ! in_array($relation['key'], $existingRelations)) { + if (!in_array($relation['key'], $existingRelations)) { $existingRelations[] = $relation['key']; $uniqueRelations = array_merge($uniqueRelations, array($relation['alias'] => $relation)); } else { // check to see if this relationship is not autogenerated, if it's not, then the user must have explicitly declared it - if ( ! isset($relation['autogenerated']) || $relation['autogenerated'] != true) { + if (!isset($relation['autogenerated']) || true != $relation['autogenerated']) { $uniqueRelations = array_merge($uniqueRelations, array($relation['alias'] => $relation)); } } } - + $this->_relations[$className] = $uniqueRelations; } } /** - * _buildUniqueRelationKey + * _buildUniqueRelationKey. * * Build a unique key to identify a relationship by * Md5 hash of all the relationship parameters * - * @param string $relation - * @return void + * @param string $relation */ protected function _buildUniqueRelationKey($relation) { - return md5($relation['local'].$relation['foreign'].$relation['class'].(isset($relation['refClass']) ? $relation['refClass']:null)); + return md5($relation['local'].$relation['foreign'].$relation['class'].(isset($relation['refClass']) ? $relation['refClass'] : null)); } /** - * _validateSchemaElement + * _validateSchemaElement. * - * @param string $name - * @param string $value - * @return void + * @param string $name */ protected function _validateSchemaElement($name, $element, $path) { @@ -754,18 +738,16 @@ protected function _validateSchemaElement($name, $element, $path) // Validators are a part of the column validation // This should be fixed, made cleaner - if ($name == 'column') { + if ('column' == $name) { $validators = Doctrine_Manager::getInstance()->getValidators(); $validation = array_merge($validation, $validators); } $validation = array_flip($validation); foreach ($element as $key => $value) { - if ( ! isset($validation[$value])) { - throw new Doctrine_Import_Exception( - sprintf('Invalid schema element named "' . $value . '" at path "' . $path . '"') - ); + if (!isset($validation[$value])) { + throw new Doctrine_Import_Exception(sprintf('Invalid schema element named "'.$value.'" at path "'.$path.'"')); } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Sqlite.php b/lib/Doctrine/Import/Sqlite.php index f6d686da6..6f854d6d3 100644 --- a/lib/Doctrine/Import/Sqlite.php +++ b/lib/Doctrine/Import/Sqlite.php @@ -20,57 +20,56 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7644 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Sqlite extends Doctrine_Import { /** - * lists all databases + * lists all databases. * * @return array */ public function listDatabases() { - } /** - * lists all availible database functions + * lists all availible database functions. * * @return array */ public function listFunctions() { - } /** - * lists all database triggers + * lists all database triggers. * * @param string|null $database + * * @return array */ public function listTriggers($database = null) { - } /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) { - $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"; + $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"; $tableNames = $this->conn->fetchColumn($query); $result = array(); @@ -80,15 +79,17 @@ public function listSequences($database = null) } } if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - $result = array_map(($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); + $result = array_map(CASE_LOWER == $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) ? 'strtolower' : 'strtoupper', $result); } + return $result; } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) @@ -98,18 +99,18 @@ public function listTableConstraints($table) $query = "SELECT sql FROM sqlite_master WHERE type='index' AND "; if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - $query .= 'LOWER(tbl_name) = ' . strtolower($table); + $query .= 'LOWER(tbl_name) = '.strtolower($table); } else { - $query .= 'tbl_name = ' . $table; + $query .= 'tbl_name = '.$table; } - $query .= ' AND sql NOT NULL ORDER BY name'; + $query .= ' AND sql NOT NULL ORDER BY name'; $indexes = $this->conn->fetchColumn($query); $result = array(); foreach ($indexes as $sql) { - if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) { + if (preg_match('/^create unique index ([^ ]+) on /i', $sql, $tmp)) { $index = $this->conn->formatter->fixIndexName($tmp[1]); - if ( ! empty($index)) { + if (!empty($index)) { $result[$index] = true; } } @@ -118,86 +119,94 @@ public function listTableConstraints($table) if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { $result = array_change_key_case($result, $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE)); } + return array_keys($result); } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - $sql = 'PRAGMA table_info(' . $table . ')'; + $sql = 'PRAGMA table_info('.$table.')'; $result = $this->conn->fetchAll($sql); $description = array(); - $columns = array(); + $columns = array(); foreach ($result as $key => $val) { $val = array_change_key_case($val, CASE_LOWER); $decl = $this->conn->dataDict->getPortableDeclaration($val); $description = array( - 'name' => $val['name'], - 'ntype' => $val['type'], - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'notnull' => (bool) $val['notnull'], - 'default' => $val['dflt_value'], - 'primary' => (bool) $val['pk'], - 'length' => null, - 'scale' => null, - 'precision' => null, - 'unsigned' => null, - 'autoincrement' => (bool) ($val['pk'] == 1 && $decl['type'][0] == 'integer'), - ); + 'name' => $val['name'], + 'ntype' => $val['type'], + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'notnull' => (bool) $val['notnull'], + 'default' => $val['dflt_value'], + 'primary' => (bool) $val['pk'], + 'length' => null, + 'scale' => null, + 'precision' => null, + 'unsigned' => null, + 'autoincrement' => (bool) (1 == $val['pk'] && 'integer' == $decl['type'][0]), + ); $columns[$val['name']] = $description; } + return $columns; } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) { - $sql = 'PRAGMA index_list(' . $table . ')'; + $sql = 'PRAGMA index_list('.$table.')'; + return $this->conn->fetchColumn($sql); - } + } + /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) { $sql = "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' " - . "UNION ALL SELECT name FROM sqlite_temp_master " - . "WHERE type = 'table' ORDER BY name"; + .'UNION ALL SELECT name FROM sqlite_temp_master ' + ."WHERE type = 'table' ORDER BY name"; return $this->conn->fetchColumn($sql); } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) { - } /** - * lists table views + * lists table views. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) @@ -207,29 +216,30 @@ public function listTableViews($table) $result = array(); foreach ($views as $row) { - if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) { - if ( ! empty($row['name'])) { + if (preg_match("/^create view .* \\bfrom\\b\\s+\\b{$table}\\b /i", $row['sql'])) { + if (!empty($row['name'])) { $result[$row['name']] = true; } } } + return $result; } /** - * lists database users + * lists database users. * * @return array */ public function listUsers() { - } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) @@ -238,4 +248,4 @@ public function listViews($database = null) return $this->conn->fetchColumn($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Inflector.php b/lib/Doctrine/Inflector.php index 25bb984e2..df86f3625 100644 --- a/lib/Doctrine/Inflector.php +++ b/lib/Doctrine/Inflector.php @@ -20,27 +20,29 @@ */ /** - * Doctrine inflector has static methods for inflecting text + * Doctrine inflector has static methods for inflecting text. * * The methods in these classes are from several different sources collected * across several different php projects and several different authors. The * original author names and emails are not known * - * @package Doctrine - * @subpackage Inflector * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3189 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Inflector { /** - * Convert word in to the format for a Doctrine table name. Converts 'ModelName' to 'model_name' + * Convert word in to the format for a Doctrine table name. Converts 'ModelName' to 'model_name'. + * + * @param string $word Word to tableize * - * @param string $word Word to tableize * @return string $word Tableized word */ public static function tableize($word) @@ -49,9 +51,10 @@ public static function tableize($word) } /** - * Convert a word in to the format for a Doctrine class name. Converts 'table_name' to 'TableName' + * Convert a word in to the format for a Doctrine class name. Converts 'table_name' to 'TableName'. + * + * @param string $word Word to classify * - * @param string $word Word to classify * @return string $word Classified word */ public static function classify($word) @@ -60,196 +63,217 @@ public static function classify($word) if (!isset($cache[$word])) { $word = preg_replace('/[$]/', '', $word); - $classify = preg_replace_callback('~(_?)([-_])([\w])~', array("Doctrine_Inflector", "classifyCallback"), ucfirst(strtolower($word))); + $classify = preg_replace_callback('~(_?)([-_])([\w])~', array('Doctrine_Inflector', 'classifyCallback'), ucfirst(strtolower($word))); $cache[$word] = $classify; } + return $cache[$word]; } /** * Callback function to classify a classname properly. * - * @param array $matches An array of matches from a pcre_replace call - * @return string $string A string with matches 1 and mathces 3 in upper case. + * @param array $matches An array of matches from a pcre_replace call + * + * @return string $string a string with matches 1 and mathces 3 in upper case */ public static function classifyCallback($matches) { - return $matches[1] . strtoupper($matches[3]); + return $matches[1].strtoupper($matches[3]); } /** - * Check if a string has utf7 characters in it + * Check if a string has utf7 characters in it. * * By bmorel at ssi dot fr * - * @param string $string - * @return boolean $bool + * @param string $string + * + * @return bool $bool */ public static function seemsUtf8($string) { - for ($i = 0; $i < strlen($string); $i++) { - if (ord($string[$i]) < 0x80) continue; # 0bbbbbbb - elseif ((ord($string[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb - elseif ((ord($string[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb - elseif ((ord($string[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb - elseif ((ord($string[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb - elseif ((ord($string[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b - else return false; # Does not match any model - for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ? - if ((++$i == strlen($string)) || ((ord($string[$i]) & 0xC0) != 0x80)) - return false; + for ($i = 0; $i < strlen($string); ++$i) { + if (ord($string[$i]) < 0x80) { + continue; + } // 0bbbbbbb + if ((ord($string[$i]) & 0xE0) == 0xC0) { + $n = 1; + } // 110bbbbb + elseif ((ord($string[$i]) & 0xF0) == 0xE0) { + $n = 2; + } // 1110bbbb + elseif ((ord($string[$i]) & 0xF8) == 0xF0) { + $n = 3; + } // 11110bbb + elseif ((ord($string[$i]) & 0xFC) == 0xF8) { + $n = 4; + } // 111110bb + elseif ((ord($string[$i]) & 0xFE) == 0xFC) { + $n = 5; + } // 1111110b + else { + return false; + } // Does not match any model + for ($j = 0; $j < $n; ++$j) { // n bytes matching 10bbbbbb follow ? + if ((++$i == strlen($string)) || ((ord($string[$i]) & 0xC0) != 0x80)) { + return false; + } + } } - } - return true; + + return true; } /** * Remove any illegal characters, accents, etc. * - * @param string $string String to unaccent + * @param string $string String to unaccent + * * @return string $string Unaccented string */ public static function unaccent($string) { - if ( ! preg_match('/[\x80-\xff]/', $string) ) { - return $string; - } + if (!preg_match('/[\x80-\xff]/', $string)) { + return $string; + } if (self::seemsUtf8($string)) { - $chars = array( - // Decompositions for Latin-1 Supplement - chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', - chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', - chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', - chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', - chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', - chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', - chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', - chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', - chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', - chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', - chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', - chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', - chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', - chr(195).chr(159) => 's', chr(195).chr(160) => 'a', - chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', - chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', - chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', - chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', - chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', - chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', - chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', - chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', - chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', - chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', - chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', - chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', - chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', - chr(195).chr(191) => 'y', - // Decompositions for Latin Extended-A - chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', - chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', - chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', - chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', - chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', - chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', - chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', - chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', - chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', - chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', - chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', - chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', - chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', - chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', - chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', - chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', - chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', - chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', - chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', - chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', - chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', - chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', - chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', - chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', - chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', - chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij', - chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', - chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', - chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', - chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', - chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', - chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', - chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', - chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', - chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', - chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', - chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', - chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', - chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', - chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', - chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', - chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe', - chr(197).chr(148) => 'R', chr(197).chr(149) => 'r', - chr(197).chr(150) => 'R', chr(197).chr(151) => 'r', - chr(197).chr(152) => 'R', chr(197).chr(153) => 'r', - chr(197).chr(154) => 'S', chr(197).chr(155) => 's', - chr(197).chr(156) => 'S', chr(197).chr(157) => 's', - chr(197).chr(158) => 'S', chr(197).chr(159) => 's', - chr(197).chr(160) => 'S', chr(197).chr(161) => 's', - chr(197).chr(162) => 'T', chr(197).chr(163) => 't', - chr(197).chr(164) => 'T', chr(197).chr(165) => 't', - chr(197).chr(166) => 'T', chr(197).chr(167) => 't', - chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', - chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', - chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', - chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', - chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', - chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', - chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', - chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', - chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', - chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', - chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', - chr(197).chr(190) => 'z', chr(197).chr(191) => 's', - // Euro Sign - chr(226).chr(130).chr(172) => 'E', - // GBP (Pound) Sign - chr(194).chr(163) => '', - 'Ä' => 'Ae', 'ä' => 'ae', 'Ü' => 'Ue', 'ü' => 'ue', - 'Ö' => 'Oe', 'ö' => 'oe', 'ß' => 'ss', - // Norwegian characters - 'Å'=>'Aa','Æ'=>'Ae','Ø'=>'O','æ'=>'a','ø'=>'o','å'=>'aa' - ); + $chars = array( + // Decompositions for Latin-1 Supplement + chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', + chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', + chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', + chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', + chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', + chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', + chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', + chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', + chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', + chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', + chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', + chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', + chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', + chr(195).chr(159) => 's', chr(195).chr(160) => 'a', + chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', + chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', + chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', + chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', + chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', + chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', + chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', + chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', + chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', + chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', + chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', + chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', + chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', + chr(195).chr(191) => 'y', + // Decompositions for Latin Extended-A + chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', + chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', + chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', + chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', + chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', + chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', + chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', + chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', + chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', + chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', + chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', + chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', + chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', + chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', + chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', + chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', + chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', + chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', + chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', + chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', + chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', + chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', + chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', + chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', + chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', + chr(196).chr(178) => 'IJ', chr(196).chr(179) => 'ij', + chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', + chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', + chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', + chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', + chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', + chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', + chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', + chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', + chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', + chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', + chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', + chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', + chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', + chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', + chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', + chr(197).chr(146) => 'OE', chr(197).chr(147) => 'oe', + chr(197).chr(148) => 'R', chr(197).chr(149) => 'r', + chr(197).chr(150) => 'R', chr(197).chr(151) => 'r', + chr(197).chr(152) => 'R', chr(197).chr(153) => 'r', + chr(197).chr(154) => 'S', chr(197).chr(155) => 's', + chr(197).chr(156) => 'S', chr(197).chr(157) => 's', + chr(197).chr(158) => 'S', chr(197).chr(159) => 's', + chr(197).chr(160) => 'S', chr(197).chr(161) => 's', + chr(197).chr(162) => 'T', chr(197).chr(163) => 't', + chr(197).chr(164) => 'T', chr(197).chr(165) => 't', + chr(197).chr(166) => 'T', chr(197).chr(167) => 't', + chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', + chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', + chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', + chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', + chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', + chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', + chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', + chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', + chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', + chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', + chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', + chr(197).chr(190) => 'z', chr(197).chr(191) => 's', + // Euro Sign + chr(226).chr(130).chr(172) => 'E', + // GBP (Pound) Sign + chr(194).chr(163) => '', + 'Ä' => 'Ae', 'ä' => 'ae', 'Ü' => 'Ue', 'ü' => 'ue', + 'Ö' => 'Oe', 'ö' => 'oe', 'ß' => 'ss', + // Norwegian characters + 'Å' => 'Aa', 'Æ' => 'Ae', 'Ø' => 'O', 'æ' => 'a', 'ø' => 'o', 'å' => 'aa', + ); - $string = strtr($string, $chars); + $string = strtr($string, $chars); } else { - // Assume ISO-8859-1 if not UTF-8 - $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158) - .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194) - .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202) - .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210) - .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218) - .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227) - .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235) - .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243) - .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251) - .chr(252).chr(253).chr(255); + // Assume ISO-8859-1 if not UTF-8 + $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158) + .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194) + .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202) + .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210) + .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218) + .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227) + .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235) + .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243) + .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251) + .chr(252).chr(253).chr(255); - $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy"; + $chars['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'; - $string = strtr($string, $chars['in'], $chars['out']); - $doubleChars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254)); - $doubleChars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); - $string = str_replace($doubleChars['in'], $doubleChars['out'], $string); + $string = strtr($string, $chars['in'], $chars['out']); + $doubleChars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254)); + $doubleChars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); + $string = str_replace($doubleChars['in'], $doubleChars['out'], $string); } return $string; } /** - * Convert any passed string to a url friendly string. Converts 'My first blog post' to 'my-first-blog-post' + * Convert any passed string to a url friendly string. Converts 'My first blog post' to 'my-first-blog-post'. + * + * @param string $text Text to urlize * - * @param string $text Text to urlize * @return string $text Urlized text */ public static function urlize($text) @@ -257,8 +281,7 @@ public static function urlize($text) // Remove all non url friendly characters with the unaccent function $text = self::unaccent($text); - if (function_exists('mb_strtolower')) - { + if (function_exists('mb_strtolower')) { $text = mb_strtolower($text); } else { $text = strtolower($text); @@ -269,10 +292,10 @@ public static function urlize($text) // More stripping. Replace spaces with dashes $text = strtolower(preg_replace('/[^A-Z^a-z^0-9^\/]+/', '-', - preg_replace('/([a-z\d])([A-Z])/', '\1_\2', - preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', - preg_replace('/::/', '/', $text))))); + preg_replace('/([a-z\d])([A-Z])/', '\1_\2', + preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', + preg_replace('/::/', '/', $text))))); return trim($text, '-'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/IntegrityMapper.php b/lib/Doctrine/IntegrityMapper.php index 9680b7eed..75b277032 100644 --- a/lib/Doctrine/IntegrityMapper.php +++ b/lib/Doctrine/IntegrityMapper.php @@ -20,75 +20,69 @@ */ /** - * Doctrine_IntegrityMapper + * Doctrine_IntegrityMapper. * - * @package Doctrine - * @subpackage IntegrityMapper * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ -class Doctrine_IntegrityMapper +class Doctrine_IntegrityMapper { /** - * processDeleteIntegrity - * - * @param Doctrine_Record $record - * @return void + * processDeleteIntegrity. */ public function processDeleteIntegrity(Doctrine_Record $record) { $coll = $this->buildIntegrityRelationQuery($record); - + $this->invokeIntegrityActions($record); } /** - * invokeIntegrityActions - * - * @param Doctrine_Record $record - * @return void + * invokeIntegrityActions. */ public function invokeIntegrityActions(Doctrine_Record $record) { $deleteActions = Doctrine_Manager::getInstance() - ->getDeleteActions($record->getTable()->getComponentName()); - + ->getDeleteActions($record->getTable()->getComponentName()) + ; + foreach ($record->getTable()->getRelations() as $relation) { $componentName = $relation->getTable()->getComponentName(); - - foreach($record->get($relation->getAlias()) as $coll) { - if ( ! ($coll instanceof Doctrine_Collection)) { + + foreach ($record->get($relation->getAlias()) as $coll) { + if (!($coll instanceof Doctrine_Collection)) { $coll = array($coll); } foreach ($coll as $record) { $this->invokeIntegrityActions($record); if (isset($deleteActions[$componentName])) { - if ($deleteActions[$componentName] === 'SET NULL') { + if ('SET NULL' === $deleteActions[$componentName]) { $record->set($relation->getForeign(), null); - } elseif ($deleteActions[$componentName] === 'CASCADE') { + } elseif ('CASCADE' === $deleteActions[$componentName]) { $this->conn->transaction->addDelete($record); } } - } } } } /** - * buildIntegrityRelationQuery - * - * @param Doctrine_Record $record + * buildIntegrityRelationQuery. + * * @return array The result */ public function buildIntegrityRelationQuery(Doctrine_Record $record) { $q = $record->getTable()->createQuery(); - + $aliases = array(); $indexes = array(); @@ -97,19 +91,19 @@ public function buildIntegrityRelationQuery(Doctrine_Record $record) $aliases[$rootAlias] = $root; foreach ((array) $record->getTable()->getIdentifier() as $id) { - $field = $rootAlias . '.' . $id; - $cond[] = $field . ' = ?'; + $field = $rootAlias.'.'.$id; + $cond[] = $field.' = ?'; $fields[] = $field; - $params = $record->get($id); + $params = $record->get($id); } $fields = implode(', ', $fields); $components[] = $root; $this->buildIntegrityRelations($record->getTable(), $aliases, $fields, $indexes, $components); - $q->select($fields)->from($root. ' ' . $rootAlias); + $q->select($fields)->from($root.' '.$rootAlias); foreach ($aliases as $alias => $name) { - $q->leftJoin($rootAlias . '.' . $name . ' ' . $alias); + $q->leftJoin($rootAlias.'.'.$name.' '.$alias); } $q->where(implode(' AND ', $cond)); @@ -117,19 +111,13 @@ public function buildIntegrityRelationQuery(Doctrine_Record $record) } /** - * buildIntegrityRelations - * - * @param Doctrine_Table $table - * @param mixed $aliases - * @param mixed $fields - * @param mixed $indexes - * @param mixed $components - * @return void + * buildIntegrityRelations. */ public function buildIntegrityRelations(Doctrine_Table $table, &$aliases, &$fields, &$indexes, &$components) { $deleteActions = Doctrine_Manager::getInstance() - ->getDeleteActions($table->getComponentName()); + ->getDeleteActions($table->getComponentName()) + ; foreach ($table->getRelations() as $relation) { $componentName = $relation->getTable()->getComponentName(); @@ -140,31 +128,31 @@ public function buildIntegrityRelations(Doctrine_Table $table, &$aliases, &$fiel $alias = strtolower(substr($relation->getAlias(), 0, 1)); - if ( ! isset($indexes[$alias])) { + if (!isset($indexes[$alias])) { $indexes[$alias] = 1; } if (isset($deleteActions[$componentName])) { if (isset($aliases[$alias])) { - $alias = $alias . ++$indexes[$alias]; + $alias = $alias.++$indexes[$alias]; } $aliases[$alias] = $relation->getAlias(); - if ($deleteActions[$componentName] === 'SET NULL') { + if ('SET NULL' === $deleteActions[$componentName]) { if ($relation instanceof Doctrine_Relation_ForeignKey) { foreach ((array) $relation->getForeign() as $foreign) { - $fields .= ', ' . $alias . '.' . $foreign; + $fields .= ', '.$alias.'.'.$foreign; } } elseif ($relation instanceof Doctrine_Relation_LocalKey) { foreach ((array) $relation->getLocal() as $foreign) { - $fields .= ', ' . $alias . '.' . $foreign; + $fields .= ', '.$alias.'.'.$foreign; } } } foreach ((array) $relation->getTable()->getIdentifier() as $id) { - $fields .= ', ' . $alias . '.' . $id; + $fields .= ', '.$alias.'.'.$id; } - if ($deleteActions[$componentName] === 'CASCADE') { + if ('CASCADE' === $deleteActions[$componentName]) { $this->buildIntegrityRelations($relation->getTable(), $aliases, $fields, $indexes, $components); } } diff --git a/lib/Doctrine/Lib.php b/lib/Doctrine/Lib.php index 97d740026..b979cebf1 100644 --- a/lib/Doctrine/Lib.php +++ b/lib/Doctrine/Lib.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Lib has not commonly used static functions, mostly for debugging purposes + * Doctrine_Lib has not commonly used static functions, mostly for debugging purposes. * - * @package Doctrine - * @subpackage Lib * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Lib @@ -37,28 +38,30 @@ class Doctrine_Lib * * This method translates a Doctrine_Record state (integer constant) * in an english string. + * * @see Doctrine_Record::STATE_* constants * - * @param integer $state the state of record - * @return string description of given state + * @param int $state the state of record + * + * @return string description of given state */ public static function getRecordStateAsString($state) { switch ($state) { case Doctrine_Record::STATE_PROXY: - return "proxy"; + return 'proxy'; break; case Doctrine_Record::STATE_CLEAN: - return "persistent clean"; + return 'persistent clean'; break; case Doctrine_Record::STATE_DIRTY: - return "persistent dirty"; + return 'persistent dirty'; break; case Doctrine_Record::STATE_TDIRTY: - return "transient dirty"; + return 'transient dirty'; break; case Doctrine_Record::STATE_TCLEAN: - return "transient clean"; + return 'transient clean'; break; } } @@ -69,21 +72,20 @@ public static function getRecordStateAsString($state) * This method returns an html representation of a given * record, containing keys, state and data. * - * @param Doctrine_Record $record * @return string */ public static function getRecordAsString(Doctrine_Record $record) { $r[] = '
';
-        $r[] = 'Component  : ' . $record->getTable()->getComponentName();
-        $r[] = 'ID         : ' . Doctrine_Core::dump($record->identifier());
-        $r[] = 'References : ' . count($record->getReferences());
-        $r[] = 'State      : ' . Doctrine_Lib::getRecordStateAsString($record->state());
-        $r[] = 'OID        : ' . $record->getOID();
-        $r[] = 'data       : ' . Doctrine_Core::dump($record->getData(), false);
+        $r[] = 'Component  : '.$record->getTable()->getComponentName();
+        $r[] = 'ID         : '.Doctrine_Core::dump($record->identifier());
+        $r[] = 'References : '.count($record->getReferences());
+        $r[] = 'State      : '.Doctrine_Lib::getRecordStateAsString($record->state());
+        $r[] = 'OID        : '.$record->getOID();
+        $r[] = 'data       : '.Doctrine_Core::dump($record->getData(), false);
         $r[] = '
'; - return implode("\n",$r)."
"; + return implode("\n", $r).'
'; } /** @@ -91,21 +93,24 @@ public static function getRecordAsString(Doctrine_Record $record) * * This method translates a Doctrine_Connection state (integer constant) * in a english description. + * * @see Doctrine_Transaction::STATE_* constants - * @param integer $state state of the connection as a string + * + * @param int $state state of the connection as a string + * * @return string */ public static function getConnectionStateAsString($state) { switch ($state) { case Doctrine_Transaction::STATE_SLEEP: - return "open"; + return 'open'; break; case Doctrine_Transaction::STATE_BUSY: - return "busy"; + return 'busy'; break; case Doctrine_Transaction::STATE_ACTIVE: - return "active"; + return 'active'; break; } } @@ -116,20 +121,19 @@ public static function getConnectionStateAsString($state) * This method returns an html dump of a connection, containing state, open * transactions and loaded tables. * - * @param Doctrine_Connection $connection * @return string */ public static function getConnectionAsString(Doctrine_Connection $connection) { $r[] = '
';
         $r[] = 'Doctrine_Connection object';
-        $r[] = 'State               : ' . Doctrine_Lib::getConnectionStateAsString($connection->transaction->getState());
-        $r[] = 'Open Transactions   : ' . $connection->transaction->getTransactionLevel();
-        $r[] = 'Table in memory     : ' . $connection->count();
-        $r[] = 'Driver name         : ' . $connection->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME);
-        $r[] = "
"; + $r[] = 'State : '.Doctrine_Lib::getConnectionStateAsString($connection->transaction->getState()); + $r[] = 'Open Transactions : '.$connection->transaction->getTransactionLevel(); + $r[] = 'Table in memory : '.$connection->count(); + $r[] = 'Driver name : '.$connection->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME); + $r[] = ''; - return implode("\n",$r)."
"; + return implode("\n", $r).'
'; } /** @@ -137,17 +141,17 @@ public static function getConnectionAsString(Doctrine_Connection $connection) * * This method returns an html dump of a table, containing component name * and table physical name. - * @param Doctrine_Table $table + * * @return string */ public static function getTableAsString(Doctrine_Table $table) { - $r[] = "
";
-        $r[] = "Component   : ".$table->getComponentName();
-        $r[] = "Table       : ".$table->getTableName();
-        $r[] = "
"; + $r[] = '
';
+        $r[] = 'Component   : '.$table->getComponentName();
+        $r[] = 'Table       : '.$table->getTableName();
+        $r[] = '
'; - return implode("\n",$r)."
"; + return implode("\n", $r).'
'; } /** @@ -157,29 +161,30 @@ public static function getTableAsString(Doctrine_Table $table) * for visual formatting. * * @todo: What about creating a config varialbe for the color? - * @param string $sql plain text query - * @return string the formatted sql code + * + * @param string $sql plain text query + * + * @return string the formatted sql code */ public static function formatSql($sql) { - $e = explode("\n",$sql); - $color = "367FAC"; + $e = explode("\n", $sql); + $color = '367FAC'; $l = $sql; - $l = str_replace("SELECT ", "SELECT
",$l); - $l = str_replace("FROM ", "FROM
",$l); - $l = str_replace(" LEFT JOIN ", "
LEFT JOIN ",$l); - $l = str_replace(" INNER JOIN ", "
INNER JOIN ",$l); - $l = str_replace(" WHERE ", "
WHERE ",$l); - $l = str_replace(" GROUP BY ", "
GROUP BY ",$l); - $l = str_replace(" HAVING ", "
HAVING ",$l); - $l = str_replace(" AS ", " AS
",$l); - $l = str_replace(" ON ", " ON ",$l); - $l = str_replace(" ORDER BY ", " ORDER BY
",$l); - $l = str_replace(" LIMIT ", " LIMIT
",$l); - $l = str_replace(" OFFSET ", " OFFSET
",$l); - $l = str_replace(" ", "
",$l); - - return $l; + $l = str_replace('SELECT ', "SELECT
", $l); + $l = str_replace('FROM ', "FROM
", $l); + $l = str_replace(' LEFT JOIN ', "
LEFT JOIN ", $l); + $l = str_replace(' INNER JOIN ', "
INNER JOIN ", $l); + $l = str_replace(' WHERE ', "
WHERE ", $l); + $l = str_replace(' GROUP BY ', "
GROUP BY ", $l); + $l = str_replace(' HAVING ', "
HAVING ", $l); + $l = str_replace(' AS ', " AS
", $l); + $l = str_replace(' ON ', " ON ", $l); + $l = str_replace(' ORDER BY ', " ORDER BY
", $l); + $l = str_replace(' LIMIT ', " LIMIT
", $l); + $l = str_replace(' OFFSET ', " OFFSET
", $l); + + return str_replace(' ', '
', $l); } /** @@ -188,18 +193,17 @@ public static function formatSql($sql) * This method returns an html dump of a collection of records, containing * all data. * - * @param Doctrine_Collection $collection * @return string */ public static function getCollectionAsString(Doctrine_Collection $collection) { - $r[] = "
";
+        $r[] = '
';
         $r[] = get_class($collection);
-        $r[] = 'data : ' . Doctrine_Core::dump($collection->getData(), false);
-        //$r[] = 'snapshot : ' . Doctrine_Core::dump($collection->getSnapshot());
-        $r[] = "
"; + $r[] = 'data : '.Doctrine_Core::dump($collection->getData(), false); + // $r[] = 'snapshot : ' . Doctrine_Core::dump($collection->getSnapshot()); + $r[] = '
'; - return implode("\n",$r); + return implode("\n", $r); } // Code from symfony sfToolkit class. See LICENSE @@ -224,52 +228,50 @@ public static function getCollectionAsString(Doctrine_Collection $collection) * Different from array_merge * If string keys have arrays for values, these arrays will merge recursively. */ - public static function arrayDeepMerge() - { - switch (func_num_args()) { - case 0: + public static function arrayDeepMerge() + { + switch (func_num_args()) { + case 0: return false; - case 1: + case 1: return func_get_arg(0); - case 2: + case 2: $args = func_get_args(); $args[2] = array(); - if (is_array($args[0]) && is_array($args[1])) - { - foreach (array_unique(array_merge(array_keys($args[0]),array_keys($args[1]))) as $key) - { + if (is_array($args[0]) && is_array($args[1])) { + foreach (array_unique(array_merge(array_keys($args[0]), array_keys($args[1]))) as $key) { $isKey0 = array_key_exists($key, $args[0]); $isKey1 = array_key_exists($key, $args[1]); - if ($isKey0 && $isKey1 && is_array($args[0][$key]) && is_array($args[1][$key])) - { + if ($isKey0 && $isKey1 && is_array($args[0][$key]) && is_array($args[1][$key])) { $args[2][$key] = self::arrayDeepMerge($args[0][$key], $args[1][$key]); - } else if ($isKey0 && $isKey1) { + } elseif ($isKey0 && $isKey1) { $args[2][$key] = $args[1][$key]; - } else if ( ! $isKey1) { + } elseif (!$isKey1) { $args[2][$key] = $args[0][$key]; - } else if ( ! $isKey0) { + } elseif (!$isKey0) { $args[2][$key] = $args[1][$key]; } } return $args[2]; - } else { - return $args[1]; } + + return $args[1]; + default: $args = func_get_args(); $args[1] = self::arrayDeepMerge($args[0], $args[1]); array_shift($args); return call_user_func_array(array('Doctrine_Lib', 'arrayDeepMerge'), $args); - break; + break; } } /** - * arrayDiffSimple + * arrayDiffSimple. * * array arrayDiffSimple ( array array1 , array array2 ) * @@ -285,19 +287,20 @@ public static function arrayDeepMerge() * * @param array $array1 * @param array $array2 + * * @static - * @access public + * * @return array */ public static function arrayDiffSimple($array1, $array2) { $diff = array(); - foreach($array1 as $key => $val) { - if(!isset($array2[$key])) { + foreach ($array1 as $key => $val) { + if (!isset($array2[$key])) { $diff[$key] = $val; } else { - if(is_array($array2[$key]) && !is_array($val)) { + if (is_array($array2[$key]) && !is_array($val)) { $diff[$key] = $val; } } @@ -313,18 +316,19 @@ public static function arrayDiffSimple($array1, $array2) * that do not exist yet. Equivalent to 'mkdir -p'. * * @param string $path - * @param integer $mode an integer (octal) chmod parameter for the - * created directories - * @return boolean true if succeeded + * @param int $mode an integer (octal) chmod parameter for the + * created directories + * + * @return bool true if succeeded */ public static function makeDirectories($path, $mode = 0777) { - if ( ! $path) { - return false; + if (!$path) { + return false; } if (is_dir($path) || is_file($path)) { - return true; + return true; } return mkdir(trim($path), $mode, true); @@ -337,30 +341,28 @@ public static function makeDirectories($path, $mode = 0777) * Equivalent to 'rm -rf'. * * @param string $folderPath - * @return boolean success of the operation + * + * @return bool success of the operation */ public static function removeDirectories($folderPath) { - if (is_dir($folderPath)) - { - foreach (scandir($folderPath) as $value) - { - if ($value != '.' && $value != '..') - { - $value = $folderPath . "/" . $value; + if (is_dir($folderPath)) { + foreach (scandir($folderPath) as $value) { + if ('.' != $value && '..' != $value) { + $value = $folderPath.'/'.$value; if (is_dir($value)) { self::removeDirectories($value); - } else if (is_file($value)) { + } elseif (is_file($value)) { unlink($value); } } } return rmdir($folderPath); - } else { - return false; } + + return false; } /** @@ -369,9 +371,8 @@ public static function removeDirectories($folderPath) * This method recursively copies all $source files and subdirs in $dest. * If $source is a file, only it will be copied in $dest. * - * @param string $source a directory path - * @param string $dest a directory path - * @return + * @param string $source a directory path + * @param string $dest a directory path */ public static function copyDirectory($source, $dest) { @@ -381,7 +382,7 @@ public static function copyDirectory($source, $dest) } // Make destination directory - if ( ! is_dir($dest)) { + if (!is_dir($dest)) { mkdir($dest); } @@ -389,13 +390,13 @@ public static function copyDirectory($source, $dest) $dir = dir($source); while (false !== $entry = $dir->read()) { // Skip pointers - if ($entry == '.' || $entry == '..') { + if ('.' == $entry || '..' == $entry) { continue; } // Deep copy directories - if ($dest !== "$source/$entry") { - self::copyDirectory("$source/$entry", "$dest/$entry"); + if ($dest !== "{$source}/{$entry}") { + self::copyDirectory("{$source}/{$entry}", "{$dest}/{$entry}"); } } @@ -412,8 +413,7 @@ public static function copyDirectory($source, $dest) * and for Doctrine coding standards. $className must use camel case naming * and underscores for directory separation. * - * @param string $classname - * @return boolean + * @return bool */ public static function isValidClassName($className) { diff --git a/lib/Doctrine/Locator.php b/lib/Doctrine/Locator.php index 8b4d2817f..79c31784a 100644 --- a/lib/Doctrine/Locator.php +++ b/lib/Doctrine/Locator.php @@ -1,6 +1,6 @@ * @author Konsta Vesterinen * @author Eevert Saukkokoski + * * @version $Revision$ + * * @since 1.0 */ class Doctrine_Locator implements Countable, IteratorAggregate { /** - * @var array $_resources an array of bound resources + * @var array an array of bound resources */ protected $_resources = array(); /** - * @var string $_classPrefix the default class prefix + * @var string the default class prefix */ protected $_classPrefix = 'Doctrine_'; /** - * @var array $_instances a pool of this object's instances + * @var array a pool of this object's instances */ protected static $_instances = array(); @@ -54,7 +57,6 @@ class Doctrine_Locator implements Countable, IteratorAggregate * Constructor. Provide an array of resources to set initial contents. * * @param array - * @return void */ public function __construct(array $defaults = null) { @@ -70,7 +72,7 @@ public function __construct(array $defaults = null) } /** - * instance + * instance. * * @return Sensei_Locator */ @@ -79,11 +81,12 @@ public static function instance() if (empty(self::$_instances)) { $obj = new Doctrine_Locator(); } + return current(self::$_instances); } /** - * setClassPrefix + * setClassPrefix. * * @param string $prefix */ @@ -93,7 +96,7 @@ public function setClassPrefix($prefix) } /** - * getClassPrefix + * getClassPrefix. * * @return string */ @@ -104,9 +107,9 @@ public function getClassPrefix() /** * contains - * checks if a resource exists under the given name + * checks if a resource exists under the given name. * - * @return boolean whether or not given resource name exists + * @return bool whether or not given resource name exists */ public function contains($name) { @@ -115,11 +118,12 @@ public function contains($name) /** * bind - * binds a resource to a name + * binds a resource to a name. + * + * @param string $name the name of the resource to bind + * @param mixed $value the value of the resource * - * @param string $name the name of the resource to bind - * @param mixed $value the value of the resource - * @return Sensei_Locator this object + * @return Sensei_Locator this object */ public function bind($name, $value) { @@ -130,55 +134,56 @@ public function bind($name, $value) /** * locate - * locates a resource by given name and returns it + * locates a resource by given name and returns it. + * + * @param string $name the name of the resource * - * @throws Doctrine_Locator_Exception if the resource could not be found - * @param string $name the name of the resource - * @return mixed the located resource + * @return mixed the located resource + * + * @throws Doctrine_Locator_Exception if the resource could not be found */ public function locate($name) { if (isset($this->_resources[$name])) { return $this->_resources[$name]; - } else { - $className = $name; - - if ( ! class_exists($className)) { - - $name = explode('.', $name); - foreach ($name as &$v) { - $v = ucfirst(strtolower($v)); - } - $name = implode('_', $name); - - $className = $this->_classPrefix . $name; + } + $className = $name; - if ( ! class_exists($className)) { - throw new Doctrine_Locator_Exception("Couldn't locate resource " . $className); - } + if (!class_exists($className)) { + $name = explode('.', $name); + foreach ($name as &$v) { + $v = ucfirst(strtolower($v)); } + $name = implode('_', $name); - $this->_resources[$name] = new $className(); + $className = $this->_classPrefix.$name; - if ($this->_resources[$name] instanceof Doctrine_Locator_Injectable) { - $this->_resources[$name]->setLocator($this); + if (!class_exists($className)) { + throw new Doctrine_Locator_Exception("Couldn't locate resource ".$className); } + } - return $this->_resources[$name]; + $this->_resources[$name] = new $className(); + + if ($this->_resources[$name] instanceof Doctrine_Locator_Injectable) { + $this->_resources[$name]->setLocator($this); } - throw new Doctrine_Locator_Exception("Couldn't locate resource " . $name); + return $this->_resources[$name]; + + throw new Doctrine_Locator_Exception("Couldn't locate resource ".$name); } /** * count * returns the number of bound resources associated with - * this object + * this object. * * @see Countable interface - * @return integer the number of resources + * + * @return int the number of resources */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_resources); @@ -187,12 +192,12 @@ public function count() /** * getIterator * returns an ArrayIterator that iterates through all - * bound resources + * bound resources. * - * @return ArrayIterator an iterator for iterating through - * all bound resources + * @return ArrayIterator an iterator for iterating through + * all bound resources */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->_resources); diff --git a/lib/Doctrine/Locator/Exception.php b/lib/Doctrine/Locator/Exception.php index 4a6386032..b3da90965 100644 --- a/lib/Doctrine/Locator/Exception.php +++ b/lib/Doctrine/Locator/Exception.php @@ -20,17 +20,21 @@ */ /** - * Doctrine_Locator_Exception + * Doctrine_Locator_Exception. * - * @package Doctrine - * @subpackage Doctrine_Locator * @category Locator + * * @license http://www.gnu.org/licenses/lgpl.txt LGPL - * @link http://www.doctrine-project.org + * + * @see http://www.doctrine-project.org + * * @author Janne Vanhala * @author Konsta Vesterinen + * * @version $Revision$ + * * @since 1.0 */ class Doctrine_Locator_Exception extends Doctrine_Exception -{ } +{ +} diff --git a/lib/Doctrine/Locator/Injectable.php b/lib/Doctrine/Locator/Injectable.php index b32ccf404..4c5aa0c9d 100644 --- a/lib/Doctrine/Locator/Injectable.php +++ b/lib/Doctrine/Locator/Injectable.php @@ -1,6 +1,6 @@ * @author Konsta Vesterinen * @author Eevert Saukkokoski + * * @version $Revision$ + * * @since 1.0 */ class Doctrine_Locator_Injectable { /** - * @var Doctrine_Locator the locator object + * @var Doctrine_Locator the locator object */ protected $_locator; /** - * @var array an array of bound resources + * @var array an array of bound resources */ protected $_resources = array(); /** - * @var Doctrine_Null $null Doctrine_Null object, used for extremely fast null value checking + * @var Doctrine_Null Doctrine_Null object, used for extremely fast null value checking */ protected static $_null; /** * setLocator - * this method can be used for setting the locator object locally + * this method can be used for setting the locator object locally. * * @param Doctrine_Locator the locator object - * @return Doctrine_Locator_Injectable this instance + * + * @return Doctrine_Locator_Injectable this instance */ public function setLocator(Doctrine_Locator $locator) { $this->_locator = $locator; + return $this; } /** * getLocator - * returns the locator associated with this object + * returns the locator associated with this object. * * if there are no locator locally associated then * this method tries to fetch the current global locator @@ -74,48 +79,51 @@ public function setLocator(Doctrine_Locator $locator) */ public function getLocator() { - if ( ! isset($this->_locator)) { + if (!isset($this->_locator)) { $this->_locator = Doctrine_Locator::instance(); - } + return $this->_locator; } /** * locate - * locates a resource by given name and returns it + * locates a resource by given name and returns it. * * if the resource cannot be found locally this method tries * to use the global locator for finding the resource * * @see Doctrine_Locator::locate() - * @throws Doctrine_Locator_Exception if the resource could not be found - * @param string $name the name of the resource - * @return mixed the located resource + * + * @param string $name the name of the resource + * + * @return mixed the located resource + * + * @throws Doctrine_Locator_Exception if the resource could not be found */ public function locate($name) { if (isset($this->_resources[$name])) { if (is_object($this->_resources[$name])) { return $this->_resources[$name]; - } else { - // get the name of the concrete implementation - $concreteImpl = $this->_resources[$name]; - - return $this->getLocator()->locate($concreteImpl); } - } else { - return $this->getLocator()->locate($name); + // get the name of the concrete implementation + $concreteImpl = $this->_resources[$name]; + + return $this->getLocator()->locate($concreteImpl); } + + return $this->getLocator()->locate($name); } /** * bind - * binds a resource to a name + * binds a resource to a name. * - * @param string $name the name of the resource to bind - * @param mixed $value the value of the resource - * @return static this object + * @param string $name the name of the resource to bind + * @param mixed $value the value of the resource + * + * @return static this object */ public function bind($name, $value) { @@ -126,10 +134,7 @@ public function bind($name, $value) /** * initNullObject - * initializes the null object - * - * @param Doctrine_Null $null - * @return void + * initializes the null object. */ public static function initNullObject(Doctrine_Null $null) { @@ -138,7 +143,7 @@ public static function initNullObject(Doctrine_Null $null) /** * getNullObject - * returns the null object associated with this object + * returns the null object associated with this object. * * @return Doctrine_Null */ diff --git a/lib/Doctrine/Locking/Exception.php b/lib/Doctrine/Locking/Exception.php index ec3bd6123..d3dc3cf9b 100644 --- a/lib/Doctrine/Locking/Exception.php +++ b/lib/Doctrine/Locking/Exception.php @@ -1,6 +1,6 @@ - */ class Doctrine_Locking_Exception extends Doctrine_Exception -{} \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Locking/Manager/Pessimistic.php b/lib/Doctrine/Locking/Manager/Pessimistic.php index 97c772b2e..2da813fa2 100644 --- a/lib/Doctrine/Locking/Manager/Pessimistic.php +++ b/lib/Doctrine/Locking/Manager/Pessimistic.php @@ -24,32 +24,33 @@ * a time-consuming task on a record or many records, which is spread over several * page requests can't be interfered by other users. * - * @package Doctrine - * @subpackage Locking - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @author Roman Borschel * @author Pierre Minnieur * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Locking_Manager_Pessimistic { /** - * The conn that is used by the locking manager + * The conn that is used by the locking manager. * * @var Doctrine_Connection object */ private $conn; /** - * The database table name for the lock tracking + * The database table name for the lock tracking. */ private $_lockTable = 'doctrine_lock_tracking'; /** - * Constructs a new locking manager object + * Constructs a new locking manager object. * * When the CREATE_TABLES attribute of the connection on which the manager * is supposed to work on is set to true, the locking table is created. @@ -62,46 +63,47 @@ public function __construct(Doctrine_Connection $conn) if ($this->conn->getAttribute(Doctrine_Core::ATTR_EXPORT) & Doctrine_Core::EXPORT_TABLES) { $columns = array(); - $columns['object_type'] = array('type' => 'string', - 'length' => 50, - 'notnull' => true, - 'primary' => true); + $columns['object_type'] = array('type' => 'string', + 'length' => 50, + 'notnull' => true, + 'primary' => true); - $columns['object_key'] = array('type' => 'string', - 'length' => 250, - 'notnull' => true, - 'primary' => true); + $columns['object_key'] = array('type' => 'string', + 'length' => 250, + 'notnull' => true, + 'primary' => true); - $columns['user_ident'] = array('type' => 'string', - 'length' => 50, - 'notnull' => true); + $columns['user_ident'] = array('type' => 'string', + 'length' => 50, + 'notnull' => true); - $columns['timestamp_obtained'] = array('type' => 'integer', - 'length' => 10, - 'notnull' => true); + $columns['timestamp_obtained'] = array('type' => 'integer', + 'length' => 10, + 'notnull' => true); $options = array('primary' => array('object_type', 'object_key')); try { $this->conn->export->createTable($this->_lockTable, $columns, $options); - } catch(Exception $e) { - + } catch (Exception $e) { } } } /** - * Obtains a lock on a {@link Doctrine_Record} + * Obtains a lock on a {@link Doctrine_Record}. * - * @param Doctrine_Record $record The record that has to be locked - * @param mixed $userIdent A unique identifier of the locking user - * @return boolean TRUE if the locking was successful, FALSE if another user - * holds a lock on this record - * @throws Doctrine_Locking_Exception If the locking failed due to database errors + * @param Doctrine_Record $record The record that has to be locked + * @param mixed $userIdent A unique identifier of the locking user + * + * @return bool TRUE if the locking was successful, FALSE if another user + * holds a lock on this record + * + * @throws Doctrine_Locking_Exception If the locking failed due to database errors */ public function getLock(Doctrine_Record $record, $userIdent) { $objectType = $record->getTable()->getComponentName(); - $key = $record->getTable()->getIdentifier(); + $key = $record->getTable()->getIdentifier(); $gotLock = false; $time = time(); @@ -115,9 +117,9 @@ public function getLock(Doctrine_Record $record, $userIdent) $dbh = $this->conn->getDbh(); $this->conn->beginTransaction(); - $stmt = $dbh->prepare('INSERT INTO ' . $this->_lockTable - . ' (object_type, object_key, user_ident, timestamp_obtained)' - . ' VALUES (:object_type, :object_key, :user_ident, :ts_obtained)'); + $stmt = $dbh->prepare('INSERT INTO '.$this->_lockTable + .' (object_type, object_key, user_ident, timestamp_obtained)' + .' VALUES (:object_type, :object_key, :user_ident, :ts_obtained)'); $stmt->bindParam(':object_type', $objectType); $stmt->bindParam(':object_key', $key); @@ -128,21 +130,21 @@ public function getLock(Doctrine_Record $record, $userIdent) $stmt->execute(); $gotLock = true; - // we catch an Exception here instead of PDOException since we might also be catching Doctrine_Exception - } catch(Exception $pkviolation) { + // we catch an Exception here instead of PDOException since we might also be catching Doctrine_Exception + } catch (Exception $pkviolation) { // PK violation occured => existing lock! } - if ( ! $gotLock) { + if (!$gotLock) { $lockingUserIdent = $this->_getLockingUserIdent($objectType, $key); - if ($lockingUserIdent !== null && $lockingUserIdent == $userIdent) { + if (null !== $lockingUserIdent && $lockingUserIdent == $userIdent) { $gotLock = true; // The requesting user already has a lock // Update timestamp - $stmt = $dbh->prepare('UPDATE ' . $this->_lockTable - . ' SET timestamp_obtained = :ts' - . ' WHERE object_type = :object_type AND' - . ' object_key = :object_key AND' - . ' user_ident = :user_ident'); + $stmt = $dbh->prepare('UPDATE '.$this->_lockTable + .' SET timestamp_obtained = :ts' + .' WHERE object_type = :object_type AND' + .' object_key = :object_key AND' + .' user_ident = :user_ident'); $stmt->bindParam(':ts', $time); $stmt->bindParam(':object_type', $objectType); $stmt->bindParam(':object_key', $key); @@ -160,17 +162,19 @@ public function getLock(Doctrine_Record $record, $userIdent) } /** - * Releases a lock on a {@link Doctrine_Record} + * Releases a lock on a {@link Doctrine_Record}. + * + * @param Doctrine_Record $record The record for which the lock has to be released + * @param mixed $userIdent The unique identifier of the locking user + * + * @return bool TRUE if a lock was released, FALSE if no lock was released * - * @param Doctrine_Record $record The record for which the lock has to be released - * @param mixed $userIdent The unique identifier of the locking user - * @return boolean TRUE if a lock was released, FALSE if no lock was released * @throws Doctrine_Locking_Exception If the release procedure failed due to database errors */ public function releaseLock(Doctrine_Record $record, $userIdent) { $objectType = $record->getTable()->getComponentName(); - $key = $record->getTable()->getIdentifier(); + $key = $record->getTable()->getIdentifier(); if (is_array($key)) { // Composite key @@ -179,7 +183,7 @@ public function releaseLock(Doctrine_Record $record, $userIdent) try { $dbh = $this->conn->getDbh(); - $stmt = $dbh->prepare("DELETE FROM $this->_lockTable WHERE + $stmt = $dbh->prepare("DELETE FROM {$this->_lockTable} WHERE object_type = :object_type AND object_key = :object_key AND user_ident = :user_ident"); @@ -190,18 +194,20 @@ public function releaseLock(Doctrine_Record $record, $userIdent) $count = $stmt->rowCount(); - return ($count > 0); + return $count > 0; } catch (PDOException $pdoe) { throw new Doctrine_Locking_Exception($pdoe->getMessage()); } } /** - * Gets the unique user identifier of a lock + * Gets the unique user identifier of a lock. + * + * @param string $objectType The type of the object (component name) + * @param mixed $key The unique key of the object. Can be string or array + * + * @return string The unique user identifier for the specified lock * - * @param string $objectType The type of the object (component name) - * @param mixed $key The unique key of the object. Can be string or array - * @return string The unique user identifier for the specified lock * @throws Doctrine_Locking_Exception If the query failed due to database errors */ private function _getLockingUserIdent($objectType, $key) @@ -213,14 +219,14 @@ private function _getLockingUserIdent($objectType, $key) try { $dbh = $this->conn->getDbh(); - $stmt = $dbh->prepare('SELECT user_ident FROM ' . $this->_lockTable - . ' WHERE object_type = :object_type AND object_key = :object_key'); + $stmt = $dbh->prepare('SELECT user_ident FROM '.$this->_lockTable + .' WHERE object_type = :object_type AND object_key = :object_key'); $stmt->bindParam(':object_type', $objectType); $stmt->bindParam(':object_key', $key); $success = $stmt->execute(); - if ( ! $success) { - throw new Doctrine_Locking_Exception("Failed to determine locking user"); + if (!$success) { + throw new Doctrine_Locking_Exception('Failed to determine locking user'); } $userIdent = $stmt->fetchColumn(); @@ -235,25 +241,29 @@ private function _getLockingUserIdent($objectType, $key) * Gets the identifier that identifies the owner of the lock on the given * record. * - * @param Doctrine_Record $lockedRecord The record. - * @return mixed The unique user identifier that identifies the owner of the lock. + * @param Doctrine_Record $lockedRecord the record + * + * @return mixed the unique user identifier that identifies the owner of the lock */ public function getLockOwner($lockedRecord) { $objectType = $lockedRecord->getTable()->getComponentName(); - $key = $lockedRecord->getTable()->getIdentifier(); + $key = $lockedRecord->getTable()->getIdentifier(); + return $this->_getLockingUserIdent($objectType, $key); } /** - * Releases locks older than a defined amount of seconds + * Releases locks older than a defined amount of seconds. * * When called without parameters all locks older than 15 minutes are released. * - * @param integer $age The maximum valid age of locks in seconds - * @param string $objectType The type of the object (component name) - * @param mixed $userIdent The unique identifier of the locking user - * @return integer The number of locks that have been released + * @param int $age The maximum valid age of locks in seconds + * @param string $objectType The type of the object (component name) + * @param mixed $userIdent The unique identifier of the locking user + * + * @return int The number of locks that have been released + * * @throws Doctrine_Locking_Exception If the release process failed due to database errors */ public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = null) @@ -262,9 +272,9 @@ public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = nu try { $dbh = $this->conn->getDbh(); - $stmt = $dbh->prepare('DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age'); + $stmt = $dbh->prepare('DELETE FROM '.$this->_lockTable.' WHERE timestamp_obtained < :age'); $stmt->bindParam(':age', $age); - $query = 'DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age'; + $query = 'DELETE FROM '.$this->_lockTable.' WHERE timestamp_obtained < :age'; if ($objectType) { $query .= ' AND object_type = :object_type'; } @@ -281,9 +291,7 @@ public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = nu } $stmt->execute(); - $count = $stmt->rowCount(); - - return $count; + return $stmt->rowCount(); } catch (PDOException $pdoe) { throw new Doctrine_Locking_Exception($pdoe->getMessage()); } diff --git a/lib/Doctrine/Manager.php b/lib/Doctrine/Manager.php index a2b08944d..f0603c4fe 100644 --- a/lib/Doctrine/Manager.php +++ b/lib/Doctrine/Manager.php @@ -20,84 +20,84 @@ */ /** - * * Doctrine_Manager is the base component of all doctrine based projects. * It opens and keeps track of all connections (database connections). * - * @package Doctrine - * @subpackage Manager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Manager extends Doctrine_Configurable implements Countable, IteratorAggregate { /** - * @var array $connections an array containing all the opened connections + * @var array an array containing all the opened connections */ - protected $_connections = array(); + protected $_connections = array(); /** - * @var array $bound an array containing all components that have a bound connection + * @var array an array containing all components that have a bound connection */ - protected $_bound = array(); + protected $_bound = array(); /** - * @var integer $index the incremented index + * @var int the incremented index */ - protected $_index = 0; + protected $_index = 0; /** - * @var integer $currIndex the current connection index + * @var int the current connection index */ - protected $_currIndex = 0; + protected $_currIndex = 0; /** - * @var Doctrine_Query_Registry the query registry + * @var Doctrine_Query_Registry the query registry */ protected $_queryRegistry; /** - * @var array Array of registered validators + * @var array Array of registered validators */ protected $_validators = array(); /** - * @var array Array of registered hydrators + * @var array Array of registered hydrators */ protected $_hydrators = array( - Doctrine_Core::HYDRATE_ARRAY => 'Doctrine_Hydrator_ArrayDriver', - Doctrine_Core::HYDRATE_RECORD => 'Doctrine_Hydrator_RecordDriver', - Doctrine_Core::HYDRATE_NONE => 'Doctrine_Hydrator_NoneDriver', - Doctrine_Core::HYDRATE_SCALAR => 'Doctrine_Hydrator_ScalarDriver', - Doctrine_Core::HYDRATE_SINGLE_SCALAR => 'Doctrine_Hydrator_SingleScalarDriver', - Doctrine_Core::HYDRATE_ON_DEMAND => 'Doctrine_Hydrator_RecordDriver', - Doctrine_Core::HYDRATE_ARRAY_HIERARCHY => 'Doctrine_Hydrator_ArrayHierarchyDriver', + Doctrine_Core::HYDRATE_ARRAY => 'Doctrine_Hydrator_ArrayDriver', + Doctrine_Core::HYDRATE_RECORD => 'Doctrine_Hydrator_RecordDriver', + Doctrine_Core::HYDRATE_NONE => 'Doctrine_Hydrator_NoneDriver', + Doctrine_Core::HYDRATE_SCALAR => 'Doctrine_Hydrator_ScalarDriver', + Doctrine_Core::HYDRATE_SINGLE_SCALAR => 'Doctrine_Hydrator_SingleScalarDriver', + Doctrine_Core::HYDRATE_ON_DEMAND => 'Doctrine_Hydrator_RecordDriver', + Doctrine_Core::HYDRATE_ARRAY_HIERARCHY => 'Doctrine_Hydrator_ArrayHierarchyDriver', Doctrine_Core::HYDRATE_RECORD_HIERARCHY => 'Doctrine_Hydrator_RecordHierarchyDriver', - Doctrine_Core::HYDRATE_ARRAY_SHALLOW => 'Doctrine_Hydrator_ArrayShallowDriver', + Doctrine_Core::HYDRATE_ARRAY_SHALLOW => 'Doctrine_Hydrator_ArrayShallowDriver', ); protected $_connectionDrivers = array( - 'db2' => 'Doctrine_Connection_Db2', - 'mysql' => 'Doctrine_Connection_Mysql', - 'mysqli' => 'Doctrine_Connection_Mysql', - 'sqlite' => 'Doctrine_Connection_Sqlite', - 'pgsql' => 'Doctrine_Connection_Pgsql', - 'oci' => 'Doctrine_Connection_Oracle', - 'oci8' => 'Doctrine_Connection_Oracle', - 'oracle' => 'Doctrine_Connection_Oracle', - 'mssql' => 'Doctrine_Connection_Mssql', - 'dblib' => 'Doctrine_Connection_Mssql', - 'odbc' => 'Doctrine_Connection_Mssql', - 'mock' => 'Doctrine_Connection_Mock' + 'db2' => 'Doctrine_Connection_Db2', + 'mysql' => 'Doctrine_Connection_Mysql', + 'mysqli' => 'Doctrine_Connection_Mysql', + 'sqlite' => 'Doctrine_Connection_Sqlite', + 'pgsql' => 'Doctrine_Connection_Pgsql', + 'oci' => 'Doctrine_Connection_Oracle', + 'oci8' => 'Doctrine_Connection_Oracle', + 'oracle' => 'Doctrine_Connection_Oracle', + 'mssql' => 'Doctrine_Connection_Mssql', + 'dblib' => 'Doctrine_Connection_Mssql', + 'odbc' => 'Doctrine_Connection_Mssql', + 'mock' => 'Doctrine_Connection_Mock', ); protected $_extensions = array(); /** - * @var boolean Whether or not the default validators have been loaded + * @var bool Whether or not the default validators have been loaded */ protected $_loadedDefaultValidators = false; @@ -106,13 +106,13 @@ class Doctrine_Manager extends Doctrine_Configurable implements Countable, Itera private $_initialized = false; /** - * constructor + * constructor. * * this is private constructor (use getInstance to get an instance of this class) */ private function __construct() { - $null = new Doctrine_Null; + $null = new Doctrine_Null(); Doctrine_Locator_Injectable::initNullObject($null); Doctrine_Record_Iterator::initNullObject($null); } @@ -124,77 +124,78 @@ private function __construct() * instance. It is idempotent and can only be called one time. Subsequent * calls does not alter the attribute values. * - * @return boolean true if inizialization was executed + * @return bool true if inizialization was executed */ public function setDefaultAttributes() { - if ( ! $this->_initialized) { + if (!$this->_initialized) { $this->_initialized = true; $attributes = array( - Doctrine_Core::ATTR_CACHE => null, - Doctrine_Core::ATTR_RESULT_CACHE => null, - Doctrine_Core::ATTR_QUERY_CACHE => null, - Doctrine_Core::ATTR_TABLE_CACHE => null, - Doctrine_Core::ATTR_LOAD_REFERENCES => true, - Doctrine_Core::ATTR_LISTENER => new Doctrine_EventListener(), - Doctrine_Core::ATTR_RECORD_LISTENER => new Doctrine_Record_Listener(), - Doctrine_Core::ATTR_THROW_EXCEPTIONS => true, - Doctrine_Core::ATTR_VALIDATE => Doctrine_Core::VALIDATE_NONE, - Doctrine_Core::ATTR_QUERY_LIMIT => Doctrine_Core::LIMIT_RECORDS, - Doctrine_Core::ATTR_IDXNAME_FORMAT => "%s_idx", - Doctrine_Core::ATTR_SEQNAME_FORMAT => "%s_seq", - Doctrine_Core::ATTR_TBLNAME_FORMAT => "%s", - Doctrine_Core::ATTR_FKNAME_FORMAT => "%s", - Doctrine_Core::ATTR_QUOTE_IDENTIFIER => false, - Doctrine_Core::ATTR_SEQCOL_NAME => 'id', - Doctrine_Core::ATTR_PORTABILITY => Doctrine_Core::PORTABILITY_NONE, - Doctrine_Core::ATTR_EXPORT => Doctrine_Core::EXPORT_ALL, - Doctrine_Core::ATTR_DECIMAL_PLACES => 2, - Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE => 'doctrine', - Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES => false, - Doctrine_Core::ATTR_USE_DQL_CALLBACKS => false, - Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE => false, - Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS => false, - Doctrine_Core::ATTR_DEFAULT_IDENTIFIER_OPTIONS => array(), - Doctrine_Core::ATTR_DEFAULT_COLUMN_OPTIONS => array(), - Doctrine_Core::ATTR_HYDRATE_OVERWRITE => true, - Doctrine_Core::ATTR_QUERY_CLASS => 'Doctrine_Query', - Doctrine_Core::ATTR_COLLECTION_CLASS => 'Doctrine_Collection', - Doctrine_Core::ATTR_TABLE_CLASS => 'Doctrine_Table', - Doctrine_Core::ATTR_CASCADE_SAVES => true, - Doctrine_Core::ATTR_TABLE_CLASS_FORMAT => '%sTable', - Doctrine_Core::ATTR_USE_TABLE_REPOSITORY => true, - Doctrine_Core::ATTR_USE_TABLE_IDENTITY_MAP => true, - ); + Doctrine_Core::ATTR_CACHE => null, + Doctrine_Core::ATTR_RESULT_CACHE => null, + Doctrine_Core::ATTR_QUERY_CACHE => null, + Doctrine_Core::ATTR_TABLE_CACHE => null, + Doctrine_Core::ATTR_LOAD_REFERENCES => true, + Doctrine_Core::ATTR_LISTENER => new Doctrine_EventListener(), + Doctrine_Core::ATTR_RECORD_LISTENER => new Doctrine_Record_Listener(), + Doctrine_Core::ATTR_THROW_EXCEPTIONS => true, + Doctrine_Core::ATTR_VALIDATE => Doctrine_Core::VALIDATE_NONE, + Doctrine_Core::ATTR_QUERY_LIMIT => Doctrine_Core::LIMIT_RECORDS, + Doctrine_Core::ATTR_IDXNAME_FORMAT => '%s_idx', + Doctrine_Core::ATTR_SEQNAME_FORMAT => '%s_seq', + Doctrine_Core::ATTR_TBLNAME_FORMAT => '%s', + Doctrine_Core::ATTR_FKNAME_FORMAT => '%s', + Doctrine_Core::ATTR_QUOTE_IDENTIFIER => false, + Doctrine_Core::ATTR_SEQCOL_NAME => 'id', + Doctrine_Core::ATTR_PORTABILITY => Doctrine_Core::PORTABILITY_NONE, + Doctrine_Core::ATTR_EXPORT => Doctrine_Core::EXPORT_ALL, + Doctrine_Core::ATTR_DECIMAL_PLACES => 2, + Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE => 'doctrine', + Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES => false, + Doctrine_Core::ATTR_USE_DQL_CALLBACKS => false, + Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE => false, + Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS => false, + Doctrine_Core::ATTR_DEFAULT_IDENTIFIER_OPTIONS => array(), + Doctrine_Core::ATTR_DEFAULT_COLUMN_OPTIONS => array(), + Doctrine_Core::ATTR_HYDRATE_OVERWRITE => true, + Doctrine_Core::ATTR_QUERY_CLASS => 'Doctrine_Query', + Doctrine_Core::ATTR_COLLECTION_CLASS => 'Doctrine_Collection', + Doctrine_Core::ATTR_TABLE_CLASS => 'Doctrine_Table', + Doctrine_Core::ATTR_CASCADE_SAVES => true, + Doctrine_Core::ATTR_TABLE_CLASS_FORMAT => '%sTable', + Doctrine_Core::ATTR_USE_TABLE_REPOSITORY => true, + Doctrine_Core::ATTR_USE_TABLE_IDENTITY_MAP => true, + ); foreach ($attributes as $attribute => $value) { $old = $this->getAttribute($attribute); - if ($old === null) { - $this->setAttribute($attribute,$value); + if (null === $old) { + $this->setAttribute($attribute, $value); } } + return true; } + return false; } /** * Returns an instance of this class - * (this class uses the singleton pattern) + * (this class uses the singleton pattern). * * @return Doctrine_Manager */ public static function getInstance() { - if ( ! isset(self::$_instance)) { + if (!isset(self::$_instance)) { self::$_instance = new self(); } + return self::$_instance; } /** - * Reset the internal static instance - * - * @return void + * Reset the internal static instance. */ public static function resetInstance() { @@ -205,9 +206,7 @@ public static function resetInstance() } /** - * Reset this instance of the manager - * - * @return void + * Reset this instance of the manager. */ public function reset() { @@ -226,22 +225,23 @@ public function reset() } /** - * Lazy-initializes the query registry object and returns it + * Lazy-initializes the query registry object and returns it. * * @return Doctrine_Query_Registry */ public function getQueryRegistry() { - if ( ! isset($this->_queryRegistry)) { - $this->_queryRegistry = new Doctrine_Query_Registry(); - } + if (!isset($this->_queryRegistry)) { + $this->_queryRegistry = new Doctrine_Query_Registry(); + } + return $this->_queryRegistry; } /** - * Sets the query registry + * Sets the query registry. * - * @return Doctrine_Manager this object + * @return Doctrine_Manager this object */ public function setQueryRegistry(Doctrine_Query_Registry $registry) { @@ -252,56 +252,60 @@ public function setQueryRegistry(Doctrine_Query_Registry $registry) /** * Open a new connection. If the adapter parameter is set this method acts as - * a short cut for Doctrine_Manager::getInstance()->openConnection($adapter, $name); + * a short cut for Doctrine_Manager::getInstance()->openConnection($adapter, $name);. * * if the adapter paramater is not set this method acts as * a short cut for Doctrine_Manager::getInstance()->getCurrentConnection() * - * @param PDO|Doctrine_Adapter_Interface $adapter database driver - * @param string $name name of the connection, if empty numeric key is used - * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name + * @param PDO|Doctrine_Adapter_Interface $adapter database driver + * @param string $name name of the connection, if empty numeric key is used + * * @return Doctrine_Connection + * + * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name */ public static function connection($adapter = null, $name = null) { - if ($adapter == null) { + if (null == $adapter) { return Doctrine_Manager::getInstance()->getCurrentConnection(); - } else { - return Doctrine_Manager::getInstance()->openConnection($adapter, $name); } + + return Doctrine_Manager::getInstance()->openConnection($adapter, $name); } /** - * Opens a new connection and saves it to Doctrine_Manager->connections + * Opens a new connection and saves it to Doctrine_Manager->connections. + * + * @param PDO|Doctrine_Adapter_Interface $adapter database driver + * @param string $name name of the connection, if empty numeric key is used * - * @param PDO|Doctrine_Adapter_Interface $adapter database driver - * @param string $name name of the connection, if empty numeric key is used - * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name - * @throws Doctrine_Manager_Exception if trying to open connection for unknown driver * @return Doctrine_Connection + * + * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name + * @throws Doctrine_Manager_Exception if trying to open connection for unknown driver */ public function openConnection($adapter, $name = null, $setCurrent = true) { if (is_object($adapter)) { - if ( ! ($adapter instanceof PDO) && ! in_array('Doctrine_Adapter_Interface', class_implements($adapter))) { - throw new Doctrine_Manager_Exception("First argument should be an instance of PDO or implement Doctrine_Adapter_Interface"); + if (!($adapter instanceof PDO) && !in_array('Doctrine_Adapter_Interface', class_implements($adapter))) { + throw new Doctrine_Manager_Exception('First argument should be an instance of PDO or implement Doctrine_Adapter_Interface'); } $driverName = $adapter->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME); - } else if (is_array($adapter)) { - if ( ! isset($adapter[0])) { + } elseif (is_array($adapter)) { + if (!isset($adapter[0])) { throw new Doctrine_Manager_Exception('Empty data source name given.'); } $e = explode(':', $adapter[0]); - if ($e[0] == 'uri') { + if ('uri' == $e[0]) { $e[0] = 'odbc'; } - $parts['dsn'] = $adapter[0]; + $parts['dsn'] = $adapter[0]; $parts['scheme'] = $e[0]; - $parts['user'] = (isset($adapter[1])) ? $adapter[1] : null; - $parts['pass'] = (isset($adapter[2])) ? $adapter[2] : null; + $parts['user'] = (isset($adapter[1])) ? $adapter[1] : null; + $parts['pass'] = (isset($adapter[2])) ? $adapter[2] : null; $driverName = $e[0]; $adapter = $parts; } else { @@ -313,28 +317,29 @@ public function openConnection($adapter, $name = null, $setCurrent = true) // Decode adapter information if (is_array($adapter)) { foreach ($adapter as $key => $value) { - $adapter[$key] = $value ? urldecode($value):null; + $adapter[$key] = $value ? urldecode($value) : null; } } // initialize the default attributes $this->setDefaultAttributes(); - if ($name !== null) { + if (null !== $name) { $name = (string) $name; if (isset($this->_connections[$name])) { if ($setCurrent) { $this->_currIndex = $name; } + return $this->_connections[$name]; } } else { $name = $this->_index; - $this->_index++; + ++$this->_index; } - if ( ! isset($this->_connectionDrivers[$driverName])) { - throw new Doctrine_Manager_Exception('Unknown driver ' . $driverName); + if (!isset($this->_connectionDrivers[$driverName])) { + throw new Doctrine_Manager_Exception('Unknown driver '.$driverName); } $className = $this->_connectionDrivers[$driverName]; @@ -346,14 +351,17 @@ public function openConnection($adapter, $name = null, $setCurrent = true) if ($setCurrent) { $this->_currIndex = $name; } + return $this->_connections[$name]; } /** - * Parse a pdo style dsn in to an array of parts + * Parse a pdo style dsn in to an array of parts. * * @param array $dsn An array of dsn information + * * @return array The array parsed + * * @todo package:dbal */ public function parsePdoDsn($dsn) @@ -363,7 +371,7 @@ public function parsePdoDsn($dsn) $names = array('dsn', 'scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment', 'unix_socket'); foreach ($names as $name) { - if ( ! isset($parts[$name])) { + if (!isset($parts[$name])) { $parts[$name] = null; } } @@ -377,9 +385,8 @@ public function parsePdoDsn($dsn) if ($string) { $e2 = explode('=', $string); - if (isset($e2[0]) && isset($e2[1])) { - if (count($e2) > 2) - { + if (isset($e2[0], $e2[1])) { + if (count($e2) > 2) { $key = $e2[0]; unset($e2[0]); $value = implode('=', $e2); @@ -395,35 +402,37 @@ public function parsePdoDsn($dsn) } /** - * Build the blank dsn parts array used with parseDsn() + * Build the blank dsn parts array used with parseDsn(). * * @see parseDsn() + * * @param string $dsn + * * @return array $parts */ protected function _buildDsnPartsArray($dsn) { // fix sqlite dsn so that it will parse correctly - $dsn = str_replace("////", "/", $dsn); - $dsn = str_replace("\\", "/", $dsn); - $dsn = preg_replace("/\/\/\/(.*):\//", "//$1:/", $dsn); + $dsn = str_replace('////', '/', $dsn); + $dsn = str_replace('\\', '/', $dsn); + $dsn = preg_replace('/\\/\\/\\/(.*):\\//', '//$1:/', $dsn); // silence any warnings $parts = @parse_url($dsn); - if ($parts === false) { + if (false === $parts) { $parts = array(); } $names = array('dsn', 'scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment'); foreach ($names as $name) { - if ( ! isset($parts[$name])) { + if (!isset($parts[$name])) { $parts[$name] = null; } } - if (count($parts) == 0 || ! isset($parts['scheme'])) { + if (0 == count($parts) || !isset($parts['scheme'])) { throw new Doctrine_Manager_Exception('Could not parse dsn'); } @@ -431,10 +440,12 @@ protected function _buildDsnPartsArray($dsn) } /** - * Parse a Doctrine style dsn string in to an array of parts + * Parse a Doctrine style dsn string in to an array of parts. * * @param string $dsn + * * @return array Parsed contents of DSN + * * @todo package:dbal */ public function parseDsn($dsn) @@ -445,36 +456,36 @@ public function parseDsn($dsn) case 'sqlite': case 'sqlite2': case 'sqlite3': - if (isset($parts['host']) && $parts['host'] == ':memory') { + if (isset($parts['host']) && ':memory' == $parts['host']) { $parts['database'] = ':memory:'; - $parts['dsn'] = 'sqlite::memory:'; + $parts['dsn'] = 'sqlite::memory:'; } else { - //fix windows dsn we have to add host: to path and set host to null + // fix windows dsn we have to add host: to path and set host to null if (isset($parts['host'])) { - $parts['path'] = $parts['host'] . ":" . $parts["path"]; + $parts['path'] = $parts['host'].':'.$parts['path']; $parts['host'] = null; } $parts['database'] = $parts['path']; - $parts['dsn'] = $parts['scheme'] . ':' . $parts['path']; + $parts['dsn'] = $parts['scheme'].':'.$parts['path']; } break; case 'mssql': case 'dblib': - if ( ! isset($parts['path']) || $parts['path'] == '/') { + if (!isset($parts['path']) || '/' == $parts['path']) { throw new Doctrine_Manager_Exception('No database available in data source name'); } if (isset($parts['path'])) { $parts['database'] = substr($parts['path'], 1); } - if ( ! isset($parts['host'])) { + if (!isset($parts['host'])) { throw new Doctrine_Manager_Exception('No hostname set in data source name'); } - $parts['dsn'] = $parts['scheme'] . ':host=' - . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port']:null) . ';dbname=' - . $parts['database']; + $parts['dsn'] = $parts['scheme'].':host=' + .$parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : null).';dbname=' + .$parts['database']; break; @@ -485,19 +496,19 @@ public function parseDsn($dsn) case 'odbc': case 'mock': case 'oracle': - if ( ! isset($parts['path']) || $parts['path'] == '/') { + if (!isset($parts['path']) || '/' == $parts['path']) { throw new Doctrine_Manager_Exception('No database available in data source name'); } if (isset($parts['path'])) { $parts['database'] = substr($parts['path'], 1); } - if ( ! isset($parts['host'])) { + if (!isset($parts['host'])) { throw new Doctrine_Manager_Exception('No hostname set in data source name'); } - $parts['dsn'] = $parts['scheme'] . ':host=' - . $parts['host'] . (isset($parts['port']) ? ';port=' . $parts['port']:null) . ';dbname=' - . $parts['database']; + $parts['dsn'] = $parts['scheme'].':host=' + .$parts['host'].(isset($parts['port']) ? ';port='.$parts['port'] : null).';dbname=' + .$parts['database']; break; default: @@ -508,26 +519,29 @@ public function parseDsn($dsn) } /** - * Get the connection instance for the passed name + * Get the connection instance for the passed name. + * + * @param string $name name of the connection, if empty numeric key is used * - * @param string $name name of the connection, if empty numeric key is used * @return Doctrine_Connection - * @throws Doctrine_Manager_Exception if trying to get a non-existent connection + * + * @throws Doctrine_Manager_Exception if trying to get a non-existent connection */ public function getConnection($name) { - if ( ! isset($this->_connections[$name])) { - throw new Doctrine_Manager_Exception('Unknown connection: ' . $name); + if (!isset($this->_connections[$name])) { + throw new Doctrine_Manager_Exception('Unknown connection: '.$name); } return $this->_connections[$name]; } /** - * Get the name of the passed connection instance + * Get the name of the passed connection instance. + * + * @param Doctrine_Connection $conn connection object to be searched for * - * @param Doctrine_Connection $conn connection object to be searched for - * @return string the name of the connection + * @return string the name of the connection */ public function getConnectionName(Doctrine_Connection $conn) { @@ -537,11 +551,12 @@ public function getConnectionName(Doctrine_Connection $conn) /** * Binds given component to given connection * this means that when ever the given component uses a connection - * it will be using the bound connection instead of the current connection + * it will be using the bound connection instead of the current connection. * * @param string $componentName * @param string $connectionName - * @return boolean + * + * @return bool */ public function bindComponent($componentName, $connectionName) { @@ -549,9 +564,10 @@ public function bindComponent($componentName, $connectionName) } /** - * Get the connection instance for the specified component + * Get the connection instance for the specified component. * * @param string $componentName + * * @return Doctrine_Connection */ public function getConnectionForComponent($componentName) @@ -566,10 +582,11 @@ public function getConnectionForComponent($componentName) } /** - * Check if a component is bound to a connection + * Check if a component is bound to a connection. * * @param string $componentName - * @return boolean + * + * @return bool */ public function hasConnectionForComponent($componentName = null) { @@ -577,10 +594,7 @@ public function hasConnectionForComponent($componentName = null) } /** - * Closes the specified connection - * - * @param Doctrine_Connection $connection - * @return void + * Closes the specified connection. */ public function closeConnection(Doctrine_Connection $connection) { @@ -588,12 +602,12 @@ public function closeConnection(Doctrine_Connection $connection) $key = array_search($connection, $this->_connections, true); - if ($key !== false) { + if (false !== $key) { unset($this->_connections[$key]); if ($key === $this->_currIndex) { $key = key($this->_connections); - $this->_currIndex = ($key !== null) ? $key : 0; + $this->_currIndex = (null !== $key) ? $key : 0; } } @@ -601,7 +615,7 @@ public function closeConnection(Doctrine_Connection $connection) } /** - * Returns all opened connections + * Returns all opened connections. * * @return array */ @@ -611,26 +625,27 @@ public function getConnections() } /** - * Sets the current connection to $key + * Sets the current connection to $key. + * + * @param mixed $key the connection key * - * @param mixed $key the connection key * @throws Doctrine_Manager_Exception - * @return void */ public function setCurrentConnection($key) { $key = (string) $key; - if ( ! isset($this->_connections[$key])) { - throw new Doctrine_Manager_Exception("Connection key '$key' does not exist."); + if (!isset($this->_connections[$key])) { + throw new Doctrine_Manager_Exception("Connection key '{$key}' does not exist."); } $this->_currIndex = $key; } /** - * Whether or not the manager contains specified connection + * Whether or not the manager contains specified connection. + * + * @param mixed $key the connection key * - * @param mixed $key the connection key - * @return boolean + * @return bool */ public function contains($key) { @@ -638,57 +653,59 @@ public function contains($key) } /** - * Returns the number of opened connections + * Returns the number of opened connections. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_connections); } /** - * Returns an ArrayIterator that iterates through all connections + * Returns an ArrayIterator that iterates through all connections. * * @return ArrayIterator */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->_connections); } /** - * Get the current connection instance + * Get the current connection instance. * - * @throws Doctrine_Connection_Exception if there are no open connections * @return Doctrine_Connection + * + * @throws Doctrine_Connection_Exception if there are no open connections */ public function getCurrentConnection() { $i = $this->_currIndex; - if ( ! isset($this->_connections[$i])) { + if (!isset($this->_connections[$i])) { throw new Doctrine_Connection_Exception('There is no open connection'); } + return $this->_connections[$i]; } /** - * Creates databases for all existing connections + * Creates databases for all existing connections. * * @param string $specifiedConnections Array of connections you wish to create the database for - * @return void + * * @todo package:dbal */ public function createDatabases($specifiedConnections = array()) { - if ( ! is_array($specifiedConnections)) { + if (!is_array($specifiedConnections)) { $specifiedConnections = (array) $specifiedConnections; } foreach ($this as $name => $connection) { - if ( ! empty($specifiedConnections) && ! in_array($name, $specifiedConnections)) { + if (!empty($specifiedConnections) && !in_array($name, $specifiedConnections)) { continue; } @@ -697,20 +714,20 @@ public function createDatabases($specifiedConnections = array()) } /** - * Drops databases for all existing connections + * Drops databases for all existing connections. * * @param string $specifiedConnections Array of connections you wish to drop the database for - * @return void + * * @todo package:dbal */ public function dropDatabases($specifiedConnections = array()) { - if ( ! is_array($specifiedConnections)) { + if (!is_array($specifiedConnections)) { $specifiedConnections = (array) $specifiedConnections; } foreach ($this as $name => $connection) { - if ( ! empty($specifiedConnections) && ! in_array($name, $specifiedConnections)) { + if (!empty($specifiedConnections) && !in_array($name, $specifiedConnections)) { continue; } @@ -719,27 +736,28 @@ public function dropDatabases($specifiedConnections = array()) } /** - * Returns a string representation of this object + * Returns a string representation of this object. * * @return string */ public function __toString() { - $r[] = "
";
-        $r[] = "Doctrine_Manager";
-        $r[] = "Connections : ".count($this->_connections);
-        $r[] = "
"; - return implode("\n",$r); + $r[] = '
';
+        $r[] = 'Doctrine_Manager';
+        $r[] = 'Connections : '.count($this->_connections);
+        $r[] = '
'; + + return implode("\n", $r); } /** - * Get available doctrine validators + * Get available doctrine validators. * * @return array $validators */ public function getValidators() { - if ( ! $this->_loadedDefaultValidators) { + if (!$this->_loadedDefaultValidators) { $this->_loadedDefaultValidators = true; $this->registerValidators(array( @@ -773,25 +791,22 @@ public function getValidators() } /** - * Register validators so that Doctrine is aware of them + * Register validators so that Doctrine is aware of them. * - * @param mixed $validators Name of validator or array of validators - * @return void + * @param mixed $validators Name of validator or array of validators */ public function registerValidators($validators) { $validators = (array) $validators; foreach ($validators as $validator) { - if ( ! in_array($validator, $this->_validators)) { + if (!in_array($validator, $this->_validators)) { $this->_validators[] = $validator; } } } /** - * Register a new driver for hydration - * - * @return void + * Register a new driver for hydration. */ public function registerHydrator($name, $class) { @@ -799,7 +814,7 @@ public function registerHydrator($name, $class) } /** - * Get all registered hydrators + * Get all registered hydrators. * * @return array $hydrators */ @@ -809,9 +824,7 @@ public function getHydrators() } /** - * Register a custom connection driver - * - * @return void + * Register a custom connection driver. */ public function registerConnectionDriver($name, $class) { @@ -819,7 +832,7 @@ public function registerConnectionDriver($name, $class) } /** - * Get all the available connection drivers + * Get all the available connection drivers. * * @return array $connectionDrivers */ @@ -829,22 +842,21 @@ public function getConnectionDrivers() } /** - * Register a Doctrine extension for extensionsAutoload() method + * Register a Doctrine extension for extensionsAutoload() method. * * @param string $name * @param string $path - * @return void */ public function registerExtension($name, $path = null) { if (is_null($path)) { - $path = Doctrine_Core::getExtensionsPath() . '/' . $name . '/lib'; + $path = Doctrine_Core::getExtensionsPath().'/'.$name.'/lib'; } $this->_extensions[$name] = $path; } /** - * Get all registered Doctrine extensions + * Get all registered Doctrine extensions. * * @return $extensions */ diff --git a/lib/Doctrine/Manager/Exception.php b/lib/Doctrine/Manager/Exception.php index 461598a2d..8ad0680f6 100644 --- a/lib/Doctrine/Manager/Exception.php +++ b/lib/Doctrine/Manager/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Manager_Exception + * Doctrine_Manager_Exception. * - * @package Doctrine - * @subpackage Manager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Manager_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Migration.php b/lib/Doctrine/Migration.php index 0208ce540..ebcbd51f3 100644 --- a/lib/Doctrine/Migration.php +++ b/lib/Doctrine/Migration.php @@ -20,39 +20,39 @@ */ /** - * Doctrine_Migration + * Doctrine_Migration. * * this class represents a database view * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Migration { - protected $_migrationTableName = 'migration_version', - $_migrationTableCreated = false, - $_connection, - $_migrationClassesDirectory = array(), - $_migrationClasses = array(), - $_reflectionClass, - $_errors = array(), - $_process; + protected $_migrationTableName = 'migration_version'; + protected $_migrationTableCreated = false; + protected $_connection; + protected $_migrationClassesDirectory = array(); + protected $_migrationClasses = array(); + protected $_reflectionClass; + protected $_errors = array(); + protected $_process; protected static $_migrationClassesForDirectories = array(); /** * Specify the path to the directory with the migration classes. * The classes will be loaded and the migration table will be created if it - * does not already exist + * does not already exist. * - * @param string $directory The path to your migrations directory - * @param mixed $connection The connection name or instance to use for this migration - * @return void + * @param string $directory The path to your migrations directory + * @param mixed $connection The connection name or instance to use for this migration */ public function __construct($directory = null, $connection = null) { @@ -63,7 +63,8 @@ public function __construct($directory = null, $connection = null) } else { if (is_string($connection)) { $this->_connection = Doctrine_Manager::getInstance() - ->getConnection($connection); + ->getConnection($connection) + ; } else { $this->_connection = $connection; } @@ -71,7 +72,7 @@ public function __construct($directory = null, $connection = null) $this->_process = new Doctrine_Migration_Process($this); - if ($directory != null) { + if (null != $directory) { $this->_migrationClassesDirectory = $directory; $this->loadMigrationClassesFromDirectory(); @@ -89,7 +90,7 @@ public function setConnection(Doctrine_Connection $conn) } /** - * Get the migration classes directory + * Get the migration classes directory. * * @return string $migrationClassesDirectory */ @@ -99,7 +100,7 @@ public function getMigrationClassesDirectory() } /** - * Get the table name for storing the version number for this migration instance + * Get the table name for storing the version number for this migration instance. * * @return string $migrationTableName */ @@ -109,27 +110,26 @@ public function getTableName() } /** - * Set the table name for storing the version number for this migration instance + * Set the table name for storing the version number for this migration instance. * * @param string $tableName - * @return void */ public function setTableName($tableName) { $this->_migrationTableName = $this->_connection - ->formatter->getTableName($tableName); + ->formatter->getTableName($tableName) + ; } /** * Load migration classes from the passed directory. Any file found with a .php - * extension will be passed to the loadMigrationClass() + * extension will be passed to the loadMigrationClass(). * - * @param string $directory Directory to load migration classes from - * @return void + * @param string $directory Directory to load migration classes from */ public function loadMigrationClassesFromDirectory($directory = null) { - $directory = $directory ? $directory:$this->_migrationClassesDirectory; + $directory = $directory ? $directory : $this->_migrationClassesDirectory; $classesToLoad = array(); $classes = get_declared_classes(); @@ -145,8 +145,8 @@ public function loadMigrationClassesFromDirectory($directory = null) foreach ($it as $file) { $info = pathinfo($file->getFileName()); - if (isset($info['extension']) && $info['extension'] == 'php') { - require_once($file->getPathName()); + if (isset($info['extension']) && 'php' == $info['extension']) { + require_once $file->getPathName(); $array = array_diff(get_declared_classes(), $classes); $className = end($array); @@ -171,22 +171,21 @@ public function loadMigrationClassesFromDirectory($directory = null) * migration classes to execute. It must be a child of Doctrine_Migration in order * to be loaded. * - * @param string $name - * @return void + * @param string $name + * @param mixed|null $path */ public function loadMigrationClass($name, $path = null) { $class = new ReflectionClass($name); while ($class->isSubclassOf($this->_reflectionClass)) { - $class = $class->getParentClass(); - if ($class === false) { + if (false === $class) { break; } } - if ($class === false) { + if (false === $class) { return false; } @@ -218,66 +217,65 @@ public function getMigrationClasses() } /** - * Set the current version of the database + * Set the current version of the database. * - * @param integer $number - * @return void + * @param int $number */ public function setCurrentVersion($number) { if ($this->hasMigrated()) { - $this->_connection->exec("UPDATE " . $this->_migrationTableName . " SET version = $number"); + $this->_connection->exec('UPDATE '.$this->_migrationTableName." SET version = {$number}"); } else { - $this->_connection->exec("INSERT INTO " . $this->_migrationTableName . " (version) VALUES ($number)"); + $this->_connection->exec('INSERT INTO '.$this->_migrationTableName." (version) VALUES ({$number})"); } } /** - * Get the current version of the database + * Get the current version of the database. * - * @return integer $version + * @return int $version */ public function getCurrentVersion() { $this->_createMigrationTable(); - $result = $this->_connection->fetchColumn("SELECT version FROM " . $this->_migrationTableName); + $result = $this->_connection->fetchColumn('SELECT version FROM '.$this->_migrationTableName); - return isset($result[0]) ? $result[0]:0; + return isset($result[0]) ? $result[0] : 0; } /** - * hReturns true/false for whether or not this database has been migrated in the past + * hReturns true/false for whether or not this database has been migrated in the past. * - * @return boolean $migrated + * @return bool $migrated */ public function hasMigrated() { $this->_createMigrationTable(); - $result = $this->_connection->fetchColumn("SELECT version FROM " . $this->_migrationTableName); + $result = $this->_connection->fetchColumn('SELECT version FROM '.$this->_migrationTableName); - return isset($result[0]) ? true:false; + return isset($result[0]) ? true : false; } /** - * Gets the latest possible version from the loaded migration classes + * Gets the latest possible version from the loaded migration classes. * - * @return integer $latestVersion + * @return int $latestVersion */ public function getLatestVersion() { $versions = array_keys($this->_migrationClasses); rsort($versions); - return isset($versions[0]) ? $versions[0]:0; + return isset($versions[0]) ? $versions[0] : 0; } /** * Get the next incremented version number based on the latest version number - * using getLatestVersion() + * using getLatestVersion(). * - * @return integer $nextVersion + * @return int $nextVersion */ public function getNextVersion() { @@ -285,19 +283,18 @@ public function getNextVersion() } /** - * Get the next incremented class version based on the loaded migration classes + * Get the next incremented class version based on the loaded migration classes. * - * @return integer $nextMigrationClassVersion + * @return int $nextMigrationClassVersion */ public function getNextMigrationClassVersion() { if (empty($this->_migrationClasses)) { return 1; - } else { - $nums = array_keys($this->_migrationClasses); - $num = end($nums) + 1; - return $num; } + $nums = array_keys($this->_migrationClasses); + + return end($nums) + 1; } /** @@ -305,9 +302,11 @@ public function getNextMigrationClassVersion() * migrate to. It will automatically know whether you are migrating up or down * based on the current version of the database. * - * @param integer $to Version to migrate to - * @param boolean $dryRun Whether or not to run the migrate process as a dry run - * @return integer $to Version number migrated to + * @param int $to Version to migrate to + * @param bool $dryRun Whether or not to run the migrate process as a dry run + * + * @return int $to Version number migrated to + * * @throws Doctrine_Exception */ public function migrate($to = null, $dryRun = false) @@ -321,7 +320,7 @@ public function migrate($to = null, $dryRun = false) try { // If nothing specified then lets assume we are migrating from // the current version to the latest version - if ($to === null) { + if (null === $to) { $to = $this->getLatestVersion(); } @@ -335,32 +334,33 @@ public function migrate($to = null, $dryRun = false) if ($dryRun) { return false; - } else { - $this->_throwErrorsException(); } + $this->_throwErrorsException(); } else { if ($dryRun) { $this->_connection->rollback(); if ($this->hasErrors()) { return false; - } else { - return $to; } - } else { - $this->_connection->commit(); - $this->setCurrentVersion($to); + return $to; } + $this->_connection->commit(); + $this->setCurrentVersion($to); + + return $to; } + return false; } /** * Run the migration process but rollback at the very end. Returns true or - * false for whether or not the migration can be ran + * false for whether or not the migration can be ran. * - * @param string $to - * @return boolean $success + * @param string $to + * + * @return bool $success */ public function migrateDryRun($to = null) { @@ -368,9 +368,9 @@ public function migrateDryRun($to = null) } /** - * Get the number of errors + * Get the number of errors. * - * @return integer $numErrors + * @return int $numErrors */ public function getNumErrors() { @@ -378,7 +378,7 @@ public function getNumErrors() } /** - * Get all the error exceptions + * Get all the error exceptions. * * @return array $errors */ @@ -388,9 +388,7 @@ public function getErrors() } /** - * Clears the error exceptions - * - * @return void + * Clears the error exceptions. */ public function clearErrors() { @@ -398,10 +396,7 @@ public function clearErrors() } /** - * Add an error to the stack. Excepts some type of Exception - * - * @param Exception $e - * @return void + * Add an error to the stack. Excepts some type of Exception. */ public function addError(Exception $e) { @@ -409,25 +404,27 @@ public function addError(Exception $e) } /** - * Whether or not the migration instance has errors + * Whether or not the migration instance has errors. * - * @return boolean + * @return bool */ public function hasErrors() { - return $this->getNumErrors() > 0 ? true:false; + return $this->getNumErrors() > 0 ? true : false; } /** - * Get instance of migration class for number/version specified + * Get instance of migration class for number/version specified. + * + * @param int $num * - * @param integer $num * @throws Doctrine_Migration_Exception $e */ public function getMigrationClass($num) { if (isset($this->_migrationClasses[$num])) { $className = $this->_migrationClasses[$num]; + return new $className(); } @@ -435,9 +432,8 @@ public function getMigrationClass($num) } /** - * Throw an exception with all the errors trigged during the migration + * Throw an exception with all the errors trigged during the migration. * - * @return void * @throws Doctrine_Migration_Exception $e */ protected function _throwErrorsException() @@ -445,23 +441,25 @@ protected function _throwErrorsException() $messages = array(); $num = 0; foreach ($this->getErrors() as $error) { - $num++; - $messages[] = ' Error #' . $num . ' - ' .$error->getMessage() . "\n" . $error->getTraceAsString() . "\n"; + ++$num; + $messages[] = ' Error #'.$num.' - '.$error->getMessage()."\n".$error->getTraceAsString()."\n"; } - $title = $this->getNumErrors() . ' error(s) encountered during migration'; - $message = $title . "\n"; - $message .= str_repeat('=', strlen($title)) . "\n"; + $title = $this->getNumErrors().' error(s) encountered during migration'; + $message = $title."\n"; + $message .= str_repeat('=', strlen($title))."\n"; $message .= implode("\n", $messages); throw new Doctrine_Migration_Exception($message); } /** - * Do the actual migration process + * Do the actual migration process. + * + * @param int $to + * + * @return int $to * - * @param integer $to - * @return integer $to * @throws Doctrine_Exception */ protected function _doMigrate($to) @@ -469,17 +467,17 @@ protected function _doMigrate($to) $from = $this->getCurrentVersion(); if ($from == $to) { - throw new Doctrine_Migration_Exception('Already at version # ' . $to); + throw new Doctrine_Migration_Exception('Already at version # '.$to); } - $direction = $from > $to ? 'down':'up'; + $direction = $from > $to ? 'down' : 'up'; - if ($direction === 'up') { - for ($i = $from + 1; $i <= $to; $i++) { + if ('up' === $direction) { + for ($i = $from + 1; $i <= $to; ++$i) { $this->_doMigrateStep($direction, $i); } } else { - for ($i = $from; $i > $to; $i--) { + for ($i = $from; $i > $to; --$i) { $this->_doMigrateStep($direction, $i); } } @@ -489,37 +487,36 @@ protected function _doMigrate($to) /** * Perform a single migration step. Executes a single migration class and - * processes the changes + * processes the changes. * * @param string $direction Direction to go, 'up' or 'down' - * @param integer $num - * @return void + * @param int $num */ protected function _doMigrateStep($direction, $num) { try { $migration = $this->getMigrationClass($num); - $method = 'pre' . $direction; - $migration->$method(); + $method = 'pre'.$direction; + $migration->{$method}(); if (method_exists($migration, $direction)) { - $migration->$direction(); - } else if (method_exists($migration, 'migrate')) { + $migration->{$direction}(); + } elseif (method_exists($migration, 'migrate')) { $migration->migrate($direction); } if ($migration->getNumChanges() > 0) { $changes = $migration->getChanges(); - if ($direction == 'down' && method_exists($migration, 'migrate')) { + if ('down' == $direction && method_exists($migration, 'migrate')) { $changes = array_reverse($changes); } foreach ($changes as $value) { list($type, $change) = $value; - $funcName = 'process' . Doctrine_Inflector::classify($type); + $funcName = 'process'.Doctrine_Inflector::classify($type); if (method_exists($this->_process, $funcName)) { try { - $this->_process->$funcName($change); + $this->_process->{$funcName}($change); } catch (Exception $e) { $this->addError($e); } @@ -529,8 +526,8 @@ protected function _doMigrateStep($direction, $num) } } - $method = 'post' . $direction; - $migration->$method(); + $method = 'post'.$direction; + $migration->{$method}(); } catch (Exception $e) { $this->addError($e); } @@ -538,10 +535,10 @@ protected function _doMigrateStep($direction, $num) /** * Create the migration table and return true. If it already exists it will - * silence the exception and return false + * silence the exception and return false. * - * @return boolean $created Whether or not the table was created. Exceptions - * are silenced when table already exists + * @return bool $created Whether or not the table was created. Exceptions + * are silenced when table already exists */ protected function _createMigrationTable() { @@ -555,8 +552,8 @@ protected function _createMigrationTable() $this->_connection->export->createTable($this->_migrationTableName, array('version' => array('type' => 'integer', 'size' => 11))); return true; - } catch(Exception $e) { + } catch (Exception $e) { return false; } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Migration/Base.php b/lib/Doctrine/Migration/Base.php index a2bcfb266..518fff28a 100644 --- a/lib/Doctrine/Migration/Base.php +++ b/lib/Doctrine/Migration/Base.php @@ -20,41 +20,42 @@ */ /** - * Base migration class. All migration classes must extend from this base class + * Base migration class. All migration classes must extend from this base class. * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ abstract class Doctrine_Migration_Base { /** - * The default options for tables created using Doctrine_Migration_Base::createTable() - * + * The default options for tables created using Doctrine_Migration_Base::createTable(). + * * @var array */ private static $defaultTableOptions = array(); protected $_changes = array(); - protected static $_opposites = array('created_table' => 'dropped_table', - 'dropped_table' => 'created_table', - 'created_constraint' => 'dropped_constraint', - 'dropped_constraint' => 'created_constraint', - 'created_foreign_key' => 'dropped_foreign_key', - 'dropped_foreign_key' => 'created_foreign_key', - 'created_column' => 'dropped_column', - 'dropped_column' => 'created_column', - 'created_index' => 'dropped_index', - 'dropped_index' => 'created_index', - ); + protected static $_opposites = array('created_table' => 'dropped_table', + 'dropped_table' => 'created_table', + 'created_constraint' => 'dropped_constraint', + 'dropped_constraint' => 'created_constraint', + 'created_foreign_key' => 'dropped_foreign_key', + 'dropped_foreign_key' => 'created_foreign_key', + 'created_column' => 'dropped_column', + 'dropped_column' => 'created_column', + 'created_index' => 'dropped_index', + 'dropped_index' => 'created_index', + ); /** - * Get the changes that have been added on this migration class instance + * Get the changes that have been added on this migration class instance. * * @return array $changes */ @@ -69,29 +70,28 @@ public function getNumChanges() } /** - * Add a change to the stack of changes to execute + * Add a change to the stack of changes to execute. * - * @param string $type The type of change - * @param array $change The array of information for the change - * @return void + * @param string $type The type of change + * @param array $change The array of information for the change */ protected function _addChange($type, array $change = array()) { - if (isset($change['upDown']) && $change['upDown'] !== null && isset(self::$_opposites[$type])) { + if (isset($change['upDown']) && null !== $change['upDown'] && isset(self::$_opposites[$type])) { $upDown = $change['upDown']; unset($change['upDown']); - if ($upDown == 'down') { + if ('down' == $upDown) { $opposite = self::$_opposites[$type]; + return $this->_changes[] = array($opposite, $change); } } + return $this->_changes[] = array($type, $change); } /** - * Sets the default options for tables created using Doctrine_Migration_Base::createTable() - * - * @param array $options + * Sets the default options for tables created using Doctrine_Migration_Base::createTable(). */ public static function setDefaultTableOptions(array $options) { @@ -99,8 +99,8 @@ public static function setDefaultTableOptions(array $options) } /** - * Returns the default options for tables created using Doctrine_Migration_Base::createTable() - * + * Returns the default options for tables created using Doctrine_Migration_Base::createTable(). + * * @return array */ public static function getDefaultTableOptions() @@ -111,11 +111,10 @@ public static function getDefaultTableOptions() /** * Add a create or drop table change. * - * @param string $upDown Whether to add the up(create) or down(drop) table change. - * @param string $tableName Name of the table - * @param array $fields Array of fields for table - * @param array $options Array of options for the table - * @return void + * @param string $upDown whether to add the up(create) or down(drop) table change + * @param string $tableName Name of the table + * @param array $fields Array of fields for table + * @param array $options Array of options for the table */ public function table($upDown, $tableName, array $fields = array(), array $options = array()) { @@ -127,10 +126,9 @@ public function table($upDown, $tableName, array $fields = array(), array $optio /** * Add a create table change. * - * @param string $tableName Name of the table - * @param array $fields Array of fields for table - * @param array $options Array of options for the table - * @return void + * @param string $tableName Name of the table + * @param array $fields Array of fields for table + * @param array $options Array of options for the table */ public function createTable($tableName, array $fields = array(), array $options = array()) { @@ -140,8 +138,7 @@ public function createTable($tableName, array $fields = array(), array $options /** * Add a drop table change. * - * @param string $tableName Name of the table - * @return void + * @param string $tableName Name of the table */ public function dropTable($tableName) { @@ -149,42 +146,38 @@ public function dropTable($tableName) } /** - * Add a rename table change + * Add a rename table change. * - * @param string $oldTableName Name of the table to change - * @param string $newTableName Name to change the table to - * @return void + * @param string $oldTableName Name of the table to change + * @param string $newTableName Name to change the table to */ public function renameTable($oldTableName, $newTableName) { $options = get_defined_vars(); - + $this->_addChange('renamed_table', $options); } /** * Add a create or drop constraint change. * - * @param string $upDown Whether to add the up(create) or down(drop) create change. - * @param string $tableName Name of the table. - * @param string $constraintName Name of the constraint. - * @param array $definition Array for the constraint definition. - * @return void + * @param string $upDown whether to add the up(create) or down(drop) create change + * @param string $tableName name of the table + * @param string $constraintName name of the constraint + * @param array $definition array for the constraint definition */ public function constraint($upDown, $tableName, $constraintName, array $definition) { $options = get_defined_vars(); - + $this->_addChange('created_constraint', $options); } /** * Add a create constraint change. * - * @param string $tableName Name of the table. - * @param string $constraintname Name of the constraint. - * @param array $definition Array for the constraint definition. - * @return void + * @param string $tableName name of the table + * @param array $definition array for the constraint definition */ public function createConstraint($tableName, $constraintName, array $definition) { @@ -194,9 +187,7 @@ public function createConstraint($tableName, $constraintName, array $definition) /** * Add a drop constraint change. * - * @param string $tableName Name of the table. - * @param string $constraintname Name of the constraint. - * @return void + * @param string $tableName name of the table */ public function dropConstraint($tableName, $constraintName, $primary = false) { @@ -206,14 +197,13 @@ public function dropConstraint($tableName, $constraintName, $primary = false) /** * Convenience method for creating or dropping primary keys. * - * @param string $direction - * @param string $tableName Name of the table - * @param string $columnNames Array of column names and column definitions - * @return void + * @param string $direction + * @param string $tableName Name of the table + * @param string $columnNames Array of column names and column definitions */ public function primaryKey($direction, $tableName, $columnNames) { - if ($direction == 'up') { + if ('up' == $direction) { $this->createPrimaryKey($tableName, $columnNames); } else { $this->dropPrimaryKey($tableName, $columnNames); @@ -221,7 +211,7 @@ public function primaryKey($direction, $tableName, $columnNames) } /** - * Convenience method for creating primary keys + * Convenience method for creating primary keys. * * [php] * $columns = array( @@ -237,10 +227,9 @@ public function primaryKey($direction, $tableName, $columnNames) * * Add new columns (addColumn()) * * Create primary constraint on columns (createConstraint()) * * Change autoincrement = true field to be autoincrement - * - * @param string $tableName Name of the table - * @param string $columnNames Array of column names and column definitions - * @return void + * + * @param string $tableName Name of the table + * @param string $columnNames Array of column names and column definitions */ public function createPrimaryKey($tableName, $columnNames) { @@ -270,7 +259,7 @@ public function createPrimaryKey($tableName, $columnNames) // Create the primary constraint for the columns $this->createConstraint($tableName, null, array( 'primary' => true, - 'fields' => $fields + 'fields' => $fields, )); // If auto increment change the column to be so @@ -297,9 +286,8 @@ public function createPrimaryKey($tableName, $columnNames) * * Remove primary constraint (dropConstraint()) * * Removing columns (removeColumn()) * - * @param string $tableName Name of the table - * @param string $columnNames Array of column names and column definitions - * @return void + * @param string $tableName Name of the table + * @param string $columnNames Array of column names and column definitions */ public function dropPrimaryKey($tableName, $columnNames) { @@ -324,11 +312,10 @@ public function dropPrimaryKey($tableName, $columnNames) /** * Add a create or drop foreign key change. * - * @param string $upDown Whether to add the up(create) or down(drop) foreign key change. - * @param string $tableName Name of the table. - * @param string $name Name of the foreign key. - * @param array $definition Array for the foreign key definition - * @return void + * @param string $upDown whether to add the up(create) or down(drop) foreign key change + * @param string $tableName name of the table + * @param string $name name of the foreign key + * @param array $definition Array for the foreign key definition */ public function foreignKey($upDown, $tableName, $name, array $definition = array()) { @@ -341,10 +328,9 @@ public function foreignKey($upDown, $tableName, $name, array $definition = array /** * Add a create foreign key change. * - * @param string $tableName Name of the table. - * @param string $name Name of the foreign key. - * @param array $definition Array for the foreign key definition - * @return void + * @param string $tableName name of the table + * @param string $name name of the foreign key + * @param array $definition Array for the foreign key definition */ public function createForeignKey($tableName, $name, array $definition) { @@ -354,9 +340,8 @@ public function createForeignKey($tableName, $name, array $definition) /** * Add a drop foreign key change. * - * @param string $tableName Name of the table. - * @param string $name Name of the foreign key. - * @return void + * @param string $tableName name of the table + * @param string $name name of the foreign key */ public function dropForeignKey($tableName, $name) { @@ -366,18 +351,17 @@ public function dropForeignKey($tableName, $name) /** * Add a add or remove column change. * - * @param string $upDown Whether to add the up(add) or down(remove) column change. - * @param string $tableName Name of the table - * @param string $columnName Name of the column - * @param string $type Type of the column - * @param string $length Length of the column - * @param array $options Array of options for the column - * @return void + * @param string $upDown whether to add the up(add) or down(remove) column change + * @param string $tableName Name of the table + * @param string $columnName Name of the column + * @param string $type Type of the column + * @param string $length Length of the column + * @param array $options Array of options for the column */ public function column($upDown, $tableName, $columnName, $type = null, $length = null, array $options = array()) { $options = get_defined_vars(); - if ( ! isset($options['options']['length'])) { + if (!isset($options['options']['length'])) { $options['options']['length'] = $length; } $options = array_merge($options, $options['options']); @@ -389,12 +373,11 @@ public function column($upDown, $tableName, $columnName, $type = null, $length = /** * Add a add column change. * - * @param string $tableName Name of the table - * @param string $columnName Name of the column - * @param string $type Type of the column - * @param string $length Length of the column - * @param array $options Array of options for the column - * @return void + * @param string $tableName Name of the table + * @param string $columnName Name of the column + * @param string $type Type of the column + * @param string $length Length of the column + * @param array $options Array of options for the column */ public function addColumn($tableName, $columnName, $type, $length = null, array $options = array()) { @@ -404,9 +387,8 @@ public function addColumn($tableName, $columnName, $type, $length = null, array /** * Add a remove column change. * - * @param string $tableName Name of the table - * @param string $columnName Name of the column - * @return void + * @param string $tableName Name of the table + * @param string $columnName Name of the column */ public function removeColumn($tableName, $columnName) { @@ -414,29 +396,27 @@ public function removeColumn($tableName, $columnName) } /** - * Add a rename column change + * Add a rename column change. * - * @param string $tableName Name of the table to rename the column on - * @param string $oldColumnName The old column name - * @param string $newColumnName The new column name - * @return void + * @param string $tableName Name of the table to rename the column on + * @param string $oldColumnName The old column name + * @param string $newColumnName The new column name */ public function renameColumn($tableName, $oldColumnName, $newColumnName) { $options = get_defined_vars(); - + $this->_addChange('renamed_column', $options); } /** - * Add a change column change + * Add a change column change. * - * @param string $tableName Name of the table to change the column on - * @param string $columnName Name of the column to change - * @param string $type New type of column - * @param string $length The length of the column - * @param array $options New options for the column - * @return void + * @param string $tableName Name of the table to change the column on + * @param string $columnName Name of the column to change + * @param string $type New type of column + * @param string $length The length of the column + * @param array $options New options for the column */ public function changeColumn($tableName, $columnName, $type = null, $length = null, array $options = array()) { @@ -449,26 +429,24 @@ public function changeColumn($tableName, $columnName, $type = null, $length = nu /** * Add a add or remove index change. * - * @param string $upDown Whether to add the up(add) or down(remove) index change. - * @param string $tableName Name of the table - * @param string $indexName Name of the index - * @param array $definition Array for the index definition - * @return void + * @param string $upDown whether to add the up(add) or down(remove) index change + * @param string $tableName Name of the table + * @param string $indexName Name of the index + * @param array $definition Array for the index definition */ public function index($upDown, $tableName, $indexName, array $definition = array()) { $options = get_defined_vars(); - + $this->_addChange('created_index', $options); } /** * Add a add index change. * - * @param string $tableName Name of the table - * @param string $indexName Name of the index - * @param array $definition Array for the index definition - * @return void + * @param string $tableName Name of the table + * @param string $indexName Name of the index + * @param array $definition Array for the index definition */ public function addIndex($tableName, $indexName, array $definition) { @@ -478,9 +456,8 @@ public function addIndex($tableName, $indexName, array $definition) /** * Add a remove index change. * - * @param string $tableName Name of the table - * @param string $indexName Name of the index - * @return void + * @param string $tableName Name of the table + * @param string $indexName Name of the index */ public function removeIndex($tableName, $indexName) { @@ -502,4 +479,4 @@ public function preDown() public function postDown() { } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Migration/Builder.php b/lib/Doctrine/Migration/Builder.php index e6ed9042a..544f9b70e 100644 --- a/lib/Doctrine/Migration/Builder.php +++ b/lib/Doctrine/Migration/Builder.php @@ -20,62 +20,60 @@ */ /** - * Doctrine_Migration_Builder + * Doctrine_Migration_Builder. * - * @package Doctrine - * @subpackage Migration * @author Konsta Vesterinen * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2939 $ */ class Doctrine_Migration_Builder extends Doctrine_Builder { /** - * The path to your migration classes directory + * The path to your migration classes directory. * * @var string */ private $migrationsPath = ''; /** - * File suffix to use when writing class definitions + * File suffix to use when writing class definitions. * - * @var string $suffix + * @var string */ private $suffix = '.php'; /** - * Instance of the migration class for the migration classes directory + * Instance of the migration class for the migration classes directory. * - * @var Doctrine_Migration $migration + * @var Doctrine_Migration */ private $migration; /** - * Class template used for writing classes - * - * @var $tpl + * Class template used for writing classes. */ private static $tpl; /** - * Instantiate new instance of the Doctrine_Migration_Builder class + * Instantiate new instance of the Doctrine_Migration_Builder class. * * * $builder = new Doctrine_Migration_Builder('/path/to/migrations'); * * - * @return void + * @param mixed|null $migrationsPath */ public function __construct($migrationsPath = null) { if ($migrationsPath instanceof Doctrine_Migration) { $this->setMigrationsPath($migrationsPath->getMigrationClassesDirectory()); $this->migration = $migrationsPath; - } else if (is_dir((string) $migrationsPath)) { + } elseif (is_dir((string) $migrationsPath)) { $this->setMigrationsPath($migrationsPath); $this->migration = new Doctrine_Migration($migrationsPath); } @@ -84,10 +82,9 @@ public function __construct($migrationsPath = null) } /** - * Set the path to write the generated migration classes + * Set the path to write the generated migration classes. * * @param string path the path where migration classes are stored and being generated - * @return void */ public function setMigrationsPath($path) { @@ -97,9 +94,9 @@ public function setMigrationsPath($path) } /** - * Get the path where generated migration classes are written to + * Get the path where generated migration classes are written to. * - * @return string the path where migration classes are stored and being generated + * @return string the path where migration classes are stored and being generated */ public function getMigrationsPath() { @@ -107,9 +104,7 @@ public function getMigrationsPath() } /** - * Loads the class template used for generating classes - * - * @return void + * Loads the class template used for generating classes. */ protected function loadTemplate() { @@ -117,7 +112,7 @@ protected function loadTemplate() return; } - self::$tpl =<< $table) { $up[] = $this->buildDropTable($table); $down[] = $this->buildCreateTable($table); } } - if ( ! empty($changes['created_tables'])) { + if (!empty($changes['created_tables'])) { foreach ($changes['created_tables'] as $tableName => $table) { $up[] = $this->buildCreateTable($table); $down[] = $this->buildDropTable($table); } } - if ( ! empty($changes['dropped_columns'])) { + if (!empty($changes['dropped_columns'])) { foreach ($changes['dropped_columns'] as $tableName => $removedColumns) { foreach ($removedColumns as $name => $column) { $up[] = $this->buildRemoveColumn($tableName, $name, $column); @@ -172,7 +168,7 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['created_columns'])) { + if (!empty($changes['created_columns'])) { foreach ($changes['created_columns'] as $tableName => $addedColumns) { foreach ($addedColumns as $name => $column) { $up[] = $this->buildAddColumn($tableName, $name, $column); @@ -181,7 +177,7 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['changed_columns'])) { + if (!empty($changes['changed_columns'])) { foreach ($changes['changed_columns'] as $tableName => $changedColumns) { foreach ($changedColumns as $name => $column) { $up[] = $this->buildChangeColumn($tableName, $name, $column); @@ -189,19 +185,19 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($up) || ! empty($down)) { + if (!empty($up) || !empty($down)) { $up = implode("\n", $up); $down = implode("\n", $down); - $className = 'Version' . $this->migration->getNextMigrationClassVersion(); + $className = 'Version'.$this->migration->getNextMigrationClassVersion(); $this->generateMigrationClass($className, array(), $up, $down); } $up = array(); $down = array(); - if ( ! empty($changes['dropped_foreign_keys'])) { + if (!empty($changes['dropped_foreign_keys'])) { foreach ($changes['dropped_foreign_keys'] as $tableName => $droppedFks) { - if ( ! empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { - continue; + if (!empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { + continue; } foreach ($droppedFks as $name => $foreignKey) { @@ -211,10 +207,10 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['dropped_indexes'])) { + if (!empty($changes['dropped_indexes'])) { foreach ($changes['dropped_indexes'] as $tableName => $removedIndexes) { - if ( ! empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { - continue; + if (!empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { + continue; } foreach ($removedIndexes as $name => $index) { @@ -224,10 +220,10 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['created_foreign_keys'])) { + if (!empty($changes['created_foreign_keys'])) { foreach ($changes['created_foreign_keys'] as $tableName => $createdFks) { - if ( ! empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { - continue; + if (!empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { + continue; } foreach ($createdFks as $name => $foreignKey) { @@ -237,10 +233,10 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['created_indexes'])) { + if (!empty($changes['created_indexes'])) { foreach ($changes['created_indexes'] as $tableName => $addedIndexes) { - if ( ! empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { - continue; + if (!empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { + continue; } foreach ($addedIndexes as $name => $index) { @@ -253,23 +249,22 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($up) || ! empty($down)) { + if (!empty($up) || !empty($down)) { $up = implode("\n", $up); $down = implode("\n", $down); - $className = 'Version' . $this->migration->getNextMigrationClassVersion(); + $className = 'Version'.$this->migration->getNextMigrationClassVersion(); $this->generateMigrationClass($className, array(), $up, $down); } + return $changes; } /** - * Generate a set of migration classes from the existing databases - * - * @return void + * Generate a set of migration classes from the existing databases. */ public function generateMigrationsFromDb() { - $directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'tmp_doctrine_models'; + $directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'tmp_doctrine_models'; Doctrine_Core::generateModelsFromDb($directory); @@ -281,15 +276,16 @@ public function generateMigrationsFromDb() } /** - * Generate a set of migrations from a set of models + * Generate a set of migrations from a set of models. + * + * @param string $modelsPath Path to models + * @param string $modelLoading What type of model loading to use when loading the models * - * @param string $modelsPath Path to models - * @param string $modelLoading What type of model loading to use when loading the models - * @return boolean + * @return bool */ public function generateMigrationsFromModels($modelsPath = null, $modelLoading = null) { - if ($modelsPath !== null) { + if (null !== $modelsPath) { $models = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($modelsPath, $modelLoading)); } else { $models = Doctrine_Core::getLoadedModels(); @@ -309,18 +305,18 @@ public function generateMigrationsFromModels($modelsPath = null, $modelLoading = $up = $this->buildCreateTable($export); $down = $this->buildDropTable($export); - $className = 'Add' . Doctrine_Inflector::classify($export['tableName']); + $className = 'Add'.Doctrine_Inflector::classify($export['tableName']); $this->generateMigrationClass($className, array(), $up, $down); } } - if ( ! empty($foreignKeys)) { + if (!empty($foreignKeys)) { $className = 'AddFks'; $up = array(); $down = array(); - foreach ($foreignKeys as $tableName => $definitions) { + foreach ($foreignKeys as $tableName => $definitions) { $tableForeignKeyNames[$tableName] = array(); foreach ($definitions as $definition) { @@ -340,40 +336,43 @@ public function generateMigrationsFromModels($modelsPath = null, $modelLoading = } /** - * Build the code for creating foreign keys + * Build the code for creating foreign keys. + * + * @param string $tableName + * @param array $definition * - * @param string $tableName - * @param array $definition * @return string $code */ public function buildCreateForeignKey($tableName, $definition) { - return " \$this->createForeignKey('" . $tableName . "', '" . $definition['name'] . "', " . $this->varExport($definition, true) . ");"; + return " \$this->createForeignKey('".$tableName."', '".$definition['name']."', ".$this->varExport($definition, true).');'; } /** - * Build the code for dropping foreign keys + * Build the code for dropping foreign keys. + * + * @param string $tableName + * @param array $definition * - * @param string $tableName - * @param array $definition * @return string $code */ public function buildDropForeignKey($tableName, $definition) { - return " \$this->dropForeignKey('" . $tableName . "', '" . $definition['name'] . "');"; + return " \$this->dropForeignKey('".$tableName."', '".$definition['name']."');"; } /** - * Build the code for creating tables + * Build the code for creating tables. + * + * @param string $tableData * - * @param string $tableData * @return string $code */ public function buildCreateTable($tableData) { - $code = " \$this->createTable('" . $tableData['tableName'] . "', "; + $code = " \$this->createTable('".$tableData['tableName']."', "; - $code .= $this->varExport($tableData['columns'], true) . ", "; + $code .= $this->varExport($tableData['columns'], true).', '; $optionsWeNeed = array('type', 'indexes', 'primary', 'collate', 'charset'); @@ -386,28 +385,30 @@ public function buildCreateTable($tableData) $code .= $this->varExport($options, true); - $code .= ");"; + $code .= ');'; return $code; } /** - * Build the code for dropping tables + * Build the code for dropping tables. + * + * @param string $tableData * - * @param string $tableData * @return string $code */ public function buildDropTable($tableData) { - return " \$this->dropTable('" . $tableData['tableName'] . "');"; + return " \$this->dropTable('".$tableData['tableName']."');"; } /** - * Build the code for adding columns + * Build the code for adding columns. * * @param string $tableName * @param string $columnName * @param string $column + * * @return string $code */ public function buildAddColumn($tableName, $columnName, $column) @@ -415,28 +416,31 @@ public function buildAddColumn($tableName, $columnName, $column) $length = $column['length']; $type = $column['type']; unset($column['length'], $column['type']); - return " \$this->addColumn('" . $tableName . "', '" . $columnName. "', '" . $type . "', '" . $length . "', " . $this->varExport($column) . ");"; + + return " \$this->addColumn('".$tableName."', '".$columnName."', '".$type."', '".$length."', ".$this->varExport($column).');'; } /** - * Build the code for removing columns + * Build the code for removing columns. * * @param string $tableName * @param string $columnName * @param string $column + * * @return string $code */ public function buildRemoveColumn($tableName, $columnName, $column) { - return " \$this->removeColumn('" . $tableName . "', '" . $columnName. "');"; + return " \$this->removeColumn('".$tableName."', '".$columnName."');"; } /** - * Build the code for changing columns + * Build the code for changing columns. * * @param string $tableName * @param string $columnName * @param string $column + * * @return string $code */ public function buildChangeColumn($tableName, $columnName, $column) @@ -444,45 +448,47 @@ public function buildChangeColumn($tableName, $columnName, $column) $length = $column['length']; $type = $column['type']; unset($column['length'], $column['type']); - return " \$this->changeColumn('" . $tableName . "', '" . $columnName. "', '" . $type . "', '" . $length . "', " . $this->varExport($column) . ");"; + + return " \$this->changeColumn('".$tableName."', '".$columnName."', '".$type."', '".$length."', ".$this->varExport($column).');'; } /** - * Build the code for adding indexes + * Build the code for adding indexes. * * @param string $tableName * @param string $indexName * @param string $index + * * @return sgtring $code */ public function buildAddIndex($tableName, $indexName, $index) { - return " \$this->addIndex('$tableName', '$indexName', " . $this->varExport($index) . ");"; + return " \$this->addIndex('{$tableName}', '{$indexName}', ".$this->varExport($index).');'; } /** - * Build the code for removing indexes + * Build the code for removing indexes. * * @param string $tableName * @param string $indexName * @param string $index + * * @return string $code */ public function buildRemoveIndex($tableName, $indexName, $index) { - return " \$this->removeIndex('$tableName', '$indexName', " . $this->varExport($index) . ");"; + return " \$this->removeIndex('{$tableName}', '{$indexName}', ".$this->varExport($index).');'; } /** - * Generate a migration class - * - * @param string $className Class name to generate - * @param array $options Options for the migration class - * @param string $up The code for the up function - * @param string $down The code for the down function - * @param boolean $return Whether or not to return the code. - * If true return and false it writes the class to disk. - * @return mixed + * Generate a migration class. + * + * @param string $className Class name to generate + * @param array $options Options for the migration class + * @param string $up The code for the up function + * @param string $down The code for the down function + * @param bool $return Whether or not to return the code. + * If true return and false it writes the class to disk. */ public function generateMigrationClass($className, $options = array(), $up = null, $down = null, $return = false) { @@ -490,53 +496,54 @@ public function generateMigrationClass($className, $options = array(), $up = nul $className = str_replace('-', '_', $className); $className = Doctrine_Inflector::classify($className); - if ($return || ! $this->getMigrationsPath()) { + if ($return || !$this->getMigrationsPath()) { return $this->buildMigrationClass($className, null, $options, $up, $down); - } else { - if ( ! $this->getMigrationsPath()) { - throw new Doctrine_Migration_Exception('You must specify the path to your migrations.'); - } - - $next = time() + $this->migration->getNextMigrationClassVersion(); - $fileName = $next . '_' . Doctrine_Inflector::tableize($className) . $this->suffix; + } + if (!$this->getMigrationsPath()) { + throw new Doctrine_Migration_Exception('You must specify the path to your migrations.'); + } - $class = $this->buildMigrationClass($className, $fileName, $options, $up, $down); + $next = time() + $this->migration->getNextMigrationClassVersion(); + $fileName = $next.'_'.Doctrine_Inflector::tableize($className).$this->suffix; - $path = $this->getMigrationsPath() . DIRECTORY_SEPARATOR . $fileName; - if (class_exists($className) || file_exists($path)) { - $this->migration->loadMigrationClass($className); - return false; - } + $class = $this->buildMigrationClass($className, $fileName, $options, $up, $down); - file_put_contents($path, $class); - require_once($path); + $path = $this->getMigrationsPath().DIRECTORY_SEPARATOR.$fileName; + if (class_exists($className) || file_exists($path)) { $this->migration->loadMigrationClass($className); - return true; + return false; } + + file_put_contents($path, $class); + require_once $path; + $this->migration->loadMigrationClass($className); + + return true; } /** - * Build the code for a migration class + * Build the code for a migration class. + * + * @param string $className Class name to generate + * @param string $fileName File name to write the class to + * @param array $options Options for the migration class + * @param string $up The code for the up function + * @param string $down The code for the down function * - * @param string $className Class name to generate - * @param string $fileName File name to write the class to - * @param array $options Options for the migration class - * @param string $up The code for the up function - * @param string $down The code for the down function * @return string $content The code for the generated class */ public function buildMigrationClass($className, $fileName = null, $options = array(), $up = null, $down = null) { - $extends = isset($options['extends']) ? $options['extends']:'Doctrine_Migration_Base'; + $extends = isset($options['extends']) ? $options['extends'] : 'Doctrine_Migration_Base'; - $content = ' */ class Doctrine_Migration_Diff { - protected $_from, - $_to, - $_changes = array('created_tables' => array(), - 'dropped_tables' => array(), - 'created_foreign_keys'=> array(), - 'dropped_foreign_keys'=> array(), - 'created_columns' => array(), - 'dropped_columns' => array(), - 'changed_columns' => array(), - 'created_indexes' => array(), - 'dropped_indexes' => array()), - $_migration, - $_startingModelFiles = array(), - $_tmpPath; - - protected static $_toPrefix = 'ToPrfx', - $_fromPrefix = 'FromPrfx'; + protected $_from; + protected $_to; + protected $_changes = array('created_tables' => array(), + 'dropped_tables' => array(), + 'created_foreign_keys' => array(), + 'dropped_foreign_keys' => array(), + 'created_columns' => array(), + 'dropped_columns' => array(), + 'changed_columns' => array(), + 'created_indexes' => array(), + 'dropped_indexes' => array()); + protected $_migration; + protected $_startingModelFiles = array(); + protected $_tmpPath; + + protected static $_toPrefix = 'ToPrfx'; + protected static $_fromPrefix = 'FromPrfx'; /** - * Instantiate new Doctrine_Migration_Diff instance + * Instantiate new Doctrine_Migration_Diff instance. * * * $diff = new Doctrine_Migration_Diff('/path/to/old_models', '/path/to/new_models', '/path/to/migrations'); @@ -62,44 +63,42 @@ class Doctrine_Migration_Diff * @param string $from The from schema information source * @param string $to The to schema information source * @param mixed $migration Instance of Doctrine_Migration or path to migration classes - * @return void */ public function __construct($from, $to, $migration) { $this->_from = $from; $this->_to = $to; $this->_startingModelFiles = Doctrine_Core::getLoadedModelFiles(); - $this->setTmpPath(sys_get_temp_dir() . DIRECTORY_SEPARATOR . getmypid()); + $this->setTmpPath(sys_get_temp_dir().DIRECTORY_SEPARATOR.getmypid()); if ($migration instanceof Doctrine_Migration) { $this->_migration = $migration; - } else if (is_dir($migration)) { + } elseif (is_dir($migration)) { $this->_migration = new Doctrine_Migration($migration); } } /** - * Set the temporary path to store the generated models for generating diffs + * Set the temporary path to store the generated models for generating diffs. * * @param string $tmpPath - * @return void */ public function setTmpPath($tmpPath) { - if ( ! is_dir($tmpPath)) { + if (!is_dir($tmpPath)) { mkdir($tmpPath, 0777, true); } $this->_tmpPath = $tmpPath; } /** - * Get unique hash id for this migration instance + * Get unique hash id for this migration instance. * * @return string $uniqueId */ protected function getUniqueId() { - return md5($this->_from . $this->_to); + return md5($this->_from.$this->_to); } /** @@ -112,11 +111,11 @@ public function generateChanges() $this->_cleanup(); $from = $this->_generateModels( - Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) . self::$_fromPrefix, + Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX).self::$_fromPrefix, $this->_from ); $to = $this->_generateModels( - Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) . self::$_toPrefix, + Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX).self::$_toPrefix, $this->_to ); @@ -124,7 +123,7 @@ public function generateChanges() } /** - * Generate a migration class for the changes in this diff instance + * Generate a migration class for the changes in this diff instance. * * @return array $changes */ @@ -139,13 +138,14 @@ public function generateMigrationClasses() * Initialize some Doctrine models at a given path. * * @param string $path + * * @return array $models */ protected function _initializeModels($path) { $manager = Doctrine_Manager::getInstance(); $modelLoading = $manager->getAttribute(Doctrine_Core::ATTR_MODEL_LOADING); - if ($modelLoading === Doctrine_Core::MODEL_LOADING_PEAR) { + if (Doctrine_Core::MODEL_LOADING_PEAR === $modelLoading) { $orig = Doctrine_Core::getModelsDirectory(); Doctrine_Core::setModelsDirectory($path); $models = Doctrine_Core::initializeModels(Doctrine_Core::loadModels($path)); @@ -153,15 +153,17 @@ protected function _initializeModels($path) } else { $models = Doctrine_Core::initializeModels(Doctrine_Core::loadModels($path)); } + return $models; } /** - * Generate a diff between the from and to schema information + * Generate a diff between the from and to schema information. + * + * @param string $from Path to set of models to migrate from + * @param string $to Path to set of models to migrate to * - * @param string $from Path to set of models to migrate from - * @param string $to Path to set of models to migrate to - * @return array $changes + * @return array $changes */ protected function _diff($from, $to) { @@ -182,10 +184,11 @@ protected function _diff($from, $to) } /** - * Build array of changes between the from and to array of schema information + * Build array of changes between the from and to array of schema information. + * + * @param array $from Array of schema information to generate changes from + * @param array $to Array of schema information to generate changes for * - * @param array $from Array of schema information to generate changes from - * @param array $to Array of schema information to generate changes for * @return array $changes */ protected function _buildChanges($from, $to) @@ -193,7 +196,7 @@ protected function _buildChanges($from, $to) // Loop over the to schema information and compare it to the from foreach ($to as $className => $info) { // If the from doesn't have this class then it is a new table - if ( ! isset($from[$className])) { + if (!isset($from[$className])) { $names = array('type', 'charset', 'collate', 'indexes', 'foreignKeys', 'primary'); $options = array(); foreach ($names as $name) { @@ -203,14 +206,14 @@ protected function _buildChanges($from, $to) } $table = array('tableName' => $info['tableName'], - 'columns' => $info['columns'], - 'options' => $options); + 'columns' => $info['columns'], + 'options' => $options); $this->_changes['created_tables'][$info['tableName']] = $table; } // Check for new and changed columns foreach ($info['columns'] as $name => $column) { // If column doesn't exist in the from schema information then it is a new column - if (isset($from[$className]) && ! isset($from[$className]['columns'][$name])) { + if (isset($from[$className]) && !isset($from[$className]['columns'][$name])) { $this->_changes['created_columns'][$info['tableName']][$name] = $column; } // If column exists in the from schema information but is not the same then it is a changed column @@ -222,12 +225,12 @@ protected function _buildChanges($from, $to) foreach ($info['options']['foreignKeys'] as $name => $foreignKey) { $foreignKey['name'] = $name; // If foreign key doesn't exist in the from schema information then we need to add a index and the new fk - if ( ! isset($from[$className]['options']['foreignKeys'][$name])) { + if (!isset($from[$className]['options']['foreignKeys'][$name])) { $this->_changes['created_foreign_keys'][$info['tableName']][$name] = $foreignKey; $indexName = Doctrine_Manager::connection()->generateUniqueIndexName($info['tableName'], $foreignKey['local']); $this->_changes['created_indexes'][$info['tableName']][$indexName] = array('fields' => array($foreignKey['local'])); // If foreign key does exist then lets see if anything has changed with it - } else if (isset($from[$className]['options']['foreignKeys'][$name])) { + } elseif (isset($from[$className]['options']['foreignKeys'][$name])) { $oldForeignKey = $from[$className]['options']['foreignKeys'][$name]; $oldForeignKey['name'] = $name; // If the foreign key has changed any then we need to drop the foreign key and readd it @@ -240,7 +243,7 @@ protected function _buildChanges($from, $to) // Check for new indexes foreach ($info['options']['indexes'] as $name => $index) { // If index doesn't exist in the from schema information - if ( ! isset($from[$className]['options']['indexes'][$name])) { + if (!isset($from[$className]['options']['indexes'][$name])) { $this->_changes['created_indexes'][$info['tableName']][$name] = $index; } } @@ -248,35 +251,35 @@ protected function _buildChanges($from, $to) // Loop over the from schema information and compare it to the to schema information foreach ($from as $className => $info) { // If the class exists in the from but not in the to then it is a dropped table - if ( ! isset($to[$className])) { + if (!isset($to[$className])) { $table = array('tableName' => $info['tableName'], - 'columns' => $info['columns'], - 'options' => array('type' => $info['options']['type'], - 'charset' => $info['options']['charset'], - 'collate' => $info['options']['collate'], - 'indexes' => $info['options']['indexes'], - 'foreignKeys' => $info['options']['foreignKeys'], - 'primary' => $info['options']['primary'])); + 'columns' => $info['columns'], + 'options' => array('type' => $info['options']['type'], + 'charset' => $info['options']['charset'], + 'collate' => $info['options']['collate'], + 'indexes' => $info['options']['indexes'], + 'foreignKeys' => $info['options']['foreignKeys'], + 'primary' => $info['options']['primary'])); $this->_changes['dropped_tables'][$info['tableName']] = $table; } // Check for removed columns foreach ($info['columns'] as $name => $column) { // If column exists in the from but not in the to then we need to remove it - if (isset($to[$className]) && ! isset($to[$className]['columns'][$name])) { + if (isset($to[$className]) && !isset($to[$className]['columns'][$name])) { $this->_changes['dropped_columns'][$info['tableName']][$name] = $column; } } // Check for dropped foreign keys foreach ($info['options']['foreignKeys'] as $name => $foreignKey) { // If the foreign key exists in the from but not in the to then we need to drop it - if ( ! isset($to[$className]['options']['foreignKeys'][$name])) { + if (!isset($to[$className]['options']['foreignKeys'][$name])) { $this->_changes['dropped_foreign_keys'][$info['tableName']][$name] = $foreignKey; } } // Check for removed indexes foreach ($info['options']['indexes'] as $name => $index) { // If the index exists in the from but not the to then we need to remove it - if ( ! isset($to[$className]['options']['indexes'][$name])) { + if (!isset($to[$className]['options']['indexes'][$name])) { $this->_changes['dropped_indexes'][$info['tableName']][$name] = $index; } } @@ -286,9 +289,10 @@ protected function _buildChanges($from, $to) } /** - * Build all the model schema information for the passed array of models + * Build all the model schema information for the passed array of models. + * + * @param array $models Array of models to build the schema information for * - * @param array $models Array of models to build the schema information for * @return array $info Array of schema information for all the passed models */ protected function _buildModelInformation(array $models) @@ -301,15 +305,14 @@ protected function _buildModelInformation(array $models) } } - $info = $this->_cleanModelInformation($info); - - return $info; + return $this->_cleanModelInformation($info); } /** - * Clean the produced model information of any potential prefix text + * Clean the produced model information of any potential prefix text. + * + * @param mixed $info Either array or string to clean of prefixes * - * @param mixed $info Either array or string to clean of prefixes * @return mixed $info Cleaned value which is either an array or string */ protected function _cleanModelInformation($info) @@ -320,18 +323,19 @@ protected function _cleanModelInformation($info) $key = $this->_cleanModelInformation($key); $info[$key] = $this->_cleanModelInformation($value); } + return $info; - } else { - $find = array( - self::$_toPrefix, - self::$_fromPrefix, - Doctrine_Inflector::tableize(self::$_toPrefix) . '_', - Doctrine_Inflector::tableize(self::$_fromPrefix) . '_', - Doctrine_Inflector::tableize(self::$_toPrefix), - Doctrine_Inflector::tableize(self::$_fromPrefix) - ); - return str_replace($find, '', (string) $info); } + $find = array( + self::$_toPrefix, + self::$_fromPrefix, + Doctrine_Inflector::tableize(self::$_toPrefix).'_', + Doctrine_Inflector::tableize(self::$_fromPrefix).'_', + Doctrine_Inflector::tableize(self::$_toPrefix), + Doctrine_Inflector::tableize(self::$_fromPrefix), + ); + + return str_replace($find, '', (string) $info); } /** @@ -339,12 +343,13 @@ protected function _cleanModelInformation($info) * Used to determine if a directory contains YAML or PHP files. * * @param string $item + * * @return string $extension */ protected function _getItemExtension($item) { if (is_dir($item)) { - $files = glob($item . DIRECTORY_SEPARATOR . '*'); + $files = glob($item.DIRECTORY_SEPARATOR.'*'); } else { $files = array($item); } @@ -358,53 +363,55 @@ protected function _getItemExtension($item) $extension = $pathInfo['extension']; } } + return $extension; } /** - * Generate a set of models for the schema information source + * Generate a set of models for the schema information source. + * + * @param string $prefix Prefix to generate the models with + * @param mixed $item The item to generate the models from * - * @param string $prefix Prefix to generate the models with - * @param mixed $item The item to generate the models from * @return string $path The path where the models were generated + * * @throws Doctrine_Migration_Exception $e */ protected function _generateModels($prefix, $item) { - $path = $this->_tmpPath . DIRECTORY_SEPARATOR . strtolower($prefix) . '_doctrine_tmp_dirs'; + $path = $this->_tmpPath.DIRECTORY_SEPARATOR.strtolower($prefix).'_doctrine_tmp_dirs'; $options = array( 'classPrefix' => $prefix, - 'generateBaseClasses' => false + 'generateBaseClasses' => false, ); if (is_string($item) && file_exists($item)) { $extension = $this->_getItemExtension($item); - if ($extension === 'yml') { + if ('yml' === $extension) { Doctrine_Core::generateModelsFromYaml($item, $path, $options); return $path; - } else if ($extension === 'php') { + } + if ('php' === $extension) { Doctrine_Lib::copyDirectory($item, $path); return $path; - } else { - throw new Doctrine_Migration_Exception('No php or yml files found at path: "' . $item . '"'); } + throw new Doctrine_Migration_Exception('No php or yml files found at path: "'.$item.'"'); } else { try { Doctrine_Core::generateModelsFromDb($path, (array) $item, $options); + return $path; } catch (Exception $e) { - throw new Doctrine_Migration_Exception('Could not generate models from connection: ' . $e->getMessage()); + throw new Doctrine_Migration_Exception('Could not generate models from connection: '.$e->getMessage()); } } } /** - * Cleanup temporary generated models after a diff is performed - * - * @return void + * Cleanup temporary generated models after a diff is performed. */ protected function _cleanup() { @@ -418,7 +425,7 @@ protected function _cleanup() } // clean up tmp directories - Doctrine_Lib::removeDirectories($this->_tmpPath . DIRECTORY_SEPARATOR . strtolower(self::$_fromPrefix) . '_doctrine_tmp_dirs'); - Doctrine_Lib::removeDirectories($this->_tmpPath . DIRECTORY_SEPARATOR . strtolower(self::$_toPrefix) . '_doctrine_tmp_dirs'); + Doctrine_Lib::removeDirectories($this->_tmpPath.DIRECTORY_SEPARATOR.strtolower(self::$_fromPrefix).'_doctrine_tmp_dirs'); + Doctrine_Lib::removeDirectories($this->_tmpPath.DIRECTORY_SEPARATOR.strtolower(self::$_toPrefix).'_doctrine_tmp_dirs'); } } diff --git a/lib/Doctrine/Migration/Exception.php b/lib/Doctrine/Migration/Exception.php index d8e5a43ce..4449cf02b 100644 --- a/lib/Doctrine/Migration/Exception.php +++ b/lib/Doctrine/Migration/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Migration_Exception + * Doctrine_Migration_Exception. * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Migration_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Migration/IrreversibleMigrationException.php b/lib/Doctrine/Migration/IrreversibleMigrationException.php index afee24ec5..fd6b3c672 100644 --- a/lib/Doctrine/Migration/IrreversibleMigrationException.php +++ b/lib/Doctrine/Migration/IrreversibleMigrationException.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Migration_IrreversibleMigration + * Doctrine_Migration_IrreversibleMigration. * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Migration_IrreversibleMigrationException extends Doctrine_Migration_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Migration/Process.php b/lib/Doctrine/Migration/Process.php index d2e53ef80..0e78bd6aa 100644 --- a/lib/Doctrine/Migration/Process.php +++ b/lib/Doctrine/Migration/Process.php @@ -20,20 +20,20 @@ */ /** - * Doctrine_Migration_Process + * Doctrine_Migration_Process. * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Migration_Process { - protected - $_migration; + protected $_migration; public function __construct(Doctrine_Migration $migration) { @@ -46,10 +46,9 @@ public function getConnection() } /** - * Process a created table change + * Process a created table change. * * @param string $table Table definition - * @return void */ public function processCreatedTable(array $table) { @@ -57,10 +56,9 @@ public function processCreatedTable(array $table) } /** - * Process a dropped table change + * Process a dropped table change. * * @param array $table Table definition - * @return void */ public function processDroppedTable(array $table) { @@ -68,10 +66,9 @@ public function processDroppedTable(array $table) } /** - * Process a renamed table change + * Process a renamed table change. * * @param array $table Renamed table definition - * @return void */ public function processRenamedTable(array $table) { @@ -79,10 +76,9 @@ public function processRenamedTable(array $table) } /** - * Process a created column change + * Process a created column change. * * @param array $column Column definition - * @return void */ public function processCreatedColumn(array $column) { @@ -90,10 +86,9 @@ public function processCreatedColumn(array $column) } /** - * Process a dropped column change + * Process a dropped column change. * * @param array $column Column definition - * @return void */ public function processDroppedColumn(array $column) { @@ -101,10 +96,9 @@ public function processDroppedColumn(array $column) } /** - * Process a renamed column change + * Process a renamed column change. * * @param array $column Column definition - * @return void */ public function processRenamedColumn(array $column) { @@ -115,25 +109,23 @@ public function processRenamedColumn(array $column) } /** - * Process a changed column change + * Process a changed column change. * * @param array $column Changed column definition - * @return void */ public function processChangedColumn(array $column) { $options = array(); $options = $column['options']; $options['type'] = $column['type']; - + $this->getConnection()->export->alterTable($column['tableName'], array('change' => array($column['columnName'] => array('definition' => $options)))); } /** - * Process a created index change + * Process a created index change. * * @param array $index Index definition - * @return void */ public function processCreatedIndex(array $index) { @@ -141,10 +133,9 @@ public function processCreatedIndex(array $index) } /** - * Process a dropped index change + * Process a dropped index change. * * @param array $index Index definition - * @return void */ public function processDroppedIndex(array $index) { @@ -152,10 +143,9 @@ public function processDroppedIndex(array $index) } /** - * Process a created constraint change + * Process a created constraint change. * * @param array $constraint Constraint definition - * @return void */ public function processCreatedConstraint(array $constraint) { @@ -163,10 +153,9 @@ public function processCreatedConstraint(array $constraint) } /** - * Process a dropped constraint change + * Process a dropped constraint change. * * @param array $constraint Constraint definition - * @return void */ public function processDroppedConstraint(array $constraint) { @@ -174,10 +163,9 @@ public function processDroppedConstraint(array $constraint) } /** - * Process a created foreign key change + * Process a created foreign key change. * * @param array $foreignKey Foreign key definition - * @return void */ public function processCreatedForeignKey(array $foreignKey) { @@ -185,13 +173,10 @@ public function processCreatedForeignKey(array $foreignKey) } /** - * Process a dropped foreign key change - * - * @param array $foreignKey - * @return void + * Process a dropped foreign key change. */ public function processDroppedForeignKey(array $foreignKey) { $this->getConnection()->export->dropForeignKey($foreignKey['tableName'], $foreignKey['definition']['name']); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Node.php b/lib/Doctrine/Node.php index 0d0e7c296..cacca98f5 100644 --- a/lib/Doctrine/Node.php +++ b/lib/Doctrine/Node.php @@ -20,35 +20,36 @@ */ /** - * Doctrine_Node + * Doctrine_Node. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node implements IteratorAggregate { /** - * @param object $record reference to associated Doctrine_Record instance + * @param object $record reference to associated Doctrine_Record instance */ protected $record; /** - * @param array $options + * @param array $options */ protected $options; /** - * @param string $iteratorType (Pre | Post | Level) + * @param string $iteratorType (Pre | Post | Level) */ protected $iteratorType; /** - * @param array $iteratorOptions + * @param array $iteratorOptions */ protected $iteratorOptions; @@ -60,16 +61,16 @@ class Doctrine_Node implements IteratorAggregate protected $_tree; /** - * contructor, creates node with reference to record and any options + * contructor, creates node with reference to record and any options. * - * @param object $record instance of Doctrine_Record - * @param array $options options + * @param object $record instance of Doctrine_Record + * @param array $options options */ public function __construct(Doctrine_Record $record, $options) { $this->record = $record; $this->options = $options; - + // Make sure that the tree object of the root class is used in the case // of column aggregation inheritance (single table inheritance). $class = $record->getTable()->getComponentName(); @@ -78,17 +79,14 @@ public function __construct(Doctrine_Record $record, $options) if ($thisTable->getOption('inheritanceMap')) { // Move up the hierarchy until we find the "subclasses" option. This option // MUST be set on the root class of the user's hierarchy that uses STI. - while ( ! $subclasses = $table->getOption('subclasses')) { + while (!$subclasses = $table->getOption('subclasses')) { $class = get_parent_class($class); $reflectionClass = new ReflectionClass($class); if ($reflectionClass->isAbstract()) { continue; } - if ($class == 'Doctrine_Record') { - throw new Doctrine_Node_Exception("No subclasses specified. You are " - . "using Single Table Inheritance with NestedSet but you have " - . "not specified the subclasses correctly. Make sure you use " - . "setSubclasses() in the root class of your hierarchy."); + if ('Doctrine_Record' == $class) { + throw new Doctrine_Node_Exception('No subclasses specified. You are using Single Table Inheritance with NestedSet but you have not specified the subclasses correctly. Make sure you use setSubclasses() in the root class of your hierarchy.'); } $table = $table->getConnection()->getTable($class); } @@ -106,27 +104,29 @@ public function __construct(Doctrine_Record $record, $options) * This is a factory method that returns node instance based upon chosen * implementation. * - * @param object $record instance of Doctrine_Record - * @param string $implName implementation (NestedSet, AdjacencyList, MaterializedPath) - * @param array $options options + * @param object $record instance of Doctrine_Record + * @param string $implName implementation (NestedSet, AdjacencyList, MaterializedPath) + * @param array $options options + * * @return Doctrine_Node - * @throws Doctrine_Node_Exception if $implName is not a valid class + * + * @throws Doctrine_Node_Exception if $implName is not a valid class */ public static function factory(Doctrine_Record $record, $implName, $options = array()) { - $class = 'Doctrine_Node_' . $implName; + $class = 'Doctrine_Node_'.$implName; - if ( ! class_exists($class)) { - throw new Doctrine_Node_Exception("The class $class must exist and extend Doctrine_Node"); + if (!class_exists($class)) { + throw new Doctrine_Node_Exception("The class {$class} must exist and extend Doctrine_Node"); } return new $class($record, $options); } /** - * setter for record attribute + * setter for record attribute. * - * @param object $record instance of Doctrine_Record + * @param object $record instance of Doctrine_Record */ public function setRecord(Doctrine_Record $record) { @@ -134,7 +134,7 @@ public function setRecord(Doctrine_Record $record) } /** - * getter for record attribute + * getter for record attribute. * * @return Doctrine_Record */ @@ -144,10 +144,10 @@ public function getRecord() } /** - * convenience function for getIterator + * convenience function for getIterator. * - * @param string $type type of iterator (Pre | Post | Level) - * @param array $options options + * @param string $type type of iterator (Pre | Post | Level) + * @param array $options options */ public function traverse($type = 'Pre', $options = array()) { @@ -155,30 +155,30 @@ public function traverse($type = 'Pre', $options = array()) } /** - * get iterator + * get iterator. * - * @param string $type type of iterator (Pre | Post | Level) - * @param array $options options + * @param string $type type of iterator (Pre | Post | Level) + * @param array $options options */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator($type = null, $options = null) { - if ($type === null) { + if (null === $type) { $type = (isset($this->iteratorType) ? $this->iteratorType : 'Pre'); } - if ($options === null) { + if (null === $options) { $options = (isset($this->iteratorOptions) ? $this->iteratorOptions : array()); } $implName = $this->record->getTable()->getOption('treeImpl'); - $iteratorClass = 'Doctrine_Node_' . $implName . '_' . ucfirst(strtolower($type)) . 'OrderIterator'; + $iteratorClass = 'Doctrine_Node_'.$implName.'_'.ucfirst(strtolower($type)).'OrderIterator'; return new $iteratorClass($this->record, $options); } /** - * sets node's iterator type + * sets node's iterator type. * * @param int */ @@ -188,7 +188,7 @@ public function setIteratorType($type) } /** - * sets node's iterator options + * sets node's iterator options. * * @param int */ diff --git a/lib/Doctrine/Node/AdjacencyList.php b/lib/Doctrine/Node/AdjacencyList.php index 2a48613aa..d31b0f9d9 100644 --- a/lib/Doctrine/Node/AdjacencyList.php +++ b/lib/Doctrine/Node/AdjacencyList.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_AdjacencyList + * Doctrine_Node_AdjacencyList. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_AdjacencyList extends Doctrine_Node implements Doctrine_Node_Interface -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/AdjacencyList/LevelOrderIterator.php b/lib/Doctrine/Node/AdjacencyList/LevelOrderIterator.php index 115e18987..f4763c6ba 100644 --- a/lib/Doctrine/Node/AdjacencyList/LevelOrderIterator.php +++ b/lib/Doctrine/Node/AdjacencyList/LevelOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_AdjacencyList_LevelOrderIterator + * Doctrine_Node_AdjacencyList_LevelOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_AdjacencyList_LevelOrderIterator implements Iterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/AdjacencyList/PostOrderIterator.php b/lib/Doctrine/Node/AdjacencyList/PostOrderIterator.php index 1c38fa3e7..7d65fa28c 100644 --- a/lib/Doctrine/Node/AdjacencyList/PostOrderIterator.php +++ b/lib/Doctrine/Node/AdjacencyList/PostOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_AdjacencyList_PostOrderIterator + * Doctrine_Node_AdjacencyList_PostOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_AdjacencyList_PostOrderIterator implements Iterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/AdjacencyList/PreOrderIterator.php b/lib/Doctrine/Node/AdjacencyList/PreOrderIterator.php index ab9322113..9eb0dfe03 100644 --- a/lib/Doctrine/Node/AdjacencyList/PreOrderIterator.php +++ b/lib/Doctrine/Node/AdjacencyList/PreOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_AdjacencyList_PreOrderIterator + * Doctrine_Node_AdjacencyList_PreOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_AdjacencyList_PreOrderIterator implements Iterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/Exception.php b/lib/Doctrine/Node/Exception.php index d13666eb5..0f9b75940 100644 --- a/lib/Doctrine/Node/Exception.php +++ b/lib/Doctrine/Node/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_Exception + * Doctrine_Node_Exception. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/Interface.php b/lib/Doctrine/Node/Interface.php index 95a717e46..c99fccc48 100644 --- a/lib/Doctrine/Node/Interface.php +++ b/lib/Doctrine/Node/Interface.php @@ -20,249 +20,245 @@ */ /** - * Doctrine_Node_Interface + * Doctrine_Node_Interface. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ -interface Doctrine_Node_Interface { - +interface Doctrine_Node_Interface +{ /** - * test if node has previous sibling + * test if node has previous sibling. * * @return bool */ public function hasPrevSibling(); /** - * test if node has next sibling + * test if node has next sibling. * * @return bool */ public function hasNextSibling(); /** - * test if node has children + * test if node has children. * * @return bool */ public function hasChildren(); /** - * test if node has parent + * test if node has parent. * * @return bool */ public function hasParent(); /** - * gets record of prev sibling or empty record + * gets record of prev sibling or empty record. * * @return Doctrine_Record */ public function getPrevSibling(); /** - * gets record of next sibling or empty record + * gets record of next sibling or empty record. * * @return Doctrine_Record */ public function getNextSibling(); /** - * gets siblings for node + * gets siblings for node. * - * @return array array of sibling Doctrine_Record objects + * @return array array of sibling Doctrine_Record objects */ public function getSiblings($includeNode = false); /** - * gets record of first child or empty record + * gets record of first child or empty record. * * @return Doctrine_Record */ public function getFirstChild(); /** - * gets record of last child or empty record + * gets record of last child or empty record. * * @return Doctrine_Record */ public function getLastChild(); /** - * gets children for node (direct descendants only) + * gets children for node (direct descendants only). * - * @return array array of sibling Doctrine_Record objects + * @return array array of sibling Doctrine_Record objects */ public function getChildren(); /** - * gets descendants for node (direct descendants only) + * gets descendants for node (direct descendants only). * - * @return Iterator iterator to traverse descendants from node + * @return Iterator iterator to traverse descendants from node */ public function getDescendants(); /** - * gets record of parent or empty record + * gets record of parent or empty record. * * @return Doctrine_Record */ public function getParent(); /** - * gets ancestors for node + * gets ancestors for node. * * @return Doctrine_Collection */ public function getAncestors(); /** - * gets path to node from root, uses record::toString() method to get node names + * gets path to node from root, uses record::toString() method to get node names. + * + * @param string $seperator path seperator + * @param bool $includeNode whether or not to include node at end of path * - * @param string $seperator path seperator - * @param bool $includeNode whether or not to include node at end of path - * @return string string representation of path + * @return string string representation of path */ public function getPath($seperator = ' > ', $includeNode = false); /** - * gets level (depth) of node in the tree + * gets level (depth) of node in the tree. * * @return int */ public function getLevel(); /** - * gets number of children (direct descendants) + * gets number of children (direct descendants). * * @return int */ public function getNumberChildren(); /** - * gets number of descendants (children and their children) + * gets number of descendants (children and their children). * * @return int */ public function getNumberDescendants(); /** - * inserts node as parent of dest record + * inserts node as parent of dest record. * * @return bool */ public function insertAsParentOf(Doctrine_Record $dest); /** - * inserts node as previous sibling of dest record + * inserts node as previous sibling of dest record. * * @return bool */ public function insertAsPrevSiblingOf(Doctrine_Record $dest); /** - * inserts node as next sibling of dest record + * inserts node as next sibling of dest record. * * @return bool */ public function insertAsNextSiblingOf(Doctrine_Record $dest); /** - * inserts node as first child of dest record + * inserts node as first child of dest record. * * @return bool */ public function insertAsFirstChildOf(Doctrine_Record $dest); /** - * inserts node as first child of dest record + * inserts node as first child of dest record. * * @return bool */ public function insertAsLastChildOf(Doctrine_Record $dest); /** - * moves node as prev sibling of dest record - * - */ + * moves node as prev sibling of dest record. + */ public function moveAsPrevSiblingOf(Doctrine_Record $dest); /** - * moves node as next sibling of dest record - * + * moves node as next sibling of dest record. */ public function moveAsNextSiblingOf(Doctrine_Record $dest); /** - * moves node as first child of dest record - * + * moves node as first child of dest record. */ public function moveAsFirstChildOf(Doctrine_Record $dest); /** - * moves node as last child of dest record - * + * moves node as last child of dest record. */ public function moveAsLastChildOf(Doctrine_Record $dest); /** - * adds node as last child of record - * + * adds node as last child of record. */ public function addChild(Doctrine_Record $record); /** - * determines if node is leaf + * determines if node is leaf. * * @return bool */ public function isLeaf(); /** - * determines if node is root + * determines if node is root. * * @return bool */ public function isRoot(); /** - * determines if node is equal to subject node + * determines if node is equal to subject node. * * @return bool */ public function isEqualTo(Doctrine_Record $subj); /** - * determines if node is child of subject node + * determines if node is child of subject node. * * @return bool */ public function isDescendantOf(Doctrine_Record $subj); /** - * determines if node is child of or sibling to subject node + * determines if node is child of or sibling to subject node. * * @return bool */ public function isDescendantOfOrEqualTo(Doctrine_Record $subj); /** - * determines if node is valid + * determines if node is valid. * * @return bool */ public function isValidNode(); /** - * deletes node and it's descendants - * + * deletes node and it's descendants. */ public function delete(); } diff --git a/lib/Doctrine/Node/MaterializedPath.php b/lib/Doctrine/Node/MaterializedPath.php index f997e6301..eb9762630 100644 --- a/lib/Doctrine/Node/MaterializedPath.php +++ b/lib/Doctrine/Node/MaterializedPath.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_MaterializedPath + * Doctrine_Node_MaterializedPath. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_MaterializedPath extends Doctrine_Node implements Doctrine_Node_Interface -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/MaterializedPath/LevelOrderIterator.php b/lib/Doctrine/Node/MaterializedPath/LevelOrderIterator.php index 6283563c3..4c0116732 100644 --- a/lib/Doctrine/Node/MaterializedPath/LevelOrderIterator.php +++ b/lib/Doctrine/Node/MaterializedPath/LevelOrderIterator.php @@ -20,21 +20,22 @@ */ /** - * Doctrine_Node_MaterializedPath_LevelOrderIterator + * Doctrine_Node_MaterializedPath_LevelOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_MaterializedPath_LevelOrderIterator implements Iterator { - private $topNode = null; + private $topNode; - private $curNode = null; + private $curNode; public function __construct($node, $opts) { @@ -65,4 +66,4 @@ public function next() { throw new Doctrine_Exception('Not yet implemented'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Node/MaterializedPath/PostOrderIterator.php b/lib/Doctrine/Node/MaterializedPath/PostOrderIterator.php index 1cc002f06..99606e898 100644 --- a/lib/Doctrine/Node/MaterializedPath/PostOrderIterator.php +++ b/lib/Doctrine/Node/MaterializedPath/PostOrderIterator.php @@ -20,21 +20,22 @@ */ /** - * Doctrine_Node_MaterializedPath_PostOrderIterator + * Doctrine_Node_MaterializedPath_PostOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_MaterializedPath_PostOrderIterator implements Iterator { - private $topNode = null; + private $topNode; - private $curNode = null; + private $curNode; public function __construct($node, $opts) { @@ -65,4 +66,4 @@ public function next() { throw new Doctrine_Exception('Not yet implemented'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Node/MaterializedPath/PreOrderIterator.php b/lib/Doctrine/Node/MaterializedPath/PreOrderIterator.php index 4ea31bd8c..704151855 100644 --- a/lib/Doctrine/Node/MaterializedPath/PreOrderIterator.php +++ b/lib/Doctrine/Node/MaterializedPath/PreOrderIterator.php @@ -20,21 +20,22 @@ */ /** - * Doctrine_Node_MaterializedPath_PreOrderIterator + * Doctrine_Node_MaterializedPath_PreOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_MaterializedPath_PreOrderIterator implements Iterator { - private $topNode = null; + private $topNode; - private $curNode = null; + private $curNode; public function __construct($node, $opts) { @@ -65,4 +66,4 @@ public function next() { throw new Doctrine_Exception('Not yet implemented'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Node/NestedSet.php b/lib/Doctrine/Node/NestedSet.php index ce754f471..5ac55d662 100644 --- a/lib/Doctrine/Node/NestedSet.php +++ b/lib/Doctrine/Node/NestedSet.php @@ -20,115 +20,116 @@ */ /** - * Doctrine_Node_NestedSet + * Doctrine_Node_NestedSet. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms - * @author Roman Borschel + * @author Roman Borschel */ class Doctrine_Node_NestedSet extends Doctrine_Node implements Doctrine_Node_Interface { /** - * test if node has previous sibling + * test if node has previous sibling. * - * @return bool + * @return bool */ public function hasPrevSibling() { - return $this->isValidNode($this->getPrevSibling()); + return $this->isValidNode($this->getPrevSibling()); } /** - * test if node has next sibling + * test if node has next sibling. * - * @return bool - */ + * @return bool + */ public function hasNextSibling() { - return $this->isValidNode($this->getNextSibling()); + return $this->isValidNode($this->getNextSibling()); } /** - * test if node has children + * test if node has children. * - * @return bool + * @return bool */ public function hasChildren() { - return (($this->getRightValue() - $this->getLeftValue()) > 1); + return ($this->getRightValue() - $this->getLeftValue()) > 1; } /** - * test if node has parent + * test if node has parent. * - * @return bool + * @return bool */ public function hasParent() { - return $this->isValidNode($this->getRecord()) && ! $this->isRoot(); + return $this->isValidNode($this->getRecord()) && !$this->isRoot(); } /** - * gets record of prev sibling or empty record + * gets record of prev sibling or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getPrevSibling() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q = $q->addWhere("$baseAlias.rgt = ?", $this->getLeftValue() - 1); + $q = $q->addWhere("{$baseAlias}.rgt = ?", $this->getLeftValue() - 1); $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $sibling = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $sibling = array_shift($result); } - + return $sibling; } /** - * gets record of next sibling or empty record + * gets record of next sibling or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getNextSibling() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q = $q->addWhere("$baseAlias.lft = ?", $this->getRightValue() + 1); + $q = $q->addWhere("{$baseAlias}.lft = ?", $this->getRightValue() + 1); $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $sibling = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $sibling = array_shift($result); } - + return $sibling; } /** - * gets siblings for node + * gets siblings for node. * - * @return array array of sibling Doctrine_Record objects + * @return array array of sibling Doctrine_Record objects */ public function getSiblings($includeNode = false) { @@ -140,94 +141,97 @@ public function getSiblings($includeNode = false) continue; } $siblings[] = $child; - } + } } + return $siblings; } /** - * gets record of first child or empty record + * gets record of first child or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getFirstChild() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q->addWhere("$baseAlias.lft = ?", $this->getLeftValue() + 1); + $q->addWhere("{$baseAlias}.lft = ?", $this->getLeftValue() + 1); $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $child = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $child = array_shift($result); } - - return $child; + + return $child; } /** - * gets record of last child or empty record + * gets record of last child or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getLastChild() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q->addWhere("$baseAlias.rgt = ?", $this->getRightValue() - 1); + $q->addWhere("{$baseAlias}.rgt = ?", $this->getRightValue() - 1); $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $child = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $child = array_shift($result); } - - return $child; + + return $child; } /** - * gets children for node (direct descendants only) + * gets children for node (direct descendants only). * - * @return mixed The children of the node or FALSE if the node has no children. + * @return mixed the children of the node or FALSE if the node has no children */ public function getChildren() - { + { return $this->getDescendants(1); } /** - * gets descendants for node (direct descendants only) + * gets descendants for node (direct descendants only). + * + * @param mixed|null $depth * - * @return mixed The descendants of the node or FALSE if the node has no descendants. + * @return mixed the descendants of the node or FALSE if the node has no descendants */ public function getDescendants($depth = null, $includeNode = false) { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); $params = array($this->record->get('lft'), $this->record->get('rgt')); - + if ($includeNode) { - $q->addWhere("$baseAlias.lft >= ? AND $baseAlias.rgt <= ?", $params)->addOrderBy("$baseAlias.lft asc"); + $q->addWhere("{$baseAlias}.lft >= ? AND {$baseAlias}.rgt <= ?", $params)->addOrderBy("{$baseAlias}.lft asc"); } else { - $q->addWhere("$baseAlias.lft > ? AND $baseAlias.rgt < ?", $params)->addOrderBy("$baseAlias.lft asc"); + $q->addWhere("{$baseAlias}.lft > ? AND {$baseAlias}.rgt < ?", $params)->addOrderBy("{$baseAlias}.lft asc"); } - - if ($depth !== null) { - $q->addWhere("$baseAlias.level <= ?", $this->record['level'] + $depth); + + if (null !== $depth) { + $q->addWhere("{$baseAlias}.level <= ?", $this->record['level'] + $depth); } - + $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); @@ -239,64 +243,68 @@ public function getDescendants($depth = null, $includeNode = false) } /** - * gets record of parent or empty record + * gets record of parent or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getParent() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue())) - ->addWhere("$baseAlias.level >= ?", $this->record['level'] - 1) - ->addOrderBy("$baseAlias.rgt asc"); + $q->addWhere("{$baseAlias}.lft < ? AND {$baseAlias}.rgt > ?", array($this->getLeftValue(), $this->getRightValue())) + ->addWhere("{$baseAlias}.level >= ?", $this->record['level'] - 1) + ->addOrderBy("{$baseAlias}.rgt asc") + ; $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); - + if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $parent = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $parent = array_shift($result); } - + return $parent; } /** - * gets ancestors for node + * gets ancestors for node. + * + * @param mixed|null $depth * - * @param integer $deth The depth 'upstairs'. - * @return mixed The ancestors of the node or FALSE if the node has no ancestors (this - * basically means it's a root node). + * @return mixed the ancestors of the node or FALSE if the node has no ancestors (this + * basically means it's a root node) */ public function getAncestors($depth = null) { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue())) - ->addOrderBy("$baseAlias.lft asc"); - if ($depth !== null) { - $q->addWhere("$baseAlias.level >= ?", $this->record['level'] - $depth); + $q->addWhere("{$baseAlias}.lft < ? AND {$baseAlias}.rgt > ?", array($this->getLeftValue(), $this->getRightValue())) + ->addOrderBy("{$baseAlias}.lft asc") + ; + if (null !== $depth) { + $q->addWhere("{$baseAlias}.level >= ?", $this->record['level'] - $depth); } $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $ancestors = $q->execute(); if (count($ancestors) <= 0) { return false; } + return $ancestors; } /** - * gets path to node from root, uses record::toString() method to get node names + * gets path to node from root, uses record::toString() method to get node names. * - * @param string $seperator path seperator - * @param bool $includeNode whether or not to include node at end of path - * @return string string representation of path - */ + * @param string $seperator path seperator + * + * @return string string representation of path + */ public function getPath($seperator = ' > ', $includeRecord = false) { $path = array(); @@ -309,25 +317,26 @@ public function getPath($seperator = ' > ', $includeRecord = false) if ($includeRecord) { $path[] = $this->getRecord()->__toString(); } - + return implode($seperator, $path); } /** - * gets number of children (direct descendants) + * gets number of children (direct descendants). * - * @return int - */ + * @return int + */ public function getNumberChildren() { $children = $this->getChildren(); - return $children === false ? 0 : count($children); + + return false === $children ? 0 : count($children); } /** - * gets number of descendants (children and their children) + * gets number of descendants (children and their children). * - * @return int + * @return int */ public function getNumberDescendants() { @@ -335,10 +344,11 @@ public function getNumberDescendants() } /** - * inserts node as parent of dest record + * inserts node as parent of dest record. * * @return bool - * @todo Wrap in transaction + * + * @todo Wrap in transaction */ public function insertAsParentOf(Doctrine_Record $dest) { @@ -350,58 +360,60 @@ public function insertAsParentOf(Doctrine_Record $dest) if ($dest->getNode()->isRoot()) { return false; } - + // cannot insert as parent of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as parent of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as parent of itself'); return false; } - $newLeft = $dest->getNode()->getLeftValue(); + $newLeft = $dest->getNode()->getLeftValue(); $newRight = $dest->getNode()->getRightValue() + 2; - $newRoot = $dest->getNode()->getRootValue(); - $newLevel = $dest->getNode()->getLevel(); - - $conn = $this->record->getTable()->getConnection(); - try { - $conn->beginInternalTransaction(); - - // Make space for new node + $newRoot = $dest->getNode()->getRootValue(); + $newLevel = $dest->getNode()->getLevel(); + + $conn = $this->record->getTable()->getConnection(); + try { + $conn->beginInternalTransaction(); + + // Make space for new node $this->shiftRLValues($dest->getNode()->getRightValue() + 1, 2, $newRoot); // Slide child nodes over one and down one to allow new parent to wrap them - $componentName = $this->_tree->getBaseComponent(); + $componentName = $this->_tree->getBaseComponent(); $q = Doctrine_Core::getTable($componentName) ->createQuery() - ->update(); - $q->set("$componentName.lft", "$componentName.lft + 1"); - $q->set("$componentName.rgt", "$componentName.rgt + 1"); - $q->set("$componentName.level", "$componentName.level + 1"); - $q->where("$componentName.lft >= ? AND $componentName.rgt <= ?", array($newLeft, $newRight)); - $q = $this->_tree->returnQueryWithRootId($q, $newRoot); - $q->execute(); + ->update() + ; + $q->set("{$componentName}.lft", "{$componentName}.lft + 1"); + $q->set("{$componentName}.rgt", "{$componentName}.rgt + 1"); + $q->set("{$componentName}.level", "{$componentName}.level + 1"); + $q->where("{$componentName}.lft >= ? AND {$componentName}.rgt <= ?", array($newLeft, $newRight)); + $q = $this->_tree->returnQueryWithRootId($q, $newRoot); + $q->execute(); $this->record['level'] = $newLevel; - $this->insertNode($newLeft, $newRight, $newRoot); - - $conn->commit(); - } catch (Exception $e) { - $conn->rollback(); - throw $e; - } - + $this->insertNode($newLeft, $newRight, $newRoot); + + $conn->commit(); + } catch (Exception $e) { + $conn->rollback(); + throw $e; + } + return true; } /** - * inserts node as previous sibling of dest record + * inserts node as previous sibling of dest record. * * @return bool - * @todo Wrap in transaction + * + * @todo Wrap in transaction */ public function insertAsPrevSiblingOf(Doctrine_Record $dest) { @@ -411,10 +423,10 @@ public function insertAsPrevSiblingOf(Doctrine_Record $dest) } // cannot insert as sibling of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as previous sibling of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as previous sibling of itself'); return false; } @@ -422,33 +434,34 @@ public function insertAsPrevSiblingOf(Doctrine_Record $dest) $newLeft = $dest->getNode()->getLeftValue(); $newRight = $dest->getNode()->getLeftValue() + 1; $newRoot = $dest->getNode()->getRootValue(); - + $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + $this->shiftRLValues($newLeft, 2, $newRoot); $this->record['level'] = $dest['level']; $this->insertNode($newLeft, $newRight, $newRoot); // update destination left/right values to prevent a refresh // $dest->getNode()->setLeftValue($dest->getNode()->getLeftValue() + 2); // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } - + return true; } /** - * inserts node as next sibling of dest record + * inserts node as next sibling of dest record. * * @return bool - * @todo Wrap in transaction - */ + * + * @todo Wrap in transaction + */ public function insertAsNextSiblingOf(Doctrine_Record $dest) { // cannot insert a node that has already has a place within the tree @@ -457,10 +470,10 @@ public function insertAsNextSiblingOf(Doctrine_Record $dest) } // cannot insert as sibling of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as next sibling of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as next sibling of itself'); return false; } @@ -472,13 +485,13 @@ public function insertAsNextSiblingOf(Doctrine_Record $dest) $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + $this->shiftRLValues($newLeft, 2, $newRoot); $this->record['level'] = $dest['level']; $this->insertNode($newLeft, $newRight, $newRoot); // update destination left/right values to prevent a refresh // no need, node not affected - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); @@ -489,10 +502,11 @@ public function insertAsNextSiblingOf(Doctrine_Record $dest) } /** - * inserts node as first child of dest record + * inserts node as first child of dest record. * * @return bool - * @todo Wrap in transaction + * + * @todo Wrap in transaction */ public function insertAsFirstChildOf(Doctrine_Record $dest) { @@ -502,10 +516,10 @@ public function insertAsFirstChildOf(Doctrine_Record $dest) } // cannot insert as child of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as first child of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as first child of itself'); return false; } @@ -517,14 +531,14 @@ public function insertAsFirstChildOf(Doctrine_Record $dest) $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + $this->shiftRLValues($newLeft, 2, $newRoot); $this->record['level'] = $dest['level'] + 1; $this->insertNode($newLeft, $newRight, $newRoot); - + // update destination left/right values to prevent a refresh // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); @@ -535,10 +549,11 @@ public function insertAsFirstChildOf(Doctrine_Record $dest) } /** - * inserts node as last child of dest record + * inserts node as last child of dest record. * * @return bool - * @todo Wrap in transaction + * + * @todo Wrap in transaction */ public function insertAsLastChildOf(Doctrine_Record $dest) { @@ -548,10 +563,10 @@ public function insertAsLastChildOf(Doctrine_Record $dest) } // cannot insert as child of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as last child of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as last child of itself'); return false; } @@ -563,20 +578,20 @@ public function insertAsLastChildOf(Doctrine_Record $dest) $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + $this->shiftRLValues($newLeft, 2, $newRoot); $this->record['level'] = $dest['level'] + 1; $this->insertNode($newLeft, $newRight, $newRoot); // update destination left/right values to prevent a refresh // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } - + return true; } @@ -584,15 +599,15 @@ public function insertAsLastChildOf(Doctrine_Record $dest) * Accomplishes moving of nodes between different trees. * Used by the move* methods if the root values of the two nodes are different. * - * @param Doctrine_Record $dest * @param unknown_type $newLeftValue * @param unknown_type $moveType + * * @todo Better exception handling/wrapping */ private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveType) { $conn = $this->record->getTable()->getConnection(); - + try { $conn->beginInternalTransaction(); @@ -617,18 +632,18 @@ private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveTy switch ($moveType) { case 'moveAsPrevSiblingOf': $this->insertAsPrevSiblingOf($dest); - break; + break; case 'moveAsFirstChildOf': $this->insertAsFirstChildOf($dest); - break; + break; case 'moveAsNextSiblingOf': $this->insertAsNextSiblingOf($dest); - break; + break; case 'moveAsLastChildOf': $this->insertAsLastChildOf($dest); - break; + break; default: - throw new Doctrine_Node_Exception("Unknown move operation: $moveType."); + throw new Doctrine_Node_Exception("Unknown move operation: {$moveType}."); } $diff = $oldRgt - $oldLft; @@ -647,11 +662,12 @@ private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveTy $q = Doctrine_Core::getTable($componentName) ->createQuery() ->update() - ->set($componentName . '.lft', $componentName.'.lft + ?', $diff) - ->set($componentName . '.rgt', $componentName.'.rgt + ?', $diff) - ->set($componentName . '.level', $componentName.'.level + ?', $levelDiff) - ->set($componentName . '.' . $rootColName, '?', $newRoot) - ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?', array($oldLft, $oldRgt)); + ->set($componentName.'.lft', $componentName.'.lft + ?', $diff) + ->set($componentName.'.rgt', $componentName.'.rgt + ?', $diff) + ->set($componentName.'.level', $componentName.'.level + ?', $levelDiff) + ->set($componentName.'.'.$rootColName, '?', $newRoot) + ->where($componentName.'.lft > ? AND '.$componentName.'.rgt < ?', array($oldLft, $oldRgt)) + ; $q = $this->_tree->returnQueryWithRootId($q, $oldRoot); $q->execute(); @@ -661,125 +677,117 @@ private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveTy $this->shiftRLValues($first, $delta, $oldRoot); $conn->commit(); - - return true; + + return true; } catch (Exception $e) { $conn->rollback(); throw $e; } - + return false; } /** - * moves node as prev sibling of dest record - * - */ + * moves node as prev sibling of dest record. + */ public function moveAsPrevSiblingOf(Doctrine_Record $dest) { if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot move node as previous sibling of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot move node as previous sibling of itself'); - return false; - } + return false; + } if ($dest->getNode()->getRootValue() != $this->getRootValue()) { // Move between trees return $this->_moveBetweenTrees($dest, $dest->getNode()->getLeftValue(), __FUNCTION__); - } else { - // Move within the tree - $oldLevel = $this->record['level']; - $this->record['level'] = $dest['level']; - $this->updateNode($dest->getNode()->getLeftValue(), $this->record['level'] - $oldLevel); } - + // Move within the tree + $oldLevel = $this->record['level']; + $this->record['level'] = $dest['level']; + $this->updateNode($dest->getNode()->getLeftValue(), $this->record['level'] - $oldLevel); + return true; } /** - * moves node as next sibling of dest record - * + * moves node as next sibling of dest record. */ public function moveAsNextSiblingOf(Doctrine_Record $dest) { if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot move node as next sibling of itself"); - + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot move node as next sibling of itself'); + return false; } if ($dest->getNode()->getRootValue() != $this->getRootValue()) { // Move between trees return $this->_moveBetweenTrees($dest, $dest->getNode()->getRightValue() + 1, __FUNCTION__); - } else { - // Move within tree - $oldLevel = $this->record['level']; - $this->record['level'] = $dest['level']; - $this->updateNode($dest->getNode()->getRightValue() + 1, $this->record['level'] - $oldLevel); } - + // Move within tree + $oldLevel = $this->record['level']; + $this->record['level'] = $dest['level']; + $this->updateNode($dest->getNode()->getRightValue() + 1, $this->record['level'] - $oldLevel); + return true; } /** - * moves node as first child of dest record - * + * moves node as first child of dest record. */ public function moveAsFirstChildOf(Doctrine_Record $dest) { if ( - $dest === $this->record || $this->isAncestorOf($dest) || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot move node as first child of itself or into a descendant"); + $dest === $this->record || $this->isAncestorOf($dest) + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot move node as first child of itself or into a descendant'); - return false; - } + return false; + } - if ($dest->getNode()->getRootValue() != $this->getRootValue()) { + if ($dest->getNode()->getRootValue() != $this->getRootValue()) { // Move between trees return $this->_moveBetweenTrees($dest, $dest->getNode()->getLeftValue() + 1, __FUNCTION__); - } else { - // Move within tree - $oldLevel = $this->record['level']; - $this->record['level'] = $dest['level'] + 1; - $this->updateNode($dest->getNode()->getLeftValue() + 1, $this->record['level'] - $oldLevel); } + // Move within tree + $oldLevel = $this->record['level']; + $this->record['level'] = $dest['level'] + 1; + $this->updateNode($dest->getNode()->getLeftValue() + 1, $this->record['level'] - $oldLevel); return true; } /** - * moves node as last child of dest record - * + * moves node as last child of dest record. */ public function moveAsLastChildOf(Doctrine_Record $dest) { if ( - $dest === $this->record || $this->isAncestorOf($dest) || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot move node as last child of itself or into a descendant"); + $dest === $this->record || $this->isAncestorOf($dest) + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot move node as last child of itself or into a descendant'); - return false; - } + return false; + } if ($dest->getNode()->getRootValue() != $this->getRootValue()) { // Move between trees return $this->_moveBetweenTrees($dest, $dest->getNode()->getRightValue(), __FUNCTION__); - } else { - // Move within tree - $oldLevel = $this->record['level']; - $this->record['level'] = $dest['level'] + 1; - $this->updateNode($dest->getNode()->getRightValue(), $this->record['level'] - $oldLevel); } - + // Move within tree + $oldLevel = $this->record['level']; + $this->record['level'] = $dest['level'] + 1; + $this->updateNode($dest->getNode()->getRightValue(), $this->record['level'] - $oldLevel); + return true; } @@ -791,19 +799,19 @@ public function moveAsLastChildOf(Doctrine_Record $dest) public function makeRoot($newRootId) { // TODO: throw exception instead? - if ($this->getLeftValue() == 1 || ! $this->_tree->getAttribute('hasManyRoots')) { + if (1 == $this->getLeftValue() || !$this->_tree->getAttribute('hasManyRoots')) { return false; } - + $oldRgt = $this->getRightValue(); $oldLft = $this->getLeftValue(); $oldRoot = $this->getRootValue(); $oldLevel = $this->record['level']; - + $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + // Update descendants lft/rgt/root/level values $diff = 1 - $oldLft; $newRoot = $newRootId; @@ -812,41 +820,41 @@ public function makeRoot($newRootId) $q = Doctrine_Core::getTable($componentName) ->createQuery() ->update() - ->set($componentName . '.lft', $componentName.'.lft + ?', array($diff)) - ->set($componentName . '.rgt', $componentName.'.rgt + ?', array($diff)) - ->set($componentName . '.level', $componentName.'.level - ?', array($oldLevel)) - ->set($componentName . '.' . $rootColName, '?', array($newRoot)) - ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?', array($oldLft, $oldRgt)); + ->set($componentName.'.lft', $componentName.'.lft + ?', array($diff)) + ->set($componentName.'.rgt', $componentName.'.rgt + ?', array($diff)) + ->set($componentName.'.level', $componentName.'.level - ?', array($oldLevel)) + ->set($componentName.'.'.$rootColName, '?', array($newRoot)) + ->where($componentName.'.lft > ? AND '.$componentName.'.rgt < ?', array($oldLft, $oldRgt)) + ; $q = $this->_tree->returnQueryWithRootId($q, $oldRoot); $q->execute(); - + // Detach from old tree (close gap in old tree) $first = $oldRgt + 1; $delta = $oldLft - $oldRgt - 1; $this->shiftRLValues($first, $delta, $this->getRootValue()); - + // Set new lft/rgt/root/level values for root node $this->setLeftValue(1); $this->setRightValue($oldRgt - $oldLft + 1); $this->setRootValue($newRootId); $this->record['level'] = 0; - + $this->record->save(); - + $conn->commit(); - + return true; } catch (Exception $e) { $conn->rollback(); throw $e; } - + return false; } /** - * adds node as last child of record - * + * adds node as last child of record. */ public function addChild(Doctrine_Record $record) { @@ -854,90 +862,92 @@ public function addChild(Doctrine_Record $record) } /** - * determines if node is leaf + * determines if node is leaf. * - * @return bool + * @return bool */ public function isLeaf() { - return (($this->getRightValue() - $this->getLeftValue()) == 1); + return ($this->getRightValue() - $this->getLeftValue()) == 1; } /** - * determines if node is root + * determines if node is root. * - * @return bool + * @return bool */ public function isRoot() { - return ($this->getLeftValue() == 1); + return 1 == $this->getLeftValue(); } /** - * determines if node is equal to subject node + * determines if node is equal to subject node. * - * @return bool - */ + * @return bool + */ public function isEqualTo(Doctrine_Record $subj) { - return (($this->getLeftValue() == $subj->getNode()->getLeftValue()) && - ($this->getRightValue() == $subj->getNode()->getRightValue()) && - ($this->getRootValue() == $subj->getNode()->getRootValue()) - ); + return ($this->getLeftValue() == $subj->getNode()->getLeftValue()) + && ($this->getRightValue() == $subj->getNode()->getRightValue()) + && ($this->getRootValue() == $subj->getNode()->getRootValue()); } /** - * determines if node is child of subject node + * determines if node is child of subject node. * * @return bool */ public function isDescendantOf(Doctrine_Record $subj) { - return (($this->getLeftValue() > $subj->getNode()->getLeftValue()) && - ($this->getRightValue() < $subj->getNode()->getRightValue()) && - ($this->getRootValue() == $subj->getNode()->getRootValue())); + return ($this->getLeftValue() > $subj->getNode()->getLeftValue()) + && ($this->getRightValue() < $subj->getNode()->getRightValue()) + && ($this->getRootValue() == $subj->getNode()->getRootValue()); } /** - * determines if node is child of or sibling to subject node + * determines if node is child of or sibling to subject node. * - * @return bool + * @return bool */ public function isDescendantOfOrEqualTo(Doctrine_Record $subj) { - return (($this->getLeftValue() >= $subj->getNode()->getLeftValue()) && - ($this->getRightValue() <= $subj->getNode()->getRightValue()) && - ($this->getRootValue() == $subj->getNode()->getRootValue())); + return ($this->getLeftValue() >= $subj->getNode()->getLeftValue()) + && ($this->getRightValue() <= $subj->getNode()->getRightValue()) + && ($this->getRootValue() == $subj->getNode()->getRootValue()); } /** - * determines if node is ancestor of subject node + * determines if node is ancestor of subject node. * - * @return bool + * @return bool */ public function isAncestorOf(Doctrine_Record $subj) { - return (($subj->getNode()->getLeftValue() > $this->getLeftValue()) && - ($subj->getNode()->getRightValue() < $this->getRightValue()) && - ($subj->getNode()->getRootValue() == $this->getRootValue())); + return ($subj->getNode()->getLeftValue() > $this->getLeftValue()) + && ($subj->getNode()->getRightValue() < $this->getRightValue()) + && ($subj->getNode()->getRootValue() == $this->getRootValue()); } /** - * determines if node is valid + * determines if node is valid. + * + * @param mixed|null $record * * @return bool */ public function isValidNode($record = null) { - if ($record === null) { - return ($this->getRightValue() > $this->getLeftValue()); - } else if ( $record instanceof Doctrine_Record ) { - return ($record->getNode()->getRightValue() > $record->getNode()->getLeftValue()); - } else { - return false; + if (null === $record) { + return $this->getRightValue() > $this->getLeftValue(); + } + if ($record instanceof Doctrine_Record) { + return $record->getNode()->getRightValue() > $record->getNode()->getLeftValue(); } + + return false; } - + /** * Detaches the node from the tree by invalidating it's lft & rgt values * (they're set to 0). @@ -949,15 +959,16 @@ public function detach() } /** - * deletes node and it's descendants - * @todo Delete more efficiently. Wrap in transaction if needed. + * deletes node and it's descendants. + * + * @todo Delete more efficiently. Wrap in transaction if needed. */ public function delete() { $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + // TODO: add the setting whether or not to delete descendants or relocate children $oldRoot = $this->getRootValue(); $q = $this->_tree->getBaseQuery(); @@ -965,7 +976,7 @@ public function delete() $baseAlias = $this->_tree->getBaseAlias(); $componentName = $this->_tree->getBaseComponent(); - $q = $q->addWhere("$baseAlias.lft >= ? AND $baseAlias.rgt <= ?", array($this->getLeftValue(), $this->getRightValue())); + $q = $q->addWhere("{$baseAlias}.lft >= ? AND {$baseAlias}.rgt <= ?", array($this->getLeftValue(), $this->getRightValue())); $q = $this->_tree->returnQueryWithRootId($q, $oldRoot); @@ -976,38 +987,39 @@ public function delete() $first = $this->getRightValue() + 1; $delta = $this->getLeftValue() - $this->getRightValue() - 1; $this->shiftRLValues($first, $delta, $oldRoot); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } - - return true; + + return true; } /** - * sets node's left and right values and save's it + * sets node's left and right values and save's it. * - * @param int $destLeft node left value - * @param int $destRight node right value - */ + * @param int $destLeft node left value + * @param int $destRight node right value + */ private function insertNode($destLeft = 0, $destRight = 0, $destRoot = 1) { $this->setLeftValue($destLeft); $this->setRightValue($destRight); $this->setRootValue($destRoot); - $this->record->save(); + $this->record->save(); } /** - * move node's and its children to location $destLeft and updates rest of tree + * move node's and its children to location $destLeft and updates rest of tree. + * + * @param int $destLeft destination left value * - * @param int $destLeft destination left value * @todo Wrap in transaction */ private function updateNode($destLeft, $levelDiff) - { + { $componentName = $this->_tree->getBaseComponent(); $left = $this->getLeftValue(); $right = $this->getRightValue(); @@ -1018,7 +1030,7 @@ private function updateNode($destLeft, $levelDiff) $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + // Make room in the new branch $this->shiftRLValues($destLeft, $treeSize, $rootId); @@ -1031,8 +1043,9 @@ private function updateNode($destLeft, $levelDiff) $q = Doctrine_Core::getTable($componentName) ->createQuery() ->update() - ->set($componentName . '.level', $componentName.'.level + ?', array($levelDiff)) - ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?', array($left, $right)); + ->set($componentName.'.level', $componentName.'.level + ?', array($levelDiff)) + ->where($componentName.'.lft > ? AND '.$componentName.'.rgt < ?', array($left, $right)) + ; $q = $this->_tree->returnQueryWithRootId($q, $rootId); $q->execute(); @@ -1044,13 +1057,13 @@ private function updateNode($destLeft, $levelDiff) $this->record->save(); $this->record->refresh(); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } - + return true; } @@ -1060,31 +1073,35 @@ private function updateNode($destLeft, $levelDiff) * Note: This method does wrap its database queries in a transaction. This should be done * by the invoking code. * - * @param int $first First node to be shifted - * @param int $delta Value to be shifted by, can be negative - */ + * @param int $first First node to be shifted + * @param int $delta Value to be shifted by, can be negative + */ private function shiftRlValues($first, $delta, $rootId = 1) { // shift left columns $componentName = $this->_tree->getBaseComponent(); - $qLeft = Doctrine_Core::getTable($componentName) + $qLeft = Doctrine_Core::getTable($componentName) ->createQuery() - ->update($componentName); + ->update($componentName) + ; $qRight = Doctrine_Core::getTable($componentName) ->createQuery() - ->update($componentName); + ->update($componentName) + ; - $qLeft = $qLeft->set($componentName . '.lft', $componentName.'.lft + ?', $delta) - ->where($componentName . '.lft >= ?', $first); + $qLeft = $qLeft->set($componentName.'.lft', $componentName.'.lft + ?', $delta) + ->where($componentName.'.lft >= ?', $first) + ; $qLeft = $this->_tree->returnQueryWithRootId($qLeft, $rootId); $resultLeft = $qLeft->execute(); // shift right columns - $qRight = $qRight->set($componentName . '.rgt', $componentName.'.rgt + ?', $delta) - ->where($componentName . '.rgt >= ?', $first); + $qRight = $qRight->set($componentName.'.rgt', $componentName.'.rgt + ?', $delta) + ->where($componentName.'.rgt >= ?', $first) + ; $qRight = $this->_tree->returnQueryWithRootId($qRight, $rootId); @@ -1092,39 +1109,43 @@ private function shiftRlValues($first, $delta, $rootId = 1) } /** - * adds '$delta' to all Left and Right values that are >= '$first' and <= '$last'. + * adds '$delta' to all Left and Right values that are >= '$first' and <= '$last'. * '$delta' can also be negative. * * Note: This method does wrap its database queries in a transaction. This should be done * by the invoking code. * - * @param int $first First node to be shifted (L value) - * @param int $last Last node to be shifted (L value) - * @param int $delta Value to be shifted by, can be negative - */ + * @param int $first First node to be shifted (L value) + * @param int $last Last node to be shifted (L value) + * @param int $delta Value to be shifted by, can be negative + */ private function shiftRlRange($first, $last, $delta, $rootId = 1) { $componentName = $this->_tree->getBaseComponent(); - $qLeft = Doctrine_Core::getTable($componentName) + $qLeft = Doctrine_Core::getTable($componentName) ->createQuery() - ->update(); + ->update() + ; $qRight = Doctrine_Core::getTable($componentName) ->createQuery() - ->update(); + ->update() + ; // shift left column values - $qLeft = $qLeft->set($componentName . '.lft', $componentName.'.lft + ?', $delta) - ->where($componentName . '.lft >= ? AND ' . $componentName . '.lft <= ?', array($first, $last)); - + $qLeft = $qLeft->set($componentName.'.lft', $componentName.'.lft + ?', $delta) + ->where($componentName.'.lft >= ? AND '.$componentName.'.lft <= ?', array($first, $last)) + ; + $qLeft = $this->_tree->returnQueryWithRootId($qLeft, $rootId); $resultLeft = $qLeft->execute(); - + // shift right column values - $qRight = $qRight->set($componentName . '.rgt', $componentName.'.rgt + ?', $delta) - ->where($componentName . '.rgt >= ? AND ' . $componentName . '.rgt <= ?', array($first, $last)); + $qRight = $qRight->set($componentName.'.rgt', $componentName.'.rgt + ?', $delta) + ->where($componentName.'.rgt >= ? AND '.$componentName.'.rgt <= ?', array($first, $last)) + ; $qRight = $this->_tree->returnQueryWithRootId($qRight, $rootId); @@ -1132,88 +1153,89 @@ private function shiftRlRange($first, $last, $delta, $rootId = 1) } /** - * gets record's left value + * gets record's left value. * - * @return int - */ + * @return int + */ public function getLeftValue() { return $this->record->get('lft'); } /** - * sets record's left value + * sets record's left value. * - * @param int - */ + * @param int + */ public function setLeftValue($lft) { - $this->record->set('lft', $lft); + $this->record->set('lft', $lft); } /** - * gets record's right value + * gets record's right value. * - * @return int - */ + * @return int + */ public function getRightValue() { - return $this->record->get('rgt'); + return $this->record->get('rgt'); } /** - * sets record's right value + * sets record's right value. * - * @param int - */ + * @param int + */ public function setRightValue($rgt) { - $this->record->set('rgt', $rgt); + $this->record->set('rgt', $rgt); } /** - * gets level (depth) of node in the tree + * gets level (depth) of node in the tree. * - * @return int - */ + * @return int + */ public function getLevel() { - if ( ! isset($this->record['level'])) { + if (!isset($this->record['level'])) { $baseAlias = $this->_tree->getBaseAlias(); $componentName = $this->_tree->getBaseComponent(); $q = $this->_tree->getBaseQuery(); - $q = $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue())); + $q = $q->addWhere("{$baseAlias}.lft < ? AND {$baseAlias}.rgt > ?", array($this->getLeftValue(), $this->getRightValue())); $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); - + $coll = $q->execute(); $this->record['level'] = count($coll) ? count($coll) : 0; } + return $this->record['level']; } /** - * get records root id value - * - */ + * get records root id value. + */ public function getRootValue() { if ($this->_tree->getAttribute('hasManyRoots')) { return $this->record->get($this->_tree->getAttribute('rootColumnName')); } + return 1; } /** - * sets records root id value + * sets records root id value. * - * @param int + * @param int */ public function setRootValue($value) { if ($this->_tree->getAttribute('hasManyRoots')) { - $this->record->set($this->_tree->getAttribute('rootColumnName'), $value); - } + $this->record->set($this->_tree->getAttribute('rootColumnName'), $value); + } } } diff --git a/lib/Doctrine/Node/NestedSet/LevelOrderIterator.php b/lib/Doctrine/Node/NestedSet/LevelOrderIterator.php index c7dde8e86..09405ac40 100644 --- a/lib/Doctrine/Node/NestedSet/LevelOrderIterator.php +++ b/lib/Doctrine/Node/NestedSet/LevelOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_NestedSet_LevelOrderIterator + * Doctrine_Node_NestedSet_LevelOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_NestedSet_LevelOrderIterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/NestedSet/PostOrderIterator.php b/lib/Doctrine/Node/NestedSet/PostOrderIterator.php index 4e8689b3d..df66a366a 100644 --- a/lib/Doctrine/Node/NestedSet/PostOrderIterator.php +++ b/lib/Doctrine/Node/NestedSet/PostOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_NestedSet_PostOrderIterator + * Doctrine_Node_NestedSet_PostOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_NestedSet_PostOrderIterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/NestedSet/PreOrderIterator.php b/lib/Doctrine/Node/NestedSet/PreOrderIterator.php index a35a72223..ba27ac324 100644 --- a/lib/Doctrine/Node/NestedSet/PreOrderIterator.php +++ b/lib/Doctrine/Node/NestedSet/PreOrderIterator.php @@ -20,50 +20,48 @@ */ /** - * Doctrine_Node_NestedSet_PreOrderIterator + * Doctrine_Node_NestedSet_PreOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_NestedSet_PreOrderIterator implements Iterator { /** - * @var Doctrine_Collection $collection + * @var Doctrine_Collection */ protected $collection; /** - * @var array $keys + * @var array */ protected $keys; - /** - * @var mixed $key - */ protected $key; /** - * @var integer $index + * @var int */ protected $index; /** - * @var integer $index + * @var int */ protected $prevIndex; /** - * @var integer $index + * @var int */ protected $traverseLevel; /** - * @var integer $count + * @var int */ protected $count; @@ -75,30 +73,28 @@ public function __construct($record, $opts) $params = array($record->get('lft'), $record->get('rgt')); if (isset($opts['include_record']) && $opts['include_record']) { - $query = $q->where("$componentName.lft >= ? AND $componentName.rgt <= ?", $params)->orderBy("$componentName.lft asc"); + $query = $q->where("{$componentName}.lft >= ? AND {$componentName}.rgt <= ?", $params)->orderBy("{$componentName}.lft asc"); } else { - $query = $q->where("$componentName.lft > ? AND $componentName.rgt < ?", $params)->orderBy("$componentName.lft asc"); + $query = $q->where("{$componentName}.lft > ? AND {$componentName}.rgt < ?", $params)->orderBy("{$componentName}.lft asc"); } - + $query = $record->getTable()->getTree()->returnQueryWithRootId($query, $record->getNode()->getRootValue()); - $this->maxLevel = isset($opts['depth']) ? ($opts['depth'] + $record->getNode()->getLevel()) : 0; - $this->options = $opts; + $this->maxLevel = isset($opts['depth']) ? ($opts['depth'] + $record->getNode()->getLevel()) : 0; + $this->options = $opts; $this->collection = isset($opts['collection']) ? $opts['collection'] : $query->execute(); - $this->keys = $this->collection->getKeys(); - $this->count = $this->collection->count(); - $this->index = -1; - $this->level = $record->getNode()->getLevel(); - $this->prevLeft = $record->getNode()->getLeftValue(); + $this->keys = $this->collection->getKeys(); + $this->count = $this->collection->count(); + $this->index = -1; + $this->level = $record->getNode()->getLevel(); + $this->prevLeft = $record->getNode()->getLeftValue(); // clear the table identity cache $record->getTable()->clear(); } /** - * rewinds the iterator - * - * @return void + * rewinds the iterator. */ public function rewind() { @@ -107,9 +103,9 @@ public function rewind() } /** - * returns the current key + * returns the current key. * - * @return integer + * @return int */ public function key() { @@ -117,7 +113,7 @@ public function key() } /** - * returns the current record + * returns the current record. * * @return Doctrine_Record */ @@ -125,13 +121,12 @@ public function current() { $record = $this->collection->get($this->key); $record->getNode()->setLevel($this->level); + return $record; } /** - * advances the internal pointer - * - * @return void + * advances the internal pointer. */ public function next() { @@ -147,11 +142,11 @@ public function next() } /** - * @return boolean whether or not the iteration will continue + * @return bool whether or not the iteration will continue */ public function valid() { - return ($this->index < $this->count); + return $this->index < $this->count; } public function count() @@ -161,7 +156,7 @@ public function count() private function updateLevel() { - if ( ! (isset($this->options['include_record']) && $this->options['include_record'] && $this->index == 0)) { + if (!(isset($this->options['include_record']) && $this->options['include_record'] && 0 == $this->index)) { $left = $this->collection->get($this->key)->getNode()->getLeftValue(); $this->level += $this->prevLeft - $left + 2; $this->prevLeft = $left; @@ -170,14 +165,15 @@ private function updateLevel() private function advanceIndex() { - $this->index++; + ++$this->index; $i = $this->index; if (isset($this->keys[$i])) { - $this->key = $this->keys[$i]; + $this->key = $this->keys[$i]; $this->updateLevel(); + return $this->current(); } return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Null.php b/lib/Doctrine/Null.php index 4897de92d..2d3cf3dd8 100644 --- a/lib/Doctrine/Null.php +++ b/lib/Doctrine/Null.php @@ -20,28 +20,29 @@ */ /** - * Doctrine_Null + * Doctrine_Null. * * Simple empty class representing a null value * used for extra fast null value testing with isset() rather than array_key_exists() * - * @package Doctrine - * @subpackage Null * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ final class Doctrine_Null -{ +{ public function exists() { - return false; + return false; } public function __toString() { return ''; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Overloadable.php b/lib/Doctrine/Overloadable.php index b8e61eee3..ccc22ed7c 100644 --- a/lib/Doctrine/Overloadable.php +++ b/lib/Doctrine/Overloadable.php @@ -21,24 +21,27 @@ /** * Doctrine_Overloadable - * a very generic overloading interface + * a very generic overloading interface. * - * @package Doctrine - * @subpackage Overloadable * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ -interface Doctrine_Overloadable { +interface Doctrine_Overloadable +{ /** * __call - * method overloader + * method overloader. + * + * @param string $m the name of the method + * @param array $a method arguments * - * @param string $m the name of the method - * @param array $a method arguments - * @return mixed return value of the method + * @return mixed return value of the method */ public function __call($m, $a); } diff --git a/lib/Doctrine/Pager.php b/lib/Doctrine/Pager.php index 818f4e721..83cdf998d 100644 --- a/lib/Doctrine/Pager.php +++ b/lib/Doctrine/Pager.php @@ -20,68 +20,65 @@ */ /** - * Doctrine_Pager + * Doctrine_Pager. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager { /** - * @var Doctrine_Query $_query Doctrine_Query object related to the pager + * @var Doctrine_Query Doctrine_Query object related to the pager */ protected $_query; /** - * @var Doctrine_Query $_countQuery Doctrine_Query object related to the counter of pager + * @var Doctrine_Query Doctrine_Query object related to the counter of pager */ protected $_countQuery; /** - * @var array $_countQueryParams Hold the params to be used by Doctrine_Query counter object of pager + * @var array Hold the params to be used by Doctrine_Query counter object of pager */ protected $_countQueryParams; /** - * @var integer $_numResults Number of results found + * @var int Number of results found */ protected $_numResults; /** - * @var integer $_maxPerPage Maximum number of itens per page + * @var int Maximum number of itens per page */ protected $_maxPerPage; /** - * @var integer $page Current page + * @var int Current page */ protected $_page; /** - * @var integer $_lastPage Last page (total of pages) + * @var int Last page (total of pages) */ protected $_lastPage; /** - * @var boolean $_executed Pager was initialized (called "execute" at least once) + * @var bool Pager was initialized (called "execute" at least once) */ protected $_executed; - - /** - * __construct + * __construct. * - * @param mixed $query Accepts either a Doctrine_Query object or a string - * (which does the Doctrine_Query class creation). - * @param int $page Current page - * @param int $maxPerPage Maximum itens per page - * @return void + * @param mixed $query accepts either a Doctrine_Query object or a string + * (which does the Doctrine_Query class creation) + * @param int $page Current page + * @param int $maxPerPage Maximum itens per page */ public function __construct($query, $page, $maxPerPage = 0) { @@ -94,12 +91,11 @@ public function __construct($query, $page, $maxPerPage = 0) } /** - * _initialize + * _initialize. * * Initialize Pager object calculating number of results * - * @param $params Optional parameters to Doctrine_Query::execute - * @return void + * @param $params Optional parameters to Doctrine_Query::execute */ protected function _initialize($params = array()) { @@ -114,11 +110,9 @@ protected function _initialize($params = array()) } /** - * _adjustOffset + * _adjustOffset. * * Adjusts last page of Doctrine_Pager, offset and limit of Doctrine_Query associated - * - * @return void */ protected function _adjustOffset() { @@ -135,11 +129,11 @@ protected function _adjustOffset() } /** - * getExecuted + * getExecuted. * * Returns the check if Pager was already executed at least once * - * @return boolen Pager was executed + * @return boolen Pager was executed */ public function getExecuted() { @@ -147,12 +141,11 @@ public function getExecuted() } /** - * _setExecuted + * _setExecuted. * * Defines if Pager was already executed * - * @param $executed Pager was executed - * @return void + * @param $executed Pager was executed */ protected function _setExecuted($executed) { @@ -160,28 +153,29 @@ protected function _setExecuted($executed) } /** - * getRange + * getRange. * * Builds and return a Doctrine_Pager_Range_* based on arguments * * @param string $rangeStyle Pager Range style - * @param array $options Custom subclass implementation options. + * @param array $options Custom subclass implementation options. * Default is a blank array + * * @return Doctrine_Pager_Range Pager Range */ public function getRange($rangeStyle, $options = array()) { - $class = 'Doctrine_Pager_Range_' . ucfirst($rangeStyle); + $class = 'Doctrine_Pager_Range_'.ucfirst($rangeStyle); return new $class($options, $this); } /** - * getNumResults + * getNumResults. * * Returns the number of results found * - * @return int the number of results found + * @return int the number of results found */ public function getNumResults() { @@ -189,18 +183,15 @@ public function getNumResults() return $this->_numResults; } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the number of results of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the number of results of a not yet executed Pager query'); } /** - * _setNumResults + * _setNumResults. * * Defines the number of total results on initial query * - * @param $nb Number of results found on initial query fetch - * @return void + * @param $nb Number of results found on initial query fetch */ protected function _setNumResults($nb) { @@ -208,11 +199,11 @@ protected function _setNumResults($nb) } /** - * getFirstPage + * getFirstPage. * * Returns the first page * - * @return int first page + * @return int first page */ public function getFirstPage() { @@ -220,11 +211,11 @@ public function getFirstPage() } /** - * getLastPage + * getLastPage. * * Returns the last page (total of pages) * - * @return int last page (total of pages) + * @return int last page (total of pages) */ public function getLastPage() { @@ -232,18 +223,15 @@ public function getLastPage() return $this->_lastPage; } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the last page number of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the last page number of a not yet executed Pager query'); } /** - * _setLastPage + * _setLastPage. * * Defines the last page (total of pages) * - * @param $page last page (total of pages) - * @return void + * @param $page last page (total of pages) */ protected function _setLastPage($page) { @@ -255,11 +243,11 @@ protected function _setLastPage($page) } /** - * getLastPage + * getLastPage. * * Returns the current page * - * @return int current page + * @return int current page */ public function getPage() { @@ -267,11 +255,11 @@ public function getPage() } /** - * getNextPage + * getNextPage. * * Returns the next page * - * @return int next page + * @return int next page */ public function getNextPage() { @@ -279,17 +267,15 @@ public function getNextPage() return min($this->getPage() + 1, $this->getLastPage()); } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the last page number of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the last page number of a not yet executed Pager query'); } /** - * getPreviousPage + * getPreviousPage. * * Returns the previous page * - * @return int previous page + * @return int previous page */ public function getPreviousPage() { @@ -297,13 +283,11 @@ public function getPreviousPage() return max($this->getPage() - 1, $this->getFirstPage()); } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the previous page number of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the previous page number of a not yet executed Pager query'); } /** - * getFirstIndice + * getFirstIndice. * * Return the first indice number for the current page * @@ -315,7 +299,7 @@ public function getFirstIndice() } /** - * getLastIndice + * getLastIndice. * * Return the last indice number for the current page * @@ -323,15 +307,15 @@ public function getFirstIndice() */ public function getLastIndice() { - return min($this->getNumResults(), ($this->getPage() * $this->getMaxPerPage())); + return min($this->getNumResults(), $this->getPage() * $this->getMaxPerPage()); } /** - * haveToPaginate + * haveToPaginate. * * Return true if it's necessary to paginate or false if not * - * @return bool true if it is necessary to paginate, false otherwise + * @return bool true if it is necessary to paginate, false otherwise */ public function haveToPaginate() { @@ -339,18 +323,15 @@ public function haveToPaginate() return $this->getNumResults() > $this->getMaxPerPage(); } - throw new Doctrine_Pager_Exception( - 'Cannot know if it is necessary to paginate a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot know if it is necessary to paginate a not yet executed Pager query'); } /** - * setPage + * setPage. * * Defines the current page and automatically adjust offset and limits * - * @param $page current page - * @return void + * @param $page current page */ public function setPage($page) { @@ -359,12 +340,11 @@ public function setPage($page) } /** - * _setPage + * _setPage. * * Defines the current page * - * @param $page current page - * @return void + * @param $page current page */ protected function _setPage($page) { @@ -373,11 +353,11 @@ protected function _setPage($page) } /** - * getLastPage + * getLastPage. * * Returns the maximum number of itens per page * - * @return int maximum number of itens per page + * @return int maximum number of itens per page */ public function getMaxPerPage() { @@ -385,18 +365,17 @@ public function getMaxPerPage() } /** - * setMaxPerPage + * setMaxPerPage. * * Defines the maximum number of itens per page and automatically adjust offset and limits * - * @param $max maximum number of itens per page - * @return void + * @param $max maximum number of itens per page */ public function setMaxPerPage($max) { if ($max > 0) { $this->_maxPerPage = $max; - } else if ($max == 0) { + } elseif (0 == $max) { $this->_maxPerPage = 25; } else { $this->_maxPerPage = abs($max); @@ -406,11 +385,11 @@ public function setMaxPerPage($max) } /** - * getResultsInPage + * getResultsInPage. * * Returns the number of itens in current page * - * @return int Number of itens in current page + * @return int Number of itens in current page */ public function getResultsInPage() { @@ -426,11 +405,11 @@ public function getResultsInPage() } /** - * getQuery + * getQuery. * * Returns the Doctrine_Query collector object related to the pager * - * @return Doctrine_Query Doctrine_Query object related to the pager + * @return Doctrine_Query Doctrine_Query object related to the pager */ public function getQuery() { @@ -438,52 +417,53 @@ public function getQuery() } /** - * _setQuery + * _setQuery. * * Defines the collector query to be used by pager * - * @param Doctrine_Query Accepts either a Doctrine_Query object or a string - * (which does the Doctrine_Query class creation). - * @return void + * @param Doctrine_Query accepts either a Doctrine_Query object or a string + * (which does the Doctrine_Query class creation) */ protected function _setQuery($query) { if (is_string($query)) { $query = Doctrine_Query::create() - ->parseDqlQuery($query); + ->parseDqlQuery($query) + ; } $this->_query = $query; } /** - * getCountQuery + * getCountQuery. * * Returns the Doctrine_Query object that is used to make the count results to pager * - * @return Doctrine_Query Doctrine_Query object related to the pager + * @return Doctrine_Query Doctrine_Query object related to the pager */ public function getCountQuery() { - return ($this->_countQuery !== null) ? $this->_countQuery : $this->_query; + return (null !== $this->_countQuery) ? $this->_countQuery : $this->_query; } /** - * setCountQuery + * setCountQuery. * * Defines the counter query to be used by pager * - * @param Doctrine_Query Accepts either a Doctrine_Query object or a string - * (which does the Doctrine_Query class creation). - * @param array Optional params to be used by counter Doctrine_Query. + * @param Doctrine_Query accepts either a Doctrine_Query object or a string + * (which does the Doctrine_Query class creation) + * @param array Optional params to be used by counter Doctrine_Query. * If not defined, the params passed to execute method will be used. - * @return void + * @param mixed|null $params */ public function setCountQuery($query, $params = null) { if (is_string($query)) { $query = Doctrine_Query::create() - ->parseDqlQuery($query); + ->parseDqlQuery($query) + ; } $this->_countQuery = $query; @@ -494,33 +474,32 @@ public function setCountQuery($query, $params = null) } /** - * getCountQueryParams + * getCountQueryParams. * * Returns the params to be used by counter Doctrine_Query * - * @return array Doctrine_Query counter params + * @return array Doctrine_Query counter params */ public function getCountQueryParams($defaultParams = array()) { - return ($this->_countQueryParams !== null) ? $this->_countQueryParams : $defaultParams; + return (null !== $this->_countQueryParams) ? $this->_countQueryParams : $defaultParams; } /** - * setCountQueryParams + * setCountQueryParams. * * Defines the params to be used by counter Doctrine_Query * - * @param array Optional params to be used by counter Doctrine_Query. + * @param array Optional params to be used by counter Doctrine_Query. * If not defined, the params passed to execute method will be used. - * @param boolean Optional argument that append the query param instead of overriding the existent ones. - * @return void + * @param bool optional argument that append the query param instead of overriding the existent ones */ public function setCountQueryParams($params = array(), $append = false) { if ($append && is_array($this->_countQueryParams)) { $this->_countQueryParams = array_merge($this->_countQueryParams, $params); } else { - if ($params !== null && !is_array($params)) { + if (null !== $params && !is_array($params)) { $params = array($params); } @@ -531,20 +510,21 @@ public function setCountQueryParams($params = array(), $append = false) } /** - * execute + * execute. * * Executes the query, populates the collection and then return it * - * @param $params Optional parameters to Doctrine_Query::execute - * @param $hydrationMode Hydration Mode of Doctrine_Query::execute returned ResultSet. - * @return Doctrine_Collection The root collection + * @param $params Optional parameters to Doctrine_Query::execute + * @param $hydrationMode Hydration Mode of Doctrine_Query::execute returned ResultSet + * + * @return Doctrine_Collection The root collection */ public function execute($params = array(), $hydrationMode = null) { - if ( !$this->getExecuted()) { + if (!$this->getExecuted()) { $this->_initialize($params); } - + return $this->getQuery()->execute($params, $hydrationMode); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Pager/Exception.php b/lib/Doctrine/Pager/Exception.php index a8f0ecd48..5d8e6c231 100644 --- a/lib/Doctrine/Pager/Exception.php +++ b/lib/Doctrine/Pager/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Pager_Exception + * Doctrine_Pager_Exception. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Pager/Layout.php b/lib/Doctrine/Pager/Layout.php index bc831b934..843a736bc 100644 --- a/lib/Doctrine/Pager/Layout.php +++ b/lib/Doctrine/Pager/Layout.php @@ -20,63 +20,61 @@ */ /** - * Doctrine_Pager_Layout + * Doctrine_Pager_Layout. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager_Layout { /** - * @var Doctrine_Pager $_pager Doctrine_Pager object related to the pager layout + * @var Doctrine_Pager Doctrine_Pager object related to the pager layout */ private $_pager; /** - * @var Doctrine_Pager_Range $_pagerRange Doctrine_Pager_Range object related to the pager layout + * @var Doctrine_Pager_Range Doctrine_Pager_Range object related to the pager layout */ private $_pagerRange; /** - * @var string $_template Template to be applied for inactive pages - * (and also active is selected template is not defined) + * @var string Template to be applied for inactive pages + * (and also active is selected template is not defined) */ private $_template; /** - * @var string $_selectedTemplate Template to be applied for active page + * @var string Template to be applied for active page */ private $_selectedTemplate; /** - * @var string $_separatorTemplate Separator template, applied between each page + * @var string Separator template, applied between each page */ private $_separatorTemplate; /** - * @var string $_urlMask URL to be assigned for each page. Masks are used as: {%var_name} + * @var string URL to be assigned for each page. Masks are used as: {%var_name} */ private $_urlMask; - + /** - * @var array $_maskReplacements Stores references of masks and their correspondent - * (replaces defined masks with new masks or values) + * @var array Stores references of masks and their correspondent + * (replaces defined masks with new masks or values) */ private $_maskReplacements = array(); - /** - * __construct + * __construct. * - * @param Doctrine_Pager $pager Doctrine_Pager object related to the pager layout - * @param Doctrine_Pager_Range $pagerRange Doctrine_Pager_Range object related to the pager layout - * @param string $urlMask URL to be assigned for each page - * @return void + * @param Doctrine_Pager $pager Doctrine_Pager object related to the pager layout + * @param Doctrine_Pager_Range $pagerRange Doctrine_Pager_Range object related to the pager layout + * @param string $urlMask URL to be assigned for each page */ public function __construct($pager, $pagerRange, $urlMask) { @@ -90,11 +88,11 @@ public function __construct($pager, $pagerRange, $urlMask) } /** - * getPager + * getPager. * * Returns the Doctrine_Pager object related to the pager layout * - * @return Doctrine_Pager Doctrine_Pager object related to the pager range + * @return Doctrine_Pager Doctrine_Pager object related to the pager range */ public function getPager() { @@ -102,12 +100,11 @@ public function getPager() } /** - * _setPager + * _setPager. * * Defines the Doctrine_Pager object related to the pager layout * - * @param $pager Doctrine_Pager object related to the pager range - * @return void + * @param $pager Doctrine_Pager object related to the pager range */ protected function _setPager($pager) { @@ -115,13 +112,14 @@ protected function _setPager($pager) } /** - * execute + * execute. * * Handy method to execute the query without need to retrieve the Pager instance * - * @param $params Optional parameters to Doctrine_Query::execute - * @param $hydrationMode Hydration Mode of Doctrine_Query::execute returned ResultSet. - * @return Doctrine_Collection The root collection + * @param $params Optional parameters to Doctrine_Query::execute + * @param $hydrationMode Hydration Mode of Doctrine_Query::execute returned ResultSet + * + * @return Doctrine_Collection The root collection */ public function execute($params = array(), $hydrationMode = null) { @@ -129,11 +127,11 @@ public function execute($params = array(), $hydrationMode = null) } /** - * getPagerRange + * getPagerRange. * * Returns the Doctrine_Pager_Range subclass object related to the pager layout * - * @return Doctrine_Pager_Range Doctrine_Pager_Range subclass object related to the pager range + * @return Doctrine_Pager_Range Doctrine_Pager_Range subclass object related to the pager range */ public function getPagerRange() { @@ -141,12 +139,11 @@ public function getPagerRange() } /** - * _setPagerRange + * _setPagerRange. * * Defines the Doctrine_Pager_Range subclass object related to the pager layout * - * @param $pagerRange Doctrine_Pager_Range subclass object related to the pager range - * @return void + * @param $pagerRange Doctrine_Pager_Range subclass object related to the pager range */ protected function _setPagerRange($pagerRange) { @@ -155,11 +152,11 @@ protected function _setPagerRange($pagerRange) } /** - * getUrlMask + * getUrlMask. * * Returns the URL to be assigned for each page * - * @return string URL to be assigned for each page + * @return string URL to be assigned for each page */ public function getUrlMask() { @@ -167,25 +164,23 @@ public function getUrlMask() } /** - * _setUrlMask + * _setUrlMask. * * Defines the URL to be assigned for each page * - * @param $urlMask URL to be assigned for each page - * @return void + * @param $urlMask URL to be assigned for each page */ protected function _setUrlMask($urlMask) { $this->_urlMask = $urlMask; } - - /** - * getTemplate + /** + * getTemplate. * * Returns the Template to be applied for inactive pages * - * @return string Template to be applied for inactive pages + * @return string Template to be applied for inactive pages */ public function getTemplate() { @@ -193,13 +188,12 @@ public function getTemplate() } /** - * setTemplate + * setTemplate. * - * Defines the Template to be applied for inactive pages + * Defines the Template to be applied for inactive pages * (also active page if selected template not defined) * - * @param $template Template to be applied for inactive pages - * @return void + * @param $template Template to be applied for inactive pages */ public function setTemplate($template) { @@ -207,11 +201,11 @@ public function setTemplate($template) } /** - * getSelectedTemplate + * getSelectedTemplate. * * Returns the Template to be applied for active page * - * @return string Template to be applied for active page + * @return string Template to be applied for active page */ public function getSelectedTemplate() { @@ -219,12 +213,11 @@ public function getSelectedTemplate() } /** - * setSelectedTemplate + * setSelectedTemplate. * * Defines the Template to be applied for active page * - * @param $selectedTemplate Template to be applied for active page - * @return void + * @param $selectedTemplate Template to be applied for active page */ public function setSelectedTemplate($selectedTemplate) { @@ -232,11 +225,11 @@ public function setSelectedTemplate($selectedTemplate) } /** - * getSeparatorTemplate + * getSeparatorTemplate. * * Returns the Separator template, applied between each page * - * @return string Separator template, applied between each page + * @return string Separator template, applied between each page */ public function getSeparatorTemplate() { @@ -244,49 +237,46 @@ public function getSeparatorTemplate() } /** - * setSeparatorTemplate + * setSeparatorTemplate. * * Defines the Separator template, applied between each page * - * @param $separatorTemplate Separator template, applied between each page - * @return void - */ + * @param $separatorTemplate Separator template, applied between each page + */ public function setSeparatorTemplate($separatorTemplate) { $this->_separatorTemplate = $separatorTemplate; } /** - * addMaskReplacement + * addMaskReplacement. * * Defines a mask replacement. When parsing template, it converts replacement * masks into new ones (or values), allowing to change masks behavior on the fly * - * @param $oldMask Mask to be replaced - * @param $newMask Mask or Value that will be defined after replacement - * @param $asValue Optional value (default false) that if defined as true, - * changes the bahavior of replacement mask to replacement - * value - * @return void - */ + * @param $oldMask Mask to be replaced + * @param $newMask Mask or Value that will be defined after replacement + * @param $asValue Optional value (default false) that if defined as true, + * changes the bahavior of replacement mask to replacement + * value + */ public function addMaskReplacement($oldMask, $newMask, $asValue = false) { if (($oldMask = trim($oldMask)) != 'page_number') { $this->_maskReplacements[$oldMask] = array( 'newMask' => $newMask, - 'asValue' => ($asValue === false) ? false : true + 'asValue' => (false === $asValue) ? false : true, ); } } /** - * removeMaskReplacement + * removeMaskReplacement. * * Remove a mask replacement * - * @param $oldMask Replacement Mask to be removed - * @return void - */ + * @param $oldMask Replacement Mask to be removed + */ public function removeMaskReplacement($oldMask) { if (isset($this->_maskReplacements[$oldMask])) { @@ -294,15 +284,12 @@ public function removeMaskReplacement($oldMask) unset($this->_maskReplacements[$oldMask]); } } - - + /** - * cleanMaskReplacements + * cleanMaskReplacements. * * Remove all mask replacements - * - * @return void - */ + */ public function cleanMaskReplacements() { $this->_maskReplacements = null; @@ -310,16 +297,13 @@ public function cleanMaskReplacements() } /** - * display + * display. * * Displays the pager on screen based on templates and options defined * - * @param $options Optional parameters to be applied in template and url mask - * @param $return Optional parameter if you want to capture the output of this method call - * (Default value is false), instead of printing it - * @return void If you would like to capture the output of Doctrine_Pager_Layout::display(), - * use the $return parameter. If this parameter is set to TRUE, this method - * will return its output, instead of printing it (which it does by default) + * @param $options Optional parameters to be applied in template and url mask + * @param $return Optional parameter if you want to capture the output of this method call + * (Default value is false), instead of printing it */ public function display($options = array(), $return = false) { @@ -327,7 +311,7 @@ public function display($options = array(), $return = false) $str = ''; // For each page in range - for ($i = 0, $l = count($range); $i < $l; $i++) { + for ($i = 0, $l = count($range); $i < $l; ++$i) { // Define some optional mask values $options['page_number'] = $range[$i]; @@ -348,28 +332,26 @@ public function display($options = array(), $return = false) } /** - * processPage + * processPage. * * Parses the template and returns the string of a processed page * * @param array Optional parameters to be applied in template and url mask - * @return string Processed template for the given page + * + * @return string Processed template for the given page */ public function processPage($options = array()) { // Check if at least basic options are defined - if ( !isset($options['page_number'])) { - throw new Doctrine_Pager_Exception( - 'Cannot process template of the given page. ' . - 'Missing at least one of needed parameters: \'page\' or \'page_number\'' - ); + if (!isset($options['page_number'])) { + throw new Doctrine_Pager_Exception('Cannot process template of the given page. Missing at least one of needed parameters: \'page\' or \'page_number\''); // Should never reach here return ''; } // Assign "page" options index if not defined yet - if ( !isset($this->_maskReplacements['page']) && !isset($options['page'])) { + if (!isset($this->_maskReplacements['page']) && !isset($options['page'])) { $options['page'] = $options['page_number']; } @@ -381,16 +363,17 @@ public function processPage($options = array()) */ public function __toString() { - return $this->display(array(), true); + return $this->display(array(), true); } /** - * _parseTemplate + * _parseTemplate. * * Parse the template of a given page and return the processed template * * @param array Optional parameters to be applied in template and url mask - * @return string + * + * @return string */ protected function _parseTemplate($options = array()) { @@ -401,12 +384,13 @@ protected function _parseTemplate($options = array()) } /** - * _parseUrlTemplate + * _parseUrlTemplate. * * Parse the url mask to return the correct template depending of the options sent. * Already process the mask replacements assigned. * - * @param $options Optional parameters to be applied in template and url mask + * @param $options Optional parameters to be applied in template and url mask + * * @return string */ protected function _parseUrlTemplate($options = array()) @@ -419,7 +403,7 @@ protected function _parseUrlTemplate($options = array()) } // Possible attempt where Selected == Template - if ($str == '') { + if ('' == $str) { $str = $this->_parseMaskReplacements($this->getTemplate()); } @@ -427,11 +411,12 @@ protected function _parseUrlTemplate($options = array()) } /** - * _parseUrl + * _parseUrl. * * Parse the mask replacements of a given page * - * @param $options Optional parameters to be applied in template and url mask + * @param $options Optional parameters to be applied in template and url mask + * * @return string */ protected function _parseReplacementsTemplate($options = array()) @@ -449,11 +434,12 @@ protected function _parseReplacementsTemplate($options = array()) } /** - * _parseUrl + * _parseUrl. * * Parse the url mask of a given page and return the processed url * - * @param $options Optional parameters to be applied in template and url mask + * @param $options Optional parameters to be applied in template and url mask + * * @return string */ protected function _parseUrl($options = array()) @@ -470,21 +456,22 @@ protected function _parseUrl($options = array()) } /** - * _parseMaskReplacements + * _parseMaskReplacements. * * Parse the mask replacements, changing from to-be replaced mask with new masks/values * - * @param $str String to have masks replaced - * @return string + * @param $str String to have masks replaced + * + * @return string */ protected function _parseMaskReplacements($str) { $replacements = array(); foreach ($this->_maskReplacements as $k => $v) { - $replacements['{%'.$k.'}'] = ($v['asValue'] === true) ? $v['newMask'] : '{%'.$v['newMask'].'}'; + $replacements['{%'.$k.'}'] = (true === $v['asValue']) ? $v['newMask'] : '{%'.$v['newMask'].'}'; } return strtr($str, $replacements); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Pager/Range.php b/lib/Doctrine/Pager/Range.php index b512684c4..39a4dcf15 100644 --- a/lib/Doctrine/Pager/Range.php +++ b/lib/Doctrine/Pager/Range.php @@ -20,52 +20,50 @@ */ /** - * Doctrine_Pager_Range + * Doctrine_Pager_Range. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ abstract class Doctrine_Pager_Range { /** - * @var array $_options Custom Doctrine_Pager_Range implementation options + * @var array Custom Doctrine_Pager_Range implementation options */ protected $_options; /** - * @var Doctrine_Pager $pager Doctrine_Pager object related to the pager range + * @var Doctrine_Pager Doctrine_Pager object related to the pager range */ private $pager; - /** - * __construct + * __construct. * - * @param array $options Custom subclass implementation options. - * Default is a blank array - * @param Doctrine_Pager $pager Optional Doctrine_Pager object to be associated - * @return void + * @param array $options Custom subclass implementation options. + * Default is a blank array + * @param Doctrine_Pager $pager Optional Doctrine_Pager object to be associated */ final public function __construct($options = array(), $pager = null) { $this->_setOptions($options); - if ($pager !== null) { + if (null !== $pager) { $this->setPager($pager); } } /** - * getPager + * getPager. * * Returns the Doctrine_Pager object related to the pager range * - * @return Doctrine_Pager Doctrine_Pager object related to the pager range + * @return Doctrine_Pager Doctrine_Pager object related to the pager range */ public function getPager() { @@ -73,13 +71,12 @@ public function getPager() } /** - * setPager + * setPager. * * Defines the Doctrine_Pager object related to the pager range and * automatically (re-)initialize Doctrine_Pager_Range * - * @param $pager Doctrine_Pager object related to the pager range - * @return void + * @param $pager Doctrine_Pager object related to the pager range */ public function setPager($pager) { @@ -92,11 +89,11 @@ public function setPager($pager) } /** - * getOptions + * getOptions. * * Returns the custom Doctrine_Pager_Range implementation options * - * @return array Custom Doctrine_Pager_Range implementation options + * @return array Custom Doctrine_Pager_Range implementation options */ public function getOptions() { @@ -104,11 +101,11 @@ public function getOptions() } /** - * getOption + * getOption. * * Returns the custom Doctrine_Pager_Range implementation offset option * - * @return array Custom Doctrine_Pager_Range implementation options + * @return array Custom Doctrine_Pager_Range implementation options */ public function getOption($option) { @@ -116,18 +113,15 @@ public function getOption($option) return $this->_options[$option]; } - throw new Doctrine_Pager_Exception( - 'Cannot access unexistent option \'' . $option . '\' in Doctrine_Pager_Range class' - ); + throw new Doctrine_Pager_Exception('Cannot access unexistent option \''.$option.'\' in Doctrine_Pager_Range class'); } /** - * _setOptions + * _setOptions. * * Defines the subclass implementation options * - * @param $options Custom Doctrine_Pager_Range implementation options - * @return void + * @param $options Custom Doctrine_Pager_Range implementation options */ protected function _setOptions($options) { @@ -135,36 +129,32 @@ protected function _setOptions($options) } /** - * isInRange + * isInRange. * * Check if a given page is in the range * - * @param $page Page to be checked - * @return boolean + * @param $page Page to be checked + * + * @return bool */ public function isInRange($page) { - return (array_search($page, $this->rangeAroundPage()) !== false); + return false !== array_search($page, $this->rangeAroundPage()); } - - /** - * _initialize + * _initialize. * * Initialize Doctrine_Page_Range subclass which does custom class definitions - * - * @return void */ abstract protected function _initialize(); - /** - * rangeAroundPage + * rangeAroundPage. * * Calculate and returns an array representing the range around the current page * * @return array */ abstract public function rangeAroundPage(); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Pager/Range/Jumping.php b/lib/Doctrine/Pager/Range/Jumping.php index 137a4f6db..f2ecc2aa0 100644 --- a/lib/Doctrine/Pager/Range/Jumping.php +++ b/lib/Doctrine/Pager/Range/Jumping.php @@ -20,29 +20,27 @@ */ /** - * Doctrine_Pager_Range_Jumping + * Doctrine_Pager_Range_Jumping. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager_Range_Jumping extends Doctrine_Pager_Range { /** - * @var int $_chunkLength Chunk length to be returned + * @var int Chunk length to be returned */ private $_chunkLength; /** - * _initialize + * _initialize. * * Initialize Doctrine_Pager_Range_Jumping and does custom assignments - * - * @return void */ protected function _initialize() { @@ -54,11 +52,11 @@ protected function _initialize() } /** - * getChunkLength + * getChunkLength. * * Returns the size of the chunk defined * - * @return int Chunk length + * @return int Chunk length */ public function getChunkLength() { @@ -66,12 +64,11 @@ public function getChunkLength() } /** - * _setChunkLength + * _setChunkLength. * * Defines the size of the chunk * - * @param $chunkLength Chunk length - * @return void + * @param $chunkLength Chunk length */ protected function _setChunkLength($chunkLength) { @@ -79,7 +76,7 @@ protected function _setChunkLength($chunkLength) } /** - * rangeAroundPage + * rangeAroundPage. * * Calculate and returns an array representing the range around the current page * @@ -106,8 +103,6 @@ public function rangeAroundPage() return range($startPage, $endPage); } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the range around the page of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the range around the page of a not yet executed Pager query'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Pager/Range/Sliding.php b/lib/Doctrine/Pager/Range/Sliding.php index 93117b6cd..93f911e68 100644 --- a/lib/Doctrine/Pager/Range/Sliding.php +++ b/lib/Doctrine/Pager/Range/Sliding.php @@ -20,29 +20,27 @@ */ /** - * Doctrine_Pager_Range_Sliding + * Doctrine_Pager_Range_Sliding. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager_Range_Sliding extends Doctrine_Pager_Range { /** - * @var int $_chunkLength Chunk length to be returned + * @var int Chunk length to be returned */ private $_chunkLength; /** - * _initialize + * _initialize. * * Initialize Doctrine_Pager_Range_Sliding and does custom assignments - * - * @return void */ protected function _initialize() { @@ -54,11 +52,11 @@ protected function _initialize() } /** - * getChunkLength + * getChunkLength. * * Returns the size of the chunk defined * - * @return int Chunk length + * @return int Chunk length */ public function getChunkLength() { @@ -66,17 +64,16 @@ public function getChunkLength() } /** - * _setChunkLength + * _setChunkLength. * * Defines the size of the chunk * - * @param $chunkLength Chunk length - * @return void + * @param $chunkLength Chunk length */ protected function _setChunkLength($chunkLength) { $chunkLength = (int) $chunkLength; - if ( !$chunkLength) { + if (!$chunkLength) { $chunkLength = 1; } else { $this->_chunkLength = $chunkLength; @@ -84,7 +81,7 @@ protected function _setChunkLength($chunkLength) } /** - * rangeAroundPage + * rangeAroundPage. * * Calculate and returns an array representing the range around the current page * @@ -95,7 +92,7 @@ public function rangeAroundPage() $pager = $this->getPager(); if ($pager->getExecuted()) { - $page = $pager->getPage(); + $page = $pager->getPage(); $pages = $pager->getLastPage(); $chunk = $this->getChunkLength(); @@ -104,8 +101,8 @@ public function rangeAroundPage() $chunk = $pages; } - $chunkStart = $page - (floor($chunk / 2)); - $chunkEnd = $page + (ceil($chunk / 2)-1); + $chunkStart = $page - floor($chunk / 2); + $chunkEnd = $page + (ceil($chunk / 2) - 1); if ($chunkStart < 1) { $adjust = 1 - $chunkStart; @@ -122,8 +119,6 @@ public function rangeAroundPage() return range($chunkStart, $chunkEnd); } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the range around the page of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the range around the page of a not yet executed Pager query'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Parser.php b/lib/Doctrine/Parser.php index d9c8c124d..7313e8208 100644 --- a/lib/Doctrine/Parser.php +++ b/lib/Doctrine/Parser.php @@ -20,69 +20,70 @@ */ /** - * Doctrine_Parser + * Doctrine_Parser. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ abstract class Doctrine_Parser { /** - * loadData + * loadData. * * Override in the parser driver * * @param string $array - * @return void + * * @author Jonathan H. Wage */ abstract public function loadData($array, $charset = 'UTF-8'); /** - * dumpData + * dumpData. * * Override in the parser driver * * @param string $array * @param string $path * @param string $charset The charset of the data being dumped - * @return void + * * @author Jonathan H. Wage */ abstract public function dumpData($array, $path = null, $charset = null); /** - * getParser + * getParser. * * Get instance of the specified parser * * @param string $type - * @return void + * * @author Jonathan H. Wage */ - static public function getParser($type) + public static function getParser($type) { $class = 'Doctrine_Parser_'.ucfirst($type); - return new $class; + return new $class(); } /** - * load + * load. * * Interface for loading and parsing data from a file * * @param string $path * @param string $type - * @return void + * * @author Jonathan H. Wage */ - static public function load($path, $type = 'xml', $charset = 'UTF-8') + public static function load($path, $type = 'xml', $charset = 'UTF-8') { $parser = self::getParser($type); @@ -90,7 +91,7 @@ static public function load($path, $type = 'xml', $charset = 'UTF-8') } /** - * dump + * dump. * * Interface for pulling and dumping data to a file * @@ -98,10 +99,10 @@ static public function load($path, $type = 'xml', $charset = 'UTF-8') * @param string $path * @param string $type * @param string $charset The charset of the data being dumped - * @return void + * * @author Jonathan H. Wage */ - static public function dump($array, $type = 'xml', $path = null, $charset = null) + public static function dump($array, $type = 'xml', $path = null, $charset = null) { $parser = self::getParser($type); @@ -109,45 +110,43 @@ static public function dump($array, $type = 'xml', $path = null, $charset = null } /** - * doLoad + * doLoad. * * Get contents whether it is the path to a file file or a string of txt. * Either should allow php code in it. * * @param string $path - * @return void */ public function doLoad($path) { ob_start(); - if ( ! file_exists($path)) { + if (!file_exists($path)) { $contents = $path; - $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'dparser_' . microtime(); + $path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'dparser_'.microtime(); file_put_contents($path, $contents); } - include($path); + include $path; // Fix #1569. Need to check if it's still all valid - $contents = ob_get_clean(); //iconv("UTF-8", "UTF-8", ob_get_clean()); + $contents = ob_get_clean(); // iconv("UTF-8", "UTF-8", ob_get_clean()); return $contents; } /** - * doDump + * doDump. * * @param string $data * @param string $path - * @return void */ public function doDump($data, $path = null) { - if ($path !== null) { + if (null !== $path) { return file_put_contents($path, $data); - } else { - return $data; } + + return $data; } } diff --git a/lib/Doctrine/Parser/Exception.php b/lib/Doctrine/Parser/Exception.php index 6a6463834..c4cb3bf0b 100644 --- a/lib/Doctrine/Parser/Exception.php +++ b/lib/Doctrine/Parser/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Parser_Exception + * Doctrine_Parser_Exception. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Parser_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Parser/Json.php b/lib/Doctrine/Parser/Json.php index df4655de1..17adf27c6 100644 --- a/lib/Doctrine/Parser/Json.php +++ b/lib/Doctrine/Parser/Json.php @@ -20,28 +20,29 @@ */ /** - * Doctrine_Parser_Json + * Doctrine_Parser_Json. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Parser_Json extends Doctrine_Parser { /** - * dumpData + * dumpData. * * Dump an array of data to a specified path or return * - * @param string $array Array of data to dump to json - * @param string $path Path to dump json data to + * @param string $array Array of data to dump to json + * @param string $path Path to dump json data to * @param string $charset The charset of the data being dumped + * * @return string $json - * @return void */ public function dumpData($array, $path = null, $charset = null) { @@ -51,19 +52,18 @@ public function dumpData($array, $path = null, $charset = null) } /** - * loadData + * loadData. * * Load and unserialize data from a file or from passed data * - * @param string $path Path to dump data to - * @return array $json Array of json objects + * @param string $path Path to dump data to + * + * @return array $json Array of json objects */ public function loadData($path, $charset = 'UTF-8') { $contents = $this->doLoad($path); - $json = json_decode($contents); - - return $json; + return json_decode($contents); } } diff --git a/lib/Doctrine/Parser/Serialize.php b/lib/Doctrine/Parser/Serialize.php index e2eff7565..8fa2fa2f2 100644 --- a/lib/Doctrine/Parser/Serialize.php +++ b/lib/Doctrine/Parser/Serialize.php @@ -20,27 +20,27 @@ */ /** - * Doctrine_Parser_Serialize + * Doctrine_Parser_Serialize. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Parser_Serialize extends Doctrine_Parser { /** - * dumpData + * dumpData. * * Dump an array of data to a specified path or return * * @param string $array * @param string $path * @param string $charset The charset of the data being dumped - * @return void */ public function dumpData($array, $path = null, $charset = null) { @@ -50,12 +50,11 @@ public function dumpData($array, $path = null, $charset = null) } /** - * loadData + * loadData. * * Load and unserialize data from a file or from passed data * * @param string $path - * @return void */ public function loadData($path, $charset = 'UTF-8') { diff --git a/lib/Doctrine/Parser/Xml.php b/lib/Doctrine/Parser/Xml.php index 0f99699eb..a24ca2f93 100644 --- a/lib/Doctrine/Parser/Xml.php +++ b/lib/Doctrine/Parser/Xml.php @@ -20,28 +20,29 @@ */ /** - * Doctrine_Parser_Xml + * Doctrine_Parser_Xml. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Parser_Xml extends Doctrine_Parser { /** - * dumpData + * dumpData. * * Convert array to xml and dump to specified path or return the xml * - * @param string $array Array of data to convert to xml - * @param string $path Path to write xml data to + * @param string $array Array of data to convert to xml + * @param string $path Path to write xml data to * @param string $charset The charset of the data being dumped + * * @return string $xml - * @return void */ public function dumpData($array, $path = null, $charset = null) { @@ -51,24 +52,25 @@ public function dumpData($array, $path = null, $charset = null) } /** - * arrayToXml + * arrayToXml. + * + * @param string $array Array to convert to xml + * @param string $rootNodeName Name of the root node + * @param string $xml SimpleXmlElement + * @param mixed|null $charset * - * @param string $array Array to convert to xml - * @param string $rootNodeName Name of the root node - * @param string $xml SimpleXmlElement * @return string $asXml String of xml built from array */ public static function arrayToXml($array, $rootNodeName = 'data', $xml = null, $charset = null) { - if ($xml === null) { - $xml = new SimpleXmlElement("<$rootNodeName/>"); + if (null === $xml) { + $xml = new SimpleXMLElement("<{$rootNodeName}/>"); } - foreach($array as $key => $value) - { + foreach ($array as $key => $value) { $key = preg_replace('/[^a-z]/i', '', $key); - if (is_array($value) && ! empty($value)) { + if (is_array($value) && !empty($value)) { $node = $xml->addChild($key); foreach ($value as $k => $v) { @@ -79,11 +81,11 @@ public static function arrayToXml($array, $rootNodeName = 'data', $xml = null, $ } self::arrayToXml($value, $rootNodeName, $node, $charset); - } else if (is_int($key)) { + } elseif (is_int($key)) { $xml->addChild($value, 'true'); } else { $charset = $charset ? $charset : 'utf-8'; - if (strcasecmp($charset, 'utf-8') !== 0 && strcasecmp($charset, 'utf8') !== 0) { + if (0 !== strcasecmp($charset, 'utf-8') && 0 !== strcasecmp($charset, 'utf8')) { $value = iconv($charset, 'UTF-8', $value); } $value = htmlspecialchars((string) $value, ENT_COMPAT, 'UTF-8'); @@ -95,12 +97,13 @@ public static function arrayToXml($array, $rootNodeName = 'data', $xml = null, $ } /** - * loadData + * loadData. * * Load xml file and return array of data * - * @param string $path Path to load xml data from - * @return array $array Array of data converted from xml + * @param string $path Path to load xml data from + * + * @return array $array Array of data converted from xml */ public function loadData($path, $charset = 'UTF-8') { @@ -112,12 +115,13 @@ public function loadData($path, $charset = 'UTF-8') } /** - * prepareData + * prepareData. * * Prepare simple xml to array for return * - * @param string $simpleXml - * @return array $return + * @param string $simpleXml + * + * @return array $return */ public function prepareData($simpleXml) { @@ -133,10 +137,10 @@ public function prepareData($simpleXml) if (count($values) > 0) { $return[$element] = $this->prepareData($value); } else { - if ( ! isset($return[$element])) { + if (!isset($return[$element])) { $return[$element] = (string) $value; } else { - if ( ! is_array($return[$element])) { + if (!is_array($return[$element])) { $return[$element] = array($return[$element], (string) $value); } else { $return[$element][] = (string) $value; @@ -148,8 +152,8 @@ public function prepareData($simpleXml) if (is_array($return)) { return $return; - } else { - return array(); } + + return array(); } } diff --git a/lib/Doctrine/Parser/Yml.php b/lib/Doctrine/Parser/Yml.php index 9990be1db..c92ff43b8 100644 --- a/lib/Doctrine/Parser/Yml.php +++ b/lib/Doctrine/Parser/Yml.php @@ -20,72 +20,72 @@ */ /** - * Doctrine_Parser_Yml + * Doctrine_Parser_Yml. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage , Thomas Courbon */ class Doctrine_Parser_Yml extends Doctrine_Parser { /** - * dumpData + * dumpData. * * Dump an array of data to a specified path or return * - * @throws Doctrine_Parser_Exception dumping error - * @param string $array Array of data to dump to yaml - * @param string $path Path to dump the yaml to + * @param string $array Array of data to dump to yaml + * @param string $path Path to dump the yaml to + * @param mixed|null $charset + * * @return string $yaml - * @return void + * + * @throws Doctrine_Parser_Exception dumping error */ public function dumpData($array, $path = null, $charset = null) { - try { - $data = sfYaml::dump($array, 6); - - return $this->doDump($data, $path); + $data = sfYaml::dump($array, 6); - } catch(InvalidArgumentException $e) { - // rethrow the exceptions - $rethrowed_exception = new Doctrine_Parser_Exception($e->getMessage(), $e->getCode()); + return $this->doDump($data, $path); + } catch (InvalidArgumentException $e) { + // rethrow the exceptions + $rethrowed_exception = new Doctrine_Parser_Exception($e->getMessage(), $e->getCode()); - throw $rethrowed_exception; + throw $rethrowed_exception; } } /** - * loadData + * loadData. * * Load and parse data from a yml file * + * @param string $path Path to load yaml data from + * + * @return array $array Array of parsed yaml data + * * @throws Doctrine_Parser_Exception parsing error - * @param string $path Path to load yaml data from - * @return array $array Array of parsed yaml data */ public function loadData($path, $charset = 'UTF-8') { try { - /* - * I still use the doLoad method even if sfYaml can load yml from a file - * since this way Doctrine can handle file on it own. - */ - $contents = $this->doLoad($path); - - $array = sfYaml::load($contents, $charset); - - return $array; + /* + * I still use the doLoad method even if sfYaml can load yml from a file + * since this way Doctrine can handle file on it own. + */ + $contents = $this->doLoad($path); - } catch(InvalidArgumentException $e) { - // rethrow the exceptions - $rethrowed_exception = new Doctrine_Parser_Exception($e->getMessage(), $e->getCode()); + return sfYaml::load($contents, $charset); + } catch (InvalidArgumentException $e) { + // rethrow the exceptions + $rethrowed_exception = new Doctrine_Parser_Exception($e->getMessage(), $e->getCode()); - throw $rethrowed_exception; + throw $rethrowed_exception; } } } diff --git a/lib/Doctrine/Parser/sfYaml/sfYaml.php b/lib/Doctrine/Parser/sfYaml/sfYaml.php index 1d89ccc97..3d5adfc8a 100644 --- a/lib/Doctrine/Parser/sfYaml/sfYaml.php +++ b/lib/Doctrine/Parser/sfYaml/sfYaml.php @@ -11,117 +11,109 @@ /** * sfYaml offers convenience methods to load and dump YAML. * - * @package symfony - * @subpackage yaml * @author Fabien Potencier + * * @version SVN: $Id: sfYaml.class.php 8988 2008-05-15 20:24:26Z fabien $ */ class sfYaml { - static protected - $spec = '1.2'; - - /** - * Sets the YAML specification version to use. - * - * @param string $version The YAML specification version - */ - static public function setSpecVersion($version) - { - if (!in_array($version, array('1.1', '1.2'))) + protected static $spec = '1.2'; + + /** + * Sets the YAML specification version to use. + * + * @param string $version The YAML specification version + */ + public static function setSpecVersion($version) { - throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version)); + if (!in_array($version, array('1.1', '1.2'))) { + throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version)); + } + + self::$spec = $version; } - self::$spec = $version; - } - - /** - * Gets the YAML specification version to use. - * - * @return string The YAML specification version - */ - static public function getSpecVersion() - { - return self::$spec; - } - - /** - * Loads YAML into a PHP array. - * - * The load method, when supplied with a YAML stream (string or file), - * will do its best to convert YAML in a file into a PHP array. - * - * Usage: - * - * $array = sfYaml::load('config.yml'); - * print_r($array); - * - * - * @param string $input Path of YAML file or string containing YAML - * - * @return array The YAML converted to a PHP array - * - * @throws InvalidArgumentException If the YAML is not valid - */ - public static function load($input) - { - $file = ''; - - // if input is a file, process it - if (strpos($input, "\n") === false && is_file($input)) + /** + * Gets the YAML specification version to use. + * + * @return string The YAML specification version + */ + public static function getSpecVersion() { - $file = $input; - - ob_start(); - $retval = include($input); - $content = ob_get_clean(); - - // if an array is returned by the config file assume it's in plain php form else in YAML - $input = is_array($retval) ? $retval : $content; + return self::$spec; } - // if an array is returned by the config file assume it's in plain php form else in YAML - if (is_array($input)) + /** + * Loads YAML into a PHP array. + * + * The load method, when supplied with a YAML stream (string or file), + * will do its best to convert YAML in a file into a PHP array. + * + * Usage: + * + * $array = sfYaml::load('config.yml'); + * print_r($array); + * + * + * @param string $input Path of YAML file or string containing YAML + * + * @return array The YAML converted to a PHP array + * + * @throws InvalidArgumentException If the YAML is not valid + */ + public static function load($input) { - return $input; - } + $file = ''; - require_once dirname(__FILE__).'/sfYamlParser.php'; + // if input is a file, process it + if (false === strpos($input, "\n") && is_file($input)) { + $file = $input; - $yaml = new sfYamlParser(); + ob_start(); + $retval = include $input; + $content = ob_get_clean(); - try - { - $ret = $yaml->parse($input); + // if an array is returned by the config file assume it's in plain php form else in YAML + $input = is_array($retval) ? $retval : $content; + } + + // if an array is returned by the config file assume it's in plain php form else in YAML + if (is_array($input)) { + return $input; + } + + require_once dirname(__FILE__).'/sfYamlParser.php'; + + $yaml = new sfYamlParser(); + + try { + $ret = $yaml->parse($input); + } catch (Exception $e) { + throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); + } + + return $ret; } - catch (Exception $e) + + /** + * Dumps a PHP array to a YAML string. + * + * The dump method, when supplied with an array, will do its best + * to convert the array into friendly YAML. + * + * @param array $array PHP array + * @param int $inline The level where you switch to inline YAML + * + * @return string A YAML string representing the original PHP array + */ + public static function dump($array, $inline = 2) { - throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); - } + require_once dirname(__FILE__).'/sfYamlDumper.php'; + + $yaml = new sfYamlDumper(); - return $ret; - } - - /** - * Dumps a PHP array to a YAML string. - * - * The dump method, when supplied with an array, will do its best - * to convert the array into friendly YAML. - * - * @param array $array PHP array - * @param integer $inline The level where you switch to inline YAML - * - * @return string A YAML string representing the original PHP array - */ - public static function dump($array, $inline = 2) - { - require_once dirname(__FILE__).'/sfYamlDumper.php'; - - $yaml = new sfYamlDumper(); - - return $yaml->dump($array, $inline); - } + return $yaml->dump($array, $inline); + } } /** @@ -131,5 +123,5 @@ public static function dump($array, $inline = 2) */ function echoln($string) { - echo $string."\n"; + echo $string."\n"; } diff --git a/lib/Doctrine/Parser/sfYaml/sfYamlDumper.php b/lib/Doctrine/Parser/sfYaml/sfYamlDumper.php index 0ada2b37d..2eda33904 100644 --- a/lib/Doctrine/Parser/sfYaml/sfYamlDumper.php +++ b/lib/Doctrine/Parser/sfYaml/sfYamlDumper.php @@ -8,53 +8,48 @@ * file that was distributed with this source code. */ -require_once(dirname(__FILE__).'/sfYamlInline.php'); +require_once dirname(__FILE__).'/sfYamlInline.php'; /** * sfYamlDumper dumps PHP variables to YAML strings. * - * @package symfony - * @subpackage yaml * @author Fabien Potencier + * * @version SVN: $Id: sfYamlDumper.class.php 10575 2008-08-01 13:08:42Z nicolas $ */ class sfYamlDumper { - /** - * Dumps a PHP value to YAML. - * - * @param mixed $input The PHP value - * @param integer $inline The level where you switch to inline YAML - * @param integer $indent The level o indentation indentation (used internally) - * - * @return string The YAML representation of the PHP value - */ - public function dump($input, $inline = 0, $indent = 0) - { - $output = ''; - $prefix = $indent ? str_repeat(' ', $indent) : ''; - - if ($inline <= 0 || !is_array($input) || empty($input)) - { - $output .= $prefix.sfYamlInline::dump($input); - } - else + /** + * Dumps a PHP value to YAML. + * + * @param mixed $input The PHP value + * @param int $inline The level where you switch to inline YAML + * @param int $indent The level o indentation indentation (used internally) + * + * @return string The YAML representation of the PHP value + */ + public function dump($input, $inline = 0, $indent = 0) { - $isAHash = array_keys($input) !== range(0, count($input) - 1); + $output = ''; + $prefix = $indent ? str_repeat(' ', $indent) : ''; - foreach ($input as $key => $value) - { - $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); + if ($inline <= 0 || !is_array($input) || empty($input)) { + $output .= $prefix.sfYamlInline::dump($input); + } else { + $isAHash = array_keys($input) !== range(0, count($input) - 1); - $output .= sprintf('%s%s%s%s', - $prefix, - $isAHash ? sfYamlInline::dump($key).':' : '-', - $willBeInlined ? ' ' : "\n", - $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 2) - ).($willBeInlined ? "\n" : ''); - } - } + foreach ($input as $key => $value) { + $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); + + $output .= sprintf('%s%s%s%s', + $prefix, + $isAHash ? sfYamlInline::dump($key).':' : '-', + $willBeInlined ? ' ' : "\n", + $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 2) + ).($willBeInlined ? "\n" : ''); + } + } - return $output; - } + return $output; + } } diff --git a/lib/Doctrine/Parser/sfYaml/sfYamlInline.php b/lib/Doctrine/Parser/sfYaml/sfYamlInline.php index 77096e43f..8919f6d62 100644 --- a/lib/Doctrine/Parser/sfYaml/sfYamlInline.php +++ b/lib/Doctrine/Parser/sfYaml/sfYamlInline.php @@ -13,418 +13,377 @@ /** * sfYamlInline implements a YAML parser/dumper for the YAML inline syntax. * - * @package symfony - * @subpackage yaml * @author Fabien Potencier + * * @version SVN: $Id: sfYamlInline.class.php 16177 2009-03-11 08:32:48Z fabien $ */ class sfYamlInline { - const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')'; - - /** - * Convert a YAML string to a PHP array. - * - * @param string $value A YAML string - * - * @return array A PHP array representing the YAML string - */ - static public function load($value) - { - $value = trim($value); - - if (0 == strlen($value)) - { - return ''; - } - - if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) + public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')'; + + /** + * Convert a YAML string to a PHP array. + * + * @param string $value A YAML string + * + * @return array A PHP array representing the YAML string + */ + public static function load($value) { - $mbEncoding = mb_internal_encoding(); - mb_internal_encoding('ASCII'); - } + $value = trim($value); - switch ($value[0]) - { - case '[': - $result = self::parseSequence($value); - break; - case '{': - $result = self::parseMapping($value); - break; - default: - $result = self::parseScalar($value); - } + if (0 == strlen($value)) { + return ''; + } - if (isset($mbEncoding)) - { - mb_internal_encoding($mbEncoding); - } + if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { + $mbEncoding = mb_internal_encoding(); + mb_internal_encoding('ASCII'); + } - return $result; - } - - /** - * Dumps a given PHP variable to a YAML string. - * - * @param mixed $value The PHP variable to convert - * - * @return string The YAML string representing the PHP array - */ - static public function dump($value) - { - if ('1.1' === sfYaml::getSpecVersion()) - { - $trueValues = array('true', 'on', '+', 'yes', 'y'); - $falseValues = array('false', 'off', '-', 'no', 'n'); - } - else - { - $trueValues = array('true'); - $falseValues = array('false'); - } + switch ($value[0]) { + case '[': + $result = self::parseSequence($value); + break; + case '{': + $result = self::parseMapping($value); + break; + default: + $result = self::parseScalar($value); + } - switch (true) - { - case is_resource($value): - throw new InvalidArgumentException('Unable to dump PHP resources in a YAML file.'); - case is_object($value): - return '!!php/object:'.serialize($value); - case is_array($value): - return self::dumpArray($value); - case null === $value: - return 'null'; - case true === $value: - return 'true'; - case false === $value: - return 'false'; - case (is_string($value) && ctype_digit($value)): - return "'$value'"; - case is_numeric($value) && false === strpbrk($value, "\f\n\r\t\v"): - return is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'$value'" : $value); - case false !== strpos($value, "\n") || false !== strpos($value, "\r"): - return sprintf('"%s"', str_replace(array('"', "\n", "\r"), array('\\"', '\n', '\r'), $value)); - case preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ - ? | < > = ! % @ ` ]/x', $value): - return sprintf("'%s'", str_replace('\'', '\'\'', $value)); - case '' == $value: - return "''"; - case preg_match(self::getTimestampRegex(), $value): - return "'$value'"; - case in_array(strtolower($value), $trueValues): - return "'$value'"; - case in_array(strtolower($value), $falseValues): - return "'$value'"; - case in_array(strtolower($value), array('null', '~')): - return "'$value'"; - default: - return $value; - } - } - - /** - * Dumps a PHP array to a YAML string. - * - * @param array $value The PHP array to dump - * - * @return string The YAML string representing the PHP array - */ - static protected function dumpArray($value) - { - // array - $keys = array_keys($value); - if ( - (1 == count($keys) && '0' == $keys[0]) - || - (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int)($v + $w);}, 0) == count($keys) * (count($keys) - 1) / 2)) - { - $output = array(); - foreach ($value as $val) - { - $output[] = self::dump($val); - } + if (isset($mbEncoding)) { + mb_internal_encoding($mbEncoding); + } - return sprintf('[%s]', implode(', ', $output)); + return $result; } - // mapping - $output = array(); - foreach ($value as $key => $val) + /** + * Dumps a given PHP variable to a YAML string. + * + * @param mixed $value The PHP variable to convert + * + * @return string The YAML string representing the PHP array + */ + public static function dump($value) { - $output[] = sprintf('%s: %s', self::dump($key), self::dump($val)); - } + if ('1.1' === sfYaml::getSpecVersion()) { + $trueValues = array('true', 'on', '+', 'yes', 'y'); + $falseValues = array('false', 'off', '-', 'no', 'n'); + } else { + $trueValues = array('true'); + $falseValues = array('false'); + } - return sprintf('{ %s }', implode(', ', $output)); - } - - /** - * Parses a scalar to a YAML string. - * - * @param scalar $scalar - * @param string $delimiters - * @param array $stringDelimiter - * @param integer $i - * @param boolean $evaluate - * - * @return string A YAML string - */ - static public function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true) - { - if (in_array($scalar[$i], $stringDelimiters)) - { - // quoted scalar - $output = self::parseQuotedScalar($scalar, $i); - } - else - { - // "normal" string - if (!$delimiters) - { - $output = substr($scalar, $i); - $i += strlen($output); - - // remove comments - if (false !== $strpos = strpos($output, ' #')) - { - $output = rtrim(substr($output, 0, $strpos)); + switch (true) { + case is_resource($value): + throw new InvalidArgumentException('Unable to dump PHP resources in a YAML file.'); + case is_object($value): + return '!!php/object:'.serialize($value); + case is_array($value): + return self::dumpArray($value); + case null === $value: + return 'null'; + case true === $value: + return 'true'; + case false === $value: + return 'false'; + case is_string($value) && ctype_digit($value): + return "'{$value}'"; + case is_numeric($value) && false === strpbrk($value, "\f\n\r\t\v"): + return is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'{$value}'" : $value); + case false !== strpos($value, "\n") || false !== strpos($value, "\r"): + return sprintf('"%s"', str_replace(array('"', "\n", "\r"), array('\\"', '\n', '\r'), $value)); + case preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ - ? | < > = ! % @ ` ]/x', $value): + return sprintf("'%s'", str_replace('\'', '\'\'', $value)); + case '' == $value: + return "''"; + case preg_match(self::getTimestampRegex(), $value): + return "'{$value}'"; + case in_array(strtolower($value), $trueValues): + return "'{$value}'"; + case in_array(strtolower($value), $falseValues): + return "'{$value}'"; + case in_array(strtolower($value), array('null', '~')): + return "'{$value}'"; + default: + return $value; } - } - else if (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) - { - $output = $match[1]; - $i += strlen($output); - } - else - { - throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', $scalar)); - } - - $output = $evaluate ? self::evaluateScalar($output) : $output; } - return $output; - } - - /** - * Parses a quoted scalar to YAML. - * - * @param string $scalar - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseQuotedScalar($scalar, &$i) - { - if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) + /** + * Dumps a PHP array to a YAML string. + * + * @param array $value The PHP array to dump + * + * @return string The YAML string representing the PHP array + */ + protected static function dumpArray($value) { - throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i))); - } + // array + $keys = array_keys($value); + if ( + (1 == count($keys) && '0' == $keys[0]) + || (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int) ($v + $w); }, 0) == count($keys) * (count($keys) - 1) / 2)) { + $output = array(); + foreach ($value as $val) { + $output[] = self::dump($val); + } - $output = substr($match[0], 1, strlen($match[0]) - 2); + return sprintf('[%s]', implode(', ', $output)); + } - if ('"' == $scalar[$i]) - { - // evaluate the string - $output = str_replace(array('\\"', '\\n', '\\r'), array('"', "\n", "\r"), $output); - } - else - { - // unescape ' - $output = str_replace('\'\'', '\'', $output); + // mapping + $output = array(); + foreach ($value as $key => $val) { + $output[] = sprintf('%s: %s', self::dump($key), self::dump($val)); + } + + return sprintf('{ %s }', implode(', ', $output)); } - $i += strlen($match[0]); - - return $output; - } - - /** - * Parses a sequence to a YAML string. - * - * @param string $sequence - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseSequence($sequence, &$i = 0) - { - $output = array(); - $len = strlen($sequence); - $i += 1; - - // [foo, bar, ...] - while ($i < $len) + /** + * Parses a scalar to a YAML string. + * + * @param scalar $scalar + * @param string $delimiters + * @param int $i + * @param bool $evaluate + * + * @return string A YAML string + */ + public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true) { - switch ($sequence[$i]) - { - case '[': - // nested sequence - $output[] = self::parseSequence($sequence, $i); - break; - case '{': - // nested mapping - $output[] = self::parseMapping($sequence, $i); - break; - case ']': - return $output; - case ',': - case ' ': - break; - default: - $isQuoted = in_array($sequence[$i], array('"', "'")); - $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i); - - if (!$isQuoted && false !== strpos($value, ': ')) - { - // embedded mapping? - try - { - $value = self::parseMapping('{'.$value.'}'); + if (in_array($scalar[$i], $stringDelimiters)) { + // quoted scalar + $output = self::parseQuotedScalar($scalar, $i); + } else { + // "normal" string + if (!$delimiters) { + $output = substr($scalar, $i); + $i += strlen($output); + + // remove comments + if (false !== $strpos = strpos($output, ' #')) { + $output = rtrim(substr($output, 0, $strpos)); + } + } elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) { + $output = $match[1]; + $i += strlen($output); + } else { + throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', $scalar)); } - catch (InvalidArgumentException $e) - { - // no, it's not - } - } - - $output[] = $value; - --$i; - } + $output = $evaluate ? self::evaluateScalar($output) : $output; + } - ++$i; + return $output; } - throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $sequence)); - } - - /** - * Parses a mapping to a YAML string. - * - * @param string $mapping - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseMapping($mapping, &$i = 0) - { - $output = array(); - $len = strlen($mapping); - $i += 1; - - // {foo: bar, bar:foo, ...} - while ($i < $len) + /** + * Parses a quoted scalar to YAML. + * + * @param string $scalar + * @param int $i + * + * @return string A YAML string + */ + protected static function parseQuotedScalar($scalar, &$i) { - switch ($mapping[$i]) - { - case ' ': - case ',': - ++$i; - continue 2; - case '}': - return $output; - } - - // key - $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); - - // value - $done = false; - while ($i < $len) - { - switch ($mapping[$i]) - { - case '[': - // nested sequence - $output[$key] = self::parseSequence($mapping, $i); - $done = true; - break; - case '{': - // nested mapping - $output[$key] = self::parseMapping($mapping, $i); - $done = true; - break; - case ':': - case ' ': - break; - default: - $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i); - $done = true; - --$i; + if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { + throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i))); } - ++$i; + $output = substr($match[0], 1, strlen($match[0]) - 2); - if ($done) - { - continue 2; + if ('"' == $scalar[$i]) { + // evaluate the string + $output = str_replace(array('\\"', '\\n', '\\r'), array('"', "\n", "\r"), $output); + } else { + // unescape ' + $output = str_replace('\'\'', '\'', $output); } - } + + $i += strlen($match[0]); + + return $output; } - throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $mapping)); - } - - /** - * Evaluates scalars and replaces magic values. - * - * @param string $scalar - * - * @return string A YAML string - */ - static protected function evaluateScalar($scalar) - { - $scalar = trim($scalar); - - if ('1.1' === sfYaml::getSpecVersion()) + /** + * Parses a sequence to a YAML string. + * + * @param string $sequence + * @param int $i + * + * @return string A YAML string + */ + protected static function parseSequence($sequence, &$i = 0) { - $trueValues = array('true', 'on', '+', 'yes', 'y'); - $falseValues = array('false', 'off', '-', 'no', 'n'); + $output = array(); + $len = strlen($sequence); + ++$i; + + // [foo, bar, ...] + while ($i < $len) { + switch ($sequence[$i]) { + case '[': + // nested sequence + $output[] = self::parseSequence($sequence, $i); + break; + case '{': + // nested mapping + $output[] = self::parseMapping($sequence, $i); + break; + case ']': + return $output; + case ',': + case ' ': + break; + default: + $isQuoted = in_array($sequence[$i], array('"', "'")); + $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i); + + if (!$isQuoted && false !== strpos($value, ': ')) { + // embedded mapping? + try { + $value = self::parseMapping('{'.$value.'}'); + } catch (InvalidArgumentException $e) { + // no, it's not + } + } + + $output[] = $value; + + --$i; + } + + ++$i; + } + + throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $sequence)); } - else + + /** + * Parses a mapping to a YAML string. + * + * @param string $mapping + * @param int $i + * + * @return string A YAML string + */ + protected static function parseMapping($mapping, &$i = 0) { - $trueValues = array('true'); - $falseValues = array('false'); + $output = array(); + $len = strlen($mapping); + ++$i; + + // {foo: bar, bar:foo, ...} + while ($i < $len) { + switch ($mapping[$i]) { + case ' ': + case ',': + ++$i; + continue 2; + case '}': + return $output; + } + + // key + $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); + + // value + $done = false; + while ($i < $len) { + switch ($mapping[$i]) { + case '[': + // nested sequence + $output[$key] = self::parseSequence($mapping, $i); + $done = true; + break; + case '{': + // nested mapping + $output[$key] = self::parseMapping($mapping, $i); + $done = true; + break; + case ':': + case ' ': + break; + default: + $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i); + $done = true; + --$i; + } + + ++$i; + + if ($done) { + continue 2; + } + } + } + + throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $mapping)); } - switch (true) + /** + * Evaluates scalars and replaces magic values. + * + * @param string $scalar + * + * @return string A YAML string + */ + protected static function evaluateScalar($scalar) { - case 'null' == strtolower($scalar): - case '' == $scalar: - case '~' == $scalar: - return null; - case 0 === strpos($scalar, '!str'): - return (string) substr($scalar, 5); - case 0 === strpos($scalar, '! '): - return intval(self::parseScalar(substr($scalar, 2))); - case 0 === strpos($scalar, '!!php/object:'): - return unserialize(substr($scalar, 13)); - case ctype_digit($scalar): - $raw = $scalar; - $cast = intval($scalar); - return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); - case in_array(strtolower($scalar), $trueValues): - return true; - case in_array(strtolower($scalar), $falseValues): - return false; - case is_numeric($scalar): - return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar); - case 0 == strcasecmp($scalar, '.inf'): - case 0 == strcasecmp($scalar, '.NaN'): - return -log(0); - case 0 == strcasecmp($scalar, '-.inf'): - return log(0); - case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): - return floatval(str_replace(',', '', $scalar)); - case preg_match(self::getTimestampRegex(), $scalar): - return strtotime($scalar); - default: - return (string) $scalar; + $scalar = trim($scalar); + + if ('1.1' === sfYaml::getSpecVersion()) { + $trueValues = array('true', 'on', '+', 'yes', 'y'); + $falseValues = array('false', 'off', '-', 'no', 'n'); + } else { + $trueValues = array('true'); + $falseValues = array('false'); + } + + switch (true) { + case 'null' == strtolower($scalar): + case '' == $scalar: + case '~' == $scalar: + return null; + case 0 === strpos($scalar, '!str'): + return (string) substr($scalar, 5); + case 0 === strpos($scalar, '! '): + return intval(self::parseScalar(substr($scalar, 2))); + case 0 === strpos($scalar, '!!php/object:'): + return unserialize(substr($scalar, 13)); + case ctype_digit($scalar): + $raw = $scalar; + $cast = intval($scalar); + + return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); + case in_array(strtolower($scalar), $trueValues): + return true; + case in_array(strtolower($scalar), $falseValues): + return false; + case is_numeric($scalar): + return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar); + case 0 == strcasecmp($scalar, '.inf'): + case 0 == strcasecmp($scalar, '.NaN'): + return -log(0); + case 0 == strcasecmp($scalar, '-.inf'): + return log(0); + case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): + return floatval(str_replace(',', '', $scalar)); + case preg_match(self::getTimestampRegex(), $scalar): + return strtotime($scalar); + default: + return (string) $scalar; + } } - } - static protected function getTimestampRegex() - { - return <<[0-9][0-9][0-9][0-9]) -(?P[0-9][0-9]?) @@ -433,10 +392,10 @@ static protected function getTimestampRegex() (?P[0-9][0-9]?) :(?P[0-9][0-9]) :(?P[0-9][0-9]) - (?:\.(?P[0-9]*))? + (?:\\.(?P[0-9]*))? (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) (?::(?P[0-9][0-9]))?))?)? $~x EOF; - } + } } diff --git a/lib/Doctrine/Parser/sfYaml/sfYamlParser.php b/lib/Doctrine/Parser/sfYaml/sfYamlParser.php index 91da2dcb1..a05354fba 100644 --- a/lib/Doctrine/Parser/sfYaml/sfYamlParser.php +++ b/lib/Doctrine/Parser/sfYaml/sfYamlParser.php @@ -8,615 +8,522 @@ * file that was distributed with this source code. */ -require_once(dirname(__FILE__).'/sfYamlInline.php'); +require_once dirname(__FILE__).'/sfYamlInline.php'; -if (!defined('PREG_BAD_UTF8_OFFSET_ERROR')) -{ - define('PREG_BAD_UTF8_OFFSET_ERROR', 5); +if (!defined('PREG_BAD_UTF8_OFFSET_ERROR')) { + define('PREG_BAD_UTF8_OFFSET_ERROR', 5); } /** * sfYamlParser parses YAML strings to convert them to PHP arrays. * - * @package symfony - * @subpackage yaml * @author Fabien Potencier + * * @version SVN: $Id: sfYamlParser.class.php 10832 2008-08-13 07:46:08Z fabien $ */ class sfYamlParser { - protected - $offset = 0, - $lines = array(), - $currentLineNb = -1, - $currentLine = '', - $refs = array(); - - /** - * Constructor - * - * @param integer $offset The offset of YAML document (used for line numbers in error messages) - */ - public function __construct($offset = 0) - { - $this->offset = $offset; - } - - /** - * Parses a YAML string to a PHP value. - * - * @param string $value A YAML string - * - * @return mixed A PHP value - * - * @throws InvalidArgumentException If the YAML is not valid - */ - public function parse($value) - { - $this->currentLineNb = -1; - $this->currentLine = ''; - $this->lines = explode("\n", $this->cleanup($value)); - - if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) + protected $offset = 0; + protected $lines = array(); + protected $currentLineNb = -1; + protected $currentLine = ''; + protected $refs = array(); + + /** + * Constructor. + * + * @param int $offset The offset of YAML document (used for line numbers in error messages) + */ + public function __construct($offset = 0) { - $mbEncoding = mb_internal_encoding(); - mb_internal_encoding('UTF-8'); + $this->offset = $offset; } - $data = array(); - while ($this->moveToNextLine()) + /** + * Parses a YAML string to a PHP value. + * + * @param string $value A YAML string + * + * @return mixed A PHP value + * + * @throws InvalidArgumentException If the YAML is not valid + */ + public function parse($value) { - if ($this->isCurrentLineEmpty()) - { - continue; - } - - // tab? - if (preg_match('#^\t+#', $this->currentLine)) - { - throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - - $isRef = $isInPlace = $isProcessed = false; - if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#u', $this->currentLine, $values)) - { - if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) - { - $isRef = $matches['ref']; - $values['value'] = $matches['value']; - } + $this->currentLineNb = -1; + $this->currentLine = ''; + $this->lines = explode("\n", $this->cleanup($value)); - // array - if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) - { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $data[] = $parser->parse($this->getNextEmbedBlock()); + if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { + $mbEncoding = mb_internal_encoding(); + mb_internal_encoding('UTF-8'); } - else - { - if (isset($values['leadspaces']) - && ' ' == $values['leadspaces'] - && preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"\{].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches)) - { - // this is a compact notation element, add to next block and parse - $c = $this->getRealCurrentLineNb(); - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - - $block = $values['value']; - if (!$this->isNextLineIndented()) - { - $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); - } - $data[] = $parser->parse($block); - } - else - { - $data[] = $this->parseValue($values['value']); - } - } - } - else if (preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values)) - { - $key = sfYamlInline::parseScalar($values['key']); - - if ('<<' === $key) - { - if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) - { - $isInPlace = substr($values['value'], 1); - if (!array_key_exists($isInPlace, $this->refs)) - { - throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - } - else - { - if (isset($values['value']) && $values['value'] !== '') - { - $value = $values['value']; - } - else - { - $value = $this->getNextEmbedBlock(); + $data = array(); + while ($this->moveToNextLine()) { + if ($this->isCurrentLineEmpty()) { + continue; } - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $parsed = $parser->parse($value); - - $merged = array(); - if (!is_array($parsed)) - { - throw new InvalidArgumentException(sprintf("YAML merge keys used with a scalar value instead of an array at line %s (%s)", $this->getRealCurrentLineNb() + 1, $this->currentLine)); + + // tab? + if (preg_match('#^\t+#', $this->currentLine)) { + throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); } - else if (isset($parsed[0])) - { - // Numeric array, merge individual elements - foreach (array_reverse($parsed) as $parsedItem) - { - if (!is_array($parsedItem)) - { - throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem)); + + $isRef = $isInPlace = $isProcessed = false; + if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#u', $this->currentLine, $values)) { + if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { + $isRef = $matches['ref']; + $values['value'] = $matches['value']; } - $merged = array_merge($parsedItem, $merged); - } - } - else - { - // Associative array, merge - $merged = array_merge($merge, $parsed); - } - $isProcessed = $merged; - } - } - else if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) - { - $isRef = $matches['ref']; - $values['value'] = $matches['value']; - } + // array + if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { + $c = $this->getRealCurrentLineNb() + 1; + $parser = new sfYamlParser($c); + $parser->refs = &$this->refs; + $data[] = $parser->parse($this->getNextEmbedBlock()); + } else { + if (isset($values['leadspaces']) + && ' ' == $values['leadspaces'] + && preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"\{].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches)) { + // this is a compact notation element, add to next block and parse + $c = $this->getRealCurrentLineNb(); + $parser = new sfYamlParser($c); + $parser->refs = &$this->refs; + + $block = $values['value']; + if (!$this->isNextLineIndented()) { + $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); + } + + $data[] = $parser->parse($block); + } else { + $data[] = $this->parseValue($values['value']); + } + } + } elseif (preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values)) { + $key = sfYamlInline::parseScalar($values['key']); + + if ('<<' === $key) { + if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) { + $isInPlace = substr($values['value'], 1); + if (!array_key_exists($isInPlace, $this->refs)) { + throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } + } else { + if (isset($values['value']) && '' !== $values['value']) { + $value = $values['value']; + } else { + $value = $this->getNextEmbedBlock(); + } + $c = $this->getRealCurrentLineNb() + 1; + $parser = new sfYamlParser($c); + $parser->refs = &$this->refs; + $parsed = $parser->parse($value); + + $merged = array(); + if (!is_array($parsed)) { + throw new InvalidArgumentException(sprintf('YAML merge keys used with a scalar value instead of an array at line %s (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } + if (isset($parsed[0])) { + // Numeric array, merge individual elements + foreach (array_reverse($parsed) as $parsedItem) { + if (!is_array($parsedItem)) { + throw new InvalidArgumentException(sprintf('Merge items must be arrays at line %s (%s).', $this->getRealCurrentLineNb() + 1, $parsedItem)); + } + $merged = array_merge($parsedItem, $merged); + } + } else { + // Associative array, merge + $merged = array_merge($merge, $parsed); + } + + $isProcessed = $merged; + } + } elseif (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { + $isRef = $matches['ref']; + $values['value'] = $matches['value']; + } - if ($isProcessed) - { - // Merge keys - $data = $isProcessed; - } - // hash - else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) - { - // if next line is less indented or equal, then it means that the current value is null - if ($this->isNextLineIndented()) - { - $data[$key] = null; - } - else - { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $data[$key] = $parser->parse($this->getNextEmbedBlock()); - } - } - else - { - if ($isInPlace) - { - $data = $this->refs[$isInPlace]; - } - else - { - $data[$key] = $this->parseValue($values['value']); - } - } - } - else - { - // 1-liner followed by newline - if (2 == count($this->lines) && empty($this->lines[1])) - { - $value = sfYamlInline::load($this->lines[0]); - if (is_array($value)) - { - $first = reset($value); - if ('*' === substr($first, 0, 1)) - { - $data = array(); - foreach ($value as $alias) - { - $data[] = $this->refs[substr($alias, 1)]; - } - $value = $data; - } - } + if ($isProcessed) { + // Merge keys + $data = $isProcessed; + } + // hash + elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { + // if next line is less indented or equal, then it means that the current value is null + if ($this->isNextLineIndented()) { + $data[$key] = null; + } else { + $c = $this->getRealCurrentLineNb() + 1; + $parser = new sfYamlParser($c); + $parser->refs = &$this->refs; + $data[$key] = $parser->parse($this->getNextEmbedBlock()); + } + } else { + if ($isInPlace) { + $data = $this->refs[$isInPlace]; + } else { + $data[$key] = $this->parseValue($values['value']); + } + } + } else { + // 1-liner followed by newline + if (2 == count($this->lines) && empty($this->lines[1])) { + $value = sfYamlInline::load($this->lines[0]); + if (is_array($value)) { + $first = reset($value); + if ('*' === substr($first, 0, 1)) { + $data = array(); + foreach ($value as $alias) { + $data[] = $this->refs[substr($alias, 1)]; + } + $value = $data; + } + } + + if (isset($mbEncoding)) { + mb_internal_encoding($mbEncoding); + } + + return $value; + } - if (isset($mbEncoding)) - { - mb_internal_encoding($mbEncoding); - } + switch (preg_last_error()) { + case PREG_INTERNAL_ERROR: + $error = 'Internal PCRE error on line'; + break; + case PREG_BACKTRACK_LIMIT_ERROR: + $error = 'pcre.backtrack_limit reached on line'; + break; + case PREG_RECURSION_LIMIT_ERROR: + $error = 'pcre.recursion_limit reached on line'; + break; + case PREG_BAD_UTF8_ERROR: + $error = 'Malformed UTF-8 data on line'; + break; + case PREG_BAD_UTF8_OFFSET_ERROR: + $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line'; + break; + default: + $error = 'Unable to parse line'; + } - return $value; - } + throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } - switch (preg_last_error()) - { - case PREG_INTERNAL_ERROR: - $error = 'Internal PCRE error on line'; - break; - case PREG_BACKTRACK_LIMIT_ERROR: - $error = 'pcre.backtrack_limit reached on line'; - break; - case PREG_RECURSION_LIMIT_ERROR: - $error = 'pcre.recursion_limit reached on line'; - break; - case PREG_BAD_UTF8_ERROR: - $error = 'Malformed UTF-8 data on line'; - break; - case PREG_BAD_UTF8_OFFSET_ERROR: - $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line'; - break; - default: - $error = 'Unable to parse line'; + if ($isRef) { + $this->refs[$isRef] = end($data); + } } - throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } + if (isset($mbEncoding)) { + mb_internal_encoding($mbEncoding); + } - if ($isRef) - { - $this->refs[$isRef] = end($data); - } + return empty($data) ? null : $data; } - if (isset($mbEncoding)) + /** + * Returns the current line number (takes the offset into account). + * + * @return int The current line number + */ + protected function getRealCurrentLineNb() { - mb_internal_encoding($mbEncoding); + return $this->currentLineNb + $this->offset; } - return empty($data) ? null : $data; - } - - /** - * Returns the current line number (takes the offset into account). - * - * @return integer The current line number - */ - protected function getRealCurrentLineNb() - { - return $this->currentLineNb + $this->offset; - } - - /** - * Returns the current line indentation. - * - * @return integer The current line indentation - */ - protected function getCurrentLineIndentation() - { - return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); - } - - /** - * Returns the next embed block of YAML. - * - * @param integer $indentation The indent level at which the block is to be read, or null for default - * - * @return string A YAML string - */ - protected function getNextEmbedBlock($indentation = null) - { - $this->moveToNextLine(); - - if (null === $indentation) + /** + * Returns the current line indentation. + * + * @return int The current line indentation + */ + protected function getCurrentLineIndentation() { - $newIndent = $this->getCurrentLineIndentation(); - - if (!$this->isCurrentLineEmpty() && 0 == $newIndent) - { - throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } + return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); } - else + + /** + * Returns the next embed block of YAML. + * + * @param int $indentation The indent level at which the block is to be read, or null for default + * + * @return string A YAML string + */ + protected function getNextEmbedBlock($indentation = null) { - $newIndent = $indentation; - } + $this->moveToNextLine(); - $data = array(substr($this->currentLine, $newIndent)); + if (null === $indentation) { + $newIndent = $this->getCurrentLineIndentation(); - while ($this->moveToNextLine()) - { - if ($this->isCurrentLineEmpty()) - { - if ($this->isCurrentLineBlank()) - { - $data[] = substr($this->currentLine, $newIndent); + if (!$this->isCurrentLineEmpty() && 0 == $newIndent) { + throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } + } else { + $newIndent = $indentation; } - continue; - } - - $indent = $this->getCurrentLineIndentation(); - - if (preg_match('#^(?P *)$#', $this->currentLine, $match)) - { - // empty line - $data[] = $match['text']; - } - else if ($indent >= $newIndent) - { - $data[] = substr($this->currentLine, $newIndent); - } - else if (0 == $indent) - { - $this->moveToPreviousLine(); + $data = array(substr($this->currentLine, $newIndent)); - break; - } - else - { - throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - } + while ($this->moveToNextLine()) { + if ($this->isCurrentLineEmpty()) { + if ($this->isCurrentLineBlank()) { + $data[] = substr($this->currentLine, $newIndent); + } - return implode("\n", $data); - } + continue; + } - /** - * Moves the parser to the next line. - */ - protected function moveToNextLine() - { - if ($this->currentLineNb >= count($this->lines) - 1) - { - return false; - } + $indent = $this->getCurrentLineIndentation(); - $this->currentLine = $this->lines[++$this->currentLineNb]; - - return true; - } - - /** - * Moves the parser to the previous line. - */ - protected function moveToPreviousLine() - { - $this->currentLine = $this->lines[--$this->currentLineNb]; - } - - /** - * Parses a YAML value. - * - * @param string $value A YAML value - * - * @return mixed A PHP value - */ - protected function parseValue($value) - { - if ('*' === substr($value, 0, 1)) - { - if (false !== $pos = strpos($value, '#')) - { - $value = substr($value, 1, $pos - 2); - } - else - { - $value = substr($value, 1); - } - - if (!array_key_exists($value, $this->refs)) - { - throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine)); - } - return $this->refs[$value]; - } + if (preg_match('#^(?P *)$#', $this->currentLine, $match)) { + // empty line + $data[] = $match['text']; + } elseif ($indent >= $newIndent) { + $data[] = substr($this->currentLine, $newIndent); + } elseif (0 == $indent) { + $this->moveToPreviousLine(); - if (preg_match('/^(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?$/', $value, $matches)) - { - $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; + break; + } else { + throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } + } - return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); - } - else - { - return sfYamlInline::load($value); + return implode("\n", $data); } - } - - /** - * Parses a folded scalar. - * - * @param string $separator The separator that was used to begin this folded scalar (| or >) - * @param string $indicator The indicator that was used to begin this folded scalar (+ or -) - * @param integer $indentation The indentation that was used to begin this folded scalar - * - * @return string The text value - */ - protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0) - { - $separator = '|' == $separator ? "\n" : ' '; - $text = ''; - - $notEOF = $this->moveToNextLine(); - - while ($notEOF && $this->isCurrentLineBlank()) + + /** + * Moves the parser to the next line. + */ + protected function moveToNextLine() { - $text .= "\n"; + if ($this->currentLineNb >= count($this->lines) - 1) { + return false; + } - $notEOF = $this->moveToNextLine(); + $this->currentLine = $this->lines[++$this->currentLineNb]; + + return true; } - if (!$notEOF) + /** + * Moves the parser to the previous line. + */ + protected function moveToPreviousLine() { - return ''; + $this->currentLine = $this->lines[--$this->currentLineNb]; } - if (!preg_match('#^(?P'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P.*)$#u', $this->currentLine, $matches)) + /** + * Parses a YAML value. + * + * @param string $value A YAML value + * + * @return mixed A PHP value + */ + protected function parseValue($value) { - $this->moveToPreviousLine(); + if ('*' === substr($value, 0, 1)) { + if (false !== $pos = strpos($value, '#')) { + $value = substr($value, 1, $pos - 2); + } else { + $value = substr($value, 1); + } - return ''; - } + if (!array_key_exists($value, $this->refs)) { + throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine)); + } - $textIndent = $matches['indent']; - $previousIndent = 0; + return $this->refs[$value]; + } - $text .= $matches['text'].$separator; - while ($this->currentLineNb + 1 < count($this->lines)) - { - $this->moveToNextLine(); + if (preg_match('/^(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?$/', $value, $matches)) { + $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; - if (preg_match('#^(?P {'.strlen($textIndent).',})(?P.+)$#u', $this->currentLine, $matches)) - { - if (' ' == $separator && $previousIndent != $matches['indent']) - { - $text = substr($text, 0, -1)."\n"; + return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); } - $previousIndent = $matches['indent']; - - $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator); - } - else if (preg_match('#^(?P *)$#', $this->currentLine, $matches)) - { - $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n"; - } - else - { - $this->moveToPreviousLine(); - break; - } + return sfYamlInline::load($value); } - if (' ' == $separator) + /** + * Parses a folded scalar. + * + * @param string $separator The separator that was used to begin this folded scalar (| or >) + * @param string $indicator The indicator that was used to begin this folded scalar (+ or -) + * @param int $indentation The indentation that was used to begin this folded scalar + * + * @return string The text value + */ + protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0) { - // replace last separator by a newline - $text = preg_replace('/ (\n*)$/', "\n$1", $text); - } + $separator = '|' == $separator ? "\n" : ' '; + $text = ''; - switch ($indicator) - { - case '': - $text = preg_replace('#\n+$#s', "\n", $text); - break; - case '+': - break; - case '-': - $text = preg_replace('#\n+$#s', '', $text); - break; - } + $notEOF = $this->moveToNextLine(); - return $text; - } + while ($notEOF && $this->isCurrentLineBlank()) { + $text .= "\n"; - /** - * Returns true if the next line is indented. - * - * @return Boolean Returns true if the next line is indented, false otherwise - */ - protected function isNextLineIndented() - { - $currentIndentation = $this->getCurrentLineIndentation(); - $notEOF = $this->moveToNextLine(); + $notEOF = $this->moveToNextLine(); + } - while ($notEOF && $this->isCurrentLineEmpty()) - { - $notEOF = $this->moveToNextLine(); + if (!$notEOF) { + return ''; + } + + if (!preg_match('#^(?P'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P.*)$#u', $this->currentLine, $matches)) { + $this->moveToPreviousLine(); + + return ''; + } + + $textIndent = $matches['indent']; + $previousIndent = 0; + + $text .= $matches['text'].$separator; + while ($this->currentLineNb + 1 < count($this->lines)) { + $this->moveToNextLine(); + + if (preg_match('#^(?P {'.strlen($textIndent).',})(?P.+)$#u', $this->currentLine, $matches)) { + if (' ' == $separator && $previousIndent != $matches['indent']) { + $text = substr($text, 0, -1)."\n"; + } + $previousIndent = $matches['indent']; + + $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator); + } elseif (preg_match('#^(?P *)$#', $this->currentLine, $matches)) { + $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n"; + } else { + $this->moveToPreviousLine(); + + break; + } + } + + if (' ' == $separator) { + // replace last separator by a newline + $text = preg_replace('/ (\n*)$/', "\n$1", $text); + } + + switch ($indicator) { + case '': + $text = preg_replace('#\n+$#s', "\n", $text); + break; + case '+': + break; + case '-': + $text = preg_replace('#\n+$#s', '', $text); + break; + } + + return $text; } - if (false === $notEOF) + /** + * Returns true if the next line is indented. + * + * @return bool Returns true if the next line is indented, false otherwise + */ + protected function isNextLineIndented() { - return false; + $currentIndentation = $this->getCurrentLineIndentation(); + $notEOF = $this->moveToNextLine(); + + while ($notEOF && $this->isCurrentLineEmpty()) { + $notEOF = $this->moveToNextLine(); + } + + if (false === $notEOF) { + return false; + } + + $ret = false; + if ($this->getCurrentLineIndentation() <= $currentIndentation) { + $ret = true; + } + + $this->moveToPreviousLine(); + + return $ret; } - $ret = false; - if ($this->getCurrentLineIndentation() <= $currentIndentation) + /** + * Returns true if the current line is blank or if it is a comment line. + * + * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise + */ + protected function isCurrentLineEmpty() { - $ret = true; + return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); } - $this->moveToPreviousLine(); - - return $ret; - } - - /** - * Returns true if the current line is blank or if it is a comment line. - * - * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise - */ - protected function isCurrentLineEmpty() - { - return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); - } - - /** - * Returns true if the current line is blank. - * - * @return Boolean Returns true if the current line is blank, false otherwise - */ - protected function isCurrentLineBlank() - { - return '' == trim($this->currentLine, ' '); - } - - /** - * Returns true if the current line is a comment line. - * - * @return Boolean Returns true if the current line is a comment line, false otherwise - */ - protected function isCurrentLineComment() - { - //checking explicitly the first char of the trim is faster than loops or strpos - $ltrimmedLine = ltrim($this->currentLine, ' '); - return $ltrimmedLine[0] === '#'; - } - - /** - * Cleanups a YAML string to be parsed. - * - * @param string $value The input YAML string - * - * @return string A cleaned up YAML string - */ - protected function cleanup($value) - { - $value = str_replace(array("\r\n", "\r"), "\n", $value); - - if (!preg_match("#\n$#", $value)) + /** + * Returns true if the current line is blank. + * + * @return bool Returns true if the current line is blank, false otherwise + */ + protected function isCurrentLineBlank() { - $value .= "\n"; + return '' == trim($this->currentLine, ' '); } - // strip YAML header - $count = 0; - $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#su', '', $value, -1, $count); - $this->offset += $count; - - // remove leading comments - $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); - if ($count == 1) + /** + * Returns true if the current line is a comment line. + * + * @return bool Returns true if the current line is a comment line, false otherwise + */ + protected function isCurrentLineComment() { - // items have been removed, update the offset - $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); - $value = $trimmedValue; + // checking explicitly the first char of the trim is faster than loops or strpos + $ltrimmedLine = ltrim($this->currentLine, ' '); + + return '#' === $ltrimmedLine[0]; } - // remove start of the document marker (---) - $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); - if ($count == 1) + /** + * Cleanups a YAML string to be parsed. + * + * @param string $value The input YAML string + * + * @return string A cleaned up YAML string + */ + protected function cleanup($value) { - // items have been removed, update the offset - $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); - $value = $trimmedValue; + $value = str_replace(array("\r\n", "\r"), "\n", $value); - // remove end of the document marker (...) - $value = preg_replace('#\.\.\.\s*$#s', '', $value); - } + if (!preg_match("#\n$#", $value)) { + $value .= "\n"; + } - return $value; - } + // strip YAML header + $count = 0; + $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#su', '', $value, -1, $count); + $this->offset += $count; + + // remove leading comments + $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); + if (1 == $count) { + // items have been removed, update the offset + $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); + $value = $trimmedValue; + } + + // remove start of the document marker (---) + $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); + if (1 == $count) { + // items have been removed, update the offset + $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); + $value = $trimmedValue; + + // remove end of the document marker (...) + $value = preg_replace('#\.\.\.\s*$#s', '', $value); + } + + return $value; + } } diff --git a/lib/Doctrine/Query.php b/lib/Doctrine/Query.php index a4d0b40f8..274086455 100644 --- a/lib/Doctrine/Query.php +++ b/lib/Doctrine/Query.php @@ -25,13 +25,15 @@ * data in an object-oriented fashion. A DQL query understands relations and inheritance * and is dbms independant. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen + * * @todo Proposal: This class does far too much. It should have only 1 task: Collecting * the DQL query parts and the query parameters (the query state and caching options/methods * can remain here, too). @@ -59,58 +61,58 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable { /** - * @var array The DQL keywords. + * @var array the DQL keywords */ - protected static $_keywords = array('ALL', - 'AND', - 'ANY', - 'AS', - 'ASC', - 'AVG', - 'BETWEEN', - 'BIT_LENGTH', - 'BY', - 'CHARACTER_LENGTH', - 'CHAR_LENGTH', - 'CURRENT_DATE', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'DELETE', - 'DESC', - 'DISTINCT', - 'EMPTY', - 'EXISTS', - 'FALSE', - 'FETCH', - 'FROM', - 'GROUP', - 'HAVING', - 'IN', - 'INDEXBY', - 'INNER', - 'IS', - 'JOIN', - 'LEFT', - 'LIKE', - 'LOWER', - 'MEMBER', - 'MOD', - 'NEW', - 'NOT', - 'NULL', - 'OBJECT', - 'OF', - 'OR', - 'ORDER', - 'OUTER', - 'POSITION', - 'SELECT', - 'SOME', - 'TRIM', - 'TRUE', - 'UNKNOWN', - 'UPDATE', - 'WHERE'); + protected static $_keywords = array('ALL', + 'AND', + 'ANY', + 'AS', + 'ASC', + 'AVG', + 'BETWEEN', + 'BIT_LENGTH', + 'BY', + 'CHARACTER_LENGTH', + 'CHAR_LENGTH', + 'CURRENT_DATE', + 'CURRENT_TIME', + 'CURRENT_TIMESTAMP', + 'DELETE', + 'DESC', + 'DISTINCT', + 'EMPTY', + 'EXISTS', + 'FALSE', + 'FETCH', + 'FROM', + 'GROUP', + 'HAVING', + 'IN', + 'INDEXBY', + 'INNER', + 'IS', + 'JOIN', + 'LEFT', + 'LIKE', + 'LOWER', + 'MEMBER', + 'MOD', + 'NEW', + 'NOT', + 'NULL', + 'OBJECT', + 'OF', + 'OR', + 'ORDER', + 'OUTER', + 'POSITION', + 'SELECT', + 'SOME', + 'TRIM', + 'TRUE', + 'UNKNOWN', + 'UPDATE', + 'WHERE'); /** * @var array @@ -118,10 +120,10 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable protected $_subqueryAliases = array(); /** - * @var array $_aggregateAliasMap an array containing all aggregate aliases, keys as dql aliases - * and values as sql aliases + * @var array an array containing all aggregate aliases, keys as dql aliases + * and values as sql aliases */ - protected $_aggregateAliasMap = array(); + protected $_aggregateAliasMap = array(); /** * @var array @@ -129,34 +131,34 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable protected $_pendingAggregates = array(); /** - * @param boolean $needsSubquery + * @param bool $needsSubquery */ protected $_needsSubquery = false; /** - * @param boolean $isSubquery whether or not this query object is a subquery of another - * query object + * @param bool $isSubquery whether or not this query object is a subquery of another + * query object */ protected $_isSubquery; /** - * @var array $_neededTables an array containing the needed table aliases + * @var array an array containing the needed table aliases */ protected $_neededTables = array(); /** - * @var array $pendingSubqueries SELECT part subqueries, these are called pending subqueries since - * they cannot be parsed directly (some queries might be correlated) + * @var array SELECT part subqueries, these are called pending subqueries since + * they cannot be parsed directly (some queries might be correlated) */ protected $_pendingSubqueries = array(); /** - * @var array $_pendingFields an array of pending fields (fields waiting to be parsed) + * @var array an array of pending fields (fields waiting to be parsed) */ protected $_pendingFields = array(); /** - * @var array $_parsers an array of parser objects, each DQL query part has its own parser + * @var array an array of parser objects, each DQL query part has its own parser */ protected $_parsers = array(); @@ -166,24 +168,27 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable protected $_expressionMap = array(); /** - * @var string $_sql cached SQL query + * @var string cached SQL query */ protected $_sql; /** * create - * returns a new Doctrine_Query object + * returns a new Doctrine_Query object. * * @param Doctrine_Connection $conn optional connection parameter - * @param string $class Query class to instantiate + * @param string $class Query class to instantiate + * * @return Doctrine_Query */ public static function create($conn = null, $class = null) { - if ( ! $class) { + if (!$class) { $class = Doctrine_Manager::getInstance() - ->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS); + ->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS) + ; } + return new $class($conn); } @@ -216,14 +221,14 @@ public function reset() /** * createSubquery - * creates a subquery + * creates a subquery. * * @return Doctrine_Hydrate */ public function createSubquery() { $class = get_class($this); - $obj = new $class(); + $obj = new $class(); // copy the aliases to the subquery $obj->copySubqueryInfo($this); @@ -235,15 +240,16 @@ public function createSubquery() } /** - * addPendingJoinCondition + * addPendingJoinCondition. * - * @param string $componentAlias component alias - * @param string $joinCondition dql join condition - * @return Doctrine_Query this object + * @param string $componentAlias component alias + * @param string $joinCondition dql join condition + * + * @return Doctrine_Query this object */ public function addPendingJoinCondition($componentAlias, $joinCondition) { - if ( ! isset($this->_pendingJoinConditions[$componentAlias])) { + if (!isset($this->_pendingJoinConditions[$componentAlias])) { $this->_pendingJoinConditions[$componentAlias] = array(); } @@ -255,6 +261,7 @@ public function addPendingJoinCondition($componentAlias, $joinCondition) * Convenience method to execute using array fetching as hydration mode. * * @param string $params + * * @return array */ public function fetchArray($params = array()) @@ -280,13 +287,14 @@ public function fetchOne($params = array(), $hydrationMode = null) return $collection; } - if ($collection === null || count($collection) === 0) { + if (null === $collection || 0 === count($collection)) { return false; } if ($collection instanceof Doctrine_Collection) { return $collection->getFirst(); - } else if (is_array($collection)) { + } + if (is_array($collection)) { return array_shift($collection); } @@ -303,23 +311,26 @@ public function fetchOne($params = array(), $hydrationMode = null) * If null is given as the first parameter this method retrieves the current * value of Doctrine_Query::$isSubquery. * - * @param boolean $bool whether or not this query acts as a subquery + * @param bool $bool whether or not this query acts as a subquery + * * @return Doctrine_Query|bool */ public function isSubquery($bool = null) { - if ($bool === null) { + if (null === $bool) { return $this->_isSubquery; } $this->_isSubquery = (bool) $bool; + return $this; } /** - * getSqlAggregateAlias + * getSqlAggregateAlias. + * + * @param string $dqlAlias the dql alias of an aggregate value * - * @param string $dqlAlias the dql alias of an aggregate value * @return string */ public function getSqlAggregateAlias($dqlAlias) @@ -329,27 +340,30 @@ public function getSqlAggregateAlias($dqlAlias) $this->_expressionMap[$dqlAlias][1] = true; return $this->_aggregateAliasMap[$dqlAlias]; - } else if ( ! empty($this->_pendingAggregates)) { + } + if (!empty($this->_pendingAggregates)) { $this->processPendingAggregates(); return $this->getSqlAggregateAlias($dqlAlias); - } else if( ! ($this->_conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EXPR)){ + } + if (!($this->_conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EXPR)) { return $dqlAlias; - } else { - throw new Doctrine_Query_Exception('Unknown aggregate alias: ' . $dqlAlias); } + throw new Doctrine_Query_Exception('Unknown aggregate alias: '.$dqlAlias); } /** - * Check if a dql alias has a sql aggregate alias + * Check if a dql alias has a sql aggregate alias. * * @param string $dqlAlias - * @return boolean + * + * @return bool */ public function hasSqlAggregateAlias($dqlAlias) { try { $this->getSqlAggregateAlias($dqlAlias); + return true; } catch (Exception $e) { return false; @@ -357,8 +371,7 @@ public function hasSqlAggregateAlias($dqlAlias) } /** - * Adjust the processed param index for "foo.bar IN ?" support - * + * Adjust the processed param index for "foo.bar IN ?" support. */ public function adjustProcessedParam($index) { @@ -384,40 +397,43 @@ public function adjustProcessedParam($index) * var_dump($q->getDqlPart('where')); * // array(2) { [0] => string(8) 'name = ?' [1] => string(8) 'date > ?' } * - * @param string $queryPart the name of the query part; can be: - * array from, containing strings; - * array select, containg string; - * boolean forUpdate; - * array set; - * array join; - * array where; - * array groupby; - * array having; - * array orderby, containing strings such as 'id ASC'; - * array limit, containing numerics; - * array offset, containing numerics; + * + * @param string $queryPart the name of the query part; can be: + * array from, containing strings; + * array select, containg string; + * boolean forUpdate; + * array set; + * array join; + * array where; + * array groupby; + * array having; + * array orderby, containing strings such as 'id ASC'; + * array limit, containing numerics; + * array offset, containing numerics; + * * @return array */ public function getDqlPart($queryPart) { - if ( ! isset($this->_dqlParts[$queryPart])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $queryPart); + if (!isset($this->_dqlParts[$queryPart])) { + throw new Doctrine_Query_Exception('Unknown query part '.$queryPart); } return $this->_dqlParts[$queryPart]; } /** - * contains + * contains. * * Method to check if a arbitrary piece of dql exists * * @param string $dql Arbitrary piece of dql to check for - * @return boolean + * + * @return bool */ public function contains($dql) { - return stripos($this->getDql(), $dql) === false ? false : true; + return false === stripos($this->getDql(), $dql) ? false : true; } /** @@ -427,9 +443,12 @@ public function contains($dql) * specific component is being parsed. For instance, the wildcard '*' * is expanded in the list of columns. * - * @throws Doctrine_Query_Exception if unknown component alias has been given - * @param string $componentAlias the alias of the component + * @param string $componentAlias the alias of the component + * * @return string SQL code + * + * @throws Doctrine_Query_Exception if unknown component alias has been given + * * @todo Description: What is a 'pending field' (and are there non-pending fields, too)? * What is 'processed'? (Meaning: What information is gathered & stored away) */ @@ -438,13 +457,13 @@ public function processPendingFields($componentAlias) $tableAlias = $this->getSqlTableAlias($componentAlias); $table = $this->_queryComponents[$componentAlias]['table']; - if ( ! isset($this->_pendingFields[$componentAlias])) { - if ($this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_NONE) { - if ( ! $this->_isSubquery && $componentAlias == $this->getRootAlias()) { - throw new Doctrine_Query_Exception("The root class of the query (alias $componentAlias) " - . " must have at least one field selected."); + if (!isset($this->_pendingFields[$componentAlias])) { + if (Doctrine_Core::HYDRATE_NONE != $this->_hydrator->getHydrationMode()) { + if (!$this->_isSubquery && $componentAlias == $this->getRootAlias()) { + throw new Doctrine_Query_Exception("The root class of the query (alias {$componentAlias}) ".' must have at least one field selected.'); } } + return; } @@ -452,15 +471,13 @@ public function processPendingFields($componentAlias) // the query (FROM xyz) or its a "fetch join"). // Check that the parent join (if there is one), is a "fetch join", too. - if ( ! $this->isSubquery() && isset($this->_queryComponents[$componentAlias]['parent'])) { + if (!$this->isSubquery() && isset($this->_queryComponents[$componentAlias]['parent'])) { $parentAlias = $this->_queryComponents[$componentAlias]['parent']; - if (is_string($parentAlias) && ! isset($this->_pendingFields[$parentAlias]) - && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_NONE - && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_SCALAR - && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_SINGLE_SCALAR) { - throw new Doctrine_Query_Exception("The left side of the join between " - . "the aliases '$parentAlias' and '$componentAlias' must have at least" - . " the primary key field(s) selected."); + if (is_string($parentAlias) && !isset($this->_pendingFields[$parentAlias]) + && Doctrine_Core::HYDRATE_NONE != $this->_hydrator->getHydrationMode() + && Doctrine_Core::HYDRATE_SCALAR != $this->_hydrator->getHydrationMode() + && Doctrine_Core::HYDRATE_SINGLE_SCALAR != $this->_hydrator->getHydrationMode()) { + throw new Doctrine_Query_Exception('The left side of the join between '."the aliases '{$parentAlias}' and '{$componentAlias}' must have at least".' the primary key field(s) selected.'); } } @@ -474,7 +491,7 @@ public function processPendingFields($componentAlias) // only auto-add the primary key fields if this query object is not // a subquery of another query object or we're using a child of the Object Graph // hydrator - if ( ! $this->_isSubquery && is_subclass_of($driverClassName, 'Doctrine_Hydrator_Graph')) { + if (!$this->_isSubquery && is_subclass_of($driverClassName, 'Doctrine_Hydrator_Graph')) { $fields = array_unique(array_merge((array) $table->getIdentifier(), $fields)); } } @@ -482,20 +499,19 @@ public function processPendingFields($componentAlias) $sql = array(); foreach ($fields as $fieldName) { $columnName = $table->getColumnName($fieldName); - if (($owner = $table->getColumnOwner($columnName)) !== null && - $owner !== $table->getComponentName()) { - + if (($owner = $table->getColumnOwner($columnName)) !== null + && $owner !== $table->getComponentName()) { $parent = $this->_conn->getTable($owner); $columnName = $parent->getColumnName($fieldName); - $parentAlias = $this->getSqlTableAlias($componentAlias . '.' . $parent->getComponentName()); - $sql[] = $this->_conn->quoteIdentifier($parentAlias) . '.' . $this->_conn->quoteIdentifier($columnName) - . ' AS ' - . $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName); + $parentAlias = $this->getSqlTableAlias($componentAlias.'.'.$parent->getComponentName()); + $sql[] = $this->_conn->quoteIdentifier($parentAlias).'.'.$this->_conn->quoteIdentifier($columnName) + .' AS ' + .$this->_conn->quoteIdentifier($tableAlias.'__'.$columnName); } else { $columnName = $table->getColumnName($fieldName); - $sql[] = $this->_conn->quoteIdentifier($tableAlias) . '.' . $this->_conn->quoteIdentifier($columnName) - . ' AS ' - . $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName); + $sql[] = $this->_conn->quoteIdentifier($tableAlias).'.'.$this->_conn->quoteIdentifier($columnName) + .' AS ' + .$this->_conn->quoteIdentifier($tableAlias.'__'.$columnName); } } @@ -508,14 +524,16 @@ public function processPendingFields($componentAlias) * Parses a nested field * * $q->parseSelectField('u.Phonenumber.value'); - * + * . * * @param string $field - * @throws Doctrine_Query_Exception if unknown component alias has been given - * @return string SQL fragment + * + * @return string SQL fragment + * + * @throws Doctrine_Query_Exception if unknown component alias has been given + * * @todo Description: Explain what this method does. Is there a relation to parseSelect()? * This method is not used from any class or testcase in the Doctrine package. - * */ public function parseSelectField($field) { @@ -531,44 +549,44 @@ public function parseSelectField($field) } $tableAlias = $this->getSqlTableAlias($componentAlias); - $table = $this->_queryComponents[$componentAlias]['table']; - + $table = $this->_queryComponents[$componentAlias]['table']; // check for wildcards - if ($field === '*') { + if ('*' === $field) { $sql = array(); foreach ($table->getColumnNames() as $field) { - $sql[] = $this->parseSelectField($componentAlias . '.' . $field); + $sql[] = $this->parseSelectField($componentAlias.'.'.$field); } return implode(', ', $sql); - } else { - $name = $table->getColumnName($field); + } + $name = $table->getColumnName($field); - $this->_neededTables[] = $tableAlias; + $this->_neededTables[] = $tableAlias; - return $this->_conn->quoteIdentifier($tableAlias . '.' . $name) - . ' AS ' - . $this->_conn->quoteIdentifier($tableAlias . '__' . $name); - } + return $this->_conn->quoteIdentifier($tableAlias.'.'.$name) + .' AS ' + .$this->_conn->quoteIdentifier($tableAlias.'__'.$name); } /** * getExpressionOwner - * returns the component alias for owner of given expression + * returns the component alias for owner of given expression. + * + * @param string $expr expression from which to get to owner from + * + * @return string the component alias * - * @param string $expr expression from which to get to owner from - * @return string the component alias * @todo Description: What does it mean if a component is an 'owner' of an expression? * What kind of 'expression' are we talking about here? */ public function getExpressionOwner($expr) { - if (strtoupper(substr(trim($expr, '( '), 0, 6)) !== 'SELECT') { + if ('SELECT' !== strtoupper(substr(trim($expr, '( '), 0, 6))) { // Fix for http://www.doctrine-project.org/jira/browse/DC-754 $expr = preg_replace('/([\'\"])[^\1]*\1/', '', $expr); - preg_match_all("/[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*[\.[a-z0-9]+]*/i", $expr, $matches); + preg_match_all('/[a-z_][a-z0-9_]*\\.[a-z_][a-z0-9_]*[\\.[a-z0-9]+]*/i', $expr, $matches); $match = current($matches); @@ -578,27 +596,28 @@ public function getExpressionOwner($expr) return $terms[0]; } } - return $this->getRootAlias(); + return $this->getRootAlias(); } /** * parseSelect * parses the query select part and - * adds selected fields to pendingFields array + * adds selected fields to pendingFields array. * * @param string $dql + * * @todo Description: What information is extracted (and then stored)? */ public function parseSelect($dql) { $refs = $this->_tokenizer->sqlExplode($dql, ','); - $pos = strpos(trim($refs[0]), ' '); + $pos = strpos(trim($refs[0]), ' '); $first = substr($refs[0], 0, $pos); // check for DISTINCT keyword - if ($first === 'DISTINCT') { + if ('DISTINCT' === $first) { $this->_sqlParts['distinct'] = true; $refs[0] = substr($refs[0], ++$pos); @@ -614,18 +633,18 @@ public function parseSelect($dql) } $terms = $this->_tokenizer->sqlExplode($reference, ' '); - $pos = strpos($terms[0], '('); + $pos = strpos($terms[0], '('); - if (count($terms) > 1 || $pos !== false) { + if (count($terms) > 1 || false !== $pos) { $expression = array_shift($terms); $alias = array_pop($terms); - if ( ! $alias) { + if (!$alias) { $alias = substr($expression, 0, $pos); } // Fix for http://www.doctrine-project.org/jira/browse/DC-706 - if ($pos !== false && substr($expression, 0, 1) !== "'" && substr($expression, 0, $pos) == '') { + if (false !== $pos && "'" !== substr($expression, 0, 1) && '' == substr($expression, 0, $pos)) { $_queryComponents = $this->_queryComponents; reset($_queryComponents); $componentAlias = key($_queryComponents); @@ -637,11 +656,11 @@ public function parseSelect($dql) $tableAlias = $this->getSqlTableAlias($componentAlias); - $index = count($this->_aggregateAliasMap); + $index = count($this->_aggregateAliasMap); - $sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index); + $sqlAlias = $this->_conn->quoteIdentifier($tableAlias.'__'.$index); - $this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias; + $this->_sqlParts['select'][] = $expression.' AS '.$sqlAlias; $this->_aggregateAliasMap[$alias] = $sqlAlias; $this->_expressionMap[$alias][0] = $expression; @@ -672,7 +691,7 @@ public function parseSelect($dql) /** * parseClause - * parses given DQL clause + * parses given DQL clause. * * this method handles five tasks: * @@ -682,7 +701,8 @@ public function parseSelect($dql) * 4. Quotes all identifiers * 5. Parses nested clauses and subqueries recursively * - * @return string SQL string + * @return string SQL string + * * @todo Description: What is a 'dql clause' (and what not)? * Refactor: Too long & nesting level */ @@ -691,7 +711,7 @@ public function parseClause($clause) $clause = $this->_conn->dataDict->parseBoolean(trim($clause)); if (is_numeric($clause)) { - return $clause; + return $clause; } $terms = $this->_tokenizer->clauseExplode($clause, array(' ', '+', '-', '*', '/', '<', '>', '=', '>=', '<=', '&', '|')); @@ -700,19 +720,19 @@ public function parseClause($clause) foreach ($terms as $term) { $pos = strpos($term[0], '('); - if ($pos !== false && substr($term[0], 0, 1) !== "'") { + if (false !== $pos && "'" !== substr($term[0], 0, 1)) { $name = substr($term[0], 0, $pos); $term[0] = $this->parseFunctionExpression($term[0]); } else { - if (substr($term[0], 0, 1) !== "'" && substr($term[0], -1) !== "'") { - if (strpos($term[0], '.') !== false) { - if ( ! is_numeric($term[0])) { + if ("'" !== substr($term[0], 0, 1) && "'" !== substr($term[0], -1)) { + if (false !== strpos($term[0], '.')) { + if (!is_numeric($term[0])) { $e = explode('.', $term[0]); $field = array_pop($e); - if ($this->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->getType()) { $componentAlias = implode('.', $e); if (empty($componentAlias)) { @@ -722,8 +742,8 @@ public function parseClause($clause) $this->load($componentAlias); // check the existence of the component alias - if ( ! isset($this->_queryComponents[$componentAlias])) { - throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias); + if (!isset($this->_queryComponents[$componentAlias])) { + throw new Doctrine_Query_Exception('Unknown component alias '.$componentAlias); } $table = $this->_queryComponents[$componentAlias]['table']; @@ -734,20 +754,20 @@ public function parseClause($clause) $field = $table->getColumnName($field); // check column existence - if ( ! $def) { - throw new Doctrine_Query_Exception('Unknown column ' . $field); + if (!$def) { + throw new Doctrine_Query_Exception('Unknown column '.$field); } if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->getSqlTableAlias($componentAlias); // build sql expression $term[0] = $this->_conn->quoteIdentifier($tableAlias) - . '.' - . $this->_conn->quoteIdentifier($field); + .'.' + .$this->_conn->quoteIdentifier($field); } else { // build sql expression $field = $this->getRoot()->getColumnName($field); @@ -755,14 +775,13 @@ public function parseClause($clause) } } } else { - if ( ! empty($term[0]) && ! in_array(strtoupper($term[0]), self::$_keywords) && - ! is_numeric($term[0]) && $term[0] !== '?' && substr($term[0], 0, 1) !== ':') { - + if (!empty($term[0]) && !in_array(strtoupper($term[0]), self::$_keywords) + && !is_numeric($term[0]) && '?' !== $term[0] && ':' !== substr($term[0], 0, 1)) { $componentAlias = $this->getRootAlias(); $found = false; - if ($componentAlias !== false && $componentAlias !== null) { + if (false !== $componentAlias && null !== $componentAlias) { $table = $this->_queryComponents[$componentAlias]['table']; // check column existence @@ -774,18 +793,17 @@ public function parseClause($clause) // get the actual column name from field name $term[0] = $table->getColumnName($term[0]); - if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->getSqlTableAlias($componentAlias); - if ($this->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->getType()) { // build sql expression $term[0] = $this->_conn->quoteIdentifier($tableAlias) - . '.' - . $this->_conn->quoteIdentifier($term[0]); + .'.' + .$this->_conn->quoteIdentifier($term[0]); } else { // build sql expression $term[0] = $this->_conn->quoteIdentifier($term[0]); @@ -795,7 +813,7 @@ public function parseClause($clause) } } - if ( ! $found) { + if (!$found) { $term[0] = $this->getSqlAggregateAlias($term[0]); } } @@ -803,14 +821,14 @@ public function parseClause($clause) } } - $str .= $term[0] . $term[1]; + $str .= $term[0].$term[1]; } + return $str; } public function parseIdentifierReference($expr) { - } public function parseFunctionExpression($expr, $parseCallback = null) @@ -818,40 +836,39 @@ public function parseFunctionExpression($expr, $parseCallback = null) $pos = strpos($expr, '('); $name = substr($expr, 0, $pos); - if ($name === '') { + if ('' === $name) { return $this->parseSubquery($expr); } - $argStr = substr($expr, ($pos + 1), -1); - $args = array(); + $argStr = substr($expr, $pos + 1, -1); + $args = array(); // parse args foreach ($this->_tokenizer->sqlExplode($argStr, ',') as $arg) { - $args[] = $parseCallback ? call_user_func_array($parseCallback, array($arg)) : $this->parseClause($arg); + $args[] = $parseCallback ? call_user_func_array($parseCallback, array($arg)) : $this->parseClause($arg); } // convert DQL function to its RDBMS specific equivalent try { $expr = call_user_func_array(array($this->_conn->expression, $name), $args); } catch (Doctrine_Expression_Exception $e) { - throw new Doctrine_Query_Exception('Unknown function ' . $name . '.'); + throw new Doctrine_Query_Exception('Unknown function '.$name.'.'); } return $expr; } - public function parseSubquery($subquery) { $trimmed = trim($this->_tokenizer->bracketTrim($subquery)); // check for possible subqueries - if (substr($trimmed, 0, 4) == 'FROM' || substr($trimmed, 0, 6) == 'SELECT') { + if ('FROM' == substr($trimmed, 0, 4) || 'SELECT' == substr($trimmed, 0, 6)) { // parse subquery $q = $this->createSubquery()->parseDqlQuery($trimmed); $trimmed = $q->getSqlQuery(); $q->free(); - } else if (substr($trimmed, 0, 4) == 'SQL:') { + } elseif ('SQL:' == substr($trimmed, 0, 4)) { $trimmed = substr($trimmed, 4); } else { $e = $this->_tokenizer->sqlExplode($trimmed, ','); @@ -866,18 +883,16 @@ public function parseSubquery($subquery) $trimmed = implode(', ', $value); } - return '(' . $trimmed . ')'; + return '('.$trimmed.')'; } - /** * processPendingSubqueries - * processes pending subqueries + * processes pending subqueries. * * subqueries can only be processed when the query is fully constructed * since some subqueries may be correlated * - * @return void * @todo Better description. i.e. What is a 'pending subquery'? What does 'processed' mean? * (parsed? sql is constructed? some information is gathered?) */ @@ -895,9 +910,9 @@ public function processPendingSubqueries() $componentAlias = key($this->_queryComponents); $tableAlias = $this->getSqlTableAlias($componentAlias); - $sqlAlias = $tableAlias . '__' . count($this->_aggregateAliasMap); + $sqlAlias = $tableAlias.'__'.count($this->_aggregateAliasMap); - $this->_sqlParts['select'][] = '(' . $sql . ') AS ' . $this->_conn->quoteIdentifier($sqlAlias); + $this->_sqlParts['select'][] = '('.$sql.') AS '.$this->_conn->quoteIdentifier($sqlAlias); $this->_aggregateAliasMap[$alias] = $sqlAlias; $this->_queryComponents[$componentAlias]['agg'][] = $alias; @@ -907,23 +922,21 @@ public function processPendingSubqueries() /** * processPendingAggregates - * processes pending aggregate values for given component alias + * processes pending aggregate values for given component alias. * - * @return void * @todo Better description. i.e. What is a 'pending aggregate'? What does 'processed' mean? */ public function processPendingAggregates() { // iterate trhough all aggregates foreach ($this->_pendingAggregates as $aggregate) { - list ($expression, $components, $alias) = $aggregate; + list($expression, $components, $alias) = $aggregate; $tableAliases = array(); // iterate through the component references within the aggregate function - if ( ! empty ($components)) { + if (!empty($components)) { foreach ($components as $component) { - if (is_numeric($component)) { continue; } @@ -934,8 +947,8 @@ public function processPendingAggregates() $componentAlias = implode('.', $e); // check the existence of the component alias - if ( ! isset($this->_queryComponents[$componentAlias])) { - throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias); + if (!isset($this->_queryComponents[$componentAlias])) { + throw new Doctrine_Query_Exception('Unknown component alias '.$componentAlias); } $table = $this->_queryComponents[$componentAlias]['table']; @@ -943,8 +956,8 @@ public function processPendingAggregates() $field = $table->getColumnName($field); // check column existence - if ( ! $table->hasColumn($field)) { - throw new Doctrine_Query_Exception('Unknown column ' . $field); + if (!$table->hasColumn($field)) { + throw new Doctrine_Query_Exception('Unknown column '.$field); } $sqlTableAlias = $this->getSqlTableAlias($componentAlias); @@ -953,20 +966,20 @@ public function processPendingAggregates() // build sql expression - $identifier = $this->_conn->quoteIdentifier($sqlTableAlias . '.' . $field); + $identifier = $this->_conn->quoteIdentifier($sqlTableAlias.'.'.$field); $expression = str_replace($component, $identifier, $expression); } } - if (count($tableAliases) !== 1) { + if (1 !== count($tableAliases)) { $componentAlias = reset($this->_tableAliasMap); $tableAlias = key($this->_tableAliasMap); } - $index = count($this->_aggregateAliasMap); - $sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index); + $index = count($this->_aggregateAliasMap); + $sqlAlias = $this->_conn->quoteIdentifier($tableAlias.'__'.$index); - $this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias; + $this->_sqlParts['select'][] = $expression.' AS '.$sqlAlias; $this->_aggregateAliasMap[$alias] = $sqlAlias; $this->_expressionMap[$alias][0] = $expression; @@ -983,32 +996,33 @@ public function processPendingAggregates() * _buildSqlQueryBase * returns the base of the generated sql query * On mysql driver special strategy has to be used for DELETE statements - * (where is this special strategy??) + * (where is this special strategy??). * - * @return string the base of the generated sql query + * @return string the base of the generated sql query */ protected function _buildSqlQueryBase() { switch ($this->_type) { case self::DELETE: $q = 'DELETE FROM '; - break; + break; case self::UPDATE: $q = 'UPDATE '; - break; + break; case self::SELECT: $distinct = ($this->_sqlParts['distinct']) ? 'DISTINCT ' : ''; - $q = 'SELECT ' . $distinct . implode(', ', $this->_sqlParts['select']) . ' FROM '; - break; + $q = 'SELECT '.$distinct.implode(', ', $this->_sqlParts['select']).' FROM '; + break; } + return $q; } /** * _buildSqlFromPart - * builds the from part of the query and returns it + * builds the from part of the query and returns it. * - * @return string the query sql from part + * @return string the query sql from part */ protected function _buildSqlFromPart($ignorePending = false) { @@ -1017,8 +1031,8 @@ protected function _buildSqlFromPart($ignorePending = false) foreach ($this->_sqlParts['from'] as $k => $part) { $e = explode(' ', $part); - if ($k === 0) { - if ( ! $ignorePending && $this->_type == self::SELECT) { + if (0 === $k) { + if (!$ignorePending && self::SELECT == $this->_type) { // We may still have pending conditions $alias = count($e) > 1 ? $this->getComponentAlias($e[1]) @@ -1026,15 +1040,15 @@ protected function _buildSqlFromPart($ignorePending = false) $where = $this->_processPendingJoinConditions($alias); // apply inheritance to WHERE part - if ( ! empty($where)) { + if (!empty($where)) { if (count($this->_sqlParts['where']) > 0) { $this->_sqlParts['where'][] = 'AND'; } - if (substr($where, 0, 1) === '(' && substr($where, -1) === ')') { + if ('(' === substr($where, 0, 1) && ')' === substr($where, -1)) { $this->_sqlParts['where'][] = $where; } else { - $this->_sqlParts['where'][] = '(' . $where . ')'; + $this->_sqlParts['where'][] = '('.$where.')'; } } } @@ -1046,21 +1060,20 @@ protected function _buildSqlFromPart($ignorePending = false) // preserve LEFT JOINs only if needed // Check if it's JOIN, if not add a comma separator instead of space - if ( ! preg_match('/\bJOIN\b/i', $part) && ! isset($this->_pendingJoinConditions[$k])) { - $q .= ', ' . $part; + if (!preg_match('/\bJOIN\b/i', $part) && !isset($this->_pendingJoinConditions[$k])) { + $q .= ', '.$part; } else { - if (substr($part, 0, 9) === 'LEFT JOIN') { + if ('LEFT JOIN' === substr($part, 0, 9)) { $aliases = array_merge($this->_subqueryAliases, - array_keys($this->_neededTables)); + array_keys($this->_neededTables)); - if ( ! in_array($e[3], $aliases) && ! in_array($e[2], $aliases) && ! empty($this->_pendingFields)) { + if (!in_array($e[3], $aliases) && !in_array($e[2], $aliases) && !empty($this->_pendingFields)) { continue; } - } - if ( ! $ignorePending && isset($this->_pendingJoinConditions[$k])) { - if (strpos($part, ' ON ') !== false) { + if (!$ignorePending && isset($this->_pendingJoinConditions[$k])) { + if (false !== strpos($part, ' ON ')) { $part .= ' AND '; } else { $part .= ' ON '; @@ -1073,13 +1086,14 @@ protected function _buildSqlFromPart($ignorePending = false) $string = $this->getInheritanceCondition($componentAlias); if ($string) { - $part = $part . ' AND ' . $string; + $part = $part.' AND '.$string; } - $q .= ' ' . $part; + $q .= ' '.$part; } $this->_sqlParts['from'][$k] = $part; } + return $q; } @@ -1089,13 +1103,14 @@ protected function _buildSqlFromPart($ignorePending = false) * handling. * * @param string $alias Component Alias + * * @return Processed pending conditions */ protected function _processPendingJoinConditions($alias) { $parts = array(); - if ($alias !== null && isset($this->_pendingJoinConditions[$alias])) { + if (null !== $alias && isset($this->_pendingJoinConditions[$alias])) { $parser = new Doctrine_Query_JoinCondition($this, $this->_tokenizer); foreach ($this->_pendingJoinConditions[$alias] as $joinCondition) { @@ -1103,20 +1118,21 @@ protected function _processPendingJoinConditions($alias) } // FIX #1860 and #1876: Cannot unset them, otherwise query cannot be reused later - //unset($this->_pendingJoinConditions[$alias]); + // unset($this->_pendingJoinConditions[$alias]); } - return (count($parts) > 0 ? '(' . implode(') AND (', $parts) . ')' : ''); + return count($parts) > 0 ? '('.implode(') AND (', $parts).')' : ''; } /** * builds the sql query from the given parameters and applies things such as - * column aggregation inheritance and limit subqueries if needed + * column aggregation inheritance and limit subqueries if needed. * - * @param array $params an array of prepared statement params (needed only in mysql driver - * when limit subquery algorithm is used) - * @param bool $limitSubquery Whether or not to try and apply the limit subquery algorithm - * @return string the built sql query + * @param array $params an array of prepared statement params (needed only in mysql driver + * when limit subquery algorithm is used) + * @param bool $limitSubquery Whether or not to try and apply the limit subquery algorithm + * + * @return string the built sql query */ public function getSqlQuery($params = array(), $limitSubquery = true) { @@ -1126,25 +1142,27 @@ public function getSqlQuery($params = array(), $limitSubquery = true) // Initialize prepared parameters array $this->_execParams = $this->getFlattenedParams(); - if ($this->_state !== self::STATE_DIRTY) { + if (self::STATE_DIRTY !== $this->_state) { $this->fixArrayParameterValues($this->getInternalParams()); // Return compiled SQL return $this->_sql; } + return $this->buildSqlQuery($limitSubquery); } /** - * Build the SQL query from the DQL + * Build the SQL query from the DQL. * * @param bool $limitSubquery Whether or not to try and apply the limit subquery algorithm + * * @return string $sql The generated SQL string */ public function buildSqlQuery($limitSubquery = true) { // reset the state - if ( ! $this->isSubquery()) { + if (!$this->isSubquery()) { $this->_queryComponents = array(); $this->_pendingAggregates = array(); $this->_aggregateAliasMap = array(); @@ -1159,18 +1177,18 @@ public function buildSqlQuery($limitSubquery = true) // this will also populate the $_queryComponents. foreach ($this->_dqlParts as $queryPartName => $queryParts) { // If we are parsing FROM clause, we'll need to diff the queryComponents later - if ($queryPartName == 'from') { + if ('from' == $queryPartName) { // Pick queryComponents before processing $queryComponentsBefore = $this->getQueryComponents(); } // FIX #1667: _sqlParts are cleaned inside _processDqlQueryPart. - if ($queryPartName != 'forUpdate') { + if ('forUpdate' != $queryPartName) { $this->_processDqlQueryPart($queryPartName, $queryParts); } // We need to define the root alias - if ($queryPartName == 'from') { + if ('from' == $queryPartName) { // Pick queryComponents aftr processing $queryComponentsAfter = $this->getQueryComponents(); @@ -1192,24 +1210,24 @@ public function buildSqlQuery($limitSubquery = true) $table = $map['table']; $rootAlias = $this->getRootAlias(); - if ( ! empty($this->_sqlParts['limit']) && $this->_needsSubquery && - $table->getAttribute(Doctrine_Core::ATTR_QUERY_LIMIT) == Doctrine_Core::LIMIT_RECORDS) { + if (!empty($this->_sqlParts['limit']) && $this->_needsSubquery + && Doctrine_Core::LIMIT_RECORDS == $table->getAttribute(Doctrine_Core::ATTR_QUERY_LIMIT)) { // We do not need a limit-subquery if DISTINCT is used // and the selected fields are either from the root component or from a localKey relation (hasOne) // (i.e. DQL: SELECT DISTINCT u.id FROM User u LEFT JOIN u.phonenumbers LIMIT 5). - if(!$this->_sqlParts['distinct']) { + if (!$this->_sqlParts['distinct']) { $this->_isLimitSubqueryUsed = true; $needsSubQuery = true; } else { - foreach( array_keys($this->_pendingFields) as $alias){ - //no subquery for root fields - if($alias == $this->getRootAlias()){ + foreach (array_keys($this->_pendingFields) as $alias) { + // no subquery for root fields + if ($alias == $this->getRootAlias()) { continue; } - //no subquery for ONE relations - if(isset($this->_queryComponents[$alias]['relation']) && - $this->_queryComponents[$alias]['relation']->getType() == Doctrine_Relation::ONE){ + // no subquery for ONE relations + if (isset($this->_queryComponents[$alias]['relation']) + && Doctrine_Relation::ONE == $this->_queryComponents[$alias]['relation']->getType()) { continue; } @@ -1221,48 +1239,48 @@ public function buildSqlQuery($limitSubquery = true) $sql = array(); - if ( ! empty($this->_pendingFields)) { + if (!empty($this->_pendingFields)) { foreach ($this->_queryComponents as $alias => $map) { $fieldSql = $this->processPendingFields($alias); - if ( ! empty($fieldSql)) { + if (!empty($fieldSql)) { $sql[] = $fieldSql; } } } - if ( ! empty($sql)) { + if (!empty($sql)) { array_unshift($this->_sqlParts['select'], implode(', ', $sql)); } $this->_pendingFields = array(); // build the basic query - $q = $this->_buildSqlQueryBase(); + $q = $this->_buildSqlQueryBase(); $q .= $this->_buildSqlFromPart(); - if ( ! empty($this->_sqlParts['set'])) { - $q .= ' SET ' . implode(', ', $this->_sqlParts['set']); + if (!empty($this->_sqlParts['set'])) { + $q .= ' SET '.implode(', ', $this->_sqlParts['set']); } $string = $this->getInheritanceCondition($this->getRootAlias()); // apply inheritance to WHERE part - if ( ! empty($string)) { + if (!empty($string)) { if (count($this->_sqlParts['where']) > 0) { $this->_sqlParts['where'][] = 'AND'; } - if (substr($string, 0, 1) === '(' && substr($string, -1) === ')') { + if ('(' === substr($string, 0, 1) && ')' === substr($string, -1)) { $this->_sqlParts['where'][] = $string; } else { - $this->_sqlParts['where'][] = '(' . $string . ')'; + $this->_sqlParts['where'][] = '('.$string.')'; } } $modifyLimit = true; $limitSubquerySql = ''; - if ( ( ! empty($this->_sqlParts['limit']) || ! empty($this->_sqlParts['offset'])) && $needsSubQuery && $limitSubquery) { + if ((!empty($this->_sqlParts['limit']) || !empty($this->_sqlParts['offset'])) && $needsSubQuery && $limitSubquery) { $subquery = $this->getLimitSubquery(); // what about composite keys? @@ -1285,19 +1303,19 @@ public function buildSqlQuery($limitSubquery = true) $subqueryAlias = $this->_conn->quoteIdentifier('doctrine_subquery_alias'); // pgsql needs special nested LIMIT subquery - $subquery = 'SELECT ' . $subqueryAlias . '.' . $this->_conn->quoteIdentifier($idColumnName) - . ' FROM (' . $subquery . ') AS ' . $subqueryAlias; + $subquery = 'SELECT '.$subqueryAlias.'.'.$this->_conn->quoteIdentifier($idColumnName) + .' FROM ('.$subquery.') AS '.$subqueryAlias; break; } - $field = $this->getSqlTableAlias($rootAlias) . '.' . $idColumnName; + $field = $this->getSqlTableAlias($rootAlias).'.'.$idColumnName; // FIX #1868: If not ID under MySQL is found to be restricted, restrict pk column for null // (which will lead to a return of 0 items) $limitSubquerySql = $this->_conn->quoteIdentifier($field) - . (( ! empty($subquery)) ? ' IN (' . $subquery . ')' : ' IS NULL') - . ((count($this->_sqlParts['where']) > 0) ? ' AND ' : ''); + .((!empty($subquery)) ? ' IN ('.$subquery.')' : ' IS NULL') + .((count($this->_sqlParts['where']) > 0) ? ' AND ' : ''); $modifyLimit = false; } @@ -1305,12 +1323,12 @@ public function buildSqlQuery($limitSubquery = true) // FIX #DC-26: Include limitSubquerySql as major relevance in conditions $emptyWhere = empty($this->_sqlParts['where']); - if ( ! ($emptyWhere && $limitSubquerySql == '')) { + if (!($emptyWhere && '' == $limitSubquerySql)) { $where = implode(' ', $this->_sqlParts['where']); - $where = ($where == '' || (substr($where, 0, 1) === '(' && substr($where, -1) === ')')) - ? $where : '(' . $where . ')'; + $where = ('' == $where || ('(' === substr($where, 0, 1) && ')' === substr($where, -1))) + ? $where : '('.$where.')'; - $q .= ' WHERE ' . $limitSubquerySql . $where; + $q .= ' WHERE '.$limitSubquerySql.$where; // . (($limitSubquerySql == '' && count($this->_sqlParts['where']) == 1) ? substr($where, 1, -1) : $where); } @@ -1325,7 +1343,7 @@ public function buildSqlQuery($limitSubquery = true) // Add the default orderBy statements defined in the relationships and table classes // Only do this for SELECT queries - if ($this->_type === self::SELECT) { + if (self::SELECT === $this->_type) { foreach ($this->_queryComponents as $alias => $map) { $sqlAlias = $this->getSqlTableAlias($alias); if (isset($map['relation'])) { @@ -1345,7 +1363,7 @@ public function buildSqlQuery($limitSubquery = true) $e = explode(',', $orderBy); foreach ($e as $v) { $v = trim($v); - if ( ! in_array($v, $this->_sqlParts['orderby'])) { + if (!in_array($v, $this->_sqlParts['orderby'])) { $this->_sqlParts['orderby'][] = $v; } } @@ -1353,15 +1371,15 @@ public function buildSqlQuery($limitSubquery = true) } } - $q .= ( ! empty($this->_sqlParts['groupby'])) ? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : ''; - $q .= ( ! empty($this->_sqlParts['having'])) ? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']): ''; - $q .= ( ! empty($this->_sqlParts['orderby'])) ? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : ''; + $q .= (!empty($this->_sqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_sqlParts['groupby']) : ''; + $q .= (!empty($this->_sqlParts['having'])) ? ' HAVING '.implode(' AND ', $this->_sqlParts['having']) : ''; + $q .= (!empty($this->_sqlParts['orderby'])) ? ' ORDER BY '.implode(', ', $this->_sqlParts['orderby']) : ''; if ($modifyLimit) { $q = $this->_conn->modifyLimitQuery($q, $this->_sqlParts['limit'], $this->_sqlParts['offset'], false, false, $this); } - $q .= $this->_sqlParts['forUpdate'] === true ? ' FOR UPDATE ' : ''; + $q .= true === $this->_sqlParts['forUpdate'] ? ' FOR UPDATE ' : ''; $this->_sql = $q; @@ -1372,13 +1390,14 @@ public function buildSqlQuery($limitSubquery = true) /** * getLimitSubquery - * this is method is used by the record limit algorithm + * this is method is used by the record limit algorithm. * * when fetching one-to-many, many-to-many associated data with LIMIT clause * an additional subquery is needed for limiting the number of returned records instead * of limiting the number of sql result set rows * - * @return string the limit subquery + * @return string the limit subquery + * * @todo A little refactor to make the method easier to understand & maybe shorter? */ public function getLimitSubquery() @@ -1390,12 +1409,12 @@ public function getLimitSubquery() // get short alias $alias = $this->getSqlTableAlias($componentAlias); // what about composite keys? - $primaryKey = $alias . '.' . $table->getColumnName($table->getIdentifier()); + $primaryKey = $alias.'.'.$table->getColumnName($table->getIdentifier()); $driverName = $this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME); // initialize the base of the subquery - if (($driverName == 'oracle' || $driverName == 'oci' || $driverName == 'oci8') && $this->_isOrderedByJoinedColumn()) { + if (('oracle' == $driverName || 'oci' == $driverName || 'oci8' == $driverName) && $this->_isOrderedByJoinedColumn()) { $subquery = 'SELECT '; } else { $subquery = 'SELECT DISTINCT '; @@ -1403,12 +1422,12 @@ public function getLimitSubquery() $subquery .= $this->_conn->quoteIdentifier($primaryKey); // pgsql & oracle need the order by fields to be preserved in select clause - if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'oci8' || $driverName == 'mssql' || $driverName == 'odbc') { + if ('pgsql' == $driverName || 'oracle' == $driverName || 'oci' == $driverName || 'oci8' == $driverName || 'mssql' == $driverName || 'odbc' == $driverName) { foreach ($this->_sqlParts['orderby'] as $part) { // Remove identifier quoting if it exists $e = $this->_tokenizer->bracketExplode($part, ' '); foreach ($e as $f) { - if ($f == 0 || (int) $f % 2 == 0) { + if (0 == $f || 0 == (int) $f % 2) { $partOriginal = str_replace(',', '', trim($f)); $e = explode('.', $partOriginal); foreach ($e as &$v) { @@ -1416,18 +1435,18 @@ public function getLimitSubquery() } $part = trim(implode('.', $e)); - if (strpos($part, '.') === false) { + if (false === strpos($part, '.')) { continue; } // don't add functions - if (strpos($part, '(') !== false) { + if (false !== strpos($part, '(')) { continue; } // don't add primarykey column (its already in the select clause) if ($part !== $primaryKey) { - $subquery .= ', ' . $partOriginal; + $subquery .= ', '.$partOriginal; } } } @@ -1436,10 +1455,10 @@ public function getLimitSubquery() $orderby = $this->_sqlParts['orderby']; $having = $this->_sqlParts['having']; - if ($driverName == 'mysql' || $driverName == 'pgsql') { + if ('mysql' == $driverName || 'pgsql' == $driverName) { foreach ($this->_expressionMap as $dqlAlias => $expr) { if (isset($expr[1])) { - $subquery .= ', ' . $expr[0] . ' AS ' . $this->_aggregateAliasMap[$dqlAlias]; + $subquery .= ', '.$expr[0].' AS '.$this->_aggregateAliasMap[$dqlAlias]; } } } else { @@ -1461,14 +1480,14 @@ public function getLimitSubquery() // Add having fields that got stripped out of select preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', implode(' ', $having), $matches, PREG_PATTERN_ORDER); if (count($matches[0]) > 0) { - $subquery .= ', ' . implode(', ', array_unique($matches[0])); + $subquery .= ', '.implode(', ', array_unique($matches[0])); } $subquery .= ' FROM'; foreach ($this->_sqlParts['from'] as $part) { // preserve LEFT JOINs only if needed - if (substr($part, 0, 9) === 'LEFT JOIN') { + if ('LEFT JOIN' === substr($part, 0, 9)) { $e = explode(' ', $part); // Fix for http://www.doctrine-project.org/jira/browse/DC-706 // Fix for http://www.doctrine-project.org/jira/browse/DC-594 @@ -1477,26 +1496,26 @@ public function getLimitSubquery() } } - $subquery .= ' ' . $part; + $subquery .= ' '.$part; } // all conditions must be preserved in subquery - $subquery .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' ', $this->_sqlParts['where']) : ''; - $subquery .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : ''; - $subquery .= ( ! empty($having))? ' HAVING ' . implode(' AND ', $having) : ''; - $subquery .= ( ! empty($orderby))? ' ORDER BY ' . implode(', ', $orderby) : ''; + $subquery .= (!empty($this->_sqlParts['where'])) ? ' WHERE '.implode(' ', $this->_sqlParts['where']) : ''; + $subquery .= (!empty($this->_sqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_sqlParts['groupby']) : ''; + $subquery .= (!empty($having)) ? ' HAVING '.implode(' AND ', $having) : ''; + $subquery .= (!empty($orderby)) ? ' ORDER BY '.implode(', ', $orderby) : ''; - if (($driverName == 'oracle' || $driverName == 'oci' || $driverName == 'oci8') && $this->_isOrderedByJoinedColumn()) { + if (('oracle' == $driverName || 'oci' == $driverName || 'oci8' == $driverName) && $this->_isOrderedByJoinedColumn()) { // When using "ORDER BY x.foo" where x.foo is a column of a joined table, // we may get duplicate primary keys because all columns in ORDER BY must appear // in the SELECT list when using DISTINCT. Hence we need to filter out the // primary keys with an additional DISTINCT subquery. // #1038 $quotedIdentifierColumnName = $this->_conn->quoteIdentifier($table->getColumnName($table->getIdentifier())); - $subquery = 'SELECT doctrine_subquery_alias.' . $quotedIdentifierColumnName - . ' FROM (' . $subquery . ') doctrine_subquery_alias' - . ' GROUP BY doctrine_subquery_alias.' . $quotedIdentifierColumnName - . ' ORDER BY MIN(ROWNUM)'; + $subquery = 'SELECT doctrine_subquery_alias.'.$quotedIdentifierColumnName + .' FROM ('.$subquery.') doctrine_subquery_alias' + .' GROUP BY doctrine_subquery_alias.'.$quotedIdentifierColumnName + .' ORDER BY MIN(ROWNUM)'; } // add driver specific limit clause @@ -1505,11 +1524,11 @@ public function getLimitSubquery() $parts = $this->_tokenizer->quoteExplode($subquery, ' ', "'", "'"); foreach ($parts as $k => $part) { - if (strpos($part, ' ') !== false) { + if (false !== strpos($part, ' ')) { continue; } - $part = str_replace(array('"', "'", '`'), "", $part); + $part = str_replace(array('"', "'", '`'), '', $part); // Fix DC-645, Table aliases ending with ')' where not replaced properly preg_match('/^(\(?)(.*?)(\)?)$/', $part, $matches); @@ -1518,11 +1537,11 @@ public function getLimitSubquery() continue; } - if (strpos($part, '.') === false) { + if (false === strpos($part, '.')) { continue; } - preg_match_all("/[a-zA-Z0-9_]+\.[a-z0-9_]+/i", $part, $m); + preg_match_all('/[a-zA-Z0-9_]+\\.[a-z0-9_]+/i', $part, $m); foreach ($m[0] as $match) { $e = explode('.', $match); @@ -1530,7 +1549,7 @@ public function getLimitSubquery() // Rebuild the original part without the newly generate alias and with quoting reapplied $e2 = array(); foreach ($e as $k2 => $v2) { - $e2[$k2] = $this->_conn->quoteIdentifier($v2); + $e2[$k2] = $this->_conn->quoteIdentifier($v2); } $match = implode('.', $e2); @@ -1539,26 +1558,26 @@ public function getLimitSubquery() // Requote the part with the newly generated alias foreach ($e as $k2 => $v2) { - $e[$k2] = $this->_conn->quoteIdentifier($v2); + $e[$k2] = $this->_conn->quoteIdentifier($v2); } - $replace = implode('.' , $e); + $replace = implode('.', $e); // Replace the original part with the new part with new sql table alias $parts[$k] = str_replace($match, $replace, $parts[$k]); } } - if ($driverName == 'mysql' || $driverName == 'pgsql') { + if ('mysql' == $driverName || 'pgsql' == $driverName) { foreach ($parts as $k => $part) { - if (strpos($part, "'") !== false) { + if (false !== strpos($part, "'")) { continue; } - if (strpos($part, '__') == false) { + if (false == strpos($part, '__')) { continue; } - preg_match_all("/[a-zA-Z0-9_]+\_\_[a-z0-9_]+/i", $part, $m); + preg_match_all('/[a-zA-Z0-9_]+\\_\\_[a-z0-9_]+/i', $part, $m); foreach ($m[0] as $match) { $e = explode('__', $match); @@ -1570,6 +1589,7 @@ public function getLimitSubquery() } $subquery = implode(' ', $parts); + return $subquery; } @@ -1578,12 +1598,12 @@ public function getLimitSubquery() * This information is needed in special scenarios like the limit-offset when its * used with an Oracle database. * - * @return boolean TRUE if the query is ordered by a joined column, FALSE otherwise. + * @return bool TRUE if the query is ordered by a joined column, FALSE otherwise */ - private function _isOrderedByJoinedColumn() { - if ( ! $this->_queryComponents) { - throw new Doctrine_Query_Exception("The query is in an invalid state for this " - . "operation. It must have been fully parsed first."); + private function _isOrderedByJoinedColumn() + { + if (!$this->_queryComponents) { + throw new Doctrine_Query_Exception('The query is in an invalid state for this operation. It must have been fully parsed first.'); } $componentAlias = key($this->_queryComponents); $mainTableAlias = $this->getSqlTableAlias($componentAlias); @@ -1591,7 +1611,7 @@ private function _isOrderedByJoinedColumn() { $part = trim($part); $e = $this->_tokenizer->bracketExplode($part, ' '); $part = trim($e[0]); - if (strpos($part, '.') === false) { + if (false === strpos($part, '.')) { continue; } list($tableAlias, $columnName) = explode('.', $part); @@ -1599,6 +1619,7 @@ private function _isOrderedByJoinedColumn() { return true; } } + return false; } @@ -1606,12 +1627,14 @@ private function _isOrderedByJoinedColumn() { * DQL PARSER * parses a DQL query * first splits the query in parts and then uses individual - * parsers for each part + * parsers for each part. + * + * @param string $query DQL query + * @param bool $clear whether or not to clear the aliases * - * @param string $query DQL query - * @param boolean $clear whether or not to clear the aliases - * @throws Doctrine_Query_Exception if some generic parsing error occurs * @return Doctrine_Query + * + * @throws Doctrine_Query_Exception if some generic parsing error occurs */ public function parseDqlQuery($query, $clear = true) { @@ -1631,35 +1654,37 @@ public function parseDqlQuery($query, $clear = true) switch ($partName) { case 'create': $this->_type = self::CREATE; - break; + break; case 'insert': $this->_type = self::INSERT; - break; + break; case 'delete': $this->_type = self::DELETE; - break; + break; case 'select': $this->_type = self::SELECT; $this->_addDqlQueryPart($partName, $subParts); - break; + break; case 'update': $this->_type = self::UPDATE; $partName = 'from'; + // no break case 'from': $this->_addDqlQueryPart($partName, $subParts); - break; + break; case 'set': $this->_addDqlQueryPart($partName, $subParts, true); - break; + break; case 'group': case 'order': $partName .= 'by'; + // no break case 'where': case 'having': case 'limit': case 'offset': $this->_addDqlQueryPart($partName, $subParts); - break; + break; } } @@ -1668,8 +1693,9 @@ public function parseDqlQuery($query, $clear = true) /** * @todo Describe & refactor... too long and nested. - * @param string $path component alias - * @param boolean $loadFields + * + * @param string $path component alias + * @param bool $loadFields */ public function load($path, $loadFields = true) { @@ -1707,10 +1733,10 @@ public function load($path, $loadFields = true) $overrideJoin = false; } - $tmp = explode(' ', $path); + $tmp = explode(' ', $path); $componentAlias = $originalAlias = (count($tmp) > 1) ? end($tmp) : null; - $e = preg_split("/[.:]/", $tmp[0], -1); + $e = preg_split('/[.:]/', $tmp[0], -1); $fullPath = $tmp[0]; $prevPath = ''; @@ -1728,7 +1754,7 @@ public function load($path, $loadFields = true) $length = strlen($prevPath); // build the current component path - $prevPath = ($prevPath) ? $prevPath . '.' . $name : $name; + $prevPath = ($prevPath) ? $prevPath.'.'.$name : $name; $delimeter = substr($fullPath, $length, 1); @@ -1741,39 +1767,39 @@ public function load($path, $loadFields = true) // if the current alias already exists, skip it if (isset($this->_queryComponents[$componentAlias])) { - throw new Doctrine_Query_Exception("Duplicate alias '$componentAlias' in query."); + throw new Doctrine_Query_Exception("Duplicate alias '{$componentAlias}' in query."); } - if ( ! isset($table)) { + if (!isset($table)) { // process the root of the path $table = $this->loadRoot($name, $componentAlias); } else { - $join = ($delimeter == ':') ? 'INNER JOIN ' : 'LEFT JOIN '; + $join = (':' == $delimeter) ? 'INNER JOIN ' : 'LEFT JOIN '; $relation = $table->getRelation($name); $localTable = $table; $table = $relation->getTable(); $this->_queryComponents[$componentAlias] = array('table' => $table, - 'parent' => $parent, - 'relation' => $relation, - 'map' => null); + 'parent' => $parent, + 'relation' => $relation, + 'map' => null); // Fix for http://www.doctrine-project.org/jira/browse/DC-701 - if ( ! $relation->isOneToOne() && ! $this->disableLimitSubquery) { + if (!$relation->isOneToOne() && !$this->disableLimitSubquery) { $this->_needsSubquery = true; } - $localAlias = $this->getSqlTableAlias($parent, $localTable->getTableName()); + $localAlias = $this->getSqlTableAlias($parent, $localTable->getTableName()); $foreignAlias = $this->getSqlTableAlias($componentAlias, $relation->getTable()->getTableName()); - $foreignSql = $this->_conn->quoteIdentifier($relation->getTable()->getTableName()) - . ' ' - . $this->_conn->quoteIdentifier($foreignAlias); + $foreignSql = $this->_conn->quoteIdentifier($relation->getTable()->getTableName()) + .' ' + .$this->_conn->quoteIdentifier($foreignAlias); $map = $relation->getTable()->inheritanceMap; - if ( ! $loadFields || ! empty($map) || $joinCondition) { + if (!$loadFields || !empty($map) || $joinCondition) { $this->_subqueryAliases[] = $foreignAlias; } @@ -1782,11 +1808,11 @@ public function load($path, $loadFields = true) $assocTableName = $asf->getTableName(); - if ( ! $loadFields || ! empty($map) || $joinCondition) { + if (!$loadFields || !empty($map) || $joinCondition) { $this->_subqueryAliases[] = $assocTableName; } - $assocPath = $prevPath . '.' . $asf->getComponentName() . ' ' . $componentAlias; + $assocPath = $prevPath.'.'.$asf->getComponentName().' '.$componentAlias; $this->_queryComponents[$assocPath] = array( 'parent' => $prevPath, @@ -1797,33 +1823,33 @@ public function load($path, $loadFields = true) $assocAlias = $this->getSqlTableAlias($assocPath, $asf->getTableName()); $queryPart = $join - . $this->_conn->quoteIdentifier($assocTableName) - . ' ' - . $this->_conn->quoteIdentifier($assocAlias); + .$this->_conn->quoteIdentifier($assocTableName) + .' ' + .$this->_conn->quoteIdentifier($assocAlias); - $queryPart .= ' ON (' . $this->_conn->quoteIdentifier($localAlias - . '.' - . $localTable->getColumnName($localTable->getIdentifier())) // what about composite keys? - . ' = ' - . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getLocalRefColumnName()); + $queryPart .= ' ON ('.$this->_conn->quoteIdentifier($localAlias + .'.' + .$localTable->getColumnName($localTable->getIdentifier())) // what about composite keys? + .' = ' + .$this->_conn->quoteIdentifier($assocAlias.'.'.$relation->getLocalRefColumnName()); if ($relation->isEqual()) { // equal nest relation needs additional condition $queryPart .= ' OR ' - . $this->_conn->quoteIdentifier($localAlias - . '.' - . $table->getColumnName($table->getIdentifier())) - . ' = ' - . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getForeignRefColumnName()); + .$this->_conn->quoteIdentifier($localAlias + .'.' + .$table->getColumnName($table->getIdentifier())) + .' = ' + .$this->_conn->quoteIdentifier($assocAlias.'.'.$relation->getForeignRefColumnName()); } $queryPart .= ')'; $this->_sqlParts['from'][] = $queryPart; - $queryPart = $join . $foreignSql; + $queryPart = $join.$foreignSql; - if ( ! $overrideJoin) { + if (!$overrideJoin) { $queryPart .= $this->buildAssociativeRelationSql($relation, $assocAlias, $foreignAlias, $localAlias); } } else { @@ -1833,7 +1859,7 @@ public function load($path, $loadFields = true) $queryPart .= $this->buildInheritanceJoinSql($table->getComponentName(), $componentAlias); $this->_sqlParts['from'][$componentAlias] = $queryPart; - if ( ! empty($joinCondition)) { + if (!empty($joinCondition)) { $this->addPendingJoinCondition($componentAlias, $joinCondition); } } @@ -1857,15 +1883,15 @@ public function load($path, $loadFields = true) protected function buildSimpleRelationSql(Doctrine_Relation $relation, $foreignAlias, $localAlias, $overrideJoin, $join) { - $queryPart = $join . $this->_conn->quoteIdentifier($relation->getTable()->getTableName()) - . ' ' - . $this->_conn->quoteIdentifier($foreignAlias); + $queryPart = $join.$this->_conn->quoteIdentifier($relation->getTable()->getTableName()) + .' ' + .$this->_conn->quoteIdentifier($foreignAlias); - if ( ! $overrideJoin) { + if (!$overrideJoin) { $queryPart .= ' ON ' - . $this->_conn->quoteIdentifier($localAlias . '.' . $relation->getLocalColumnName()) - . ' = ' - . $this->_conn->quoteIdentifier($foreignAlias . '.' . $relation->getForeignColumnName()); + .$this->_conn->quoteIdentifier($localAlias.'.'.$relation->getLocalColumnName()) + .' = ' + .$this->_conn->quoteIdentifier($foreignAlias.'.'.$relation->getForeignColumnName()); } return $queryPart; @@ -1881,19 +1907,19 @@ protected function buildIndexBy($componentAlias, $mapWith = null) if (isset($mapWith)) { $terms = explode('.', $mapWith); - if (count($terms) == 1) { + if (1 == count($terms)) { $indexBy = $terms[0]; - } else if (count($terms) == 2) { + } elseif (2 == count($terms)) { $column = true; $indexBy = $terms[1]; } - } else if ($table->getBoundQueryPart('indexBy') !== null) { + } elseif (null !== $table->getBoundQueryPart('indexBy')) { $indexBy = $table->getBoundQueryPart('indexBy'); } - if ($indexBy !== null) { - if ( $column && ! $table->hasColumn($table->getColumnName($indexBy))) { - throw new Doctrine_Query_Exception("Couldn't use key mapping. Column " . $indexBy . " does not exist."); + if (null !== $indexBy) { + if ($column && !$table->hasColumn($table->getColumnName($indexBy))) { + throw new Doctrine_Query_Exception("Couldn't use key mapping. Column ".$indexBy.' does not exist.'); } $this->_queryComponents[$componentAlias]['map'] = $indexBy; @@ -1902,7 +1928,6 @@ protected function buildIndexBy($componentAlias, $mapWith = null) return $this->_queryComponents[$componentAlias]; } - protected function buildAssociativeRelationSql(Doctrine_Relation $relation, $assocAlias, $foreignAlias, $localAlias) { $table = $relation->getTable(); @@ -1915,30 +1940,32 @@ protected function buildAssociativeRelationSql(Doctrine_Relation $relation, $ass $localIdentifier = $table->getColumnName($table->getIdentifier()); - $queryPart .= $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier) - . ' = ' - . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getForeignRefColumnName()); + $queryPart .= $this->_conn->quoteIdentifier($foreignAlias.'.'.$localIdentifier) + .' = ' + .$this->_conn->quoteIdentifier($assocAlias.'.'.$relation->getForeignRefColumnName()); if ($relation->isEqual()) { $queryPart .= ' OR ' - . $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier) - . ' = ' - . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getLocalRefColumnName()) - . ') AND ' - . $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier) - . ' != ' - . $this->_conn->quoteIdentifier($localAlias . '.' . $localIdentifier); + .$this->_conn->quoteIdentifier($foreignAlias.'.'.$localIdentifier) + .' = ' + .$this->_conn->quoteIdentifier($assocAlias.'.'.$relation->getLocalRefColumnName()) + .') AND ' + .$this->_conn->quoteIdentifier($foreignAlias.'.'.$localIdentifier) + .' != ' + .$this->_conn->quoteIdentifier($localAlias.'.'.$localIdentifier); } return $queryPart; } /** - * loadRoot + * loadRoot. * * @param string $name * @param string $componentAlias + * * @return Doctrine_Table + * * @todo DESCRIBE ME! * @todo this method is called only in Doctrine_Query class. Shouldn't be private or protected? */ @@ -1946,7 +1973,7 @@ public function loadRoot($name, $componentAlias) { // get the connection for the component $manager = Doctrine_Manager::getInstance(); - if ( ! $this->_passedConn && $manager->hasConnectionForComponent($name)) { + if (!$this->_passedConn && $manager->hasConnectionForComponent($name)) { $this->_conn = $manager->getConnectionForComponent($name); } @@ -1958,8 +1985,8 @@ public function loadRoot($name, $componentAlias) // quote table name $queryPart = $this->_conn->quoteIdentifier($tableName); - if ($this->_type === self::SELECT) { - $queryPart .= ' ' . $this->_conn->quoteIdentifier($tableAlias); + if (self::SELECT === $this->_type) { + $queryPart .= ' '.$this->_conn->quoteIdentifier($tableAlias); } $this->_tableAliasMap[$tableAlias] = $componentAlias; @@ -1975,15 +2002,17 @@ public function loadRoot($name, $componentAlias) /** * @todo DESCRIBE ME! - * @param string $name component class name - * @param string $componentAlias alias of the component in the dql - * @return string query part + * + * @param string $name component class name + * @param string $componentAlias alias of the component in the dql + * + * @return string query part */ public function buildInheritanceJoinSql($name, $componentAlias) { // get the connection for the component $manager = Doctrine_Manager::getInstance(); - if ( ! $this->_passedConn && $manager->hasConnectionForComponent($name)) { + if (!$this->_passedConn && $manager->hasConnectionForComponent($name)) { $this->_conn = $manager->getConnectionForComponent($name); } @@ -1998,22 +2027,22 @@ public function buildInheritanceJoinSql($name, $componentAlias) foreach ($table->getOption('joinedParents') as $parent) { $parentTable = $this->_conn->getTable($parent); - $parentAlias = $componentAlias . '.' . $parent; + $parentAlias = $componentAlias.'.'.$parent; // get the short alias for the parent table $parentTableAlias = $this->getSqlTableAlias($parentAlias, $parentTable->getTableName()); - $queryPart .= ' LEFT JOIN ' . $this->_conn->quoteIdentifier($parentTable->getTableName()) - . ' ' . $this->_conn->quoteIdentifier($parentTableAlias) . ' ON '; + $queryPart .= ' LEFT JOIN '.$this->_conn->quoteIdentifier($parentTable->getTableName()) + .' '.$this->_conn->quoteIdentifier($parentTableAlias).' ON '; - //Doctrine_Core::dump($table->getIdentifier()); + // Doctrine_Core::dump($table->getIdentifier()); foreach ((array) $table->getIdentifier() as $identifier) { $column = $table->getColumnName($identifier); $queryPart .= $this->_conn->quoteIdentifier($tableAlias) - . '.' . $this->_conn->quoteIdentifier($column) - . ' = ' . $this->_conn->quoteIdentifier($parentTableAlias) - . '.' . $this->_conn->quoteIdentifier($column); + .'.'.$this->_conn->quoteIdentifier($column) + .' = '.$this->_conn->quoteIdentifier($parentTableAlias) + .'.'.$this->_conn->quoteIdentifier($column); } } @@ -2034,31 +2063,31 @@ public function getCountSqlQuery() $this->getSqlQuery(array(), false); // this is ugly // initialize temporary variables - $where = $this->_sqlParts['where']; - $having = $this->_sqlParts['having']; + $where = $this->_sqlParts['where']; + $having = $this->_sqlParts['having']; $groupby = $this->_sqlParts['groupby']; $rootAlias = $this->getRootAlias(); $tableAlias = $this->getSqlTableAlias($rootAlias); // Build the query base - $q = 'SELECT COUNT(*) AS ' . $this->_conn->quoteIdentifier('num_results') . ' FROM '; + $q = 'SELECT COUNT(*) AS '.$this->_conn->quoteIdentifier('num_results').' FROM '; // Build the from clause $from = $this->_buildSqlFromPart(true); // Build the where clause - $where = ( ! empty($where)) ? ' WHERE ' . implode(' ', $where) : ''; + $where = (!empty($where)) ? ' WHERE '.implode(' ', $where) : ''; // Build the group by clause - $groupby = ( ! empty($groupby)) ? ' GROUP BY ' . implode(', ', $groupby) : ''; + $groupby = (!empty($groupby)) ? ' GROUP BY '.implode(', ', $groupby) : ''; // Build the having clause - $having = ( ! empty($having)) ? ' HAVING ' . implode(' AND ', $having) : ''; + $having = (!empty($having)) ? ' HAVING '.implode(' AND ', $having) : ''; // Building the from clause and finishing query - if (count($this->_queryComponents) == 1 && empty($having)) { - $q .= $from . $where . $groupby . $having; + if (1 == count($this->_queryComponents) && empty($having)) { + $q .= $from.$where.$groupby.$having; } else { // Subselect fields will contain only the pk of root entity $ta = $this->_conn->quoteIdentifier($tableAlias); @@ -2066,34 +2095,34 @@ public function getCountSqlQuery() $map = $this->getRootDeclaration(); $idColumnNames = $map['table']->getIdentifierColumnNames(); - $pkFields = $ta . '.' . implode(', ' . $ta . '.', $this->_conn->quoteMultipleIdentifier($idColumnNames)); + $pkFields = $ta.'.'.implode(', '.$ta.'.', $this->_conn->quoteMultipleIdentifier($idColumnNames)); // We need to do some magic in select fields if the query contain anything in having clause $selectFields = $pkFields; - if ( ! empty($having)) { + if (!empty($having)) { // For each field defined in select clause foreach ($this->_sqlParts['select'] as $field) { // We only include aggregate expressions to count query // This is needed because HAVING clause will use field aliases - if (strpos($field, '(') !== false) { - $selectFields .= ', ' . $field; + if (false !== strpos($field, '(')) { + $selectFields .= ', '.$field; } } // Add having fields that got stripped out of select preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', $having, $matches, PREG_PATTERN_ORDER); if (count($matches[0]) > 0) { - $selectFields .= ', ' . implode(', ', array_unique($matches[0])); + $selectFields .= ', '.implode(', ', array_unique($matches[0])); } } // If we do not have a custom group by, apply the default one if (empty($groupby)) { - $groupby = ' GROUP BY ' . $pkFields; + $groupby = ' GROUP BY '.$pkFields; } - $q .= '(SELECT ' . $selectFields . ' FROM ' . $from . $where . $groupby . $having . ') ' - . $this->_conn->quoteIdentifier('dctrn_count_query'); + $q .= '(SELECT '.$selectFields.' FROM '.$from.$where.$groupby.$having.') ' + .$this->_conn->quoteIdentifier('dctrn_count_query'); } return $q; @@ -2116,10 +2145,11 @@ public function getCountSqlQuery() * LEFT JOIN u.Phonenumber p * WHERE p.phonenumber = '123 123' * - * @param array $params an array of prepared statement parameters - * @return integer the count of this query + * @param array $params an array of prepared statement parameters + * + * @return int the count of this query */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count($params = array()) { $q = $this->getCountSqlQuery(); @@ -2132,7 +2162,7 @@ public function count($params = array()) $hash = $this->getResultCacheHash($params).'_count'; $cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash); - if ($cached === false) { + if (false === $cached) { // cache miss $results = $this->getConnection()->fetchAll($q, $params); $cacheDriver->save($hash, serialize($results), $this->getResultCacheLifeSpan()); @@ -2162,38 +2192,35 @@ public function count($params = array()) * * This methods parses a Dql query and builds the query parts. * - * @param string $query Dql query - * @param array $params prepared statement parameters - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string $query Dql query + * @param array $params prepared statement parameters + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @see Doctrine_Core::FETCH_* constants - * @return mixed */ public function query($query, $params = array(), $hydrationMode = null) { $this->parseDqlQuery($query); + return $this->execute($params, $hydrationMode); } /** * Copies a Doctrine_Query object. * - * @return Doctrine_Query Copy of the Doctrine_Query instance. + * @return Doctrine_Query copy of the Doctrine_Query instance */ public function copy(Doctrine_Query $query = null) { - if ( ! $query) { + if (!$query) { $query = $this; } - $new = clone $query; - - return $new; + return clone $query; } /** * Magic method called after cloning process. - * - * @return void */ public function __clone() { @@ -2213,15 +2240,15 @@ public function __clone() /** * Kill the reference for the passed class property. * This method simply copies the value to a temporary variable and then unsets - * the reference and re-assigns the old value but not by reference + * the reference and re-assigns the old value but not by reference. * * @param string $key */ protected function _killReference($key) { - $tmp = $this->$key; - unset($this->$key); - $this->$key = $tmp; + $tmp = $this->{$key}; + unset($this->{$key}); + $this->{$key} = $tmp; } /** @@ -2231,7 +2258,7 @@ protected function _killReference($key) * This method can therefore be used to reduce memory usage when creating * a lot of query objects during a request. * - * @return Doctrine_Query this object + * @return Doctrine_Query this object */ public function free() { diff --git a/lib/Doctrine/Query/Abstract.php b/lib/Doctrine/Query/Abstract.php index 247886f1c..b8c8f2950 100644 --- a/lib/Doctrine/Query/Abstract.php +++ b/lib/Doctrine/Query/Abstract.php @@ -20,131 +20,133 @@ */ /** - * Doctrine_Query_Abstract + * Doctrine_Query_Abstract. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1393 $ + * * @author Konsta Vesterinen + * * @todo See {@link Doctrine_Query} */ abstract class Doctrine_Query_Abstract { /** - * QUERY TYPE CONSTANTS + * QUERY TYPE CONSTANTS. */ /** - * constant for SELECT queries + * constant for SELECT queries. */ - const SELECT = 0; + public const SELECT = 0; /** - * constant for DELETE queries + * constant for DELETE queries. */ - const DELETE = 1; + public const DELETE = 1; /** - * constant for UPDATE queries + * constant for UPDATE queries. */ - const UPDATE = 2; + public const UPDATE = 2; /** - * constant for INSERT queries + * constant for INSERT queries. */ - const INSERT = 3; + public const INSERT = 3; /** - * constant for CREATE queries + * constant for CREATE queries. */ - const CREATE = 4; + public const CREATE = 4; /** @todo document the query states (and the transitions between them). */ /** * A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts. */ - const STATE_CLEAN = 1; + public const STATE_CLEAN = 1; /** * A query object is in state DIRTY when it has DQL parts that have not yet been * parsed/processed. */ - const STATE_DIRTY = 2; + public const STATE_DIRTY = 2; /** * A query is in DIRECT state when ... ? */ - const STATE_DIRECT = 3; + public const STATE_DIRECT = 3; /** * A query object is on LOCKED state when ... ? */ - const STATE_LOCKED = 4; + public const STATE_LOCKED = 4; /** - * @var array Table alias map. Keys are SQL aliases and values DQL aliases. + * @var array Table alias map. Keys are SQL aliases and values DQL aliases. */ protected $_tableAliasMap = array(); /** - * @var Doctrine_View The view object used by this query, if any. + * @var Doctrine_View the view object used by this query, if any */ protected $_view; /** - * @var integer $_state The current state of this query. + * @var int the current state of this query */ protected $_state = self::STATE_CLEAN; /** - * @var array $_params The parameters of this query. + * @var array the parameters of this query */ protected $_params = array('exec' => array(), - 'join' => array(), - 'where' => array(), - 'set' => array(), - 'having' => array()); + 'join' => array(), + 'where' => array(), + 'set' => array(), + 'having' => array()); /** - * @var array $_execParams The parameters passed to connection statement + * @var array The parameters passed to connection statement */ protected $_execParams = array(); /* Caching properties */ /** - * @var Doctrine_Cache_Interface The cache driver used for caching result sets. + * @var Doctrine_Cache_Interface the cache driver used for caching result sets */ protected $_resultCache; /** - * @var string Key to use for result cache entry in the cache driver + * @var string Key to use for result cache entry in the cache driver */ protected $_resultCacheHash; /** - * @var boolean $_expireResultCache A boolean value that indicates whether or not - * expire the result cache. + * @var bool a boolean value that indicates whether or not + * expire the result cache */ protected $_expireResultCache = false; protected $_resultCacheTTL; /** - * @var Doctrine_Cache_Interface The cache driver used for caching queries. + * @var Doctrine_Cache_Interface the cache driver used for caching queries */ protected $_queryCache; protected $_expireQueryCache = false; protected $_queryCacheTTL; /** - * @var boolean $_autoFree A boolean value that indicates whether or not use auto free. + * @var bool a boolean value that indicates whether or not use auto free */ protected $_autoFree = false; /** - * @var Doctrine_Connection The connection used by this query object. + * @var Doctrine_Connection the connection used by this query object */ protected $_conn; @@ -154,45 +156,44 @@ abstract class Doctrine_Query_Abstract protected $_passedConn = false; /** - * @var array $_sqlParts The SQL query string parts. Filled during the DQL parsing process. + * @var array The SQL query string parts. Filled during the DQL parsing process. */ protected $_sqlParts = array( - 'select' => array(), - 'distinct' => false, - 'forUpdate' => false, - 'from' => array(), - 'set' => array(), - 'join' => array(), - 'where' => array(), - 'groupby' => array(), - 'having' => array(), - 'orderby' => array(), - 'limit' => false, - 'offset' => false, - ); + 'select' => array(), + 'distinct' => false, + 'forUpdate' => false, + 'from' => array(), + 'set' => array(), + 'join' => array(), + 'where' => array(), + 'groupby' => array(), + 'having' => array(), + 'orderby' => array(), + 'limit' => false, + 'offset' => false, + ); /** - * @var array $_dqlParts an array containing all DQL query parts; @see Doctrine_Query::getDqlPart() + * @var array an array containing all DQL query parts; @see Doctrine_Query::getDqlPart() */ protected $_dqlParts = array( - 'from' => array(), - 'select' => array(), - 'forUpdate' => false, - 'set' => array(), - 'join' => array(), - 'where' => array(), - 'groupby' => array(), - 'having' => array(), - 'orderby' => array(), - 'limit' => array(), - 'offset' => array(), - ); - + 'from' => array(), + 'select' => array(), + 'forUpdate' => false, + 'set' => array(), + 'join' => array(), + 'where' => array(), + 'groupby' => array(), + 'having' => array(), + 'orderby' => array(), + 'limit' => array(), + 'offset' => array(), + ); /** - * @var array $_queryComponents Two dimensional array containing the components of this query, - * informations about their relations and other related information. - * The components are constructed during query parsing. + * @var array Two dimensional array containing the components of this query, + * informations about their relations and other related information. + * The components are constructed during query parsing. * * Keys are component aliases and values the following: * @@ -219,51 +220,51 @@ abstract class Doctrine_Query_Abstract */ protected $_queryComponents = array(); - /** - * Stores the root DQL alias + /** + * Stores the root DQL alias. * * @var string */ protected $_rootAlias = ''; /** - * @var integer $type the query type + * @var int the query type * * @see Doctrine_Query::* constants */ protected $_type = self::SELECT; /** - * @var Doctrine_Hydrator The hydrator object used to hydrate query results. + * @var Doctrine_Hydrator the hydrator object used to hydrate query results */ protected $_hydrator; /** - * @var Doctrine_Query_Tokenizer The tokenizer that is used during the query parsing process. + * @var Doctrine_Query_Tokenizer the tokenizer that is used during the query parsing process */ protected $_tokenizer; /** - * @var Doctrine_Query_Parser The parser that is used for query parsing. + * @var Doctrine_Query_Parser the parser that is used for query parsing */ protected $_parser; /** - * @var array $_tableAliasSeeds A simple array keys representing table aliases and values - * table alias seeds. The seeds are used for generating short table - * aliases. + * @var array A simple array keys representing table aliases and values + * table alias seeds. The seeds are used for generating short table + * aliases. */ protected $_tableAliasSeeds = array(); /** - * @var array $_options an array of options + * @var array an array of options */ - protected $_options = array( - 'hydrationMode' => Doctrine_Core::HYDRATE_RECORD + protected $_options = array( + 'hydrationMode' => Doctrine_Core::HYDRATE_RECORD, ); /** - * @var boolean + * @var bool */ protected $_isLimitSubqueryUsed = false; @@ -278,34 +279,34 @@ abstract class Doctrine_Query_Abstract protected $_preQueried = false; /** - * @var array $_pendingJoinConditions an array containing pending joins + * @var array an array containing pending joins */ protected $_pendingJoinConditions = array(); /** - * Fix for http://www.doctrine-project.org/jira/browse/DC-701 + * Fix for http://www.doctrine-project.org/jira/browse/DC-701. * - * @var bool Boolean variable for whether the limitSubquery method of accessing tables via a many relationship should be used. + * @var bool boolean variable for whether the limitSubquery method of accessing tables via a many relationship should be used */ protected $disableLimitSubquery = false; /** * Constructor. * - * @param Doctrine_Connection $connection The connection object the query will use. - * @param Doctrine_Hydrator_Abstract $hydrator The hydrator that will be used for generating result sets. + * @param Doctrine_Connection $connection the connection object the query will use + * @param Doctrine_Hydrator_Abstract $hydrator the hydrator that will be used for generating result sets * * @throws Doctrine_Connection_Exception */ public function __construct(Doctrine_Connection $connection = null, - Doctrine_Hydrator_Abstract $hydrator = null) + Doctrine_Hydrator_Abstract $hydrator = null) { - if ($connection === null) { + if (null === $connection) { $connection = Doctrine_Manager::getInstance()->getCurrentConnection(); } else { $this->_passedConn = true; } - if ($hydrator === null) { + if (null === $hydrator) { $hydrator = new Doctrine_Hydrator(); } $this->_conn = $connection; @@ -317,10 +318,7 @@ public function __construct(Doctrine_Connection $connection = null, } /** - * Set the connection this query object should use - * - * @param Doctrine_Connection $connection - * @return void + * Set the connection this query object should use. */ public function setConnection(Doctrine_Connection $connection) { @@ -329,7 +327,7 @@ public function setConnection(Doctrine_Connection $connection) } /** - * setOption + * setOption. * * @param string $name option name * @param string $value option value @@ -338,45 +336,45 @@ public function setConnection(Doctrine_Connection $connection) */ public function setOption($name, $value) { - if ( ! isset($this->_options[$name])) { - throw new Doctrine_Query_Exception('Unknown option ' . $name); + if (!isset($this->_options[$name])) { + throw new Doctrine_Query_Exception('Unknown option '.$name); } $this->_options[$name] = $value; } /** * setAutoFree - * Sets auto free + * Sets auto free. * - * @param boolean $value True or false (true by default) + * @param bool $value True or false (true by default) * * @return $this */ public function setAutoFree($value = true) { - $this->_autoFree = (boolean) $value; + $this->_autoFree = (bool) $value; return $this; } /** * hasSqlTableAlias - * whether or not this object has given tableAlias + * whether or not this object has given tableAlias. * * @param string $sqlTableAlias the table alias to be checked * - * @return boolean true if this object has given alias, otherwise false + * @return bool true if this object has given alias, otherwise false */ public function hasSqlTableAlias($sqlTableAlias) { - return (isset($this->_tableAliasMap[$sqlTableAlias])); + return isset($this->_tableAliasMap[$sqlTableAlias]); } /** * getTableAliasMap - * returns all table aliases + * returns all table aliases. * - * @return array table aliases as an array + * @return array table aliases as an array */ public function getTableAliasMap() { @@ -389,66 +387,67 @@ public function getTableAliasMap() * * the query is built from $_dqlParts * - * @return string the DQL query + * @return string the DQL query */ public function getDql() { $q = ''; - if ($this->_type == self::SELECT) { - $q .= ( ! empty($this->_dqlParts['select'])) ? 'SELECT ' . implode(', ', $this->_dqlParts['select']) : ''; - $q .= ( ! empty($this->_dqlParts['from'])) ? ' FROM ' . implode(' ', $this->_dqlParts['from']) : ''; - } else if ($this->_type == self::DELETE) { + if (self::SELECT == $this->_type) { + $q .= (!empty($this->_dqlParts['select'])) ? 'SELECT '.implode(', ', $this->_dqlParts['select']) : ''; + $q .= (!empty($this->_dqlParts['from'])) ? ' FROM '.implode(' ', $this->_dqlParts['from']) : ''; + } elseif (self::DELETE == $this->_type) { $q .= 'DELETE'; - $q .= ( ! empty($this->_dqlParts['from'])) ? ' FROM ' . implode(' ', $this->_dqlParts['from']) : ''; - } else if ($this->_type == self::UPDATE) { + $q .= (!empty($this->_dqlParts['from'])) ? ' FROM '.implode(' ', $this->_dqlParts['from']) : ''; + } elseif (self::UPDATE == $this->_type) { $q .= 'UPDATE '; - $q .= ( ! empty($this->_dqlParts['from'])) ? implode(' ', $this->_dqlParts['from']) : ''; - $q .= ( ! empty($this->_dqlParts['set'])) ? ' SET ' . implode(' ', $this->_dqlParts['set']) : ''; + $q .= (!empty($this->_dqlParts['from'])) ? implode(' ', $this->_dqlParts['from']) : ''; + $q .= (!empty($this->_dqlParts['set'])) ? ' SET '.implode(' ', $this->_dqlParts['set']) : ''; } - $q .= ( ! empty($this->_dqlParts['where'])) ? ' WHERE ' . implode(' ', $this->_dqlParts['where']) : ''; - $q .= ( ! empty($this->_dqlParts['groupby'])) ? ' GROUP BY ' . implode(', ', $this->_dqlParts['groupby']) : ''; - $q .= ( ! empty($this->_dqlParts['having'])) ? ' HAVING ' . implode(' AND ', $this->_dqlParts['having']) : ''; - $q .= ( ! empty($this->_dqlParts['orderby'])) ? ' ORDER BY ' . implode(', ', $this->_dqlParts['orderby']) : ''; - $q .= ( ! empty($this->_dqlParts['limit'])) ? ' LIMIT ' . implode(' ', $this->_dqlParts['limit']) : ''; - $q .= ( ! empty($this->_dqlParts['offset'])) ? ' OFFSET ' . implode(' ', $this->_dqlParts['offset']) : ''; + $q .= (!empty($this->_dqlParts['where'])) ? ' WHERE '.implode(' ', $this->_dqlParts['where']) : ''; + $q .= (!empty($this->_dqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_dqlParts['groupby']) : ''; + $q .= (!empty($this->_dqlParts['having'])) ? ' HAVING '.implode(' AND ', $this->_dqlParts['having']) : ''; + $q .= (!empty($this->_dqlParts['orderby'])) ? ' ORDER BY '.implode(', ', $this->_dqlParts['orderby']) : ''; + $q .= (!empty($this->_dqlParts['limit'])) ? ' LIMIT '.implode(' ', $this->_dqlParts['limit']) : ''; + $q .= (!empty($this->_dqlParts['offset'])) ? ' OFFSET '.implode(' ', $this->_dqlParts['offset']) : ''; return $q; } /** * getSqlQueryPart - * gets an SQL query part from the SQL query part array + * gets an SQL query part from the SQL query part array. * * @param string $part the name of the query part to get * - * @return mixed * @throws Doctrine_Query_Exception if trying to get an unknown query part */ public function getSqlQueryPart($part) { - if ( ! isset($this->_sqlParts[$part])) { - throw new Doctrine_Query_Exception('Unknown SQL query part ' . $part); + if (!isset($this->_sqlParts[$part])) { + throw new Doctrine_Query_Exception('Unknown SQL query part '.$part); } + return $this->_sqlParts[$part]; } /** * setSqlQueryPart - * sets an SQL query part in the SQL query part array + * sets an SQL query part in the SQL query part array. * * @param string $name the name of the query part to be set * @param string $part query part string * * @return $this this object + * * @throws Doctrine_Query_Exception if trying to set unknown query part */ public function setSqlQueryPart($name, $part) { - if ( ! isset($this->_sqlParts[$name])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $name); + if (!isset($this->_sqlParts[$name])) { + throw new Doctrine_Query_Exception('Unknown query part '.$name); } - if ($name !== 'limit' && $name !== 'offset') { + if ('limit' !== $name && 'offset' !== $name) { if (is_array($part)) { $this->_sqlParts[$name] = $part; } else { @@ -463,43 +462,46 @@ public function setSqlQueryPart($name, $part) /** * addSqlQueryPart - * adds an SQL query part to the SQL query part array + * adds an SQL query part to the SQL query part array. * * @param string $name the name of the query part to be added * @param string $part query part string * * @return $this this object + * * @throws Doctrine_Query_Exception if trying to add unknown query part */ public function addSqlQueryPart($name, $part) { - if ( ! isset($this->_sqlParts[$name])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $name); + if (!isset($this->_sqlParts[$name])) { + throw new Doctrine_Query_Exception('Unknown query part '.$name); } if (is_array($part)) { $this->_sqlParts[$name] = array_merge($this->_sqlParts[$name], $part); } else { $this->_sqlParts[$name][] = $part; } + return $this; } /** * removeSqlQueryPart - * removes a query part from the query part array + * removes a query part from the query part array. * * @param string $name the name of the query part to be removed * * @return $this this object + * * @throws Doctrine_Query_Exception if trying to remove unknown query part */ public function removeSqlQueryPart($name) { - if ( ! isset($this->_sqlParts[$name])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $name); + if (!isset($this->_sqlParts[$name])) { + throw new Doctrine_Query_Exception('Unknown query part '.$name); } - if ($name == 'limit' || $name == 'offset' || $name == 'forUpdate') { + if ('limit' == $name || 'offset' == $name || 'forUpdate' == $name) { $this->_sqlParts[$name] = false; } else { $this->_sqlParts[$name] = array(); @@ -510,20 +512,21 @@ public function removeSqlQueryPart($name) /** * removeDqlQueryPart - * removes a dql query part from the dql query part array + * removes a dql query part from the dql query part array. * * @param string $name the name of the query part to be removed * * @return $this this object + * * @throws Doctrine_Query_Exception if trying to remove unknown query part */ public function removeDqlQueryPart($name) { - if ( ! isset($this->_dqlParts[$name])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $name); + if (!isset($this->_dqlParts[$name])) { + throw new Doctrine_Query_Exception('Unknown query part '.$name); } - if ($name == 'limit' || $name == 'offset') { + if ('limit' == $name || 'offset' == $name) { $this->_dqlParts[$name] = false; } else { $this->_dqlParts[$name] = array(); @@ -560,7 +563,7 @@ public function getFlattenedParams($params = array()) } /** - * getInternalParams + * getInternalParams. * * @param array $params * @@ -572,9 +575,7 @@ public function getInternalParams($params = array()) } /** - * setParams - * - * @param array $params + * setParams. */ public function setParams(array $params = array()) { @@ -583,7 +584,7 @@ public function setParams(array $params = array()) /** * getCountQueryParams - * Retrieves the parameters for count query + * Retrieves the parameters for count query. * * @param array $params * @@ -591,7 +592,7 @@ public function setParams(array $params = array()) */ public function getCountQueryParams($params = array()) { - if ( ! is_array($params)) { + if (!is_array($params)) { $params = array($params); } @@ -619,7 +620,7 @@ public function fixArrayParameterValues($params = array()) $i += $c; } else { - $i++; + ++$i; } } @@ -629,10 +630,9 @@ public function fixArrayParameterValues($params = array()) /** * setView * sets a database view this query object uses - * this method should only be called internally by doctrine + * this method should only be called internally by doctrine. * - * @param Doctrine_View $view database view - * @return void + * @param Doctrine_View $view database view */ public function setView(Doctrine_View $view) { @@ -641,9 +641,9 @@ public function setView(Doctrine_View $view) /** * getView - * returns the view associated with this query object (if any) + * returns the view associated with this query object (if any). * - * @return Doctrine_View the view associated with this query object + * @return Doctrine_View the view associated with this query object */ public function getView() { @@ -651,9 +651,9 @@ public function getView() } /** - * limitSubqueryUsed + * limitSubqueryUsed. * - * @return boolean + * @return bool */ public function isLimitSubqueryUsed() { @@ -662,7 +662,7 @@ public function isLimitSubqueryUsed() /** * Returns the inheritance condition for the passed componentAlias - * If no component alias is specified it defaults to the root component + * If no component alias is specified it defaults to the root component. * * This function is used to append a SQL condition to models which have inheritance mapping * The condition is applied to the FROM component in the WHERE, but the condition is applied to @@ -671,6 +671,7 @@ public function isLimitSubqueryUsed() * @param string $componentAlias * * @return string|null $str SQL condition string + * * @throws Doctrine_Query_Exception */ public function getInheritanceCondition($componentAlias) @@ -684,7 +685,7 @@ public function getInheritanceCondition($componentAlias) $tableAlias = $this->getSqlTableAlias($componentAlias); - if ($this->_type !== Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT !== $this->_type) { $tableAlias = ''; } else { $tableAlias .= '.'; @@ -692,16 +693,16 @@ public function getInheritanceCondition($componentAlias) // Fix for 2015: loop through whole inheritanceMap to add all // keyFields for inheritance (and not only the first) - $retVal = ""; - $count = 0; + $retVal = ''; + $count = 0; foreach ($map as $field => $value) { if ($count++ > 0) { $retVal .= ' AND '; } - $identifier = $this->_conn->quoteIdentifier($tableAlias . $field); - $retVal .= $identifier . ' = ' . $this->_conn->quote($value); + $identifier = $this->_conn->quoteIdentifier($tableAlias.$field); + $retVal .= $identifier.' = '.$this->_conn->quote($value); } return $retVal; @@ -710,7 +711,7 @@ public function getInheritanceCondition($componentAlias) /** * getSqlTableAlias * some database such as Oracle need the identifier lengths to be < ~30 chars - * hence Doctrine creates as short identifier aliases as possible + * hence Doctrine creates as short identifier aliases as possible. * * this method is used for the creation of short table aliases, its also * smart enough to check if an alias already exists for given component (componentAlias) @@ -719,18 +720,19 @@ public function getInheritanceCondition($componentAlias) * @param string $tableName the table name from which the table alias is being created * * @return string the generated / fetched short alias + * * @throws Doctrine_Query_Exception */ public function getSqlTableAlias($componentAlias, $tableName = null) { $alias = array_search($componentAlias, $this->_tableAliasMap); - if ($alias !== false) { + if (false !== $alias) { return $alias; } - if ($tableName === null) { - throw new Doctrine_Query_Exception("Couldn't get short alias for " . $componentAlias); + if (null === $tableName) { + throw new Doctrine_Query_Exception("Couldn't get short alias for ".$componentAlias); } return $this->generateSqlTableAlias($componentAlias, $tableName); @@ -738,7 +740,7 @@ public function getSqlTableAlias($componentAlias, $tableName = null) /** * generateNewSqlTableAlias - * generates a new alias from given table alias + * generates a new alias from given table alias. * * @param string $oldAlias table alias from which to generate the new alias from * @@ -749,16 +751,16 @@ public function generateNewSqlTableAlias($oldAlias) if (isset($this->_tableAliasMap[$oldAlias])) { // generate a new alias $name = substr($oldAlias, 0, 1); - $i = ((int) substr($oldAlias, 1)); + $i = ((int) substr($oldAlias, 1)); // Fix #1530: It was reaching unexistent seeds index - if ( ! isset($this->_tableAliasSeeds[$name])) { + if (!isset($this->_tableAliasSeeds[$name])) { $this->_tableAliasSeeds[$name] = 1; } - $newIndex = ($this->_tableAliasSeeds[$name] + (($i == 0) ? 1 : $i)); + $newIndex = ($this->_tableAliasSeeds[$name] + ((0 == $i) ? 1 : $i)); - return $name . $newIndex; + return $name.$newIndex; } return $oldAlias; @@ -766,26 +768,28 @@ public function generateNewSqlTableAlias($oldAlias) /** * getSqlTableAliasSeed - * returns the alias seed for given table alias + * returns the alias seed for given table alias. * * @param string $sqlTableAlias table alias that identifies the alias seed * - * @return integer table alias seed + * @return int table alias seed */ public function getSqlTableAliasSeed($sqlTableAlias) { - if ( ! isset($this->_tableAliasSeeds[$sqlTableAlias])) { + if (!isset($this->_tableAliasSeeds[$sqlTableAlias])) { return 0; } + return $this->_tableAliasSeeds[$sqlTableAlias]; } /** * hasAliasDeclaration - * whether or not this object has a declaration for given component alias + * whether or not this object has a declaration for given component alias. + * + * @param string $componentAlias the component alias the retrieve the declaration from * - * @param string $componentAlias the component alias the retrieve the declaration from - * @return boolean + * @return bool */ public function hasAliasDeclaration($componentAlias) { @@ -794,17 +798,18 @@ public function hasAliasDeclaration($componentAlias) /** * getQueryComponent - * get the declaration for given component alias + * get the declaration for given component alias. * * @param string $componentAlias the component alias the retrieve the declaration from * * @return array the alias declaration + * * @throws Doctrine_Query_Exception */ public function getQueryComponent($componentAlias) { - if ( ! isset($this->_queryComponents[$componentAlias])) { - throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias); + if (!isset($this->_queryComponents[$componentAlias])) { + throw new Doctrine_Query_Exception('Unknown component alias '.$componentAlias); } return $this->_queryComponents[$componentAlias]; @@ -812,7 +817,7 @@ public function getQueryComponent($componentAlias) /** * copySubqueryInfo - * copy aliases from another Hydrate object + * copy aliases from another Hydrate object. * * this method is needed by DQL subqueries which need the aliases * of the parent query @@ -824,22 +829,23 @@ public function getQueryComponent($componentAlias) */ public function copySubqueryInfo(Doctrine_Query_Abstract $query) { - $this->_params =& $query->_params; - $this->_tableAliasMap =& $query->_tableAliasMap; - $this->_queryComponents =& $query->_queryComponents; + $this->_params = &$query->_params; + $this->_tableAliasMap = &$query->_tableAliasMap; + $this->_queryComponents = &$query->_queryComponents; $this->_tableAliasSeeds = $query->_tableAliasSeeds; + return $this; } /** * getRootAlias - * returns the alias of the root component + * returns the alias of the root component. * * @return string */ public function getRootAlias() { - if ( ! $this->_queryComponents) { + if (!$this->_queryComponents) { $this->getSqlQuery(array(), false); } @@ -848,28 +854,28 @@ public function getRootAlias() /** * getRootDeclaration - * returns the root declaration + * returns the root declaration. * * @return array */ public function getRootDeclaration() { - $map = $this->_queryComponents[$this->_rootAlias]; - return $map; + return $this->_queryComponents[$this->_rootAlias]; } /** * getRoot - * returns the root component for this object + * returns the root component for this object. * * @return Doctrine_Table root components table + * * @throws Doctrine_Query_Exception */ public function getRoot() { $map = $this->_queryComponents[$this->_rootAlias]; - if ( ! isset($map['table'])) { + if (!isset($map['table'])) { throw new Doctrine_Query_Exception('Root component not initialized.'); } @@ -879,11 +885,12 @@ public function getRoot() /** * generateSqlTableAlias * generates a table alias from given table name and associates - * it with given component alias + * it with given component alias. * - * @param string $componentAlias the component alias to be associated with generated table alias - * @param string $tableName the table name from which to generate the table alias - * @return string the generated table alias + * @param string $componentAlias the component alias to be associated with generated table alias + * @param string $tableName the table name from which to generate the table alias + * + * @return string the generated table alias */ public function generateSqlTableAlias($componentAlias, $tableName) { @@ -892,15 +899,15 @@ public function generateSqlTableAlias($componentAlias, $tableName) $alias = $char; - if ( ! isset($this->_tableAliasSeeds[$alias])) { + if (!isset($this->_tableAliasSeeds[$alias])) { $this->_tableAliasSeeds[$alias] = 1; } while (isset($this->_tableAliasMap[$alias])) { - if ( ! isset($this->_tableAliasSeeds[$alias])) { + if (!isset($this->_tableAliasSeeds[$alias])) { $this->_tableAliasSeeds[$alias] = 1; } - $alias = $char . ++$this->_tableAliasSeeds[$alias]; + $alias = $char.++$this->_tableAliasSeeds[$alias]; } $this->_tableAliasMap[$alias] = $componentAlias; @@ -910,49 +917,52 @@ public function generateSqlTableAlias($componentAlias, $tableName) /** * getComponentAlias - * get component alias associated with given table alias + * get component alias associated with given table alias. * * @param string $sqlTableAlias the SQL table alias that identifies the component alias * * @return string component alias + * * @throws Doctrine_Query_Exception */ public function getComponentAlias($sqlTableAlias) { $sqlTableAlias = trim($sqlTableAlias, '[]`"'); - if ( ! isset($this->_tableAliasMap[$sqlTableAlias])) { - throw new Doctrine_Query_Exception('Unknown table alias ' . $sqlTableAlias); + if (!isset($this->_tableAliasMap[$sqlTableAlias])) { + throw new Doctrine_Query_Exception('Unknown table alias '.$sqlTableAlias); } + return $this->_tableAliasMap[$sqlTableAlias]; } /** * calculateQueryCacheHash - * calculate hash key for query cache + * calculate hash key for query cache. * - * @return string the hash + * @return string the hash */ public function calculateQueryCacheHash() { $dql = $this->getDql(); - $hash = md5($dql . var_export($this->_pendingJoinConditions, true) . 'DOCTRINE_QUERY_CACHE_SALT'); - return $hash; + + return md5($dql.var_export($this->_pendingJoinConditions, true).'DOCTRINE_QUERY_CACHE_SALT'); } /** * calculateResultCacheHash - * calculate hash key for result cache + * calculate hash key for result cache. * * @param array $params - * @return string the hash + * + * @return string the hash */ public function calculateResultCacheHash($params = array()) { $dql = $this->getDql(); $conn = $this->getConnection(); $params = $this->getFlattenedParams($params); - $hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $dql . var_export($this->_pendingJoinConditions, true) . var_export($params, true)); - return $hash; + + return md5($this->_hydrator->getHydrationMode().$conn->getName().$conn->getOption('dsn').$dql.var_export($this->_pendingJoinConditions, true).var_export($params, true)); } /** @@ -960,23 +970,25 @@ public function calculateResultCacheHash($params = array()) * or generates a unique key from the query automatically. * * @param array $params + * * @return string $hash */ public function getResultCacheHash($params = array()) { - if ($this->_resultCacheHash) { - return $this->_resultCacheHash; - } else { - return $this->calculateResultCacheHash($params); - } + if ($this->_resultCacheHash) { + return $this->_resultCacheHash; + } + + return $this->calculateResultCacheHash($params); } /** - * _execute + * _execute. * * @param array $params * * @return PDOStatement|int The executed PDOStatement or the number of affected rows + * * @throws Doctrine_Connection_Exception * @throws Doctrine_Exception */ @@ -992,8 +1004,8 @@ protected function _execute($params) $dqlParams = $this->getFlattenedParams($params); // Check if we're not using a Doctrine_View - if ( ! $this->_view) { - if ($this->_queryCache !== false && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) { + if (!$this->_view) { + if (false !== $this->_queryCache && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) { $queryCacheDriver = $this->getQueryCacheDriver(); $hash = $this->calculateQueryCacheHash(); $cached = $queryCacheDriver->fetch($hash); @@ -1017,7 +1029,7 @@ protected function _execute($params) // Check again because getSqlQuery() above could have flipped the _queryCache flag // if this query contains the limit sub query algorithm we don't need to cache it - if ($this->_queryCache !== false && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) { + if (false !== $this->_queryCache && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) { // Convert query into a serialized form $serializedQuery = $this->getCachedForm($query); @@ -1035,12 +1047,12 @@ protected function _execute($params) // Get prepared SQL params for execution $params = $this->getInternalParams(); - if ($this->isLimitSubqueryUsed() && - $this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME) !== 'mysql') { + if ($this->isLimitSubqueryUsed() + && 'mysql' !== $this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME)) { $params = array_merge((array) $params, (array) $params); } - if ($this->_type !== self::SELECT) { + if (self::SELECT !== $this->_type) { return $this->_conn->exec($query, $params); } @@ -1053,12 +1065,13 @@ protected function _execute($params) /** * execute - * executes the query and populates the data set + * executes the query and populates the data set. * * @param array $params - * @param null|int|string $hydrationMode one of the Doctrine_Core::HYDRATE_* constants or null + * @param int|string|null $hydrationMode one of the Doctrine_Core::HYDRATE_* constants or null * * @return Doctrine_Collection|array the root collection (the result type depends on the hydrator) + * * @throws Doctrine_Connection_Exception * @throws Doctrine_Hydrator_Exception * @throws Doctrine_Query_Exception @@ -1077,18 +1090,18 @@ public function execute($params = array(), $hydrationMode = null) $this->_preQuery($dqlParams); - if ($hydrationMode !== null) { + if (null !== $hydrationMode) { $this->_hydrator->setHydrationMode($hydrationMode); } $hydrationMode = $this->_hydrator->getHydrationMode(); - if ($this->_resultCache && $this->_type == self::SELECT) { + if ($this->_resultCache && self::SELECT == $this->_type) { $cacheDriver = $this->getResultCacheDriver(); $hash = $this->getResultCacheHash($params); $cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash); - if ($cached === false) { + if (false === $cached) { // cache miss $stmt = $this->_execute($params); $this->_hydrator->setQueryComponents($this->_queryComponents); @@ -1106,7 +1119,7 @@ public function execute($params = array(), $hydrationMode = null) $result = $stmt; } else { $this->_hydrator->setQueryComponents($this->_queryComponents); - if ($this->_type == self::SELECT && $hydrationMode == Doctrine_Core::HYDRATE_ON_DEMAND) { + if (self::SELECT == $this->_type && Doctrine_Core::HYDRATE_ON_DEMAND == $hydrationMode) { $hydrationDriver = $this->_hydrator->getHydratorDriver($hydrationMode, $this->_tableAliasMap); $result = new Doctrine_Collection_OnDemand($stmt, $hydrationDriver, $this->_tableAliasMap); } else { @@ -1122,40 +1135,40 @@ public function execute($params = array(), $hydrationMode = null) } /** - * Blank template method free(). Override to be used to free query object memory + * Blank template method free(). Override to be used to free query object memory. */ public function free() { } /** - * Get the dql call back for this query + * Get the dql call back for this query. * * @return array $callback */ protected function _getDqlCallback() { $callback = false; - if ( ! empty($this->_dqlParts['from'])) { + if (!empty($this->_dqlParts['from'])) { switch ($this->_type) { case self::DELETE: $callback = array( 'callback' => 'preDqlDelete', - 'const' => Doctrine_Event::RECORD_DQL_DELETE + 'const' => Doctrine_Event::RECORD_DQL_DELETE, ); - break; + break; case self::UPDATE: $callback = array( 'callback' => 'preDqlUpdate', - 'const' => Doctrine_Event::RECORD_DQL_UPDATE + 'const' => Doctrine_Event::RECORD_DQL_UPDATE, ); - break; + break; case self::SELECT: $callback = array( 'callback' => 'preDqlSelect', - 'const' => Doctrine_Event::RECORD_DQL_SELECT + 'const' => Doctrine_Event::RECORD_DQL_SELECT, ); - break; + break; } } @@ -1164,22 +1177,21 @@ protected function _getDqlCallback() /** * Pre query method which invokes the pre*Query() methods on the model instance or any attached - * record listeners + * record listeners. * * @param array $params * - * @return void * @throws Doctrine_Connection_Exception */ protected function _preQuery($params = array()) { - if ( ! $this->_preQueried && $this->getConnection()->getAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS)) { + if (!$this->_preQueried && $this->getConnection()->getAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS)) { $this->_preQueried = true; $callback = $this->_getDqlCallback(); // if there is no callback for the query type, then we can return early - if ( ! $callback) { + if (!$callback) { return; } @@ -1201,9 +1213,10 @@ protected function _preQuery($params = array()) } /** - * Returns an array of components to execute the query callbacks for + * Returns an array of components to execute the query callbacks for. + * + * @param array $params * - * @param array $params * @return array $components */ protected function _getDqlCallbackComponents($params = array()) @@ -1223,15 +1236,13 @@ protected function _getDqlCallbackComponents($params = array()) if ($componentsBefore !== $componentsAfter) { return Doctrine_Lib::arrayDiffSimple($componentsAfter, $componentsBefore); - } else { - return $componentsAfter; } + + return $componentsAfter; } /** - * Blank hook methods which can be implemented in Doctrine_Query child classes - * - * @return void + * Blank hook methods which can be implemented in Doctrine_Query child classes. */ public function preQuery() { @@ -1240,10 +1251,11 @@ public function preQuery() /** * Constructs the query from the cached form. * - * @param string The cached query, in a serialized form. - * @return array The custom component that was cached together with the essential - * query data. This can be either a result set (result caching) - * or an SQL query string (query caching). + * @param string the cached query, in a serialized form + * + * @return array The custom component that was cached together with the essential + * query data. This can be either a result set (result caching) + * or an SQL query string (query caching). */ protected function _constructQueryFromCache($cached) { @@ -1255,9 +1267,9 @@ protected function _constructQueryFromCache($cached) $cachedComponents = $cached[1]; foreach ($cachedComponents as $alias => $components) { $e = explode('.', $components['name']); - if (count($e) === 1) { + if (1 === count($e)) { $manager = Doctrine_Manager::getInstance(); - if ( ! $this->_passedConn && $manager->hasConnectionForComponent($e[0])) { + if (!$this->_passedConn && $manager->hasConnectionForComponent($e[0])) { $this->_conn = $manager->getConnectionForComponent($e[0]); } $queryComponents[$alias]['table'] = $this->_conn->getTable($e[0]); @@ -1283,9 +1295,9 @@ protected function _constructQueryFromCache($cached) /** * getCachedForm - * returns the cached form of this query for given resultSet + * returns the cached form of this query for given resultSet. * - * @param array|null|Doctrine_Collection $customComponent + * @param array|Doctrine_Collection|null $customComponent * * @return string serialized string representation of this query */ @@ -1294,10 +1306,10 @@ public function getCachedForm($customComponent = null) $componentInfo = array(); foreach ($this->getQueryComponents() as $alias => $components) { - if ( ! isset($components['parent'])) { + if (!isset($components['parent'])) { $componentInfo[$alias]['name'] = $components['table']->getComponentName(); } else { - $componentInfo[$alias]['name'] = $components['parent'] . '.' . $components['relation']->getAlias(); + $componentInfo[$alias]['name'] = $components['parent'].'.'.$components['relation']->getAlias(); } if (isset($components['agg'])) { $componentInfo[$alias]['agg'] = $components['agg']; @@ -1330,6 +1342,7 @@ public function getCachedForm($customComponent = null) * @param string $select Query SELECT part * * @return $this + * * @throws Doctrine_Query_Exception */ public function addSelect($select) @@ -1339,7 +1352,7 @@ public function addSelect($select) /** * addSqlTableAlias - * adds an SQL table alias and associates it a component alias + * adds an SQL table alias and associates it a component alias. * * @param string $componentAlias the alias for the query component associated with given tableAlias * @param string $sqlTableAlias the table alias to be added @@ -1349,16 +1362,18 @@ public function addSelect($select) public function addSqlTableAlias($sqlTableAlias, $componentAlias) { $this->_tableAliasMap[$sqlTableAlias] = $componentAlias; + return $this; } /** * addFrom - * adds fields to the FROM part of the query + * adds fields to the FROM part of the query. * * @param string $from Query FROM part * * @return $this + * * @throws Doctrine_Query_Exception */ public function addFrom($from) @@ -1370,6 +1385,7 @@ public function addFrom($from) * Alias for @see Doctrine_Query_Abstract::andWhere(). * * @return $this this object + * * @throws Doctrine_Query_Exception */ public function addWhere($where, $params = array()) @@ -1381,12 +1397,13 @@ public function addWhere($where, $params = array()) * Adds conditions to the WHERE part of the query. * * $q->andWhere('u.birthDate > ?', '1975-01-01'); - * + * . * * @param string $where Query WHERE part * @param mixed $params An array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function andWhere($where, $params = array()) @@ -1408,12 +1425,13 @@ public function andWhere($where, $params = array()) * Adds conditions to the WHERE part of the query * * $q->orWhere('u.role = ?', 'admin'); - * + * . * * @param string $where Query WHERE part * @param mixed $params An array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function orWhere($where, $params = array()) @@ -1434,11 +1452,12 @@ public function orWhere($where, $params = array()) /** * Adds IN condition to the query WHERE part. Alias to @see andWhereIn(). * - * @param string $expr the operand of the IN - * @param mixed $params an array of parameters or a simple scalar - * @param boolean $not whether or not to use NOT in front of IN + * @param string $expr the operand of the IN + * @param mixed $params an array of parameters or a simple scalar + * @param bool $not whether or not to use NOT in front of IN * * @return $this + * * @throws Doctrine_Query_Exception */ public function whereIn($expr, $params = array(), $not = false) @@ -1450,19 +1469,20 @@ public function whereIn($expr, $params = array(), $not = false) * Adds IN condition to the query WHERE part * * $q->whereIn('u.id', array(10, 23, 44)); - * + * . * - * @param string $expr The operand of the IN - * @param mixed $params An array of parameters or a simple scalar - * @param boolean $not Whether or not to use NOT in front of IN. Defaults to false (simple IN clause) + * @param string $expr The operand of the IN + * @param mixed $params An array of parameters or a simple scalar + * @param bool $not Whether or not to use NOT in front of IN. Defaults to false (simple IN clause) + * + * @return $this this object * - * @return $this this object. * @throws Doctrine_Query_Exception */ public function andWhereIn($expr, $params = array(), $not = false) { // if there's no params, return (else we'll get a WHERE IN (), invalid SQL) - if (isset($params) and is_array($params) and (count($params) == 0)) { + if (isset($params) and is_array($params) and (0 == count($params))) { return $this; } @@ -1479,19 +1499,20 @@ public function andWhereIn($expr, $params = array(), $not = false) * $q->orWhereIn('u.id', array(10, 23)) * ->orWhereIn('u.id', 44); * // will select all record with id equal to 10, 23 or 44 - * + * . * - * @param string $expr The operand of the IN - * @param mixed $params An array of parameters or a simple scalar - * @param boolean $not Whether or not to use NOT in front of IN + * @param string $expr The operand of the IN + * @param mixed $params An array of parameters or a simple scalar + * @param bool $not Whether or not to use NOT in front of IN * * @return $this + * * @throws Doctrine_Query_Exception */ public function orWhereIn($expr, $params = array(), $not = false) { // if there's no params, return (else we'll get a WHERE IN (), invalid SQL) - if (isset($params) and (count($params) == 0)) { + if (isset($params) and (0 == count($params))) { return $this; } @@ -1510,7 +1531,7 @@ protected function _processWhereIn($expr, $params = array(), $not = false) $params = (array) $params; // if there's no params, return (else we'll get a WHERE IN (), invalid SQL) - if (count($params) == 0) { + if (0 == count($params)) { throw new Doctrine_Query_Exception('You must pass at least one parameter when using an IN() condition.'); } @@ -1527,7 +1548,7 @@ protected function _processWhereIn($expr, $params = array(), $not = false) $this->_params['where'] = array_merge($this->_params['where'], $params); - return $expr . ($not === true ? ' NOT' : '') . ' IN (' . implode(', ', $a) . ')'; + return $expr.(true === $not ? ' NOT' : '').' IN ('.implode(', ', $a).')'; } /** @@ -1535,12 +1556,13 @@ protected function _processWhereIn($expr, $params = array(), $not = false) * * $q->whereNotIn('u.id', array(10, 20)); * // will exclude users with id 10 and 20 from the select - * + * . * * @param string $expr the operand of the NOT IN * @param mixed $params an array of parameters or a simple scalar * - * @return $this this object + * @return $this this object + * * @throws Doctrine_Query_Exception */ public function whereNotIn($expr, $params = array()) @@ -1556,6 +1578,7 @@ public function whereNotIn($expr, $params = array()) * @param mixed $params An array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function andWhereNotIn($expr, $params = array()) @@ -1564,12 +1587,13 @@ public function andWhereNotIn($expr, $params = array()) } /** - * Adds NOT IN condition to the query WHERE part + * Adds NOT IN condition to the query WHERE part. * * @param string $expr The operand of the NOT IN * @param mixed $params An array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function orWhereNotIn($expr, $params = array()) @@ -1581,11 +1605,12 @@ public function orWhereNotIn($expr, $params = array()) * Adds fields to the GROUP BY part of the query. * * $q->groupBy('u.id'); - * + * . * * @param string $groupby Query GROUP BY part * * @return $this + * * @throws Doctrine_Query_Exception */ public function addGroupBy($groupby) @@ -1606,6 +1631,7 @@ public function addGroupBy($groupby) * @param mixed $params an array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function addHaving($having, $params = array()) @@ -1615,16 +1641,18 @@ public function addHaving($having, $params = array()) } else { $this->_params['having'][] = $params; } + return $this->_addDqlQueryPart('having', $having, true); } /** * addOrderBy - * adds fields to the ORDER BY part of the query + * adds fields to the ORDER BY part of the query. * * @param string $orderby Query ORDER BY part * * @return $this + * * @throws Doctrine_Query_Exception */ public function addOrderBy($orderby) @@ -1634,11 +1662,12 @@ public function addOrderBy($orderby) /** * select - * sets the SELECT part of the query + * sets the SELECT part of the query. * * @param string $select Query SELECT part * * @return $this + * * @throws Doctrine_Query_Exception */ public function select($select = null) @@ -1646,9 +1675,9 @@ public function select($select = null) $this->_type = self::SELECT; if ($select) { return $this->_addDqlQueryPart('select', $select); - } else { - return $this; } + + return $this; } /** @@ -1656,15 +1685,16 @@ public function select($select = null) * Makes the query SELECT DISTINCT. * * $q->distinct(); - * + * . * - * @param bool $flag Whether or not the SELECT is DISTINCT (default true). + * @param bool $flag whether or not the SELECT is DISTINCT (default true) * * @return $this */ public function distinct($flag = true) { $this->_sqlParts['distinct'] = (bool) $flag; + return $this; } @@ -1672,55 +1702,60 @@ public function distinct($flag = true) * forUpdate * Makes the query SELECT FOR UPDATE. * - * @param bool $flag Whether or not the SELECT is FOR UPDATE (default true). + * @param bool $flag whether or not the SELECT is FOR UPDATE (default true) * * @return $this */ public function forUpdate($flag = true) { $this->_sqlParts['forUpdate'] = (bool) $flag; + return $this; } /** * delete - * sets the query type to DELETE + * sets the query type to DELETE. * - * @param null|string $from + * @param string|null $from * * @return $this + * * @throws Doctrine_Query_Exception */ public function delete($from = null) { $this->_type = self::DELETE; - if ($from != null) { + if (null != $from) { return $this->_addDqlQueryPart('from', $from); } + return $this; } /** * update - * sets the UPDATE part of the query + * sets the UPDATE part of the query. * * @param string|null $from Query UPDATE part * * @return $this + * * @throws Doctrine_Query_Exception */ public function update($from = null) { $this->_type = self::UPDATE; - if ($from != null) { + if (null != $from) { return $this->_addDqlQueryPart('from', $from); } + return $this; } /** * set - * sets the SET part of the query + * sets the SET part of the query. * * NOTE: best way is to use: $query->set(array('key' => 'value', ...)) * @@ -1732,6 +1767,7 @@ public function update($from = null) * '?', array(null)) or set(array('key' => null)) * * @return $this + * * @throws Doctrine_Query_Exception */ public function set($key, $value = null, $params = null) @@ -1740,18 +1776,18 @@ public function set($key, $value = null, $params = null) foreach ($key as $k => $v) { $this->set($k, '?', array($v)); } + return $this; - } else { - if ($params !== null) { - if (is_array($params)) { - $this->_params['set'] = array_merge($this->_params['set'], $params); - } else { - $this->_params['set'][] = $params; - } + } + if (null !== $params) { + if (is_array($params)) { + $this->_params['set'] = array_merge($this->_params['set'], $params); + } else { + $this->_params['set'][] = $params; } - - return $this->_addDqlQueryPart('set', $key . ' = ' . $value, true); } + + return $this->_addDqlQueryPart('set', $key.' = '.$value, true); } /** @@ -1759,11 +1795,12 @@ public function set($key, $value = null, $params = null) * sets the FROM part of the query * * $q->from('User u'); - * + * . * * @param string $from Query FROM part * * @return $this + * * @throws Doctrine_Query_Exception */ public function from($from) @@ -1773,11 +1810,12 @@ public function from($from) /** * innerJoin - * appends an INNER JOIN to the FROM part of the query + * appends an INNER JOIN to the FROM part of the query. * * @param string $join Query INNER JOIN * * @return $this + * * @throws Doctrine_Query_Exception */ public function innerJoin($join, $params = array()) @@ -1788,16 +1826,17 @@ public function innerJoin($join, $params = array()) $this->_params['join'][] = $params; } - return $this->_addDqlQueryPart('from', 'INNER JOIN ' . $join, true); + return $this->_addDqlQueryPart('from', 'INNER JOIN '.$join, true); } /** * leftJoin - * appends a LEFT JOIN to the FROM part of the query + * appends a LEFT JOIN to the FROM part of the query. * * @param string $join Query LEFT JOIN * * @return $this + * * @throws Doctrine_Query_Exception */ public function leftJoin($join, $params = array()) @@ -1808,16 +1847,17 @@ public function leftJoin($join, $params = array()) $this->_params['join'][] = $params; } - return $this->_addDqlQueryPart('from', 'LEFT JOIN ' . $join, true); + return $this->_addDqlQueryPart('from', 'LEFT JOIN '.$join, true); } /** * groupBy - * sets the GROUP BY part of the query + * sets the GROUP BY part of the query. * * @param string $groupby Query GROUP BY part * * @return $this + * * @throws Doctrine_Query_Exception */ public function groupBy($groupby) @@ -1827,12 +1867,13 @@ public function groupBy($groupby) /** * where - * sets the WHERE part of the query + * sets the WHERE part of the query. * * @param string $where Query WHERE part * @param mixed $params an array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function where($where, $params = array()) @@ -1850,12 +1891,13 @@ public function where($where, $params = array()) /** * having - * sets the HAVING part of the query + * sets the HAVING part of the query. * * @param string $having Query HAVING part * @param mixed $params an array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function having($having, $params = array()) @@ -1875,11 +1917,12 @@ public function having($having, $params = array()) * * $q->orderBy('u.name'); * $query->orderBy('u.birthDate DESC'); - * + * . * * @param string $orderby Query ORDER BY part * * @return $this + * * @throws Doctrine_Query_Exception */ public function orderBy($orderby) @@ -1889,11 +1932,12 @@ public function orderBy($orderby) /** * limit - * sets the Query query limit + * sets the Query query limit. * - * @param integer $limit limit to be used for limiting the query results + * @param int $limit limit to be used for limiting the query results * * @return $this + * * @throws Doctrine_Query_Exception */ public function limit($limit) @@ -1903,11 +1947,12 @@ public function limit($limit) /** * offset - * sets the Query query offset + * sets the Query query offset. * - * @param integer $offset offset to be used for paginating the query + * @param int $offset offset to be used for paginating the query * * @return $this + * * @throws Doctrine_Query_Exception */ public function offset($offset) @@ -1917,30 +1962,29 @@ public function offset($offset) /** * Resets all the sql parts. - * - * @return void */ protected function clear() { $this->_sqlParts = array( - 'select' => array(), - 'distinct' => false, - 'forUpdate' => false, - 'from' => array(), - 'set' => array(), - 'join' => array(), - 'where' => array(), - 'groupby' => array(), - 'having' => array(), - 'orderby' => array(), - 'limit' => false, - 'offset' => false, - ); + 'select' => array(), + 'distinct' => false, + 'forUpdate' => false, + 'from' => array(), + 'set' => array(), + 'join' => array(), + 'where' => array(), + 'groupby' => array(), + 'having' => array(), + 'orderby' => array(), + 'limit' => false, + 'offset' => false, + ); } public function setHydrationMode($hydrationMode) { $this->_hydrator->setHydrationMode($hydrationMode); + return $this; } @@ -1963,7 +2007,7 @@ public function getSqlParts() } /** - * getType + * getType. * * returns the type of this query object * by default the type is Doctrine_Query_Abstract::SELECT but if update() or delete() @@ -1974,7 +2018,7 @@ public function getSqlParts() * @see Doctrine_Query_Abstract::UPDATE * @see Doctrine_Query_Abstract::DELETE * - * @return integer return the query type + * @return int return the query type */ public function getType() { @@ -1982,33 +2026,34 @@ public function getType() } /** - * useResultCache - * - * @throws Doctrine_Query_Exception + * useResultCache. * * @param bool|Doctrine_Cache_Interface|null $driver cache driver (true: use default driver | null: disable caching) - * @param integer $timeToLive (in sec) how long the cache entry is valid + * @param int $timeToLive (in sec) how long the cache entry is valid * @param string $resultCacheHash The key to use for storing the queries result cache entry * * @return $this this object + * + * @throws Doctrine_Query_Exception */ public function useResultCache($driver = true, $timeToLive = null, $resultCacheHash = null) { - if ($driver !== null && $driver !== true && ! ($driver instanceOf Doctrine_Cache_Interface)) { + if (null !== $driver && true !== $driver && !($driver instanceof Doctrine_Cache_Interface)) { $msg = 'First argument should be instance of Doctrine_Cache_Interface or null.'; throw new Doctrine_Query_Exception($msg); } $this->_resultCache = $driver; $this->_resultCacheHash = $resultCacheHash; - if ($timeToLive !== null) { + if (null !== $timeToLive) { $this->setResultCacheLifeSpan($timeToLive); } + return $this; } /** - * Set the result cache hash to be used for storing the results in the cache driver + * Set the result cache hash to be used for storing the results in the cache driver. * * @param string $resultCacheHash * @@ -2022,79 +2067,84 @@ public function setResultCacheHash($resultCacheHash) } /** - * Clear the result cache entry for this query + * Clear the result cache entry for this query. * * @return $this + * * @throws Doctrine_Exception */ public function clearResultCache() { $this->getResultCacheDriver() - ->delete($this->getResultCacheHash()); + ->delete($this->getResultCacheHash()) + ; return $this; } /** - * useQueryCache - * - * @throws Doctrine_Query_Exception + * useQueryCache. * * @param Doctrine_Cache_Interface|bool $driver cache driver - * @param integer $timeToLive how long the cache entry is valid + * @param int $timeToLive how long the cache entry is valid * * @return $this this object + * + * @throws Doctrine_Query_Exception */ public function useQueryCache($driver = true, $timeToLive = null) { - if ($driver !== null && $driver !== true && $driver !== false && ! ($driver instanceOf Doctrine_Cache_Interface)) { + if (null !== $driver && true !== $driver && false !== $driver && !($driver instanceof Doctrine_Cache_Interface)) { $msg = 'First argument should be instance of Doctrine_Cache_Interface or null.'; throw new Doctrine_Query_Exception($msg); } $this->_queryCache = $driver; - if ($timeToLive !== null) { + if (null !== $timeToLive) { $this->setQueryCacheLifeSpan($timeToLive); } + return $this; } /** - * expireCache + * expireCache. * - * @param boolean $expire whether or not to force cache expiration + * @param bool $expire whether or not to force cache expiration * * @return $this this object */ public function expireResultCache($expire = true) { $this->_expireResultCache = $expire; + return $this; } /** - * expireQueryCache + * expireQueryCache. * - * @param boolean $expire whether or not to force cache expiration + * @param bool $expire whether or not to force cache expiration * * @return $this this object */ public function expireQueryCache($expire = true) { $this->_expireQueryCache = $expire; + return $this; } /** - * setResultCacheLifeSpan + * setResultCacheLifeSpan. * - * @param integer $timeToLive how long the cache entry is valid (in seconds) + * @param int $timeToLive how long the cache entry is valid (in seconds) * * @return $this this object */ public function setResultCacheLifeSpan($timeToLive) { - if ($timeToLive !== null) { + if (null !== $timeToLive) { $timeToLive = (int) $timeToLive; } $this->_resultCacheTTL = $timeToLive; @@ -2105,7 +2155,7 @@ public function setResultCacheLifeSpan($timeToLive) /** * Gets the life span of the result cache in seconds. * - * @return integer + * @return int */ public function getResultCacheLifeSpan() { @@ -2113,15 +2163,15 @@ public function getResultCacheLifeSpan() } /** - * setQueryCacheLifeSpan + * setQueryCacheLifeSpan. * - * @param integer $timeToLive how long the cache entry is valid + * @param int $timeToLive how long the cache entry is valid * * @return $this this object */ public function setQueryCacheLifeSpan($timeToLive) { - if ($timeToLive !== null) { + if (null !== $timeToLive) { $timeToLive = (int) $timeToLive; } $this->_queryCacheTTL = $timeToLive; @@ -2132,7 +2182,7 @@ public function setQueryCacheLifeSpan($timeToLive) /** * Gets the life span of the query cache the Query object is using. * - * @return integer The life span in seconds. + * @return int the life span in seconds */ public function getQueryCacheLifeSpan() { @@ -2141,38 +2191,40 @@ public function getQueryCacheLifeSpan() /** * getResultCacheDriver - * returns the cache driver used for caching result sets + * returns the cache driver used for caching result sets. + * + * @return Doctrine_Cache_Interface|bool|null cache driver * - * @return Doctrine_Cache_Interface|boolean|null cache driver * @throws Doctrine_Exception */ public function getResultCacheDriver() { if ($this->_resultCache instanceof Doctrine_Cache_Interface) { return $this->_resultCache; - } else { - return $this->_conn->getResultCacheDriver(); } + + return $this->_conn->getResultCacheDriver(); } /** * getQueryCacheDriver - * returns the cache driver used for caching queries + * returns the cache driver used for caching queries. + * + * @return Doctrine_Cache_Interface|bool|null cache driver * - * @return Doctrine_Cache_Interface|boolean|null cache driver * @throws Doctrine_Exception */ public function getQueryCacheDriver() { if ($this->_queryCache instanceof Doctrine_Cache_Interface) { return $this->_queryCache; - } else { - return $this->_conn->getQueryCacheDriver(); } + + return $this->_conn->getQueryCacheDriver(); } /** - * getConnection + * getConnection. * * @return Doctrine_Connection */ @@ -2184,8 +2236,9 @@ public function getConnection() /** * Checks if there's at least one DQL part defined to the internal parts collection. * - * @param string $queryPartName The name of the query part. - * @return boolean + * @param string $queryPartName the name of the query part + * + * @return bool */ protected function _hasDqlQueryPart($queryPartName) { @@ -2201,20 +2254,21 @@ protected function _hasDqlQueryPart($queryPartName) * @see $_dqlParts; * @see Doctrine_Query::getDqlPart() * - * @param string $queryPartName The name of the query part. - * @param string $queryPart The actual query part to add. - * @param boolean $append Whether to append $queryPart to already existing - * parts under the same $queryPartName. Defaults to FALSE - * (previously added parts with the same name get overridden). + * @param string $queryPartName the name of the query part + * @param string $queryPart the actual query part to add + * @param bool $append Whether to append $queryPart to already existing + * parts under the same $queryPartName. Defaults to FALSE + * (previously added parts with the same name get overridden). * * @return $this + * * @throws Doctrine_Query_Exception */ protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false) { // We should prevent nullable query parts - if ($queryPart === null) { - throw new Doctrine_Query_Exception('Cannot define NULL as part of query when defining \'' . $queryPartName . '\'.'); + if (null === $queryPart) { + throw new Doctrine_Query_Exception('Cannot define NULL as part of query when defining \''.$queryPartName.'\'.'); } if ($append) { @@ -2224,30 +2278,32 @@ protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false) } $this->_state = Doctrine_Query::STATE_DIRTY; + return $this; } /** * _processDqlQueryPart - * parses given query part + * parses given query part. * * @param string $queryPartName the name of the query part * @param array $queryParts an array containing the query part data * * @todo Better description. "parses given query part" ??? Then wheres the difference * between process/parseQueryPart? I suppose this does something different. + * * @throws Doctrine_Query_Exception */ protected function _processDqlQueryPart($queryPartName, $queryParts) { $this->removeSqlQueryPart($queryPartName); - if (is_array($queryParts) && ! empty($queryParts)) { + if (is_array($queryParts) && !empty($queryParts)) { foreach ($queryParts as $queryPart) { $parser = $this->_getParser($queryPartName); $sql = $parser->parse($queryPart); if (isset($sql)) { - if ($queryPartName == 'limit' || $queryPartName == 'offset') { + if ('limit' == $queryPartName || 'offset' == $queryPartName) { $this->setSqlQueryPart($queryPartName, $sql); } else { $this->addSqlQueryPart($queryPartName, $sql); @@ -2259,21 +2315,23 @@ protected function _processDqlQueryPart($queryPartName, $queryParts) /** * _getParser - * parser lazy-loader + * parser lazy-loader. * - * @throws Doctrine_Query_Exception if unknown parser name given * @return Doctrine_Query_Part + * + * @throws Doctrine_Query_Exception if unknown parser name given + * * @todo Doc/Description: What is the parameter for? Which parsers are available? */ protected function _getParser($name) { - if ( ! isset($this->_parsers[$name])) { - $class = 'Doctrine_Query_' . ucwords(strtolower($name)); + if (!isset($this->_parsers[$name])) { + $class = 'Doctrine_Query_'.ucwords(strtolower($name)); Doctrine_Core::autoload($class); - if ( ! class_exists($class)) { - throw new Doctrine_Query_Exception('Unknown parser ' . $name); + if (!class_exists($class)) { + throw new Doctrine_Query_Exception('Unknown parser '.$name); } $this->_parsers[$name] = new $class($this, $this->_tokenizer); @@ -2295,9 +2353,10 @@ abstract public function getSqlQuery($params = array()); /** * parseDqlQuery - * parses a dql query + * parses a dql query. + * + * @param string $query query to be parsed * - * @param string $query query to be parsed * @return $this this object */ abstract public function parseDqlQuery($query); @@ -2305,7 +2364,7 @@ abstract public function parseDqlQuery($query); /** * toString magic call * this method is automatically called when Doctrine_Query object is trying to be used as a string - * So, it it converted into its DQL correspondant + * So, it it converted into its DQL correspondant. * * @return string DQL string */ @@ -2317,7 +2376,7 @@ public function __toString() /** * Gets the disableLimitSubquery property. * - * @return boolean + * @return bool */ public function getDisableLimitSubquery() { @@ -2328,7 +2387,7 @@ public function getDisableLimitSubquery() * Allows you to set the disableLimitSubquery property -- setting this to true will * restrict the query object from using the limit sub query method of tranversing many relationships. * - * @param boolean $disableLimitSubquery + * @param bool $disableLimitSubquery */ public function setDisableLimitSubquery($disableLimitSubquery) { diff --git a/lib/Doctrine/Query/Check.php b/lib/Doctrine/Query/Check.php index c730ce01c..7c87e3942 100644 --- a/lib/Doctrine/Query/Check.php +++ b/lib/Doctrine/Query/Check.php @@ -20,40 +20,42 @@ */ /** - * Doctrine_Query_Check + * Doctrine_Query_Check. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Check { /** - * @var Doctrine_Table $table Doctrine_Table object + * @var Doctrine_Table Doctrine_Table object */ protected $table; /** - * @var string $sql database specific sql CHECK constraint definition - * parsed from the given dql CHECK definition + * @var string database specific sql CHECK constraint definition + * parsed from the given dql CHECK definition */ protected $sql; - + protected $_tokenizer; /** - * @param Doctrine_Table|string $table Doctrine_Table object + * @param Doctrine_Table|string $table Doctrine_Table object */ public function __construct($table) { - if ( ! ($table instanceof Doctrine_Table)) { + if (!($table instanceof Doctrine_Table)) { $table = Doctrine_Manager::getInstance() - ->getCurrentConnection() - ->getTable($table); + ->getCurrentConnection() + ->getTable($table) + ; } $this->table = $table; $this->_tokenizer = new Doctrine_Query_Tokenizer(); @@ -61,7 +63,7 @@ public function __construct($table) /** * getTable - * returns the table object associated with this object + * returns the table object associated with this object. * * @return Doctrine_Connection */ @@ -71,9 +73,10 @@ public function getTable() } /** - * parse + * parse. + * + * @param string $dql DQL CHECK constraint definition * - * @param string $dql DQL CHECK constraint definition * @return string */ public function parse($dql) @@ -82,12 +85,7 @@ public function parse($dql) } /** - * parseClause - * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * parseClause. */ public function parseClause($dql) { @@ -110,17 +108,17 @@ public function parseClause($dql) $r = implode(' OR ', $ret); } else { - $ret = $this->parseSingle($dql); - return $ret; + return $this->parseSingle($dql); } } - return '(' . $r . ')'; + + return '('.$r.')'; } - + public function parseSingle($part) { $e = explode(' ', $part); - + $e[0] = $this->parseFunction($e[0]); switch ($e[1]) { @@ -129,34 +127,34 @@ public function parseSingle($part) case '=': case '!=': case '<>': - - break; + break; default: - throw new Doctrine_Query_Exception('Unknown operator ' . $e[1]); + throw new Doctrine_Query_Exception('Unknown operator '.$e[1]); } return implode(' ', $e); } - public function parseFunction($dql) + public function parseFunction($dql) { if (($pos = strpos($dql, '(')) !== false) { - $func = substr($dql, 0, $pos); - $value = substr($dql, ($pos + 1), -1); - - $expr = $this->table->getConnection()->expression; + $func = substr($dql, 0, $pos); + $value = substr($dql, $pos + 1, -1); - if ( ! method_exists($expr, $func)) { - throw new Doctrine_Query_Exception('Unknown function ' . $func); + $expr = $this->table->getConnection()->expression; + + if (!method_exists($expr, $func)) { + throw new Doctrine_Query_Exception('Unknown function '.$func); } - - $func = $expr->$func($value); + + $func = $expr->{$func}($value); } + return $func; } /** - * getSql + * getSql. * * returns database specific sql CHECK constraint definition * parsed from the given dql CHECK definition @@ -167,4 +165,4 @@ public function getSql() { return $this->sql; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Condition.php b/lib/Doctrine/Query/Condition.php index a4256b565..7de528c3f 100644 --- a/lib/Doctrine/Query/Condition.php +++ b/lib/Doctrine/Query/Condition.php @@ -20,31 +20,33 @@ */ /** - * Doctrine_Query_Condition + * Doctrine_Query_Condition. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Query_Condition extends Doctrine_Query_Part { /** * DQL CONDITION PARSER - * parses the join condition/where/having part of the query string + * parses the join condition/where/having part of the query string. * * @param string $str + * * @return string */ public function parse($str) { $tmp = trim($str); - + $parts = $this->_tokenizer->bracketExplode($str, array(' OR '), '(', ')'); - + if (count($parts) > 1) { $ret = array(); foreach ($parts as $part) { @@ -58,18 +60,18 @@ public function parse($str) // Ticket #1388: We need to make sure we're not splitting a BETWEEN ... AND ... clause $tmp = array(); - for ($i = 0, $l = count($parts); $i < $l; $i++) { + for ($i = 0, $l = count($parts); $i < $l; ++$i) { $test = $this->_tokenizer->sqlExplode($parts[$i]); - if (count($test) == 3 && strtoupper($test[1]) == 'BETWEEN') { - $tmp[] = $parts[$i] . ' AND ' . $parts[++$i]; - } else if (count($test) == 4 && strtoupper($test[1]) == 'NOT' && strtoupper($test[2]) == 'BETWEEN') { - $tmp[] = $parts[$i] . ' AND ' . $parts[++$i]; + if (3 == count($test) && 'BETWEEN' == strtoupper($test[1])) { + $tmp[] = $parts[$i].' AND '.$parts[++$i]; + } elseif (4 == count($test) && 'NOT' == strtoupper($test[1]) && 'BETWEEN' == strtoupper($test[2])) { + $tmp[] = $parts[$i].' AND '.$parts[++$i]; } else { $tmp[] = $parts[$i]; } } - + $parts = $tmp; unset($tmp); @@ -82,56 +84,56 @@ public function parse($str) $r = implode(' AND ', $ret); } else { // Fix for #710 - if (substr($parts[0],0,1) == '(' && substr($parts[0], -1) == ')') { + if ('(' == substr($parts[0], 0, 1) && ')' == substr($parts[0], -1)) { return $this->parse(substr($parts[0], 1, -1)); + } + // Processing NOT here + if ('NOT ' === strtoupper(substr($parts[0], 0, 4))) { + $r = 'NOT ('.$this->parse(substr($parts[0], 4)).')'; } else { - // Processing NOT here - if (strtoupper(substr($parts[0], 0, 4)) === 'NOT ') { - $r = 'NOT ('.$this->parse(substr($parts[0], 4)).')'; - } else { - return $this->load($parts[0]); - } + return $this->load($parts[0]); } } } - - return '(' . $r . ')'; + + return '('.$r.')'; } /** - * parses a literal value and returns the parsed value + * parses a literal value and returns the parsed value. * * boolean literals are parsed to integers * components are parsed to associated table aliases * - * @param string $value literal value to be parsed + * @param string $value literal value to be parsed + * * @return string */ public function parseLiteralValue($value) { // check that value isn't a string - if (strpos($value, '\'') === false) { + if (false === strpos($value, '\'')) { // parse booleans $value = $this->query->getConnection() - ->dataDict->parseBoolean($value); + ->dataDict->parseBoolean($value) + ; $a = explode('.', $value); if (count($a) > 1) { - // either a float or a component.. + // either a float or a component.. - if ( ! is_numeric($a[0])) { + if (!is_numeric($a[0])) { // a component found - $field = array_pop($a); - $reference = implode('.', $a); - $value = $this->query->getConnection()->quoteIdentifier( - $this->query->getSqlTableAlias($reference). '.' . $field + $field = array_pop($a); + $reference = implode('.', $a); + $value = $this->query->getConnection()->quoteIdentifier( + $this->query->getSqlTableAlias($reference).'.'.$field ); } } - } else { - // string literal found } + // string literal found return $value; } diff --git a/lib/Doctrine/Query/Exception.php b/lib/Doctrine/Query/Exception.php index 35630770d..d02e037a0 100644 --- a/lib/Doctrine/Query/Exception.php +++ b/lib/Doctrine/Query/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Query_Exception + * Doctrine_Query_Exception. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Query/Filter.php b/lib/Doctrine/Query/Filter.php index 5598fac2b..b831bba49 100644 --- a/lib/Doctrine/Query/Filter.php +++ b/lib/Doctrine/Query/Filter.php @@ -20,44 +20,38 @@ */ /** - * Doctrine_Query_Filter + * Doctrine_Query_Filter. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Query_Filter implements Doctrine_Query_Filter_Interface { /** - * preQuery + * preQuery. * * Method for listening the preQuery method of Doctrine_Query and * hooking into the query building procedure, doing any custom / specialized * query building procedures that are neccessary. - * - * @return void */ public function preQuery(Doctrine_Query $query) { - } /** - * postQuery + * postQuery. * * Method for listening the postQuery method of Doctrine_Query and * to hook into the query building procedure, doing any custom / specialized * post query procedures (for example logging) that are neccessary. - * - * @param Doctrine_Query $query - * @return void */ public function postQuery(Doctrine_Query $query) { - } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Filter/Chain.php b/lib/Doctrine/Query/Filter/Chain.php index 2262a8b18..3cdc4fafc 100644 --- a/lib/Doctrine/Query/Filter/Chain.php +++ b/lib/Doctrine/Query/Filter/Chain.php @@ -20,28 +20,26 @@ */ /** - * Doctrine_Query_Filter_Chain + * Doctrine_Query_Filter_Chain. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Query_Filter_Chain { /** - * @var array $_filters an array of Doctrine_Query_Filter objects + * @var array an array of Doctrine_Query_Filter objects */ protected $_filters = array(); /** - * add - * - * @param Doctrine_Query_Filter $filter - * @return void + * add. */ public function add(Doctrine_Query_Filter $filter) { @@ -50,25 +48,19 @@ public function add(Doctrine_Query_Filter $filter) /** * returns a Doctrine_Query_Filter on success - * and null on failure - * - * @param mixed $key - * @return mixed + * and null on failure. */ public function get($key) { - if ( ! isset($this->_filters[$key])) { - throw new Doctrine_Query_Exception('Unknown filter ' . $key); + if (!isset($this->_filters[$key])) { + throw new Doctrine_Query_Exception('Unknown filter '.$key); } + return $this->_filters[$key]; } /** - * set - * - * @param mixed $key - * @param Doctrine_Query_Filter $listener - * @return void + * set. */ public function set($key, Doctrine_Query_Filter $listener) { @@ -76,13 +68,11 @@ public function set($key, Doctrine_Query_Filter $listener) } /** - * preQuery + * preQuery. * * Method for listening the preQuery method of Doctrine_Query and * hooking into the query building procedure, doing any custom / specialized * query building procedures that are neccessary. - * - * @return void */ public function preQuery(Doctrine_Query $query) { @@ -92,13 +82,11 @@ public function preQuery(Doctrine_Query $query) } /** - * postQuery + * postQuery. * * Method for listening the postQuery method of Doctrine_Query and * to hook into the query building procedure, doing any custom / specialized * post query procedures (for example logging) that are neccessary. - * - * @return void */ public function postQuery(Doctrine_Query $query) { @@ -106,4 +94,4 @@ public function postQuery(Doctrine_Query $query) $filter->postQuery($query); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Filter/Interface.php b/lib/Doctrine/Query/Filter/Interface.php index 9ed69e786..9258d3a0c 100644 --- a/lib/Doctrine/Query/Filter/Interface.php +++ b/lib/Doctrine/Query/Filter/Interface.php @@ -20,38 +20,34 @@ */ /** - * Doctrine_Query_Filter_Interface + * Doctrine_Query_Filter_Interface. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ interface Doctrine_Query_Filter_Interface { - /** - * preQuery + * preQuery. * * Method for listening the preQuery method of Doctrine_Query and * hooking into the query building procedure, doing any custom / specialized * query building procedures that are neccessary. - * - * @return void */ public function preQuery(Doctrine_Query $query); /** - * postQuery + * postQuery. * * Method for listening the postQuery method of Doctrine_Query and * to hook into the query building procedure, doing any custom / specialized * post query procedures (for example logging) that are neccessary. - * - * @return void */ public function postQuery(Doctrine_Query $query); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Forupdate.php b/lib/Doctrine/Query/Forupdate.php index 6e5851812..d51c7fd53 100644 --- a/lib/Doctrine/Query/Forupdate.php +++ b/lib/Doctrine/Query/Forupdate.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Query_Forupdate + * Doctrine_Query_Forupdate. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1352 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Forupdate extends Doctrine_Query_Part { - public function parse($forUpdate) + public function parse($forUpdate) { return (bool) $forUpdate; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/From.php b/lib/Doctrine/Query/From.php index d9f9c86fa..df6c28037 100644 --- a/lib/Doctrine/Query/From.php +++ b/lib/Doctrine/Query/From.php @@ -20,25 +20,25 @@ */ /** - * Doctrine_Query_From + * Doctrine_Query_From. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_From extends Doctrine_Query_Part { /** * DQL FROM PARSER - * parses the FROM part of the query string + * parses the FROM part of the query string. * * @param string $str - * @param boolean $return if to return the parsed FROM and skip load() - * @return void + * @param bool $return if to return the parsed FROM and skip load() */ public function parse($str, $return = false) { @@ -52,9 +52,10 @@ public function parse($str, $return = false) switch (trim($parts[0])) { case 'INNER': $operator = ':'; + // no break case 'LEFT': array_shift($parts); - break; + break; } $last = ''; @@ -68,7 +69,7 @@ public function parse($str, $return = false) $e = explode(' ', $part); - if (end($e) == 'INNER' || end($e) == 'LEFT') { + if ('INNER' == end($e) || 'LEFT' == end($e)) { $last = array_pop($e); } $part = implode(' ', $e); @@ -79,7 +80,7 @@ public function parse($str, $return = false) $e2 = explode('.', $e[0]); if ($operator) { - $e[0] = array_shift($e2) . $operator . implode('.', $e2); + $e[0] = array_shift($e2).$operator.implode('.', $e2); } if ($return) { @@ -89,8 +90,9 @@ public function parse($str, $return = false) } } - $operator = ($last == 'INNER') ? ':' : '.'; + $operator = ('INNER' == $last) ? ':' : '.'; } + return $from; } } diff --git a/lib/Doctrine/Query/Groupby.php b/lib/Doctrine/Query/Groupby.php index e7293a605..82c05096a 100644 --- a/lib/Doctrine/Query/Groupby.php +++ b/lib/Doctrine/Query/Groupby.php @@ -20,24 +20,22 @@ */ /** - * Doctrine_Query_Groupby + * Doctrine_Query_Groupby. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Groupby extends Doctrine_Query_Part { /** * DQL GROUP BY PARSER - * parses the group by part of the query string - * - * @param string $str - * @return void + * parses the group by part of the query string. */ public function parse($clause, $append = false) { @@ -48,19 +46,18 @@ public function parse($clause, $append = false) $pos = strpos($term[0], '('); $hasComma = false; - if ($pos !== false) { + if (false !== $pos) { $name = substr($term[0], 0, $pos); $term[0] = $this->query->parseFunctionExpression($term[0]); } else { - if (substr($term[0], 0, 1) !== "'" && substr($term[0], -1) !== "'") { - - if (strpos($term[0], '.') !== false) { - if ( ! is_numeric($term[0])) { + if ("'" !== substr($term[0], 0, 1) && "'" !== substr($term[0], -1)) { + if (false !== strpos($term[0], '.')) { + if (!is_numeric($term[0])) { $e = explode('.', $term[0]); $field = array_pop($e); - + // Check if field name still has comma if (($pos = strpos($field, ',')) !== false) { $field = substr($field, 0, $pos); @@ -70,7 +67,7 @@ public function parse($clause, $append = false) // Grab query connection $conn = $this->query->getConnection(); - if ($this->query->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->query->getType()) { $componentAlias = implode('.', $e); if (empty($componentAlias)) { @@ -90,18 +87,18 @@ public function parse($clause, $append = false) $field = $table->getColumnName($field); // check column existence - if ( ! $def) { - throw new Doctrine_Query_Exception('Unknown column ' . $field); + if (!$def) { + throw new Doctrine_Query_Exception('Unknown column '.$field); } if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->query->getSqlTableAlias($componentAlias); // build sql expression - $term[0] = $conn->quoteIdentifier($tableAlias) . '.' . $conn->quoteIdentifier($field); + $term[0] = $conn->quoteIdentifier($tableAlias).'.'.$conn->quoteIdentifier($field); } else { // build sql expression $field = $this->query->getRoot()->getColumnName($field); @@ -109,22 +106,21 @@ public function parse($clause, $append = false) } } } else { - if ( ! empty($term[0]) && - ! is_numeric($term[0]) && - $term[0] !== '?' && substr($term[0], 0, 1) !== ':') { - + if (!empty($term[0]) + && !is_numeric($term[0]) + && '?' !== $term[0] && ':' !== substr($term[0], 0, 1)) { $componentAlias = $this->query->getRootAlias(); $found = false; - + // Check if field name still has comma if (($pos = strpos($term[0], ',')) !== false) { $term[0] = substr($term[0], 0, $pos); $hasComma = true; } - if ($componentAlias !== false && - $componentAlias !== null) { + if (false !== $componentAlias + && null !== $componentAlias) { $queryComponent = $this->query->getQueryComponent($componentAlias); $table = $queryComponent['table']; @@ -138,18 +134,17 @@ public function parse($clause, $append = false) // get the actual column name from field name $term[0] = $table->getColumnName($term[0]); - if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->query->getSqlTableAlias($componentAlias); $conn = $this->query->getConnection(); - if ($this->query->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->query->getType()) { // build sql expression $term[0] = $conn->quoteIdentifier($tableAlias) - . '.' . $conn->quoteIdentifier($term[0]); + .'.'.$conn->quoteIdentifier($term[0]); } else { // build sql expression $term[0] = $conn->quoteIdentifier($term[0]); @@ -159,7 +154,7 @@ public function parse($clause, $append = false) } } - if ( ! $found) { + if (!$found) { $term[0] = $this->query->getSqlAggregateAlias($term[0]); } } @@ -167,7 +162,7 @@ public function parse($clause, $append = false) } } - $str .= $term[0] . ($hasComma ? ',' : '') . $term[1]; + $str .= $term[0].($hasComma ? ',' : '').$term[1]; } return $str; diff --git a/lib/Doctrine/Query/Having.php b/lib/Doctrine/Query/Having.php index cb7308d74..c68f76775 100644 --- a/lib/Doctrine/Query/Having.php +++ b/lib/Doctrine/Query/Having.php @@ -20,75 +20,73 @@ */ /** - * Doctrine_Query_Having + * Doctrine_Query_Having. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7666 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Having extends Doctrine_Query_Condition { /** - * DQL Aggregate Function parser + * DQL Aggregate Function parser. * * @param string $func - * @return mixed */ private function parseAggregateFunction($func) { $pos = strpos($func, '('); // Check for subqueries - if ($pos === 0 && substr($func, 1, 6) == 'SELECT') { + if (0 === $pos && 'SELECT' == substr($func, 1, 6)) { // This code is taken from WHERE.php $sub = $this->_tokenizer->bracketTrim($func); $q = $this->query->createSubquery()->parseDqlQuery($sub, false); $sql = $q->getSqlQuery(); $q->free(); - return '(' . $sql . ')'; + + return '('.$sql.')'; } - if ($pos !== false) { - $funcs = array(); + if (false !== $pos) { + $funcs = array(); - $name = substr($func, 0, $pos); - $func = substr($func, ($pos + 1), -1); + $name = substr($func, 0, $pos); + $func = substr($func, $pos + 1, -1); $params = $this->_tokenizer->bracketExplode($func, ',', '(', ')'); foreach ($params as $k => $param) { $params[$k] = $this->parseAggregateFunction($param); } - $funcs = $name . '(' . implode(', ', $params) . ')'; - - return $funcs; - } else { - return $this->_parseAliases($func); + return $name.'('.implode(', ', $params).')'; } + + return $this->_parseAliases($func); } /** * _parseAliases - * Processes part of the query not being an aggregate function + * Processes part of the query not being an aggregate function. * - * @param mixed $value * @return string */ private function _parseAliases($value) { - if ( ! is_numeric($value)) { + if (!is_numeric($value)) { $a = explode('.', $value); if (count($a) > 1) { $field = array_pop($a); - $ref = implode('.', $a); - $map = $this->query->load($ref, false); + $ref = implode('.', $a); + $map = $this->query->load($ref, false); $field = $map['table']->getColumnName($field); - $value = $this->query->getConnection()->quoteIdentifier($this->query->getSqlTableAlias($ref) . '.' . $field); + $value = $this->query->getConnection()->quoteIdentifier($this->query->getSqlTableAlias($ref).'.'.$field); } else { $field = end($a); if ($this->query->hasSqlAggregateAlias($field)) { @@ -102,22 +100,23 @@ private function _parseAliases($value) /** * load - * returns the parsed query part + * returns the parsed query part. * * @param string $having + * * @return string */ final public function load($having) { $tokens = $this->_tokenizer->bracketExplode($having, ' ', '(', ')'); $part = $this->parseAggregateFunction(array_shift($tokens)); - $operator = array_shift($tokens); - $value = implode(' ', $tokens); + $operator = array_shift($tokens); + $value = implode(' ', $tokens); // check the RHS for aggregate functions $value = $this->parseAggregateFunction($value); - $part .= ' ' . $operator . ' ' . $value; + $part .= ' '.$operator.' '.$value; return $part; } diff --git a/lib/Doctrine/Query/JoinCondition.php b/lib/Doctrine/Query/JoinCondition.php index 9de41e3cb..66413bd79 100644 --- a/lib/Doctrine/Query/JoinCondition.php +++ b/lib/Doctrine/Query/JoinCondition.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Query_JoinCondition + * Doctrine_Query_JoinCondition. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_JoinCondition extends Doctrine_Query_Condition @@ -38,32 +39,32 @@ public function load($condition) $e = $this->_tokenizer->sqlExplode($condition); foreach ($e as $k => $v) { - if ( ! $v) { - unset($e[$k]); - } + if (!$v) { + unset($e[$k]); + } } $e = array_values($e); if (($l = count($e)) > 2) { $leftExpr = $this->query->parseClause($e[0]); - $operator = $e[1]; + $operator = $e[1]; - if ($l == 4) { + if (4 == $l) { // FIX: "field NOT IN (XXX)" issue // Related to ticket #1329 - $operator .= ' ' . $e[2]; // Glue "NOT" and "IN" + $operator .= ' '.$e[2]; // Glue "NOT" and "IN" $e[2] = $e[3]; // Move "(XXX)" to previous index unset($e[3]); // Remove unused index - } else if ($l >= 5) { + } elseif ($l >= 5) { // FIX: "field BETWEEN field2 AND field3" issue // Related to ticket #1488 - $e[2] .= ' ' . $e[3] . ' ' . $e[4]; + $e[2] .= ' '.$e[3].' '.$e[4]; unset($e[3], $e[4]); // Remove unused indexes } - if (substr(trim($e[2]), 0, 1) != '(') { + if ('(' != substr(trim($e[2]), 0, 1)) { $expr = new Doctrine_Expression($e[2], $this->query->getConnection()); $e[2] = $expr->getSql(); } @@ -75,20 +76,21 @@ public function load($condition) // Defining needed information $value = $e[2]; - if (substr($value, 0, 1) == '(') { + if ('(' == substr($value, 0, 1)) { // trim brackets - $trimmed = $this->_tokenizer->bracketTrim($value); + $trimmed = $this->_tokenizer->bracketTrim($value); $trimmed_upper = strtoupper($trimmed); - if (substr($trimmed_upper, 0, 4) == 'FROM' || substr($trimmed_upper, 0, 6) == 'SELECT') { + if ('FROM' == substr($trimmed_upper, 0, 4) || 'SELECT' == substr($trimmed_upper, 0, 6)) { // subquery found $q = $this->query->createSubquery() - ->parseDqlQuery($trimmed, false); - $value = '(' . $q->getSqlQuery() . ')'; + ->parseDqlQuery($trimmed, false) + ; + $value = '('.$q->getSqlQuery().')'; $q->free(); - } elseif (substr($trimmed_upper, 0, 4) == 'SQL:') { + } elseif ('SQL:' == substr($trimmed_upper, 0, 4)) { // Change due to bug "(" XXX ")" - //$value = '(' . substr($trimmed, 4) . ')'; + // $value = '(' . substr($trimmed, 4) . ')'; $value = substr($trimmed, 4); } else { // simple in expression found @@ -99,12 +101,12 @@ public function load($condition) $value[] = $this->parseLiteralValue($part); } - $value = '(' . implode(', ', $value) . ')'; + $value = '('.implode(', ', $value).')'; } - } elseif ( ! $hasRightAggExpression) { + } elseif (!$hasRightAggExpression) { // Possible expression found (field1 AND field2) // In relation to ticket #1488 - $e = $this->_tokenizer->bracketExplode($value, array(' AND ', ' \&\& '), '(', ')'); + $e = $this->_tokenizer->bracketExplode($value, array(' AND ', ' \&\& '), '(', ')'); $value = array(); foreach ($e as $part) { @@ -115,15 +117,13 @@ public function load($condition) } if ($hasRightAggExpression) { - $rightExpr = $rightMatches[1] . '(' . $value . ')' . $rightMatches[3]; + $rightExpr = $rightMatches[1].'('.$value.')'.$rightMatches[3]; $rightExpr = $this->query->parseClause($rightExpr); } else { $rightExpr = $value; } - $condition = $leftExpr . ' ' . $operator . ' ' . $rightExpr; - - return $condition; + return $leftExpr.' '.$operator.' '.$rightExpr; } $parser = new Doctrine_Query_Where($this->query, $this->_tokenizer); @@ -131,8 +131,7 @@ public function load($condition) return $parser->parse($condition); } - - protected function _processPossibleAggExpression(& $expr, & $matches = array()) + protected function _processPossibleAggExpression(&$expr, &$matches = array()) { $hasAggExpr = preg_match('/(.*[^\s\(\=])\(([^\)]*)\)(.*)/', $expr, $matches); @@ -140,18 +139,18 @@ protected function _processPossibleAggExpression(& $expr, & $matches = array()) $expr = $matches[2]; // We need to process possible comma separated items - if (substr(trim($matches[3]), 0, 1) == ',') { + if (',' == substr(trim($matches[3]), 0, 1)) { $xplod = $this->_tokenizer->sqlExplode(trim($matches[3], ' )'), ','); $matches[3] = array(); foreach ($xplod as $part) { - if ($part != '') { + if ('' != $part) { $matches[3][] = $this->parseLiteralValue($part); } } - $matches[3] = '), ' . implode(', ', $matches[3]); + $matches[3] = '), '.implode(', ', $matches[3]); } } diff --git a/lib/Doctrine/Query/Limit.php b/lib/Doctrine/Query/Limit.php index c6c97bfaa..f2094141e 100644 --- a/lib/Doctrine/Query/Limit.php +++ b/lib/Doctrine/Query/Limit.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Query_Limit + * Doctrine_Query_Limit. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1352 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Limit extends Doctrine_Query_Part { - public function parse($limit) + public function parse($limit) { return (int) $limit; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Offset.php b/lib/Doctrine/Query/Offset.php index 29deb7b91..c47dd6869 100644 --- a/lib/Doctrine/Query/Offset.php +++ b/lib/Doctrine/Query/Offset.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Query_Offset + * Doctrine_Query_Offset. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1352 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Offset extends Doctrine_Query_Part @@ -36,4 +37,4 @@ public function parse($offset) { return (int) $offset; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Orderby.php b/lib/Doctrine/Query/Orderby.php index 6853d9e9e..639c98193 100644 --- a/lib/Doctrine/Query/Orderby.php +++ b/lib/Doctrine/Query/Orderby.php @@ -20,24 +20,24 @@ */ /** - * Doctrine_Query_Orderby + * Doctrine_Query_Orderby. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Orderby extends Doctrine_Query_Part { /** * DQL ORDER BY PARSER - * parses the order by part of the query string + * parses the order by part of the query string. * * @param string $clause - * @return void */ public function parse($clause, $append = false) { @@ -48,19 +48,18 @@ public function parse($clause, $append = false) $pos = strpos($term[0], '('); $hasComma = false; - if ($pos !== false) { + if (false !== $pos) { $name = substr($term[0], 0, $pos); $term[0] = $this->query->parseFunctionExpression($term[0], array($this, 'parse')); } else { - if (substr($term[0], 0, 1) !== "'" && substr($term[0], -1) !== "'") { - - if (strpos($term[0], '.') !== false) { - if ( ! is_numeric($term[0])) { + if ("'" !== substr($term[0], 0, 1) && "'" !== substr($term[0], -1)) { + if (false !== strpos($term[0], '.')) { + if (!is_numeric($term[0])) { $e = explode('.', $term[0]); $field = array_pop($e); - + // Check if field name still has comma if (($pos = strpos($field, ',')) !== false) { $field = substr($field, 0, $pos); @@ -70,7 +69,7 @@ public function parse($clause, $append = false) // Grab query connection $conn = $this->query->getConnection(); - if ($this->query->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->query->getType()) { $componentAlias = implode('.', $e); if (empty($componentAlias)) { @@ -90,19 +89,19 @@ public function parse($clause, $append = false) $field = $table->getColumnName($field); // check column existence - if ( ! $def) { - throw new Doctrine_Query_Exception('Unknown column ' . $field); + if (!$def) { + throw new Doctrine_Query_Exception('Unknown column '.$field); } if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->query->getSqlTableAlias($componentAlias); // build sql expression - $term[0] = $conn->quoteIdentifier($tableAlias) . '.' . $conn->quoteIdentifier($field); - + $term[0] = $conn->quoteIdentifier($tableAlias).'.'.$conn->quoteIdentifier($field); + // driver specific modifications $term[0] = method_exists($conn, 'modifyOrderByColumn') ? $conn->modifyOrderByColumn($table, $field, $term[0]) : $term[0]; } else { @@ -112,22 +111,21 @@ public function parse($clause, $append = false) } } } else { - if ( ! empty($term[0]) && - ! is_numeric($term[0]) && - $term[0] !== '?' && substr($term[0], 0, 1) !== ':') { - + if (!empty($term[0]) + && !is_numeric($term[0]) + && '?' !== $term[0] && ':' !== substr($term[0], 0, 1)) { $componentAlias = $this->query->getRootAlias(); $found = false; - + // Check if field name still has comma if (($pos = strpos($term[0], ',')) !== false) { $term[0] = substr($term[0], 0, $pos); $hasComma = true; } - if ($componentAlias !== false && - $componentAlias !== null) { + if (false !== $componentAlias + && null !== $componentAlias) { $queryComponent = $this->query->getQueryComponent($componentAlias); $table = $queryComponent['table']; @@ -141,23 +139,22 @@ public function parse($clause, $append = false) // get the actual column name from field name $field = $table->getColumnName($term[0]); - if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->query->getSqlTableAlias($componentAlias); $conn = $this->query->getConnection(); - if ($this->query->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->query->getType()) { // build sql expression $term[0] = $conn->quoteIdentifier($tableAlias) - . '.' . $conn->quoteIdentifier($field); + .'.'.$conn->quoteIdentifier($field); } else { // build sql expression $term[0] = $conn->quoteIdentifier($field); } - + // driver specific modifications $term[0] = method_exists($conn, 'modifyOrderByColumn') ? $conn->modifyOrderByColumn($table, $field, $term[0]) : $term[0]; } else { @@ -165,10 +162,10 @@ public function parse($clause, $append = false) } } - if ( ! $found) { + if (!$found) { $tmp = strtoupper(trim($term[0], ', ')); - if ($tmp !== 'DESC' && $tmp !== 'ASC') { + if ('DESC' !== $tmp && 'ASC' !== $tmp) { $term[0] = $this->query->getSqlAggregateAlias($term[0]); } } @@ -177,7 +174,7 @@ public function parse($clause, $append = false) } } - $str .= $term[0] . ($hasComma ? ',' : '') . $term[1]; + $str .= $term[0].($hasComma ? ',' : '').$term[1]; } return $str; diff --git a/lib/Doctrine/Query/Parser.php b/lib/Doctrine/Query/Parser.php index 100bf299a..2d64bf707 100644 --- a/lib/Doctrine/Query/Parser.php +++ b/lib/Doctrine/Query/Parser.php @@ -20,16 +20,15 @@ */ /** - * Doctrine_Query_Parser + * Doctrine_Query_Parser. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ -class Doctrine_Query_Parser +class Doctrine_Query_Parser { - -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Part.php b/lib/Doctrine/Query/Part.php index 629ed2ad4..1d0293d78 100644 --- a/lib/Doctrine/Query/Part.php +++ b/lib/Doctrine/Query/Part.php @@ -20,33 +20,34 @@ */ /** - * Doctrine_Query_Part + * Doctrine_Query_Part. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Query_Part { /** - * @var Doctrine_Query $query the query object associated with this parser + * @var Doctrine_Query the query object associated with this parser */ protected $query; - + protected $_tokenizer; /** - * @param Doctrine_Query $query the query object associated with this parser + * @param Doctrine_Query $query the query object associated with this parser */ public function __construct($query, Doctrine_Query_Tokenizer $tokenizer = null) { $this->query = $query; - if ( ! $tokenizer) { + if (!$tokenizer) { $tokenizer = new Doctrine_Query_Tokenizer(); } $this->_tokenizer = $tokenizer; diff --git a/lib/Doctrine/Query/Registry.php b/lib/Doctrine/Query/Registry.php index 8a5245b4c..0d9f5d9f1 100644 --- a/lib/Doctrine/Query/Registry.php +++ b/lib/Doctrine/Query/Registry.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Query_Registry + * Doctrine_Query_Registry. * - * @package Doctrine - * @subpackage Query * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Query_Registry @@ -40,44 +40,44 @@ public function add($key, $query) $query = clone $query; } - if (strpos($key, '/') === false) { + if (false === strpos($key, '/')) { $this->_queries[$key] = $query; } else { // namespace found - + $e = explode('/', $key); $this->_queries[$e[0]][$e[1]] = $query; } } - + public function get($key, $namespace = null) { if (isset($namespace)) { - if ( ! isset($this->_queries[$namespace][$key])) { - throw new Doctrine_Query_Registry_Exception('A query with the name ' . $namespace . '/' . $key . ' does not exist.'); + if (!isset($this->_queries[$namespace][$key])) { + throw new Doctrine_Query_Registry_Exception('A query with the name '.$namespace.'/'.$key.' does not exist.'); } $query = $this->_queries[$namespace][$key]; } else { - if ( ! isset($this->_queries[$key])) { - throw new Doctrine_Query_Registry_Exception('A query with the name ' . $key . ' does not exist.'); + if (!isset($this->_queries[$key])) { + throw new Doctrine_Query_Registry_Exception('A query with the name '.$key.' does not exist.'); } $query = $this->_queries[$key]; } - - if ( ! ($query instanceof Doctrine_Query)) { + + if (!($query instanceof Doctrine_Query)) { $query = Doctrine_Query::create() - ->parseDqlQuery($query); + ->parseDqlQuery($query) + ; } - + return clone $query; } - - + public function has($key, $namespace = null) { - return isset($namespace) + return isset($namespace) ? isset($this->_queries[$namespace][$key]) : isset($this->_queries[$key]); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Registry/Exception.php b/lib/Doctrine/Query/Registry/Exception.php index 55042f7f7..354b2719d 100644 --- a/lib/Doctrine/Query/Registry/Exception.php +++ b/lib/Doctrine/Query/Registry/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Query_Exception + * Doctrine_Query_Exception. * - * @package Doctrine - * @subpackage Query * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Query_Registry_Exception extends Doctrine_Query_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Query/Select.php b/lib/Doctrine/Query/Select.php index 349c78400..8490feb61 100644 --- a/lib/Doctrine/Query/Select.php +++ b/lib/Doctrine/Query/Select.php @@ -20,19 +20,20 @@ */ /** - * Doctrine_Query_Select + * Doctrine_Query_Select. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Select extends Doctrine_Query_Part { - public function parse($dql) + public function parse($dql) { $this->query->parseSelect($dql); } diff --git a/lib/Doctrine/Query/Set.php b/lib/Doctrine/Query/Set.php index 5da9871ef..4e9d30344 100644 --- a/lib/Doctrine/Query/Set.php +++ b/lib/Doctrine/Query/Set.php @@ -20,87 +20,87 @@ */ /** - * Doctrine_Query + * Doctrine_Query. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Set extends Doctrine_Query_Part { public function parse($dql) { - $terms = $this->_tokenizer->sqlExplode($dql, ' '); + $terms = $this->_tokenizer->sqlExplode($dql, ' '); $termsTranslation = array(); - + foreach ($terms as $term) { - $termOriginal = $term; - - // We need to check for agg functions here + $termOriginal = $term; + + // We need to check for agg functions here $matches = array(); $hasAggExpression = $this->_processPossibleAggExpression($term, $matches); - $lftExpr = (($hasAggExpression) ? $matches[1] . '(' : ''); - $rgtExpr = (($hasAggExpression) ? $matches[3] . ')' : ''); - - preg_match_all("/^([a-zA-Z0-9_]+[\.[a-zA-Z0-9_]+]*)(\sAS\s[a-zA-Z0-9_]+)?/i", $term, $m, PREG_SET_ORDER); - + $lftExpr = (($hasAggExpression) ? $matches[1].'(' : ''); + $rgtExpr = (($hasAggExpression) ? $matches[3].')' : ''); + + preg_match_all('/^([a-zA-Z0-9_]+[\\.[a-zA-Z0-9_]+]*)(\\sAS\\s[a-zA-Z0-9_]+)?/i', $term, $m, PREG_SET_ORDER); + if (isset($m[0])) { $processed = array(); - + foreach ($m as $piece) { $part = $piece[1]; $e = explode('.', trim($part)); - $fieldName = array_pop($e); - $reference = (count($e) > 0) ? implode('.', $e) : $this->query->getRootAlias(); - $aliasMap = $this->query->getQueryComponent($reference); + $fieldName = array_pop($e); + $reference = (count($e) > 0) ? implode('.', $e) : $this->query->getRootAlias(); + $aliasMap = $this->query->getQueryComponent($reference); - if ($aliasMap['table']->hasField($fieldName)) { - $columnName = $aliasMap['table']->getColumnName($fieldName); + if ($aliasMap['table']->hasField($fieldName)) { + $columnName = $aliasMap['table']->getColumnName($fieldName); $columnName = $aliasMap['table']->getConnection()->quoteIdentifier($columnName); $part = $columnName; } - - $processed[] = $part . (isset($piece[2]) ? $piece[2] : ''); + + $processed[] = $part.(isset($piece[2]) ? $piece[2] : ''); } - - $termsTranslation[$termOriginal] = $lftExpr . implode(' ', $processed) . $rgtExpr; + + $termsTranslation[$termOriginal] = $lftExpr.implode(' ', $processed).$rgtExpr; } - } + } return strtr($dql, $termsTranslation); } - - protected function _processPossibleAggExpression(& $expr, & $matches = array()) + protected function _processPossibleAggExpression(&$expr, &$matches = array()) { $hasAggExpr = preg_match('/(.*[^\s\(\=])\(([^\)]*)\)(.*)/', $expr, $matches); - + if ($hasAggExpr) { $expr = $matches[2]; // We need to process possible comma separated items - if (substr(trim($matches[3]), 0, 1) == ',') { + if (',' == substr(trim($matches[3]), 0, 1)) { $xplod = $this->_tokenizer->sqlExplode(trim($matches[3], ' )'), ','); - + $matches[3] = array(); - + foreach ($xplod as $part) { - if ($part != '') { + if ('' != $part) { $matches[3][] = $this->parseLiteralValue($part); } } - $matches[3] = '), ' . implode(', ', $matches[3]); + $matches[3] = '), '.implode(', ', $matches[3]); } } - + return $hasAggExpr; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Tokenizer.php b/lib/Doctrine/Query/Tokenizer.php index aed58797d..a72a9aa41 100644 --- a/lib/Doctrine/Query/Tokenizer.php +++ b/lib/Doctrine/Query/Tokenizer.php @@ -20,24 +20,24 @@ */ /** - * Doctrine_Query_Tokenizer + * Doctrine_Query_Tokenizer. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Guilherme Blanco * @author Stefan Klug */ class Doctrine_Query_Tokenizer { - /** * Splits the given dql query into an array where keys represent different - * query part names and values are arrays splitted using sqlExplode method + * query part names and values are arrays splitted using sqlExplode method. * * example: * @@ -50,11 +50,11 @@ class Doctrine_Query_Tokenizer * 'where' => array('u.name', 'LIKE', '?') * ); * - * @param string $query DQL query + * @param string $query DQL query * - * @throws Doctrine_Query_Exception If some generic parsing error occurs + * @return array An array containing the query string parts * - * @return array An array containing the query string parts + * @throws Doctrine_Query_Exception If some generic parsing error occurs */ public function tokenizeQuery($query) { @@ -75,35 +75,33 @@ public function tokenizeQuery($query) case 'offset': case 'having': $p = $token; - //$parts[$token] = array(); + // $parts[$token] = array(); $parts[$token] = ''; - break; + break; case 'order': case 'group': $i = ($index + 1); - if (isset($tokens[$i]) && strtolower($tokens[$i]) === 'by') { + if (isset($tokens[$i]) && 'by' === strtolower($tokens[$i])) { $p = $token; $parts[$token] = ''; - //$parts[$token] = array(); + // $parts[$token] = array(); } else { - $parts[$p] .= "$token "; - //$parts[$p][] = $token; + $parts[$p] .= "{$token} "; + // $parts[$p][] = $token; } - break; + break; case 'by': break; default: - if ( ! isset($p)) { - throw new Doctrine_Query_Tokenizer_Exception( - "Couldn't tokenize query. Encountered invalid token: '$token'." - ); + if (!isset($p)) { + throw new Doctrine_Query_Tokenizer_Exception("Couldn't tokenize query. Encountered invalid token: '{$token}'."); } - $parts[$p] .= "$token "; - //$parts[$p][] = $token; + $parts[$p] .= "{$token} "; + // $parts[$p][] = $token; } } @@ -111,7 +109,7 @@ public function tokenizeQuery($query) } /** - * Trims brackets from string + * Trims brackets from string. * * @param string $str String to remove the brackets * @param string $e1 First bracket, usually '(' @@ -123,9 +121,9 @@ public function bracketTrim($str, $e1 = '(', $e2 = ')') { if (substr($str, 0, 1) === $e1 && substr($str, -1) === $e2) { return substr($str, 1, -1); - } else { - return $str; } + + return $str; } /** @@ -156,7 +154,7 @@ public function bracketExplode($str, $d = ' ', $e1 = '(', $e2 = ')') } // Bracket explode has to be case insensitive - $regexp = $this->getSplitRegExpFromArray($d) . 'i'; + $regexp = $this->getSplitRegExpFromArray($d).'i'; $terms = $this->clauseExplodeRegExp($str, $regexp, $e1, $e2); $res = array(); @@ -170,7 +168,7 @@ public function bracketExplode($str, $d = ' ', $e1 = '(', $e2 = ')') } /** - * Explode quotes from string + * Explode quotes from string. * * Note: quoteExplode always trims the returned pieces * @@ -195,7 +193,7 @@ public function quoteExplode($str, $d = ' ') } // According to the testcases quoteExplode is case insensitive - $regexp = $this->getSplitRegExpFromArray($d) . 'i'; + $regexp = $this->getSplitRegExpFromArray($d).'i'; $terms = $this->clauseExplodeCountBrackets($str, $regexp); $res = array(); @@ -209,7 +207,7 @@ public function quoteExplode($str, $d = ' ') /** * Explodes a string into array using custom brackets and - * quote delimeters + * quote delimeters. * * Note: sqlExplode trims all returned parts * @@ -255,7 +253,7 @@ public function sqlExplode($str, $d = ' ', $e1 = '(', $e2 = ')') /** * Explodes a string into array using custom brackets and quote delimeters * Each array element is a array of length 2 where the first entry contains - * the term, and the second entry contains the corresponding delimiter + * the term, and the second entry contains the corresponding delimiter. * * example: * @@ -291,9 +289,7 @@ public function clauseExplode($str, array $d, $e1 = '(', $e2 = ')') /** * Builds regular expression for split from array. Return regular - * expression to be applied - * - * @param $d + * expression to be applied. * * @return string */ @@ -302,7 +298,7 @@ private function getSplitRegExpFromArray(array $d) foreach ($d as $key => $string) { $escapedString = preg_quote($string); if (preg_match('#^\w+$#', $string)) { - $escapedString = "\W$escapedString\W"; + $escapedString = "\\W{$escapedString}\\W"; } $d[$key] = $escapedString; } @@ -311,16 +307,11 @@ private function getSplitRegExpFromArray(array $d) $d[] = '\s'; } - return '#(' . implode('|', $d) . ')#'; + return '#('.implode('|', $d).')#'; } /** - * Same as clauseExplode, but you give a regexp, which splits the string - * - * @param $str - * @param $regexp - * @param $e1 - * @param $e2 + * Same as clauseExplode, but you give a regexp, which splits the string. * * @return array */ @@ -330,7 +321,7 @@ private function clauseExplodeRegExp($str, $regexp, $e1 = '(', $e2 = ')') $terms = $this->mergeBracketTerms($terms); // This is only here to comply with the old function signature - foreach ($terms as & $val) { + foreach ($terms as &$val) { unset($val[2]); } @@ -338,12 +329,7 @@ private function clauseExplodeRegExp($str, $regexp, $e1 = '(', $e2 = ')') } /** - * this function is like clauseExplode, but it doesn't merge bracket terms - * - * @param $str - * @param $d - * @param $e1 - * @param $e2 + * this function is like clauseExplode, but it doesn't merge bracket terms. * * @return unknown_type */ @@ -355,13 +341,13 @@ private function clauseExplodeCountBrackets($str, $regexp, $e1 = '(', $e2 = ')') foreach ($quoteTerms as $key => $val) { if ($key & 1) { // a quoted string - // If the last term had no ending delimiter, we append the string to the element, - // otherwise, we create a new element without delimiter - if ($terms[$i - 1][1] == '') { - $terms[$i - 1][0] .= $val; - } else { - $terms[$i++] = array($val, '', 0); - } + // If the last term had no ending delimiter, we append the string to the element, + // otherwise, we create a new element without delimiter + if ('' == $terms[$i - 1][1]) { + $terms[$i - 1][0] .= $val; + } else { + $terms[$i++] = array($val, '', 0); + } } else { // Not a quoted string // Do the clause explode $subterms = $this->clauseExplodeNonQuoted($val, $regexp); @@ -374,7 +360,7 @@ private function clauseExplodeCountBrackets($str, $regexp, $e1 = '(', $e2 = ')') } // If the previous term had no delimiter, merge them - if ($i > 0 && $terms[$i - 1][1] == '') { + if ($i > 0 && '' == $terms[$i - 1][1]) { $first = array_shift($subterms); $idx = $i - 1; @@ -399,7 +385,7 @@ private function clauseExplodeCountBrackets($str, $regexp, $e1 = '(', $e2 = ')') * [0] = the term itself * [1] = the delimiter splitting this term from the next * [2] = the sum of opening and closing brackets in this term - * (eg. -2 means 2 closing brackets (or 1 opening and 3 closing)) + * (eg. -2 means 2 closing brackets (or 1 opening and 3 closing)). * * example: * @@ -415,11 +401,6 @@ private function clauseExplodeCountBrackets($str, $regexp, $e1 = '(', $e2 = ')') * array("d))'", '', -2) * ); * - * @param $str - * @param $d - * @param $e1 - * @param $e2 - * * @return array */ private function clauseExplodeNonQuoted($str, $regexp) @@ -430,7 +411,7 @@ private function clauseExplodeNonQuoted($str, $regexp) foreach ($str as $key => $val) { // Every odd entry is a delimiter, so add it to the previous term entry - if ( ! ($key & 1)) { + if (!($key & 1)) { $term[$i] = array($val, ''); } else { $term[$i++][1] = $val; @@ -446,7 +427,7 @@ private function clauseExplodeNonQuoted($str, $regexp) * unbalanced bracket count. * Note that only the third parameter in each term is used to get the * bracket overhang. This is needed to be able to handle quoted strings - * wich contain brackets + * wich contain brackets. * * example: * @@ -475,26 +456,25 @@ private function mergeBracketTerms(array $terms) $i = 0; foreach ($terms as $val) { - if ( ! isset($res[$i])) { + if (!isset($res[$i])) { $res[$i] = array($val[0], $val[1], $val[2]); } else { - $res[$i][0] .= $res[$i][1] . $val[0]; + $res[$i][0] .= $res[$i][1].$val[0]; $res[$i][1] = $val[1]; $res[$i][2] += $val[2]; } // Bracket overhang - if ($res[$i][2] == 0) { - $i++; + if (0 == $res[$i][2]) { + ++$i; } } return $res; } - /** - * Explodes the given string by + * Explodes the given string by . * * example: * @@ -513,11 +493,11 @@ private function mergeBracketTerms(array $terms) public function quotedStringExplode($str) { // Split by all possible incarnations of a quote - $split = array("\\'","''","'", "\\\"", "\"\"", "\""); + $split = array("\\'", "''", "'", '\\"', '""', '"'); foreach ($split as &$v) { $v = preg_quote($v); } - $split = '#(' . implode('|', $split) . ')#'; + $split = '#('.implode('|', $split).')#'; $str = preg_split($split, $str, -1, PREG_SPLIT_DELIM_CAPTURE); $parts = array(); @@ -527,26 +507,26 @@ public function quotedStringExplode($str) foreach ($str as $key => $val) { // This is some kind of quote if ($key & 1) { - if ( ! $mode) { - if ($val == "'" || $val == "\"") { + if (!$mode) { + if ("'" == $val || '"' == $val) { $mode = $val; - $i++; + ++$i; } - } else if ($mode == $val) { - if ( ! isset($parts[$i])) { + } elseif ($mode == $val) { + if (!isset($parts[$i])) { $parts[$i] = $val; } else { $parts[$i] .= $val; } $mode = false; - $i++; + ++$i; continue; } } - if ( ! isset($parts[$i])) { + if (!isset($parts[$i])) { $parts[$i] = $val; } else { $parts[$i] .= $val; diff --git a/lib/Doctrine/Query/Tokenizer/Exception.php b/lib/Doctrine/Query/Tokenizer/Exception.php index a658ce061..b4e46d647 100644 --- a/lib/Doctrine/Query/Tokenizer/Exception.php +++ b/lib/Doctrine/Query/Tokenizer/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Query_Exception + * Doctrine_Query_Exception. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2702 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Tokenizer_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Query/Where.php b/lib/Doctrine/Query/Where.php index 554d6751f..bc6e20c60 100644 --- a/lib/Doctrine/Query/Where.php +++ b/lib/Doctrine/Query/Where.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Query_Where + * Doctrine_Query_Where. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7672 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Where extends Doctrine_Query_Condition @@ -37,19 +38,19 @@ public function load($where) // Handle operator ("AND" | "OR"), reducing overhead of this method processment $possibleOp = strtolower($where); - if ($possibleOp == 'and' || $possibleOp == 'or') - { + if ('and' == $possibleOp || 'or' == $possibleOp) { return $where; } $where = $this->_tokenizer->bracketTrim(trim($where)); - $conn = $this->query->getConnection(); + $conn = $this->query->getConnection(); $terms = $this->_tokenizer->sqlExplode($where); if (count($terms) > 1) { - if (substr($where, 0, 6) == 'EXISTS') { + if ('EXISTS' == substr($where, 0, 6)) { return $this->parseExists($where, true); - } elseif (preg_match('/^NOT\s+EXISTS\b/i', $where) !== 0) { + } + if (0 !== preg_match('/^NOT\s+EXISTS\b/i', $where)) { return $this->parseExists($where, false); } } @@ -63,7 +64,7 @@ public function load($where) $rightExpr = array_pop($terms); $operator = trim(substr($where, strlen($leftExpr), -strlen($rightExpr))); - if (strpos($leftExpr, "'") === false && strpos($leftExpr, '(') === false) { + if (false === strpos($leftExpr, "'") && false === strpos($leftExpr, '(')) { // normal field reference found $a = explode('.', $leftExpr); $fieldname = array_pop($a); // Discard the field name (not needed!) @@ -81,7 +82,7 @@ public function load($where) // @TODO apply database dependent parsing // list($leftExpr, $operator, $rightExpr) = $conn->modifyWhereCondition($leftExpr, $operator, $rightExpr); $driverName = strtolower($conn->getDriverName()); - if ($driverName == 'mssql' && !empty($reference)) { + if ('mssql' == $driverName && !empty($reference)) { $cmp = $this->query->getQueryComponent($reference); $table = $cmp['table']; @@ -89,20 +90,17 @@ public function load($where) $column = $table->getColumnName($fieldname); $columndef = $table->getColumnDefinition($column); - if ($columndef['type'] == 'string' && ($columndef['length'] == NULL || $columndef['length'] > $conn->varchar_max_length) && strtoupper($rightExpr) != 'NULL') { + if ('string' == $columndef['type'] && (null == $columndef['length'] || $columndef['length'] > $conn->varchar_max_length) && 'NULL' != strtoupper($rightExpr)) { $operator = 'LIKE'; } } } - $sql = $this->_buildSql($leftExpr, $operator, $rightExpr); - - return $sql; - } else { - return $where; + return $this->_buildSql($leftExpr, $operator, $rightExpr); } - } + return $where; + } protected function _buildSql($leftExpr, $operator, $rightExpr) { @@ -112,41 +110,37 @@ protected function _buildSql($leftExpr, $operator, $rightExpr) // BETWEEN operation if ('BETWEEN' == strtoupper(substr($operator, 0, 7))) { $midExpr = trim(substr($operator, 7, -3)); - $operator = 'BETWEEN ' . $this->query->parseClause($midExpr) . ' AND'; + $operator = 'BETWEEN '.$this->query->parseClause($midExpr).' AND'; } // NOT BETWEEN operation if ('NOT BETWEEN' == strtoupper(substr($operator, 0, 11))) { $midExpr = trim(substr($operator, 11, -3)); - $operator = 'NOT BETWEEN ' . $this->query->parseClause($midExpr) . ' AND'; + $operator = 'NOT BETWEEN '.$this->query->parseClause($midExpr).' AND'; } $op = strtolower($operator); - $isInX = ($op == 'in' || $op == 'not in'); + $isInX = ('in' == $op || 'not in' == $op); // Check if we are not dealing with "obj.field IN :named" - if (substr($rightExpr, 0 , 1) == ':' && $isInX) { - throw new Doctrine_Query_Exception( - 'Cannot use ' . $operator . ' with a named parameter in "' . - $leftExprOriginal . ' ' . $operator . ' ' . $rightExpr . '"' - ); + if (':' == substr($rightExpr, 0, 1) && $isInX) { + throw new Doctrine_Query_Exception('Cannot use '.$operator.' with a named parameter in "'.$leftExprOriginal.' '.$operator.' '.$rightExpr.'"'); } // Right Expression - $rightExpr = ($rightExpr == '?' && $isInX) + $rightExpr = ('?' == $rightExpr && $isInX) ? $this->_buildWhereInArraySqlPart($rightExpr) : $this->query->parseClause($rightExpr); - return $leftExpr . ' ' . $operator . ' ' . $rightExpr; + return $leftExpr.' '.$operator.' '.$rightExpr; } - protected function _buildWhereInArraySqlPart($rightExpr) { $params = $this->query->getInternalParams(); $value = array(); - for ($i = 0, $l = count($params); $i < $l; $i++) { + for ($i = 0, $l = count($params); $i < $l; ++$i) { if (is_array($params[$i])) { $value = array_fill(0, count($params[$i]), $rightExpr); $this->query->adjustProcessedParam($i); @@ -155,14 +149,15 @@ protected function _buildWhereInArraySqlPart($rightExpr) } } - return '(' . (count($value) > 0 ? implode(', ', $value) : $rightExpr) . ')'; + return '('.(count($value) > 0 ? implode(', ', $value) : $rightExpr).')'; } /** - * parses an EXISTS expression + * parses an EXISTS expression. + * + * @param string $where query where part to be parsed + * @param bool $negation whether or not to use the NOT keyword * - * @param string $where query where part to be parsed - * @param boolean $negation whether or not to use the NOT keyword * @return string */ public function parseExists($where, $negation) @@ -171,7 +166,7 @@ public function parseExists($where, $negation) $pos = strpos($where, '('); - if ($pos == false) { + if (false == $pos) { throw new Doctrine_Query_Exception('Unknown expression, expected a subquery with () -marks'); } @@ -181,6 +176,6 @@ public function parseExists($where, $negation) $sql = $q->getSqlQuery(); $q->free(); - return $operator . ' (' . $sql . ')'; + return $operator.' ('.$sql.')'; } } diff --git a/lib/Doctrine/RawSql.php b/lib/Doctrine/RawSql.php index 73220e2e9..8488201c4 100644 --- a/lib/Doctrine/RawSql.php +++ b/lib/Doctrine/RawSql.php @@ -20,7 +20,7 @@ */ /** - * Doctrine_RawSql + * Doctrine_RawSql. * * Doctrine_RawSql is an implementation of Doctrine_Query_Abstract that skips the entire * DQL parsing procedure. The "DQL" that is passed to a RawSql query object for execution @@ -28,28 +28,30 @@ * in a RawSql query is the SELECT part, which has a special syntax that provides Doctrine * with the necessary information to properly hydrate the query results. * - * @package Doctrine - * @subpackage RawSql * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_RawSql extends Doctrine_Query_Abstract { /** - * @var array $fields + * @var array */ private $fields = array(); /** * Constructor. * - * @param Doctrine_Connection The connection object the query will use. - * @param Doctrine_Hydrator_Abstract The hydrator that will be used for generating result sets. + * @param Doctrine_Connection the connection object the query will use + * @param Doctrine_Hydrator_Abstract the hydrator that will be used for generating result sets */ - function __construct(Doctrine_Connection $connection = null, Doctrine_Hydrator_Abstract $hydrator = null) { + public function __construct(Doctrine_Connection $connection = null, Doctrine_Hydrator_Abstract $hydrator = null) + { parent::__construct($connection, $hydrator); // Fix #1472. It's alid to disable QueryCache since there's no DQL for RawSql. @@ -71,31 +73,34 @@ protected function clear() * the user of the RawSql query is responsible for writing SQL that is portable between * different DBMS. * - * @param string $queryPartName the name of the query part - * @param string $queryPart query part to be parsed - * @param boolean $append whether or not to append the query part to its stack - * if false is given, this method will overwrite - * the given query part stack with $queryPart - * @return Doctrine_Query this object + * @param string $queryPartName the name of the query part + * @param string $queryPart query part to be parsed + * @param bool $append whether or not to append the query part to its stack + * if false is given, this method will overwrite + * the given query part stack with $queryPart + * + * @return Doctrine_Query this object */ - public function parseDqlQueryPart($queryPartName, $queryPart, $append = false) + public function parseDqlQueryPart($queryPartName, $queryPart, $append = false) { - if ($queryPartName == 'select') { - $this->_parseSelectFields($queryPart); - return $this; - } - if ( ! isset($this->_sqlParts[$queryPartName])) { - $this->_sqlParts[$queryPartName] = array(); - } - - if ( ! $append) { - $this->_sqlParts[$queryPartName] = array($queryPart); - } else { - $this->_sqlParts[$queryPartName][] = $queryPart; - } - return $this; + if ('select' == $queryPartName) { + $this->_parseSelectFields($queryPart); + + return $this; + } + if (!isset($this->_sqlParts[$queryPartName])) { + $this->_sqlParts[$queryPartName] = array(); + } + + if (!$append) { + $this->_sqlParts[$queryPartName] = array($queryPart); + } else { + $this->_sqlParts[$queryPartName][] = $queryPart; + } + + return $this; } - + /** * Adds a DQL query part. Overrides Doctrine_Query_Abstract::_addDqlQueryPart(). * This implementation for RawSql parses the new parts right away, generating the SQL. @@ -104,7 +109,7 @@ protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false) { return $this->parseDqlQueryPart($queryPartName, $queryPart, $append); } - + /** * Add select parts to fields. * @@ -116,7 +121,7 @@ private function _parseSelectFields($queryPart) $this->fields = $m[1]; $this->_sqlParts['select'] = array(); } - + /** * parseDqlQuery * parses an sql query and adds the parts to internal array. @@ -124,8 +129,9 @@ private function _parseSelectFields($queryPart) * This implementation simply tokenizes the provided query string and uses them * as SQL parts right away. * - * @param string $query query to be parsed - * @return Doctrine_RawSql this object + * @param string $query query to be parsed + * + * @return Doctrine_RawSql this object */ public function parseDqlQuery($query) { @@ -145,30 +151,30 @@ public function parseDqlQuery($query) case 'offset': case 'having': $type = $partLowerCase; - if ( ! isset($parts[$partLowerCase])) { + if (!isset($parts[$partLowerCase])) { $parts[$partLowerCase] = array(); } break; case 'order': case 'group': $i = $key + 1; - if (isset($tokens[$i]) && strtolower($tokens[$i]) === 'by') { - $type = $partLowerCase . 'by'; + if (isset($tokens[$i]) && 'by' === strtolower($tokens[$i])) { + $type = $partLowerCase.'by'; $parts[$type] = array(); } else { - //not a keyword so we add it to the previous type + // not a keyword so we add it to the previous type $parts[$type][] = $part; } break; case 'by': break; default: - //not a keyword so we add it to the previous type. - if ( ! isset($parts[$type][0])) { + // not a keyword so we add it to the previous type. + if (!isset($parts[$type][0])) { $parts[$type][0] = $part; } else { // why does this add to index 0 and not append to the - // array. If it had done that one could have used + // array. If it had done that one could have used // parseQueryPart. $parts[$type][0] .= ' '.$part; } @@ -185,10 +191,10 @@ public function parseDqlQuery($query) * getSqlQuery * builds the sql query. * - * @return string the built sql query + * @return string the built sql query */ public function getSqlQuery($params = array()) - { + { // Assign building/execution specific params $this->_params['exec'] = $params; @@ -199,47 +205,47 @@ public function getSqlQuery($params = array()) $this->fixArrayParameterValues($this->_execParams); $select = array(); - + $formatter = $this->getConnection()->formatter; foreach ($this->fields as $field) { $e = explode('.', $field); - if ( ! isset($e[1])) { + if (!isset($e[1])) { throw new Doctrine_RawSql_Exception('All selected fields in Sql query must be in format tableAlias.fieldName'); } // try to auto-add component - if ( ! $this->hasSqlTableAlias($e[0])) { + if (!$this->hasSqlTableAlias($e[0])) { try { $this->addComponent($e[0], ucwords($e[0])); } catch (Doctrine_Exception $exception) { - throw new Doctrine_RawSql_Exception('The associated component for table alias ' . $e[0] . ' couldn\'t be found.'); + throw new Doctrine_RawSql_Exception('The associated component for table alias '.$e[0].' couldn\'t be found.'); } } $componentAlias = $this->getComponentAlias($e[0]); - - if ($e[1] == '*') { + + if ('*' == $e[1]) { foreach ($this->_queryComponents[$componentAlias]['table']->getColumnNames() as $name) { - $field = $formatter->quoteIdentifier($e[0]) . '.' . $formatter->quoteIdentifier($name); + $field = $formatter->quoteIdentifier($e[0]).'.'.$formatter->quoteIdentifier($name); - $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($e[0] . '__' . $name); + $select[$componentAlias][$field] = $field.' AS '.$formatter->quoteIdentifier($e[0].'__'.$name); } } else { - $field = $formatter->quoteIdentifier($e[0]) . '.' . $formatter->quoteIdentifier($e[1]); - $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($e[0] . '__' . $e[1]); + $field = $formatter->quoteIdentifier($e[0]).'.'.$formatter->quoteIdentifier($e[1]); + $select[$componentAlias][$field] = $field.' AS '.$formatter->quoteIdentifier($e[0].'__'.$e[1]); } } // force-add all primary key fields - if ( ! isset($this->_sqlParts['distinct']) || $this->_sqlParts['distinct'] != true) { + if (!isset($this->_sqlParts['distinct']) || true != $this->_sqlParts['distinct']) { foreach ($this->getTableAliasMap() as $tableAlias => $componentAlias) { $map = $this->_queryComponents[$componentAlias]; foreach ((array) $map['table']->getIdentifierColumnNames() as $key) { - $field = $formatter->quoteIdentifier($tableAlias) . '.' . $formatter->quoteIdentifier($key); + $field = $formatter->quoteIdentifier($tableAlias).'.'.$formatter->quoteIdentifier($key); - if ( ! isset($this->_sqlParts['select'][$field])) { - $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($tableAlias . '__' . $key); + if (!isset($this->_sqlParts['select'][$field])) { + $select[$componentAlias][$field] = $field.' AS '.$formatter->quoteIdentifier($tableAlias.'__'.$key); } } } @@ -247,55 +253,56 @@ public function getSqlQuery($params = array()) $q = 'SELECT '; - if (isset($this->_sqlParts['distinct']) && $this->_sqlParts['distinct'] == true) { + if (isset($this->_sqlParts['distinct']) && true == $this->_sqlParts['distinct']) { $q .= 'DISTINCT '; } // first add the fields of the root component reset($this->_queryComponents); $componentAlias = key($this->_queryComponents); - + $this->_rootAlias = $componentAlias; $q .= implode(', ', $select[$componentAlias]); unset($select[$componentAlias]); foreach ($select as $component => $fields) { - if ( ! empty($fields)) { - $q .= ', ' . implode(', ', $fields); + if (!empty($fields)) { + $q .= ', '.implode(', ', $fields); } } $string = $this->getInheritanceCondition($this->getRootAlias()); - if ( ! empty($string)) { + if (!empty($string)) { $this->_sqlParts['where'][] = $string; } - $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : ''; - $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : ''; - $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : ''; - $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : ''; - $q .= ( ! empty($this->_sqlParts['orderby']))? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : ''; - $q .= ( ! empty($this->_sqlParts['limit']))? ' LIMIT ' . implode(' ', $this->_sqlParts['limit']) : ''; - $q .= ( ! empty($this->_sqlParts['offset']))? ' OFFSET ' . implode(' ', $this->_sqlParts['offset']) : ''; + $q .= (!empty($this->_sqlParts['from'])) ? ' FROM '.implode(' ', $this->_sqlParts['from']) : ''; + $q .= (!empty($this->_sqlParts['where'])) ? ' WHERE '.implode(' AND ', $this->_sqlParts['where']) : ''; + $q .= (!empty($this->_sqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_sqlParts['groupby']) : ''; + $q .= (!empty($this->_sqlParts['having'])) ? ' HAVING '.implode(' AND ', $this->_sqlParts['having']) : ''; + $q .= (!empty($this->_sqlParts['orderby'])) ? ' ORDER BY '.implode(', ', $this->_sqlParts['orderby']) : ''; + $q .= (!empty($this->_sqlParts['limit'])) ? ' LIMIT '.implode(' ', $this->_sqlParts['limit']) : ''; + $q .= (!empty($this->_sqlParts['offset'])) ? ' OFFSET '.implode(' ', $this->_sqlParts['offset']) : ''; - if ( ! empty($string)) { + if (!empty($string)) { array_pop($this->_sqlParts['where']); } + return $q; } - /** + /** * getCountQuery * builds the count query. * - * @return string the built sql query + * @return string the built sql query */ - public function getCountSqlQuery($params = array()) + public function getCountSqlQuery($params = array()) { - //Doing COUNT( DISTINCT rootComponent.id ) - //This is not correct, if the result is not hydrated by doctrine, but it mimics the behaviour of Doctrine_Query::getCountQuery + // Doing COUNT( DISTINCT rootComponent.id ) + // This is not correct, if the result is not hydrated by doctrine, but it mimics the behaviour of Doctrine_Query::getCountQuery reset($this->_queryComponents); $componentAlias = key($this->_queryComponents); @@ -305,33 +312,33 @@ public function getCountSqlQuery($params = array()) $fields = array(); foreach ((array) $this->_queryComponents[$componentAlias]['table']->getIdentifierColumnNames() as $key) { - $fields[] = $tableAlias . '.' . $key; + $fields[] = $tableAlias.'.'.$key; } - $q = 'SELECT COUNT(*) as num_results FROM (SELECT DISTINCT '.implode(', ',$fields); + $q = 'SELECT COUNT(*) as num_results FROM (SELECT DISTINCT '.implode(', ', $fields); $string = $this->getInheritanceCondition($this->getRootAlias()); - if ( ! empty($string)) { + if (!empty($string)) { $this->_sqlParts['where'][] = $string; } - $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : ''; - $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : ''; - $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : ''; - $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : ''; + $q .= (!empty($this->_sqlParts['from'])) ? ' FROM '.implode(' ', $this->_sqlParts['from']) : ''; + $q .= (!empty($this->_sqlParts['where'])) ? ' WHERE '.implode(' AND ', $this->_sqlParts['where']) : ''; + $q .= (!empty($this->_sqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_sqlParts['groupby']) : ''; + $q .= (!empty($this->_sqlParts['having'])) ? ' HAVING '.implode(' AND ', $this->_sqlParts['having']) : ''; $q .= ') as results'; - if ( ! empty($string)) { + if (!empty($string)) { array_pop($this->_sqlParts['where']); } return $q; } - /** + /** * count - * fetches the count of the query + * fetches the count of the query. * * This method executes the main query without all the * selected fields, ORDER BY part, LIMIT part and OFFSET part. @@ -339,8 +346,10 @@ public function getCountSqlQuery($params = array()) * This is an exact copy of the Dql Version * * @see Doctrine_Query::count() - * @param array $params an array of prepared statement parameters - * @return integer the count of this query + * + * @param array $params an array of prepared statement parameters + * + * @return int the count of this query */ public function count($params = array()) { @@ -364,9 +373,9 @@ public function count($params = array()) /** * getFields - * returns the fields associated with this parser + * returns the fields associated with this parser. * - * @return array all the fields associated with this parser + * @return array all the fields associated with this parser */ public function getFields() { @@ -374,15 +383,15 @@ public function getFields() } /** - * addComponent + * addComponent. * * @param string $tableAlias - * @param string $componentName + * * @return Doctrine_RawSql */ public function addComponent($tableAlias, $path) { - $tmp = explode(' ', $path); + $tmp = explode(' ', $path); $originalAlias = (count($tmp) > 1) ? end($tmp) : null; $e = explode('.', $tmp[0]); @@ -405,7 +414,7 @@ public function addComponent($tableAlias, $path) $length = strlen($currPath); // build the current component path - $currPath = ($currPath) ? $currPath . '.' . $component : $component; + $currPath = ($currPath) ? $currPath.'.'.$component : $component; $delimeter = substr($fullPath, $length, 1); @@ -415,18 +424,19 @@ public function addComponent($tableAlias, $path) } else { $componentAlias = $currPath; } - if ( ! isset($table)) { + if (!isset($table)) { $conn = Doctrine_Manager::getInstance() - ->getConnectionForComponent($component); - + ->getConnectionForComponent($component) + ; + $table = $conn->getTable($component); $this->_queryComponents[$componentAlias] = array('table' => $table); } else { $relation = $table->getRelation($component); - $this->_queryComponents[$componentAlias] = array('table' => $relation->getTable(), - 'parent' => $parent, - 'relation' => $relation); + $this->_queryComponents[$componentAlias] = array('table' => $relation->getTable(), + 'parent' => $parent, + 'relation' => $relation); } $this->addSqlTableAlias($tableAlias, $componentAlias); @@ -438,17 +448,18 @@ public function addComponent($tableAlias, $path) /** * calculateResultCacheHash - * calculate hash key for result cache + * calculate hash key for result cache. * * @param array $params - * @return string the hash + * + * @return string the hash */ public function calculateResultCacheHash($params = array()) { $sql = $this->getSqlQuery(); $conn = $this->getConnection(); $params = $this->getFlattenedParams($params); - $hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $sql . var_export($params, true)); - return $hash; + + return md5($this->_hydrator->getHydrationMode().$conn->getName().$conn->getOption('dsn').$sql.var_export($params, true)); } } diff --git a/lib/Doctrine/RawSql/Exception.php b/lib/Doctrine/RawSql/Exception.php index a53bd400b..82662d5c6 100644 --- a/lib/Doctrine/RawSql/Exception.php +++ b/lib/Doctrine/RawSql/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_RawSql_Exception + * Doctrine_RawSql_Exception. * - * @package Doctrine - * @subpackage RawSql * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_RawSql_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Record.php b/lib/Doctrine/Record.php index 2a2d92c06..89a3917b0 100644 --- a/lib/Doctrine/Record.php +++ b/lib/Doctrine/Record.php @@ -21,82 +21,81 @@ /** * Doctrine_Record - * All record classes should inherit this super class + * All record classes should inherit this super class. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7673 $ */ abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Countable, IteratorAggregate, Serializable { /** - * STATE CONSTANTS + * STATE CONSTANTS. */ /** * DIRTY STATE - * a Doctrine_Record is in dirty state when its properties are changed + * a Doctrine_Record is in dirty state when its properties are changed. */ - const STATE_DIRTY = 1; + public const STATE_DIRTY = 1; /** * TDIRTY STATE * a Doctrine_Record is in transient dirty state when it is created - * and some of its fields are modified but it is NOT yet persisted into database + * and some of its fields are modified but it is NOT yet persisted into database. */ - const STATE_TDIRTY = 2; + public const STATE_TDIRTY = 2; /** * CLEAN STATE * a Doctrine_Record is in clean state when all of its properties are loaded from the database - * and none of its properties are changed + * and none of its properties are changed. */ - const STATE_CLEAN = 3; + public const STATE_CLEAN = 3; /** * PROXY STATE - * a Doctrine_Record is in proxy state when its properties are not fully loaded + * a Doctrine_Record is in proxy state when its properties are not fully loaded. */ - const STATE_PROXY = 4; + public const STATE_PROXY = 4; /** * NEW TCLEAN - * a Doctrine_Record is in transient clean state when it is created and none of its fields are modified + * a Doctrine_Record is in transient clean state when it is created and none of its fields are modified. */ - const STATE_TCLEAN = 5; + public const STATE_TCLEAN = 5; /** * LOCKED STATE - * a Doctrine_Record is temporarily locked during deletes and saves + * a Doctrine_Record is temporarily locked during deletes and saves. * * This state is used internally to ensure that circular deletes * and saves will not cause infinite loops */ - const STATE_LOCKED = 6; - - /** - * TLOCKED STATE - * a Doctrine_Record is temporarily locked (and transient) during deletes and saves - * - * This state is used internally to ensure that circular deletes - * and saves will not cause infinite loops - */ - const STATE_TLOCKED = 7; + public const STATE_LOCKED = 6; + /** + * TLOCKED STATE + * a Doctrine_Record is temporarily locked (and transient) during deletes and saves. + * + * This state is used internally to ensure that circular deletes + * and saves will not cause infinite loops + */ + public const STATE_TLOCKED = 7; /** - * @var Doctrine_Node_ node object + * @var Doctrine_Node_ node object */ protected $_node; /** - * @var integer $_id the primary keys of this object + * @var int the primary keys of this object */ - protected $_id = array(); + protected $_id = array(); /** * each element is one of 3 following types: @@ -104,115 +103,117 @@ abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Count * - null - field has NULL value in DB * - Doctrine_Null - field value is unknown, it wasn't loaded yet * - * @var array $_data the record data + * @var array the record data */ - protected $_data = array(); + protected $_data = array(); /** - * @var array $_values the values array, aggregate values and such are mapped into this array + * @var array the values array, aggregate values and such are mapped into this array */ - protected $_values = array(); + protected $_values = array(); /** - * @var integer $_state the state of this record + * @var int the state of this record + * * @see STATE_* constants */ protected $_state; /** - * @var array $_lastModified an array containing field names that were modified in the previous transaction + * @var array an array containing field names that were modified in the previous transaction */ protected $_lastModified = array(); /** - * @var array $_modified an array containing field names that have been modified + * @var array an array containing field names that have been modified + * * @todo Better name? $_modifiedFields? */ - protected $_modified = array(); + protected $_modified = array(); /** - * @var array $_oldValues an array of the old values from set properties + * @var array an array of the old values from set properties */ - protected $_oldValues = array(); + protected $_oldValues = array(); /** - * @var Doctrine_Validator_ErrorStack error stack object + * @var Doctrine_Validator_ErrorStack error stack object */ protected $_errorStack; /** - * @var array $_references an array containing all the references + * @var array an array containing all the references */ - protected $_references = array(); + protected $_references = array(); /** - * Doctrine_Collection of objects needing to be deleted on save + * Doctrine_Collection of objects needing to be deleted on save. * * @var string */ protected $_pendingDeletes = array(); /** - * Array of pending un links in format alias => keys to be executed after save + * Array of pending un links in format alias => keys to be executed after save. * - * @var array $_pendingUnlinks + * @var array */ protected $_pendingUnlinks = array(); /** - * Array of custom accessors for cache + * Array of custom accessors for cache. * * @var array */ protected static $_customAccessors = array(); /** - * Array of custom mutators for cache + * Array of custom mutators for cache. * * @var array */ protected static $_customMutators = array(); /** - * Whether or not to serialize references when a Doctrine_Record is serialized + * Whether or not to serialize references when a Doctrine_Record is serialized. * - * @var boolean + * @var bool */ protected $_serializeReferences = false; /** - * Array containing the save hooks and events that have been invoked + * Array containing the save hooks and events that have been invoked. * * @var array */ protected $_invokedSaveHooks = array(); /** - * @var integer $index this index is used for creating object identifiers + * @var int this index is used for creating object identifiers */ private static $_index = 1; /** - * @var integer $oid object identifier, each Record object has a unique object identifier + * @var int object identifier, each Record object has a unique object identifier */ private $_oid; /** - * constructor - * @param Doctrine_Table|null $table a Doctrine_Table object or null, - * if null the table object is retrieved from current connection + * constructor. * - * @param boolean $isNewEntry whether or not this record is transient + * @param Doctrine_Table|null $table a Doctrine_Table object or null, + * if null the table object is retrieved from current connection + * @param bool $isNewEntry whether or not this record is transient * - * @throws Doctrine_Connection_Exception if object is created using the new operator and there are no - * open connections - * @throws Doctrine_Record_Exception if the cleanData operation fails somehow + * @throws Doctrine_Connection_Exception if object is created using the new operator and there are no + * open connections + * @throws Doctrine_Record_Exception if the cleanData operation fails somehow */ public function __construct($table = null, $isNewEntry = false) { if (isset($table) && $table instanceof Doctrine_Table) { $this->_table = $table; - $exists = ( ! $isNewEntry); + $exists = (!$isNewEntry); } else { // get the table of this class $class = get_class($this); @@ -223,13 +224,13 @@ public function __construct($table = null, $isNewEntry = false) // Check if the current connection has the records table in its registry // If not this record is only used for creating table definition and setting up // relations. - if ( ! $this->_table->getConnection()->hasTable($this->_table->getComponentName())) { + if (!$this->_table->getConnection()->hasTable($this->_table->getComponentName())) { return; } $this->_oid = self::$_index; - self::$_index++; + ++self::$_index; // get the data array $this->_data = $this->_table->getData(); @@ -241,7 +242,7 @@ public function __construct($table = null, $isNewEntry = false) $this->prepareIdentifiers($exists); - if ( ! $exists) { + if (!$exists) { if ($count > count($this->_values)) { $this->_state = Doctrine_Record::STATE_TDIRTY; } else { @@ -254,7 +255,7 @@ public function __construct($table = null, $isNewEntry = false) $this->_state = Doctrine_Record::STATE_CLEAN; if ($this->isInProxyState()) { - $this->_state = Doctrine_Record::STATE_PROXY; + $this->_state = Doctrine_Record::STATE_PROXY; } } @@ -271,23 +272,25 @@ public function __construct($table = null, $isNewEntry = false) /** * Set whether or not to serialize references. * This is used by caching since we want to serialize references when caching - * but not when just normally serializing a instance + * but not when just normally serializing a instance. * - * @param boolean $bool - * @return boolean $bool + * @param bool $bool + * + * @return bool $bool */ public function serializeReferences($bool = null) { - if ( ! is_null($bool)) { + if (!is_null($bool)) { $this->_serializeReferences = $bool; } + return $this->_serializeReferences; } /** * the current instance counter used to generate unique ids for php objects. Contains the next identifier. * - * @return integer + * @return int */ public static function _index() { @@ -297,26 +300,25 @@ public static function _index() /** * setUp * this method is used for setting up relations and attributes - * it should be implemented by child classes - * - * @return void + * it should be implemented by child classes. */ public function setUp() - { } + { + } + /** * construct * Empty template method to provide concrete Record classes with the possibility - * to hook into the constructor procedure - * - * @return void + * to hook into the constructor procedure. */ public function construct() - { } + { + } /** * @see $_oid; * - * @return integer the object identifier + * @return int the object identifier */ public function getOid() { @@ -335,24 +337,25 @@ public function oid() * $this->invokeSaveHooks('pre', 'save'); * * - * @param string $when 'post' or 'pre' - * @param string $type serialize, unserialize, save, delete, update, insert, validate, dqlSelect, dqlDelete, hydrate - * @param Doctrine_Event $event event raised - * @return Doctrine_Event the event generated using the type, if not specified + * @param string $when 'post' or 'pre' + * @param string $type serialize, unserialize, save, delete, update, insert, validate, dqlSelect, dqlDelete, hydrate + * @param Doctrine_Event $event event raised + * + * @return Doctrine_Event the event generated using the type, if not specified */ public function invokeSaveHooks($when, $type, $event = null) { - $func = $when . ucfirst($type); + $func = $when.ucfirst($type); if (is_null($event)) { - $constant = constant('Doctrine_Event::RECORD_' . strtoupper($type)); - //echo $func . " - " . 'Doctrine_Event::RECORD_' . strtoupper($type) . "\n"; + $constant = constant('Doctrine_Event::RECORD_'.strtoupper($type)); + // echo $func . " - " . 'Doctrine_Event::RECORD_' . strtoupper($type) . "\n"; $event = new Doctrine_Event($this, $constant); } - if ( ! isset($this->_invokedSaveHooks[$func])) { - $this->$func($event); - $this->getTable()->getRecordListener()->$func($event); + if (!isset($this->_invokedSaveHooks[$func])) { + $this->{$func}($event); + $this->getTable()->getRecordListener()->{$func}($event); $this->_invokedSaveHooks[$func] = $event; } else { @@ -363,7 +366,7 @@ public function invokeSaveHooks($when, $type, $event = null) } /** - * makes all the already used save hooks available again + * makes all the already used save hooks available again. */ public function clearInvokedSaveHooks() { @@ -373,17 +376,18 @@ public function clearInvokedSaveHooks() /** * tests validity of the record using the current data. * - * @param boolean $deep run the validation process on the relations - * @param boolean $hooks invoke save hooks before start - * @return boolean whether or not this record is valid + * @param bool $deep run the validation process on the relations + * @param bool $hooks invoke save hooks before start + * + * @return bool whether or not this record is valid */ public function isValid($deep = false, $hooks = true) { - if ( ! $this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) { + if (!$this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) { return true; } - if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) { + if (self::STATE_LOCKED == $this->_state || self::STATE_TLOCKED == $this->_state) { return true; } @@ -400,12 +404,11 @@ public function isValid($deep = false, $hooks = true) $this->preValidate($event); $this->getTable()->getRecordListener()->preValidate($event); - if ( ! $event->skipOperation) { - + if (!$event->skipOperation) { $validator = new Doctrine_Validator(); $validator->validateRecord($this); $this->validate(); - if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) { + if (self::STATE_TDIRTY == $this->_state || self::STATE_TCLEAN == $this->_state) { $this->validateOnInsert(); } else { $this->validateOnUpdate(); @@ -415,19 +418,19 @@ public function isValid($deep = false, $hooks = true) $this->getTable()->getRecordListener()->postValidate($event); $this->postValidate($event); - $valid = $this->getErrorStack()->count() == 0 ? true : false; + $valid = 0 == $this->getErrorStack()->count() ? true : false; if ($valid && $deep) { $stateBeforeLock = $this->_state; $this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED; foreach ($this->_references as $reference) { if ($reference instanceof Doctrine_Record) { - if ( ! $valid = $reference->isValid($deep)) { + if (!$valid = $reference->isValid($deep)) { break; } - } else if ($reference instanceof Doctrine_Collection) { + } elseif ($reference instanceof Doctrine_Collection) { foreach ($reference as $record) { - if ( ! $valid = $record->isValid($deep)) { + if (!$valid = $record->isValid($deep)) { break; } } @@ -445,7 +448,8 @@ public function isValid($deep = false, $hooks = true) * validations that are neccessary. */ protected function validate() - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -453,7 +457,8 @@ protected function validate() * updated. */ protected function validateOnUpdate() - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -461,63 +466,72 @@ protected function validateOnUpdate() * inserted into the data store the first time. */ protected function validateOnInsert() - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the serializing procedure. */ public function preSerialize($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the serializing procedure. */ public function postSerialize($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the serializing procedure. */ public function preUnserialize($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the serializing procedure. */ public function postUnserialize($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the saving procedure. */ public function preSave($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the saving procedure. */ public function postSave($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the deletion procedure. */ public function preDelete($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the deletion procedure. */ public function postDelete($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -525,7 +539,8 @@ public function postDelete($event) * updated. */ public function preUpdate($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -533,7 +548,8 @@ public function preUpdate($event) * updated. */ public function postUpdate($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -541,7 +557,8 @@ public function postUpdate($event) * inserted into the data store the first time. */ public function preInsert($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -549,7 +566,8 @@ public function preInsert($event) * inserted into the data store the first time. */ public function postInsert($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -557,52 +575,60 @@ public function postInsert($event) * validating it. */ public function preValidate($event) - { } + { + } + /** * Empty template method to provide concrete Record classes with the possibility * to hook into the validation procedure. */ public function postValidate($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter DQL select - * queries at runtime + * queries at runtime. */ public function preDqlSelect($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter DQL update - * queries at runtime + * queries at runtime. */ public function preDqlUpdate($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter DQL delete - * queries at runtime + * queries at runtime. */ public function preDqlDelete($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter hydration - * before it runs + * before it runs. */ public function preHydrate($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter hydration - * after it runs + * after it runs. */ public function postHydrate($event) - { } + { + } /** * Get the record error stack as a human readable string. - * Useful for outputting errors to user via web browser + * Useful for outputting errors to user via web browser. * * @return string $message */ @@ -613,24 +639,25 @@ public function getErrorStackAsString() if (count($errorStack)) { $message = sprintf("Validation failed in class %s\n\n", get_class($this)); - $message .= " " . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " had validation error" . (count($errorStack) > 1 ? 's' : null) . ":\n\n"; + $message .= ' '.count($errorStack).' field'.(count($errorStack) > 1 ? 's' : null).' had validation error'.(count($errorStack) > 1 ? 's' : null).":\n\n"; foreach ($errorStack as $field => $errors) { - $message .= " * " . count($errors) . " validator" . (count($errors) > 1 ? 's' : null) . " failed on $field (" . implode(", ", $errors) . ")\n"; + $message .= ' * '.count($errors).' validator'.(count($errors) > 1 ? 's' : null)." failed on {$field} (".implode(', ', $errors).")\n"; } + return $message; - } else { - return false; } + + return false; } /** * retrieves the ErrorStack. To be called after a failed validation attempt (@see isValid()). * - * @return Doctrine_Validator_ErrorStack returns the errorStack associated with this record + * @return Doctrine_Validator_ErrorStack returns the errorStack associated with this record */ public function getErrorStack() { - if ( ! $this->_errorStack) { + if (!$this->_errorStack) { $this->_errorStack = new Doctrine_Validator_ErrorStack(get_class($this)); } @@ -638,16 +665,18 @@ public function getErrorStack() } /** - * assigns the ErrorStack or returns it if called without parameters + * assigns the ErrorStack or returns it if called without parameters. * * @param Doctrine_Validator_ErrorStack errorStack to be assigned for this record - * @return void|Doctrine_Validator_ErrorStack returns the errorStack associated with this record + * @param mixed|null $stack + * + * @return void|Doctrine_Validator_ErrorStack returns the errorStack associated with this record */ public function errorStack($stack = null) { - if ($stack !== null) { - if ( ! ($stack instanceof Doctrine_Validator_ErrorStack)) { - throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.'); + if (null !== $stack) { + if (!($stack instanceof Doctrine_Validator_ErrorStack)) { + throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.'); } $this->_errorStack = $stack; } else { @@ -656,9 +685,7 @@ public function errorStack($stack = null) } /** - * Assign the inheritance column values - * - * @return void + * Assign the inheritance column values. */ public function assignInheritanceValues() { @@ -667,7 +694,7 @@ public function assignInheritanceValues() $k = $this->_table->getFieldName($k); $old = $this->get($k, false); - if (((string) $old !== (string) $v || $old === null) && !in_array($k, $this->_modified)) { + if (((string) $old !== (string) $v || null === $old) && !in_array($k, $this->_modified)) { $this->set($k, $v); } } @@ -675,26 +702,27 @@ public function assignInheritanceValues() /** * setDefaultValues - * sets the default values for records internal data + * sets the default values for records internal data. + * + * @param bool $overwrite whether or not to overwrite the already set values * - * @param boolean $overwrite whether or not to overwrite the already set values - * @return boolean + * @return bool */ public function assignDefaultValues($overwrite = false) { - if ( ! $this->_table->hasDefaultValues()) { + if (!$this->_table->hasDefaultValues()) { return false; } foreach ($this->_data as $column => $value) { $default = $this->_table->getDefaultValueOf($column); - if ($default === null) { + if (null === $default) { continue; } if ($value === self::$_null || $overwrite) { $this->_data[$column] = $default; - $this->_modified[] = $column; + $this->_modified[] = $column; $this->_state = Doctrine_Record::STATE_TDIRTY; } } @@ -706,8 +734,9 @@ public function assignDefaultValues($overwrite = false) * record and returns the values that were removed from $data. Also converts * any values of 'null' to objects of type Doctrine_Null. * - * @param array $data data array to be cleaned - * @return array values cleaned from data + * @param array $data data array to be cleaned + * + * @return array values cleaned from data */ public function cleanData(&$data) { @@ -717,9 +746,9 @@ public function cleanData(&$data) foreach ($this->getTable()->getFieldNames() as $fieldName) { if (isset($tmp[$fieldName])) { $data[$fieldName] = $tmp[$fieldName]; - } else if (array_key_exists($fieldName, $tmp)) { + } elseif (array_key_exists($fieldName, $tmp)) { $data[$fieldName] = null; - } else if ( !isset($this->_data[$fieldName])) { + } elseif (!isset($this->_data[$fieldName])) { $data[$fieldName] = self::$_null; } unset($tmp[$fieldName]); @@ -730,11 +759,9 @@ public function cleanData(&$data) /** * hydrate - * hydrates this object from given array + * hydrates this object from given array. * - * @param array $data - * @param boolean $overwriteLocalChanges whether to overwrite the unsaved (dirty) data - * @return void + * @param bool $overwriteLocalChanges whether to overwrite the unsaved (dirty) data */ public function hydrate(array $data, $overwriteLocalChanges = true) { @@ -755,10 +782,9 @@ public function hydrate(array $data, $overwriteLocalChanges = true) /** * prepareIdentifiers - * prepares identifiers for later use + * prepares identifiers for later use. * - * @param boolean $exists whether or not this record exists in persistent data store - * @return void + * @param bool $exists whether or not this record exists in persistent data store */ private function prepareIdentifiers($exists = true) { @@ -792,7 +818,7 @@ private function prepareIdentifiers($exists = true) /** * serialize - * this method is automatically called when an instance of Doctrine_Record is serialized + * this method is automatically called when an instance of Doctrine_Record is serialized. * * @return string */ @@ -804,11 +830,11 @@ public function serialize() } /** - * this method is automatically called everytime an instance is unserialized + * this method is automatically called everytime an instance is unserialized. * - * @param string $serialized Doctrine_Record as serialized string - * @throws Doctrine_Record_Exception if the cleanData operation fails somehow - * @return void + * @param string $serialized Doctrine_Record as serialized string + * + * @throws Doctrine_Record_Exception if the cleanData operation fails somehow */ public function unserialize($serialized) { @@ -818,12 +844,12 @@ public function unserialize($serialized) } /** - * Serializes the current instance for php 7.4+ + * Serializes the current instance for php 7.4+. * * @return array */ - public function __serialize() { - + public function __serialize() + { $event = new Doctrine_Event($this, Doctrine_Event::RECORD_SERIALIZE); $this->preSerialize($event); @@ -831,13 +857,10 @@ public function __serialize() { $vars = get_object_vars($this); - if ( ! $this->serializeReferences()) { + if (!$this->serializeReferences()) { unset($vars['_references']); } - unset($vars['_table']); - unset($vars['_errorStack']); - unset($vars['_filter']); - unset($vars['_node']); + unset($vars['_table'], $vars['_errorStack'], $vars['_filter'], $vars['_node']); $data = $this->_data; if ($this->exists()) { @@ -845,7 +868,7 @@ public function __serialize() { } foreach ($data as $k => $v) { - if ($v instanceof Doctrine_Record && $this->_table->getTypeOf($k) != 'object') { + if ($v instanceof Doctrine_Record && 'object' != $this->_table->getTypeOf($k)) { unset($vars['_data'][$k]); } elseif ($v === self::$_null) { unset($vars['_data'][$k]); @@ -872,15 +895,13 @@ public function __serialize() { } /** - * Unserializes a Doctrine_Record instance for php 7.4+ - * - * @param array $serialized + * Unserializes a Doctrine_Record instance for php 7.4+. */ public function __unserialize($data) { $event = new Doctrine_Event($this, Doctrine_Event::RECORD_UNSERIALIZE); - $manager = Doctrine_Manager::getInstance(); + $manager = Doctrine_Manager::getInstance(); $connection = $manager->getConnectionForComponent(get_class($this)); $this->_table = $connection->getTable(get_class($this)); @@ -888,8 +909,8 @@ public function __unserialize($data) $this->preUnserialize($event); $this->getTable()->getRecordListener()->preUnserialize($event); - foreach($data as $k => $v) { - $this->$k = $v; + foreach ($data as $k => $v) { + $this->{$k} = $v; } foreach ($this->_data as $k => $v) { @@ -904,7 +925,6 @@ public function __unserialize($data) case 'enum': $this->_data[$k] = $this->_table->enumValue($k, $this->_data[$k]); break; - } } @@ -918,7 +938,7 @@ public function __unserialize($data) // Add the unserialized record to repository and entity map. $this->_oid = self::$_index; - self::$_index++; + ++self::$_index; $this->_table->getRepository()->add($this); $this->_table->addRecord($this); @@ -931,17 +951,19 @@ public function __unserialize($data) } /** - * assigns the state of this record or returns it if called without parameters + * assigns the state of this record or returns it if called without parameters. + * + * @param int|string $state if set, this method tries to set the record state to $state * - * @param integer|string $state if set, this method tries to set the record state to $state * @see Doctrine_Record::STATE_* constants * - * @throws Doctrine_Record_State_Exception if trying to set an unknown state - * @return null|integer + * @return int|null + * + * @throws Doctrine_Record_State_Exception if trying to set an unknown state */ public function state($state = null) { - if ($state == null) { + if (null == $state) { return $this->_state; } @@ -952,10 +974,10 @@ public function state($state = null) } else { $err = true; } - } else if (is_string($state)) { + } elseif (is_string($state)) { $upper = strtoupper($state); - $const = 'Doctrine_Record::STATE_' . $upper; + $const = 'Doctrine_Record::STATE_'.$upper; if (defined($const)) { $this->_state = constant($const); } else { @@ -963,32 +985,32 @@ public function state($state = null) } } - if ($this->_state === Doctrine_Record::STATE_TCLEAN || - $this->_state === Doctrine_Record::STATE_CLEAN) { + if (Doctrine_Record::STATE_TCLEAN === $this->_state + || Doctrine_Record::STATE_CLEAN === $this->_state) { $this->_resetModified(); } if ($err) { - throw new Doctrine_Record_State_Exception('Unknown record state ' . $state); + throw new Doctrine_Record_State_Exception('Unknown record state '.$state); } } /** * refresh - * refresh internal data from the database - * - * @param bool $deep If true, fetch also current relations. Caution: this deletes - * any aggregated values you may have queried beforee + * refresh internal data from the database. * - * @throws Doctrine_Record_Exception When the refresh operation fails (when the database row - * this record represents does not exist anymore) + * @param bool $deep If true, fetch also current relations. Caution: this deletes + * any aggregated values you may have queried beforee * * @return false|Doctrine_Record false if the record is not saved yet + * + * @throws Doctrine_Record_Exception When the refresh operation fails (when the database row + * this record represents does not exist anymore) */ public function refresh($deep = false) { $id = $this->identifier(); - if ( ! is_array($id)) { + if (!is_array($id)) { $id = array($id); } if (empty($id)) { @@ -1002,9 +1024,9 @@ public function refresh($deep = false) if ($deep) { $query = $this->getTable()->createQuery(); foreach (array_keys($this->_references) as $name) { - $query->leftJoin(get_class($this) . '.' . $name); + $query->leftJoin(get_class($this).'.'.$name); } - $query->where(implode(' = ? AND ', (array)$this->getTable()->getIdentifier()) . ' = ?'); + $query->where(implode(' = ? AND ', (array) $this->getTable()->getIdentifier()).' = ?'); $this->clearRelated(); $record = $query->fetchOne($id); } else { @@ -1017,7 +1039,7 @@ public function refresh($deep = false) $this->getTable()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, $overwrite); - if ($record === false) { + if (false === $record) { throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist.'); } @@ -1032,7 +1054,7 @@ public function refresh($deep = false) /** * refresh - * refresh data of related objects from the database + * refresh data of related objects from the database. * * @param string $name name of a related component. if set, this method only refreshes * the specified related component @@ -1046,7 +1068,7 @@ public function refreshRelated($name = null) $reference = $rel->fetchRelatedFor($this); if ($reference instanceof Doctrine_Collection) { $this->_references[$alias] = $reference; - } else if ($reference instanceof Doctrine_Record) { + } elseif ($reference instanceof Doctrine_Record) { if ($reference->exists()) { $this->_references[$alias] = $reference; } else { @@ -1060,7 +1082,7 @@ public function refreshRelated($name = null) $reference = $rel->fetchRelatedFor($this); if ($reference instanceof Doctrine_Collection) { $this->_references[$name] = $reference; - } else if ($reference instanceof Doctrine_Record) { + } elseif ($reference instanceof Doctrine_Record) { if ($reference->exists()) { $this->_references[$name] = $reference; } else { @@ -1071,10 +1093,9 @@ public function refreshRelated($name = null) } /** - * Clear a related reference or all references + * Clear a related reference or all references. * * @param string $name The relationship reference to clear - * @return void */ public function clearRelated($name = null) { @@ -1091,7 +1112,8 @@ public function clearRelated($name = null) * exist in the database, the related reference will be cleared immediately. * * @param string $name - * @return boolean Whether or not the related relationship exists + * + * @return bool Whether or not the related relationship exists */ public function relatedExists($name) { @@ -1099,14 +1121,11 @@ public function relatedExists($name) return true; } - $reference = $this->$name; + $reference = $this->{$name}; if ($reference instanceof Doctrine_Record) { $exists = $reference->exists(); } elseif ($reference instanceof Doctrine_Collection) { - throw new Doctrine_Record_Exception( - 'You can only call relatedExists() on a relationship that '. - 'returns an instance of Doctrine_Record' - ); + throw new Doctrine_Record_Exception('You can only call relatedExists() on a relationship that returns an instance of Doctrine_Record'); } else { $exists = false; } @@ -1121,7 +1140,7 @@ public function relatedExists($name) /** * returns the table object for this record. * - * @return Doctrine_Table a Doctrine_Table object + * @return Doctrine_Table a Doctrine_Table object */ public function getTable() { @@ -1129,9 +1148,9 @@ public function getTable() } /** - * return all the internal data (columns) + * return all the internal data (columns). * - * @return array an array containing all the properties + * @return array an array containing all the properties */ public function getData() { @@ -1142,14 +1161,12 @@ public function getData() * returns the value of a property (column). If the property is not yet loaded * this method does NOT load it. * - * @param $name name of the property - * @throws Doctrine_Record_Exception if trying to get an unknown property - * @return mixed + * @throws Doctrine_Record_Exception if trying to get an unknown property */ public function rawGet($fieldName) { - if ( ! array_key_exists($fieldName, $this->_data)) { - throw new Doctrine_Record_Exception('Unknown property '. $fieldName); + if (!array_key_exists($fieldName, $this->_data)) { + throw new Doctrine_Record_Exception('Unknown property '.$fieldName); } if ($this->_data[$fieldName] === self::$_null) { return null; @@ -1162,8 +1179,9 @@ public function rawGet($fieldName) * loads all the uninitialized properties from the database. * Used to move a record from PROXY to CLEAN/DIRTY state. * - * @param array $data overwriting data to load in the record. Instance is hydrated from the table if not specified. - * @return boolean + * @param array $data overwriting data to load in the record. Instance is hydrated from the table if not specified. + * + * @return bool */ public function load(array $data = array()) { @@ -1171,7 +1189,7 @@ public function load(array $data = array()) if ($this->exists() && $this->isInProxyState()) { $id = $this->identifier(); - if ( ! is_array($id)) { + if (!is_array($id)) { $id = array($id); } @@ -1184,15 +1202,15 @@ public function load(array $data = array()) if (is_array($data)) { foreach ($data as $field => $value) { - if ($table->hasField($field) && ( ! array_key_exists($field, $this->_data) || $this->_data[$field] === self::$_null)) { - $this->_data[$field] = $value; - } + if ($table->hasField($field) && (!array_key_exists($field, $this->_data) || $this->_data[$field] === self::$_null)) { + $this->_data[$field] = $value; + } } } if ($this->isModified()) { $this->_state = Doctrine_Record::STATE_DIRTY; - } else if (!$this->isInProxyState()) { + } elseif (!$this->isInProxyState()) { $this->_state = Doctrine_Record::STATE_CLEAN; } @@ -1203,21 +1221,22 @@ public function load(array $data = array()) } /** - * indicates whether record has any not loaded fields + * indicates whether record has any not loaded fields. * - * @return boolean + * @return bool */ public function isInProxyState() { $count = 0; foreach ($this->_data as $value) { if ($value !== self::$_null) { - $count++; + ++$count; } } if ($count < $this->_table->getColumnCount()) { return true; } + return false; } @@ -1227,7 +1246,8 @@ public function isInProxyState() * * @param string $fieldName * @param string $accessor - * @return boolean + * + * @return bool */ public function hasAccessor($fieldName, $accessor = null) { @@ -1235,15 +1255,14 @@ public function hasAccessor($fieldName, $accessor = null) if ($accessor) { self::$_customAccessors[$componentName][$fieldName] = $accessor; } else { - return (isset(self::$_customAccessors[$componentName][$fieldName]) && self::$_customAccessors[$componentName][$fieldName]); + return isset(self::$_customAccessors[$componentName][$fieldName]) && self::$_customAccessors[$componentName][$fieldName]; } } /** - * clears the accessor for a field name + * clears the accessor for a field name. * * @param string $fieldName - * @return void */ public function clearAccessor($fieldName) { @@ -1252,37 +1271,41 @@ public function clearAccessor($fieldName) } /** - * gets the custom accessor for a field name + * gets the custom accessor for a field name. * * @param string $fieldName + * * @return string $accessor */ public function getAccessor($fieldName) { if ($this->hasAccessor($fieldName)) { $componentName = $this->_table->getComponentName(); + return self::$_customAccessors[$componentName][$fieldName]; } } /** - * gets all accessors for this component instance + * gets all accessors for this component instance. * * @return array $accessors */ public function getAccessors() { $componentName = $this->_table->getComponentName(); + return isset(self::$_customAccessors[$componentName]) ? self::$_customAccessors[$componentName] : array(); } /** * sets a fieldname to have a custom mutator or check if a field has a custom - * mutator defined (when called without the $mutator parameter) + * mutator defined (when called without the $mutator parameter). * * @param string $fieldName * @param string $mutator - * @return boolean + * + * @return bool */ public function hasMutator($fieldName, $mutator = null) { @@ -1290,29 +1313,28 @@ public function hasMutator($fieldName, $mutator = null) if ($mutator) { self::$_customMutators[$componentName][$fieldName] = $mutator; } else { - return (isset(self::$_customMutators[$componentName][$fieldName]) && self::$_customMutators[$componentName][$fieldName]); + return isset(self::$_customMutators[$componentName][$fieldName]) && self::$_customMutators[$componentName][$fieldName]; } } /** - * gets the custom mutator for a field name + * gets the custom mutator for a field name. * - * @param string $fieldname * @return string */ public function getMutator($fieldName) { if ($this->hasMutator($fieldName)) { $componentName = $this->_table->getComponentName(); + return self::$_customMutators[$componentName][$fieldName]; } } /** - * clears the custom mutator for a field name + * clears the custom mutator for a field name. * * @param string $fieldName - * @return void */ public function clearMutator($fieldName) { @@ -1321,20 +1343,20 @@ public function clearMutator($fieldName) } /** - * gets all custom mutators for this component instance + * gets all custom mutators for this component instance. * * @return array $mutators */ public function getMutators() { $componentName = $this->_table->getComponentName(); + return self::$_customMutators[$componentName]; } /** - * Set a fieldname to have a custom accessor and mutator + * Set a fieldname to have a custom accessor and mutator. * - * @param string $fieldname * @param string $accessor * @param string $mutator */ @@ -1345,12 +1367,12 @@ public function hasAccessorMutator($fieldName, $accessor, $mutator) } /** - * returns a value of a property or a related component + * returns a value of a property or a related component. + * + * @param mixed $fieldName name of the property or related component + * @param bool $load whether or not to invoke the loading procedure * - * @param mixed $fieldName name of the property or related component - * @param boolean $load whether or not to invoke the loading procedure - * @throws Doctrine_Record_Exception if trying to get a value of unknown property / related component - * @return mixed + * @throws Doctrine_Record_Exception if trying to get a value of unknown property / related component */ public function get($fieldName, $load = true) { @@ -1359,13 +1381,15 @@ public function get($fieldName, $load = true) $accessor = $this->hasAccessor($fieldName) ? $this->getAccessor($fieldName) - : 'get' . Doctrine_Inflector::classify($fieldName); + : 'get'.Doctrine_Inflector::classify($fieldName); if ($this->hasAccessor($fieldName) || method_exists($this, $accessor)) { $this->hasAccessor($fieldName, $accessor); - return $this->$accessor($load, $fieldName); + + return $this->{$accessor}($load, $fieldName); } } + return $this->_get($fieldName, $load); } @@ -1393,7 +1417,7 @@ protected function _get($fieldName, $load = true) } try { - if ( ! isset($this->_references[$fieldName])) { + if (!isset($this->_references[$fieldName])) { if ($load) { $rel = $this->_table->getRelation($fieldName); $this->_references[$fieldName] = $rel->fetchRelatedFor($this); @@ -1413,13 +1437,13 @@ protected function _get($fieldName, $load = true) try { $value = $filter->filterGet($this, $fieldName); $success = true; - } catch (Doctrine_Exception $e) {} + } catch (Doctrine_Exception $e) { + } } if ($success) { return $value; - } else { - throw $e; } + throw $e; } } @@ -1427,9 +1451,8 @@ protected function _get($fieldName, $load = true) * sets a value that will be managed as if it were a field by magic accessor and mutators, @see get() and @see set(). * Normally used by Doctrine for the mapping of aggregate values. * - * @param string $name the name of the mapped value - * @param mixed $value mixed value to be mapped - * @return void + * @param string $name the name of the mapped value + * @param mixed $value mixed value to be mapped */ public function mapValue($name, $value = null) { @@ -1437,10 +1460,11 @@ public function mapValue($name, $value = null) } /** - * Tests whether a mapped value exists + * Tests whether a mapped value exists. + * + * @param string $name the name of the property * - * @param string $name the name of the property - * @return boolean + * @return bool */ public function hasMappedValue($name) { @@ -1450,28 +1474,29 @@ public function hasMappedValue($name) /** * alters mapped values, properties and related components. * - * @param mixed $name name of the property or reference - * @param mixed $value value of the property or reference - * @param boolean $load whether or not to refresh / load the uninitialized record data - * - * @throws Doctrine_Record_Exception if trying to set a value for unknown property / related component - * @throws Doctrine_Record_Exception if trying to set a value of wrong type for related component + * @param mixed $value value of the property or reference + * @param bool $load whether or not to refresh / load the uninitialized record data * * @return Doctrine_Record + * + * @throws Doctrine_Record_Exception if trying to set a value for unknown property / related component + * @throws Doctrine_Record_Exception if trying to set a value of wrong type for related component */ public function set($fieldName, $value, $load = true) { if ($this->_table->getAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE) || $this->hasMutator($fieldName)) { $componentName = $this->_table->getComponentName(); $mutator = $this->hasMutator($fieldName) - ? $this->getMutator($fieldName): - 'set' . Doctrine_Inflector::classify($fieldName); + ? $this->getMutator($fieldName) : + 'set'.Doctrine_Inflector::classify($fieldName); if ($this->hasMutator($fieldName) || method_exists($this, $mutator)) { $this->hasMutator($fieldName, $mutator); - return $this->$mutator($value, $load, $fieldName); + + return $this->{$mutator}($value, $load, $fieldName); } } + return $this->_set($fieldName, $value, $load); } @@ -1479,12 +1504,12 @@ protected function _set($fieldName, $value, $load = true) { if (array_key_exists($fieldName, $this->_values)) { $this->_values[$fieldName] = $value; - } else if (array_key_exists($fieldName, $this->_data)) { + } elseif (array_key_exists($fieldName, $this->_data)) { $type = $this->_table->getTypeOf($fieldName); if ($value instanceof Doctrine_Record) { $id = $value->getIncremented(); - if ($id !== null && $type !== 'object') { + if (null !== $id && 'object' !== $type) { $value = $id; } } @@ -1496,7 +1521,7 @@ protected function _set($fieldName, $value, $load = true) } if ($this->_isValueModified($type, $old, $value)) { - if ($value === null) { + if (null === $value) { $value = $this->_table->getDefaultValueOf($fieldName); } $this->_data[$fieldName] = $value; @@ -1522,13 +1547,13 @@ protected function _set($fieldName, $value, $load = true) try { $value = $filter->filterSet($this, $fieldName, $value); $success = true; - } catch (Doctrine_Exception $e) {} + } catch (Doctrine_Exception $e) { + } } if ($success) { return $value; - } else { - throw $e; } + throw $e; } } @@ -1537,7 +1562,7 @@ protected function _set($fieldName, $value, $load = true) /** * Check if a value has changed according to Doctrine - * Doctrine is loose with type checking in the same ways PHP is for consistancy of behavior + * Doctrine is loose with type checking in the same ways PHP is for consistancy of behavior. * * This function basically says if what is being set is of Doctrine type boolean and something * like current_value == 1 && new_value = true would not be considered modified @@ -1545,10 +1570,11 @@ protected function _set($fieldName, $value, $load = true) * Simply doing $old !== $new will return false for boolean columns would mark the field as modified * and change it in the database when it is not necessary * - * @param string $type Doctrine type of the column - * @param string $old Old value - * @param string $new New value - * @return boolean $modified Whether or not Doctrine considers the value modified + * @param string $type Doctrine type of the column + * @param string $old Old value + * @param string $new New value + * + * @return bool $modified Whether or not Doctrine considers the value modified */ protected function _isValueModified($type, $old, $new) { @@ -1556,23 +1582,26 @@ protected function _isValueModified($type, $old, $new) return true; } - if ($type == 'boolean' && (is_bool($old) || is_numeric($old)) && (is_bool($new) || is_numeric($new)) && $old == $new) { + if ('boolean' == $type && (is_bool($old) || is_numeric($old)) && (is_bool($new) || is_numeric($new)) && $old == $new) { return false; - } else if (in_array($type, array('decimal', 'float', 'double')) && is_numeric($old) && is_numeric($new)) { + } + if (in_array($type, array('decimal', 'float', 'double')) && is_numeric($old) && is_numeric($new)) { return $old * 100 != $new * 100; - } else if (in_array($type, array('integer', 'int')) && is_numeric($old) && is_numeric($new)) { + } + if (in_array($type, array('integer', 'int')) && is_numeric($old) && is_numeric($new)) { return $old != $new; - } else if ($type == 'timestamp' || $type == 'date') { + } + if ('timestamp' == $type || 'date' == $type) { $oldStrToTime = @strtotime((string) $old); $newStrToTime = @strtotime((string) $new); if ($oldStrToTime && $newStrToTime) { return $oldStrToTime !== $newStrToTime; - } else { - return $old !== $new; } - } else { + return $old !== $new; } + + return $old !== $new; } /** @@ -1581,23 +1610,24 @@ protected function _isValueModified($type, $old, $new) * This method inserts a related component instance in this record * relations, populating the foreign keys accordingly. * - * @param string $name related component alias in the relation - * @param Doctrine_Record|Doctrine_Collection $value object to be linked as a related component + * @param string $name related component alias in the relation + * @param Doctrine_Record|Doctrine_Collection $value object to be linked as a related component + * * @todo Refactor. What about composite keys? */ public function coreSetRelated($name, $value) { $rel = $this->_table->getRelation($name); - if ($value === null) { + if (null === $value) { $value = self::$_null; } // one-to-many or one-to-one relation if ($rel instanceof Doctrine_Relation_ForeignKey || $rel instanceof Doctrine_Relation_LocalKey) { - if ( ! $rel->isOneToOne()) { + if (!$rel->isOneToOne()) { // one-to-many relation found - if ( ! ($value instanceof Doctrine_Collection)) { + if (!($value instanceof Doctrine_Collection)) { throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references."); } @@ -1615,12 +1645,12 @@ public function coreSetRelated($name, $value) } // one-to-one relation found - if ( ! ($value instanceof Doctrine_Record) && ! ($value instanceof Doctrine_Null)) { + if (!($value instanceof Doctrine_Record) && !($value instanceof Doctrine_Null)) { throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Record or Doctrine_Null when setting one-to-one references."); } if ($rel instanceof Doctrine_Relation_LocalKey) { - if ($value !== self::$_null && ! empty($foreignFieldName) && $foreignFieldName != $value->getTable()->getIdentifier()) { + if ($value !== self::$_null && !empty($foreignFieldName) && $foreignFieldName != $value->getTable()->getIdentifier()) { $this->set($localFieldName, $value->rawGet($foreignFieldName), false); } else { // FIX: Ticket #1280 fits in this situation @@ -1631,9 +1661,9 @@ public function coreSetRelated($name, $value) $value->set($foreignFieldName, $this, false); } } - } else if ($rel instanceof Doctrine_Relation_Association) { + } elseif ($rel instanceof Doctrine_Relation_Association) { // join table relation found - if ( ! ($value instanceof Doctrine_Collection)) { + if (!($value instanceof Doctrine_Collection)) { throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Collection when setting many-to-many references."); } } @@ -1642,10 +1672,11 @@ public function coreSetRelated($name, $value) } /** - * test whether a field (column, mapped value, related component, accessor) is accessible by @see get() + * test whether a field (column, mapped value, related component, accessor) is accessible by @see get(). * * @param string $fieldName - * @return boolean + * + * @return bool */ public function contains($fieldName) { @@ -1660,36 +1691,36 @@ public function contains($fieldName) if (isset($this->_values[$fieldName])) { return true; } - if (isset($this->_references[$fieldName]) && - $this->_references[$fieldName] !== self::$_null) { - + if (isset($this->_references[$fieldName]) + && $this->_references[$fieldName] !== self::$_null) { return true; } + return false; } /** * deletes a column or a related component. + * * @param string $name - * @return void */ public function __unset($name) { if (array_key_exists($name, $this->_data)) { $this->_data[$name] = array(); - } else if (isset($this->_references[$name])) { + } elseif (isset($this->_references[$name])) { if ($this->_references[$name] instanceof Doctrine_Record) { - $this->_pendingDeletes[] = $this->$name; + $this->_pendingDeletes[] = $this->{$name}; $this->_references[$name] = self::$_null; } elseif ($this->_references[$name] instanceof Doctrine_Collection) { - $this->_pendingDeletes[] = $this->$name; + $this->_pendingDeletes[] = $this->{$name}; $this->_references[$name]->setData(array()); } } } /** - * returns Doctrine_Record instances which need to be deleted on save + * returns Doctrine_Record instances which need to be deleted on save. * * @return array */ @@ -1699,7 +1730,7 @@ public function getPendingDeletes() } /** - * returns Doctrine_Record instances which need to be unlinked (deleting the relation) on save + * returns Doctrine_Record instances which need to be unlinked (deleting the relation) on save. * * @return array $pendingUnlinks */ @@ -1709,9 +1740,7 @@ public function getPendingUnlinks() } /** - * resets pending record unlinks - * - * @return void + * resets pending record unlinks. */ public function resetPendingUnlinks() { @@ -1721,17 +1750,17 @@ public function resetPendingUnlinks() /** * applies the changes made to this object into database * this method is smart enough to know if any changes are made - * and whether to use INSERT or UPDATE statement + * and whether to use INSERT or UPDATE statement. * * this method also saves the related components * - * @param Doctrine_Connection $conn optional connection parameter - * @throws Exception if record is not valid and validation is active - * @return void + * @param Doctrine_Connection $conn optional connection parameter + * + * @throws Exception if record is not valid and validation is active */ public function save(Doctrine_Connection $conn = null) { - if ($conn === null) { + if (null === $conn) { $conn = $this->_table->getConnection(); } $conn->unitOfWork->saveGraph($this); @@ -1743,12 +1772,15 @@ public function save(Doctrine_Connection $conn = null) * throw an exception when validation fails but returns TRUE on * success or FALSE on failure. * - * @param Doctrine_Connection $conn optional connection parameter - * @return TRUE if the record was saved sucessfully without errors, FALSE otherwise. + * @param Doctrine_Connection $conn optional connection parameter + * + * @return true if the record was saved sucessfully without errors, FALSE otherwise */ - public function trySave(Doctrine_Connection $conn = null) { + public function trySave(Doctrine_Connection $conn = null) + { try { $this->save($conn); + return true; } catch (Doctrine_Validator_Exception $ignored) { return false; @@ -1766,32 +1798,36 @@ public function trySave(Doctrine_Connection $conn = null) { * query isemulated through this method for other DBMS using standard types * of queries inside a transaction to assure the atomicity of the operation. * - * @param Doctrine_Connection $conn optional connection parameter - * @throws Doctrine_Connection_Exception if some of the key values was null - * @throws Doctrine_Connection_Exception if there were no key fields - * @throws Doctrine_Connection_Exception if something fails at database level - * @return integer number of rows affected + * @param Doctrine_Connection $conn optional connection parameter + * + * @return int number of rows affected + * + * @throws Doctrine_Connection_Exception if some of the key values was null + * @throws Doctrine_Connection_Exception if there were no key fields + * @throws Doctrine_Connection_Exception if something fails at database level */ public function replace(Doctrine_Connection $conn = null) { - if ($conn === null) { + if (null === $conn) { $conn = $this->_table->getConnection(); } + return $conn->unitOfWork->saveGraph($this, true); } /** * retrieves an array of modified fields and associated new values. * - * @param boolean $old pick the old values (instead of the new ones) - * @param boolean $last pick only lastModified values (@see getLastModified()) + * @param bool $old pick the old values (instead of the new ones) + * @param bool $last pick only lastModified values (@see getLastModified()) + * * @return array $a */ public function getModified($old = false, $last = false) { $a = array(); - $modified = $last ? $this->_lastModified:$this->_modified; + $modified = $last ? $this->_lastModified : $this->_modified; foreach ($modified as $fieldName) { if ($old) { $a[$fieldName] = isset($this->_oldValues[$fieldName]) @@ -1801,13 +1837,15 @@ public function getModified($old = false, $last = false) $a[$fieldName] = $this->_data[$fieldName]; } } + return $a; } /** * returns an array of the modified fields from the last transaction. * - * @param boolean $old pick the old values (instead of the new ones) + * @param bool $old pick the old values (instead of the new ones) + * * @return array */ public function getLastModified($old = false) @@ -1822,8 +1860,8 @@ public function getLastModified($old = false) * adds column aggregation inheritance and converts Records into primary * key values. * - * @param array $array * @return array + * * @todo What about a little bit more expressive name? getPreparedData? */ public function getPrepared(array $array = array()) @@ -1848,32 +1886,32 @@ public function getPrepared(array $array = array()) $a[$field] = serialize($this->_data[$field]); break; case 'gzip': - $a[$field] = gzcompress($this->_data[$field],5); + $a[$field] = gzcompress($this->_data[$field], 5); break; case 'boolean': $a[$field] = $this->getTable()->getConnection()->convertBooleans($this->_data[$field]); - break; + break; case 'set': if (is_array($this->_data[$field])) { $a[$field] = implode(',', $this->_data[$field]); } else { $a[$field] = $this->_data[$field]; } - break; + break; default: if ($this->_data[$field] instanceof Doctrine_Record) { $a[$field] = $this->_data[$field]->getIncremented(); - if ($a[$field] !== null) { + if (null !== $a[$field]) { $this->_data[$field] = $a[$field]; } } else { $a[$field] = $this->_data[$field]; } - /** TODO: - if ($this->_data[$v] === null) { - throw new Doctrine_Record_Exception('Unexpected null value.'); - } - */ + /* TODO: + * if ($this->_data[$v] === null) { + * throw new Doctrine_Record_Exception('Unexpected null value.'); + * } + */ } } @@ -1881,20 +1919,20 @@ public function getPrepared(array $array = array()) } /** - * implements Countable interface + * implements Countable interface. * - * @return integer the number of columns in this record + * @return int the number of columns in this record */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_data); } /** - * alias for @see count() + * alias for @see count(). * - * @return integer the number of columns in this record + * @return int the number of columns in this record */ public function columnCount() { @@ -1902,16 +1940,18 @@ public function columnCount() } /** - * returns the record representation as an array + * returns the record representation as an array. + * + * @see http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models + * + * @param bool $deep whether to include relations + * @param bool $prefixKey not used * - * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models - * @param boolean $deep whether to include relations - * @param boolean $prefixKey not used * @return array */ public function toArray($deep = true, $prefixKey = false) { - if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) { + if (self::STATE_LOCKED == $this->_state || self::STATE_TLOCKED == $this->_state) { return false; } @@ -1934,14 +1974,14 @@ public function toArray($deep = true, $prefixKey = false) } } - if ($this->_table->getIdentifierType() == Doctrine_Core::IDENTIFIER_AUTOINC) { - $i = $this->_table->getIdentifier(); - $a[$i] = $this->getIncremented(); + if (Doctrine_Core::IDENTIFIER_AUTOINC == $this->_table->getIdentifierType()) { + $i = $this->_table->getIdentifier(); + $a[$i] = $this->getIncremented(); } if ($deep) { foreach ($this->_references as $key => $relation) { - if ( ! $relation instanceof Doctrine_Null) { + if (!$relation instanceof Doctrine_Null) { $a[$key] = $relation->toArray($deep, $prefixKey); } } @@ -1960,19 +2000,18 @@ public function toArray($deep = true, $prefixKey = false) /** * merges this record with an array of values - * or with another existing instance of this object + * or with another existing instance of this object. * * @see fromArray() - * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models - * @param string $array array of data to merge, see link for documentation - * @param bool $deep whether or not to merge relations - * @return void + * @see http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models + * + * @param bool $deep whether or not to merge relations */ public function merge($data, $deep = true) { if ($data instanceof $this) { $array = $data->toArray($deep); - } else if (is_array($data)) { + } elseif (is_array($data)) { $array = $data; } @@ -1980,46 +2019,47 @@ public function merge($data, $deep = true) } /** - * imports data from a php array + * imports data from a php array. * - * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models - * @param string $array array of data, see link for documentation - * @param bool $deep whether or not to act on relations - * @return void + * @see http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models + * + * @param string $array array of data, see link for documentation + * @param bool $deep whether or not to act on relations */ public function fromArray(array $array, $deep = true) { $refresh = false; foreach ($array as $key => $value) { - if ($key == '_identifier') { + if ('_identifier' == $key) { $refresh = true; $this->assignIdentifier($value); continue; } if ($deep && $this->getTable()->hasRelation($key)) { - if ( ! $this->$key) { + if (!$this->{$key}) { $this->refreshRelated($key); } if (is_array($value)) { - if (isset($value[0]) && ! is_array($value[0])) { + if (isset($value[0]) && !is_array($value[0])) { $this->unlink($key, array(), false); $this->link($key, $value, false); } else { - $this->$key->fromArray($value, $deep); + $this->{$key}->fromArray($value, $deep); } } - } else if ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { + } elseif ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { $this->set($key, $value); } else { - $method = 'set' . Doctrine_Inflector::classify($key); + $method = 'set'.Doctrine_Inflector::classify($key); try { if (is_callable(array($this, $method))) { - $this->$method($value); + $this->{$method}($value); } - } catch (Doctrine_Record_Exception $e) {} + } catch (Doctrine_Record_Exception $e) { + } } } @@ -2031,7 +2071,7 @@ public function fromArray(array $array, $deep = true) } /** - * synchronizes a Doctrine_Record instance and its relations with data from an array + * synchronizes a Doctrine_Record instance and its relations with data from an array. * * it expects an array representation of a Doctrine_Record similar to the return * value of the toArray() method. If the array contains relations it will create @@ -2040,43 +2080,43 @@ public function fromArray(array $array, $deep = true) * does not touch what it is not in $array) * * @param array $array representation of a Doctrine_Record - * @param bool $deep whether or not to act on relations + * @param bool $deep whether or not to act on relations */ public function synchronizeWithArray(array $array, $deep = true) { $refresh = false; foreach ($array as $key => $value) { - if ($key == '_identifier') { + if ('_identifier' == $key) { $refresh = true; $this->assignIdentifier($value); continue; } if ($deep && $this->getTable()->hasRelation($key)) { - if ( ! $this->$key) { + if (!$this->{$key}) { $this->refreshRelated($key); } if (is_array($value)) { - if (isset($value[0]) && ! is_array($value[0])) { + if (isset($value[0]) && !is_array($value[0])) { $this->unlink($key, array(), false); $this->link($key, $value, false); } else { - $this->$key->synchronizeWithArray($value); - $this->$key = $this->$key; + $this->{$key}->synchronizeWithArray($value); + $this->{$key} = $this->{$key}; } } - } else if ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { + } elseif ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { $this->set($key, $value); } } // Eliminate relationships missing in the $array foreach ($this->_references as $name => $relation) { - $rel = $this->getTable()->getRelation($name); + $rel = $this->getTable()->getRelation($name); - if ( ! $rel->isRefClass() && ! isset($array[$name]) && ( ! $rel->isOneToOne() || ! isset($array[$rel->getLocalFieldName()]))) { - unset($this->$name); + if (!$rel->isRefClass() && !isset($array[$name]) && (!$rel->isOneToOne() || !isset($array[$rel->getLocalFieldName()]))) { + unset($this->{$name}); } } @@ -2086,62 +2126,63 @@ public function synchronizeWithArray(array $array, $deep = true) } /** - * exports instance to a chosen format + * exports instance to a chosen format. + * + * @param string $type format type: array, xml, yml, json + * @param string $deep whether or not to export all relationships * - * @param string $type format type: array, xml, yml, json - * @param string $deep whether or not to export all relationships - * @return string representation as $type format. Array is $type is array + * @return string representation as $type format. Array is $type is array */ public function exportTo($type, $deep = true) { - if ($type == 'array') { + if ('array' == $type) { return $this->toArray($deep); - } else { - return Doctrine_Parser::dump($this->toArray($deep, true), $type); } + + return Doctrine_Parser::dump($this->toArray($deep, true), $type); } /** - * imports data from a chosen format in the current instance + * imports data from a chosen format in the current instance. * - * @param string $type Format type: xml, yml, json - * @param string $data Data to be parsed and imported - * @return void + * @param string $type Format type: xml, yml, json + * @param string $data Data to be parsed and imported */ public function importFrom($type, $data, $deep = true) { - if ($type == 'array') { + if ('array' == $type) { return $this->fromArray($data, $deep); - } else { - return $this->fromArray(Doctrine_Parser::load($data, $type), $deep); } + + return $this->fromArray(Doctrine_Parser::load($data, $type), $deep); } /** - * returns true if this record is saved in the database, otherwise false (it is transient) + * returns true if this record is saved in the database, otherwise false (it is transient). * - * @return boolean + * @return bool */ public function exists() { - return ($this->_state !== Doctrine_Record::STATE_TCLEAN && - $this->_state !== Doctrine_Record::STATE_TDIRTY && - $this->_state !== Doctrine_Record::STATE_TLOCKED && - $this->_state !== null); + return Doctrine_Record::STATE_TCLEAN !== $this->_state + && Doctrine_Record::STATE_TDIRTY !== $this->_state + && Doctrine_Record::STATE_TLOCKED !== $this->_state + && null !== $this->_state; } /** - * returns true if this record was modified, otherwise false + * returns true if this record was modified, otherwise false. + * + * @param bool $deep whether to process also the relations for changes * - * @param boolean $deep whether to process also the relations for changes - * @return boolean + * @return bool */ public function isModified($deep = false) { - $modified = ($this->_state === Doctrine_Record::STATE_DIRTY || - $this->_state === Doctrine_Record::STATE_TDIRTY); - if ( ! $modified && $deep) { - if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) { + $modified = (Doctrine_Record::STATE_DIRTY === $this->_state + || Doctrine_Record::STATE_TDIRTY === $this->_state); + if (!$modified && $deep) { + if (self::STATE_LOCKED == $this->_state || self::STATE_TLOCKED == $this->_state) { return false; } @@ -2153,7 +2194,7 @@ public function isModified($deep = false) if ($modified = $reference->isModified($deep)) { break; } - } else if ($reference instanceof Doctrine_Collection) { + } elseif ($reference instanceof Doctrine_Collection) { foreach ($reference as $record) { if ($modified = $record->isModified($deep)) { break 2; @@ -2163,27 +2204,32 @@ public function isModified($deep = false) } $this->_state = $stateBeforeLock; } + return $modified; } /** - * checks existence of properties and related components - * @param mixed $fieldName name of the property or reference - * @return boolean + * checks existence of properties and related components. + * + * @param mixed $fieldName name of the property or reference + * + * @return bool */ public function hasRelation($fieldName) { if (isset($this->_data[$fieldName]) || isset($this->_id[$fieldName])) { return true; } + return $this->_table->hasRelation($fieldName); } /** - * implements IteratorAggregate interface - * @return Doctrine_Record_Iterator iterator through data + * implements IteratorAggregate interface. + * + * @return Doctrine_Record_Iterator iterator through data */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new Doctrine_Record_Iterator($this); @@ -2191,31 +2237,33 @@ public function getIterator() /** * deletes this data access object and all the related composites - * this operation is isolated by a transaction + * this operation is isolated by a transaction. * * this event can be listened by the onPreDelete and onDelete listeners * - * @return boolean true if successful + * @return bool true if successful */ public function delete(Doctrine_Connection $conn = null) { - if ($conn == null) { + if (null == $conn) { $conn = $this->_table->getConnection(); } + return $conn->unitOfWork->delete($this); } /** * generates a copy of this object. Returns an instance of the same class of $this. * - * @param boolean $deep whether to duplicates the objects targeted by the relations + * @param bool $deep whether to duplicates the objects targeted by the relations + * * @return Doctrine_Record */ public function copy($deep = false) { $data = $this->_data; $idtype = $this->_table->getIdentifierType(); - if ($idtype === Doctrine_Core::IDENTIFIER_AUTOINC || $idtype === Doctrine_Core::IDENTIFIER_SEQUENCE) { + if (Doctrine_Core::IDENTIFIER_AUTOINC === $idtype || Doctrine_Core::IDENTIFIER_SEQUENCE === $idtype) { $id = $this->_table->getIdentifier(); unset($data[$id]); @@ -2225,7 +2273,7 @@ public function copy($deep = false) $modified = array(); foreach ($data as $key => $val) { - if ( ! ($val instanceof Doctrine_Null)) { + if (!($val instanceof Doctrine_Null)) { $ret->_modified[] = $key; } } @@ -2236,7 +2284,7 @@ public function copy($deep = false) foreach ($value as $valueKey => $record) { $ret->{$key}[$valueKey] = $record->copy($deep); } - } else if ($value instanceof Doctrine_Record) { + } elseif ($value instanceof Doctrine_Record) { $ret->set($key, $value->copy($deep)); } } @@ -2246,21 +2294,20 @@ public function copy($deep = false) } /** - * assigns an identifier to the instance, for database storage + * assigns an identifier to the instance, for database storage. * - * @param mixed $id a key value or an array of keys - * @return void + * @param mixed $id a key value or an array of keys */ public function assignIdentifier($id = false) { - if ($id === false) { - $this->_id = array(); - $this->_data = $this->cleanData($this->_data); - $this->_state = Doctrine_Record::STATE_TCLEAN; + if (false === $id) { + $this->_id = array(); + $this->_data = $this->cleanData($this->_data); + $this->_state = Doctrine_Record::STATE_TCLEAN; $this->_resetModified(); - } elseif ($id === true) { + } elseif (true === $id) { $this->prepareIdentifiers(true); - $this->_state = Doctrine_Record::STATE_CLEAN; + $this->_state = Doctrine_Record::STATE_CLEAN; $this->_resetModified(); } else { if (is_array($id)) { @@ -2279,7 +2326,7 @@ public function assignIdentifier($id = false) } /** - * returns the primary keys of this object + * returns the primary keys of this object. * * @return array */ @@ -2289,15 +2336,16 @@ public function identifier() } /** - * returns the value of autoincremented primary key of this object (if any) + * returns the value of autoincremented primary key of this object (if any). + * + * @return int * - * @return integer * @todo Better name? */ final public function getIncremented() { $id = current($this->_id); - if ($id === false) { + if (false === $id) { return null; } @@ -2308,7 +2356,7 @@ final public function getIncremented() * getLast * this method is used internally by Doctrine_Query * it is needed to provide compatibility between - * records and collections + * records and collections. * * @return Doctrine_Record */ @@ -2318,9 +2366,11 @@ public function getLast() } /** - * tests whether a relation is set - * @param string $name relation alias - * @return boolean + * tests whether a relation is set. + * + * @param string $name relation alias + * + * @return bool */ public function hasReference($name) { @@ -2328,9 +2378,10 @@ public function hasReference($name) } /** - * gets a related component + * gets a related component. * * @param string $name + * * @return Doctrine_Record|Doctrine_Collection */ public function reference($name) @@ -2341,22 +2392,24 @@ public function reference($name) } /** - * gets a related component and fails if it does not exist + * gets a related component and fails if it does not exist. * * @param string $name - * @throws Doctrine_Record_Exception if trying to get an unknown related component + * + * @throws Doctrine_Record_Exception if trying to get an unknown related component */ public function obtainReference($name) { if (isset($this->_references[$name])) { return $this->_references[$name]; } - throw new Doctrine_Record_Exception("Unknown reference $name"); + throw new Doctrine_Record_Exception("Unknown reference {$name}"); } /** - * get all related components - * @return array various Doctrine_Collection or Doctrine_Record instances + * get all related components. + * + * @return array various Doctrine_Collection or Doctrine_Record instances */ public function getReferences() { @@ -2364,10 +2417,9 @@ public function getReferences() } /** - * set a related component + * set a related component. * * @param string $alias - * @param Doctrine_Access $coll */ final public function setRelated($alias, Doctrine_Access $coll) { @@ -2376,11 +2428,11 @@ final public function setRelated($alias, Doctrine_Access $coll) /** * loadReference - * loads a related component + * loads a related component. + * + * @param string $name alias of the relation * - * @throws Doctrine_Table_Exception if trying to load an unknown related component - * @param string $name alias of the relation - * @return void + * @throws Doctrine_Table_Exception if trying to load an unknown related component */ public function loadReference($name) { @@ -2389,11 +2441,12 @@ public function loadReference($name) } /** - * call + * call. * - * @param string|array $callback valid callback - * @param string $column column name + * @param string|array $callback valid callback + * @param string $column column name * @param mixed arg1 ... argN optional callback arguments + * * @return Doctrine_Record provides a fluent interface */ public function call($callback, $column) @@ -2409,25 +2462,26 @@ public function call($callback, $column) $this->_data[$fieldName] = $newvalue; } + return $this; } /** - * getter for node associated with this record + * getter for node associated with this record. * - * @return Doctrine_Node false if component is not a Tree + * @return Doctrine_Node false if component is not a Tree */ public function getNode() { - if ( ! $this->_table->isTree()) { + if (!$this->_table->isTree()) { return false; } - if ( ! isset($this->_node)) { + if (!isset($this->_node)) { $this->_node = Doctrine_Node::factory($this, - $this->getTable()->getOption('treeImpl'), - $this->getTable()->getOption('treeOptions') - ); + $this->getTable()->getOption('treeImpl'), + $this->getTable()->getOption('treeOptions') + ); } return $this->_node; @@ -2441,19 +2495,20 @@ public function unshiftFilter(Doctrine_Record_Filter $filter) /** * unlink * removes links from this record to given records - * if no ids are given, it removes all links + * if no ids are given, it removes all links. * - * @param string $alias related component alias - * @param array $ids the identifiers of the related records - * @param boolean $now whether or not to execute now or set as pending unlinks - * @return Doctrine_Record this object (fluent interface) + * @param string $alias related component alias + * @param array $ids the identifiers of the related records + * @param bool $now whether or not to execute now or set as pending unlinks + * + * @return Doctrine_Record this object (fluent interface) */ public function unlink($alias, $ids = array(), $now = false) { $ids = (array) $ids; // fix for #1622 - if ( ! isset($this->_references[$alias]) && $this->hasRelation($alias)) { + if (!isset($this->_references[$alias]) && $this->hasRelation($alias)) { $this->loadReference($alias); } @@ -2474,24 +2529,27 @@ public function unlink($alias, $ids = array(), $now = false) } } - if ( ! $this->exists() || $now === false) { - if ( ! $ids) { + if (!$this->exists() || false === $now) { + if (!$ids) { $ids = $allIds; } foreach ($ids as $id) { $this->_pendingUnlinks[$alias][$id] = true; } + return $this; - } else { - return $this->unlinkInDb($alias, $ids); } + + return $this->unlinkInDb($alias, $ids); } /** - * unlink now the related components, querying the db - * @param string $alias related component alias - * @param array $ids the identifiers of the related records - * @return Doctrine_Record this object (fluent interface) + * unlink now the related components, querying the db. + * + * @param string $alias related component alias + * @param array $ids the identifiers of the related records + * + * @return Doctrine_Record this object (fluent interface) */ public function unlinkInDb($alias, $ids = array()) { @@ -2501,18 +2559,20 @@ public function unlinkInDb($alias, $ids = array()) $q = $rel->getAssociationTable() ->createQuery() ->delete() - ->where($rel->getLocal() . ' = ?', array_values($this->identifier())); + ->where($rel->getLocal().' = ?', array_values($this->identifier())) + ; if (count($ids) > 0) { $q->whereIn($rel->getForeign(), $ids); } $q->execute(); - } else if ($rel instanceof Doctrine_Relation_ForeignKey) { + } elseif ($rel instanceof Doctrine_Relation_ForeignKey) { $q = $rel->getTable()->createQuery() ->update() ->set($rel->getForeign(), '?', array(null)) - ->addWhere($rel->getForeign() . ' = ?', array_values($this->identifier())); + ->addWhere($rel->getForeign().' = ?', array_values($this->identifier())) + ; if (count($ids) > 0) { $q->whereIn($rel->getTable()->getIdentifier(), $ids); @@ -2520,33 +2580,36 @@ public function unlinkInDb($alias, $ids = array()) $q->execute(); } + return $this; } /** - * creates links from this record to given records + * creates links from this record to given records. + * + * @param string $alias related component alias + * @param array $ids the identifiers of the related records + * @param bool $now wether or not to execute now or set pending * - * @param string $alias related component alias - * @param array $ids the identifiers of the related records - * @param boolean $now wether or not to execute now or set pending - * @return Doctrine_Record this object (fluent interface) + * @return Doctrine_Record this object (fluent interface) */ public function link($alias, $ids, $now = false) { $ids = (array) $ids; - if ( ! count($ids)) { + if (!count($ids)) { return $this; } - if ( ! $this->exists() || $now === false) { + if (!$this->exists() || false === $now) { $relTable = $this->getTable()->getRelation($alias)->getTable(); $records = $relTable->createQuery() ->whereIn($relTable->getIdentifier(), $ids) - ->execute(); + ->execute() + ; foreach ($records as $record) { - if ($this->$alias instanceof Doctrine_Record) { + if ($this->{$alias} instanceof Doctrine_Record) { $this->set($alias, $record); } else { if ($c = $this->get($alias)) { @@ -2564,17 +2627,18 @@ public function link($alias, $ids, $now = false) } return $this; - } else { - return $this->linkInDb($alias, $ids); } + + return $this->linkInDb($alias, $ids); } /** - * creates links from this record to given records now, querying the db + * creates links from this record to given records now, querying the db. + * + * @param string $alias related component alias + * @param array $ids the identifiers of the related records * - * @param string $alias related component alias - * @param array $ids the identifiers of the related records - * @return Doctrine_Record this object (fluent interface) + * @return Doctrine_Record this object (fluent interface) */ public function linkInDb($alias, $ids) { @@ -2586,43 +2650,45 @@ public function linkInDb($alias, $ids) if ($rel instanceof Doctrine_Relation_Association) { $modelClassName = $rel->getAssociationTable()->getComponentName(); $localFieldName = $rel->getLocalFieldName(); - $localFieldDef = $rel->getAssociationTable()->getColumnDefinition($localFieldName); + $localFieldDef = $rel->getAssociationTable()->getColumnDefinition($localFieldName); - if ($localFieldDef['type'] == 'integer') { - $identifier = (integer) $identifier; + if ('integer' == $localFieldDef['type']) { + $identifier = (int) $identifier; } $foreignFieldName = $rel->getForeignFieldName(); - $foreignFieldDef = $rel->getAssociationTable()->getColumnDefinition($foreignFieldName); + $foreignFieldDef = $rel->getAssociationTable()->getColumnDefinition($foreignFieldName); - if ($foreignFieldDef['type'] == 'integer') { + if ('integer' == $foreignFieldDef['type']) { foreach ($ids as $i => $id) { - $ids[$i] = (integer) $id; + $ids[$i] = (int) $id; } } foreach ($ids as $id) { - $record = new $modelClassName; + $record = new $modelClassName(); $record[$localFieldName] = $identifier; $record[$foreignFieldName] = $id; $record->save(); } - } else if ($rel instanceof Doctrine_Relation_ForeignKey) { + } elseif ($rel instanceof Doctrine_Relation_ForeignKey) { $q = $rel->getTable() ->createQuery() ->update() - ->set($rel->getForeign(), '?', array_values($this->identifier())); + ->set($rel->getForeign(), '?', array_values($this->identifier())) + ; if (count($ids) > 0) { $q->whereIn($rel->getTable()->getIdentifier(), $ids); } $q->execute(); - } else if ($rel instanceof Doctrine_Relation_LocalKey) { + } elseif ($rel instanceof Doctrine_Relation_LocalKey) { $q = $this->getTable() ->createQuery() ->update() - ->set($rel->getLocalFieldName(), '?', $ids); + ->set($rel->getLocalFieldName(), '?', $ids) + ; if (count($ids) > 0) { $q->whereIn($rel->getTable()->getIdentifier(), array_values($this->identifier())); @@ -2638,19 +2704,17 @@ public function linkInDb($alias, $ids) * Reset the modified array and store the old array in lastModified so it * can be accessed by users after saving a record, since the modified array * is reset after the object is saved. - * - * @return void */ protected function _resetModified() { - if ( ! empty($this->_modified)) { + if (!empty($this->_modified)) { $this->_lastModified = $this->_modified; $this->_modified = array(); } } /** - * magic method used for method overloading + * magic method used for method overloading. * * the function of this method is to try to find a given method from the templates (behaviors) * the record is using, and if found, execute it. Note that already existing methods would not be @@ -2658,14 +2722,16 @@ protected function _resetModified() * * So, in sense, this method replicates the usage of mixins (as seen in some programming languages) * - * @param string $method name of the method - * @param array $args method arguments - * @return mixed the return value of the given method + * @param string $method name of the method + * @param array $args method arguments + * + * @return mixed the return value of the given method */ public function __call($method, $args) { if (($template = $this->_table->getMethodOwner($method)) !== false) { $template->setInvoker($this); + return call_user_func_array(array($template, $method), $args); } @@ -2682,8 +2748,7 @@ public function __call($method, $args) } /** - * used to delete node from tree - MUST BE USE TO DELETE RECORD IF TABLE ACTS AS TREE - * + * used to delete node from tree - MUST BE USE TO DELETE RECORD IF TABLE ACTS AS TREE. */ public function deleteNode() { @@ -2696,11 +2761,12 @@ public function deleteNode() * from the instance pool. * Note: The entity is no longer useable after free() has been called. Any operations * done with the entity afterwards can lead to unpredictable results. - * @param boolean $deep whether to free also the related components + * + * @param bool $deep whether to free also the related components */ public function free($deep = false) { - if ($this->_state != self::STATE_LOCKED && $this->_state != self::STATE_TLOCKED) { + if (self::STATE_LOCKED != $this->_state && self::STATE_TLOCKED != $this->_state) { $this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED; $this->_table->getRepository()->evict($this->_oid); @@ -2710,7 +2776,7 @@ public function free($deep = false) if ($deep) { foreach ($this->_references as $name => $reference) { - if ( ! ($reference instanceof Doctrine_Null)) { + if (!($reference instanceof Doctrine_Null)) { $reference->free($deep); } } @@ -2721,7 +2787,7 @@ public function free($deep = false) } /** - * __toString alias + * __toString alias. * * @return string */ @@ -2731,7 +2797,8 @@ public function toString() } /** - * magic method + * magic method. + * * @return string representation of this object */ public function __toString() diff --git a/lib/Doctrine/Record/Abstract.php b/lib/Doctrine/Record/Abstract.php index 709b72bbd..317076826 100644 --- a/lib/Doctrine/Record/Abstract.php +++ b/lib/Doctrine/Record/Abstract.php @@ -20,38 +20,36 @@ */ /** - * Doctrine_Record_Abstract + * Doctrine_Record_Abstract. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ abstract class Doctrine_Record_Abstract extends Doctrine_Access { /** - * @param Doctrine_Table $_table reference to associated Doctrine_Table instance + * @param Doctrine_Table $_table reference to associated Doctrine_Table instance */ protected $_table; public function setTableDefinition() { - } public function setUp() { - - } + } /** * getTable - * returns the associated table object + * returns the associated table object. * - * @return Doctrine_Table the associated table object + * @return Doctrine_Table the associated table object */ public function getTable() { @@ -59,9 +57,11 @@ public function getTable() } /** - * addListener + * addListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable|Doctrine_Record_Listener_Interface $listener + * @param mixed|null $name + * * @return Doctrine_Record */ public function addListener($listener, $name = null) @@ -72,7 +72,7 @@ public function addListener($listener, $name = null) } /** - * getListener + * getListener. * * @return Doctrine_EventListener_Interface|Doctrine_Overloadable|Doctrine_Record_Listener_Interface */ @@ -82,9 +82,10 @@ public function getListener() } /** - * setListener + * setListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable|Doctrine_Record_Listener_Interface $listener + * * @return Doctrine_Record */ public function setListener($listener) @@ -98,32 +99,30 @@ public function setListener($listener) * index * defines or retrieves an index * if the second parameter is set this method defines an index - * if not this method retrieves index named $name + * if not this method retrieves index named $name. * - * @param string $name the name of the index - * @param array $definition the definition array - * @return mixed + * @param string $name the name of the index + * @param array $definition the definition array */ public function index($name, array $definition = array()) { - if ( ! $definition) { + if (!$definition) { return $this->_table->getIndex($name); - } else { - return $this->_table->addIndex($name, $definition); } + + return $this->_table->addIndex($name, $definition); } /** - * Defines a n-uple of fields that must be unique for every record. + * Defines a n-uple of fields that must be unique for every record. * - * This method Will automatically add UNIQUE index definition + * This method Will automatically add UNIQUE index definition * and validate the values on save. The UNIQUE index is not created in the * database until you use @see export(). * - * @param array $fields values are fieldnames - * @param array $options array of options for unique validator - * @param bool $createUniqueIndex Whether or not to create a unique index in the database - * @return void + * @param array $fields values are fieldnames + * @param array $options array of options for unique validator + * @param bool $createUniqueIndex Whether or not to create a unique index in the database */ public function unique($fields, $options = array(), $createUniqueIndex = true) { @@ -150,21 +149,21 @@ public function setSubclasses($map) $class = get_class($this); // Set the inheritance map for subclasses if (isset($map[$class])) { - // fix for #1621 - $mapFieldNames = $map[$class]; - $mapColumnNames = array(); + // fix for #1621 + $mapFieldNames = $map[$class]; + $mapColumnNames = array(); - foreach ($mapFieldNames as $fieldName => $val) { - $mapColumnNames[$this->getTable()->getColumnName($fieldName)] = $val; + foreach ($mapFieldNames as $fieldName => $val) { + $mapColumnNames[$this->getTable()->getColumnName($fieldName)] = $val; } - + $this->_table->setOption('inheritanceMap', $mapColumnNames); + return; - } else { - // Put an index on the key column - $mapFieldName = array_keys(end($map)); - $this->index($this->getTable()->getTableName().'_'.$mapFieldName[0], array('fields' => array($mapFieldName[0]))); } + // Put an index on the key column + $mapFieldName = array_keys(end($map)); + $this->index($this->getTable()->getTableName().'_'.$mapFieldName[0], array('fields' => array($mapFieldName[0]))); // Set the subclasses array for the parent class $this->_table->setOption('subclasses', array_keys($map)); @@ -172,16 +171,13 @@ public function setSubclasses($map) /** * attribute - * sets or retrieves an option + * sets or retrieves an option. * * @see Doctrine_Core::ATTR_* constants availible attributes - * @param mixed $attr - * @param mixed $value - * @return mixed */ public function attribute($attr, $value) { - if ($value == null) { + if (null == $value) { if (is_array($attr)) { foreach ($attr as $k => $v) { $this->_table->setAttribute($k, $v); @@ -191,21 +187,21 @@ public function attribute($attr, $value) } } else { $this->_table->setAttribute($attr, $value); - } + } } /** * option - * sets or retrieves an option + * sets or retrieves an option. * * @see Doctrine_Table::$options availible options - * @param mixed $name the name of the option - * @param mixed $value options value - * @return mixed + * + * @param mixed $name the name of the option + * @param mixed $value options value */ public function option($name, $value = null) { - if ($value === null) { + if (null === $value) { if (is_array($name)) { foreach ($name as $k => $v) { $this->_table->setOption($k, $v); @@ -219,12 +215,11 @@ public function option($name, $value = null) } /** - * Binds One-to-One aggregate relation + * Binds One-to-One aggregate relation. * - * @param string $componentName the name of the related component - * @param string $options relation options * @see Doctrine_Relation::_$definition - * @return Doctrine_Record this object + * + * @return Doctrine_Record this object */ public function hasOne() { @@ -234,12 +229,11 @@ public function hasOne() } /** - * Binds One-to-Many / Many-to-Many aggregate relation + * Binds One-to-Many / Many-to-Many aggregate relation. * - * @param string $componentName the name of the related component - * @param string $options relation options * @see Doctrine_Relation::_$definition - * @return Doctrine_Record this object + * + * @return Doctrine_Record this object */ public function hasMany() { @@ -249,13 +243,11 @@ public function hasMany() } /** - * Sets a column definition + * Sets a column definition. * * @param string $name * @param string $type - * @param integer $length - * @param mixed $options - * @return void + * @param int $length */ public function hasColumn($name, $type = null, $length = null, $options = array()) { @@ -263,15 +255,12 @@ public function hasColumn($name, $type = null, $length = null, $options = array( } /** - * Set multiple column definitions at once - * - * @param array $definitions - * @return void + * Set multiple column definitions at once. */ public function hasColumns(array $definitions) { foreach ($definitions as $name => $options) { - $length = isset($options['length']) ? $options['length']:null; + $length = isset($options['length']) ? $options['length'] : null; $this->hasColumn($name, $options['type'], $length, $options); } } @@ -289,10 +278,6 @@ public function hasColumns(array $definitions) * 'unique' => true * )); * } - * - * @param string $columnName - * @param array $validators - * @return void */ public function setColumnOptions($name, array $options) { @@ -300,12 +285,11 @@ public function setColumnOptions($name, array $options) } /** - * Set an individual column option + * Set an individual column option. * - * @param string $columnName - * @param string $option - * @param string $value - * @return void + * @param string $columnName + * @param string $option + * @param string $value */ public function setColumnOption($columnName, $option, $value) { @@ -314,21 +298,22 @@ public function setColumnOption($columnName, $option, $value) /** * bindQueryParts - * binds query parts to given component + * binds query parts to given component. * - * @param array $queryParts an array of pre-bound query parts - * @return Doctrine_Record this object + * @param array $queryParts an array of pre-bound query parts + * + * @return Doctrine_Record this object */ public function bindQueryParts(array $queryParts) { - $this->_table->bindQueryParts($queryParts); + $this->_table->bindQueryParts($queryParts); return $this; } public function loadGenerator(Doctrine_Record_Generator $generator) { - $generator->initialize($this->_table); + $generator->initialize($this->_table); $this->_table->addGenerator($generator, get_class($generator)); } @@ -336,31 +321,33 @@ public function loadGenerator(Doctrine_Record_Generator $generator) /** * Loads the given plugin. * - * This method loads a behavior in the record. It will add the behavior + * This method loads a behavior in the record. It will add the behavior * also to the record table if it. * It is tipically called in @see setUp(). * - * @param mixed $tpl if an object, must be a subclass of Doctrine_Template. - * If a string, Doctrine will try to instantiate an object of the classes Doctrine_Template_$tpl and subsequently $tpl, using also autoloading capabilities if defined. - * @param array $options argument to pass to the template constructor if $tpl is a class name - * @throws Doctrine_Record_Exception if $tpl is neither an instance of Doctrine_Template subclass or a valid class name, that could be instantiated. - * @return Doctrine_Record this object; provides a fluent interface. + * @param mixed $tpl if an object, must be a subclass of Doctrine_Template. + * If a string, Doctrine will try to instantiate an object of the classes Doctrine_Template_$tpl and subsequently $tpl, using also autoloading capabilities if defined. + * @param array $options argument to pass to the template constructor if $tpl is a class name + * + * @return Doctrine_Record this object; provides a fluent interface + * + * @throws Doctrine_Record_Exception if $tpl is neither an instance of Doctrine_Template subclass or a valid class name, that could be instantiated */ public function actAs($tpl, array $options = array()) { - if ( ! is_object($tpl)) { - $className = 'Doctrine_Template_' . $tpl; + if (!is_object($tpl)) { + $className = 'Doctrine_Template_'.$tpl; if (class_exists($className, true)) { $tpl = new $className($options); - } else if (class_exists($tpl, true)) { + } elseif (class_exists($tpl, true)) { $tpl = new $tpl($options); } else { - throw new Doctrine_Record_Exception('Could not load behavior named: "' . $tpl . '"'); + throw new Doctrine_Record_Exception('Could not load behavior named: "'.$tpl.'"'); } } - if ( ! ($tpl instanceof Doctrine_Template)) { + if (!($tpl instanceof Doctrine_Template)) { throw new Doctrine_Record_Exception('Loaded behavior class is not an instance of Doctrine_Template.'); } @@ -381,9 +368,10 @@ public function actAs($tpl, array $options = array()) * * This method will add a CHECK constraint to the record table. * - * @param mixed $constraint either a SQL constraint portion or an array of CHECK constraints. If array, all values will be added as constraint - * @param string $name optional constraint name. Not used if $constraint is an array. - * @return Doctrine_Record this object + * @param mixed $constraint either a SQL constraint portion or an array of CHECK constraints. If array, all values will be added as constraint + * @param string $name optional constraint name. Not used if $constraint is an array. + * + * @return Doctrine_Record this object */ public function check($constraint, $name = null) { @@ -394,6 +382,7 @@ public function check($constraint, $name = null) } else { $this->_table->addCheckConstraint($constraint, $name); } + return $this; } } diff --git a/lib/Doctrine/Record/Exception.php b/lib/Doctrine/Record/Exception.php index ceec785cb..0d66e8f06 100644 --- a/lib/Doctrine/Record/Exception.php +++ b/lib/Doctrine/Record/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. * - * @package Doctrine - * @subpackage Record * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Record_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Record/Filter.php b/lib/Doctrine/Record/Filter.php index b122ff723..8cb824920 100644 --- a/lib/Doctrine/Record/Filter.php +++ b/lib/Doctrine/Record/Filter.php @@ -21,14 +21,14 @@ /** * Doctrine_Record_Filter - * Filters the record getters and setters + * Filters the record getters and setters. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1298 $ */ abstract class Doctrine_Record_Filter @@ -65,8 +65,6 @@ abstract public function filterSet(Doctrine_Record $record, $propertyOrRelation, * * @param string $propertyOrRelation * - * @return mixed - * * @thrown Doctrine_Exception when this way is not available */ abstract public function filterGet(Doctrine_Record $record, $propertyOrRelation); diff --git a/lib/Doctrine/Record/Filter/Compound.php b/lib/Doctrine/Record/Filter/Compound.php index 38e599aec..0a92b1b81 100644 --- a/lib/Doctrine/Record/Filter/Compound.php +++ b/lib/Doctrine/Record/Filter/Compound.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Record_Filter_Compound + * Doctrine_Record_Filter_Compound. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1298 $ */ class Doctrine_Record_Filter_Compound extends Doctrine_Record_Filter @@ -72,7 +72,7 @@ public function filterSet(Doctrine_Record $record, $propertyOrRelation, $value) // Related to PHP-7.0 compatibility so an explicit call to method get is required. $record[$alias]; - if ( ! $record->exists()) { + if (!$record->exists()) { if (isset($record[$alias][$propertyOrRelation])) { $record[$alias][$propertyOrRelation] = $value; @@ -94,8 +94,6 @@ public function filterSet(Doctrine_Record $record, $propertyOrRelation, $value) * * @param string $propertyOrRelation * - * @return mixed - * * @thrown Doctrine_Record_UnknownPropertyException when this way is not available */ public function filterGet(Doctrine_Record $record, $propertyOrRelation) @@ -105,7 +103,7 @@ public function filterGet(Doctrine_Record $record, $propertyOrRelation) // Related to PHP-7.0 compatibility so an explicit call to method get is required. $record[$alias]; - if ( ! $record->exists()) { + if (!$record->exists()) { if (isset($record[$alias][$propertyOrRelation])) { return $record[$alias][$propertyOrRelation]; } diff --git a/lib/Doctrine/Record/Filter/Standard.php b/lib/Doctrine/Record/Filter/Standard.php index f2a665358..42d0a0033 100644 --- a/lib/Doctrine/Record/Filter/Standard.php +++ b/lib/Doctrine/Record/Filter/Standard.php @@ -21,14 +21,14 @@ /** * Doctrine_Record_Filter_Standard - * Filters the record getters and setters + * Filters the record getters and setters. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1298 $ */ class Doctrine_Record_Filter_Standard extends Doctrine_Record_Filter diff --git a/lib/Doctrine/Record/Generator.php b/lib/Doctrine/Record/Generator.php index 728207ee0..e2a397a79 100644 --- a/lib/Doctrine/Record/Generator.php +++ b/lib/Doctrine/Record/Generator.php @@ -20,44 +20,44 @@ */ /** - * Doctrine_Record_Generator + * Doctrine_Record_Generator. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Plugin * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ abstract class Doctrine_Record_Generator extends Doctrine_Record_Abstract { /** - * _options + * _options. * - * @var array $_options an array of plugin specific options + * @var array an array of plugin specific options */ protected $_options = array( - 'generateFiles' => false, - 'generatePath' => false, + 'generateFiles' => false, + 'generatePath' => false, 'builderOptions' => array(), - 'identifier' => false, - 'table' => false, - 'pluginTable' => false, - 'children' => array(), - 'cascadeDelete' => true, - 'appLevelDelete' => false + 'identifier' => false, + 'table' => false, + 'pluginTable' => false, + 'children' => array(), + 'cascadeDelete' => true, + 'appLevelDelete' => false, ); /** - * Whether or not the generator has been initialized + * Whether or not the generator has been initialized. * - * @var bool $_initialized + * @var bool */ protected $_initialized = false; /** - * An alias for getOption + * An alias for getOption. * * @param string $option */ @@ -66,53 +66,52 @@ public function __get($option) if (isset($this->_options[$option])) { return $this->_options[$option]; } + return null; } /** - * __isset + * __isset. * * @param string $option */ - public function __isset($option) + public function __isset($option) { return isset($this->_options[$option]); } /** - * Returns the value of an option + * Returns the value of an option. * - * @param $option the name of the option to retrieve - * @return mixed the value of the option + * @return mixed the value of the option */ public function getOption($name) { - if ( ! isset($this->_options[$name])) { - throw new Doctrine_Exception('Unknown option ' . $name); + if (!isset($this->_options[$name])) { + throw new Doctrine_Exception('Unknown option '.$name); } - + return $this->_options[$name]; } /** - * Sets given value to an option + * Sets given value to an option. + * + * @param $value the value of the option * - * @param $option the name of the option to be changed - * @param $value the value of the option - * @return Doctrine_Plugin this object + * @return Doctrine_Plugin this object */ public function setOption($name, $value) { $this->_options[$name] = $value; - + return $this; } /** - * Add child record generator + * Add child record generator. * - * @param Doctrine_Record_Generator $generator - * @return void + * @param Doctrine_Record_Generator $generator */ public function addChild($generator) { @@ -120,9 +119,9 @@ public function addChild($generator) } /** - * Returns all options and their associated values + * Returns all options and their associated values. * - * @return array all options as an associative array + * @return array all options as an associative array */ public function getOptions() { @@ -130,18 +129,16 @@ public function getOptions() } /** - * Initialize the plugin. Call in Doctrine_Template setTableDefinition() in order to initiate a generator in a template + * Initialize the plugin. Call in Doctrine_Template setTableDefinition() in order to initiate a generator in a template. * * @see Doctrine_Template_I18n - * @param Doctrine_Table $table - * @return void */ public function initialize(Doctrine_Table $table) { - if ($this->_initialized) { - return false; - } - + if ($this->_initialized) { + return false; + } + $this->_initialized = true; $this->initOptions(); @@ -161,8 +158,9 @@ public function initialize(Doctrine_Table $table) } // check that class doesn't exist (otherwise we cannot create it) - if ($this->_options['generateFiles'] === false && class_exists($this->_options['className'])) { + if (false === $this->_options['generateFiles'] && class_exists($this->_options['className'])) { $this->_table = Doctrine_Core::getTable($this->_options['className']); + return false; } @@ -187,12 +185,10 @@ public function initialize(Doctrine_Table $table) /** * Create the new Doctrine_Table instance in $this->_table based on the owning * table. - * - * @return void */ public function buildTable() { - // Bind model + // Bind model $conn = $this->_options['table']->getConnection(); $bindConnName = $conn->getManager()->getConnectionForComponent($this->_options['table']->getComponentName())->getName(); if ($bindConnName) { @@ -203,7 +199,7 @@ public function buildTable() // Create table $tableClass = $conn->getAttribute(Doctrine_Core::ATTR_TABLE_CLASS); - $this->_table = new $tableClass($this->_options['className'], $conn); + $this->_table = new $tableClass($this->_options['className'], $conn); $this->_table->setGenerator($this); // If custom table name set then lets use it @@ -227,31 +223,26 @@ public function buildTable() $conn->addTable($this->_table); } - /** + /** * Empty template method for providing the concrete plugins the ability - * to initialize options before the actual definition is being built - * - * @return void + * to initialize options before the actual definition is being built. */ public function initOptions() { - } /** - * Build the child behavior definitions that are attached to this generator - * - * @return void + * Build the child behavior definitions that are attached to this generator. */ public function buildChildDefinitions() { - if ( ! isset($this->_options['children'])) { + if (!isset($this->_options['children'])) { throw new Doctrine_Record_Exception("Unknown option 'children'."); } foreach ($this->_options['children'] as $child) { if ($child instanceof Doctrine_Template) { - if ($child->getPlugin() !== null) { + if (null !== $child->getPlugin()) { $this->_table->addGenerator($child->getPlugin(), get_class($child->getPlugin())); } @@ -273,8 +264,9 @@ public function buildChildDefinitions() * These columns are automatically added to the generated model so we can * create foreign keys back to the table object that owns the plugin. * - * @param Doctrine_Table $table the table object that owns the plugin - * @return array an array of foreign key definitions + * @param Doctrine_Table $table the table object that owns the plugin + * + * @return array an array of foreign key definitions */ public function buildForeignKeys(Doctrine_Table $table) { @@ -283,53 +275,50 @@ public function buildForeignKeys(Doctrine_Table $table) foreach ((array) $table->getIdentifier() as $field) { $def = $table->getDefinitionOf($field); - unset($def['autoincrement']); - unset($def['sequence']); - unset($def['primary']); + unset($def['autoincrement'], $def['sequence'], $def['primary']); - $col = $table->hasColumn($field) ? $field : $table->getColumnName($field) . ' as ' . $field; + $col = $table->hasColumn($field) ? $field : $table->getColumnName($field).' as '.$field; $def['primary'] = true; $fk[$col] = $def; } + return $fk; } /** - * Build the local relationship on the generated model for this generator - * instance which points to the invoking table in $this->_options['table'] + * Build the local relationship on the generated model for this generator + * instance which points to the invoking table in $this->_options['table']. * * @param string $alias Alias of the foreign relation - * @return void */ public function buildLocalRelation($alias = null) { $options = array( - 'local' => $this->getRelationLocalKey(), - 'foreign' => $this->getRelationForeignKey(), - 'owningSide' => true + 'local' => $this->getRelationLocalKey(), + 'foreign' => $this->getRelationForeignKey(), + 'owningSide' => true, ); - if (isset($this->_options['cascadeDelete']) && $this->_options['cascadeDelete'] && ! $this->_options['appLevelDelete']) { + if (isset($this->_options['cascadeDelete']) && $this->_options['cascadeDelete'] && !$this->_options['appLevelDelete']) { $options['onDelete'] = 'CASCADE'; $options['onUpdate'] = 'CASCADE'; } $aliasStr = ''; - if ($alias !== null) { - $aliasStr = ' as ' . $alias; + if (null !== $alias) { + $aliasStr = ' as '.$alias; } - $this->hasOne($this->_options['table']->getComponentName() . $aliasStr, $options); + $this->hasOne($this->_options['table']->getComponentName().$aliasStr, $options); } /** - * Add a Doctrine_Relation::MANY relationship to the generator owner table + * Add a Doctrine_Relation::MANY relationship to the generator owner table. * - * @param string $name - * @param array $options - * @return void + * @param string $name + * @param array $options */ public function ownerHasMany($name, $options) { @@ -337,11 +326,10 @@ public function ownerHasMany($name, $options) } /** - * Add a Doctrine_Relation::ONE relationship to the generator owner table + * Add a Doctrine_Relation::ONE relationship to the generator owner table. * - * @param string $name - * @param array $options - * @return void + * @param string $name + * @param array $options */ public function ownerHasOne($name, $options) { @@ -353,14 +341,13 @@ public function ownerHasOne($name, $options) * which points back to the model generated in this generator instance. * * @param string $alias Alias of the foreign relation - * @return void */ public function buildForeignRelation($alias = null) { $options = array( - 'local' => $this->getRelationForeignKey(), - 'foreign' => $this->getRelationLocalKey(), - 'localKey' => false + 'local' => $this->getRelationForeignKey(), + 'foreign' => $this->getRelationLocalKey(), + 'localKey' => false, ); if (isset($this->_options['cascadeDelete']) && $this->_options['cascadeDelete'] && $this->_options['appLevelDelete']) { @@ -369,15 +356,15 @@ public function buildForeignRelation($alias = null) $aliasStr = ''; - if ($alias !== null) { - $aliasStr = ' as ' . $alias; + if (null !== $alias) { + $aliasStr = ' as '.$alias; } - $this->ownerHasMany($this->_table->getComponentName() . $aliasStr, $options); + $this->ownerHasMany($this->_table->getComponentName().$aliasStr, $options); } /** - * Get the local key of the generated relationship + * Get the local key of the generated relationship. * * @return string $local */ @@ -387,7 +374,7 @@ public function getRelationLocalKey() } /** - * Get the foreign key of the generated relationship + * Get the foreign key of the generated relationship. * * @return string $foreign */ @@ -402,16 +389,14 @@ public function getRelationForeignKey() return $column; } } - + return $identifier; } /** - * This method can be used for generating the relation from the plugin + * This method can be used for generating the relation from the plugin * table to the owner table. By default buildForeignRelation() and buildLocalRelation() are called - * Those methods can be overridden or this entire method can be overridden - * - * @return void + * Those methods can be overridden or this entire method can be overridden. */ public function buildRelation() { @@ -420,10 +405,7 @@ public function buildRelation() } /** - * Generate a Doctrine_Record from a populated Doctrine_Table instance - * - * @param Doctrine_Table $table - * @return void + * Generate a Doctrine_Record from a populated Doctrine_Table instance. */ public function generateClassFromTable(Doctrine_Table $table) { @@ -436,11 +418,10 @@ public function generateClassFromTable(Doctrine_Table $table) } /** - * Generates the class definition for plugin class + * Generates the class definition for plugin class. * - * @param array $definition Definition array defining columns, relations and options - * for the model - * @return void + * @param array $definition Definition array defining columns, relations and options + * for the model */ public function generateClass(array $definition = array()) { @@ -451,7 +432,7 @@ public function generateClass(array $definition = array()) } $builder = new Doctrine_Import_Builder(); - $builderOptions = isset($this->_options['builderOptions']) ? (array) $this->_options['builderOptions']:array(); + $builderOptions = isset($this->_options['builderOptions']) ? (array) $this->_options['builderOptions'] : array(); $builder->setOptions($builderOptions); if ($this->_options['generateFiles']) { @@ -467,4 +448,4 @@ public function generateClass(array $definition = array()) eval($def); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Record/Iterator.php b/lib/Doctrine/Record/Iterator.php index 6385c0131..a8ba4a863 100644 --- a/lib/Doctrine/Record/Iterator.php +++ b/lib/Doctrine/Record/Iterator.php @@ -20,32 +20,30 @@ */ /** - * Doctrine_Record_Iterator + * Doctrine_Record_Iterator. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Record_Iterator extends ArrayIterator { /** - * @var Doctrine_Record $record + * @var Doctrine_Record */ private $record; /** - * @var Doctrine_Null $null + * @var Doctrine_Null */ private static $null; /** - * constructor - * - * @param Doctrine_Record $record + * constructor. */ public function __construct(Doctrine_Record $record) { @@ -54,9 +52,7 @@ public function __construct(Doctrine_Record $record) } /** - * initNullObject - * - * @param Doctrine_Null $null + * initNullObject. */ public static function initNullObject(Doctrine_Null $null) { @@ -64,19 +60,17 @@ public static function initNullObject(Doctrine_Null $null) } /** - * current - * - * @return mixed + * current. */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function current() { $value = parent::current(); if ($value === self::$null) { return null; - } else { - return $value; } + + return $value; } } diff --git a/lib/Doctrine/Record/Listener.php b/lib/Doctrine/Record/Listener.php index 24e8858dd..355465f47 100644 --- a/lib/Doctrine/Record/Listener.php +++ b/lib/Doctrine/Record/Listener.php @@ -20,120 +20,140 @@ */ /** - * Doctrine_Record_Listener + * Doctrine_Record_Listener. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Record_Listener implements Doctrine_Record_Listener_Interface { /** - * @var array $_options an array containing options + * @var array an array containing options */ - protected $_options = array('disabled' => false); - - /** - * setOption - * sets an option in order to allow flexible listener - * - * @param mixed $name the name of the option to set - * @param mixed $value the value of the option - */ - public function setOption($name, $value = null) - { - if (is_array($name)) { - $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $name); - } else { - $this->_options[$name] = $value; + protected $_options = array('disabled' => false); + + /** + * setOption + * sets an option in order to allow flexible listener. + * + * @param mixed $name the name of the option to set + * @param mixed $value the value of the option + */ + public function setOption($name, $value = null) + { + if (is_array($name)) { + $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $name); + } else { + $this->_options[$name] = $value; } } - + /** * getOptions - * returns all options of this template and the associated values + * returns all options of this template and the associated values. * - * @return array all options and their values + * @return array all options and their values */ public function getOptions() { return $this->_options; } - /** - * getOption - * returns the value of given option - * - * @param string $name the name of the option - * @return mixed the value of given option - */ - public function getOption($name) - { - if (isset($this->_options[$name])) { - return $this->_options[$name]; - } + /** + * getOption + * returns the value of given option. + * + * @param string $name the name of the option + * + * @return mixed the value of given option + */ + public function getOption($name) + { + if (isset($this->_options[$name])) { + return $this->_options[$name]; + } - return null; + return null; } - + public function preSerialize(Doctrine_Event $event) - { } + { + } public function postSerialize(Doctrine_Event $event) - { } + { + } public function preUnserialize(Doctrine_Event $event) - { } + { + } public function postUnserialize(Doctrine_Event $event) - { } + { + } public function preDqlSelect(Doctrine_Event $event) - { } + { + } public function preSave(Doctrine_Event $event) - { } + { + } public function postSave(Doctrine_Event $event) - { } + { + } public function preDqlDelete(Doctrine_Event $event) - { } + { + } public function preDelete(Doctrine_Event $event) - { } + { + } public function postDelete(Doctrine_Event $event) - { } + { + } public function preDqlUpdate(Doctrine_Event $event) - { } + { + } public function preUpdate(Doctrine_Event $event) - { } + { + } public function postUpdate(Doctrine_Event $event) - { } + { + } public function preInsert(Doctrine_Event $event) - { } + { + } public function postInsert(Doctrine_Event $event) - { } + { + } public function preHydrate(Doctrine_Event $event) - { } + { + } public function postHydrate(Doctrine_Event $event) - { } + { + } public function preValidate(Doctrine_Event $event) - { } - + { + } + public function postValidate(Doctrine_Event $event) - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Record/Listener/Chain.php b/lib/Doctrine/Record/Listener/Chain.php index 93a10937c..e7932b7cb 100644 --- a/lib/Doctrine/Record/Listener/Chain.php +++ b/lib/Doctrine/Record/Listener/Chain.php @@ -22,62 +22,63 @@ /** * Doctrine_Record_Listener_Chain * this class represents a chain of different listeners, - * useful for having multiple listeners listening the events at the same time + * useful for having multiple listeners listening the events at the same time. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Record_Listener_Chain extends Doctrine_Access implements Doctrine_Record_Listener_Interface { /** - * @var array $listeners an array containing all listeners + * @var array an array containing all listeners */ protected $_listeners = array(); /** - * @var array $_options an array containing chain options + * @var array an array containing chain options + */ + protected $_options = array('disabled' => false); + + /** + * setOption + * sets an option in order to allow flexible listener chaining. + * + * @param mixed $name the name of the option to set + * @param mixed $value the value of the option + */ + public function setOption($name, $value = null) + { + if (is_array($name)) { + $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $name); + } else { + $this->_options[$name] = $value; + } + } + + /** + * getOption + * returns the value of given option. + * + * @param string $name the name of the option + * + * @return mixed the value of given option */ - protected $_options = array('disabled' => false); - - /** - * setOption - * sets an option in order to allow flexible listener chaining - * - * @param mixed $name the name of the option to set - * @param mixed $value the value of the option - */ - public function setOption($name, $value = null) - { - if (is_array($name)) { - $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $name); - } else { - $this->_options[$name] = $value; + public function getOption($name) + { + if (isset($this->_options[$name])) { + return $this->_options[$name]; } - } - - /** - * getOption - * returns the value of given option - * - * @param string $name the name of the option - * @return mixed the value of given option - */ - public function getOption($name) - { - if (isset($this->_options[$name])) { - return $this->_options[$name]; - } - - return null; + + return null; } /** - * Get array of configured options + * Get array of configured options. * * @return array $options */ @@ -88,20 +89,18 @@ public function getOptions() /** * add - * adds a listener to the chain of listeners + * adds a listener to the chain of listeners. * * @param object $listener * @param string $name - * @return void */ public function add($listener, $name = null) { - if ( ! ($listener instanceof Doctrine_Record_Listener_Interface) && - ! ($listener instanceof Doctrine_Overloadable)) { - + if (!($listener instanceof Doctrine_Record_Listener_Interface) + && !($listener instanceof Doctrine_Overloadable)) { throw new Doctrine_EventListener_Exception("Couldn't add eventlistener. Record listeners should implement either Doctrine_Record_Listener_Interface or Doctrine_Overloadable"); } - if ($name === null) { + if (null === $name) { $this->_listeners[] = $listener; } else { $this->_listeners[$name] = $listener; @@ -110,25 +109,23 @@ public function add($listener, $name = null) /** * returns a Doctrine_Record_Listener on success - * and null on failure - * - * @param mixed $key - * @return mixed + * and null on failure. */ public function get($key) { - if ( ! isset($this->_listeners[$key])) { + if (!isset($this->_listeners[$key])) { return null; } + return $this->_listeners[$key]; } /** - * set + * set. * - * @param mixed $key - * @param Doctrine_Record_Listener $listener listener to be added - * @return Doctrine_Record_Listener_Chain this object + * @param Doctrine_Record_Listener $listener listener to be added + * + * @return Doctrine_Record_Listener_Chain this object */ public function set($key, $listener) { @@ -137,13 +134,13 @@ public function set($key, $listener) public function preSerialize(Doctrine_Event $event) { - $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preSerialize', $disabled))) { + $disabled = $this->getOption('disabled'); + + if (true !== $disabled && !(is_array($disabled) && in_array('preSerialize', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preSerialize', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preSerialize', $disabled))) { $listener->preSerialize($event); } } @@ -153,12 +150,12 @@ public function preSerialize(Doctrine_Event $event) public function postSerialize(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postSerialize', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postSerialize', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postSerialize', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postSerialize', $disabled))) { $listener->postSerialize($event); } } @@ -168,12 +165,12 @@ public function postSerialize(Doctrine_Event $event) public function preUnserialize(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preUnserialize', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preUnserialize', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preUnserialize', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preUnserialize', $disabled))) { $listener->preUnserialize($event); } } @@ -183,12 +180,12 @@ public function preUnserialize(Doctrine_Event $event) public function postUnserialize(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postUnserialize', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postUnserialize', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postUnserialize', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postUnserialize', $disabled))) { $listener->postUnserialize($event); } } @@ -198,12 +195,12 @@ public function postUnserialize(Doctrine_Event $event) public function preDqlSelect(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlSelect', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlSelect', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlSelect', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlSelect', $disabled))) { $listener->preDqlSelect($event); } } @@ -213,12 +210,12 @@ public function preDqlSelect(Doctrine_Event $event) public function preSave(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preSave', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preSave', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preSave', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preSave', $disabled))) { $listener->preSave($event); } } @@ -228,12 +225,12 @@ public function preSave(Doctrine_Event $event) public function postSave(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postSave', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postSave', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postSave', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postSave', $disabled))) { $listener->postSave($event); } } @@ -243,12 +240,12 @@ public function postSave(Doctrine_Event $event) public function preDqlDelete(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlDelete', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlDelete', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlDelete', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlDelete', $disabled))) { $listener->preDqlDelete($event); } } @@ -258,12 +255,12 @@ public function preDqlDelete(Doctrine_Event $event) public function preDelete(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preDelete', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preDelete', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preDelete', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preDelete', $disabled))) { $listener->preDelete($event); } } @@ -273,12 +270,12 @@ public function preDelete(Doctrine_Event $event) public function postDelete(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postDelete', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postDelete', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postDelete', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postDelete', $disabled))) { $listener->postDelete($event); } } @@ -288,12 +285,12 @@ public function postDelete(Doctrine_Event $event) public function preDqlUpdate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlUpdate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlUpdate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlUpdate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlUpdate', $disabled))) { $listener->preDqlUpdate($event); } } @@ -303,12 +300,12 @@ public function preDqlUpdate(Doctrine_Event $event) public function preUpdate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preUpdate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preUpdate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preUpdate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preUpdate', $disabled))) { $listener->preUpdate($event); } } @@ -318,12 +315,12 @@ public function preUpdate(Doctrine_Event $event) public function postUpdate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postUpdate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postUpdate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postUpdate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postUpdate', $disabled))) { $listener->postUpdate($event); } } @@ -333,12 +330,12 @@ public function postUpdate(Doctrine_Event $event) public function preInsert(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preInsert', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preInsert', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preInsert', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preInsert', $disabled))) { $listener->preInsert($event); } } @@ -348,12 +345,12 @@ public function preInsert(Doctrine_Event $event) public function postInsert(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postInsert', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postInsert', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postInsert', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postInsert', $disabled))) { $listener->postInsert($event); } } @@ -363,12 +360,12 @@ public function postInsert(Doctrine_Event $event) public function preHydrate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preHydrate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preHydrate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preHydrate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preHydrate', $disabled))) { $listener->preHydrate($event); } } @@ -378,45 +375,45 @@ public function preHydrate(Doctrine_Event $event) public function postHydrate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postHydrate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postHydrate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postHydrate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postHydrate', $disabled))) { $listener->postHydrate($event); } } } } - + public function preValidate(Doctrine_Event $event) - { + { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preValidate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preValidate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preValidate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preValidate', $disabled))) { $listener->preValidate($event); } } } } - + public function postValidate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postValidate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postValidate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postValidate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postValidate', $disabled))) { $listener->postValidate($event); } } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Record/Listener/Interface.php b/lib/Doctrine/Record/Listener/Interface.php index bb2ce6ae2..c32b52138 100644 --- a/lib/Doctrine/Record/Listener/Interface.php +++ b/lib/Doctrine/Record/Listener/Interface.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Record_Listener + * Doctrine_Record_Listener. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ interface Doctrine_Record_Listener_Interface @@ -61,8 +61,8 @@ public function postUpdate(Doctrine_Event $event); public function preInsert(Doctrine_Event $event); public function postInsert(Doctrine_Event $event); - + public function preHydrate(Doctrine_Event $event); - + public function postHydrate(Doctrine_Event $event); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Record/State/Exception.php b/lib/Doctrine/Record/State/Exception.php index bbafb7006..0c5d320c2 100644 --- a/lib/Doctrine/Record/State/Exception.php +++ b/lib/Doctrine/Record/State/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. * - * @package Doctrine - * @subpackage Record * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Record_State_Exception extends Doctrine_Record_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Record/UnknownPropertyException.php b/lib/Doctrine/Record/UnknownPropertyException.php index 389004f89..9461e1d4c 100644 --- a/lib/Doctrine/Record/UnknownPropertyException.php +++ b/lib/Doctrine/Record/UnknownPropertyException.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Record_UnknownPropertyException + * Doctrine_Record_UnknownPropertyException. * - * @package Doctrine - * @subpackage Record * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 4252 $ + * * @author Konsta Vesterinen */ class Doctrine_Record_UnknownPropertyException extends Doctrine_Record_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Relation.php b/lib/Doctrine/Relation.php index cbdcb6ff2..2818e0167 100644 --- a/lib/Doctrine/Relation.php +++ b/lib/Doctrine/Relation.php @@ -21,66 +21,67 @@ /** * Doctrine_Relation - * This class represents a relation between components + * This class represents a relation between components. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Relation implements ArrayAccess { /** - * RELATION CONSTANTS + * RELATION CONSTANTS. */ /** - * constant for ONE_TO_ONE and MANY_TO_ONE relationships + * constant for ONE_TO_ONE and MANY_TO_ONE relationships. */ - const ONE = 0; + public const ONE = 0; /** - * constant for MANY_TO_MANY and ONE_TO_MANY relationships + * constant for MANY_TO_MANY and ONE_TO_MANY relationships. */ - const MANY = 1; + public const MANY = 1; // TRUE => mandatory, everything else is just a default value. this should be refactored // since TRUE can bot be used as a default value this way. All values should be default values. /** - * @var array $definition @see __construct() + * @var array @see __construct() */ - protected $definition = array('alias' => true, - 'foreign' => true, - 'local' => true, - 'class' => true, - 'type' => true, - 'table' => true, - 'localTable' => true, - 'name' => null, - 'refTable' => null, - 'onDelete' => null, - 'onUpdate' => null, - 'deferred' => null, - 'deferrable' => null, - 'constraint' => null, - 'equal' => false, - 'cascade' => array(), // application-level cascades - 'owningSide' => false, // whether this is the owning side - 'refClassRelationAlias' => null, - 'foreignKeyName' => null, - 'orderBy' => null - ); - - protected $_isRefClass = null; + protected $definition = array('alias' => true, + 'foreign' => true, + 'local' => true, + 'class' => true, + 'type' => true, + 'table' => true, + 'localTable' => true, + 'name' => null, + 'refTable' => null, + 'onDelete' => null, + 'onUpdate' => null, + 'deferred' => null, + 'deferrable' => null, + 'constraint' => null, + 'equal' => false, + 'cascade' => array(), // application-level cascades + 'owningSide' => false, // whether this is the owning side + 'refClassRelationAlias' => null, + 'foreignKeyName' => null, + 'orderBy' => null, + ); + + protected $_isRefClass; /** - * constructor + * constructor. * - * @param array $definition an associative array with the following structure: - * name foreign key constraint name + * @param array $definition an associative array with the following structure: + * name foreign key constraint name * * local the local field(s) * @@ -129,8 +130,8 @@ public function __construct(array $definition) { $def = array(); foreach ($this->definition as $key => $val) { - if ( ! isset($definition[$key]) && $val) { - throw new Doctrine_Exception($key . ' is required!'); + if (!isset($definition[$key]) && $val) { + throw new Doctrine_Exception($key.' is required!'); } if (isset($definition[$key])) { $def[$key] = $definition[$key]; @@ -143,15 +144,15 @@ public function __construct(array $definition) /** * hasConstraint - * whether or not this relation has an explicit constraint + * whether or not this relation has an explicit constraint. * - * @return boolean + * @return bool */ public function hasConstraint() { - return ($this->definition['constraint'] || - ($this->definition['onUpdate']) || - ($this->definition['onDelete'])); + return $this->definition['constraint'] + || $this->definition['onUpdate'] + || $this->definition['onDelete']; } public function isDeferred() @@ -172,16 +173,13 @@ public function isEqual() /** * @return bool */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetExists($offset) { return isset($this->definition[$offset]); } - /** - * @return mixed - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetGet($offset) { if (isset($this->definition[$offset])) { @@ -191,10 +189,7 @@ public function offsetGet($offset) return null; } - /** - * @return void - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetSet($offset, $value) { if (isset($this->definition[$offset])) { @@ -202,17 +197,14 @@ public function offsetSet($offset, $value) } } - /** - * @return void - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetUnset($offset) { $this->definition[$offset] = false; } /** - * toArray + * toArray. * * @return array */ @@ -223,7 +215,7 @@ public function toArray() /** * getAlias - * returns the relation alias + * returns the relation alias. * * @return string */ @@ -234,10 +226,11 @@ final public function getAlias() /** * getType - * returns the relation type, either 0 or 1 + * returns the relation type, either 0 or 1. * * @see Doctrine_Relation MANY_* and ONE_* constants - * @return integer + * + * @return int */ final public function getType() { @@ -248,7 +241,7 @@ final public function getType() * Checks whether this relation cascades deletions to the related objects * on the application level. * - * @return boolean + * @return bool */ public function isCascadeDelete() { @@ -257,20 +250,21 @@ public function isCascadeDelete() /** * getTable - * returns the foreign table object + * returns the foreign table object. * * @return Doctrine_Table */ final public function getTable() { return Doctrine_Manager::getInstance() - ->getConnectionForComponent($this->definition['class']) - ->getTable($this->definition['class']); + ->getConnectionForComponent($this->definition['class']) + ->getTable($this->definition['class']) + ; } /** * getClass - * returns the name of the related class + * returns the name of the related class. * * @return string */ @@ -281,7 +275,7 @@ final public function getClass() /** * getLocal - * returns the name of the local column + * returns the name of the local column. * * @return string */ @@ -292,7 +286,7 @@ final public function getLocal() /** * getLocalFieldName - * returns the field name of the local column + * returns the field name of the local column. */ final public function getLocalFieldName() { @@ -301,7 +295,7 @@ final public function getLocalFieldName() /** * getLocalColumnName - * returns the column name of the local column + * returns the column name of the local column. * * @return string $columnName */ @@ -313,7 +307,7 @@ final public function getLocalColumnName() /** * getForeign * returns the name of the foreignkey column where - * the localkey column is pointing at + * the localkey column is pointing at. * * @return string */ @@ -324,7 +318,7 @@ final public function getForeign() /** * getLocalFieldName - * returns the field name of the foreign column + * returns the field name of the foreign column. */ final public function getForeignFieldName() { @@ -333,56 +327,54 @@ final public function getForeignFieldName() /** * getForeignColumnName - * returns the column name of the foreign column + * returns the column name of the foreign column. * * @return string $columnName */ final public function getForeignColumnName() { - return $this->definition['table']->getColumnName($this->definition['foreign']); + return $this->definition['table']->getColumnName($this->definition['foreign']); } /** * isOneToOne - * returns whether or not this relation is a one-to-one relation + * returns whether or not this relation is a one-to-one relation. * - * @return boolean + * @return bool */ final public function isOneToOne() { - return ($this->definition['type'] == Doctrine_Relation::ONE); + return Doctrine_Relation::ONE == $this->definition['type']; } /** - * getRelationDql + * getRelationDql. + * + * @param int $count * - * @param integer $count * @return string */ public function getRelationDql($count) { $component = $this->getTable()->getComponentName(); - $dql = 'FROM ' . $component - . ' WHERE ' . $component . '.' . $this->definition['foreign'] - . ' IN (' . substr(str_repeat('?, ', $count), 0, -2) . ')' - . $this->getOrderBy($component); - - return $dql; + return 'FROM '.$component + .' WHERE '.$component.'.'.$this->definition['foreign'] + .' IN ('.substr(str_repeat('?, ', $count), 0, -2).')' + .$this->getOrderBy($component); } /** - * fetchRelatedFor + * fetchRelatedFor. * * fetches a component related to given record * - * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ abstract public function fetchRelatedFor(Doctrine_Record $record); /** - * Get the name of the foreign key for this relationship + * Get the name of the foreign key for this relationship. * * @return string $foreignKeyName */ @@ -391,59 +383,62 @@ public function getForeignKeyName() if (isset($this->definition['foreignKeyName'])) { return $this->definition['foreignKeyName']; } + return $this['localTable']->getConnection()->generateUniqueRelationForeignKeyName($this); } /** - * Get the relationship orderby SQL/DQL + * Get the relationship orderby SQL/DQL. + * + * @param string $alias The alias to use + * @param bool $columnNames Whether or not to use column names instead of field names * - * @param string $alias The alias to use - * @param boolean $columnNames Whether or not to use column names instead of field names * @return string $orderBy */ public function getOrderBy($alias = null, $columnNames = false) { - if ( ! $alias) { - $alias = $this->getTable()->getComponentName(); + if (!$alias) { + $alias = $this->getTable()->getComponentName(); } if ($orderBy = $this->getOrderByStatement($alias, $columnNames)) { - return ' ORDER BY ' . $orderBy; + return ' ORDER BY '.$orderBy; } } /** - * Get the relationship orderby statement + * Get the relationship orderby statement. + * + * @param string $alias The alias to use + * @param bool $columnNames Whether or not to use column names instead of field names * - * @param string $alias The alias to use - * @param boolean $columnNames Whether or not to use column names instead of field names * @return string $orderByStatement */ public function getOrderByStatement($alias = null, $columnNames = false) { $table = $this->getTable(); - if ( ! $alias) { - $alias = $table->getComponentName(); + if (!$alias) { + $alias = $table->getComponentName(); } if (isset($this->definition['orderBy'])) { return $table->processOrderBy($alias, $this->definition['orderBy'], $columnNames); - } else { - return $table->getOrderByStatement($alias, $columnNames); } + + return $table->getOrderByStatement($alias, $columnNames); } public function isRefClass() { - if ($this->_isRefClass === null) { + if (null === $this->_isRefClass) { $this->_isRefClass = false; $table = $this->getTable(); foreach ($table->getRelations() as $name => $relation) { foreach ($relation['table']->getRelations() as $relation) { if (isset($relation['refTable']) && $relation['refTable'] === $table) { $this->_isRefClass = true; - break(2); + break 2; } } } @@ -453,20 +448,21 @@ public function isRefClass() } /** - * __toString + * __toString. * * @return string */ public function __toString() { - $r[] = "
";
+        $r[] = '
';
         foreach ($this->definition as $k => $v) {
             if (is_object($v)) {
-                $v = 'Object(' . get_class($v) . ')';
+                $v = 'Object('.get_class($v).')';
             }
-            $r[] = $k . ' : ' . $v;
+            $r[] = $k.' : '.$v;
         }
-        $r[] = "
"; + $r[] = '
'; + return implode("\n", $r); } } diff --git a/lib/Doctrine/Relation/Association.php b/lib/Doctrine/Relation/Association.php index 6d4c3ca7f..35543c312 100644 --- a/lib/Doctrine/Relation/Association.php +++ b/lib/Doctrine/Relation/Association.php @@ -22,15 +22,15 @@ /** * Doctrine_Relation_Association this class takes care of association mapping * (= many-to-many relationships, where the relationship is handled with an additional relational table - * which holds 2 foreign keys) + * which holds 2 foreign keys). * - * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Association extends Doctrine_Relation @@ -49,29 +49,30 @@ public function getAssociationTable() } /** - * getRelationDql + * getRelationDql. + * + * @param int $count * - * @param integer $count * @return string */ public function getRelationDql($count, $context = 'record') { $table = $this->definition['refTable']; $component = $this->definition['refTable']->getComponentName(); - + switch ($context) { - case "record": - $sub = substr(str_repeat("?, ", $count),0,-2); - $dql = 'FROM ' . $this->getTable()->getComponentName(); - $dql .= '.' . $component; - $dql .= ' WHERE ' . $this->getTable()->getComponentName() - . '.' . $component . '.' . $this->getLocalRefColumnName() . ' IN (' . $sub . ')'; + case 'record': + $sub = substr(str_repeat('?, ', $count), 0, -2); + $dql = 'FROM '.$this->getTable()->getComponentName(); + $dql .= '.'.$component; + $dql .= ' WHERE '.$this->getTable()->getComponentName() + .'.'.$component.'.'.$this->getLocalRefColumnName().' IN ('.$sub.')'; $dql .= $this->getOrderBy($this->getTable()->getComponentName(), false); break; - case "collection": - $sub = substr(str_repeat("?, ", $count),0,-2); - $dql = 'FROM ' . $component . '.' . $this->getTable()->getComponentName(); - $dql .= ' WHERE ' . $component . '.' . $this->getLocalRefColumnName() . ' IN (' . $sub . ')'; + case 'collection': + $sub = substr(str_repeat('?, ', $count), 0, -2); + $dql = 'FROM '.$component.'.'.$this->getTable()->getComponentName(); + $dql .= ' WHERE '.$component.'.'.$this->getLocalRefColumnName().' IN ('.$sub.')'; $dql .= $this->getOrderBy($component, false); break; } @@ -79,59 +80,59 @@ public function getRelationDql($count, $context = 'record') return $dql; } - /** + /** * getLocalRefColumnName - * returns the column name of the local reference column + * returns the column name of the local reference column. */ final public function getLocalRefColumnName() { - return $this->definition['refTable']->getColumnName($this->definition['local']); + return $this->definition['refTable']->getColumnName($this->definition['local']); } /** * getLocalRefFieldName - * returns the field name of the local reference column + * returns the field name of the local reference column. */ final public function getLocalRefFieldName() { - return $this->definition['refTable']->getFieldName($this->definition['local']); + return $this->definition['refTable']->getFieldName($this->definition['local']); } /** * getForeignRefColumnName - * returns the column name of the foreign reference column + * returns the column name of the foreign reference column. */ final public function getForeignRefColumnName() { - return $this->definition['refTable']->getColumnName($this->definition['foreign']); + return $this->definition['refTable']->getColumnName($this->definition['foreign']); } /** * getForeignRefFieldName - * returns the field name of the foreign reference column + * returns the field name of the foreign reference column. */ final public function getForeignRefFieldName() { - return $this->definition['refTable']->getFieldName($this->definition['foreign']); + return $this->definition['refTable']->getFieldName($this->definition['foreign']); } /** - * fetchRelatedFor + * fetchRelatedFor. * * fetches a component related to given record * - * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->getIncremented(); - if (empty($id) || ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { + if (empty($id) || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $coll = Doctrine_Collection::create($this->getTable()); } else { $coll = $this->getTable()->getConnection()->query($this->getRelationDql(1), array($id)); } $coll->setReference($record, $this); + return $coll; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Relation/Association/Self.php b/lib/Doctrine/Relation/Association/Self.php index 1f9487bed..5f53d25b7 100644 --- a/lib/Doctrine/Relation/Association/Self.php +++ b/lib/Doctrine/Relation/Association/Self.php @@ -20,22 +20,24 @@ */ /** - * Doctrine_Relation_Association_Self + * Doctrine_Relation_Association_Self. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Association_Self extends Doctrine_Relation_Association { /** - * getRelationDql + * getRelationDql. + * + * @param int $count * - * @param integer $count * @return string */ public function getRelationDql($count, $context = 'record') @@ -44,73 +46,74 @@ public function getRelationDql($count, $context = 'record') case 'record': $identifierColumnNames = $this->definition['table']->getIdentifierColumnNames(); $identifier = array_pop($identifierColumnNames); - $sub = 'SELECT '.$this->definition['foreign'] - . ' FROM '.$this->definition['refTable']->getTableName() - . ' WHERE '.$this->definition['local'] - . ' = ?'; + $sub = 'SELECT '.$this->definition['foreign'] + .' FROM '.$this->definition['refTable']->getTableName() + .' WHERE '.$this->definition['local'] + .' = ?'; - $sub2 = 'SELECT '.$this->definition['local'] - . ' FROM '.$this->definition['refTable']->getTableName() - . ' WHERE '.$this->definition['foreign'] - . ' = ?'; + $sub2 = 'SELECT '.$this->definition['local'] + .' FROM '.$this->definition['refTable']->getTableName() + .' WHERE '.$this->definition['foreign'] + .' = ?'; - $dql = 'FROM ' . $this->definition['table']->getComponentName() - . '.' . $this->definition['refTable']->getComponentName() - . ' WHERE ' . $this->definition['table']->getComponentName() - . '.' . $identifier - . ' IN (' . $sub . ')' - . ' || ' . $this->definition['table']->getComponentName() - . '.' . $identifier - . ' IN (' . $sub2 . ')'; + $dql = 'FROM '.$this->definition['table']->getComponentName() + .'.'.$this->definition['refTable']->getComponentName() + .' WHERE '.$this->definition['table']->getComponentName() + .'.'.$identifier + .' IN ('.$sub.')' + .' || '.$this->definition['table']->getComponentName() + .'.'.$identifier + .' IN ('.$sub2.')'; - $dql .= $this->getOrderBy($this->definition['table']->getComponentName(), false); + $dql .= $this->getOrderBy($this->definition['table']->getComponentName(), false); break; case 'collection': - $sub = substr(str_repeat('?, ', $count),0,-2); - $dql = 'FROM '.$this->definition['refTable']->getComponentName() - . '.' . $this->definition['table']->getComponentName() - . ' WHERE '.$this->definition['refTable']->getComponentName() - . '.' . $this->definition['local'] . ' IN (' . $sub . ')'; + $sub = substr(str_repeat('?, ', $count), 0, -2); + $dql = 'FROM '.$this->definition['refTable']->getComponentName() + .'.'.$this->definition['table']->getComponentName() + .' WHERE '.$this->definition['refTable']->getComponentName() + .'.'.$this->definition['local'].' IN ('.$sub.')'; $dql .= $this->getOrderBy($this->definition['refTable']->getComponentName(), false); - }; + } return $dql; } public function fetchRelatedFor(Doctrine_Record $record) { - $id = $record->getIncremented(); + $id = $record->getIncremented(); $q = new Doctrine_RawSql(); $assocTable = $this->getAssociationFactory()->getTableName(); - $tableName = $record->getTable()->getTableName(); + $tableName = $record->getTable()->getTableName(); $identifierColumnNames = $record->getTable()->getIdentifierColumnNames(); $identifier = array_pop($identifierColumnNames); - $sub = 'SELECT '.$this->getForeign(). + $sub = 'SELECT '.$this->getForeign(). ' FROM '.$assocTable. ' WHERE '.$this->getLocal(). ' = ?'; - $sub2 = 'SELECT '.$this->getLocal(). + $sub2 = 'SELECT '.$this->getLocal(). ' FROM '.$assocTable. ' WHERE '.$this->getForeign(). ' = ?'; $q->select('{'.$tableName.'.*}, {'.$assocTable.'.*}') - ->from($tableName . ' INNER JOIN '.$assocTable.' ON '. - $tableName . '.' . $identifier . ' = ' . $assocTable . '.' . $this->getLocal() . ' OR ' . - $tableName . '.' . $identifier . ' = ' . $assocTable . '.' . $this->getForeign() - ) - ->where($tableName.'.'.$identifier.' IN ('.$sub.') OR '. - $tableName.'.'.$identifier.' IN ('.$sub2.')' - ); - $q->addComponent($tableName, $record->getTable()->getComponentName()); - $q->addComponent($assocTable, $record->getTable()->getComponentName(). '.' . $this->getAssociationFactory()->getComponentName()); + ->from($tableName.' INNER JOIN '.$assocTable.' ON '. + $tableName.'.'.$identifier.' = '.$assocTable.'.'.$this->getLocal().' OR '. + $tableName.'.'.$identifier.' = '.$assocTable.'.'.$this->getForeign() + ) + ->where($tableName.'.'.$identifier.' IN ('.$sub.') OR '. + $tableName.'.'.$identifier.' IN ('.$sub2.')' + ) + ; + $q->addComponent($tableName, $record->getTable()->getComponentName()); + $q->addComponent($assocTable, $record->getTable()->getComponentName().'.'.$this->getAssociationFactory()->getComponentName()); $q->orderBy($this->getOrderByStatement($tableName, true)); return $q->execute(array($id, $id)); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Relation/Exception.php b/lib/Doctrine/Relation/Exception.php index 8937b9e2b..53e96f3cd 100644 --- a/lib/Doctrine/Relation/Exception.php +++ b/lib/Doctrine/Relation/Exception.php @@ -17,18 +17,20 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * . - */ + */ /** - * Doctrine_Relation_Exception + * Doctrine_Relation_Exception. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1344 $ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Relation/ForeignKey.php b/lib/Doctrine/Relation/ForeignKey.php index f07bbefbf..09f056faa 100644 --- a/lib/Doctrine/Relation/ForeignKey.php +++ b/lib/Doctrine/Relation/ForeignKey.php @@ -21,24 +21,23 @@ /** * Doctrine_Relation_ForeignKey - * This class represents a foreign key relation + * This class represents a foreign key relation. * - * @package Doctrine - * @subpackage Relation * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Relation_ForeignKey extends Doctrine_Relation { /** - * fetchRelatedFor + * fetchRelatedFor. * * fetches a component related to given record * - * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) @@ -46,55 +45,54 @@ public function fetchRelatedFor(Doctrine_Record $record) $id = array(); $localTable = $record->getTable(); foreach ((array) $this->definition['local'] as $local) { - $value = $record->get($localTable->getFieldName($local)); - if (isset($value)) { - $id[] = $value; - } + $value = $record->get($localTable->getFieldName($local)); + if (isset($value)) { + $id[] = $value; + } } if ($this->isOneToOne()) { - if ( ! $record->exists() || empty($id) || - ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { - + if (!$record->exists() || empty($id) + || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $related = $this->getTable()->create(); } else { - $dql = 'FROM ' . $this->getTable()->getComponentName() - . ' WHERE ' . $this->getCondition() . $this->getOrderBy(null, false); + $dql = 'FROM '.$this->getTable()->getComponentName() + .' WHERE '.$this->getCondition().$this->getOrderBy(null, false); $coll = $this->getTable()->getConnection()->query($dql, $id); $related = $coll[0]; } $related->set($related->getTable()->getFieldName($this->definition['foreign']), - $record, false); + $record, false); } else { - - if ( ! $record->exists() || empty($id) || - ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { - + if (!$record->exists() || empty($id) + || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $related = Doctrine_Collection::create($this->getTable()); } else { - $query = $this->getRelationDql(1); - $related = $this->getTable()->getConnection()->query($query, $id); + $query = $this->getRelationDql(1); + $related = $this->getTable()->getConnection()->query($query, $id); } $related->setReference($record, $this); } + return $related; } /** - * getCondition + * getCondition. * * @param string $alias */ public function getCondition($alias = null) { - if ( ! $alias) { - $alias = $this->getTable()->getComponentName(); + if (!$alias) { + $alias = $this->getTable()->getComponentName(); } $conditions = array(); foreach ((array) $this->definition['foreign'] as $foreign) { - $conditions[] = $alias . '.' . $foreign . ' = ?'; + $conditions[] = $alias.'.'.$foreign.' = ?'; } + return implode(' AND ', $conditions); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Relation/LocalKey.php b/lib/Doctrine/Relation/LocalKey.php index 1663b9681..4910b6f1f 100644 --- a/lib/Doctrine/Relation/LocalKey.php +++ b/lib/Doctrine/Relation/LocalKey.php @@ -21,24 +21,23 @@ /** * Doctrine_Relation_LocalKey - * This class represents a local key relation + * This class represents a local key relation. * - * @package Doctrine - * @subpackage Relation * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Relation_LocalKey extends Doctrine_Relation { /** - * fetchRelatedFor + * fetchRelatedFor. * * fetches a component related to given record * - * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) @@ -46,24 +45,25 @@ public function fetchRelatedFor(Doctrine_Record $record) $localFieldName = $record->getTable()->getFieldName($this->definition['local']); $id = $record->get($localFieldName); - if (is_null($id) || ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { + if (is_null($id) || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $related = $this->getTable()->create(); - // Ticket #1131 Patch. - if ( ! is_null($id)) { + // Ticket #1131 Patch. + if (!is_null($id)) { $related->assignIdentifier($id); $related->state(Doctrine_Record::STATE_PROXY); } } else { - $dql = 'FROM ' . $this->getTable()->getComponentName() - . ' WHERE ' . $this->getCondition() . $this->getOrderBy(null, false); + $dql = 'FROM '.$this->getTable()->getComponentName() + .' WHERE '.$this->getCondition().$this->getOrderBy(null, false); $related = $this->getTable() - ->getConnection() - ->query($dql, array($id)) - ->getFirst(); - - if ( ! $related || empty($related)) { + ->getConnection() + ->query($dql, array($id)) + ->getFirst() + ; + + if (!$related || empty($related)) { $related = $this->getTable()->create(); } } @@ -74,15 +74,16 @@ public function fetchRelatedFor(Doctrine_Record $record) } /** - * getCondition + * getCondition. * * @param string $alias */ public function getCondition($alias = null) { - if ( ! $alias) { - $alias = $this->getTable()->getComponentName(); + if (!$alias) { + $alias = $this->getTable()->getComponentName(); } - return $alias . '.' . $this->definition['foreign'] . ' = ?'; + + return $alias.'.'.$this->definition['foreign'].' = ?'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Relation/Nest.php b/lib/Doctrine/Relation/Nest.php index 65b5f7325..cbedd7b04 100644 --- a/lib/Doctrine/Relation/Nest.php +++ b/lib/Doctrine/Relation/Nest.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Relation_Association_Self + * Doctrine_Relation_Association_Self. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1434 $ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Nest extends Doctrine_Relation_Association @@ -36,55 +37,53 @@ public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->getIncremented(); - if (empty($id) || ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { + if (empty($id) || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { return Doctrine_Collection::create($this->getTable()); - } else { - $q = new Doctrine_RawSql($this->getTable()->getConnection()); - $formatter = $q->getConnection()->formatter; - - $assocTable = $this->getAssociationFactory()->getTableName(); - $tableName = $record->getTable()->getTableName(); - $identifierColumnNames = $record->getTable()->getIdentifierColumnNames(); - $identifier = $formatter->quoteIdentifier(array_pop($identifierColumnNames)); + } + $q = new Doctrine_RawSql($this->getTable()->getConnection()); + $formatter = $q->getConnection()->formatter; - $sub = 'SELECT ' . $formatter->quoteIdentifier($this->getForeignRefColumnName()) - . ' FROM ' . $formatter->quoteIdentifier($assocTable) - . ' WHERE ' . $formatter->quoteIdentifier($this->getLocalRefColumnName()) - . ' = ?'; + $assocTable = $this->getAssociationFactory()->getTableName(); + $tableName = $record->getTable()->getTableName(); + $identifierColumnNames = $record->getTable()->getIdentifierColumnNames(); + $identifier = $formatter->quoteIdentifier(array_pop($identifierColumnNames)); - $condition[] = $formatter->quoteIdentifier($tableName) . '.' . $identifier . ' IN (' . $sub . ')'; - $joinCondition[] = $formatter->quoteIdentifier($tableName) . '.' . $identifier . ' = ' . $formatter->quoteIdentifier($assocTable) . '.' . $formatter->quoteIdentifier($this->getForeignRefColumnName()); + $sub = 'SELECT '.$formatter->quoteIdentifier($this->getForeignRefColumnName()) + .' FROM '.$formatter->quoteIdentifier($assocTable) + .' WHERE '.$formatter->quoteIdentifier($this->getLocalRefColumnName()) + .' = ?'; - if ($this->definition['equal']) { - $sub2 = 'SELECT ' . $formatter->quoteIdentifier($this->getLocalRefColumnName()) - . ' FROM ' . $formatter->quoteIdentifier($assocTable) - . ' WHERE ' . $formatter->quoteIdentifier($this->getForeignRefColumnName()) - . ' = ?'; + $condition[] = $formatter->quoteIdentifier($tableName).'.'.$identifier.' IN ('.$sub.')'; + $joinCondition[] = $formatter->quoteIdentifier($tableName).'.'.$identifier.' = '.$formatter->quoteIdentifier($assocTable).'.'.$formatter->quoteIdentifier($this->getForeignRefColumnName()); - $condition[] = $formatter->quoteIdentifier($tableName) . '.' . $identifier . ' IN (' . $sub2 . ')'; - $joinCondition[] = $formatter->quoteIdentifier($tableName) . '.' . $identifier . ' = ' . $formatter->quoteIdentifier($assocTable) . '.' . $formatter->quoteIdentifier($this->getLocalRefColumnName()); - } - $q->select('{'.$tableName.'.*}, {'.$assocTable.'.*}') - ->from($formatter->quoteIdentifier($tableName) . ' INNER JOIN ' . $formatter->quoteIdentifier($assocTable) . ' ON ' . implode(' OR ', $joinCondition)) - ->where(implode(' OR ', $condition)); - if ($orderBy = $this->getOrderByStatement($tableName, true)) { - $q->addOrderBy($orderBy); - } else { - $q->addOrderBy($formatter->quoteIdentifier($tableName) . '.' . $identifier . ' ASC'); - } - $q->addComponent($tableName, $this->getClass()); + if ($this->definition['equal']) { + $sub2 = 'SELECT '.$formatter->quoteIdentifier($this->getLocalRefColumnName()) + .' FROM '.$formatter->quoteIdentifier($assocTable) + .' WHERE '.$formatter->quoteIdentifier($this->getForeignRefColumnName()) + .' = ?'; - $path = $this->getClass(). '.' . $this->getAssociationFactory()->getComponentName(); - if ($this->definition['refClassRelationAlias']) { - $path = $this->getClass(). '.' . $this->definition['refClassRelationAlias']; - } - $q->addComponent($assocTable, $path); + $condition[] = $formatter->quoteIdentifier($tableName).'.'.$identifier.' IN ('.$sub2.')'; + $joinCondition[] = $formatter->quoteIdentifier($tableName).'.'.$identifier.' = '.$formatter->quoteIdentifier($assocTable).'.'.$formatter->quoteIdentifier($this->getLocalRefColumnName()); + } + $q->select('{'.$tableName.'.*}, {'.$assocTable.'.*}') + ->from($formatter->quoteIdentifier($tableName).' INNER JOIN '.$formatter->quoteIdentifier($assocTable).' ON '.implode(' OR ', $joinCondition)) + ->where(implode(' OR ', $condition)) + ; + if ($orderBy = $this->getOrderByStatement($tableName, true)) { + $q->addOrderBy($orderBy); + } else { + $q->addOrderBy($formatter->quoteIdentifier($tableName).'.'.$identifier.' ASC'); + } + $q->addComponent($tableName, $this->getClass()); - $params = ($this->definition['equal']) ? array($id, $id) : array($id); + $path = $this->getClass().'.'.$this->getAssociationFactory()->getComponentName(); + if ($this->definition['refClassRelationAlias']) { + $path = $this->getClass().'.'.$this->definition['refClassRelationAlias']; + } + $q->addComponent($assocTable, $path); - $res = $q->execute($params); + $params = ($this->definition['equal']) ? array($id, $id) : array($id); - return $res; - } + return $q->execute($params); } } diff --git a/lib/Doctrine/Relation/Parser.php b/lib/Doctrine/Relation/Parser.php index 45eda5bd5..214f92a1a 100644 --- a/lib/Doctrine/Relation/Parser.php +++ b/lib/Doctrine/Relation/Parser.php @@ -20,38 +20,39 @@ */ /** - * Doctrine_Relation_Parser + * Doctrine_Relation_Parser. * - * @package Doctrine - * @subpackage Relation * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @todo Composite key support? */ class Doctrine_Relation_Parser { /** - * @var Doctrine_Table $_table the table object this parser belongs to + * @var Doctrine_Table the table object this parser belongs to */ protected $_table; /** - * @var array $_relations an array containing all the Doctrine_Relation objects for this table + * @var array an array containing all the Doctrine_Relation objects for this table */ protected $_relations = array(); /** - * @var array $_pending relations waiting for parsing + * @var array relations waiting for parsing */ - protected $_pending = array(); + protected $_pending = array(); /** - * constructor + * constructor. * - * @param Doctrine_Table $table the table object this parser belongs to + * @param Doctrine_Table $table the table object this parser belongs to */ public function __construct(Doctrine_Table $table) { @@ -59,9 +60,9 @@ public function __construct(Doctrine_Table $table) } /** - * getTable + * getTable. * - * @return Doctrine_Table the table object this parser belongs to + * @return Doctrine_Table the table object this parser belongs to */ public function getTable() { @@ -69,23 +70,23 @@ public function getTable() } /** - * getPendingRelation + * getPendingRelation. * - * @return array an array defining a pending relation + * @return array an array defining a pending relation */ public function getPendingRelation($name) { - if ( ! isset($this->_pending[$name])) { - throw new Doctrine_Relation_Exception('Unknown pending relation ' . $name); + if (!isset($this->_pending[$name])) { + throw new Doctrine_Relation_Exception('Unknown pending relation '.$name); } return $this->_pending[$name]; } /** - * getPendingRelations + * getPendingRelations. * - * @return array an array containing all the pending relations + * @return array an array containing all the pending relations */ public function getPendingRelations() { @@ -94,24 +95,25 @@ public function getPendingRelations() /** * unsetPendingRelations - * Removes a relation. Warning: this only affects pending relations + * Removes a relation. Warning: this only affects pending relations. * * @param string relation to remove */ public function unsetPendingRelations($name) { - unset($this->_pending[$name]); + unset($this->_pending[$name]); } /** - * Check if a relation alias exists + * Check if a relation alias exists. * * @param string $name - * @return boolean $bool + * + * @return bool $bool */ public function hasRelation($name) { - if ( ! isset($this->_pending[$name]) && ! isset($this->_relations[$name])) { + if (!isset($this->_pending[$name]) && !isset($this->_relations[$name])) { return false; } @@ -119,11 +121,9 @@ public function hasRelation($name) } /** - * binds a relation + * binds a relation. * * @param string $name - * @param string $field - * @return void */ public function bind($name, $options = array()) { @@ -134,13 +134,12 @@ public function bind($name, $options = array()) $name = $e[0]; $alias = isset($e[1]) ? $e[1] : $name; - if ( ! isset($options['type'])) { + if (!isset($options['type'])) { throw new Doctrine_Relation_Exception('Relation type not set.'); } if ($this->hasRelation($alias)) { - unset($this->_relations[$alias]); - unset($this->_pending[$alias]); + unset($this->_relations[$alias], $this->_pending[$alias]); } $this->_pending[$alias] = array_merge($options, array('class' => $name, 'alias' => $alias)); @@ -149,9 +148,9 @@ public function bind($name, $options = array()) } /** - * getRelation + * getRelation. * - * @param string $alias relation alias + * @param string $alias relation alias */ public function getRelation($alias, $recursive = true) { @@ -172,30 +171,29 @@ public function getRelation($alias, $recursive = true) $backRefRelationName = isset($def['refClassRelationAlias']) ? $def['refClassRelationAlias'] : $def['refClass']; - if ( ! isset($this->_pending[$backRefRelationName]) && ! isset($this->_relations[$backRefRelationName])) { - + if (!isset($this->_pending[$backRefRelationName]) && !isset($this->_relations[$backRefRelationName])) { $parser = $def['refTable']->getRelationParser(); - if ( ! $parser->hasRelation($this->_table->getComponentName())) { + if (!$parser->hasRelation($this->_table->getComponentName())) { $parser->bind($this->_table->getComponentName(), - array('type' => Doctrine_Relation::ONE, - 'local' => $def['local'], - 'foreign' => $idColumnName, - 'localKey' => true, - )); + array('type' => Doctrine_Relation::ONE, + 'local' => $def['local'], + 'foreign' => $idColumnName, + 'localKey' => true, + )); } - if ( ! $this->hasRelation($backRefRelationName)) { + if (!$this->hasRelation($backRefRelationName)) { if (in_array($def['class'], $localClasses)) { - $this->bind($def['refClass'] . " as " . $backRefRelationName, array( - 'type' => Doctrine_Relation::MANY, - 'foreign' => $def['foreign'], - 'local' => $idColumnName)); + $this->bind($def['refClass'].' as '.$backRefRelationName, array( + 'type' => Doctrine_Relation::MANY, + 'foreign' => $def['foreign'], + 'local' => $idColumnName)); } else { - $this->bind($def['refClass'] . " as " . $backRefRelationName, array( - 'type' => Doctrine_Relation::MANY, - 'foreign' => $def['local'], - 'local' => $idColumnName)); + $this->bind($def['refClass'].' as '.$backRefRelationName, array( + 'type' => Doctrine_Relation::MANY, + 'foreign' => $def['local'], + 'local' => $idColumnName)); } } } @@ -216,7 +214,7 @@ public function getRelation($alias, $recursive = true) foreach ($foreign as $fk) { // Check if its already not indexed (primary key) - if ( ! $rel['table']->isIdentifier($rel['table']->getFieldName($fk))) { + if (!$rel['table']->isIdentifier($rel['table']->getFieldName($fk))) { $rel['table']->addIndex($fk, array('fields' => array($fk))); } } @@ -228,6 +226,7 @@ public function getRelation($alias, $recursive = true) // unset pending relation unset($this->_pending[$alias]); $this->_relations[$alias] = $rel; + return $rel; } } @@ -235,16 +234,15 @@ public function getRelation($alias, $recursive = true) $this->getRelations(); return $this->getRelation($alias, false); - } else { - throw new Doctrine_Table_Exception('Unknown relation alias ' . $alias); } + throw new Doctrine_Table_Exception('Unknown relation alias '.$alias); } /** * getRelations - * returns an array containing all relation objects + * returns an array containing all relation objects. * - * @return array an array of Doctrine_Relation objects + * @return array an array of Doctrine_Relation objects */ public function getRelations() { @@ -259,7 +257,7 @@ public function getRelations() * getImpl * returns the table class of the concrete implementation for given template * if the given template is not a template then this method just returns the - * table class for the given record + * table class for the given record. * * @param string $template */ @@ -270,8 +268,8 @@ public function getImpl($template) if (class_exists($template) && in_array('Doctrine_Template', class_parents($template))) { $impl = $this->_table->getImpl($template); - if ($impl === null) { - throw new Doctrine_Relation_Parser_Exception("Couldn't find concrete implementation for template " . $template); + if (null === $impl) { + throw new Doctrine_Relation_Parser_Exception("Couldn't find concrete implementation for template ".$template); } } else { $impl = $template; @@ -281,10 +279,11 @@ public function getImpl($template) } /** - * Completes the given association definition + * Completes the given association definition. * - * @param array $def definition array to be completed - * @return array completed definition array + * @param array $def definition array to be completed + * + * @return array completed definition array */ public function completeAssocDefinition($def) { @@ -297,20 +296,19 @@ public function completeAssocDefinition($def) $id = $def['refTable']->getIdentifierColumnNames(); if (count($id) > 1) { - if ( ! isset($def['foreign'])) { + if (!isset($def['foreign'])) { // foreign key not set // try to guess the foreign key $def['foreign'] = ($def['local'] === $id[0]) ? $id[1] : $id[0]; } - if ( ! isset($def['local'])) { + if (!isset($def['local'])) { // foreign key not set // try to guess the foreign key $def['local'] = ($def['foreign'] === $id[0]) ? $id[1] : $id[0]; } } else { - - if ( ! isset($def['foreign'])) { + if (!isset($def['foreign'])) { // foreign key not set // try to guess the foreign key @@ -318,7 +316,7 @@ public function completeAssocDefinition($def) $def['foreign'] = $columns; } - if ( ! isset($def['local'])) { + if (!isset($def['local'])) { // local key not set // try to guess the local key $columns = $this->getIdentifiers($this->_table); @@ -326,17 +324,18 @@ public function completeAssocDefinition($def) $def['local'] = $columns; } } + return $def; } /** * getIdentifiers - * gives a list of identifiers from given table + * gives a list of identifiers from given table. * * the identifiers are in format: * [componentName].[identifier] * - * @param Doctrine_Table $table table object to retrieve identifiers from + * @param Doctrine_Table $table table object to retrieve identifiers from */ public function getIdentifiers(Doctrine_Table $table) { @@ -344,22 +343,23 @@ public function getIdentifiers(Doctrine_Table $table) if (is_array($table->getIdentifier())) { $columns = array(); foreach ((array) $table->getIdentifierColumnNames() as $identColName) { - $columns[] = $componentNameToLower . '_' . $identColName; + $columns[] = $componentNameToLower.'_'.$identColName; } } else { - $columns = $componentNameToLower . '_' . $table->getColumnName( - $table->getIdentifier()); + $columns = $componentNameToLower.'_'.$table->getColumnName( + $table->getIdentifier()); } return $columns; } /** - * guessColumns + * guessColumns. + * + * @param array $classes an array of class names + * @param Doctrine_Table $foreignTable foreign table object * - * @param array $classes an array of class names - * @param Doctrine_Table $foreignTable foreign table object - * @return array an array of column names + * @return array an array of column names */ public function guessColumns(array $classes, Doctrine_Table $foreignTable) { @@ -367,15 +367,15 @@ public function guessColumns(array $classes, Doctrine_Table $foreignTable) foreach ($classes as $class) { try { - $table = $conn->getTable($class); + $table = $conn->getTable($class); } catch (Doctrine_Table_Exception $e) { continue; } $columns = $this->getIdentifiers($table); - $found = true; + $found = true; foreach ((array) $columns as $column) { - if ( ! $foreignTable->hasColumn($column)) { + if (!$foreignTable->hasColumn($column)) { $found = false; break; } @@ -385,7 +385,7 @@ public function guessColumns(array $classes, Doctrine_Table $foreignTable) } } - if ( ! $found) { + if (!$found) { throw new Doctrine_Relation_Exception("Couldn't find columns."); } @@ -393,10 +393,12 @@ public function guessColumns(array $classes, Doctrine_Table $foreignTable) } /** - * Completes the given definition + * Completes the given definition. + * + * @param array $def definition array to be completed + * + * @return array completed definition array * - * @param array $def definition array to be completed - * @return array completed definition array * @todo Description: What does it mean to complete a definition? What is done (not how)? * Refactor (too long & nesting level) */ @@ -408,7 +410,7 @@ public function completeDefinition($def) $def['class'] = $def['table']->getComponentName(); $foreignClasses = array_merge($def['table']->getOption('parents'), array($def['class'])); - $localClasses = array_merge($this->_table->getOption('parents'), array($this->_table->getComponentName())); + $localClasses = array_merge($this->_table->getOption('parents'), array($this->_table->getComponentName())); $localIdentifierColumnNames = $this->_table->getIdentifierColumnNames(); $localIdentifierCount = count($localIdentifierColumnNames); @@ -419,7 +421,7 @@ public function completeDefinition($def) if (isset($def['local'])) { $def['local'] = $def['localTable']->getColumnName($def['local']); - if ( ! isset($def['foreign'])) { + if (!isset($def['foreign'])) { // local key is set, but foreign key is not // try to guess the foreign key @@ -434,14 +436,14 @@ public function completeDefinition($def) } else { $def['foreign'] = $def['table']->getColumnName($def['foreign']); - if ($localIdentifierCount == 1) { + if (1 == $localIdentifierCount) { if ($def['local'] == $localIdColumnName && isset($def['owningSide']) - && $def['owningSide'] === true) { + && true === $def['owningSide']) { $def['localKey'] = true; - } else if (($def['local'] !== $localIdColumnName && $def['type'] == Doctrine_Relation::ONE)) { + } elseif ($def['local'] !== $localIdColumnName && Doctrine_Relation::ONE == $def['type']) { $def['localKey'] = true; } - } else if ($localIdentifierCount > 1 && ! isset($def['localKey'])) { + } elseif ($localIdentifierCount > 1 && !isset($def['localKey'])) { // It's a composite key and since 'foreign' can not point to a composite // key currently, we know that 'local' must be the foreign key. $def['localKey'] = true; @@ -475,31 +477,33 @@ public function completeDefinition($def) $identifierColumnNames = $table->getIdentifierColumnNames(); $idColumnName = array_pop($identifierColumnNames); $column = strtolower($table->getComponentName()) - . '_' . $idColumnName; + .'_'.$idColumnName; foreach ($foreignClasses as $class2) { $table2 = $conn->getTable($class2); if ($table2->hasColumn($column)) { $def['foreign'] = $column; $def['local'] = $idColumnName; + return $def; } } } foreach ($foreignClasses as $class) { - $table = $conn->getTable($class); + $table = $conn->getTable($class); $identifierColumnNames = $table->getIdentifierColumnNames(); $idColumnName = array_pop($identifierColumnNames); $column = strtolower($table->getComponentName()) - . '_' . $idColumnName; + .'_'.$idColumnName; foreach ($localClasses as $class2) { $table2 = $conn->getTable($class2); if ($table2->hasColumn($column)) { - $def['foreign'] = $idColumnName; - $def['local'] = $column; + $def['foreign'] = $idColumnName; + $def['local'] = $column; $def['localKey'] = true; + return $def; } } @@ -510,17 +514,13 @@ public function completeDefinition($def) foreach ((array) $this->_table->getIdentifierColumnNames() as $id) { // ?? should this not be $this->_table->getComponentName() ?? $column = strtolower($table->getComponentName()) - . '_' . $id; + .'_'.$id; $col = $this->_table->getColumnDefinition($id); $type = $col['type']; $length = $col['length']; - unset($col['type']); - unset($col['length']); - unset($col['autoincrement']); - unset($col['sequence']); - unset($col['primary']); + unset($col['type'], $col['length'], $col['autoincrement'], $col['sequence'], $col['primary']); $def['table']->setColumn($column, $type, $length, $col); @@ -534,6 +534,7 @@ public function completeDefinition($def) $def['local'] = $localIdColumnName; } } + return $def; } } diff --git a/lib/Doctrine/Relation/Parser/Exception.php b/lib/Doctrine/Relation/Parser/Exception.php index b8447bfbd..77a813983 100644 --- a/lib/Doctrine/Relation/Parser/Exception.php +++ b/lib/Doctrine/Relation/Parser/Exception.php @@ -17,18 +17,20 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * . - */ + */ /** - * Doctrine_Relation_Parser_Exception + * Doctrine_Relation_Parser_Exception. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Parser_Exception extends Doctrine_Relation_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Search.php b/lib/Doctrine/Search.php index f6449b3c4..ecf943df4 100644 --- a/lib/Doctrine/Search.php +++ b/lib/Doctrine/Search.php @@ -20,51 +20,49 @@ */ /** - * Doctrine_Search + * Doctrine_Search. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search extends Doctrine_Record_Generator { - const INDEX_FILES = 0; - - const INDEX_TABLES = 1; - - protected $_options = array('generateFiles' => false, - 'analyzer' => 'Doctrine_Search_Analyzer_Standard', - 'analyzer_options' => array(), - 'type' => self::INDEX_TABLES, - 'className' => '%CLASS%Index', - 'generatePath' => false, - 'table' => null, - 'batchUpdates' => false, - 'pluginTable' => false, - 'fields' => array(), - 'connection' => null, - 'children' => array(), - 'cascadeDelete' => true, - 'appLevelDelete' => false); + public const INDEX_FILES = 0; + + public const INDEX_TABLES = 1; + + protected $_options = array('generateFiles' => false, + 'analyzer' => 'Doctrine_Search_Analyzer_Standard', + 'analyzer_options' => array(), + 'type' => self::INDEX_TABLES, + 'className' => '%CLASS%Index', + 'generatePath' => false, + 'table' => null, + 'batchUpdates' => false, + 'pluginTable' => false, + 'fields' => array(), + 'connection' => null, + 'children' => array(), + 'cascadeDelete' => true, + 'appLevelDelete' => false); + /** - * __construct - * - * @param array $options - * @return void + * __construct. */ public function __construct(array $options) { $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options); - - if ( ! isset($this->_options['analyzer'])) { + + if (!isset($this->_options['analyzer'])) { $this->_options['analyzer'] = 'Doctrine_Search_Analyzer_Standard'; } - if ( ! isset($this->_options['analyzer_options'])) { + if (!isset($this->_options['analyzer_options'])) { $this->_options['analyzer_options'] = array(); } @@ -75,7 +73,7 @@ public function buildTable() { $result = parent::buildTable(); - if ( ! isset($this->_options['connection'])) { + if (!isset($this->_options['connection'])) { $manager = Doctrine_Manager::getInstance(); $this->_options['connection'] = $manager->getConnectionForComponent($this->_options['table']->getComponentName()); $manager->bindComponent($this->_options['className'], $this->_options['connection']->getName()); @@ -85,11 +83,12 @@ public function buildTable() } /** - * Searchable keyword search - * - * @param string $string Keyword string to search for - * @param Doctrine_Query $query Query object to alter. Adds where condition to limit the results using the search index - * @return array ids and relevancy + * Searchable keyword search. + * + * @param string $string Keyword string to search for + * @param Doctrine_Query $query Query object to alter. Adds where condition to limit the results using the search index + * + * @return array ids and relevancy */ public function search($string, $query = null) { @@ -101,24 +100,23 @@ public function search($string, $query = null) $newQuery = $query->copy(); $query->getSqlQuery(); $key = (array) $this->getOption('table')->getIdentifier(); - $newQuery->addWhere($query->getRootAlias() . '.'.current($key).' IN (SQL:' . $q->getSqlQuery() . ')', $q->getParams()); + $newQuery->addWhere($query->getRootAlias().'.'.current($key).' IN (SQL:'.$q->getSqlQuery().')', $q->getParams()); return $newQuery; - } else { - if ( ! isset($this->_options['connection'])) { - $this->_options['connection'] = $this->_table->getConnection(); - } - $q->query($string); - return $this->_options['connection']->fetchAll($q->getSqlQuery(), $q->getParams()); } + if (!isset($this->_options['connection'])) { + $this->_options['connection'] = $this->_table->getConnection(); + } + $q->query($string); + + return $this->_options['connection']->fetchAll($q->getSqlQuery(), $q->getParams()); } - + /** - * analyze a text in the encoding format - * - * @param string $text + * analyze a text in the encoding format. + * + * @param string $text * @param string $encoding - * @return void */ public function analyze($text, $encoding = null) { @@ -127,40 +125,41 @@ public function analyze($text, $encoding = null) /** * updateIndex - * updates the index + * updates the index. * - * @param Doctrine_Record $record - * @return integer + * @param mixed|null $encoding + * + * @return int */ public function updateIndex(array $data, $encoding = null) { $this->initialize($this->_options['table']); $fields = $this->getOption('fields'); - $class = $this->getOption('className'); - $name = $this->getOption('table')->getComponentName(); - $conn = $this->getOption('table')->getConnection(); + $class = $this->getOption('className'); + $name = $this->getOption('table')->getComponentName(); + $conn = $this->getOption('table')->getConnection(); $identifier = $this->_options['table']->getIdentifier(); $q = Doctrine_Core::getTable($class) ->createQuery() - ->delete(); + ->delete() + ; foreach ((array) $identifier as $id) { - $q->addWhere($id . ' = ?', array($data[$id])); + $q->addWhere($id.' = ?', array($data[$id])); } $q->execute(); - if ($this->_options['batchUpdates'] === true) { - $index = new $class(); + if (true === $this->_options['batchUpdates']) { + $index = new $class(); foreach ((array) $this->_options['table']->getIdentifier() as $id) { - $index->$id = $data[$id]; + $index->{$id} = $data[$id]; } $index->save(); } else { foreach ($fields as $field) { - $value = isset($data[$field]) ? $data[$field] : null; $terms = $this->analyze($value, $encoding); @@ -172,7 +171,7 @@ public function updateIndex(array $data, $encoding = null) $index->position = $pos; $index->field = $field; foreach ((array) $this->_options['table']->getIdentifier() as $id) { - $index->$id = $data[$id]; + $index->{$id} = $data[$id]; } $index->save(); @@ -183,28 +182,26 @@ public function updateIndex(array $data, $encoding = null) } /** - * readTableData - * - * @param mixed $limit - * @param mixed $offset + * readTableData. + * * @return Doctrine_Collection The collection of results */ public function readTableData($limit = null, $offset = null) { $this->initialize($this->_options['table']); - $conn = $this->_options['table']->getConnection(); + $conn = $this->_options['table']->getConnection(); $tableName = $this->_options['table']->getTableName(); - $id = current($this->_options['table']->getIdentifierColumnNames()); - $tableId = current($this->_table->getIdentifierColumnNames()); + $id = current($this->_options['table']->getIdentifierColumnNames()); + $tableId = current($this->_table->getIdentifierColumnNames()); - $query = 'SELECT * FROM ' . $conn->quoteIdentifier($tableName) - . ' WHERE ' . $conn->quoteIdentifier($id) - . ' IN (SELECT ' . $conn->quoteIdentifier($tableId) - . ' FROM ' . $conn->quoteIdentifier($this->_table->getTableName()) - . ' WHERE keyword = \'\') OR ' . $conn->quoteIdentifier($id) - . ' NOT IN (SELECT ' . $conn->quoteIdentifier($tableId) - . ' FROM ' . $conn->quoteIdentifier($this->_table->getTableName()) . ')'; + $query = 'SELECT * FROM '.$conn->quoteIdentifier($tableName) + .' WHERE '.$conn->quoteIdentifier($id) + .' IN (SELECT '.$conn->quoteIdentifier($tableId) + .' FROM '.$conn->quoteIdentifier($this->_table->getTableName()) + .' WHERE keyword = \'\') OR '.$conn->quoteIdentifier($id) + .' NOT IN (SELECT '.$conn->quoteIdentifier($tableId) + .' FROM '.$conn->quoteIdentifier($this->_table->getTableName()).')'; $query = $conn->modifyLimitQuery($query, $limit, $offset); @@ -212,11 +209,9 @@ public function readTableData($limit = null, $offset = null) } /** - * batchUpdateIndex - * - * @param mixed $limit - * @param mixed $offset - * @return void + * batchUpdateIndex. + * + * @param mixed|null $encoding */ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null) { @@ -224,12 +219,12 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null $this->initialize($table); - $id = $table->getIdentifierColumnNames(); - $class = $this->_options['className']; - $fields = $this->_options['fields']; - $conn = $this->_options['table']->getConnection(); - - for ($i = 0; $i < count($fields); $i++) { + $id = $table->getIdentifierColumnNames(); + $class = $this->_options['className']; + $fields = $this->_options['fields']; + $conn = $this->_options['table']->getConnection(); + + for ($i = 0; $i < count($fields); ++$i) { $fields[$i] = $table->getColumnName($fields[$i], $fields[$i]); } @@ -242,24 +237,23 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null } } - if (count($ids) > 0) - { - $sql = 'DELETE FROM ' . $conn->quoteIdentifier($this->_table->getTableName()); + if (count($ids) > 0) { + $sql = 'DELETE FROM '.$conn->quoteIdentifier($this->_table->getTableName()); - if (count($id) == 1) { + if (1 == count($id)) { $placeholders = str_repeat('?, ', count($ids)); $placeholders = substr($placeholders, 0, strlen($placeholders) - 2); - $sql .= ' WHERE ' . $conn->quoteIdentifier($table->getIdentifier()) . ' IN (' . substr($placeholders, 0) . ')'; + $sql .= ' WHERE '.$conn->quoteIdentifier($table->getIdentifier()).' IN ('.substr($placeholders, 0).')'; } else { // composite primary key $placeholders = ''; foreach ($table->getIdentifier() as $id) { - $placeholders .= $conn->quoteIdentifier($id) . ' = ? AND '; + $placeholders .= $conn->quoteIdentifier($id).' = ? AND '; } - $placeholders = '(' . substr($placeholders, 0, strlen($placeholders) - 5) . ') OR '; + $placeholders = '('.substr($placeholders, 0, strlen($placeholders) - 5).') OR '; $placeholders = str_repeat($placeholders, count($rows)); $placeholders = substr($placeholders, 0, strlen($placeholders) - 4); - $sql .= ' WHERE ' . $placeholders; + $sql .= ' WHERE '.$placeholders; } $conn->exec($sql, $ids); @@ -269,21 +263,21 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null $conn->beginTransaction(); try { foreach ($fields as $field) { - $data = $row[$field]; - + $data = $row[$field]; + $terms = $this->analyze($data, $encoding); - + foreach ($terms as $pos => $term) { $index = new $class(); - + $index->keyword = $term; $index->position = $pos; $index->field = $field; - + foreach ((array) $table->getIdentifier() as $identifier) { - $index->$identifier = $row[$table->getColumnName($identifier, $identifier)]; + $index->{$identifier} = $row[$table->getColumnName($identifier, $identifier)]; } - + $index->save(); $index->free(true); } @@ -297,21 +291,19 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null } /** - * buildDefinition - * - * @return void + * buildDefinition. */ public function setTableDefinition() { - if ( ! isset($this->_options['table'])) { - throw new Doctrine_Record_Exception("Unknown option 'table'."); - } + if (!isset($this->_options['table'])) { + throw new Doctrine_Record_Exception("Unknown option 'table'."); + } $componentName = $this->_options['table']->getComponentName(); $className = $this->getOption('className'); - $autoLoad = (bool) ($this->_options['generateFiles']); + $autoLoad = (bool) $this->_options['generateFiles']; if (class_exists($className, $autoLoad)) { return false; } @@ -324,17 +316,17 @@ public function setTableDefinition() $this->_table->removeColumn($name); } - $columns = array('keyword' => array('type' => 'string', - 'length' => 200, - 'primary' => true, - ), - 'field' => array('type' => 'string', - 'length' => 50, - 'primary' => true), - 'position' => array('type' => 'integer', - 'length' => 8, - 'primary' => true, - )); + $columns = array('keyword' => array('type' => 'string', + 'length' => 200, + 'primary' => true, + ), + 'field' => array('type' => 'string', + 'length' => 50, + 'primary' => true), + 'position' => array('type' => 'integer', + 'length' => 8, + 'primary' => true, + )); $this->hasColumns($columns); $this->hasColumns($previousIdentifier); diff --git a/lib/Doctrine/Search/Analyzer.php b/lib/Doctrine/Search/Analyzer.php index 75b1aed05..cbb7ef0e8 100644 --- a/lib/Doctrine/Search/Analyzer.php +++ b/lib/Doctrine/Search/Analyzer.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Search_Analyzer + * Doctrine_Search_Analyzer. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Analyzer implements Doctrine_Search_Analyzer_Interface @@ -43,4 +43,4 @@ public function analyze($text, $encoding = null) { return $text; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Analyzer/Exception.php b/lib/Doctrine/Search/Analyzer/Exception.php index 87fad8677..7052ae3ac 100644 --- a/lib/Doctrine/Search/Analyzer/Exception.php +++ b/lib/Doctrine/Search/Analyzer/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Search_Analyzer_Exception + * Doctrine_Search_Analyzer_Exception. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Analyzer_Exception extends Doctrine_Search_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Search/Analyzer/Interface.php b/lib/Doctrine/Search/Analyzer/Interface.php index 4722ce713..41c2cea1c 100644 --- a/lib/Doctrine/Search/Analyzer/Interface.php +++ b/lib/Doctrine/Search/Analyzer/Interface.php @@ -20,17 +20,17 @@ */ /** - * Doctrine_Search_Analyzer_Interface + * Doctrine_Search_Analyzer_Interface. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ interface Doctrine_Search_Analyzer_Interface { public function analyze($text); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Analyzer/Standard.php b/lib/Doctrine/Search/Analyzer/Standard.php index 0773eacb2..890dbd623 100644 --- a/lib/Doctrine/Search/Analyzer/Standard.php +++ b/lib/Doctrine/Search/Analyzer/Standard.php @@ -20,246 +20,246 @@ */ /** - * Doctrine_Search_Analyzer_Standard + * Doctrine_Search_Analyzer_Standard. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Analyzer_Standard extends Doctrine_Search_Analyzer implements Doctrine_Search_Analyzer_Interface { protected static $_stopwords = array( - // Ticket #1787. Fixed searchable behavior numeric evaluation - // Removed the numeric 0-9 from here - 'a', - 'about', - 'after', - 'all', - 'almost', - 'along', - 'also', - 'although', - 'amp', - 'an', - 'and', - 'another', - 'any', - 'are', - 'area', - 'arent', - 'around', - 'as', - 'at', - 'available', - 'back', - 'be', - 'because', - 'been', - 'before', - 'being', - 'best', - 'better', - 'big', - 'bit', - 'both', - 'but', - 'by', - 'c', - 'came', - 'can', - 'capable', - 'control', - 'could', - 'course', - 'd', - 'dan', - 'day', - 'decided', - 'did', - 'didn', - 'different', - 'div', - 'do', - 'doesn', - 'don', - 'down', - 'drive', - 'e', - 'each', - 'easily', - 'easy', - 'edition', - 'either', - 'end', - 'enough', - 'even', - 'every', - 'example', - 'few', - 'find', - 'first', - 'for', - 'found', - 'from', - 'get', - 'go', - 'going', - 'good', - 'got', - 'gt', - 'had', - 'hard', - 'has', - 'have', - 'he', - 'her', - 'here', - 'how', - 'i', - 'if', - 'in', - 'into', - 'is', - 'isn', - 'it', - 'just', - 'know', - 'last', - 'left', - 'li', - 'like', - 'little', - 'll', - 'long', - 'look', - 'lot', - 'lt', - 'm', - 'made', - 'make', - 'many', - 'mb', - 'me', - 'menu', - 'might', - 'mm', - 'more', - 'most', - 'much', - 'my', - 'name', - 'nbsp', - 'need', - 'new', - 'no', - 'not', - 'now', - 'number', - 'of', - 'off', - 'old', - 'on', - 'one', - 'only', - 'or', - 'original', - 'other', - 'our', - 'out', - 'over', - 'part', - 'place', - 'point', - 'pretty', - 'probably', - 'problem', - 'put', - 'quite', - 'quot', - 'r', - 're', - 'really', - 'results', - 'right', - 's', - 'same', - 'saw', - 'see', - 'set', - 'several', - 'she', - 'sherree', - 'should', - 'since', - 'size', - 'small', - 'so', - 'some', - 'something', - 'special', - 'still', - 'stuff', - 'such', - 'sure', - 'system', - 't', - 'take', - 'than', - 'that', - 'the', - 'their', - 'them', - 'then', - 'there', - 'these', - 'they', - 'thing', - 'things', - 'think', - 'this', - 'those', - 'though', - 'through', - 'time', - 'to', - 'today', - 'together', - 'too', - 'took', - 'two', - 'up', - 'us', - 'use', - 'used', - 'using', - 've', - 'very', - 'want', - 'was', - 'way', - 'we', - 'well', - 'went', - 'were', - 'what', - 'when', - 'where', - 'which', - 'while', - 'white', - 'who', - 'will', - 'with', - 'would', - 'yet', - 'you', - 'your', - 'yours' - ); + // Ticket #1787. Fixed searchable behavior numeric evaluation + // Removed the numeric 0-9 from here + 'a', + 'about', + 'after', + 'all', + 'almost', + 'along', + 'also', + 'although', + 'amp', + 'an', + 'and', + 'another', + 'any', + 'are', + 'area', + 'arent', + 'around', + 'as', + 'at', + 'available', + 'back', + 'be', + 'because', + 'been', + 'before', + 'being', + 'best', + 'better', + 'big', + 'bit', + 'both', + 'but', + 'by', + 'c', + 'came', + 'can', + 'capable', + 'control', + 'could', + 'course', + 'd', + 'dan', + 'day', + 'decided', + 'did', + 'didn', + 'different', + 'div', + 'do', + 'doesn', + 'don', + 'down', + 'drive', + 'e', + 'each', + 'easily', + 'easy', + 'edition', + 'either', + 'end', + 'enough', + 'even', + 'every', + 'example', + 'few', + 'find', + 'first', + 'for', + 'found', + 'from', + 'get', + 'go', + 'going', + 'good', + 'got', + 'gt', + 'had', + 'hard', + 'has', + 'have', + 'he', + 'her', + 'here', + 'how', + 'i', + 'if', + 'in', + 'into', + 'is', + 'isn', + 'it', + 'just', + 'know', + 'last', + 'left', + 'li', + 'like', + 'little', + 'll', + 'long', + 'look', + 'lot', + 'lt', + 'm', + 'made', + 'make', + 'many', + 'mb', + 'me', + 'menu', + 'might', + 'mm', + 'more', + 'most', + 'much', + 'my', + 'name', + 'nbsp', + 'need', + 'new', + 'no', + 'not', + 'now', + 'number', + 'of', + 'off', + 'old', + 'on', + 'one', + 'only', + 'or', + 'original', + 'other', + 'our', + 'out', + 'over', + 'part', + 'place', + 'point', + 'pretty', + 'probably', + 'problem', + 'put', + 'quite', + 'quot', + 'r', + 're', + 'really', + 'results', + 'right', + 's', + 'same', + 'saw', + 'see', + 'set', + 'several', + 'she', + 'sherree', + 'should', + 'since', + 'size', + 'small', + 'so', + 'some', + 'something', + 'special', + 'still', + 'stuff', + 'such', + 'sure', + 'system', + 't', + 'take', + 'than', + 'that', + 'the', + 'their', + 'them', + 'then', + 'there', + 'these', + 'they', + 'thing', + 'things', + 'think', + 'this', + 'those', + 'though', + 'through', + 'time', + 'to', + 'today', + 'together', + 'too', + 'took', + 'two', + 'up', + 'us', + 'use', + 'used', + 'using', + 've', + 'very', + 'want', + 'was', + 'way', + 'we', + 'well', + 'went', + 'were', + 'what', + 'when', + 'where', + 'which', + 'while', + 'white', + 'who', + 'will', + 'with', + 'would', + 'yet', + 'you', + 'your', + 'yours', + ); public function analyze($text, $encoding = null) { @@ -269,9 +269,9 @@ public function analyze($text, $encoding = null) $text = str_replace(' ', ' ', $text); $terms = explode(' ', $text); - + $ret = array(); - if ( ! empty($terms)) { + if (!empty($terms)) { foreach ($terms as $i => $term) { if (empty($term)) { continue; @@ -285,6 +285,7 @@ public function analyze($text, $encoding = null) $ret[$i] = $lower; } } + return $ret; } } diff --git a/lib/Doctrine/Search/Analyzer/Utf8.php b/lib/Doctrine/Search/Analyzer/Utf8.php index 88edd1216..d6f26634e 100644 --- a/lib/Doctrine/Search/Analyzer/Utf8.php +++ b/lib/Doctrine/Search/Analyzer/Utf8.php @@ -20,17 +20,17 @@ */ /** - * Doctrine_Search_Analyzer_Utf8 + * Doctrine_Search_Analyzer_Utf8. * - * This class is used to analyze (ie tokenize) an input $text in + * This class is used to analyze (ie tokenize) an input $text in * $encoding encoding, and return an array of words to be indexed. * - * @package Doctrine - * @subpackage Search * @author Brice Figureau * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Analyzer_Utf8 extends Doctrine_Search_Analyzer_Standard @@ -38,11 +38,11 @@ class Doctrine_Search_Analyzer_Utf8 extends Doctrine_Search_Analyzer_Standard public function analyze($text, $encoding = null) { if (is_null($encoding)) { - $encoding = isset($this->_options['encoding']) ? $this->_options['encoding']:'utf-8'; + $encoding = isset($this->_options['encoding']) ? $this->_options['encoding'] : 'utf-8'; } // check that $text encoding is utf-8, if not convert it - if (strcasecmp($encoding, 'utf-8') != 0 && strcasecmp($encoding, 'utf8') != 0) { + if (0 != strcasecmp($encoding, 'utf-8') && 0 != strcasecmp($encoding, 'utf8')) { $text = iconv($encoding, 'UTF-8', $text); } @@ -50,9 +50,9 @@ public function analyze($text, $encoding = null) $text = str_replace(' ', ' ', $text); $terms = explode(' ', $text); - + $ret = array(); - if ( ! empty($terms)) { + if (!empty($terms)) { foreach ($terms as $i => $term) { if (empty($term)) { continue; @@ -66,6 +66,7 @@ public function analyze($text, $encoding = null) $ret[$i] = $lower; } } + return $ret; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Exception.php b/lib/Doctrine/Search/Exception.php index 4018a960e..5ed34ae14 100644 --- a/lib/Doctrine/Search/Exception.php +++ b/lib/Doctrine/Search/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Search_Exception + * Doctrine_Search_Exception. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Search/File.php b/lib/Doctrine/Search/File.php index feff520f4..a86d3266e 100644 --- a/lib/Doctrine/Search/File.php +++ b/lib/Doctrine/Search/File.php @@ -20,28 +20,28 @@ */ /** - * Doctrine_Search + * Doctrine_Search. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_File extends Doctrine_Search { /** - * constructor + * constructor. * - * @param array $options an array of plugin options + * @param array $options an array of plugin options */ public function __construct(array $options = array()) { parent::__construct($options); - if ( ! isset($this->_options['resource'])) { + if (!isset($this->_options['resource'])) { $conn = Doctrine_Manager::connection(); $tableClass = $conn->getAttribute(Doctrine_Core::ATTR_TABLE_CLASS); $table = new $tableClass('File', $conn); @@ -58,22 +58,20 @@ public function __construct(array $options = array()) public function buildRelation() { - } /** - * indexes given directory + * indexes given directory. * - * @param string $dir the name of the directory to index - * @return void + * @param string $dir the name of the directory to index */ public function indexDirectory($dir) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), - RecursiveIteratorIterator::LEAVES_ONLY); - + RecursiveIteratorIterator::LEAVES_ONLY); + foreach ($it as $file) { - if (strpos($file, DIRECTORY_SEPARATOR . '.svn') !== false) { + if (false !== strpos($file, DIRECTORY_SEPARATOR.'.svn')) { continue; } @@ -82,7 +80,7 @@ public function indexDirectory($dir) } $this->updateIndex(array('url' => $file->getPathName(), - 'content' => file_get_contents($file))); + 'content' => file_get_contents($file))); } } } diff --git a/lib/Doctrine/Search/Indexer.php b/lib/Doctrine/Search/Indexer.php index 2fe82298d..52d300028 100644 --- a/lib/Doctrine/Search/Indexer.php +++ b/lib/Doctrine/Search/Indexer.php @@ -20,22 +20,22 @@ */ /** - * Doctrine_Search_Indexer + * Doctrine_Search_Indexer. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Indexer { public function indexDirectory($dir) { - if ( ! file_exists($dir)) { - throw new Doctrine_Search_Indexer_Exception('Unknown directory ' . $dir); + if (!file_exists($dir)) { + throw new Doctrine_Search_Indexer_Exception('Unknown directory '.$dir); } $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY); @@ -43,7 +43,7 @@ public function indexDirectory($dir) $files = array(); foreach ($it as $file) { $name = $file->getPathName(); - if (strpos($name, '.svn') === false) { + if (false === strpos($name, '.svn')) { $files[] = $name; } } @@ -51,21 +51,23 @@ public function indexDirectory($dir) $q = Doctrine_Core::getTable('Doctrine_File') ->createQuery('f') ->delete() - ->where('f.url LIKE ?', array($dir . '%')) - ->execute(); + ->where('f.url LIKE ?', array($dir.'%')) + ->execute() + ; // clear the index $q = Doctrine_Core::getTable('Doctrine_File_Index') ->createQuery('i') ->where('i.file_id = ?') - ->execute(); + ->execute() + ; $coll = Doctrine_Collection::create('Doctrine_File'); foreach ($files as $file) { $coll[]->url = $file; } - + $coll->save(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Indexer/Dir.php b/lib/Doctrine/Search/Indexer/Dir.php index 63df7d640..f52755b8e 100644 --- a/lib/Doctrine/Search/Indexer/Dir.php +++ b/lib/Doctrine/Search/Indexer/Dir.php @@ -20,28 +20,28 @@ */ /** - * Doctrine_Search_Indexer_Dir + * Doctrine_Search_Indexer_Dir. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Indexer_Dir { public function add($dir) { - if ( ! file_exists($dir)) { - throw new Doctrine_Search_Indexer_Exception('Unknown directory ' . $dir); + if (!file_exists($dir)) { + throw new Doctrine_Search_Indexer_Exception('Unknown directory '.$dir); } $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY); - + foreach ($it as $file) { $this->indexFile($file); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Indexer/Exception.php b/lib/Doctrine/Search/Indexer/Exception.php index f94d96657..4fb8f4f9c 100644 --- a/lib/Doctrine/Search/Indexer/Exception.php +++ b/lib/Doctrine/Search/Indexer/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Search_Indexer + * Doctrine_Search_Indexer. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Indexer_Exception extends Doctrine_Search_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Search/Listener.php b/lib/Doctrine/Search/Listener.php index d0ee73d48..e5dfc3c69 100644 --- a/lib/Doctrine/Search/Listener.php +++ b/lib/Doctrine/Search/Listener.php @@ -20,17 +20,17 @@ */ /** - * Doctrine_Search_Listener + * Doctrine_Search_Listener. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ -class Doctrine_Search_Listener extends Doctrine_Record_Listener +class Doctrine_Search_Listener extends Doctrine_Record_Listener { protected $_search; @@ -45,15 +45,15 @@ public function preUpdate(Doctrine_Event $event) public function postUpdate(Doctrine_Event $event) { - $record = $event->getInvoker(); + $record = $event->getInvoker(); - $this->_search->updateIndex($record->toArray()); + $this->_search->updateIndex($record->toArray()); } public function postInsert(Doctrine_Event $event) { $record = $event->getInvoker(); - + $this->_search->updateIndex($record->toArray()); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Parser.php b/lib/Doctrine/Search/Parser.php index e9f39bd22..aa7fc9276 100644 --- a/lib/Doctrine/Search/Parser.php +++ b/lib/Doctrine/Search/Parser.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Search_Parser_Standard + * Doctrine_Search_Parser_Standard. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Parser @@ -35,7 +35,7 @@ class Doctrine_Search_Parser public function parse($file) { $contents = file_get_contents($file); - + return array('url' => $file, 'contents' => $contents); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Query.php b/lib/Doctrine/Search/Query.php index 81af580d8..eef9fbb6e 100644 --- a/lib/Doctrine/Search/Query.php +++ b/lib/Doctrine/Search/Query.php @@ -20,43 +20,39 @@ */ /** - * Doctrine_Search_Query + * Doctrine_Search_Query. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Query { - /** - * @var Doctrine_Table $_table the index table + * @var Doctrine_Table the index table */ protected $_table = array(); - + protected $_sql = ''; - + protected $_params = array(); - + protected $_words = array(); - + protected $_tokenizer; protected $_condition; - /** - * @param Doctrine_Table $_table the index table - */ public function __construct($table) { if (is_string($table)) { - $table = Doctrine_Core::getTable($table); + $table = Doctrine_Core::getTable($table); } else { - if ( ! $table instanceof Doctrine_Table) { + if (!$table instanceof Doctrine_Table) { throw new Doctrine_Search_Exception('Invalid argument type. Expected instance of Doctrine_Table.'); } } @@ -66,10 +62,9 @@ public function __construct($table) $foreignId = current(array_diff($this->_table->getColumnNames(), array('keyword', 'field', 'position'))); - $this->_condition = $foreignId . ' %s (SELECT ' . $foreignId . ' FROM ' . $this->_table->getTableName() . ' WHERE '; + $this->_condition = $foreignId.' %s (SELECT '.$foreignId.' FROM '.$this->_table->getTableName().' WHERE '; } - public function query($text, $includeRelevance = true) { $text = trim($text); @@ -77,40 +72,40 @@ public function query($text, $includeRelevance = true) $foreignId = current(array_diff($this->_table->getColumnNames(), array('keyword', 'field', 'position'))); $weighted = false; - if (strpos($text, '^') === false) { + if (false === strpos($text, '^')) { if ($includeRelevance) { - $select = 'SELECT COUNT(keyword) AS relevance, ' . $foreignId; + $select = 'SELECT COUNT(keyword) AS relevance, '.$foreignId; } else { - $select = 'SELECT ' . $foreignId; + $select = 'SELECT '.$foreignId; } } else { if ($includeRelevance) { - $select = 'SELECT SUM(sub_relevance) AS relevance, ' . $foreignId; + $select = 'SELECT SUM(sub_relevance) AS relevance, '.$foreignId; } else { - $select = 'SELECT ' . $foreignId; + $select = 'SELECT '.$foreignId; } } - - $from = 'FROM ' . $this->_table->getTableName(); + + $from = 'FROM '.$this->_table->getTableName(); $where = 'WHERE '; $where .= $this->parseClause($text); - $groupby = 'GROUP BY ' . $foreignId; + $groupby = 'GROUP BY '.$foreignId; if ($includeRelevance) { $orderBy = 'ORDER BY relevance DESC'; } else { $orderBy = null; } - $this->_sql = $select . ' ' . $from . ' ' . $where . ' ' . $groupby; - if (isset($orderBy) && $orderBy !== null) { - $this->_sql .= ' ' . $orderBy; + $this->_sql = $select.' '.$from.' '.$where.' '.$groupby; + if (isset($orderBy) && null !== $orderBy) { + $this->_sql .= ' '.$orderBy; } } public function parseClause($originalClause, $recursive = false) { $clause = $this->_tokenizer->bracketTrim($originalClause); - + $brackets = false; if ($clause !== $originalClause) { @@ -118,7 +113,7 @@ public function parseClause($originalClause, $recursive = false) } $foreignId = current(array_diff($this->_table->getColumnNames(), array('keyword', 'field', 'position'))); - + $terms = $this->_tokenizer->sqlExplode($clause, ' OR ', '(', ')'); $ret = array(); @@ -138,33 +133,33 @@ public function parseClause($originalClause, $recursive = false) $return = implode(' OR ', $ret); if ($leavesOnly && $recursive) { - $return = sprintf($this->_condition, 'IN') . $return . ')'; + $return = sprintf($this->_condition, 'IN').$return.')'; $brackets = false; } } else { $terms = $this->_tokenizer->sqlExplode($clause, ' ', '(', ')'); - - if (count($terms) === 1 && ! $recursive) { + + if (1 === count($terms) && !$recursive) { $return = $this->parseTerm($clause); } else { foreach ($terms as $k => $term) { $term = trim($term); - - if ($term === 'AND') { + + if ('AND' === $term) { continue; } - - if (substr($term, 0, 1) === '-') { + + if ('-' === substr($term, 0, 1)) { $operator = 'NOT IN'; $term = substr($term, 1); } else { $operator = 'IN'; } - + if ($this->isExpression($term)) { $ret[$k] = $this->parseClause($term, true); } else { - $ret[$k] = sprintf($this->_condition, $operator) . $this->parseTerm($term) . ')'; + $ret[$k] = sprintf($this->_condition, $operator).$this->parseTerm($term).')'; } } $return = implode(' AND ', $ret); @@ -172,28 +167,27 @@ public function parseClause($originalClause, $recursive = false) } if ($brackets) { - return '(' . $return . ')'; - } else { - return $return; + return '('.$return.')'; } + + return $return; } public function isExpression($term) { - if (strpos($term, '(') !== false) { + if (false !== strpos($term, '(')) { return true; - } else { - $terms = $this->_tokenizer->quoteExplode($term); - - return (count($terms) > 1); } + $terms = $this->_tokenizer->quoteExplode($term); + + return count($terms) > 1; } public function parseTerm($term) { $negation = false; - if (strpos($term, "'") === false) { + if (false === strpos($term, "'")) { $where = $this->parseWord($term); } else { $term = trim($term, "' "); @@ -202,12 +196,13 @@ public function parseTerm($term) $where = $this->parseWord($terms[0]); foreach ($terms as $k => $word) { - if ($k === 0) { + if (0 === $k) { continue; } - $where .= ' AND (position + ' . $k . ') IN (SELECT position FROM ' . $this->_table->getTableName() . ' WHERE ' . $this->parseWord($word) . ')'; + $where .= ' AND (position + '.$k.') IN (SELECT position FROM '.$this->_table->getTableName().' WHERE '.$this->parseWord($word).')'; } } + return $where; } @@ -215,9 +210,8 @@ public function parseWord($word) { $this->_words[] = str_replace('*', '', $word); - if (strpos($word, '?') !== false || - strpos($word, '*') !== false) { - + if (false !== strpos($word, '?') + || false !== strpos($word, '*')) { $word = str_replace('*', '%', $word); $where = 'keyword LIKE ?'; @@ -246,4 +240,4 @@ public function getSqlQuery() { return $this->_sql; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Record.php b/lib/Doctrine/Search/Record.php index 3dc4f9b91..bf2913a67 100644 --- a/lib/Doctrine/Search/Record.php +++ b/lib/Doctrine/Search/Record.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Search_Record + * Doctrine_Search_Record. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Record extends Doctrine_Template @@ -37,7 +37,7 @@ public function setTableDefinition() $this->hasColumn('keyword', 'string', 250, array('notnull' => true)); $this->hasColumn('field', 'string', 50, array('notnull' => true)); $this->hasColumn('position', 'integer', 8); - // depending on the identifiers of the owner record this record + // depending on the identifiers of the owner record this record // has also one to many foreign key columns } @@ -45,4 +45,4 @@ public function setUp() { $this->hasOne('[Component]', array('onDelete' => 'CASCADE')); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence.php b/lib/Doctrine/Sequence.php index 76ee236c6..0779b4552 100644 --- a/lib/Doctrine/Sequence.php +++ b/lib/Doctrine/Sequence.php @@ -23,23 +23,24 @@ * Doctrine_Sequence * The base class for sequence handling drivers. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence extends Doctrine_Connection_Module { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence + * * @throws Doctrine_Sequence_Exception */ public function nextId($seqName, $ondemand = true) @@ -49,10 +50,12 @@ public function nextId($seqName, $ondemand = true) /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted + * @param mixed|null $table + * @param mixed|null $field */ public function lastInsertId($table = null, $field = null) { @@ -60,16 +63,17 @@ public function lastInsertId($table = null, $field = null) } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $this->warnings[] = 'database does not support getting current sequence value, the sequence value was incremented'; + return $this->nextId($seqName); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Db2.php b/lib/Doctrine/Sequence/Db2.php index dc6bfe104..877ad5050 100644 --- a/lib/Doctrine/Sequence/Db2.php +++ b/lib/Doctrine/Sequence/Db2.php @@ -20,73 +20,76 @@ */ /** - * Doctrine_Sequence_Db2 + * Doctrine_Sequence_Db2. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Db2 extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence + * * @throws Doctrine_Sequence_Exception */ public function nextId($seqName, $ondemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = 'SELECT NEXTVAL FOR ' . $sequenceName . ' AS VAL FROM SYSIBM.SYSDUMMY1'; - + $query = 'SELECT NEXTVAL FOR '.$sequenceName.' AS VAL FROM SYSIBM.SYSDUMMY1'; + try { $result = $this->conn->fetchOne($query); - $result = ($result) ? $result['VAL'] : null; - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + $result = ($result) ? $result['VAL'] : null; + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { try { $result = $this->conn->export->createSequence($seqName); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } - + return $this->nextId($seqName, false); - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } + return $result; } - + /** * Return the most recent value from the specified sequence in the database. * This is supported only on RDBMS brands that support sequences * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null. * * @param string $sequenceName - * @return integer + * + * @return int + * * @throws Doctrine_Adapter_Db2_Exception */ public function currId($sequenceName) { $sql = 'SELECT PREVVAL FOR ' - . $this->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName)) - . ' AS VAL FROM SYSIBM.SYSDUMMY1'; + .$this->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName)) + .' AS VAL FROM SYSIBM.SYSDUMMY1'; - $stmt = $this->query($sql); + $stmt = $this->query($sql); $result = $stmt->fetchAll(Doctrine_Core::FETCH_ASSOC); if ($result) { return $result[0]['VAL']; - } else { - return null; } + + return null; } /** @@ -102,21 +105,24 @@ public function currId($sequenceName) * The IDENTITY_VAL_LOCAL() function gives the last generated identity value * in the current process, even if it was for a GENERATED column. * - * @param string $tableName OPTIONAL + * @param string $tableName OPTIONAL * @param string $primaryKey OPTIONAL - * @return integer + * + * @return int + * * @throws Doctrine_Adapter_Db2_Exception */ public function lastInsertId($tableName = null, $primaryKey = null) { $this->_connect(); - if ($tableName !== null) { + if (null !== $tableName) { $sequenceName = $tableName; if ($primaryKey) { - $sequenceName .= "_$primaryKey"; + $sequenceName .= "_{$primaryKey}"; } $sequenceName .= '_seq'; + return $this->lastSequenceId($sequenceName); } @@ -125,8 +131,8 @@ public function lastInsertId($tableName = null, $primaryKey = null) $result = $stmt->fetchAll(Doctrine_Core::FETCH_ASSOC); if ($result) { return $result[0]['VAL']; - } else { - return null; } + + return null; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Exception.php b/lib/Doctrine/Sequence/Exception.php index 9476b1f81..1e088ebf9 100644 --- a/lib/Doctrine/Sequence/Exception.php +++ b/lib/Doctrine/Sequence/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Sequence_Exception + * Doctrine_Sequence_Exception. * - * @package Doctrine - * @subpackage Sequence * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Sequence_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Sequence/Mssql.php b/lib/Doctrine/Sequence/Mssql.php index fff760886..07663b1e7 100644 --- a/lib/Doctrine/Sequence/Mssql.php +++ b/lib/Doctrine/Sequence/Mssql.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Sequence_Mssql + * Doctrine_Sequence_Mssql. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Mssql extends Doctrine_Sequence @@ -35,40 +35,39 @@ class Doctrine_Sequence_Mssql extends Doctrine_Sequence protected $warnings; /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextId($seqName, $onDemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); if ($this->checkSequence($sequenceName)) { - $query = 'SET IDENTITY_INSERT ' . $sequenceName . ' OFF ' - . 'INSERT INTO ' . $sequenceName . ' DEFAULT VALUES'; + $query = 'SET IDENTITY_INSERT '.$sequenceName.' OFF ' + .'INSERT INTO '.$sequenceName.' DEFAULT VALUES'; } else { - $query = 'INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (0)'; + $query = 'INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES (0)'; } - + try { $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { // Since we are creating the sequence on demand // we know the first id = 1 so initialize the // sequence at 2 try { $result = $this->conn->export->createSequence($seqName, 2); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } - - /** + + /* * This could actually be a table that starts at 18.. oh well.. * we will keep the fallback to return 1 in case we skip this.. which * should really not happen.. otherwise the returned values is biased. @@ -76,68 +75,66 @@ public function nextId($seqName, $onDemand = true) if ($this->checkSequence($seqName)) { return $this->lastInsertId($seqName); } - + return 1; } - + throw $e; } - + $value = $this->lastInsertId($sequenceName); if (is_numeric($value)) { - $query = 'DELETE FROM ' . $sequenceName . ' WHERE ' . $seqcolName . ' < ' . $value; - + $query = 'DELETE FROM '.$sequenceName.' WHERE '.$seqcolName.' < '.$value; + try { $this->conn->exec($query); } catch (Doctrine_Connection_Exception $e) { - throw new Doctrine_Sequence_Exception( - 'Could not delete previous sequence from ' . - $sequenceName . ' at ' . __FILE__ . ' in ' . - __FUNCTION__ . ' with the message: ' . $e->getMessage() - ); + throw new Doctrine_Sequence_Exception('Could not delete previous sequence from '.$sequenceName.' at '.__FILE__.' in '.__FUNCTION__.' with the message: '.$e->getMessage()); } } + return $value; } /** * Checks if there's a sequence that exists. * - * @param string $seqName The sequence name to verify. - * @return bool $tableExists The value if the table exists or not - * @access private + * @param string $seqName the sequence name to verify + * + * @return bool $tableExists The value if the table exists or not */ public function checkSequence($seqName) { - $query = 'SELECT COUNT(1) FROM ' . $seqName; + $query = 'SELECT COUNT(1) FROM '.$seqName; try { $this->conn->execute($query); } catch (Doctrine_Connection_Exception $e) { - if ($e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + if (Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { return false; } } + return true; } /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted + * @param mixed|null $table + * @param mixed|null $field */ public function lastInsertId($table = null, $field = null) { $serverInfo = $this->conn->getServerVersion(); if (is_array($serverInfo) - && ! is_null($serverInfo['major']) + && !is_null($serverInfo['major']) && $serverInfo['major'] >= 8) { - - if (isset($table)) - { - $query = 'SELECT IDENT_CURRENT(\'' . $this->conn->quoteIdentifier($table) . '\')'; + if (isset($table)) { + $query = 'SELECT IDENT_CURRENT(\''.$this->conn->quoteIdentifier($table).'\')'; } else { $query = 'SELECT SCOPE_IDENTITY()'; } @@ -149,16 +146,17 @@ public function lastInsertId($table = null, $field = null) } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $this->warnings[] = 'database does not support getting current sequence value, the sequence value was incremented'; + return $this->nextId($seqName); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Mysql.php b/lib/Doctrine/Sequence/Mysql.php index 03b5f0a9f..320c50fe9 100644 --- a/lib/Doctrine/Sequence/Mysql.php +++ b/lib/Doctrine/Sequence/Mysql.php @@ -20,69 +20,71 @@ */ /** - * Doctrine_Sequence_Mysql + * Doctrine_Sequence_Mysql. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Mysql extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextId($seqName, $onDemand = true) { - $sequenceName = $this->conn->quoteIdentifier($seqName, true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (NULL)'; - + $sequenceName = $this->conn->quoteIdentifier($seqName, true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $query = 'INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES (NULL)'; + try { $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { // Since we are creating the sequence on demand // we know the first id = 1 so initialize the // sequence at 2 try { $result = $this->conn->export->createSequence($seqName, 2); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } // First ID of a newly created sequence is 1 return 1; - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } $value = $this->lastInsertId(); if (is_numeric($value)) { - $query = 'DELETE FROM ' . $sequenceName . ' WHERE ' . $seqcolName . ' < ' . $value; + $query = 'DELETE FROM '.$sequenceName.' WHERE '.$seqcolName.' < '.$value; $this->conn->exec($query); } - + return $value; } /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted - * @return integer|boolean + * @param mixed|null $table + * @param mixed|null $field + * + * @return int|bool */ public function lastInsertId($table = null, $field = null) { @@ -90,18 +92,18 @@ public function lastInsertId($table = null, $field = null) } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { - $sequenceName = $this->conn->quoteIdentifier($seqName, true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'SELECT MAX(' . $seqcolName . ') FROM ' . $sequenceName; + $sequenceName = $this->conn->quoteIdentifier($seqName, true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $query = 'SELECT MAX('.$seqcolName.') FROM '.$sequenceName; return (int) $this->conn->fetchOne($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Oracle.php b/lib/Doctrine/Sequence/Oracle.php index 6a8fa6452..76b571dec 100644 --- a/lib/Doctrine/Sequence/Oracle.php +++ b/lib/Doctrine/Sequence/Oracle.php @@ -20,45 +20,44 @@ */ /** - * Doctrine_Sequence_Oracle + * Doctrine_Sequence_Oracle. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Oracle extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool onDemand when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextID($seqName, $onDemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = 'SELECT ' . $sequenceName . '.nextval FROM DUAL'; + $query = 'SELECT '.$sequenceName.'.nextval FROM DUAL'; try { $result = $this->conn->fetchOne($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { try { $result = $this->conn->export->createSequence($seqName); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } return $this->nextId($seqName, false); - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } return $result; @@ -66,32 +65,34 @@ public function nextID($seqName, $onDemand = true) /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted + * @param mixed|null $table + * @param mixed|null $field */ public function lastInsertID($table = null, $field = null) { - $seqName = $table . (empty($field) ? '' : '_'.$field); - $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); + $seqName = $table.(empty($field) ? '' : '_'.$field); + $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - return $this->conn->fetchOne('SELECT ' . $sequenceName . '.currval FROM DUAL'); + return $this->conn->fetchOne('SELECT '.$sequenceName.'.currval FROM DUAL'); } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = 'SELECT (last_number-1) FROM user_sequences'; - $query .= ' WHERE sequence_name=' . $this->conn->quote($sequenceName, 'text'); - $query .= ' OR sequence_name=' . $this->conn->quote(strtoupper($sequenceName), 'text'); + $query = 'SELECT (last_number-1) FROM user_sequences'; + $query .= ' WHERE sequence_name='.$this->conn->quote($sequenceName, 'text'); + $query .= ' OR sequence_name='.$this->conn->quote(strtoupper($sequenceName), 'text'); return $this->conn->fetchOne($query); } diff --git a/lib/Doctrine/Sequence/Pgsql.php b/lib/Doctrine/Sequence/Pgsql.php index 2fbb5d586..ffd932c84 100644 --- a/lib/Doctrine/Sequence/Pgsql.php +++ b/lib/Doctrine/Sequence/Pgsql.php @@ -20,78 +20,81 @@ */ /** - * Doctrine_Sequence_Pgsql + * Doctrine_Sequence_Pgsql. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Pgsql extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool onDemand when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextId($seqName, $onDemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = "SELECT NEXTVAL('" . $sequenceName . "')"; + $query = "SELECT NEXTVAL('".$sequenceName."')"; try { $result = (int) $this->conn->fetchOne($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { try { $result = $this->conn->export->createSequence($seqName); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } return $this->nextId($seqName, false); - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } return $result; } /** - * lastInsertId + * lastInsertId. * * Returns the autoincrement ID if supported or $id or fetches the current * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted - * @return integer the autoincremented id + * @param mixed|null $table + * @param mixed|null $field + * + * @return int the autoincremented id */ public function lastInsertId($table = null, $field = null) { - $seqName = $table . (empty($field) ? '' : '_' . $field); + $seqName = $table.(empty($field) ? '' : '_'.$field); $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - return (int) $this->conn->fetchOne("SELECT CURRVAL('" . $sequenceName . "')"); + return (int) $this->conn->fetchOne("SELECT CURRVAL('".$sequenceName."')"); } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - return (int) $this->conn->fetchOne('SELECT last_value FROM ' . $sequenceName); + + return (int) $this->conn->fetchOne('SELECT last_value FROM '.$sequenceName); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Sqlite.php b/lib/Doctrine/Sequence/Sqlite.php index 04c8cba0b..8800d37b9 100644 --- a/lib/Doctrine/Sequence/Sqlite.php +++ b/lib/Doctrine/Sequence/Sqlite.php @@ -20,68 +20,71 @@ */ /** - * Doctrine_Sequence_Sqlite + * Doctrine_Sequence_Sqlite. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Sqlite extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence - * @param bool $onDemand when true missing sequences are automatic created + * @param string $seqName name of the sequence + * @param bool $onDemand when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextId($seqName, $onDemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (NULL)'; + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $query = 'INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES (NULL)'; try { $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { // Since we are creating the sequence on demand // we know the first id = 1 so initialize the // sequence at 2 try { $result = $this->conn->export->createSequence($seqName, 2); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } + // First ID of a newly created sequence is 1 return 1; - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } $value = $this->conn->getDbh()->lastInsertId(); if (is_numeric($value)) { - $query = 'DELETE FROM ' . $sequenceName . ' WHERE ' . $seqcolName . ' < ' . $value; + $query = 'DELETE FROM '.$sequenceName.' WHERE '.$seqcolName.' < '.$value; $this->conn->exec($query); } - + return $value; } /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted - * @return integer|boolean + * @param mixed|null $table + * @param mixed|null $field + * + * @return int|bool */ public function lastInsertId($table = null, $field = null) { @@ -89,19 +92,19 @@ public function lastInsertId($table = null, $field = null) } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'SELECT MAX(' . $seqcolName . ') FROM ' . $sequenceName; + $query = 'SELECT MAX('.$seqcolName.') FROM '.$sequenceName; return (int) $this->conn->fetchOne($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Table.php b/lib/Doctrine/Table.php index faac80574..251201f35 100644 --- a/lib/Doctrine/Table.php +++ b/lib/Doctrine/Table.php @@ -21,53 +21,53 @@ /** * Doctrine_Table represents a database table - * each Doctrine_Table holds the information of foreignKeys and associations - * + * each Doctrine_Table holds the information of foreignKeys and associations. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Table extends Doctrine_Configurable implements Countable, Serializable { /** - * @var array $data temporary data which is then loaded into Doctrine_Record::$_data + * @var array temporary data which is then loaded into Doctrine_Record::$_data */ - protected $_data = array(); + protected $_data = array(); /** - * @var mixed $identifier The field names of all fields that are part of the identifier/primary key + * @var mixed The field names of all fields that are part of the identifier/primary key */ protected $_identifier = array(); /** * @see Doctrine_Identifier constants - * @var integer $identifierType the type of identifier this table uses + * + * @var int the type of identifier this table uses */ protected $_identifierType; /** - * @var Doctrine_Connection $conn Doctrine_Connection object that created this table + * @var Doctrine_Connection Doctrine_Connection object that created this table */ protected $_conn; /** - * @var array $identityMap first level cache + * @var array first level cache */ - protected $_identityMap = array(); + protected $_identityMap = array(); /** - * @var Doctrine_Table_Repository $repository record repository + * @var Doctrine_Table_Repository record repository */ protected $_repository; /** - * @var array $columns an array of column definitions, - * keys are column names and values are column definitions + * @var array an array of column definitions, + * keys are column names and values are column definitions * * the definition array has atleast the following values: * @@ -80,45 +80,44 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable, Seriali * -- notblank notblank validator + notnull constraint * ... many more */ - protected $_columns = array(); + protected $_columns = array(); /** - * Array of unique sets of fields. These values are validated on save + * Array of unique sets of fields. These values are validated on save. * - * @var array $_uniques + * @var array */ protected $_uniques = array(); /** - * @var array $_fieldNames an array of field names, used to look up field names - * from column names. Keys are column - * names and values are field names. - * Alias for columns are here. + * @var array an array of field names, used to look up field names + * from column names. Keys are column + * names and values are field names. + * Alias for columns are here. */ - protected $_fieldNames = array(); + protected $_fieldNames = array(); /** - * - * @var array $_columnNames an array of column names - * keys are field names and values column names. - * used to look up column names from field names. - * this is the reverse lookup map of $_fieldNames. + * @var array an array of column names + * keys are field names and values column names. + * used to look up column names from field names. + * this is the reverse lookup map of $_fieldNames. */ protected $_columnNames = array(); /** - * @var integer $columnCount cached column count, Doctrine_Record uses this column count in when - * determining its state + * @var int cached column count, Doctrine_Record uses this column count in when + * determining its state */ protected $columnCount; /** - * @var boolean $hasDefaultValues whether or not this table has default values + * @var bool whether or not this table has default values */ protected $hasDefaultValues; /** - * @var array $options an array containing all options + * @var array an array containing all options * * -- name name of the component, for example component name of the GroupTable is 'Group' * @@ -160,83 +159,88 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable, Seriali * * -- versioning */ - protected $_options = array('name' => null, - 'tableName' => null, - 'sequenceName' => null, - 'inheritanceMap' => array(), - 'enumMap' => array(), - 'type' => null, - 'charset' => null, - 'collate' => null, - 'treeImpl' => null, - 'treeOptions' => array(), - 'indexes' => array(), - 'parents' => array(), - 'joinedParents' => array(), - 'queryParts' => array(), - 'versioning' => null, - 'subclasses' => array(), - 'orderBy' => null - ); - - /** - * @var Doctrine_Tree $tree tree object associated with this table + protected $_options = array('name' => null, + 'tableName' => null, + 'sequenceName' => null, + 'inheritanceMap' => array(), + 'enumMap' => array(), + 'type' => null, + 'charset' => null, + 'collate' => null, + 'treeImpl' => null, + 'treeOptions' => array(), + 'indexes' => array(), + 'parents' => array(), + 'joinedParents' => array(), + 'queryParts' => array(), + 'versioning' => null, + 'subclasses' => array(), + 'orderBy' => null, + ); + + /** + * @var Doctrine_Tree tree object associated with this table */ protected $_tree; /** - * @var Doctrine_Relation_Parser $_parser relation parser object + * @var Doctrine_Relation_Parser relation parser object */ protected $_parser; /** * @see Doctrine_Template - * @var array $_templates an array containing all templates attached to this table + * + * @var array an array containing all templates attached to this table */ - protected $_templates = array(); + protected $_templates = array(); /** * @see Doctrine_Record_Filter - * @var array $_filters an array containing all record filters attached to this table + * + * @var array an array containing all record filters attached to this table */ - protected $_filters = array(); + protected $_filters = array(); /** * @see Doctrine_Record_Generator - * @var array $_generators an array containing all generators attached to this table + * + * @var array an array containing all generators attached to this table */ - protected $_generators = array(); + protected $_generators = array(); /** - * Generator instance responsible for constructing this table + * Generator instance responsible for constructing this table. * * @see Doctrine_Record_Generator - * @var Doctrine_Record_Generator $generator + * + * @var Doctrine_Record_Generator */ protected $_generator; /** - * @var array $_invokedMethods method invoker cache + * @var array method invoker cache */ protected $_invokedMethods = array(); /** - * @var boolean $_useIdentityMap Use or not identyMap cache + * @var bool Use or not identyMap cache */ protected $_useIdentityMap = true; /** - * @var Doctrine_Record $record empty instance of the given model + * @var Doctrine_Record empty instance of the given model */ protected $record; /** - * the constructor + * the constructor. + * + * @param string $name the name of the component + * @param Doctrine_Connection $conn the connection associated with this table + * @param bool $initDefinition whether to init the in-memory schema * - * @throws Doctrine_Connection_Exception if there are no opened connections - * @param string $name the name of the component - * @param Doctrine_Connection $conn the connection associated with this table - * @param boolean $initDefinition whether to init the in-memory schema + * @throws Doctrine_Connection_Exception if there are no opened connections */ public function __construct($name, Doctrine_Connection $conn, $initDefinition = false) { @@ -267,12 +271,12 @@ public function __construct($name, Doctrine_Connection $conn, $initDefinition = $this->getTree()->setUp(); } } else { - if ( ! isset($this->_options['tableName'])) { + if (!isset($this->_options['tableName'])) { $this->setTableName(Doctrine_Inflector::tableize($this->_options['name'])); } } - $this->_filters[] = new Doctrine_Record_Filter_Standard(); + $this->_filters[] = new Doctrine_Record_Filter_Standard(); if ($this->getAttribute(Doctrine_Core::ATTR_USE_TABLE_REPOSITORY)) { $this->_repository = new Doctrine_Table_Repository($this); } else { @@ -290,22 +294,19 @@ public function __construct($name, Doctrine_Connection $conn, $initDefinition = * This method provides concrete Table classes with the possibility * to hook into the constructor procedure. It is called after the * Doctrine_Table construction process is finished. - * - * @return void */ public function construct() - { } + { + } /** * Initializes the in-memory table definition. - * - * @param string $name */ public function initDefinition() { $name = $this->_options['name']; - if ( ! class_exists($name) || empty($name)) { - throw new Doctrine_Exception("Couldn't find class " . $name); + if (!class_exists($name) || empty($name)) { + throw new Doctrine_Exception("Couldn't find class ".$name); } $record = new $name($this); @@ -316,7 +317,7 @@ public function initDefinition() // get parent classes do { - if ($class === 'Doctrine_Record') { + if ('Doctrine_Record' === $class) { break; } @@ -324,8 +325,8 @@ public function initDefinition() $names[] = $name; } while ($class = get_parent_class($class)); - if ($class === false) { - throw new Doctrine_Table_Exception('Class "' . $name . '" must be a child class of Doctrine_Record'); + if (false === $class) { + throw new Doctrine_Table_Exception('Class "'.$name.'" must be a child class of Doctrine_Record'); } // reverse names @@ -340,7 +341,6 @@ public function initDefinition() // get the declaring class of setTableDefinition method $method = new ReflectionMethod($this->_options['name'], 'setTableDefinition'); $class = $method->getDeclaringClass(); - } else { $class = new ReflectionClass($class); } @@ -348,13 +348,12 @@ public function initDefinition() $this->_options['joinedParents'] = array(); foreach (array_reverse($this->_options['parents']) as $parent) { - if ($parent === $class->getName()) { continue; } $ref = new ReflectionClass($parent); - if ($ref->isAbstract() || ! $class->isSubclassOf($parent)) { + if ($ref->isAbstract() || !$class->isSubclassOf($parent)) { continue; } $parentTable = $this->_conn->getTable($parent); @@ -363,17 +362,16 @@ public function initDefinition() $parentColumns = $parentTable->getColumns(); foreach ($parentColumns as $columnName => $definition) { - if ( ! isset($definition['primary']) || $definition['primary'] === false) { + if (!isset($definition['primary']) || false === $definition['primary']) { if (isset($this->_columns[$columnName])) { $found = true; break; - } else { - if ( ! isset($parentColumns[$columnName]['owner'])) { - $parentColumns[$columnName]['owner'] = $parentTable->getComponentName(); - } - - $this->_options['joinedParents'][] = $parentColumns[$columnName]['owner']; } + if (!isset($parentColumns[$columnName]['owner'])) { + $parentColumns[$columnName]['owner'] = $parentTable->getComponentName(); + } + + $this->_options['joinedParents'][] = $parentColumns[$columnName]['owner']; } else { unset($parentColumns[$columnName]); } @@ -384,7 +382,7 @@ public function initDefinition() } foreach ($parentColumns as $columnName => $definition) { - $fullName = $columnName . ' as ' . $parentTable->getFieldName($columnName); + $fullName = $columnName.' as '.$parentTable->getFieldName($columnName); $this->setColumn($fullName, $definition['type'], $definition['length'], $definition, true); } @@ -402,7 +400,7 @@ public function initDefinition() $this->columnCount = count($this->_columns); - if ( ! isset($this->_options['tableName'])) { + if (!isset($this->_options['tableName'])) { $this->setTableName(Doctrine_Inflector::tableize($class->getName())); } @@ -415,21 +413,19 @@ public function initDefinition() * Called in the construction process, builds the identifier definition * copying in the schema the list of the fields which constitutes * the primary key. - * - * @return void */ public function initIdentifier() { switch (count($this->_identifier)) { case 0: - if ( ! empty($this->_options['joinedParents'])) { + if (!empty($this->_options['joinedParents'])) { $root = current($this->_options['joinedParents']); $table = $this->_conn->getTable($root); $this->_identifier = $table->getIdentifier(); - $this->_identifierType = ($table->getIdentifierType() !== Doctrine_Core::IDENTIFIER_AUTOINC) + $this->_identifierType = (Doctrine_Core::IDENTIFIER_AUTOINC !== $table->getIdentifierType()) ? $table->getIdentifierType() : Doctrine_Core::IDENTIFIER_NATURAL; // add all inherited primary keys @@ -438,27 +434,26 @@ public function initIdentifier() // inherited primary keys shouldn't contain autoinc // and sequence definitions - unset($definition['autoincrement']); - unset($definition['sequence']); + unset($definition['autoincrement'], $definition['sequence']); // add the inherited primary key column - $fullName = $id . ' as ' . $table->getFieldName($id); + $fullName = $id.' as '.$table->getFieldName($id); $this->setColumn($fullName, $definition['type'], $definition['length'], - $definition, true); + $definition, true); } } else { $identifierOptions = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_IDENTIFIER_OPTIONS); - $name = (isset($identifierOptions['name']) && $identifierOptions['name']) ? $identifierOptions['name']:'id'; + $name = (isset($identifierOptions['name']) && $identifierOptions['name']) ? $identifierOptions['name'] : 'id'; $name = sprintf($name, $this->getTableName()); - $definition = array('type' => (isset($identifierOptions['type']) && $identifierOptions['type']) ? $identifierOptions['type']:'integer', - 'length' => (isset($identifierOptions['length']) && $identifierOptions['length']) ? $identifierOptions['length']:8, - 'autoincrement' => isset($identifierOptions['autoincrement']) ? $identifierOptions['autoincrement']:true, - 'primary' => isset($identifierOptions['primary']) ? $identifierOptions['primary']:true); + $definition = array('type' => (isset($identifierOptions['type']) && $identifierOptions['type']) ? $identifierOptions['type'] : 'integer', + 'length' => (isset($identifierOptions['length']) && $identifierOptions['length']) ? $identifierOptions['length'] : 8, + 'autoincrement' => isset($identifierOptions['autoincrement']) ? $identifierOptions['autoincrement'] : true, + 'primary' => isset($identifierOptions['primary']) ? $identifierOptions['primary'] : true); unset($identifierOptions['name'], $identifierOptions['type'], $identifierOptions['length']); foreach ($identifierOptions as $key => $value) { - if ( ! isset($definition[$key]) || ! $definition[$key]) { + if (!isset($definition[$key]) || !$definition[$key]) { $definition[$key] = $value; } } @@ -467,7 +462,7 @@ public function initIdentifier() $this->_identifier = $name; $this->_identifierType = Doctrine_Core::IDENTIFIER_AUTOINC; } - $this->columnCount++; + ++$this->columnCount; break; case 1: foreach ($this->_identifier as $pk) { @@ -485,7 +480,7 @@ public function initIdentifier() switch (strtolower($e2[0])) { case 'autoincrement': case 'autoinc': - if ($value !== false) { + if (false !== $value) { $this->_identifierType = Doctrine_Core::IDENTIFIER_AUTOINC; $found = true; } @@ -507,7 +502,7 @@ public function initIdentifier() break; } } - if ( ! isset($this->_identifierType)) { + if (!isset($this->_identifierType)) { $this->_identifierType = Doctrine_Core::IDENTIFIER_NATURAL; } } @@ -526,16 +521,17 @@ public function initIdentifier() * The owner of a column is the name of the component in a hierarchy that * defines the column. * - * @param string $columnName the column name - * @return string the name of the owning/defining component + * @param string $columnName the column name + * + * @return string the name of the owning/defining component */ public function getColumnOwner($columnName) { if (isset($this->_columns[$columnName]['owner'])) { return $this->_columns[$columnName]['owner']; - } else { - return $this->getComponentName(); } + + return $this->getComponentName(); } /** @@ -546,13 +542,14 @@ public function getColumnOwner($columnName) * but primarily it is first used to instantiate all the internal * in memory schema definition. * - * @return Doctrine_Record Empty instance of the record + * @return Doctrine_Record Empty instance of the record */ public function getRecordInstance() { - if ( ! $this->record) { - $this->record = new $this->_options['name']; + if (!$this->record) { + $this->record = new $this->_options['name'](); } + return $this->record; } @@ -560,11 +557,12 @@ public function getRecordInstance() * Checks whether a column is inherited from a component further up in the hierarchy. * * @param string $columnName The column name - * @return boolean TRUE if column is inherited, FALSE otherwise. + * + * @return bool TRUE if column is inherited, FALSE otherwise */ public function isInheritedColumn($columnName) { - return (isset($this->_columns[$columnName]['owner'])); + return isset($this->_columns[$columnName]['owner']); } /** @@ -573,13 +571,14 @@ public function isInheritedColumn($columnName) * Checks if $fieldName is part of the table identifier, which defines * the one-column or multi-column primary key. * - * @param string $fieldName The field name - * @return boolean TRUE if the field is part of the table identifier/primary key field(s), + * @param string $fieldName The field name + * + * @return bool TRUE if the field is part of the table identifier/primary key field(s), */ public function isIdentifier($fieldName) { - return ($fieldName === $this->getIdentifier() || - in_array($fieldName, (array) $this->getIdentifier())); + return $fieldName === $this->getIdentifier() + || in_array($fieldName, (array) $this->getIdentifier()); } /** @@ -588,30 +587,29 @@ public function isIdentifier($fieldName) * This method checks if the primary key is a AUTOINCREMENT column or * if the table uses a natural key. * - * @return boolean TRUE if the identifier is autoincrement - * FALSE otherwise + * @return bool TRUE if the identifier is autoincrement + * FALSE otherwise */ public function isIdentifierAutoincrement() { - return $this->getIdentifierType() === Doctrine_Core::IDENTIFIER_AUTOINC; + return Doctrine_Core::IDENTIFIER_AUTOINC === $this->getIdentifierType(); } /** * Checks whether a field identifier is a composite key. * - * @return boolean TRUE if the identifier is a composite key, - * FALSE otherwise + * @return bool TRUE if the identifier is a composite key, + * FALSE otherwise */ public function isIdentifierComposite() { - return $this->getIdentifierType() === Doctrine_Core::IDENTIFIER_COMPOSITE; + return Doctrine_Core::IDENTIFIER_COMPOSITE === $this->getIdentifierType(); } /** - * getMethodOwner + * getMethodOwner. * * @param string $method - * @return void */ public function getMethodOwner($method) { @@ -620,7 +618,7 @@ public function getMethodOwner($method) } /** - * setMethodOwner + * setMethodOwner. * * @param string $method * @param string $class @@ -636,10 +634,11 @@ public function setMethodOwner($method, $class) * This method create a physical table in the database, using the * definition that comes from the component Doctrine_Record instance. * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @return boolean whether or not the export operation was successful - * false if table already existed in the database + * @return bool whether or not the export operation was successful + * false if table already existed in the database + * + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function export() { @@ -653,7 +652,8 @@ public function export() * keys are tableName, columns (@see $_columns) and options. * The options subarray contains 'primary' and 'foreignKeys'. * - * @param boolean $parseForeignKeys whether to include foreign keys definition in the options + * @param bool $parseForeignKeys whether to include foreign keys definition in the options + * * @return array */ public function getExportableFormat($parseForeignKeys = true) @@ -662,7 +662,6 @@ public function getExportableFormat($parseForeignKeys = true) $primary = array(); foreach ($this->getColumns() as $name => $definition) { - if (isset($definition['owner'])) { continue; } @@ -685,38 +684,37 @@ public function getExportableFormat($parseForeignKeys = true) $this->_options['foreignKeys'] : array(); if ($parseForeignKeys && $this->getAttribute(Doctrine_Core::ATTR_EXPORT) & Doctrine_Core::EXPORT_CONSTRAINTS) { - $constraints = array(); $emptyIntegrity = array('onUpdate' => null, - 'onDelete' => null); + 'onDelete' => null); foreach ($this->getRelations() as $name => $relation) { $fk = $relation->toArray(); $fk['foreignTable'] = $relation->getTable()->getTableName(); // do not touch tables that have EXPORT_NONE attribute - if ($relation->getTable()->getAttribute(Doctrine_Core::ATTR_EXPORT) === Doctrine_Core::EXPORT_NONE) { + if (Doctrine_Core::EXPORT_NONE === $relation->getTable()->getAttribute(Doctrine_Core::ATTR_EXPORT)) { continue; } if ($relation->getTable() === $this && in_array($relation->getLocal(), $primary)) { if ($relation->hasConstraint()) { - throw new Doctrine_Table_Exception("Badly constructed integrity constraints. Cannot define constraint of different fields in the same table."); + throw new Doctrine_Table_Exception('Badly constructed integrity constraints. Cannot define constraint of different fields in the same table.'); } continue; } $integrity = array('onUpdate' => $fk['onUpdate'], - 'onDelete' => $fk['onDelete']); + 'onDelete' => $fk['onDelete']); $fkName = $relation->getForeignKeyName(); if ($relation instanceof Doctrine_Relation_LocalKey) { - $def = array('name' => $fkName, - 'local' => $relation->getLocalColumnName(), - 'foreign' => $relation->getForeignColumnName(), - 'foreignTable' => $relation->getTable()->getTableName()); + $def = array('name' => $fkName, + 'local' => $relation->getLocalColumnName(), + 'foreign' => $relation->getForeignColumnName(), + 'foreignTable' => $relation->getTable()->getTableName()); if ($integrity !== $emptyIntegrity) { $def = array_merge($def, $integrity); @@ -734,17 +732,18 @@ public function getExportableFormat($parseForeignKeys = true) $options['primary'] = $primary; return array('tableName' => $this->getOption('tableName'), - 'columns' => $columns, - 'options' => array_merge($this->getOptions(), $options)); + 'columns' => $columns, + 'options' => array_merge($this->getOptions(), $options)); } /** * Check if a foreign definition already exists in the fks array for a - * foreign table, local and foreign key + * foreign table, local and foreign key. + * + * @param array $def Foreign key definition to check for + * @param array $foreignKeys Array of existing foreign key definitions to check in * - * @param array $def Foreign key definition to check for - * @param array $foreignKeys Array of existing foreign key definitions to check in - * @return boolean $result Whether or not the foreign key was found + * @return bool $result Whether or not the foreign key was found */ protected function _checkForeignKeyExists($def, $foreignKeys) { @@ -753,13 +752,14 @@ protected function _checkForeignKeyExists($def, $foreignKeys) return $key; } } + return false; } /** * Retrieves the relation parser associated with this table. * - * @return Doctrine_Relation_Parser relation parser object + * @return Doctrine_Relation_Parser relation parser object */ public function getRelationParser() { @@ -777,13 +777,13 @@ public function getRelationParser() * * * @param string $option - * @return mixed */ public function __get($option) { if (isset($this->_options[$option])) { return $this->_options[$option]; } + return null; } @@ -807,7 +807,7 @@ public function __isset($option) /** * Retrieves all options of this table and the associated values. * - * @return array all options and their values + * @return array all options and their values */ public function getOptions() { @@ -820,8 +820,7 @@ public function getOptions() * This method sets options of the table that are specified in the argument. * It has no effect on other options. * - * @param array $options keys are option names - * @return void + * @param array $options keys are option names */ public function setOptions($options) { @@ -836,8 +835,7 @@ public function setOptions($options) * This method adds a foreign key to the schema definition. * It does not add the key to the physical table in the db; @see export(). * - * @param array $definition definition of the foreign key - * @return void + * @param array $definition definition of the foreign key */ public function addForeignKey(array $definition) { @@ -851,10 +849,8 @@ public function addForeignKey(array $definition) * It does not add the constraint to the physical table in the * db; @see export(). * - * @param $definition - * @param mixed $name if string used as name for the constraint. - * Otherwise it is indexed numerically. - * @return void + * @param mixed $name if string used as name for the constraint. + * Otherwise it is indexed numerically. */ public function addCheckConstraint($definition, $name) { @@ -873,9 +869,8 @@ public function addCheckConstraint($definition, $name) * This method adds an INDEX to the schema definition. * It does not add the index to the physical table in the db; @see export(). * - * @param string $index index name - * @param array $definition keys are type, fields - * @return void + * @param string $index index name + * @param array $definition keys are type, fields */ public function addIndex($index, array $definition) { @@ -901,8 +896,9 @@ public function addIndex($index, array $definition) * * This method returns a given index definition: @see addIndex(). * - * @param string $index index name; @see addIndex() - * @return array|boolean array on success, FALSE on failure + * @param string $index index name; @see addIndex() + * + * @return array|bool array on success, FALSE on failure */ public function getIndex($index) { @@ -920,15 +916,13 @@ public function getIndex($index) * and validate the values on save. The UNIQUE index is not created in the * database until you use @see export(). * - * @param array $fields values are fieldnames - * @param array $options array of options for unique validator - * @param bool $createUniqueIndex Whether or not to create a unique index in the database - * @return void + * @param array $fields values are fieldnames + * @param array $options array of options for unique validator */ public function unique($fields, $options = array(), $createdUniqueIndex = true) { if ($createdUniqueIndex) { - $name = implode('_', $fields) . '_unqidx'; + $name = implode('_', $fields).'_unqidx'; $definition = array('type' => 'unique', 'fields' => $fields); $this->addIndex($name, $definition); } @@ -942,28 +936,27 @@ public function unique($fields, $options = array(), $createdUniqueIndex = true) * This method defines a relation on this table, that will be present on * every record belonging to this component. * - * @param array $args first value is a string, name of related component; - * second value is array, options for the relation. + * @param array $args first value is a string, name of related component; + * second value is array, options for the relation + * * @see Doctrine_Relation::_$definition - * @param integer $type Doctrine_Relation::ONE or Doctrine_Relation::MANY - * @return void + * + * @param int $type Doctrine_Relation::ONE or Doctrine_Relation::MANY + * * @todo Name proposal: addRelation */ public function bind($args, $type) { - $options = ( ! isset($args[1])) ? array() : $args[1]; + $options = (!isset($args[1])) ? array() : $args[1]; $options['type'] = $type; $this->_parser->bind($args[0], $options); } /** - * Binds One-to-One aggregate relation + * Binds One-to-One aggregate relation. * - * @param string $componentName the name of the related component - * @param string $options relation options * @see Doctrine_Relation::_$definition - * @return void */ public function hasOne() { @@ -971,12 +964,9 @@ public function hasOne() } /** - * Binds One-to-Many / Many-to-Many aggregate relation + * Binds One-to-Many / Many-to-Many aggregate relation. * - * @param string $componentName the name of the related component - * @param string $options relation options * @see Doctrine_Relation::_$definition - * @return void */ public function hasMany() { @@ -991,8 +981,9 @@ public function hasMany() * recognized as there's only one Doctrine_Relation object on the owning * side. * - * @param string $alias the relation alias to search for. - * @return bool true if the relation exists. Otherwise false. + * @param string $alias the relation alias to search for + * + * @return bool true if the relation exists. Otherwise false. */ public function hasRelation($alias) { @@ -1002,7 +993,8 @@ public function hasRelation($alias) /** * Retrieves a relation object for this component. * - * @param string $alias relation alias; @see hasRelation() + * @param string $alias relation alias; @see hasRelation() + * * @return Doctrine_Relation */ public function getRelation($alias, $recursive = true) @@ -1031,19 +1023,21 @@ public function getRelations() * ->where('myuser.Phonenumber = ?', '5551234'); * * - * @param string $alias name for component aliasing + * @param string $alias name for component aliasing + * * @return Doctrine_Query */ public function createQuery($alias = '') { - if ( ! empty($alias)) { - $alias = ' ' . trim($alias); + if (!empty($alias)) { + $alias = ' '.trim($alias); } $class = $this->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS); return Doctrine_Query::create(null, $class) - ->from($this->getComponentName() . $alias); + ->from($this->getComponentName().$alias) + ; } /** @@ -1063,9 +1057,11 @@ public function getRepository() * allow flexible method chaining. * * @see Doctrine_Table::$_options for available options - * @param string $name the name of the option to set - * @param mixed $value the value of the option - * @return Doctrine_Table this object + * + * @param string $name the name of the option to set + * @param mixed $value the value of the option + * + * @return Doctrine_Table this object */ public function setOption($name, $value) { @@ -1077,8 +1073,8 @@ public function setOption($name, $value) case 'inheritanceMap': case 'index': case 'treeOptions': - if ( ! is_array($value)) { - throw new Doctrine_Table_Exception($name . ' should be an array.'); + if (!is_array($value)) { + throw new Doctrine_Table_Exception($name.' should be an array.'); } break; } @@ -1089,23 +1085,26 @@ public function setOption($name, $value) * Returns the value of a given option. * * @see Doctrine_Table::$_options for available options - * @param string $name the name of the option - * @return mixed the value of given option + * + * @param string $name the name of the option + * + * @return mixed the value of given option */ public function getOption($name) { if (isset($this->_options[$name])) { return $this->_options[$name]; } + return null; } - /** - * Get the table orderby statement + * Get the table orderby statement. + * + * @param string $alias The alias to use + * @param bool $columnNames Whether or not to use column names instead of field names * - * @param string $alias The alias to use - * @param boolean $columnNames Whether or not to use column names instead of field names * @return string $orderByStatement */ public function getOrderByStatement($alias = null, $columnNames = false) @@ -1119,15 +1118,16 @@ public function getOrderByStatement($alias = null, $columnNames = false) * Process an order by statement to be prefixed with the passed alias and * field names converted to column names if the 3rd argument is true. * - * @param string $alias The alias to prefix columns with - * @param string $orderBy The order by to process - * @param string $columnNames Whether or not to convert field names to column names + * @param string $alias The alias to prefix columns with + * @param string $orderBy The order by to process + * @param string $columnNames Whether or not to convert field names to column names + * * @return string $orderBy */ public function processOrderBy($alias, $orderBy, $columnNames = false) { - if ( ! $alias) { - $alias = $this->getComponentName(); + if (!$alias) { + $alias = $this->getComponentName(); } // Php8.1 require a string @@ -1135,7 +1135,7 @@ public function processOrderBy($alias, $orderBy, $columnNames = false) $orderBy = ''; } - if ( ! is_array($orderBy)) { + if (!is_array($orderBy)) { $e1 = explode(',', $orderBy); } else { $e1 = $orderBy; @@ -1148,12 +1148,12 @@ public function processOrderBy($alias, $orderBy, $columnNames = false) $e2[0] = $this->getColumnName($e2[0]); } if ($this->hasField($this->getFieldName($e2[0]))) { - $e1[$k] = $alias . '.' . $e2[0]; + $e1[$k] = $alias.'.'.$e2[0]; } else { $e1[$k] = $e2[0]; } if (isset($e2[1])) { - $e1[$k] .= ' ' . $e2[1]; + $e1[$k] .= ' '.$e2[1]; } } @@ -1166,14 +1166,13 @@ public function processOrderBy($alias, $orderBy, $columnNames = false) * If the actual name for the alias cannot be found * this method returns the given alias. * - * @param string $alias column alias - * @return string column name + * @return string column name */ public function getColumnName($fieldName) { // FIX ME: This is being used in places where an array is passed, but it should not be an array // For example in places where Doctrine should support composite foreign/primary keys - $fieldName = is_array($fieldName) ? $fieldName[0]:$fieldName; + $fieldName = is_array($fieldName) ? $fieldName[0] : $fieldName; if (isset($this->_columnNames[$fieldName])) { return $this->_columnNames[$fieldName]; @@ -1190,13 +1189,15 @@ public function getColumnName($fieldName) * Retrieves a column definition from this table schema. * * @param string $columnName - * @return array column definition; @see $_columns + * + * @return array column definition; @see $_columns */ public function getColumnDefinition($columnName) { - if ( ! isset($this->_columns[$columnName])) { + if (!isset($this->_columns[$columnName])) { return false; } + return $this->_columns[$columnName]; } @@ -1205,14 +1206,16 @@ public function getColumnDefinition($columnName) * * If no alias can be found the column name is returned. * - * @param string $columnName column name - * @return string column alias + * @param string $columnName column name + * + * @return string column alias */ public function getFieldName($columnName) { if (isset($this->_fieldNames[$columnName])) { return $this->_fieldNames[$columnName]; } + return $columnName; } @@ -1231,8 +1234,6 @@ public function getFieldName($columnName) * } * * @param string $columnName - * @param array $validators - * @return void */ public function setColumnOptions($columnName, array $options) { @@ -1248,23 +1249,22 @@ public function setColumnOptions($columnName, array $options) } /** - * Set an individual column option + * Set an individual column option. * * @param string $columnName * @param string $option * @param string $value - * @return void */ public function setColumnOption($columnName, $option, $value) { - if ($option == 'primary') { + if ('primary' == $option) { if (isset($this->_identifier)) { $this->_identifier = (array) $this->_identifier; } - if ($value && ! in_array($columnName, $this->_identifier)) { + if ($value && !in_array($columnName, $this->_identifier)) { $this->_identifier[] = $columnName; - } else if (!$value && in_array($columnName, $this->_identifier)) { + } elseif (!$value && in_array($columnName, $this->_identifier)) { $key = array_search($columnName, $this->_identifier); unset($this->_identifier[$key]); } @@ -1275,10 +1275,7 @@ public function setColumnOption($columnName, $option, $value) } /** - * Set multiple column definitions at once - * - * @param array $definitions - * @return void + * Set multiple column definitions at once. */ public function setColumns(array $definitions) { @@ -1293,14 +1290,14 @@ public function setColumns(array $definitions) * This method does not alter the database table; @see export(); * * @see $_columns; - * @param string $name column physical name - * @param string $type type of data - * @param integer $length maximum length - * @param mixed $options - * @param boolean $prepend Whether to prepend or append the new column to the column list. - * By default the column gets appended. - * @throws Doctrine_Table_Exception if trying use wrongly typed parameter - * @return void + * + * @param string $name column physical name + * @param string $type type of data + * @param int $length maximum length + * @param bool $prepend Whether to prepend or append the new column to the column list. + * By default the column gets appended. + * + * @throws Doctrine_Table_Exception if trying use wrongly typed parameter */ public function setColumn($name, $type = null, $length = null, $options = array(), $prepend = false) { @@ -1310,7 +1307,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( foreach ($options as $k => $option) { if (is_numeric($k)) { - if ( ! empty($option)) { + if (!empty($option)) { $options[$option] = true; } unset($options[$k]); @@ -1318,8 +1315,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( } // extract column name & field name - if (stripos($name, ' as ')) - { + if (stripos($name, ' as ')) { if (strpos($name, ' as ')) { $parts = explode(' as ', $name); } else { @@ -1351,18 +1347,18 @@ public function setColumn($name, $type = null, $length = null, $options = array( $defaultOptions = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_COLUMN_OPTIONS); - if (isset($defaultOptions['length']) && $defaultOptions['length'] && $length == null) { + if (isset($defaultOptions['length']) && $defaultOptions['length'] && null == $length) { $length = $defaultOptions['length']; } - if ($length == null) { + if (null == $length) { switch ($type) { case 'integer': $length = 8; - break; + break; case 'decimal': $length = 18; - break; + break; case 'string': case 'clob': case 'float': @@ -1371,20 +1367,23 @@ public function setColumn($name, $type = null, $length = null, $options = array( case 'object': case 'blob': case 'gzip': - //$length = 2147483647; + // $length = 2147483647; - //All the DataDict driver classes have work-arounds to deal - //with unset lengths. + // All the DataDict driver classes have work-arounds to deal + // with unset lengths. $length = null; - break; + break; case 'boolean': $length = 1; + // no break case 'date': // YYYY-MM-DD ISO 8601 $length = 10; + // no break case 'time': // HH:NN:SS+00:00 ISO 8601 $length = 14; + // no break case 'timestamp': // YYYY-MM-DDTHH:MM:SS+00:00 ISO 8601 $length = 25; @@ -1399,7 +1398,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( } foreach ($defaultOptions as $key => $value) { - if ( ! array_key_exists($key, $options) || is_null($options[$key])) { + if (!array_key_exists($key, $options) || is_null($options[$key])) { $options[$key] = $value; } } @@ -1414,7 +1413,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( if (isset($this->_identifier)) { $this->_identifier = (array) $this->_identifier; } - if ( ! in_array($fieldName, $this->_identifier)) { + if (!in_array($fieldName, $this->_identifier)) { $this->_identifier[] = $fieldName; } } @@ -1426,7 +1425,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( /** * Finds out whether this table has default values for columns. * - * @return boolean + * @return bool */ public function hasDefaultValues() { @@ -1436,25 +1435,27 @@ public function hasDefaultValues() /** * Retrieves the default value (if any) for a given column. * - * @param string $fieldName column name - * @return mixed default value as set in definition + * @param string $fieldName column name + * + * @return mixed default value as set in definition */ public function getDefaultValueOf($fieldName) { $columnName = $this->getColumnName($fieldName); - if ( ! isset($this->_columns[$columnName])) { + if (!isset($this->_columns[$columnName])) { throw new Doctrine_Table_Exception("Couldn't get default value. Column ".$columnName." doesn't exist."); } if (isset($this->_columns[$columnName]['default'])) { return $this->_columns[$columnName]['default']; - } else { - return null; } + + return null; } /** * Returns the definition of the identifier key. - * @return string can be array if a multi-column primary key is used. + * + * @return string can be array if a multi-column primary key is used */ public function getIdentifier() { @@ -1465,8 +1466,10 @@ public function getIdentifier() * Retrieves the type of primary key. * * This method finds out if the primary key is multifield. + * * @see Doctrine_Identifier constants - * @return integer + * + * @return int */ public function getIdentifierType() { @@ -1475,8 +1478,10 @@ public function getIdentifierType() /** * Finds out whether the table definition contains a given column. + * * @param string $columnName - * @return boolean + * + * @return bool */ public function hasColumn($columnName) { @@ -1488,8 +1493,10 @@ public function hasColumn($columnName) * * This method returns true if @see hasColumn() returns true or if an alias * named $fieldName exists. + * * @param string $fieldName - * @return boolean + * + * @return bool */ public function hasField($fieldName) { @@ -1518,7 +1525,7 @@ public function setConnection(Doctrine_Connection $conn) /** * Returns the connection associated with this table (if any). * - * @return Doctrine_Connection|null the connection object + * @return Doctrine_Connection|null the connection object */ public function getConnection() { @@ -1536,6 +1543,7 @@ public function getConnection() * @param array $array an array where keys are field names and * values representing field values. Can contain * also related components; + * * @see Doctrine_Record::fromArray() * * @return Doctrine_Record the created record object @@ -1557,13 +1565,11 @@ public function create(array $array = array()) * * @param string $queryKey query key name to use for storage * @param string|Doctrine_Query $query DQL string or object - * - * @return void */ public function addNamedQuery($queryKey, $query) { $registry = Doctrine_Manager::getInstance()->getQueryRegistry(); - $registry->add($this->getComponentName() . '/' . $queryKey, $query); + $registry->add($this->getComponentName().'/'.$queryKey, $query); } /** @@ -1572,14 +1578,16 @@ public function addNamedQuery($queryKey, $query) * This method clones a new query object from a previously registered one. * * @see addNamedQuery() - * @param string $queryKey query key name + * + * @param string $queryKey query key name + * * @return Doctrine_Query */ public function createNamedQuery($queryKey) { $queryRegistry = Doctrine_Manager::getInstance()->getQueryRegistry(); - if (strpos($queryKey, '/') !== false) { + if (false !== strpos($queryKey, '/')) { $e = explode('/', $queryKey); return $queryRegistry->get($e[1], $e[0]); @@ -1597,13 +1605,6 @@ public function createNamedQuery($queryKey) * $table->find('namedQueryForYearArchive', array(2009), Doctrine_Core::HYDRATE_ARRAY); * * - * @param mixed $name Database Row ID or Query Name defined previously as a NamedQuery - * @param mixed $params This argument is the hydration mode (Doctrine_Core::HYDRATE_ARRAY or - * Doctrine_Core::HYDRATE_RECORD) if first param is a Database Row ID. - * Otherwise this argument expect an array of query params. - * @param int $hydrationMode Optional Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD if - * first argument is a NamedQuery - * * @return Doctrine_Collection|array|Doctrine_Record|false Doctrine_Collection, array, Doctrine_Record or false if no result */ public function find() @@ -1621,14 +1622,14 @@ public function find() $m = $name; // Check for possible cross-access - if ( ! is_array($name) && strpos($name, '/') !== false) { + if (!is_array($name) && false !== strpos($name, '/')) { list($ns, $m) = explode('/', $name); } // Define query to be used if ( - ! is_array($name) && - Doctrine_Manager::getInstance()->getQueryRegistry()->has($m, $ns) + !is_array($name) + && Doctrine_Manager::getInstance()->getQueryRegistry()->has($m, $ns) ) { // We're dealing with a named query $q = $this->createNamedQuery($name); @@ -1637,21 +1638,22 @@ public function find() $params = ($num_args >= 2) ? func_get_arg(1) : array(); // Hydration mode - $hydrationMode = ($num_args == 3) ? func_get_arg(2) : null; + $hydrationMode = (3 == $num_args) ? func_get_arg(2) : null; // Executing query $res = $q->execute($params, $hydrationMode); } else { // We're passing a single ID or an array of IDs $q = $this->createQuery('dctrn_find') - ->where('dctrn_find.' . implode(' = ? AND dctrn_find.', (array) $this->getIdentifier()) . ' = ?') - ->limit(1); + ->where('dctrn_find.'.implode(' = ? AND dctrn_find.', (array) $this->getIdentifier()).' = ?') + ->limit(1) + ; // Parameters construction $params = is_array($name) ? array_values($name) : array($name); // Hydration mode - $hydrationMode = ($num_args == 2) ? func_get_arg(1) : null; + $hydrationMode = (2 == $num_args) ? func_get_arg(1) : null; // Executing query $res = $q->fetchOne($params, $hydrationMode); @@ -1663,7 +1665,8 @@ public function find() /** * Retrieves all the records stored in this table. * - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array */ public function findAll($hydrationMode = null) @@ -1674,9 +1677,10 @@ public function findAll($hydrationMode = null) /** * Finds records in this table with a given SQL where clause. * - * @param string $dql DQL WHERE clause to use - * @param array $params query parameters (a la PDO) - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string $dql DQL WHERE clause to use + * @param array $params query parameters (a la PDO) + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array * * @todo This actually takes DQL, not SQL, but it requires column names @@ -1685,21 +1689,23 @@ public function findAll($hydrationMode = null) public function findBySql($dql, $params = array(), $hydrationMode = null) { return $this->createQuery('dctrn_find') - ->where($dql)->execute($params, $hydrationMode); + ->where($dql)->execute($params, $hydrationMode) + ; } /** * Finds records in this table with a given DQL where clause. * - * @param string $dql DQL WHERE clause - * @param array $params preparated statement parameters - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string $dql DQL WHERE clause + * @param array $params preparated statement parameters + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array */ public function findByDql($dql, $params = array(), $hydrationMode = null) { $parser = $this->createQuery(); - $query = 'FROM ' . $this->getComponentName() . ' dctrn_find WHERE ' . $dql; + $query = 'FROM '.$this->getComponentName().' dctrn_find WHERE '.$dql; return $parser->query($query, $params, $hydrationMode); } @@ -1707,24 +1713,25 @@ public function findByDql($dql, $params = array(), $hydrationMode = null) /** * Find records basing on a field. * - * @param string $column field for the WHERE clause - * @param string|array $value prepared statement parameter - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string|array $value prepared statement parameter + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array */ public function findBy($fieldName, $value, $hydrationMode = null) { return $this->createQuery('dctrn_find') ->where($this->buildFindByWhere($fieldName), (array) $value) - ->execute(array(), $hydrationMode); + ->execute(array(), $hydrationMode) + ; } /** * Finds the first record that satisfy the clause. * - * @param string $column field for the WHERE clause - * @param string|array $value prepared statement parameter - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string|array $value prepared statement parameter + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Record */ public function findOneBy($fieldName, $value, $hydrationMode = null) @@ -1732,7 +1739,8 @@ public function findOneBy($fieldName, $value, $hydrationMode = null) return $this->createQuery('dctrn_find') ->where($this->buildFindByWhere($fieldName), (array) $value) ->limit(1) - ->fetchOne(array(), $hydrationMode); + ->fetchOne(array(), $hydrationMode) + ; } /** @@ -1742,10 +1750,12 @@ public function findOneBy($fieldName, $value, $hydrationMode = null) * query in the query registry. * * @param string $queryKey the query key - * @param array $params prepared statement params (if any) - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD - * @throws Doctrine_Query_Registry if no query for given queryKey is found + * @param array $params prepared statement params (if any) + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array + * + * @throws Doctrine_Query_Registry if no query for given queryKey is found */ public function execute($queryKey, $params = array(), $hydrationMode = Doctrine_Core::HYDRATE_RECORD) { @@ -1759,10 +1769,12 @@ public function execute($queryKey, $params = array(), $hydrationMode = Doctrine_ * the associated named query in the query registry. * * @param string $queryKey the query key - * @param array $params prepared statement params (if any) - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD - * @throws Doctrine_Query_Registry if no query for given queryKey is found + * @param array $params prepared statement params (if any) + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Record|array + * + * @throws Doctrine_Query_Registry if no query for given queryKey is found */ public function executeOne($queryKey, $params = array(), $hydrationMode = Doctrine_Core::HYDRATE_RECORD) { @@ -1774,7 +1786,6 @@ public function executeOne($queryKey, $params = array(), $hydrationMode = Doctri * * This method ensures that records are reloaded from the db. * - * @return void * @todo what about a more descriptive name? clearIdentityMap? */ public function clear() @@ -1788,8 +1799,10 @@ public function clear() * This method is used internally to cache records, ensuring that only one * object that represents a sql record exists in all scopes. * - * @param Doctrine_Record $record record to be added - * @return boolean true if record was not present in the map + * @param Doctrine_Record $record record to be added + * + * @return bool true if record was not present in the map + * * @todo Better name? registerRecord? */ public function addRecord(Doctrine_Record $record) @@ -1815,9 +1828,10 @@ public function addRecord(Doctrine_Record $record) * This method deletes from the cache the given record; can be used to * force reloading of an object from database. * - * @param Doctrine_Record $record record to remove from cache - * @return boolean true if the record was found and removed, - * false if the record wasn't found. + * @param Doctrine_Record $record record to remove from cache + * + * @return bool true if the record was found and removed, + * false if the record wasn't found */ public function removeRecord(Doctrine_Record $record) { @@ -1829,6 +1843,7 @@ public function removeRecord(Doctrine_Record $record) if (isset($this->_identityMap[$id])) { unset($this->_identityMap[$id]); + return true; } @@ -1845,16 +1860,16 @@ public function removeRecord(Doctrine_Record $record) */ public function getRecord() { - if ( ! empty($this->_data)) { + if (!empty($this->_data)) { $identifierFieldNames = $this->getIdentifier(); - if ( ! is_array($identifierFieldNames)) { + if (!is_array($identifierFieldNames)) { $identifierFieldNames = array($identifierFieldNames); } $found = false; foreach ($identifierFieldNames as $fieldName) { - if ( ! isset($this->_data[$fieldName])) { + if (!isset($this->_data[$fieldName])) { // primary key column not found return new record $found = true; break; @@ -1866,6 +1881,7 @@ public function getRecord() $recordName = $this->getComponentName(); $record = new $recordName($this, true); $this->_data = array(); + return $record; } @@ -1875,7 +1891,7 @@ public function getRecord() $record = $this->_identityMap[$id]; if ($record->getTable()->getAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE)) { $record->hydrate($this->_data); - if ($record->state() == Doctrine_Record::STATE_PROXY) { + if (Doctrine_Record::STATE_PROXY == $record->state()) { if (!$record->isInProxyState()) { $record->state(Doctrine_Record::STATE_CLEAN); } @@ -1912,11 +1928,12 @@ public function getRecord() * if the subclassing option is not set. * * @return string The name of the class to create + * * @deprecated */ public function getClassnameToReturn() { - if ( ! isset($this->_options['subclasses'])) { + if (!isset($this->_options['subclasses'])) { return $this->_options['name']; } foreach ($this->_options['subclasses'] as $subclass) { @@ -1924,56 +1941,63 @@ public function getClassnameToReturn() $inheritanceMap = $table->getOption('inheritanceMap'); $nomatch = false; foreach ($inheritanceMap as $key => $value) { - if ( ! isset($this->_data[$key]) || $this->_data[$key] != $value) { + if (!isset($this->_data[$key]) || $this->_data[$key] != $value) { $nomatch = true; break; } } - if ( ! $nomatch) { + if (!$nomatch) { return $table->getComponentName(); } } + return $this->_options['name']; } /** - * @param $id database row id - * @throws Doctrine_Find_Exception + * @param $id database row id + * * @return Doctrine_Record + * + * @throws Doctrine_Find_Exception */ final public function getProxy($id = null) { - if ($id !== null) { + if (null !== $id) { $identifierColumnNames = $this->getIdentifierColumnNames(); - $query = 'SELECT ' . implode(', ', (array) $identifierColumnNames) - . ' FROM ' . $this->getTableName() - . ' WHERE ' . implode(' = ? && ', (array) $identifierColumnNames) . ' = ?'; + $query = 'SELECT '.implode(', ', (array) $identifierColumnNames) + .' FROM '.$this->getTableName() + .' WHERE '.implode(' = ? && ', (array) $identifierColumnNames).' = ?'; $query = $this->applyInheritance($query); $params = array_merge(array($id), array_values($this->_options['inheritanceMap'])); $this->_data = $this->_conn->execute($query, $params)->fetch(PDO::FETCH_ASSOC); - if ($this->_data === false) + if (false === $this->_data) { return false; + } } + return $this->getRecord(); } /** - * applyInheritance - * @param $where query where part to be modified - * @return string query where part with column aggregation inheritance added + * applyInheritance. + * + * @param $where query where part to be modified + * + * @return string query where part with column aggregation inheritance added */ final public function applyInheritance($where) { - if ( ! empty($this->_options['inheritanceMap'])) { + if (!empty($this->_options['inheritanceMap'])) { $a = array(); foreach ($this->_options['inheritanceMap'] as $field => $value) { - $a[] = $this->getColumnName($field) . ' = ?'; + $a[] = $this->getColumnName($field).' = ?'; } $i = implode(' AND ', $a); - $where .= ' AND ' . $i; + $where .= ' AND '.$i; } return $where; @@ -1982,16 +2006,16 @@ final public function applyInheritance($where) /** * Implements Countable interface. * - * @return integer number of records in the table + * @return int number of records in the table */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return $this->createQuery()->count(); } /** - * @return Doctrine_Query a Doctrine_Query object + * @return Doctrine_Query a Doctrine_Query object */ public function getQueryObject() { @@ -2005,6 +2029,7 @@ public function getQueryObject() * Retrieves the enum values for a given field. * * @param string $fieldName + * * @return array */ public function getEnumValues($fieldName) @@ -2012,9 +2037,9 @@ public function getEnumValues($fieldName) $columnName = $this->getColumnName($fieldName); if (isset($this->_columns[$columnName]['values'])) { return $this->_columns[$columnName]['values']; - } else { - return array(); } + + return array(); } /** @@ -2024,8 +2049,7 @@ public function getEnumValues($fieldName) * on the connection, index and value are the same thing. * * @param string $fieldName - * @param integer $index numeric index of the enum - * @return mixed + * @param int $index numeric index of the enum */ public function enumValue($fieldName, $index) { @@ -2044,11 +2068,13 @@ public function enumValue($fieldName, $index) /** * Retrieves an enum index. + * * @see enumValue() * * @param string $fieldName - * @param mixed $value value of the enum considered - * @return integer can be string if native enums are used. + * @param mixed $value value of the enum considered + * + * @return int can be string if native enums are used */ public function enumIndex($fieldName, $value) { @@ -2057,16 +2083,19 @@ public function enumIndex($fieldName, $value) if ($this->_conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) { return $value; } + return array_search($value, $values); } /** * Validates a given field using table ATTR_VALIDATE rules. + * * @see Doctrine_Core::ATTR_VALIDATE * - * @param string $fieldName - * @param string $value - * @param Doctrine_Record $record record to consider; if it does not exists, it is created + * @param string $fieldName + * @param string $value + * @param Doctrine_Record $record record to consider; if it does not exists, it is created + * * @return Doctrine_Validator_ErrorStack $errorStack */ public function validateField($fieldName, $value, Doctrine_Record $record = null) @@ -2074,16 +2103,16 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null if ($record instanceof Doctrine_Record) { $errorStack = $record->getErrorStack(); } else { - $record = $this->create(); + $record = $this->create(); $errorStack = new Doctrine_Validator_ErrorStack($this->getOption('name')); } if ($value === self::$_null) { $value = null; - } else if ($value instanceof Doctrine_Record && $value->exists()) { + } elseif ($value instanceof Doctrine_Record && $value->exists()) { $value = $value->getIncremented(); - } else if ($value instanceof Doctrine_Record && ! $value->exists()) { - foreach($this->getRelations() as $relation) { + } elseif ($value instanceof Doctrine_Record && !$value->exists()) { + foreach ($this->getRelations() as $relation) { if ($fieldName == $relation->getLocalFieldName() && (get_class($value) == $relation->getClass() || is_subclass_of($value, $relation->getClass()))) { return $errorStack; } @@ -2094,16 +2123,16 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null // Validate field type, if type validation is enabled if ($this->getAttribute(Doctrine_Core::ATTR_VALIDATE) & Doctrine_Core::VALIDATE_TYPES) { - if ( ! Doctrine_Validator::isValidType($value, $dataType)) { + if (!Doctrine_Validator::isValidType($value, $dataType)) { $errorStack->add($fieldName, 'type'); } - if ($dataType == 'enum') { + if ('enum' == $dataType) { $enumIndex = $this->enumIndex($fieldName, $value); - if ($enumIndex === false && $value !== null) { + if (false === $enumIndex && null !== $value) { $errorStack->add($fieldName, 'enum'); } } - if ($dataType == 'set') { + if ('set' == $dataType) { $values = $this->_columns[$fieldName]['values']; // Convert string to array if (is_string($value)) { @@ -2115,7 +2144,7 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null } // Make sure each set value is valid foreach ($value as $k => $v) { - if ( ! in_array($v, $values)) { + if (!in_array($v, $values)) { $errorStack->add($fieldName, 'set'); } } @@ -2124,14 +2153,14 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null // Validate field length, if length validation is enabled if ($this->getAttribute(Doctrine_Core::ATTR_VALIDATE) & Doctrine_Core::VALIDATE_LENGTHS) { - if ( ! Doctrine_Validator::validateLength($value, $dataType, $this->getFieldLength($fieldName))) { + if (!Doctrine_Validator::validateLength($value, $dataType, $this->getFieldLength($fieldName))) { $errorStack->add($fieldName, 'length'); } } // Run all custom validators foreach ($this->getFieldValidators($fieldName) as $validatorName => $args) { - if ( ! is_string($validatorName)) { + if (!is_string($validatorName)) { $validatorName = $args; $args = array(); } @@ -2140,7 +2169,7 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null $validator->invoker = $record; $validator->field = $fieldName; $validator->args = $args; - if ( ! $validator->validate($value)) { + if (!$validator->validate($value)) { $errorStack->add($fieldName, $validator); } } @@ -2153,8 +2182,6 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null * * This methods validates 'unique' sets of fields for the given Doctrine_Record instance. * Pushes error to the record error stack if they are generated. - * - * @param Doctrine_Record $record */ public function validateUniques(Doctrine_Record $record) { @@ -2162,16 +2189,15 @@ public function validateUniques(Doctrine_Record $record) $validator = Doctrine_Validator::getValidator('unique'); $validator->invoker = $record; - foreach ($this->_uniques as $unique) - { + foreach ($this->_uniques as $unique) { list($fields, $options) = $unique; $validator->args = $options; $validator->field = $fields; $values = array(); foreach ($fields as $field) { - $values[] = $record->$field; + $values[] = $record->{$field}; } - if ( ! $validator->validate($values)) { + if (!$validator->validate($values)) { foreach ($fields as $field) { $errorStack->add($field, $validator); } @@ -2180,7 +2206,7 @@ public function validateUniques(Doctrine_Record $record) } /** - * @return integer the number of columns in this table + * @return int the number of columns in this table */ public function getColumnCount() { @@ -2191,7 +2217,8 @@ public function getColumnCount() * Retrieves all columns of the table. * * @see $_columns; - * @return array keys are column names and values are definition + * + * @return array keys are column names and values are definition */ public function getColumns() { @@ -2202,18 +2229,20 @@ public function getColumns() * Removes a field name from the table schema information. * * @param string $fieldName - * @return boolean true if the field is found and removed. - * False otherwise. + * + * @return bool true if the field is found and removed. + * False otherwise. */ public function removeColumn($fieldName) { - if ( ! $this->hasField($fieldName)) { - return false; + if (!$this->hasField($fieldName)) { + return false; } $columnName = $this->getColumnName($fieldName); unset($this->_columnNames[$fieldName], $this->_fieldNames[$columnName], $this->_columns[$columnName]); $this->columnCount = count($this->_columns); + return true; } @@ -2224,15 +2253,15 @@ public function removeColumn($fieldName) */ public function getColumnNames(array $fieldNames = null) { - if ($fieldNames === null) { + if (null === $fieldNames) { return array_keys($this->_columns); - } else { - $columnNames = array(); - foreach ($fieldNames as $fieldName) { - $columnNames[] = $this->getColumnName($fieldName); - } - return $columnNames; } + $columnNames = array(); + foreach ($fieldNames as $fieldName) { + $columnNames[] = $this->getColumnName($fieldName); + } + + return $columnNames; } /** @@ -2247,6 +2276,7 @@ public function getIdentifierColumnNames() /** * Gets the array of unique fields sets. + * * @see $_uniques; * * @return array numeric array @@ -2273,11 +2303,13 @@ public function getFieldNames() * which can be a column name or a field name (alias). * * @param string $fieldName - * @return array false on failure + * + * @return array false on failure */ public function getDefinitionOf($fieldName) { $columnName = $this->getColumnName($fieldName); + return $this->getColumnDefinition($columnName); } @@ -2285,7 +2317,8 @@ public function getDefinitionOf($fieldName) * Retrieves the type of a field. * * @param string $fieldName - * @return string false on failure + * + * @return string false on failure */ public function getTypeOf($fieldName) { @@ -2296,7 +2329,8 @@ public function getTypeOf($fieldName) * Retrieves the type of a column. * * @param string $columnName - * @return string false if column is not found + * + * @return string false if column is not found */ public function getTypeOfColumn($columnName) { @@ -2307,9 +2341,7 @@ public function getTypeOfColumn($columnName) * Doctrine uses this function internally. * Users are strongly discouraged to use this function. * - * @access private - * @param array $data internal data - * @return void + * @param array $data internal data */ public function setData(array $data) { @@ -2346,57 +2378,61 @@ public function getData() * $table->prepareValue($field, $value); // Doctrine_Null * * - * @throws Doctrine_Table_Exception if unserialization of array/object typed column fails or - * @throws Doctrine_Table_Exception if uncompression of gzip typed column fails * - * @param string $field the name of the field - * @param string $value field value - * @param string $typeHint Type hint used to pass in the type of the value to prepare - * if it is already known. This enables the method to skip - * the type determination. Used i.e. during hydration. - * @return mixed prepared value + * @param string $value field value + * @param string $typeHint Type hint used to pass in the type of the value to prepare + * if it is already known. This enables the method to skip + * the type determination. Used i.e. during hydration. + * + * @return mixed prepared value + * + * @throws Doctrine_Table_Exception if unserialization of array/object typed column fails or + * @throws Doctrine_Table_Exception if uncompression of gzip typed column fails * */ public function prepareValue($fieldName, $value, $typeHint = null) { if ($value === self::$_null) { return self::$_null; - } else if ($value === null) { + } + if (null === $value) { return null; - } else { - $type = is_null($typeHint) ? $this->getTypeOf($fieldName) : $typeHint; + } + $type = is_null($typeHint) ? $this->getTypeOf($fieldName) : $typeHint; - switch ($type) { - case 'enum': - case 'integer': - case 'string'; - // don't do any casting here PHP INT_MAX is smaller than what the databases support + switch ($type) { + case 'enum': + case 'integer': + case 'string': + // don't do any casting here PHP INT_MAX is smaller than what the databases support break; - case 'set': - return explode(',', $value); + case 'set': + return explode(',', $value); break; - case 'boolean': - return (boolean) $value; + case 'boolean': + return (bool) $value; break; - case 'array': - case 'object': - if (is_string($value)) { - $value = empty($value) ? null:unserialize($value); + case 'array': + case 'object': + if (is_string($value)) { + $value = empty($value) ? null : unserialize($value); - if ($value === false) { - throw new Doctrine_Table_Exception('Unserialization of ' . $fieldName . ' failed.'); - } - return $value; + if (false === $value) { + throw new Doctrine_Table_Exception('Unserialization of '.$fieldName.' failed.'); } - break; - case 'gzip': - $value = gzuncompress($value); - if ($value === false) { - throw new Doctrine_Table_Exception('Uncompressing of ' . $fieldName . ' failed.'); - } return $value; + } + break; + case 'gzip': + $value = gzuncompress($value); + + if (false === $value) { + throw new Doctrine_Table_Exception('Uncompressing of '.$fieldName.' failed.'); + } + + return $value; break; - } } + return $value; } @@ -2410,15 +2446,17 @@ public function prepareValue($fieldName, $value, $typeHint = null) public function getTree() { if (isset($this->_options['treeImpl'])) { - if ( ! $this->_tree) { + if (!$this->_tree) { $options = isset($this->_options['treeOptions']) ? $this->_options['treeOptions'] : array(); $this->_tree = Doctrine_Tree::factory($this, $this->_options['treeImpl'], $options ); } + return $this->_tree; } + return false; } @@ -2446,7 +2484,6 @@ public function getTableName() * sets the table name in the schema definition. * * @param string $tableName - * @return void */ public function setTableName($tableName) { @@ -2456,17 +2493,17 @@ public function setTableName($tableName) /** * Determines if table acts as tree. * - * @return boolean if tree return true, otherwise returns false + * @return bool if tree return true, otherwise returns false */ public function isTree() { - return ( ! is_null($this->_options['treeImpl'])) ? true : false; + return (!is_null($this->_options['treeImpl'])) ? true : false; } /** * Retrieves all templates (behaviors) attached to this table. * - * @return array an array containing all templates + * @return array an array containing all templates */ public function getTemplates() { @@ -2479,38 +2516,43 @@ public function getTemplates() * This method retrieves a behavior/template object attached to the table. * For Doctrine_Template_* classes, the base name can be used. * - * @param string $template name of the behavior - * @throws Doctrine_Table_Exception if the given template is - * not set on this table + * @param string $template name of the behavior + * * @return Doctrine_Template + * + * @throws Doctrine_Table_Exception if the given template is + * not set on this table */ public function getTemplate($template) { - if (isset($this->_templates['Doctrine_Template_' . $template])) { - return $this->_templates['Doctrine_Template_' . $template]; - } else if (isset($this->_templates[$template])) { + if (isset($this->_templates['Doctrine_Template_'.$template])) { + return $this->_templates['Doctrine_Template_'.$template]; + } + if (isset($this->_templates[$template])) { return $this->_templates[$template]; } - throw new Doctrine_Table_Exception('Template ' . $template . ' not loaded'); + throw new Doctrine_Table_Exception('Template '.$template.' not loaded'); } /** * Checks if the table has a given template. * - * @param string $template name of template; @see getTemplate() - * @return boolean + * @param string $template name of template; @see getTemplate() + * + * @return bool */ public function hasTemplate($template) { - return isset($this->_templates[$template]) || isset($this->_templates['Doctrine_Template_' . $template]); + return isset($this->_templates[$template]) || isset($this->_templates['Doctrine_Template_'.$template]); } /** * Adds a template to this table. * - * @param string $template template name - * @param Doctrine_Template $impl behavior to attach + * @param string $template template name + * @param Doctrine_Template $impl behavior to attach + * * @return Doctrine_Table */ public function addTemplate($template, Doctrine_Template $impl) @@ -2534,12 +2576,13 @@ public function getGenerators() * Gets generator instance for a passed name. * * @param string $generator + * * @return Doctrine_Record_Generator $generator */ public function getGenerator($generator) { - if ( ! isset($this->_generators[$generator])) { - throw new Doctrine_Table_Exception('Generator ' . $generator . ' not loaded'); + if (!isset($this->_generators[$generator])) { + throw new Doctrine_Table_Exception('Generator '.$generator.' not loaded'); } return $this->_generators[$generator]; @@ -2549,7 +2592,6 @@ public function getGenerator($generator) * Checks if a generator name exists. * * @param string $generator - * @return void */ public function hasGenerator($generator) { @@ -2559,25 +2601,23 @@ public function hasGenerator($generator) /** * Adds a generate to the table instance. * - * @param Doctrine_Record_Generator $generator * @param string $name + * * @return Doctrine_Table */ public function addGenerator(Doctrine_Record_Generator $generator, $name = null) { - if ($name === null) { + if (null === $name) { $this->_generators[] = $generator; } else { $this->_generators[$name] = $generator; } + return $this; } /** - * Set the generator responsible for creating this table - * - * @param Doctrine_Record_Generator $generator - * @return void + * Set the generator responsible for creating this table. */ public function setGenerator(Doctrine_Record_Generator $generator) { @@ -2585,9 +2625,9 @@ public function setGenerator(Doctrine_Record_Generator $generator) } /** - * Check whether this table was created by a record generator or not + * Check whether this table was created by a record generator or not. * - * @return boolean + * @return bool */ public function isGenerator() { @@ -2595,7 +2635,7 @@ public function isGenerator() } /** - * Get the parent generator responsible for this table instance + * Get the parent generator responsible for this table instance. * * @return Doctrine_Record_Generator */ @@ -2606,10 +2646,12 @@ public function getParentGenerator() /** * Binds query parts to this component. + * * @see bindQueryPart() * - * @param array $queryParts an array of pre-bound query parts - * @return Doctrine_Table this object + * @param array $queryParts an array of pre-bound query parts + * + * @return Doctrine_Table this object */ public function bindQueryParts(array $queryParts) { @@ -2625,8 +2667,8 @@ public function bindQueryParts(array $queryParts) * Every query created by this table will have this part set by default. * * @param string $queryPart - * @param mixed $value - * @return Doctrine_Record this object + * + * @return Doctrine_Record this object */ public function bindQueryPart($queryPart, $value) { @@ -2639,7 +2681,8 @@ public function bindQueryPart($queryPart, $value) * Gets the names of all validators being applied on a field. * * @param string $fieldName - * @return array names of validators + * + * @return array names of validators */ public function getFieldValidators($fieldName) { @@ -2648,32 +2691,32 @@ public function getFieldValidators($fieldName) // this loop is a dirty workaround to get the validators filtered out of // the options, since everything is squeezed together currently foreach ($this->_columns[$columnName] as $name => $args) { - if (empty($name) - || $name == 'primary' - || $name == 'protected' - || $name == 'autoincrement' - || $name == 'default' - || $name == 'values' - || $name == 'sequence' - || $name == 'zerofill' - || $name == 'owner' - || $name == 'scale' - || $name == 'type' - || $name == 'length' - || $name == 'fixed' - || $name == 'comment' - || $name == 'alias' - || $name == 'charset' - || $name == 'collation' - || $name == 'extra') { + if (empty($name) + || 'primary' == $name + || 'protected' == $name + || 'autoincrement' == $name + || 'default' == $name + || 'values' == $name + || 'sequence' == $name + || 'zerofill' == $name + || 'owner' == $name + || 'scale' == $name + || 'type' == $name + || 'length' == $name + || 'fixed' == $name + || 'comment' == $name + || 'alias' == $name + || 'charset' == $name + || 'collation' == $name + || 'extra' == $name) { continue; } - if ($name == 'notnull' && isset($this->_columns[$columnName]['autoincrement']) - && $this->_columns[$columnName]['autoincrement'] === true) { + if ('notnull' == $name && isset($this->_columns[$columnName]['autoincrement']) + && true === $this->_columns[$columnName]['autoincrement']) { continue; } // skip it if it's explicitly set to FALSE (i.e. notnull => false) - if ($args === false) { + if (false === $args) { continue; } $validators[$name] = $args; @@ -2685,10 +2728,11 @@ public function getFieldValidators($fieldName) /** * Gets the maximum length of a field. * For integer fields, length is bytes occupied. - * For decimal fields, it is the total number of cyphers + * For decimal fields, it is the total number of cyphers. * * @param string $fieldName - * @return integer + * + * @return int */ public function getFieldLength($fieldName) { @@ -2697,14 +2741,16 @@ public function getFieldLength($fieldName) /** * Retrieves a bound query part. + * * @see bindQueryPart() * - * @param string $queryPart field interested - * @return string value of the bind + * @param string $queryPart field interested + * + * @return string value of the bind */ public function getBoundQueryPart($queryPart) { - if ( ! isset($this->_options['queryParts'][$queryPart])) { + if (!isset($this->_options['queryParts'][$queryPart])) { return null; } @@ -2712,10 +2758,9 @@ public function getBoundQueryPart($queryPart) } /** - * unshiftFilter + * unshiftFilter. * - * @param Doctrine_Record_Filter $filter - * @return Doctrine_Table this object (provides a fluent interface) + * @return Doctrine_Table this object (provides a fluent interface) */ public function unshiftFilter(Doctrine_Record_Filter $filter) { @@ -2729,7 +2774,7 @@ public function unshiftFilter(Doctrine_Record_Filter $filter) } /** - * getFilters + * getFilters. * * @return array $filters */ @@ -2752,14 +2797,17 @@ public function __toString() } /** - * Helper method for buildFindByWhere to decide if a string is greater than another + * Helper method for buildFindByWhere to decide if a string is greater than another. * * @param string $a * @param string $b */ private function isGreaterThan($a, $b) { - if (strlen($a) == strlen($b)) return 0; + if (strlen($a) == strlen($b)) { + return 0; + } + return (strlen($a) > strlen($b)) ? 1 : -1; } @@ -2784,7 +2832,7 @@ public function buildFindByWhere($fieldName) $fields = array_reverse(array_unique($fields)); // Identify fields and operators - preg_match_all('/(' . implode('|', $fields) . ')(Or|And)?/', $fieldName, $matches); + preg_match_all('/('.implode('|', $fields).')(Or|And)?/', $fieldName, $matches); $fieldsFound = $matches[1]; $operatorFound = $matches[2]; foreach ($operatorFound as &$v) { @@ -2792,9 +2840,9 @@ public function buildFindByWhere($fieldName) } // Check if $fieldName has unidentified parts left - if (strlen(implode('', $fieldsFound) . implode('', $operatorFound)) !== strlen($fieldName)) { - $expression = preg_replace('/(' . implode('|', $fields) . ')(Or|And)?/', '($1)$2', $fieldName); - throw new Doctrine_Table_Exception('Invalid expression found: ' . $expression); + if (strlen(implode('', $fieldsFound).implode('', $operatorFound)) !== strlen($fieldName)) { + $expression = preg_replace('/('.implode('|', $fields).')(Or|And)?/', '($1)$2', $fieldName); + throw new Doctrine_Table_Exception('Invalid expression found: '.$expression); } // Build result @@ -2803,22 +2851,22 @@ public function buildFindByWhere($fieldName) foreach ($fieldsFound as $index => $field) { $field = $this->_resolveFindByFieldName($field); if (!$field) { - throw new Doctrine_Table_Exception('Invalid field name to find by: ' . $field); + throw new Doctrine_Table_Exception('Invalid field name to find by: '.$field); } - if ($operatorFound[$index] == 'OR' && !$bracketOpen) { + if ('OR' == $operatorFound[$index] && !$bracketOpen) { $where .= '('; $bracketOpen = true; } - $where .= 'dctrn_find.' . $field . ' = ?'; + $where .= 'dctrn_find.'.$field.' = ?'; - if ($operatorFound[$index] != 'OR' && $lastOperator == 'OR') { + if ('OR' != $operatorFound[$index] && 'OR' == $lastOperator) { $where .= ')'; $bracketOpen = false; } - $where .= ' ' . strtoupper($operatorFound[$index]) . ' '; + $where .= ' '.strtoupper($operatorFound[$index]).' '; $lastOperator = $operatorFound[$index]; } @@ -2835,6 +2883,7 @@ public function buildFindByWhere($fieldName) * to get the column or field name. * * @param string $name + * * @return string $fieldName */ protected function _resolveFindByFieldName($name) @@ -2842,19 +2891,22 @@ protected function _resolveFindByFieldName($name) $fieldName = Doctrine_Inflector::tableize($name); if ($this->hasColumn($name) || $this->hasField($name)) { return $this->getFieldName($this->getColumnName($name)); - } else if ($this->hasColumn($fieldName) || $this->hasField($fieldName)) { + } + if ($this->hasColumn($fieldName) || $this->hasField($fieldName)) { return $this->getFieldName($this->getColumnName($fieldName)); - } else { - return false; } + + return false; } /** - * deletes table row(s) matching the specified identifier + * deletes table row(s) matching the specified identifier. + * + * @param mixed $identifier an associateve array containing identifier column-value pairs * - * @throws Doctrine_Connection_Exception if something went wrong at the database level - * @param mixed $identifier An associateve array containing identifier column-value pairs. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @return int the number of affected rows. Boolean false if empty value array was given, + * + * @throws Doctrine_Connection_Exception if something went wrong at the database level */ public function delete($identifier) { @@ -2864,9 +2916,10 @@ public function delete($identifier) /** * Inserts a table row with specified data. * - * @param array $fields An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param array $fields An associative array containing column-value pairs. + * Values can be strings or Doctrine_Expression instances. + * + * @return int the number of affected rows. Boolean false if empty value array was given, */ public function insert(array $fields) { @@ -2876,11 +2929,13 @@ public function insert(array $fields) /** * Updates table row(s) with specified data. * - * @throws Doctrine_Connection_Exception if something went wrong at the database level - * @param array $fields An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @param mixed $identifier An associateve array containing identifier column-value pairs. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param array $fields An associative array containing column-value pairs. + * Values can be strings or Doctrine_Expression instances. + * @param mixed $identifier an associateve array containing identifier column-value pairs + * + * @return int the number of affected rows. Boolean false if empty value array was given, + * + * @throws Doctrine_Connection_Exception if something went wrong at the database level */ public function update(array $fields, $identifier) { @@ -2898,25 +2953,24 @@ public function update(array $fields, $identifier) * query isemulated through this method for other DBMS using standard types * of queries inside a transaction to assure the atomicity of the operation. * - * - * @param array $fields an associative array that describes the fields and the - * values that will be inserted or updated in the specified table. The - * indexes of the array are the names of all the fields of the table. + * @param array $fields an associative array that describes the fields and the + * values that will be inserted or updated in the specified table. The + * indexes of the array are the names of all the fields of the table. * * The values of the array are values to be assigned to the specified field. - * - * @param mixed $keys an array containing all key fields (primary key fields - * or unique index fields) for this table + * @param mixed $keys an array containing all key fields (primary key fields + * or unique index fields) for this table * * the uniqueness of a row will be determined according to * the provided key fields * * this method will fail if no key fields are specified * - * @throws Doctrine_Connection_Exception if this driver doesn't support replace - * @throws Doctrine_Connection_Exception if some of the key values was null - * @throws Doctrine_Connection_Exception if there were no key fields - * @throws PDOException if something fails at PDO level + * @throws Doctrine_Connection_Exception if this driver doesn't support replace + * @throws Doctrine_Connection_Exception if some of the key values was null + * @throws Doctrine_Connection_Exception if there were no key fields + * @throws PDOException if something fails at PDO level + * * @ return integer number of rows affected */ public function replace(array $fields, $keys) @@ -2937,54 +2991,55 @@ public function __call($method, $arguments) { $lcMethod = strtolower($method); - if (substr($lcMethod, 0, 6) == 'findby') { + if ('findby' == substr($lcMethod, 0, 6)) { $by = substr($method, 6, strlen($method)); $method = 'findBy'; - } else if (substr($lcMethod, 0, 9) == 'findoneby') { + } elseif ('findoneby' == substr($lcMethod, 0, 9)) { $by = substr($method, 9, strlen($method)); $method = 'findOneBy'; } if (isset($by)) { - if ( ! isset($arguments[0])) { - throw new Doctrine_Table_Exception('You must specify the value to ' . $method); + if (!isset($arguments[0])) { + throw new Doctrine_Table_Exception('You must specify the value to '.$method); } $fieldName = $this->_resolveFindByFieldName($by); $count = count(explode('Or', $by)) + (count(explode('And', $by)) - 1); - if (count($arguments) > $count) - { + if (count($arguments) > $count) { $hydrationMode = end($arguments); unset($arguments[count($arguments) - 1]); } else { $hydrationMode = null; } if ($this->hasField($fieldName)) { - return $this->$method($fieldName, $arguments[0], $hydrationMode); - } else if ($this->hasRelation($by)) { + return $this->{$method}($fieldName, $arguments[0], $hydrationMode); + } + if ($this->hasRelation($by)) { $relation = $this->getRelation($by); - if ($relation['type'] === Doctrine_Relation::MANY) { + if (Doctrine_Relation::MANY === $relation['type']) { throw new Doctrine_Table_Exception('Cannot findBy many relationship.'); } - return $this->$method($relation['local'], $arguments[0], $hydrationMode); - } else { - return $this->$method($by, $arguments, $hydrationMode); + return $this->{$method}($relation['local'], $arguments[0], $hydrationMode); } + + return $this->{$method}($by, $arguments, $hydrationMode); } // Forward the method on to the record instance and see if it has anything or one of its behaviors try { - return call_user_func_array(array($this->getRecordInstance(), $method . 'TableProxy'), $arguments); - } catch (Doctrine_Record_UnknownPropertyException $e) {} + return call_user_func_array(array($this->getRecordInstance(), $method.'TableProxy'), $arguments); + } catch (Doctrine_Record_UnknownPropertyException $e) { + } throw new Doctrine_Table_Exception(sprintf('Unknown method %s::%s', get_class($this), $method)); } /** * serialize - * this method is automatically called when an instance of Doctrine_Record is serialized + * this method is automatically called when an instance of Doctrine_Record is serialized. * * @return string */ @@ -2996,10 +3051,9 @@ public function serialize() } /** - * this method is automatically called everytime an instance is unserialized + * this method is automatically called everytime an instance is unserialized. * - * @param string $serialized Doctrine_Record as serialized string - * @return void + * @param string $serialized Doctrine_Record as serialized string */ public function unserialize($serialized) { @@ -3008,14 +3062,13 @@ public function unserialize($serialized) $this->__unserialize($data); } - /** - * Serializes the current instance for php 7.4+ + * Serializes the current instance for php 7.4+. * * @return array */ - public function __serialize() { - + public function __serialize() + { $options = $this->_options; unset($options['declaringClass']); @@ -3035,12 +3088,12 @@ public function __serialize() { } /** - * Unserializes a Doctrine_Record instance for php 7.4+ + * Unserializes a Doctrine_Record instance for php 7.4+. * * @param array $data */ - public function __unserialize($data) { - + public function __unserialize($data) + { $this->_identifier = $data[0]; $this->_identifierType = $data[1]; $this->_columns = $data[2]; @@ -3056,7 +3109,6 @@ public function __unserialize($data) { /** * Creates new instance and initialize it from cache. - * */ public function initializeFromCache(Doctrine_Connection $conn) { @@ -3066,8 +3118,8 @@ public function initializeFromCache(Doctrine_Connection $conn) $this->_parser = new Doctrine_Relation_Parser($this); $name = $this->_options['name']; - if ( ! class_exists($name) || empty($name)) { - throw new Doctrine_Exception("Couldn't find class " . $name); + if (!class_exists($name) || empty($name)) { + throw new Doctrine_Exception("Couldn't find class ".$name); } $record = new $name($this); @@ -3075,20 +3127,19 @@ public function initializeFromCache(Doctrine_Connection $conn) // get parent classes do { - if ($class === 'Doctrine_Record') { + if ('Doctrine_Record' === $class) { break; } } while ($class = get_parent_class($class)); - if ($class === false) { - throw new Doctrine_Table_Exception('Class "' . $name . '" must be a child class of Doctrine_Record'); + if (false === $class) { + throw new Doctrine_Table_Exception('Class "'.$name.'" must be a child class of Doctrine_Record'); } if (method_exists($record, 'setTableDefinition')) { // get the declaring class of setTableDefinition method $method = new ReflectionMethod($this->_options['name'], 'setTableDefinition'); $class = $method->getDeclaringClass(); - } else { $class = new ReflectionClass($class); } @@ -3104,7 +3155,7 @@ public function initializeFromCache(Doctrine_Connection $conn) $this->getTree()->setUp(); } - $this->_filters[] = new Doctrine_Record_Filter_Standard(); + $this->_filters[] = new Doctrine_Record_Filter_Standard(); if ($this->getAttribute(Doctrine_Core::ATTR_USE_TABLE_REPOSITORY)) { $this->_repository = new Doctrine_Table_Repository($this); } else { diff --git a/lib/Doctrine/Table/Exception.php b/lib/Doctrine/Table/Exception.php index a12d39226..812cbd5be 100644 --- a/lib/Doctrine/Table/Exception.php +++ b/lib/Doctrine/Table/Exception.php @@ -21,21 +21,23 @@ /** * thrown when user tries to initialize a new instance of Doctrine_Table, - * while there already exists an instance of that table + * while there already exists an instance of that table. * - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Table_Exception extends Doctrine_Exception { public function __construct($message = "Couldn't initialize table. One instance of this table already exists. Always use Doctrine_Session::getTable(\$name) - to get on instance of a Doctrine_Table.") { + to get on instance of a Doctrine_Table.") + { parent::__construct($message); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Table/Repository.php b/lib/Doctrine/Table/Repository.php index 715160434..7a22fbf99 100644 --- a/lib/Doctrine/Table/Repository.php +++ b/lib/Doctrine/Table/Repository.php @@ -22,34 +22,32 @@ /** * Doctrine_Repository * each record is added into Doctrine_Repository at the same time they are created, - * loaded from the database or retrieved from the cache + * loaded from the database or retrieved from the cache. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Table_Repository implements Countable, IteratorAggregate { /** - * @var object Doctrine_Table $table + * @var object Doctrine_Table */ private $table; /** - * @var array $registry - * an array of all records - * keys representing record object identifiers + * @var array + * an array of all records + * keys representing record object identifiers */ private $registry = array(); /** - * constructor - * - * @param Doctrine_Table $table + * constructor. */ public function __construct(Doctrine_Table $table) { @@ -57,7 +55,7 @@ public function __construct(Doctrine_Table $table) } /** - * getTable + * getTable. * * @return Doctrine_Table */ @@ -67,10 +65,11 @@ public function getTable() } /** - * add + * add. + * + * @param Doctrine_Record $record record to be added into registry * - * @param Doctrine_Record $record record to be added into registry - * @return boolean + * @return bool */ public function add(Doctrine_Record $record) { @@ -85,69 +84,78 @@ public function add(Doctrine_Record $record) } /** - * get - * @param integer $oid + * get. + * + * @param int $oid + * * @throws Doctrine_Table_Repository_Exception */ public function get($oid) { - if ( ! isset($this->registry[$oid])) { - throw new Doctrine_Table_Repository_Exception("Unknown object identifier"); + if (!isset($this->registry[$oid])) { + throw new Doctrine_Table_Repository_Exception('Unknown object identifier'); } + return $this->registry[$oid]; } /** * count - * Doctrine_Registry implements interface Countable - * @return integer the number of records this registry has + * Doctrine_Registry implements interface Countable. + * + * @return int the number of records this registry has */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->registry); } /** - * @param integer $oid object identifier - * @return boolean whether ot not the operation was successful + * @param int $oid object identifier + * + * @return bool whether ot not the operation was successful */ public function evict($oid) { - if ( ! isset($this->registry[$oid])) { + if (!isset($this->registry[$oid])) { return false; } unset($this->registry[$oid]); + return true; } /** - * @return integer number of records evicted + * @return int number of records evicted */ public function evictAll() { $evicted = 0; - foreach ($this->registry as $oid=>$record) { + foreach ($this->registry as $oid => $record) { if ($this->evict($oid)) { - $evicted++; + ++$evicted; } } + return $evicted; } /** - * getIterator + * getIterator. + * * @return ArrayIterator */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->registry); } /** - * contains - * @param integer $oid object identifier + * contains. + * + * @param int $oid object identifier */ public function contains($oid) { @@ -155,8 +163,7 @@ public function contains($oid) } /** - * loadAll - * @return void + * loadAll. */ public function loadAll() { diff --git a/lib/Doctrine/Table/Repository/Exception.php b/lib/Doctrine/Table/Repository/Exception.php index 8e433ff13..d18c58bed 100644 --- a/lib/Doctrine/Table/Repository/Exception.php +++ b/lib/Doctrine/Table/Repository/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Table_Repository_Exception + * Doctrine_Table_Repository_Exception. * - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Table_Repository_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Table/Repository/None.php b/lib/Doctrine/Table/Repository/None.php index fe651cae6..fc20cb80a 100644 --- a/lib/Doctrine/Table/Repository/None.php +++ b/lib/Doctrine/Table/Repository/None.php @@ -22,23 +22,24 @@ /** * Doctrine_Repository * each record is added into Doctrine_Repository at the same time they are created, - * loaded from the database or retrieved from the cache + * loaded from the database or retrieved from the cache. * * @author Jérôme Macias - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 115 $ */ class Doctrine_Table_Repository_None extends Doctrine_Table_Repository implements Countable, IteratorAggregate { /** - * add + * add. + * + * @param Doctrine_Record $record record to be added into registry * - * @param Doctrine_Record $record record to be added into registry - * @return boolean + * @return bool */ public function add(Doctrine_Record $record) { @@ -46,33 +47,35 @@ public function add(Doctrine_Record $record) } /** - * get + * get. + * + * @param int $oid * - * @param integer $oid * @throws Doctrine_Table_Repository_Exception */ public function get($oid) { - throw new Doctrine_Table_Repository_Exception("Unknown object identifier"); + throw new Doctrine_Table_Repository_Exception('Unknown object identifier'); } /** * count - * Doctrine_Registry implements interface Countable + * Doctrine_Registry implements interface Countable. * - * @return integer the number of records this registry has + * @return int the number of records this registry has */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return 0; } /** - * evict + * evict. + * + * @param int $oid object identifier * - * @param integer $oid object identifier - * @return boolean whether ot not the operation was successful + * @return bool whether ot not the operation was successful */ public function evict($oid) { @@ -80,9 +83,9 @@ public function evict($oid) } /** - * evictAll + * evictAll. * - * @return integer number of records evicted + * @return int number of records evicted */ public function evictAll() { diff --git a/lib/Doctrine/Task.php b/lib/Doctrine/Task.php index 3a9311c07..9d1c8f9b4 100644 --- a/lib/Doctrine/Task.php +++ b/lib/Doctrine/Task.php @@ -20,34 +20,36 @@ */ /** - * Doctrine_Task - * + * Doctrine_Task. + * * Abstract class used for writing Doctrine Tasks * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ abstract class Doctrine_Task { - public $dispatcher = null, - $taskName = null, /*Treat as protected*/ - $description = null, - $arguments = array(), - $requiredArguments = array(), - $optionalArguments = array(); + public $dispatcher; + public $taskName; + public /* Treat as protected */ + $description; + public $arguments = array(); + public $requiredArguments = array(); + public $optionalArguments = array(); /** - * __construct + * __construct. * * Since this is an abstract classes that extend this must follow a patter of Doctrine_Task_{TASK_NAME} * This is what determines the task name for executing it. * - * @return void + * @param mixed|null $dispatcher */ public function __construct($dispatcher = null) { @@ -55,7 +57,7 @@ public function __construct($dispatcher = null) $taskName = (string) $this->getTaskName(); - //Derive the task name only if it wasn't entered at design-time + // Derive the task name only if it wasn't entered at design-time if ('' === trim($taskName)) { $taskName = self::deriveTaskName(get_class($this)); } @@ -68,14 +70,15 @@ public function __construct($dispatcher = null) } /** - * Returns the name of the task the specified class _would_ implement - * + * Returns the name of the task the specified class _would_ implement. + * * N.B. This method does not check if the specified class is actually a Doctrine Task - * + * * This is public so we can easily test its reactions to fully-qualified class names, without having to add * PHP 5.3-specific test code - * + * * @param string $className + * * @return string|bool */ public static function deriveTaskName($className) @@ -83,8 +86,8 @@ public static function deriveTaskName($className) $nameParts = explode('\\', $className); foreach ($nameParts as &$namePart) { - $prefix = __CLASS__ . '_'; - $baseName = strpos($namePart, $prefix) === 0 ? substr($namePart, strlen($prefix)) : $namePart; + $prefix = __CLASS__.'_'; + $baseName = 0 === strpos($namePart, $prefix) ? substr($namePart, strlen($prefix)) : $namePart; $namePart = str_replace('_', '-', Doctrine_Inflector::tableize($baseName)); } @@ -92,52 +95,45 @@ public static function deriveTaskName($className) } /** - * notify + * notify. * - * @param string $notification - * @return void + * @param string $notification */ public function notify($notification = null) { if (is_object($this->dispatcher) && method_exists($this->dispatcher, 'notify')) { $args = func_get_args(); - + return call_user_func_array(array($this->dispatcher, 'notify'), $args); - } else if ( $notification !== null ) { + } + if (null !== $notification) { return $notification; - } else { - return false; } + + return false; } /** - * ask - * - * @return void + * ask. */ public function ask() { $args = func_get_args(); - + call_user_func_array(array($this, 'notify'), $args); - - $answer = strtolower(trim(fgets(STDIN))); - - return $answer; + + return strtolower(trim(fgets(STDIN))); } /** - * execute + * execute. * * Override with each task class - * - * @return void - * @abstract */ - abstract function execute(); + abstract public function execute(); /** - * validate + * validate. * * Validates that all required fields are present * @@ -146,22 +142,21 @@ abstract function execute(); public function validate() { $requiredArguments = $this->getRequiredArguments(); - + foreach ($requiredArguments as $arg) { - if ( ! isset($this->arguments[$arg])) { + if (!isset($this->arguments[$arg])) { return false; } } - + return true; } /** - * addArgument + * addArgument. * - * @param string $name - * @param string $value - * @return void + * @param string $name + * @param string $value */ public function addArgument($name, $value) { @@ -169,23 +164,22 @@ public function addArgument($name, $value) } /** - * getArgument + * getArgument. * - * @param string $name - * @param string $default - * @return mixed + * @param string $name + * @param string $default */ public function getArgument($name, $default = null) { - if (isset($this->arguments[$name]) && $this->arguments[$name] !== null) { + if (isset($this->arguments[$name]) && null !== $this->arguments[$name]) { return $this->arguments[$name]; - } else { - return $default; } + + return $default; } /** - * getArguments + * getArguments. * * @return array $arguments */ @@ -195,10 +189,7 @@ public function getArguments() } /** - * setArguments - * - * @param array $args - * @return void + * setArguments. */ public function setArguments(array $args) { @@ -206,9 +197,10 @@ public function setArguments(array $args) } /** - * Returns TRUE if the specified task name is valid, or FALSE otherwise - * + * Returns TRUE if the specified task name is valid, or FALSE otherwise. + * * @param string $taskName + * * @return bool */ protected static function validateTaskName($taskName) @@ -221,24 +213,23 @@ protected static function validateTaskName($taskName) } /** - * Sets the name of the task, the name that's used to invoke it through a CLI + * Sets the name of the task, the name that's used to invoke it through a CLI. * * @param string $taskName + * * @throws InvalidArgumentException If the task name is invalid */ protected function setTaskName($taskName) { - if (! self::validateTaskName($taskName)) { - throw new InvalidArgumentException( - sprintf('The task name "%s", in %s, is invalid', $taskName, get_class($this)) - ); + if (!self::validateTaskName($taskName)) { + throw new InvalidArgumentException(sprintf('The task name "%s", in %s, is invalid', $taskName, get_class($this))); } $this->taskName = $taskName; } /** - * getTaskName + * getTaskName. * * @return string $taskName */ @@ -248,7 +239,7 @@ public function getTaskName() } /** - * getDescription + * getDescription. * * @return string $description */ @@ -258,7 +249,7 @@ public function getDescription() } /** - * getRequiredArguments + * getRequiredArguments. * * @return array $requiredArguments */ @@ -268,7 +259,7 @@ public function getRequiredArguments() } /** - * getOptionalArguments + * getOptionalArguments. * * @return array $optionalArguments */ @@ -278,7 +269,7 @@ public function getOptionalArguments() } /** - * getRequiredArgumentsDescriptions + * getRequiredArgumentsDescriptions. * * @return array $requiredArgumentsDescriptions */ @@ -288,7 +279,7 @@ public function getRequiredArgumentsDescriptions() } /** - * getOptionalArgumentsDescriptions + * getOptionalArgumentsDescriptions. * * @return array $optionalArgumentsDescriptions */ @@ -296,4 +287,4 @@ public function getOptionalArgumentsDescriptions() { return $this->optionalArguments; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/BuildAll.php b/lib/Doctrine/Task/BuildAll.php index 07d07e216..1219c4596 100644 --- a/lib/Doctrine/Task/BuildAll.php +++ b/lib/Doctrine/Task/BuildAll.php @@ -20,47 +20,50 @@ */ /** - * Doctrine_Task_BuildAll + * Doctrine_Task_BuildAll. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_BuildAll extends Doctrine_Task { - public $description = 'Calls generate-models-from-yaml, create-db, and create-tables', - $requiredArguments = array(), - $optionalArguments = array(); - - protected $models, - $createDb, - $tables; - + public $description = 'Calls generate-models-from-yaml, create-db, and create-tables'; + public $requiredArguments = array(); + public $optionalArguments = array(); + + protected $models; + + protected $createDb; + + protected $tables; + public function __construct($dispatcher = null) { parent::__construct($dispatcher); - + $this->models = new Doctrine_Task_GenerateModelsYaml($this->dispatcher); $this->createDb = new Doctrine_Task_CreateDb($this->dispatcher); $this->tables = new Doctrine_Task_CreateTables($this->dispatcher); - + $this->requiredArguments = array_merge($this->requiredArguments, $this->models->requiredArguments, $this->createDb->requiredArguments, $this->tables->requiredArguments); $this->optionalArguments = array_merge($this->optionalArguments, $this->models->optionalArguments, $this->createDb->optionalArguments, $this->tables->optionalArguments); } - + public function execute() { $this->models->setArguments($this->getArguments()); $this->models->execute(); - + $this->createDb->setArguments($this->getArguments()); $this->createDb->execute(); - + $this->tables->setArguments($this->getArguments()); $this->tables->execute(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/BuildAllLoad.php b/lib/Doctrine/Task/BuildAllLoad.php index 90e685a01..b9c6c9c24 100644 --- a/lib/Doctrine/Task/BuildAllLoad.php +++ b/lib/Doctrine/Task/BuildAllLoad.php @@ -20,42 +20,43 @@ */ /** - * Doctrine_Task_BuildAllLoad + * Doctrine_Task_BuildAllLoad. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_BuildAllLoad extends Doctrine_Task { - public $description = 'Calls build-all, and load-data', - $requiredArguments = array(), - $optionalArguments = array(); + public $description = 'Calls build-all, and load-data'; + public $requiredArguments = array(); + public $optionalArguments = array(); + + protected $buildAll; + protected $loadData; - protected $buildAll, - $loadData; - public function __construct($dispatcher = null) { parent::__construct($dispatcher); $this->buildAll = new Doctrine_Task_BuildAll($this->dispatcher); $this->loadData = new Doctrine_Task_LoadData($this->dispatcher); - + $this->requiredArguments = array_merge($this->requiredArguments, $this->buildAll->requiredArguments, $this->loadData->requiredArguments); $this->optionalArguments = array_merge($this->optionalArguments, $this->buildAll->optionalArguments, $this->loadData->optionalArguments); } - + public function execute() { $this->buildAll->setArguments($this->getArguments()); $this->buildAll->execute(); - + $this->loadData->setArguments($this->getArguments()); $this->loadData->execute(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/BuildAllReload.php b/lib/Doctrine/Task/BuildAllReload.php index 1cd3c1aba..2a1c3b769 100644 --- a/lib/Doctrine/Task/BuildAllReload.php +++ b/lib/Doctrine/Task/BuildAllReload.php @@ -20,42 +20,43 @@ */ /** - * Doctrine_Task_BuildAllReload + * Doctrine_Task_BuildAllReload. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_BuildAllReload extends Doctrine_Task { - public $description = 'Calls rebuild-db and load-data', - $requiredArguments = array(), - $optionalArguments = array(); + public $description = 'Calls rebuild-db and load-data'; + public $requiredArguments = array(); + public $optionalArguments = array(); + + protected $rebuildDb; + protected $loadData; - protected $rebuildDb, - $loadData; - public function __construct($dispatcher = null) { parent::__construct($dispatcher); $this->rebuildDb = new Doctrine_Task_RebuildDb($this->dispatcher); $this->loadData = new Doctrine_Task_LoadData($this->dispatcher); - + $this->requiredArguments = array_merge($this->requiredArguments, $this->rebuildDb->requiredArguments, $this->loadData->requiredArguments); $this->optionalArguments = array_merge($this->optionalArguments, $this->rebuildDb->optionalArguments, $this->loadData->optionalArguments); } - + public function execute() { $this->rebuildDb->setArguments($this->getArguments()); $this->rebuildDb->execute(); - + $this->loadData->setArguments($this->getArguments()); $this->loadData->execute(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/Compile.php b/lib/Doctrine/Task/Compile.php index d958d9d7d..d75a56bff 100644 --- a/lib/Doctrine/Task/Compile.php +++ b/lib/Doctrine/Task/Compile.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Task_Compile + * Doctrine_Task_Compile. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_Compile extends Doctrine_Task { - public $description = 'Compile doctrine classes in to one single php file', - $requiredArguments = array(), - $optionalArguments = array('drivers' => 'Specify list of drivers you wish to compile. Ex: mysql|mssql|sqlite', - 'compiled_path' => 'The path where you want to write the compiled doctrine libs.'); - + public $description = 'Compile doctrine classes in to one single php file'; + public $requiredArguments = array(); + public $optionalArguments = array('drivers' => 'Specify list of drivers you wish to compile. Ex: mysql|mssql|sqlite', + 'compiled_path' => 'The path where you want to write the compiled doctrine libs.'); + public function execute() { $compiledPath = Doctrine_Core::compile($this->getArgument('compiled_path'), $this->getArgument('drivers', array())); - - $this->notify('Compiled Doctrine successfully to: ' . $compiledPath); + + $this->notify('Compiled Doctrine successfully to: '.$compiledPath); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/CreateDb.php b/lib/Doctrine/Task/CreateDb.php index 475f04051..9ec74ef32 100644 --- a/lib/Doctrine/Task/CreateDb.php +++ b/lib/Doctrine/Task/CreateDb.php @@ -20,31 +20,32 @@ */ /** - * Doctrine_Task_CreateDb + * Doctrine_Task_CreateDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_CreateDb extends Doctrine_Task { - public $description = 'Create all databases for your connections. If the database already exists, nothing happens.', - $optionalArguments = array(); - + public $description = 'Create all databases for your connections. If the database already exists, nothing happens.'; + public $optionalArguments = array(); + public function execute() { $manager = Doctrine_Manager::getInstance(); foreach ($manager as $name => $connection) { try { $connection->createDatabase(); - $this->notify("Successfully created database for connection named '" . $name . "'"); + $this->notify("Successfully created database for connection named '".$name."'"); } catch (Exception $e) { $this->notify($e->getMessage()); } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/CreateTables.php b/lib/Doctrine/Task/CreateTables.php index 649489c24..52adce9cf 100644 --- a/lib/Doctrine/Task/CreateTables.php +++ b/lib/Doctrine/Task/CreateTables.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_Task_CreateTables + * Doctrine_Task_CreateTables. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_CreateTables extends Doctrine_Task { - public $description = 'Create tables for all existing database connections. If table exists nothing happens.', - $requiredArguments = array('models_path' => 'Specify path to your models directory.'), - $optionalArguments = array(); - + public $description = 'Create tables for all existing database connections. If table exists nothing happens.'; + public $requiredArguments = array('models_path' => 'Specify path to your models directory.'); + public $optionalArguments = array(); + public function execute() { Doctrine_Core::createTablesFromModels($this->getArgument('models_path')); - + $this->notify('Created tables successfully'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/Dql.php b/lib/Doctrine/Task/Dql.php index b85c70df0..71e463521 100644 --- a/lib/Doctrine/Task/Dql.php +++ b/lib/Doctrine/Task/Dql.php @@ -20,22 +20,23 @@ */ /** - * Doctrine_Task_Dql + * Doctrine_Task_Dql. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_Dql extends Doctrine_Task { - public $description = 'Execute dql query and display the results', - $requiredArguments = array('models_path' => 'Specify path to your Doctrine_Record definitions.', - 'dql_query' => 'Specify the complete dql query to execute.'), - $optionalArguments = array('params' => 'Comma separated list of the params to replace the ? tokens in the dql'); + public $description = 'Execute dql query and display the results'; + public $requiredArguments = array('models_path' => 'Specify path to your Doctrine_Record definitions.', + 'dql_query' => 'Specify the complete dql query to execute.'); + public $optionalArguments = array('params' => 'Comma separated list of the params to replace the ? tokens in the dql'); public function execute() { @@ -46,9 +47,9 @@ public function execute() $query = Doctrine_Query::create(); $params = $this->getArgument('params'); - $params = $params ? explode(',', $params):array(); + $params = $params ? explode(',', $params) : array(); - $this->notify('executing: "' . $dql . '" (' . implode(', ', $params) . ')'); + $this->notify('executing: "'.$dql.'" ('.implode(', ', $params).')'); $results = $query->query($dql, $params, Doctrine_Core::HYDRATE_ARRAY); @@ -70,4 +71,4 @@ protected function _printResults($array) } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/DropDb.php b/lib/Doctrine/Task/DropDb.php index c2c07adc1..d9997d524 100644 --- a/lib/Doctrine/Task/DropDb.php +++ b/lib/Doctrine/Task/DropDb.php @@ -20,28 +20,29 @@ */ /** - * Doctrine_Task_DropDb + * Doctrine_Task_DropDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_DropDb extends Doctrine_Task { - public $description = 'Drop database for all existing connections', - $requiredArguments = array(), - $optionalArguments = array('force' => 'Whether or not to force the drop database task'); + public $description = 'Drop database for all existing connections'; + public $requiredArguments = array(); + public $optionalArguments = array('force' => 'Whether or not to force the drop database task'); public function execute() { - if ( ! $this->getArgument('force')) { + if (!$this->getArgument('force')) { $answer = $this->ask('Are you sure you wish to drop your databases? (y/n)'); - if ($answer != 'y') { + if ('y' != $answer) { $this->notify('Successfully cancelled'); return; @@ -52,10 +53,10 @@ public function execute() foreach ($manager as $name => $connection) { try { $connection->dropDatabase(); - $this->notify("Successfully dropped database for connection named '" . $name . "'"); + $this->notify("Successfully dropped database for connection named '".$name."'"); } catch (Exception $e) { $this->notify($e->getMessage()); } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/DumpData.php b/lib/Doctrine/Task/DumpData.php index 7b6add9f7..45fb11d66 100644 --- a/lib/Doctrine/Task/DumpData.php +++ b/lib/Doctrine/Task/DumpData.php @@ -20,29 +20,30 @@ */ /** - * Doctrine_Task_DumpData + * Doctrine_Task_DumpData. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_DumpData extends Doctrine_Task { - public $description = 'Dump data to a yaml data fixture file.', - $requiredArguments = array('data_fixtures_path' => 'Specify path to write the yaml data fixtures file to.', - 'models_path' => 'Specify path to your Doctrine_Record definitions.'), - $optionalArguments = array(); + public $description = 'Dump data to a yaml data fixture file.'; + public $requiredArguments = array('data_fixtures_path' => 'Specify path to write the yaml data fixtures file to.', + 'models_path' => 'Specify path to your Doctrine_Record definitions.'); + public $optionalArguments = array(); public function execute() { - $models = Doctrine_Core::loadModels($this->getArgument('models_path')); + $models = Doctrine_Core::loadModels($this->getArgument('models_path')); - if (empty($models)) { - throw new Doctrine_Task_Exception('No models were loaded'); + if (empty($models)) { + throw new Doctrine_Task_Exception('No models were loaded'); } $path = $this->getArgument('data_fixtures_path'); @@ -51,7 +52,7 @@ public function execute() $path = $path[0]; } - if ( ! empty($path)) { + if (!empty($path)) { Doctrine_Core::dumpData($path); $this->notify(sprintf('Dumped data successfully to: %s', $path)); @@ -59,4 +60,4 @@ public function execute() throw new Doctrine_Task_Exception('Unable to find data fixtures path.'); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/Exception.php b/lib/Doctrine/Task/Exception.php index a04890f85..cc315be4e 100644 --- a/lib/Doctrine/Task/Exception.php +++ b/lib/Doctrine/Task/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Task_Exception + * Doctrine_Task_Exception. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Task/GenerateMigration.php b/lib/Doctrine/Task/GenerateMigration.php index 40be329d6..c720d5f76 100644 --- a/lib/Doctrine/Task/GenerateMigration.php +++ b/lib/Doctrine/Task/GenerateMigration.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Task_GenerateMigration + * Doctrine_Task_GenerateMigration. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateMigration extends Doctrine_Task { - public $description = 'Generate new migration class definition', - $requiredArguments = array('class_name' => 'Name of the migration class to generate', - 'migrations_path' => 'Specify the complete path to your migration classes folder.'), - $optionalArguments = array(); - + public $description = 'Generate new migration class definition'; + public $requiredArguments = array('class_name' => 'Name of the migration class to generate', + 'migrations_path' => 'Specify the complete path to your migration classes folder.'); + public $optionalArguments = array(); + public function execute() { Doctrine_Core::generateMigrationClass($this->getArgument('class_name'), $this->getArgument('migrations_path')); - + $this->notify(sprintf('Generated migration class: %s successfully to %s', $this->getArgument('class_name'), $this->getArgument('migrations_path'))); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateMigrationsDb.php b/lib/Doctrine/Task/GenerateMigrationsDb.php index 98ca86173..982f78948 100644 --- a/lib/Doctrine/Task/GenerateMigrationsDb.php +++ b/lib/Doctrine/Task/GenerateMigrationsDb.php @@ -20,22 +20,23 @@ */ /** - * Doctrine_Task_GenerateMigrationsDb + * Doctrine_Task_GenerateMigrationsDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateMigrationsDb extends Doctrine_Task { - public $description = 'Generate migration classes for an existing database', - $requiredArguments = array('migrations_path' => 'Specify the complete path to your migration classes folder.'), - $optionalArguments = array(); - + public $description = 'Generate migration classes for an existing database'; + public $requiredArguments = array('migrations_path' => 'Specify the complete path to your migration classes folder.'); + public $optionalArguments = array(); + public function execute() { try { @@ -43,7 +44,7 @@ public function execute() $yamlSchemaPath = $this->getArgument('yaml_schema_path'); $migration = new Doctrine_Migration($migrationsPath); $result1 = false; - if ( ! count($migration->getMigrationClasses())) { + if (!count($migration->getMigrationClasses())) { $result1 = Doctrine_Core::generateMigrationsFromDb($migrationsPath); } $connections = array(); @@ -52,14 +53,13 @@ public function execute() } $changes = Doctrine_Core::generateMigrationsFromDiff($migrationsPath, $connections, $yamlSchemaPath); $numChanges = count($changes, true) - count($changes); - $result = ($result1 || $numChanges) ? true:false; + $result = ($result1 || $numChanges) ? true : false; } catch (Exception $e) { $result = false; } - if ( ! $result) { + if (!$result) { throw new Doctrine_Task_Exception('Could not generate migration classes from database'); - } else { - $this->notify('Generated migration classes successfully from database'); } + $this->notify('Generated migration classes successfully from database'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateMigrationsDiff.php b/lib/Doctrine/Task/GenerateMigrationsDiff.php index ac92aa685..083fe649e 100644 --- a/lib/Doctrine/Task/GenerateMigrationsDiff.php +++ b/lib/Doctrine/Task/GenerateMigrationsDiff.php @@ -20,25 +20,26 @@ */ /** - * Doctrine_Task_GenerateMigrationsDiff + * Doctrine_Task_GenerateMigrationsDiff. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateMigrationsDiff extends Doctrine_Task { - public $description = 'Generate migration classes from a generated difference between your models and yaml schema files', - $requiredArguments = array('migrations_path' => 'Specify the path to your migration classes folder.', - 'yaml_schema_path' => 'Specify the path to your yaml schema files folder.'), - $optionalArguments = array('models_path' => 'Specify the path to your doctrine models folder.'); + public $description = 'Generate migration classes from a generated difference between your models and yaml schema files'; + public $requiredArguments = array('migrations_path' => 'Specify the path to your migration classes folder.', + 'yaml_schema_path' => 'Specify the path to your yaml schema files folder.'); + public $optionalArguments = array('models_path' => 'Specify the path to your doctrine models folder.'); public function execute() - { + { $migrationsPath = $this->getArgument('migrations_path'); $modelsPath = $this->getArgument('models_path'); $yamlSchemaPath = $this->getArgument('yaml_schema_path'); @@ -49,10 +50,9 @@ public function execute() $numChanges = count($changes, true) - count($changes); - if ( ! $numChanges) { + if (!$numChanges) { throw new Doctrine_Task_Exception('Could not generate migration classes from difference'); - } else { - $this->notify('Generated migration classes successfully from difference'); } + $this->notify('Generated migration classes successfully from difference'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateMigrationsModels.php b/lib/Doctrine/Task/GenerateMigrationsModels.php index 7a462356c..8ff14cf05 100644 --- a/lib/Doctrine/Task/GenerateMigrationsModels.php +++ b/lib/Doctrine/Task/GenerateMigrationsModels.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Task_GenerateMigrationsModels + * Doctrine_Task_GenerateMigrationsModels. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateMigrationsModels extends Doctrine_Task { - public $description = 'Generate migration classes for an existing set of models', - $requiredArguments = array('migrations_path' => 'Specify the path to your migration classes folder.', - 'models_path' => 'Specify the path to your doctrine models folder.'), - $optionalArguments = array(); - + public $description = 'Generate migration classes for an existing set of models'; + public $requiredArguments = array('migrations_path' => 'Specify the path to your migration classes folder.', + 'models_path' => 'Specify the path to your doctrine models folder.'); + public $optionalArguments = array(); + public function execute() - { + { Doctrine_Core::generateMigrationsFromModels($this->getArgument('migrations_path'), $this->getArgument('models_path')); - + $this->notify('Generated migration classes successfully from models'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateModelsDb.php b/lib/Doctrine/Task/GenerateModelsDb.php index af59c4f35..eb545b019 100644 --- a/lib/Doctrine/Task/GenerateModelsDb.php +++ b/lib/Doctrine/Task/GenerateModelsDb.php @@ -20,22 +20,23 @@ */ /** - * Doctrine_Task_GenerateModelsDb + * Doctrine_Task_GenerateModelsDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateModelsDb extends Doctrine_Task { - public $description = 'Generates your Doctrine_Record definitions from your existing database connections.', - $requiredArguments = array('models_path' => 'Specify path to your Doctrine_Record definitions.'), - $optionalArguments = array('connection' => 'Optionally specify a single connection to generate the models for.'); - + public $description = 'Generates your Doctrine_Record definitions from your existing database connections.'; + public $requiredArguments = array('models_path' => 'Specify path to your Doctrine_Record definitions.'); + public $optionalArguments = array('connection' => 'Optionally specify a single connection to generate the models for.'); + public function execute() { $configs = $this->dispatcher->getConfig(); diff --git a/lib/Doctrine/Task/GenerateModelsYaml.php b/lib/Doctrine/Task/GenerateModelsYaml.php index 2bd82b1c1..7411c3f97 100644 --- a/lib/Doctrine/Task/GenerateModelsYaml.php +++ b/lib/Doctrine/Task/GenerateModelsYaml.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Task_GenerateModelsYaml + * Doctrine_Task_GenerateModelsYaml. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateModelsYaml extends Doctrine_Task { - public $description = 'Generates your Doctrine_Record definitions from a Yaml schema file', - $requiredArguments = array('yaml_schema_path' => 'Specify the complete directory path to your yaml schema files.', - 'models_path' => 'Specify complete path to your Doctrine_Record definitions.'), - $optionalArguments = array('generate_models_options' => 'Array of options for generating models'); - + public $description = 'Generates your Doctrine_Record definitions from a Yaml schema file'; + public $requiredArguments = array('yaml_schema_path' => 'Specify the complete directory path to your yaml schema files.', + 'models_path' => 'Specify complete path to your Doctrine_Record definitions.'); + public $optionalArguments = array('generate_models_options' => 'Array of options for generating models'); + public function execute() { Doctrine_Core::generateModelsFromYaml($this->getArgument('yaml_schema_path'), $this->getArgument('models_path'), $this->getArgument('generate_models_options', array())); - + $this->notify('Generated models successfully from YAML schema'); } } diff --git a/lib/Doctrine/Task/GenerateSql.php b/lib/Doctrine/Task/GenerateSql.php index be2a002d4..ce0068d77 100644 --- a/lib/Doctrine/Task/GenerateSql.php +++ b/lib/Doctrine/Task/GenerateSql.php @@ -20,37 +20,38 @@ */ /** - * Doctrine_Task_GenerateSql + * Doctrine_Task_GenerateSql. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateSql extends Doctrine_Task { - public $description = 'Generate sql for all existing database connections.', - $requiredArguments = array('models_path' => 'Specify complete path to your Doctrine_Record definitions.', - 'sql_path' => 'Path to write the generated sql.'), - $optionalArguments = array(); - + public $description = 'Generate sql for all existing database connections.'; + public $requiredArguments = array('models_path' => 'Specify complete path to your Doctrine_Record definitions.', + 'sql_path' => 'Path to write the generated sql.'); + public $optionalArguments = array(); + public function execute() { if (is_dir($this->getArgument('sql_path'))) { - $path = $this->getArgument('sql_path') . DIRECTORY_SEPARATOR . 'schema.sql'; - } else if (is_file($this->getArgument('sql_path'))) { + $path = $this->getArgument('sql_path').DIRECTORY_SEPARATOR.'schema.sql'; + } elseif (is_file($this->getArgument('sql_path'))) { $path = $this->getArgument('sql_path'); } else { throw new Doctrine_Task_Exception('Invalid sql path.'); } - + $sql = Doctrine_Core::generateSqlFromModels($this->getArgument('models_path')); - + file_put_contents($path, $sql); - + $this->notify('Generated SQL successfully for models'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateYamlDb.php b/lib/Doctrine/Task/GenerateYamlDb.php index 2da50293a..92248c85f 100644 --- a/lib/Doctrine/Task/GenerateYamlDb.php +++ b/lib/Doctrine/Task/GenerateYamlDb.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_Task_GenerateYamlDb + * Doctrine_Task_GenerateYamlDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateYamlDb extends Doctrine_Task { - public $description = 'Generates a Yaml schema file from an existing database', - $requiredArguments = array('yaml_schema_path' => 'Specify the path to your yaml schema files.'), - $optionalArguments = array(); - + public $description = 'Generates a Yaml schema file from an existing database'; + public $requiredArguments = array('yaml_schema_path' => 'Specify the path to your yaml schema files.'); + public $optionalArguments = array(); + public function execute() { Doctrine_Core::generateYamlFromDb($this->getArgument('yaml_schema_path')); - + $this->notify('Generate YAML schema successfully from database'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateYamlModels.php b/lib/Doctrine/Task/GenerateYamlModels.php index a25cfb14b..d287e641d 100644 --- a/lib/Doctrine/Task/GenerateYamlModels.php +++ b/lib/Doctrine/Task/GenerateYamlModels.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_Task_GenerateFromModels + * Doctrine_Task_GenerateFromModels. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateYamlModels extends Doctrine_Task { - public $description = 'Generates a Yaml schema file from existing Doctrine_Record definitions', - $requiredArguments = array('yaml_schema_path' => 'Specify the complete directory path to your yaml schema files.'), - $optionalArguments = array('models_path' => 'Specify complete path to your Doctrine_Record definitions.'); + public $description = 'Generates a Yaml schema file from existing Doctrine_Record definitions'; + public $requiredArguments = array('yaml_schema_path' => 'Specify the complete directory path to your yaml schema files.'); + public $optionalArguments = array('models_path' => 'Specify complete path to your Doctrine_Record definitions.'); public function execute() { Doctrine_Core::generateYamlFromModels($this->getArgument('yaml_schema_path'), $this->getArgument('models_path')); - + $this->notify('Generated YAML schema successfully from models'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/LoadData.php b/lib/Doctrine/Task/LoadData.php index 32e31efa1..7f2f5264a 100644 --- a/lib/Doctrine/Task/LoadData.php +++ b/lib/Doctrine/Task/LoadData.php @@ -20,23 +20,24 @@ */ /** - * Doctrine_Task_LoadData + * Doctrine_Task_LoadData. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_LoadData extends Doctrine_Task { - public $description = 'Load data from a yaml data fixture file.', - $requiredArguments = array('data_fixtures_path' => 'Specify the complete path to load the yaml data fixtures files from.', - 'models_path' => 'Specify path to your Doctrine_Record definitions.'), - $optionalArguments = array('append' => 'Whether or not to append the data', - 'charset' => 'Specify the charset to use for yaml laod'); + public $description = 'Load data from a yaml data fixture file.'; + public $requiredArguments = array('data_fixtures_path' => 'Specify the complete path to load the yaml data fixtures files from.', + 'models_path' => 'Specify path to your Doctrine_Record definitions.'); + public $optionalArguments = array('append' => 'Whether or not to append the data', + 'charset' => 'Specify the charset to use for yaml laod'); public function execute() { diff --git a/lib/Doctrine/Task/Migrate.php b/lib/Doctrine/Task/Migrate.php index 18aaa284e..c23e8773f 100644 --- a/lib/Doctrine/Task/Migrate.php +++ b/lib/Doctrine/Task/Migrate.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_Task_Migrate + * Doctrine_Task_Migrate. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_Migrate extends Doctrine_Task { - public $description = 'Migrate database to latest version or the specified version', - $requiredArguments = array('migrations_path' => 'Specify path to your migrations directory.'), - $optionalArguments = array('version' => 'Version to migrate to. If you do not specify, the db will be migrated from the current version to the latest.'); - + public $description = 'Migrate database to latest version or the specified version'; + public $requiredArguments = array('migrations_path' => 'Specify path to your migrations directory.'); + public $optionalArguments = array('version' => 'Version to migrate to. If you do not specify, the db will be migrated from the current version to the latest.'); + public function execute() { $version = Doctrine_Core::migrate($this->getArgument('migrations_path'), $this->getArgument('version')); - - $this->notify('migrated successfully to version #' . $version); + + $this->notify('migrated successfully to version #'.$version); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/RebuildDb.php b/lib/Doctrine/Task/RebuildDb.php index ad9623f6d..085dd723d 100644 --- a/lib/Doctrine/Task/RebuildDb.php +++ b/lib/Doctrine/Task/RebuildDb.php @@ -20,30 +20,31 @@ */ /** - * Doctrine_Task_RebuildDb + * Doctrine_Task_RebuildDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_RebuildDb extends Doctrine_Task { - public $description = 'Drops and re-creates databases', - $requiredArguments = array(), - $optionalArguments = array(); + public $description = 'Drops and re-creates databases'; + public $requiredArguments = array(); + public $optionalArguments = array(); + + protected $dropDb; + protected $createDb; + protected $createTables; - protected $dropDb, - $createDb, - $createTables; - public function __construct($dispatcher = null) { parent::__construct($dispatcher); - + $this->dropDb = new Doctrine_Task_DropDb($this->dispatcher); $this->createDb = new Doctrine_Task_CreateDb($this->dispatcher); $this->createTables = new Doctrine_Task_CreateTables($this->dispatcher); @@ -63,4 +64,4 @@ public function execute() $this->createTables->setArguments($this->getArguments()); $this->createTables->execute(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template.php b/lib/Doctrine/Template.php index f42caf957..2b03d97fb 100644 --- a/lib/Doctrine/Template.php +++ b/lib/Doctrine/Template.php @@ -21,38 +21,36 @@ /** * Base abstract class for defining templates which are the base of all behaviors that can be attached - * to your Doctrine models + * to your Doctrine models. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ abstract class Doctrine_Template extends Doctrine_Record_Abstract { /** - * @var Doctrine_Record $_invoker the record that invoked the last delegated call + * @var Doctrine_Record the record that invoked the last delegated call */ protected $_invoker; /** - * @var Doctrine_Record_Generator $_plugin + * @var Doctrine_Record_Generator */ protected $_plugin; /** - * @var array $_options Template options + * @var array Template options */ protected $_options = array(); /** - * __construct - * - * @param string $array - * @return void + * __construct. */ public function __construct(array $options = array()) { @@ -60,9 +58,9 @@ public function __construct(array $options = array()) } /** - * Set the table object that this Template belongs to + * Set the table object that this Template belongs to. * - * @var Doctrine_Table $table the table object this Template belongs to + * @var Doctrine_Table the table object this Template belongs to */ public function setTable(Doctrine_Table $table) { @@ -70,9 +68,9 @@ public function setTable(Doctrine_Table $table) } /** - * returns the associated table object + * returns the associated table object. * - * @return Doctrine_Table the associated table object + * @return Doctrine_Table the associated table object */ public function getTable() { @@ -80,10 +78,11 @@ public function getTable() } /** - * sets the last used invoker + * sets the last used invoker. + * + * @param Doctrine_Record $invoker the record that invoked the last delegated call * - * @param Doctrine_Record $invoker the record that invoked the last delegated call - * @return Doctrine_Template this object + * @return Doctrine_Template this object */ public function setInvoker(Doctrine_Record_Abstract $invoker) { @@ -91,9 +90,9 @@ public function setInvoker(Doctrine_Record_Abstract $invoker) } /** - * returns the last used invoker + * returns the last used invoker. * - * @return Doctrine_Record the record that invoked the last delegated call + * @return Doctrine_Record the record that invoked the last delegated call */ public function getInvoker() { @@ -101,22 +100,19 @@ public function getInvoker() } /** - * Adds a plugin as a child to this plugin - * - * @param Doctrine_Template $template + * Adds a plugin as a child to this plugin. + * * @return Doctrine_Template. Chainable. */ public function addChild(Doctrine_Template $template) { $this->_plugin->addChild($template); - + return $this; } /** - * Get plugin instance - * - * @return void + * Get plugin instance. */ public function getPlugin() { @@ -124,9 +120,9 @@ public function getPlugin() } /** - * Check if this template has a generator plugin + * Check if this template has a generator plugin. * - * @return boolean + * @return bool */ public function hasPlugin() { @@ -135,9 +131,9 @@ public function hasPlugin() /** * getOptions - * returns all options of this template and the associated values + * returns all options of this template and the associated values. * - * @return array all options and their values + * @return array all options and their values */ public function getOptions() { @@ -146,37 +142,32 @@ public function getOptions() /** * getOption - * returns the value of given option + * returns the value of given option. + * + * @param string $name the name of the option + * @param mixed $default default value if option is not found * - * @param string $name the name of the option - * @param mixed $default default value if option is not found - * @return mixed the value of given option + * @return mixed the value of given option */ public function getOption($name, $default = null) { if (isset($this->_options[$name])) { return $this->_options[$name]; } + return $default; } /** - * get - * - * @param mixed $name - * @return void + * get. */ - public function get($name) + public function get($name) { throw new Doctrine_Exception("Templates doesn't support accessors."); } /** - * set - * - * @param mixed $name - * @param mixed $value - * @return void + * set. */ public function set($name, $value) { @@ -184,22 +175,16 @@ public function set($name, $value) } /** - * Blank method for template setup - * - * @return void + * Blank method for template setup. */ public function setUp() { - } /** - * Blank method for template table definition - * - * @return void + * Blank method for template table definition. */ public function setTableDefinition() { - } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Geographical.php b/lib/Doctrine/Template/Geographical.php index 9c99e817c..dc9429afa 100644 --- a/lib/Doctrine/Template/Geographical.php +++ b/lib/Doctrine/Template/Geographical.php @@ -20,38 +20,37 @@ */ /** - * Easily add longitude and latitude columns to your records and use inherited functionality for - * calculating distances + * Easily add longitude and latitude columns to your records and use inherited functionality for + * calculating distances. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Template_Geographical extends Doctrine_Template { /** - * Array of geographical options + * Array of geographical options. * * @var string */ - protected $_options = array('latitude' => array('name' => 'latitude', - 'type' => 'decimal', - 'size' => 10, - 'options' => array('scale' => 6)), - 'longitude' => array('name' => 'longitude', - 'type' => 'decimal', - 'size' => 10, - 'options' => array('scale' => 6))); + protected $_options = array('latitude' => array('name' => 'latitude', + 'type' => 'decimal', + 'size' => 10, + 'options' => array('scale' => 6)), + 'longitude' => array('name' => 'longitude', + 'type' => 'decimal', + 'size' => 10, + 'options' => array('scale' => 6))); /** - * Set table definition for Geographical behavior - * - * @return void + * Set table definition for Geographical behavior. */ public function setTableDefinition() { @@ -60,8 +59,8 @@ public function setTableDefinition() } /** - * Initiate and get a distance query with the select parts for the number of kilometers and miles - * between this record and other zipcode records in the database + * Initiate and get a distance query with the select parts for the number of kilometers and miles + * between this record and other zipcode records in the database. * * @return Doctrine_Query $query */ @@ -74,9 +73,9 @@ public function getDistanceQuery() $latName = $this->_options['latitude']['name']; $longName = $this->_options['longitude']['name']; - $query->addSelect($rootAlias . '.*'); + $query->addSelect($rootAlias.'.*'); - $sql = "((ACOS(SIN(%s * PI() / 180) * SIN(" . $rootAlias . "." . $latName . " * PI() / 180) + COS(%s * PI() / 180) * COS(" . $rootAlias . "." . $latName . " * PI() / 180) * COS((%s - " . $rootAlias . "." . $longName . ") * PI() / 180)) * 180 / PI()) * 60 * %s) as %s"; + $sql = '((ACOS(SIN(%s * PI() / 180) * SIN('.$rootAlias.'.'.$latName.' * PI() / 180) + COS(%s * PI() / 180) * COS('.$rootAlias.'.'.$latName.' * PI() / 180) * COS((%s - '.$rootAlias.'.'.$longName.') * PI() / 180)) * 180 / PI()) * 60 * %s) as %s'; $milesSql = sprintf($sql, $invoker->get($latName), $invoker->get($latName), $invoker->get($longName), '1.1515', 'miles'); $query->addSelect($milesSql); @@ -88,20 +87,20 @@ public function getDistanceQuery() } /** - * Get distance between this record and another + * Get distance between this record and another. * - * @param string $Doctrine_Record - * @param string $kilometers - * @return integer + * @param string $kilometers + * + * @return int */ public function getDistance(Doctrine_Record $record, $kilometers = false) { $query = $this->getDistanceQuery($kilometers); - + $conditions = array(); $values = array(); foreach ((array) $record->getTable()->getIdentifier() as $id) { - $conditions[] = $query->getRootAlias() . '.' . $id . ' = ?'; + $conditions[] = $query->getRootAlias().'.'.$id.' = ?'; $values[] = $record->get($id); } @@ -112,11 +111,11 @@ public function getDistance(Doctrine_Record $record, $kilometers = false) $query->limit(1); $result = $query->execute()->getFirst(); - + if (isset($result['kilometers']) && $result['miles']) { - return $kilometers ? $result->get('kilometers'):$result->get('miles'); - } else { - return 0; + return $kilometers ? $result->get('kilometers') : $result->get('miles'); } + + return 0; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/I18n.php b/lib/Doctrine/Template/I18n.php index 808b4016c..1bd0b2a3f 100644 --- a/lib/Doctrine/Template/I18n.php +++ b/lib/Doctrine/Template/I18n.php @@ -20,47 +20,41 @@ */ /** - * Add multilingual capabilities to your Doctrine models + * Add multilingual capabilities to your Doctrine models. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_I18n extends Doctrine_Template { /** - * __construct - * - * @param string $array - * @return void + * __construct. */ public function __construct(array $options = array()) { - parent::__construct($options); + parent::__construct($options); $this->_plugin = new Doctrine_I18n($this->_options); } /** - * Initialize the I18n plugin for the template - * - * @return void + * Initialize the I18n plugin for the template. */ public function setUp() { - $this->_plugin->initialize($this->_table); + $this->_plugin->initialize($this->_table); } /** - * Get the plugin instance for the I18n template - * - * @return void + * Get the plugin instance for the I18n template. */ public function getI18n() { return $this->_plugin; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Listener/Sluggable.php b/lib/Doctrine/Template/Listener/Sluggable.php index cc627a001..083da74f6 100644 --- a/lib/Doctrine/Template/Listener/Sluggable.php +++ b/lib/Doctrine/Template/Listener/Sluggable.php @@ -20,30 +20,28 @@ */ /** - * Easily create a slug for each record based on a specified set of fields + * Easily create a slug for each record based on a specified set of fields. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Listener_Sluggable extends Doctrine_Record_Listener { /** - * Array of sluggable options + * Array of sluggable options. * * @var string */ protected $_options = array(); /** - * __construct - * - * @param string $array - * @return void + * __construct. */ public function __construct(array $options) { @@ -51,27 +49,21 @@ public function __construct(array $options) } /** - * Set the slug value automatically when a record is inserted - * - * @param Doctrine_Event $event - * @return void + * Set the slug value automatically when a record is inserted. */ public function preInsert(Doctrine_Event $event) { $record = $event->getInvoker(); $name = $record->getTable()->getFieldName($this->_options['name']); - if ( ! $record->$name) { - $record->$name = $this->buildSlugFromFields($record); + if (!$record->{$name}) { + $record->{$name} = $this->buildSlugFromFields($record); } } /** * Set the slug value automatically when a record is updated if the options are configured - * to allow it - * - * @param Doctrine_Event $event - * @return void + * to allow it. */ public function preUpdate(Doctrine_Event $event) { @@ -79,32 +71,33 @@ public function preUpdate(Doctrine_Event $event) $record = $event->getInvoker(); $name = $record->getTable()->getFieldName($this->_options['name']); - if ( ! $record->$name || ( - false !== $this->_options['canUpdate'] && - ! array_key_exists($name, $record->getModified()) - )) { - $record->$name = $this->buildSlugFromFields($record); - } else if ( ! empty($record->$name) && - false !== $this->_options['canUpdate'] && - array_key_exists($name, $record->getModified() + if (!$record->{$name} || ( + false !== $this->_options['canUpdate'] + && !array_key_exists($name, $record->getModified()) )) { - $record->$name = $this->buildSlugFromSlugField($record); + $record->{$name} = $this->buildSlugFromFields($record); + } elseif (!empty($record->{$name}) + && false !== $this->_options['canUpdate'] + && array_key_exists($name, $record->getModified() + )) { + $record->{$name} = $this->buildSlugFromSlugField($record); } } } /** - * Generate the slug for a given Doctrine_Record based on the configured options + * Generate the slug for a given Doctrine_Record based on the configured options. * * @param Doctrine_Record $record + * * @return string $slug */ protected function buildSlugFromFields($record) { if (empty($this->_options['fields'])) { if (is_callable($this->_options['provider'])) { - $value = call_user_func($this->_options['provider'], $record); - } else if (method_exists($record, 'getUniqueSlug')) { + $value = call_user_func($this->_options['provider'], $record); + } elseif (method_exists($record, 'getUniqueSlug')) { $value = $record->getUniqueSlug($record); } else { $value = (string) $record; @@ -112,30 +105,31 @@ protected function buildSlugFromFields($record) } else { $value = ''; foreach ($this->_options['fields'] as $field) { - $value .= $record->$field . ' '; + $value .= $record->{$field}.' '; } $value = substr($value, 0, -1); } - if ($this->_options['unique'] === true) { - return $this->getUniqueSlug($record, $value); - } + if (true === $this->_options['unique']) { + return $this->getUniqueSlug($record, $value); + } return call_user_func_array($this->_options['builder'], array($value, $record)); } /** - * Generate the slug for a given Doctrine_Record slug field + * Generate the slug for a given Doctrine_Record slug field. * * @param Doctrine_Record $record + * * @return string $slug */ protected function buildSlugFromSlugField($record) { $name = $record->getTable()->getFieldName($this->_options['name']); - $value = $record->$name; + $value = $record->{$name}; - if ($this->_options['unique'] === true) { + if (true === $this->_options['unique']) { return $this->getUniqueSlug($record, $value); } @@ -144,52 +138,53 @@ protected function buildSlugFromSlugField($record) /** * Creates a unique slug for a given Doctrine_Record. This function enforces the uniqueness by - * incrementing the values with a postfix if the slug is not unique + * incrementing the values with a postfix if the slug is not unique. * * @param Doctrine_Record $record - * @param string $slugFromFields + * @param string $slugFromFields + * * @return string $slug */ public function getUniqueSlug($record, $slugFromFields) { /* fix for use with Column Aggregation Inheritance */ if ($record->getTable()->getOption('inheritanceMap')) { - $parentTable = $record->getTable()->getOption('parents'); - $i = 0; - // Be sure that you do not instanciate an abstract class; - $reflectionClass = new ReflectionClass($parentTable[$i]); - while ($reflectionClass->isAbstract()) { - $i++; + $parentTable = $record->getTable()->getOption('parents'); + $i = 0; + // Be sure that you do not instanciate an abstract class; $reflectionClass = new ReflectionClass($parentTable[$i]); - } - $table = Doctrine_Core::getTable($parentTable[$i]); + while ($reflectionClass->isAbstract()) { + ++$i; + $reflectionClass = new ReflectionClass($parentTable[$i]); + } + $table = Doctrine_Core::getTable($parentTable[$i]); } else { - $table = $record->getTable(); + $table = $record->getTable(); } $name = $table->getFieldName($this->_options['name']); - $proposal = call_user_func_array($this->_options['builder'], array($slugFromFields, $record)); + $proposal = call_user_func_array($this->_options['builder'], array($slugFromFields, $record)); $slug = $proposal; - $whereString = 'r.' . $name . ' LIKE ?'; + $whereString = 'r.'.$name.' LIKE ?'; $whereParams = array($proposal.'%'); if ($record->exists()) { $identifier = $record->identifier(); - $whereString .= ' AND r.' . implode(' != ? AND r.', $table->getIdentifierColumnNames()) . ' != ?'; + $whereString .= ' AND r.'.implode(' != ? AND r.', $table->getIdentifierColumnNames()).' != ?'; $whereParams = array_merge($whereParams, array_values($identifier)); } foreach ($this->_options['uniqueBy'] as $uniqueBy) { - if (is_null($record->$uniqueBy)) { + if (is_null($record->{$uniqueBy})) { $whereString .= ' AND r.'.$uniqueBy.' IS NULL'; } else { $whereString .= ' AND r.'.$uniqueBy.' = ?'; - $value = $record->$uniqueBy; + $value = $record->{$uniqueBy}; if ($value instanceof Doctrine_Record) { $value = current((array) $value->identifier()); } - $whereParams[] = $value; + $whereParams[] = $value; } } @@ -198,24 +193,25 @@ public function getUniqueSlug($record, $slugFromFields) $table->bindQueryPart('indexBy', null); $query = $table->createQuery('r') - ->select('r.' . $name) - ->where($whereString , $whereParams) - ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY); + ->select('r.'.$name) + ->where($whereString, $whereParams) + ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) + ; // We need to introspect SoftDelete to check if we are not disabling unique records too if ($table->hasTemplate('Doctrine_Template_SoftDelete')) { - $softDelete = $table->getTemplate('Doctrine_Template_SoftDelete'); + $softDelete = $table->getTemplate('Doctrine_Template_SoftDelete'); - // we have to consider both situations here - if ($softDelete->getOption('type') == 'boolean') { + // we have to consider both situations here + if ('boolean' == $softDelete->getOption('type')) { $conn = $query->getConnection(); $query->addWhere( - '(r.' . $softDelete->getOption('name') . ' = ' . $conn->convertBooleans(true) . - ' OR r.' . $softDelete->getOption('name') . ' = ' . $conn->convertBooleans(false) . ')' + '(r.'.$softDelete->getOption('name').' = '.$conn->convertBooleans(true). + ' OR r.'.$softDelete->getOption('name').' = '.$conn->convertBooleans(false).')' ); } else { - $query->addWhere('(r.' . $softDelete->getOption('name') . ' IS NOT NULL OR r.' . $softDelete->getOption('name') . ' IS NULL)'); + $query->addWhere('(r.'.$softDelete->getOption('name').' IS NOT NULL OR r.'.$softDelete->getOption('name').' IS NULL)'); } } @@ -233,7 +229,7 @@ public function getUniqueSlug($record, $slugFromFields) $i = 1; while (in_array(strtolower($slug), $similarSlugs)) { $slug = call_user_func_array($this->_options['builder'], array($proposal.'-'.$i, $record)); - $i++; + ++$i; } // If slug is longer then the column length then we need to trim it @@ -244,6 +240,6 @@ public function getUniqueSlug($record, $slugFromFields) $slug = $this->getUniqueSlug($record, $slug); } - return $slug; + return $slug; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Listener/SoftDelete.php b/lib/Doctrine/Template/Listener/SoftDelete.php index fda661deb..93f666b52 100644 --- a/lib/Doctrine/Template/Listener/SoftDelete.php +++ b/lib/Doctrine/Template/Listener/SoftDelete.php @@ -24,29 +24,29 @@ * sets a delete flag instead of actually deleting the record and all queries automatically * include a check for the deleted flag to exclude deleted records. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Template_Listener_SoftDelete extends Doctrine_Record_Listener { /** - * Array of SoftDelete options + * Array of SoftDelete options. * * @var string */ protected $_options = array(); /** - * __construct + * __construct. * - * @param string $options - * @return void + * @param string $options */ public function __construct(array $options) { @@ -54,10 +54,9 @@ public function __construct(array $options) } /** - * Set the hard delete flag so that it is really deleted + * Set the hard delete flag so that it is really deleted. * - * @param boolean $bool - * @return void + * @param bool $bool */ public function hardDelete($bool) { @@ -65,91 +64,79 @@ public function hardDelete($bool) } /** - * Skip the normal delete options so we can override it with our own - * - * @param Doctrine_Event $event - * @return void + * Skip the normal delete options so we can override it with our own. */ public function preDelete(Doctrine_Event $event) { $name = $this->_options['name']; $invoker = $event->getInvoker(); - - if ($this->_options['type'] == 'timestamp') { - $invoker->$name = date('Y-m-d H:i:s', time()); - } else if ($this->_options['type'] == 'boolean') { - $invoker->$name = true; + + if ('timestamp' == $this->_options['type']) { + $invoker->{$name} = date('Y-m-d H:i:s', time()); + } elseif ('boolean' == $this->_options['type']) { + $invoker->{$name} = true; } - if ( ! $this->_options['hardDelete']) { + if (!$this->_options['hardDelete']) { $event->skipOperation(); } } /** - * Implement postDelete() hook and set the deleted flag to true - * - * @param Doctrine_Event $event - * @return void + * Implement postDelete() hook and set the deleted flag to true. */ public function postDelete(Doctrine_Event $event) { - if ( ! $this->_options['hardDelete']) { + if (!$this->_options['hardDelete']) { $event->getInvoker()->save(); } } /** * Implement preDqlDelete() hook and modify a dql delete query so it updates the deleted flag - * instead of deleting the record - * - * @param Doctrine_Event $event - * @return void + * instead of deleting the record. */ public function preDqlDelete(Doctrine_Event $event) { $params = $event->getParams(); - $field = $params['alias'] . '.' . $this->_options['name']; + $field = $params['alias'].'.'.$this->_options['name']; $query = $event->getQuery(); - if ( ! $query->contains($field)) { - $query->from('')->update($params['component']['table']->getOption('name') . ' ' . $params['alias']); - - if ($this->_options['type'] == 'timestamp') { + if (!$query->contains($field)) { + $query->from('')->update($params['component']['table']->getOption('name').' '.$params['alias']); + + if ('timestamp' == $this->_options['type']) { $query->set($field, '?', date('Y-m-d H:i:s', time())); - $query->addWhere($field . ' IS NULL'); - } else if ($this->_options['type'] == 'boolean') { + $query->addWhere($field.' IS NULL'); + } elseif ('boolean' == $this->_options['type']) { $query->set($field, $query->getConnection()->convertBooleans(true)); $query->addWhere( - $field . ' = ' . $query->getConnection()->convertBooleans(false) + $field.' = '.$query->getConnection()->convertBooleans(false) ); } } } /** - * Implement preDqlSelect() hook and add the deleted flag to all queries for which this model + * Implement preDqlSelect() hook and add the deleted flag to all queries for which this model * is being used in. - * - * @param Doctrine_Event $event - * @return void */ public function preDqlSelect(Doctrine_Event $event) { $params = $event->getParams(); - $field = $params['alias'] . '.' . $this->_options['name']; + $field = $params['alias'].'.'.$this->_options['name']; $query = $event->getQuery(); // We only need to add the restriction if: // 1 - We are in the root query // 2 - We are in the subquery and it defines the component with that alias - if (( ! $query->isSubquery() || ($query->isSubquery() && $query->contains(' ' . $params['alias'] . ' '))) && ! $query->contains($field)) { - if ($this->_options['type'] == 'timestamp') { - $query->addPendingJoinCondition($params['alias'], $field . ' IS NULL'); - } else if ($this->_options['type'] == 'boolean') { + if ((!$query->isSubquery() || ($query->isSubquery() && $query->contains(' '.$params['alias'].' '))) && !$query->contains($field)) { + if ('timestamp' == $this->_options['type']) { + $query->addPendingJoinCondition($params['alias'], $field.' IS NULL'); + } elseif ('boolean' == $this->_options['type']) { $query->addPendingJoinCondition( - $params['alias'], $field . ' = ' . $query->getConnection()->convertBooleans(false) + $params['alias'], $field.' = '.$query->getConnection()->convertBooleans(false) ); } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Listener/Timestampable.php b/lib/Doctrine/Template/Listener/Timestampable.php index 5be06d106..685d772d3 100644 --- a/lib/Doctrine/Template/Listener/Timestampable.php +++ b/lib/Doctrine/Template/Listener/Timestampable.php @@ -23,27 +23,26 @@ * Listener for the Timestampable behavior which automatically sets the created * and updated columns when a record is inserted and updated. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Listener_Timestampable extends Doctrine_Record_Listener { /** - * Array of timestampable options + * Array of timestampable options. * * @var string */ protected $_options = array(); /** - * __construct - * - * @param array $options + * __construct. */ public function __construct(array $options) { @@ -51,69 +50,63 @@ public function __construct(array $options) } /** - * Set the created and updated Timestampable columns when a record is inserted - * - * @param Doctrine_Event $event + * Set the created and updated Timestampable columns when a record is inserted. */ public function preInsert(Doctrine_Event $event) { - if ( ! $this->_options['created']['disabled']) { + if (!$this->_options['created']['disabled']) { $createdName = $event->getInvoker()->getTable()->getFieldName($this->_options['created']['name']); $modified = $event->getInvoker()->getModified(); - if ( ! isset($modified[$createdName])) { - $event->getInvoker()->$createdName = $this->getTimestamp('created', $event->getInvoker()->getTable()->getConnection()); + if (!isset($modified[$createdName])) { + $event->getInvoker()->{$createdName} = $this->getTimestamp('created', $event->getInvoker()->getTable()->getConnection()); } } - if ( ! $this->_options['updated']['disabled'] && $this->_options['updated']['onInsert']) { + if (!$this->_options['updated']['disabled'] && $this->_options['updated']['onInsert']) { $updatedName = $event->getInvoker()->getTable()->getFieldName($this->_options['updated']['name']); $modified = $event->getInvoker()->getModified(); - if ( ! isset($modified[$updatedName])) { - $event->getInvoker()->$updatedName = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); + if (!isset($modified[$updatedName])) { + $event->getInvoker()->{$updatedName} = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); } } } /** - * Set updated Timestampable column when a record is updated - * - * @param Doctrine_Event $event + * Set updated Timestampable column when a record is updated. */ public function preUpdate(Doctrine_Event $event) { - if ( ! $this->_options['updated']['disabled']) { + if (!$this->_options['updated']['disabled']) { $updatedName = $event->getInvoker()->getTable()->getFieldName($this->_options['updated']['name']); $modified = $event->getInvoker()->getModified(); - if ( ! isset($modified[$updatedName])) { - $event->getInvoker()->$updatedName = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); + if (!isset($modified[$updatedName])) { + $event->getInvoker()->{$updatedName} = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); } } } /** - * Set the updated field for dql update queries - * - * @param Doctrine_Event $event + * Set the updated field for dql update queries. */ public function preDqlUpdate(Doctrine_Event $event) { - if ( ! $this->_options['updated']['disabled']) { + if (!$this->_options['updated']['disabled']) { $params = $event->getParams(); $updatedName = $event->getInvoker()->getTable()->getFieldName($this->_options['updated']['name']); - $field = $params['alias'] . '.' . $updatedName; + $field = $params['alias'].'.'.$updatedName; $query = $event->getQuery(); - if ( ! $query->contains($field)) { + if (!$query->contains($field)) { $query->set($field, '?', $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection())); } } } /** - * Gets the timestamp in the correct format based on the way the behavior is configured + * Gets the timestamp in the correct format based on the way the behavior is configured. * * @param string $type - * @param null|Doctrine_Connection $conn + * @param Doctrine_Connection|null $conn * * @return Doctrine_Expression|int|string */ @@ -121,16 +114,16 @@ public function getTimestamp($type, $conn = null) { $options = $this->_options[$type]; - if ($options['expression'] !== false && is_string($options['expression'])) { + if (false !== $options['expression'] && is_string($options['expression'])) { return new Doctrine_Expression($options['expression'], $conn); - } else { - if ($options['type'] == 'date') { - return date($options['format'], time()); - } else if ($options['type'] == 'timestamp') { - return date($options['format'], time()); - } else { - return time(); - } } + if ('date' == $options['type']) { + return date($options['format'], time()); + } + if ('timestamp' == $options['type']) { + return date($options['format'], time()); + } + + return time(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/NestedSet.php b/lib/Doctrine/Template/NestedSet.php index 41e7b92d8..fa22d0c15 100644 --- a/lib/Doctrine/Template/NestedSet.php +++ b/lib/Doctrine/Template/NestedSet.php @@ -20,22 +20,21 @@ */ /** - * Doctrine template which implements the custom NestedSet implementation + * Doctrine template which implements the custom NestedSet implementation. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Roman Borschel */ class Doctrine_Template_NestedSet extends Doctrine_Template { /** - * Set up NestedSet template - * - * @return void + * Set up NestedSet template. */ public function setUp() { @@ -44,12 +43,10 @@ public function setUp() } /** - * Call set table definition for the NestedSet behavior - * - * @return void + * Call set table definition for the NestedSet behavior. */ public function setTableDefinition() { $this->_table->getTree()->setTableDefinition(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Searchable.php b/lib/Doctrine/Template/Searchable.php index bfa33de3a..adc4e2c1d 100644 --- a/lib/Doctrine/Template/Searchable.php +++ b/lib/Doctrine/Template/Searchable.php @@ -20,34 +20,29 @@ */ /** - * Doctrine_Template_Searchable + * Doctrine_Template_Searchable. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Template_Searchable extends Doctrine_Template { /** - * __construct - * - * @param array $options - * @return void + * __construct. */ public function __construct(array $options = array()) { - parent::__construct($options); - $this->_plugin = new Doctrine_Search($this->_options); + parent::__construct($options); + $this->_plugin = new Doctrine_Search($this->_options); } /** - * Setup the Searchable template behavior - * - * @return void + * Setup the Searchable template behavior. */ public function setUp() { @@ -58,11 +53,11 @@ public function setUp() /** * Make the batchUpdateIndex() function available to the template so Doctrine_Record child classes - * with the behavior enabled can all the function + * with the behavior enabled can all the function. * - * @param integer $limit - * @param integer $offset - * @return void + * @param int $limit + * @param int $offset + * @param mixed|null $encoding */ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null) { @@ -70,11 +65,11 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null } /** - * Proxy method so the batch updating can be called from table classes + * Proxy method so the batch updating can be called from table classes. * - * @param integer $limit - * @param integer $offset - * @return void + * @param int $limit + * @param int $offset + * @param mixed|null $encoding */ public function batchUpdateIndexTableProxy($limit = null, $offset = null, $encoding = null) { @@ -82,11 +77,12 @@ public function batchUpdateIndexTableProxy($limit = null, $offset = null, $encod } /** - * Searchable keyword search proxy for Doctrine_Table - * - * @param string $string Keyword string to search for - * @param Doctrine_Query $query Query object to alter. Adds where condition to limit the results using the search index - * @return array ids and relevancy + * Searchable keyword search proxy for Doctrine_Table. + * + * @param string $string Keyword string to search for + * @param Doctrine_Query $query Query object to alter. Adds where condition to limit the results using the search index + * + * @return array ids and relevancy */ public function searchTableProxy($string, $query = null) { diff --git a/lib/Doctrine/Template/Sluggable.php b/lib/Doctrine/Template/Sluggable.php index 045019eb0..4a7fc0620 100644 --- a/lib/Doctrine/Template/Sluggable.php +++ b/lib/Doctrine/Template/Sluggable.php @@ -20,64 +20,63 @@ */ /** - * Doctrine_Template_Sluggable + * Doctrine_Template_Sluggable. * * Easily create a slug for each record based on a specified set of fields * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Sluggable extends Doctrine_Template { /** - * Array of Sluggable options + * Array of Sluggable options. * * @var string */ protected $_options = array( - 'name' => 'slug', - 'alias' => null, - 'type' => 'string', - 'length' => 255, - 'unique' => true, - 'options' => array(), - 'fields' => array(), - 'uniqueBy' => array(), - 'uniqueIndex' => true, - 'canUpdate' => false, - 'builder' => array('Doctrine_Inflector', 'urlize'), - 'provider' => null, - 'indexName' => null + 'name' => 'slug', + 'alias' => null, + 'type' => 'string', + 'length' => 255, + 'unique' => true, + 'options' => array(), + 'fields' => array(), + 'uniqueBy' => array(), + 'uniqueIndex' => true, + 'canUpdate' => false, + 'builder' => array('Doctrine_Inflector', 'urlize'), + 'provider' => null, + 'indexName' => null, ); /** - * Set table definition for Sluggable behavior - * - * @return void + * Set table definition for Sluggable behavior. */ public function setTableDefinition() { $name = $this->_options['name']; if ($this->_options['alias']) { - $name .= ' as ' . $this->_options['alias']; + $name .= ' as '.$this->_options['alias']; } - if ($this->_options['indexName'] === null) { + if (null === $this->_options['indexName']) { $this->_options['indexName'] = $this->getTable()->getTableName().'_sluggable'; } $this->hasColumn($name, $this->_options['type'], $this->_options['length'], $this->_options['options']); - - if ($this->_options['unique'] == true && $this->_options['uniqueIndex'] == true) { + + if (true == $this->_options['unique'] && true == $this->_options['uniqueIndex']) { $indexFields = array($this->_options['name']); $indexFields = array_merge($indexFields, $this->_options['uniqueBy']); $this->index($this->_options['indexName'], array('fields' => $indexFields, - 'type' => 'unique')); + 'type' => 'unique')); } $this->addListener(new Doctrine_Template_Listener_Sluggable($this->_options)); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/SoftDelete.php b/lib/Doctrine/Template/SoftDelete.php index 105a9355e..2b1de3b7e 100644 --- a/lib/Doctrine/Template/SoftDelete.php +++ b/lib/Doctrine/Template/SoftDelete.php @@ -20,49 +20,48 @@ */ /** - * Doctrine_Template_SoftDelete + * Doctrine_Template_SoftDelete. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Template_SoftDelete extends Doctrine_Template { /** - * Array of SoftDelete options + * Array of SoftDelete options. * * @var string */ protected $_options = array( - 'name' => 'deleted_at', - 'type' => 'timestamp', - 'length' => null, - 'options' => array( - 'notnull' => false + 'name' => 'deleted_at', + 'type' => 'timestamp', + 'length' => null, + 'options' => array( + 'notnull' => false, ), - 'hardDelete' => false + 'hardDelete' => false, ); protected $_listener; /** - * Set table definition for SoftDelete behavior - * - * @return void + * Set table definition for SoftDelete behavior. */ public function setTableDefinition() { // BC to 1.0.X of SoftDelete behavior - if ($this->_options['type'] == 'boolean') { + if ('boolean' == $this->_options['type']) { $this->_options['length'] = 1; $this->_options['options'] = array('default' => false, 'notnull' => true); } - + $this->hasColumn($this->_options['name'], $this->_options['type'], $this->_options['length'], $this->_options['options']); $this->_listener = new Doctrine_Template_Listener_SoftDelete($this->_options); @@ -70,19 +69,21 @@ public function setTableDefinition() } /** - * Add a hardDelete() method to any of the models who act as SoftDelete behavior + * Add a hardDelete() method to any of the models who act as SoftDelete behavior. * * @param Doctrine_Connection $conn - * @return integer $result Number of affected rows. + * + * @return int $result number of affected rows */ public function hardDelete($conn = null) { - if ($conn === null) { + if (null === $conn) { $conn = $this->_table->getConnection(); } $this->_listener->hardDelete(true); $result = $this->_invoker->delete(); $this->_listener->hardDelete(false); + return $result; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Timestampable.php b/lib/Doctrine/Template/Timestampable.php index 444bb84f3..2ce89d006 100644 --- a/lib/Doctrine/Template/Timestampable.php +++ b/lib/Doctrine/Template/Timestampable.php @@ -20,65 +20,64 @@ */ /** - * Doctrine_Template_Timestampable + * Doctrine_Template_Timestampable. * * Easily add created and updated at timestamps to your doctrine records that are automatically set * when records are saved * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Timestampable extends Doctrine_Template { /** - * Array of Timestampable options + * Array of Timestampable options. * * @var string */ - protected $_options = array('created' => array('name' => 'created_at', - 'alias' => null, - 'type' => 'timestamp', - 'format' => 'Y-m-d H:i:s', - 'disabled' => false, - 'expression' => false, - 'options' => array('notnull' => true)), - 'updated' => array('name' => 'updated_at', - 'alias' => null, - 'type' => 'timestamp', - 'format' => 'Y-m-d H:i:s', - 'disabled' => false, - 'expression' => false, - 'onInsert' => true, - 'options' => array('notnull' => true))); + protected $_options = array('created' => array('name' => 'created_at', + 'alias' => null, + 'type' => 'timestamp', + 'format' => 'Y-m-d H:i:s', + 'disabled' => false, + 'expression' => false, + 'options' => array('notnull' => true)), + 'updated' => array('name' => 'updated_at', + 'alias' => null, + 'type' => 'timestamp', + 'format' => 'Y-m-d H:i:s', + 'disabled' => false, + 'expression' => false, + 'onInsert' => true, + 'options' => array('notnull' => true))); /** - * Set table definition for Timestampable behavior - * - * @return void + * Set table definition for Timestampable behavior. */ public function setTableDefinition() { - if ( ! $this->_options['created']['disabled']) { + if (!$this->_options['created']['disabled']) { $name = $this->_options['created']['name']; if ($this->_options['created']['alias']) { - $name .= ' as ' . $this->_options['created']['alias']; + $name .= ' as '.$this->_options['created']['alias']; } $this->hasColumn($name, $this->_options['created']['type'], null, $this->_options['created']['options']); } - if ( ! $this->_options['updated']['disabled']) { + if (!$this->_options['updated']['disabled']) { $name = $this->_options['updated']['name']; if ($this->_options['updated']['alias']) { - $name .= ' as ' . $this->_options['updated']['alias']; + $name .= ' as '.$this->_options['updated']['alias']; } $this->hasColumn($name, $this->_options['updated']['type'], null, $this->_options['updated']['options']); } $this->addListener(new Doctrine_Template_Listener_Timestampable($this->_options)); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Versionable.php b/lib/Doctrine/Template/Versionable.php index 7afba2b1a..8cf92d57c 100644 --- a/lib/Doctrine/Template/Versionable.php +++ b/lib/Doctrine/Template/Versionable.php @@ -20,53 +20,49 @@ */ /** - * Doctrine_Template_Versionable + * Doctrine_Template_Versionable. * * Add revisioning/audit log to your models * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Versionable extends Doctrine_Template { /** - * Array of AuditLog Options + * Array of AuditLog Options. * * @var array */ - protected $_options = array('version' => array('name' => 'version', - 'alias' => null, - 'type' => 'integer', - 'length' => 8, - 'options' => array()), - 'generateRelations' => true, - 'tableName' => false, - 'generateFiles' => false, - 'auditLog' => true, - 'deleteVersions' => true, - 'listener' => 'Doctrine_AuditLog_Listener'); + protected $_options = array('version' => array('name' => 'version', + 'alias' => null, + 'type' => 'integer', + 'length' => 8, + 'options' => array()), + 'generateRelations' => true, + 'tableName' => false, + 'generateFiles' => false, + 'auditLog' => true, + 'deleteVersions' => true, + 'listener' => 'Doctrine_AuditLog_Listener'); /** - * __construct - * - * @param array $options - * @return void + * __construct. */ public function __construct(array $options = array()) { - parent::__construct($options); + parent::__construct($options); $this->_plugin = new Doctrine_AuditLog($this->_options); } /** - * Setup the Versionable behavior for the template - * - * @return void + * Setup the Versionable behavior for the template. */ public function setUp() { @@ -75,7 +71,7 @@ public function setUp() } $version = $this->_options['version']; - $name = $version['name'] . (isset($version['alias']) ? ' as ' . $version['alias'] : ''); + $name = $version['name'].(isset($version['alias']) ? ' as '.$version['alias'] : ''); $this->hasColumn($name, $version['type'], $version['length'], $version['options']); $listener = $this->_options['listener']; @@ -83,41 +79,40 @@ public function setUp() } /** - * Get plugin for Versionable template - * - * @return void + * Get plugin for Versionable template. */ public function getAuditLog() { return $this->_plugin; } - /** + /** * revert * reverts this record to given version, this method only works if versioning plugin - * is enabled + * is enabled. + * + * @param int $version an integer > 1 * - * @throws Doctrine_Record_Exception if given version does not exist - * @param integer $version an integer > 1 - * @return Doctrine_Record this object + * @return Doctrine_Record this object + * + * @throws Doctrine_Record_Exception if given version does not exist */ public function revert($version) { $auditLog = $this->_plugin; - if ( ! $auditLog->getOption('auditLog')) { + if (!$auditLog->getOption('auditLog')) { throw new Doctrine_Record_Exception('Audit log is turned off, no version history is recorded.'); } $data = $auditLog->getVersion($this->getInvoker(), $version); - if ( ! isset($data[0])) { - throw new Doctrine_Record_Exception('Version ' . $version . ' does not exist!'); + if (!isset($data[0])) { + throw new Doctrine_Record_Exception('Version '.$version.' does not exist!'); } $this->getInvoker()->merge($data[0]); - return $this->getInvoker(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction.php b/lib/Doctrine/Transaction.php index 23eeaa25f..086336561 100644 --- a/lib/Doctrine/Transaction.php +++ b/lib/Doctrine/Transaction.php @@ -21,77 +21,79 @@ /** * Doctrine_Transaction - * Handles transaction savepoint and isolation abstraction + * Handles transaction savepoint and isolation abstraction. * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7651 $ */ class Doctrine_Transaction extends Doctrine_Connection_Module { /** - * Doctrine_Transaction is in sleep state when it has no active transactions + * Doctrine_Transaction is in sleep state when it has no active transactions. */ - const STATE_SLEEP = 0; + public const STATE_SLEEP = 0; /** - * Doctrine_Transaction is in active state when it has one active transaction + * Doctrine_Transaction is in active state when it has one active transaction. */ - const STATE_ACTIVE = 1; + public const STATE_ACTIVE = 1; /** - * Doctrine_Transaction is in busy state when it has multiple active transactions + * Doctrine_Transaction is in busy state when it has multiple active transactions. */ - const STATE_BUSY = 2; + public const STATE_BUSY = 2; /** - * @var integer $_nestingLevel The current nesting level of this transaction. - * A nesting level of 0 means there is currently no active - * transaction. + * @var int The current nesting level of this transaction. + * A nesting level of 0 means there is currently no active + * transaction. */ protected $_nestingLevel = 0; - + /** - * @var integer $_internalNestingLevel The current internal nesting level of this transaction. - * "Internal" means transactions started by Doctrine itself. - * Therefore the internal nesting level is always - * lower or equal to the overall nesting level. - * A level of 0 means there is currently no active - * transaction that was initiated by Doctrine itself. + * @var int The current internal nesting level of this transaction. + * "Internal" means transactions started by Doctrine itself. + * Therefore the internal nesting level is always + * lower or equal to the overall nesting level. + * A level of 0 means there is currently no active + * transaction that was initiated by Doctrine itself. */ protected $_internalNestingLevel = 0; /** - * @var array $invalid an array containing all invalid records within this transaction + * @var array an array containing all invalid records within this transaction + * * @todo What about a more verbose name? $invalidRecords? */ - protected $invalid = array(); + protected $invalid = array(); /** - * @var array $savepoints an array containing all savepoints + * @var array an array containing all savepoints */ - protected $savePoints = array(); + protected $savePoints = array(); /** - * @var array $_collections an array of Doctrine_Collection objects that were affected during the Transaction + * @var array an array of Doctrine_Collection objects that were affected during the Transaction */ - protected $_collections = array(); + protected $_collections = array(); /** * addCollection - * adds a collection in the internal array of collections + * adds a collection in the internal array of collections. * * at the end of each commit this array is looped over and * of every collection Doctrine then takes a snapshot in order * to keep the collections up to date with the database * - * @param Doctrine_Collection $coll a collection to be added - * @return Doctrine_Transaction this object + * @param Doctrine_Collection $coll a collection to be added + * + * @return Doctrine_Transaction this object */ public function addCollection(Doctrine_Collection $coll) { @@ -105,7 +107,8 @@ public function addCollection(Doctrine_Collection $coll) * returns the state of this transaction module. * * @see Doctrine_Connection_Transaction::STATE_* constants - * @return integer the connection state + * + * @return int the connection state */ public function getState() { @@ -123,11 +126,10 @@ public function getState() /** * addInvalid - * adds record into invalid records list + * adds record into invalid records list. * - * @param Doctrine_Record $record - * @return boolean false if record already existed in invalid records list, - * otherwise true + * @return bool false if record already existed in invalid records list, + * otherwise true */ public function addInvalid(Doctrine_Record $record) { @@ -135,15 +137,15 @@ public function addInvalid(Doctrine_Record $record) return false; } $this->invalid[] = $record; + return true; } - - /** - * Return the invalid records - * - * @return array An array of invalid records - */ + /** + * Return the invalid records. + * + * @return array An array of invalid records + */ public function getInvalid() { return $this->invalid; @@ -151,15 +153,15 @@ public function getInvalid() /** * getTransactionLevel - * get the current transaction nesting level + * get the current transaction nesting level. * - * @return integer + * @return int */ public function getTransactionLevel() { return $this->_nestingLevel; } - + public function getInternalTransactionLevel() { return $this->_internalNestingLevel; @@ -177,35 +179,37 @@ public function getInternalTransactionLevel() * * Listeners: onPreTransactionBegin, onTransactionBegin * - * @param string $savepoint name of a savepoint to set - * @throws Doctrine_Transaction_Exception if the transaction fails at database level - * @return integer current transaction nesting level + * @param string $savepoint name of a savepoint to set + * + * @return int current transaction nesting level + * + * @throws Doctrine_Transaction_Exception if the transaction fails at database level */ public function beginTransaction($savepoint = null) { $this->conn->connect(); - + $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER); - if ( ! is_null($savepoint)) { + if (!is_null($savepoint)) { $this->savePoints[] = $savepoint; $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_CREATE); $listener->preSavepointCreate($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->createSavePoint($savepoint); } $listener->postSavepointCreate($event); } else { - if ($this->_nestingLevel == 0) { + if (0 == $this->_nestingLevel) { $event = new Doctrine_Event($this, Doctrine_Event::TX_BEGIN); $listener->preTransactionBegin($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { try { $this->_doBeginTransaction(); } catch (Exception $e) { @@ -216,9 +220,7 @@ public function beginTransaction($savepoint = null) } } - $level = ++$this->_nestingLevel; - - return $level; + return ++$this->_nestingLevel; } /** @@ -228,44 +230,45 @@ public function beginTransaction($savepoint = null) * * Listeners: preTransactionCommit, postTransactionCommit * - * @param string $savepoint name of a savepoint to release - * @throws Doctrine_Transaction_Exception if the transaction fails at database level - * @throws Doctrine_Validator_Exception if the transaction fails due to record validations - * @return boolean false if commit couldn't be performed, true otherwise + * @param string $savepoint name of a savepoint to release + * + * @return bool false if commit couldn't be performed, true otherwise + * + * @throws Doctrine_Transaction_Exception if the transaction fails at database level + * @throws Doctrine_Validator_Exception if the transaction fails due to record validations */ public function commit($savepoint = null) { - if ($this->_nestingLevel == 0) { - throw new Doctrine_Transaction_Exception("Commit failed. There is no active transaction."); + if (0 == $this->_nestingLevel) { + throw new Doctrine_Transaction_Exception('Commit failed. There is no active transaction.'); } - + $this->conn->connect(); $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER); - if ( ! is_null($savepoint)) { + if (!is_null($savepoint)) { $this->_nestingLevel -= $this->removeSavePoints($savepoint); $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_COMMIT); $listener->preSavepointCommit($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->releaseSavePoint($savepoint); } $listener->postSavepointCommit($event); } else { - - if ($this->_nestingLevel == 1 || $this->_internalNestingLevel == 1) { - if ( ! empty($this->invalid)) { - if ($this->_internalNestingLevel == 1) { + if (1 == $this->_nestingLevel || 1 == $this->_internalNestingLevel) { + if (!empty($this->invalid)) { + if (1 == $this->_internalNestingLevel) { $tmp = $this->invalid; $this->invalid = array(); throw new Doctrine_Validator_Exception($tmp); } } - if ($this->_nestingLevel == 1) { + if (1 == $this->_nestingLevel) { // take snapshots of all collections used within this transaction foreach ($this->_collections as $coll) { $coll->takeSnapshot(); @@ -275,19 +278,19 @@ public function commit($savepoint = null) $event = new Doctrine_Event($this, Doctrine_Event::TX_COMMIT); $listener->preTransactionCommit($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->_doCommit(); } $listener->postTransactionCommit($event); } } - + if ($this->_nestingLevel > 0) { - $this->_nestingLevel--; - } + --$this->_nestingLevel; + } if ($this->_internalNestingLevel > 0) { - $this->_internalNestingLevel--; - } + --$this->_internalNestingLevel; + } } return true; @@ -303,9 +306,12 @@ public function commit($savepoint = null) * this method can be listened with onPreTransactionRollback and onTransactionRollback * eventlistener methods * - * @param string $savepoint name of a savepoint to rollback to - * @throws Doctrine_Transaction_Exception if the rollback operation fails at database level - * @return boolean false if rollback couldn't be performed, true otherwise + * @param string $savepoint name of a savepoint to rollback to + * + * @return bool false if rollback couldn't be performed, true otherwise + * + * @throws Doctrine_Transaction_Exception if the rollback operation fails at database level + * * @todo Shouldnt this method only commit a rollback if the transactionLevel is 1 * (STATE_ACTIVE)? Explanation: Otherwise a rollback that is triggered from inside doctrine * in an (emulated) nested transaction would lead to a complete database level @@ -315,41 +321,44 @@ public function commit($savepoint = null) */ public function rollback($savepoint = null) { - if ($this->_nestingLevel == 0) { - throw new Doctrine_Transaction_Exception("Rollback failed. There is no active transaction."); + if (0 == $this->_nestingLevel) { + throw new Doctrine_Transaction_Exception('Rollback failed. There is no active transaction.'); } - + $this->conn->connect(); if ($this->_internalNestingLevel >= 1 && $this->_nestingLevel > 1) { - $this->_internalNestingLevel--; - $this->_nestingLevel--; + --$this->_internalNestingLevel; + --$this->_nestingLevel; + return false; - } else if ($this->_nestingLevel > 1) { - $this->_nestingLevel--; + } + if ($this->_nestingLevel > 1) { + --$this->_nestingLevel; + return false; } $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER); - if ( ! is_null($savepoint)) { + if (!is_null($savepoint)) { $this->_nestingLevel -= $this->removeSavePoints($savepoint); $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_ROLLBACK); $listener->preSavepointRollback($event); - - if ( ! $event->skipOperation) { + + if (!$event->skipOperation) { $this->rollbackSavePoint($savepoint); } $listener->postSavepointRollback($event); } else { $event = new Doctrine_Event($this, Doctrine_Event::TX_ROLLBACK); - + $listener->preTransactionRollback($event); - - if ( ! $event->skipOperation) { + + if (!$event->skipOperation) { $this->_nestingLevel = 0; $this->_internalNestingLevel = 0; try { @@ -367,10 +376,9 @@ public function rollback($savepoint = null) /** * releaseSavePoint - * creates a new savepoint + * creates a new savepoint. * - * @param string $savepoint name of a savepoint to create - * @return void + * @param string $savepoint name of a savepoint to create */ protected function createSavePoint($savepoint) { @@ -379,10 +387,9 @@ protected function createSavePoint($savepoint) /** * releaseSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to release - * @return void + * @param string $savepoint name of a savepoint to release */ protected function releaseSavePoint($savepoint) { @@ -391,16 +398,15 @@ protected function releaseSavePoint($savepoint) /** * rollbackSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to rollback to - * @return void + * @param string $savepoint name of a savepoint to rollback to */ protected function rollbackSavePoint($savepoint) { throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.'); } - + /** * Performs the rollback. */ @@ -408,7 +414,7 @@ protected function _doRollback() { $this->conn->getDbh()->rollback(); } - + /** * Performs the commit. */ @@ -416,7 +422,7 @@ protected function _doCommit() { $this->conn->getDbh()->commit(); } - + /** * Begins a database transaction. */ @@ -428,10 +434,11 @@ protected function _doBeginTransaction() /** * removeSavePoints * removes a savepoint from the internal savePoints array of this transaction object - * and all its children savepoints + * and all its children savepoints. * - * @param sring $savepoint name of the savepoint to remove - * @return integer removed savepoints + * @param sring $savepoint name of the savepoint to remove + * + * @return int removed savepoints */ private function removeSavePoints($savepoint) { @@ -441,13 +448,13 @@ private function removeSavePoints($savepoint) $i = 0; foreach ($this->savePoints as $key => $sp) { - if ( ! $found) { + if (!$found) { if ($sp === $savepoint) { $found = true; } } if ($found) { - $i++; + ++$i; unset($this->savePoints[$key]); } } @@ -456,7 +463,7 @@ private function removeSavePoints($savepoint) } /** - * setIsolation + * setIsolation. * * Set the transacton isolation level. * (implemented by the connection drivers) @@ -473,9 +480,8 @@ private function removeSavePoints($savepoint) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) * - * @throws Doctrine_Transaction_Exception if the feature is not supported by the driver - * @throws PDOException if something fails at the PDO level - * @return void + * @throws Doctrine_Transaction_Exception if the feature is not supported by the driver + * @throws PDOException if something fails at the PDO level */ public function setIsolation($isolation) { @@ -483,32 +489,35 @@ public function setIsolation($isolation) } /** - * getTransactionIsolation + * getTransactionIsolation. * * fetches the current session transaction isolation level * * note: some drivers may support setting the transaction isolation level * but not fetching it * - * @throws Doctrine_Transaction_Exception if the feature is not supported by the driver - * @throws PDOException if something fails at the PDO level - * @return string returns the current session transaction isolation level + * @return string returns the current session transaction isolation level + * + * @throws Doctrine_Transaction_Exception if the feature is not supported by the driver + * @throws PDOException if something fails at the PDO level */ public function getIsolation() { throw new Doctrine_Transaction_Exception('Fetching transaction isolation level not supported by this driver.'); } - + /** * Initiates a transaction. * * This method must only be used by Doctrine itself to initiate transactions. * Userland-code must use {@link beginTransaction()}. + * + * @param mixed|null $savepoint */ public function beginInternalTransaction($savepoint = null) { - $this->_internalNestingLevel++; + ++$this->_internalNestingLevel; + return $this->beginTransaction($savepoint); } - } diff --git a/lib/Doctrine/Transaction/Exception.php b/lib/Doctrine/Transaction/Exception.php index aa0a64e5c..04a953071 100644 --- a/lib/Doctrine/Transaction/Exception.php +++ b/lib/Doctrine/Transaction/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Transaction_Exception + * Doctrine_Transaction_Exception. * - * @package Doctrine - * @subpackage Transaction * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Transaction_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Transaction/Mock.php b/lib/Doctrine/Transaction/Mock.php index aab70ad8b..5928016c9 100644 --- a/lib/Doctrine/Transaction/Mock.php +++ b/lib/Doctrine/Transaction/Mock.php @@ -21,16 +21,17 @@ /** * Doctrine_Transaction_Mock - * This class is used for testing purposes + * This class is used for testing purposes. * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Transaction_Mock extends Doctrine_Transaction -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Transaction/Mssql.php b/lib/Doctrine/Transaction/Mssql.php index a347b9c2f..a92b7105e 100644 --- a/lib/Doctrine/Transaction/Mssql.php +++ b/lib/Doctrine/Transaction/Mssql.php @@ -20,14 +20,13 @@ */ /** - * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Mssql extends Doctrine_Transaction @@ -44,12 +43,13 @@ class Doctrine_Transaction_Mssql extends Doctrine_Transaction * mssql specific modes: * SNAPSHOT * - * @link http://msdn2.microsoft.com/en-us/library/ms173763.aspx - * @throws PDOException if something fails at the PDO level - * @throws Doctrine_Transaction_Exception if using unknown isolation level or unknown wait option - * @return void + * @see http://msdn2.microsoft.com/en-us/library/ms173763.aspx + * + * @throws PDOException if something fails at the PDO level + * @throws Doctrine_Transaction_Exception if using unknown isolation level or unknown wait option */ - public function setIsolation($isolation, $options = array()) { + public function setIsolation($isolation, $options = array()) + { switch ($isolation) { case 'READ UNCOMMITTED': case 'READ COMMITTED': @@ -58,14 +58,14 @@ public function setIsolation($isolation, $options = array()) { case 'SNAPSHOT': break; default: - throw new Doctrine_Transaction_Exception('isolation level is not supported: ' . $isolation); + throw new Doctrine_Transaction_Exception('isolation level is not supported: '.$isolation); } - $query = 'SET TRANSACTION ISOLATION LEVEL ' . $isolation; + $query = 'SET TRANSACTION ISOLATION LEVEL '.$isolation; $this->conn->execute($query); } - + /** * Performs the rollback. */ @@ -73,7 +73,7 @@ protected function _doRollback() { $this->conn->getDbh()->exec('ROLLBACK TRANSACTION'); } - + /** * Performs the commit. */ @@ -81,7 +81,7 @@ protected function _doCommit() { $this->conn->getDbh()->exec('COMMIT TRANSACTION'); } - + /** * Begins a database transaction. */ @@ -89,4 +89,4 @@ protected function _doBeginTransaction() { $this->conn->getDbh()->exec('BEGIN TRANSACTION'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction/Mysql.php b/lib/Doctrine/Transaction/Mysql.php index 412e729a8..227d2c18b 100644 --- a/lib/Doctrine/Transaction/Mysql.php +++ b/lib/Doctrine/Transaction/Mysql.php @@ -20,56 +20,52 @@ */ /** - * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Mysql extends Doctrine_Transaction { /** * createSavepoint - * creates a new savepoint + * creates a new savepoint. * - * @param string $savepoint name of a savepoint to set - * @return void + * @param string $savepoint name of a savepoint to set */ protected function createSavePoint($savepoint) { - $query = 'SAVEPOINT ' . $savepoint; + $query = 'SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * releaseSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to release - * @return void + * @param string $savepoint name of a savepoint to release */ protected function releaseSavePoint($savepoint) { - $query = 'RELEASE SAVEPOINT ' . $savepoint; + $query = 'RELEASE SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * rollbackSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to rollback to - * @return void + * @param string $savepoint name of a savepoint to rollback to */ protected function rollbackSavePoint($savepoint) { - $query = 'ROLLBACK TO SAVEPOINT ' . $savepoint; + $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; return $this->conn->execute($query); } @@ -83,9 +79,8 @@ protected function rollbackSavePoint($savepoint) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) * - * @throws Doctrine_Transaction_Exception if using unknown isolation level - * @throws PDOException if something fails at the PDO level - * @return void + * @throws Doctrine_Transaction_Exception if using unknown isolation level + * @throws PDOException if something fails at the PDO level */ public function setIsolation($isolation) { @@ -96,21 +91,21 @@ public function setIsolation($isolation) case 'SERIALIZABLE': break; default: - throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . ' is not supported.'); + throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.' is not supported.'); } - $query = 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $isolation; + $query = 'SET SESSION TRANSACTION ISOLATION LEVEL '.$isolation; return $this->conn->execute($query); } /** - * getTransactionIsolation + * getTransactionIsolation. * - * @return string returns the current session transaction isolation level + * @return string returns the current session transaction isolation level */ public function getIsolation() { return $this->conn->fetchOne('SELECT @@tx_isolation'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction/Oracle.php b/lib/Doctrine/Transaction/Oracle.php index 9098cd837..feb1a9d28 100644 --- a/lib/Doctrine/Transaction/Oracle.php +++ b/lib/Doctrine/Transaction/Oracle.php @@ -20,38 +20,35 @@ */ /** - * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Oracle extends Doctrine_Transaction { /** * createSavepoint - * creates a new savepoint + * creates a new savepoint. * - * @param string $savepoint name of a savepoint to set - * @return void + * @param string $savepoint name of a savepoint to set */ protected function createSavePoint($savepoint) { - $query = 'SAVEPOINT ' . $savepoint; + $query = 'SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * releaseSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to release - * @return void + * @param string $savepoint name of a savepoint to release */ protected function releaseSavePoint($savepoint) { @@ -61,14 +58,13 @@ protected function releaseSavePoint($savepoint) /** * rollbackSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to rollback to - * @return void + * @param string $savepoint name of a savepoint to rollback to */ protected function rollbackSavePoint($savepoint) { - $query = 'ROLLBACK TO SAVEPOINT ' . $savepoint; + $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; return $this->conn->execute($query); } @@ -81,9 +77,9 @@ protected function rollbackSavePoint($savepoint) * READ COMMITTED (prevents dirty reads) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) - * @throws PDOException if something fails at the PDO level - * @throws Doctrine_Transaction_Exception if using unknown isolation level - * @return void + * + * @throws PDOException if something fails at the PDO level + * @throws Doctrine_Transaction_Exception if using unknown isolation level */ public function setIsolation($isolation) { @@ -97,10 +93,11 @@ public function setIsolation($isolation) $isolation = 'SERIALIZABLE'; break; default: - throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . ' is not supported.'); + throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.' is not supported.'); } - $query = 'ALTER SESSION SET ISOLATION_LEVEL = ' . $isolation; + $query = 'ALTER SESSION SET ISOLATION_LEVEL = '.$isolation; + return $this->conn->execute($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction/Pgsql.php b/lib/Doctrine/Transaction/Pgsql.php index d4ba042d8..bbb900e1b 100644 --- a/lib/Doctrine/Transaction/Pgsql.php +++ b/lib/Doctrine/Transaction/Pgsql.php @@ -20,57 +20,53 @@ */ /** - * * @author Konsta Vesterinen * @author Paul Cooper (PEAR MDB2 Pgsql driver) * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Pgsql extends Doctrine_Transaction { /** * createSavepoint - * creates a new savepoint + * creates a new savepoint. * - * @param string $savepoint name of a savepoint to set - * @return void + * @param string $savepoint name of a savepoint to set */ protected function createSavePoint($savepoint) { - $query = 'SAVEPOINT ' . $savepoint; + $query = 'SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * releaseSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to release - * @return void + * @param string $savepoint name of a savepoint to release */ protected function releaseSavePoint($savepoint) { - $query = 'RELEASE SAVEPOINT ' . $savepoint; + $query = 'RELEASE SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * rollbackSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to rollback to - * @return void + * @param string $savepoint name of a savepoint to rollback to */ protected function rollbackSavePoint($savepoint) { - $query = 'ROLLBACK TO SAVEPOINT ' . $savepoint; + $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; return $this->conn->execute($query); } @@ -83,9 +79,9 @@ protected function rollbackSavePoint($savepoint) * READ COMMITTED (prevents dirty reads) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) - * @throws PDOException if something fails at the PDO level - * @throws Doctrine_Transaction_Exception if using unknown isolation level or unknown wait option - * @return void + * + * @throws PDOException if something fails at the PDO level + * @throws Doctrine_Transaction_Exception if using unknown isolation level or unknown wait option */ public function setIsolation($isolation) { @@ -99,7 +95,8 @@ public function setIsolation($isolation) throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.' is not supported.'); } - $query = 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ' . $isolation; + $query = 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL '.$isolation; + return $this->conn->execute($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction/Sqlite.php b/lib/Doctrine/Transaction/Sqlite.php index 7e343d1ef..3d312c33f 100644 --- a/lib/Doctrine/Transaction/Sqlite.php +++ b/lib/Doctrine/Transaction/Sqlite.php @@ -20,14 +20,13 @@ */ /** - * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Sqlite extends Doctrine_Transaction @@ -40,9 +39,9 @@ class Doctrine_Transaction_Sqlite extends Doctrine_Transaction * READ COMMITTED (prevents dirty reads) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) - * @throws PDOException if something fails at the PDO level - * @throws Doctrine_Transaction_Exception if using unknown isolation level - * @return void + * + * @throws PDOException if something fails at the PDO level + * @throws Doctrine_Transaction_Exception if using unknown isolation level */ public function setIsolation($isolation) { @@ -56,11 +55,11 @@ public function setIsolation($isolation) $isolation = 1; break; default: - throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . 'is not supported.'); + throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.'is not supported.'); } - $query = 'PRAGMA read_uncommitted = ' . $isolation; + $query = 'PRAGMA read_uncommitted = '.$isolation; return $this->conn->execute($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Tree.php b/lib/Doctrine/Tree.php index ec1ed5955..4f53b64ba 100644 --- a/lib/Doctrine/Tree.php +++ b/lib/Doctrine/Tree.php @@ -18,22 +18,23 @@ * and is licensed under the LGPL. For more information, see * . */ - + /** - * Doctrine_Tree + * Doctrine_Tree. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Tree { /** - * @param object $table reference to associated Doctrine_Table instance + * @param object $table reference to associated Doctrine_Table instance */ protected $table; @@ -41,14 +42,14 @@ class Doctrine_Tree * @param array $options */ protected $options = array(); - + protected $_baseComponent; /** - * constructor, creates tree with reference to table and any options + * constructor, creates tree with reference to table and any options. * - * @param object $table instance of Doctrine_Table - * @param array $options options + * @param object $table instance of Doctrine_Table + * @param array $options options */ public function __construct(Doctrine_Table $table, $options) { @@ -63,13 +64,13 @@ public function __construct(Doctrine_Table $table, $options) } $this->_baseComponent = $class; } - //echo $this->_baseComponent; + // echo $this->_baseComponent; } /** - * Used to define table attributes required for the given implementation + * Used to define table attributes required for the given implementation. * - * @throws Doctrine_Tree_Exception if table attributes have not been defined + * @throws Doctrine_Tree_Exception if table attributes have not been defined */ public function setTableDefinition() { @@ -77,8 +78,7 @@ public function setTableDefinition() } /** - * this method is used for setting up relations and attributes and should be used by specific implementations - * + * this method is used for setting up relations and attributes and should be used by specific implementations. */ public function setUp() { @@ -87,41 +87,40 @@ public function setUp() /** * Factory method to create a Tree. * - * This is a factory method that returns a tree instance based upon + * This is a factory method that returns a tree instance based upon * chosen implementation. * - * @param object $table instance of Doctrine_Table - * @param string $impName implementation (NestedSet, AdjacencyList, MaterializedPath) - * @param array $options options + * @param object $table instance of Doctrine_Table + * @param array $options options + * * @return Doctrine_Tree - * @throws Doctrine_Exception if class $implName does not extend Doctrine_Tree + * + * @throws Doctrine_Exception if class $implName does not extend Doctrine_Tree */ public static function factory(Doctrine_Table $table, $implName, $options = array()) { - $class = 'Doctrine_Tree_' . $implName; - if ( ! class_exists($class)) { + $class = 'Doctrine_Tree_'.$implName; + if (!class_exists($class)) { throw new Doctrine_Exception('The chosen class must extend Doctrine_Tree'); } + return new $class($table, $options); } /** - * gets tree attribute value - * - */ + * gets tree attribute value. + */ public function getAttribute($name) { - return isset($this->options[$name]) ? $this->options[$name] : null; + return isset($this->options[$name]) ? $this->options[$name] : null; } /** - * sets tree attribute value - * - * @param mixed + * sets tree attribute value. */ public function setAttribute($name, $value) { - $this->options[$name] = $value; + $this->options[$name] = $value; } /** diff --git a/lib/Doctrine/Tree/AdjacencyList.php b/lib/Doctrine/Tree/AdjacencyList.php index 4430289c9..6c80e0459 100644 --- a/lib/Doctrine/Tree/AdjacencyList.php +++ b/lib/Doctrine/Tree/AdjacencyList.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Tree_AdjacencyList + * Doctrine_Tree_AdjacencyList. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Tree_AdjacencyList extends Doctrine_Tree implements Doctrine_Tree_Interface -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Tree/Exception.php b/lib/Doctrine/Tree/Exception.php index 0f3846155..6c76d2fc6 100644 --- a/lib/Doctrine/Tree/Exception.php +++ b/lib/Doctrine/Tree/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Tree_Exception + * Doctrine_Tree_Exception. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Tree_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Tree/Interface.php b/lib/Doctrine/Tree/Interface.php index 4a88116c4..f448850b4 100644 --- a/lib/Doctrine/Tree/Interface.php +++ b/lib/Doctrine/Tree/Interface.php @@ -20,48 +20,51 @@ */ /** - * Doctrine_Tree_Interface + * Doctrine_Tree_Interface. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ -interface Doctrine_Tree_Interface { - +interface Doctrine_Tree_Interface +{ /** - * creates root node from given record or from a new record + * creates root node from given record or from a new record. * - * @param Doctrine_Record $record instance of Doctrine_Record + * @param Doctrine_Record $record instance of Doctrine_Record */ public function createRoot(Doctrine_Record $record = null); /** - * returns root node + * returns root node. * * @return Doctrine_Record */ public function fetchRoot($root_id = 1); /** - * optimised method to returns iterator for traversal of the entire tree from root + * optimised method to returns iterator for traversal of the entire tree from root. + * + * @param array $options options + * @param mixed|null $hydrationMode * - * @param array $options options - * @param integer $fetchmode One of the Doctrine_Core::HYDRATE_* constants. - * @return Iterator instance of Doctrine_Node__PreOrderIterator + * @return Iterator instance of Doctrine_Node__PreOrderIterator */ public function fetchTree($options = array(), $hydrationMode = null); /** - * optimised method that returns iterator for traversal of the tree from the given record primary key + * optimised method that returns iterator for traversal of the tree from the given record primary key. + * + * @param mixed $pk primary key as used by table::find() to locate node to traverse tree from + * @param array $options options + * @param mixed|null $hydrationMode * - * @param mixed $pk primary key as used by table::find() to locate node to traverse tree from - * @param array $options options - * @param integer $fetchmode One of the Doctrine_Core::HYDRATE_* constants. - * @return iterator instance of Doctrine_Node__PreOrderIterator + * @return iterator instance of Doctrine_Node__PreOrderIterator */ public function fetchBranch($pk, $options = array(), $hydrationMode = null); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Tree/MaterializedPath.php b/lib/Doctrine/Tree/MaterializedPath.php index 9fb5d436e..babaa0583 100644 --- a/lib/Doctrine/Tree/MaterializedPath.php +++ b/lib/Doctrine/Tree/MaterializedPath.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Tree_MaterializedPath + * Doctrine_Tree_MaterializedPath. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Tree_MaterializedPath extends Doctrine_Tree implements Doctrine_Tree_Interface -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Tree/NestedSet.php b/lib/Doctrine/Tree/NestedSet.php index 53ba87269..9537de2e5 100644 --- a/lib/Doctrine/Tree/NestedSet.php +++ b/lib/Doctrine/Tree/NestedSet.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Tree_NestedSet + * Doctrine_Tree_NestedSet. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms * @author Roman Borschel */ class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Interface { private $_baseQuery; - private $_baseAlias = "base"; + private $_baseAlias = 'base'; /** - * constructor, creates tree with reference to table and sets default root options + * constructor, creates tree with reference to table and sets default root options. * - * @param object $table instance of Doctrine_Table - * @param array $options options + * @param object $table instance of Doctrine_Table + * @param array $options options */ public function __construct(Doctrine_Table $table, $options) { @@ -55,8 +56,7 @@ public function __construct(Doctrine_Table $table, $options) /** * used to define table attributes required for the NestetSet implementation - * adds lft and rgt columns for corresponding left and right values - * + * adds lft and rgt columns for corresponding left and right values. */ public function setTableDefinition() { @@ -67,7 +67,7 @@ public function setTableDefinition() $this->table->setColumn('lft', 'integer', 4); $this->table->setColumn('rgt', 'integer', 4); if ($level = $this->getAttribute('levelColumnName')) { - $this->table->setColumn($level . ' AS level', 'integer', 2); + $this->table->setColumn($level.' AS level', 'integer', 2); } else { $this->table->setColumn('level', 'integer', 2); } @@ -82,27 +82,24 @@ public function setTableDefinition() * the records id will be assigned to the root id. You must use numeric columns for the id * and root id columns. * - * @param object $record instance of Doctrine_Record + * @param object $record instance of Doctrine_Record */ public function createRoot(Doctrine_Record $record = null) { if ($this->getAttribute('hasManyRoots')) { - if ( ! $record || ( ! $record->exists() && ! $record->getNode()->getRootValue()) + if (!$record || (!$record->exists() && !$record->getNode()->getRootValue()) || $record->getTable()->isIdentifierComposite()) { - throw new Doctrine_Tree_Exception("Node must have a root id set or must " - . " be persistent and have a single-valued numeric primary key in order to" - . " be created as a root node. Automatic assignment of a root id on" - . " transient/new records is no longer supported."); + throw new Doctrine_Tree_Exception('Node must have a root id set or must be persistent and have a single-valued numeric primary key in order to be created as a root node. Automatic assignment of a root id on transient/new records is no longer supported.'); } - - if ($record->exists() && ! $record->getNode()->getRootValue()) { + + if ($record->exists() && !$record->getNode()->getRootValue()) { // Default: root_id = id $identifier = $record->getTable()->getIdentifier(); $record->getNode()->setRootValue($record->get($identifier)); } } - - if ( ! $record) { + + if (!$record) { $record = $this->table->create(); } @@ -118,14 +115,15 @@ public function createRoot(Doctrine_Record $record = null) /** * Fetches a/the root node. * - * @param integer $rootId + * @param int $rootId + * * @todo Better $rootid = null and exception if $rootId == null && hasManyRoots? * Fetching with id = 1 is too magical and cant work reliably anyway. */ public function fetchRoot($rootId = 1) { $q = $this->getBaseQuery(); - $q = $q->addWhere($this->_baseAlias . '.lft = ?', 1); + $q = $q->addWhere($this->_baseAlias.'.lft = ?', 1); // if tree has many roots, then specify root id $q = $this->returnQueryWithRootId($q, $rootId); @@ -138,11 +136,11 @@ public function fetchRoot($rootId = 1) if ($data instanceof Doctrine_Collection) { $root = $data->getFirst(); $root['level'] = 0; - } else if (is_array($data)) { + } elseif (is_array($data)) { $root = array_shift($data); $root['level'] = 0; } else { - throw new Doctrine_Tree_Exception("Unexpected data structure returned."); + throw new Doctrine_Tree_Exception('Unexpected data structure returned.'); } return $root; @@ -151,9 +149,10 @@ public function fetchRoot($rootId = 1) /** * Fetches a tree. * - * @param array $options Options - * @param integer $fetchmode One of the Doctrine_Core::HYDRATE_* constants. - * @return mixed The tree or FALSE if the tree could not be found. + * @param array $options Options + * @param mixed|null $hydrationMode + * + * @return mixed the tree or FALSE if the tree could not be found */ public function fetchTree($options = array(), $hydrationMode = null) { @@ -162,19 +161,19 @@ public function fetchTree($options = array(), $hydrationMode = null) $depth = isset($options['depth']) ? $options['depth'] : null; - $q->addWhere($this->_baseAlias . ".lft >= ?", 1); + $q->addWhere($this->_baseAlias.'.lft >= ?', 1); // if tree has many roots, then specify root id $rootId = isset($options['root_id']) ? $options['root_id'] : '1'; if (is_array($rootId)) { - $q->addOrderBy($this->_baseAlias . "." . $this->getAttribute('rootColumnName') . - ", " . $this->_baseAlias . ".lft ASC"); + $q->addOrderBy($this->_baseAlias.'.'.$this->getAttribute('rootColumnName'). + ', '.$this->_baseAlias.'.lft ASC'); } else { - $q->addOrderBy($this->_baseAlias . ".lft ASC"); + $q->addOrderBy($this->_baseAlias.'.lft ASC'); } - if ( ! is_null($depth)) { - $q->addWhere($this->_baseAlias . ".level BETWEEN ? AND ?", array(0, $depth)); + if (!is_null($depth)) { + $q->addWhere($this->_baseAlias.'.level BETWEEN ? AND ?', array(0, $depth)); } $q = $this->returnQueryWithRootId($q, $rootId); @@ -191,16 +190,18 @@ public function fetchTree($options = array(), $hydrationMode = null) /** * Fetches a branch of a tree. * - * @param mixed $pk primary key as used by table::find() to locate node to traverse tree from - * @param array $options Options. - * @param integer $fetchmode One of the Doctrine_Core::HYDRATE_* constants. - * @return mixed The branch or FALSE if the branch could not be found. + * @param mixed $pk primary key as used by table::find() to locate node to traverse tree from + * @param array $options options + * @param mixed|null $hydrationMode + * + * @return mixed the branch or FALSE if the branch could not be found + * * @todo Only fetch the lft and rgt values of the initial record. more is not needed. */ public function fetchBranch($pk, $options = array(), $hydrationMode = null) { $record = $this->table->find($pk); - if ( ! ($record instanceof Doctrine_Record) || !$record->exists()) { + if (!($record instanceof Doctrine_Record) || !$record->exists()) { // TODO: if record doesn't exist, throw exception or similar? return false; } @@ -209,11 +210,12 @@ public function fetchBranch($pk, $options = array(), $hydrationMode = null) $q = $this->getBaseQuery(); $params = array($record->get('lft'), $record->get('rgt')); - $q->addWhere($this->_baseAlias . ".lft >= ? AND " . $this->_baseAlias . ".rgt <= ?", $params) - ->addOrderBy($this->_baseAlias . ".lft asc"); + $q->addWhere($this->_baseAlias.'.lft >= ? AND '.$this->_baseAlias.'.rgt <= ?', $params) + ->addOrderBy($this->_baseAlias.'.lft asc') + ; - if ( ! is_null($depth)) { - $q->addWhere($this->_baseAlias . ".level BETWEEN ? AND ?", array($record->get('level'), $record->get('level')+$depth)); + if (!is_null($depth)) { + $q->addWhere($this->_baseAlias.'.level BETWEEN ? AND ?', array($record->get('level'), $record->get('level') + $depth)); } $q = $this->returnQueryWithRootId($q, $record->getNode()->getRootValue()); @@ -225,30 +227,31 @@ public function fetchBranch($pk, $options = array(), $hydrationMode = null) * Fetches all root nodes. If the tree has only one root this is the same as * fetchRoot(). * - * @return mixed The root nodes. + * @return mixed the root nodes */ public function fetchRoots() { $q = $this->getBaseQuery(); - $q = $q->addWhere($this->_baseAlias . '.lft = ?', 1); + $q = $q->addWhere($this->_baseAlias.'.lft = ?', 1); + return $q->execute(); } /** - * returns parsed query with root id where clause added if applicable + * returns parsed query with root id where clause added if applicable. + * + * @param object $query Doctrine_Query * - * @param object $query Doctrine_Query - * @param integer $root_id id of destination root * @return Doctrine_Query */ public function returnQueryWithRootId($query, $rootId = 1) { if ($root = $this->getAttribute('rootColumnName')) { if (is_array($rootId)) { - $query->addWhere($root . ' IN (' . implode(',', array_fill(0, count($rootId), '?')) . ')', - $rootId); + $query->addWhere($root.' IN ('.implode(',', array_fill(0, count($rootId), '?')).')', + $rootId); } else { - $query->addWhere($root . ' = ?', $rootId); + $query->addWhere($root.' = ?', $rootId); } } @@ -258,20 +261,19 @@ public function returnQueryWithRootId($query, $rootId = 1) /** * Enter description here... * - * @param array $options * @return unknown */ public function getBaseQuery() { - if ( ! isset($this->_baseQuery)) { + if (!isset($this->_baseQuery)) { $this->_baseQuery = $this->_createBaseQuery(); } + return $this->_baseQuery->copy(); } /** * Enter description here... - * */ public function getBaseAlias() { @@ -280,35 +282,32 @@ public function getBaseAlias() /** * Enter description here... - * */ private function _createBaseQuery() { - $this->_baseAlias = "base"; - $q = Doctrine_Core::getTable($this->getBaseComponent()) + $this->_baseAlias = 'base'; + + return Doctrine_Core::getTable($this->getBaseComponent()) ->createQuery($this->_baseAlias) - ->select($this->_baseAlias . '.*'); - return $q; + ->select($this->_baseAlias.'.*') + ; } /** * Enter description here... - * - * @param Doctrine_Query $query */ public function setBaseQuery(Doctrine_Query $query) { $this->_baseAlias = $query->getRootAlias(); - $query->addSelect($this->_baseAlias . ".lft, " . $this->_baseAlias . ".rgt, ". $this->_baseAlias . ".level"); + $query->addSelect($this->_baseAlias.'.lft, '.$this->_baseAlias.'.rgt, '.$this->_baseAlias.'.level'); if ($this->getAttribute('rootColumnName')) { - $query->addSelect($this->_baseAlias . "." . $this->getAttribute('rootColumnName')); + $query->addSelect($this->_baseAlias.'.'.$this->getAttribute('rootColumnName')); } $this->_baseQuery = $query; } /** * Enter description here... - * */ public function resetBaseQuery() { diff --git a/lib/Doctrine/Util.php b/lib/Doctrine/Util.php index 2001bae29..d4ecd63c8 100644 --- a/lib/Doctrine/Util.php +++ b/lib/Doctrine/Util.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Util + * Doctrine_Util. * - * @package Doctrine - * @subpackage Util * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Util extends Doctrine_Connection_Module -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Validator.php b/lib/Doctrine/Validator.php index bab8fe82c..903ce771c 100644 --- a/lib/Doctrine/Validator.php +++ b/lib/Doctrine/Validator.php @@ -20,51 +20,50 @@ */ /** - * This class is responsible for performing all validations on record properties + * This class is responsible for performing all validations on record properties. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Roman Borschel * @author Konsta Vesterinen */ class Doctrine_Validator extends Doctrine_Locator_Injectable { /** - * @var array $validators an array of validator objects + * @var array an array of validator objects */ private static $validators = array(); /** - * Get a validator instance for the passed $name + * Get a validator instance for the passed $name. + * + * @param string $name Name of the validator or the validator class name * - * @param string $name Name of the validator or the validator class name * @return Doctrine_Validator_Interface $validator */ public static function getValidator($name) { - if ( ! isset(self::$validators[$name])) { - $class = 'Doctrine_Validator_' . ucwords(strtolower($name)); + if (!isset(self::$validators[$name])) { + $class = 'Doctrine_Validator_'.ucwords(strtolower($name)); if (class_exists($class)) { - self::$validators[$name] = new $class; - } else if (class_exists($name)) { - self::$validators[$name] = new $name; + self::$validators[$name] = new $class(); + } elseif (class_exists($name)) { + self::$validators[$name] = new $name(); } else { - throw new Doctrine_Exception("Validator named '$name' not available."); + throw new Doctrine_Exception("Validator named '{$name}' not available."); } - } + return self::$validators[$name]; } /** - * Validates a given record and saves possible errors in Doctrine_Validator::$stack - * - * @param Doctrine_Record $record - * @return void + * Validates a given record and saves possible errors in Doctrine_Validator::$stack. */ public function validateRecord(Doctrine_Record $record) { @@ -72,7 +71,7 @@ public function validateRecord(Doctrine_Record $record) // if record is transient all fields will be validated // if record is persistent only the modified fields will be validated - $fields = $record->exists() ? $record->getModified():$record->getData(); + $fields = $record->exists() ? $record->getModified() : $record->getData(); foreach ($fields as $fieldName => $value) { $table->validateField($fieldName, $value, $record); } @@ -82,21 +81,23 @@ public function validateRecord(Doctrine_Record $record) /** * Validates the length of a field. * - * @param string $value Value to validate - * @param string $type Type of field being validated - * @param string $maximumLength Maximum length allowed for the column - * @return boolean $success True/false for whether the value passed validation + * @param string $value Value to validate + * @param string $type Type of field being validated + * @param string $maximumLength Maximum length allowed for the column + * + * @return bool $success True/false for whether the value passed validation */ public static function validateLength($value, $type, $maximumLength) { - if ($maximumLength === null ) { + if (null === $maximumLength) { return true; } - if ($type == 'timestamp' || $type == 'integer' || $type == 'enum') { + if ('timestamp' == $type || 'integer' == $type || 'enum' == $type) { return true; - } else if ($type == 'array' || $type == 'object') { + } + if ('array' == $type || 'object' == $type) { $length = strlen(serialize($value)); - } else if ($type == 'decimal' || $type == 'float') { + } elseif ('decimal' == $type || 'float' == $type) { $value = abs($value); $localeInfo = localeconv(); @@ -108,7 +109,7 @@ public static function validateLength($value, $type, $maximumLength) if (isset($e[1])) { $length += strlen($e[1]); } - } else if ($type === 'blob') { + } elseif ('blob' === $type) { $length = strlen($value); } else { $length = self::getStringLength($value); @@ -118,36 +119,38 @@ public static function validateLength($value, $type, $maximumLength) } /** - * Get length of passed string. Will use multibyte character functions if they exist + * Get length of passed string. Will use multibyte character functions if they exist. * * @param string $string - * @return integer $length + * + * @return int $length */ public static function getStringLength($string) { if (function_exists('mb_strlen')) { return mb_strlen((string) $string, 'utf8'); - } else { - return strlen(utf8_decode((string) $string)); } + + return strlen(utf8_decode((string) $string)); } /** - * Whether or not errors exist on this validator + * Whether or not errors exist on this validator. * - * @return boolean True/false for whether or not this validate instance has error + * @return bool True/false for whether or not this validate instance has error */ public function hasErrors() { - return (count($this->stack) > 0); + return count($this->stack) > 0; } /** - * Validate the type of the passed variable + * Validate the type of the passed variable. * - * @param mixed $var Variable to validate - * @param string $type Type of the variable expected - * @return boolean + * @param mixed $var Variable to validate + * @param string $type Type of the variable expected + * + * @return bool */ public static function isValidType($var, $type) { @@ -155,16 +158,16 @@ public static function isValidType($var, $type) return true; } - if ($var === null) { + if (null === $var) { return true; } if (is_array($var)) { - return $type === 'array'; + return 'array' === $type; } if (is_object($var)) { - return $type === 'object'; + return 'object' === $type; } switch ($type) { @@ -173,7 +176,7 @@ public static function isValidType($var, $type) case 'decimal': return (string) $var == (string) (float) $var; case 'integer': - return (string) $var === (string)round((float) $var); + return (string) $var === (string) round((float) $var); case 'string': return is_string($var) || is_numeric($var); case 'blob': @@ -186,15 +189,18 @@ public static function isValidType($var, $type) case 'object': return is_object($var); case 'boolean': - return is_bool($var) || (is_numeric($var) && ($var == 0 || $var == 1)); + return is_bool($var) || (is_numeric($var) && (0 == $var || 1 == $var)); case 'timestamp': $validator = self::getValidator('timestamp'); + return $validator->validate($var); case 'time': $validator = self::getValidator('time'); + return $validator->validate($var); case 'date': $validator = self::getValidator('date'); + return $validator->validate($var); case 'enum': return is_string($var) || is_int($var); diff --git a/lib/Doctrine/Validator/Country.php b/lib/Doctrine/Validator/Country.php index 2029721a8..01146d536 100644 --- a/lib/Doctrine/Validator/Country.php +++ b/lib/Doctrine/Validator/Country.php @@ -20,265 +20,266 @@ */ /** - * Doctrine_Validator_Country + * Doctrine_Validator_Country. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Country extends Doctrine_Validator_Driver { private static $countries = array( - 'ad' => 'Andorra', - 'ae' => 'United Arab Emirates', - 'af' => 'Afghanistan', - 'ag' => 'Antigua and Barbuda', - 'ai' => 'Anguilla', - 'al' => 'Albania', - 'am' => 'Armenia', - 'an' => 'Netherlands Antilles', - 'ao' => 'Angola', - 'aq' => 'Antarctica', - 'ar' => 'Argentina', - 'as' => 'American Samoa', - 'at' => 'Austria', - 'au' => 'Australia', - 'aw' => 'Aruba', - 'az' => 'Azerbaijan', - 'ba' => 'Bosnia Hercegovina', - 'bb' => 'Barbados', - 'bd' => 'Bangladesh', - 'be' => 'Belgium', - 'bf' => 'Burkina Faso', - 'bg' => 'Bulgaria', - 'bh' => 'Bahrain', - 'bi' => 'Burundi', - 'bj' => 'Benin', - 'bm' => 'Bermuda', - 'bn' => 'Brunei Darussalam', - 'bo' => 'Bolivia', - 'br' => 'Brazil', - 'bs' => 'Bahamas', - 'bt' => 'Bhutan', - 'bv' => 'Bouvet Island', - 'bw' => 'Botswana', - 'by' => 'Belarus (Byelorussia)', - 'bz' => 'Belize', - 'ca' => 'Canada', - 'cc' => 'Cocos Islands', - 'cd' => 'Congo, The Democratic Republic of the', - 'cf' => 'Central African Republic', - 'cg' => 'Congo', - 'ch' => 'Switzerland', - 'ci' => 'Ivory Coast', - 'ck' => 'Cook Islands', - 'cl' => 'Chile', - 'cm' => 'Cameroon', - 'cn' => 'China', - 'co' => 'Colombia', - 'cr' => 'Costa Rica', - 'cs' => 'Czechoslovakia', - 'cu' => 'Cuba', - 'cv' => 'Cape Verde', - 'cx' => 'Christmas Island', - 'cy' => 'Cyprus', - 'cz' => 'Czech Republic', - 'de' => 'Germany', - 'dj' => 'Djibouti', - 'dk' => 'Denmark', - 'dm' => 'Dominica', - 'do' => 'Dominican Republic', - 'dz' => 'Algeria', - 'ec' => 'Ecuador', - 'ee' => 'Estonia', - 'eg' => 'Egypt', - 'eh' => 'Western Sahara', - 'er' => 'Eritrea', - 'es' => 'Spain', - 'et' => 'Ethiopia', - 'fi' => 'Finland', - 'fj' => 'Fiji', - 'fk' => 'Falkland Islands', - 'fm' => 'Micronesia', - 'fo' => 'Faroe Islands', - 'fr' => 'France', - 'fx' => 'France, Metropolitan FX', - 'ga' => 'Gabon', - 'gb' => 'United Kingdom (Great Britain)', - 'gd' => 'Grenada', - 'ge' => 'Georgia', - 'gf' => 'French Guiana', - 'gh' => 'Ghana', - 'gi' => 'Gibraltar', - 'gl' => 'Greenland', - 'gm' => 'Gambia', - 'gn' => 'Guinea', - 'gp' => 'Guadeloupe', - 'gq' => 'Equatorial Guinea', - 'gr' => 'Greece', - 'gs' => 'South Georgia and the South Sandwich Islands', - 'gt' => 'Guatemala', - 'gu' => 'Guam', - 'gw' => 'Guinea-bissau', - 'gy' => 'Guyana', - 'hk' => 'Hong Kong', - 'hm' => 'Heard and McDonald Islands', - 'hn' => 'Honduras', - 'hr' => 'Croatia', - 'ht' => 'Haiti', - 'hu' => 'Hungary', - 'id' => 'Indonesia', - 'ie' => 'Ireland', - 'il' => 'Israel', - 'in' => 'India', - 'io' => 'British Indian Ocean Territory', - 'iq' => 'Iraq', - 'ir' => 'Iran', - 'is' => 'Iceland', - 'it' => 'Italy', - 'jm' => 'Jamaica', - 'jo' => 'Jordan', - 'jp' => 'Japan', - 'ke' => 'Kenya', - 'kg' => 'Kyrgyzstan', - 'kh' => 'Cambodia', - 'ki' => 'Kiribati', - 'km' => 'Comoros', - 'kn' => 'Saint Kitts and Nevis', - 'kp' => 'North Korea', - 'kr' => 'South Korea', - 'kw' => 'Kuwait', - 'ky' => 'Cayman Islands', - 'kz' => 'Kazakhstan', - 'la' => 'Laos', - 'lb' => 'Lebanon', - 'lc' => 'Saint Lucia', - 'li' => 'Lichtenstein', - 'lk' => 'Sri Lanka', - 'lr' => 'Liberia', - 'ls' => 'Lesotho', - 'lt' => 'Lithuania', - 'lu' => 'Luxembourg', - 'lv' => 'Latvia', - 'ly' => 'Libya', - 'ma' => 'Morocco', - 'mc' => 'Monaco', - 'md' => 'Moldova Republic', - 'mg' => 'Madagascar', - 'mh' => 'Marshall Islands', - 'mk' => 'Macedonia, The Former Yugoslav Republic of', - 'ml' => 'Mali', - 'mm' => 'Myanmar', - 'mn' => 'Mongolia', - 'mo' => 'Macau', - 'mp' => 'Northern Mariana Islands', - 'mq' => 'Martinique', - 'mr' => 'Mauritania', - 'ms' => 'Montserrat', - 'mt' => 'Malta', - 'mu' => 'Mauritius', - 'mv' => 'Maldives', - 'mw' => 'Malawi', - 'mx' => 'Mexico', - 'my' => 'Malaysia', - 'mz' => 'Mozambique', - 'na' => 'Namibia', - 'nc' => 'New Caledonia', - 'ne' => 'Niger', - 'nf' => 'Norfolk Island', - 'ng' => 'Nigeria', - 'ni' => 'Nicaragua', - 'nl' => 'Netherlands', - 'no' => 'Norway', - 'np' => 'Nepal', - 'nr' => 'Nauru', - 'nt' => 'Neutral Zone', - 'nu' => 'Niue', - 'nz' => 'New Zealand', - 'om' => 'Oman', - 'pa' => 'Panama', - 'pe' => 'Peru', - 'pf' => 'French Polynesia', - 'pg' => 'Papua New Guinea', - 'ph' => 'Philippines', - 'pk' => 'Pakistan', - 'pl' => 'Poland', - 'pm' => 'St. Pierre and Miquelon', - 'pn' => 'Pitcairn', - 'pr' => 'Puerto Rico', - 'pt' => 'Portugal', - 'pw' => 'Palau', - 'py' => 'Paraguay', - 'qa' => 'Qatar', - 're' => 'Reunion', - 'ro' => 'Romania', - 'ru' => 'Russia', - 'rw' => 'Rwanda', - 'sa' => 'Saudi Arabia', - 'sb' => 'Solomon Islands', - 'sc' => 'Seychelles', - 'sd' => 'Sudan', - 'se' => 'Sweden', - 'sg' => 'Singapore', - 'sh' => 'St. Helena', - 'si' => 'Slovenia', - 'sj' => 'Svalbard and Jan Mayen Islands', - 'sk' => 'Slovakia (Slovak Republic)', - 'sl' => 'Sierra Leone', - 'sm' => 'San Marino', - 'sn' => 'Senegal', - 'so' => 'Somalia', - 'sr' => 'Suriname', - 'st' => 'Sao Tome and Principe', - 'sv' => 'El Salvador', - 'sy' => 'Syria', - 'sz' => 'Swaziland', - 'tc' => 'Turks and Caicos Islands', - 'td' => 'Chad', - 'tf' => 'French Southern Territories', - 'tg' => 'Togo', - 'th' => 'Thailand', - 'tj' => 'Tajikistan', - 'tk' => 'Tokelau', - 'tm' => 'Turkmenistan', - 'tn' => 'Tunisia', - 'to' => 'Tonga', - 'tp' => 'East Timor', - 'tr' => 'Turkey', - 'tt' => 'Trinidad, Tobago', - 'tv' => 'Tuvalu', - 'tw' => 'Taiwan', - 'tz' => 'Tanzania', - 'ua' => 'Ukraine', - 'ug' => 'Uganda', - 'uk' => 'United Kingdom', - 'um' => 'United States Minor Islands', - 'us' => 'United States of America', - 'uy' => 'Uruguay', - 'uz' => 'Uzbekistan', - 'va' => 'Vatican City', - 'vc' => 'Saint Vincent, Grenadines', - 've' => 'Venezuela', - 'vg' => 'Virgin Islands (British)', - 'vi' => 'Virgin Islands (USA)', - 'vn' => 'Viet Nam', - 'vu' => 'Vanuatu', - 'wf' => 'Wallis and Futuna Islands', - 'ws' => 'Samoa', - 'ye' => 'Yemen', - 'yt' => 'Mayotte', - 'yu' => 'Yugoslavia', - 'za' => 'South Africa', - 'zm' => 'Zambia', - 'zr' => 'Zaire', - 'zw' => 'Zimbabwe'); + 'ad' => 'Andorra', + 'ae' => 'United Arab Emirates', + 'af' => 'Afghanistan', + 'ag' => 'Antigua and Barbuda', + 'ai' => 'Anguilla', + 'al' => 'Albania', + 'am' => 'Armenia', + 'an' => 'Netherlands Antilles', + 'ao' => 'Angola', + 'aq' => 'Antarctica', + 'ar' => 'Argentina', + 'as' => 'American Samoa', + 'at' => 'Austria', + 'au' => 'Australia', + 'aw' => 'Aruba', + 'az' => 'Azerbaijan', + 'ba' => 'Bosnia Hercegovina', + 'bb' => 'Barbados', + 'bd' => 'Bangladesh', + 'be' => 'Belgium', + 'bf' => 'Burkina Faso', + 'bg' => 'Bulgaria', + 'bh' => 'Bahrain', + 'bi' => 'Burundi', + 'bj' => 'Benin', + 'bm' => 'Bermuda', + 'bn' => 'Brunei Darussalam', + 'bo' => 'Bolivia', + 'br' => 'Brazil', + 'bs' => 'Bahamas', + 'bt' => 'Bhutan', + 'bv' => 'Bouvet Island', + 'bw' => 'Botswana', + 'by' => 'Belarus (Byelorussia)', + 'bz' => 'Belize', + 'ca' => 'Canada', + 'cc' => 'Cocos Islands', + 'cd' => 'Congo, The Democratic Republic of the', + 'cf' => 'Central African Republic', + 'cg' => 'Congo', + 'ch' => 'Switzerland', + 'ci' => 'Ivory Coast', + 'ck' => 'Cook Islands', + 'cl' => 'Chile', + 'cm' => 'Cameroon', + 'cn' => 'China', + 'co' => 'Colombia', + 'cr' => 'Costa Rica', + 'cs' => 'Czechoslovakia', + 'cu' => 'Cuba', + 'cv' => 'Cape Verde', + 'cx' => 'Christmas Island', + 'cy' => 'Cyprus', + 'cz' => 'Czech Republic', + 'de' => 'Germany', + 'dj' => 'Djibouti', + 'dk' => 'Denmark', + 'dm' => 'Dominica', + 'do' => 'Dominican Republic', + 'dz' => 'Algeria', + 'ec' => 'Ecuador', + 'ee' => 'Estonia', + 'eg' => 'Egypt', + 'eh' => 'Western Sahara', + 'er' => 'Eritrea', + 'es' => 'Spain', + 'et' => 'Ethiopia', + 'fi' => 'Finland', + 'fj' => 'Fiji', + 'fk' => 'Falkland Islands', + 'fm' => 'Micronesia', + 'fo' => 'Faroe Islands', + 'fr' => 'France', + 'fx' => 'France, Metropolitan FX', + 'ga' => 'Gabon', + 'gb' => 'United Kingdom (Great Britain)', + 'gd' => 'Grenada', + 'ge' => 'Georgia', + 'gf' => 'French Guiana', + 'gh' => 'Ghana', + 'gi' => 'Gibraltar', + 'gl' => 'Greenland', + 'gm' => 'Gambia', + 'gn' => 'Guinea', + 'gp' => 'Guadeloupe', + 'gq' => 'Equatorial Guinea', + 'gr' => 'Greece', + 'gs' => 'South Georgia and the South Sandwich Islands', + 'gt' => 'Guatemala', + 'gu' => 'Guam', + 'gw' => 'Guinea-bissau', + 'gy' => 'Guyana', + 'hk' => 'Hong Kong', + 'hm' => 'Heard and McDonald Islands', + 'hn' => 'Honduras', + 'hr' => 'Croatia', + 'ht' => 'Haiti', + 'hu' => 'Hungary', + 'id' => 'Indonesia', + 'ie' => 'Ireland', + 'il' => 'Israel', + 'in' => 'India', + 'io' => 'British Indian Ocean Territory', + 'iq' => 'Iraq', + 'ir' => 'Iran', + 'is' => 'Iceland', + 'it' => 'Italy', + 'jm' => 'Jamaica', + 'jo' => 'Jordan', + 'jp' => 'Japan', + 'ke' => 'Kenya', + 'kg' => 'Kyrgyzstan', + 'kh' => 'Cambodia', + 'ki' => 'Kiribati', + 'km' => 'Comoros', + 'kn' => 'Saint Kitts and Nevis', + 'kp' => 'North Korea', + 'kr' => 'South Korea', + 'kw' => 'Kuwait', + 'ky' => 'Cayman Islands', + 'kz' => 'Kazakhstan', + 'la' => 'Laos', + 'lb' => 'Lebanon', + 'lc' => 'Saint Lucia', + 'li' => 'Lichtenstein', + 'lk' => 'Sri Lanka', + 'lr' => 'Liberia', + 'ls' => 'Lesotho', + 'lt' => 'Lithuania', + 'lu' => 'Luxembourg', + 'lv' => 'Latvia', + 'ly' => 'Libya', + 'ma' => 'Morocco', + 'mc' => 'Monaco', + 'md' => 'Moldova Republic', + 'mg' => 'Madagascar', + 'mh' => 'Marshall Islands', + 'mk' => 'Macedonia, The Former Yugoslav Republic of', + 'ml' => 'Mali', + 'mm' => 'Myanmar', + 'mn' => 'Mongolia', + 'mo' => 'Macau', + 'mp' => 'Northern Mariana Islands', + 'mq' => 'Martinique', + 'mr' => 'Mauritania', + 'ms' => 'Montserrat', + 'mt' => 'Malta', + 'mu' => 'Mauritius', + 'mv' => 'Maldives', + 'mw' => 'Malawi', + 'mx' => 'Mexico', + 'my' => 'Malaysia', + 'mz' => 'Mozambique', + 'na' => 'Namibia', + 'nc' => 'New Caledonia', + 'ne' => 'Niger', + 'nf' => 'Norfolk Island', + 'ng' => 'Nigeria', + 'ni' => 'Nicaragua', + 'nl' => 'Netherlands', + 'no' => 'Norway', + 'np' => 'Nepal', + 'nr' => 'Nauru', + 'nt' => 'Neutral Zone', + 'nu' => 'Niue', + 'nz' => 'New Zealand', + 'om' => 'Oman', + 'pa' => 'Panama', + 'pe' => 'Peru', + 'pf' => 'French Polynesia', + 'pg' => 'Papua New Guinea', + 'ph' => 'Philippines', + 'pk' => 'Pakistan', + 'pl' => 'Poland', + 'pm' => 'St. Pierre and Miquelon', + 'pn' => 'Pitcairn', + 'pr' => 'Puerto Rico', + 'pt' => 'Portugal', + 'pw' => 'Palau', + 'py' => 'Paraguay', + 'qa' => 'Qatar', + 're' => 'Reunion', + 'ro' => 'Romania', + 'ru' => 'Russia', + 'rw' => 'Rwanda', + 'sa' => 'Saudi Arabia', + 'sb' => 'Solomon Islands', + 'sc' => 'Seychelles', + 'sd' => 'Sudan', + 'se' => 'Sweden', + 'sg' => 'Singapore', + 'sh' => 'St. Helena', + 'si' => 'Slovenia', + 'sj' => 'Svalbard and Jan Mayen Islands', + 'sk' => 'Slovakia (Slovak Republic)', + 'sl' => 'Sierra Leone', + 'sm' => 'San Marino', + 'sn' => 'Senegal', + 'so' => 'Somalia', + 'sr' => 'Suriname', + 'st' => 'Sao Tome and Principe', + 'sv' => 'El Salvador', + 'sy' => 'Syria', + 'sz' => 'Swaziland', + 'tc' => 'Turks and Caicos Islands', + 'td' => 'Chad', + 'tf' => 'French Southern Territories', + 'tg' => 'Togo', + 'th' => 'Thailand', + 'tj' => 'Tajikistan', + 'tk' => 'Tokelau', + 'tm' => 'Turkmenistan', + 'tn' => 'Tunisia', + 'to' => 'Tonga', + 'tp' => 'East Timor', + 'tr' => 'Turkey', + 'tt' => 'Trinidad, Tobago', + 'tv' => 'Tuvalu', + 'tw' => 'Taiwan', + 'tz' => 'Tanzania', + 'ua' => 'Ukraine', + 'ug' => 'Uganda', + 'uk' => 'United Kingdom', + 'um' => 'United States Minor Islands', + 'us' => 'United States of America', + 'uy' => 'Uruguay', + 'uz' => 'Uzbekistan', + 'va' => 'Vatican City', + 'vc' => 'Saint Vincent, Grenadines', + 've' => 'Venezuela', + 'vg' => 'Virgin Islands (British)', + 'vi' => 'Virgin Islands (USA)', + 'vn' => 'Viet Nam', + 'vu' => 'Vanuatu', + 'wf' => 'Wallis and Futuna Islands', + 'ws' => 'Samoa', + 'ye' => 'Yemen', + 'yt' => 'Mayotte', + 'yu' => 'Yugoslavia', + 'za' => 'South Africa', + 'zm' => 'Zambia', + 'zr' => 'Zaire', + 'zw' => 'Zimbabwe'); /** - * returns all available country codes + * returns all available country codes. * * @return array */ @@ -288,10 +289,9 @@ public static function getCountries() } /** - * checks if given value is a valid country code + * checks if given value is a valid country code. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -302,4 +302,4 @@ public function validate($value) return isset(self::$countries[$value]); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Creditcard.php b/lib/Doctrine/Validator/Creditcard.php index 82d64c979..00c59813e 100644 --- a/lib/Doctrine/Validator/Creditcard.php +++ b/lib/Doctrine/Validator/Creditcard.php @@ -20,66 +20,67 @@ */ /** - * Doctrine_Validator_Creditcard + * Doctrine_Validator_Creditcard. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Creditcard extends Doctrine_Validator_Driver -{ +{ /** - * checks if given value is a valid credit card number + * checks if given value is a valid credit card number. * - * @link http://www.owasp.org/index.php/OWASP_Validation_Regex_Repository - * @param mixed $value - * @return boolean + * @see http://www.owasp.org/index.php/OWASP_Validation_Regex_Repository + * + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } - $cardType = ""; + $cardType = ''; $card_regexes = array( - "/^4\d{12}(\d\d\d){0,1}$/" => 'visa', - "/^5[12345]\d{14}$/" => 'mastercard', - "/^3[47]\d{13}$/" => 'amex', - "/^6011\d{12}$/" => 'discover', - "/^30[012345]\d{11}$/" => 'diners', - "/^3[68]\d{12}$/" => 'diners', + '/^4\\d{12}(\\d\\d\\d){0,1}$/' => 'visa', + '/^5[12345]\\d{14}$/' => 'mastercard', + '/^3[47]\\d{13}$/' => 'amex', + '/^6011\\d{12}$/' => 'discover', + '/^30[012345]\\d{11}$/' => 'diners', + '/^3[68]\\d{12}$/' => 'diners', ); foreach ($card_regexes as $regex => $type) { if (preg_match($regex, $value)) { - $cardType = $type; - break; + $cardType = $type; + break; } } - if ( ! $cardType) { + if (!$cardType) { return false; } /* mod 10 checksum algorithm */ $revcode = strrev($value); $checksum = 0; - for ($i = 0; $i < strlen($revcode); $i++) { + for ($i = 0; $i < strlen($revcode); ++$i) { $currentNum = intval($revcode[$i]); if ($i & 1) { /* Odd position */ - $currentNum *= 2; + $currentNum *= 2; } /* Split digits and add. */ $checksum += $currentNum % 10; if ($currentNum > 9) { - $checksum += 1; + ++$checksum; } } - if ($checksum % 10 == 0) { + if (0 == $checksum % 10) { return true; - } else { - return false; } + + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Date.php b/lib/Doctrine/Validator/Date.php index 7173191e4..a2f653842 100644 --- a/lib/Doctrine/Validator/Date.php +++ b/lib/Doctrine/Validator/Date.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Validator_Date + * Doctrine_Validator_Date. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Date extends Doctrine_Validator_Driver { /** - * checks if given value is a valid date + * checks if given value is a valid date. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -45,11 +45,12 @@ public function validate($value) } $e = explode('-', $value); - if (count($e) !== 3) { + if (3 !== count($e)) { return false; } $e2 = explode(' ', $e[2]); $e[2] = $e2[0]; + return checkdate($e[1], $e[2], $e[0]); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Driver.php b/lib/Doctrine/Validator/Driver.php index 97a989828..34a28bf04 100644 --- a/lib/Doctrine/Validator/Driver.php +++ b/lib/Doctrine/Validator/Driver.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Validator_Driver + * Doctrine_Validator_Driver. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Driver { /** - * @var array $_args an array of plugin specific args + * @var array an array of plugin specific args */ public $args; public $invoker; @@ -41,7 +42,7 @@ class Doctrine_Validator_Driver /** * __get - * an alias for getOption + * an alias for getOption. * * @param string $arg */ @@ -50,11 +51,12 @@ public function __get($arg) if (isset($this->args[$arg])) { return $this->args[$arg]; } + return null; } /** - * __isset + * __isset. * * @param string $arg */ @@ -64,52 +66,55 @@ public function __isset($arg) } /** - * sets given value to an argument + * sets given value to an argument. + * + * @param $arg the name of the option to be changed + * @param $value the value of the option * - * @param $arg the name of the option to be changed - * @param $value the value of the option - * @return Doctrine_Validator_Driver this object + * @return Doctrine_Validator_Driver this object */ public function __set($arg, $value) { $this->args[$arg] = $value; - + return $this; } /** - * returns the value of an argument + * returns the value of an argument. * - * @param $arg the name of the option to retrieve - * @return mixed the value of the option + * @param $arg the name of the option to retrieve + * + * @return mixed the value of the option */ public function getArg($arg) { - if ( ! isset($this->args[$arg])) { - throw new Doctrine_Validator_Exception('Unknown option ' . $arg); + if (!isset($this->args[$arg])) { + throw new Doctrine_Validator_Exception('Unknown option '.$arg); } - + return $this->args[$arg]; } /** - * sets given value to an argument + * sets given value to an argument. + * + * @param $arg the name of the option to be changed + * @param $value the value of the option * - * @param $arg the name of the option to be changed - * @param $value the value of the option - * @return Doctrine_Validator_Driver this object + * @return Doctrine_Validator_Driver this object */ public function setArg($arg, $value) { $this->args[$arg] = $value; - + return $this; } /** - * returns all args and their associated values + * returns all args and their associated values. * - * @return array all args as an associative array + * @return array all args as an associative array */ public function getArgs() { @@ -119,10 +124,10 @@ public function getArgs() public function __toString() { $className = get_class($this); - if (strpos($className, 'Doctrine_Validator_') === 0) { + if (0 === strpos($className, 'Doctrine_Validator_')) { return strtolower(substr($className, 19)); - } else { - return $className; } + + return $className; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Email.php b/lib/Doctrine/Validator/Email.php index e15c21824..e35ba304d 100644 --- a/lib/Doctrine/Validator/Email.php +++ b/lib/Doctrine/Validator/Email.php @@ -20,24 +20,25 @@ */ /** - * Doctrine_Validator_Email + * Doctrine_Validator_Email. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Email extends Doctrine_Validator_Driver { /** - * checks if given value is a valid email address + * checks if given value is a valid email address. + * + * @see http://iamcal.com/publish/articles/php/parsing_email/pdf/ * - * @link http://iamcal.com/publish/articles/php/parsing_email/pdf/ - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -45,10 +46,10 @@ public function validate($value) return true; } - if (isset($this->args) && (! isset($this->args['check_mx']) || $this->args['check_mx'] == true)) { + if (isset($this->args) && (!isset($this->args['check_mx']) || true == $this->args['check_mx'])) { $parts = explode('@', $value); - if (isset($parts[1]) && $parts[1] && ! $this->_checkMX($parts[1])) { + if (isset($parts[1]) && $parts[1] && !$this->_checkMX($parts[1])) { return false; } } @@ -56,7 +57,7 @@ public function validate($value) $e = explode('.', $value); $tld = end($e); - if (preg_match("/[^a-zA-Z]/", $tld)) { + if (preg_match('/[^a-zA-Z]/', $tld)) { return false; } @@ -64,13 +65,13 @@ public function validate($value) $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; $quotedPair = '\\x5c[\\x00-\\x7f]'; - $domainLiteral = "\\x5b($dtext|$quotedPair)*\\x5d"; - $quotedString = "\\x22($qtext|$quotedPair)*\\x22"; + $domainLiteral = "\\x5b({$dtext}|{$quotedPair})*\\x5d"; + $quotedString = "\\x22({$qtext}|{$quotedPair})*\\x22"; $domainRef = $atom; - $subDomain = "($domainRef|$domainLiteral)"; - $word = "($atom|$quotedString)"; - $domain = "$subDomain(\\x2e$subDomain)+"; - + $subDomain = "({$domainRef}|{$domainLiteral})"; + $word = "({$atom}|{$quotedString})"; + $domain = "{$subDomain}(\\x2e{$subDomain})+"; + /* following pseudocode to allow strict checking - ask pookey about this if you're puzzled @@ -78,42 +79,44 @@ public function validate($value) $domain = "$sub_domain(\\x2e$sub_domain)*"; } */ - - $localPart = "$word(\\x2e$word)*"; - $addrSpec = "$localPart\\x40$domain"; - - return (bool) preg_match("!^$addrSpec$!D", $value); + + $localPart = "{$word}(\\x2e{$word})*"; + $addrSpec = "{$localPart}\\x40{$domain}"; + + return (bool) preg_match("!^{$addrSpec}$!D", $value); } - + /** - * Check DNS Records for MX type + * Check DNS Records for MX type. * * @param string $host Host name - * @return boolean + * + * @return bool */ private function _checkMX($host) { // We have different behavior here depending of OS and PHP version - if (strtolower(substr(PHP_OS, 0, 3)) == 'win' && version_compare(PHP_VERSION, '5.3.0', '<')) { + if ('win' == strtolower(substr(PHP_OS, 0, 3)) && version_compare(PHP_VERSION, '5.3.0', '<')) { $output = array(); - - @exec('nslookup -type=MX '.escapeshellcmd($host) . ' 2>&1', $output); - + + @exec('nslookup -type=MX '.escapeshellcmd($host).' 2>&1', $output); + if (empty($output)) { throw new Doctrine_Exception('Unable to execute DNS lookup. Are you sure PHP can call exec()?'); - } + } foreach ($output as $line) { - if (preg_match('/^'.$host.'/', $line)) { - return true; + if (preg_match('/^'.$host.'/', $line)) { + return true; } } - + return false; - } else if (function_exists('checkdnsrr')) { + } + if (function_exists('checkdnsrr')) { return checkdnsrr($host, 'MX'); } - + throw new Doctrine_Exception('Could not retrieve DNS record information. Remove check_mx = true to prevent this warning'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/ErrorStack.php b/lib/Doctrine/Validator/ErrorStack.php index b3f5c41c1..662e5fdaa 100644 --- a/lib/Doctrine/Validator/ErrorStack.php +++ b/lib/Doctrine/Validator/ErrorStack.php @@ -20,15 +20,15 @@ */ /** - * Doctrine_Validator_ErrorStack + * Doctrine_Validator_ErrorStack. * - * @package Doctrine - * @subpackage Validator * @author Konsta Vesterinen * @author Roman Borschel * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Validator_ErrorStack extends Doctrine_Access implements Countable, IteratorAggregate @@ -41,22 +41,21 @@ class Doctrine_Validator_ErrorStack extends Doctrine_Access implements Countable protected $_errors = array(); /** - * Array of validators that failed + * Array of validators that failed. * * @var array */ protected $_validators = array(); /** - * Get model class name for the error stack + * Get model class name for the error stack. * * @var string */ protected $_className; /** - * Constructor - * + * Constructor. */ public function __construct($className) { @@ -68,12 +67,13 @@ public function __construct($className) * * @param string $invalidFieldName * @param string|Doctrine_Validator_Driver $errorCode + * * @throws Doctrine_Exception */ public function add($invalidFieldName, $errorCode = 'general') { if (is_object($errorCode)) { - if ( ! ($errorCode instanceof Doctrine_Validator_Driver)) { + if (!($errorCode instanceof Doctrine_Validator_Driver)) { throw new Doctrine_Exception('Validators must be an instance of Doctrine_Validator_Driver'); } $validator = $errorCode; @@ -100,10 +100,9 @@ public function remove($fieldName) } /** - * Get errors for field + * Get errors for field. * * @param string $fieldName - * @return mixed */ public function get($fieldName) { @@ -111,11 +110,10 @@ public function get($fieldName) } /** - * Alias for add() + * Alias for add(). * * @param string $fieldName * @param string $errorCode - * @return void */ public function set($fieldName, $errorCode) { @@ -123,10 +121,11 @@ public function set($fieldName, $errorCode) } /** - * Check if a field has an error + * Check if a field has an error. * * @param string $fieldName - * @return boolean + * + * @return bool */ public function contains($fieldName) { @@ -135,8 +134,6 @@ public function contains($fieldName) /** * Removes all errors from the stack. - * - * @return void */ public function clear() { @@ -149,7 +146,7 @@ public function clear() * * @return ArrayIterator unknown */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->_errors); @@ -161,18 +158,18 @@ public function toArray() } /** - * Count the number of errors + * Count the number of errors. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_errors); } /** - * Get the classname where the errors occured + * Get the classname where the errors occured. * * @return string */ @@ -182,7 +179,7 @@ public function getClassname() } /** - * Get array of failed validators + * Get array of failed validators. * * @return array */ @@ -190,4 +187,4 @@ public function getValidators() { return $this->_validators; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Exception.php b/lib/Doctrine/Validator/Exception.php index 98d3534fb..f6db1eb19 100644 --- a/lib/Doctrine/Validator/Exception.php +++ b/lib/Doctrine/Validator/Exception.php @@ -20,26 +20,23 @@ */ /** - * Doctrine_Validator_Exception + * Doctrine_Validator_Exception. * - * @package Doctrine - * @subpackage Validator * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Validator_Exception extends Doctrine_Exception implements Countable, IteratorAggregate { /** - * @var array $invalid + * @var array */ private $invalid = array(); - /** - * @param Doctrine_Validator $validator - */ public function __construct(array $invalid) { $this->invalid = $invalid; @@ -51,20 +48,20 @@ public function getInvalidRecords() return $this->invalid; } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->invalid); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->invalid); } /** - * Generate a message with all classes that have exceptions + * Generate a message with all classes that have exceptions. */ private function generateMessage() { @@ -72,14 +69,15 @@ private function generateMessage() foreach ($this->invalid as $record) { $message .= $record->getErrorStackAsString(); } + return $message; } /** - * This method will apply the value of the $function variable as a user_func - * to tall errorstack objects in the exception + * This method will apply the value of the $function variable as a user_func + * to tall errorstack objects in the exception. * - * @param mixed Either string with function name or array with object, + * @param mixed Either string with function name or array with object, * functionname. See call_user_func in php manual for more inforamtion */ public function inspect($function) @@ -88,4 +86,4 @@ public function inspect($function) call_user_func($function, $record->getErrorStack()); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Future.php b/lib/Doctrine/Validator/Future.php index db5d7de79..39b7080d3 100644 --- a/lib/Doctrine/Validator/Future.php +++ b/lib/Doctrine/Validator/Future.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Validator_Future + * Doctrine_Validator_Future. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Roman Borschel */ class Doctrine_Validator_Future extends Doctrine_Validator_Driver @@ -35,8 +36,7 @@ class Doctrine_Validator_Future extends Doctrine_Validator_Driver /** * checks if the given value is a valid date in the future. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -45,14 +45,14 @@ public function validate($value) } $e = explode('-', $value); - if (count($e) !== 3) { + if (3 !== count($e)) { return false; } - + if (is_array($this->args) && isset($this->args['timezone'])) { switch (strtolower($this->args['timezone'])) { case 'gmt': - $now = gmdate("U") - date("Z"); + $now = gmdate('U') - date('Z'); break; default: $now = getdate(); @@ -61,19 +61,21 @@ public function validate($value) } else { $now = getdate(); } - + if ($now['year'] > $e[0]) { return false; - } else if ($now['year'] == $e[0]) { + } + if ($now['year'] == $e[0]) { if ($now['mon'] > $e[1]) { return false; - } else if ($now['mon'] == $e[1]) { + } + if ($now['mon'] == $e[1]) { return $now['mday'] < $e[2]; - } else { - return true; } - } else { + return true; } + + return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/HtmlColor.php b/lib/Doctrine/Validator/HtmlColor.php index a7249bfcb..ac4651669 100644 --- a/lib/Doctrine/Validator/HtmlColor.php +++ b/lib/Doctrine/Validator/HtmlColor.php @@ -20,32 +20,33 @@ */ /** - * Doctrine_Validator_HtmlColor + * Doctrine_Validator_HtmlColor. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_HtmlColor extends Doctrine_Validator_Driver { /** - * checks if given value is a valid html color code + * checks if given value is a valid html color code. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } - if ( ! preg_match("/^#{0,1}[0-9a-fA-F]{6}$/", $value)) { + if (!preg_match('/^#{0,1}[0-9a-fA-F]{6}$/', $value)) { return false; } + return true; } } diff --git a/lib/Doctrine/Validator/Ip.php b/lib/Doctrine/Validator/Ip.php index ab7ce928f..6198ce2a5 100644 --- a/lib/Doctrine/Validator/Ip.php +++ b/lib/Doctrine/Validator/Ip.php @@ -20,26 +20,26 @@ */ /** - * Doctrine_Validator_Ip + * Doctrine_Validator_Ip. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Ip extends Doctrine_Validator_Driver { /** - * checks if given value is valid ip address + * checks if given value is valid ip address. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { return is_null($value) ? true : (bool) filter_var($value, FILTER_VALIDATE_IP); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Minlength.php b/lib/Doctrine/Validator/Minlength.php index 34323fff1..e68c8ebb3 100644 --- a/lib/Doctrine/Validator/Minlength.php +++ b/lib/Doctrine/Validator/Minlength.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Validator_Regexp + * Doctrine_Validator_Regexp. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Gijs van Dulmen */ class Doctrine_Validator_Minlength extends Doctrine_Validator_Driver { /** - * checks if given value is more length than the minimum length required + * checks if given value is more length than the minimum length required. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -49,4 +49,4 @@ public function validate($value) return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Nospace.php b/lib/Doctrine/Validator/Nospace.php index b5585f671..c3032d1fa 100644 --- a/lib/Doctrine/Validator/Nospace.php +++ b/lib/Doctrine/Validator/Nospace.php @@ -20,29 +20,30 @@ */ /** - * Doctrine_Validator_Nospace + * Doctrine_Validator_Nospace. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Nospace extends Doctrine_Validator_Driver { /** - * checks that value doesn't contain any space chars + * checks that value doesn't contain any space chars. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } - return ($value === null || ! preg_match('/\s/', $value)); + + return null === $value || !preg_match('/\s/', $value); } } diff --git a/lib/Doctrine/Validator/Notblank.php b/lib/Doctrine/Validator/Notblank.php index fe6591105..ee9d37071 100644 --- a/lib/Doctrine/Validator/Notblank.php +++ b/lib/Doctrine/Validator/Notblank.php @@ -20,27 +20,27 @@ */ /** - * Doctrine_Validator_Notblank + * Doctrine_Validator_Notblank. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Notblank extends Doctrine_Validator_Driver { /** * checks that value isn't blank - * a value is blank when its either null or contains only space characters + * a value is blank when its either null or contains only space characters. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { - return (null !== $value && '' !== trim($value)); + return null !== $value && '' !== trim($value); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Notnull.php b/lib/Doctrine/Validator/Notnull.php index a0721c805..7a2804180 100644 --- a/lib/Doctrine/Validator/Notnull.php +++ b/lib/Doctrine/Validator/Notnull.php @@ -20,26 +20,26 @@ */ /** - * Doctrine_Validator_Notnull + * Doctrine_Validator_Notnull. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Notnull extends Doctrine_Validator_Driver { /** - * checks that given value isn't null + * checks that given value isn't null. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { - return ($value !== null); + return null !== $value; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Past.php b/lib/Doctrine/Validator/Past.php index f2e6be17f..a3798eb96 100644 --- a/lib/Doctrine/Validator/Past.php +++ b/lib/Doctrine/Validator/Past.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Validator_Past + * Doctrine_Validator_Past. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Roman Borschel */ class Doctrine_Validator_Past extends Doctrine_Validator_Driver @@ -35,8 +36,7 @@ class Doctrine_Validator_Past extends Doctrine_Validator_Driver /** * checks if the given value is a valid date in the past. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -45,14 +45,14 @@ public function validate($value) } $e = explode('-', $value); - if (count($e) !== 3) { + if (3 !== count($e)) { return false; } - + if (is_array($this->args) && isset($this->args['timezone'])) { switch (strtolower($this->args['timezone'])) { case 'gmt': - $now = gmdate("U") - date("Z"); + $now = gmdate('U') - date('Z'); break; default: $now = getdate(); @@ -61,19 +61,21 @@ public function validate($value) } else { $now = getdate(); } - + if ($now['year'] < $e[0]) { return false; - } else if ($now['year'] == $e[0]) { + } + if ($now['year'] == $e[0]) { if ($now['mon'] < $e[1]) { return false; - } else if ($now['mon'] == $e[1]) { + } + if ($now['mon'] == $e[1]) { return $now['mday'] > $e[2]; - } else { - return true; } - } else { + return true; } + + return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Range.php b/lib/Doctrine/Validator/Range.php index 4b160a720..79b229955 100644 --- a/lib/Doctrine/Validator/Range.php +++ b/lib/Doctrine/Validator/Range.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Validator_Range + * Doctrine_Validator_Range. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Range extends Doctrine_Validator_Driver { /** - * checks if value is within given range + * checks if value is within given range. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -49,6 +49,7 @@ public function validate($value) if (isset($this->args[1]) && $value > $this->args[1]) { return false; } + return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Readonly.php b/lib/Doctrine/Validator/Readonly.php index 115d08304..f0977407f 100755 --- a/lib/Doctrine/Validator/Readonly.php +++ b/lib/Doctrine/Validator/Readonly.php @@ -18,26 +18,25 @@ */ /** - * Doctrine_Validator_Readonly + * Doctrine_Validator_Readonly. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org + * * @author Adam Huttler */ class Doctrine_Validator_Readonly extends Doctrine_Validator_Driver { /** - * checks if value has been modified + * checks if value has been modified. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { $modified = $this->invoker->getModified(); - + return array_key_exists($this->field, $modified) ? false : true; } } diff --git a/lib/Doctrine/Validator/Regexp.php b/lib/Doctrine/Validator/Regexp.php index 036b76faf..3ccfe5094 100644 --- a/lib/Doctrine/Validator/Regexp.php +++ b/lib/Doctrine/Validator/Regexp.php @@ -20,46 +20,45 @@ */ /** - * Doctrine_Validator_Regexp + * Doctrine_Validator_Regexp. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Regexp extends Doctrine_Validator_Driver { /** - * checks if given value satisfies a regular expression + * checks if given value satisfies a regular expression. * - * @param mixed $value - * @param mixed $args - * @return boolean + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } - if ( ! isset($this->args)) { - return true; + if (!isset($this->args)) { + return true; } if (is_array($this->args)) { foreach ($this->args as $regexp) { - if ( ! preg_match($regexp, $value)) { + if (!preg_match($regexp, $value)) { return false; } } + + return true; + } + if (preg_match($this->args, $value)) { return true; - } else { - if (preg_match($this->args, $value)) { - return true; - } } return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Time.php b/lib/Doctrine/Validator/Time.php index cf5fed8fb..2bb100ae5 100644 --- a/lib/Doctrine/Validator/Time.php +++ b/lib/Doctrine/Validator/Time.php @@ -20,25 +20,25 @@ */ /** - * Doctrine_Validator_Time + * Doctrine_Validator_Time. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3884 $ + * * @author Mark Pearson */ class Doctrine_Validator_Time extends Doctrine_Validator_Driver { /** - * validate + * validate. * * checks if given value is a valid time * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -46,7 +46,7 @@ public function validate($value) return true; } - if ( ! preg_match('/^\s*(\d{2}):(\d{2})(:(\d{2}))?(\.(\d{1,6}))?([+-]\d{1,2}(:(\d{2}))?)?\s*$/', $value, $matches)) { + if (!preg_match('/^\s*(\d{2}):(\d{2})(:(\d{2}))?(\.(\d{1,6}))?([+-]\d{1,2}(:(\d{2}))?)?\s*$/', $value, $matches)) { return false; } @@ -57,10 +57,10 @@ public function validate($value) $tz_hh = (isset($matches[7])) ? intval($matches[7]) : 0; $tz_mm = (isset($matches[9])) ? intval($matches[9]) : 0; - return ($hh >= 0 && $hh <= 23) && - ($mm >= 0 && $mm <= 59) && - ($ss >= 0 && $ss <= 59) && - ($tz_hh >= -13 && $tz_hh <= 14) && - ($tz_mm >= 0 && $tz_mm <= 59) ; + return ($hh >= 0 && $hh <= 23) + && ($mm >= 0 && $mm <= 59) + && ($ss >= 0 && $ss <= 59) + && ($tz_hh >= -13 && $tz_hh <= 14) + && ($tz_mm >= 0 && $tz_mm <= 59); } } diff --git a/lib/Doctrine/Validator/Timestamp.php b/lib/Doctrine/Validator/Timestamp.php index 5070ac2e0..03c426ad9 100644 --- a/lib/Doctrine/Validator/Timestamp.php +++ b/lib/Doctrine/Validator/Timestamp.php @@ -20,24 +20,24 @@ */ /** - * Doctrine_Validator_Timestamp + * Doctrine_Validator_Timestamp. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3884 $ + * * @author Mark Pearson */ class Doctrine_Validator_Timestamp extends Doctrine_Validator_Driver { /** * checks if given value is a valid timestamp - * ISO-8601 timestamp (YYYY-MM-DDTHH:MM:SS+00:00) or (YYYY-MM-DD HH:MM:SS) + * ISO-8601 timestamp (YYYY-MM-DDTHH:MM:SS+00:00) or (YYYY-MM-DD HH:MM:SS). * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -54,14 +54,14 @@ public function validate($value) $dateValidator = Doctrine_Validator::getValidator('date'); $timeValidator = Doctrine_Validator::getValidator('time'); - if ( ! $dateValidator->validate($date)) { + if (!$dateValidator->validate($date)) { return false; } - if ( ! $timeValidator->validate($time)) { + if (!$timeValidator->validate($time)) { return false; - } + } return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Unique.php b/lib/Doctrine/Validator/Unique.php index 672235b1d..33600aab1 100644 --- a/lib/Doctrine/Validator/Unique.php +++ b/lib/Doctrine/Validator/Unique.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Validator_Unique + * Doctrine_Validator_Unique. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Unique extends Doctrine_Validator_Driver { /** - * checks if given value is unique + * checks if given value is unique. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -49,47 +49,47 @@ public function validate($value) $pks = $table->getIdentifierColumnNames(); if (is_array($pks)) { - for ($i = 0, $l = count($pks); $i < $l; $i++) { + for ($i = 0, $l = count($pks); $i < $l; ++$i) { $pks[$i] = $conn->quoteIdentifier($pks[$i]); } - + $pks = implode(', ', $pks); } - $sql = 'SELECT ' . $pks . ' FROM ' . $conn->quoteIdentifier($table->getTableName()) . ' WHERE '; - + $sql = 'SELECT '.$pks.' FROM '.$conn->quoteIdentifier($table->getTableName()).' WHERE '; + if (is_array($this->field)) { foreach ($this->field as $k => $v) { $this->field[$k] = $conn->quoteIdentifier($table->getColumnName($v)); } - - $sql .= implode(' = ? AND ', $this->field) . ' = ?'; + + $sql .= implode(' = ? AND ', $this->field).' = ?'; $values = $value; } else { - $sql .= $conn->quoteIdentifier($table->getColumnName($this->field)) . ' = ?'; + $sql .= $conn->quoteIdentifier($table->getColumnName($this->field)).' = ?'; $values = array(); $values[] = $value; } - - // If the record is not new we need to add primary key checks because its ok if the + + // If the record is not new we need to add primary key checks because its ok if the // unique value already exists in the database IF the record in the database is the same // as the one that is validated here. $state = $this->invoker->state(); - if ( ! ($state == Doctrine_Record::STATE_TDIRTY || $state == Doctrine_Record::STATE_TCLEAN)) { + if (!(Doctrine_Record::STATE_TDIRTY == $state || Doctrine_Record::STATE_TCLEAN == $state)) { foreach ((array) $table->getIdentifierColumnNames() as $pk) { - $sql .= ' AND ' . $conn->quoteIdentifier($pk) . ' != ?'; + $sql .= ' AND '.$conn->quoteIdentifier($pk).' != ?'; $pkFieldName = $table->getFieldName($pk); - $values[] = $this->invoker->$pkFieldName; + $values[] = $this->invoker->{$pkFieldName}; } } if (isset($this->args) && is_array($this->args) && isset($this->args['where'])) { - $sql .= ' AND ' . $this->args['where']; + $sql .= ' AND '.$this->args['where']; } - $stmt = $table->getConnection()->getDbh()->prepare($sql); + $stmt = $table->getConnection()->getDbh()->prepare($sql); $stmt->execute($values); - return ( ! is_array($stmt->fetch())); + return !is_array($stmt->fetch()); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Unsigned.php b/lib/Doctrine/Validator/Unsigned.php index 4ac099740..4f05af54c 100644 --- a/lib/Doctrine/Validator/Unsigned.php +++ b/lib/Doctrine/Validator/Unsigned.php @@ -20,41 +20,40 @@ */ /** - * Doctrine_Validator_Unsigned + * Doctrine_Validator_Unsigned. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Unsigned extends Doctrine_Validator_Driver { /** - * checks if given value is a valid unsigned integer or float + * checks if given value is a valid unsigned integer or float. * * valid values: null, '', 5, '5', 5.9, '5.9' * invalid values: -5, '-5', 'five', -5.9, '-5.9', '5.5.5' * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { - if (is_null($value) || $value == '') { + if (is_null($value) || '' == $value) { return true; } if (preg_match('/[^0-9\-\.]/', $value)) { return false; } - if ((double) $value >= 0) - { + if ((float) $value >= 0) { return true; } return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Usstate.php b/lib/Doctrine/Validator/Usstate.php index 41bc8c492..1a1ce4656 100644 --- a/lib/Doctrine/Validator/Usstate.php +++ b/lib/Doctrine/Validator/Usstate.php @@ -20,89 +20,91 @@ */ /** - * Doctrine_Validator_Usstate + * Doctrine_Validator_Usstate. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Usstate extends Doctrine_Validator_Driver { private static $states = array( - 'AK' => true, - 'AL' => true, - 'AR' => true, - 'AZ' => true, - 'CA' => true, - 'CO' => true, - 'CT' => true, - 'DC' => true, - 'DE' => true, - 'FL' => true, - 'GA' => true, - 'HI' => true, - 'IA' => true, - 'ID' => true, - 'IL' => true, - 'IN' => true, - 'KS' => true, - 'KY' => true, - 'LA' => true, - 'MA' => true, - 'MD' => true, - 'ME' => true, - 'MI' => true, - 'MN' => true, - 'MO' => true, - 'MS' => true, - 'MT' => true, - 'NC' => true, - 'ND' => true, - 'NE' => true, - 'NH' => true, - 'NJ' => true, - 'NM' => true, - 'NV' => true, - 'NY' => true, - 'OH' => true, - 'OK' => true, - 'OR' => true, - 'PA' => true, - 'PR' => true, - 'RI' => true, - 'SC' => true, - 'SD' => true, - 'TN' => true, - 'TX' => true, - 'UT' => true, - 'VA' => true, - 'VI' => true, - 'VT' => true, - 'WA' => true, - 'WI' => true, - 'WV' => true, - 'WY' => true - ); + 'AK' => true, + 'AL' => true, + 'AR' => true, + 'AZ' => true, + 'CA' => true, + 'CO' => true, + 'CT' => true, + 'DC' => true, + 'DE' => true, + 'FL' => true, + 'GA' => true, + 'HI' => true, + 'IA' => true, + 'ID' => true, + 'IL' => true, + 'IN' => true, + 'KS' => true, + 'KY' => true, + 'LA' => true, + 'MA' => true, + 'MD' => true, + 'ME' => true, + 'MI' => true, + 'MN' => true, + 'MO' => true, + 'MS' => true, + 'MT' => true, + 'NC' => true, + 'ND' => true, + 'NE' => true, + 'NH' => true, + 'NJ' => true, + 'NM' => true, + 'NV' => true, + 'NY' => true, + 'OH' => true, + 'OK' => true, + 'OR' => true, + 'PA' => true, + 'PR' => true, + 'RI' => true, + 'SC' => true, + 'SD' => true, + 'TN' => true, + 'TX' => true, + 'UT' => true, + 'VA' => true, + 'VI' => true, + 'VT' => true, + 'WA' => true, + 'WI' => true, + 'WV' => true, + 'WY' => true, + ); + public function getStates() { return self::$states; } /** - * checks if given value is a valid US state code + * checks if given value is a valid US state code. * - * @param string $args - * @return boolean + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } + return isset(self::$states[$value]); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/View.php b/lib/Doctrine/View.php index 1785f0cbb..a4655cef2 100644 --- a/lib/Doctrine/View.php +++ b/lib/Doctrine/View.php @@ -20,77 +20,75 @@ */ /** - * Doctrine_View + * Doctrine_View. * * this class represents a database view * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage View * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_View { /** - * SQL DROP constant + * SQL DROP constant. */ - const DROP = 'DROP VIEW %s'; + public const DROP = 'DROP VIEW %s'; /** - * SQL CREATE constant + * SQL CREATE constant. */ - const CREATE = 'CREATE VIEW %s AS %s'; + public const CREATE = 'CREATE VIEW %s AS %s'; /** - * SQL SELECT constant + * SQL SELECT constant. */ - const SELECT = 'SELECT * FROM %s'; + public const SELECT = 'SELECT * FROM %s'; /** - * @var string $name the name of the view + * @var string the name of the view */ protected $_name; /** - * @var Doctrine_Query $query the DQL query object this view is hooked into + * @var Doctrine_Query the DQL query object this view is hooked into */ protected $_query; /** - * @var Doctrine_Connection $conn the connection object + * @var Doctrine_Connection the connection object */ protected $_conn; /** - * @var string $_dql The view dql string + * @var string The view dql string */ protected $_dql; /** - * @var string $_sql The view sql string + * @var string The view sql string */ protected $_sql; /** - * constructor - * - * @param Doctrine_Query $query + * constructor. */ public function __construct(Doctrine_Query $query, $viewName) { - $this->_name = $viewName; + $this->_name = $viewName; $this->_query = $query; $this->_query->setView($this); - $this->_conn = $query->getConnection(); + $this->_conn = $query->getConnection(); $this->_dql = $query->getDql(); $this->_sql = $query->getSqlQuery(); } /** - * returns the associated query object + * returns the associated query object. * * @return Doctrine_Query */ @@ -100,7 +98,7 @@ public function getQuery() } /** - * returns the name of this view + * returns the name of this view. * * @return string */ @@ -110,7 +108,7 @@ public function getName() } /** - * returns the connection object + * returns the connection object. * * @return Doctrine_Connection */ @@ -120,38 +118,36 @@ public function getConnection() } /** - * creates this view + * creates this view. * * @throws Doctrine_View_Exception - * @return void */ public function create() { $sql = sprintf(self::CREATE, $this->_name, $this->_query->getSqlQuery()); try { $this->_conn->execute($sql, $this->_query->getFlattenedParams()); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { throw new Doctrine_View_Exception($e->__toString()); } } /** - * drops this view from the database + * drops this view from the database. * * @throws Doctrine_View_Exception - * @return void */ public function drop() { try { $this->_conn->execute(sprintf(self::DROP, $this->_name)); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { throw new Doctrine_View_Exception($e->__toString()); } } /** - * returns a collection of Doctrine_Record objects + * returns a collection of Doctrine_Record objects. * * @return Doctrine_Collection */ @@ -161,7 +157,7 @@ public function execute() } /** - * returns the select sql for this view + * returns the select sql for this view. * * @return string */ @@ -171,7 +167,7 @@ public function getSelectSql() } /** - * Get the view sql string + * Get the view sql string. * * @return string $sql */ @@ -181,7 +177,7 @@ public function getViewSql() } /** - * Get the view dql string + * Get the view dql string. * * @return string $dql */ @@ -189,4 +185,4 @@ public function getViewDql() { return $this->_dql; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/View/Exception.php b/lib/Doctrine/View/Exception.php index e32a62a9b..0dbd77364 100644 --- a/lib/Doctrine/View/Exception.php +++ b/lib/Doctrine/View/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_View_Exception + * Doctrine_View_Exception. * - * @package Doctrine - * @subpackage View * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_View_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/tests/AccessTestCase.php b/tests/AccessTestCase.php index f3fcff42d..77979ef14 100644 --- a/tests/AccessTestCase.php +++ b/tests/AccessTestCase.php @@ -20,57 +20,61 @@ */ /** - * Doctrine_Access_TestCase + * Doctrine_Access_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Access_TestCase extends Doctrine_UnitTestCase +class Doctrine_Access_TestCase extends Doctrine_UnitTestCase { - public function prepareData() + public function prepareData() { - } - public function prepareTables() + public function prepareTables() { - $this->tables = array('Entity', 'User'); + $this->tables = array('Entity', 'User'); parent::prepareTables(); } - public function testUnset() + public function testUnset() { - } - public function testIsset() + public function testIsset() { $user = new User(); - $this->assertTrue(isset($user->name)); + $this->assertTrue(isset($user->name)); $this->assertFalse(isset($user->unknown)); - + $this->assertTrue(isset($user['name'])); $this->assertFalse(isset($user['unknown'])); - + $coll = new Doctrine_Collection('User'); - + $this->assertFalse(isset($coll[0])); // test repeated call $this->assertFalse(isset($coll[0])); $coll[0]; - + $this->assertTrue(isset($coll[0])); // test repeated call $this->assertTrue(isset($coll[0])); } - public function testOffsetMethods() + public function testOffsetMethods() { $user = new User(); $this->assertEqual($user['name'], null); @@ -89,15 +93,15 @@ public function testOffsetMethods() $this->assertEqual($user['name'], 'zYne'); } - public function testOverload() + public function testOverload() { $user = new User(); - $this->assertEqual($user->name,null); + $this->assertEqual($user->name, null); $user->name = 'Jack'; $this->assertEqual($user->name, 'Jack'); - + $user->save(); $user = $this->connection->getTable('User')->find($user->identifier()); @@ -108,10 +112,11 @@ public function testOverload() $user->name = 'zYne'; $this->assertEqual($user->name, 'zYne'); } - - public function testSet() { + + public function testSet() + { $user = new User(); - $this->assertEqual($user->get('name'),null); + $this->assertEqual($user->get('name'), null); $user->set('name', 'Jack'); $this->assertEqual($user->get('name'), 'Jack'); diff --git a/tests/AuditLogTestCase.php b/tests/AuditLogTestCase.php index 1c1242698..42411ceb5 100644 --- a/tests/AuditLogTestCase.php +++ b/tests/AuditLogTestCase.php @@ -20,21 +20,27 @@ */ /** - * Doctrine_AuditLog_TestCase + * Doctrine_AuditLog_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_AuditLog_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + { + } public function prepareTables() { @@ -101,7 +107,6 @@ public function testTableName() $this->assertEqual($entity->getAuditLog()->getTable()->getComponentName(), 'VersioningTestClass'); } - public function testNoAuditLogThrowsExceptions() { $entity = new VersioningTest2(); @@ -118,4 +123,4 @@ public function testNoAuditLogThrowsExceptions() $this->assertEqual($e->getMessage(), 'Audit log is turned off, no version history is recorded.'); } } -} \ No newline at end of file +} diff --git a/tests/BaseTestCase.php b/tests/BaseTestCase.php index 5a865cab2..a7f6f4bed 100644 --- a/tests/BaseTestCase.php +++ b/tests/BaseTestCase.php @@ -20,36 +20,42 @@ */ /** - * Doctrine_Base_TestCase + * Doctrine_Base_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Base_TestCase extends Doctrine_UnitTestCase { public function testAggressiveModelLoading() { $path = realpath('ModelLoadingTest/Aggressive'); - + $models = Doctrine_Core::loadModels($path, Doctrine_Core::MODEL_LOADING_AGGRESSIVE); // Ensure the correct model names were returned - $this->assertTrue(isset($models['AggressiveModelLoadingUser']) && $models['AggressiveModelLoadingUser'] == 'AggressiveModelLoadingUser'); - $this->assertTrue(isset($models['AggressiveModelLoadingProfile']) && $models['AggressiveModelLoadingProfile'] == 'AggressiveModelLoadingProfile'); - $this->assertTrue(isset($models['AggressiveModelLoadingContact']) && $models['AggressiveModelLoadingContact'] == 'AggressiveModelLoadingContact'); + $this->assertTrue(isset($models['AggressiveModelLoadingUser']) && 'AggressiveModelLoadingUser' == $models['AggressiveModelLoadingUser']); + $this->assertTrue(isset($models['AggressiveModelLoadingProfile']) && 'AggressiveModelLoadingProfile' == $models['AggressiveModelLoadingProfile']); + $this->assertTrue(isset($models['AggressiveModelLoadingContact']) && 'AggressiveModelLoadingContact' == $models['AggressiveModelLoadingContact']); // Make sure it does not include the base classes - $this->assertTrue( ! isset($models['BaseAggressiveModelLoadingUser'])); - + $this->assertTrue(!isset($models['BaseAggressiveModelLoadingUser'])); + $filteredModels = Doctrine_Core::filterInvalidModels($models); // Make sure filterInvalidModels filters out base abstract classes - $this->assertTrue( ! isset($models['BaseAggressiveModelLoadingUser'])); + $this->assertTrue(!isset($models['BaseAggressiveModelLoadingUser'])); } public function testConservativeModelLoading() @@ -58,10 +64,10 @@ public function testConservativeModelLoading() $models = Doctrine_Core::loadModels($path, Doctrine_Core::MODEL_LOADING_CONSERVATIVE); - $this->assertTrue( ! class_exists('ConservativeModelLoadingUser', false)); - $this->assertTrue( ! class_exists('ConservativeModelLoadingProfile', false)); - $this->assertTrue( ! class_exists('ConservativeModelLoadingContact', false)); - $this->assertTrue( ! class_exists('BaseConservativeModelLoadingUser', false)); + $this->assertTrue(!class_exists('ConservativeModelLoadingUser', false)); + $this->assertTrue(!class_exists('ConservativeModelLoadingProfile', false)); + $this->assertTrue(!class_exists('ConservativeModelLoadingContact', false)); + $this->assertTrue(!class_exists('BaseConservativeModelLoadingUser', false)); } public function testAllModelsAvailable() @@ -72,10 +78,10 @@ public function testAllModelsAvailable() $this->assertTrue(class_exists('AggressiveModelLoadingContact')); $this->assertTrue(class_exists('BaseAggressiveModelLoadingUser')); - $this->assertTrue( class_exists('ConservativeModelLoadingUser', true)); - $this->assertTrue( class_exists('ConservativeModelLoadingProfile', true)); - $this->assertTrue( class_exists('ConservativeModelLoadingContact', true)); - $this->assertTrue( class_exists('BaseConservativeModelLoadingUser', true)); + $this->assertTrue(class_exists('ConservativeModelLoadingUser', true)); + $this->assertTrue(class_exists('ConservativeModelLoadingProfile', true)); + $this->assertTrue(class_exists('ConservativeModelLoadingContact', true)); + $this->assertTrue(class_exists('BaseConservativeModelLoadingUser', true)); } public function testModelLoadingCacheInformation() @@ -85,7 +91,7 @@ public function testModelLoadingCacheInformation() $this->assertTrue(in_array('AggressiveModelLoadingUser', $models)); $this->assertTrue(in_array('ConservativeModelLoadingProfile', $models)); $this->assertTrue(in_array('ConservativeModelLoadingContact', $models)); - + $modelFiles = Doctrine_Core::getLoadedModelFiles(); $this->assertTrue(file_exists($modelFiles['ConservativeModelLoadingUser'])); $this->assertTrue(file_exists($modelFiles['ConservativeModelLoadingProfile'])); diff --git a/tests/BatchIteratorTestCase.php b/tests/BatchIteratorTestCase.php index 7e3fca498..b8c5bb96c 100644 --- a/tests/BatchIteratorTestCase.php +++ b/tests/BatchIteratorTestCase.php @@ -20,67 +20,75 @@ */ /** - * Doctrine_BatchIterator_TestCase + * Doctrine_BatchIterator_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_BatchIterator_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { - $this->tables = array("EntityAddress", "Entity", "User", "Group", "Address", "Email", "Phonenumber"); +class Doctrine_BatchIterator_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { + $this->tables = array('EntityAddress', 'Entity', 'User', 'Group', 'Address', 'Email', 'Phonenumber'); parent::prepareTables(); } - public function testIterator() { + public function testIterator() + { $graph = new Doctrine_Query($this->connection); - $entities = $graph->query("FROM Entity"); + $entities = $graph->query('FROM Entity'); $i = 0; - foreach($entities as $entity) { - $this->assertEqual(gettype($entity->name),"string"); - $i++; + foreach ($entities as $entity) { + $this->assertEqual(gettype($entity->name), 'string'); + ++$i; } $this->assertTrue($i == $entities->count()); - - $user = $graph->query("FROM User"); - foreach($user[1]->Group as $group) { + + $user = $graph->query('FROM User'); + foreach ($user[1]->Group as $group) { $this->assertTrue(is_string($group->name)); - } - + } + $user = new User(); - $user->name = "tester"; - - $user->Address[0]->address = "street 1"; - $user->Address[1]->address = "street 2"; - - $this->assertEqual($user->name, "tester"); - $this->assertEqual($user->Address[0]->address, "street 1"); - $this->assertEqual($user->Address[1]->address, "street 2"); + $user->name = 'tester'; + + $user->Address[0]->address = 'street 1'; + $user->Address[1]->address = 'street 2'; + + $this->assertEqual($user->name, 'tester'); + $this->assertEqual($user->Address[0]->address, 'street 1'); + $this->assertEqual($user->Address[1]->address, 'street 2'); - foreach($user->Address as $address) { + foreach ($user->Address as $address) { $a[] = $address->address; } - $this->assertEqual($a, array("street 1", "street 2")); + $this->assertEqual($a, array('street 1', 'street 2')); $user->save(); - + $user = $user->getTable()->find($user->id); - $this->assertEqual($user->name, "tester"); - $this->assertEqual($user->Address[0]->address, "street 1"); - $this->assertEqual($user->Address[1]->address, "street 2"); - + $this->assertEqual($user->name, 'tester'); + $this->assertEqual($user->Address[0]->address, 'street 1'); + $this->assertEqual($user->Address[1]->address, 'street 2'); + $user = $user->getTable()->find($user->id); $a = array(); - foreach($user->Address as $address) { + foreach ($user->Address as $address) { $a[] = $address->address; } - $this->assertEqual($a, array("street 1", "street 2")); - + $this->assertEqual($a, array('street 1', 'street 2')); - $user = $graph->query("FROM User"); + $user = $graph->query('FROM User'); } -} \ No newline at end of file +} diff --git a/tests/Cache/AbstractTestCase.php b/tests/Cache/AbstractTestCase.php index a123ac9e2..f2f3590cf 100644 --- a/tests/Cache/AbstractTestCase.php +++ b/tests/Cache/AbstractTestCase.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Cache_Abstract_TestCase + * Doctrine_Cache_Abstract_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Cache * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ abstract class Doctrine_Cache_Abstract_TestCase extends Doctrine_UnitTestCase @@ -48,7 +49,7 @@ public function prepareData() public function testAsResultCache() { - if ( !$this->_isEnabled()) { + if (!$this->_isEnabled()) { return; } $this->_clearCache(); @@ -58,14 +59,15 @@ public function testAsResultCache() $queryCountBefore = $this->conn->count(); - for ($i = 0; $i < 10; $i++) { + for ($i = 0; $i < 10; ++$i) { $u = Doctrine_Query::create() ->from('User u') ->addWhere('u.name = ?', array('Hans')) ->useResultCache($cache, 3600, 'hans_query') - ->execute(); + ->execute() + ; $this->assertEqual(1, count($u)); - $this->assertEqual("Hans", $u[0]->name); + $this->assertEqual('Hans', $u[0]->name); } // Just 1 query should be run @@ -75,7 +77,7 @@ public function testAsResultCache() public function testCacheCore() { - if ( !$this->_isEnabled()) { + if (!$this->_isEnabled()) { return; } $this->_clearCache(); @@ -93,7 +95,7 @@ public function testCacheCore() public function testDeleteByPrefix() { - if ( !$this->_isEnabled()) { + if (!$this->_isEnabled()) { return; } $this->_clearCache(); @@ -112,7 +114,7 @@ public function testDeleteByPrefix() public function testDeleteBySuffix() { - if ( !$this->_isEnabled()) { + if (!$this->_isEnabled()) { return; } $this->_clearCache(); @@ -128,10 +130,10 @@ public function testDeleteBySuffix() $this->assertFalse($cache->contains('bar_suffix')); $this->assertTrue($cache->contains('foo')); } - + public function testDeleteByRegex() { - if ( !$this->_isEnabled()) { + if (!$this->_isEnabled()) { return; } $this->_clearCache(); @@ -147,8 +149,10 @@ public function testDeleteByRegex() $this->assertFalse($cache->contains('bar_match_me')); $this->assertTrue($cache->contains('foo')); } - - abstract protected function _clearCache(); + + abstract protected function _clearCache(); + abstract protected function _isEnabled(); + abstract protected function _getCacheDriver(); } diff --git a/tests/Cache/ApcTestCase.php b/tests/Cache/ApcTestCase.php index ed141caa8..cce1b7168 100644 --- a/tests/Cache/ApcTestCase.php +++ b/tests/Cache/ApcTestCase.php @@ -20,16 +20,21 @@ */ /** - * Doctrine_Cache_Apc_TestCase + * Doctrine_Cache_Apc_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Cache * @author David Abdemoulaie * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Cache_Apc_TestCase extends Doctrine_Cache_Abstract_TestCase { @@ -37,12 +42,12 @@ protected function _clearCache() { apc_clear_cache('user'); } - + protected function _isEnabled() { return extension_loaded('apc'); } - + protected function _getCacheDriver() { return new Doctrine_Cache_Apc(); diff --git a/tests/Cache/ArrayTestCase.php b/tests/Cache/ArrayTestCase.php index 5ff131189..aa4a62c09 100644 --- a/tests/Cache/ArrayTestCase.php +++ b/tests/Cache/ArrayTestCase.php @@ -20,16 +20,21 @@ */ /** - * Doctrine_Cache_Array_TestCase + * Doctrine_Cache_Array_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Cache * @author David Abdemoulaie * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision: 7490 $ + * + * @internal + * + * @coversNothing */ class Doctrine_Cache_Array_TestCase extends Doctrine_Cache_Abstract_TestCase { @@ -37,12 +42,12 @@ protected function _clearCache() { // do nothing } - + protected function _isEnabled() { return true; } - + protected function _getCacheDriver() { return new Doctrine_Cache_Array(); diff --git a/tests/Cache/DbTestCase.php b/tests/Cache/DbTestCase.php index 594103662..d54d237da 100644 --- a/tests/Cache/DbTestCase.php +++ b/tests/Cache/DbTestCase.php @@ -20,16 +20,21 @@ */ /** - * Doctrine_Cache_Db_TestCase + * Doctrine_Cache_Db_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Cache * @author David Abdemoulaie * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision: 7490 $ + * + * @internal + * + * @coversNothing */ class Doctrine_Cache_Db_TestCase extends Doctrine_Cache_Abstract_TestCase { @@ -46,6 +51,7 @@ public function setUp() $this->connection->exec('DROP TABLE IF EXISTS d_cache'); $this->cache->createTable(); } + protected function _clearCache() { $this->connection->exec('DELETE FROM d_cache'); @@ -63,7 +69,7 @@ protected function _getCacheDriver() public function testAsResultCache() { - if ( !$this->_isEnabled()) { + if (!$this->_isEnabled()) { return; } $this->_clearCache(); @@ -73,14 +79,15 @@ public function testAsResultCache() $queryCountBefore = $this->conn->count(); - for ($i = 0; $i < 10; $i++) { + for ($i = 0; $i < 10; ++$i) { $u = Doctrine_Query::create() ->from('User u') ->addWhere('u.name = ?', array('Hans')) ->useResultCache($cache, 3600, 'hans_query') - ->execute(); + ->execute() + ; $this->assertEqual(1, count($u)); - $this->assertEqual("Hans", $u[0]->name); + $this->assertEqual('Hans', $u[0]->name); } $this->assertTrue($cache->contains('hans_query')); diff --git a/tests/Cache/MemcacheTestCase.php b/tests/Cache/MemcacheTestCase.php index 68c4004cf..404de9806 100644 --- a/tests/Cache/MemcacheTestCase.php +++ b/tests/Cache/MemcacheTestCase.php @@ -20,32 +20,38 @@ */ /** - * Doctrine_Cache_Memcache_TestCase + * Doctrine_Cache_Memcache_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Cache * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Cache_Memcache_TestCase extends Doctrine_UnitTestCase +class Doctrine_Cache_Memcache_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { } + public function prepareTables() + { + } + public function prepareData() - { } + { + } } -class Doctrine_Cache_Memcache_Mock extends Doctrine_Cache_Memcache +class Doctrine_Cache_Memcache_Mock extends Doctrine_Cache_Memcache { } -if ( ! class_exists('Memcache')) -{ +if (!class_exists('Memcache')) { class Memcache { - } } diff --git a/tests/Cache/Query/SqliteTestCase.php b/tests/Cache/Query/SqliteTestCase.php index ee95083ec..1ef5a1d28 100644 --- a/tests/Cache/Query/SqliteTestCase.php +++ b/tests/Cache/Query/SqliteTestCase.php @@ -20,16 +20,22 @@ */ /** - * Doctrine_Cache_Query_Sqlite_TestCase + * Doctrine_Cache_Query_Sqlite_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Cache_Query_Sqlite_TestCase extends Doctrine_UnitTestCase +class Doctrine_Cache_Query_Sqlite_TestCase extends Doctrine_UnitTestCase { } diff --git a/tests/Cache/QuerySqliteTestCase.php b/tests/Cache/QuerySqliteTestCase.php index 8e9c9da2f..4ec49c172 100644 --- a/tests/Cache/QuerySqliteTestCase.php +++ b/tests/Cache/QuerySqliteTestCase.php @@ -1,5 +1,10 @@ connection->getAttribute(Doctrine_Core::ATTR_CACHE_DIR); - if (file_exists($dir.DIRECTORY_SEPARATOR."stats.cache")) - unlink($dir.DIRECTORY_SEPARATOR."stats.cache"); + if (file_exists($dir.DIRECTORY_SEPARATOR.'stats.cache')) { + unlink($dir.DIRECTORY_SEPARATOR.'stats.cache'); + } $this->cache = new Doctrine_Cache_Query_Sqlite($this->connection); $this->cache->deleteAll(); } - public function testStore() { - - $this->cache->store("SELECT * FROM user", array(array('name' => 'Jack Daniels')), 60); + public function testStore() + { + $this->cache->store('SELECT * FROM user', array(array('name' => 'Jack Daniels')), 60); $this->assertEqual($this->cache->count(), 1); - $this->cache->store("SELECT * FROM group", array(array('name' => 'Drinkers club')), 60); - - $md5 = md5("SELECT * FROM user"); + $this->cache->store('SELECT * FROM group', array(array('name' => 'Drinkers club')), 60); + + $md5 = md5('SELECT * FROM user'); $result = $this->cache->fetch($md5); $this->assertEqual($result, array(array('name' => 'Jack Daniels'))); - $md5 = md5("SELECT * FROM group"); + $md5 = md5('SELECT * FROM group'); $result = $this->cache->fetch($md5); $this->assertEqual($result, array(array('name' => 'Drinkers club'))); $this->assertEqual($this->cache->count(), 2); - + $this->cache->delete($md5); $this->assertEqual($this->cache->count(), 1); - + $this->cache->deleteAll(); $this->assertEqual($this->cache->count(), 0); } diff --git a/tests/Cache/SqliteTestCase.php b/tests/Cache/SqliteTestCase.php index beebc50c7..53c77091c 100644 --- a/tests/Cache/SqliteTestCase.php +++ b/tests/Cache/SqliteTestCase.php @@ -20,21 +20,29 @@ */ /** - * Doctrine_Cache_Sqlite_TestCase + * Doctrine_Cache_Sqlite_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Cache * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Cache_Sqlite_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { } + public function prepareTables() + { + } + public function prepareData() - { } + { + } } diff --git a/tests/Cache/XcacheTestCase.php b/tests/Cache/XcacheTestCase.php index 4a5b87316..f2da2f42e 100644 --- a/tests/Cache/XcacheTestCase.php +++ b/tests/Cache/XcacheTestCase.php @@ -20,22 +20,27 @@ */ /** - * Doctrine_Cache_Xcache_TestCase + * Doctrine_Cache_Xcache_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Cache * @author David Abdemoulaie * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision: 7490 $ + * + * @internal + * + * @coversNothing */ class Doctrine_Cache_Xcache_TestCase extends Doctrine_Cache_Abstract_TestCase { protected function _clearCache() { - for ($i = 0, $count = xcache_count(XC_TYPE_VAR); $i < $count; $i++) { + for ($i = 0, $count = xcache_count(XC_TYPE_VAR); $i < $count; ++$i) { xcache_clear_cache(XC_TYPE_VAR, $i); } } diff --git a/tests/CacheSqliteTestCase.php b/tests/CacheSqliteTestCase.php index 221c739b6..042df0900 100644 --- a/tests/CacheSqliteTestCase.php +++ b/tests/CacheSqliteTestCase.php @@ -1,17 +1,23 @@ manager->setAttribute(Doctrine_Core::ATTR_CACHE,Doctrine_Core::CACHE_NONE); + $this->manager->setAttribute(Doctrine_Core::ATTR_CACHE, Doctrine_Core::CACHE_NONE); $dir = $this->connection->getAttribute(Doctrine_Core::ATTR_CACHE_DIR); - if (file_exists($dir.DIRECTORY_SEPARATOR."stats.cache")) { - unlink($dir.DIRECTORY_SEPARATOR."stats.cache"); + if (file_exists($dir.DIRECTORY_SEPARATOR.'stats.cache')) { + unlink($dir.DIRECTORY_SEPARATOR.'stats.cache'); } $this->cache = new Doctrine_Cache_Sqlite($this->objTable); @@ -22,42 +28,41 @@ public function testStore() { // does not store proxy objects $this->assertFalse($this->cache->store($this->objTable->getProxy(4))); - + $this->assertTrue($this->cache->store($this->objTable->find(4))); $record = $this->cache->fetch(4); $this->assertTrue($record instanceof Doctrine_Record); - foreach($this->old as $name => $value) { + foreach ($this->old as $name => $value) { $this->assertEqual($record->get($name), $value); } $this->assertEqual($record->obtainIdentifier(), $this->old->obtainIdentifier()); - } public function testFetchMultiple() { - $this->assertFalse($this->cache->fetchMultiple(array(5,6))); + $this->assertFalse($this->cache->fetchMultiple(array(5, 6))); $this->cache->store($this->objTable->find(5)); - $array = $this->cache->fetchMultiple(array(5,6)); - $this->assertEqual(gettype($array), "array"); + $array = $this->cache->fetchMultiple(array(5, 6)); + $this->assertEqual(gettype($array), 'array'); $this->assertEqual(count($array), 1); $this->assertTrue($array[0] instanceof Doctrine_Record); } public function testDeleteMultiple() { - $this->assertEqual($this->cache->deleteMultiple(array()),0); + $this->assertEqual($this->cache->deleteMultiple(array()), 0); $this->cache->store($this->objTable->find(5)); $this->cache->store($this->objTable->find(6)); - $count = $this->cache->deleteMultiple(array(5,6)); + $count = $this->cache->deleteMultiple(array(5, 6)); - $this->assertEqual($count,2); + $this->assertEqual($count, 2); $this->cache->store($this->objTable->find(6)); - $count = $this->cache->deleteMultiple(array(5,6)); - $this->assertEqual($count,1); + $count = $this->cache->deleteMultiple(array(5, 6)); + $this->assertEqual($count, 1); } public function testDelete() @@ -65,7 +70,7 @@ public function testDelete() $this->cache->store($this->objTable->find(5)); $this->assertTrue($this->cache->fetch(5) instanceof Doctrine_Record); - $this->assertEqual($this->cache->delete(5),true); + $this->assertEqual($this->cache->delete(5), true); $this->assertFalse($this->cache->fetch(5)); $this->assertFalse($this->cache->delete(0)); @@ -89,17 +94,17 @@ public function testSaveStats() $this->cache->store($this->objTable->find(5)); $this->cache->store($this->objTable->find(6)); $this->cache->store($this->objTable->find(7)); - $this->cache->fetchMultiple(array(5,6,7)); + $this->cache->fetchMultiple(array(5, 6, 7)); $this->assertTrue($this->cache->saveStats()); - $this->assertTrue(gettype($this->cache->getStats()), "array"); - $this->assertEqual($this->cache->getStats(),array(5 => 1, 6 => 1, 7 => 1)); + $this->assertTrue(gettype($this->cache->getStats()), 'array'); + $this->assertEqual($this->cache->getStats(), array(5 => 1, 6 => 1, 7 => 1)); - $this->cache->fetchMultiple(array(5,6,7)); + $this->cache->fetchMultiple(array(5, 6, 7)); $this->cache->fetch(5); $this->cache->fetch(7); $this->assertTrue($this->cache->saveStats()); - $this->assertEqual($this->cache->getStats(),array(5 => 3, 6 => 2, 7 => 3)); + $this->assertEqual($this->cache->getStats(), array(5 => 3, 6 => 2, 7 => 3)); } public function testClean() @@ -113,13 +118,13 @@ public function testClean() $this->assertEqual($this->cache->count(), 6); $this->cache->fetch(5); $this->cache->fetch(7); - $this->cache->fetchMultiple(array(5,6,7)); - $this->cache->fetchMultiple(array(5,6,7)); - $this->cache->fetchMultiple(array(5,6,7)); - $this->cache->fetchMultiple(array(4,5,6,7,8,9)); + $this->cache->fetchMultiple(array(5, 6, 7)); + $this->cache->fetchMultiple(array(5, 6, 7)); + $this->cache->fetchMultiple(array(5, 6, 7)); + $this->cache->fetchMultiple(array(4, 5, 6, 7, 8, 9)); $this->assertTrue($this->cache->saveStats()); - + $this->manager->setAttribute(Doctrine_Core::ATTR_CACHE_SIZE, 3); $this->assertEqual($this->cache->clean(), 3); } -} \ No newline at end of file +} diff --git a/tests/ClassTableInheritanceTestCase.php b/tests/ClassTableInheritanceTestCase.php index 986742cc5..038b25909 100644 --- a/tests/ClassTableInheritanceTestCase.php +++ b/tests/ClassTableInheritanceTestCase.php @@ -20,22 +20,31 @@ */ /** - * Doctrine_ClassTableInheritance_TestCase + * Doctrine_ClassTableInheritance_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_ClassTableInheritance_TestCase extends Doctrine_UnitTestCase +class Doctrine_ClassTableInheritance_TestCase extends Doctrine_UnitTestCase { public function prepareTables() - { } + { + } + public function prepareData() - { } + { + } public function testClassTableInheritanceIsTheDefaultInheritanceType() { @@ -55,7 +64,7 @@ public function testExportGeneratesAllInheritedTables() $this->assertEqual($sql[2], 'CREATE TABLE c_t_i_test_parent4 (id INTEGER, age INTEGER, PRIMARY KEY(id))'); $this->assertEqual($sql[3], 'CREATE TABLE c_t_i_test_parent3 (id INTEGER, added INTEGER, PRIMARY KEY(id))'); $this->assertEqual($sql[4], 'CREATE TABLE c_t_i_test_parent2 (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(200), verified INTEGER)'); - + foreach ($sql as $query) { $this->conn->exec($query); } @@ -66,7 +75,7 @@ public function testInheritedPropertiesGetOwnerFlags() $class = new CTITest(); $table = $class->getTable(); - + $columns = $table->getColumns(); $this->assertEqual($columns['verified']['owner'], 'CTITestParent2'); @@ -76,24 +85,24 @@ public function testInheritedPropertiesGetOwnerFlags() public function testNewlyCreatedRecordsHaveInheritedPropertiesInitialized() { - $profiler = new Doctrine_Connection_Profiler(); + $profiler = new Doctrine_Connection_Profiler(); - $this->conn->addListener($profiler); + $this->conn->addListener($profiler); $record = new CTITest(); $this->assertEqual($record->toArray(), array('id' => null, - 'age' => null, - 'name' => null, - 'verified' => null, - 'added' => null)); + 'age' => null, + 'name' => null, + 'verified' => null, + 'added' => null)); $record->age = 13; $record->name = 'Jack Daniels'; $record->verified = true; $record->added = time(); $record->save(); - + // pop the commit event $profiler->pop(); $this->assertEqual($profiler->pop()->getQuery(), 'INSERT INTO c_t_i_test_parent4 (age, id) VALUES (?, ?)'); @@ -105,7 +114,7 @@ public function testNewlyCreatedRecordsHaveInheritedPropertiesInitialized() $this->assertEqual($profiler->pop()->getQuery(), 'INSERT INTO c_t_i_test_parent2 (name, verified) VALUES (?, ?)'); $this->conn->addListener(new Doctrine_EventListener()); } - + public function testParentalJoinsAreAddedAutomaticallyWithDql() { $q = new Doctrine_Query(); @@ -114,7 +123,7 @@ public function testParentalJoinsAreAddedAutomaticallyWithDql() $this->assertEqual($q->getSqlQuery(), 'SELECT c.id AS c__id, c3.added AS c__added, c2.name AS c__name, c2.verified AS c__verified, c.age AS c__age FROM c_t_i_test_parent4 c LEFT JOIN c_t_i_test_parent2 c2 ON c.id = c2.id LEFT JOIN c_t_i_test_parent3 c3 ON c.id = c3.id WHERE (c.id = 1)'); $record = $q->fetchOne(); - + $this->assertEqual($record->id, 1); $this->assertEqual($record->name, 'Jack Daniels'); $this->assertEqual($record->verified, true); @@ -137,10 +146,10 @@ public function testReferenfingParentColumnsUsesProperAliases() public function testFetchingCtiRecordsSupportsLimitSubqueryAlgorithm() { - $record = new CTITestOneToManyRelated; - $record->name = 'Someone'; - $record->cti_id = 1; - $record->save(); + $record = new CTITestOneToManyRelated(); + $record->name = 'Someone'; + $record->cti_id = 1; + $record->save(); $this->conn->clear(); @@ -148,7 +157,7 @@ public function testFetchingCtiRecordsSupportsLimitSubqueryAlgorithm() $q->from('CTITestOneToManyRelated c')->leftJoin('c.CTITest c2')->where('c.id = 1')->limit(1); $record = $q->fetchOne(); - + $this->assertEqual($record->name, 'Someone'); $this->assertEqual($record->cti_id, 1); @@ -166,17 +175,17 @@ public function testUpdatingCtiRecordsUpdatesAllParentTables() $this->conn->clear(); $profiler = new Doctrine_Connection_Profiler(); - $this->conn->addListener($profiler); + $this->conn->addListener($profiler); $record = $this->conn->getTable('CTITest')->find(1); - + $record->age = 11; $record->name = 'Jack'; $record->verified = false; $record->added = 0; - + $record->save(); - + // pop the commit event $profiler->pop(); $this->assertEqual($profiler->pop()->getQuery(), 'UPDATE c_t_i_test_parent4 SET age = ? WHERE id = ?'); @@ -188,26 +197,26 @@ public function testUpdatingCtiRecordsUpdatesAllParentTables() $this->assertEqual($profiler->pop()->getQuery(), 'UPDATE c_t_i_test_parent2 SET name = ?, verified = ? WHERE id = ?'); $this->conn->addListener(new Doctrine_EventListener()); } - + public function testUpdateOperationIsPersistent() { $this->conn->clear(); - + $record = $this->conn->getTable('CTITest')->find(1); - + $this->assertEqual($record->id, 1); $this->assertEqual($record->name, 'Jack'); $this->assertEqual($record->verified, false); $this->assertEqual($record->added, 0); $this->assertEqual($record->age, 11); } - + public function testValidationSkipsOwnerOption() { $this->conn->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); $record = $this->conn->getTable('CTITest')->find(1); try { - $record->name = "winston"; + $record->name = 'winston'; $this->assertTrue($record->isValid()); $this->pass(); } catch (Exception $e) { @@ -215,20 +224,20 @@ public function testValidationSkipsOwnerOption() } $this->conn->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - + public function testDeleteIssuesQueriesOnAllJoinedTables() { $this->conn->clear(); $profiler = new Doctrine_Connection_Profiler(); - $this->conn->addListener($profiler); + $this->conn->addListener($profiler); $record = $this->conn->getTable('CTITest')->find(1); - + $record->delete(); // pop the commit event - + // pop the prepare event $profiler->pop(); $this->assertEqual($profiler->pop()->getQuery(), 'DELETE FROM c_t_i_test_parent2 WHERE id = ?'); @@ -238,14 +247,14 @@ public function testDeleteIssuesQueriesOnAllJoinedTables() $this->assertEqual($profiler->pop()->getQuery(), 'DELETE FROM c_t_i_test_parent4 WHERE id = ?'); $this->conn->addListener(new Doctrine_EventListener()); } - + public function testNoIdCti() { $NoIdTestChild = new NoIdTestChild(); $NoIdTestChild->name = 'test'; $NoIdTestChild->child_column = 'test'; $NoIdTestChild->save(); - + $NoIdTestChild = Doctrine_Core::getTable('NoIdTestChild')->find(1); $this->assertEqual($NoIdTestChild->myid, 1); $this->assertEqual($NoIdTestChild->name, 'test'); @@ -253,7 +262,8 @@ public function testNoIdCti() } } abstract class CTIAbstractBase extends Doctrine_Record -{ } +{ +} class CTITestParent1 extends CTIAbstractBase { public function setTableDefinition() @@ -265,7 +275,7 @@ class CTITestParent2 extends CTITestParent1 { public function setTableDefinition() { - parent::setTableDefinition(); + parent::setTableDefinition(); $this->hasColumn('verified', 'boolean', 1); } @@ -284,9 +294,13 @@ public function setTableDefinition() $this->hasColumn('age', 'integer', 4); } } +/** + * @internal + * + * @coversNothing + */ class CTITest extends CTITestParent4 { - } class CTITestOneToManyRelated extends Doctrine_Record @@ -296,7 +310,7 @@ public function setTableDefinition() $this->hasColumn('name', 'string'); $this->hasColumn('cti_id', 'integer'); } - + public function setUp() { $this->hasMany('CTITest', array('local' => 'cti_id', 'foreign' => 'id')); @@ -318,4 +332,4 @@ public function setTableDefinition() { $this->hasColumn('child_column', 'string'); } -} \ No newline at end of file +} diff --git a/tests/CliTestCase.php b/tests/CliTestCase.php index 967c86c8f..fc7daa940 100644 --- a/tests/CliTestCase.php +++ b/tests/CliTestCase.php @@ -20,28 +20,36 @@ */ /** - * Doctrine_Cli_TestCase + * Doctrine_Cli_TestCase. * - * @package Doctrine * @author Dan Bettles * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Cli_TestCase extends UnitTestCase { /** * @ignore + * * @var string */ protected $fixturesPath; /** - * The names of some of the Doctrine Task classes - * + * The names of some of the Doctrine Task classes. + * * @ignore + * * @var array */ protected $doctrineTaskClassName = array( @@ -52,12 +60,13 @@ class Doctrine_Cli_TestCase extends UnitTestCase /** * @ignore + * * @return string */ protected function getFixturesPath() { - if (! isset($this->fixturesPath)) { - $this->fixturesPath = dirname(__FILE__) . '/CliTestCase'; + if (!isset($this->fixturesPath)) { + $this->fixturesPath = dirname(__FILE__).'/CliTestCase'; } return $this->fixturesPath; @@ -152,6 +161,7 @@ public function testGetconfigvalueThrowsAnExceptionIfTheSpecifiedElementDoesNotE } catch (OutOfBoundsException $e) { if ($e->getMessage() == "The element \"{$key}\" does not exist in the config") { $this->pass(); + return; } } @@ -210,18 +220,18 @@ public function testDoctrineTaskClassesAreNotAlreadyLoaded() } } - //Apologies for this cheap, non-atomic test - this area needs some more work once this round of refactoring's done + // Apologies for this cheap, non-atomic test - this area needs some more work once this round of refactoring's done public function testAutomaticallyIncludesAndRegistersDoctrineTasks() { $cli = new Doctrine_Cli_TestCase_EmptyCli(array('autoregister_custom_tasks' => false)); - //Make sure those Doctrine core Tasks are loaded + // Make sure those Doctrine core Tasks are loaded foreach ($this->doctrineTaskClassName as $className => $taskName) { $this->assertTrue(class_exists($className, false)); $this->assertTrue($cli->taskClassIsRegistered($className)); } - //Now, make sure we haven't registered any custom Tasks + // Now, make sure we haven't registered any custom Tasks $this->assertFalse($cli->taskClassIsRegistered('Doctrine_Cli_TestCase_EmptyTask')); } @@ -237,11 +247,11 @@ public function testRegistertaskclassRegistersTheSpecifiedClass() $this->assertFalse($cli->taskClassIsRegistered('Doctrine_Cli_TestCase_TestTask02')); - require_once($this->getFixturesPath() . '/TestTask02.php'); + require_once $this->getFixturesPath().'/TestTask02.php'; $cli->registerTaskClass('Doctrine_Cli_TestCase_TestTask02'); $this->assertTrue($cli->taskClassIsRegistered('Doctrine_Cli_TestCase_TestTask02')); - //Nothing should happen if we attempt to register a registered class + // Nothing should happen if we attempt to register a registered class $cli->registerTaskClass('Doctrine_Cli_TestCase_TestTask02'); $this->assertTrue($cli->taskClassIsRegistered('Doctrine_Cli_TestCase_TestTask02')); } @@ -253,8 +263,9 @@ public function testRegistertaskclassThrowsAnExceptionIfTheSpecifiedClassIsNotLo try { $cli->registerTaskClass('anything'); } catch (InvalidArgumentException $e) { - if ($e->getMessage() == 'The task class "anything" does not exist') { + if ('The task class "anything" does not exist' == $e->getMessage()) { $this->pass(); + return; } } @@ -273,6 +284,7 @@ public function testRegistertaskclassThrowsAnExceptionIfTheSpecifiedClassIsNotAT } catch (DomainException $e) { if ($e->getMessage() == "The class \"{$thisClassName}\" is not a Doctrine Task") { $this->pass(); + return; } } @@ -287,17 +299,18 @@ public function testLoadtasksThrowsAnExceptionIfTheSpecifiedDirectoryDoesNotExis { $cli = new Doctrine_Cli_TestCase_PassiveCli(); - $directory = $this->getFixturesPath() . '/foo'; - + $directory = $this->getFixturesPath().'/foo'; + try { $cli->loadTasks($directory); } catch (InvalidArgumentException $e) { if ($e->getMessage() == "The directory \"{$directory}\" does not exist") { $this->pass(); + return; } } - + $this->fail(); } @@ -307,10 +320,10 @@ public function testLoadtasksThrowsAnExceptionIfTheSpecifiedDirectoryDoesNotExis public function testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory() { $cli = new Doctrine_Cli_TestCase_PassiveCli(); - + $this->assertEqual(array(), $cli->getRegisteredTasks()); - - $loadedTaskName = $cli->loadTasks($this->getFixturesPath() . '/' . __FUNCTION__); + + $loadedTaskName = $cli->loadTasks($this->getFixturesPath().'/'.__FUNCTION__); $expectedTaskName = array('doctrine-style-task' => 'doctrine-style-task'); $this->assertEqual($expectedTaskName, $loadedTaskName); @@ -343,11 +356,11 @@ public function testGetloadedtasksReturnsAnArrayOfTaskNames() $expectedTaskName = array_combine($this->doctrineTaskClassName, $this->doctrineTaskClassName); $this->assertEqual($expectedTaskName, array_intersect_assoc($expectedTaskName, $loadedTaskNames)); } - + /* * Exists only to ensure the method behaves the same as it did before refactoring */ - public function test_gettaskclassfromargsReturnsTheNameOfTheClassAssociatedWithTheSpecifiedTask() + public function testGettaskclassfromargsReturnsTheNameOfTheClassAssociatedWithTheSpecifiedTask() { $cli = new Doctrine_Cli_TestCase_PassiveCli02(); $this->assertEqual('Doctrine_Task_TaskName', $cli->_getTaskClassFromArgs(array('scriptName', 'task-name'))); @@ -355,17 +368,17 @@ public function test_gettaskclassfromargsReturnsTheNameOfTheClassAssociatedWithT public function testRunByDefaultDoesNotThrowExceptions() { - //Hide printed output from the CLI + // Hide printed output from the CLI ob_start(); $cli = new Doctrine_Cli_TestCase_NoisyCli(); $cli->run(array()); $this->pass(); - + $cli = new Doctrine_Cli_TestCase_NoisyCli(array('rethrow_exceptions' => false)); $cli->run(array()); $this->pass(); - + $cli = new Doctrine_Cli_TestCase_NoisyCli(array('rethrow_exceptions' => 0)); $cli->run(array()); $this->pass(); @@ -375,22 +388,23 @@ public function testRunByDefaultDoesNotThrowExceptions() public function testRunThrowsExceptionsIfTheCliWasConstructedWithTheRethrowexceptionsOptionSetToTrue() { - //Hide printed output from the CLI + // Hide printed output from the CLI ob_start(); $cli = new Doctrine_Cli_TestCase_NoisyCli(array('rethrow_exceptions' => 1)); - + try { $cli->run(array()); - //The same exception must be re-thrown... + // The same exception must be re-thrown... } catch (Doctrine_Cli_TestCase_Exception $e) { - //...And it must be formatted + // ...And it must be formatted if (preg_match('/Foo\W+/', $e->getMessage())) { $this->pass(); + return; } } - + $this->fail(); ob_end_clean(); @@ -407,7 +421,9 @@ public function testGettaskinstanceReturnsTheTaskSetWithSettaskinstance() class Doctrine_Cli_TestCase_PassiveCli extends Doctrine_Cli { - protected function includeAndRegisterTaskClasses() {} + protected function includeAndRegisterTaskClasses() + { + } } class Doctrine_Cli_TestCase_EmptyCli extends Doctrine_Cli @@ -416,7 +432,9 @@ class Doctrine_Cli_TestCase_EmptyCli extends Doctrine_Cli class Doctrine_Cli_TestCase_EmptyTask extends Doctrine_Task { - public function execute() {} + public function execute() + { + } } class Doctrine_Cli_TestCase_PassiveCli02 extends Doctrine_Cli_TestCase_PassiveCli @@ -441,5 +459,7 @@ protected function _run(array $args) class Doctrine_Cli_TestCase_TestTask01 extends Doctrine_Task { - public function execute() {} + public function execute() + { + } } diff --git a/tests/CliTestCase/TestTask02.php b/tests/CliTestCase/TestTask02.php index dd96e85b0..82d44c20c 100644 --- a/tests/CliTestCase/TestTask02.php +++ b/tests/CliTestCase/TestTask02.php @@ -1,11 +1,12 @@ */ - class Doctrine_Cli_TestCase_TestTask02 extends Doctrine_Task { - public function execute() {} -} \ No newline at end of file + public function execute() + { + } +} diff --git a/tests/CliTestCase/cli-default.php b/tests/CliTestCase/cli-default.php index cf3e8f524..090a7f810 100644 --- a/tests/CliTestCase/cli-default.php +++ b/tests/CliTestCase/cli-default.php @@ -1,14 +1,14 @@ */ -require_once(dirname(dirname(dirname(__FILE__))) . '/lib/Doctrine/Core.php'); +require_once dirname(dirname(dirname(__FILE__))).'/lib/Doctrine/Core.php'; spl_autoload_register(array('Doctrine_Core', 'autoload')); -require_once(dirname(__FILE__) . '/TestTask02.php'); +require_once dirname(__FILE__).'/TestTask02.php'; $cli = new Doctrine_Cli(); $cli->run($_SERVER['argv']); diff --git a/tests/CliTestCase/cli-with-custom-tasks.php b/tests/CliTestCase/cli-with-custom-tasks.php index ef081e51f..637ab7197 100644 --- a/tests/CliTestCase/cli-with-custom-tasks.php +++ b/tests/CliTestCase/cli-with-custom-tasks.php @@ -1,20 +1,20 @@ */ -require_once(dirname(dirname(dirname(__FILE__))) . '/lib/Doctrine/Core.php'); +require_once dirname(dirname(dirname(__FILE__))).'/lib/Doctrine/Core.php'; spl_autoload_register(array('Doctrine_Core', 'autoload')); $cli = new Doctrine_Cli(); -require_once(dirname(__FILE__) . '/TestTask02.php'); +require_once dirname(__FILE__).'/TestTask02.php'; -//Either...: +// Either...: $cli->registerTaskClass('Doctrine_Cli_TestCase_TestTask02'); -//...Or: +// ...Or: $cli->registerIncludedTaskClasses(); $cli->run($_SERVER['argv']); diff --git a/tests/CliTestCase/cli-without-autoregistered-custom-tasks.php b/tests/CliTestCase/cli-without-autoregistered-custom-tasks.php index f9b644f5a..b7c454aa5 100644 --- a/tests/CliTestCase/cli-without-autoregistered-custom-tasks.php +++ b/tests/CliTestCase/cli-without-autoregistered-custom-tasks.php @@ -1,14 +1,14 @@ */ -require_once(dirname(dirname(dirname(__FILE__))) . '/lib/Doctrine/Core.php'); +require_once dirname(dirname(dirname(__FILE__))).'/lib/Doctrine/Core.php'; spl_autoload_register(array('Doctrine_Core', 'autoload')); -require_once(dirname(__FILE__) . '/TestTask02.php'); +require_once dirname(__FILE__).'/TestTask02.php'; $cli = new Doctrine_Cli(array('autoregister_custom_tasks' => false)); $cli->run($_SERVER['argv']); diff --git a/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/DoctrineStyleTask.php b/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/DoctrineStyleTask.php index 1b2d3c82a..d1f166b45 100644 --- a/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/DoctrineStyleTask.php +++ b/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/DoctrineStyleTask.php @@ -1,11 +1,12 @@ */ - class Doctrine_Task_DoctrineStyleTask extends Doctrine_Task { - public function execute() {} -} \ No newline at end of file + public function execute() + { + } +} diff --git a/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/EmptyFile.php b/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/EmptyFile.php index 4745fdf8b..f70236e30 100644 --- a/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/EmptyFile.php +++ b/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/EmptyFile.php @@ -1,8 +1,8 @@ */ -//This empty file shouldn't cause any problems for the CLI \ No newline at end of file +// This empty file shouldn't cause any problems for the CLI diff --git a/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/InvalidClassNameForATask.php b/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/InvalidClassNameForATask.php index 8cfdf6a00..eb66fd5c6 100644 --- a/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/InvalidClassNameForATask.php +++ b/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/InvalidClassNameForATask.php @@ -1,11 +1,12 @@ */ - class Doctrine_Cli_TestCase_InvalidClassNameForATask extends Doctrine_Task { - public function execute() {} -} \ No newline at end of file + public function execute() + { + } +} diff --git a/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/TaskDeclaredInAnIncFile.inc.php b/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/TaskDeclaredInAnIncFile.inc.php index 732998629..bdcc386ba 100644 --- a/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/TaskDeclaredInAnIncFile.inc.php +++ b/tests/CliTestCase/testLoadtasksLoadsDoctrineStyleTasksFromTheSpecifiedDirectory/TaskDeclaredInAnIncFile.inc.php @@ -1,11 +1,12 @@ */ - class Doctrine_Task_TaskDeclaredInAnIncFile extends Doctrine_Task { - public function execute() {} -} \ No newline at end of file + public function execute() + { + } +} diff --git a/tests/Collection/SnapshotTestCase.php b/tests/Collection/SnapshotTestCase.php index 0605cd576..ae3878855 100644 --- a/tests/Collection/SnapshotTestCase.php +++ b/tests/Collection/SnapshotTestCase.php @@ -20,28 +20,34 @@ */ /** - * Doctrine_Collection_Snapshot_TestCase + * Doctrine_Collection_Snapshot_TestCase. * * This test case is used for testing the snapshot functionality * of the Doctrine_Collection * - * Snapshots are used for counting the diff between original and changed + * Snapshots are used for counting the diff between original and changed * state of the collection. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Collection_Snapshot_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables = array('Entity', 'User', 'Group', 'GroupUser', 'Account', 'Album', 'Phonenumber', 'Email', 'Book'); - + parent::prepareTables(); } @@ -52,8 +58,7 @@ public function testDiffForSimpleCollection() $coll = $q->execute(); $this->assertEqual($coll->count(), 8); - unset($coll[0]); - unset($coll[1]); + unset($coll[0], $coll[1]); $coll[]->name = 'new user'; @@ -73,7 +78,8 @@ public function testDiffForOneToManyRelatedCollection() { $q = new Doctrine_Query(); $q->from('User u LEFT JOIN u.Phonenumber p') - ->where('u.id = 8'); + ->where('u.id = 8') + ; $coll = $q->execute(); @@ -98,7 +104,6 @@ public function testDiffForOneToManyRelatedCollection() $coll = $q->execute(); $this->assertEqual($coll[0]->Phonenumber->count(), 1); - } public function testDiffForManyToManyRelatedCollection() @@ -112,7 +117,8 @@ public function testDiffForManyToManyRelatedCollection() $this->connection->clear(); $users = Doctrine_Query::create()->from('User u LEFT JOIN u.Group g') - ->where('u.id = ' . $user->id)->execute(); + ->where('u.id = '.$user->id)->execute() + ; $this->assertEqual($users[0]->Group[0]->name, 'PHP'); $this->assertEqual($users[0]->Group[1]->name, 'Web'); @@ -125,19 +131,18 @@ public function testDiffForManyToManyRelatedCollection() $this->assertEqual(count($user->Group->getSnapshot()), 1); unset($user->Group[1]); $this->assertEqual(count($user->Group->getSnapshot()), 1); - + $count = count($this->conn); $user->save(); $this->assertEqual(count($user->Group->getSnapshot()), 0); - + $this->conn->clear(); $users = Doctrine_Query::create()->from('User u LEFT JOIN u.Group g') - ->where('u.id = ' . $user->id)->execute(); - - $this->assertEqual(count($user->Group), 0); + ->where('u.id = '.$user->id)->execute() + ; + $this->assertEqual(count($user->Group), 0); } - } diff --git a/tests/CollectionOffsetTestCase.php b/tests/CollectionOffsetTestCase.php index c3a509080..029cff6ad 100644 --- a/tests/CollectionOffsetTestCase.php +++ b/tests/CollectionOffsetTestCase.php @@ -1,8 +1,15 @@ connection->query("FROM User-o"); +/** + * @internal + * + * @coversNothing + */ +class Doctrine_Collection_Offset_TestCase extends Doctrine_UnitTestCase +{ + public function testExpand() + { + $users = $this->connection->query('FROM User-o'); $this->assertTrue($users instanceof Doctrine_Collection_Offset); $this->assertEqual(count($users), 5); @@ -13,7 +20,7 @@ public function testExpand() { $this->connection->setAttribute(Doctrine_Core::ATTR_COLL_LIMIT, 3); - $users = $this->connection->query("FROM User-o"); + $users = $this->connection->query('FROM User-o'); $this->assertEqual(count($users), 3); $this->assertEqual($users[0]->getState(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($users[1]->getState(), Doctrine_Record::STATE_CLEAN); @@ -31,16 +38,14 @@ public function testExpand() { $this->assertEqual($users[6]->getState(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($users[7]->getState(), Doctrine_Record::STATE_CLEAN); - $users[5]; $this->assertEqual(count($users), 8); $this->assertEqual($users[3]->getState(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($users[4]->getState(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($users[5]->getState(), Doctrine_Record::STATE_CLEAN); - $this->connection->setAttribute(Doctrine_Core::ATTR_COLL_LIMIT, 1); - $users = $this->connection->query("FROM User-b, User.Phonenumber-o WHERE User.".$this->objTable->getIdentifier()." = 5"); + $users = $this->connection->query('FROM User-b, User.Phonenumber-o WHERE User.'.$this->objTable->getIdentifier().' = 5'); $this->assertEqual(count($users), 1); @@ -49,15 +54,15 @@ public function testExpand() { $coll[1]; $this->assertEqual(count($coll), 3); - $this->assertEqual($coll[1]->phonenumber, "456 456"); - + $this->assertEqual($coll[1]->phonenumber, '456 456'); } - public function testGetIterator() { + public function testGetIterator() + { $this->connection->setAttribute(Doctrine_Core::ATTR_COLL_LIMIT, 4); - $coll = $this->connection->query("FROM User-o"); + $coll = $this->connection->query('FROM User-o'); - foreach($coll as $user) { + foreach ($coll as $user) { } $this->assertEqual($coll->count(), 8); $this->assertEqual($coll[3]->getState(), Doctrine_Record::STATE_CLEAN); @@ -65,9 +70,9 @@ public function testGetIterator() { $this->connection->setAttribute(Doctrine_Core::ATTR_COLL_LIMIT, 3); - $coll = $this->connection->query("FROM User-o"); + $coll = $this->connection->query('FROM User-o'); - foreach($coll as $user) { + foreach ($coll as $user) { } $this->assertEqual($coll->count(), 8); $this->assertEqual($coll[3]->getState(), Doctrine_Record::STATE_CLEAN); diff --git a/tests/CollectionTestCase.php b/tests/CollectionTestCase.php index 9de8d0cdd..5224cb4cf 100644 --- a/tests/CollectionTestCase.php +++ b/tests/CollectionTestCase.php @@ -20,19 +20,25 @@ */ /** - * Doctrine_Collection_TestCase + * Doctrine_Collection_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Collection_TestCase extends Doctrine_UnitTestCase +class Doctrine_Collection_TestCase extends Doctrine_UnitTestCase { - public function testLoadRelatedForAssociation() + public function testLoadRelatedForAssociation() { $coll = $this->connection->query('FROM User'); @@ -45,15 +51,15 @@ public function testLoadRelatedForAssociation() $coll[2]->Group[0]->name = 'Actors House 4'; $coll[2]->Group[1]->name = 'Actors House 5'; $coll[2]->Group[2]->name = 'Actors House 6'; - + $coll[5]->Group[0]->name = 'Actors House 7'; $coll[5]->Group[1]->name = 'Actors House 8'; $coll[5]->Group[2]->name = 'Actors House 9'; - + $coll->save(); - + $this->connection->clear(); - + $coll = $this->connection->query('FROM User'); $this->assertEqual($coll->count(), 8); @@ -63,7 +69,7 @@ public function testLoadRelatedForAssociation() $this->assertEqual($coll[5]->Group->count(), 3); $this->connection->clear(); - + $coll = $this->connection->query('FROM User'); $this->assertEqual($coll->count(), 8); @@ -71,24 +77,24 @@ public function testLoadRelatedForAssociation() $count = $this->connection->count(); $coll->loadRelated('Group'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->assertEqual($coll[0]->Group->count(), 2); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->assertEqual($coll[1]->Group->count(), 1); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->assertEqual($coll[2]->Group->count(), 3); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->assertEqual($coll[5]->Group->count(), 3); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->connection->clear(); } - public function testOffsetGetWithNullArgumentReturnsNewRecord() + public function testOffsetGetWithNullArgumentReturnsNewRecord() { $coll = new Doctrine_Collection('User'); $this->assertEqual($coll->count(), 0); @@ -99,7 +105,7 @@ public function testOffsetGetWithNullArgumentReturnsNewRecord() $this->assertEqual($coll[0]->name, 'zYne'); } - public function testLoadRelatedForNormalAssociation() + public function testLoadRelatedForNormalAssociation() { $resource = new Doctrine_Collection('Resource'); $resource[0]->name = 'resource 1'; @@ -110,7 +116,7 @@ public function testLoadRelatedForNormalAssociation() $resource[1]->Type[1]->type = 'type 4'; $resource->save(); - + $this->connection->clear(); $resources = $this->connection->query('FROM Resource'); @@ -118,42 +124,42 @@ public function testLoadRelatedForNormalAssociation() $count = $this->connection->count(); $resources->loadRelated('Type'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->assertEqual($resources[0]->name, 'resource 1'); $this->assertEqual($resource[0]->Type[0]->type, 'type 1'); $this->assertEqual($resource[0]->Type[1]->type, 'type 2'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->assertEqual($resource[1]->name, 'resource 2'); $this->assertEqual($resource[1]->Type[0]->type, 'type 3'); $this->assertEqual($resource[1]->Type[1]->type, 'type 4'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); } - - public function testAdd() + + public function testAdd() { $coll = new Doctrine_Collection($this->objTable); $coll->add(new User()); - $this->assertEqual($coll->count(),1); + $this->assertEqual($coll->count(), 1); $coll->add(new User()); - $this->assertTrue($coll->count(),2); + $this->assertTrue($coll->count(), 2); - $this->assertEqual($coll->getKeys(), array(0,1)); + $this->assertEqual($coll->getKeys(), array(0, 1)); $coll[2] = new User(); - $this->assertTrue($coll->count(),3); - $this->assertEqual($coll->getKeys(), array(0,1,2)); + $this->assertTrue($coll->count(), 3); + $this->assertEqual($coll->getKeys(), array(0, 1, 2)); } - public function testLoadRelated() + public function testLoadRelated() { $coll = $this->connection->query('FROM User u'); $q = $coll->loadRelated(); $this->assertTrue($q instanceof Doctrine_Query); - + $q->addFrom('User.Group g'); $this->assertEqual($q->getSqlQuery($coll->getPrimaryKeys()), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e.id IN (?, ?, ?, ?, ?, ?, ?, ?) AND (e.type = 0))'); @@ -166,20 +172,20 @@ public function testLoadRelated() $this->assertEqual($count, $this->connection->count()); } - public function testLoadRelatedForLocalKeyRelation() + public function testLoadRelatedForLocalKeyRelation() { $coll = $this->connection->query('FROM User'); $this->assertEqual($coll->count(), 8); - + $count = $this->connection->count(); $coll->loadRelated('Email'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->assertEqual($coll[0]->Email->address, 'zYne@example.com'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->assertEqual($coll[2]->Email->address, 'caine@example.com'); @@ -187,46 +193,45 @@ public function testLoadRelatedForLocalKeyRelation() $this->assertEqual($coll[4]->Email->address, 'stallone@example.com'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $this->connection->clear(); } - public function testLoadRelatedForForeignKey() + public function testLoadRelatedForForeignKey() { - $coll = $this->connection->query("FROM User"); + $coll = $this->connection->query('FROM User'); $this->assertEqual($coll->count(), 8); - + $count = $this->connection->count(); - $coll->loadRelated("Phonenumber"); + $coll->loadRelated('Phonenumber'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); - $this->assertEqual($coll[0]->Phonenumber[0]->phonenumber, "123 123"); + $this->assertEqual($coll[0]->Phonenumber[0]->phonenumber, '123 123'); - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); $coll[0]->Phonenumber[1]->phonenumber; - $this->assertEqual(($count + 1), $this->connection->count()); + $this->assertEqual($count + 1, $this->connection->count()); + + $this->assertEqual($coll[4]->Phonenumber[0]->phonenumber, '111 555 333'); + $this->assertEqual($coll[4]['Phonenumber'][1]->phonenumber, '123 213'); + $this->assertEqual($coll[4]['Phonenumber'][2]->phonenumber, '444 555'); - $this->assertEqual($coll[4]->Phonenumber[0]->phonenumber, "111 555 333"); - $this->assertEqual($coll[4]["Phonenumber"][1]->phonenumber, "123 213"); - $this->assertEqual($coll[4]["Phonenumber"][2]->phonenumber, "444 555"); + $this->assertEqual($coll[5]->Phonenumber[0]->phonenumber, '111 222 333'); - $this->assertEqual($coll[5]->Phonenumber[0]->phonenumber, "111 222 333"); + $this->assertEqual($coll[6]->Phonenumber[0]->phonenumber, '111 222 333'); + $this->assertEqual($coll[6]['Phonenumber'][1]->phonenumber, '222 123'); + $this->assertEqual($coll[6]['Phonenumber'][2]->phonenumber, '123 456'); + $this->assertEqual($count + 1, $this->connection->count()); - $this->assertEqual($coll[6]->Phonenumber[0]->phonenumber, "111 222 333"); - $this->assertEqual($coll[6]["Phonenumber"][1]->phonenumber, "222 123"); - $this->assertEqual($coll[6]["Phonenumber"][2]->phonenumber, "123 456"); - - $this->assertEqual(($count + 1), $this->connection->count()); - $this->connection->clear(); } - public function testCount() + public function testCount() { $coll = new Doctrine_Collection($this->connection->getTable('User')); $this->assertEqual($coll->count(), 0); @@ -234,55 +239,53 @@ public function testCount() $this->assertEqual($coll->count(), 1); } - public function testGenerator() + public function testGenerator() { $coll = new Doctrine_Collection($this->objTable); $coll->setKeyColumn('name'); $user = new User(); - $user->name = "name"; + $user->name = 'name'; $coll->add($user); - $this->assertTrue($coll["name"] === $user); + $this->assertTrue($coll['name'] === $user); - $this->connection->getTable("email")->setAttribute(Doctrine_Core::ATTR_COLL_KEY,"address"); - $emails = $this->connection->getTable("email")->findAll(); - foreach($emails as $k => $v) { - $this->assertTrue(gettype($k), "string"); + $this->connection->getTable('email')->setAttribute(Doctrine_Core::ATTR_COLL_KEY, 'address'); + $emails = $this->connection->getTable('email')->findAll(); + foreach ($emails as $k => $v) { + $this->assertTrue(gettype($k), 'string'); } - } - public function testFetchCollectionWithIdAsIndex() + public function testFetchCollectionWithIdAsIndex() { $user = new User(); $user->attribute(Doctrine_Core::ATTR_COLL_KEY, 'id'); - + $users = $user->getTable()->findAll(); $this->assertFalse($users->contains(0)); $this->assertEqual($users->count(), 8); } - public function testFetchCollectionWithNameAsIndex() + public function testFetchCollectionWithNameAsIndex() { $user = new User(); $user->attribute(Doctrine_Core::ATTR_COLL_KEY, 'name'); - + $users = $user->getTable()->findAll(); $this->assertFalse($users->contains(0)); $this->assertEqual($users->count(), 8); } - public function testFetchMultipleCollections() + public function testFetchMultipleCollections() { $this->connection->clear(); - + $user = new User(); $user->attribute(Doctrine_Core::ATTR_COLL_KEY, 'id'); $phonenumber = new Phonenumber(); $phonenumber->attribute(Doctrine_Core::ATTR_COLL_KEY, 'id'); - $q = new Doctrine_Query(); $users = $q->from('User u, u.Phonenumber p')->execute(); $this->assertFalse($users->contains(0)); @@ -338,4 +341,4 @@ class MyConnectionCollection extends MyCollection class MyPhonenumberCollection extends MyConnectionCollection { -} \ No newline at end of file +} diff --git a/tests/ColumnAggregationInheritanceTestCase.php b/tests/ColumnAggregationInheritanceTestCase.php index c46d11008..b628a617d 100644 --- a/tests/ColumnAggregationInheritanceTestCase.php +++ b/tests/ColumnAggregationInheritanceTestCase.php @@ -20,28 +20,34 @@ */ /** - * Doctrine_ColumnAggregationInheritance_TestCase + * Doctrine_ColumnAggregationInheritance_TestCase. * - * @package Doctrine * @author Konsta Vesterinen - * @author Bjarte Stien Karlsen + * @author Bjarte Stien Karlsen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_ColumnAggregationInheritance_TestCase extends Doctrine_UnitTestCase +class Doctrine_ColumnAggregationInheritance_TestCase extends Doctrine_UnitTestCase { - protected $otherEntity = null; + protected $otherEntity; public function prepareData() { parent::prepareData(); - //we create a test entity that is not a user and not a group + // we create a test entity that is not a user and not a group $entity = new Entity(); - $entity->name='Other Entity'; - $entity->type = 2; + $entity->name = 'Other Entity'; + $entity->type = 2; $entity->save(); $this->otherEntity = $entity; } @@ -50,25 +56,25 @@ public function testQueriedClassReturnedIfNoSubclassMatch() { $q = new Doctrine_Query(); $entityOther = $q->from('Entity')->where('id = ?')->execute(array($this->otherEntity->id))->getFirst(); - $this->assertTrue($entityOther instanceOf Entity); + $this->assertTrue($entityOther instanceof Entity); } public function testSubclassReturnedIfInheritanceMatches() { $q = new Doctrine_Query(); $group = $q->from('Entity')->where('id=?')->execute(array(1))->getFirst(); - $this->assertTrue($group instanceOf Group); + $this->assertTrue($group instanceof Group); $q = new Doctrine_Query(); $user = $q->from('Entity')->where('id=?')->execute(array(5))->getFirst(); - $this->assertTrue($user instanceOf User); + $this->assertTrue($user instanceof User); } public function testStringColumnInheritance() { $q = new Doctrine_Query(); $q->select('g.name')->from('Group g'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 1)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 1)'); } public function testSubclassFieldSetWhenCreatingNewSubclassedRecord() @@ -80,4 +86,4 @@ public function testSubclassFieldSetWhenCreatingNewSubclassedRecord() $child->save(); $this->assertEqual($child->type, '0'); } -} \ No newline at end of file +} diff --git a/tests/ColumnAliasTestCase.php b/tests/ColumnAliasTestCase.php index edaf526c4..76ae39e8f 100644 --- a/tests/ColumnAliasTestCase.php +++ b/tests/ColumnAliasTestCase.php @@ -20,44 +20,50 @@ */ /** - * Doctrine_ColumnAlias_TestCase + * Doctrine_ColumnAlias_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_ColumnAlias_TestCase extends Doctrine_UnitTestCase +class Doctrine_ColumnAlias_TestCase extends Doctrine_UnitTestCase { - public function prepareData() + public function prepareData() { $book1 = new Book(); $book1->name = 'Das Boot'; $book1->save(); - + $record1 = new ColumnAliasTest(); $record1->alias1 = 'first'; $record1->alias2 = 123; $record1->anotherField = 'camelCase'; $record1->bookId = $book1->id; $record1->save(); - + $record2 = new ColumnAliasTest(); $record2->alias1 = 'one'; $record2->alias2 = 456; $record2->anotherField = 'KoQ'; $record2->save(); - + $record2->anotherField = 'foo'; } - + public function prepareTables() - { + { $this->tables = array('ColumnAliasTest', 'Book'); - + parent::prepareTables(); } @@ -65,20 +71,22 @@ public function testAliasesAreSupportedForJoins() { $q = new Doctrine_Query(); $q->select('c.*, b.name')->from('ColumnAliasTest c') - ->innerJoin('c.book b') - ->where('c.anotherField = ?', 'camelCase'); + ->innerJoin('c.book b') + ->where('c.anotherField = ?', 'camelCase') + ; $result = $q->execute(); $this->assertTrue(isset($result[0]->book)); $this->assertEqual($result[0]->book->name, 'Das Boot'); } - + public function testAliasesAreSupportedForArrayFetching() { $q = new Doctrine_Query(); $q->select('c.*, b.name')->from('ColumnAliasTest c') - ->innerJoin('c.book b') - ->where('c.anotherField = ?', 'camelCase') - ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY); + ->innerJoin('c.book b') + ->where('c.anotherField = ?', 'camelCase') + ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) + ; $result = $q->execute(); $this->assertEqual($result[0]['alias1'], 'first'); $this->assertEqual($result[0]['alias2'], 123); @@ -89,18 +97,18 @@ public function testAliasesAreSupportedForArrayFetching() public function testAliasesAreSupportedForRecordPropertyAccessors() { - $record = new ColumnAliasTest; + $record = new ColumnAliasTest(); try { $record->alias1 = 'someone'; $record->alias2 = 187; - + $this->assertEqual($record->alias1, 'someone'); $this->assertEqual($record->alias2, 187); } catch (Doctrine_Record_Exception $e) { $this->fail(); } } - + public function testAliasesAreSupportedForDqlSelectPart() { $q = new Doctrine_Query(); @@ -111,14 +119,15 @@ public function testAliasesAreSupportedForDqlSelectPart() $this->assertEqual($coll[0]->alias2, 123); $this->assertEqual($coll[0]->anotherField, 'camelCase'); } - + public function testAliasesAreSupportedForDqlWherePart() { $q = new Doctrine_Query(); $q->select('c.alias1, c.alias2, c.anotherField') - ->from('ColumnAliasTest c') - ->where('c.anotherField = ?'); + ->from('ColumnAliasTest c') + ->where('c.anotherField = ?') + ; $coll = $q->execute(array('KoQ')); @@ -126,7 +135,7 @@ public function testAliasesAreSupportedForDqlWherePart() $this->assertEqual($coll[0]->alias2, 456); $this->assertEqual($coll[0]->anotherField, 'KoQ'); } - + public function testAliasesAreSupportedForDqlAggregateFunctions() { $q = new Doctrine_Query(); @@ -137,19 +146,19 @@ public function testAliasesAreSupportedForDqlAggregateFunctions() $this->assertEqual($coll[0]->MAX, 456); } - + public function testAliasesAreSupportedForDqlHavingPart() { $q = new Doctrine_Query(); $q->select('c.alias2') - ->from('ColumnAliasTest c') - ->groupby('c.id') - ->having('c.alias2 > 123'); + ->from('ColumnAliasTest c') + ->groupby('c.id') + ->having('c.alias2 > 123') + ; $coll = $q->execute(); - + $this->assertEqual($coll[0]->alias2, 456); } } - diff --git a/tests/CompositePrimaryKeyTestCase.php b/tests/CompositePrimaryKeyTestCase.php index 075a0f220..0693910be 100644 --- a/tests/CompositePrimaryKeyTestCase.php +++ b/tests/CompositePrimaryKeyTestCase.php @@ -1,13 +1,23 @@ tables = array(); - $this->tables[] = "CPK_Test"; - $this->tables[] = "CPK_Test2"; - $this->tables[] = "CPK_Association"; - + $this->tables[] = 'CPK_Test'; + $this->tables[] = 'CPK_Test2'; + $this->tables[] = 'CPK_Association'; + parent::prepareTables(); } } diff --git a/tests/ConcreteInheritanceTestCase.php b/tests/ConcreteInheritanceTestCase.php index b4ca5dc23..04a5c0a17 100644 --- a/tests/ConcreteInheritanceTestCase.php +++ b/tests/ConcreteInheritanceTestCase.php @@ -20,21 +20,26 @@ */ /** - * Doctrine_ConcreteInheritance_TestCase + * Doctrine_ConcreteInheritance_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_ConcreteInheritance_TestCase extends Doctrine_UnitTestCase +class Doctrine_ConcreteInheritance_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { - } } @@ -61,4 +66,4 @@ public function setTableDefinition() parent::setTableDefinition(); $this->hasColumn('child_column', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/ConfigurableTestCase.php b/tests/ConfigurableTestCase.php index 4ace013b6..376add00b 100644 --- a/tests/ConfigurableTestCase.php +++ b/tests/ConfigurableTestCase.php @@ -1,14 +1,18 @@ connection->getTable('Entity')->setAttribute(Doctrine_Core::ATTR_IDXNAME_FORMAT, '%s_idx'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } @@ -56,7 +60,7 @@ public function testExceptionIsThrownWhenSettingSequenceNameFormatAttributeAtTab try { $this->connection->getTable('Entity')->setAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT, '%s_seq'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } @@ -67,7 +71,7 @@ public function testSettingFieldCaseIsSuccesfulWithZero() try { $this->connection->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, 0); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->connection->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, $original); @@ -79,7 +83,7 @@ public function testSettingFieldCaseIsSuccesfulWithCaseConstants() try { $this->connection->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, CASE_LOWER); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->connection->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, $original); @@ -91,7 +95,7 @@ public function testSettingFieldCaseIsSuccesfulWithCaseConstants2() try { $this->connection->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, CASE_UPPER); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->connection->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, $original); @@ -102,7 +106,7 @@ public function testExceptionIsThrownWhenSettingFieldCaseToNotZeroOneOrTwo() try { $this->connection->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, -1); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } @@ -112,7 +116,7 @@ public function testExceptionIsThrownWhenSettingFieldCaseToNotZeroOneOrTwo2() try { $this->connection->setAttribute(Doctrine_Core::ATTR_FIELD_CASE, 5); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } @@ -147,7 +151,7 @@ public function testSequenceColumnNameAttributeAcceptsStrings() public function testValidatorAttributeAcceptsBooleans() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, true); - + $this->assertEqual($this->manager->getAttribute(Doctrine_Core::ATTR_VALIDATE), true); $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, false); } @@ -161,14 +165,14 @@ public function testPortabilityAttributeAcceptsPortabilityConstants() { $this->manager->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_RTRIM | Doctrine_Core::PORTABILITY_FIX_CASE); - $this->assertEqual($this->manager->getAttribute(Doctrine_Core::ATTR_PORTABILITY), - Doctrine_Core::PORTABILITY_RTRIM | Doctrine_Core::PORTABILITY_FIX_CASE); + $this->assertEqual($this->manager->getAttribute(Doctrine_Core::ATTR_PORTABILITY), + Doctrine_Core::PORTABILITY_RTRIM | Doctrine_Core::PORTABILITY_FIX_CASE); $this->manager->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL); } public function testDefaultListenerIsDoctrineEventListener() { - $this->assertTrue($this->manager->getAttribute(Doctrine_Core::ATTR_LISTENER) instanceof Doctrine_EventListener); + $this->assertTrue($this->manager->getAttribute(Doctrine_Core::ATTR_LISTENER) instanceof Doctrine_EventListener); } public function testListenerAttributeAcceptsEventListenerObjects() @@ -185,9 +189,9 @@ public function testCollectionKeyAttributeAcceptsValidColumnName() $original = $this->connection->getTable('User')->getAttribute(Doctrine_Core::ATTR_COLL_KEY); try { $this->connection->getTable('User')->setAttribute(Doctrine_Core::ATTR_COLL_KEY, 'name'); - + $this->pass(); - } catch(Exception $e) { + } catch (Exception $e) { $this->fail(); } $this->connection->getTable('User')->setAttribute(Doctrine_Core::ATTR_COLL_KEY, $original); @@ -197,9 +201,9 @@ public function testSettingInvalidColumnNameToCollectionKeyAttributeThrowsExcept { try { $this->connection->getTable('User')->setAttribute(Doctrine_Core::ATTR_COLL_KEY, 'unknown'); - + $this->fail(); - } catch(Exception $e) { + } catch (Exception $e) { $this->pass(); } } @@ -208,9 +212,9 @@ public function testSettingCollectionKeyAttributeOnOtherThanTableLevelThrowsExce { try { $this->connection->setAttribute(Doctrine_Core::ATTR_COLL_KEY, 'name'); - + $this->fail(); - } catch(Exception $e) { + } catch (Exception $e) { $this->pass(); } } @@ -219,4 +223,4 @@ public function testGetAttributes() { $this->assertTrue(is_array($this->manager->getAttributes())); } -} \ No newline at end of file +} diff --git a/tests/Connection/CustomTestCase.php b/tests/Connection/CustomTestCase.php index 6fd75b448..c8c2c1572 100644 --- a/tests/Connection/CustomTestCase.php +++ b/tests/Connection/CustomTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Connection_Custom_TestCase + * Doctrine_Connection_Custom_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Connection_Custom_TestCase extends Doctrine_UnitTestCase +class Doctrine_Connection_Custom_TestCase extends Doctrine_UnitTestCase { protected $_conn; protected $_dbh; @@ -50,10 +56,15 @@ public function testConnection() } } +/** + * @internal + * + * @coversNothing + */ class Doctrine_Connection_Test extends Doctrine_Connection_Common { /** - * @var string $driverName The name of this connection driver + * @var string The name of this connection driver */ protected $driverName = 'Mock'; } @@ -115,4 +126,4 @@ public function setAttribute($attribute, $value) public function sqliteCreateFunction() { } -} \ No newline at end of file +} diff --git a/tests/Connection/MssqlTestCase.php b/tests/Connection/MssqlTestCase.php index c17571f11..464ea7add 100644 --- a/tests/Connection/MssqlTestCase.php +++ b/tests/Connection/MssqlTestCase.php @@ -20,70 +20,77 @@ */ /** - * Doctrine_Connection_Mssql_TestCase + * Doctrine_Connection_Mssql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Connection_Mssql_TestCase extends Doctrine_UnitTestCase { - public function testAlreadyExistsErrorIsSupported() { + public function testAlreadyExistsErrorIsSupported() + { $this->assertTrue($this->exc->processErrorInfo(array(0, 2714, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ALREADY_EXISTS); } public function testAlreadyExistsErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1913, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ALREADY_EXISTS); } public function testValueCountOnRowErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 110, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_VALUE_COUNT_ON_ROW); } public function testNoSuchFieldErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 155, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } public function testNoSuchFieldErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 207, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } public function testNoSuchTableErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 208, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } public function testNoSuchTableErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 3701, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } public function testSyntaxErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 170, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } @@ -121,4 +128,4 @@ public function testDivZeroErrorIsSupported() $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_DIVZERO); } -} \ No newline at end of file +} diff --git a/tests/Connection/MysqlTestCase.php b/tests/Connection/MysqlTestCase.php index df42d32a2..18dade069 100644 --- a/tests/Connection/MysqlTestCase.php +++ b/tests/Connection/MysqlTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Connection_Mysql_TestCase + * Doctrine_Connection_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Connection_Mysql_TestCase extends Doctrine_UnitTestCase { @@ -41,28 +47,28 @@ public function testQuoteIdentifier() public function testNotLockedErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1100, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOT_LOCKED); } public function testNotFoundErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1091, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOT_FOUND); } public function testSyntaxErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1064, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } public function testNoSuchDbErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1049, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHDB); } @@ -76,21 +82,21 @@ public function testNoSuchFieldErrorIsSupported() public function testNoSuchTableErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1051, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } public function testNoSuchTableErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1146, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } public function testConstraintErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1048, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } @@ -104,70 +110,70 @@ public function testConstraintErrorIsSupported2() public function testConstraintErrorIsSupported3() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1217, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } public function testNoDbSelectedErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1046, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NODBSELECTED); } public function testAccessViolationErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1142, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ACCESS_VIOLATION); } public function testAccessViolationErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1044, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ACCESS_VIOLATION); } public function testCannotDropErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1008, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CANNOT_DROP); } public function testCannotCreateErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1004, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CANNOT_CREATE); } public function testCannotCreateErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1005, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CANNOT_CREATE); } public function testCannotCreateErrorIsSupported3() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1006, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CANNOT_CREATE); } public function testAlreadyExistsErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1007, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ALREADY_EXISTS); } public function testAlreadyExistsErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1022, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ALREADY_EXISTS); } @@ -188,14 +194,14 @@ public function testAlreadyExistsErrorIsSupported4() public function testAlreadyExistsErrorIsSupported5() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1062, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ALREADY_EXISTS); } public function testValueCountOnRowErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 1136, ''))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_VALUE_COUNT_ON_ROW); } -} \ No newline at end of file +} diff --git a/tests/Connection/OracleTestCase.php b/tests/Connection/OracleTestCase.php index 73f547c2a..258198dee 100644 --- a/tests/Connection/OracleTestCase.php +++ b/tests/Connection/OracleTestCase.php @@ -20,71 +20,77 @@ */ /** - * Doctrine_Connection_Oracle_TestCase + * Doctrine_Connection_Oracle_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Connection_Oracle_TestCase extends Doctrine_UnitTestCase +class Doctrine_Connection_Oracle_TestCase extends Doctrine_UnitTestCase { public function testNoSuchTableErrorIsSupported() { $this->exc->processErrorInfo(array(0, 942, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } public function testSyntaxErrorIsSupported() { $this->exc->processErrorInfo(array(0, 900, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } public function testSyntaxErrorIsSupported2() { $this->exc->processErrorInfo(array(0, 921, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } public function testSyntaxErrorIsSupported3() { $this->exc->processErrorInfo(array(0, 923, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } public function testNoSuchFieldErrorIsSupported() { $this->exc->processErrorInfo(array(0, 904, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } public function testConstraintErrorIsSupported() { $this->exc->processErrorInfo(array(0, 1, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } public function testConstraintErrorIsSupported2() { $this->exc->processErrorInfo(array(0, 2291, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } public function testConstraintErrorIsSupported3() { $this->exc->processErrorInfo(array(0, 2449, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } @@ -98,63 +104,63 @@ public function testConstraintErrorIsSupported4() public function testNoSuchTableErrorIsSupported4() { $this->exc->processErrorInfo(array(0, 2289, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } public function testInvalidNumberErrorIsSupported() { $this->exc->processErrorInfo(array(0, 1722, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_INVALID_NUMBER); } public function testDivZeroErrorIsSupported1() { $this->exc->processErrorInfo(array(0, 1476, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_DIVZERO); } public function testNotFoundErrorIsSupported() { $this->exc->processErrorInfo(array(0, 1418, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOT_FOUND); } public function testNotNullConstraintErrorIsSupported() { $this->exc->processErrorInfo(array(0, 1400, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT_NOT_NULL); } public function testNotNullConstraintErrorIsSupported2() { $this->exc->processErrorInfo(array(0, 1407, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT_NOT_NULL); } public function testInvalidErrorIsSupported() { $this->exc->processErrorInfo(array(0, 1401, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_INVALID); } public function testAlreadyExistsErrorIsSupported() { $this->exc->processErrorInfo(array(0, 955, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ALREADY_EXISTS); } - + public function testValueCountOnRowErrorIsSupported() { $this->exc->processErrorInfo(array(0, 913, '')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_VALUE_COUNT_ON_ROW); } -} \ No newline at end of file +} diff --git a/tests/Connection/PgsqlTestCase.php b/tests/Connection/PgsqlTestCase.php index 63411a0f3..8c203db48 100644 --- a/tests/Connection/PgsqlTestCase.php +++ b/tests/Connection/PgsqlTestCase.php @@ -20,198 +20,203 @@ */ /** - * Doctrine_Connection_Pgsql_TestCase + * Doctrine_Connection_Pgsql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Connection_Pgsql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Connection_Pgsql_TestCase extends Doctrine_UnitTestCase { - - public function testNoSuchTableErrorIsSupported() + public function testNoSuchTableErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'table test does not exist'))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } - public function testNoSuchTableErrorIsSupported2() + public function testNoSuchTableErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'relation does not exist'))); $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } - public function testNoSuchTableErrorIsSupported3() + public function testNoSuchTableErrorIsSupported3() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'sequence does not exist'))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } - public function testNoSuchTableErrorIsSupported4() + public function testNoSuchTableErrorIsSupported4() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'class xx not found'))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } - public function testSyntaxErrorIsSupported() + public function testSyntaxErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'parser: parse error at or near'))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } - public function testSyntaxErrorIsSupported2() + public function testSyntaxErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'syntax error at'))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } - public function testSyntaxErrorIsSupported3() + public function testSyntaxErrorIsSupported3() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'column reference r.r is ambiguous'))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } - public function testInvalidNumberErrorIsSupported() + public function testInvalidNumberErrorIsSupported() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'pg_atoi: error in somewhere: can\'t parse '))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_INVALID_NUMBER); } - public function testInvalidNumberErrorIsSupported2() + public function testInvalidNumberErrorIsSupported2() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'value unknown is out of range for type bigint'))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_INVALID_NUMBER); } - public function testInvalidNumberErrorIsSupported3() + public function testInvalidNumberErrorIsSupported3() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'integer out of range'))); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_INVALID_NUMBER); } - public function testInvalidNumberErrorIsSupported4() + public function testInvalidNumberErrorIsSupported4() { $this->assertTrue($this->exc->processErrorInfo(array(0, 0, 'invalid input syntax for type integer'))); $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_INVALID_NUMBER); } - public function testNoSuchFieldErrorIsSupported() + public function testNoSuchFieldErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'column name (of relation xx) does not exist')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } - public function testNoSuchFieldErrorIsSupported2() + public function testNoSuchFieldErrorIsSupported2() { $this->exc->processErrorInfo(array(0, 0, 'attribute xx not found')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } - public function testNoSuchFieldErrorIsSupported3() + public function testNoSuchFieldErrorIsSupported3() { $this->exc->processErrorInfo(array(0, 0, 'relation xx does not have attribute')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } - public function testNoSuchFieldErrorIsSupported4() + public function testNoSuchFieldErrorIsSupported4() { $this->exc->processErrorInfo(array(0, 0, 'column xx specified in USING clause does not exist in left table')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } - public function testNoSuchFieldErrorIsSupported5() + public function testNoSuchFieldErrorIsSupported5() { $this->exc->processErrorInfo(array(0, 0, 'column xx specified in USING clause does not exist in right table')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } - public function testNotFoundErrorIsSupported() + public function testNotFoundErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'index xx does not exist/')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOT_FOUND); } - - public function testNotNullConstraintErrorIsSupported() + + public function testNotNullConstraintErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'violates not-null constraint')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT_NOT_NULL); } - public function testConstraintErrorIsSupported() + public function testConstraintErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'referential integrity violation')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } - public function testConstraintErrorIsSupported2() + public function testConstraintErrorIsSupported2() { $this->exc->processErrorInfo(array(0, 0, 'violates xx constraint')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } public function testInvalidErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'value too long for type character')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_INVALID); } - public function testAlreadyExistsErrorIsSupported() + public function testAlreadyExistsErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'relation xx already exists')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ALREADY_EXISTS); } - public function testDivZeroErrorIsSupported() + public function testDivZeroErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'division by zero')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_DIVZERO); } - public function testDivZeroErrorIsSupported2() + public function testDivZeroErrorIsSupported2() { $this->exc->processErrorInfo(array(0, 0, 'divide by zero')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_DIVZERO); } public function testAccessViolationErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'permission denied')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_ACCESS_VIOLATION); } - - public function testValueCountOnRowErrorIsSupported() + + public function testValueCountOnRowErrorIsSupported() { $this->exc->processErrorInfo(array(0, 0, 'more expressions than target columns')); - + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_VALUE_COUNT_ON_ROW); } } diff --git a/tests/Connection/ProfilerTestCase.php b/tests/Connection/ProfilerTestCase.php index 03d70ec13..9ca0ace1d 100644 --- a/tests/Connection/ProfilerTestCase.php +++ b/tests/Connection/ProfilerTestCase.php @@ -20,27 +20,37 @@ */ /** - * Doctrine_Connection_Profiler_TestCase + * Doctrine_Connection_Profiler_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Db * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Connection_Profiler_TestCase extends Doctrine_UnitTestCase +class Doctrine_Connection_Profiler_TestCase extends Doctrine_UnitTestCase { public function prepareTables() - {} - public function prepareData() - {} - public function setUp() - {} + { + } - public function testQuery() + public function prepareData() + { + } + + public function setUp() + { + } + + public function testQuery() { $this->conn = Doctrine_Manager::getInstance()->openConnection(array('sqlite::memory:')); @@ -49,19 +59,18 @@ public function testQuery() $this->conn->setListener($this->profiler); $this->conn->exec('CREATE TABLE test (id INT)'); - + $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'CREATE TABLE test (id INT)'); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Event::CONN_EXEC); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + $this->assertEqual($this->conn->count(), 1); } public function testPrepareAndExecute() { - - $stmt = $this->conn->prepare('INSERT INTO test (id) VALUES (?)'); + $stmt = $this->conn->prepare('INSERT INTO test (id) VALUES (?)'); $event = $this->profiler->lastEvent(); $this->assertEqual($event->getQuery(), 'INSERT INTO test (id) VALUES (?)'); @@ -81,7 +90,6 @@ public function testPrepareAndExecute() public function testMultiplePrepareAndExecute() { - $stmt = $this->conn->prepare('INSERT INTO test (id) VALUES (?)'); $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'INSERT INTO test (id) VALUES (?)'); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); @@ -93,28 +101,27 @@ public function testMultiplePrepareAndExecute() $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Event::CONN_PREPARE); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - /** TODO: strange errors here - $stmt->execute(array(1)); - $stmt2->execute(array(1)); - - $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'INSERT INTO test (id) VALUES (?)'); - $this->assertTrue($this->profiler->lastEvent()->hasEnded()); - $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Event::EXECUTE); - $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - - $this->assertEqual($this->conn->count(), 4); - */ + /* TODO: strange errors here + * $stmt->execute(array(1)); + * $stmt2->execute(array(1)); + * + * $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'INSERT INTO test (id) VALUES (?)'); + * $this->assertTrue($this->profiler->lastEvent()->hasEnded()); + * $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Event::EXECUTE); + * $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); + * + * $this->assertEqual($this->conn->count(), 4); + */ } - - public function testExecuteStatementMultipleTimes() + + public function testExecuteStatementMultipleTimes() { try { $stmt = $this->conn->prepare('INSERT INTO test (id) VALUES (?)'); $stmt->execute(array(1)); $stmt->execute(array(1)); $this->pass(); - } catch(Doctrine_Db_Exception $e) { - + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'INSERT INTO test (id) VALUES (?)'); @@ -128,23 +135,23 @@ public function testExecuteStatementMultipleTimes() $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); } - public function testTransactionRollback() + public function testTransactionRollback() { try { $this->conn->beginTransaction(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), null); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Event::TX_BEGIN); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + try { $this->conn->rollback(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } @@ -154,23 +161,23 @@ public function testTransactionRollback() $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); } - public function testTransactionCommit() + public function testTransactionCommit() { try { $this->conn->beginTransaction(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), null); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Event::TX_BEGIN); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + try { $this->conn->commit(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); $this->conn->rollback(); } diff --git a/tests/Connection/SqliteTestCase.php b/tests/Connection/SqliteTestCase.php index 6e3eec3f0..ddc378217 100644 --- a/tests/Connection/SqliteTestCase.php +++ b/tests/Connection/SqliteTestCase.php @@ -20,92 +20,98 @@ */ /** - * Doctrine_Connection_Sqlite_TestCase + * Doctrine_Connection_Sqlite_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Connection_Sqlite_TestCase extends Doctrine_UnitTestCase { public function testNoSuchTableErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, 'no such table: test1')); - + $this->exc->processErrorInfo(array(0, 0, 'no such table: test1')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHTABLE); } public function testNoSuchIndexErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, 'no such index: test1')); - + $this->exc->processErrorInfo(array(0, 0, 'no such index: test1')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOT_FOUND); } public function testUniquePrimaryKeyErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, 'PRIMARY KEY must be unique')); - + $this->exc->processErrorInfo(array(0, 0, 'PRIMARY KEY must be unique')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } public function testIsNotUniqueErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, 'is not unique')); - + $this->exc->processErrorInfo(array(0, 0, 'is not unique')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } public function testColumnsNotUniqueErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, 'columns name, id are not unique')); - + $this->exc->processErrorInfo(array(0, 0, 'columns name, id are not unique')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } public function testUniquenessConstraintErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, 'uniqueness constraint failed')); - + $this->exc->processErrorInfo(array(0, 0, 'uniqueness constraint failed')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT); } public function testNotNullConstraintErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, 'may not be NULL')); - + $this->exc->processErrorInfo(array(0, 0, 'may not be NULL')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_CONSTRAINT_NOT_NULL); } public function testNoSuchFieldErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, 'no such column: column1')); - + $this->exc->processErrorInfo(array(0, 0, 'no such column: column1')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } public function testColumnNotPresentInTablesErrorIsSupported2() { - $this->exc->processErrorInfo(array(0,0, 'column not present in both tables')); - + $this->exc->processErrorInfo(array(0, 0, 'column not present in both tables')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_NOSUCHFIELD); } public function testNearSyntaxErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, "near \"SELECT FROM\": syntax error")); - + $this->exc->processErrorInfo(array(0, 0, 'near "SELECT FROM": syntax error')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_SYNTAX); } public function testValueCountOnRowErrorIsSupported() { - $this->exc->processErrorInfo(array(0,0, '3 values for 2 columns')); - + $this->exc->processErrorInfo(array(0, 0, '3 values for 2 columns')); + $this->assertEqual($this->exc->getPortableCode(), Doctrine_Core::ERR_VALUE_COUNT_ON_ROW); } -} \ No newline at end of file +} diff --git a/tests/Connection/UnitOfWork.php b/tests/Connection/UnitOfWork.php index f368447a6..8770ef861 100644 --- a/tests/Connection/UnitOfWork.php +++ b/tests/Connection/UnitOfWork.php @@ -20,26 +20,32 @@ */ /** - * Doctrine_Connection_UnitOfWork_TestCase + * Doctrine_Connection_UnitOfWork_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Connection_UnitOfWork_TestCase extends Doctrine_UnitTestCase +class Doctrine_Connection_UnitOfWork_TestCase extends Doctrine_UnitTestCase { - public function testFlush() + public function testFlush() { $user = $this->connection->getTable('User')->find(4); $this->assertTrue(is_numeric($user->Phonenumber[0]->entity_id)); - $user = $this->connection->create('Email'); - $user = $this->connection->create('User'); - $record = $this->connection->create('Phonenumber'); + $user = $this->connection->create('Email'); + $user = $this->connection->create('User'); + $record = $this->connection->create('Phonenumber'); $user->Email->address = 'example@drinkmore.info'; $this->assertTrue($user->email_id instanceof Email); @@ -54,8 +60,6 @@ public function testFlush() $user->Phonenumber[2]->phonenumber = '123 123'; $user->Phonenumber[3]->phonenumber = '321 2132'; - - $this->assertTrue($user->Phonenumber[0]->entity_id instanceof User); $this->assertTrue($user->Phonenumber[2]->entity_id instanceof User); @@ -77,18 +81,17 @@ public function testFlush() $this->assertTrue($user->Phonenumber->count(), 4); $this->assertEqual($user->Group->count(), 2); - $user = $this->objTable->find(5); - $pf = $this->connection->getTable('Phonenumber'); + $pf = $this->connection->getTable('Phonenumber'); $this->assertTrue($user->Phonenumber instanceof Doctrine_Collection); - $this->assertTrue($user->Phonenumber->count() == 3); + $this->assertTrue(3 == $user->Phonenumber->count()); $coll = new Doctrine_Collection($pf); $user->Phonenumber = $coll; - $this->assertTrue($user->Phonenumber->count() == 0); + $this->assertTrue(0 == $user->Phonenumber->count()); $this->connection->flush(); unset($user); @@ -104,7 +107,6 @@ public function testFlush() $user->Phonenumber[1]->phonenumber = '123 123'; $this->connection->flush(); - $this->assertEqual($user->Phonenumber->count(), 2); unset($user); @@ -127,7 +129,7 @@ public function testFlush() unset($user); $user = $this->objTable->find(5); $this->assertEqual($user->Phonenumber->count(), 0); - + // ADDING REFERENCES WITH STRING KEYS $user->Phonenumber['home']->phonenumber = '123 123'; @@ -149,16 +151,12 @@ public function testFlush() $coll['home']->phonenumber = '444 444'; $coll['work']->phonenumber = '444 444'; - - - $user->Phonenumber = $coll; $this->connection->flush(); $this->assertEqual($user->Phonenumber->count(), 3); $user = $this->objTable->find(5); $this->assertEqual($user->Phonenumber->count(), 3); - // ONE-TO-ONE REFERENCES $user->Email->address = 'drinker@drinkmore.info'; @@ -183,31 +181,27 @@ public function testFlush() $user = $this->objTable->find(5); $this->assertTrue($user->Email instanceof Email); $this->assertEqual($user->Email->address, 'absolutist@nottodrink.com'); - - $emails = $this->connection->query("FROM Email WHERE Email.id = $id"); - //$this->assertEqual(count($emails),0); + + $emails = $this->connection->query("FROM Email WHERE Email.id = {$id}"); + // $this->assertEqual(count($emails),0); } - public function testTransactions() + public function testTransactions() { - $this->connection->beginTransaction(); - $this->assertEqual($this->connection->transaction->getState(),Doctrine_Transaction::STATE_ACTIVE); + $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_ACTIVE); $this->connection->commit(); - $this->assertEqual($this->connection->transaction->getState(),Doctrine_Transaction::STATE_SLEEP); + $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_SLEEP); $this->connection->beginTransaction(); - + $user = $this->objTable->find(6); - + $user->name = 'Jack Daniels'; $this->connection->flush(); $this->connection->commit(); $user = $this->objTable->find(6); $this->assertEqual($user->name, 'Jack Daniels'); - } - - } diff --git a/tests/ConnectionTestCase.php b/tests/ConnectionTestCase.php index 70d3f28be..5bf6ef5c1 100644 --- a/tests/ConnectionTestCase.php +++ b/tests/ConnectionTestCase.php @@ -20,39 +20,44 @@ */ /** - * Doctrine_Connection_TestCase + * Doctrine_Connection_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Connection_TestCase extends Doctrine_UnitTestCase +class Doctrine_Connection_TestCase extends Doctrine_UnitTestCase { - - public function testUnknownModule() + public function testUnknownModule() { try { $this->connection->unknown; $this->fail(); - } catch(Doctrine_Connection_Exception $e) { + } catch (Doctrine_Connection_Exception $e) { $this->pass(); } } - public function testGetModule() + public function testGetModule() { $this->assertTrue($this->connection->unitOfWork instanceof Doctrine_Connection_UnitOfWork); - //$this->assertTrue($this->connection->dataDict instanceof Doctrine_DataDict); + // $this->assertTrue($this->connection->dataDict instanceof Doctrine_DataDict); $this->assertTrue($this->connection->expression instanceof Doctrine_Expression_Driver); $this->assertTrue($this->connection->transaction instanceof Doctrine_Transaction); $this->assertTrue($this->connection->export instanceof Doctrine_Export); } - public function testFetchAll() + public function testFetchAll() { $this->conn->exec('DROP TABLE entity'); $this->conn->exec('CREATE TABLE entity (id INT, name TEXT)'); @@ -62,94 +67,90 @@ public function testFetchAll() $a = $this->conn->fetchAll('SELECT * FROM entity'); - - $this->assertEqual($a, array ( - 0 => - array ( - 'id' => '1', - 'name' => 'zYne', - ), - 1 => - array ( - 'id' => '2', - 'name' => 'John', - ), - )); + $this->assertEqual($a, array( + 0 => array( + 'id' => '1', + 'name' => 'zYne', + ), + 1 => array( + 'id' => '2', + 'name' => 'John', + ), + )); } public function testFetchOne() { $c = $this->conn->fetchOne('SELECT COUNT(1) FROM entity'); - + $this->assertEqual($c, 2); - + $c = $this->conn->fetchOne('SELECT COUNT(1) FROM entity WHERE id = ?', array(1)); - + $this->assertEqual($c, 1); } - - public function testFetchColumn() + public function testFetchColumn() { $a = $this->conn->fetchColumn('SELECT * FROM entity'); - $this->assertEqual($a, array ( - 0 => '1', - 1 => '2', - )); + $this->assertEqual($a, array( + 0 => '1', + 1 => '2', + )); $a = $this->conn->fetchColumn('SELECT * FROM entity WHERE id = ?', array(1)); - $this->assertEqual($a, array ( - 0 => '1', - )); + $this->assertEqual($a, array( + 0 => '1', + )); } - public function testFetchArray() + public function testFetchArray() { $a = $this->conn->fetchArray('SELECT * FROM entity'); - $this->assertEqual($a, array ( - 0 => '1', - 1 => 'zYne', - )); + $this->assertEqual($a, array( + 0 => '1', + 1 => 'zYne', + )); $a = $this->conn->fetchArray('SELECT * FROM entity WHERE id = ?', array(1)); - $this->assertEqual($a, array ( - 0 => '1', - 1 => 'zYne', - )); + $this->assertEqual($a, array( + 0 => '1', + 1 => 'zYne', + )); } - public function testFetchRow() + public function testFetchRow() { $c = $this->conn->fetchRow('SELECT * FROM entity'); - $this->assertEqual($c, array ( - 'id' => '1', - 'name' => 'zYne', - )); + $this->assertEqual($c, array( + 'id' => '1', + 'name' => 'zYne', + )); $c = $this->conn->fetchRow('SELECT * FROM entity WHERE id = ?', array(1)); - - $this->assertEqual($c, array ( - 'id' => '1', - 'name' => 'zYne', - )); + + $this->assertEqual($c, array( + 'id' => '1', + 'name' => 'zYne', + )); } - public function testFetchPairs() + public function testFetchPairs() { $this->conn->exec('DROP TABLE entity'); } - public function testGetManager() + public function testGetManager() { $this->assertTrue($this->connection->getManager() === $this->manager); } - public function testDeleteOnTransientRecordIsIgnored() + public function testDeleteOnTransientRecordIsIgnored() { $user = $this->connection->create('User'); try { @@ -159,80 +160,79 @@ public function testDeleteOnTransientRecordIsIgnored() } } - public function testGetTable() + public function testGetTable() { $table = $this->connection->getTable('Group'); $this->assertTrue($table instanceof Doctrine_Table); try { $table = $this->connection->getTable('Unknown'); $f = false; - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $f = true; } $this->assertTrue($f); $table = $this->connection->getTable('User'); $this->assertTrue($table instanceof UserTable); - } - public function testCreate() + public function testCreate() { $email = $this->connection->create('Email'); $this->assertTrue($email instanceof Email); } - public function testGetDbh() + public function testGetDbh() { $this->assertTrue($this->connection->getDbh() instanceof PDO); } - public function testCount() + public function testCount() { $this->assertTrue(is_integer(count($this->connection))); } - public function testGetIterator() + public function testGetIterator() { $this->assertTrue($this->connection->getIterator() instanceof ArrayIterator); } public function testGetState() { - $this->assertEqual($this->connection->transaction->getState(),Doctrine_Transaction::STATE_SLEEP); + $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_SLEEP); $this->assertEqual(Doctrine_Lib::getConnectionStateAsString($this->connection->transaction->getState()), 'open'); } - public function testGetTables() + public function testGetTables() { $this->assertTrue(is_array($this->connection->getTables())); } - public function testRollback() + public function testRollback() { $this->connection->beginTransaction(); - $this->assertEqual($this->connection->transaction->getTransactionLevel(),1); + $this->assertEqual($this->connection->transaction->getTransactionLevel(), 1); $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_ACTIVE); $this->connection->rollback(); $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_SLEEP); - $this->assertEqual($this->connection->transaction->getTransactionLevel(),0); + $this->assertEqual($this->connection->transaction->getTransactionLevel(), 0); } public function testNestedTransactions() { - $this->assertEqual($this->connection->transaction->getTransactionLevel(),0); + $this->assertEqual($this->connection->transaction->getTransactionLevel(), 0); $this->connection->beginTransaction(); - $this->assertEqual($this->connection->transaction->getTransactionLevel(),1); + $this->assertEqual($this->connection->transaction->getTransactionLevel(), 1); $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_ACTIVE); $this->connection->beginTransaction(); $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_BUSY); - $this->assertEqual($this->connection->transaction->getTransactionLevel(),2); + $this->assertEqual($this->connection->transaction->getTransactionLevel(), 2); $this->connection->commit(); $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_ACTIVE); - $this->assertEqual($this->connection->transaction->getTransactionLevel(),1); + $this->assertEqual($this->connection->transaction->getTransactionLevel(), 1); $this->connection->commit(); $this->assertEqual($this->connection->transaction->getState(), Doctrine_Transaction::STATE_SLEEP); - $this->assertEqual($this->connection->transaction->getTransactionLevel(),0); + $this->assertEqual($this->connection->transaction->getTransactionLevel(), 0); } public function testSqliteDsn() diff --git a/tests/ConnectionTransactionTestCase.php b/tests/ConnectionTransactionTestCase.php index 44e1970b9..7e3dd163f 100644 --- a/tests/ConnectionTransactionTestCase.php +++ b/tests/ConnectionTransactionTestCase.php @@ -3,7 +3,7 @@ class Transaction_TestLogger implements Doctrine_Overloadable { private $messages = array(); - + public function __call($m, $a) { $this->messages[] = $m; @@ -25,18 +25,21 @@ public function getAll() } } +/** + * @internal + * + * @coversNothing + */ class Doctrine_Connection_Transaction_TestCase extends Doctrine_UnitTestCase { public function prepareData() { - } public function testInsert() { $count = count($this->dbh); - $listener = new Transaction_TestLogger(); $user = new User(); @@ -57,7 +60,7 @@ public function testInsert() $this->assertEqual($listener->pop(), 'onPreTransactionBegin'); $this->assertEqual($user->id, 1); - + $this->assertTrue($count < count($this->dbh)); $this->connection->commit(); @@ -70,7 +73,6 @@ public function testInsertMultiple() { $count = count($this->dbh); - $listener = new Transaction_TestLogger(); $users = new Doctrine_Collection('User'); @@ -84,7 +86,6 @@ public function testInsertMultiple() $users[0]->save(); $users[1]->save(); - $this->assertEqual($listener->pop(), 'onSave'); $this->assertEqual($listener->pop(), 'onInsert'); $this->assertEqual($listener->pop(), 'onPreInsert'); @@ -97,7 +98,7 @@ public function testInsertMultiple() $this->assertEqual($users[0]->id, 2); $this->assertEqual($users[1]->id, 3); - + $this->assertTrue($count < count($this->dbh)); $this->connection->commit(); @@ -110,9 +111,8 @@ public function testUpdate() { $count = count($this->dbh); - $user = $this->connection->getTable('User')->find(1); - + $listener = new Transaction_TestLogger(); $user->getTable()->getConnection()->setListener($listener); $this->connection->beginTransaction(); @@ -130,7 +130,7 @@ public function testUpdate() $this->assertEqual($listener->pop(), 'onPreTransactionBegin'); $this->assertEqual($user->id, 1); - + $this->assertTrue($count < count($this->dbh)); $this->connection->commit(); @@ -156,7 +156,6 @@ public function testUpdateMultiple() $users[1]->save(); $users[2]->save(); - $this->assertEqual($listener->pop(), 'onSave'); $this->assertEqual($listener->pop(), 'onUpdate'); $this->assertEqual($listener->pop(), 'onPreUpdate'); @@ -169,7 +168,7 @@ public function testUpdateMultiple() $this->assertEqual($users[1]->id, 2); $this->assertEqual($users[2]->id, 3); - + $this->assertTrue($count < count($this->dbh)); $this->connection->commit(); @@ -197,9 +196,9 @@ public function testDelete() $this->connection->commit(); - $this->assertTrue(($count + 1), count($this->dbh)); + $this->assertTrue($count + 1, count($this->dbh)); $this->assertEqual($listener->pop(), 'onTransactionCommit'); $this->assertEqual($listener->pop(), 'onPreTransactionCommit'); } -} \ No newline at end of file +} diff --git a/tests/CtiColumnAggregationInheritanceTestCase.php b/tests/CtiColumnAggregationInheritanceTestCase.php index c398771b9..93b498372 100644 --- a/tests/CtiColumnAggregationInheritanceTestCase.php +++ b/tests/CtiColumnAggregationInheritanceTestCase.php @@ -20,22 +20,28 @@ */ /** - * Doctrine_CtiColumnAggregation_TestCase + * Doctrine_CtiColumnAggregation_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_CtiColumnAggregationInheritance_TestCase extends Doctrine_UnitTestCase +class Doctrine_CtiColumnAggregationInheritance_TestCase extends Doctrine_UnitTestCase { - } abstract class CTICAAbstractBase extends Doctrine_Record -{ } +{ +} class CTICATestParent1 extends CTICAAbstractBase { public function setTableDefinition() @@ -47,16 +53,15 @@ class CTICATestParent2 extends CTICATestParent1 { public function setTableDefinition() { - parent::setTableDefinition(); + parent::setTableDefinition(); $this->hasColumn('verified', 'boolean', 1); $this->hasColumn('type', 'integer', 2); - - $this->setSubclasses(array( - 'CTICATest' => array('type' => 1), - 'CTICATest2' => array('type' => 2) - )); + $this->setSubclasses(array( + 'CTICATest' => array('type' => 1), + 'CTICATest2' => array('type' => 2), + )); } } class CTICATestParent3 extends CTICATestParent2 @@ -73,9 +78,13 @@ public function setTableDefinition() $this->hasColumn('age', 'integer', 4); } } +/** + * @internal + * + * @coversNothing + */ class CTICATest extends CTICATestParent4 { - } class CTICATest2 extends CTICATestParent2 { @@ -92,7 +101,7 @@ public function setTableDefinition() $this->hasColumn('name', 'string'); $this->hasColumn('cti_id', 'integer'); } - + public function setUp() { $this->hasMany('CTICATestParent1', array('local' => 'cti_id', 'foreign' => 'id')); diff --git a/tests/CustomPrimaryKeyTestCase.php b/tests/CustomPrimaryKeyTestCase.php index 90f94e0e4..0e8aacf76 100644 --- a/tests/CustomPrimaryKeyTestCase.php +++ b/tests/CustomPrimaryKeyTestCase.php @@ -20,44 +20,49 @@ */ /** - * Doctrine_CustomPrimaryKey_TestCase + * Doctrine_CustomPrimaryKey_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_CustomPrimaryKey_TestCase extends Doctrine_UnitTestCase +class Doctrine_CustomPrimaryKey_TestCase extends Doctrine_UnitTestCase { - public function prepareData() + public function prepareData() { - } - - public function prepareTables() + + public function prepareTables() { $this->tables = array('CustomPK'); - + parent::prepareTables(); } - public function testOperations() + public function testOperations() { $c = new CustomPK(); $this->assertTrue($c instanceof Doctrine_Record); $c->name = 'custom pk test'; $this->assertEqual($c->identifier(), array()); - + $c->save(); $this->assertEqual($c->identifier(), array('uid' => 1)); $this->connection->clear(); - + $c = $this->connection->getTable('CustomPK')->find(1); - + $this->assertEqual($c->identifier(), array('uid' => 1)); } -} \ No newline at end of file +} diff --git a/tests/CustomResultSetOrderTestCase.php b/tests/CustomResultSetOrderTestCase.php index 37c7794d8..2ecbb221e 100644 --- a/tests/CustomResultSetOrderTestCase.php +++ b/tests/CustomResultSetOrderTestCase.php @@ -20,69 +20,76 @@ */ /** - * Doctrine_CustomResultSetOrder_TestCase + * Doctrine_CustomResultSetOrder_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_CustomResultSetOrder_TestCase extends Doctrine_UnitTestCase { - +class Doctrine_CustomResultSetOrder_TestCase extends Doctrine_UnitTestCase +{ /** * Prepares the data under test. - * + * * 1st category: 3 Boards * 2nd category: 1 Board * 3rd category: 0 boards - * */ - public function prepareData() { + public function prepareData() + { $this->connection->clear(); $cat1 = new CategoryWithPosition(); $cat1->position = 0; - $cat1->name = "First"; - + $cat1->name = 'First'; + $cat2 = new CategoryWithPosition(); $cat2->position = 0; // same 'priority' as the first - $cat2->name = "Second"; - + $cat2->name = 'Second'; + $cat3 = new CategoryWithPosition(); $cat3->position = 1; - $cat3->name = "Third"; - + $cat3->name = 'Third'; + $board1 = new BoardWithPosition(); $board1->position = 0; - + $board2 = new BoardWithPosition(); $board2->position = 1; - + $board3 = new BoardWithPosition(); $board3->position = 2; - + // The first category gets 3 boards! $cat1->Boards[0] = $board1; $cat1->Boards[1] = $board2; $cat1->Boards[2] = $board3; - + $board4 = new BoardWithPosition(); $board4->position = 0; - + // The second category gets 1 board! $cat2->Boards[0] = $board4; - + $this->connection->flush(); } /** * Prepares the tables. */ - public function prepareTables() { - $this->tables[] = "CategoryWithPosition"; - $this->tables[] = "BoardWithPosition"; + public function prepareTables() + { + $this->tables[] = 'CategoryWithPosition'; + $this->tables[] = 'BoardWithPosition'; parent::prepareTables(); } @@ -90,7 +97,7 @@ public function prepareTables() { * Checks whether the boards are correctly assigned to the categories. * * The 'evil' result set that confuses the object population is displayed below. - * + * * catId | catPos | catName | boardPos | board.category_id * 1 | 0 | First | 0 | 1 * 2 | 0 | Second | 0 | 2 <-- The split that confuses the object population @@ -98,17 +105,19 @@ public function prepareTables() { * 1 | 0 | First | 2 | 1 * 3 | 2 | Third | NULL */ - public function testQueryWithOrdering2() { + public function testQueryWithOrdering2() + { $q = new Doctrine_Query($this->connection); $categories = $q->select('c.*, b.*') - ->from('CategoryWithPosition c') - ->leftJoin('c.Boards b') - ->orderBy('c.position ASC, b.position ASC') - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + ->from('CategoryWithPosition c') + ->leftJoin('c.Boards b') + ->orderBy('c.position ASC, b.position ASC') + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY) + ; $this->assertEqual(3, count($categories), 'Some categories were doubled!'); - + // Check each category foreach ($categories as $category) { switch ($category['name']) { @@ -116,18 +125,17 @@ public function testQueryWithOrdering2() { // The first category should have 3 boards, right? // It has only 1! The other two slipped to the 2nd category! $this->assertEqual(3, count($category['Boards'])); - break; + break; case 'Second': // The second category should have 1 board, but it got 3 now $this->assertEqual(1, count($category['Boards'])); - break; + break; case 'Third': // The third has no boards as expected. - //print $category->Boards[0]->position; + // print $category->Boards[0]->position; $this->assertEqual(0, count($category['Boards'])); - break; + break; } - } } @@ -135,45 +143,45 @@ public function testQueryWithOrdering2() { * Checks whether the boards are correctly assigned to the categories. * * The 'evil' result set that confuses the object population is displayed below. - * - * catId | catPos | catName | boardPos | board.category_id + * + * catId | catPos | catName | boardPos | board.category_id * 1 | 0 | First | 0 | 1 * 2 | 0 | Second | 0 | 2 <-- The split that confuses the object population * 1 | 0 | First | 1 | 1 * 1 | 0 | First | 2 | 1 * 3 | 2 | Third | NULL */ - public function testQueryWithOrdering() { + public function testQueryWithOrdering() + { $q = new Doctrine_Query($this->connection); $categories = $q->select('c.*, b.*') - ->from('CategoryWithPosition c') - ->leftJoin('c.Boards b') - ->orderBy('c.position ASC, b.position ASC') - ->execute(); + ->from('CategoryWithPosition c') + ->leftJoin('c.Boards b') + ->orderBy('c.position ASC, b.position ASC') + ->execute() + ; $this->assertEqual(3, $categories->count(), 'Some categories were doubled!'); - + // Check each category foreach ($categories as $category) { - switch ($category->name) { case 'First': // The first category should have 3 boards $this->assertEqual(3, $category->Boards->count()); - break; + break; case 'Second': // The second category should have 1 board $this->assertEqual(1, $category->Boards->count()); - break; + break; case 'Third': // The third has no boards as expected. - //print $category->Boards[0]->position; + // print $category->Boards[0]->position; $this->assertEqual(0, $category->Boards->count()); - break; + break; } - } } } diff --git a/tests/DBTestCase.php b/tests/DBTestCase.php index ef8ebddcf..489426918 100644 --- a/tests/DBTestCase.php +++ b/tests/DBTestCase.php @@ -20,41 +20,48 @@ */ /** - * Doctrine_Db_TestCase + * Doctrine_Db_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Db_TestCase extends Doctrine_UnitTestCase { + public function prepareData() + { + } - public function prepareData() - { } + public function prepareTables() + { + } - public function prepareTables() - { } + public function init() + { + } - public function init() - { } - - public function testInitialize() + public function testInitialize() { $this->conn = Doctrine_Manager::getInstance()->openConnection(array('sqlite::memory:')); $this->conn->exec('CREATE TABLE entity (id INTEGER, name TEXT)'); $this->conn->exec("INSERT INTO entity (id, name) VALUES (1, 'zYne')"); $this->conn->exec("INSERT INTO entity (id, name) VALUES (2, 'John')"); - - + $this->assertEqual($this->conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME), 'sqlite'); } - public function testAddValidEventListener() + public function testAddValidEventListener() { $this->conn->setListener(new Doctrine_EventListener()); @@ -63,7 +70,7 @@ public function testAddValidEventListener() $ret = $this->conn->addListener(new Doctrine_Connection_TestLogger()); $this->pass(); $this->assertTrue($ret instanceof Doctrine_Connection); - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->fail(); } $this->assertTrue($this->conn->getListener() instanceof Doctrine_EventListener_Chain); @@ -73,18 +80,18 @@ public function testAddValidEventListener() $ret = $this->conn->addListener(new Doctrine_Connection_TestValidListener()); $this->pass(); $this->assertTrue($ret instanceof Doctrine_Connection); - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->fail(); } $this->assertTrue($this->conn->getListener() instanceof Doctrine_EventListener_Chain); $this->assertTrue($this->conn->getListener()->get(0) instanceof Doctrine_Connection_TestLogger); $this->assertTrue($this->conn->getListener()->get(1) instanceof Doctrine_Connection_TestValidListener); - + try { $ret = $this->conn->addListener(new Doctrine_EventListener_Chain(), 'chain'); $this->pass(); $this->assertTrue($ret instanceof Doctrine_Connection); - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->fail(); } $this->assertTrue($this->conn->getListener() instanceof Doctrine_EventListener_Chain); @@ -98,7 +105,7 @@ public function testAddValidEventListener() $ret = $this->conn->addListener(new Doctrine_EventListener_Chain(), 'chain'); $this->pass(); $this->assertTrue($ret instanceof Doctrine_Connection); - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->fail(); } $this->assertTrue($this->conn->getListener() instanceof Doctrine_EventListener_Chain); @@ -107,7 +114,7 @@ public function testAddValidEventListener() $this->assertTrue($this->conn->getListener()->get('chain') instanceof Doctrine_EventListener_Chain); } - public function testListeningEventsWithSingleListener() + public function testListeningEventsWithSingleListener() { $this->conn->setListener(new Doctrine_Connection_TestLogger()); $listener = $this->conn->getListener(); @@ -115,17 +122,17 @@ public function testListeningEventsWithSingleListener() $this->assertEqual($listener->pop(), 'postPrepare'); $this->assertEqual($listener->pop(), 'prePrepare'); - + $stmt->execute(array(1)); $this->assertEqual($listener->pop(), 'postStmtExecute'); $this->assertEqual($listener->pop(), 'preStmtExecute'); - + $this->conn->exec('DELETE FROM entity'); $this->assertEqual($listener->pop(), 'postExec'); $this->assertEqual($listener->pop(), 'preExec'); - + $this->conn->beginTransaction(); $this->assertEqual($listener->pop(), 'postTransactionBegin'); @@ -137,12 +144,12 @@ public function testListeningEventsWithSingleListener() $this->assertEqual($listener->pop(), 'preExec'); $this->conn->commit(); - + $this->assertEqual($listener->pop(), 'postTransactionCommit'); $this->assertEqual($listener->pop(), 'preTransactionCommit'); } - public function testListeningQueryEventsWithListenerChain() + public function testListeningQueryEventsWithListenerChain() { $this->conn->exec('DROP TABLE entity'); @@ -160,9 +167,8 @@ public function testListeningQueryEventsWithListenerChain() $this->assertEqual($listener2->pop(), 'preExec'); } - public function testListeningPrepareEventsWithListenerChain() + public function testListeningPrepareEventsWithListenerChain() { - $stmt = $this->conn->prepare('INSERT INTO entity (id) VALUES(?)'); $listener = $this->conn->getListener()->get(0); $listener2 = $this->conn->getListener()->get(1); @@ -247,7 +253,7 @@ public function testListeningExecEventsWithListenerChain() $this->assertEqual($listener2->pop(), 'preExec'); } - public function testListeningTransactionEventsWithListenerChain() + public function testListeningTransactionEventsWithListenerChain() { $this->conn->beginTransaction(); $listener = $this->conn->getListener()->get(0); @@ -264,157 +270,170 @@ public function testListeningTransactionEventsWithListenerChain() $this->assertEqual($listener->pop(), 'postTransactionCommit'); $this->assertEqual($listener->pop(), 'preTransactionCommit'); - + $this->assertEqual($listener->pop(), 'postExec'); $this->assertEqual($listener->pop(), 'preExec'); - + $this->conn->exec('DROP TABLE entity'); } - public function testSetValidEventListener() + public function testSetValidEventListener() { try { $this->conn->setListener(new Doctrine_Connection_TestLogger()); $this->pass(); - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->fail(); } $this->assertTrue($this->conn->getListener() instanceof Doctrine_Connection_TestLogger); try { $this->conn->setListener(new Doctrine_Connection_TestValidListener()); $this->pass(); - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->fail(); } $this->assertTrue($this->conn->getListener() instanceof Doctrine_Connection_TestValidListener); try { $this->conn->setListener(new Doctrine_EventListener_Chain()); $this->pass(); - - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->fail(); } $this->assertTrue($this->conn->getListener() instanceof Doctrine_EventListener_Chain); try { $this->conn->setListener(new Doctrine_EventListener()); $this->pass(); - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->fail(); } $this->assertTrue($this->conn->getListener() instanceof Doctrine_EventListener); } - public function testSetInvalidEventListener() + public function testSetInvalidEventListener() { try { $this->conn->setListener(new Doctrine_Connection_TestInvalidListener()); $this->fail(); - } catch(Doctrine_EventListener_Exception $e) { + } catch (Doctrine_EventListener_Exception $e) { $this->pass(); } } - public function testInvalidDSN() + + public function testInvalidDSN() { $manager = Doctrine_Manager::getInstance(); try { $this->conn = $manager->openConnection(''); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } try { $this->conn = $manager->openConnection('unknown'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); - } + } try { $this->conn = $manager->openConnection(0); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } - public function testInvalidScheme() + + public function testInvalidScheme() { $manager = Doctrine_Manager::getInstance(); try { $this->conn = $manager->openConnection('unknown://:memory:'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } - public function testInvalidHost() + + public function testInvalidHost() { $manager = Doctrine_Manager::getInstance(); try { $this->conn = $manager->openConnection('mysql://user:password@'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } - public function testInvalidDatabase() + + public function testInvalidDatabase() { $manager = Doctrine_Manager::getInstance(); try { $this->conn = $manager->openConnection('mysql://user:password@host/'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } - /** - public function testGetConnectionPdoLikeDSN() - { - $this->conn = Doctrine_Manager::openConnection(array('mysql:host=localhost;dbname=test', 'root', 'password')); - $this->assertEqual($this->conn->getOption('dsn'), 'mysql:host=localhost;dbname=test'); - $this->assertEqual($this->conn->getOption('username'), 'root'); - $this->assertEqual($this->conn->getOption('password'), 'password'); - + /* + * public function testGetConnectionPdoLikeDSN() + * { + * $this->conn = Doctrine_Manager::openConnection(array('mysql:host=localhost;dbname=test', 'root', 'password')); + * $this->assertEqual($this->conn->getOption('dsn'), 'mysql:host=localhost;dbname=test'); + * $this->assertEqual($this->conn->getOption('username'), 'root'); + * $this->assertEqual($this->conn->getOption('password'), 'password'); + * + * + * $this->conn = Doctrine_Connection::getConnection('sqlite::memory:'); + * + * $this->assertEqual($this->conn->getOption('dsn'), 'sqlite::memory:'); + * $this->assertEqual($this->conn->getOption('username'), false); + * $this->assertEqual($this->conn->getOption('password'), false); + * } + * public function testDriverName() + * { + * + * } + * + * public function testGetConnectionWithPearLikeDSN() + * { + * $this->conn = Doctrine_Connection::getConnection('mysql://zYne:password@localhost/test'); + * $this->assertEqual($this->conn->getOption('dsn'), 'mysql:host=localhost;dbname=test'); + * $this->assertEqual($this->conn->getOption('username'), 'zYne'); + * $this->assertEqual($this->conn->getOption('password'), 'password'); + * + * + * $this->conn = Doctrine_Connection::getConnection('sqlite://:memory:'); + * + * $this->assertEqual($this->conn->getOption('dsn'), 'sqlite::memory:'); + * $this->assertEqual($this->conn->getOption('username'), false); + * $this->assertEqual($this->conn->getOption('password'), false); + * } + */ +} - $this->conn = Doctrine_Connection::getConnection('sqlite::memory:'); +class Doctrine_Connection_TestLogger implements Doctrine_Overloadable +{ + private $messages = array(); - $this->assertEqual($this->conn->getOption('dsn'), 'sqlite::memory:'); - $this->assertEqual($this->conn->getOption('username'), false); - $this->assertEqual($this->conn->getOption('password'), false); - } - public function testDriverName() + public function __call($m, $a) { - + $this->messages[] = $m; } - public function testGetConnectionWithPearLikeDSN() + public function pop() { - $this->conn = Doctrine_Connection::getConnection('mysql://zYne:password@localhost/test'); - $this->assertEqual($this->conn->getOption('dsn'), 'mysql:host=localhost;dbname=test'); - $this->assertEqual($this->conn->getOption('username'), 'zYne'); - $this->assertEqual($this->conn->getOption('password'), 'password'); - - - $this->conn = Doctrine_Connection::getConnection('sqlite://:memory:'); - - $this->assertEqual($this->conn->getOption('dsn'), 'sqlite::memory:'); - $this->assertEqual($this->conn->getOption('username'), false); - $this->assertEqual($this->conn->getOption('password'), false); - } - */ -} - -class Doctrine_Connection_TestLogger implements Doctrine_Overloadable { - private $messages = array(); - - public function __call($m, $a) { - $this->messages[] = $m; - } - public function pop() { return array_pop($this->messages); } - public function getAll() { + + public function getAll() + { return $this->messages; } } -class Doctrine_Connection_TestValidListener extends Doctrine_EventListener { } -class Doctrine_Connection_TestInvalidListener { } +class Doctrine_Connection_TestValidListener extends Doctrine_EventListener +{ +} +class Doctrine_Connection_TestInvalidListener +{ +} diff --git a/tests/Data/ExportTestCase.php b/tests/Data/ExportTestCase.php index 3c176c3d0..af4b96ef9 100644 --- a/tests/Data/ExportTestCase.php +++ b/tests/Data/ExportTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Data_Export_TestCase + * Doctrine_Data_Export_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Data_Export_TestCase extends Doctrine_UnitTestCase +class Doctrine_Data_Export_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -52,7 +58,7 @@ public function testI18nExport() $array = Doctrine_Parser::load('test.yml', 'yml'); - $this->assertTrue( ! empty($array)); + $this->assertTrue(!empty($array)); $this->assertTrue(isset($array['I18nTestExport']['I18nTestExport_1'])); $this->assertTrue(isset($array['I18nTestExportTranslation']['I18nTestExportTranslation_1_en'])); $this->assertTrue(isset($array['I18nTestExportTranslation']['I18nTestExportTranslation_1_fr'])); @@ -64,7 +70,8 @@ public function testI18nExport() $q = Doctrine_Query::create() ->from('I18nTestExport e') - ->leftJoin('e.Translation t'); + ->leftJoin('e.Translation t') + ; $results = $q->execute(); $this->assertEqual(get_class($results[0]->test_object), 'stdClass'); @@ -93,4 +100,4 @@ public function setUp() { $this->actAs('I18n', array('fields' => array('name', 'title'))); } -} \ No newline at end of file +} diff --git a/tests/Data/ImportTestCase.php b/tests/Data/ImportTestCase.php index fa07a25cd..5f679323e 100644 --- a/tests/Data/ImportTestCase.php +++ b/tests/Data/ImportTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Data_Import_TestCase + * Doctrine_Data_Import_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Data_Import_TestCase extends Doctrine_UnitTestCase +class Doctrine_Data_Import_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -43,10 +49,10 @@ public function prepareTables() $this->tables[] = 'I18nNumberLang'; parent::prepareTables(); } - + public function testInlineMany() { - $yml = <<from('User u, u.Phonenumber') - ->where('u.name = ?', 'jwage'); + ->where('u.name = ?', 'jwage') + ; $user = $query->execute()->getFirst(); @@ -82,7 +89,7 @@ public function testInlineMany() public function testInlineOne() { - $yml = <<from('User u, u.Album a, a.User u2') - ->where('u.name = ?', 'zYne-'); + ->where('u.name = ?', 'zYne-') + ; $user = $query->execute()->getFirst(); @@ -116,7 +124,7 @@ public function testInlineOne() public function testNormalMany() { - $yml = <<from('User u, u.Phonenumber') - ->where('u.name = ?', 'jwage2'); + ->where('u.name = ?', 'jwage2') + ; $user = $query->execute()->getFirst(); @@ -155,7 +164,7 @@ public function testNormalMany() public function testI18nImport() { - $yml = <<fail($e->getMessage()); } - unlink('test.yml'); + unlink('test.yml'); } public function testImportNestedSetData() { - $yml = <<fail(); } - unlink('test.yml'); + unlink('test.yml'); } - + public function testImportNestedSetMultipleTreeData() { - $yml = <<from('ImportNestedSetMultipleTree insmt') - ->orderBy('insmt.root_id ASC, insmt.lft ASC'); + ->orderBy('insmt.root_id ASC, insmt.lft ASC') + ; $i = $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY); @@ -315,7 +325,7 @@ public function testImportNestedSetMultipleTreeData() $this->assertEqual($i[4]['rgt'], 3); $this->assertEqual($i[4]['level'], 1); $this->assertEqual($i[4]['root_id'], $i[3]['root_id']); - + $this->assertEqual($i[5]['name'], 'Item 2.2'); $this->assertEqual($i[5]['lft'], 4); $this->assertEqual($i[5]['rgt'], 11); @@ -327,13 +337,13 @@ public function testImportNestedSetMultipleTreeData() $this->fail(); } - unlink('test.yml'); + unlink('test.yml'); } public function testMany2ManyManualDataFixtures() { self::prepareTables(); - $yml = <<pass(); } - + unlink('test.yml'); } public function testNormalNonRecursiveFixturesLoading() { self::prepareTables(); - $yml1 = <<setFormat('yml'); $array = $import->doParsing(); @@ -437,7 +447,7 @@ public function testRecursiveFixturesLoading() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_RECURSIVE_MERGE_FIXTURES, true); self::prepareTables(); - $yml1 = <<setFormat('yml'); $array = $import->doParsing(); @@ -473,7 +483,7 @@ public function testRecursiveFixturesLoading() public function testIncorrectYamlRelationThrowsException() { self::prepareTables(); - $yml = <<fail($e->getMessage()); } - unlink('test.yml'); + unlink('test.yml'); } - } class ImportNestedSet extends Doctrine_Record @@ -576,7 +585,7 @@ public function setUp() $this->actAs( 'NestedSet', array( 'hasManyRoots' => true, - 'rootColumnName' => 'root_id' + 'rootColumnName' => 'root_id', ) ); } @@ -609,4 +618,4 @@ public function setUp() { $this->actAs('I18n', array('fields' => array('name', 'title'))); } -} \ No newline at end of file +} diff --git a/tests/DataDict/MssqlTestCase.php b/tests/DataDict/MssqlTestCase.php index 93011eb16..4413592db 100644 --- a/tests/DataDict/MssqlTestCase.php +++ b/tests/DataDict/MssqlTestCase.php @@ -20,143 +20,149 @@ */ /** - * Doctrine_DataDict_Mysql_TestCase + * Doctrine_DataDict_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_DataDict_Mssql_TestCase extends Doctrine_UnitTestCase +class Doctrine_DataDict_Mssql_TestCase extends Doctrine_UnitTestCase { - public function testGetPortableDeclarationSupportsNativeBitType() + public function testGetPortableDeclarationSupportsNativeBitType() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'bit')); - + $this->assertEqual($type, array('type' => array('boolean'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeStringTypes() + public function testGetPortableDeclarationSupportsNativeStringTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'text')); $this->assertEqual($type, array('type' => array('string', 'clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'char', 'length' => 1)); $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => true)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => true)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'varchar', 'length' => 1)); - + $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => false)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => false)); } - public function testGetPortableDeclarationSupportsNativeBlobTypes() + public function testGetPortableDeclarationSupportsNativeBlobTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'image')); - + $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'varbinary')); $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeIntegerTypes() + public function testGetPortableDeclarationSupportsNativeIntegerTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'int')); - + $this->assertEqual($type, array('type' => array('integer'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'int', 'length' => 1)); - + $this->assertEqual($type, array('type' => array('integer', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => null)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeTimestampType() + public function testGetPortableDeclarationSupportsNativeTimestampType() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'datetime')); - + $this->assertEqual($type, array('type' => array('timestamp'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeDecimalTypes() + public function testGetPortableDeclarationSupportsNativeDecimalTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'decimal')); $this->assertEqual($type, array('type' => array('decimal'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'money')); $this->assertEqual($type, array('type' => array('decimal'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeFloatTypes() + public function testGetPortableDeclarationSupportsNativeFloatTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'float')); $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'real')); $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'numeric')); $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetNativeDefinitionSupportsIntegerType() + public function testGetNativeDefinitionSupportsIntegerType() { $a = array('type' => 'integer', 'length' => 20, 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'INT'); - + $a['length'] = 4; $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'INT'); @@ -166,94 +172,94 @@ public function testGetNativeDefinitionSupportsIntegerType() $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'INT'); } - public function testGetNativeDefinitionSupportsFloatType() + public function testGetNativeDefinitionSupportsFloatType() { $a = array('type' => 'float', 'length' => 20, 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'FLOAT'); } - public function testGetNativeDefinitionSupportsBooleanType() + public function testGetNativeDefinitionSupportsBooleanType() { $a = array('type' => 'boolean', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'BIT'); } - public function testGetNativeDefinitionSupportsDateType() + public function testGetNativeDefinitionSupportsDateType() { $a = array('type' => 'date', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CHAR(10)'); } - public function testGetNativeDefinitionSupportsTimestampType() + public function testGetNativeDefinitionSupportsTimestampType() { $a = array('type' => 'timestamp', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CHAR(19)'); } - public function testGetNativeDefinitionSupportsTimeType() + public function testGetNativeDefinitionSupportsTimeType() { $a = array('type' => 'time', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CHAR(8)'); } - public function testGetNativeDefinitionSupportsClobType() + public function testGetNativeDefinitionSupportsClobType() { $a = array('type' => 'clob'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDefinitionSupportsBlobType() + public function testGetNativeDefinitionSupportsBlobType() { $a = array('type' => 'blob'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'IMAGE'); } - public function testGetNativeDefinitionSupportsCharType() + public function testGetNativeDefinitionSupportsCharType() { $a = array('type' => 'char', 'length' => 10); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CHAR(10)'); } - public function testGetNativeDefinitionSupportsVarcharType() + public function testGetNativeDefinitionSupportsVarcharType() { $a = array('type' => 'varchar', 'length' => 10); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR(10)'); } - public function testGetNativeDefinitionSupportsArrayType() + public function testGetNativeDefinitionSupportsArrayType() { $a = array('type' => 'array', 'length' => 40); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR(40)'); } - public function testGetNativeDefinitionSupportsStringType() + public function testGetNativeDefinitionSupportsStringType() { $a = array('type' => 'string'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDefinitionSupportsArrayType2() + public function testGetNativeDefinitionSupportsArrayType2() { $a = array('type' => 'array'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDefinitionSupportsObjectType() + public function testGetNativeDefinitionSupportsObjectType() { $a = array('type' => 'object'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } -} \ No newline at end of file +} diff --git a/tests/DataDict/MysqlTestCase.php b/tests/DataDict/MysqlTestCase.php index fd67636aa..6f039efda 100644 --- a/tests/DataDict/MysqlTestCase.php +++ b/tests/DataDict/MysqlTestCase.php @@ -20,241 +20,245 @@ */ /** - * Doctrine_DataDict_Mysql_TestCase + * Doctrine_DataDict_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_DataDict_Mysql_TestCase extends Doctrine_UnitTestCase { - public function testGetCharsetFieldDeclarationReturnsValidSql() + public function testGetCharsetFieldDeclarationReturnsValidSql() { $this->assertEqual($this->dataDict->getCharsetFieldDeclaration('UTF-8'), 'CHARACTER SET UTF-8'); } - public function testGetCollationFieldDeclarationReturnsValidSql() + public function testGetCollationFieldDeclarationReturnsValidSql() { $this->assertEqual($this->dataDict->getCollationFieldDeclaration('xx'), 'COLLATE xx'); } - public function testGetPortableDeclarationSupportsNativeIntegerTypes() + public function testGetPortableDeclarationSupportsNativeIntegerTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'tinyint')); - $this->assertEqual($type, array('type' => array('integer', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => null)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'smallint unsigned')); - $this->assertEqual($type, array('type' => array('integer'), - 'length' => 2, - 'unsigned' => true, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('integer'), + 'length' => 2, + 'unsigned' => true, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'mediumint unsigned')); - $this->assertEqual($type, array('type' => array('integer'), - 'length' => 3, - 'unsigned' => true, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('integer'), + 'length' => 3, + 'unsigned' => true, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'int unsigned')); - $this->assertEqual($type, array('type' => array('integer'), - 'length' => 4, - 'unsigned' => true, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('integer'), + 'length' => 4, + 'unsigned' => true, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'integer unsigned')); - $this->assertEqual($type, array('type' => array('integer'), - 'length' => 4, - 'unsigned' => true, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('integer'), + 'length' => 4, + 'unsigned' => true, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'bigint unsigned')); - $this->assertEqual($type, array('type' => array('integer'), - 'length' => 8, - 'unsigned' => true, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('integer'), + 'length' => 8, + 'unsigned' => true, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeStringTypes() + public function testGetPortableDeclarationSupportsNativeStringTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'text')); $this->assertEqual($type, array('type' => array('string', 'clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => false)); + 'length' => null, + 'unsigned' => null, + 'fixed' => false)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'longtext')); $this->assertEqual($type, array('type' => array('string', 'clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => false)); - + 'length' => null, + 'unsigned' => null, + 'fixed' => false)); + $type = $this->dataDict->getPortableDeclaration(array('type' => 'mediumtext')); $this->assertEqual($type, array('type' => array('string', 'clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => false)); + 'length' => null, + 'unsigned' => null, + 'fixed' => false)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'tinytext')); $this->assertEqual($type, array('type' => array('string', 'clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => false)); + 'length' => null, + 'unsigned' => null, + 'fixed' => false)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'char(1)')); $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => true)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => true)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'varchar(1)')); $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => false)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => false)); } - public function testGetPortableDeclarationSupportsNativeFloatTypes() + public function testGetPortableDeclarationSupportsNativeFloatTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'float')); - + $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'real unsigned')); $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => true, - 'fixed' => null)); + 'length' => null, + 'unsigned' => true, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'double')); - + $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeDateType() + public function testGetPortableDeclarationSupportsNativeDateType() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'date')); - + $this->assertEqual($type, array('type' => array('date'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeDecimalTypes() + public function testGetPortableDeclarationSupportsNativeDecimalTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'decimal')); - + $this->assertEqual($type, array('type' => array('decimal'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'unknown')); - + $this->assertEqual($type, array('type' => array('decimal'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); - + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); + $type = $this->dataDict->getPortableDeclaration(array('type' => 'numeric')); - + $this->assertEqual($type, array('type' => array('decimal'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeTimestampTypes() + public function testGetPortableDeclarationSupportsNativeTimestampTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'timestamp')); - + $this->assertEqual($type, array('type' => array('timestamp'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); - + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); + $type = $this->dataDict->getPortableDeclaration(array('type' => 'datetime')); - + $this->assertEqual($type, array('type' => array('timestamp'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeYearType() + public function testGetPortableDeclarationSupportsNativeYearType() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'year')); - $this->assertEqual($type, array('type' => array('integer', 'date'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeBlobTypes() + public function testGetPortableDeclarationSupportsNativeBlobTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'blob')); $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'mediumblob')); $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); - + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); + $type = $this->dataDict->getPortableDeclaration(array('type' => 'tinyblob')); $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'longblob')); $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetNativeDefinitionSupportsIntegerType() + public function testGetNativeDefinitionSupportsIntegerType() { $a = array('type' => 'integer', 'length' => 20, 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'BIGINT'); - + $a['length'] = 4; $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'INT'); @@ -264,101 +268,101 @@ public function testGetNativeDefinitionSupportsIntegerType() $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'SMALLINT'); } - public function testGetNativeDeclarationSupportsFloatType() + public function testGetNativeDeclarationSupportsFloatType() { $a = array('type' => 'float', 'length' => 20, 'fixed' => false); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'FLOAT(20, 2)'); } - public function testGetNativeDeclarationSupportsBooleanType() + public function testGetNativeDeclarationSupportsBooleanType() { $a = array('type' => 'boolean', 'fixed' => false); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'TINYINT(1)'); } - public function testGetNativeDeclarationSupportsDateType() + public function testGetNativeDeclarationSupportsDateType() { $a = array('type' => 'date', 'fixed' => false); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'DATE'); } - public function testGetNativeDeclarationSupportsTimestampType() + public function testGetNativeDeclarationSupportsTimestampType() { $a = array('type' => 'timestamp', 'fixed' => false); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'DATETIME'); } - public function testGetNativeDeclarationSupportsTimeType() + public function testGetNativeDeclarationSupportsTimeType() { $a = array('type' => 'time', 'fixed' => false); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'TIME'); } - public function testGetNativeDeclarationSupportsClobType() + public function testGetNativeDeclarationSupportsClobType() { $a = array('type' => 'clob'); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'LONGTEXT'); } - public function testGetNativeDeclarationSupportsBlobType() + public function testGetNativeDeclarationSupportsBlobType() { $a = array('type' => 'blob'); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'LONGBLOB'); } - public function testGetNativeDeclarationSupportsCharType() + public function testGetNativeDeclarationSupportsCharType() { $a = array('type' => 'char', 'length' => 10); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'CHAR(10)'); } - public function testGetNativeDeclarationSupportsVarcharType() + public function testGetNativeDeclarationSupportsVarcharType() { $a = array('type' => 'varchar', 'length' => 10); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'VARCHAR(10)'); } - public function testGetNativeDeclarationSupportsArrayType() + public function testGetNativeDeclarationSupportsArrayType() { $a = array('type' => 'array', 'length' => 40); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'TINYTEXT'); } - public function testGetNativeDeclarationSupportsStringType() + public function testGetNativeDeclarationSupportsStringType() { $a = array('type' => 'string'); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDeclarationSupportsStringTypeWithLongLength() + public function testGetNativeDeclarationSupportsStringTypeWithLongLength() { $a = array('type' => 'string', 'length' => 2000); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDeclarationSupportsArrayType2() + public function testGetNativeDeclarationSupportsArrayType2() { $a = array('type' => 'array'); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'LONGTEXT'); } - public function testGetNativeDeclarationSupportsObjectType() + public function testGetNativeDeclarationSupportsObjectType() { $a = array('type' => 'object'); $this->assertEqual($this->dataDict->GetNativeDeclaration($a), 'LONGTEXT'); } -} \ No newline at end of file +} diff --git a/tests/DataDict/OracleTestCase.php b/tests/DataDict/OracleTestCase.php index 78d92c30b..b8216d21d 100644 --- a/tests/DataDict/OracleTestCase.php +++ b/tests/DataDict/OracleTestCase.php @@ -20,192 +20,195 @@ */ /** - * Doctrine_DataDict_Oracle_TestCase + * Doctrine_DataDict_Oracle_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_DataDict_Oracle_TestCase extends Doctrine_UnitTestCase { - public function testGetPortableDeclarationSupportsNativeFloatType() + public function testGetPortableDeclarationSupportsNativeFloatType() { $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'float')); $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } public function testGetPortableDeclarationSupportsNativeIntegerTypes() { $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'integer')); - + $this->assertEqual($type, array('type' => array('integer'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'pls_integer', 'data_length' => 1)); - + $this->assertEqual($type, array('type' => array('integer', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => null)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'binary_integer', 'data_length' => 1)); - + $this->assertEqual($type, array('type' => array('integer', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => null)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeStringTypes() + public function testGetPortableDeclarationSupportsNativeStringTypes() { $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'varchar')); $this->assertEqual($type, array('type' => array('string'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'varchar2', 'data_length' => 1)); $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => false)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => false)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'nvarchar2', 'data_length' => 1)); - + $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => false)); - + 'length' => 1, + 'unsigned' => null, + 'fixed' => false)); + $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'char', 'data_length' => 1)); $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => true)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => true)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'nchar', 'data_length' => 1)); - + $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => true)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => true)); } - public function testGetPortableDeclarationSupportsNativeNumberType() + public function testGetPortableDeclarationSupportsNativeNumberType() { $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'number')); - - $this->assertEqual($type, array('type' => array('integer'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('integer'), + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'number', 'data_length' => 1)); - - $this->assertEqual($type, array('type' => array('integer', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('integer', 'boolean'), + 'length' => 1, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeTimestampType() + public function testGetPortableDeclarationSupportsNativeTimestampType() { $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'date')); - + $this->assertEqual($type, array('type' => array('timestamp'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'timestamp')); - + $this->assertEqual($type, array('type' => array('timestamp'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeClobTypes() + public function testGetPortableDeclarationSupportsNativeClobTypes() { $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'clob')); - + $this->assertEqual($type, array('type' => array('clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'long')); - + $this->assertEqual($type, array('type' => array('string', 'clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); - + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); + $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'nclob')); - - $this->assertEqual($type, array('type' => array('clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('clob'), + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeBlobTypes() + public function testGetPortableDeclarationSupportsNativeBlobTypes() { $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'blob')); - + $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'long raw')); $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'long raw')); $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); - + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); + $type = $this->dataDict->getPortableDeclaration(array('data_type' => 'raw')); $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetNativeDefinitionSupportsIntegerType() + public function testGetNativeDefinitionSupportsIntegerType() { $a = array('type' => 'integer', 'length' => 20, 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'INTEGER'); - + $a['length'] = 8; - + $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'NUMBER(20)'); - + $a['length'] = 4; $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'NUMBER(10)'); @@ -213,77 +216,77 @@ public function testGetNativeDefinitionSupportsIntegerType() $a['length'] = 3; $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'NUMBER(8)'); - + $a['length'] = 2; - + $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'NUMBER(5)'); - + $a['length'] = 1; - + $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'NUMBER(3)'); - + unset($a['length']); - + $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'INTEGER'); } - public function testGetNativeDefinitionSupportsFloatType() + public function testGetNativeDefinitionSupportsFloatType() { $a = array('type' => 'float', 'length' => 20, 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'NUMBER'); } - public function testGetNativeDefinitionSupportsBooleanType() + public function testGetNativeDefinitionSupportsBooleanType() { $a = array('type' => 'boolean', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'NUMBER(1)'); } - public function testGetNativeDefinitionSupportsDateType() + public function testGetNativeDefinitionSupportsDateType() { $a = array('type' => 'date', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'DATE'); } - public function testGetNativeDefinitionSupportsTimestampType() + public function testGetNativeDefinitionSupportsTimestampType() { $a = array('type' => 'timestamp', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'DATE'); } - public function testGetNativeDefinitionSupportsTimeType() + public function testGetNativeDefinitionSupportsTimeType() { $a = array('type' => 'time', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'DATE'); } - public function testGetNativeDefinitionSupportsClobType() + public function testGetNativeDefinitionSupportsClobType() { $a = array('type' => 'clob'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CLOB'); } - public function testGetNativeDefinitionSupportsBlobType() + public function testGetNativeDefinitionSupportsBlobType() { $a = array('type' => 'blob'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'BLOB'); } - public function testGetNativeDefinitionSupportsCharType() + public function testGetNativeDefinitionSupportsCharType() { $a = array('type' => 'char', 'length' => 10); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CHAR(10)'); } - public function testGetNativeDefinitionSupportsVarcharType() + public function testGetNativeDefinitionSupportsVarcharType() { $a = array('type' => 'varchar', 'length' => 10); @@ -293,45 +296,45 @@ public function testGetNativeDefinitionSupportsVarcharType() public function testGetNativeDefinitionSupportsVarcharOwnParams() { $a = array('type' => 'varchar', 'length' => 10); - + $this->conn->setParam('char_unit', 'CHAR'); $this->conn->setParam('varchar2_max_length', 1000); - + $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR2(10 CHAR)'); - + $a['length'] = 1001; $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CLOB'); - + $this->conn->setParam('char_unit', 'BYTE'); $this->conn->setParam('varchar2_max_length', 4000); - + $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR2(1001 BYTE)'); - + $this->conn->setParam('char_unit', null); } - public function testGetNativeDefinitionSupportsArrayType() + public function testGetNativeDefinitionSupportsArrayType() { $a = array('type' => 'array', 'length' => 40); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR2(40)'); } - public function testGetNativeDefinitionSupportsStringType() + public function testGetNativeDefinitionSupportsStringType() { $a = array('type' => 'string'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CLOB'); } - public function testGetNativeDefinitionSupportsArrayType2() + public function testGetNativeDefinitionSupportsArrayType2() { $a = array('type' => 'array'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CLOB'); } - public function testGetNativeDefinitionSupportsObjectType() + public function testGetNativeDefinitionSupportsObjectType() { $a = array('type' => 'object'); @@ -341,8 +344,7 @@ public function testGetNativeDefinitionSupportsObjectType() public function testGetNativeDefinitionSupportsLargerStrings() { $a = array('type' => 'string', 'length' => 4001); - + $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CLOB'); } - } diff --git a/tests/DataDict/PgsqlTestCase.php b/tests/DataDict/PgsqlTestCase.php index d919bdc4e..7c452ca13 100644 --- a/tests/DataDict/PgsqlTestCase.php +++ b/tests/DataDict/PgsqlTestCase.php @@ -20,212 +20,215 @@ */ /** - * Doctrine_DataDict_Oracle_TestCase + * Doctrine_DataDict_Oracle_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_DataDict_Pgsql_TestCase extends Doctrine_UnitTestCase +class Doctrine_DataDict_Pgsql_TestCase extends Doctrine_UnitTestCase { - public function getDeclaration($type) + public function getDeclaration($type) { return $this->dataDict->getPortableDeclaration(array('type' => $type, 'name' => 'colname', 'length' => 2, 'fixed' => true)); } - - public function testGetPortableDeclarationSupportsNativeBlobTypes() + + public function testGetPortableDeclarationSupportsNativeBlobTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'blob')); - - $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + + $this->assertEqual($type, array('type' => array('blob'), + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'tinyblob')); - $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('blob'), + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'mediumblob')); - $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); - + $this->assertEqual($type, array('type' => array('blob'), + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); + $type = $this->dataDict->getPortableDeclaration(array('type' => 'longblob')); - $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('blob'), + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'bytea')); - $this->assertEqual($type, array('type' => array('blob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + $this->assertEqual($type, array('type' => array('blob'), + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'oid')); $this->assertEqual($type, array('type' => array('blob', 'clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } public function testGetPortableDeclarationSupportsNativeTimestampTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'timestamp')); - + $this->assertEqual($type, array('type' => array('timestamp'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'datetime')); - + $this->assertEqual($type, array('type' => array('timestamp'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeDecimalTypes() + public function testGetPortableDeclarationSupportsNativeDecimalTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'decimal')); $this->assertEqual($type, array('type' => array('decimal'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'money')); $this->assertEqual($type, array('type' => array('decimal'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'numeric')); $this->assertEqual($type, array('type' => array('decimal'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeFloatTypes() + public function testGetPortableDeclarationSupportsNativeFloatTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'float')); - + $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'double')); - + $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'real')); - + $this->assertEqual($type, array('type' => array('float'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeYearType() + public function testGetPortableDeclarationSupportsNativeYearType() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'year')); $this->assertEqual($type, array('type' => array('integer', 'date'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeDateType() + public function testGetPortableDeclarationSupportsNativeDateType() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'date')); - + $this->assertEqual($type, array('type' => array('date'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeTimeType() + public function testGetPortableDeclarationSupportsNativeTimeType() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'time')); - + $this->assertEqual($type, array('type' => array('time'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); } - public function testGetPortableDeclarationSupportsNativeStringTypes() + public function testGetPortableDeclarationSupportsNativeStringTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'text')); $this->assertEqual($type, array('type' => array('string', 'clob'), - 'length' => null, - 'unsigned' => null, - 'fixed' => null)); + 'length' => null, + 'unsigned' => null, + 'fixed' => null)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'interval')); $this->assertEqual($type, array('type' => array('string'), - 'length' => null, - 'unsigned' => null, - 'fixed' => false)); + 'length' => null, + 'unsigned' => null, + 'fixed' => false)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'varchar', 'length' => 1)); $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => false)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => false)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'unknown', 'length' => 1)); - + $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => true)); + 'length' => 1, + 'unsigned' => null, + 'fixed' => true)); - $type = $this->dataDict->getPortableDeclaration(array('type' => 'char', 'length' => 1)); $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => true)); - + 'length' => 1, + 'unsigned' => null, + 'fixed' => true)); $type = $this->dataDict->getPortableDeclaration(array('type' => 'bpchar', 'length' => 1)); - - $this->assertEqual($type, array('type' => array('string', 'boolean'), - 'length' => 1, - 'unsigned' => null, - 'fixed' => true)); + $this->assertEqual($type, array('type' => array('string', 'boolean'), + 'length' => 1, + 'unsigned' => null, + 'fixed' => true)); } - public function testGetPortableDeclarationSupportsNativeIntegerTypes() + public function testGetPortableDeclarationSupportsNativeIntegerTypes() { $type = $this->dataDict->getPortableDeclaration(array('type' => 'smallint')); @@ -250,12 +253,12 @@ public function testGetPortableDeclarationSupportsNativeBooleanTypes() $this->assertEqual($this->getDeclaration('boolean'), array('type' => array('boolean'), 'length' => 1, 'unsigned' => false, 'fixed' => null)); } - public function testGetNativeDefinitionSupportsIntegerType() + public function testGetNativeDefinitionSupportsIntegerType() { $a = array('type' => 'integer', 'length' => 20, 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'BIGINT'); - + $a['length'] = 4; $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'INT'); @@ -265,7 +268,7 @@ public function testGetNativeDefinitionSupportsIntegerType() $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'SMALLINT'); } - public function testGetNativeDefinitionSupportsIntegerTypeWithAutoinc() + public function testGetNativeDefinitionSupportsIntegerTypeWithAutoinc() { $a = array('type' => 'integer', 'length' => 20, 'fixed' => false, 'autoincrement' => true); @@ -280,7 +283,7 @@ public function testGetNativeDefinitionSupportsIntegerTypeWithAutoinc() $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'SERIAL'); } - public function testGetNativeDefinitionSupportsFloatType() + public function testGetNativeDefinitionSupportsFloatType() { $a = array('type' => 'float', 'length' => 20, 'fixed' => false); @@ -294,77 +297,77 @@ public function testGetNativeDefinitionSupportsBooleanType() $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'BOOLEAN'); } - public function testGetNativeDefinitionSupportsDateType() + public function testGetNativeDefinitionSupportsDateType() { $a = array('type' => 'date', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'DATE'); } - public function testGetNativeDefinitionSupportsTimestampType() + public function testGetNativeDefinitionSupportsTimestampType() { $a = array('type' => 'timestamp', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TIMESTAMP'); } - public function testGetNativeDefinitionSupportsTimeType() + public function testGetNativeDefinitionSupportsTimeType() { $a = array('type' => 'time', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TIME'); } - public function testGetNativeDefinitionSupportsClobType() + public function testGetNativeDefinitionSupportsClobType() { $a = array('type' => 'clob'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDefinitionSupportsBlobType() + public function testGetNativeDefinitionSupportsBlobType() { $a = array('type' => 'blob'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'BYTEA'); } - public function testGetNativeDefinitionSupportsCharType() + public function testGetNativeDefinitionSupportsCharType() { $a = array('type' => 'char', 'length' => 10); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CHAR(10)'); } - public function testGetNativeDefinitionSupportsVarcharType() + public function testGetNativeDefinitionSupportsVarcharType() { $a = array('type' => 'varchar', 'length' => 10); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR(10)'); } - public function testGetNativeDefinitionSupportsArrayType() + public function testGetNativeDefinitionSupportsArrayType() { $a = array('type' => 'array', 'length' => 40); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR(40)'); } - public function testGetNativeDefinitionSupportsStringType() + public function testGetNativeDefinitionSupportsStringType() { $a = array('type' => 'string'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDefinitionSupportsArrayType2() + public function testGetNativeDefinitionSupportsArrayType2() { $a = array('type' => 'array'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDefinitionSupportsObjectType() + public function testGetNativeDefinitionSupportsObjectType() { $a = array('type' => 'object'); diff --git a/tests/DataDict/SqliteTestCase.php b/tests/DataDict/SqliteTestCase.php index a0c3753f4..a14c2d9dd 100644 --- a/tests/DataDict/SqliteTestCase.php +++ b/tests/DataDict/SqliteTestCase.php @@ -20,24 +20,30 @@ */ /** - * Doctrine_DataDict_Sqlite_TestCase + * Doctrine_DataDict_Sqlite_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_DataDict_Sqlite_TestCase extends Doctrine_UnitTestCase +class Doctrine_DataDict_Sqlite_TestCase extends Doctrine_UnitTestCase { - public function testBooleanMapsToBooleanType() + public function testBooleanMapsToBooleanType() { $this->assertDeclarationType('boolean', 'boolean'); } - public function testIntegersMapToIntegerType() + public function testIntegersMapToIntegerType() { $this->assertDeclarationType('tinyint', array('integer', 'boolean')); $this->assertDeclarationType('smallint', 'integer'); @@ -49,7 +55,7 @@ public function testIntegersMapToIntegerType() $this->assertDeclarationType('bigserial', 'integer'); } - public function testBlobsMapToBlobType() + public function testBlobsMapToBlobType() { $this->assertDeclarationType('tinyblob', 'blob'); $this->assertDeclarationType('mediumblob', 'blob'); @@ -57,25 +63,25 @@ public function testBlobsMapToBlobType() $this->assertDeclarationType('blob', 'blob'); } - public function testDecimalMapsToDecimal() + public function testDecimalMapsToDecimal() { $this->assertDeclarationType('decimal', 'decimal'); $this->assertDeclarationType('numeric', 'decimal'); } - public function testFloatRealAndDoubleMapToFloat() + public function testFloatRealAndDoubleMapToFloat() { $this->assertDeclarationType('float', 'float'); $this->assertDeclarationType('double', 'float'); $this->assertDeclarationType('real', 'float'); } - public function testYearMapsToIntegerAndDate() + public function testYearMapsToIntegerAndDate() { - $this->assertDeclarationType('year', array('integer','date')); + $this->assertDeclarationType('year', array('integer', 'date')); } - public function testGetNativeDefinitionSupportsIntegerType() + public function testGetNativeDefinitionSupportsIntegerType() { $a = array('type' => 'integer', 'length' => 20, 'fixed' => false); @@ -90,91 +96,91 @@ public function testGetNativeDefinitionSupportsIntegerType() $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'INTEGER'); } - public function testGetNativeDefinitionSupportsFloatType() + public function testGetNativeDefinitionSupportsFloatType() { $a = array('type' => 'float', 'length' => 20, 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'DOUBLE'); } - public function testGetNativeDefinitionSupportsBooleanType() + public function testGetNativeDefinitionSupportsBooleanType() { $a = array('type' => 'boolean', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'INTEGER'); } - public function testGetNativeDefinitionSupportsDateType() + public function testGetNativeDefinitionSupportsDateType() { $a = array('type' => 'date', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'DATE'); } - public function testGetNativeDefinitionSupportsTimestampType() + public function testGetNativeDefinitionSupportsTimestampType() { $a = array('type' => 'timestamp', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'DATETIME'); } - public function testGetNativeDefinitionSupportsTimeType() + public function testGetNativeDefinitionSupportsTimeType() { $a = array('type' => 'time', 'fixed' => false); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TIME'); } - public function testGetNativeDefinitionSupportsClobType() + public function testGetNativeDefinitionSupportsClobType() { $a = array('type' => 'clob'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'LONGTEXT'); } - public function testGetNativeDefinitionSupportsBlobType() + public function testGetNativeDefinitionSupportsBlobType() { $a = array('type' => 'blob'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'LONGBLOB'); } - public function testGetNativeDefinitionSupportsCharType() + public function testGetNativeDefinitionSupportsCharType() { $a = array('type' => 'char', 'length' => 10); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'CHAR(10)'); } - public function testGetNativeDefinitionSupportsVarcharType() + public function testGetNativeDefinitionSupportsVarcharType() { $a = array('type' => 'varchar', 'length' => 10); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR(10)'); } - public function testGetNativeDefinitionSupportsArrayType() + public function testGetNativeDefinitionSupportsArrayType() { $a = array('type' => 'array', 'length' => 40); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'VARCHAR(40)'); } - public function testGetNativeDefinitionSupportsStringType() + public function testGetNativeDefinitionSupportsStringType() { $a = array('type' => 'string'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDefinitionSupportsArrayType2() + public function testGetNativeDefinitionSupportsArrayType2() { $a = array('type' => 'array'); $this->assertEqual($this->dataDict->getNativeDeclaration($a), 'TEXT'); } - public function testGetNativeDefinitionSupportsObjectType() + public function testGetNativeDefinitionSupportsObjectType() { $a = array('type' => 'object'); diff --git a/tests/DataDictSqliteTestCase.php b/tests/DataDictSqliteTestCase.php index f2019de66..92aa92c08 100644 --- a/tests/DataDictSqliteTestCase.php +++ b/tests/DataDictSqliteTestCase.php @@ -1,63 +1,63 @@ dbh->query("CREATE TABLE test (col_null NULL, - col_int INTEGER NOT NULL, - col_real REAL, - col_text TEXT DEFAULT 'default' NOT NULL, - col_blob BLOB)"); - - $this->dict = new Doctrine_DataDict_Sqlite($this->dbh); - $this->columns = $this->dict->listTableColumns('test'); - } - public function testListTables() { - $result = $this->dict->listTables(); - - } - public function testIntegerType() { - $this->assertEqual($this->columns['col_int']->isUnique(), false); - $this->assertEqual($this->columns['col_int']->isNotNull(), true); - $this->assertEqual($this->columns['col_int']->defaultValue(), null); - $this->assertEqual($this->columns['col_int']->isPrimaryKey(), false); - $this->assertEqual($this->columns['col_int']->getType(), 'INTEGER'); - $this->assertEqual($this->columns['col_int']->getName(), 'col_int'); - } - public function testNullType() { - $this->assertEqual($this->columns['col_null']->isUnique(), false); - $this->assertEqual($this->columns['col_null']->isNotNull(), false); - $this->assertEqual($this->columns['col_null']->defaultValue(), null); - $this->assertEqual($this->columns['col_null']->isPrimaryKey(), false); - $this->assertEqual($this->columns['col_null']->getType(), 'numeric'); - $this->assertEqual($this->columns['col_null']->getName(), 'col_null'); - } - public function testTextType() { - $this->assertEqual($this->columns['col_text']->isUnique(), false); - $this->assertEqual($this->columns['col_text']->isNotNull(), true); - $this->assertEqual($this->columns['col_text']->defaultValue(), 'default'); - $this->assertEqual($this->columns['col_text']->isPrimaryKey(), false); - $this->assertEqual($this->columns['col_text']->getType(), 'TEXT'); - $this->assertEqual($this->columns['col_text']->getName(), 'col_text'); - } - public function testBlobType() { - $this->assertEqual($this->columns['col_blob']->isUnique(), false); - $this->assertEqual($this->columns['col_blob']->isNotNull(), false); - $this->assertEqual($this->columns['col_blob']->defaultValue(), null); - $this->assertEqual($this->columns['col_blob']->isPrimaryKey(), false); - $this->assertEqual($this->columns['col_blob']->getType(), 'BLOB'); - $this->assertEqual($this->columns['col_blob']->getName(), 'col_blob'); - } - public function testRealType() { - $this->assertEqual($this->columns['col_real']->isUnique(), false); - $this->assertEqual($this->columns['col_real']->isNotNull(), false); - $this->assertEqual($this->columns['col_real']->defaultValue(), null); - $this->assertEqual($this->columns['col_real']->isPrimaryKey(), false); - $this->assertEqual($this->columns['col_real']->getType(), 'REAL'); - $this->assertEqual($this->columns['col_real']->getName(), 'col_real'); - } -} -*/ +/* + * class Doctrine_DataDict_Sqlite_TestCase extends Doctrine_UnitTestCase { + * private $dict; + * + * private $columns; + * public function prepareData() { } + * public function prepareTables() { + * $this->dbh->query("CREATE TABLE test (col_null NULL, + * col_int INTEGER NOT NULL, + * col_real REAL, + * col_text TEXT DEFAULT 'default' NOT NULL, + * col_blob BLOB)"); + * + * $this->dict = new Doctrine_DataDict_Sqlite($this->dbh); + * $this->columns = $this->dict->listTableColumns('test'); + * } + * public function testListTables() { + * $result = $this->dict->listTables(); + * + * } + * public function testIntegerType() { + * $this->assertEqual($this->columns['col_int']->isUnique(), false); + * $this->assertEqual($this->columns['col_int']->isNotNull(), true); + * $this->assertEqual($this->columns['col_int']->defaultValue(), null); + * $this->assertEqual($this->columns['col_int']->isPrimaryKey(), false); + * $this->assertEqual($this->columns['col_int']->getType(), 'INTEGER'); + * $this->assertEqual($this->columns['col_int']->getName(), 'col_int'); + * } + * public function testNullType() { + * $this->assertEqual($this->columns['col_null']->isUnique(), false); + * $this->assertEqual($this->columns['col_null']->isNotNull(), false); + * $this->assertEqual($this->columns['col_null']->defaultValue(), null); + * $this->assertEqual($this->columns['col_null']->isPrimaryKey(), false); + * $this->assertEqual($this->columns['col_null']->getType(), 'numeric'); + * $this->assertEqual($this->columns['col_null']->getName(), 'col_null'); + * } + * public function testTextType() { + * $this->assertEqual($this->columns['col_text']->isUnique(), false); + * $this->assertEqual($this->columns['col_text']->isNotNull(), true); + * $this->assertEqual($this->columns['col_text']->defaultValue(), 'default'); + * $this->assertEqual($this->columns['col_text']->isPrimaryKey(), false); + * $this->assertEqual($this->columns['col_text']->getType(), 'TEXT'); + * $this->assertEqual($this->columns['col_text']->getName(), 'col_text'); + * } + * public function testBlobType() { + * $this->assertEqual($this->columns['col_blob']->isUnique(), false); + * $this->assertEqual($this->columns['col_blob']->isNotNull(), false); + * $this->assertEqual($this->columns['col_blob']->defaultValue(), null); + * $this->assertEqual($this->columns['col_blob']->isPrimaryKey(), false); + * $this->assertEqual($this->columns['col_blob']->getType(), 'BLOB'); + * $this->assertEqual($this->columns['col_blob']->getName(), 'col_blob'); + * } + * public function testRealType() { + * $this->assertEqual($this->columns['col_real']->isUnique(), false); + * $this->assertEqual($this->columns['col_real']->isNotNull(), false); + * $this->assertEqual($this->columns['col_real']->defaultValue(), null); + * $this->assertEqual($this->columns['col_real']->isPrimaryKey(), false); + * $this->assertEqual($this->columns['col_real']->getType(), 'REAL'); + * $this->assertEqual($this->columns['col_real']->getName(), 'col_real'); + * } + * } + */ diff --git a/tests/DataDictTestCase.php b/tests/DataDictTestCase.php index 66059782b..8aa914780 100644 --- a/tests/DataDictTestCase.php +++ b/tests/DataDictTestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_DataDict_TestCase + * Doctrine_DataDict_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_DataDict_TestCase extends Doctrine_UnitTestCase { +class Doctrine_DataDict_TestCase extends Doctrine_UnitTestCase +{ } diff --git a/tests/DataType/BooleanTestCase.php b/tests/DataType/BooleanTestCase.php index 78863ea0a..821e34ab9 100644 --- a/tests/DataType/BooleanTestCase.php +++ b/tests/DataType/BooleanTestCase.php @@ -20,24 +20,36 @@ */ /** - * Doctrine_DataType_Boolean_TestCase + * Doctrine_DataType_Boolean_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_DataType_Boolean_TestCase extends Doctrine_UnitTestCase { - public function prepareData() { } - public function prepareTables() { - $this->tables = array("BooleanTest"); +class Doctrine_DataType_Boolean_TestCase extends Doctrine_UnitTestCase +{ + public function prepareData() + { + } + + public function prepareTables() + { + $this->tables = array('BooleanTest'); parent::prepareTables(); } - - public function testSetFalse() { + + public function testSetFalse() + { $test = new BooleanTest(); $test->is_working = false; @@ -49,21 +61,24 @@ public function testSetFalse() { $this->assertIdentical($test->is_working, false); } - public function testSetTrue() { + public function testSetTrue() + { $test = new BooleanTest(); $test->is_working = true; $this->assertIdentical($test->is_working, true); $test->save(); - + $test->refresh(); $this->assertIdentical($test->is_working, true); - + $this->connection->clear(); - + $test = $test->getTable()->find($test->id); $this->assertIdentical($test->is_working, true); } - public function testNormalQuerying() { + + public function testNormalQuerying() + { $query = new Doctrine_Query($this->connection); $ret = $query->query('FROM BooleanTest WHERE BooleanTest.is_working = 0'); $this->assertEqual(count($ret), 1); @@ -73,7 +88,9 @@ public function testNormalQuerying() { $this->assertEqual(count($ret), 1); } - public function testPreparedQueries() { + + public function testPreparedQueries() + { $query = new Doctrine_Query($this->connection); $ret = $query->query('FROM BooleanTest WHERE BooleanTest.is_working = ?', array(false)); $this->assertEqual(count($ret), 1); @@ -82,7 +99,9 @@ public function testPreparedQueries() { $ret = $query->query('FROM BooleanTest WHERE BooleanTest.is_working = ?', array(true)); $this->assertEqual(count($ret), 1); } - public function testFetchingWithSmartConversion() { + + public function testFetchingWithSmartConversion() + { $query = new Doctrine_Query($this->connection); $ret = $query->query('FROM BooleanTest WHERE BooleanTest.is_working = false'); $this->assertEqual(count($ret), 1); @@ -93,7 +112,8 @@ public function testFetchingWithSmartConversion() { $this->assertEqual(count($ret), 1); } - public function testSavingNullValue() { + public function testSavingNullValue() + { $test = new BooleanTest(); $test->is_working = null; @@ -103,7 +123,7 @@ public function testSavingNullValue() { $test->refresh(); $this->assertIdentical($test->is_working, null); - + $test = new BooleanTest(); $test->is_working_notnull = null; @@ -114,5 +134,4 @@ public function testSavingNullValue() { $test->refresh(); $this->assertIdentical($test->is_working_notnull, false); } - } diff --git a/tests/DataType/EnumTestCase.php b/tests/DataType/EnumTestCase.php index a722becdc..596d137dd 100644 --- a/tests/DataType/EnumTestCase.php +++ b/tests/DataType/EnumTestCase.php @@ -20,42 +20,50 @@ */ /** - * Doctrine_DataType_Enum_TestCase + * Doctrine_DataType_Enum_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_DataType_Enum_TestCase extends Doctrine_UnitTestCase +class Doctrine_DataType_Enum_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } - public function prepareTables() + public function prepareData() + { + } + + public function prepareTables() { - $this->tables = array("EnumTest", "EnumTest2", "EnumTest3"); + $this->tables = array('EnumTest', 'EnumTest2', 'EnumTest3'); parent::prepareTables(); } - public function testParameterConversion() + public function testParameterConversion() { $test = new EnumTest(); $test->status = 'open'; $this->assertEqual($test->status, 'open'); $test->save(); - + try { $query = new Doctrine_Query($this->connection); $ret = $query->query("FROM EnumTest WHERE EnumTest.status = 'open'"); $this->assertEqual(count($ret), 1); } catch (Exception $e) { - $this->fail(); + $this->fail(); } } - + public function testUpdate() { $test = new EnumTest2(); @@ -73,9 +81,10 @@ public function testDqlUpdate() { $query = new Doctrine_Query($this->connection); $query->update('EnumTest2 u') - ->set('u.status', '?', 'verified'); + ->set('u.status', '?', 'verified') + ; - $this->assertEqual($query->getSqlQuery(), 'UPDATE enum_test2 SET status = ?'); + $this->assertEqual($query->getSqlQuery(), 'UPDATE enum_test2 SET status = ?'); $query->execute(); @@ -87,13 +96,14 @@ public function testDqlUpdate() $this->fail(); } } - - public function testParameterConversionInCount() + + public function testParameterConversionInCount() { try { $query = new Doctrine_Query($this->connection); $ret = $query->parseDqlQuery("FROM EnumTest WHERE EnumTest.status = 'open'") - ->count(); + ->count() + ; $this->assertEqual($ret, 1); } catch (Exception $e) { $this->fail(); @@ -101,15 +111,16 @@ public function testParameterConversionInCount() try { $query = new Doctrine_Query($this->connection); - $ret = $query->parseDqlQuery("FROM EnumTest WHERE EnumTest.status = ?") - ->count(array('open')); + $ret = $query->parseDqlQuery('FROM EnumTest WHERE EnumTest.status = ?') + ->count(array('open')) + ; $this->assertEqual($ret, 1); } catch (Exception $e) { $this->fail($e->getMessage()); } } - public function testInAndNotIn() + public function testInAndNotIn() { try { $query = new Doctrine_Query($this->connection); @@ -128,7 +139,7 @@ public function testInAndNotIn() } } - public function testExpressionComposition() + public function testExpressionComposition() { try { $query = new Doctrine_Query($this->connection); @@ -139,7 +150,7 @@ public function testExpressionComposition() } } - public function testNotEqual() + public function testNotEqual() { try { $query = new Doctrine_Query($this->connection); @@ -150,9 +161,8 @@ public function testNotEqual() } } - public function testEnumType() + public function testEnumType() { - $enum = new EnumTest(); $enum->status = 'open'; $this->assertEqual($enum->status, 'open'); @@ -172,7 +182,7 @@ public function testEnumType() $this->assertEqual($enum->status, 'closed'); } - public function testEnumTypeWithCaseConversion() + public function testEnumTypeWithCaseConversion() { $this->conn->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER); @@ -185,8 +195,8 @@ public function testEnumTypeWithCaseConversion() $this->assertEqual($enum->status, 'open'); $enum->refresh(); - $this->assertEqual($enum->status, 'open'); - + $this->assertEqual($enum->status, 'open'); + $enum->status = 'closed'; $this->assertEqual($enum->status, 'closed'); @@ -200,7 +210,7 @@ public function testEnumTypeWithCaseConversion() $this->conn->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL); } - public function testFailingRefresh() + public function testFailingRefresh() { $enum = $this->connection->getTable('EnumTest')->find(1); @@ -210,7 +220,7 @@ public function testFailingRefresh() $enum->refresh(); $this->fail(); - } catch(Doctrine_Record_Exception $e) { + } catch (Doctrine_Record_Exception $e) { $this->pass(); } } @@ -219,8 +229,9 @@ public function testEnumFetchArray() { $q = new Doctrine_Query(); $q->select('e.*') - ->from('EnumTest e') - ->limit(1); + ->from('EnumTest e') + ->limit(1) + ; $ret = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); if (is_numeric($ret[0]['status'])) { @@ -232,11 +243,12 @@ public function testLiteralEnumValueConversionSupportsJoins() { $q = new Doctrine_Query($this->connection); $q->addSelect('e.*') - ->addSelect('e3.*') - ->from('EnumTest e') - ->leftJoin('e.Enum3 e3') - ->where("e.status = 'verified'") - ->execute(); + ->addSelect('e3.*') + ->from('EnumTest e') + ->leftJoin('e.Enum3 e3') + ->where("e.status = 'verified'") + ->execute() + ; $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.status AS e__status, e.text AS e__text, e2.text AS e2__text FROM enum_test e LEFT JOIN enum_test3 e2 ON e.text = e2.text WHERE (e.status = 'verified')"); } @@ -255,4 +267,4 @@ public function testInvalidValueErrors() } Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, $orig); } -} \ No newline at end of file +} diff --git a/tests/Db/ProfilerTestCase.php b/tests/Db/ProfilerTestCase.php index bad7733a4..7ed64ce43 100644 --- a/tests/Db/ProfilerTestCase.php +++ b/tests/Db/ProfilerTestCase.php @@ -20,25 +20,33 @@ */ /** - * Doctrine_Connection_Profiler_TestCase + * Doctrine_Connection_Profiler_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Db * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Connection_Profiler_TestCase extends Doctrine_UnitTestCase +class Doctrine_Connection_Profiler_TestCase extends Doctrine_UnitTestCase { public function prepareTables() - {} - public function prepareData() - {} - - public function testQuery() + { + } + + public function prepareData() + { + } + + public function testQuery() { $this->conn = Doctrine_Manager::getInstance()->openConnection(array('sqlite::memory:')); @@ -47,18 +55,18 @@ public function testQuery() $this->conn->setListener($this->profiler); $this->conn->exec('CREATE TABLE test (id INT)'); - + $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'CREATE TABLE test (id INT)'); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Db_Event::EXEC); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + $this->assertEqual($this->conn->count(), 1); } - public function testPrepareAndExecute() - { - $stmt = $this->conn->prepare('INSERT INTO test (id) VALUES (?)'); + public function testPrepareAndExecute() + { + $stmt = $this->conn->prepare('INSERT INTO test (id) VALUES (?)'); $event = $this->profiler->lastEvent(); $this->assertEqual($event->getQuery(), 'INSERT INTO test (id) VALUES (?)'); @@ -75,9 +83,9 @@ public function testPrepareAndExecute() $this->assertEqual($this->conn->count(), 2); } - public function testMultiplePrepareAndExecute() - { + public function testMultiplePrepareAndExecute() + { $stmt = $this->conn->prepare('INSERT INTO test (id) VALUES (?)'); $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'INSERT INTO test (id) VALUES (?)'); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); @@ -99,8 +107,8 @@ public function testMultiplePrepareAndExecute() $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); $this->assertEqual($this->conn->count(), 4); - } + public function testExecuteStatementMultipleTimes() { try { @@ -108,8 +116,7 @@ public function testExecuteStatementMultipleTimes() $stmt->execute(array(1)); $stmt->execute(array(1)); $this->pass(); - } catch(Doctrine_Db_Exception $e) { - + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'INSERT INTO test (id) VALUES (?)'); @@ -122,23 +129,24 @@ public function testExecuteStatementMultipleTimes() $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Db_Event::EXECUTE); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); } - public function testTransactionRollback() + + public function testTransactionRollback() { try { $this->conn->beginTransaction(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), null); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Db_Event::BEGIN); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + try { $this->conn->rollback(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } @@ -147,23 +155,24 @@ public function testTransactionRollback() $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Db_Event::ROLLBACK); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); } - public function testTransactionCommit() + + public function testTransactionCommit() { try { $this->conn->beginTransaction(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), null); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getCode(), Doctrine_Db_Event::BEGIN); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + try { $this->conn->commit(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); $this->conn->rollback(); } diff --git a/tests/DbProfilerTestCase.php b/tests/DbProfilerTestCase.php index 1494f3751..6f75debb8 100644 --- a/tests/DbProfilerTestCase.php +++ b/tests/DbProfilerTestCase.php @@ -1,12 +1,26 @@ dbh = Doctrine_Db2::getConnection('sqlite::memory:'); $this->profiler = new Doctrine_Db_Profiler(); @@ -14,17 +28,18 @@ public function testQuery() { $this->dbh->setListener($this->profiler); $this->dbh->query('CREATE TABLE test (id INT)'); - + $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'CREATE TABLE test (id INT)'); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getType(), Doctrine_Db_Event::QUERY); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + $this->assertEqual($this->dbh->count(), 1); } - public function testPrepareAndExecute() { - $stmt = $this->dbh->prepare('INSERT INTO test (id) VALUES (?)'); + public function testPrepareAndExecute() + { + $stmt = $this->dbh->prepare('INSERT INTO test (id) VALUES (?)'); $event = $this->profiler->lastEvent(); $this->assertEqual($event->getQuery(), 'INSERT INTO test (id) VALUES (?)'); @@ -41,8 +56,9 @@ public function testPrepareAndExecute() { $this->assertEqual($this->dbh->count(), 2); } - public function testMultiplePrepareAndExecute() { + public function testMultiplePrepareAndExecute() + { $stmt = $this->dbh->prepare('INSERT INTO test (id) VALUES (?)'); $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'INSERT INTO test (id) VALUES (?)'); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); @@ -65,14 +81,15 @@ public function testMultiplePrepareAndExecute() { $this->assertEqual($this->dbh->count(), 4); } - public function testExecuteStatementMultipleTimes() { + + public function testExecuteStatementMultipleTimes() + { try { $stmt = $this->dbh->prepare('INSERT INTO test (id) VALUES (?)'); $stmt->execute(array(1)); $stmt->execute(array(1)); $this->pass(); - } catch(Doctrine_Db_Exception $e) { - + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), 'INSERT INTO test (id) VALUES (?)'); @@ -85,22 +102,24 @@ public function testExecuteStatementMultipleTimes() { $this->assertEqual($this->profiler->lastEvent()->getType(), Doctrine_Db_Event::EXECUTE); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); } - public function testTransactionRollback() { + + public function testTransactionRollback() + { try { $this->dbh->beginTransaction(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), null); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getType(), Doctrine_Db_Event::BEGIN); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + try { $this->dbh->rollback(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } @@ -109,22 +128,24 @@ public function testTransactionRollback() { $this->assertEqual($this->profiler->lastEvent()->getType(), Doctrine_Db_Event::ROLLBACK); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); } - public function testTransactionCommit() { + + public function testTransactionCommit() + { try { $this->dbh->beginTransaction(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); } $this->assertEqual($this->profiler->lastEvent()->getQuery(), null); $this->assertTrue($this->profiler->lastEvent()->hasEnded()); $this->assertEqual($this->profiler->lastEvent()->getType(), Doctrine_Db_Event::BEGIN); $this->assertTrue(is_numeric($this->profiler->lastEvent()->getElapsedSecs())); - + try { $this->dbh->commit(); $this->pass(); - } catch(Doctrine_Db_Exception $e) { + } catch (Doctrine_Db_Exception $e) { $this->fail($e->__toString()); $this->dbh->rollback(); } diff --git a/tests/DoctrineTest.php b/tests/DoctrineTest.php index 59e60b050..4fd392993 100644 --- a/tests/DoctrineTest.php +++ b/tests/DoctrineTest.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_UnitTestCase + * Doctrine_UnitTestCase. * - * @package Doctrine * @author Konsta Vesterinen * @author Bjarte S. Karlsen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ -require_once dirname(__FILE__) . '/DoctrineTest/UnitTestCase.php'; -require_once dirname(__FILE__) . '/DoctrineTest/GroupTest.php'; -require_once dirname(__FILE__) . '/DoctrineTest/Doctrine_UnitTestCase.php'; -require_once dirname(__FILE__) . '/DoctrineTest/Reporter.php'; +require_once dirname(__FILE__).'/DoctrineTest/UnitTestCase.php'; +require_once dirname(__FILE__).'/DoctrineTest/GroupTest.php'; +require_once dirname(__FILE__).'/DoctrineTest/Doctrine_UnitTestCase.php'; +require_once dirname(__FILE__).'/DoctrineTest/Reporter.php'; class DoctrineTest { - protected $testGroup; // the default test group protected $groups; @@ -64,48 +65,47 @@ public function addTestCase($testCase) } /** - * Run the tests + * Run the tests. * * This method will run the tests with the correct Reporter. It will run * grouped tests if asked to and filter results. It also has support for * running coverage report. - * */ public function run() { $testGroup = $this->testGroup; if (PHP_SAPI === 'cli') { - require_once(dirname(__FILE__) . '/DoctrineTest/Reporter/Cli.php'); + require_once dirname(__FILE__).'/DoctrineTest/Reporter/Cli.php'; $reporter = new DoctrineTest_Reporter_Cli(); $argv = $_SERVER['argv']; array_shift($argv); $options = $this->parseOptions($argv); } else { - require_once(dirname(__FILE__) . '/DoctrineTest/Reporter/Html.php'); + require_once dirname(__FILE__).'/DoctrineTest/Reporter/Html.php'; $options = $_GET; if (isset($options['filter'])) { - if ( ! is_array($options['filter'])) { + if (!is_array($options['filter'])) { $options['filter'] = explode(',', $options['filter']); } } if (isset($options['group'])) { - if ( ! is_array($options['group'])) { + if (!is_array($options['group'])) { $options['group'] = explode(',', $options['group']); } } $reporter = new DoctrineTest_Reporter_Html(); } - //replace global group with custom group if we have group option set + // replace global group with custom group if we have group option set if (isset($options['group'])) { $testGroup = new GroupTest('Doctrine Custom Test', 'custom'); - foreach($options['group'] as $group) { + foreach ($options['group'] as $group) { if (isset($this->groups[$group])) { $testGroup->addTestCase($this->groups[$group]); - } else if (class_exists($group)) { - $testGroup->addTestCase(new $group); + } elseif (class_exists($group)) { + $testGroup->addTestCase(new $group()); } else { - die($group . " is not a valid group or doctrine test class\n "); + exit($group." is not a valid group or doctrine test class\n "); } } } @@ -113,8 +113,8 @@ public function run() if (isset($options['ticket'])) { $testGroup = new GroupTest('Doctrine Custom Test', 'custom'); foreach ($options['ticket'] as $ticket) { - $class = 'Doctrine_Ticket_' . $ticket. '_TestCase'; - $testGroup->addTestCase(new $class); + $class = 'Doctrine_Ticket_'.$ticket.'_TestCase'; + $testGroup->addTestCase(new $class()); } } @@ -123,7 +123,7 @@ public function run() $filter = $options['filter']; } - //show help text + // show help text if (isset($options['help'])) { $availableGroups = array_keys($this->groups); sort($availableGroups); @@ -135,14 +135,13 @@ public function run() echo " -coverage will generate coverage report data that can be viewed with the cc.php script in this folder. NB! This takes time. You need xdebug to run this\n"; echo " -group Use this option to run just a group of tests or tests with a given classname. Groups are currently defined as the variable name they are called in this script.\n"; echo " -filter case insensitive strings that will be applied to the className of the tests. A test_classname must contain all of these strings to be run\n"; - echo "\nAvailable groups:\n " . implode(', ', $availableGroups) . "\n"; + echo "\nAvailable groups:\n ".implode(', ', $availableGroups)."\n"; - die(); + exit; } - //generate coverage report + // generate coverage report if (isset($options['coverage'])) { - /* * The below code will not work for me (meus). It would be nice if * somebody could give it a try. Just replace this block of code @@ -170,10 +169,11 @@ public function run() $ret = $testGroup->run($reporter, $filter); $result['coverage'] = xdebug_get_code_coverage(); xdebug_stop_code_coverage(); - file_put_contents(dirname(__FILE__) . '/coverage/coverage.txt', serialize($result)); - require_once dirname(__FILE__) . '/DoctrineTest/Coverage.php'; + file_put_contents(dirname(__FILE__).'/coverage/coverage.txt', serialize($result)); + require_once dirname(__FILE__).'/DoctrineTest/Coverage.php'; $coverageGeneration = new DoctrineTest_Coverage(); $coverageGeneration->generateReport(); + return $ret; // */ } @@ -189,27 +189,26 @@ public function run() $time = $endTime - $startTime; if (PHP_SAPI === 'cli') { - echo "\nTests ran in " . $time . " seconds and used " . (memory_get_peak_usage() / 1024) . " KB of memory\n\n"; + echo "\nTests ran in ".$time.' seconds and used '.(memory_get_peak_usage() / 1024)." KB of memory\n\n"; } else { - echo "

Tests ran in " . $time . " seconds and used " . (memory_get_peak_usage() / 1024) . " KB of memory

"; + echo '

Tests ran in '.$time.' seconds and used '.(memory_get_peak_usage() / 1024).' KB of memory

'; } return $result; } /** - * Require all the models needed in the tests - * + * Require all the models needed in the tests. */ public function requireModels() { - $models = new DirectoryIterator(dirname(__FILE__) . '/models/'); + $models = new DirectoryIterator(dirname(__FILE__).'/models/'); - foreach($models as $key => $file) { - if ($file->isFile() && ! $file->isDot()) { + foreach ($models as $key => $file) { + if ($file->isFile() && !$file->isDot()) { $e = explode('.', $file->getFileName()); - if (end($e) === 'php') { + if ('php' === end($e)) { require_once $file->getPathname(); } } @@ -217,21 +216,23 @@ public function requireModels() } /** - * Parse Options from cli into an associative array + * Parse Options from cli into an associative array. * * @param array $array An argv array from cli + * * @return array An array with options */ - public function parseOptions($array) { + public function parseOptions($array) + { $currentName = ''; $options = array(); - foreach($array as $name) { - if (strpos($name, '--') === 0) { + foreach ($array as $name) { + if (0 === strpos($name, '--')) { $name = ltrim($name, '--'); $currentName = $name; - if ( ! isset($options[$currentName])) { + if (!isset($options[$currentName])) { $options[$currentName] = array(); } } else { @@ -245,16 +246,17 @@ public function parseOptions($array) { } /** - * Autoload test cases + * Autoload test cases. * * Will create test case if it does not exist * * @param string $class The name of the class to autoload - * @return boolean True + * + * @return bool True */ public static function autoload($class) { - if (strpos($class, 'TestCase') === false) { + if (false === strpos($class, 'TestCase')) { return false; } @@ -262,27 +264,27 @@ public static function autoload($class) $count = count($e); $prefix = array_shift($e); - if ($prefix !== 'Doctrine') { + if ('Doctrine' !== $prefix) { return false; } $dir = array_shift($e); - $file = $dir . '_' . substr(implode('_', $e), 0, -(strlen('_TestCase'))) . 'TestCase.php'; - $file = str_replace('_', (($count > 3) ? DIRECTORY_SEPARATOR : ''), $file); + $file = $dir.'_'.substr(implode('_', $e), 0, -strlen('_TestCase')).'TestCase.php'; + $file = str_replace('_', ($count > 3) ? DIRECTORY_SEPARATOR : '', $file); // create a test case file if it doesn't exist - if ( ! file_exists($file)) { + if (!file_exists($file)) { $contents = file_get_contents(DOCTRINE_DIR.'/tests/template.tpl'); $contents = sprintf($contents, $class, $class); - if ( ! file_exists($dir)) { + if (!file_exists($dir)) { mkdir($dir, 0777); } file_put_contents($file, $contents); } - require_once($file); + require_once $file; return true; } diff --git a/tests/DoctrineTest/Coverage.php b/tests/DoctrineTest/Coverage.php index 4307124b0..e44a2a690 100644 --- a/tests/DoctrineTest/Coverage.php +++ b/tests/DoctrineTest/Coverage.php @@ -20,24 +20,24 @@ */ /** - * Doctrine_UnitTestCase + * Doctrine_UnitTestCase. * - * @package Doctrine * @author Konsta Vesterinen * @author Bjarte S. Karlsen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ - class DoctrineTest_Coverage { - - const COVERED = 1; - const MAYBE = -2; - const NOTCOVERED = -1; + public const COVERED = 1; + public const MAYBE = -2; + public const NOTCOVERED = -1; private $covered; private $totallines = 0; @@ -47,23 +47,22 @@ class DoctrineTest_Coverage private $result; /* - * Create a new Coverage object. We read data from a fixed file. + * Create a new Coverage object. We read data from a fixed file. */ public function __construct() { - $this->result = unserialize(file_get_contents($this->getCoverageDir() . "coverage.txt")); - $this->sortBy ="percentage"; // default sort + $this->result = unserialize(file_get_contents($this->getCoverageDir().'coverage.txt')); + $this->sortBy = 'percentage'; // default sort } /** - * Get the directory to store coverage report in + * Get the directory to store coverage report in. * * @return string The path to store the coverage in */ public function getCoverageDir() { - $dir = Doctrine_Core::getPath() . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "tests" . DIRECTORY_SEPARATOR . "coverage" . DIRECTORY_SEPARATOR; - return $dir; + return Doctrine_Core::getPath().DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'tests'.DIRECTORY_SEPARATOR.'coverage'.DIRECTORY_SEPARATOR; } /* @@ -72,95 +71,91 @@ public function getCoverageDir() */ public function showSummary() { - if ( isset($_GET['order'])) { + if (isset($_GET['order'])) { $this->sortBy = $_GET['order']; } - if ( ! isset($this->result['data'])) { - die("Impropper coverage report. Please regenerate"); + if (!isset($this->result['data'])) { + exit('Impropper coverage report. Please regenerate'); } - $coveredArray = $this->result["data"]; - //lets sort it. - uasort($coveredArray, array($this,"sortArray")); + $coveredArray = $this->result['data']; + // lets sort it. + uasort($coveredArray, array($this, 'sortArray')); - //and flip if it perhaps? - if (isset($_GET["flip"]) && $_GET["flip"] == "true") { + // and flip if it perhaps? + if (isset($_GET['flip']) && 'true' == $_GET['flip']) { $coveredArray = array_reverse($coveredArray, true); } - $totals = $this->result["totals"]; - - echo 'TOTAL' , - $totals['percentage'] , '%' , - $totals['lines'] , '' , - $totals['covered'] , '', - $totals['maybe'] , '', - $totals['notcovered'] , ''; + $totals = $this->result['totals']; - foreach($coveredArray as $class => $info) { + echo 'TOTAL' , + $totals['percentage'] , '%' , + $totals['lines'] , '' , + $totals['covered'] , '', + $totals['maybe'] , '', + $totals['notcovered'] , ''; + foreach ($coveredArray as $class => $info) { echo ''; - if ( $info['type'] == "covered") { + if ('covered' == $info['type']) { echo '', $class , ''; - }else{ + } else { echo $class; } - echo '' . $info['percentage'] . ' % ' . $info['total'] . '' . $info['covered'] . '' . $info['maybe'] . '' . $info['notcovered']. ''; + echo ''.$info['percentage'].' % '.$info['total'].''.$info['covered'].''.$info['maybe'].''.$info['notcovered'].''; } } /** - * Return the revision the coverage was made against + * Return the revision the coverage was made against. * *@param int The revision number */ public function getRevision() { - return $this->result["revision"]; + return $this->result['revision']; } /** * Generate the report. * - * This method will analyze the coverage data and create a data array that - * contains information about each of the classes in Doctrine/lib. It will - * also generate html files for each file that has coverage data with - * information about what lines that are covered. - * + * This method will analyze the coverage data and create a data array that + * contains information about each of the classes in Doctrine/lib. It will + * also generate html files for each file that has coverage data with + * information about what lines that are covered. * * @uses generateCoverageInfoCoveredFile * @uses saveFile * @uses generateCoverageInfoNotCoveredFile * @uses getCoverageDir * @uses calculateTotalPercentage - * */ public function generateReport() { - $svn_info = explode(" ", exec("svn info | grep Revision")); - $this->result["revision"] = $svn_info[1]; + $svn_info = explode(' ', exec('svn info | grep Revision')); + $this->result['revision'] = $svn_info[1]; - //loop through all files and generate coverage files for them + // loop through all files and generate coverage files for them $it = new RecursiveDirectoryIterator(Doctrine_Core::getPath()); $notCoveredArray = array(); foreach (new RecursiveIteratorIterator($it) as $file) { - - if (strpos($file->getPathname(), "config.php")) { + if (strpos($file->getPathname(), 'config.php')) { continue; } - if (strpos($file->getPathname(), ".svn")) { + if (strpos($file->getPathname(), '.svn')) { continue; - } - + } + $class = $this->getClassNameFromFileName($file->getPathname()); if (strpos($class, '_Interface')) { continue; } - if ( ! class_exists($class)) { + if (!class_exists($class)) { continue; } @@ -171,43 +166,43 @@ public function generateReport() $coverageInfo[$class] = $this->generateCoverageInfoNotCoveredFile($class); } } - $this->result["totals"] = array( - "lines" => $this->totallines, - "notcovered" => $this->totalnotcovered, - "covered" => $this->totalcovered, - "maybe" => $this->totalmaybe, - "percentage" => $this->calculateTotalPercentage()); + $this->result['totals'] = array( + 'lines' => $this->totallines, + 'notcovered' => $this->totalnotcovered, + 'covered' => $this->totalcovered, + 'maybe' => $this->totalmaybe, + 'percentage' => $this->calculateTotalPercentage()); - $this->result["data"] = $coverageInfo; + $this->result['data'] = $coverageInfo; - file_put_contents($this->getCoverageDir() . "coverage.txt", serialize($this->result)); - return true; + file_put_contents($this->getCoverageDir().'coverage.txt', serialize($this->result)); + return true; } /** - * * Return the name of a class from its filename. * - * This method simply removes the Doctrine Path and raplces _ with / and + * This method simply removes the Doctrine Path and raplces _ with / and * removes .php to get the classname for a file * * @param string $fileName The name of the file + * * @return string The name of the class */ public function getClassNameFromFileName($fileName) { - $path = Doctrine_Core::getPath() . DIRECTORY_SEPARATOR; - $class = str_replace($path, "", $fileName); - $class = str_replace(DIRECTORY_SEPARATOR, "_", $class); - $class = substr($class, 0,-4); - return $class; + $path = Doctrine_Core::getPath().DIRECTORY_SEPARATOR; + $class = str_replace($path, '', $fileName); + $class = str_replace(DIRECTORY_SEPARATOR, '_', $class); + + return substr($class, 0, -4); } /** - * Calculate total coverage percentage + * Calculate total coverage percentage. * - * @return double The percetage as a double + * @return float The percetage as a double */ public function calculateTotalPercentage() { @@ -217,10 +212,11 @@ public function calculateTotalPercentage() /** * Generate Coverage for a class that is not in the coverage report. * - * This method will simply check if the method has no lines that should be - * tested or not. Then it will return data to be stored for later use. + * This method will simply check if the method has no lines that should be + * tested or not. Then it will return data to be stored for later use. * * @param string $class The name of a class + * * @return array An associative array with coverage information */ public function generateCoverageInfoNotCoveredFile($class) @@ -241,27 +237,26 @@ public function generateCoverageInfoNotCoveredFile($class) } $this->totallines += $lines; $this->totalnotcovered += $lines; - if ($lines == 0) { - return array("covered" => 0, "maybe" => 0, "notcovered"=>$lines, "total" => $lines, "percentage" => 100, "type" => "notcovered"); - } else { - return array("covered" => 0, "maybe" => 0, "notcovered"=>$lines, "total" => $lines, "percentage" => 0, "type" => "notcovered"); + if (0 == $lines) { + return array('covered' => 0, 'maybe' => 0, 'notcovered' => $lines, 'total' => $lines, 'percentage' => 100, 'type' => 'notcovered'); } - } + return array('covered' => 0, 'maybe' => 0, 'notcovered' => $lines, 'total' => $lines, 'percentage' => 0, 'type' => 'notcovered'); + } /* - * Save a html report for the given filename + * Save a html report for the given filename * - * @param string $fileName The name of the file + * @param string $fileName The name of the file */ public function saveFile($fileName) { $className = $this->getClassNameFromFileName($fileName); - $title = "Coverage for " . $className; - + $title = 'Coverage for '.$className; + $html = ' - ' . $title . ' + '.$title.' -

' . $title . '

Back to coverage report

'; - $coveredLines = $this->result["coverage"][$fileName]; +

'.$title.'

Back to coverage report

'; + $coveredLines = $this->result['coverage'][$fileName]; $fileArray = file($fileName); - $html .= '' . "\n"; + $html .= '
'."\n"; foreach ($fileArray as $num => $line) { - $linenum = $num+1; - $html .= '' . "\n"; - $class ="normal"; - if (isset($coveredLines[$linenum]) && $coveredLines[$linenum] == self::COVERED) { - $class = "covered"; - } else if (isset($coveredLines[$linenum]) && $coveredLines[$linenum] == self::NOTCOVERED) { - $class ="red"; - } else if (isset($coveredLines[$linenum]) && $coveredLines[$linenum] == self::MAYBE) { - $class ="orange"; + $linenum = $num + 1; + $html .= ''."\n"; + $class = 'normal'; + if (isset($coveredLines[$linenum]) && self::COVERED == $coveredLines[$linenum]) { + $class = 'covered'; + } elseif (isset($coveredLines[$linenum]) && self::NOTCOVERED == $coveredLines[$linenum]) { + $class = 'red'; + } elseif (isset($coveredLines[$linenum]) && self::MAYBE == $coveredLines[$linenum]) { + $class = 'orange'; } - $line = str_replace(" ", " ", htmlspecialchars($line)); - $html .= '' . "\n"; + $line = str_replace(' ', ' ', htmlspecialchars($line)); + $html .= ''."\n"; } - $html .='
' . $linenum . '
'.$linenum.'' . $line . '
'.$line.'
'; - file_put_contents($this->getCoverageDir() . $className . ".html",$html); + $html .= ''; + file_put_contents($this->getCoverageDir().$className.'.html', $html); } /* @@ -300,36 +295,37 @@ public function saveFile($fileName) */ public function generateCoverageInfoCoveredFile($file) { - $lines = $this->result["coverage"][$file]; + $lines = $this->result['coverage'][$file]; - $total = count($lines) -1; //we have to remove one since it always reports the last line as a hit + $total = count($lines) - 1; // we have to remove one since it always reports the last line as a hit $covered = 0; $maybe = 0; $notcovered = 0; foreach ($lines as $result) { - switch($result) { - case self::COVERED: - $covered++; - break; - case self::NOTCOVERED: - $notcovered++; - break; - case self::MAYBE: - $maybe++; - break; + switch ($result) { + case self::COVERED: + $covered++; + break; + case self::NOTCOVERED: + $notcovered++; + break; + case self::MAYBE: + $maybe++; + break; } } - $covered--; //again we have to remove that last line. + --$covered; // again we have to remove that last line. $this->totallines += $total; $this->totalcovered += $covered; $this->totalnotcovered += $notcovered; $this->totalmaybe += $maybe; - if ($total === 0) { + if (0 === $total) { $total = 1; } $percentage = round((($covered + $maybe) / $total) * 100, 2); - return array("covered" => $covered, "maybe" => $maybe, "notcovered"=>$notcovered, "total" => $total, "percentage" => $percentage, "type" => "covered"); + + return array('covered' => $covered, 'maybe' => $maybe, 'notcovered' => $notcovered, 'total' => $total, 'percentage' => $percentage, 'type' => 'covered'); } /* @@ -341,6 +337,7 @@ public function sortArray($a, $b) if ($a[$this->sortBy] == $b[$this->sortBy]) { return 0; } - return ( $a[$this->sortBy] < $b[$this->sortBy]) ? 1 : -1; + + return ($a[$this->sortBy] < $b[$this->sortBy]) ? 1 : -1; } } diff --git a/tests/DoctrineTest/Doctrine_UnitTestCase.php b/tests/DoctrineTest/Doctrine_UnitTestCase.php index a1f0fb2f7..048dd8eda 100644 --- a/tests/DoctrineTest/Doctrine_UnitTestCase.php +++ b/tests/DoctrineTest/Doctrine_UnitTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_UnitTestCase + * Doctrine_UnitTestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_UnitTestCase extends UnitTestCase { @@ -70,7 +76,7 @@ public function setUp() { parent::setUp(); - if ( ! $this->init) { + if (!$this->init) { $this->init(); } if (isset($this->objTable)) { @@ -96,59 +102,57 @@ public function init() { $this->_name = get_class($this); - $this->manager = Doctrine_Manager::getInstance(); + $this->manager = Doctrine_Manager::getInstance(); $this->manager->setAttribute(Doctrine_Core::ATTR_EXPORT, Doctrine_Core::EXPORT_ALL); $this->tables = array_merge($this->tables, - array('entity', - 'entityReference', - 'email', - 'phonenumber', - 'groupuser', - 'album', - 'song', - 'element', - 'testerror', - 'description', - 'address', - 'account', - 'task', - 'resource', - 'assignment', - 'resourceType', - 'resourceReference') - ); - + array('entity', + 'entityReference', + 'email', + 'phonenumber', + 'groupuser', + 'album', + 'song', + 'element', + 'testerror', + 'description', + 'address', + 'account', + 'task', + 'resource', + 'assignment', + 'resourceType', + 'resourceReference') + ); $class = get_class($this); - $e = explode('_', $class); + $e = explode('_', $class); - - if ( ! $this->driverName) { + if (!$this->driverName) { $this->driverName = 'main'; - switch($e[1]) { + switch ($e[1]) { case 'Export': case 'Import': case 'Transaction': case 'DataDict': case 'Sequence': $this->driverName = 'Sqlite'; - break; + break; } $module = $e[1]; if (count($e) > 3) { $driver = $e[2]; - switch($e[2]) { + switch ($e[2]) { case 'Mysql': case 'Mssql': case 'Oracle': case 'Pgsql': case 'Sqlite': $this->driverName = $e[2]; - break; + break; } } } @@ -158,13 +162,12 @@ public function init() $this->manager->setCurrentConnection($this->driverName); $this->connection->evictTables(); - $this->dbh = $this->adapter = $this->connection->getDbh(); + $this->dbh = $this->adapter = $this->connection->getDbh(); $this->listener = $this->manager->getAttribute(Doctrine_Core::ATTR_LISTENER); $this->manager->setAttribute(Doctrine_Core::ATTR_LISTENER, $this->listener); - - } catch(Doctrine_Manager_Exception $e) { - if ($this->driverName == 'main') { + } catch (Doctrine_Manager_Exception $e) { + if ('main' == $this->driverName) { $this->dbh = new PDO('sqlite::memory:'); $this->dbh->sqliteCreateFunction('trim', 'trim', 1); } else { @@ -173,21 +176,18 @@ public function init() $this->conn = $this->connection = $this->manager->openConnection($this->dbh, $this->driverName); - if ($this->driverName !== 'main') { - $exc = 'Doctrine_Connection_' . ucwords($this->driverName) . '_Exception'; + if ('main' !== $this->driverName) { + $exc = 'Doctrine_Connection_'.ucwords($this->driverName).'_Exception'; $this->exc = new $exc(); - - } else { } $this->listener = new Doctrine_EventListener(); $this->manager->setAttribute(Doctrine_Core::ATTR_LISTENER, $this->listener); } - if ($this->driverName !== 'main') { - + if ('main' !== $this->driverName) { if (isset($module)) { - switch($module) { + switch ($module) { case 'Export': case 'Import': case 'Transaction': @@ -195,11 +195,11 @@ public function init() case 'Expression': $lower = strtolower($module); - $this->$lower = $this->connection->$lower; - break; + $this->{$lower} = $this->connection->{$lower}; + break; case 'DataDict': $this->dataDict = $this->connection->dataDict; - break; + break; } } } @@ -207,28 +207,30 @@ public function init() $this->connection->setListener(new Doctrine_EventListener()); $this->query = new Doctrine_Query($this->connection); - if ($this->driverName === 'main') { + if ('main' === $this->driverName) { $this->prepareTables(); $this->prepareData(); foreach ($this->tables as $name) { - $this->connection->getTable(ucwords($name))->clear(); + $this->connection->getTable(ucwords($name))->clear(); } } } - public function prepareTables() { - foreach($this->tables as $name) { + + public function prepareTables() + { + foreach ($this->tables as $name) { $name = ucwords($name); $table = $this->connection->getTable($name); - $query = 'DROP TABLE ' . $table->getTableName(); + $query = 'DROP TABLE '.$table->getTableName(); try { $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { - + } catch (Doctrine_Connection_Exception $e) { } } $this->conn->export->exportClasses($this->tables); $this->objTable = $this->connection->getTable('User'); } + public function prepareData() { $groups = new Doctrine_Collection($this->connection->getTable('Group')); @@ -237,14 +239,12 @@ public function prepareData() $groups[1]->name = 'Quality Actors'; - $groups[2]->name = 'Action Actors'; $groups[2]['Phonenumber'][0]->phonenumber = '123 123'; $groups->save(); $users = new Doctrine_Collection('User'); - $users[0]->name = 'zYne'; $users[0]['Email']->address = 'zYne@example.com'; $users[0]['Phonenumber'][0]->phonenumber = '123 123'; @@ -287,20 +287,23 @@ public function prepareData() $this->users = $users; $this->users->save(); } + public function getConnection() { return $this->connection; } + public function assertDeclarationType($type, $type2) { $dec = $this->getDeclaration($type); - if ( ! is_array($type2)) { + if (!is_array($type2)) { $type2 = array($type2); } $this->assertEqual($dec['type'], $type2); } + public function getDeclaration($type) { return $this->dataDict->getPortableDeclaration(array('type' => $type, 'name' => 'colname', 'length' => 1, 'fixed' => true)); diff --git a/tests/DoctrineTest/GroupTest.php b/tests/DoctrineTest/GroupTest.php index b17f5e37e..428b00f36 100644 --- a/tests/DoctrineTest/GroupTest.php +++ b/tests/DoctrineTest/GroupTest.php @@ -1,4 +1,10 @@ _title = $title; - $this->_name = $name; - if ( PHP_SAPI != 'cli' && ! defined('STDOUT')) { + $this->_name = $name; + if (PHP_SAPI != 'cli' && !defined('STDOUT')) { define('STDOUT', ''); } $this->_formatter = new Doctrine_Cli_AnsiColorFormatter(); @@ -30,28 +36,30 @@ public function getName() public function addTestCase(UnitTestCase $testCase) { - if ($testCase instanceOf GroupTest) { + if ($testCase instanceof GroupTest) { $this->_testCases = array_merge($this->_testCases, $testCase->getTestCases()); - } else { + } else { $this->_testCases[get_class($testCase)] = $testCase; - } + } } public function shouldBeRun($testCase, $filter) { - if ( ! is_array($filter)) { + if (!is_array($filter)) { return true; } - foreach($filter as $subFilter) { + foreach ($filter as $subFilter) { $name = strtolower(get_class($testCase)); $pos = strpos($name, strtolower($subFilter)); - //it can be 0 so we have to use === to see if false - if ($pos === false) { + // it can be 0 so we have to use === to see if false + if (false === $pos) { return false; } } + return true; } + public function run(DoctrineTest_Reporter $reporter = null, $filter = null) { set_time_limit(900); @@ -64,20 +72,20 @@ public function run(DoctrineTest_Reporter $reporter = null, $filter = null) $lastRunsFails = $this->getLastRunsFails(); foreach ($this->_testCases as $k => $testCase) { - if ($this->_onlyRunFailed && ! isset($lastRunsFails[get_class($testCase)])) { + if ($this->_onlyRunFailed && !isset($lastRunsFails[get_class($testCase)])) { continue; } $reporter->setTestCase($testCase); - if ( ! $this->shouldBeRun($testCase, $filter)) { + if (!$this->shouldBeRun($testCase, $filter)) { continue; } try { $testCase->run(); } catch (Exception $e) { - $this->_failed += 1; - $message = 'Unexpected ' . get_class($e) . ' thrown in [' . get_class($testCase) . '] with message [' . $e->getMessage() . '] in ' . $e->getFile() . ' on line ' . $e->getLine() . "\n\nTrace\n-------------\n\n" . $e->getTraceAsString(); + ++$this->_failed; + $message = 'Unexpected '.get_class($e).' thrown in ['.get_class($testCase).'] with message ['.$e->getMessage().'] in '.$e->getFile().' on line '.$e->getLine()."\n\nTrace\n-------------\n\n".$e->getTraceAsString(); $testCase->addMessage($message); } @@ -109,4 +117,4 @@ public function getTestCases() { return $this->_testCases; } -} \ No newline at end of file +} diff --git a/tests/DoctrineTest/Reporter.php b/tests/DoctrineTest/Reporter.php index 5f9727009..9379f1754 100644 --- a/tests/DoctrineTest/Reporter.php +++ b/tests/DoctrineTest/Reporter.php @@ -2,9 +2,8 @@ class DoctrineTest_Reporter { - protected - $_formatter, - $_test; + protected $_formatter; + protected $_test; public function __construct() { @@ -15,19 +14,19 @@ public function format($message, $type) { if (PHP_SAPI == 'cli') { return $this->_formatter->format($message, $type); + } + if ('INFO' == $type) { + $color = 'green'; + } elseif ('ERROR' == $type) { + $color = 'red'; } else { - if ($type == 'INFO') { - $color = 'green'; - } else if ($type == 'ERROR') { - $color = 'red'; - } else { - $color = 'black'; - } - return '' . $message . ''; + $color = 'black'; } + + return ''.$message.''; } - - public function setTestCase($test) + + public function setTestCase($test) { $this->_test = $test; } @@ -37,20 +36,20 @@ public function paintMessages() $max = 80; $class = get_class($this->_test); $messages = $this->_test->getMessages(); - $failed = ($this->_test->getFailCount() || count($messages)) ? true:false; + $failed = ($this->_test->getFailCount() || count($messages)) ? true : false; - if ($class != 'GroupTest') { + if ('GroupTest' != $class) { $strRepeatLength = $max - strlen($class); - echo $class.str_repeat('.', $strRepeatLength).$this->format($failed ? 'failed':'passed', $failed ? 'ERROR':'INFO')."\n"; + echo $class.str_repeat('.', $strRepeatLength).$this->format($failed ? 'failed' : 'passed', $failed ? 'ERROR' : 'INFO')."\n"; } - if (! empty($messages)) { + if (!empty($messages)) { echo "\n"; echo "\n"; foreach ($messages as $message) { - echo $this->format($message, 'ERROR') . "\n\n"; + echo $this->format($message, 'ERROR')."\n\n"; } echo "\n"; } } -} \ No newline at end of file +} diff --git a/tests/DoctrineTest/Reporter/Cli.php b/tests/DoctrineTest/Reporter/Cli.php index 54e9c3eb1..85f00c004 100644 --- a/tests/DoctrineTest/Reporter/Cli.php +++ b/tests/DoctrineTest/Reporter/Cli.php @@ -4,17 +4,17 @@ class DoctrineTest_Reporter_Cli extends DoctrineTest_Reporter { public function paintHeader($name) { - echo $this->format($name, 'INFO') . "\n"; - echo str_repeat('=', strlen($name)) . "\n"; + echo $this->format($name, 'INFO')."\n"; + echo str_repeat('=', strlen($name))."\n"; } public function paintFooter() { echo "\n"; - echo $this->format("Tested: " . $this->_test->getTestCaseCount() . ' test cases.', 'INFO') . "\n"; - echo $this->format("Successes: " . $this->_test->getPassCount() . " passes.", 'INFO') . "\n"; - echo $this->format("Failures: " . $this->_test->getFailCount() . " fails.", $this->_test->getFailCount() ? 'ERROR':'INFO') . "\n"; - echo $this->format("Number of new Failures: " . $this->_test->getNumNewFails(), $this->_test->getNumNewFails() ? 'ERROR':'INFO') . ' ' . implode(", ", $this->_test->getNewFails()) . "\n"; - echo $this->format("Number of fixed Failures: " . $this->_test->getNumFixedFails(), $this->_test->getNumFixedFails() ? 'INFO':'HEADER') . ' ' . implode(", ", $this->_test->getFixedFails()) . "\n"; + echo $this->format('Tested: '.$this->_test->getTestCaseCount().' test cases.', 'INFO')."\n"; + echo $this->format('Successes: '.$this->_test->getPassCount().' passes.', 'INFO')."\n"; + echo $this->format('Failures: '.$this->_test->getFailCount().' fails.', $this->_test->getFailCount() ? 'ERROR' : 'INFO')."\n"; + echo $this->format('Number of new Failures: '.$this->_test->getNumNewFails(), $this->_test->getNumNewFails() ? 'ERROR' : 'INFO').' '.implode(', ', $this->_test->getNewFails())."\n"; + echo $this->format('Number of fixed Failures: '.$this->_test->getNumFixedFails(), $this->_test->getNumFixedFails() ? 'INFO' : 'HEADER').' '.implode(', ', $this->_test->getFixedFails())."\n"; } -} \ No newline at end of file +} diff --git a/tests/DoctrineTest/Reporter/Html.php b/tests/DoctrineTest/Reporter/Html.php index 0810ffd76..4a6e54e9a 100644 --- a/tests/DoctrineTest/Reporter/Html.php +++ b/tests/DoctrineTest/Reporter/Html.php @@ -3,7 +3,7 @@ class DoctrineTest_Reporter_Html extends DoctrineTest_Reporter { public function paintHeader($name) { -?> + ?> Doctrine Unit Tests @@ -49,7 +49,7 @@ public function paintHeader($name)
-

+

'; - - $this->paintSummary(); + echo '
'; + + $this->paintSummary(); } public function paintMessages() @@ -69,14 +69,14 @@ public function paintMessages() public function paintSummary() { - print '
'; + echo '
'; - echo $this->format("Tested: " . $this->_test->getTestCaseCount() . ' test cases.', 'INFO') . "
"; - echo $this->format("Successes: " . $this->_test->getPassCount() . " passes.", 'INFO') . "
"; - echo $this->format("Failures: " . $this->_test->getFailCount() . " fails.", $this->_test->getFailCount() ? 'ERROR':'INFO') . "
"; - echo $this->format("Number of new Failures: " . $this->_test->getNumNewFails(), $this->_test->getNumNewFails() ? 'ERROR':'INFO') . ' ' . implode(", ", $this->_test->getNewFails()) . "
"; - echo $this->format("Number of fixed Failures: " . $this->_test->getNumFixedFails(), $this->_test->getNumFixedFails() ? 'INFO':'HEADER') . ' ' . implode(", ", $this->_test->getFixedFails()) . "
"; + echo $this->format('Tested: '.$this->_test->getTestCaseCount().' test cases.', 'INFO').'
'; + echo $this->format('Successes: '.$this->_test->getPassCount().' passes.', 'INFO').'
'; + echo $this->format('Failures: '.$this->_test->getFailCount().' fails.', $this->_test->getFailCount() ? 'ERROR' : 'INFO').'
'; + echo $this->format('Number of new Failures: '.$this->_test->getNumNewFails(), $this->_test->getNumNewFails() ? 'ERROR' : 'INFO').' '.implode(', ', $this->_test->getNewFails()).'
'; + echo $this->format('Number of fixed Failures: '.$this->_test->getNumFixedFails(), $this->_test->getNumFixedFails() ? 'INFO' : 'HEADER').' '.implode(', ', $this->_test->getFixedFails()).'
'; - print '
'; + echo '
'; } -} \ No newline at end of file +} diff --git a/tests/DoctrineTest/UnitTestCase.php b/tests/DoctrineTest/UnitTestCase.php index a2b4193fd..3a3fa5a06 100644 --- a/tests/DoctrineTest/UnitTestCase.php +++ b/tests/DoctrineTest/UnitTestCase.php @@ -1,10 +1,11 @@ array(), 'fails' => array()); @@ -43,8 +44,8 @@ public function assertEqual($value, $value2) if ($value == $value2) { $this->pass(); } else { - $seperator = "
"; - if (PHP_SAPI === "cli") { + $seperator = '
'; + if (PHP_SAPI === 'cli') { $seperator = "\n"; } @@ -56,7 +57,7 @@ public function assertEqual($value, $value2) $value2 = var_export($value2, true); } - $message = "$seperator Value1: $value $seperator != $seperator Value2: $value2 $seperator"; + $message = "{$seperator} Value1: {$value} {$seperator} != {$seperator} Value2: {$value2} {$seperator}"; $this->_fail($message); } } @@ -90,7 +91,7 @@ public function assertTrue($expr) public function assertFalse($expr) { - if ( ! $expr) { + if (!$expr) { $this->pass(); } else { $this->_fail(); @@ -115,41 +116,40 @@ public function assertNotNull($expr) } } - public function pass() + public function pass() { $class = get_class($this); - if ( ! isset(self::$_passesAndFails['fails'][$class])) { + if (!isset(self::$_passesAndFails['fails'][$class])) { self::$_passesAndFails['passes'][$class] = $class; } - $this->_passed++; + ++$this->_passed; } - public function fail($message = "") + public function fail($message = '') { - $this->_fail($message); + $this->_fail($message); } - public function _fail($message = "") + public function _fail($message = '') { $trace = debug_backtrace(); array_shift($trace); - foreach ($trace as $stack) { - if (substr($stack['function'], 0, 4) === 'test') { + if ('test' === substr($stack['function'], 0, 4)) { $class = new ReflectionClass($stack['class']); - if ( ! isset($line)) { + if (!isset($line)) { $line = $stack['line']; } - $errorMessage = $class->getName() . ' : method ' . $stack['function'] . ' failed on line ' . $line; - $this->_messages[] = $errorMessage . " " . $message; + $errorMessage = $class->getName().' : method '.$stack['function'].' failed on line '.$line; + $this->_messages[] = $errorMessage.' '.$message; break; } $line = $stack['line']; } - $this->_failed++; + ++$this->_failed; $class = get_class($this); if (isset(self::$_passesAndFails['passes'][$class])) { unset(self::$_passesAndFails['passes'][$class]); @@ -166,7 +166,7 @@ public function run(DoctrineTest_Reporter $reporter = null, $filter = null) } } - public function getMessages() + public function getMessages() { return $this->_messages; } @@ -183,13 +183,12 @@ public function getPassCount() public function getPassesAndFailsCachePath() { - $dir = dirname(__FILE__) . '/doctrine_tests'; - if ( ! is_dir($dir)) { + $dir = dirname(__FILE__).'/doctrine_tests'; + if (!is_dir($dir)) { mkdir($dir, 0777, true); } - $path = $dir . '/' . md5(serialize(array_keys($this->_testCases))); - return $path; + return $dir.'/'.md5(serialize(array_keys($this->_testCases))); } public function cachePassesAndFails() @@ -228,6 +227,7 @@ public function getNewFails() $newFails[$fail] = $fail; } } + return $newFails; } @@ -241,6 +241,7 @@ public function getFixedFails() $fixed[$fail] = $fail; } } + return $fixed; } @@ -267,7 +268,7 @@ private function doRunTestAndTearDown($method) $this->tryFinally( function () use ($test, $method) { - $test->$method(); + $test->{$method}(); }, function () use ($test) { $test->tearDown(); diff --git a/tests/DriverTestCase.php b/tests/DriverTestCase.php index c247eed3c..136f7a55b 100644 --- a/tests/DriverTestCase.php +++ b/tests/DriverTestCase.php @@ -1,29 +1,31 @@ name = $name; } - public function getName() + public function getName() { return $this->name; } - public function pop() + public function pop() { return array_pop($this->queries); } - public function forceException($name, $message = '', $code = 0) + public function forceException($name, $message = '', $code = 0) { $this->exception = array($name, $message, $code); } @@ -42,9 +44,9 @@ public function query($query) { $this->queries[] = $query; - $e = $this->exception; + $e = $this->exception; - if ( ! empty($e)) { + if (!empty($e)) { $name = $e[0]; $this->exception = array(); @@ -62,16 +64,16 @@ public function getAll() public function quote($input) { - return "'" . addslashes($input) . "'"; + return "'".addslashes($input)."'"; } public function exec($statement) { $this->queries[] = $statement; - $e = $this->exception; + $e = $this->exception; - if ( ! empty($e)) { + if (!empty($e)) { $name = $e[0]; $this->exception = array(); @@ -96,13 +98,13 @@ public function lastInsertId() $this->queries[] = 'LAST_INSERT_ID()'; if ($this->lastInsertIdFail) { return null; - } else { - return 1; } + + return 1; } public function beginTransaction() - { + { $this->queries[] = 'BEGIN TRANSACTION'; } @@ -111,43 +113,40 @@ public function commit() $this->queries[] = 'COMMIT'; } - public function rollBack() - { + public function rollBack() + { $this->queries[] = 'ROLLBACK'; } public function errorCode() { - } public function errorInfo() { - } public function getAttribute($attribute) { - if ($attribute == PDO::ATTR_DRIVER_NAME) { + if (PDO::ATTR_DRIVER_NAME == $attribute) { return strtolower($this->name); } } public function setAttribute($attribute, $value) { - } } class AdapterStatementMock { private $mock; - + private $query; public function __construct(AdapterMock $mock, $query) { - $this->mock = $mock; + $this->mock = $mock; $this->query = $query; } @@ -164,6 +163,7 @@ public function fetchAll($fetchMode) public function execute() { $this->mock->addQuery($this->query); + return true; } @@ -173,6 +173,11 @@ public function fetchColumn($colnum = 0) } } +/** + * @internal + * + * @coversNothing + */ class Doctrine_Driver_UnitTestCase extends UnitTestCase { protected $driverName = false; @@ -186,15 +191,14 @@ class Doctrine_Driver_UnitTestCase extends UnitTestCase public function __construct($driverName, $generic = false) { - $this->driverName = $driverName; - $this->generic = $generic; + $this->generic = $generic; } public function assertDeclarationType($type, $type2) { $dec = $this->getDeclaration($type); - if ( ! is_array($type2)) { + if (!is_array($type2)) { $type2 = array($type2); } $this->assertEqual($dec[0], $type2); @@ -217,35 +221,38 @@ public function init() $this->manager->setDefaultAttributes(); $this->conn = $this->manager->openConnection($this->adapter); - if ( ! $this->generic) { - $this->export = $this->conn->export; + if (!$this->generic) { + $this->export = $this->conn->export; $name = $this->adapter->getName(); - if ($this->adapter->getName() == 'oci') + if ('oci' == $this->adapter->getName()) { $name = 'Oracle'; - - $tx = 'Doctrine_Transaction_' . ucwords($name); - $dataDict = 'Doctrine_DataDict_' . ucwords($name); - - $exc = 'Doctrine_Connection_' . ucwords($name) . '_Exception'; - + } + + $tx = 'Doctrine_Transaction_'.ucwords($name); + $dataDict = 'Doctrine_DataDict_'.ucwords($name); + + $exc = 'Doctrine_Connection_'.ucwords($name).'_Exception'; + $this->exc = new $exc(); - if (class_exists($tx)) + if (class_exists($tx)) { $this->transaction = new $tx($this->conn); + } if (class_exists($dataDict)) { $this->dataDict = new $dataDict($this->conn); } - //$this->dataDict = $this->conn->dataDict; + // $this->dataDict = $this->conn->dataDict; } else { - $this->export = new Doctrine_Export($this->conn); + $this->export = new Doctrine_Export($this->conn); $this->transaction = new Doctrine_Transaction($this->conn); } } - public function setUp() { + public function setUp() + { static $init = false; - if ( ! $init) { + if (!$init) { $this->init(); $init = true; } diff --git a/tests/EventListener/ChainTestCase.php b/tests/EventListener/ChainTestCase.php index af27013dd..dea8aa9e8 100644 --- a/tests/EventListener/ChainTestCase.php +++ b/tests/EventListener/ChainTestCase.php @@ -20,31 +20,37 @@ */ /** - * Doctrine_EventListener_Chain_TestCase + * Doctrine_EventListener_Chain_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_EventListener_Chain_TestCase extends Doctrine_UnitTestCase +class Doctrine_EventListener_Chain_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } - public function prepareTables() + public function prepareData() + { + } + + public function prepareTables() { $this->tables = array('EventListenerChainTest'); parent::prepareTables(); } - public function testAccessorInvokerChain() - { - $e = new EventListenerChainTest; - $e->name = "something"; + public function testAccessorInvokerChain() + { + $e = new EventListenerChainTest(); + $e->name = 'something'; } - } - diff --git a/tests/EventListenerTestCase.php b/tests/EventListenerTestCase.php index f84218340..d787af0a6 100644 --- a/tests/EventListenerTestCase.php +++ b/tests/EventListenerTestCase.php @@ -20,181 +20,199 @@ */ /** - * Doctrine_EventListener_TestCase + * Doctrine_EventListener_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_EventListener_TestCase extends Doctrine_UnitTestCase { +class Doctrine_EventListener_TestCase extends Doctrine_UnitTestCase +{ private $logger; + public function prepareData() + { + } - public function prepareData() - { } - public function prepareTables() { + public function prepareTables() + { $this->tables = array('EventListenerTest'); parent::prepareTables(); } - public function testSetListener() { + public function testSetListener() + { $this->logger = new Doctrine_EventListener_TestLogger(); - - $e = new EventListenerTest; - - $e->getTable()->setListener($this->logger); - - $e->name = 'listener'; - $e->save(); - - $this->assertEqual($e->getTable()->getListener(), $this->logger); - } - - /** - public function testOnLoad() { - $this->logger->clear(); - $this->assertEqual($this->connection->getTable('EventListenerTest')->getListener(), $this->logger); - $this->connection->clear(); - - $e = $this->connection->getTable('EventListenerTest')->find(1); - - - $this->assertEqual($e->getTable()->getListener(), $this->logger); - - $this->assertEqual($this->logger->pop(), 'onLoad'); - $this->assertEqual($this->logger->pop(), 'onPreLoad'); - } - - public function testOnCreate() { - $e = new EventListenerTest; - - - $e->setListener($this->logger); - $this->logger->clear(); - $e = new EventListenerTest; - - $this->assertEqual($this->logger->pop(), 'onCreate'); - $this->assertEqual($this->logger->pop(), 'onPreCreate'); - $this->assertEqual($this->logger->count(), 0); - } - public function testOnSleepAndOnWakeUp() { - $e = new EventListenerTest; - - $this->logger->clear(); - - $s = serialize($e); - - $this->assertEqual($this->logger->pop(), 'onSleep'); - $this->assertEqual($this->logger->count(), 0); - - $e = unserialize($s); - $this->assertEqual($this->logger->pop(), 'onWakeUp'); - $this->assertEqual($this->logger->count(), 0); - } - public function testTransaction() { $e = new EventListenerTest(); - $e->name = "test 1"; - - $this->logger->clear(); - - $e->save(); - $this->assertEqual($this->logger->pop(), 'onSave'); - $this->assertEqual($this->logger->pop(), 'onInsert'); - $this->assertEqual($this->logger->pop(), 'onPreInsert'); - $this->assertEqual($this->logger->pop(), 'onPreSave'); - - $e->name = "test 2"; + $e->getTable()->setListener($this->logger); + $e->name = 'listener'; $e->save(); - $this->assertEqual($this->logger->pop(), 'onSave'); - $this->assertEqual($this->logger->pop(), 'onUpdate'); - $this->assertEqual($this->logger->pop(), 'onPreUpdate'); - $this->assertEqual($this->logger->pop(), 'onPreSave'); - - $this->logger->clear(); - - $e->delete(); - - $this->assertEqual($this->logger->pop(), 'onDelete'); - $this->assertEqual($this->logger->pop(), 'onPreDelete'); + $this->assertEqual($e->getTable()->getListener(), $this->logger); } - public function testTransactionWithConnectionListener() { - $e = new EventListenerTest(); - $e->getTable()->getConnection()->setListener($this->logger); - - $e->name = "test 2"; - - $this->logger->clear(); - - $e->save(); - - $this->assertEqual($this->logger->pop(), 'onTransactionCommit'); - $this->assertEqual($this->logger->pop(), 'onPreTransactionCommit'); - $this->assertEqual($this->logger->pop(), 'onSave'); - $this->assertEqual($this->logger->pop(), 'onInsert'); - $this->assertEqual($this->logger->pop(), 'onPreInsert'); - $this->assertEqual($this->logger->pop(), 'onPreSave'); - $this->assertEqual($this->logger->pop(), 'onTransactionBegin'); - $this->assertEqual($this->logger->pop(), 'onPreTransactionBegin'); - - $e->name = "test 1"; - - $e->save(); - - $this->assertEqual($this->logger->pop(), 'onTransactionCommit'); - $this->assertEqual($this->logger->pop(), 'onPreTransactionCommit'); - $this->assertEqual($this->logger->pop(), 'onSave'); - $this->assertEqual($this->logger->pop(), 'onUpdate'); - $this->assertEqual($this->logger->pop(), 'onPreUpdate'); - $this->assertEqual($this->logger->pop(), 'onPreSave'); - - $this->assertEqual($this->logger->pop(), 'onTransactionBegin'); - $this->assertEqual($this->logger->pop(), 'onPreTransactionBegin'); - - $this->logger->clear(); - - $e->delete(); - - $this->assertEqual($this->logger->pop(), 'onTransactionCommit'); - $this->assertEqual($this->logger->pop(), 'onPreTransactionCommit'); - $this->assertEqual($this->logger->pop(), 'onDelete'); - - $this->assertEqual($this->logger->pop(), 'onPreDelete'); - $this->assertEqual($this->logger->pop(), 'onTransactionBegin'); - $this->assertEqual($this->logger->pop(), 'onPreTransactionBegin'); - - $this->connection->setListener(new Doctrine_EventListener()); - } - */ + /* + * public function testOnLoad() { + * $this->logger->clear(); + * $this->assertEqual($this->connection->getTable('EventListenerTest')->getListener(), $this->logger); + * $this->connection->clear(); + * + * $e = $this->connection->getTable('EventListenerTest')->find(1); + * + * + * $this->assertEqual($e->getTable()->getListener(), $this->logger); + * + * $this->assertEqual($this->logger->pop(), 'onLoad'); + * $this->assertEqual($this->logger->pop(), 'onPreLoad'); + * } + * + * public function testOnCreate() { + * $e = new EventListenerTest; + * + * + * $e->setListener($this->logger); + * $this->logger->clear(); + * $e = new EventListenerTest; + * + * $this->assertEqual($this->logger->pop(), 'onCreate'); + * $this->assertEqual($this->logger->pop(), 'onPreCreate'); + * $this->assertEqual($this->logger->count(), 0); + * } + * public function testOnSleepAndOnWakeUp() { + * $e = new EventListenerTest; + * + * $this->logger->clear(); + * + * $s = serialize($e); + * + * $this->assertEqual($this->logger->pop(), 'onSleep'); + * $this->assertEqual($this->logger->count(), 0); + * + * $e = unserialize($s); + * + * $this->assertEqual($this->logger->pop(), 'onWakeUp'); + * $this->assertEqual($this->logger->count(), 0); + * } + * public function testTransaction() { + * $e = new EventListenerTest(); + * $e->name = "test 1"; + * + * $this->logger->clear(); + * + * $e->save(); + * + * $this->assertEqual($this->logger->pop(), 'onSave'); + * $this->assertEqual($this->logger->pop(), 'onInsert'); + * $this->assertEqual($this->logger->pop(), 'onPreInsert'); + * $this->assertEqual($this->logger->pop(), 'onPreSave'); + * + * $e->name = "test 2"; + * + * $e->save(); + * + * $this->assertEqual($this->logger->pop(), 'onSave'); + * $this->assertEqual($this->logger->pop(), 'onUpdate'); + * $this->assertEqual($this->logger->pop(), 'onPreUpdate'); + * $this->assertEqual($this->logger->pop(), 'onPreSave'); + * + * $this->logger->clear(); + * + * $e->delete(); + * + * $this->assertEqual($this->logger->pop(), 'onDelete'); + * $this->assertEqual($this->logger->pop(), 'onPreDelete'); + * } + * public function testTransactionWithConnectionListener() { + * $e = new EventListenerTest(); + * $e->getTable()->getConnection()->setListener($this->logger); + * + * $e->name = "test 2"; + * + * $this->logger->clear(); + * + * $e->save(); + * + * $this->assertEqual($this->logger->pop(), 'onTransactionCommit'); + * $this->assertEqual($this->logger->pop(), 'onPreTransactionCommit'); + * $this->assertEqual($this->logger->pop(), 'onSave'); + * $this->assertEqual($this->logger->pop(), 'onInsert'); + * $this->assertEqual($this->logger->pop(), 'onPreInsert'); + * $this->assertEqual($this->logger->pop(), 'onPreSave'); + * + * $this->assertEqual($this->logger->pop(), 'onTransactionBegin'); + * $this->assertEqual($this->logger->pop(), 'onPreTransactionBegin'); + * + * $e->name = "test 1"; + * + * $e->save(); + * + * $this->assertEqual($this->logger->pop(), 'onTransactionCommit'); + * $this->assertEqual($this->logger->pop(), 'onPreTransactionCommit'); + * $this->assertEqual($this->logger->pop(), 'onSave'); + * $this->assertEqual($this->logger->pop(), 'onUpdate'); + * $this->assertEqual($this->logger->pop(), 'onPreUpdate'); + * $this->assertEqual($this->logger->pop(), 'onPreSave'); + * + * $this->assertEqual($this->logger->pop(), 'onTransactionBegin'); + * $this->assertEqual($this->logger->pop(), 'onPreTransactionBegin'); + * + * $this->logger->clear(); + * + * $e->delete(); + * + * $this->assertEqual($this->logger->pop(), 'onTransactionCommit'); + * $this->assertEqual($this->logger->pop(), 'onPreTransactionCommit'); + * $this->assertEqual($this->logger->pop(), 'onDelete'); + * + * $this->assertEqual($this->logger->pop(), 'onPreDelete'); + * $this->assertEqual($this->logger->pop(), 'onTransactionBegin'); + * $this->assertEqual($this->logger->pop(), 'onPreTransactionBegin'); + * + * $this->connection->setListener(new Doctrine_EventListener()); + * } + */ } -class Doctrine_EventListener_TestLogger implements Doctrine_Overloadable, Countable { +class Doctrine_EventListener_TestLogger implements Doctrine_Overloadable, Countable +{ private $messages = array(); - public function __call($m, $a) { - + public function __call($m, $a) + { $this->messages[] = $m; } - public function pop() { + + public function pop() + { return array_pop($this->messages); } - public function clear() { + + public function clear() + { $this->messages = array(); } - public function getAll() { + + public function getAll() + { return $this->messages; } - #[\ReturnTypeWillChange] - public function count() { + + #[ReturnTypeWillChange] + public function count() + { return count($this->messages); } } - diff --git a/tests/Export/CheckConstraintTestCase.php b/tests/Export/CheckConstraintTestCase.php index 49b1b8955..c1294fc94 100644 --- a/tests/Export/CheckConstraintTestCase.php +++ b/tests/Export/CheckConstraintTestCase.php @@ -20,31 +20,40 @@ */ /** - * Doctrine_Export_CheckConstraint_TestCase + * Doctrine_Export_CheckConstraint_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Export_CheckConstraint_TestCase extends Doctrine_UnitTestCase +class Doctrine_Export_CheckConstraint_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() - { } - + { + } + public function testCheckConstraints() { $e = $this->conn->export; $sql = $e->exportClassesSql(array('CheckConstraintTest')); - + $this->assertEqual($sql[0], 'CREATE TABLE check_constraint_test (id INTEGER PRIMARY KEY AUTOINCREMENT, price DECIMAL(2,2), discounted_price DECIMAL(2,2), CHECK (price >= 100), CHECK (price <= 5000), CHECK (price > discounted_price))'); - + try { $dbh = new PDO('sqlite::memory:'); $dbh->exec($sql[0]); diff --git a/tests/Export/MssqlTestCase.php b/tests/Export/MssqlTestCase.php index d6ff4cb0d..3bedd8574 100644 --- a/tests/Export/MssqlTestCase.php +++ b/tests/Export/MssqlTestCase.php @@ -20,31 +20,41 @@ */ /** - * Doctrine_Export_Mssql_TestCase + * Doctrine_Export_Mssql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Export_Mssql_TestCase extends Doctrine_UnitTestCase { public function prepareTables() - { } + { + } + public function prepareData() - { } + { + } public function testAlterTableName() { $this->export->alterTable('user', array( - 'name' => 'userlist' + 'name' => 'userlist', )); - + $this->assertEqual($this->adapter->pop(), "EXECUTE sp_RENAME '[user]', 'userlist';"); -} + } + public function testAlterTableRename() { $this->export->alterTable('user', array( @@ -56,23 +66,25 @@ public function testAlterTableRename() 'length' => 1, 'default' => 'M', ), - ) - ) + ), + ), )); $this->assertEqual($this->adapter->pop(), "EXECUTE sp_RENAME '[user].[sex]', 'gender', 'COLUMN';"); } + public function testAlterTableRemove() { $this->export->alterTable('user', array( 'remove' => array( 'file_limit' => array(), 'time_limit' => array(), - ) + ), )); - $this->assertEqual($this->adapter->pop(), "ALTER TABLE user DROP COLUMN file_limit, time_limit;"); + $this->assertEqual($this->adapter->pop(), 'ALTER TABLE user DROP COLUMN file_limit, time_limit;'); } + public function testAlterTableChange() { $this->export->alterTable('user', array( @@ -84,21 +96,23 @@ public function testAlterTableChange() 'length' => '20', ), ), - ) + ), )); - $this->assertEqual($this->adapter->pop(), "ALTER TABLE user ALTER COLUMN name VARCHAR(20) NULL;"); + $this->assertEqual($this->adapter->pop(), 'ALTER TABLE user ALTER COLUMN name VARCHAR(20) NULL;'); } + public function testAlterTableThrowsExceptionWithoutValidTableName() { try { $this->export->alterTable(0, array(), array()); $this->fail(); - } catch(Doctrine_Export_Exception $e) { + } catch (Doctrine_Export_Exception $e) { $this->pass(); } } + public function testAlterTableMultipleColumnAlterationsRequireMultipleAlterTableQueries() { $this->export->alterTable('user', array( @@ -117,56 +131,58 @@ public function testAlterTableMultipleColumnAlterationsRequireMultipleAlterTable 'length' => '20', ), ), - ) + ), )); $this->assertEqual($this->adapter->pop(), 'ALTER TABLE user ALTER COLUMN name VARCHAR(20) NULL; ALTER TABLE user ALTER COLUMN name2 VARCHAR(20) NULL;'); } + public function testCreateTableExecutesSql() { $name = 'mytable'; - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1)); - + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1)); $this->export->createTable($name, $fields); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id BIGINT NULL)'); } + public function testCreateTableSupportsMultiplePks() { $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10, 'notnull' => true), - 'type' => array('type' => 'integer', 'length' => 3, 'notnull' => true)); + $fields = array('name' => array('type' => 'char', 'length' => 10, 'notnull' => true), + 'type' => array('type' => 'integer', 'length' => 3, 'notnull' => true)); $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (name CHAR(10) NOT NULL, type INT NOT NULL, PRIMARY KEY([name], [type]))'); } + public function testCreateTableSupportsAutoincPks() { $name = 'mytable'; - $fields = array('id' => array('type' => 'integer', 'notnull' => true, 'unsigned' => 1, 'autoincrement' => true)); + $fields = array('id' => array('type' => 'integer', 'notnull' => true, 'unsigned' => 1, 'autoincrement' => true)); $options = array('primary' => array('id')); $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id BIGINT NOT NULL identity, PRIMARY KEY([id]))'); } + public function testCreateTableSupportsForeignKeys() { $name = 'mytable'; $fields = array('id' => array('type' => 'boolean', 'primary' => true, 'notnull' => true), - 'foreignKey' => array('type' => 'integer') - ); + 'foreignKey' => array('type' => 'integer'), + ); $options = array('foreignKeys' => array(array('local' => 'foreignKey', - 'foreign' => 'id', - 'foreignTable' => 'sometable')) - ); - + 'foreign' => 'id', + 'foreignTable' => 'sometable')), + ); $sql = $this->export->createTableSql($name, $fields, $options); @@ -174,53 +190,58 @@ public function testCreateTableSupportsForeignKeys() $this->assertEqual($sql[0], 'CREATE TABLE mytable (id BIT NOT NULL, foreignKey INT NULL, PRIMARY KEY([id]))'); $this->assertEqual($sql[1], 'ALTER TABLE [mytable] ADD FOREIGN KEY ([foreignKey]) REFERENCES [sometable]([id])'); } + public function testCreateDatabaseExecutesSql() { $this->export->createDatabase('db'); - + $this->assertEqual($this->adapter->pop(), 'CREATE DATABASE db'); } + public function testDropDatabaseExecutesSql() { $this->export->dropDatabase('db'); $this->assertEqual($this->adapter->pop(), 'DROP DATABASE db'); } + public function testDropIndexExecutesSql() { $this->export->dropIndex('sometable', 'relevancy'); $this->assertEqual($this->adapter->pop(), 'DROP INDEX [relevancy_idx] ON [sometable]'); } + public function testCreateTableSupportsIndexesUsingSingleFieldString() { - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true, 'notnull' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true, 'notnull' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array( - 'fields' => array('name'))) - ); + 'indexes' => array('myindex' => array( + 'fields' => array('name'))), + ); $this->export->createTable('sometable', $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE INDEX [myindex] ON [sometable] ([name])'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id BIGINT NOT NULL identity, name VARCHAR(4) NULL, PRIMARY KEY([id]))'); } + public function testCreateTableSupportsCompoundForeignKeys() { $name = 'mytable'; $fields = array('id' => array('type' => 'boolean', 'primary' => true, 'notnull' => true), - 'lang' => array('type' => 'integer', 'primary' => true, 'notnull' => true) - ); - $options = array('foreignKeys' => array(array('local' => array ('id', 'lang' ), - 'foreign' => array ('id', 'lang'), - 'foreignTable' => 'sometable')) - ); + 'lang' => array('type' => 'integer', 'primary' => true, 'notnull' => true), + ); + $options = array('foreignKeys' => array(array('local' => array('id', 'lang'), + 'foreign' => array('id', 'lang'), + 'foreignTable' => 'sometable')), + ); $sql = $this->export->createTableSql($name, $fields, $options); - + $this->assertEqual(count($sql), 2); $this->assertEqual($sql[0], 'CREATE TABLE mytable (id BIT NOT NULL, lang INT NOT NULL, PRIMARY KEY([id], [lang]))'); $this->assertEqual($sql[1], 'ALTER TABLE [mytable] ADD FOREIGN KEY ([id], [lang]) REFERENCES [sometable]([id], [lang])'); diff --git a/tests/Export/MysqlTestCase.php b/tests/Export/MysqlTestCase.php index 399add35b..2f9b27207 100644 --- a/tests/Export/MysqlTestCase.php +++ b/tests/Export/MysqlTestCase.php @@ -20,22 +20,31 @@ */ /** - * Doctrine_Export_Mysql_TestCase + * Doctrine_Export_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Export_Mysql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Export_Mysql_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { } - public function prepareData() - { } + public function prepareTables() + { + } + + public function prepareData() + { + } public function testAlterTableThrowsExceptionWithoutValidTableName() { @@ -43,115 +52,125 @@ public function testAlterTableThrowsExceptionWithoutValidTableName() $this->export->alterTable(0, array(), array()); $this->fail(); - } catch(Doctrine_Export_Exception $e) { + } catch (Doctrine_Export_Exception $e) { $this->pass(); } } - public function testCreateTableExecutesSql() + + public function testCreateTableExecutesSql() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1)); + + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1)); $options = array('type' => 'MYISAM'); - + $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id INT UNSIGNED) ENGINE = MYISAM'); } - public function testCreateTableSupportsDefaultTableType() + + public function testCreateTableSupportsDefaultTableType() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1)); + + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1)); $this->export->createTable($name, $fields); // INNODB is the default type $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id INT UNSIGNED) ENGINE = INNODB'); } - public function testCreateTableSupportsMultiplePks() + + public function testCreateTableSupportsMultiplePks() { $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10), - 'type' => array('type' => 'integer', 'length' => 3)); - + $fields = array('name' => array('type' => 'char', 'length' => 10), + 'type' => array('type' => 'integer', 'length' => 3)); + $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); - + $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (name CHAR(10), type MEDIUMINT, PRIMARY KEY(name, type)) ENGINE = INNODB'); } - public function testCreateTableSupportsAutoincPks() + + public function testCreateTableSupportsAutoincPks() { $name = 'mytable'; - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true)); - $options = array('primary' => array('id'), - 'type' => 'INNODB'); - + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true)); + $options = array('primary' => array('id'), + 'type' => 'INNODB'); + $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id INT UNSIGNED AUTO_INCREMENT, PRIMARY KEY(id)) ENGINE = INNODB'); } - public function testCreateTableSupportsCharType() + + public function testCreateTableSupportsCharType() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'char', 'length' => 3)); + + $fields = array('id' => array('type' => 'char', 'length' => 3)); $options = array('type' => 'MYISAM'); - + $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id CHAR(3)) ENGINE = MYISAM'); } - public function testCreateTableSupportsCharType2() + + public function testCreateTableSupportsCharType2() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'char')); + + $fields = array('id' => array('type' => 'char')); $options = array('type' => 'MYISAM'); - + $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id CHAR(255)) ENGINE = MYISAM'); } - public function testCreateTableSupportsVarcharType() + + public function testCreateTableSupportsVarcharType() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'varchar', 'length' => '100')); + + $fields = array('id' => array('type' => 'varchar', 'length' => '100')); $options = array('type' => 'MYISAM'); $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id VARCHAR(100)) ENGINE = MYISAM'); } - public function testCreateTableSupportsIntegerType() + + public function testCreateTableSupportsIntegerType() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'integer', 'length' => '10')); + + $fields = array('id' => array('type' => 'integer', 'length' => '10')); $options = array('type' => 'MYISAM'); $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id BIGINT) ENGINE = MYISAM'); } - public function testCreateTableSupportsBlobType() + + public function testCreateTableSupportsBlobType() { $name = 'mytable'; - - $fields = array('content' => array('type' => 'blob')); + + $fields = array('content' => array('type' => 'blob')); $options = array('type' => 'MYISAM'); $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (content LONGBLOB) ENGINE = MYISAM'); } - public function testCreateTableSupportsBlobType2() + + public function testCreateTableSupportsBlobType2() { $name = 'mytable'; - - $fields = array('content' => array('type' => 'blob', 'length' => 2000)); + + $fields = array('content' => array('type' => 'blob', 'length' => 2000)); $options = array('type' => 'MYISAM'); $this->export->createTable($name, $fields, $options); @@ -162,33 +181,34 @@ public function testCreateTableSupportsBlobType2() public function testCreateTableSupportsBooleanType() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'boolean')); + + $fields = array('id' => array('type' => 'boolean')); $options = array('type' => 'MYISAM'); $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id TINYINT(1)) ENGINE = MYISAM'); } + public function testCreateTableSupportsForeignKeys() { $name = 'mytable'; - + $fields = array('id' => array('type' => 'boolean', 'primary' => true), - 'foreignKey' => array('type' => 'integer') - ); + 'foreignKey' => array('type' => 'integer'), + ); $options = array('type' => 'INNODB', - 'foreignKeys' => array(array('local' => 'foreignKey', - 'foreign' => 'id', - 'foreignTable' => 'sometable')) - ); - + 'foreignKeys' => array(array('local' => 'foreignKey', + 'foreign' => 'id', + 'foreignTable' => 'sometable')), + ); $sql = $this->export->createTableSql($name, $fields, $options); $this->assertEqual($sql[0], 'CREATE TABLE mytable (id TINYINT(1), foreignKey INT, INDEX foreignKey_idx (foreignKey)) ENGINE = INNODB'); $this->assertEqual($sql[1], 'ALTER TABLE mytable ADD FOREIGN KEY (foreignKey) REFERENCES sometable(id)'); } + public function testForeignKeyIdentifierQuoting() { $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); @@ -196,14 +216,13 @@ public function testForeignKeyIdentifierQuoting() $name = 'mytable'; $fields = array('id' => array('type' => 'boolean', 'primary' => true), - 'foreignKey' => array('type' => 'integer') - ); + 'foreignKey' => array('type' => 'integer'), + ); $options = array('type' => 'INNODB', - 'foreignKeys' => array(array('local' => 'foreignKey', - 'foreign' => 'id', - 'foreignTable' => 'sometable')) - ); - + 'foreignKeys' => array(array('local' => 'foreignKey', + 'foreign' => 'id', + 'foreignTable' => 'sometable')), + ); $sql = $this->export->createTableSql($name, $fields, $options); @@ -212,54 +231,57 @@ public function testForeignKeyIdentifierQuoting() $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); } + public function testIndexIdentifierQuoting() { $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array('fields' => array('id', 'name'))) - ); + 'indexes' => array('myindex' => array('fields' => array('id', 'name'))), + ); $this->export->createTable('sometable', $fields, $options); - //this was the old line, but it looks like the table is created first - //and then the index so i replaced it with the ones below - //$this->assertEqual($var, 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4), INDEX myindex (id, name))'); + // this was the old line, but it looks like the table is created first + // and then the index so i replaced it with the ones below + // $this->assertEqual($var, 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4), INDEX myindex (id, name))'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE `sometable` (`id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(4), INDEX `myindex_idx` (`id`, `name`), PRIMARY KEY(`id`)) ENGINE = INNODB'); $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); } + public function testCreateTableDoesNotAutoAddIndexesWhenIndexForFkFieldAlreadyExists() { $name = 'mytable'; - + $fields = array('id' => array('type' => 'boolean', 'primary' => true), - 'foreignKey' => array('type' => 'integer') - ); + 'foreignKey' => array('type' => 'integer'), + ); $options = array('type' => 'INNODB', - 'foreignKeys' => array(array('local' => 'foreignKey', - 'foreign' => 'id', - 'foreignTable' => 'sometable')), - 'indexes' => array('myindex' => array('fields' => array('foreignKey'))), - ); - + 'foreignKeys' => array(array('local' => 'foreignKey', + 'foreign' => 'id', + 'foreignTable' => 'sometable')), + 'indexes' => array('myindex' => array('fields' => array('foreignKey'))), + ); $sql = $this->export->createTableSql($name, $fields, $options); $this->assertEqual($sql[0], 'CREATE TABLE mytable (id TINYINT(1), foreignKey INT, INDEX myindex_idx (foreignKey)) ENGINE = INNODB'); $this->assertEqual($sql[1], 'ALTER TABLE mytable ADD FOREIGN KEY (foreignKey) REFERENCES sometable(id)'); } + public function testCreateDatabaseExecutesSql() { $this->export->createDatabase('db'); $this->assertEqual($this->adapter->pop(), 'CREATE DATABASE db'); } - public function testDropDatabaseExecutesSql() + + public function testDropDatabaseExecutesSql() { $this->export->dropDatabase('db'); @@ -268,102 +290,109 @@ public function testDropDatabaseExecutesSql() $this->assertEqual($this->adapter->pop(), 'SET FOREIGN_KEY_CHECKS = 0'); } - public function testDropIndexExecutesSql() + public function testDropIndexExecutesSql() { $this->export->dropIndex('sometable', 'relevancy'); $this->assertEqual($this->adapter->pop(), 'DROP INDEX relevancy_idx ON sometable'); } + public function testUnknownIndexSortingAttributeThrowsException() { $fields = array('id' => array('sorting' => 'ASC'), - 'name' => array('sorting' => 'unknown')); + 'name' => array('sorting' => 'unknown')); try { $this->export->getIndexFieldDeclarationList($fields); $this->fail(); - } catch(Doctrine_Export_Exception $e) { + } catch (Doctrine_Export_Exception $e) { $this->pass(); } } + public function testIndexDeclarationsSupportSortingAndLengthAttributes() { $fields = array('id' => array('sorting' => 'ASC', 'length' => 10), - 'name' => array('sorting' => 'DESC', 'length' => 1)); + 'name' => array('sorting' => 'DESC', 'length' => 1)); $this->assertEqual($this->export->getIndexFieldDeclarationList($fields), 'id(10) ASC, name(1) DESC'); } + public function testCreateTableSupportsIndexesUsingSingleFieldString() { - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array( - 'fields' => 'name')) - ); + 'indexes' => array('myindex' => array( + 'fields' => 'name')), + ); - $this->export->createTable('sometable', $fields, $options); + $this->export->createTable('sometable', $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id INT UNSIGNED AUTO_INCREMENT, name VARCHAR(4), INDEX myindex_idx (name), PRIMARY KEY(id)) ENGINE = INNODB'); } + public function testCreateTableSupportsIndexesWithCustomSorting() { - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array( - 'fields' => array( - 'id' => array('sorting' => 'ASC'), - 'name' => array('sorting' => 'DESC') - ) - )) - ); + 'indexes' => array('myindex' => array( + 'fields' => array( + 'id' => array('sorting' => 'ASC'), + 'name' => array('sorting' => 'DESC'), + ), + )), + ); $this->export->createTable('sometable', $fields, $options); - + $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id INT UNSIGNED AUTO_INCREMENT, name VARCHAR(4), INDEX myindex_idx (id ASC, name DESC), PRIMARY KEY(id)) ENGINE = INNODB'); } + public function testCreateTableSupportsFulltextIndexes() { - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), - 'content' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), + 'content' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array( - 'fields' => array( - 'content' => array('sorting' => 'DESC') - ), - 'type' => 'fulltext', - )), - 'type' => 'MYISAM', - ); + 'indexes' => array('myindex' => array( + 'fields' => array( + 'content' => array('sorting' => 'DESC'), + ), + 'type' => 'fulltext', + )), + 'type' => 'MYISAM', + ); $this->export->createTable('sometable', $fields, $options); - + $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id INT UNSIGNED AUTO_INCREMENT, content VARCHAR(4), FULLTEXT INDEX myindex_idx (content DESC), PRIMARY KEY(id)) ENGINE = MYISAM'); } + public function testCreateTableSupportsCompoundForeignKeys() { $name = 'mytable'; $fields = array('id' => array('type' => 'boolean', 'primary' => true), - 'lang' => array('type' => 'integer', 'primary' => true) - ); + 'lang' => array('type' => 'integer', 'primary' => true), + ); $options = array('type' => 'INNODB', - 'foreignKeys' => array(array('local' => array ('id', 'lang' ), - 'foreign' => array ('id', 'lang'), - 'foreignTable' => 'sometable')) - ); + 'foreignKeys' => array(array('local' => array('id', 'lang'), + 'foreign' => array('id', 'lang'), + 'foreignTable' => 'sometable')), + ); $sql = $this->export->createTableSql($name, $fields, $options); $this->assertEqual($sql[0], 'CREATE TABLE mytable (id TINYINT(1), lang INT, INDEX id_idx (id), INDEX lang_idx (lang)) ENGINE = INNODB'); $this->assertEqual($sql[1], 'ALTER TABLE mytable ADD FOREIGN KEY (id, lang) REFERENCES sometable(id, lang)'); } + public function testCreateTableSupportsFieldCharset() { $sql = $this->export->createTableSql('mytable', array( @@ -372,6 +401,7 @@ public function testCreateTableSupportsFieldCharset() $this->assertEqual($sql[0], 'CREATE TABLE mytable (name VARCHAR(255) CHARACTER SET utf8) ENGINE = INNODB'); } + public function testCreateTableSupportsFieldCollation() { $sql = $this->export->createTableSql('mytable', array( @@ -380,4 +410,4 @@ public function testCreateTableSupportsFieldCollation() $this->assertEqual($sql[0], 'CREATE TABLE mytable (name VARCHAR(255) COLLATE utf8_general_ci) ENGINE = INNODB'); } -} \ No newline at end of file +} diff --git a/tests/Export/OracleTestCase.php b/tests/Export/OracleTestCase.php index 5c16b2602..3f95acc68 100644 --- a/tests/Export/OracleTestCase.php +++ b/tests/Export/OracleTestCase.php @@ -20,180 +20,188 @@ */ /** - * Doctrine_Export_Oracle_TestCase + * Doctrine_Export_Oracle_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Export_Oracle_TestCase extends Doctrine_UnitTestCase +class Doctrine_Export_Oracle_TestCase extends Doctrine_UnitTestCase { - public function testCreateSequenceExecutesSql() + public function testCreateSequenceExecutesSql() { $sequenceName = 'sequence'; $start = 1; - $query = 'CREATE SEQUENCE ' . $sequenceName . '_seq START WITH ' . $start . ' INCREMENT BY 1 NOCACHE'; + $query = 'CREATE SEQUENCE '.$sequenceName.'_seq START WITH '.$start.' INCREMENT BY 1 NOCACHE'; $this->export->createSequence($sequenceName, $start); - + $this->assertEqual($this->adapter->pop(), $query); } - public function testDropSequenceExecutesSql() + public function testDropSequenceExecutesSql() { $sequenceName = 'sequence'; - $query = 'DROP SEQUENCE ' . $sequenceName; + $query = 'DROP SEQUENCE '.$sequenceName; $this->export->dropSequence($sequenceName); - - $this->assertEqual($this->adapter->pop(), $query . '_seq'); + + $this->assertEqual($this->adapter->pop(), $query.'_seq'); } - public function testCreateTableExecutesSql() + + public function testCreateTableExecutesSql() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'integer')); + + $fields = array('id' => array('type' => 'integer')); $options = array('type' => 'MYISAM'); - + $this->export->createTable($name, $fields); $this->assertEqual($this->adapter->pop(), 'COMMIT'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id INTEGER)'); $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); } - public function testCreateTableSupportsDefaultAttribute() + + public function testCreateTableSupportsDefaultAttribute() { $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10, 'default' => 'def'), - 'type' => array('type' => 'integer', 'length' => 3, 'default' => 12) - ); - + $fields = array('name' => array('type' => 'char', 'length' => 10, 'default' => 'def'), + 'type' => array('type' => 'integer', 'length' => 3, 'default' => 12), + ); + $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); - $this->assertEqual($this->adapter->pop(), 'COMMIT'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (name CHAR(10) DEFAULT \'def\', type NUMBER(8) DEFAULT 12, PRIMARY KEY(name, type))'); $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); } - + public function testCreateTableWithOwnParams() { $this->conn->setParam('char_unit', 'CHAR'); $this->conn->setParam('varchar2_max_length', 1000); - + $fields = array( 'type' => array('type' => 'char', 'length' => 10, 'default' => 'admin'), 'name' => array('type' => 'string', 'length' => 1000), 'about' => array('type' => 'string', 'length' => 1001, 'default' => 'def'), ); - + $sql = $this->export->createTableSql('mytable', $fields); $this->assertEqual($sql[0], "CREATE TABLE mytable (type CHAR(10 CHAR) DEFAULT 'admin', name VARCHAR2(1000 CHAR), about CLOB DEFAULT 'def')"); - + $this->conn->setParam('char_unit', null); $this->conn->setParam('varchar2_max_length', 4000); } - - public function testCreateTableSupportsMultiplePks() + + public function testCreateTableSupportsMultiplePks() { $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10), - 'type' => array('type' => 'integer', 'length' => 3)); - + $fields = array('name' => array('type' => 'char', 'length' => 10), + 'type' => array('type' => 'integer', 'length' => 3)); + $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); - $this->assertEqual($this->adapter->pop(), 'COMMIT'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (name CHAR(10), type NUMBER(8), PRIMARY KEY(name, type))'); $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); } - public function testCreateTableSupportsAutoincPks() + + public function testCreateTableSupportsAutoincPks() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'integer', 'autoincrement' => true)); + $fields = array('id' => array('type' => 'integer', 'autoincrement' => true)); $this->export->createTable($name, $fields); $this->assertEqual($this->adapter->pop(), 'COMMIT'); $this->assertEqual(substr($this->adapter->pop(), 0, 14), 'CREATE TRIGGER'); - $this->assertEqual($this->adapter->pop(), 'CREATE SEQUENCE MYTABLE_seq START WITH 1 INCREMENT BY 1 NOCACHE'); - $this->assertEqual(substr($this->adapter->pop(), 0, 7), "DECLARE"); + $this->assertEqual($this->adapter->pop(), 'CREATE SEQUENCE MYTABLE_seq START WITH 1 INCREMENT BY 1 NOCACHE'); + $this->assertEqual(substr($this->adapter->pop(), 0, 7), 'DECLARE'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id INTEGER)'); $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); } - public function testCreateTableSupportsCharType() + public function testCreateTableSupportsCharType() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'char', 'length' => 3)); + + $fields = array('id' => array('type' => 'char', 'length' => 3)); $this->export->createTable($name, $fields); $this->adapter->pop(); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id CHAR(3))'); } + public function testCreateTableSupportsUniqueConstraint() { - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - ); + ); $sql = $this->export->createTableSql('sometable', $fields, $options); $this->assertEqual($sql[0], 'CREATE TABLE sometable (id INTEGER UNIQUE, name VARCHAR2(4), PRIMARY KEY(id))'); } + public function testCreateTableSupportsIndexes() { - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array('fields' => array('id', 'name'))) - ); + 'indexes' => array('myindex' => array('fields' => array('id', 'name'))), + ); $sql = $this->export->createTableSql('sometable', $fields, $options); $this->assertEqual($sql[0], 'CREATE TABLE sometable (id INTEGER UNIQUE, name VARCHAR2(4), PRIMARY KEY(id))'); $this->assertEqual($sql[4], 'CREATE INDEX myindex ON sometable (id, name)'); - - $fields = array('id'=> array('type'=>'integer', 'unisgned' => 1, 'autoincrement' => true), - 'name' => array('type' => 'string', 'length' => 4), - 'category' => array('type'=>'integer', 'length'=>2), - ); + + $fields = array('id' => array('type' => 'integer', 'unisgned' => 1, 'autoincrement' => true), + 'name' => array('type' => 'string', 'length' => 4), + 'category' => array('type' => 'integer', 'length' => 2), + ); $options = array('primary' => array('id'), - 'indexes' => array('category_index' => array('fields'=> array('category')), 'unique_index' => array('type'=> 'unique', 'fields'=> array('id', 'name'))), - ); + 'indexes' => array('category_index' => array('fields' => array('category')), 'unique_index' => array('type' => 'unique', 'fields' => array('id', 'name'))), + ); $sql = $this->export->createTableSql('sometable', $fields, $options); $this->assertEqual($sql[0], 'CREATE TABLE sometable (id INTEGER, name VARCHAR2(4), category NUMBER(5), PRIMARY KEY(id), CONSTRAINT unique_index UNIQUE (id, name))'); $this->assertEqual($sql[4], 'CREATE INDEX category_index ON sometable (category)'); } - + public function testIdentifierQuoting() { - $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); - + $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array('fields' => array('id', 'name'))) - ); - - $sql = $this->export->createTableSql('sometable', $fields, $options); + 'indexes' => array('myindex' => array('fields' => array('id', 'name'))), + ); + + $sql = $this->export->createTableSql('sometable', $fields, $options); $this->assertEqual($sql[0], 'CREATE TABLE "sometable" ("id" INTEGER, "name" VARCHAR2(4), PRIMARY KEY("id"))'); $this->assertEqual($sql[1], 'DECLARE constraints_Count NUMBER; @@ -224,12 +232,12 @@ public function testIdentifierQuoting() END LOOP; END IF; END;'); - $this->assertEqual($sql[4], 'CREATE INDEX "myindex" ON "sometable" ("id", "name")'); - - // test dropping sequence - $sql = $this->export->dropSequenceSql('sometable'); - $this->assertEqual($sql, 'DROP SEQUENCE "sometable_seq"'); - + $this->assertEqual($sql[4], 'CREATE INDEX "myindex" ON "sometable" ("id", "name")'); + + // test dropping sequence + $sql = $this->export->dropSequenceSql('sometable'); + $this->assertEqual($sql, 'DROP SEQUENCE "sometable_seq"'); + $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); } } diff --git a/tests/Export/PgsqlTestCase.php b/tests/Export/PgsqlTestCase.php index aa99596bc..f9f0e3537 100644 --- a/tests/Export/PgsqlTestCase.php +++ b/tests/Export/PgsqlTestCase.php @@ -20,47 +20,56 @@ */ /** - * Doctrine_Export_Mysql_TestCase + * Doctrine_Export_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Export_Pgsql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Export_Pgsql_TestCase extends Doctrine_UnitTestCase { - public function testCreateDatabaseExecutesSql() + public function testCreateDatabaseExecutesSql() { $this->export->createDatabase('db'); $this->assertEqual($this->adapter->pop(), 'CREATE DATABASE db'); } + public function testDropDatabaseExecutesSql() { $this->export->dropDatabase('db'); $this->assertEqual($this->adapter->pop(), 'DROP DATABASE db'); } - public function testCreateTableSupportsAutoincPks() + + public function testCreateTableSupportsAutoincPks() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true)); + + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true)); $options = array('primary' => array('id')); - + $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id SERIAL, PRIMARY KEY(id))'); } - public function testQuoteAutoincPks() + + public function testQuoteAutoincPks() { $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); $name = 'mytable'; - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true)); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true)); $options = array('primary' => array('id')); $this->export->createTable($name, $fields, $options); @@ -68,8 +77,8 @@ public function testQuoteAutoincPks() $this->assertEqual($this->adapter->pop(), 'CREATE TABLE "mytable" ("id" SERIAL, PRIMARY KEY("id"))'); $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10), - 'type' => array('type' => 'integer', 'length' => 3)); + $fields = array('name' => array('type' => 'char', 'length' => 10), + 'type' => array('type' => 'integer', 'length' => 3)); $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); @@ -78,6 +87,7 @@ public function testQuoteAutoincPks() $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); } + public function testForeignKeyIdentifierQuoting() { $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); @@ -85,13 +95,12 @@ public function testForeignKeyIdentifierQuoting() $name = 'mytable'; $fields = array('id' => array('type' => 'boolean', 'primary' => true), - 'foreignKey' => array('type' => 'integer') - ); + 'foreignKey' => array('type' => 'integer'), + ); $options = array('foreignKeys' => array(array('local' => 'foreignKey', - 'foreign' => 'id', - 'foreignTable' => 'sometable')) - ); - + 'foreign' => 'id', + 'foreignTable' => 'sometable')), + ); $sql = $this->export->createTableSql($name, $fields, $options); @@ -100,79 +109,82 @@ public function testForeignKeyIdentifierQuoting() $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); } - public function testCreateTableSupportsDefaultAttribute() + + public function testCreateTableSupportsDefaultAttribute() { $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10, 'default' => 'def'), - 'type' => array('type' => 'integer', 'length' => 3, 'default' => 12), - 'is_active' => array('type' => 'boolean', 'default'=>'0'), - 'is_admin' => array('type' => 'boolean', 'default'=>'true'), - ); - + $fields = array('name' => array('type' => 'char', 'length' => 10, 'default' => 'def'), + 'type' => array('type' => 'integer', 'length' => 3, 'default' => 12), + 'is_active' => array('type' => 'boolean', 'default' => '0'), + 'is_admin' => array('type' => 'boolean', 'default' => 'true'), + ); + $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), "CREATE TABLE mytable (name CHAR(10) DEFAULT 'def', type INT DEFAULT 12, is_active BOOLEAN DEFAULT 'false', is_admin BOOLEAN DEFAULT 'true', PRIMARY KEY(name, type))"); } + public function testCreateTableSupportsMultiplePks() - { + { $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10), - 'type' => array('type' => 'integer', 'length' => 3)); - + $fields = array('name' => array('type' => 'char', 'length' => 10), + 'type' => array('type' => 'integer', 'length' => 3)); + $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); - + $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (name CHAR(10), type INT, PRIMARY KEY(name, type))'); } + public function testExportSql() { - $sql = $this->export->exportClassesSql(array("FooRecord", "FooReferenceRecord", "FooLocallyOwned", "FooForeignlyOwned", "FooForeignlyOwnedWithPK", "FooBarRecord", "BarRecord")); - //dirname(__FILE__) . DIRECTORY_SEPARATOR . '_files'); - - $this->assertEqual($sql, array ( 0 => 'CREATE TABLE foo_reference (foo1 BIGINT, foo2 BIGINT, PRIMARY KEY(foo1, foo2))', - 1 => 'CREATE TABLE foo_locally_owned (id BIGSERIAL, name VARCHAR(200), PRIMARY KEY(id))', - 2 => 'CREATE TABLE foo_foreignly_owned_with_pk (id BIGSERIAL, name VARCHAR(200), PRIMARY KEY(id))', - 3 => 'CREATE TABLE foo_foreignly_owned (id BIGSERIAL, name VARCHAR(200), fooid BIGINT, PRIMARY KEY(id))', - 4 => 'CREATE TABLE foo_bar_record (fooid BIGINT, barid BIGINT, PRIMARY KEY(fooid, barid))', - 5 => 'CREATE TABLE foo (id BIGSERIAL, name VARCHAR(200) NOT NULL, parent_id BIGINT, local_foo BIGINT, PRIMARY KEY(id))', - 6 => 'CREATE TABLE bar (id BIGSERIAL, name VARCHAR(200), PRIMARY KEY(id))', - 7 => 'ALTER TABLE foo_reference ADD CONSTRAINT foo_reference_foo1_foo_id FOREIGN KEY (foo1) REFERENCES foo(id) NOT DEFERRABLE INITIALLY IMMEDIATE', - 8 => 'ALTER TABLE foo_bar_record ADD CONSTRAINT foo_bar_record_fooid_foo_id FOREIGN KEY (fooid) REFERENCES foo(id) NOT DEFERRABLE INITIALLY IMMEDIATE', - 9 => 'ALTER TABLE foo ADD CONSTRAINT foo_parent_id_foo_id FOREIGN KEY (parent_id) REFERENCES foo(id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE', - 10 => 'ALTER TABLE foo ADD CONSTRAINT foo_local_foo_foo_locally_owned_id FOREIGN KEY (local_foo) REFERENCES foo_locally_owned(id) ON DELETE RESTRICT NOT DEFERRABLE INITIALLY IMMEDIATE', - )); + $sql = $this->export->exportClassesSql(array('FooRecord', 'FooReferenceRecord', 'FooLocallyOwned', 'FooForeignlyOwned', 'FooForeignlyOwnedWithPK', 'FooBarRecord', 'BarRecord')); + // dirname(__FILE__) . DIRECTORY_SEPARATOR . '_files'); + + $this->assertEqual($sql, array(0 => 'CREATE TABLE foo_reference (foo1 BIGINT, foo2 BIGINT, PRIMARY KEY(foo1, foo2))', + 1 => 'CREATE TABLE foo_locally_owned (id BIGSERIAL, name VARCHAR(200), PRIMARY KEY(id))', + 2 => 'CREATE TABLE foo_foreignly_owned_with_pk (id BIGSERIAL, name VARCHAR(200), PRIMARY KEY(id))', + 3 => 'CREATE TABLE foo_foreignly_owned (id BIGSERIAL, name VARCHAR(200), fooid BIGINT, PRIMARY KEY(id))', + 4 => 'CREATE TABLE foo_bar_record (fooid BIGINT, barid BIGINT, PRIMARY KEY(fooid, barid))', + 5 => 'CREATE TABLE foo (id BIGSERIAL, name VARCHAR(200) NOT NULL, parent_id BIGINT, local_foo BIGINT, PRIMARY KEY(id))', + 6 => 'CREATE TABLE bar (id BIGSERIAL, name VARCHAR(200), PRIMARY KEY(id))', + 7 => 'ALTER TABLE foo_reference ADD CONSTRAINT foo_reference_foo1_foo_id FOREIGN KEY (foo1) REFERENCES foo(id) NOT DEFERRABLE INITIALLY IMMEDIATE', + 8 => 'ALTER TABLE foo_bar_record ADD CONSTRAINT foo_bar_record_fooid_foo_id FOREIGN KEY (fooid) REFERENCES foo(id) NOT DEFERRABLE INITIALLY IMMEDIATE', + 9 => 'ALTER TABLE foo ADD CONSTRAINT foo_parent_id_foo_id FOREIGN KEY (parent_id) REFERENCES foo(id) ON DELETE CASCADE NOT DEFERRABLE INITIALLY IMMEDIATE', + 10 => 'ALTER TABLE foo ADD CONSTRAINT foo_local_foo_foo_locally_owned_id FOREIGN KEY (local_foo) REFERENCES foo_locally_owned(id) ON DELETE RESTRICT NOT DEFERRABLE INITIALLY IMMEDIATE', + )); } - public function testAlterTableSql() + public function testAlterTableSql() { - $changes = array( - 'add' => array('newfield' => array('type' => 'int')), - 'remove' => array('oldfield' => array()) - ); + $changes = array( + 'add' => array('newfield' => array('type' => 'int')), + 'remove' => array('oldfield' => array()), + ); $sql = $this->export->alterTableSql('mytable', $changes); - $this->assertEqual($sql, array( - 0 => 'ALTER TABLE mytable ADD newfield INT', - 1 => 'ALTER TABLE mytable DROP oldfield' - )); + $this->assertEqual($sql, array( + 0 => 'ALTER TABLE mytable ADD newfield INT', + 1 => 'ALTER TABLE mytable DROP oldfield', + )); } - public function testAlterTableSqlIdentifierQuoting() + public function testAlterTableSqlIdentifierQuoting() { - $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); - - $changes = array( - 'add' => array('newfield' => array('type' => 'int')), - 'remove' => array('oldfield' => array()) - ); + $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); + + $changes = array( + 'add' => array('newfield' => array('type' => 'int')), + 'remove' => array('oldfield' => array()), + ); $sql = $this->export->alterTableSql('mytable', $changes); - $this->assertEqual($sql, array( - 0 => 'ALTER TABLE "mytable" ADD "newfield" INT', - 1 => 'ALTER TABLE "mytable" DROP "oldfield"' - )); + $this->assertEqual($sql, array( + 0 => 'ALTER TABLE "mytable" ADD "newfield" INT', + 1 => 'ALTER TABLE "mytable" DROP "oldfield"', + )); } -} \ No newline at end of file +} diff --git a/tests/Export/RecordTestCase.php b/tests/Export/RecordTestCase.php index 39a6976af..39fdaa870 100644 --- a/tests/Export/RecordTestCase.php +++ b/tests/Export/RecordTestCase.php @@ -20,29 +20,40 @@ */ clearstatcache(); /** - * Doctrine_Export_Record_TestCase + * Doctrine_Export_Record_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Export_Record_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { } - public function prepareData() - { } - public function setUp() { + public function prepareTables() + { + } + + public function prepareData() + { + } + + public function setUp() + { $this->driverName = 'mysql'; - if ( ! $this->init) { + if (!$this->init) { $this->init(); } - $this->init = true; + $this->init = true; } public function testExportSupportsForeignKeys() @@ -96,13 +107,11 @@ public function testExportSupportsForeignKeysForManyToManyRelations() public function testExportModelFromDirectory() { - - Doctrine_Core::createTablesFromModels(dirname(__FILE__) . DIRECTORY_SEPARATOR .'..' . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . 'export'); + Doctrine_Core::createTablesFromModels(dirname(__FILE__).DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'models'.DIRECTORY_SEPARATOR.'export'); $this->assertEqual($this->adapter->pop(), 'COMMIT'); $this->assertEqual($this->adapter->pop(), 'ALTER TABLE cms__category_languages ADD CONSTRAINT cms__category_languages_category_id_cms__category_id FOREIGN KEY (category_id) REFERENCES cms__category(id) ON DELETE CASCADE'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE cms__category_languages (id BIGINT AUTO_INCREMENT, name TEXT, category_id BIGINT, language_id BIGINT, INDEX index_category_idx (category_id), INDEX index_language_idx (language_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB'); - $this->assertEqual($this->adapter->pop(), 'CREATE TABLE cms__category (id BIGINT AUTO_INCREMENT, created DATETIME, parent BIGINT, position MEDIUMINT, active BIGINT, INDEX index_parent_idx (parent), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB'); + $this->assertEqual($this->adapter->pop(), 'CREATE TABLE cms__category (id BIGINT AUTO_INCREMENT, created DATETIME, parent BIGINT, position MEDIUMINT, active BIGINT, INDEX index_parent_idx (parent), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB'); $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); } - } diff --git a/tests/Export/SchemaTestCase.php b/tests/Export/SchemaTestCase.php index 960611a6f..a035ea9df 100644 --- a/tests/Export/SchemaTestCase.php +++ b/tests/Export/SchemaTestCase.php @@ -20,43 +20,49 @@ */ /** - * Doctrine_Export_Schema_TestCase + * Doctrine_Export_Schema_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Export_Schema_TestCase extends Doctrine_UnitTestCase +class Doctrine_Export_Schema_TestCase extends Doctrine_UnitTestCase { - public $tables = array('Entity', - 'EntityReference', - 'EntityAddress', - 'Email', - 'Phonenumber', - 'Groupuser', - 'Group', - 'User', - 'Album', - 'Song', - 'Element', - 'TestError', - 'Description', - 'Address', - 'Account', - 'Task', - 'Resource', - 'Assignment', - 'ResourceType', - 'ResourceReference'); - + public $tables = array('Entity', + 'EntityReference', + 'EntityAddress', + 'Email', + 'Phonenumber', + 'Groupuser', + 'Group', + 'User', + 'Album', + 'Song', + 'Element', + 'TestError', + 'Description', + 'Address', + 'Account', + 'Task', + 'Resource', + 'Assignment', + 'ResourceType', + 'ResourceReference'); + public function testYmlExport() { $export = new Doctrine_Export_Schema(); - $export->exportSchema('schema-export.yml', 'yml', dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'models', $this->tables); + $export->exportSchema('schema-export.yml', 'yml', dirname(dirname(__FILE__)).DIRECTORY_SEPARATOR.'models', $this->tables); unlink('schema-export.yml'); } } diff --git a/tests/Export/SqliteTestCase.php b/tests/Export/SqliteTestCase.php index 377696153..a1e9ed717 100644 --- a/tests/Export/SqliteTestCase.php +++ b/tests/Export/SqliteTestCase.php @@ -20,169 +20,183 @@ */ /** - * Doctrine_Export_Sqlite_TestCase + * Doctrine_Export_Sqlite_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Export_Sqlite_TestCase extends Doctrine_UnitTestCase +class Doctrine_Export_Sqlite_TestCase extends Doctrine_UnitTestCase { public function testCreateDatabaseDoesNotExecuteSqlAndCreatesSqliteFile() { $this->export->createDatabase('sqlite.db'); - + $this->assertTrue(file_exists('sqlite.db')); } + public function testDropDatabaseDoesNotExecuteSqlAndDeletesSqliteFile() { $this->export->dropDatabase('sqlite.db'); $this->assertFalse(file_exists('sqlite.db')); } - public function testCreateTableSupportsAutoincPks() + + public function testCreateTableSupportsAutoincPks() { $name = 'mytable'; - - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true)); + + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true)); $this->export->createTable($name, $fields); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (id INTEGER PRIMARY KEY AUTOINCREMENT)'); } - public function testCreateTableSupportsDefaultAttribute() + + public function testCreateTableSupportsDefaultAttribute() { $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10, 'default' => 'def'), - 'type' => array('type' => 'integer', 'length' => 3, 'default' => 12) - ); + $fields = array('name' => array('type' => 'char', 'length' => 10, 'default' => 'def'), + 'type' => array('type' => 'integer', 'length' => 3, 'default' => 12), + ); $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (name CHAR(10) DEFAULT \'def\', type INTEGER DEFAULT 12, PRIMARY KEY(name, type))'); } - public function testCreateTableSupportsMultiplePks() + + public function testCreateTableSupportsMultiplePks() { $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10), - 'type' => array('type' => 'integer', 'length' => 3)); - + $fields = array('name' => array('type' => 'char', 'length' => 10), + 'type' => array('type' => 'integer', 'length' => 3)); + $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); - + $this->assertEqual($this->adapter->pop(), 'CREATE TABLE mytable (name CHAR(10), type INTEGER, PRIMARY KEY(name, type))'); } + public function testCreateTableSupportsIndexes() { - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array('fields' => array('id', 'name'))) - ); + 'indexes' => array('myindex' => array('fields' => array('id', 'name'))), + ); $this->export->createTable('sometable', $fields, $options); - //this was the old line, but it looks like the table is created first - //and then the index so i replaced it with the ones below - //$this->assertEqual($var, 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4), INDEX myindex (id, name))'); + // this was the old line, but it looks like the table is created first + // and then the index so i replaced it with the ones below + // $this->assertEqual($var, 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4), INDEX myindex (id, name))'); - $this->assertEqual($this->adapter->pop(),"CREATE INDEX myindex_idx ON sometable (id, name)"); + $this->assertEqual($this->adapter->pop(), 'CREATE INDEX myindex_idx ON sometable (id, name)'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4))'); } + public function testIdentifierQuoting() { $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array('fields' => array('id', 'name'))) - ); + 'indexes' => array('myindex' => array('fields' => array('id', 'name'))), + ); $this->export->createTable('sometable', $fields, $options); - //this was the old line, but it looks like the table is created first - //and then the index so i replaced it with the ones below - //$this->assertEqual($var, 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4), INDEX myindex (id, name))'); + // this was the old line, but it looks like the table is created first + // and then the index so i replaced it with the ones below + // $this->assertEqual($var, 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4), INDEX myindex (id, name))'); - $this->assertEqual($this->adapter->pop(),'CREATE INDEX "myindex_idx" ON "sometable" ("id", "name")'); + $this->assertEqual($this->adapter->pop(), 'CREATE INDEX "myindex_idx" ON "sometable" ("id", "name")'); $this->assertEqual($this->adapter->pop(), 'CREATE TABLE "sometable" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "name" VARCHAR(4))'); $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); } - public function testQuoteMultiplePks() + + public function testQuoteMultiplePks() { $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); $name = 'mytable'; - $fields = array('name' => array('type' => 'char', 'length' => 10), - 'type' => array('type' => 'integer', 'length' => 3)); - + $fields = array('name' => array('type' => 'char', 'length' => 10), + 'type' => array('type' => 'integer', 'length' => 3)); + $options = array('primary' => array('name', 'type')); $this->export->createTable($name, $fields, $options); - + $this->assertEqual($this->adapter->pop(), 'CREATE TABLE "mytable" ("name" CHAR(10), "type" INTEGER, PRIMARY KEY("name", "type"))'); $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); } + public function testUnknownIndexSortingAttributeThrowsException() { $fields = array('id' => array('sorting' => 'ASC'), - 'name' => array('sorting' => 'unknown')); + 'name' => array('sorting' => 'unknown')); try { $this->export->getIndexFieldDeclarationList($fields); $this->fail(); - } catch(Doctrine_Export_Exception $e) { + } catch (Doctrine_Export_Exception $e) { $this->pass(); } } + public function testCreateTableSupportsIndexesWithCustomSorting() { - $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), - 'name' => array('type' => 'string', 'length' => 4), - ); + $fields = array('id' => array('type' => 'integer', 'unsigned' => 1, 'autoincrement' => true, 'unique' => true), + 'name' => array('type' => 'string', 'length' => 4), + ); $options = array('primary' => array('id'), - 'indexes' => array('myindex' => array( - 'fields' => array( - 'id' => array('sorting' => 'ASC'), - 'name' => array('sorting' => 'DESC') - ) - )) - ); + 'indexes' => array('myindex' => array( + 'fields' => array( + 'id' => array('sorting' => 'ASC'), + 'name' => array('sorting' => 'DESC'), + ), + )), + ); $this->export->createTable('sometable', $fields, $options); - - //removed this assertion and inserted the two below -// $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4), INDEX myindex (id ASC, name DESC))'); - $this->assertEqual($this->adapter->pop(),"CREATE INDEX myindex_idx ON sometable (id ASC, name DESC)"); + // removed this assertion and inserted the two below + // $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4), INDEX myindex (id ASC, name DESC))'); - $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4))'); + $this->assertEqual($this->adapter->pop(), 'CREATE INDEX myindex_idx ON sometable (id ASC, name DESC)'); + $this->assertEqual($this->adapter->pop(), 'CREATE TABLE sometable (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(4))'); } - /** - public function testExportSupportsEmulationOfCascadingDeletes() - { - $r = new ForeignKeyTest; - - $this->assertEqual($this->adapter->pop(), 'COMMIT'); - $this->assertEqual($this->adapter->pop(), 'CREATE TRIGGER doctrine_foreign_key_test_cscd_delete AFTER DELETE ON foreign_key_test BEGIN DELETE FROM foreign_key_test WHERE parent_id = old.id;END;'); - $this->assertEqual($this->adapter->pop(), 'CREATE TABLE foreign_key_test (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(2147483647), code INTEGER, content VARCHAR(4000), parent_id INTEGER)'); - $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); - } - */ + /* + * public function testExportSupportsEmulationOfCascadingDeletes() + * { + * $r = new ForeignKeyTest; + * + * $this->assertEqual($this->adapter->pop(), 'COMMIT'); + * $this->assertEqual($this->adapter->pop(), 'CREATE TRIGGER doctrine_foreign_key_test_cscd_delete AFTER DELETE ON foreign_key_test BEGIN DELETE FROM foreign_key_test WHERE parent_id = old.id;END;'); + * $this->assertEqual($this->adapter->pop(), 'CREATE TABLE foreign_key_test (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(2147483647), code INTEGER, content VARCHAR(4000), parent_id INTEGER)'); + * $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); + * } + */ } diff --git a/tests/ExportTestCase.php b/tests/ExportTestCase.php index 85981914f..136ddf3bd 100644 --- a/tests/ExportTestCase.php +++ b/tests/ExportTestCase.php @@ -20,71 +20,82 @@ */ /** - * Doctrine_Export_TestCase + * Doctrine_Export_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Export_TestCase extends Doctrine_UnitTestCase +class Doctrine_Export_TestCase extends Doctrine_UnitTestCase { - public function testCreateTableThrowsExceptionWithoutValidTableName() + public function testCreateTableThrowsExceptionWithoutValidTableName() { try { $this->export->createTable(0, array(), array()); $this->fail(); - } catch(Doctrine_Export_Exception $e) { + } catch (Doctrine_Export_Exception $e) { $this->pass(); } } - public function testCreateTableThrowsExceptionWithEmptyFieldsArray() + + public function testCreateTableThrowsExceptionWithEmptyFieldsArray() { try { $this->export->createTable('sometable', array(), array()); $this->fail(); - } catch(Doctrine_Export_Exception $e) { + } catch (Doctrine_Export_Exception $e) { $this->pass(); } } - public function testDropConstraintExecutesSql() + + public function testDropConstraintExecutesSql() { $this->export->dropConstraint('sometable', 'relevancy'); $this->assertEqual($this->adapter->pop(), 'ALTER TABLE sometable DROP CONSTRAINT relevancy'); } - public function testCreateIndexExecutesSql() + + public function testCreateIndexExecutesSql() { $this->export->createIndex('sometable', 'relevancy', array('fields' => array('title' => array(), 'content' => array()))); - + $this->assertEqual($this->adapter->pop(), 'CREATE INDEX relevancy_idx ON sometable (title, content)'); } - public function testDropIndexExecutesSql() + public function testDropIndexExecutesSql() { $this->export->dropIndex('sometable', 'relevancy'); - + $this->assertEqual($this->adapter->pop(), 'DROP INDEX relevancy_idx'); } - public function testDropTableExecutesSql() + + public function testDropTableExecutesSql() { $this->export->dropTable('sometable'); - + $this->assertEqual($this->adapter->pop(), 'DROP TABLE sometable'); } - public function testRecordIsExportedProperly() - { + public function testRecordIsExportedProperly() + { } - public function testExport() + + public function testExport() { - } + public function testDropDottedForeignKey() { $this->export->dropForeignKey('sometable', 'normal_foreign_key'); diff --git a/tests/Expression/DriverTestCase.php b/tests/Expression/DriverTestCase.php index 5b99e16da..01f8f6b2d 100644 --- a/tests/Expression/DriverTestCase.php +++ b/tests/Expression/DriverTestCase.php @@ -20,152 +20,215 @@ */ /** - * Doctrine_Expression_Driver_TestCase + * Doctrine_Expression_Driver_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Expression_Driver_TestCase extends Doctrine_UnitTestCase { - +class Doctrine_Expression_Driver_TestCase extends Doctrine_UnitTestCase +{ /** - * AGGREGATE FUNCTIONS + * AGGREGATE FUNCTIONS. */ - public function testAvgReturnsValidSql() { + public function testAvgReturnsValidSql() + { $this->expr = new Doctrine_Expression_Mock(); $this->assertEqual($this->expr->avg('id'), 'AVG(id)'); } - public function testCountReturnsValidSql() { + + public function testCountReturnsValidSql() + { $this->assertEqual($this->expr->count('id'), 'COUNT(id)'); } - public function testMaxReturnsValidSql() { + + public function testMaxReturnsValidSql() + { $this->assertEqual($this->expr->max('id'), 'MAX(id)'); } - public function testMinReturnsValidSql() { + + public function testMinReturnsValidSql() + { $this->assertEqual($this->expr->min('id'), 'MIN(id)'); } - public function testSumReturnsValidSql() { + + public function testSumReturnsValidSql() + { $this->assertEqual($this->expr->sum('id'), 'SUM(id)'); } - public function testRegexpImplementedOnlyAtDriverLevel() { + public function testRegexpImplementedOnlyAtDriverLevel() + { try { $this->expr->regexp('[abc]'); $this->fail(); - } catch(Doctrine_Expression_Exception $e) { + } catch (Doctrine_Expression_Exception $e) { $this->pass(); } } - public function testSoundexImplementedOnlyAtDriverLevel() { + + public function testSoundexImplementedOnlyAtDriverLevel() + { try { $this->expr->soundex('arnold'); $this->fail(); - } catch(Doctrine_Expression_Exception $e) { + } catch (Doctrine_Expression_Exception $e) { $this->pass(); } } /** - * TIME FUNCTIONS + * TIME FUNCTIONS. */ - public function testNowReturnsValidSql() { + public function testNowReturnsValidSql() + { $this->assertEqual($this->expr->now(), 'NOW()'); } /** - * STRING FUNCTIONS + * STRING FUNCTIONS. */ - public function testUpperReturnsValidSql() { + public function testUpperReturnsValidSql() + { $this->assertEqual($this->expr->upper('id', 3), 'UPPER(id)'); } - public function testLowerReturnsValidSql() { + + public function testLowerReturnsValidSql() + { $this->assertEqual($this->expr->lower('id'), 'LOWER(id)'); } - public function testLengthReturnsValidSql() { + + public function testLengthReturnsValidSql() + { $this->assertEqual($this->expr->length('id'), 'LENGTH(id)'); } - public function testLtrimReturnsValidSql() { + + public function testLtrimReturnsValidSql() + { $this->assertEqual($this->expr->ltrim('id'), 'LTRIM(id)'); } - public function testLocateReturnsValidSql() { + + public function testLocateReturnsValidSql() + { $this->assertEqual($this->expr->locate('id', 3), 'LOCATE(id, 3)'); } - public function testConcatReturnsValidSql() { + + public function testConcatReturnsValidSql() + { $this->assertEqual($this->expr->concat('id', 'type'), 'CONCAT(id, type)'); } - public function testSubstringReturnsValidSql() { + + public function testSubstringReturnsValidSql() + { $this->assertEqual($this->expr->substring('id', 3), 'SUBSTRING(id FROM 3)'); $this->assertEqual($this->expr->substring('id', 3, 2), 'SUBSTRING(id FROM 3 FOR 2)'); } /** - * MATH FUNCTIONS + * MATH FUNCTIONS. */ - public function testRoundReturnsValidSql() { + public function testRoundReturnsValidSql() + { $this->assertEqual($this->expr->round(2.3), 'ROUND(2.3, 0)'); $this->assertEqual($this->expr->round(2.3, 1), 'ROUND(2.3, 1)'); } - public function testModReturnsValidSql() { + + public function testModReturnsValidSql() + { $this->assertEqual($this->expr->mod(2, 3), 'MOD(2, 3)'); } - public function testSubReturnsValidSql() { + + public function testSubReturnsValidSql() + { $this->assertEqual($this->expr->sub(array(2, 3)), '(2 - 3)'); } - public function testMulReturnsValidSql() { + + public function testMulReturnsValidSql() + { $this->assertEqual($this->expr->mul(array(2, 3)), '(2 * 3)'); } - public function testAddReturnsValidSql() { + + public function testAddReturnsValidSql() + { $this->assertEqual($this->expr->add(array(2, 3)), '(2 + 3)'); } - public function testDivReturnsValidSql() { + + public function testDivReturnsValidSql() + { $this->assertEqual($this->expr->div(array(2, 3)), '(2 / 3)'); } /** - * ASSERT OPERATORS + * ASSERT OPERATORS. */ - public function testEqReturnsValidSql() { + public function testEqReturnsValidSql() + { $this->assertEqual($this->expr->eq(1, 1), '1 = 1'); } - public function testNeqReturnsValidSql() { + + public function testNeqReturnsValidSql() + { $this->assertEqual($this->expr->neq(1, 2), '1 <> 2'); } - public function testGtReturnsValidSql() { + + public function testGtReturnsValidSql() + { $this->assertEqual($this->expr->gt(2, 1), '2 > 1'); } - public function testGteReturnsValidSql() { + + public function testGteReturnsValidSql() + { $this->assertEqual($this->expr->gte(1, 1), '1 >= 1'); } - public function testLtReturnsValidSql() { + + public function testLtReturnsValidSql() + { $this->assertEqual($this->expr->lt(1, 2), '1 < 2'); } - public function testLteReturnsValidSql() { + + public function testLteReturnsValidSql() + { $this->assertEqual($this->expr->lte(1, 1), '1 <= 1'); } /** - * WHERE OPERATORS + * WHERE OPERATORS. */ - public function testNotReturnsValidSql() { + public function testNotReturnsValidSql() + { $this->assertEqual($this->expr->not('id'), 'NOT(id)'); } - public function testInReturnsValidSql() { + + public function testInReturnsValidSql() + { $this->assertEqual($this->expr->in('id', array(1, 2)), 'id IN (1, 2)'); } - public function testIsNullReturnsValidSql() { + + public function testIsNullReturnsValidSql() + { $this->assertEqual($this->expr->isNull('type'), 'type IS NULL'); } - public function testIsNotNullReturnsValidSql() { + + public function testIsNotNullReturnsValidSql() + { $this->assertEqual($this->expr->isNotNull('type'), 'type IS NOT NULL'); } - public function testBetweenReturnsValidSql() { + + public function testBetweenReturnsValidSql() + { $this->assertEqual($this->expr->between('age', 12, 14), 'age BETWEEN 12 AND 14'); } -} \ No newline at end of file +} diff --git a/tests/Expression/MssqlTestCase.php b/tests/Expression/MssqlTestCase.php index 4d5bac712..2301a1b65 100644 --- a/tests/Expression/MssqlTestCase.php +++ b/tests/Expression/MssqlTestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_Expression_Mssql_TestCase + * Doctrine_Expression_Mssql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Expression_Mssql_TestCase extends Doctrine_UnitTestCase { +class Doctrine_Expression_Mssql_TestCase extends Doctrine_UnitTestCase +{ } diff --git a/tests/Expression/MysqlTestCase.php b/tests/Expression/MysqlTestCase.php index c0762e0e7..6d2196814 100644 --- a/tests/Expression/MysqlTestCase.php +++ b/tests/Expression/MysqlTestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_Expression_Mysql_TestCase + * Doctrine_Expression_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Expression_Mysql_TestCase extends Doctrine_UnitTestCase { +class Doctrine_Expression_Mysql_TestCase extends Doctrine_UnitTestCase +{ } diff --git a/tests/Expression/OracleTestCase.php b/tests/Expression/OracleTestCase.php index c92c406d9..fc78b1660 100644 --- a/tests/Expression/OracleTestCase.php +++ b/tests/Expression/OracleTestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_Expression_Oracle_TestCase + * Doctrine_Expression_Oracle_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Expression_Oracle_TestCase extends Doctrine_UnitTestCase { +class Doctrine_Expression_Oracle_TestCase extends Doctrine_UnitTestCase +{ } diff --git a/tests/Expression/PgsqlTestCase.php b/tests/Expression/PgsqlTestCase.php index 00f95e8aa..fe0d113ad 100644 --- a/tests/Expression/PgsqlTestCase.php +++ b/tests/Expression/PgsqlTestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_Expression_Pgsql_TestCase + * Doctrine_Expression_Pgsql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Expression_Pgsql_TestCase extends Doctrine_UnitTestCase { +class Doctrine_Expression_Pgsql_TestCase extends Doctrine_UnitTestCase +{ } diff --git a/tests/Expression/SqliteTestCase.php b/tests/Expression/SqliteTestCase.php index c4a8e92c2..ec255ed1b 100644 --- a/tests/Expression/SqliteTestCase.php +++ b/tests/Expression/SqliteTestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_Expression_Sqlite_TestCase + * Doctrine_Expression_Sqlite_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Expression_Sqlite_TestCase extends Doctrine_UnitTestCase { +class Doctrine_Expression_Sqlite_TestCase extends Doctrine_UnitTestCase +{ } diff --git a/tests/ExpressionTestCase.php b/tests/ExpressionTestCase.php index dad0c3e3d..353b07af9 100644 --- a/tests/ExpressionTestCase.php +++ b/tests/ExpressionTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Expression_TestCase + * Doctrine_Expression_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Expression_TestCase extends Doctrine_UnitTestCase { @@ -66,4 +72,3 @@ public function testExpressionParserSupportsParensInClauses() $this->assertEqual($e->getSql(), "CONCAT('(some)', '(one)')"); } } - diff --git a/tests/Extension/TestExtension/lib/Doctrine/Template/TestBehavior.php b/tests/Extension/TestExtension/lib/Doctrine/Template/TestBehavior.php index fbcad67cc..a8c5241a1 100755 --- a/tests/Extension/TestExtension/lib/Doctrine/Template/TestBehavior.php +++ b/tests/Extension/TestExtension/lib/Doctrine/Template/TestBehavior.php @@ -6,4 +6,4 @@ public function setTableDefinition() { $this->hasColumn('test', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Extension/TestExtension/lib/Doctrine/Test.php b/tests/Extension/TestExtension/lib/Doctrine/Test.php index de8f62280..26282bb6c 100755 --- a/tests/Extension/TestExtension/lib/Doctrine/Test.php +++ b/tests/Extension/TestExtension/lib/Doctrine/Test.php @@ -2,4 +2,4 @@ class Doctrine_Test { -} \ No newline at end of file +} diff --git a/tests/ExtensionTestCase.php b/tests/ExtensionTestCase.php index c7dd166c8..ed6ce6719 100755 --- a/tests/ExtensionTestCase.php +++ b/tests/ExtensionTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Extension_TestCase + * Doctrine_Extension_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Extension_TestCase extends Doctrine_UnitTestCase { @@ -38,7 +44,8 @@ public function prepareTables() spl_autoload_register(array('Doctrine_Core', 'extensionsAutoload')); Doctrine_Manager::getInstance() - ->registerExtension('TestExtension'); + ->registerExtension('TestExtension') + ; $this->tables[] = 'ExtensionBehaviorTest'; parent::prepareTables(); @@ -64,6 +71,11 @@ public function tearDown() } } +/** + * @internal + * + * @coversNothing + */ class ExtensionBehaviorTest extends Doctrine_Record { public function setTableDefinition() diff --git a/tests/ForeignKeyTestCase.php b/tests/ForeignKeyTestCase.php index 0a8851577..8c460d506 100644 --- a/tests/ForeignKeyTestCase.php +++ b/tests/ForeignKeyTestCase.php @@ -20,37 +20,45 @@ */ /** - * Doctrine_ForeignKey_TestCase + * Doctrine_ForeignKey_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_ForeignKey_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() - { } - + { + } public function testExportingForeignKeysSupportsAssociationTables() { $this->dbh = new Doctrine_Adapter_Mock('mysql'); $this->conn = $this->manager->openConnection($this->dbh); - + $sql = $this->conn->export->exportClassesSql(array('ClientModel', 'ClientToAddressModel', 'AddressModel')); - - $this->assertEqual($sql, array ( - 0 => 'CREATE TABLE clients_to_addresses (client_id BIGINT, address_id BIGINT, INDEX client_id_idx (client_id), INDEX address_id_idx (address_id), PRIMARY KEY(client_id, address_id)) ENGINE = INNODB', - 1 => 'CREATE TABLE clients (id INT UNSIGNED NOT NULL AUTO_INCREMENT, short_name VARCHAR(32) NOT NULL UNIQUE, PRIMARY KEY(id)) ENGINE = INNODB', - 2 => 'CREATE TABLE addresses (id BIGINT AUTO_INCREMENT, address1 VARCHAR(255) NOT NULL, address2 VARCHAR(255) NOT NULL, city VARCHAR(255) NOT NULL, state VARCHAR(10) NOT NULL, zip VARCHAR(15) NOT NULL, PRIMARY KEY(id)) ENGINE = INNODB', - 3 => 'ALTER TABLE clients_to_addresses ADD CONSTRAINT FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE', - 4 => 'ALTER TABLE clients_to_addresses ADD CONSTRAINT FOREIGN KEY (address_id) REFERENCES addresses(id) ON DELETE CASCADE', - )); + + $this->assertEqual($sql, array( + 0 => 'CREATE TABLE clients_to_addresses (client_id BIGINT, address_id BIGINT, INDEX client_id_idx (client_id), INDEX address_id_idx (address_id), PRIMARY KEY(client_id, address_id)) ENGINE = INNODB', + 1 => 'CREATE TABLE clients (id INT UNSIGNED NOT NULL AUTO_INCREMENT, short_name VARCHAR(32) NOT NULL UNIQUE, PRIMARY KEY(id)) ENGINE = INNODB', + 2 => 'CREATE TABLE addresses (id BIGINT AUTO_INCREMENT, address1 VARCHAR(255) NOT NULL, address2 VARCHAR(255) NOT NULL, city VARCHAR(255) NOT NULL, state VARCHAR(10) NOT NULL, zip VARCHAR(15) NOT NULL, PRIMARY KEY(id)) ENGINE = INNODB', + 3 => 'ALTER TABLE clients_to_addresses ADD CONSTRAINT FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE', + 4 => 'ALTER TABLE clients_to_addresses ADD CONSTRAINT FOREIGN KEY (address_id) REFERENCES addresses(id) ON DELETE CASCADE', + )); } } diff --git a/tests/HookTestCase.php b/tests/HookTestCase.php index ceecdbd7f..cbdf6ea34 100644 --- a/tests/HookTestCase.php +++ b/tests/HookTestCase.php @@ -20,23 +20,28 @@ */ /** - * Doctrine_Hook_TestCase + * Doctrine_Hook_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Hook_TestCase extends Doctrine_UnitTestCase +class Doctrine_Hook_TestCase extends Doctrine_UnitTestCase { - - public function testWordLikeParserSupportsHyphens() + public function testWordLikeParserSupportsHyphens() { $parser = new Doctrine_Hook_WordLike(); - + $parser->parse('u', 'name', "'some guy' OR zYne"); $this->assertEqual($parser->getCondition(), '(u.name LIKE ? OR u.name LIKE ?)'); @@ -82,7 +87,7 @@ public function testHookOrderbyAcceptsMultipleParameters() $hook->hookOrderBy($a['orderby']); $this->assertEqual($hook->getQuery()->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0) ORDER BY e.name ASC, e.id DESC'); - $users = $hook->getQuery()->execute(); + $users = $hook->getQuery()->execute(); } public function testHookWhereAcceptsArrays() @@ -90,7 +95,7 @@ public function testHookWhereAcceptsArrays() $hook = new Doctrine_Hook('SELECT u.name FROM User u LEFT JOIN u.Phonenumber p'); $a['where'] = array('u.name' => 'Jack Daniels', - 'u.loginname' => 'TheMan'); + 'u.loginname' => 'TheMan'); $hook->hookWhere($a['where']); $this->assertEqual($hook->getQuery()->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.name LIKE ? OR e.name LIKE ?) AND e.loginname LIKE ? AND (e.type = 0)'); @@ -168,5 +173,4 @@ public function testIntegerParserSupportsNestingConditions() $this->assertEqual($parser->getCondition(), '((m.year > ? AND m.year < ?) OR m.year = ?)'); $this->assertEqual($parser->getParams(), array('1998', '2000', '2001')); } - } diff --git a/tests/Hydrate/CollectionInitializationTestCase.php b/tests/Hydrate/CollectionInitializationTestCase.php index cd3d44bd4..7c96d7e23 100644 --- a/tests/Hydrate/CollectionInitializationTestCase.php +++ b/tests/Hydrate/CollectionInitializationTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Hydrate_CollectionInitialization_TestCase + * Doctrine_Hydrate_CollectionInitialization_TestCase. * - * @package Doctrine * @author Roman Borschel * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Hydrate_CollectionInitialization_TestCase extends Doctrine_UnitTestCase { @@ -36,35 +42,37 @@ public function prepareData() { $user = new User(); $user->name = 'romanb'; - + $user->Phonenumber[0]->phonenumber = '112'; $user->Phonenumber[1]->phonenumber = '110'; - + $user->save(); } - + public function prepareTables() { - $this->tables = array('Entity', 'Phonenumber'); + $this->tables = array('Entity', 'Phonenumber'); parent::prepareTables(); } - + public function testCollectionsAreReinitializedOnHydration() { // query for user with first phonenumber. $q = Doctrine_Query::create(); - $q->select("u.*, p.*")->from("User u")->innerJoin("u.Phonenumber p") - ->where("p.phonenumber = '112'"); - + $q->select('u.*, p.*')->from('User u')->innerJoin('u.Phonenumber p') + ->where("p.phonenumber = '112'") + ; + $users = $q->execute(); $this->assertEqual(1, count($users)); $this->assertEqual(1, count($users[0]->Phonenumber)); $this->assertEqual('112', $users[0]->Phonenumber[0]->phonenumber); - + // now query again. this time for the other phonenumber. collection should be re-initialized. $q = Doctrine_Query::create(); - $q->select("u.*, p.*")->from("User u")->innerJoin("u.Phonenumber p") - ->where("p.phonenumber = '110'"); + $q->select('u.*, p.*')->from('User u')->innerJoin('u.Phonenumber p') + ->where("p.phonenumber = '110'") + ; $users = $q->execute(); $this->assertEqual(1, count($users)); $this->assertEqual(1, count($users[0]->Phonenumber)); @@ -72,7 +80,7 @@ public function testCollectionsAreReinitializedOnHydration() // now query again. this time for both phonenumbers. collection should be re-initialized. $q = Doctrine_Query::create(); - $q->select("u.*, p.*")->from("User u")->innerJoin("u.Phonenumber p"); + $q->select('u.*, p.*')->from('User u')->innerJoin('u.Phonenumber p'); $users = $q->execute(); $this->assertEqual(1, count($users)); $this->assertEqual(2, count($users[0]->Phonenumber)); @@ -81,7 +89,7 @@ public function testCollectionsAreReinitializedOnHydration() // now query AGAIN for both phonenumbers. collection should be re-initialized (2 elements, not 4). $q = Doctrine_Query::create(); - $q->select("u.*, p.*")->from("User u")->innerJoin("u.Phonenumber p"); + $q->select('u.*, p.*')->from('User u')->innerJoin('u.Phonenumber p'); $users = $q->execute(); $this->assertEqual(1, count($users)); $this->assertEqual(2, count($users[0]->Phonenumber)); @@ -91,7 +99,7 @@ public function testCollectionsAreReinitializedOnHydration() public function testOneToManyReverseMatching() { - $users = Doctrine_Query::create() + $users = Doctrine_Query::create() ->from('User u') ->leftJoin('u.Phonenumber p') ->having('COUNT(p.id) > 0') diff --git a/tests/Hydrate/DriverTestCase.php b/tests/Hydrate/DriverTestCase.php index 4a9de48f6..fc91b91d7 100644 --- a/tests/Hydrate/DriverTestCase.php +++ b/tests/Hydrate/DriverTestCase.php @@ -20,26 +20,34 @@ */ /** - * Doctrine_Hydrate_Driver_TestCase + * Doctrine_Hydrate_Driver_TestCase. * - * @package Doctrine * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Hydrate_Driver_TestCase extends Doctrine_UnitTestCase { public function testCustomHydrator() { Doctrine_Manager::getInstance() - ->registerHydrator('MyHydrator', 'MyHydrator'); + ->registerHydrator('MyHydrator', 'MyHydrator') + ; $result = Doctrine_Core::getTable('User') ->createQuery('u') - ->execute(array(), 'MyHydrator'); + ->execute(array(), 'MyHydrator') + ; $this->assertEqual($result, 'MY_HYDRATOR'); } @@ -48,11 +56,13 @@ public function testCustomHydratorUsingClassInstance() { $hydrator = new MyHydrator(); Doctrine_Manager::getInstance() - ->registerHydrator('MyHydrator', $hydrator); + ->registerHydrator('MyHydrator', $hydrator) + ; $result = Doctrine_Core::getTable('User') ->createQuery('u') - ->execute(array(), 'MyHydrator'); + ->execute(array(), 'MyHydrator') + ; $this->assertEqual($result, 'MY_HYDRATOR'); } @@ -72,14 +82,16 @@ public function testCustomHydratorConstructor() public function testCustomHydratorUsingClassInstanceExceptingException() { - $hydrator = new StdClass(); + $hydrator = new stdClass(); Doctrine_Manager::getInstance() - ->registerHydrator('MyHydrator', $hydrator); + ->registerHydrator('MyHydrator', $hydrator) + ; try { - Doctrine_Core::getTable('User') + Doctrine_Core::getTable('User') ->createQuery('u') - ->execute(array(), 'MyHydrator'); + ->execute(array(), 'MyHydrator') + ; $this->fail('Expected exception not thrown: Doctrine_Hydrator_Exception'); } catch (Doctrine_Hydrator_Exception $e) { @@ -97,4 +109,4 @@ public function hydrateResultSet($stmt) { return 'MY_HYDRATOR'; } -} \ No newline at end of file +} diff --git a/tests/Hydrate/FetchModeTestCase.php b/tests/Hydrate/FetchModeTestCase.php index 634782f23..25ffa185e 100644 --- a/tests/Hydrate/FetchModeTestCase.php +++ b/tests/Hydrate/FetchModeTestCase.php @@ -20,49 +20,56 @@ */ /** - * Doctrine_Hydrate_FetchMode_TestCase + * Doctrine_Hydrate_FetchMode_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Hydrate_FetchMode_TestCase extends Doctrine_UnitTestCase +class Doctrine_Hydrate_FetchMode_TestCase extends Doctrine_UnitTestCase { - public function testFetchArraySupportsOneToManyRelations() { $q = new Doctrine_Query(); $q->select('u.*, p.*')->from('User u')->innerJoin('u.Phonenumber p')->where("u.name = 'zYne'"); - + $users = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertTrue(is_array($users)); $this->assertEqual(count($users), 1); } + public function testFetchArraySupportsOneToManyRelations2() { $q = new Doctrine_Query(); $q->select('u.*, p.*')->from('User u')->innerJoin('u.Phonenumber p'); - + $users = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertTrue(is_array($users)); $this->assertEqual(count($users), 8); } + public function testFetchArraySupportsOneToManyRelations3() { $q = new Doctrine_Query(); $q->select('u.*, p.*')->from('User u')->innerJoin('u.Phonenumber p')->where("u.name = 'Jean Reno'"); - + $users = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertTrue(is_array($users)); @@ -70,23 +77,25 @@ public function testFetchArraySupportsOneToManyRelations3() $this->assertEqual(count($users), 1); $this->assertEqual(count($users[0]['Phonenumber']), 3); } + public function testFetchArraySupportsOneToOneRelations() { $q = new Doctrine_Query(); $q->select('u.*, e.*')->from('User u')->innerJoin('u.Email e'); - + $users = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertEqual(count($users), 8); $this->assertEqual($users[0]['Email']['address'], 'zYne@example.com'); } + public function testFetchArraySupportsOneToOneRelations2() { $q = new Doctrine_Query(); $q->select('u.*, e.*')->from('User u')->innerJoin('u.Email e')->where("u.name = 'zYne'"); - + $users = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertEqual(count($users), 1); @@ -105,7 +114,7 @@ public function testFetchRecordSupportsOneToOneRelations() $this->assertEqual($users[0]['Email']['address'], 'zYne@example.com'); $this->assertTrue($users[0] instanceof User); - $this->assertTrue($users instanceof Doctrine_Collection); + $this->assertTrue($users instanceof Doctrine_Collection); $this->assertEqual($users[0]->state(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($users[0]->id, 4); @@ -144,33 +153,32 @@ public function testFetchRecordSupportsSimpleFetching() $this->assertTrue($users[0] instanceof User); $this->assertEqual($users[0]->state(), Doctrine_Record::STATE_CLEAN); - $this->assertEqual($this->conn->count(), $count + 1); } public function testFetchArrayNull() { $u = new User(); - $u->name = "fetch_array_test"; + $u->name = 'fetch_array_test'; $u->created = null; $u->save(); - + $q = new Doctrine_Query(); $q->select('u.*')->from('User u')->where('u.id = ?'); $users = $q->execute(array($u->id), Doctrine_Core::HYDRATE_ARRAY); $this->assertEqual($users[0]['created'], null); } - + public function testHydrateNone() { $u = new User(); - $u->name = "fetch_array_test"; + $u->name = 'fetch_array_test'; $u->created = null; $u->save(); - + $q = new Doctrine_Query(); $q->select('COUNT(u.id) num')->from('User u')->where('u.id = ?'); $res = $q->execute(array($u->id), Doctrine_Core::HYDRATE_NONE); $this->assertEqual(1, $res[0][0]); } -} \ No newline at end of file +} diff --git a/tests/Hydrate/PerformanceTestCase.php b/tests/Hydrate/PerformanceTestCase.php index 405c9b593..f04d800a1 100644 --- a/tests/Hydrate/PerformanceTestCase.php +++ b/tests/Hydrate/PerformanceTestCase.php @@ -20,25 +20,29 @@ */ /** - * Doctrine_Hydrate_Scalar_TestCase + * Doctrine_Hydrate_Scalar_TestCase. * - * @package Doctrine * @author Roman Borschel * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Hydrate_Performance_TestCase extends Doctrine_UnitTestCase { public function prepareData() { - for ($i = 0; $i < 10000; $i++) - { + for ($i = 0; $i < 10000; ++$i) { $test = new HydratePerformance(); - for ($j = 1; $j <= 6; $j++) - { + for ($j = 1; $j <= 6; ++$j) { $test->set('column'.$j, 'Test value'); } $test->save(); @@ -56,14 +60,15 @@ public function testPerformance() $s = microtime(true); $q = Doctrine_Core::getTable('HydratePerformance') - ->createQuery('u'); + ->createQuery('u') + ; $records = $q->execute(); $e = microtime(true); $time = $e - $s; - echo PHP_EOL.'Hydration for ' . count($records) . ' records took ' . $time . PHP_EOL; + echo PHP_EOL.'Hydration for '.count($records).' records took '.$time.PHP_EOL; } } @@ -78,4 +83,4 @@ public function setTableDefinition() $this->hasColumn('column5', 'string', 255); $this->hasColumn('column6 ', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Hydrate/ScalarTestCase.php b/tests/Hydrate/ScalarTestCase.php index 50d58a984..98ba85df4 100644 --- a/tests/Hydrate/ScalarTestCase.php +++ b/tests/Hydrate/ScalarTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Hydrate_Scalar_TestCase + * Doctrine_Hydrate_Scalar_TestCase. * - * @package Doctrine * @author Roman Borschel * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Hydrate_Scalar_TestCase extends Doctrine_UnitTestCase { @@ -40,25 +46,26 @@ public function prepareData() $user->Phonenumber[1]->phonenumber = '110'; $user->save(); } - + public function prepareTables() { - $this->tables = array('Entity', 'Phonenumber'); + $this->tables = array('Entity', 'Phonenumber'); parent::prepareTables(); } - + public function testHydrateScalarWithJoin() { $q = Doctrine_Query::create(); - $q->select("u.*, p.*") - ->from("User u") - ->innerJoin("u.Phonenumber p"); - + $q->select('u.*, p.*') + ->from('User u') + ->innerJoin('u.Phonenumber p') + ; + $res = $q->execute(array(), Doctrine_Core::HYDRATE_SCALAR); - + $this->assertTrue(is_array($res)); $this->assertEqual(2, count($res)); - //row1 + // row1 $this->assertEqual(1, $res[0]['u_id']); $this->assertEqual('romanb', $res[0]['u_name']); $this->assertEqual(null, $res[0]['u_loginname']); @@ -70,7 +77,7 @@ public function testHydrateScalarWithJoin() $this->assertEqual(1, $res[0]['p_id']); $this->assertEqual(112, $res[0]['p_phonenumber']); $this->assertEqual(1, $res[0]['p_entity_id']); - //row2 + // row2 $this->assertEqual(1, $res[1]['u_id']); $this->assertEqual('romanb', $res[1]['u_name']); $this->assertEqual(null, $res[1]['u_loginname']); @@ -82,20 +89,20 @@ public function testHydrateScalarWithJoin() $this->assertEqual(2, $res[1]['p_id']); $this->assertEqual(110, $res[1]['p_phonenumber']); $this->assertEqual(1, $res[1]['p_entity_id']); - + $q->free(); } - + public function testHydrateScalar() { $q = Doctrine_Query::create(); - $q->select("u.*")->from("User u"); - + $q->select('u.*')->from('User u'); + $res = $q->execute(array(), Doctrine_Core::HYDRATE_SCALAR); - + $this->assertTrue(is_array($res)); $this->assertEqual(1, count($res)); - //row1 + // row1 $this->assertEqual(1, $res[0]['u_id']); $this->assertEqual('romanb', $res[0]['u_name']); $this->assertEqual(null, $res[0]['u_loginname']); @@ -104,68 +111,70 @@ public function testHydrateScalar() $this->assertEqual(null, $res[0]['u_created']); $this->assertEqual(null, $res[0]['u_updated']); $this->assertEqual(null, $res[0]['u_email_id']); - + $q->free(); } - + public function testHydrateSingleScalarDoesNotAddPKToSelect() { $q = Doctrine_Query::create(); - $q->select("u.name")->from("User u"); + $q->select('u.name')->from('User u'); $res = $q->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR); $this->assertEqual('romanb', $res); $q->free(); } - + public function testHydrateSingleScalarWithAggregate() { $q = Doctrine_Query::create(); - $q->select("COUNT(u.id) num_ids")->from("User u"); + $q->select('COUNT(u.id) num_ids')->from('User u'); $res = $q->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR); $this->assertEqual(1, $res); $q->free(); } - + public function testHydrateScalarWithJoinAndAggregate() { $q = Doctrine_Query::create(); - $q->select("u.id, UPPER(u.name) nameUpper, p.*") - ->from("User u") - ->innerJoin("u.Phonenumber p"); - + $q->select('u.id, UPPER(u.name) nameUpper, p.*') + ->from('User u') + ->innerJoin('u.Phonenumber p') + ; + $res = $q->execute(array(), Doctrine_Core::HYDRATE_SCALAR); - + $this->assertTrue(is_array($res)); $this->assertEqual(2, count($res)); - - //row1 + + // row1 $this->assertEqual(1, $res[0]['u_id']); $this->assertEqual('ROMANB', $res[0]['u_nameUpper']); $this->assertEqual(1, $res[0]['p_id']); $this->assertEqual(112, $res[0]['p_phonenumber']); $this->assertEqual(1, $res[0]['p_entity_id']); - //row2 + // row2 $this->assertEqual(1, $res[1]['u_id']); $this->assertEqual('ROMANB', $res[1]['u_nameUpper']); $this->assertEqual(2, $res[1]['p_id']); $this->assertEqual(110, $res[1]['p_phonenumber']); $this->assertEqual(1, $res[1]['p_entity_id']); - + $q->free(); } public function testHydrateArrayShallowWithJoin() { $q = Doctrine_Query::create(); - $q->select("u.*, p.id as phonenumber_id, p.phonenumber, p.entity_id") - ->from("User u") - ->innerJoin("u.Phonenumber p"); + $q->select('u.*, p.id as phonenumber_id, p.phonenumber, p.entity_id') + ->from('User u') + ->innerJoin('u.Phonenumber p') + ; $res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY_SHALLOW); $this->assertTrue(is_array($res)); $this->assertEqual(2, count($res)); - //row1 + // row1 $this->assertEqual(1, $res[0]['id']); $this->assertEqual('romanb', $res[0]['name']); $this->assertEqual(null, $res[0]['loginname']); @@ -177,7 +186,7 @@ public function testHydrateArrayShallowWithJoin() $this->assertEqual(1, $res[0]['phonenumber_id']); $this->assertEqual(112, $res[0]['phonenumber']); $this->assertEqual(1, $res[0]['entity_id']); - //row2 + // row2 $this->assertEqual(1, $res[1]['id']); $this->assertEqual('romanb', $res[1]['name']); $this->assertEqual(null, $res[1]['loginname']); @@ -196,13 +205,13 @@ public function testHydrateArrayShallowWithJoin() public function testHydrateArrayShallow() { $q = Doctrine_Query::create(); - $q->select("u.*")->from("User u"); + $q->select('u.*')->from('User u'); $res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY_SHALLOW); $this->assertTrue(is_array($res)); $this->assertEqual(1, count($res)); - //row1 + // row1 $this->assertEqual(1, $res[0]['id']); $this->assertEqual('romanb', $res[0]['name']); $this->assertEqual(null, $res[0]['loginname']); @@ -218,22 +227,23 @@ public function testHydrateArrayShallow() public function testHydrateArrayShallowWithJoinAndAggregate() { $q = Doctrine_Query::create(); - $q->select("u.id, UPPER(u.name) nameUpper, p.id as phonenumber_id, p.phonenumber, p.entity_id") - ->from("User u") - ->innerJoin("u.Phonenumber p"); + $q->select('u.id, UPPER(u.name) nameUpper, p.id as phonenumber_id, p.phonenumber, p.entity_id') + ->from('User u') + ->innerJoin('u.Phonenumber p') + ; $res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY_SHALLOW); $this->assertTrue(is_array($res)); $this->assertEqual(2, count($res)); - //row1 + // row1 $this->assertEqual(1, $res[0]['id']); $this->assertEqual('ROMANB', $res[0]['nameUpper']); $this->assertEqual(1, $res[0]['id']); $this->assertEqual(112, $res[0]['phonenumber']); $this->assertEqual(1, $res[0]['entity_id']); - //row2 + // row2 $this->assertEqual(1, $res[1]['id']); $this->assertEqual('ROMANB', $res[1]['nameUpper']); $this->assertEqual(2, $res[1]['phonenumber_id']); @@ -242,4 +252,4 @@ public function testHydrateArrayShallowWithJoinAndAggregate() $q->free(); } -} \ No newline at end of file +} diff --git a/tests/HydrateTestCase.php b/tests/HydrateTestCase.php index c17acfac2..702bd60a7 100644 --- a/tests/HydrateTestCase.php +++ b/tests/HydrateTestCase.php @@ -20,47 +20,55 @@ */ /** - * Doctrine_Hydrate_TestCase + * Doctrine_Hydrate_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Hydrate_TestCase extends Doctrine_UnitTestCase { protected $testData1 = array( - array( - 'e' => array('id' => 1, 'name' => 'zYne'), - 'p' => array('id' => 1, 'phonenumber' => '123 123', 'user_id' => 1) - ), - array( - 'e' => array('id' => 2, 'name' => 'John'), - 'p' => array('id' => 2, 'phonenumber' => '222 222', 'user_id' => 2) - ), - array( - 'e' => array('id' => 2, 'name' => 'John'), - 'p' => array('id' => 3, 'phonenumber' => '343 343', 'user_id' => 2) - ), - array( - 'e' => array('id' => 3, 'name' => 'Arnold'), - 'p' => array('id' => 4, 'phonenumber' => '333 333', 'user_id' => 3) - ), - array( - 'e' => array('id' => 4, 'name' => 'Arnold'), - 'p' => array('id' => null, 'phonenumber' => null, 'user_id' => null) - ) - ); + array( + 'e' => array('id' => 1, 'name' => 'zYne'), + 'p' => array('id' => 1, 'phonenumber' => '123 123', 'user_id' => 1), + ), + array( + 'e' => array('id' => 2, 'name' => 'John'), + 'p' => array('id' => 2, 'phonenumber' => '222 222', 'user_id' => 2), + ), + array( + 'e' => array('id' => 2, 'name' => 'John'), + 'p' => array('id' => 3, 'phonenumber' => '343 343', 'user_id' => 2), + ), + array( + 'e' => array('id' => 3, 'name' => 'Arnold'), + 'p' => array('id' => 4, 'phonenumber' => '333 333', 'user_id' => 3), + ), + array( + 'e' => array('id' => 4, 'name' => 'Arnold'), + 'p' => array('id' => null, 'phonenumber' => null, 'user_id' => null), + ), + ); + public function prepareData() - { } + { + } public function testHydrateHooks() { $user = new User(); - $user->getTable()->addRecordListener(new HydrationListener); + $user->getTable()->addRecordListener(new HydrationListener()); $user->name = 'zYne'; $user->save(); @@ -76,16 +84,17 @@ public function testHydrateHooks() class HydrationListener extends Doctrine_Record_Listener { - public function preHydrate(Doctrine_Event $event) + public function preHydrate(Doctrine_Event $event) { $data = $event->data; $data['password'] = 'default pass'; - + $event->data = $data; } + public function postHydrate(Doctrine_Event $event) { - foreach ($event->data as $key => $value) { + foreach ($event->data as $key => $value) { $event->data[$key] = strtoupper((string) $value); } } @@ -99,9 +108,9 @@ public function setData($data) { $this->data = $data; } - + public function hydrateResultSet($stmt) { return true; } -} \ No newline at end of file +} diff --git a/tests/I18nTestCase.php b/tests/I18nTestCase.php index 81f6e2caa..c1c4f05b1 100644 --- a/tests/I18nTestCase.php +++ b/tests/I18nTestCase.php @@ -20,21 +20,27 @@ */ /** - * Doctrine_I18n_TestCase + * Doctrine_I18n_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_I18n_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + { + } public function prepareTables() { @@ -45,9 +51,9 @@ public function prepareTables() public function testTranslationTableGetsExported() { - $this->conn->setAttribute(Doctrine_Core::ATTR_EXPORT, Doctrine_Core::EXPORT_ALL); - - $this->assertTrue(Doctrine_Core::EXPORT_ALL & Doctrine_Core::EXPORT_TABLES); + $this->conn->setAttribute(Doctrine_Core::ATTR_EXPORT, Doctrine_Core::EXPORT_ALL); + + $this->assertTrue(Doctrine_Core::EXPORT_ALL & Doctrine_Core::EXPORT_TABLES); $this->assertTrue(Doctrine_Core::EXPORT_ALL & Doctrine_Core::EXPORT_CONSTRAINTS); $this->assertTrue(Doctrine_Core::EXPORT_ALL & Doctrine_Core::EXPORT_PLUGINS); @@ -61,7 +67,7 @@ public function testTranslationTableGetsExported() public function testTranslatedColumnsAreRemovedFromMainComponent() { $i = new I18nTest(); - + $columns = $i->getTable()->getColumns(); $this->assertFalse(isset($columns['title'])); @@ -77,7 +83,6 @@ public function testTranslationTableIsInitializedProperly() $i->Translation['EN']->title = 'some title'; $this->assertEqual($i->Translation->getTable()->getComponentName(), 'I18nTestTranslation'); - $i->Translation['FI']->name = 'joku nimi'; $i->Translation['FI']->title = 'joku otsikko'; $i->Translation['FI']->lang = 'FI'; @@ -91,10 +96,8 @@ public function testTranslationTableIsInitializedProperly() $this->assertEqual($t->name, 'some name'); $this->assertEqual($t->title, 'some title'); $this->assertEqual($t->lang, 'EN'); - } - public function testUpdatingI18nItems() { $i = Doctrine_Query::create()->query('FROM I18nTest')->getFirst(); @@ -112,7 +115,6 @@ public function testUpdatingI18nItems() $this->assertEqual($t->title, 'updated title'); } - public function testDataFetching() { $i = Doctrine_Query::create()->from('I18nTest i')->innerJoin('i.Translation t INDEXBY t.lang')->orderby('t.lang')->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY); @@ -125,13 +127,13 @@ public function testDataFetching() $this->assertEqual($i['Translation']['FI']['title'], 'joku otsikko'); $this->assertEqual($i['Translation']['FI']['lang'], 'FI'); } - + public function testIndexByLangIsAttachedToNewlyCreatedCollections() { - $coll = new Doctrine_Collection('I18nTestTranslation'); + $coll = new Doctrine_Collection('I18nTestTranslation'); $coll['EN']['name'] = 'some name'; - + $this->assertEqual($coll['EN']->lang, 'EN'); } @@ -141,4 +143,4 @@ public function testIndexByLangIsAttachedToFetchedCollections() $this->assertTrue($coll['FI']->exists()); } -} \ No newline at end of file +} diff --git a/tests/Import/BuilderTestCase.php b/tests/Import/BuilderTestCase.php index 7415c0911..bed386fe2 100644 --- a/tests/Import/BuilderTestCase.php +++ b/tests/Import/BuilderTestCase.php @@ -20,21 +20,27 @@ */ /** - * Doctrine_Import_Builder_TestCase + * Doctrine_Import_Builder_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Import_Builder_TestCase extends Doctrine_UnitTestCase +class Doctrine_Import_Builder_TestCase extends Doctrine_UnitTestCase { public function testInheritanceGeneration() { - $path = dirname(__FILE__) . '/import_builder_test'; + $path = dirname(__FILE__).'/import_builder_test'; $import = new Doctrine_Import_Schema(); $import->setOption('generateTableClasses', true); @@ -55,10 +61,10 @@ public function testInheritanceGeneration() $this->assertTrue($schemaTestInheritanceParent->isSubclassOf('PackageSchemaTestInheritanceParent')); $this->assertTrue($schemaTestInheritanceChild1->isSubclassOf('BaseSchemaTestInheritanceChild1')); $this->assertTrue($schemaTestInheritanceChild2->isSubclassOf('BaseSchemaTestInheritanceChild2')); - + $this->assertTrue($schemaTestInheritanceChild1->isSubclassOf('SchemaTestInheritanceParent')); $this->assertTrue($schemaTestInheritanceChild1->isSubclassOf('BaseSchemaTestInheritanceParent')); - + $this->assertTrue($schemaTestInheritanceChild2->isSubclassOf('SchemaTestInheritanceParent')); $this->assertTrue($schemaTestInheritanceChild2->isSubclassOf('BaseSchemaTestInheritanceParent')); $this->assertTrue($schemaTestInheritanceChild2->isSubclassOf('SchemaTestInheritanceChild1')); @@ -74,22 +80,22 @@ public function testInheritanceGeneration() $this->assertTrue($schemaTestInheritanceChild2Table->isSubclassOf('SchemaTestInheritanceChild1Table')); $this->assertTrue($schemaTestInheritanceChild2Table->isSubclassOf('PackageSchemaTestInheritanceChild1Table')); - # Simple Inheritance + // Simple Inheritance $schemaTestSimpleInheritanceParent = new ReflectionClass('SchemaTestSimpleInheritanceParent'); $schemaTestSimpleInheritanceChild = new ReflectionClass('SchemaTestSimpleInheritanceChild'); $this->assertTrue($schemaTestSimpleInheritanceParent->hasMethod('setTableDefinition')); $this->assertTrue($schemaTestSimpleInheritanceChild->isSubclassOf('SchemaTestSimpleInheritanceParent')); - # Class Table Inheritance + // Class Table Inheritance $schemaTestClassTableInheritanceParent = new ReflectionClass('SchemaTestClassTableInheritanceParent'); $schemaTestClassTableInheritanceChild = new ReflectionClass('SchemaTestClassTableInheritanceChild'); - # Concrete Inheritance + // Concrete Inheritance $schemaTestConcreteInheritanceParent = new ReflectionClass('SchemaTestConcreteInheritanceParent'); $schemaTestConcreteInheritanceChild = new ReflectionClass('SchemaTestConcreteInheritanceChild'); - # Column Aggregation Inheritance + // Column Aggregation Inheritance $schemaTestColumnAggregationInheritanceParent = new ReflectionClass('SchemaTestColumnAggregationInheritanceParent'); $schemaTestColumnAggregationInheritanceChild = new ReflectionClass('SchemaTestColumnAggregationInheritanceChild'); @@ -122,4 +128,4 @@ public function testBaseTableClass() $class = $builder->buildTableClassDefinition('MyTestTable', array('className' => 'MyTest')); $this->assertTrue(strpos($class, 'class MyTestTable extends MyBaseTable')); } -} \ No newline at end of file +} diff --git a/tests/Import/MssqlTestCase.php b/tests/Import/MssqlTestCase.php index 4871406df..c6f03cd5b 100644 --- a/tests/Import/MssqlTestCase.php +++ b/tests/Import/MssqlTestCase.php @@ -20,53 +20,64 @@ */ /** - * Doctrine_Import_Mssql_TestCase + * Doctrine_Import_Mssql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Import_Mssql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Import_Mssql_TestCase extends Doctrine_UnitTestCase { - public function testListSequencesExecutesSql() + public function testListSequencesExecutesSql() { $this->import->listSequences('table'); - + $this->assertEqual($this->adapter->pop(), "SELECT name FROM sysobjects WHERE xtype = 'U'"); } + public function testListTableColumnsExecutesSql() { $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); $this->import->listTableColumns('table'); - - $this->assertEqual($this->adapter->pop(), "EXEC sp_columns @table_name = table"); + + $this->assertEqual($this->adapter->pop(), 'EXEC sp_columns @table_name = table'); } + public function testListTablesExecutesSql() { $this->import->listTables(); - + $this->assertEqual($this->adapter->pop(), "SELECT name FROM sysobjects WHERE type = 'U' AND name <> 'dtproperties' AND name <> 'sysdiagrams' ORDER BY name"); } + public function testListTriggersExecutesSql() { $this->import->listTriggers(); - + $this->assertEqual($this->adapter->pop(), "SELECT name FROM sysobjects WHERE xtype = 'TR'"); } + public function testListTableTriggersExecutesSql() { $this->import->listTableTriggers('table'); - + $this->assertEqual($this->adapter->pop(), "SELECT name FROM sysobjects WHERE xtype = 'TR' AND object_name(parent_obj) = 'table'"); } + public function testListViewsExecutesSql() { $this->import->listViews(); - + $this->assertEqual($this->adapter->pop(), "SELECT name FROM sysobjects WHERE xtype = 'V'"); } } diff --git a/tests/Import/MysqlTestCase.php b/tests/Import/MysqlTestCase.php index 8e94e09eb..8831c8184 100644 --- a/tests/Import/MysqlTestCase.php +++ b/tests/Import/MysqlTestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_Import_Mysql_TestCase + * Doctrine_Import_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Import_Mysql_TestCase extends Doctrine_UnitTestCase { +class Doctrine_Import_Mysql_TestCase extends Doctrine_UnitTestCase +{ } diff --git a/tests/Import/OracleTestCase.php b/tests/Import/OracleTestCase.php index 413d73ccb..6d7a43e2b 100644 --- a/tests/Import/OracleTestCase.php +++ b/tests/Import/OracleTestCase.php @@ -20,26 +20,33 @@ */ /** - * Doctrine_Import_Oracle_TestCase + * Doctrine_Import_Oracle_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Import_Oracle_TestCase extends Doctrine_UnitTestCase +class Doctrine_Import_Oracle_TestCase extends Doctrine_UnitTestCase { public function testListSequencesExecutesSql() { $this->conn->setAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE, true); $this->import->listSequences('table'); - - $this->assertEqual($this->adapter->pop(), "SELECT sequence_name FROM sys.user_sequences"); + + $this->assertEqual($this->adapter->pop(), 'SELECT sequence_name FROM sys.user_sequences'); } + public function testListTableColumnsExecutesSql() { $this->import->listTableColumns('table'); @@ -57,57 +64,64 @@ public function testListTableColumnsExecutesSql() $this->assertEqual($this->adapter->pop(), $q); } + public function testListTableIndexesExecutesSql() { $this->import->listTableIndexes('table'); $q = 'SELECT index_name name FROM user_indexes' - . " WHERE table_name = 'table' OR table_name = 'TABLE'" - . " AND generated = 'N'"; + ." WHERE table_name = 'table' OR table_name = 'TABLE'" + ." AND generated = 'N'"; $this->assertEqual($this->adapter->pop(), $q); } + public function testListTablesExecutesSql() { $this->import->listTables(); - + $q = "SELECT * FROM user_objects WHERE object_type = 'TABLE' and object_name in (select table_name from user_tables)"; $this->assertEqual($this->adapter->pop(), $q); } + public function testListDatabasesExecutesSql() { $this->import->listDatabases(); - + $q = 'SELECT username FROM sys.user_users'; $this->assertEqual($this->adapter->pop(), $q); } + public function testListUsersExecutesSql() { $this->import->listUsers(); - + $q = 'SELECT username FROM sys.all_users'; $this->assertEqual($this->adapter->pop(), $q); } + public function testListViewsExecutesSql() { $this->import->listViews(); - + $q = 'SELECT view_name FROM sys.user_views'; $this->assertEqual($this->adapter->pop(), $q); } + public function testListFunctionsExecutesSql() { $this->import->listFunctions(); - + $q = "SELECT name FROM sys.user_source WHERE line = 1 AND type = 'FUNCTION'"; $this->assertEqual($this->adapter->pop(), $q); } + public function testListTableConstraintsExecutesSql() { $this->import->listTableConstraints('table'); - - $q = "SELECT index_name name FROM user_constraints" - . " WHERE table_name = 'table' OR table_name = 'TABLE'"; + + $q = 'SELECT index_name name FROM user_constraints' + ." WHERE table_name = 'table' OR table_name = 'TABLE'"; $this->assertEqual($this->adapter->pop(), $q); } diff --git a/tests/Import/PgsqlTestCase.php b/tests/Import/PgsqlTestCase.php index f2e1eff3d..dc617502b 100644 --- a/tests/Import/PgsqlTestCase.php +++ b/tests/Import/PgsqlTestCase.php @@ -20,22 +20,28 @@ */ /** - * Doctrine_Import_Pgsql_TestCase + * Doctrine_Import_Pgsql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Import_Pgsql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Import_Pgsql_TestCase extends Doctrine_UnitTestCase { - public function testListSequencesExecutesSql() + public function testListSequencesExecutesSql() { $this->import->listSequences('table'); - + $this->assertEqual($this->adapter->pop(), "SELECT regexp_replace(relname, '_seq$', '') FROM @@ -44,10 +50,11 @@ public function testListSequencesExecutesSql() (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')"); } + public function testListTableColumnsExecutesSql() { $this->import->listTableColumns('table'); - + $this->assertEqual($this->adapter->pop(), "SELECT ordinal_position as attnum, column_name as field, @@ -68,10 +75,11 @@ public function testListTableColumnsExecutesSql() WHERE table_name = 'table' ORDER BY ordinal_position"); } + public function testListTableIndexesExecutesSql() { $this->import->listTableIndexes('table'); - + $this->assertEqual($this->adapter->pop(), "SELECT relname FROM @@ -85,10 +93,11 @@ public function testListTableIndexesExecutesSql() AND indisprimary != 't' )"); } + public function testListTablesExecutesSql() { $this->import->listTables(); - + $q = "SELECT c.relname AS table_name FROM pg_class c, pg_user u @@ -105,31 +114,35 @@ public function testListTablesExecutesSql() AND c.relname !~ '^pg_'"; $this->assertEqual($this->adapter->pop(), $q); } + public function testListDatabasesExecutesSql() { $this->import->listDatabases(); - + $q = 'SELECT datname FROM pg_database'; $this->assertEqual($this->adapter->pop(), $q); } + public function testListUsersExecutesSql() { $this->import->listUsers(); - + $q = 'SELECT usename FROM pg_user'; $this->assertEqual($this->adapter->pop(), $q); } + public function testListViewsExecutesSql() { $this->import->listViews(); - + $q = 'SELECT viewname FROM pg_views'; $this->assertEqual($this->adapter->pop(), $q); } + public function testListFunctionsExecutesSql() { $this->import->listFunctions(); - + $q = "SELECT proname FROM @@ -144,11 +157,11 @@ public function testListFunctionsExecutesSql() WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema'"; $this->assertEqual($this->adapter->pop(), $q); } + public function testListTableConstraintsExecutesSql() { $this->import->listTableConstraints('table'); - $q = "SELECT relname FROM diff --git a/tests/Import/PluginHierarchyTestCase.php b/tests/Import/PluginHierarchyTestCase.php index 6082cbcc4..4bc736957 100644 --- a/tests/Import/PluginHierarchyTestCase.php +++ b/tests/Import/PluginHierarchyTestCase.php @@ -20,23 +20,27 @@ */ /** - * Doctrine_Import_PluginHierarchy_TestCase + * Doctrine_Import_PluginHierarchy_TestCase. * - * @package Doctrine - * @subpackage Doctrine_Import_Builder * @author Brice Figureau * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Import_PluginHierarchy_TestCase extends Doctrine_UnitTestCase { - public function testImportOfHieriarchyOfPluginGeneration() { - $yml = <<setOption('generateTableClasses', true); @@ -75,12 +79,12 @@ public function testImportOfHieriarchyOfPluginGeneration() 3 => 'CREATE TABLE wiki_test (id INTEGER PRIMARY KEY AUTOINCREMENT)', 4 => 'CREATE UNIQUE INDEX wiki_test_translation_sluggable_idx ON wiki_test_translation (slug)', ); - - foreach($sql as $idx => $req) { + + foreach ($sql as $idx => $req) { $this->assertEqual($req, $result[$idx]); - } - + } + Doctrine_Lib::removeDirectories($path); unlink('wiki.yml'); } -} \ No newline at end of file +} diff --git a/tests/Import/SchemaTestCase.php b/tests/Import/SchemaTestCase.php index a480499db..e889c7894 100644 --- a/tests/Import/SchemaTestCase.php +++ b/tests/Import/SchemaTestCase.php @@ -20,33 +20,39 @@ */ /** - * Doctrine_Import_Schema_TestCase + * Doctrine_Import_Schema_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Import_Schema_TestCase extends Doctrine_UnitTestCase +class Doctrine_Import_Schema_TestCase extends Doctrine_UnitTestCase { public $buildSchema; public $schema; - + public function testYmlImport() { - $path = dirname(__FILE__) . '/import_builder_test'; - + $path = dirname(__FILE__).'/import_builder_test'; + $import = new Doctrine_Import_Schema(); $import->importSchema('schema.yml', 'yml', $path); - - if ( ! file_exists($path . '/SchemaTestUser.php')) { + + if (!file_exists($path.'/SchemaTestUser.php')) { $this->fail(); } - - if ( ! file_exists($path . '/SchemaTestProfile.php')) { + + if (!file_exists($path.'/SchemaTestProfile.php')) { $this->fail(); } @@ -54,12 +60,12 @@ public function testYmlImport() Doctrine_Lib::removeDirectories($path); } - + public function testBuildSchema() { $schema = new Doctrine_Import_Schema(); $array = $schema->buildSchema('schema.yml', 'yml'); - + $model = $array['SchemaTestUser']; $this->assertTrue(array_key_exists('connection', $model)); @@ -77,37 +83,37 @@ public function testBuildSchema() $this->assertTrue(array_key_exists('detect_relations', $model) && is_bool($model['detect_relations'])); $this->assertEqual($array['AliasTest']['columns']['test_col']['name'], 'test_col as test_col_alias'); } - + public function testSchemaRelationshipCompletion() { $this->buildSchema = new Doctrine_Import_Schema(); $this->schema = $this->buildSchema->buildSchema('schema.yml', 'yml'); - + foreach ($this->schema as $name => $properties) { foreach ($properties['relations'] as $alias => $relation) { - if ( ! $this->_verifyMultiDirectionalRelationship($name, $alias, $relation)) { + if (!$this->_verifyMultiDirectionalRelationship($name, $alias, $relation)) { $this->fail(); - + return false; } } } - + $this->pass(); } - + protected function _verifyMultiDirectionalRelationship($class, $relationAlias, $relation) { $foreignClass = $relation['class']; - $foreignAlias = isset($relation['foreignAlias']) ? $relation['foreignAlias']:$class; - + $foreignAlias = isset($relation['foreignAlias']) ? $relation['foreignAlias'] : $class; + $foreignClassRelations = $this->schema[$foreignClass]['relations']; - + // Check to see if the foreign class has the opposite end defined for the class/foreignAlias if (isset($foreignClassRelations[$foreignAlias])) { return true; - } else { - return false; } + + return false; } -} \ No newline at end of file +} diff --git a/tests/Import/SqliteTestCase.php b/tests/Import/SqliteTestCase.php index 812d3f41f..3231418fb 100644 --- a/tests/Import/SqliteTestCase.php +++ b/tests/Import/SqliteTestCase.php @@ -20,40 +20,49 @@ */ /** - * Doctrine_Import_Sqlite_TestCase + * Doctrine_Import_Sqlite_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Import_Sqlite_TestCase extends Doctrine_UnitTestCase +class Doctrine_Import_Sqlite_TestCase extends Doctrine_UnitTestCase { - public function testListSequencesExecutesSql() + public function testListSequencesExecutesSql() { $this->import->listSequences('table'); - + $this->assertEqual($this->adapter->pop(), "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"); } + public function testListTableColumnsExecutesSql() { $this->import->listTableColumns('table'); - - $this->assertEqual($this->adapter->pop(), "PRAGMA table_info(table)"); + + $this->assertEqual($this->adapter->pop(), 'PRAGMA table_info(table)'); } + public function testListTableIndexesExecutesSql() { $this->import->listTableIndexes('table'); - - $this->assertEqual($this->adapter->pop(), "PRAGMA index_list(table)"); + + $this->assertEqual($this->adapter->pop(), 'PRAGMA index_list(table)'); } + public function testListTablesExecutesSql() { $this->import->listTables(); - + $q = "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' UNION ALL SELECT name FROM sqlite_temp_master WHERE type = 'table' ORDER BY name"; $this->assertEqual($this->adapter->pop(), $q); diff --git a/tests/ImportTestCase.php b/tests/ImportTestCase.php index 8d062a252..a66ecc24b 100644 --- a/tests/ImportTestCase.php +++ b/tests/ImportTestCase.php @@ -20,22 +20,31 @@ */ /** - * Doctrine_Import_TestCase + * Doctrine_Import_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Import_TestCase extends Doctrine_UnitTestCase +class Doctrine_Import_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { } - public function prepareData() - { } + public function prepareTables() + { + } + + public function prepareData() + { + } public function testImport() { @@ -51,4 +60,4 @@ public function testImport() $this->assertTrue(file_exists('Import/_files/generated/BaseImportTestUser.php')); Doctrine_Lib::removeDirectories('Import/_files'); } -} \ No newline at end of file +} diff --git a/tests/IntegrityActionTestCase.php b/tests/IntegrityActionTestCase.php index 5eb5880b7..8b0f042ab 100644 --- a/tests/IntegrityActionTestCase.php +++ b/tests/IntegrityActionTestCase.php @@ -20,52 +20,62 @@ */ /** - * Doctrine_IntegrityAction_TestCase + * Doctrine_IntegrityAction_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_IntegrityAction_TestCase extends Doctrine_UnitTestCase +class Doctrine_IntegrityAction_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() { $this->tables = array('CascadeDeleteTest', 'CascadeDeleteRelatedTest', 'CascadeDeleteRelatedTest2'); - + parent::prepareTables(); } + public function testIntegrityActionsAreAddedIntoGlobalActionsArray() { - $c = new CascadeDeleteTest; - $c2 = new CascadeDeleteRelatedTest; + $c = new CascadeDeleteTest(); + $c2 = new CascadeDeleteRelatedTest(); $expected = array('CascadeDeleteRelatedTest' => 'CASCADE'); $this->assertEqual($this->manager->getDeleteActions('CascadeDeleteTest'), $expected); - + $expected = array('CascadeDeleteRelatedTest' => 'SET NULL'); $this->assertEqual($this->manager->getUpdateActions('CascadeDeleteTest'), $expected); } + public function testOnDeleteCascadeEmulation() { - $c = new CascadeDeleteTest; + $c = new CascadeDeleteTest(); $c->name = 'c 1'; $c->Related[]->name = 'r 1'; $c->Related[]->name = 'r 2'; $c->Related[0]->Related[]->name = 'r r 1'; $c->Related[1]->Related[]->name = 'r r 2'; - + $c->save(); - + $this->connection->clear(); - + $c = $this->conn->queryOne('FROM CascadeDeleteTest c WHERE c.id = 1'); - + $c->delete(); } } diff --git a/tests/ManagerTestCase.php b/tests/ManagerTestCase.php index 752ce6a3f..8d3ed45f1 100644 --- a/tests/ManagerTestCase.php +++ b/tests/ManagerTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Manager_TestCase + * Doctrine_Manager_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Manager_TestCase extends Doctrine_UnitTestCase { @@ -38,89 +44,101 @@ class Doctrine_Manager_TestCase extends Doctrine_UnitTestCase protected $conn1; protected $conn2; - public function testGetInstance() { - $this->assertTrue(Doctrine_Manager::getInstance() instanceOf Doctrine_Manager); + public function testGetInstance() + { + $this->assertTrue(Doctrine_Manager::getInstance() instanceof Doctrine_Manager); } - public function testOpenConnection() { - $this->assertTrue($this->connection instanceOf Doctrine_Connection); + + public function testOpenConnection() + { + $this->assertTrue($this->connection instanceof Doctrine_Connection); } - public function testGetIterator() { + + public function testGetIterator() + { $this->assertTrue($this->manager->getIterator() instanceof ArrayIterator); } - public function testCount() { + + public function testCount() + { $this->assertTrue(is_integer(count($this->manager))); } - public function testGetCurrentConnection() { + + public function testGetCurrentConnection() + { $this->assertTrue($this->manager->getCurrentConnection() === $this->connection); } - public function testGetConnections() { + + public function testGetConnections() + { $this->assertTrue(is_integer(count($this->manager->getConnections()))); } - public function testClassifyTableize() { - $name = "Forum_Category"; - $this->assertEqual(Doctrine_Inflector::tableize($name), "forum__category"); + + public function testClassifyTableize() + { + $name = 'Forum_Category'; + $this->assertEqual(Doctrine_Inflector::tableize($name), 'forum__category'); $this->assertEqual(Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)), $name); - - } + public function testDsnParser() { $mysql = 'mysql://user:pass@localhost/dbname'; $sqlite = 'sqlite:////full/unix/path/to/file.db'; $sqlitewin = 'sqlite:///c:/full/windows/path/to/file.db'; $sqlitewin2 = 'sqlite:///D:\full\windows\path\to\file.db'; - + $manager = Doctrine_Manager::getInstance(); - + try { $res = $manager->parseDsn($mysql); $expectedMysqlDsn = array( - "scheme" => "mysql", - "host" => "localhost", - "user" => "user", - "pass" => "pass", - "path" => "/dbname", - "dsn" => "mysql:host=localhost;dbname=dbname", - "port" => NULL, - "query" => NULL, - "fragment" => NULL, - "database" => "dbname"); + 'scheme' => 'mysql', + 'host' => 'localhost', + 'user' => 'user', + 'pass' => 'pass', + 'path' => '/dbname', + 'dsn' => 'mysql:host=localhost;dbname=dbname', + 'port' => null, + 'query' => null, + 'fragment' => null, + 'database' => 'dbname'); $this->assertEqual($expectedMysqlDsn, $res); } catch (Exception $e) { $this->fail($e->getMessage()); } - + try { $expectedDsn = array( - "scheme" => "sqlite", - "host" => NULL, - "user" => NULL, - "pass" => NULL, - "path" => "/full/unix/path/to/file.db", - "dsn" => "sqlite:/full/unix/path/to/file.db", - "port" => NULL, - "query" => NULL, - "fragment" => NULL, - "database" => "/full/unix/path/to/file.db"); - + 'scheme' => 'sqlite', + 'host' => null, + 'user' => null, + 'pass' => null, + 'path' => '/full/unix/path/to/file.db', + 'dsn' => 'sqlite:/full/unix/path/to/file.db', + 'port' => null, + 'query' => null, + 'fragment' => null, + 'database' => '/full/unix/path/to/file.db'); + $res = $manager->parseDsn($sqlite); $this->assertEqual($expectedDsn, $res); } catch (Exception $e) { $this->fail($e->getMessage()); } - + try { - $expectedDsn = array( - "scheme" => "sqlite", - "host" => NULL, - "path" => "c:/full/windows/path/to/file.db", - "dsn" => "sqlite:c:/full/windows/path/to/file.db", - "port" => NULL, - "user" => NULL, - "pass" => NULL, - "query" => NULL, - "fragment" => NULL, - "database" => "c:/full/windows/path/to/file.db"); + $expectedDsn = array( + 'scheme' => 'sqlite', + 'host' => null, + 'path' => 'c:/full/windows/path/to/file.db', + 'dsn' => 'sqlite:c:/full/windows/path/to/file.db', + 'port' => null, + 'user' => null, + 'pass' => null, + 'query' => null, + 'fragment' => null, + 'database' => 'c:/full/windows/path/to/file.db'); $res = $manager->parseDsn($sqlitewin); $this->assertEqual($expectedDsn, $res); } catch (Exception $e) { @@ -128,61 +146,66 @@ public function testDsnParser() } try { - $expectedDsn = array( - "scheme" => "sqlite", - "host" => NULL, - "path" => 'D:/full/windows/path/to/file.db', - "dsn" => 'sqlite:D:/full/windows/path/to/file.db', - "port" => NULL, - "user" => NULL, - "pass" => NULL, - "query" => NULL, - "fragment" => NULL, - "database" => 'D:/full/windows/path/to/file.db'); + $expectedDsn = array( + 'scheme' => 'sqlite', + 'host' => null, + 'path' => 'D:/full/windows/path/to/file.db', + 'dsn' => 'sqlite:D:/full/windows/path/to/file.db', + 'port' => null, + 'user' => null, + 'pass' => null, + 'query' => null, + 'fragment' => null, + 'database' => 'D:/full/windows/path/to/file.db'); $res = $manager->parseDsn($sqlitewin2); $this->assertEqual($expectedDsn, $res); } catch (Exception $e) { $this->fail($e->getMessage()); } } - + public function testCreateDatabases() { - // We need to know if we're under Windows or *NIX - $OS = strtoupper(substr(PHP_OS, 0,3)); + // We need to know if we're under Windows or *NIX + $OS = strtoupper(substr(PHP_OS, 0, 3)); - $tmp_dir = ($OS == 'WIN') ? str_replace('\\','/',sys_get_temp_dir()) : '/tmp'; - - $this->conn1_database = $tmp_dir . "/doctrine1.db"; - $this->conn2_database = $tmp_dir . "/doctrine2.db"; + $tmp_dir = ('WIN' == $OS) ? str_replace('\\', '/', sys_get_temp_dir()) : '/tmp'; + + $this->conn1_database = $tmp_dir.'/doctrine1.db'; + $this->conn2_database = $tmp_dir.'/doctrine2.db'; + + $this->conn1 = Doctrine_Manager::connection('sqlite:///'.$this->conn1_database, 'doctrine1'); + $this->conn2 = Doctrine_Manager::connection('sqlite:///'.$this->conn2_database, 'doctrine2'); - $this->conn1 = Doctrine_Manager::connection('sqlite:///' . $this->conn1_database, 'doctrine1'); - $this->conn2 = Doctrine_Manager::connection('sqlite:///' . $this->conn2_database, 'doctrine2'); - $result1 = $this->conn1->createDatabase(); $result2 = $this->conn2->createDatabase(); } - + public function testDropDatabases() { $result1 = $this->conn1->dropDatabase(); $result2 = $this->conn2->dropDatabase(); } - + public function testConnectionInformationDecoded() { - $dsn = 'mysql://' . urlencode('test/t') . ':' . urlencode('p@ssword') . '@localhost/' . urlencode('db/name'); + $dsn = 'mysql://'.urlencode('test/t').':'.urlencode('p@ssword').'@localhost/'.urlencode('db/name'); - $conn = $this->openAdditionalConnection($dsn); - $options = $conn->getOptions(); + $conn = $this->openAdditionalConnection($dsn); + $options = $conn->getOptions(); - $this->assertEqual($options['username'], 'test/t'); - $this->assertEqual($options['password'], 'p@ssword'); - $this->assertEqual($options['dsn'], 'mysql:host=localhost;dbname=db/name'); + $this->assertEqual($options['username'], 'test/t'); + $this->assertEqual($options['password'], 'p@ssword'); + $this->assertEqual($options['dsn'], 'mysql:host=localhost;dbname=db/name'); } - public function prepareData() { } - public function prepareTables() { } + public function prepareData() + { + } + + public function prepareTables() + { + } public function testGetConnectionDrivers() { diff --git a/tests/Migration/BaseTestCase.php b/tests/Migration/BaseTestCase.php index 3a889b0b6..5967369c8 100644 --- a/tests/Migration/BaseTestCase.php +++ b/tests/Migration/BaseTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Migration_Base_TestCase - * - * @package Doctrine + * Doctrine_Migration_Base_TestCase. + * * @author Dan Bettles * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Migration_Base_TestCase extends UnitTestCase { diff --git a/tests/Migration/DiffTestCase.php b/tests/Migration/DiffTestCase.php index 7a05d7c1d..d573988ba 100644 --- a/tests/Migration/DiffTestCase.php +++ b/tests/Migration/DiffTestCase.php @@ -20,23 +20,29 @@ */ /** - * Doctrine_Migration_Diff_TestCase + * Doctrine_Migration_Diff_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Migration_Diff_TestCase extends Doctrine_UnitTestCase +class Doctrine_Migration_Diff_TestCase extends Doctrine_UnitTestCase { public function testTest() { - $from = dirname(__FILE__) . '/Diff/schema/from.yml'; - $to = dirname(__FILE__) . '/Diff/schema/to.yml'; - $migrationsPath = dirname(__FILE__) . '/Diff/migrations'; + $from = dirname(__FILE__).'/Diff/schema/from.yml'; + $to = dirname(__FILE__).'/Diff/schema/to.yml'; + $migrationsPath = dirname(__FILE__).'/Diff/migrations'; Doctrine_Lib::makeDirectories($migrationsPath); $diff = new Doctrine_Migration_Diff($from, $to, $migrationsPath); @@ -56,11 +62,11 @@ public function testTest() $this->assertEqual($changes['dropped_indexes']['user']['is_active'], array('fields' => array('is_active'))); $diff->generateMigrationClasses(); - $files = glob($migrationsPath . '/*.php'); + $files = glob($migrationsPath.'/*.php'); $this->assertEqual(count($files), 2); $this->assertTrue(strpos($files[0], '_version1.php')); $this->assertTrue(strpos($files[1], '_version2.php')); - + $code1 = file_get_contents($files[0]); $this->assertTrue(strpos($code1, 'this->dropTable')); $this->assertTrue(strpos($code1, 'this->createTable')); @@ -76,4 +82,4 @@ public function testTest() Doctrine_Lib::removeDirectories($migrationsPath); } -} \ No newline at end of file +} diff --git a/tests/MigrationTestCase.php b/tests/MigrationTestCase.php index 59b2b336c..34fbd53db 100644 --- a/tests/MigrationTestCase.php +++ b/tests/MigrationTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Migration_TestCase + * Doctrine_Migration_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Migration_TestCase extends Doctrine_UnitTestCase { @@ -73,17 +79,17 @@ public function testMigration() $this->assertFalse($this->conn->import->tableExists('migration_user')); $this->assertFalse($this->conn->import->tableExists('migration_profile')); $this->assertEqual(array( - 1 => 'AddPhonenumber', - 2 => 'AddUser', - 3 => 'AddProfile', - 4 => 'DropProfile', - 5 => 'Test5', - 6 => 'Test6', - 7 => 'Test7', - 8 => 'Test8', - 9 => 'Test9', - 10 => 'Test10', - 11 => 'Test11', + 1 => 'AddPhonenumber', + 2 => 'AddUser', + 3 => 'AddProfile', + 4 => 'DropProfile', + 5 => 'Test5', + 6 => 'Test6', + 7 => 'Test7', + 8 => 'Test8', + 9 => 'Test9', + 10 => 'Test10', + 11 => 'Test11', ), $migration->getMigrationClasses()); } @@ -113,12 +119,12 @@ public function testMigrateClearsErrors() public function testMigrationClassNameInflected() { $tests = array('test-class-Name', - 'test_class_name', - 'test:class:name', - 'test(class)name', - 'test*class*name', - 'test class name', - 'test&class&name'); + 'test_class_name', + 'test:class:name', + 'test(class)name', + 'test*class*name', + 'test class name', + 'test&class&name'); $builder = new Doctrine_Migration_Builder(); diff --git a/tests/ModelLoadingTest/Aggressive/Models.php b/tests/ModelLoadingTest/Aggressive/Models.php index 8205faae8..d35ec0c7e 100644 --- a/tests/ModelLoadingTest/Aggressive/Models.php +++ b/tests/ModelLoadingTest/Aggressive/Models.php @@ -1,9 +1,9 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_NestedSet_Hydration_TestCase extends Doctrine_UnitTestCase { @@ -44,11 +50,11 @@ public function prepareData() $node->name = 'root'; $treeMngr = $this->conn->getTable('NestedSetTest_SingleRootNode')->getTree(); $treeMngr->createRoot($node); - + $node2 = new NestedSetTest_SingleRootNode(); $node2->name = 'node2'; $node2->getNode()->insertAsLastChildOf($node); - + $node3 = new NestedSetTest_SingleRootNode(); $node3->name = 'node3'; $node3->getNode()->insertAsLastChildOf($node2); @@ -58,7 +64,8 @@ public function testRecordHierarchyHydration() { $results = Doctrine_Core::getTable('NestedSetTest_SingleRootNode') ->createQuery('n') - ->execute(array(), Doctrine_Core::HYDRATE_RECORD_HIERARCHY); + ->execute(array(), Doctrine_Core::HYDRATE_RECORD_HIERARCHY) + ; $this->assertEqual($results[0]['__children'][0]['__children'][0]['name'], 'node3'); $this->assertTrue($results instanceof Doctrine_Collection); @@ -68,7 +75,8 @@ public function testArrayHierarchyHydration() { $results = Doctrine_Core::getTable('NestedSetTest_SingleRootNode') ->createQuery('n') - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY); + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY) + ; $this->assertEqual($results[0]['__children'][0]['__children'][0]['name'], 'node3'); $this->assertTrue(is_array($results)); @@ -78,11 +86,13 @@ public function testArrayHierarchyToArray() { $array = Doctrine_Core::getTable('NestedSetTest_SingleRootNode') ->createQuery('n') - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY); + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY) + ; $coll = Doctrine_Core::getTable('NestedSetTest_SingleRootNode') ->createQuery('n') - ->execute(array(), Doctrine_Core::HYDRATE_RECORD_HIERARCHY); + ->execute(array(), Doctrine_Core::HYDRATE_RECORD_HIERARCHY) + ; $this->assertEqual($array, $coll->toArray()); } @@ -92,7 +102,8 @@ public function testHierarchyHydrationNotAllowedOnInvalidModel() try { $results = Doctrine_Core::getTable('User') ->createQuery('u') - ->execute(array(), Doctrine_Core::HYDRATE_RECORD_HIERARCHY); + ->execute(array(), Doctrine_Core::HYDRATE_RECORD_HIERARCHY) + ; $this->fail(); } catch (Exception $e) { @@ -102,11 +113,12 @@ public function testHierarchyHydrationNotAllowedOnInvalidModel() try { $results = Doctrine_Core::getTable('User') ->createQuery('u') - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY); + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY_HIERARCHY) + ; $this->fail(); } catch (Exception $e) { $this->pass(); } } -} \ No newline at end of file +} diff --git a/tests/NestedSet/MultiRootTestCase.php b/tests/NestedSet/MultiRootTestCase.php index 265b8511c..8cb8b3970 100644 --- a/tests/NestedSet/MultiRootTestCase.php +++ b/tests/NestedSet/MultiRootTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Record_State_TestCase + * Doctrine_Record_State_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_NestedSet_MultiRoot_TestCase extends Doctrine_UnitTestCase { @@ -39,9 +45,11 @@ public function prepareTables() } public function prepareData() - {} - - public function testSavingNewRecordAsRootWithoutRootIdThrowsException() { + { + } + + public function testSavingNewRecordAsRootWithoutRootIdThrowsException() + { $node = new NestedSet_MultiRootNode(); $node->name = 'root'; try { @@ -52,8 +60,9 @@ public function testSavingNewRecordAsRootWithoutRootIdThrowsException() { $this->pass(); } } - - public function testSavingNewRecordWithRootIdWorks() { + + public function testSavingNewRecordWithRootIdWorks() + { $node = new NestedSet_MultiRootNode(); $node->name = 'root'; $node->root_id = 42; @@ -67,8 +76,9 @@ public function testSavingNewRecordWithRootIdWorks() { $this->fail(); } } - - public function testSavingPersistentRecordAsRootAssignsIdToRootId() { + + public function testSavingPersistentRecordAsRootAssignsIdToRootId() + { $node = new NestedSet_MultiRootNode(); $node->name = 'root'; $node->save(); @@ -83,8 +93,9 @@ public function testSavingPersistentRecordAsRootAssignsIdToRootId() { $this->fail(); } } - - public function testSaveMultipleRootsWithChildren() { + + public function testSaveMultipleRootsWithChildren() + { $root1 = new NestedSet_MultiRootNode(); $root1->name = 'root1'; $root1->save(); @@ -97,7 +108,7 @@ public function testSaveMultipleRootsWithChildren() { } catch (Doctrine_Tree_Exception $e) { $this->fail(); } - + $root2 = new NestedSet_MultiRootNode(); $root2->name = 'root'; $root2->save(); @@ -110,12 +121,12 @@ public function testSaveMultipleRootsWithChildren() { } catch (Doctrine_Tree_Exception $e) { $this->fail(); } - + // now a child for root1 $child1 = new NestedSet_MultiRootNode(); - $child1->name = "child1"; + $child1->name = 'child1'; $child1->getNode()->insertAsLastChildOf($root1); - + $root1->refresh(); // ! updates lft/rgt // test insertion $this->assertEqual(2, $child1->lft); @@ -125,12 +136,12 @@ public function testSaveMultipleRootsWithChildren() { $this->assertEqual(1, $root1->lft); $this->assertEqual(4, $root1->rgt); $this->assertEqual(0, $root1->level); - + // now a child for root2 $child2 = new NestedSet_MultiRootNode(); - $child2->name = "child2"; + $child2->name = 'child2'; $child2->getNode()->insertAsLastChildOf($root2); - + $root2->refresh(); // ! updates lft/rgt // test insertion $this->assertEqual(2, $child2->lft); @@ -140,7 +151,7 @@ public function testSaveMultipleRootsWithChildren() { $this->assertEqual(1, $root2->lft); $this->assertEqual(4, $root2->rgt); $this->assertEqual(0, $root2->level); - + // query some $root1Id = $root1->id; $root2Id = $root2->id; @@ -149,17 +160,16 @@ public function testSaveMultipleRootsWithChildren() { $treeMngr = $this->conn->getTable('NestedSet_MultiRootNode')->getTree(); $root1 = $treeMngr->fetchRoot($root1Id); $desc = $root1->getNode()->getDescendants(); - $this->assertTrue($desc !== false); + $this->assertTrue(false !== $desc); $this->assertEqual(1, count($desc)); $this->assertEqual('child1', $desc[0]['name']); $this->assertEqual(1, $desc[0]['level']); // check the root2 child $root2 = $treeMngr->fetchRoot($root2Id); $desc = $root2->getNode()->getDescendants(); - $this->assertTrue($desc !== false); + $this->assertTrue(false !== $desc); $this->assertEqual(1, count($desc)); $this->assertEqual('child2', $desc[0]['name']); $this->assertEqual(1, $desc[0]['level']); } - } diff --git a/tests/NestedSet/SingleRootTestCase.php b/tests/NestedSet/SingleRootTestCase.php index 7a449d454..3318824b6 100644 --- a/tests/NestedSet/SingleRootTestCase.php +++ b/tests/NestedSet/SingleRootTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Record_State_TestCase + * Doctrine_Record_State_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_NestedSet_SingleRoot_TestCase extends Doctrine_UnitTestCase { @@ -44,16 +50,16 @@ public function prepareData() $node->name = 'root'; $treeMngr = $this->conn->getTable('NestedSetTest_SingleRootNode')->getTree(); $treeMngr->createRoot($node); - + $node2 = new NestedSetTest_SingleRootNode(); $node2->name = 'node2'; $node2->getNode()->insertAsLastChildOf($node); - + $node3 = new NestedSetTest_SingleRootNode(); $node3->name = 'node3'; $node3->getNode()->insertAsLastChildOf($node2); } - + public function testLftRgtValues() { $treeMngr = $this->conn->getTable('NestedSetTest_SingleRootNode')->getTree(); @@ -67,7 +73,7 @@ public function testGetDescendants() $treeMngr = $this->conn->getTable('NestedSetTest_SingleRootNode')->getTree(); $root = $treeMngr->fetchRoot(); $desc = $root->getNode()->getDescendants(); - $this->assertTrue($desc !== false); + $this->assertTrue(false !== $desc); $this->assertEqual(2, count($desc)); $this->assertEqual('node2', $desc[0]['name']); $this->assertEqual(1, $desc[0]['level']); @@ -80,13 +86,13 @@ public function testGetNumberChildren() $this->assertEqual(1, $root->getNode()->getNumberChildren()); $this->assertFalse($root->getNode()->hasParent()); } - + public function testGetAncestors() { - $node = $this->conn->query("SELECT n.* FROM NestedSetTest_SingleRootNode n WHERE n.name = ?", - array('node2'))->getFirst(); + $node = $this->conn->query('SELECT n.* FROM NestedSetTest_SingleRootNode n WHERE n.name = ?', + array('node2'))->getFirst(); $anc = $node->getNode()->getAncestors(); - $this->assertTrue($anc !== false); + $this->assertTrue(false !== $anc); $this->assertEqual(1, count($anc)); $this->assertEqual('root', $anc[0]['name']); $this->assertEqual(0, $anc[0]['level']); diff --git a/tests/NestedSet/TimestampableMultiRootTestCase.php b/tests/NestedSet/TimestampableMultiRootTestCase.php index 20972a138..e243a11a8 100644 --- a/tests/NestedSet/TimestampableMultiRootTestCase.php +++ b/tests/NestedSet/TimestampableMultiRootTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Record_State_TestCase + * Doctrine_Record_State_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_NestedSet_TimestampableMultiRoot_TestCase extends Doctrine_UnitTestCase { @@ -39,11 +45,12 @@ public function prepareTables() } public function prepareData() - {} - - - public function testSavingNewRecordWithRootIdWorks() { - Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true ); + { + } + + public function testSavingNewRecordWithRootIdWorks() + { + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); $node = new NestedSet_Timestampable_MultiRootNode(); $node->name = 'root'; $node->root_id = 42; @@ -53,30 +60,29 @@ public function testSavingNewRecordWithRootIdWorks() { $node2 = new NestedSet_Timestampable_MultiRootNode(); $node2->name = 'node2'; $node2->root_id = 42; - //try { - $treeMngr = $this->conn->getTable('NestedSet_Timestampable_MultiRootNode')->getTree(); - $treeMngr->createRoot($node); - $this->assertEqual(1, $node['lft']); - $this->assertEqual(2, $node['rgt']); - $this->assertNotEqual(null, $node['created_at']); - $this->assertNotEqual(null, $node['updated_at']); - $child1->name = "child1"; - $child1->getNode()->insertAsLastChildOf($node); - - $node->refresh(); // ! updates lft/rgt - // test insertion - $this->assertEqual(2, $child1->lft); - $this->assertEqual(3, $child1->rgt); - $this->assertEqual(1, $child1->level); - // test node has been shifted - $this->assertEqual(1, $node->lft); - $this->assertEqual(4, $node->rgt); - $this->assertEqual(0, $node->level); - - $node->getNode()->delete(); - //} catch (Exception $e) { + // try { + $treeMngr = $this->conn->getTable('NestedSet_Timestampable_MultiRootNode')->getTree(); + $treeMngr->createRoot($node); + $this->assertEqual(1, $node['lft']); + $this->assertEqual(2, $node['rgt']); + $this->assertNotEqual(null, $node['created_at']); + $this->assertNotEqual(null, $node['updated_at']); + $child1->name = 'child1'; + $child1->getNode()->insertAsLastChildOf($node); + + $node->refresh(); // ! updates lft/rgt + // test insertion + $this->assertEqual(2, $child1->lft); + $this->assertEqual(3, $child1->rgt); + $this->assertEqual(1, $child1->level); + // test node has been shifted + $this->assertEqual(1, $node->lft); + $this->assertEqual(4, $node->rgt); + $this->assertEqual(0, $node->level); + + $node->getNode()->delete(); + // } catch (Exception $e) { // $this->fail(); - //} + // } } - } diff --git a/tests/NewCoreTestCase.php b/tests/NewCoreTestCase.php index f75bdecba..38372bb11 100644 --- a/tests/NewCoreTestCase.php +++ b/tests/NewCoreTestCase.php @@ -20,22 +20,28 @@ */ /** - * Doctrine_NewCore_TestCase + * Doctrine_NewCore_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_NewCore_TestCase extends Doctrine_UnitTestCase +class Doctrine_NewCore_TestCase extends Doctrine_UnitTestCase { public function testFromParser() { $q = new Doctrine_Query(); - + $q->load('User u', true); $this->assertEqual($q->getSqlQueryPart('from'), array('entity e')); diff --git a/tests/OneTableOneClassInheritanceTestCase.php b/tests/OneTableOneClassInheritanceTestCase.php index 0f193b0d0..aa2662fc6 100644 --- a/tests/OneTableOneClassInheritanceTestCase.php +++ b/tests/OneTableOneClassInheritanceTestCase.php @@ -20,26 +20,36 @@ */ /** - * Doctrine_OneTableOneClassInheritance_TestCase + * Doctrine_OneTableOneClassInheritance_TestCase. * - * @package Doctrine - * @author Bjarte Stien Karlsen + * @author Bjarte Stien Karlsen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_OneTableOneClassInheritance_TestCase extends Doctrine_UnitTestCase +class Doctrine_OneTableOneClassInheritance_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } - public function prepareTables() - { } + public function prepareData() + { + } + + public function prepareTables() + { + } + public function testTableExporting() { $sql = $this->conn->export->exportClassesSql(array('ConcreteInheritanceTestParent', - 'ConcreteInheritanceTestChild')); + 'ConcreteInheritanceTestChild')); $this->assertEqual($sql[0], 'CREATE TABLE concrete_inheritance_test_parent (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(2147483647))'); $this->assertEqual($sql[1], 'CREATE TABLE concrete_inheritance_test_child (id INTEGER PRIMARY KEY AUTOINCREMENT, age INTEGER, name VARCHAR(2147483647))'); } diff --git a/tests/ParserTestCase.php b/tests/ParserTestCase.php index 7f5e54862..309e26da8 100644 --- a/tests/ParserTestCase.php +++ b/tests/ParserTestCase.php @@ -20,38 +20,44 @@ */ /** - * Doctrine_Parser_TestCase + * Doctrine_Parser_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Parser_TestCase extends Doctrine_UnitTestCase +class Doctrine_Parser_TestCase extends Doctrine_UnitTestCase { public function testGetParserInstance() { $instance = Doctrine_Parser::getParser('Yml'); - + if ($instance instanceof Doctrine_Parser_Yml) { $this->pass(); } else { $this->fail(); } } - + public function testFacadeLoadAndDump() { Doctrine_Parser::dump(array('test' => 'good job', 'test2' => true, array('testing' => false)), 'yml', 'test.yml'); $array = Doctrine_Parser::load('test.yml', 'yml'); - + $this->assertEqual($array, array('test' => 'good job', 'test2' => true, array('testing' => false))); unlink('test.yml'); } - + public function testParserSupportsEmbeddingPhpSyntax() { $parser = Doctrine_Parser::getParser('Yml'); @@ -62,29 +68,29 @@ public function testParserSupportsEmbeddingPhpSyntax() w00t: not now "; $data = $parser->doLoad($yml); - + $array = $parser->loadData($data); - + $this->assertEqual($array, array('test' => 'good job', 'test2' => true, 'testing' => false, 'w00t' => 'not now')); } - + public function testParserWritingToDisk() { $parser = Doctrine_Parser::getParser('Yml'); $parser->doDump('test', 'test.yml'); - + $this->assertEqual('test', file_get_contents('test.yml')); unlink('test.yml'); } - + public function testParserReturningLoadedData() { $parser = Doctrine_Parser::getParser('Yml'); $result = $parser->doDump('test'); - + $this->assertEqual('test', $result); } - + public function testLoadFromString() { $yml = "--- @@ -95,7 +101,7 @@ public function testLoadFromString() "; $array = Doctrine_Parser::load($yml, 'yml'); - + $this->assertEqual($array, array('test' => 'good job', 'test2' => true, 'testing' => false, 'w00t' => 'not now')); } } diff --git a/tests/PessimisticLockingTestCase.php b/tests/PessimisticLockingTestCase.php index 306067b78..83e795a99 100644 --- a/tests/PessimisticLockingTestCase.php +++ b/tests/PessimisticLockingTestCase.php @@ -20,36 +20,42 @@ */ /** - * Doctrine_Boolean_TestCase + * Doctrine_Boolean_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_PessimisticLocking_TestCase extends Doctrine_UnitTestCase { private $lockingManager; /** - * Sets up everything for the lock testing + * Sets up everything for the lock testing. * * Creates a locking manager and a test record to work with. */ public function testInitData() { $this->lockingManager = new Doctrine_Locking_Manager_Pessimistic($this->connection); - + // Create sample data to test on $entry1 = new Forum_Entry(); $entry1->author = 'Bart Simpson'; - $entry1->topic = 'I love donuts!'; + $entry1->topic = 'I love donuts!'; $entry1->save(); } - + public function prepareTables() { $this->tables = array('Forum_Entry', 'Entity', 'Phonenumber', 'Email', 'Groupuser'); @@ -57,22 +63,22 @@ public function prepareTables() } /** - * Tests the basic locking mechanism - * - * Currently tested: successful lock, failed lock, release lock + * Tests the basic locking mechanism. + * + * Currently tested: successful lock, failed lock, release lock */ public function testLock() { $entries = $this->connection->query("FROM Forum_Entry WHERE Forum_Entry.author = 'Bart Simpson'"); - + // Test successful lock $gotLock = $this->lockingManager->getLock($entries[0], 'romanb'); $this->assertTrue($gotLock); - + // Test failed lock (another user already got a lock on the entry) $gotLock = $this->lockingManager->getLock($entries[0], 'konstav'); $this->assertFalse($gotLock); - + // Test release lock $released = $this->lockingManager->releaseLock($entries[0], 'romanb'); $this->assertTrue($released); @@ -88,18 +94,18 @@ public function testReleaseAgedLocks() $this->lockingManager->getLock($entries[0], 'romanb'); $released = $this->lockingManager->releaseAgedLocks(-1); // age -1 seconds => release all $this->assertEqual(1, $released); - + // A second call should return false (no locks left) $released = $this->lockingManager->releaseAgedLocks(-1); $this->assertEqual(0, $released); - + // Test with further parameters $this->lockingManager->getLock($entries[0], 'romanb'); $released = $this->lockingManager->releaseAgedLocks(-1, 'User'); // shouldnt release anything $this->assertEqual(0, $released); $released = $this->lockingManager->releaseAgedLocks(-1, 'Forum_Entry'); // should release the lock $this->assertEqual(1, $released); - + $this->lockingManager->getLock($entries[0], 'romanb'); $released = $this->lockingManager->releaseAgedLocks(-1, 'Forum_Entry', 'zyne'); // shouldnt release anything $this->assertEqual(0, $released); @@ -110,8 +116,6 @@ public function testReleaseAgedLocks() /** * Tests the retrieving of a lock's owner. * This test implicitly tests getLock(). - * - * @param Doctrine_Record $lockedRecord */ public function testGetLockOwner() { @@ -119,4 +123,4 @@ public function testGetLockOwner() $gotLock = $this->lockingManager->getLock($entries[0], 'romanb'); $this->assertEqual('romanb', $this->lockingManager->getLockOwner($entries[0])); } -} \ No newline at end of file +} diff --git a/tests/PluginTestCase.php b/tests/PluginTestCase.php index bc8ab0b8e..e32766e94 100644 --- a/tests/PluginTestCase.php +++ b/tests/PluginTestCase.php @@ -20,24 +20,31 @@ */ /** - * Doctrine_Plugin_TestCase + * Doctrine_Plugin_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Plugin_TestCase extends Doctrine_UnitTestCase +class Doctrine_Plugin_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + { + } public function prepareTables() - { } + { + } public function testNestedPluginsGetExportedRecursively() { @@ -52,7 +59,6 @@ public function testNestedPluginsGetExportedRecursively() foreach ($sql as $query) { $this->conn->exec($query); } - } public function testCreatingNewRecordsInvokesAllPlugins() @@ -63,23 +69,23 @@ public function testCreatingNewRecordsInvokesAllPlugins() $fi = $wiki->Translation['FI']; $fi->title = 'Michael Jeffrey Jordan'; - $fi->content = "Michael Jeffrey Jordan (s. 17. helmikuuta 1963, Brooklyn, New York) on yhdysvaltalainen entinen NBA-koripalloilija, jota pidet��n yleisesti kaikkien aikojen parhaana pelaajana."; + $fi->content = 'Michael Jeffrey Jordan (s. 17. helmikuuta 1963, Brooklyn, New York) on yhdysvaltalainen entinen NBA-koripalloilija, jota pidet��n yleisesti kaikkien aikojen parhaana pelaajana.'; $fi->save(); $this->assertEqual($fi->version, 1); $fi->title = 'Micheal Jordan'; $fi->save(); - + $this->assertEqual($fi->version, 2); } public function testSavingUnmodifiedRecordsDoesNotInvokeTimestampableListener() { - $this->conn->clear(); + $this->conn->clear(); $wiki = Doctrine_Query::create()->from('Wiki w')->where('w.id = 1')->fetchOne(); - + $wiki->save(); $this->assertEqual($wiki->Translation['FI']->version, 2); @@ -87,7 +93,7 @@ public function testSavingUnmodifiedRecordsDoesNotInvokeTimestampableListener() public function testSearchableChildTemplate() { - $this->conn->clear(); + $this->conn->clear(); $wiki = new Wiki(); $wiki->state(Doctrine_Record::STATE_TDIRTY); @@ -100,7 +106,7 @@ public function testSearchableChildTemplate() $t = Doctrine_Core::getTable('WikiTranslationIndex'); $oQuery = new Doctrine_Search_Query($t); - $oQuery->query("jordan"); + $oQuery->query('jordan'); $out = $this->conn->fetchAll($oQuery->getSqlQuery(), $oQuery->getParams()); $this->assertEqual($out[0]['relevance'], 2); @@ -111,18 +117,18 @@ public function testSearchableChildTemplate() public function testSluggableChildTemplate() { - $this->conn->clear(); + $this->conn->clear(); $wiki = new Wiki(); $wiki->state(Doctrine_Record::STATE_TDIRTY); $wiki->save(); $fi = $wiki->Translation['FI']; $fi->title = 'This is the title'; - $fi->content = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla sed."; + $fi->content = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla sed.'; $fi->save(); $this->assertEqual($fi->slug, 'this-is-the-title'); - } + } } class Wiki extends Doctrine_Record @@ -142,11 +148,12 @@ public function setUp() $i18n = new Doctrine_Template_I18n($options); $i18n->addChild($auditLog) - ->addChild($search) - ->addChild($slug); + ->addChild($search) + ->addChild($slug) + ; $this->actAs($i18n); $this->actAs('Timestampable'); } -} \ No newline at end of file +} diff --git a/tests/Query/AggregateValueTestCase.php b/tests/Query/AggregateValueTestCase.php index 75c480322..e629e82c5 100644 --- a/tests/Query/AggregateValueTestCase.php +++ b/tests/Query/AggregateValueTestCase.php @@ -20,25 +20,32 @@ */ /** - * Doctrine_Query_AggregateValue_TestCase + * Doctrine_Query_AggregateValue_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_AggregateValue_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_AggregateValue_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { + public function prepareData() + { } - public function testInitData() + + public function testInitData() { $users = new Doctrine_Collection('User'); - + $users[0]->name = 'John'; $users[0]->Phonenumber[0]->phonenumber = '123 123'; $users[0]->Phonenumber[1]->phonenumber = '222 222'; @@ -61,7 +68,7 @@ public function testRecordSupportsValueMapping() try { $record->get('count'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } @@ -69,7 +76,7 @@ public function testRecordSupportsValueMapping() try { $i = $record->get('count'); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertEqual($i, 3); @@ -82,7 +89,7 @@ public function testAggregateValueIsMappedToNewRecordOnEmptyResultSet() $q = new Doctrine_Query(); $q->select('COUNT(u.id) count')->from('User u'); - $this->assertEqual($q->getSqlQuery(), "SELECT COUNT(e.id) AS e__0 FROM entity e WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT COUNT(e.id) AS e__0 FROM entity e WHERE (e.type = 0)'); $users = $q->execute(); @@ -100,10 +107,10 @@ public function testAggregateValueIsMappedToRecord() $users = $q->execute(); $this->assertEqual($users->count(), 2); - + $this->assertEqual($users[0]->state(), Doctrine_Record::STATE_PROXY); $this->assertEqual($users[1]->state(), Doctrine_Record::STATE_PROXY); - + $this->assertEqual($users[0]->count, 2); $this->assertEqual($users[1]->count, 2); } @@ -117,21 +124,21 @@ public function testAggregateOrder() $users = $q->execute(); $this->assertEqual($users->count(), 2); - + $this->assertEqual($users[0]->state(), Doctrine_Record::STATE_PROXY); $this->assertEqual($users[1]->state(), Doctrine_Record::STATE_PROXY); - + $this->assertEqual($users[0]->count, 2); $this->assertEqual($users[1]->count, 2); } - public function testAggregateValueMappingSupportsLeftJoins() + public function testAggregateValueMappingSupportsLeftJoins() { $q = new Doctrine_Query(); $q->select('u.name, COUNT(p.id) count')->from('User u')->leftJoin('u.Phonenumber p')->groupby('u.id'); - $users = $q->execute(); + $users = $q->execute(); $this->assertEqual(count($users), 4); @@ -163,7 +170,7 @@ public function testAggregateValueMappingSupportsMultipleValues() $this->assertEqual($users[0]->max, 3); $this->assertEqual($users[0]->count, 3); } - + public function testAggregateValueMappingSupportsMultipleValues2() { $q = new Doctrine_Query(); @@ -175,7 +182,7 @@ public function testAggregateValueMappingSupportsMultipleValues2() $this->assertEqual($users[0]['max'], 3); $this->assertEqual($users[0]['count'], 3); } - + public function testAggregateValueMappingSupportsInnerJoins() { $q = new Doctrine_Query(); @@ -190,6 +197,7 @@ public function testAggregateValueMappingSupportsInnerJoins() $this->assertEqual($users[1]->count, 2); $this->assertEqual($users[2]->count, 1); } + public function testAggregateFunctionParser() { $q = new Doctrine_Query(); @@ -197,6 +205,7 @@ public function testAggregateFunctionParser() $this->assertEqual($q->getSqlQuery(), 'SELECT SUM(q.price) AS q__0 FROM query_test__item q'); } + public function testAggregateFunctionParser2() { $q = new Doctrine_Query(); @@ -204,6 +213,7 @@ public function testAggregateFunctionParser2() $this->assertEqual($q->getSqlQuery(), 'SELECT SUM(q.price * q.quantity) AS q__0 FROM query_test__item q'); } + public function testAggregateFunctionParser3() { $q = new Doctrine_Query(); @@ -211,6 +221,7 @@ public function testAggregateFunctionParser3() $this->assertEqual($q->getSqlQuery(), 'SELECT MOD(q.price, q.quantity) AS q__0 FROM query_test__item q'); } + public function testAggregateFunctionParser4() { $q = new Doctrine_Query(); @@ -218,12 +229,14 @@ public function testAggregateFunctionParser4() $this->assertEqual($q->getSqlQuery(), 'SELECT CONCAT(q.price, q.quantity) AS q__0 FROM query_test__item q'); } + public function testAggregateFunctionParsingSupportsMultipleComponentReferences() { $q = new Doctrine_Query(); $q->select('SUM(i.price * i.quantity)') - ->from('QueryTest_Item i'); + ->from('QueryTest_Item i') + ; - $this->assertEqual($q->getSqlQuery(), "SELECT SUM(q.price * q.quantity) AS q__0 FROM query_test__item q"); + $this->assertEqual($q->getSqlQuery(), 'SELECT SUM(q.price * q.quantity) AS q__0 FROM query_test__item q'); } -} \ No newline at end of file +} diff --git a/tests/Query/ApplyInheritanceTestCase.php b/tests/Query/ApplyInheritanceTestCase.php index 466464f21..f13fbfb2a 100644 --- a/tests/Query/ApplyInheritanceTestCase.php +++ b/tests/Query/ApplyInheritanceTestCase.php @@ -20,38 +20,43 @@ */ /** - * Doctrine_Query_ApplyInheritance_TestCase + * Doctrine_Query_ApplyInheritance_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_ApplyInheritance_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_ApplyInheritance_TestCase extends Doctrine_UnitTestCase { - public function prepareData() + public function prepareData() { - } - - public function prepareTables() + + public function prepareTables() { $this->tables = array('InheritanceDeal', 'InheritanceEntityUser', 'InheritanceUser'); - + parent::prepareTables(); } - + public function testApplyInheritance() { $query = new Doctrine_Query(); $query->from('InheritanceDeal d, d.Users u'); $query->where('u.id = 1'); - + $sql = 'SELECT i.id AS i__id, i.name AS i__name, i2.id AS i2__id, i2.username AS i2__username FROM inheritance_deal i LEFT JOIN inheritance_entity_user i3 ON (i.id = i3.entity_id) AND i3.type = 1 LEFT JOIN inheritance_user i2 ON i2.id = i3.user_id WHERE (i2.id = 1)'; - + $this->assertEqual($sql, $query->getSqlQuery()); } } diff --git a/tests/Query/CacheTestCase.php b/tests/Query/CacheTestCase.php index cf45fe799..1b8f09f3a 100644 --- a/tests/Query/CacheTestCase.php +++ b/tests/Query/CacheTestCase.php @@ -20,19 +20,24 @@ */ /** - * Doctrine_Query_Cache_TestCase + * Doctrine_Query_Cache_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Query_Cache_TestCase extends Doctrine_UnitTestCase { - public function testQueryCacheAddsQueryIntoCache() { $cache = $this->_getCacheDriver(); @@ -42,7 +47,8 @@ public function testQueryCacheAddsQueryIntoCache() ->from('User u') ->leftJoin('u.Phonenumber p') ->where('u.name = ?', 'walhala') - ->useQueryCache($cache); + ->useQueryCache($cache) + ; $coll = $q->execute(); @@ -64,7 +70,8 @@ public function testQueryCacheWorksWithGlobalConfiguration() $q = Doctrine_Query::create() ->select('u.id, u.name, p.id') ->from('User u') - ->leftJoin('u.Phonenumber p'); + ->leftJoin('u.Phonenumber p') + ; $coll = $q->execute(); @@ -119,7 +126,8 @@ public function testResultSetCacheSupportsPreparedStatements() $cache = $this->_getCacheDriver(); $q->useResultCache($cache); $q->select('u.name')->from('User u')->leftJoin('u.Phonenumber p') - ->where('u.id = ?'); + ->where('u.id = ?') + ; $coll = $q->execute(array(5)); @@ -138,9 +146,9 @@ public function testResultSetCacheSupportsPreparedStatements() $this->assertTrue($coll[0] instanceof Doctrine_Record); // references to related objects are not serialized/unserialized, so the following // would trigger an additional query (lazy-load). - //echo $this->conn->count() . "
"; - //$this->assertTrue($coll[0]->Phonenumber[0] instanceof Doctrine_Record); - //echo $this->conn->count() . "
"; // count is increased => lazy load + // echo $this->conn->count() . "
"; + // $this->assertTrue($coll[0]->Phonenumber[0] instanceof Doctrine_Record); + // echo $this->conn->count() . "
"; // count is increased => lazy load $this->assertTrue($cache->contains($q->calculateResultCacheHash(array(5)))); $this->assertEqual(count($coll), 1); } @@ -154,7 +162,8 @@ public function testUseCacheSupportsBooleanTrueAsParameter() $q->useResultCache(true); $q->select('u.name')->from('User u')->leftJoin('u.Phonenumber p') - ->where('u.id = ?'); + ->where('u.id = ?') + ; $coll = $q->execute(array(5)); @@ -238,7 +247,8 @@ public function testQueryCacheCanBeDisabledForSingleQuery() $cache = $this->_getCacheDriver(); $q = new Doctrine_Query(); $q->select('u.name')->from('User u')->leftJoin('u.Phonenumber p')->where('u.name = ?', 'walhala') - ->useQueryCache(false); + ->useQueryCache(false) + ; $coll = $q->execute(); @@ -250,9 +260,9 @@ public function testQueryCacheCanBeDisabledForSingleQuery() $this->assertFalse($cache->contains($q->calculateQueryCacheHash())); $this->assertEqual(count($coll), 0); } - + protected function _getCacheDriver() { return new Doctrine_Cache_Array(); } -} \ No newline at end of file +} diff --git a/tests/Query/CheckTestCase.php b/tests/Query/CheckTestCase.php index 57078f44b..8a16ff991 100644 --- a/tests/Query/CheckTestCase.php +++ b/tests/Query/CheckTestCase.php @@ -20,49 +20,61 @@ */ /** - * Doctrine_Query_Check_TestCase + * Doctrine_Query_Check_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Check_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Check_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() - { } + { + } + public function testCheckParserSupportsStandardFunctions() { $q = new Doctrine_Query_Check('User'); - + $q->parse('LENGTH(name) > 6'); - + $this->assertEqual($q->getSql(), 'LENGTH(name) > 6'); } + public function testCheckParserThrowsExceptionForUnknownOperator() { $q = new Doctrine_Query_Check('User'); - + try { $q->parse('LENGTH(name) ? 6'); $this->fail(); - } catch(Doctrine_Query_Exception $e) { + } catch (Doctrine_Query_Exception $e) { $this->pass(); } } + public function testCheckParserThrowsExceptionForUnknownFunction() { $q = new Doctrine_Query_Check('User'); - + try { $q->parse('SomeUnknownFunction(name) = 6'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } diff --git a/tests/Query/ComponentAliasTestCase.php b/tests/Query/ComponentAliasTestCase.php index 1ea65effb..046a8952d 100644 --- a/tests/Query/ComponentAliasTestCase.php +++ b/tests/Query/ComponentAliasTestCase.php @@ -20,19 +20,24 @@ */ /** - * Doctrine_Query_ComponentAlias_TestCase + * Doctrine_Query_ComponentAlias_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Query_ComponentAlias_TestCase extends Doctrine_UnitTestCase { - public function testQueryWithSingleAlias() { $this->connection->clear(); @@ -47,7 +52,7 @@ public function testQueryWithSingleAlias() $this->assertEqual($users->count(), 8); $this->assertTrue($users[0]->Phonenumber instanceof Doctrine_Collection); $this->assertEqual($q->getSqlQuery(), - "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)"); + 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); $this->assertEqual($count, count($this->conn)); } @@ -65,9 +70,10 @@ public function testQueryWithNestedAliases() $this->assertEqual($users->count(), 8); $this->assertTrue($users[0]->Phonenumber instanceof Doctrine_Collection); $this->assertEqual($q->getSqlQuery(), - "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e2.id = p.entity_id WHERE (e.type = 0)"); - $this->assertEqual(($count + 1), count($this->conn)); + 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e2.id = p.entity_id WHERE (e.type = 0)'); + $this->assertEqual($count + 1, count($this->conn)); } + public function testQueryWithNestedAliasesAndArrayFetching() { $this->connection->clear(); @@ -95,15 +101,14 @@ public function testQueryWithMultipleNestedAliases() $count = count($this->conn); - - $this->assertTrue($users[0]->Phonenumber instanceof Doctrine_Collection); + $this->assertTrue($users[0]->Phonenumber instanceof Doctrine_Collection); $this->assertEqual($q->getSqlQuery(), - "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id, p2.id AS p2__id, p2.phonenumber AS p2__phonenumber, p2.entity_id AS p2__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE (e.id IN (5, 6) AND (e.type = 0))"); + 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id, p2.id AS p2__id, p2.phonenumber AS p2__phonenumber, p2.entity_id AS p2__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE (e.id IN (5, 6) AND (e.type = 0))'); $this->assertEqual(count($users), 2); $this->assertEqual(count($users[0]['Group']), 1); $this->assertEqual(count($users[0]['Group'][0]['Phonenumber']), 1); $this->assertEqual(count($users[1]['Group']), 0); - + $this->assertEqual($count, count($this->conn)); } @@ -119,5 +124,4 @@ public function testQueryWithMultipleNestedAliasesAndArrayFetching() $this->assertEqual(count($users[0]['Group'][0]['Phonenumber']), 1); $this->assertEqual(count($users[1]['Group']), 0); } - } diff --git a/tests/Query/ConditionTestCase.php b/tests/Query/ConditionTestCase.php index b4933996c..d097220f3 100644 --- a/tests/Query/ConditionTestCase.php +++ b/tests/Query/ConditionTestCase.php @@ -20,36 +20,47 @@ */ /** - * Doctrine_Query_Condition_TestCase + * Doctrine_Query_Condition_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Condition_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Condition_TestCase extends Doctrine_UnitTestCase { - public function prepareData() { } - public function prepareTables() { } - + public function prepareData() + { + } + + public function prepareTables() + { + } + /** @todo belongs in TokenizerTestCase? */ - public function testBracktExplode() + public function testBracktExplode() { $tokenizer = new Doctrine_Query_Tokenizer(); - $str = "item OR item OR item"; - $parts = $tokenizer->bracketExplode($str, array(' OR '), "(", ")"); - - $this->assertEqual($parts, array('item','item','item')); + $str = 'item OR item OR item'; + $parts = $tokenizer->bracketExplode($str, array(' OR '), '(', ')'); + $this->assertEqual($parts, array('item', 'item', 'item')); } - public function testConditionParser() + + public function testConditionParser() { $query = new Doctrine_Query($this->connection); - $query->select('User.id')->from("User")->where("User.name LIKE 'z%' OR User.name LIKE 's%'"); + $query->select('User.id')->from('User')->where("User.name LIKE 'z%' OR User.name LIKE 's%'"); $sql = "SELECT e.id AS e__id FROM entity e WHERE (e.name LIKE 'z%' OR e.name LIKE 's%') AND (e.type = 0)"; $this->assertEqual($query->getSqlQuery(), $sql); @@ -80,11 +91,11 @@ public function testConditionParser() $this->assertEqual($query->getSqlQuery(), "SELECT e.id AS e__id FROM entity e WHERE ((e.name LIKE 'z%' OR e.name LIKE 's%') AND e.name LIKE 'a%') AND (e.type = 0)"); } - public function testConditionParser2() + public function testConditionParser2() { $query = new Doctrine_Query($this->connection); - $query->select('User.id')->from("User")->where("User.name LIKE 'z%' OR User.name LIKE 's%'"); + $query->select('User.id')->from('User')->where("User.name LIKE 'z%' OR User.name LIKE 's%'"); $sql = "SELECT e.id AS e__id FROM entity e WHERE (e.name LIKE 'z%' OR e.name LIKE 's%') AND (e.type = 0)"; $this->assertEqual($query->getSqlQuery(), $sql); @@ -116,4 +127,4 @@ public function testConditionParser2() $query->where("(((((User.name LIKE 'z%') OR User.name LIKE 's%')) AND User.name LIKE 'a%'))"); $this->assertEqual($query->getSqlQuery(), $sql); } -} \ No newline at end of file +} diff --git a/tests/Query/CopyTestCase.php b/tests/Query/CopyTestCase.php index cc9137122..70d45c2cf 100644 --- a/tests/Query/CopyTestCase.php +++ b/tests/Query/CopyTestCase.php @@ -20,28 +20,34 @@ */ /** - * Doctrine_Query_Copy_TestCase + * Doctrine_Query_Copy_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Copy_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Copy_TestCase extends Doctrine_UnitTestCase { public function testQueryCopy() { $q = new Doctrine_Query(); $q->from('User u'); - + $q2 = $q->copy(); - + $this->assertEqual($q->getSqlQuery(), $q2->getSqlQuery()); - $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); } -} \ No newline at end of file +} diff --git a/tests/Query/DeleteTestCase.php b/tests/Query/DeleteTestCase.php index b7e268487..cd7a74b18 100644 --- a/tests/Query/DeleteTestCase.php +++ b/tests/Query/DeleteTestCase.php @@ -21,17 +21,23 @@ /** * Doctrine_Query_Delete_TestCase - * This test case is used for testing DQL DELETE queries + * This test case is used for testing DQL DELETE queries. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Delete_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Delete_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -39,7 +45,7 @@ public function prepareTables() parent::prepareTables(); } - public function testDeleteAllWithColumnAggregationInheritance() + public function testDeleteAllWithColumnAggregationInheritance() { $q = new Doctrine_Query(); @@ -50,56 +56,56 @@ public function testDeleteAllWithColumnAggregationInheritance() $q = new Doctrine_Query(); $q->delete()->from('User'); - + $this->assertEqual($q->getSqlQuery(), 'DELETE FROM entity WHERE (type = 0)'); } - public function testDeleteAll() + public function testDeleteAll() { $q = new Doctrine_Query(); $q->parseDqlQuery('DELETE FROM Entity'); $this->assertEqual($q->getSqlQuery(), 'DELETE FROM entity'); - + $q = new Doctrine_Query(); $q->delete()->from('Entity'); - + $this->assertEqual($q->getSqlQuery(), 'DELETE FROM entity'); } - public function testDeleteWithCondition() + public function testDeleteWithCondition() { $q = new Doctrine_Query(); $q->parseDqlQuery('DELETE FROM Entity WHERE id = 3'); $this->assertEqual($q->getSqlQuery(), 'DELETE FROM entity WHERE (id = 3)'); - + $q = new Doctrine_Query(); $q->delete()->from('Entity')->where('id = 3'); - + $this->assertEqual($q->getSqlQuery(), 'DELETE FROM entity WHERE (id = 3)'); } - public function testDeleteWithLimit() + public function testDeleteWithLimit() { $q = new Doctrine_Query(); $q->parseDqlQuery('DELETE FROM Entity LIMIT 20'); $this->assertEqual($q->getSqlQuery(), 'DELETE FROM entity LIMIT 20'); - + $q = new Doctrine_Query(); $q->delete()->from('Entity')->limit(20); - + $this->assertEqual($q->getSqlQuery(), 'DELETE FROM entity LIMIT 20'); } - public function testDeleteWithLimitAndOffset() + public function testDeleteWithLimitAndOffset() { $q = new Doctrine_Query(); @@ -110,7 +116,7 @@ public function testDeleteWithLimitAndOffset() $q = new Doctrine_Query(); $q->delete()->from('Entity')->limit(10)->offset(20); - + $this->assertEqual($q->getSqlQuery(), 'DELETE FROM entity LIMIT 10 OFFSET 20'); } @@ -134,4 +140,4 @@ public function setTableDefinition() { $this->hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Query/DriverTestCase.php b/tests/Query/DriverTestCase.php index b16ba7946..61ad8baa7 100644 --- a/tests/Query/DriverTestCase.php +++ b/tests/Query/DriverTestCase.php @@ -20,22 +20,31 @@ */ /** - * Doctrine_Query_Driver_TestCase + * Doctrine_Query_Driver_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Query_Driver_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() - { } + { + } public function testLimitQueriesForPgsql() { @@ -44,7 +53,7 @@ public function testLimitQueriesForPgsql() $conn = $this->manager->openConnection($this->dbh); $q = new Doctrine_Query($conn); - + $q->from('User u')->limit(5); $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0) LIMIT 5'); @@ -57,12 +66,12 @@ public function testLimitQueriesForSqlite() $conn = $this->manager->openConnection($this->dbh); $q = new Doctrine_Query($conn); - + $q->from('User u')->limit(5); $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0) LIMIT 5'); } - + public function testLimitQueriesForMysql() { $this->dbh = new Doctrine_Adapter_Mock('mysql'); @@ -70,7 +79,7 @@ public function testLimitQueriesForMysql() $conn = $this->manager->openConnection($this->dbh); $q = new Doctrine_Query($conn); - + $q->from('User u')->limit(5); $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0) LIMIT 5'); @@ -101,73 +110,74 @@ public function testLimitOffsetQueriesForOracle() $this->assertEqual($q->getSqlQuery(), 'SELECT b.* FROM ( SELECT a.*, ROWNUM AS doctrine_rownum FROM ( SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0) ) a ) b WHERE doctrine_rownum BETWEEN 3 AND 7'); } - + public function testLimitOffsetLimitSubqueriesForOracle() { $this->dbh = new Doctrine_Adapter_Mock('oracle'); $conn = $this->manager->openConnection($this->dbh); $q = new Doctrine_Query($conn); $q->from('User u')->innerJoin('u.Phonenumber p')->limit(5)->offset(2); - - $correctSql = "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, " - . "e.password AS e__password, e.type AS e__type, e.created AS e__created, " - . "e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, " - . "p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id " - . "FROM entity e " - . "INNER JOIN phonenumber p ON e.id = p.entity_id " - . "WHERE e.id IN (" - . "SELECT b.id FROM ( " - . "SELECT a.*, ROWNUM AS doctrine_rownum " - . "FROM ( " - . "SELECT DISTINCT e2.id " - . "FROM entity e2 " - . "INNER JOIN phonenumber p2 ON e2.id = p2.entity_id " - . "WHERE (e2.type = 0) " - . ") a " - . " ) b " - . "WHERE doctrine_rownum BETWEEN 3 AND 7" - . ") AND (e.type = 0)"; - + + $correctSql = 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, ' + .'e.password AS e__password, e.type AS e__type, e.created AS e__created, ' + .'e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, ' + .'p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id ' + .'FROM entity e ' + .'INNER JOIN phonenumber p ON e.id = p.entity_id ' + .'WHERE e.id IN (' + .'SELECT b.id FROM ( ' + .'SELECT a.*, ROWNUM AS doctrine_rownum ' + .'FROM ( ' + .'SELECT DISTINCT e2.id ' + .'FROM entity e2 ' + .'INNER JOIN phonenumber p2 ON e2.id = p2.entity_id ' + .'WHERE (e2.type = 0) ' + .') a ' + .' ) b ' + .'WHERE doctrine_rownum BETWEEN 3 AND 7' + .') AND (e.type = 0)'; + $this->assertEqual($q->getSqlQuery(), $correctSql); } - - /** - * Ticket #1038 - */ + + /** + * Ticket #1038. + */ public function testLimitOffsetLimitSubqueriesForOracleWithGroupByOrderBy() { $this->dbh = new Doctrine_Adapter_Mock('oracle'); $conn = $this->manager->openConnection($this->dbh); $q = new Doctrine_Query($conn); - // The orderBy(p.id) will force p.id to be added to the SELECT part of the + // The orderBy(p.id) will force p.id to be added to the SELECT part of the // SELECT DISTINCT subquery because that is required by oracle. This, however, // can result in duplicated primary keys that would cause incorrect ROWNUM calculations, - // hence an additional subquery used to filter out the primary keys is added. + // hence an additional subquery used to filter out the primary keys is added. $q->from('User u')->innerJoin('u.Phonenumber p') - ->groupBy('u.name') // ! - ->orderBy('p.id') // !! - ->limit(5)->offset(2); - $correctSql = "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, " - . "e.password AS e__password, e.type AS e__type, e.created AS e__created, " - . "e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, " - . "p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id " - . "FROM entity e " - . "INNER JOIN phonenumber p ON e.id = p.entity_id " - . "WHERE e.id IN (" - . "SELECT b.id FROM ( " - . "SELECT a.*, ROWNUM AS doctrine_rownum " - . "FROM ( " - . "SELECT doctrine_subquery_alias.id FROM (" - . "SELECT e2.id, p2.id " - . "FROM entity e2 " - . "INNER JOIN phonenumber p2 ON e2.id = p2.entity_id " - . "WHERE (e2.type = 0) GROUP BY e2.name ORDER BY p2.id" - . ") doctrine_subquery_alias GROUP BY doctrine_subquery_alias.id ORDER BY MIN(ROWNUM) " - . ") a " - . " ) b " - . "WHERE doctrine_rownum BETWEEN 3 AND 7" - . ") AND (e.type = 0) GROUP BY e.name ORDER BY p.id"; - - $this->assertEqual($q->getSqlQuery(), $correctSql); - } + ->groupBy('u.name') // ! + ->orderBy('p.id') // !! + ->limit(5)->offset(2) + ; + $correctSql = 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, ' + .'e.password AS e__password, e.type AS e__type, e.created AS e__created, ' + .'e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, ' + .'p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id ' + .'FROM entity e ' + .'INNER JOIN phonenumber p ON e.id = p.entity_id ' + .'WHERE e.id IN (' + .'SELECT b.id FROM ( ' + .'SELECT a.*, ROWNUM AS doctrine_rownum ' + .'FROM ( ' + .'SELECT doctrine_subquery_alias.id FROM (' + .'SELECT e2.id, p2.id ' + .'FROM entity e2 ' + .'INNER JOIN phonenumber p2 ON e2.id = p2.entity_id ' + .'WHERE (e2.type = 0) GROUP BY e2.name ORDER BY p2.id' + .') doctrine_subquery_alias GROUP BY doctrine_subquery_alias.id ORDER BY MIN(ROWNUM) ' + .') a ' + .' ) b ' + .'WHERE doctrine_rownum BETWEEN 3 AND 7' + .') AND (e.type = 0) GROUP BY e.name ORDER BY p.id'; + + $this->assertEqual($q->getSqlQuery(), $correctSql); + } } diff --git a/tests/Query/ExpressionTestCase.php b/tests/Query/ExpressionTestCase.php index ed4066ff5..92cc508d6 100644 --- a/tests/Query/ExpressionTestCase.php +++ b/tests/Query/ExpressionTestCase.php @@ -1,5 +1,5 @@ + * * @version $Revision$ + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Expression_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Expression_TestCase extends Doctrine_UnitTestCase { public function testUnknownExpressionInSelectClauseThrowsException() { @@ -39,12 +45,13 @@ public function testUnknownExpressionInSelectClauseThrowsException() try { $q = Doctrine_Query::create() - ->parseDqlQuery("SELECT SOMEUNKNOWNFUNC(u.name, ' ', u.loginname) FROM User u"); + ->parseDqlQuery("SELECT SOMEUNKNOWNFUNC(u.name, ' ', u.loginname) FROM User u") + ; $sql = $q->getSqlQuery(); - $this->fail('SOMEUNKNOWNFUNC() should throw an Exception, but actually it passed and generated the SQL: ' . $sql); - } catch(Doctrine_Query_Exception $e) { + $this->fail('SOMEUNKNOWNFUNC() should throw an Exception, but actually it passed and generated the SQL: '.$sql); + } catch (Doctrine_Query_Exception $e) { $this->pass(); } @@ -52,7 +59,6 @@ public function testUnknownExpressionInSelectClauseThrowsException() $this->conn->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL); } - public function testUnknownExpressionInSelectClauseDoesntThrowException() { // Deactivate portability expression mode @@ -60,13 +66,14 @@ public function testUnknownExpressionInSelectClauseDoesntThrowException() try { $q = Doctrine_Query::create() - ->parseDqlQuery("SELECT SOMEUNKNOWNFUNC(u.name, ' ', u.loginname) FROM User u"); + ->parseDqlQuery("SELECT SOMEUNKNOWNFUNC(u.name, ' ', u.loginname) FROM User u") + ; $sql = $q->getSqlQuery(); $this->pass(); - } catch(Doctrine_Query_Exception $e) { - $this->fail('SOMEUNKNOWNFUNC() should pass, but actually it fail with message: ' . $e->getMessage()); + } catch (Doctrine_Query_Exception $e) { + $this->fail('SOMEUNKNOWNFUNC() should pass, but actually it fail with message: '.$e->getMessage()); } // Reassign old portability mode @@ -82,7 +89,7 @@ public function testUnknownColumnWithinFunctionInSelectClauseThrowsException() $q->execute(); $this->fail(); - } catch(Doctrine_Query_Exception $e) { + } catch (Doctrine_Query_Exception $e) { $this->pass(); } } @@ -92,48 +99,49 @@ public function testConcatIsSupportedInSelectClause() $q = new Doctrine_Query(); $q->parseDqlQuery('SELECT u.id, CONCAT(u.name, u.loginname) FROM User u'); - + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, CONCAT(e.name, e.loginname) AS e__0 FROM entity e WHERE (e.type = 0)'); } - public function testConcatInSelectClauseSupportsLiteralStrings() + public function testConcatInSelectClauseSupportsLiteralStrings() { $q = new Doctrine_Query(); - + $q->parseDqlQuery("SELECT u.id, CONCAT(u.name, 'The Man') FROM User u"); - + $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, CONCAT(e.name, 'The Man') AS e__0 FROM entity e WHERE (e.type = 0)"); } - public function testConcatInSelectClauseSupportsMoreThanTwoArgs() + public function testConcatInSelectClauseSupportsMoreThanTwoArgs() { $q = new Doctrine_Query(); - + $q->parseDqlQuery("SELECT u.id, CONCAT(u.name, 'The Man', u.loginname) FROM User u"); - + $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, CONCAT(e.name, 'The Man', e.loginname) AS e__0 FROM entity e WHERE (e.type = 0)"); } public function testNonPortableFunctionsAreSupported() { - $query = new Doctrine_Query(); - // we are using stored procedure here, so adjust portability settings - $this->conn->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL ^ Doctrine_Core::PORTABILITY_EXPR); + $query = new Doctrine_Query(); + // we are using stored procedure here, so adjust portability settings + $this->conn->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL ^ Doctrine_Core::PORTABILITY_EXPR); - $lat = '13.23'; - $lon = '33.23'; - $radius = '33'; + $lat = '13.23'; + $lon = '33.23'; + $radius = '33'; - $query->select("l.*, i18n.*, GeoDistKM(l.lat, l.lon, $lat, $lon) distance") - ->from('Location l, l.LocationI18n i18n') - ->where('l.id <> ? AND i18n.culture = ?', array(1, 'en')) - ->having("distance < $radius") - ->orderby('distance ASC') - ->groupby('l.id') - ->limit(5); + $query->select("l.*, i18n.*, GeoDistKM(l.lat, l.lon, {$lat}, {$lon}) distance") + ->from('Location l, l.LocationI18n i18n') + ->where('l.id <> ? AND i18n.culture = ?', array(1, 'en')) + ->having("distance < {$radius}") + ->orderby('distance ASC') + ->groupby('l.id') + ->limit(5) + ; - $this->assertEqual($query->getSqlQuery(), "SELECT l.id AS l__id, l.lat AS l__lat, l.lon AS l__lon, l2.name AS l2__name, l2.id AS l2__id, l2.culture AS l2__culture, GeoDistKM(l.lat, l.lon, 13.23, 33.23) AS l__0 FROM location l LEFT JOIN location_i18n l2 ON l.id = l2.id WHERE l.id IN (SELECT DISTINCT l3.id FROM location l3 LEFT JOIN location_i18n l4 ON l3.id = l4.id WHERE (l3.id <> ? AND l4.culture = ?) GROUP BY l3.id HAVING GeoDistKM(l3.lat, l3.lon, 13.23, 33.23) < 33 ORDER BY GeoDistKM(l3.lat, l3.lon, 13.23, 33.23) LIMIT 5) AND (l.id <> ? AND l2.culture = ?) GROUP BY l.id HAVING l__0 < 33 ORDER BY l__0 ASC"); + $this->assertEqual($query->getSqlQuery(), 'SELECT l.id AS l__id, l.lat AS l__lat, l.lon AS l__lon, l2.name AS l2__name, l2.id AS l2__id, l2.culture AS l2__culture, GeoDistKM(l.lat, l.lon, 13.23, 33.23) AS l__0 FROM location l LEFT JOIN location_i18n l2 ON l.id = l2.id WHERE l.id IN (SELECT DISTINCT l3.id FROM location l3 LEFT JOIN location_i18n l4 ON l3.id = l4.id WHERE (l3.id <> ? AND l4.culture = ?) GROUP BY l3.id HAVING GeoDistKM(l3.lat, l3.lon, 13.23, 33.23) < 33 ORDER BY GeoDistKM(l3.lat, l3.lon, 13.23, 33.23) LIMIT 5) AND (l.id <> ? AND l2.culture = ?) GROUP BY l.id HAVING l__0 < 33 ORDER BY l__0 ASC'); - $this->conn->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL); + $this->conn->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL); } } diff --git a/tests/Query/FromTestCase.php b/tests/Query/FromTestCase.php index 8f793c397..42e23e44d 100644 --- a/tests/Query/FromTestCase.php +++ b/tests/Query/FromTestCase.php @@ -20,34 +20,42 @@ */ /** - * Doctrine_Query_From_TestCase + * Doctrine_Query_From_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_From_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_From_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } public function testCount() { $count = Doctrine_Query::create()->from('User')->count(); - + $this->assertEqual($count, 0); } + public function testLeftJoin() { $q = new Doctrine_Query(); $q->from('User u LEFT JOIN u.Group'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e.type = 0)'); } public function testDefaultJoinIsLeftJoin() @@ -56,7 +64,7 @@ public function testDefaultJoinIsLeftJoin() $q->from('User u JOIN u.Group'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e.type = 0)'); } public function testInnerJoin() @@ -65,55 +73,60 @@ public function testInnerJoin() $q->from('User u INNER JOIN u.Group'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e.type = 0)'); } - public function testMultipleLeftJoin() + public function testMultipleLeftJoin() { $q = new Doctrine_Query(); $q->from('User u LEFT JOIN u.Group LEFT JOIN u.Phonenumber'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); } - public function testMultipleLeftJoin2() + + public function testMultipleLeftJoin2() { $q = new Doctrine_Query(); $q->from('User u LEFT JOIN u.Group LEFT JOIN u.Phonenumber'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, e2.id AS e2__id, e2.name AS e2__name, e2.loginname AS e2__loginname, e2.password AS e2__password, e2.type AS e2__type, e2.created AS e2__created, e2.updated AS e2__updated, e2.email_id AS e2__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); } - public function testMultipleInnerJoin() + + public function testMultipleInnerJoin() { $q = new Doctrine_Query(); $q->select('u.name')->from('User u INNER JOIN u.Group INNER JOIN u.Phonenumber'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 INNER JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 INNER JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); } - public function testMultipleInnerJoin2() + + public function testMultipleInnerJoin2() { $q = new Doctrine_Query(); $q->select('u.name')->from('User u INNER JOIN u.Group, u.Phonenumber'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 INNER JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 INNER JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); } - public function testMixingOfJoins() + + public function testMixingOfJoins() { $q = new Doctrine_Query(); $q->select('u.name, g.name, p.phonenumber')->from('User u INNER JOIN u.Group g LEFT JOIN u.Phonenumber p'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id, e2.name AS e2__name, p.id AS p__id, p.phonenumber AS p__phonenumber FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)"); - } + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id, e2.name AS e2__name, p.id AS p__id, p.phonenumber AS p__phonenumber FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); + } + public function testMixingOfJoins2() { $q = new Doctrine_Query(); $q->select('u.name, g.name, p.phonenumber')->from('User u INNER JOIN u.Group g LEFT JOIN g.Phonenumber p'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id, e2.name AS e2__name, p.id AS p__id, p.phonenumber AS p__phonenumber FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e2.id = p.entity_id WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id, e2.name AS e2__name, p.id AS p__id, p.phonenumber AS p__phonenumber FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN phonenumber p ON e2.id = p.entity_id WHERE (e.type = 0)'); } -} \ No newline at end of file +} diff --git a/tests/Query/GroupbyTestCase.php b/tests/Query/GroupbyTestCase.php index c25c8cb0a..2dfe639e8 100644 --- a/tests/Query/GroupbyTestCase.php +++ b/tests/Query/GroupbyTestCase.php @@ -1,5 +1,5 @@ + * * @version $Revision$ + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * + * @internal + * + * @coversNothing */ class Doctrine_Query_Groupby_TestCase extends Doctrine_UnitTestCase { - public function testAggregateFunctionsInHavingReturnValidSql() + public function testAggregateFunctionsInHavingReturnValidSql() { $q = new Doctrine_Query(); - + $q->parseDqlQuery('SELECT u.name, COUNT(p.id) count FROM User u LEFT JOIN u.Phonenumber p GROUP BY count'); - + $this->assertEqual($q->getQuery(), 'SELECT e.id AS e__id, e.name AS e__name, COUNT(p.id) AS p__0 FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0) GROUP BY p__0'); } } diff --git a/tests/Query/HavingTestCase.php b/tests/Query/HavingTestCase.php index 8c366c57b..46b235daf 100644 --- a/tests/Query/HavingTestCase.php +++ b/tests/Query/HavingTestCase.php @@ -1,5 +1,5 @@ + * * @version $Revision$ + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Having_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Having_TestCase extends Doctrine_UnitTestCase { - public function testAggregateFunctionsInHavingReturnValidSql() + public function testAggregateFunctionsInHavingReturnValidSql() { $q = new Doctrine_Query(); - + $q->parseDqlQuery('SELECT u.name FROM User u LEFT JOIN u.Phonenumber p HAVING COUNT(p.id) > 2'); - + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0) HAVING COUNT(p.id) > 2'); } - public function testAggregateFunctionsInHavingReturnValidSql2() + + public function testAggregateFunctionsInHavingReturnValidSql2() { $q = new Doctrine_Query(); - + $q->parseDqlQuery("SELECT u.name FROM User u LEFT JOIN u.Phonenumber p HAVING MAX(u.name) = 'zYne'"); $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0) HAVING MAX(e.name) = 'zYne'"); } - public function testAggregateFunctionsInHavingSupportMultipleParameters() + public function testAggregateFunctionsInHavingSupportMultipleParameters() { $q = new Doctrine_Query(); @@ -58,10 +65,8 @@ public function testAggregateFunctionsInHavingSupportMultipleParameters() public function testReturnFuncIfNumeric() { - $having = new Doctrine_Query_Having(new Doctrine_Query()); - $part = $having->load("1"); - $this->assertEqual("1",trim($part)); - + $having = new Doctrine_Query_Having(new Doctrine_Query()); + $part = $having->load('1'); + $this->assertEqual('1', trim($part)); } - } diff --git a/tests/Query/HydrateNoneTestCase.php b/tests/Query/HydrateNoneTestCase.php index 11217ff79..fbd148d13 100644 --- a/tests/Query/HydrateNoneTestCase.php +++ b/tests/Query/HydrateNoneTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Query_Check_TestCase + * Doctrine_Query_Check_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_HydrateNone_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_HydrateNone_TestCase extends Doctrine_UnitTestCase { public function testCheckParserSupportsStandardFunctions() { diff --git a/tests/Query/IdentifierQuotingTestCase.php b/tests/Query/IdentifierQuotingTestCase.php index 56474726e..7a56e6bf3 100644 --- a/tests/Query/IdentifierQuotingTestCase.php +++ b/tests/Query/IdentifierQuotingTestCase.php @@ -20,32 +20,39 @@ */ /** - * Doctrine_Query_IdentifierQuoting_TestCase + * Doctrine_Query_IdentifierQuoting_TestCase. * * This test case is used for testing DQL API quotes all identifiers properly * if idenfitier quoting is turned on * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_IdentifierQuoting_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_IdentifierQuoting_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { + public function prepareTables() + { $this->tables = array('Entity', 'Phonenumber'); - + parent::prepareTables(); } public function prepareData() - { } + { + } - public function testQuerySupportsIdentifierQuoting() + public function testQuerySupportsIdentifierQuoting() { $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); @@ -65,7 +72,7 @@ public function testQuerySupportsIdentifierQuotingInWherePart() $q->parseDqlQuery('SELECT u.name FROM User u WHERE u.id = 3'); $this->assertEqual($q->getSqlQuery(), 'SELECT "e"."id" AS "e__id", "e"."name" AS "e__name" FROM "entity" "e" WHERE ("e"."id" = 3 AND ("e"."type" = 0))'); - + $q->execute(); } @@ -80,14 +87,13 @@ public function testQuerySupportsIdentifierQuotingWorksWithinFunctions() } */ - public function testQuerySupportsIdentifierQuotingWithJoins() + public function testQuerySupportsIdentifierQuotingWithJoins() { $q = new Doctrine_Query(); $q->parseDqlQuery('SELECT u.name FROM User u LEFT JOIN u.Phonenumber p'); $this->assertEqual($q->getSqlQuery(), 'SELECT "e"."id" AS "e__id", "e"."name" AS "e__name" FROM "entity" "e" LEFT JOIN "phonenumber" "p" ON "e"."id" = "p"."entity_id" WHERE ("e"."type" = 0)'); - } public function testLimitSubqueryAlgorithmSupportsIdentifierQuoting() @@ -98,13 +104,13 @@ public function testLimitSubqueryAlgorithmSupportsIdentifierQuoting() $this->assertEqual($q->getSqlQuery(), 'SELECT "e"."id" AS "e__id", "e"."name" AS "e__name" FROM "entity" "e" INNER JOIN "phonenumber" "p" ON "e"."id" = "p"."entity_id" WHERE "e"."id" IN (SELECT DISTINCT "e2"."id" FROM "entity" "e2" INNER JOIN "phonenumber" "p2" ON "e2"."id" = "p2"."entity_id" WHERE ("e2"."type" = 0) LIMIT 5) AND ("e"."type" = 0)'); } - + public function testCountQuerySupportsIdentifierQuoting() { $q = new Doctrine_Query(); $q->parseDqlQuery('SELECT u.name FROM User u INNER JOIN u.Phonenumber p'); - + $this->assertEqual($q->getCountSqlQuery(), 'SELECT COUNT(*) AS "num_results" FROM (SELECT "e"."id" FROM "entity" "e" INNER JOIN "phonenumber" "p" ON "e"."id" = "p"."entity_id" WHERE ("e"."type" = 0) GROUP BY "e"."id") "dctrn_count_query"'); } @@ -113,7 +119,7 @@ public function testUpdateQuerySupportsIdentifierQuoting() $q = new Doctrine_Query(); $q->parseDqlQuery('UPDATE User u SET u.name = ? WHERE u.id = ?'); - + $this->assertEqual($q->getSqlQuery(), 'UPDATE "entity" SET "name" = ? WHERE ("id" = ? AND ("type" = 0))'); } @@ -122,7 +128,7 @@ public function testUpdateQuerySupportsIdentifierQuoting2() $q = new Doctrine_Query(); $q->update('User')->set('name', '?', 'guilhermeblanco')->where('id = ?'); - + $this->assertEqual($q->getSqlQuery(), 'UPDATE "entity" SET "name" = ? WHERE ("id" = ? AND ("type" = 0))'); } @@ -131,7 +137,7 @@ public function testUpdateQuerySupportsIdentifierQuoting3() $q = new Doctrine_Query(); $q->update('User')->set('name', 'LOWERCASE(name)')->where('id = ?'); - + $this->assertEqual($q->getSqlQuery(), 'UPDATE "entity" SET "name" = LOWERCASE("name") WHERE ("id" = ? AND ("type" = 0))'); } @@ -140,7 +146,7 @@ public function testUpdateQuerySupportsIdentifierQuoting4() $q = new Doctrine_Query(); $q->update('User u')->set('u.name', 'LOWERCASE(u.name)')->where('u.id = ?'); - + $this->assertEqual($q->getSqlQuery(), 'UPDATE "entity" SET "name" = LOWERCASE("name") WHERE ("id" = ? AND ("type" = 0))'); } @@ -149,7 +155,7 @@ public function testUpdateQuerySupportsIdentifierQuoting5() $q = new Doctrine_Query(); $q->update('User u')->set('u.name', 'UPPERCASE(LOWERCASE(u.name))')->where('u.id = ?'); - + $this->assertEqual($q->getSqlQuery(), 'UPDATE "entity" SET "name" = UPPERCASE(LOWERCASE("name")) WHERE ("id" = ? AND ("type" = 0))'); } @@ -158,7 +164,7 @@ public function testUpdateQuerySupportsIdentifierQuoting6() $q = new Doctrine_Query(); $q->update('User u')->set('u.name', 'UPPERCASE(LOWERCASE(u.id))')->where('u.id = ?'); - + $this->assertEqual($q->getSqlQuery(), 'UPDATE "entity" SET "name" = UPPERCASE(LOWERCASE("id")) WHERE ("id" = ? AND ("type" = 0))'); } @@ -167,7 +173,7 @@ public function testUpdateQuerySupportsIdentifierQuoting7() $q = new Doctrine_Query(); $q->update('User u')->set('u.name', 'CURRENT_TIMESTAMP')->where('u.id = ?'); - + $this->assertEqual($q->getSqlQuery(), 'UPDATE "entity" SET "name" = CURRENT_TIMESTAMP WHERE ("id" = ? AND ("type" = 0))'); } @@ -176,7 +182,7 @@ public function testUpdateQuerySupportsIdentifierQuoting8() $q = new Doctrine_Query(); $q->update('User u')->set('u.id', 'u.id + 1')->where('u.name = ?'); - + $this->assertEqual($q->getSqlQuery(), 'UPDATE "entity" SET "id" = "id" + 1 WHERE ("name" = ? AND ("type" = 0))'); $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, false); diff --git a/tests/Query/JoinConditionTestCase.php b/tests/Query/JoinConditionTestCase.php index a8ec86856..3425a3c48 100644 --- a/tests/Query/JoinConditionTestCase.php +++ b/tests/Query/JoinConditionTestCase.php @@ -20,28 +20,36 @@ */ /** - * Doctrine_Query_JoinCondition_TestCase + * Doctrine_Query_JoinCondition_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_JoinCondition_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_JoinCondition_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } - public function prepareTables() - { } + public function prepareTables() + { + } public function testJoinConditionsAreSupportedForOneToManyLeftJoins() { $q = new Doctrine_Query(); - + $q->parseDqlQuery("SELECT u.name, p.id FROM User u LEFT JOIN u.Phonenumber p ON p.phonenumber = '123 123'"); $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON (p.phonenumber = '123 123') WHERE (e.type = 0)"); @@ -50,7 +58,7 @@ public function testJoinConditionsAreSupportedForOneToManyLeftJoins() public function testJoinConditionsAreSupportedForOneToManyInnerJoins() { $q = new Doctrine_Query(); - + $q->parseDqlQuery("SELECT u.name, p.id FROM User u INNER JOIN u.Phonenumber p ON p.phonenumber = '123 123'"); $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e INNER JOIN phonenumber p ON (p.phonenumber = '123 123') WHERE (e.type = 0)"); @@ -59,28 +67,28 @@ public function testJoinConditionsAreSupportedForOneToManyInnerJoins() public function testJoinConditionsAreSupportedForManyToManyLeftJoins() { $q = new Doctrine_Query(); - - $q->parseDqlQuery("SELECT u.name, g.id FROM User u LEFT JOIN u.Group g ON g.id > 2"); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON (e2.id > 2) AND e2.type = 1 WHERE (e.type = 0)"); + $q->parseDqlQuery('SELECT u.name, g.id FROM User u LEFT JOIN u.Group g ON g.id > 2'); + + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON (e2.id > 2) AND e2.type = 1 WHERE (e.type = 0)'); } public function testJoinConditionsAreSupportedForManyToManyInnerJoins() { $q = new Doctrine_Query(); - - $q->parseDqlQuery("SELECT u.name, g.id FROM User u INNER JOIN u.Group g ON g.id > 2"); - - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON (e2.id > 2) AND e2.type = 1 WHERE (e.type = 0)"); + + $q->parseDqlQuery('SELECT u.name, g.id FROM User u INNER JOIN u.Group g ON g.id > 2'); + + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e2.id AS e2__id FROM entity e INNER JOIN groupuser g ON (e.id = g.user_id) INNER JOIN entity e2 ON (e2.id > 2) AND e2.type = 1 WHERE (e.type = 0)'); } public function testJoinConditionsWithClauseAndAliases() { $q = new Doctrine_Query(); - $q->parseDqlQuery("SELECT a.name, b.id FROM User a LEFT JOIN a.Phonenumber b ON a.name = b.phonenumber"); + $q->parseDqlQuery('SELECT a.name, b.id FROM User a LEFT JOIN a.Phonenumber b ON a.name = b.phonenumber'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON (e.name = p.phonenumber) WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON (e.name = p.phonenumber) WHERE (e.type = 0)'); } public function testJoinWithConditionAndNotInClause() @@ -88,8 +96,8 @@ public function testJoinWithConditionAndNotInClause() // Related to ticket #1329 $q = new Doctrine_Query(); - $q->parseDqlQuery("SELECT a.name, b.id FROM User a LEFT JOIN a.Phonenumber b WITH a.id NOT IN (1, 2, 3)"); + $q->parseDqlQuery('SELECT a.name, b.id FROM User a LEFT JOIN a.Phonenumber b WITH a.id NOT IN (1, 2, 3)'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id AND (e.id NOT IN (1, 2, 3)) WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id AND (e.id NOT IN (1, 2, 3)) WHERE (e.type = 0)'); } } diff --git a/tests/Query/JoinTestCase.php b/tests/Query/JoinTestCase.php index 40509640b..2d8342aa6 100644 --- a/tests/Query/JoinTestCase.php +++ b/tests/Query/JoinTestCase.php @@ -20,25 +20,32 @@ */ /** - * Doctrine_Query_JoinCondition_TestCase + * Doctrine_Query_JoinCondition_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Query_Join_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables = array('Record_Country', 'Record_City', 'Record_District', 'Entity', - 'User', 'Group', 'Email', 'Phonenumber', 'Groupuser', 'Account'); + 'User', 'Group', 'Email', 'Phonenumber', 'Groupuser', 'Account'); parent::prepareTables(); } + public function prepareData() { } @@ -55,7 +62,7 @@ public function testInitData() $c->City[0]->District->name = 'District 1'; $c->City[2]->District->name = 'District 2'; - + $this->assertTrue(gettype($c->City[0]->District), 'object'); $this->assertTrue(gettype($c->City[0]->District->name), 'string'); @@ -69,21 +76,22 @@ public function testQuerySupportsCustomJoins() $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c')->innerJoin('c.City c2 ON c2.id = 2') - ->where('c.id = ?', array(1)); + ->from('Record_Country c')->innerJoin('c.City c2 ON c2.id = 2') + ->where('c.id = ?', array(1)) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id FROM record__country r INNER JOIN record__city r2 ON (r2.id = 2) WHERE (r.id = ?)'); } - public function testQueryAggFunctionInJoins() { $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c') - ->innerJoin('c.City c2 WITH LOWER(c2.name) LIKE LOWER(?)', array('city 1')) - ->where('c.id = ?', array(1)); + ->from('Record_Country c') + ->innerJoin('c.City c2 WITH LOWER(c2.name) LIKE LOWER(?)', array('city 1')) + ->where('c.id = ?', array(1)) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id FROM record__country r INNER JOIN record__city r2 ON r.id = r2.country_id AND (LOWER(r2.name) LIKE LOWER(?)) WHERE (r.id = ?)'); } @@ -94,7 +102,8 @@ public function testSubQueryInJoins() $q = new Doctrine_Query(); $q->from('Record_Country c') - ->innerJoin('c.City c2 WITH (c2.name = ? OR c2.id IN (SELECT c3.id FROM Record_City c3 WHERE c3.id = ? OR c3.id = ?))'); + ->innerJoin('c.City c2 WITH (c2.name = ? OR c2.id IN (SELECT c3.id FROM Record_City c3 WHERE c3.id = ? OR c3.id = ?))') + ; $sql = $q->getSqlQuery(); $this->assertEqual($sql, 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id FROM record__country r INNER JOIN record__city r2 ON r.id = r2.country_id AND ((r2.name = ? OR r2.id IN (SELECT r3.id AS r3__id FROM record__city r3 WHERE (r3.id = ? OR r3.id = ?))))'); @@ -109,60 +118,61 @@ public function testQueryMultipleAggFunctionInJoins() $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c') - ->innerJoin('c.City c2 WITH LOWER(UPPER(c2.name)) LIKE LOWER(?)', array('city 1')) - ->where('c.id = ?', array(1)); + ->from('Record_Country c') + ->innerJoin('c.City c2 WITH LOWER(UPPER(c2.name)) LIKE LOWER(?)', array('city 1')) + ->where('c.id = ?', array(1)) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id FROM record__country r INNER JOIN record__city r2 ON r.id = r2.country_id AND (LOWER(UPPER(r2.name)) LIKE LOWER(?)) WHERE (r.id = ?)'); } - - + public function testQueryMultipleAggFunctionInJoins2() { $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c') - ->innerJoin('c.City c2 WITH LOWER(UPPER(c2.name)) LIKE CONCAT(UPPER(?), UPPER(c2.name))', array('city 1')) - ->where('c.id = ?', array(1)); + ->from('Record_Country c') + ->innerJoin('c.City c2 WITH LOWER(UPPER(c2.name)) LIKE CONCAT(UPPER(?), UPPER(c2.name))', array('city 1')) + ->where('c.id = ?', array(1)) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id FROM record__country r INNER JOIN record__city r2 ON r.id = r2.country_id AND (LOWER(UPPER(r2.name)) LIKE CONCAT(UPPER(?), UPPER(r2.name))) WHERE (r.id = ?)'); } - - + public function testQueryMultipleAggFunctionInJoins3() { $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c') - ->innerJoin('c.City c2 WITH CONCAT(UPPER(c2.name), c2.name) LIKE UPPER(?)', array('CITY 1city 1')) - ->where('c.id = ?', array(1)); + ->from('Record_Country c') + ->innerJoin('c.City c2 WITH CONCAT(UPPER(c2.name), c2.name) LIKE UPPER(?)', array('CITY 1city 1')) + ->where('c.id = ?', array(1)) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id FROM record__country r INNER JOIN record__city r2 ON r.id = r2.country_id AND (CONCAT(UPPER(r2.name), r2.name) LIKE UPPER(?)) WHERE (r.id = ?)'); } - public function testQueryWithInInsideJoins() { $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c') - ->innerJoin('c.City c2 WITH c2.id IN (?, ?)', array(1, 2)) - ->where('c.id = ?', array(1)); + ->from('Record_Country c') + ->innerJoin('c.City c2 WITH c2.id IN (?, ?)', array(1, 2)) + ->where('c.id = ?', array(1)) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id FROM record__country r INNER JOIN record__city r2 ON r.id = r2.country_id AND (r2.id IN (?, ?)) WHERE (r.id = ?)'); } - public function testQuerySupportsCustomJoinsAndWithKeyword() { $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c')->innerJoin('c.City c2 WITH c2.id = 2') - ->where('c.id = ?', array(1)); + ->from('Record_Country c')->innerJoin('c.City c2 WITH c2.id = 2') + ->where('c.id = ?', array(1)) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id FROM record__country r INNER JOIN record__city r2 ON r.id = r2.country_id AND (r2.id = 2) WHERE (r.id = ?)'); } @@ -172,8 +182,9 @@ public function testRecordHydrationWorksWithDeeplyNestedStructuresAndArrayFetchi $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c')->leftJoin('c.City c2')->leftJoin('c2.District d') - ->where('c.id = ?', array(1)); + ->from('Record_Country c')->leftJoin('c.City c2')->leftJoin('c2.District d') + ->where('c.id = ?', array(1)) + ; $countries = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); @@ -191,10 +202,11 @@ public function testRecordHydrationWorksWithDeeplyNestedStructures() $q = new Doctrine_Query(); $q->select('c.*, c2.*, d.*') - ->from('Record_Country c')->leftJoin('c.City c2')->leftJoin('c2.District d') - ->where('c.id = ?', array(1)); + ->from('Record_Country c')->leftJoin('c.City c2')->leftJoin('c2.District d') + ->where('c.id = ?', array(1)) + ; - $this->assertEqual($q->getSqlQuery(), "SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id, r3.id AS r3__id, r3.name AS r3__name FROM record__country r LEFT JOIN record__city r2 ON r.id = r2.country_id LEFT JOIN record__district r3 ON r2.district_id = r3.id WHERE (r.id = ?)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT r.id AS r__id, r.name AS r__name, r2.id AS r2__id, r2.name AS r2__name, r2.country_id AS r2__country_id, r2.district_id AS r2__district_id, r3.id AS r3__id, r3.name AS r3__name FROM record__country r LEFT JOIN record__city r2 ON r.id = r2.country_id LEFT JOIN record__district r3 ON r2.district_id = r3.id WHERE (r.id = ?)'); $countries = $q->execute(); @@ -229,7 +241,8 @@ public function testMultipleJoins() { $q = new Doctrine_Query(); $q->select('u.id, g.id, e.id')->from('User u') - ->leftJoin('u.Group g')->leftJoin('g.Email e'); + ->leftJoin('u.Group g')->leftJoin('g.Email e') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e2.id AS e2__id, e3.id AS e3__id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 LEFT JOIN email e3 ON e2.email_id = e3.id WHERE (e.type = 0)'); try { @@ -244,7 +257,8 @@ public function testMultipleJoins2() { $q = new Doctrine_Query(); $q->select('u.id, g.id, e.id')->from('Group g') - ->leftJoin('g.User u')->leftJoin('u.Account a'); + ->leftJoin('g.User u')->leftJoin('u.Account a') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e2.id AS e2__id FROM entity e LEFT JOIN groupuser g ON (e.id = g.group_id) LEFT JOIN entity e2 ON e2.id = g.user_id AND e2.type = 0 LEFT JOIN account a ON e2.id = a.entity_id WHERE (e.type = 1)'); try { @@ -259,7 +273,7 @@ public function testMapKeywordForQueryWithOneComponent() { $q = new Doctrine_Query(); $coll = $q->from('Record_City c INDEXBY c.name')->fetchArray(); - + $this->assertTrue(isset($coll['City 1'])); $this->assertTrue(isset($coll['City 2'])); $this->assertTrue(isset($coll['City 3'])); @@ -282,7 +296,7 @@ public function testMapKeywordThrowsExceptionOnNonExistentColumn() try { $q = new Doctrine_Query(); $country = $q->from('Record_Country c LEFT JOIN c.City c2 INDEXBY c2.unknown')->fetchOne(); - + $this->fail(); } catch (Doctrine_Query_Exception $e) { $this->pass(); diff --git a/tests/Query/LimitTestCase.php b/tests/Query/LimitTestCase.php index 716381033..24f5608d4 100644 --- a/tests/Query/LimitTestCase.php +++ b/tests/Query/LimitTestCase.php @@ -20,51 +20,57 @@ */ /** - * Doctrine_Query_Limit_TestCase + * Doctrine_Query_Limit_TestCase. * * This test case is used for testing DQL LIMIT clause * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Limit_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Limit_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() + public function prepareTables() { - $this->tables[] = "Photo"; - $this->tables[] = "Tag"; - $this->tables[] = "Phototag"; + $this->tables[] = 'Photo'; + $this->tables[] = 'Tag'; + $this->tables[] = 'Phototag'; parent::prepareTables(); } - - public function testLimitWithNormalManyToMany() + + public function testLimitWithNormalManyToMany() { - $coll = new Doctrine_Collection($this->connection->getTable("Photo")); + $coll = new Doctrine_Collection($this->connection->getTable('Photo')); $tag = new Tag(); - $tag->tag = "Some tag"; + $tag->tag = 'Some tag'; $coll[0]->Tag[0] = $tag; - $coll[0]->name = "photo 1"; + $coll[0]->name = 'photo 1'; $coll[1]->Tag[0] = $tag; - $coll[1]->name = "photo 2"; + $coll[1]->name = 'photo 2'; $coll[2]->Tag[0] = $tag; - $coll[2]->name = "photo 3"; - $coll[3]->Tag[0]->tag = "Other tag"; - $coll[3]->name = "photo 4"; + $coll[2]->name = 'photo 3'; + $coll[3]->Tag[0]->tag = 'Other tag'; + $coll[3]->name = 'photo 4'; $this->connection->flush(); $q = new Doctrine_Query(); $q->from('Photo')->where('Photo.Tag.id = ?')->orderby('Photo.id DESC')->limit(100); $photos = $q->execute(array(1)); - $this->assertEqual($photos->count(), 3); - $this->assertEqual($q->getSqlQuery(), - "SELECT p.id AS p__id, p.name AS p__name FROM photo p LEFT JOIN phototag p2 ON (p.id = p2.photo_id) LEFT JOIN tag t ON t.id = p2.tag_id WHERE p.id IN (SELECT DISTINCT p3.id FROM photo p3 LEFT JOIN phototag p4 ON (p3.id = p4.photo_id) LEFT JOIN tag t2 ON t2.id = p4.tag_id WHERE t2.id = ? ORDER BY p3.id DESC LIMIT 100) AND (t.id = ?) ORDER BY p.id DESC"); + $this->assertEqual($photos->count(), 3); + $this->assertEqual($q->getSqlQuery(), + 'SELECT p.id AS p__id, p.name AS p__name FROM photo p LEFT JOIN phototag p2 ON (p.id = p2.photo_id) LEFT JOIN tag t ON t.id = p2.tag_id WHERE p.id IN (SELECT DISTINCT p3.id FROM photo p3 LEFT JOIN phototag p4 ON (p3.id = p4.photo_id) LEFT JOIN tag t2 ON t2.id = p4.tag_id WHERE t2.id = ? ORDER BY p3.id DESC LIMIT 100) AND (t.id = ?) ORDER BY p.id DESC'); } public function testLimitWithOneToOneLeftJoin() @@ -74,9 +80,9 @@ public function testLimitWithOneToOneLeftJoin() $users = $q->execute(); $this->assertEqual($users->count(), 5); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e2.id AS e2__id, e2.address AS e2__address FROM entity e LEFT JOIN email e2 ON e.email_id = e2.id WHERE (e.type = 0) LIMIT 5"); - + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e2.id AS e2__id, e2.address AS e2__address FROM entity e LEFT JOIN email e2 ON e.email_id = e2.id WHERE (e.type = 0) LIMIT 5'); } + public function testLimitWithOneToOneInnerJoin() { $q = new Doctrine_Query(); @@ -84,18 +90,18 @@ public function testLimitWithOneToOneInnerJoin() $users = $q->execute(); $this->assertEqual($users->count(), 5); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e2.id AS e2__id, e2.address AS e2__address FROM entity e INNER JOIN email e2 ON e.email_id = e2.id WHERE (e.type = 0) LIMIT 5"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e2.id AS e2__id, e2.address AS e2__address FROM entity e INNER JOIN email e2 ON e.email_id = e2.id WHERE (e.type = 0) LIMIT 5'); } - public function testLimitWithOneToManyLeftJoin() + public function testLimitWithOneToManyLeftJoin() { $q = new Doctrine_Query(); $q->select('u.id, p.*')->from('User u, u.Phonenumber p')->limit(5); $sql = $q->getSqlQuery(); - $this->assertEqual($q->getSqlQuery(), - 'SELECT e.id AS e__id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE (e2.type = 0) LIMIT 5) AND (e.type = 0)'); + $this->assertEqual($q->getSqlQuery(), + 'SELECT e.id AS e__id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE (e2.type = 0) LIMIT 5) AND (e.type = 0)'); $users = $q->execute(); $count = $this->conn->count(); @@ -112,7 +118,7 @@ public function testLimitWithOneToManyLeftJoin() $this->assertEqual($count, $this->conn->count()); } - public function testLimitWithOneToManyLeftJoinAndCondition() + public function testLimitWithOneToManyLeftJoinAndCondition() { $q = new Doctrine_Query(); $q->select('User.name')->from('User')->where("User.Phonenumber.phonenumber LIKE '%123%'")->limit(5); @@ -128,15 +134,13 @@ public function testLimitWithOneToManyLeftJoinAndCondition() $this->assertEqual($users[4]->name, 'Jean Reno'); $this->assertEqual($q->getSqlQuery(), - "SELECT e.id AS e__id, e.name AS e__name FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE p2.phonenumber LIKE '%123%' AND (e2.type = 0) LIMIT 5) AND (p.phonenumber LIKE '%123%' AND (e.type = 0))"); + "SELECT e.id AS e__id, e.name AS e__name FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE p2.phonenumber LIKE '%123%' AND (e2.type = 0) LIMIT 5) AND (p.phonenumber LIKE '%123%' AND (e.type = 0))"); } - - public function testLimitWithOneToManyLeftJoinAndOrderBy() + public function testLimitWithOneToManyLeftJoinAndOrderBy() { $q = new Doctrine_Query(); $q->select('User.name')->distinct()->from('User')->where("User.Phonenumber.phonenumber LIKE '%123%'")->orderby('User.Email.address')->limit(5); - $users = $q->execute(); @@ -149,13 +153,12 @@ public function testLimitWithOneToManyLeftJoinAndOrderBy() $this->assertEqual($users->count(), 5); } - public function testLimitWithOneToManyInnerJoin() + public function testLimitWithOneToManyInnerJoin() { $q = new Doctrine_Query(); $q->select('u.id, p.*')->from('User u INNER JOIN u.Phonenumber p'); $q->limit(5); - $sql = $q->getSqlQuery(); $users = $q->execute(); @@ -164,7 +167,6 @@ public function testLimitWithOneToManyInnerJoin() $users[0]->Phonenumber[0]; $this->assertEqual($count, $this->conn->count()); - $q->offset(2); $users = $q->execute(); @@ -172,12 +174,12 @@ public function testLimitWithOneToManyInnerJoin() $this->assertEqual($users->count(), 5); $users[3]->Phonenumber[0]; $this->assertEqual($count, $this->conn->count()); - + $this->assertEqual($q->getSqlQuery(), - 'SELECT e.id AS e__id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e INNER JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 INNER JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE (e2.type = 0) LIMIT 5 OFFSET 2) AND (e.type = 0)'); + 'SELECT e.id AS e__id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e INNER JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 INNER JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE (e2.type = 0) LIMIT 5 OFFSET 2) AND (e.type = 0)'); } - public function testLimitWithPreparedQueries() + public function testLimitWithPreparedQueries() { $q = new Doctrine_Query(); $q->select('u.id, p.id')->from('User u LEFT JOIN u.Phonenumber p'); @@ -191,29 +193,28 @@ public function testLimitWithPreparedQueries() $this->assertEqual($count, $this->conn->count()); $this->assertEqual($q->getSqlQuery(), - 'SELECT e.id AS e__id, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE e2.name = ? AND (e2.type = 0) LIMIT 5) AND (e.name = ? AND (e.type = 0))'); + 'SELECT e.id AS e__id, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE e2.name = ? AND (e2.type = 0) LIMIT 5) AND (e.name = ? AND (e.type = 0))'); $q = new Doctrine_Query(); $q->select('u.id, p.id')->from('User u LEFT JOIN u.Phonenumber p'); - $q->where("u.name LIKE ? OR u.name LIKE ?"); + $q->where('u.name LIKE ? OR u.name LIKE ?'); $q->limit(5); $users = $q->execute(array('%zYne%', '%Arnold%')); $this->assertEqual($users->count(), 2); - $count = $this->conn->count(); $users[0]->Phonenumber[0]; $this->assertEqual($count, $this->conn->count()); $this->assertEqual($q->getSqlQuery(), - "SELECT e.id AS e__id, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON" - . " e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2" - . " ON e2.id = p2.entity_id WHERE (e2.name LIKE ? OR e2.name LIKE ?) AND (e2.type = 0) LIMIT 5) AND " - . "(e.name LIKE ? OR e.name LIKE ?) AND (e.type = 0)"); + 'SELECT e.id AS e__id, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON' + .' e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2' + .' ON e2.id = p2.entity_id WHERE (e2.name LIKE ? OR e2.name LIKE ?) AND (e2.type = 0) LIMIT 5) AND ' + .'(e.name LIKE ? OR e.name LIKE ?) AND (e.type = 0)'); } - public function testConnectionFlushing() + public function testConnectionFlushing() { $q = new Doctrine_Query(); $q->from('User.Phonenumber'); @@ -223,56 +224,57 @@ public function testConnectionFlushing() $users = $q->execute(); $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE e.id IN (SELECT DISTINCT e2.id FROM entity e2 LEFT JOIN phonenumber p2 ON e2.id = p2.entity_id WHERE e2.name = ? AND (e2.type = 0) LIMIT 5) AND (e.name = ? AND (e.type = 0))'); - + $this->assertEqual($users->count(), 1); - //$this->connection->flush(); + // $this->connection->flush(); } - public function testLimitWithManyToManyColumnAggInheritanceLeftJoin() + + public function testLimitWithManyToManyColumnAggInheritanceLeftJoin() { $q = new Doctrine_Query(); $q->from('User.Group')->limit(5); - + $users = $q->execute(); $this->assertEqual($users->count(), 5); - + $user = $this->objTable->find(5); - - $user->Group[1]->name = "Tough guys inc."; - - $user->Group[2]->name = "Terminators"; - + + $user->Group[1]->name = 'Tough guys inc.'; + + $user->Group[2]->name = 'Terminators'; + $user2 = $this->objTable->find(4); - //$user2->Group = $user->Group; + // $user2->Group = $user->Group; $user2->Group = new Doctrine_Collection('Group'); $user2->Group[] = $user->Group[0]; $user2->Group[] = $user->Group[1]; $user2->Group[] = $user->Group[2]; - + $user3 = $this->objTable->find(6); - //$user3->Group = $user->Group; + // $user3->Group = $user->Group; $user3->Group = new Doctrine_Collection('Group'); $user3->Group[] = $user->Group[0]; $user3->Group[] = $user->Group[1]; $user3->Group[] = $user->Group[2]; - $this->assertEqual($user->Group[0]->name, "Action Actors"); + $this->assertEqual($user->Group[0]->name, 'Action Actors'); $this->assertEqual(count($user->Group), 3); $this->assertEqual(count($user2->Group), 3); $this->assertEqual(count($user3->Group), 3); $this->connection->flush(); - - $this->assertEqual($user->Group[0]->name, "Action Actors"); + + $this->assertEqual($user->Group[0]->name, 'Action Actors'); $this->assertEqual(count($user->Group), 3); - + $q = new Doctrine_Query(); - $q->from("User")->where("User.Group.id = ?")->orderby("User.id ASC")->limit(5); - + $q->from('User')->where('User.Group.id = ?')->orderby('User.id ASC')->limit(5); + $users = $q->execute(array($user->Group[1]->id)); - + $this->assertEqual($users->count(), 3); - + $this->connection->clear(); $q = new Doctrine_Query(); $q->from('User')->where('User.Group.id = ?')->orderby('User.id DESC'); @@ -281,10 +283,10 @@ public function testLimitWithManyToManyColumnAggInheritanceLeftJoin() $this->assertEqual($users->count(), 3); } - public function testLimitAttribute() + public function testLimitAttribute() { $this->manager->setAttribute(Doctrine_Core::ATTR_QUERY_LIMIT, Doctrine_Core::LIMIT_ROWS); - + $this->connection->clear(); $q = new Doctrine_Query(); $q->from('User')->where('User.Group.name = ?')->orderby('User.id DESC')->limit(5); @@ -292,28 +294,28 @@ public function testLimitAttribute() $this->assertEqual($users->count(), 3); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e2.name = ? AND (e.type = 0)) ORDER BY e.id DESC LIMIT 5"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e LEFT JOIN groupuser g ON (e.id = g.user_id) LEFT JOIN entity e2 ON e2.id = g.group_id AND e2.type = 1 WHERE (e2.name = ? AND (e.type = 0)) ORDER BY e.id DESC LIMIT 5'); $this->manager->setAttribute(Doctrine_Core::ATTR_QUERY_LIMIT, Doctrine_Core::LIMIT_RECORDS); } - public function testLimitWithManyToManyAndColumnAggregationInheritance() + public function testLimitWithManyToManyAndColumnAggregationInheritance() { $q = new Doctrine_Query(); - $q->from('User u, u.Group g')->where('g.id > 1')->orderby('u.name DESC')->limit(10); - + $q->from('User u, u.Group g')->where('g.id > 1')->orderby('u.name DESC')->limit(10); } public function testLimitNoticesOrderbyJoins() { $q = new Doctrine_Query(); - + $q->from('Photo p') - ->leftJoin('p.Tag t') - ->orderby('t.id DESC')->limit(10); + ->leftJoin('p.Tag t') + ->orderby('t.id DESC')->limit(10) + ; - $this->assertEqual($q->getSqlQuery(), "SELECT p.id AS p__id, p.name AS p__name, t.id AS t__id, t.tag AS t__tag FROM photo p LEFT JOIN phototag p2 ON (p.id = p2.photo_id) LEFT JOIN tag t ON t.id = p2.tag_id WHERE p.id IN (SELECT DISTINCT p3.id FROM photo p3 LEFT JOIN phototag p4 ON (p3.id = p4.photo_id) LEFT JOIN tag t2 ON t2.id = p4.tag_id ORDER BY t2.id DESC LIMIT 10) ORDER BY t.id DESC"); + $this->assertEqual($q->getSqlQuery(), 'SELECT p.id AS p__id, p.name AS p__name, t.id AS t__id, t.tag AS t__tag FROM photo p LEFT JOIN phototag p2 ON (p.id = p2.photo_id) LEFT JOIN tag t ON t.id = p2.tag_id WHERE p.id IN (SELECT DISTINCT p3.id FROM photo p3 LEFT JOIN phototag p4 ON (p3.id = p4.photo_id) LEFT JOIN tag t2 ON t2.id = p4.tag_id ORDER BY t2.id DESC LIMIT 10) ORDER BY t.id DESC'); } - + public function testLimitSubqueryNotNeededIfSelectSingleFieldDistinct() { $q = new Doctrine_Query(); @@ -323,7 +325,7 @@ public function testLimitSubqueryNotNeededIfSelectSingleFieldDistinct() $users = $q->execute(array('zYne')); $this->assertEqual(1, $users->count()); - - $this->assertEqual($q->getSqlQuery(), "SELECT DISTINCT e.id AS e__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.name = ? AND (e.type = 0)) LIMIT 5"); + + $this->assertEqual($q->getSqlQuery(), 'SELECT DISTINCT e.id AS e__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.name = ? AND (e.type = 0)) LIMIT 5'); } } diff --git a/tests/Query/MultiJoin2TestCase.php b/tests/Query/MultiJoin2TestCase.php index 566535daf..f42849833 100644 --- a/tests/Query/MultiJoin2TestCase.php +++ b/tests/Query/MultiJoin2TestCase.php @@ -20,69 +20,78 @@ */ /** - * Doctrine_Query_MultiJoin2_TestCase + * Doctrine_Query_MultiJoin2_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_MultiJoin2_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_MultiJoin2_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() - { + { $this->tables = array('QueryTest_Category', 'QueryTest_Board', 'QueryTest_User', 'QueryTest_Entry'); - + parent::prepareTables(); } - public function testInitializeData() + + public function testInitializeData() { $query = new Doctrine_Query($this->connection); - + $cat = new QueryTest_Category(); $cat->rootCategoryId = 0; $cat->parentCategoryId = 0; - $cat->name = "Cat1"; + $cat->name = 'Cat1'; $cat->position = 0; $cat->save(); - + $board = new QueryTest_Board(); - $board->name = "B1"; + $board->name = 'B1'; $board->categoryId = $cat->id; $board->position = 0; $board->save(); - + $author = new QueryTest_User(); - $author->username = "romanb"; + $author->username = 'romanb'; $author->save(); $lastEntry = new QueryTest_Entry(); $lastEntry->authorId = $author->id; $lastEntry->date = 1234; $lastEntry->save(); - } - public function testMultipleJoinFetchingWithDeepJoins() + public function testMultipleJoinFetchingWithDeepJoins() { $query = new Doctrine_Query($this->connection); $queryCount = $this->connection->count(); try { $categories = $query->select('c.*, subCats.*, b.*, le.*, a.*') - ->from('QueryTest_Category c') - ->leftJoin('c.subCategories subCats') - ->leftJoin('c.boards b') - ->leftJoin('b.lastEntry le') - ->leftJoin('le.author a') - ->where('c.parentCategoryId = 0') - ->orderBy('c.position ASC, subCats.position ASC, b.position ASC') - ->execute(); + ->from('QueryTest_Category c') + ->leftJoin('c.subCategories subCats') + ->leftJoin('c.boards b') + ->leftJoin('b.lastEntry le') + ->leftJoin('le.author a') + ->where('c.parentCategoryId = 0') + ->orderBy('c.position ASC, subCats.position ASC, b.position ASC') + ->execute() + ; // Test that accessing a loaded (but empty) relation doesnt trigger an extra query $this->assertEqual($queryCount + 1, $this->connection->count()); @@ -92,21 +101,22 @@ public function testMultipleJoinFetchingWithDeepJoins() $this->fail($e->getMessage()); } } - - public function testMultipleJoinFetchingWithArrayFetching() + + public function testMultipleJoinFetchingWithArrayFetching() { $query = new Doctrine_Query($this->connection); $queryCount = $this->connection->count(); try { $categories = $query->select('c.*, subCats.*, b.*, le.*, a.*') - ->from('QueryTest_Category c') - ->leftJoin('c.subCategories subCats') - ->leftJoin('c.boards b') - ->leftJoin('b.lastEntry le') - ->leftJoin('le.author a') - ->where('c.parentCategoryId = 0') - ->orderBy('c.position ASC, subCats.position ASC, b.position ASC') - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + ->from('QueryTest_Category c') + ->leftJoin('c.subCategories subCats') + ->leftJoin('c.boards b') + ->leftJoin('b.lastEntry le') + ->leftJoin('le.author a') + ->where('c.parentCategoryId = 0') + ->orderBy('c.position ASC, subCats.position ASC, b.position ASC') + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY) + ; $this->pass(); } catch (Doctrine_Exception $e) { $this->fail($e->getMessage()); diff --git a/tests/Query/MultiJoinTestCase.php b/tests/Query/MultiJoinTestCase.php index 5f6ef49cd..f667f221d 100644 --- a/tests/Query/MultiJoinTestCase.php +++ b/tests/Query/MultiJoinTestCase.php @@ -20,20 +20,26 @@ */ /** - * Doctrine_Query_MultiJoin_TestCase + * Doctrine_Query_MultiJoin_TestCase. * * When the order is not explicit then you must not expect that relationships * are ordered by the primary key. This test case illustrate this behavior. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_MultiJoin_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_MultiJoin_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -41,14 +47,13 @@ public function prepareTables() $this->tables[] = 'Author'; parent::prepareTables(); } - public function testInitializeData() - { + public function testInitializeData() + { $query = new Doctrine_Query($this->connection); $user = $this->connection->getTable('User')->find(4); - $album = $this->connection->create('Album'); $album->Song[0]; @@ -61,7 +66,6 @@ public function testInitializeData() $this->assertEqual(count($user->Album[0]->Song), 3); - $user->Album[1]->Song[0]->title = 'Not Built To Last'; $user->Album[1]->Song[1]->title = 'The Wonders At Your Feet'; $user->Album[1]->Song[2]->title = 'Feast Of Burden'; @@ -74,21 +78,21 @@ public function testInitializeData() $this->assertEqual(count($user->Album[0]->Song), 3); $this->assertEqual(count($user->Album[1]->Song), 4); - - + $user = $this->connection->getTable('User')->find(5); - + $user->Album[0]->name = 'Clayman'; $user->Album[1]->name = 'Colony'; $user->Album[1]->Song[0]->title = 'Colony'; $user->Album[1]->Song[1]->title = 'Ordinary Story'; - + $user->save(); - + $this->assertEqual(count($user->Album[0]->Song), 0); $this->assertEqual(count($user->Album[1]->Song), 2); } - public function testMultipleOneToManyFetching() + + public function testMultipleOneToManyFetching() { $this->connection->clear(); @@ -140,7 +144,7 @@ public function testMultipleOneToManyFetching() $this->assertEqual($users[1]->Phonenumber[2]->phonenumber, '789 789'); } - public function testInitializeMoreData() + public function testInitializeMoreData() { $user = $this->connection->getTable('User')->find(4); $user->Book[0]->name = 'The Prince'; @@ -150,7 +154,6 @@ public function testInitializeMoreData() $user->Book[1]->Author[0]->name = 'Someone'; $user->Book[1]->Author[1]->name = 'Niccolo Machiavelli'; - $user->save(); $user = $this->connection->getTable('User')->find(5); @@ -164,12 +167,13 @@ public function testInitializeMoreData() $this->connection->clear(); } - public function testMultipleOneToManyFetching2() + + public function testMultipleOneToManyFetching2() { $query = new Doctrine_Query(); - $users = $query->query("FROM User.Album.Song, User.Book.Author WHERE User.id IN (4,5)"); - + $users = $query->query('FROM User.Album.Song, User.Book.Author WHERE User.id IN (4,5)'); + $this->assertEqual($users->count(), 2); $this->assertEqual($users[0]->id, 4); @@ -229,11 +233,11 @@ public function testMultipleOneToManyFetching2() $this->assertEqual($users[1]->Book[1]->Author[1]->name, 'Voltaire'); } - public function testMultipleOneToManyFetchingWithOrderBy() + public function testMultipleOneToManyFetchingWithOrderBy() { $query = new Doctrine_Query(); - $users = $query->query("FROM User.Album.Song WHERE User.id IN (4,5) ORDER BY User.Album.Song.title DESC"); + $users = $query->query('FROM User.Album.Song WHERE User.id IN (4,5) ORDER BY User.Album.Song.title DESC'); $this->assertEqual($users[0]->id, 4); $this->assertEqual($users[0]->Album[0]->id, 2); diff --git a/tests/Query/MultipleAggregateValueTestCase.php b/tests/Query/MultipleAggregateValueTestCase.php index 71c09f446..44d986725 100644 --- a/tests/Query/MultipleAggregateValueTestCase.php +++ b/tests/Query/MultipleAggregateValueTestCase.php @@ -20,35 +20,43 @@ */ /** - * Doctrine_Query_MultipleAggregateValue_TestCase + * Doctrine_Query_MultipleAggregateValue_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_MultipleAggregateValue_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_MultipleAggregateValue_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } + public function testInitData() { $user = new User(); $user->name = 'jon'; - + $user->Album[0] = new Album(); $user->Album[1] = new Album(); $user->Album[2] = new Album(); - + $user->Book[0] = new Book(); $user->Book[1] = new Book(); $user->save(); } - + public function testMultipleAggregateValues() { $query = new Doctrine_Query(); @@ -57,20 +65,21 @@ public function testMultipleAggregateValues() $query->leftJoin('u.Album a, u.Book b'); $query->where("u.name = 'jon'"); $query->limit(1); - + $user = $query->execute()->getFirst(); - + try { $name = $user->name; $num_albums = $user->num_albums; - $num_books = $user->num_books; + $num_books = $user->num_books; } catch (Doctrine_Exception $e) { $this->fail(); } - + $this->assertEqual($num_albums, 3); $this->assertEqual($num_books, 2); } + public function testMultipleAggregateValuesWithArrayFetching() { $query = new Doctrine_Query(); @@ -79,7 +88,7 @@ public function testMultipleAggregateValuesWithArrayFetching() $query->leftJoin('u.Album a, u.Book b'); $query->where("u.name = 'jon'"); $query->limit(1); - + $users = $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY); try { diff --git a/tests/Query/MysqlSubqueryHavingTestCase.php b/tests/Query/MysqlSubqueryHavingTestCase.php index 6e04ce560..86b85423f 100644 --- a/tests/Query/MysqlSubqueryHavingTestCase.php +++ b/tests/Query/MysqlSubqueryHavingTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Query_MysqlSubquery_TestCase + * Doctrine_Query_MysqlSubquery_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_MysqlSubqueryHaving_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_MysqlSubqueryHaving_TestCase extends Doctrine_UnitTestCase { public function setUp() { @@ -54,7 +60,7 @@ public function testGetLimitSubqueryWithHavingOnAggregateValues() $this->assertEqual($this->dbh->pop(), 'SELECT DISTINCT e2.id, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id HAVING a2__0 > 0 ORDER BY a2__0 DESC LIMIT 5'); } - + public function testGetLimitSubqueryWithHavingOnAggregateValuesIncorrectAlias() { $q = new Doctrine_Query(); diff --git a/tests/Query/MysqlSubqueryTestCase.php b/tests/Query/MysqlSubqueryTestCase.php index 54542018d..c7b4348a0 100644 --- a/tests/Query/MysqlSubqueryTestCase.php +++ b/tests/Query/MysqlSubqueryTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Query_MysqlSubquery_TestCase + * Doctrine_Query_MysqlSubquery_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_MysqlSubquery_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_MysqlSubquery_TestCase extends Doctrine_UnitTestCase { public function setUp() { @@ -53,6 +59,7 @@ public function testGetLimitSubquerSupportsOrderByWithAggregateValues() $this->assertEqual($this->dbh->pop(), 'SELECT DISTINCT e2.id, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id ORDER BY a2__0 LIMIT 5'); } + public function testGetLimitSubquerySupportsOrderByWithAggregateValuesAndDescKeyword() { $q = new Doctrine_Query(); @@ -68,6 +75,7 @@ public function testGetLimitSubquerySupportsOrderByWithAggregateValuesAndDescKey $this->assertEqual($this->dbh->pop(), 'SELECT DISTINCT e2.id, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id ORDER BY a2__0 DESC, e2.name LIMIT 5'); } + public function testGetLimitSubquerySupportsOrderByWithAggregateValuesAndColumns() { $q = new Doctrine_Query(); @@ -83,6 +91,7 @@ public function testGetLimitSubquerySupportsOrderByWithAggregateValuesAndColumns $this->assertEqual($this->dbh->pop(), 'SELECT DISTINCT e2.id, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id ORDER BY a2__0, e2.name LIMIT 5'); } + public function testGetLimitSubquerySupportsOrderByAndHavingWithAggregateValues() { $q = new Doctrine_Query(); @@ -96,9 +105,10 @@ public function testGetLimitSubquerySupportsOrderByAndHavingWithAggregateValues( $q->execute(); $this->dbh->pop(); - + $this->assertEqual($this->dbh->pop(), 'SELECT DISTINCT e2.id, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id HAVING a2__0 > 0 ORDER BY a2__0 DESC LIMIT 5'); } + public function testGetLimitSubquerySupportsHavingWithAggregateValues() { $q = new Doctrine_Query(); @@ -111,7 +121,7 @@ public function testGetLimitSubquerySupportsHavingWithAggregateValues() $q->execute(); $this->dbh->pop(); - + $this->assertEqual($this->dbh->pop(), 'SELECT DISTINCT e2.id, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id HAVING a2__0 > 0 LIMIT 5'); } } diff --git a/tests/Query/OneToOneFetchingTestCase.php b/tests/Query/OneToOneFetchingTestCase.php index 84a530761..4b84c9c3d 100644 --- a/tests/Query/OneToOneFetchingTestCase.php +++ b/tests/Query/OneToOneFetchingTestCase.php @@ -20,20 +20,28 @@ */ /** - * Doctrine_Query_MultiJoin2_TestCase + * Doctrine_Query_MultiJoin2_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_OneToOneFetching_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_OneToOneFetching_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() { $this->tables[] = 'QueryTest_Category'; @@ -43,56 +51,56 @@ public function prepareTables() $this->tables[] = 'QueryTest_Rank'; parent::prepareTables(); } - public function testInitializeData() + + public function testInitializeData() { $query = new Doctrine_Query($this->connection); - + $cat = new QueryTest_Category(); $cat->rootCategoryId = 0; $cat->parentCategoryId = 0; - $cat->name = "Testcat"; + $cat->name = 'Testcat'; $cat->position = 0; $cat->save(); - + $board = new QueryTest_Board(); - $board->name = "Testboard"; + $board->name = 'Testboard'; $board->categoryId = $cat->id; $board->position = 0; $board->save(); - + $author = new QueryTest_User(); - $author->username = "romanbb"; + $author->username = 'romanbb'; $author->save(); - + $lastEntry = new QueryTest_Entry(); $lastEntry->authorId = $author->id; $lastEntry->date = 1234; $lastEntry->save(); - + // Set the last entry $board->lastEntry = $lastEntry; $board->save(); - + $visibleRank = new QueryTest_Rank(); - $visibleRank->title = "Freak"; - $visibleRank->color = "red"; - $visibleRank->icon = "freak.png"; + $visibleRank->title = 'Freak'; + $visibleRank->color = 'red'; + $visibleRank->icon = 'freak.png'; $visibleRank->save(); - + // grant him a rank $author->visibleRank = $visibleRank; $author->save(); - } /** * Tests that one-one relations are correctly loaded with array fetching * when the related records EXIST. - * + * * !!! Currently it produces a notice with: - * !!! Array to string conversion in Doctrine\Hydrate.php on line 937 - * + * !!! Array to string conversion in Doctrine\Hydrate.php on line 937 + * * !!! And shortly after exits with a fatal error: * !!! Fatal error: Cannot create references to/from string offsets nor overloaded objects * !!! in Doctrine\Hydrate.php on line 939 @@ -101,84 +109,83 @@ public function testOneToOneArrayFetchingWithExistingRelations() { $query = new Doctrine_Query($this->connection); try { - $categories = $query->select("c.*, b.*, le.*, a.username, vr.title, vr.color, vr.icon") - ->from("QueryTest_Category c") - ->leftJoin("c.boards b") - ->leftJoin("b.lastEntry le") - ->leftJoin("le.author a") - ->leftJoin("a.visibleRank vr") - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + $categories = $query->select('c.*, b.*, le.*, a.username, vr.title, vr.color, vr.icon') + ->from('QueryTest_Category c') + ->leftJoin('c.boards b') + ->leftJoin('b.lastEntry le') + ->leftJoin('le.author a') + ->leftJoin('a.visibleRank vr') + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY) + ; // --> currently quits here with a fatal error! <-- - + // check boards/categories $this->assertEqual(1, count($categories)); $this->assertTrue(isset($categories[0]['boards'])); $this->assertEqual(1, count($categories[0]['boards'])); - + // get the baord for inspection $board = $categories[0]['boards'][0]; - + $this->assertTrue(isset($board['lastEntry'])); - + // lastentry should've 2 fields. one regular field, one relation. - //$this->assertEqual(2, count($board['lastEntry'])); - $this->assertEqual(1234, (int)$board['lastEntry']['date']); + // $this->assertEqual(2, count($board['lastEntry'])); + $this->assertEqual(1234, (int) $board['lastEntry']['date']); $this->assertTrue(isset($board['lastEntry']['author'])); // author should've 2 fields. one regular field, one relation. - //$this->assertEqual(2, count($board['lastEntry']['author'])); + // $this->assertEqual(2, count($board['lastEntry']['author'])); $this->assertEqual('romanbb', $board['lastEntry']['author']['username']); $this->assertTrue(isset($board['lastEntry']['author']['visibleRank'])); // visibleRank should've 3 regular fields - //$this->assertEqual(3, count($board['lastEntry']['author']['visibleRank'])); + // $this->assertEqual(3, count($board['lastEntry']['author']['visibleRank'])); $this->assertEqual('Freak', $board['lastEntry']['author']['visibleRank']['title']); $this->assertEqual('red', $board['lastEntry']['author']['visibleRank']['color']); $this->assertEqual('freak.png', $board['lastEntry']['author']['visibleRank']['icon']); - } catch (Doctrine_Exception $e) { - $this->fail(); + $this->fail(); } } - /** + /** * Tests that one-one relations are correctly loaded with array fetching * when the related records DONT EXIST. */ public function testOneToOneArrayFetchingWithEmptyRelations() { // temporarily remove the relation to fake a non-existant one - $board = $this->connection->query("FROM QueryTest_Board b WHERE b.name = ?", array('Testboard'))->getFirst(); + $board = $this->connection->query('FROM QueryTest_Board b WHERE b.name = ?', array('Testboard'))->getFirst(); $lastEntryId = $board->lastEntryId; $board->lastEntryId = 0; $board->save(); - + $query = new Doctrine_Query($this->connection); try { - $categories = $query->select("c.*, b.*, le.*, a.username, vr.title, vr.color, vr.icon") - ->from("QueryTest_Category c") - ->leftJoin("c.boards b") - ->leftJoin("b.lastEntry le") - ->leftJoin("le.author a") - ->leftJoin("a.visibleRank vr") - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - + $categories = $query->select('c.*, b.*, le.*, a.username, vr.title, vr.color, vr.icon') + ->from('QueryTest_Category c') + ->leftJoin('c.boards b') + ->leftJoin('b.lastEntry le') + ->leftJoin('le.author a') + ->leftJoin('a.visibleRank vr') + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY) + ; // check boards/categories $this->assertEqual(1, count($categories)); $this->assertTrue(isset($categories[0]['boards'])); $this->assertEqual(1, count($categories[0]['boards'])); - + // get the board for inspection $tmpBoard = $categories[0]['boards'][0]; - - $this->assertTrue( ! isset($tmpBoard['lastEntry'])); - + + $this->assertTrue(!isset($tmpBoard['lastEntry'])); } catch (Doctrine_Exception $e) { - $this->fail(); + $this->fail(); } - + $board->lastEntryId = $lastEntryId; $board->save(); } @@ -189,58 +196,58 @@ public function testOneToOneRecordFetchingWithExistingRelations() { $query = new Doctrine_Query($this->connection); try { - $categories = $query->select("c.*, b.*, le.date, a.username, vr.title, vr.color, vr.icon") - ->from("QueryTest_Category c") - ->leftJoin("c.boards b") - ->leftJoin("b.lastEntry le") - ->leftJoin("le.author a") - ->leftJoin("a.visibleRank vr") - ->execute(); - + $categories = $query->select('c.*, b.*, le.date, a.username, vr.title, vr.color, vr.icon') + ->from('QueryTest_Category c') + ->leftJoin('c.boards b') + ->leftJoin('b.lastEntry le') + ->leftJoin('le.author a') + ->leftJoin('a.visibleRank vr') + ->execute() + ; + // check boards/categories $this->assertEqual(1, count($categories)); $this->assertEqual(1, count($categories[0]['boards'])); - + // get the baord for inspection $board = $categories[0]['boards'][0]; - $this->assertEqual(1234, (int)$board['lastEntry']['date']); + $this->assertEqual(1234, (int) $board['lastEntry']['date']); $this->assertTrue(isset($board['lastEntry']['author'])); - + $this->assertEqual('romanbb', $board['lastEntry']['author']['username']); $this->assertTrue(isset($board['lastEntry']['author']['visibleRank'])); - + $this->assertEqual('Freak', $board['lastEntry']['author']['visibleRank']['title']); $this->assertEqual('red', $board['lastEntry']['author']['visibleRank']['color']); $this->assertEqual('freak.png', $board['lastEntry']['author']['visibleRank']['icon']); - } catch (Doctrine_Exception $e) { - $this->fail(); + $this->fail(); } } - // Tests that one-one relations are correctly loaded with record fetching // when the related records DONT EXIST. public function testOneToOneRecordFetchingWithEmptyRelations() { // temporarily remove the relation to fake a non-existant one - $board = $this->connection->query("FROM QueryTest_Board b WHERE b.name = ?", array('Testboard'))->getFirst(); + $board = $this->connection->query('FROM QueryTest_Board b WHERE b.name = ?', array('Testboard'))->getFirst(); $lastEntryId = $board->lastEntryId; $board->lastEntryId = null; $board->lastEntry = null; $board->save(); - + $query = new Doctrine_Query($this->connection); try { - $categories = $query->select("c.*, b.*, le.*, a.username, vr.title, vr.color, vr.icon") - ->from("QueryTest_Category c") - ->leftJoin("c.boards b") - ->leftJoin("b.lastEntry le") - ->leftJoin("le.author a") - ->leftJoin("a.visibleRank vr") - ->execute(); + $categories = $query->select('c.*, b.*, le.*, a.username, vr.title, vr.color, vr.icon') + ->from('QueryTest_Category c') + ->leftJoin('c.boards b') + ->leftJoin('b.lastEntry le') + ->leftJoin('le.author a') + ->leftJoin('a.visibleRank vr') + ->execute() + ; // check boards/categories $this->assertEqual(1, count($categories)); @@ -249,15 +256,13 @@ public function testOneToOneRecordFetchingWithEmptyRelations() // get the board for inspection $tmpBoard = $categories[0]['boards'][0]; - $this->assertTrue( ! isset($tmpBoard['lastEntry'])); - + $this->assertTrue(!isset($tmpBoard['lastEntry'])); } catch (Doctrine_Exception $e) { - print $e; + echo $e; $this->fail(); } $board->lastEntryId = $lastEntryId; - //$board->save(); + // $board->save(); } - } diff --git a/tests/Query/OrderbyTestCase.php b/tests/Query/OrderbyTestCase.php index 815fe0d57..99ca5bb5b 100644 --- a/tests/Query/OrderbyTestCase.php +++ b/tests/Query/OrderbyTestCase.php @@ -20,36 +20,45 @@ */ /** - * Doctrine_Query_Orderby_TestCase + * Doctrine_Query_Orderby_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Orderby_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Orderby_TestCase extends Doctrine_UnitTestCase { public function testOrderByRandomIsSupported() { $q = new Doctrine_Query(); - + $q->select('u.name, RANDOM() rand') - ->from('User u') - ->orderby('rand DESC'); + ->from('User u') + ->orderby('rand DESC') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, ((RANDOM() + 2147483648) / 4294967296) AS e__0 FROM entity e WHERE (e.type = 0) ORDER BY e__0 DESC'); } + public function testOrderByAggregateValueIsSupported() { $q = new Doctrine_Query(); $q->select('u.name, COUNT(p.phonenumber) count') - ->from('User u') - ->leftJoin('u.Phonenumber p') - ->orderby('count DESC'); + ->from('User u') + ->leftJoin('u.Phonenumber p') + ->orderby('count DESC') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, COUNT(p.phonenumber) AS p__0 FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0) ORDER BY p__0 DESC'); } @@ -59,10 +68,11 @@ public function testOrderByWithCoalesce() { try { $q = new Doctrine_Query(); - + $q->select('u.name') - ->from('User u') - ->orderby('COALESCE(u.id, u.name) DESC'); + ->from('User u') + ->orderby('COALESCE(u.id, u.name) DESC') + ; // nonesese results expected, but query is syntatically ok. $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0) ORDER BY COALESCE(e.id, e.name) DESC'); $this->pass(); @@ -70,15 +80,16 @@ public function testOrderByWithCoalesce() $this->fail($e->getMessage()); } } - + public function testOrderByWithMultipleCoalesce() { try { $q = new Doctrine_Query(); - + $q->select('u.name') - ->from('User u') - ->orderby('COALESCE(u.id, u.name) DESC, COALESCE(u.name, u.id) ASC'); + ->from('User u') + ->orderby('COALESCE(u.id, u.name) DESC, COALESCE(u.name, u.id) ASC') + ; // nonesese results expected, but query is syntatically ok. $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0) ORDER BY COALESCE(e.id, e.name) DESC, COALESCE(e.name, e.id) ASC'); $this->pass(); @@ -91,10 +102,11 @@ public function testOrderByWithDifferentOrderning() { try { $q = new Doctrine_Query(); - + $q->select('u.name') - ->from('User u') - ->orderby('u.id ASC, u.name DESC'); + ->from('User u') + ->orderby('u.id ASC, u.name DESC') + ; // nonesese results expected, but query is syntatically ok. $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0) ORDER BY e.id ASC, e.name DESC'); $this->pass(); diff --git a/tests/Query/PgsqlSubqueryTestCase.php b/tests/Query/PgsqlSubqueryTestCase.php index 46256fc60..e66d16bc3 100644 --- a/tests/Query/PgsqlSubqueryTestCase.php +++ b/tests/Query/PgsqlSubqueryTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Query_PgsqlSubquery_TestCase + * Doctrine_Query_PgsqlSubquery_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Query_PgsqlSubquery_TestCase extends Doctrine_UnitTestCase { @@ -50,10 +56,9 @@ public function testGetLimitSubqueryWithOrderByOnAggregateValues() $q->execute(); $this->assertEqual($this->dbh->pop(), 'SELECT e.id AS e__id, e.name AS e__name, COUNT(DISTINCT a.id) AS a__0 FROM entity e LEFT JOIN album a ON e.id = a.user_id WHERE e.id IN ' - . '(SELECT doctrine_subquery_alias.id FROM ' - . '(SELECT DISTINCT e2.id, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id ORDER BY a2__0 LIMIT 5) ' - . 'AS doctrine_subquery_alias) AND (e.type = 0) GROUP BY e.id ORDER BY a__0'); - + .'(SELECT doctrine_subquery_alias.id FROM ' + .'(SELECT DISTINCT e2.id, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id ORDER BY a2__0 LIMIT 5) ' + .'AS doctrine_subquery_alias) AND (e.type = 0) GROUP BY e.id ORDER BY a__0'); } public function testGetLimitSubqueryWithOrderByOnAggregateValuesAndColumns() @@ -69,5 +74,4 @@ public function testGetLimitSubqueryWithOrderByOnAggregateValuesAndColumns() $this->assertEqual($this->dbh->pop(), 'SELECT e.id AS e__id, e.name AS e__name, COUNT(DISTINCT a.id) AS a__0 FROM entity e LEFT JOIN album a ON e.id = a.user_id WHERE e.id IN (SELECT doctrine_subquery_alias.id FROM (SELECT DISTINCT e2.id, e2.name, COUNT(DISTINCT a2.id) AS a2__0 FROM entity e2 LEFT JOIN album a2 ON e2.id = a2.user_id WHERE (e2.type = 0) GROUP BY e2.id ORDER BY a2__0, e2.name LIMIT 5) AS doctrine_subquery_alias) AND (e.type = 0) GROUP BY e.id ORDER BY a__0, e.name'); } - } diff --git a/tests/Query/ReferenceModelTestCase.php b/tests/Query/ReferenceModelTestCase.php index a8138b9db..86babcd93 100644 --- a/tests/Query/ReferenceModelTestCase.php +++ b/tests/Query/ReferenceModelTestCase.php @@ -20,31 +20,42 @@ */ /** - * Doctrine_Query_ReferenceModel_TestCase + * Doctrine_Query_ReferenceModel_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_ReferenceModel_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { +class Doctrine_Query_ReferenceModel_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { $this->tables = array(); - $this->tables[] = "Forum_Category"; - $this->tables[] = "Forum_Entry"; - $this->tables[] = "Forum_Board"; - $this->tables[] = "Forum_Thread"; + $this->tables[] = 'Forum_Category'; + $this->tables[] = 'Forum_Entry'; + $this->tables[] = 'Forum_Board'; + $this->tables[] = 'Forum_Thread'; parent::prepareTables(); $this->connection->clear(); } - public function prepareData() - { } - public function testInitializeData() { + public function prepareData() + { + } + + public function testInitializeData() + { $this->connection->clear(); $query = new Doctrine_Query($this->connection); @@ -74,14 +85,15 @@ public function testInitializeData() { $this->connection->clear(); } - public function testSelfReferencingWithNestedOrderBy() { + public function testSelfReferencingWithNestedOrderBy() + { $query = new Doctrine_Query(); - + $query->from('Forum_Category.Subcategory.Subcategory'); $query->orderby('Forum_Category.id ASC, Forum_Category.Subcategory.name DESC'); $coll = $query->execute(); - + $category = $coll[0]; $this->assertEqual($category->name, 'Root'); @@ -95,110 +107,110 @@ public function testSelfReferencingWithNestedOrderBy() { $this->connection->clear(); } - /** - public function testSelfReferencingWithDoubleNesting() { - $query = new Doctrine_Query(); - $category = new Forum_Category(); - - $query->from('Forum_Category.Subcategory.Subcategory'); - $coll = $query->execute(); - $category = $coll[0]; - - $count = count($this->dbh); - - $this->assertEqual($category->name, 'Root'); - - $this->assertEqual($count, count($this->dbh)); - $this->assertEqual($category->Subcategory[0]->name, 'Sub 1'); - $this->assertEqual($category->Subcategory[1]->name, 'Sub 2'); - - $this->assertEqual($count, count($this->dbh)); - $this->assertEqual($category->Subcategory[0]->Subcategory[0]->name, 'Sub 1 Sub 1'); - $this->assertEqual($category->Subcategory[0]->Subcategory[1]->name, 'Sub 1 Sub 2'); - $this->assertEqual($category->Subcategory[1]->Subcategory[0]->name, 'Sub 2 Sub 1'); - $this->assertEqual($category->Subcategory[1]->Subcategory[1]->name, 'Sub 2 Sub 2'); - $this->assertEqual($count, count($this->dbh)); - - $this->connection->clear(); - } - public function testSelfReferencingWithNestingAndConditions() { - $query = new Doctrine_Query(); - $query->from("Forum_Category.Parent.Parent")->where("Forum_Category.name LIKE 'Sub%Sub%'"); - $coll = $query->execute(); - - - $count = count($this->dbh); - $this->assertEqual($coll->count(), 4); - $this->assertEqual($coll[0]->name, 'Sub 1 Sub 1'); - $this->assertEqual($coll[1]->name, 'Sub 1 Sub 2'); - $this->assertEqual($coll[2]->name, 'Sub 2 Sub 1'); - $this->assertEqual($coll[3]->name, 'Sub 2 Sub 2'); - - $this->assertEqual($count, count($this->dbh)); - - $this->assertEqual($coll[0]->Parent->name, 'Sub 1'); - $this->assertEqual($coll[1]->Parent->name, 'Sub 1'); - $this->assertEqual($coll[2]->Parent->name, 'Sub 2'); - $this->assertEqual($coll[3]->Parent->name, 'Sub 2'); - - $this->assertEqual($count, count($this->dbh)); - - $this->assertEqual($coll[0]->Parent->Parent->name, 'Root'); - $this->assertEqual($coll[1]->Parent->Parent->name, 'Root'); - $this->assertEqual($coll[2]->Parent->Parent->name, 'Root'); - $this->assertEqual($coll[3]->Parent->Parent->name, 'Root'); - - $this->assertEqual($count, count($this->dbh)); - } - public function testSelfReferencingWithNestingAndMultipleConditions() { - $query = new Doctrine_Query(); - $query->from("Forum_Category.Parent, Forum_Category.Subcategory")->where("Forum_Category.name = 'Sub 1' || Forum_Category.name = 'Sub 2'"); - - - $coll = $query->execute(); - - $count = count($this->dbh); - - $this->assertEqual($coll->count(), 2); - $this->assertEqual($coll[0]->name, 'Sub 1'); - $this->assertEqual($coll[1]->name, 'Sub 2'); - - $this->assertEqual($count, count($this->dbh)); - - $this->assertEqual($coll[0]->Subcategory[0]->name, 'Sub 1 Sub 1'); - $this->assertEqual($coll[0]->Subcategory[1]->name, 'Sub 1 Sub 2'); - $this->assertEqual($coll[1]->Subcategory[0]->name, 'Sub 2 Sub 1'); - $this->assertEqual($coll[1]->Subcategory[1]->name, 'Sub 2 Sub 2'); - - $this->assertEqual($count, count($this->dbh)); - - $this->assertEqual($coll[0]->Parent->name, 'Root'); - $this->assertEqual($coll[1]->Parent->name, 'Root'); - - $this->assertEqual($count, count($this->dbh)); - - $this->connection->clear(); - } - public function testSelfReferencingWithIsNull() { - $query = new Doctrine_Query(); - $query->from('Forum_Category.Subcategory.Subcategory')->where('Forum_Category.parent_category_id IS NULL'); - $coll = $query->execute(); - $this->assertEqual($coll->count(), 1); - - $count = count($this->dbh); - $category = $coll[0]; - $this->assertEqual($category->name, 'Root'); - - $this->assertEqual($count, count($this->dbh)); - $this->assertEqual($category->Subcategory[0]->name, 'Sub 1'); - $this->assertEqual($category->Subcategory[1]->name, 'Sub 2'); - - $this->assertEqual($count, count($this->dbh)); - $this->assertEqual($category->Subcategory[0]->Subcategory[0]->name, 'Sub 1 Sub 1'); - $this->assertEqual($category->Subcategory[0]->Subcategory[1]->name, 'Sub 1 Sub 2'); - $this->assertEqual($category->Subcategory[1]->Subcategory[0]->name, 'Sub 2 Sub 1'); - $this->assertEqual($category->Subcategory[1]->Subcategory[1]->name, 'Sub 2 Sub 2'); - $this->assertEqual($count, count($this->dbh)); - } - */ + /* + * public function testSelfReferencingWithDoubleNesting() { + * $query = new Doctrine_Query(); + * $category = new Forum_Category(); + * + * $query->from('Forum_Category.Subcategory.Subcategory'); + * $coll = $query->execute(); + * $category = $coll[0]; + * + * $count = count($this->dbh); + * + * $this->assertEqual($category->name, 'Root'); + * + * $this->assertEqual($count, count($this->dbh)); + * $this->assertEqual($category->Subcategory[0]->name, 'Sub 1'); + * $this->assertEqual($category->Subcategory[1]->name, 'Sub 2'); + * + * $this->assertEqual($count, count($this->dbh)); + * $this->assertEqual($category->Subcategory[0]->Subcategory[0]->name, 'Sub 1 Sub 1'); + * $this->assertEqual($category->Subcategory[0]->Subcategory[1]->name, 'Sub 1 Sub 2'); + * $this->assertEqual($category->Subcategory[1]->Subcategory[0]->name, 'Sub 2 Sub 1'); + * $this->assertEqual($category->Subcategory[1]->Subcategory[1]->name, 'Sub 2 Sub 2'); + * $this->assertEqual($count, count($this->dbh)); + * + * $this->connection->clear(); + * } + * public function testSelfReferencingWithNestingAndConditions() { + * $query = new Doctrine_Query(); + * $query->from("Forum_Category.Parent.Parent")->where("Forum_Category.name LIKE 'Sub%Sub%'"); + * $coll = $query->execute(); + * + * + * $count = count($this->dbh); + * $this->assertEqual($coll->count(), 4); + * $this->assertEqual($coll[0]->name, 'Sub 1 Sub 1'); + * $this->assertEqual($coll[1]->name, 'Sub 1 Sub 2'); + * $this->assertEqual($coll[2]->name, 'Sub 2 Sub 1'); + * $this->assertEqual($coll[3]->name, 'Sub 2 Sub 2'); + * + * $this->assertEqual($count, count($this->dbh)); + * + * $this->assertEqual($coll[0]->Parent->name, 'Sub 1'); + * $this->assertEqual($coll[1]->Parent->name, 'Sub 1'); + * $this->assertEqual($coll[2]->Parent->name, 'Sub 2'); + * $this->assertEqual($coll[3]->Parent->name, 'Sub 2'); + * + * $this->assertEqual($count, count($this->dbh)); + * + * $this->assertEqual($coll[0]->Parent->Parent->name, 'Root'); + * $this->assertEqual($coll[1]->Parent->Parent->name, 'Root'); + * $this->assertEqual($coll[2]->Parent->Parent->name, 'Root'); + * $this->assertEqual($coll[3]->Parent->Parent->name, 'Root'); + * + * $this->assertEqual($count, count($this->dbh)); + * } + * public function testSelfReferencingWithNestingAndMultipleConditions() { + * $query = new Doctrine_Query(); + * $query->from("Forum_Category.Parent, Forum_Category.Subcategory")->where("Forum_Category.name = 'Sub 1' || Forum_Category.name = 'Sub 2'"); + * + * + * $coll = $query->execute(); + * + * $count = count($this->dbh); + * + * $this->assertEqual($coll->count(), 2); + * $this->assertEqual($coll[0]->name, 'Sub 1'); + * $this->assertEqual($coll[1]->name, 'Sub 2'); + * + * $this->assertEqual($count, count($this->dbh)); + * + * $this->assertEqual($coll[0]->Subcategory[0]->name, 'Sub 1 Sub 1'); + * $this->assertEqual($coll[0]->Subcategory[1]->name, 'Sub 1 Sub 2'); + * $this->assertEqual($coll[1]->Subcategory[0]->name, 'Sub 2 Sub 1'); + * $this->assertEqual($coll[1]->Subcategory[1]->name, 'Sub 2 Sub 2'); + * + * $this->assertEqual($count, count($this->dbh)); + * + * $this->assertEqual($coll[0]->Parent->name, 'Root'); + * $this->assertEqual($coll[1]->Parent->name, 'Root'); + * + * $this->assertEqual($count, count($this->dbh)); + * + * $this->connection->clear(); + * } + * public function testSelfReferencingWithIsNull() { + * $query = new Doctrine_Query(); + * $query->from('Forum_Category.Subcategory.Subcategory')->where('Forum_Category.parent_category_id IS NULL'); + * $coll = $query->execute(); + * $this->assertEqual($coll->count(), 1); + * + * $count = count($this->dbh); + * $category = $coll[0]; + * $this->assertEqual($category->name, 'Root'); + * + * $this->assertEqual($count, count($this->dbh)); + * $this->assertEqual($category->Subcategory[0]->name, 'Sub 1'); + * $this->assertEqual($category->Subcategory[1]->name, 'Sub 2'); + * + * $this->assertEqual($count, count($this->dbh)); + * $this->assertEqual($category->Subcategory[0]->Subcategory[0]->name, 'Sub 1 Sub 1'); + * $this->assertEqual($category->Subcategory[0]->Subcategory[1]->name, 'Sub 1 Sub 2'); + * $this->assertEqual($category->Subcategory[1]->Subcategory[0]->name, 'Sub 2 Sub 1'); + * $this->assertEqual($category->Subcategory[1]->Subcategory[1]->name, 'Sub 2 Sub 2'); + * $this->assertEqual($count, count($this->dbh)); + * } + */ } diff --git a/tests/Query/RegistryTestCase.php b/tests/Query/RegistryTestCase.php index 8789c0989..8f8a5593a 100644 --- a/tests/Query/RegistryTestCase.php +++ b/tests/Query/RegistryTestCase.php @@ -20,26 +20,34 @@ */ /** - * Doctrine_Query_Registry_TestCase + * Doctrine_Query_Registry_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Query_Registry_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables = array('User'); - + parent::prepareTables(); } + public function prepareData() - { } + { + } public function testAddingQueries() { @@ -57,11 +65,11 @@ public function testAddingQueriesWithNamespaces() $registry->add('User/all', 'SELECT u.* FROM User u'); $this->assertEqual($registry->get('all', 'User')->getDql(), 'SELECT u.* FROM User u'); - + $this->manager->setQueryRegistry($registry); $user = new User(); - + $user->getTable()->execute('all'); } } diff --git a/tests/Query/RemoveQueryPartTestCase.php b/tests/Query/RemoveQueryPartTestCase.php index aefcacb33..9b16aab4d 100644 --- a/tests/Query/RemoveQueryPartTestCase.php +++ b/tests/Query/RemoveQueryPartTestCase.php @@ -20,66 +20,72 @@ */ /** - * Doctrine_Query_Copy_TestCase + * Doctrine_Query_Copy_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_RemoveQueryPart_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_RemoveQueryPart_TestCase extends Doctrine_UnitTestCase { - public function testQueryRemoveOrderByPart() - { - $q = new Doctrine_Query(); - $q->from('User u'); + public function testQueryRemoveOrderByPart() + { + $q = new Doctrine_Query(); + $q->from('User u'); $q->orderBy('u.id DESC'); - $q->removeDqlQueryPart('orderby'); + $q->removeDqlQueryPart('orderby'); - $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); - } + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); + } - public function testQueryRemoveLimitPart() - { - $q = new Doctrine_Query(); - $q->from('User u'); + public function testQueryRemoveLimitPart() + { + $q = new Doctrine_Query(); + $q->from('User u'); $q->limit(20); - $q->removeDqlQueryPart('limit'); + $q->removeDqlQueryPart('limit'); - $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); - } + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); + } - public function testQueryRemoveOffsetPart() - { - $q = new Doctrine_Query(); - $q->from('User u'); + public function testQueryRemoveOffsetPart() + { + $q = new Doctrine_Query(); + $q->from('User u'); $q->offset(10); - $q->removeDqlQueryPart('offset'); + $q->removeDqlQueryPart('offset'); - $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); - } + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); + } - public function testQuerySetLimitToZero() - { - $q = new Doctrine_Query(); - $q->from('User u'); + public function testQuerySetLimitToZero() + { + $q = new Doctrine_Query(); + $q->from('User u'); $q->limit(20); - $q->limit(0); + $q->limit(0); - $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); - } + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); + } - public function testQuerySetOffsetToZero() - { - $q = new Doctrine_Query(); - $q->from('User u'); + public function testQuerySetOffsetToZero() + { + $q = new Doctrine_Query(); + $q->from('User u'); $q->offset(20); - $q->offset(0); + $q->offset(0); - $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); - } -} \ No newline at end of file + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); + } +} diff --git a/tests/Query/SelectExpressionTestCase.php b/tests/Query/SelectExpressionTestCase.php index d72549759..be66862f6 100644 --- a/tests/Query/SelectExpressionTestCase.php +++ b/tests/Query/SelectExpressionTestCase.php @@ -21,25 +21,34 @@ /** * Doctrine_Query_SelectExpression_TestCase - * This test case is used for testing DQL SELECT expressions functionality + * This test case is used for testing DQL SELECT expressions functionality. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_SelectExpression_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_SelectExpression_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } - public function prepareTables() - { + public function prepareData() + { + } + + public function prepareTables() + { $this->tables = array('User'); parent::prepareTables(); } + public function testAdditionExpression() { $query = new Doctrine_Query(); @@ -49,64 +58,64 @@ public function testAdditionExpression() try { $users = $query->execute(); $this->pass(); - } catch(Exception $e) { + } catch (Exception $e) { $this->fail(); } } - + public function testSubtractionExpression() { $query = new Doctrine_Query(); $query->select('u.*, (u.id - u.id) subtraction'); $query->from('User u'); - + try { $users = $query->execute(); $this->pass(); - } catch(Exception $e) { + } catch (Exception $e) { $this->fail(); } } - + public function testDivisionExpression() { $query = new Doctrine_Query(); $query->select('u.*, (u.id/u.id) division'); $query->from('User u'); - + try { $users = $query->execute(); $this->pass(); - } catch(Exception $e) { + } catch (Exception $e) { $this->fail(); - } + } } - + public function testMultiplicationExpression() { $query = new Doctrine_Query(); $query->select('u.*, (u.id * u.id) multiplication'); $query->from('User u'); - + try { $users = $query->execute(); $this->pass(); - } catch(Exception $e) { + } catch (Exception $e) { $this->fail(); - } + } } - + public function testOrderByExpression() { $query = new Doctrine_Query(); $query->select('u.*, (u.id * u.id) multiplication'); $query->from('User u'); $query->orderby('multiplication asc'); - + try { $users = $query->execute(); $this->pass(); - } catch(Exception $e) { + } catch (Exception $e) { $this->fail(); } } diff --git a/tests/Query/SelectTestCase.php b/tests/Query/SelectTestCase.php index f4c7820f9..aaeaecece 100644 --- a/tests/Query/SelectTestCase.php +++ b/tests/Query/SelectTestCase.php @@ -20,22 +20,27 @@ */ /** - * Doctrine_Query_Select_TestCase + * Doctrine_Query_Select_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Query_Select_TestCase extends Doctrine_UnitTestCase { - public function testParseSelect() { - $q = new Doctrine_Query(); + $q = new Doctrine_Query(); $q->select('TRIM(u.name) name')->from('User u'); @@ -46,7 +51,8 @@ public function testAggregateFunctionParsingSupportsMultipleComponentReferences( { $q = new Doctrine_Query(); $q->select("CONCAT(u.name, ' ', e.address) value") - ->from('User u')->innerJoin('u.Email e'); + ->from('User u')->innerJoin('u.Email e') + ; $this->assertEqual($q->getSqlQuery(), "SELECT CONCAT(e.name, ' ', e2.address) AS e__0 FROM entity e INNER JOIN email e2 ON e.email_id = e2.id WHERE (e.type = 0)"); @@ -57,22 +63,22 @@ public function testAggregateFunctionParsingSupportsMultipleComponentReferences( public function testSelectDistinctIsSupported() { $q = new Doctrine_Query(); - + $q->distinct()->select('u.name')->from('User u'); - $this->assertEqual($q->getSqlQuery(), "SELECT DISTINCT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT DISTINCT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0)'); } public function testSelectDistinctIsSupported2() { $q = new Doctrine_Query(); - + $q->select('DISTINCT u.name')->from('User u'); - $this->assertEqual($q->getSqlQuery(), "SELECT DISTINCT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'SELECT DISTINCT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0)'); } - public function testAggregateFunctionWithDistinctKeyword() + public function testAggregateFunctionWithDistinctKeyword() { $q = new Doctrine_Query(); @@ -81,7 +87,7 @@ public function testAggregateFunctionWithDistinctKeyword() $this->assertEqual($q->getSqlQuery(), 'SELECT COUNT(DISTINCT e.name) AS e__0 FROM entity e WHERE (e.type = 0)'); } - public function testAggregateFunction() + public function testAggregateFunction() { $q = new Doctrine_Query(); @@ -90,7 +96,7 @@ public function testAggregateFunction() $this->assertEqual($q->getSqlQuery(), 'SELECT COUNT(e.id) AS e__0 FROM entity e WHERE (e.type = 0)'); } - public function testSelectPartSupportsMultipleAggregateFunctions() + public function testSelectPartSupportsMultipleAggregateFunctions() { $q = new Doctrine_Query(); @@ -113,7 +119,8 @@ public function testChangeUpdateToSelect() $q = Doctrine_Query::create() ->update('User u') ->set('u.password', '?', 'newpassword') - ->where('u.username = ?', 'jwage'); + ->where('u.username = ?', 'jwage') + ; $this->assertEqual($q->getType(), Doctrine_Query_Abstract::UPDATE); $this->assertEqual($q->getDql(), 'UPDATE User u SET u.password = ? WHERE u.username = ?'); @@ -124,16 +131,16 @@ public function testChangeUpdateToSelect() $this->assertEqual($q->getDql(), ' FROM User u WHERE u.username = ?'); } - public function testUnknownAggregateFunction() + public function testUnknownAggregateFunction() { $q = new Doctrine_Query(); - + try { $q->parseDqlQuery('SELECT UNKNOWN(u.id) FROM User u'); - + $q->getSqlQuery(); $this->fail(); - } catch(Doctrine_Query_Exception $e) { + } catch (Doctrine_Query_Exception $e) { $this->pass(); } } @@ -162,33 +169,36 @@ public function testSingleComponentWithAsterisk() $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.type = 0)'); } + public function testSingleComponentWithMultipleColumns() { $q = new Doctrine_Query(); - $q->parseDqlQuery('SELECT u.name, u.type FROM User u'); - + $q->parseDqlQuery('SELECT u.name, u.type FROM User u'); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.type AS e__type FROM entity e WHERE (e.type = 0)'); } + public function testMultipleComponentsWithAsterisk() { $q = new Doctrine_Query(); $q->parseDqlQuery('SELECT u.*, p.* FROM User u, u.Phonenumber p'); - $this->assertEqual($q->getSqlQuery(),'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); } + public function testMultipleComponentsWithMultipleColumns() { $q = new Doctrine_Query(); $q->parseDqlQuery('SELECT u.id, u.name, p.id FROM User u, u.Phonenumber p'); - $this->assertEqual($q->getSqlQuery(),'SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); } + public function testAggregateFunctionValueHydrationWithAliases() { - $q = new Doctrine_Query(); $q->parseDqlQuery('SELECT u.id, COUNT(p.id) count FROM User u, u.Phonenumber p GROUP BY u.id'); @@ -201,6 +211,7 @@ public function testAggregateFunctionValueHydrationWithAliases() $this->assertEqual($users[3]->count, 1); $this->assertEqual($users[4]->count, 3); } + public function testMultipleAggregateFunctionValueHydrationWithAliases() { $q = new Doctrine_Query(); @@ -220,6 +231,7 @@ public function testMultipleAggregateFunctionValueHydrationWithAliases() $this->assertEqual($users[3]->max, '111 222 333'); $this->assertEqual($users[4]->max, '444 555'); } + public function testMultipleAggregateFunctionValueHydrationWithAliasesAndCleanRecords() { $this->connection->clear(); @@ -227,7 +239,7 @@ public function testMultipleAggregateFunctionValueHydrationWithAliasesAndCleanRe $q = new Doctrine_Query(); $q->parseDqlQuery('SELECT u.id, COUNT(p.id) count, MAX(p.phonenumber) max FROM User u, u.Phonenumber p GROUP BY u.id'); - + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, COUNT(p.id) AS p__0, MAX(p.phonenumber) AS p__1 FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0) GROUP BY e.id'); $users = $q->execute(); @@ -251,7 +263,8 @@ public function testWhereInSupportInDql() ->select('u.id, p.id') ->from('User u') ->leftJoin('u.Phonenumber p') - ->where('u.id IN ?'); + ->where('u.id IN ?') + ; $params = array(array(4, 5, 6)); @@ -261,7 +274,7 @@ public function testWhereInSupportInDql() ); $users = $q->execute($params, Doctrine_Core::HYDRATE_ARRAY); - + $this->assertEqual(count($users), 3); } } diff --git a/tests/Query/ShortAliasesTestCase.php b/tests/Query/ShortAliasesTestCase.php index 49f2d027b..37c90faa4 100644 --- a/tests/Query/ShortAliasesTestCase.php +++ b/tests/Query/ShortAliasesTestCase.php @@ -1,31 +1,38 @@ select('u.name')->from('User u'); + * + * $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0)'); + * } + */ + public function testShortAliasesWithOneToManyLeftJoin() + { $q = new Doctrine_Query(); - $q->select('u.name')->from('User u'); - - $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name FROM entity e WHERE (e.type = 0)'); - } - */ - public function testShortAliasesWithOneToManyLeftJoin() { - $q = new Doctrine_Query(); - $q->select('u.name, p.id')->from('User u LEFT JOIN u.Phonenumber p'); $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, p.id AS p__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)'); $users = $q->execute(); - - $this->assertEqual($users->count(), 8); + $this->assertEqual($users->count(), 8); } public function testQuoteEncapedDots() { $q = new Doctrine_Query(); - $q->select("CONCAT('testing.dot\'\"s.inquotes', p.id, '\'\"') as test, u.name")->from('User u LEFT JOIN u.Phonenumber p'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, CONCAT('testing.dot\'\"s.inquotes', p.id, '\'\"') AS e__0 FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)"); + $q->select("CONCAT('testing.dot\\'\"s.inquotes', p.id, '\\'\"') as test, u.name")->from('User u LEFT JOIN u.Phonenumber p'); + $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, CONCAT('testing.dot\\'\"s.inquotes', p.id, '\\'\"') AS e__0 FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0)"); } -} \ No newline at end of file +} diff --git a/tests/Query/SubqueryTestCase.php b/tests/Query/SubqueryTestCase.php index d7e9fb5ef..dbd313ef0 100644 --- a/tests/Query/SubqueryTestCase.php +++ b/tests/Query/SubqueryTestCase.php @@ -21,26 +21,31 @@ /** * Doctrine_Query_Subquery_TestCase - * This test case is used for testing DQL subquery functionality + * This test case is used for testing DQL subquery functionality. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Subquery_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Subquery_TestCase extends Doctrine_UnitTestCase { - public function testSubqueryWithWherePartAndInExpression() { $q = new Doctrine_Query(); $q->from('User u')->where("u.id NOT IN (SELECT u2.id FROM User u2 WHERE u2.name = 'zYne')"); $this->assertEqual($q->getSqlQuery(), - "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id NOT IN (SELECT e2.id AS e2__id FROM entity e2 WHERE (e2.name = 'zYne' AND (e2.type = 0))) AND (e.type = 0))"); + "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id NOT IN (SELECT e2.id AS e2__id FROM entity e2 WHERE (e2.name = 'zYne' AND (e2.type = 0))) AND (e.type = 0))"); $users = $q->execute(); @@ -53,14 +58,14 @@ public function testSubqueryAllowsSelectingOfAnyField() $q = new Doctrine_Query(); $q->from('User u')->where('u.id NOT IN (SELECT g.user_id FROM Groupuser g)'); - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id NOT IN (SELECT g.user_id AS g__user_id FROM groupuser g) AND (e.type = 0))"); + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id NOT IN (SELECT g.user_id AS g__user_id FROM groupuser g) AND (e.type = 0))'); } public function testSubqueryInSelectPart() { // ticket #307 $q = new Doctrine_Query(); - + $q->parseDqlQuery("SELECT u.name, (SELECT COUNT(p.id) FROM Phonenumber p WHERE p.entity_id = u.id) pcount FROM User u WHERE u.name = 'zYne' LIMIT 1"); $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, (SELECT COUNT(p.id) AS p__0 FROM phonenumber p WHERE (p.entity_id = e.id)) AS e__0 FROM entity e WHERE (e.name = 'zYne' AND (e.type = 0)) LIMIT 1"); @@ -79,7 +84,7 @@ public function testSubqueryInSelectPartWithRawSql() { // ticket DC-706 $q = new Doctrine_Query(); - + $q->parseDqlQuery("SELECT u.name, (SQL:SELECT COUNT(p.id) AS p__0 FROM phonenumber p WHERE (p.entity_id = e.id)) as pcount FROM User u WHERE u.name = 'zYne' LIMIT 1"); $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, (SELECT COUNT(p.id) AS p__0 FROM phonenumber p WHERE (p.entity_id = e.id)) AS e__0 FROM entity e WHERE (e.name = 'zYne' AND (e.type = 0)) LIMIT 1"); @@ -98,11 +103,10 @@ public function testSubqueryInSelectPart2() { // ticket #307 $q = new Doctrine_Query(); - + $q->parseDqlQuery("SELECT u.name, (SELECT COUNT(w.id) FROM User w WHERE w.id = u.id) pcount FROM User u WHERE u.name = 'zYne' LIMIT 1"); - - $this->assertNotEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, (SELECT COUNT(e.id) AS e__0 FROM entity e WHERE e.id = e.id AND (e.type = 0)) AS e__0 FROM entity e WHERE e.name = 'zYne' AND (e.type = 0) LIMIT 1"); + $this->assertNotEqual($q->getSqlQuery(), "SELECT e.id AS e__id, e.name AS e__name, (SELECT COUNT(e.id) AS e__0 FROM entity e WHERE e.id = e.id AND (e.type = 0)) AS e__0 FROM entity e WHERE e.name = 'zYne' AND (e.type = 0) LIMIT 1"); } public function testGetLimitSubqueryOrderBy2() @@ -132,17 +136,18 @@ public function testAggregateFunctionsInOrderByAndHavingWithCount() $q = new Doctrine_Query(); $q->select('u.*, COUNT(a.id) num_albums') - ->from('User u') - ->leftJoin('u.Album a') - ->orderby('num_albums desc') - ->groupby('u.id') - ->having('num_albums > 0') - ->limit(5); - + ->from('User u') + ->leftJoin('u.Album a') + ->orderby('num_albums desc') + ->groupby('u.id') + ->having('num_albums > 0') + ->limit(5) + ; + try { $this->assertEqual($q->getCountSqlQuery(), 'SELECT COUNT(*) AS num_results FROM (SELECT e.id, COUNT(a.id) AS a__0 FROM entity e LEFT JOIN album a ON e.id = a.user_id WHERE (e.type = 0) GROUP BY e.id HAVING a__0 > 0) dctrn_count_query'); $q->count(); - + $this->pass(); } catch (Doctrine_Exception $e) { $this->fail($e->getMessage()); diff --git a/tests/Query/UpdateTestCase.php b/tests/Query/UpdateTestCase.php index 9f083c249..43542da40 100644 --- a/tests/Query/UpdateTestCase.php +++ b/tests/Query/UpdateTestCase.php @@ -21,26 +21,35 @@ /** * Doctrine_Query_Delete_TestCase - * This test case is used for testing DQL UPDATE queries + * This test case is used for testing DQL UPDATE queries. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Update_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Update_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } - public function prepareTables() + public function prepareData() + { + } + + public function prepareTables() { $this->tables = array('Entity', 'User', 'EnumTest'); parent::prepareTables(); } - public function testUpdateAllWithColumnAggregationInheritance() + + public function testUpdateAllWithColumnAggregationInheritance() { $q = new Doctrine_Query(); @@ -55,7 +64,7 @@ public function testUpdateAllWithColumnAggregationInheritance() $this->assertEqual($q->getSqlQuery(), "UPDATE entity SET name = 'someone' WHERE (type = 0)"); } - public function testUpdateWorksWithMultipleColumns() + public function testUpdateWorksWithMultipleColumns() { $q = new Doctrine_Query(); @@ -69,8 +78,8 @@ public function testUpdateWorksWithMultipleColumns() $this->assertEqual($q->getSqlQuery(), "UPDATE entity SET name = 'someone', email_id = 5 WHERE (type = 0)"); } - - public function testUpdateSupportsConditions() + + public function testUpdateSupportsConditions() { $q = new Doctrine_Query(); @@ -78,21 +87,25 @@ public function testUpdateSupportsConditions() $this->assertEqual($q->getSqlQuery(), "UPDATE entity SET name = 'someone' WHERE (id = 5 AND (type = 0))"); } + public function testUpdateSupportsColumnReferencing() { $q = new Doctrine_Query(); $q->update('User u')->set('u.id', 'u.id + 1'); - $this->assertEqual($q->getSqlQuery(), "UPDATE entity SET id = id + 1 WHERE (type = 0)"); + $this->assertEqual($q->getSqlQuery(), 'UPDATE entity SET id = id + 1 WHERE (type = 0)'); } + public function testUpdateSupportsComplexExpressions() { $q = new Doctrine_Query(); $q->update('User u')->set('u.name', "CONCAT(?, CONCAT(':', SUBSTRING(u.name, LOCATE(':', u.name)+1, LENGTH(u.name) - LOCATE(':', u.name)+1)))", array('gblanco')) - ->where('u.id IN (SELECT u2.id FROM User u2 WHERE u2.name = ?) AND u.email_id = ?', array('guilhermeblanco', 5)); + ->where('u.id IN (SELECT u2.id FROM User u2 WHERE u2.name = ?) AND u.email_id = ?', array('guilhermeblanco', 5)) + ; $this->assertEqual($q->getSqlQuery(), "UPDATE entity SET name = CONCAT(?, CONCAT(':', SUBSTRING(name, LOCATE(':', name)+1, LENGTH(name) - LOCATE(':', name)+1))) WHERE (id IN (SELECT e2.id AS e2__id FROM entity e2 WHERE (e2.name = ? AND (e2.type = 0))) AND email_id = ?) AND (type = 0)"); } + public function testUpdateSupportsNullSetting() { $user = new User(); @@ -105,21 +118,24 @@ public function testUpdateSupportsNullSetting() $user->free(); $q = Doctrine_Query::create() - ->update('User u') - ->set('u.name', 'NULL') - ->where('u.id = ?', $id); + ->update('User u') + ->set('u.name', 'NULL') + ->where('u.id = ?', $id) + ; $this->assertEqual($q->getSqlQuery(), 'UPDATE entity SET name = NULL WHERE (id = ? AND (type = 0))'); $q->execute(); $user = Doctrine_Query::create() - ->from('User u') - ->where('u.id = ?', $id) - ->fetchOne(); + ->from('User u') + ->where('u.id = ?', $id) + ->fetchOne() + ; $this->assertEqual($user->name, ''); } + public function testEnumAndAnotherColumnUpdate() { $enumTest = new EnumTest(); @@ -131,20 +147,22 @@ public function testEnumAndAnotherColumnUpdate() $enumTest->free(); $q = Doctrine_Query::create() - ->update('EnumTest t') - ->set('status', '?', 'closed') - ->set('text', '?', 'test2') - ->where('t.id = ?', $id); + ->update('EnumTest t') + ->set('status', '?', 'closed') + ->set('text', '?', 'test2') + ->where('t.id = ?', $id) + ; $q->execute(); $this->assertEqual($q->getSqlQuery(), 'UPDATE enum_test SET status = ?, text = ? WHERE (id = ?)'); $enumTest = Doctrine_Query::create() - ->from('EnumTest t') - ->where('t.id = ?', $id) - ->fetchOne(); + ->from('EnumTest t') + ->where('t.id = ?', $id) + ->fetchOne() + ; $this->assertEqual($enumTest->status, 'closed'); $this->assertEqual($enumTest->text, 'test2'); } -} \ No newline at end of file +} diff --git a/tests/Query/WhereTestCase.php b/tests/Query/WhereTestCase.php index adc62cdf0..9cdb52f61 100644 --- a/tests/Query/WhereTestCase.php +++ b/tests/Query/WhereTestCase.php @@ -21,22 +21,29 @@ /** * Doctrine_Query_Where_TestCase - * This test case is used for testing DQL WHERE part functionality + * This test case is used for testing DQL WHERE part functionality. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_Where_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_Where_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } - public function prepareTables() + public function prepareTables() { $this->tables = array('Entity', 'EnumTest', 'GroupUser', 'Account', 'Book'); parent::prepareTables(); @@ -92,7 +99,7 @@ public function testArithmeticExpressionAreSupportedInWherePart() $this->assertEqual($accounts[0]->amount, 1000); } - public function testDirectMultipleParameterSetting() + public function testDirectMultipleParameterSetting() { $user = new User(); $user->name = 'someone.2'; @@ -108,14 +115,13 @@ public function testDirectMultipleParameterSetting() $this->assertEqual($users[0]->name, 'someone'); $this->assertEqual($users[1]->name, 'someone.2'); } - + public function testExceptionIsThrownWhenParameterIsNull() { - try - { + try { Doctrine_Query::create()->delete('User')->whereIn('User.id', null)->execute(); - $this->fail("Should throw exception"); - } catch(Doctrine_Query_Exception $e) { + $this->fail('Should throw exception'); + } catch (Doctrine_Query_Exception $e) { $this->pass(); } } @@ -124,7 +130,8 @@ public function testDirectMultipleParameterSetting2() { $q = Doctrine_Query::create() ->from('User') - ->where('User.id IN (?, ?)', array(1, 2)); + ->where('User.id IN (?, ?)', array(1, 2)) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id IN (?, ?) AND (e.type = 0))'); @@ -143,7 +150,7 @@ public function testDirectMultipleParameterSetting2() $this->assertEqual($users[0]->name, 'someone'); $this->assertEqual($users[1]->name, 'someone.2'); } - + public function testNotInExpression() { $q = new Doctrine_Query(); @@ -155,20 +162,20 @@ public function testNotInExpression() $this->assertEqual($users[0]->name, 'someone.2'); } - public function testExistsExpression() + public function testExistsExpression() { $q = new Doctrine_Query(); - + $user = new User(); $user->name = 'someone with a group'; $user->Group[0]->name = 'some group'; $user->save(); - + // find all users which have groups try { $q->from('User u')->where('EXISTS (SELECT g.id FROM Groupuser g WHERE g.user_id = u.id)'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $users = $q->execute(); @@ -177,7 +184,7 @@ public function testExistsExpression() $this->assertEqual($users[0]->name, 'someone with a group'); } - public function testNotExistsExpression() + public function testNotExistsExpression() { $q = new Doctrine_Query(); @@ -185,7 +192,7 @@ public function testNotExistsExpression() try { $q->from('User u')->where('NOT EXISTS (SELECT Groupuser.id FROM Groupuser WHERE Groupuser.user_id = u.id)'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $users = $q->execute(); @@ -194,21 +201,20 @@ public function testNotExistsExpression() $this->assertEqual($users[1]->name, 'someone.2'); } - public function testComponentAliases() + public function testComponentAliases() { $q = new Doctrine_Query(); - $q->from('User u')->addWhere('u.id IN (?, ?)', array(1,2)); + $q->from('User u')->addWhere('u.id IN (?, ?)', array(1, 2)); $users = $q->execute(); $this->assertEqual($users->count(), 2); $this->assertEqual($users[0]->name, 'someone'); - $this->assertEqual($users[1]->name, 'someone.2'); - + $this->assertEqual($users[1]->name, 'someone.2'); } - public function testComponentAliases2() + public function testComponentAliases2() { $q = new Doctrine_Query(); @@ -223,40 +229,40 @@ public function testComponentAliases2() public function testOperatorWithNoTrailingSpaces() { $q = new Doctrine_Query(); - + $q->select('User.id')->from('User')->where("User.name='someone'"); $users = $q->execute(); $this->assertEqual($users->count(), 1); - + $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id FROM entity e WHERE (e.name = 'someone' AND (e.type = 0))"); } - public function testOperatorWithNoTrailingSpaces2() + public function testOperatorWithNoTrailingSpaces2() { $q = new Doctrine_Query(); - + $q->select('User.id')->from('User')->where("User.name='foo.bar'"); $users = $q->execute(); $this->assertEqual($users->count(), 0); - + $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id FROM entity e WHERE (e.name = 'foo.bar' AND (e.type = 0))"); } - public function testOperatorWithSingleTrailingSpace() + public function testOperatorWithSingleTrailingSpace() { $q = new Doctrine_Query(); - + $q->select('User.id')->from('User')->where("User.name= 'foo.bar'"); $users = $q->execute(); $this->assertEqual($users->count(), 0); - + $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id FROM entity e WHERE (e.name = 'foo.bar' AND (e.type = 0))"); } - public function testOperatorWithSingleTrailingSpace2() + public function testOperatorWithSingleTrailingSpace2() { $q = new Doctrine_Query(); @@ -264,7 +270,7 @@ public function testOperatorWithSingleTrailingSpace2() $users = $q->execute(); $this->assertEqual($users->count(), 0); - + $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id FROM entity e WHERE (e.name = 'foo.bar' AND (e.type = 0))"); } @@ -289,16 +295,16 @@ public function testDeepComponentReferencingIsSupported2() public function testLiteralValueAsInOperatorOperandIsSupported() { $q = new Doctrine_Query(); - + $q->select('u.id')->from('User u')->where('1 IN (1, 2)'); - + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id FROM entity e WHERE (1 IN (1, 2) AND (e.type = 0))'); } public function testCorrelatedSubqueryWithInOperatorIsSupported() { $q = new Doctrine_Query(); - + $q->select('u.id')->from('User u')->where('u.name IN (SELECT u2.name FROM User u2 WHERE u2.id = u.id)'); $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id FROM entity e WHERE (e.name IN (SELECT e2.name AS e2__name FROM entity e2 WHERE (e2.id = e.id AND (e2.type = 0))) AND (e.type = 0))'); diff --git a/tests/QueryTestCase.php b/tests/QueryTestCase.php index bf349c31b..cd56d82e0 100644 --- a/tests/QueryTestCase.php +++ b/tests/QueryTestCase.php @@ -20,39 +20,45 @@ */ /** - * Doctrine_Query_TestCase + * Doctrine_Query_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Query_TestCase extends Doctrine_UnitTestCase +class Doctrine_Query_TestCase extends Doctrine_UnitTestCase { - public function testWhereInSupportInDql() { $q = Doctrine_Query::create() ->from('User u') ->where('u.id IN ?', array(array(1, 2, 3))) ->whereNotIn('u.name', array('', 'a')) - ->addWhere('u.id NOT IN ?', array(array(4, 5, 6, 7))); + ->addWhere('u.id NOT IN ?', array(array(4, 5, 6, 7))) + ; $this->assertEqual( $q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id IN (?, ?, ?) AND e.name NOT IN (?, ?) AND e.id NOT IN (?, ?, ?, ?) AND (e.type = 0))' ); } - - + public function testWhereInSupportInDql2() { $q = Doctrine_Query::create() ->from('User u') - ->where('u.id IN ?', array(1)); + ->where('u.id IN ?', array(1)) + ; $this->assertEqual( $q->getSqlQuery(), @@ -60,7 +66,6 @@ public function testWhereInSupportInDql2() ); } - public function testGetQueryHookResetsTheManuallyAddedDqlParts() { $q = new MyQuery(); @@ -73,10 +78,9 @@ public function testGetQueryHookResetsTheManuallyAddedDqlParts() $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id = 4 AND (e.type = 0))'); } - public function testParseClauseSupportsArithmeticOperators() { - $q = new Doctrine_Query(); + $q = new Doctrine_Query(); $str = $q->parseClause('2 + 3'); @@ -86,9 +90,10 @@ public function testParseClauseSupportsArithmeticOperators() $this->assertEqual($str, '2 + 3 - 5 * 6'); } + public function testParseClauseSupportsArithmeticOperatorsWithFunctions() { - $q = new Doctrine_Query(); + $q = new Doctrine_Query(); $str = $q->parseClause('ACOS(2) + 3'); @@ -97,7 +102,7 @@ public function testParseClauseSupportsArithmeticOperatorsWithFunctions() public function testParseClauseSupportsArithmeticOperatorsWithParenthesis() { - $q = new Doctrine_Query(); + $q = new Doctrine_Query(); $str = $q->parseClause('(3 + 3)*3'); @@ -110,7 +115,7 @@ public function testParseClauseSupportsArithmeticOperatorsWithParenthesis() public function testParseClauseSupportsArithmeticOperatorsWithParenthesisAndFunctions() { - $q = new Doctrine_Query(); + $q = new Doctrine_Query(); $str = $q->parseClause('(3 + 3)*ACOS(3)'); @@ -123,13 +128,13 @@ public function testParseClauseSupportsArithmeticOperatorsWithParenthesisAndFunc public function testParseClauseSupportsComponentReferences() { - $q = new Doctrine_Query(); + $q = new Doctrine_Query(); $q->from('User u')->leftJoin('u.Phonenumber p'); $q->getSqlQuery(); - //Doctrine_Core::dump($q->getCachedForm(array('foo' => 'bar'))); + // Doctrine_Core::dump($q->getCachedForm(array('foo' => 'bar'))); $this->assertEqual($q->parseClause("CONCAT('u.name', u.name)"), "CONCAT('u.name', e.name)"); } - + public function testCountMaintainsParams() { $q = new Doctrine_Query(); @@ -156,19 +161,19 @@ public function testQueryCopyClone() $query = new Doctrine_Query(); $query->select('u.*')->from('User u'); $sql = $query->getSqlQuery(); - + $data = $query->execute(); $query2 = $query->copy(); - + $this->assertTrue($sql, $query2->getSqlQuery()); - + $query2->limit(0); $query2->offset(0); $query2->select('COUNT(u.id) as nb'); - + $this->assertTrue($query2->getSqlQuery(), 'SELECT COUNT(e.id) AS e__0 FROM entity e WHERE (e.type = 0)'); } - + public function testNullAggregateIsSet() { $user = new User(); @@ -180,10 +185,11 @@ public function testNullAggregateIsSet() $user->free(); $query = Doctrine_Query::create() - ->select('u.*, p.*, SUM(p.phonenumber) summ') - ->from('User u') - ->leftJoin('u.Phonenumber p') - ->where('u.id = ?', $id); + ->select('u.*, p.*, SUM(p.phonenumber) summ') + ->from('User u') + ->leftJoin('u.Phonenumber p') + ->where('u.id = ?', $id) + ; $users = $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY); @@ -194,17 +200,17 @@ public function testQueryWithNoSelectFromRootTableThrowsException() { try { $users = Doctrine_Query::create() - ->select('p.*') - ->from('User u') - ->leftJoin('u.Phonenumber p') - ->execute(); + ->select('p.*') + ->from('User u') + ->leftJoin('u.Phonenumber p') + ->execute() + ; $this->fail(); } catch (Doctrine_Query_Exception $e) { $this->pass(); } } - - + public function testOrQuerySupport() { $q1 = Doctrine_Query::create() @@ -212,30 +218,31 @@ public function testOrQuerySupport() ->from('User u') ->leftJoin('u.Phonenumber p') ->where('u.name = ?') - ->orWhere('u.loginname = ?'); - + ->orWhere('u.loginname = ?') + ; + $q2 = Doctrine_Query::create() ->select('u.id') ->from('User u') ->leftJoin('u.Phonenumber p') - ->where('u.name = ? OR u.loginname = ?'); + ->where('u.name = ? OR u.loginname = ?') + ; $this->assertEqual( $q1->getSqlQuery(), - 'SELECT e.id AS e__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id ' . + 'SELECT e.id AS e__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id '. 'WHERE (e.name = ? OR e.loginname = ? AND (e.type = 0))' ); - + $items1 = $q1->execute(array('zYne', 'jwage'), Doctrine_Core::HYDRATE_ARRAY); $items2 = $q2->execute(array('zYne', 'jwage'), Doctrine_Core::HYDRATE_ARRAY); $this->assertEqual(count($items1), count($items2)); - + $q1->free(); $q2->free(); } - public function testOrQuerySupport2() { $q1 = Doctrine_Query::create() @@ -244,20 +251,22 @@ public function testOrQuerySupport2() ->leftJoin('u.Phonenumber p') ->where('u.name = ?') ->andWhere('u.loginname = ?') - ->orWhere('u.id = ?'); - + ->orWhere('u.id = ?') + ; + $q2 = Doctrine_Query::create() ->select('u.id') ->from('User u') ->leftJoin('u.Phonenumber p') - ->where('(u.name = ? AND u.loginname = ?) OR (u.id = ?)'); + ->where('(u.name = ? AND u.loginname = ?) OR (u.id = ?)') + ; $this->assertEqual( $q1->getSqlQuery(), - 'SELECT e.id AS e__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id ' . + 'SELECT e.id AS e__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id '. 'WHERE (e.name = ? AND e.loginname = ? OR e.id = ? AND (e.type = 0))' ); - + $items1 = $q1->execute(array('jon', 'jwage', 4), Doctrine_Core::HYDRATE_ARRAY); $items2 = $q2->execute(array('jon', 'jwage', 4), Doctrine_Core::HYDRATE_ARRAY); @@ -266,8 +275,7 @@ public function testOrQuerySupport2() $q1->free(); $q2->free(); } - - + public function testOrQuerySupport3() { $q1 = Doctrine_Query::create() @@ -276,22 +284,24 @@ public function testOrQuerySupport3() ->leftJoin('u.Phonenumber p') ->where("u.name = 'jon'") ->andWhere("u.loginname = 'jwage'") - ->orWhere("u.id = 4") - ->orWhere("u.id = 5") - ->andWhere("u.name LIKE 'Arnold%'"); - + ->orWhere('u.id = 4') + ->orWhere('u.id = 5') + ->andWhere("u.name LIKE 'Arnold%'") + ; + $q2 = Doctrine_Query::create() ->select('u.id') ->from('User u') ->leftJoin('u.Phonenumber p') - ->where("((u.name = 'jon' AND u.loginname = 'jwage') OR (u.id = 4 OR (u.id = 5 AND u.name LIKE 'Arnold%')))"); + ->where("((u.name = 'jon' AND u.loginname = 'jwage') OR (u.id = 4 OR (u.id = 5 AND u.name LIKE 'Arnold%')))") + ; $this->assertEqual( $q1->getSqlQuery(), - "SELECT e.id AS e__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id " . + 'SELECT e.id AS e__id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id '. "WHERE (e.name = 'jon' AND e.loginname = 'jwage' OR e.id = 4 OR e.id = 5 AND e.name LIKE 'Arnold%' AND (e.type = 0))" ); - + $items1 = $q1->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $items2 = $q2->execute(array(), Doctrine_Core::HYDRATE_ARRAY); @@ -300,32 +310,30 @@ public function testOrQuerySupport3() $q1->free(); $q2->free(); } - + public function testParseTableAliasesWithBetweenInWhereClause() { - $q1 = Doctrine_Query::create() ->select('u.id') ->from('QueryTest_User u') - ->where("now() BETWEEN u.QueryTest_Subscription.begin AND u.QueryTest_Subscription.begin") - ->addWhere( 'u.id != 5' ) - ; - + ->where('now() BETWEEN u.QueryTest_Subscription.begin AND u.QueryTest_Subscription.begin') + ->addWhere('u.id != 5') + ; + $expected = 'SELECT q.id AS q__id FROM query_test__user q LEFT JOIN query_test__subscription q2 ON q.subscriptionid = q2.id WHERE (datetime(\'now\') BETWEEN q2.begin AND q2.begin AND q.id != 5)'; - - $this->assertEqual( $q1->getSqlQuery(), $expected ); - - } + $this->assertEqual($q1->getSqlQuery(), $expected); + } public function testQuoteAndBracketUsageAsValueInQuery() { $q = Doctrine_Query::create() ->select('u.id') ->from('User u') - ->where("u.name = 'John O\'Connor (West)'"); + ->where("u.name = 'John O\\'Connor (West)'") + ; - $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id FROM entity e WHERE (e.name = 'John O\'Connor (West)' AND (e.type = 0))"); + $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id FROM entity e WHERE (e.name = 'John O\\'Connor (West)' AND (e.type = 0))"); } public function testAsAndBracketUsageAsValueInQuery() @@ -333,7 +341,8 @@ public function testAsAndBracketUsageAsValueInQuery() $q = Doctrine_Query::create() ->select('u.id') ->from('User u') - ->where("u.name = 'Total Kjeldahl Nitrogen (TKN) as N'"); + ->where("u.name = 'Total Kjeldahl Nitrogen (TKN) as N'") + ; $this->assertEqual($q->getSqlQuery(), "SELECT e.id AS e__id FROM entity e WHERE (e.name = 'Total Kjeldahl Nitrogen (TKN) as N' AND (e.type = 0))"); } @@ -369,19 +378,19 @@ public function testSetQueryClassTableAttribute() $userTable->setAttribute(Doctrine_Core::ATTR_QUERY_CLASS, 'Doctrine_Query'); } - + public function testNoLimitSubqueryIfXToOneSelected() { - $q = Doctrine_Query::create() - ->select('u.name, e.address') - ->from('User u') - ->leftJoin('u.Email e') - ->leftJoin('u.Phonenumber p') - ->distinct() - ->limit(1); - - $this->assertEqual($q->getSqlQuery(), "SELECT DISTINCT e.id AS e__id, e.name AS e__name, e2.id AS e2__id, e2.address AS e2__address FROM entity e LEFT JOIN email e2 ON e.email_id = e2.id LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0) LIMIT 1"); + ->select('u.name, e.address') + ->from('User u') + ->leftJoin('u.Email e') + ->leftJoin('u.Phonenumber p') + ->distinct() + ->limit(1) + ; + + $this->assertEqual($q->getSqlQuery(), 'SELECT DISTINCT e.id AS e__id, e.name AS e__name, e2.id AS e2__id, e2.address AS e2__address FROM entity e LEFT JOIN email e2 ON e.email_id = e2.id LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (e.type = 0) LIMIT 1'); } } @@ -391,4 +400,4 @@ public function preQuery() { $this->where('u.id = 4'); } -} \ No newline at end of file +} diff --git a/tests/RawSqlTestCase.php b/tests/RawSqlTestCase.php index 9d7e74e3c..77bf2c4ea 100644 --- a/tests/RawSqlTestCase.php +++ b/tests/RawSqlTestCase.php @@ -21,26 +21,32 @@ /** * Doctrine_RawSql_TestCase - * This class tests the functinality of Doctrine_RawSql component + * This class tests the functinality of Doctrine_RawSql component. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1181 $ + * * @author Konsta Vesterinen + * + * @internal + * + * @coversNothing */ -class Doctrine_RawSql_TestCase extends Doctrine_UnitTestCase +class Doctrine_RawSql_TestCase extends Doctrine_UnitTestCase { public function testQueryParser() { $sql = 'SELECT {p.*} FROM photos p'; $query = new Doctrine_RawSql($this->connection); $query->parseDqlQuery($sql); - - $this->assertEqual($query->getSqlQueryPart('from'), array('photos p')); + $this->assertEqual($query->getSqlQueryPart('from'), array('photos p')); $sql = 'SELECT {p.*} FROM (SELECT p.* FROM photos p LEFT JOIN photos_tags t ON t.photo_id = p.id WHERE t.tag_id = 65) p LEFT JOIN photos_tags t ON t.photo_id = p.id WHERE p.can_see = -1 AND t.tag_id = 62 LIMIT 200'; $query->parseDqlQuery($sql); @@ -50,7 +56,7 @@ public function testQueryParser() $this->assertEqual($query->getSqlQueryPart('limit'), array(200)); } - public function testAsteriskOperator() + public function testAsteriskOperator() { // Selecting with * @@ -67,7 +73,7 @@ public function testAsteriskOperator() $this->assertEqual($coll->count(), 11); } - public function testLazyPropertyLoading() + public function testLazyPropertyLoading() { $query = new Doctrine_RawSql($this->connection); $this->connection->clear(); @@ -85,19 +91,20 @@ public function testLazyPropertyLoading() $this->assertEqual($coll->count(), 11); $this->assertEqual($coll[0]->state(), Doctrine_Record::STATE_PROXY); - $this->assertEqual($coll[3]->state(), Doctrine_Record::STATE_PROXY); + $this->assertEqual($coll[3]->state(), Doctrine_Record::STATE_PROXY); } - public function testSmartMapping() + + public function testSmartMapping() { $query = new Doctrine_RawSql($this->connection); // smart component mapping (no need for additional addComponent call - + $query->parseDqlQuery('SELECT {entity.name}, {entity.id} FROM entity'); $fields = $query->getFields(); $this->assertEqual($fields, array('entity.name', 'entity.id')); - - $coll = $query->execute(); + + $coll = $query->execute(); $this->assertEqual($coll->count(), 11); @@ -105,7 +112,7 @@ public function testSmartMapping() $this->assertEqual($coll[3]->state(), Doctrine_Record::STATE_PROXY); } - public function testMultipleComponents() + public function testMultipleComponents() { $query = new Doctrine_RawSql($this->connection); // multi component fetching @@ -120,14 +127,14 @@ public function testMultipleComponents() $this->assertEqual($coll->count(), 11); $count = $this->conn->count(); - + $coll[4]->Phonenumber[0]->phonenumber; $this->assertEqual($count, $this->conn->count()); $coll[5]->Phonenumber[0]->phonenumber; $this->assertEqual($count, $this->conn->count()); } - + public function testAliasesAreSupportedInAddComponent() { $query = new Doctrine_RawSql(); @@ -142,36 +149,36 @@ public function testAliasesAreSupportedInAddComponent() $this->assertEqual($coll->count(), 11); $count = $this->conn->count(); - + $coll[4]['Phonenumber'][0]['phonenumber']; $this->assertEqual($count, $this->conn->count()); $coll[5]['Phonenumber'][0]['phonenumber']; $this->assertEqual($count, $this->conn->count()); } + public function testPrimaryKeySelectForcing() { // forcing the select of primary key fields - + $query = new Doctrine_RawSql($this->connection); $query->parseDqlQuery('SELECT {entity.name} FROM entity'); - + $coll = $query->execute(); - + $this->assertEqual($coll->count(), 11); $this->assertTrue(is_numeric($coll[0]->id)); $this->assertTrue(is_numeric($coll[3]->id)); $this->assertTrue(is_numeric($coll[7]->id)); } - + public function testConvenienceMethods() { - $query = new Doctrine_RawSql($this->connection); $query->select('{entity.name}')->from('entity'); $query->addComponent('entity', 'User'); - + $coll = $query->execute(); $this->assertEqual($coll->count(), 8); @@ -180,7 +187,7 @@ public function testConvenienceMethods() $this->assertTrue(is_numeric($coll[7]->id)); } - public function testColumnAggregationInheritance() + public function testColumnAggregationInheritance() { // forcing the select of primary key fields @@ -196,7 +203,7 @@ public function testColumnAggregationInheritance() $this->assertTrue(is_numeric($coll[7]->id)); } - public function testColumnAggregationInheritanceWithOrderBy() + public function testColumnAggregationInheritanceWithOrderBy() { // forcing the select of primary key fields @@ -205,8 +212,7 @@ public function testColumnAggregationInheritanceWithOrderBy() $query->parseDqlQuery('SELECT {entity.name} FROM entity ORDER BY entity.name'); $query->addComponent('entity', 'User'); - $this->assertEqual($query->getSqlQuery(), "SELECT entity.name AS entity__name, entity.id AS entity__id FROM entity WHERE entity.type = 0 ORDER BY entity.name"); - + $this->assertEqual($query->getSqlQuery(), 'SELECT entity.name AS entity__name, entity.id AS entity__id FROM entity WHERE entity.type = 0 ORDER BY entity.name'); $coll = $query->execute(); @@ -214,17 +220,16 @@ public function testColumnAggregationInheritanceWithOrderBy() $this->assertTrue(is_numeric($coll[0]->id)); $this->assertTrue(is_numeric($coll[3]->id)); $this->assertTrue(is_numeric($coll[7]->id)); - } - public function testQueryParser2() + public function testQueryParser2() { $query = new Doctrine_RawSql(); - + $query->parseDqlQuery("SELECT {entity.name} FROM (SELECT entity.name FROM entity WHERE entity.name = 'something') WHERE entity.id = 2 ORDER BY entity.name"); $this->assertEqual($query->getSqlQuery(), - "SELECT entity.name AS entity__name, entity.id AS entity__id FROM (SELECT entity.name FROM entity WHERE entity.name = 'something') WHERE entity.id = 2 ORDER BY entity.name"); + "SELECT entity.name AS entity__name, entity.id AS entity__id FROM (SELECT entity.name FROM entity WHERE entity.name = 'something') WHERE entity.id = 2 ORDER BY entity.name"); } public function testSelectingWithoutIdentifiersOnRootComponent() @@ -239,7 +244,7 @@ public function testSelectingWithoutIdentifiersOnRootComponent() $this->assertEqual(count($coll), 3); } - + public function testSwitchingTheFieldOrder() { $query = new Doctrine_RawSql(); @@ -252,47 +257,47 @@ public function testSwitchingTheFieldOrder() $this->assertEqual(count($coll), 3); } - + public function testParseQueryPartShouldAddPartIfNotSelectAndAppend() { - $query = new Doctrine_Rawsql(); - $query->parseDqlQueryPart("test", "test", true); - $parts = $query->getSqlParts(); - $this->assertTrue(isset($parts["test"])); - $this->assertTrue(is_array($parts["test"])); - $this->assertTrue(isset($parts["test"][0])); - $this->assertEqual("test", $parts["test"][0]); + $query = new Doctrine_Rawsql(); + $query->parseDqlQueryPart('test', 'test', true); + $parts = $query->getSqlParts(); + $this->assertTrue(isset($parts['test'])); + $this->assertTrue(is_array($parts['test'])); + $this->assertTrue(isset($parts['test'][0])); + $this->assertEqual('test', $parts['test'][0]); } - + public function testParseQueryShouldExtractGroupBy() { $query = new Doctrine_RawSql(); - $query->parseDqlQuery("having group"); + $query->parseDqlQuery('having group'); $parts = $query->getSqlParts(); - $this->assertEqual($parts["having"][0], "group"); + $this->assertEqual($parts['having'][0], 'group'); } public function testThrowExceptionIfFieldNameIsOnWrongForm() - { - $query = new Doctrine_RawSql(); - $query->parseDqlQueryPart("select", "{test}"); - try{ - $query->getSqlQuery(); - $this->fail("Should throw exception"); - } catch(Doctrine_RawSql_Exception $exception) { - $this->assertEqual($exception->getMessage(), "All selected fields in Sql query must be in format tableAlias.fieldName"); - } + { + $query = new Doctrine_RawSql(); + $query->parseDqlQueryPart('select', '{test}'); + try { + $query->getSqlQuery(); + $this->fail('Should throw exception'); + } catch (Doctrine_RawSql_Exception $exception) { + $this->assertEqual($exception->getMessage(), 'All selected fields in Sql query must be in format tableAlias.fieldName'); + } } public function testThrowExceptionIfAliasDoesNotExist() - { - $query = new Doctrine_RawSql(); - $query->parseDqlQueryPart("select", "{test.test}"); - try { - $query->getSqlQuery(); - $this->fail("Should throw exception"); - } catch(Doctrine_RawSql_Exception $exception) { - $this->assertEqual($exception->getMessage(), "The associated component for table alias test couldn't be found."); - } + { + $query = new Doctrine_RawSql(); + $query->parseDqlQueryPart('select', '{test.test}'); + try { + $query->getSqlQuery(); + $this->fail('Should throw exception'); + } catch (Doctrine_RawSql_Exception $exception) { + $this->assertEqual($exception->getMessage(), "The associated component for table alias test couldn't be found."); + } } } diff --git a/tests/Record/CascadingDeleteTestCase.php b/tests/Record/CascadingDeleteTestCase.php index 3dd18f43d..5ccd135e7 100644 --- a/tests/Record/CascadingDeleteTestCase.php +++ b/tests/Record/CascadingDeleteTestCase.php @@ -20,20 +20,28 @@ */ /** - * Doctrine_CascadingDelete_TestCase + * Doctrine_CascadingDelete_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Record_CascadingDelete_TestCase extends Doctrine_UnitTestCase +class Doctrine_Record_CascadingDelete_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() { $this->tables = array(); @@ -46,9 +54,10 @@ public function prepareTables() $this->tables[] = 'CascadeDelete_ManyManyAToB'; parent::prepareTables(); } + public function testCascadingDeleteEmulation() { - $r = new ForeignKeyTest; + $r = new ForeignKeyTest(); $r->name = 'Parent'; $r->Children[0]->name = 'Child 1'; $this->assertEqual($r->id, null); @@ -61,12 +70,12 @@ public function testCascadingDeleteEmulation() $this->connection->clear(); $r = $this->connection->query('FROM ForeignKeyTest'); - + $this->assertEqual($r->count(), 2); - + // should delete the first child $r[0]->delete(); - + $this->assertEqual(Doctrine_Record::STATE_TCLEAN, $r[0]->state()); $this->assertEqual(Doctrine_Record::STATE_TCLEAN, $r[0]->Children[0]->state()); @@ -76,13 +85,13 @@ public function testCascadingDeleteEmulation() $this->assertEqual($r->count(), 0); } - + public function testCascadingDeleteEmulationWithListenerInvocations() { $cascadeListener = new CascadeDeleteListener($this); $this->conn->getTable('ForeignKeyTest')->addRecordListener($cascadeListener); - - $r = new ForeignKeyTest; + + $r = new ForeignKeyTest(); $r->name = 'Parent'; $r->Children[0]->name = 'Child 1'; $r->Children[0]->Children[0]->name = 'Child 1 Child 1'; @@ -92,27 +101,27 @@ public function testCascadingDeleteEmulationWithListenerInvocations() $this->connection->clear(); $r = $this->connection->query('FROM ForeignKeyTest'); - + $this->assertEqual($r->count(), 4); // should delete the children recursively $r[0]->delete(); - + // validate listener invocations $this->assertTrue($cascadeListener->preDeleteInvoked); $this->assertEqual(4, $cascadeListener->preDeleteInvocationCount); $this->assertTrue($cascadeListener->postDeleteInvoked); $this->assertEqual(4, $cascadeListener->postDeleteInvocationCount); $cascadeListener->reset(); - + $this->connection->clear(); $r = $this->connection->query('FROM ForeignKeyTest'); $this->assertEqual($r->count(), 0); } - + public function testBidirectionalCascadeDeleteDoesNotCauseInfiniteLoop() - { + { $house = new CascadeDelete_House(); $house->bathrooms = 4; $owner = new CascadeDelete_HouseOwner(); @@ -120,21 +129,20 @@ public function testBidirectionalCascadeDeleteDoesNotCauseInfiniteLoop() $owner->house = $house; $house->owner = $owner; $owner->save(); - + $this->assertEqual(Doctrine_Record::STATE_CLEAN, $owner->state()); $this->assertEqual(Doctrine_Record::STATE_CLEAN, $house->state()); $this->assertTrue($owner->exists()); $this->assertTrue($house->exists()); - + $house->delete(); - + $this->assertEqual(Doctrine_Record::STATE_TCLEAN, $owner->state()); $this->assertEqual(Doctrine_Record::STATE_TCLEAN, $house->state()); $this->assertFalse($owner->exists()); $this->assertFalse($house->exists()); - } - + public function testCascadingDeleteInOneToZeroOrOneRelation() { $owner = new CascadeDelete_HouseOwner(); @@ -144,11 +152,10 @@ public function testCascadingDeleteInOneToZeroOrOneRelation() $owner->delete(); $this->pass(); } catch (Doctrine_Exception $e) { - $this->fail("Failed to delete record. Message:" . $e->getMessage()); + $this->fail('Failed to delete record. Message:'.$e->getMessage()); } - } - + public function testDeletionOfCompositeKeys() { $compItem = new CascadeDelete_CompositeKeyItem(); @@ -156,11 +163,11 @@ public function testDeletionOfCompositeKeys() $compItem->id2 = 11; $compItem->save(); $compItem->delete(); - + $this->assertEqual(Doctrine_Record::STATE_TCLEAN, $compItem->state()); $this->assertFalse($compItem->exists()); } - + public function testCascadeDeleteManyMany() { $a1 = new CascadeDelete_ManyManySideA(); @@ -168,17 +175,17 @@ public function testCascadeDeleteManyMany() $b1 = new CascadeDelete_ManyManySideB(); $b1->name = 'other'; $a1->Bs[] = $b1; - //$b1->As[] = $a1; <- This causes 2 insertions into the AToB table => BUG - + // $b1->As[] = $a1; <- This causes 2 insertions into the AToB table => BUG + $a1->save(); - + $a1->delete(); - + $this->assertEqual(Doctrine_Record::STATE_TCLEAN, $a1->state()); $this->assertFalse($a1->exists()); $this->assertEqual(Doctrine_Record::STATE_TCLEAN, $b1->state()); $this->assertFalse($b1->exists()); - + $a1->refreshRelated('assocsA'); $this->assertEqual(0, count($a1->assocsA)); $b1->refreshRelated('assocsB'); @@ -188,127 +195,146 @@ public function testCascadeDeleteManyMany() /* This listener is used to verify the correct invocations of listeners during the delete procedure, as well as to verify the object states at the defined points. */ -class CascadeDeleteListener extends Doctrine_Record_Listener { - +class CascadeDeleteListener extends Doctrine_Record_Listener +{ private $_test; public $preDeleteInvoked = false; public $preDeleteInvocationCount = 0; public $postDeleteInvoked = false; public $postDeleteInvocationCount = 0; - - public function __construct($test) { + + public function __construct($test) + { $this->_test = $test; } - - public function preDelete(Doctrine_Event $event) { + + public function preDelete(Doctrine_Event $event) + { $this->_test->assertEqual(Doctrine_Record::STATE_CLEAN, $event->getInvoker()->state()); $this->preDeleteInvoked = true; - $this->preDeleteInvocationCount++; + ++$this->preDeleteInvocationCount; } - - public function postDelete(Doctrine_Event $event) { + + public function postDelete(Doctrine_Event $event) + { $this->_test->assertEqual(Doctrine_Record::STATE_TCLEAN, $event->getInvoker()->state()); $this->postDeleteInvoked = true; - $this->postDeleteInvocationCount++; + ++$this->postDeleteInvocationCount; } - - public function reset() { + + public function reset() + { $this->preDeleteInvoked = false; $this->preDeleteInvocationCount = 0; $this->postDeleteInvoked = false; $this->postDeleteInvocationCount = 0; } - } /* The following is a typical one-to-one cascade => delete scenario. The association is bidirectional, as is the cascade. */ -class CascadeDelete_HouseOwner extends Doctrine_Record { - public function setTableDefinition() { +class CascadeDelete_HouseOwner extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('name', 'string', 50); } - public function setUp() { + + public function setUp() + { $this->hasOne('CascadeDelete_House as house', array( - 'local' => 'id', 'foreign' => 'owner_id', - 'cascade' => array('delete'))); + 'local' => 'id', 'foreign' => 'owner_id', + 'cascade' => array('delete'))); } } -class CascadeDelete_House extends Doctrine_Record { - public function setTableDefinition() { +class CascadeDelete_House extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('bathrooms', 'integer', 1); $this->hasColumn('owner_id', 'integer', 4); } - public function setUp() { + + public function setUp() + { $this->hasOne('CascadeDelete_HouseOwner as owner', array( - 'local' => 'owner_id', 'foreign' => 'id', - 'cascade' => array('delete'))); + 'local' => 'owner_id', 'foreign' => 'id', + 'cascade' => array('delete'))); } } - /* The following is just a stand-alone class with a composite-key to test the new deletion routines with composite keys. Composite foreign keys are currently not supported, so we can't test this class in a cascade => delete scenario. */ -class CascadeDelete_CompositeKeyItem extends Doctrine_Record { - public function setTableDefinition() { +class CascadeDelete_CompositeKeyItem extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id1', 'integer', 4, array('primary' => true)); $this->hasColumn('id2', 'integer', 4, array('primary' => true)); } } - /* The following is an app-level cascade => delete setup of a many-many association - Note that such a scenario is very unlikely in the real world and also pretty + Note that such a scenario is very unlikely in the real world and also pretty slow. */ -class CascadeDelete_ManyManySideA extends Doctrine_Record { - public function setTableDefinition() { +class CascadeDelete_ManyManySideA extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('name', 'string', 4); } - public function setUp() { + + public function setUp() + { $this->hasMany('CascadeDelete_ManyManySideB as Bs', array( - 'local' => 'a_id', 'foreign' => 'b_id', - 'refClass' => 'CascadeDelete_ManyManyAToB', - 'cascade' => array('delete'))); - + 'local' => 'a_id', 'foreign' => 'b_id', + 'refClass' => 'CascadeDelete_ManyManyAToB', + 'cascade' => array('delete'))); + // overrides the doctrine-generated relation to the association class // in order to apply the app-level cascade $this->hasMany('CascadeDelete_ManyManyAToB as assocsA', array( - 'local' => 'id', 'foreign' => 'a_id', - 'cascade' => array('delete'))); + 'local' => 'id', 'foreign' => 'a_id', + 'cascade' => array('delete'))); } } -class CascadeDelete_ManyManySideB extends Doctrine_Record { - public function setTableDefinition() { +class CascadeDelete_ManyManySideB extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('name', 'string', 4); } - public function setUp() { + + public function setUp() + { $this->hasMany('CascadeDelete_ManyManySideA as As', array( - 'local' => 'b_id', 'foreign' => 'a_id', - 'refClass' => 'CascadeDelete_ManyManyAToB', - 'cascade' => array('delete'))); - + 'local' => 'b_id', 'foreign' => 'a_id', + 'refClass' => 'CascadeDelete_ManyManyAToB', + 'cascade' => array('delete'))); + // overrides the doctrine-generated relation to the association class // in order to apply the app-level cascade $this->hasMany('CascadeDelete_ManyManyAToB as assocsB', array( - 'local' => 'id', 'foreign' => 'b_id', - 'cascade' => array('delete'))); + 'local' => 'id', 'foreign' => 'b_id', + 'cascade' => array('delete'))); } } -class CascadeDelete_ManyManyAToB extends Doctrine_Record { - public function setTableDefinition() { +class CascadeDelete_ManyManyAToB extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('a_id', 'integer', 4, array('primary' => true)); $this->hasColumn('b_id', 'integer', 4, array('primary' => true)); } } - - diff --git a/tests/Record/FilterTestCase.php b/tests/Record/FilterTestCase.php index 7b82b45f7..1c1eaf5ad 100644 --- a/tests/Record/FilterTestCase.php +++ b/tests/Record/FilterTestCase.php @@ -20,33 +20,42 @@ */ /** - * Doctrine_Record_Filter_TestCase + * Doctrine_Record_Filter_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Record_Filter_TestCase extends Doctrine_UnitTestCase +class Doctrine_Record_Filter_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() { $this->tables = array('CompositeRecord', 'RelatedCompositeRecord'); - + parent::prepareTables(); } + public function testStandardFiltersThrowsExceptionWhenGettingUnknownProperties() { $u = new User(); - + try { $u->unknown; - + $this->fail(); } catch (Doctrine_Record_Exception $e) { $this->pass(); @@ -56,10 +65,10 @@ public function testStandardFiltersThrowsExceptionWhenGettingUnknownProperties() public function testStandardFiltersThrowsExceptionWhenSettingUnknownProperties() { $u = new User(); - + try { $u->unknown = 'something'; - + $this->fail(); } catch (Doctrine_Record_Exception $e) { $this->pass(); @@ -69,9 +78,9 @@ public function testStandardFiltersThrowsExceptionWhenSettingUnknownProperties() public function testCompoundFilterSupportsAccessingRelatedComponentProperties() { $u = new CompositeRecord(); - + try { - $u->name = 'someone'; + $u->name = 'someone'; $u->address = 'something'; $u->save(); @@ -90,11 +99,12 @@ public function setTableDefinition() { $this->hasColumn('name', 'string'); } + public function setUp() { - $this->hasOne('RelatedCompositeRecord as Related', array('foreign' => 'foreign_id')); + $this->hasOne('RelatedCompositeRecord as Related', array('foreign' => 'foreign_id')); - $this->unshiftFilter(new Doctrine_Record_Filter_Compound(array('Related'))); + $this->unshiftFilter(new Doctrine_Record_Filter_Compound(array('Related'))); } } class RelatedCompositeRecord extends Doctrine_Record diff --git a/tests/Record/FromArrayTestCase.php b/tests/Record/FromArrayTestCase.php index ee6922545..885e090e9 100755 --- a/tests/Record/FromArrayTestCase.php +++ b/tests/Record/FromArrayTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Record_FromArray_TestCase + * Doctrine_Record_FromArray_TestCase. * - * @package Doctrine * @author Stephen Ostrow * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Record_FromArray_TestCase extends Doctrine_UnitTestCase { @@ -38,10 +44,10 @@ public function prepareTables() { parent::prepareTables(); } - + public function prepareData() { - # Create an existing group + // Create an existing group $group = new Group(); $group->name = 'Group One'; $group->save(); @@ -53,28 +59,28 @@ public function testFromArrayRecord() $user = new User(); $userArray = $user->toArray(); - # add a Phonenumber + // add a Phonenumber $userArray['Phonenumber'][0]['phonenumber'] = '555 321'; - - # add an Email address + + // add an Email address $userArray['Email']['address'] = 'johndow@mail.com'; - - # add group - $userArray['Group'][0]['name'] = 'New Group'; # This is a n-m relationship - # add a group which exists - $userArray['Group'][1]['_identifier'] = $this->previous_group; # This is a n-m relationship where the group was made in prepareData - + + // add group + $userArray['Group'][0]['name'] = 'New Group'; // This is a n-m relationship + // add a group which exists + $userArray['Group'][1]['_identifier'] = $this->previous_group; // This is a n-m relationship where the group was made in prepareData + $user->fromArray($userArray); - + $this->assertEqual($user->Phonenumber->count(), 1); $this->assertEqual($user->Phonenumber[0]->phonenumber, '555 321'); $this->assertEqual($user->Group[0]->name, 'New Group'); $this->assertEqual($user->Group[1]->name, 'Group One'); - + try { - $user->save(); - } catch (Exception $e ) { - $this->fail("Failed saving with " . $e->getMessage()); + $user->save(); + } catch (Exception $e) { + $this->fail('Failed saving with '.$e->getMessage()); } } @@ -92,4 +98,4 @@ public function testFromArrayAfterSaveRecord() $this->assertEqual($user->Group[0]->name, 'Group One'); $this->assertEqual($user->Group[1]->name, 'New Group'); } -} \ No newline at end of file +} diff --git a/tests/Record/GeneratorTestCase.php b/tests/Record/GeneratorTestCase.php index c9e963278..50ea64d7f 100644 --- a/tests/Record/GeneratorTestCase.php +++ b/tests/Record/GeneratorTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Record_Generator_TestCase + * Doctrine_Record_Generator_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Record_Generator_TestCase extends Doctrine_UnitTestCase +class Doctrine_Record_Generator_TestCase extends Doctrine_UnitTestCase { public function testGeneratorComponentBinding() { @@ -44,9 +50,9 @@ public function testGeneratorComponentBinding() $i->Translation['EN']->title = 'en test'; $i->Translation['FR']->title = 'fr test'; $i->save(); - + $this->pass(); - + $this->assertTrue($i->id > 0); $this->assertEqual($i->Translation['EN']->title, 'en test'); $this->assertEqual($i->Translation['FR']->title, 'fr test'); @@ -64,9 +70,9 @@ public function setTableDefinition() $this->hasColumn('name', 'string'); $this->hasColumn('title', 'string'); } - + public function setUp() { $this->actAs('I18n', array('fields' => array('title'))); } -} \ No newline at end of file +} diff --git a/tests/Record/HookTestCase.php b/tests/Record/HookTestCase.php index 1f970224d..dff77bebf 100644 --- a/tests/Record/HookTestCase.php +++ b/tests/Record/HookTestCase.php @@ -20,22 +20,30 @@ */ /** - * Doctrine_Record_Hook_TestCase + * Doctrine_Record_Hook_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Record_Hook_TestCase extends Doctrine_UnitTestCase +class Doctrine_Record_Hook_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } - public function prepareTables() - { + { + } + + public function prepareTables() + { $this->tables = array('RecordHookTest', 'SoftDeleteTest'); parent::prepareTables(); @@ -44,7 +52,7 @@ public function prepareTables() public function testInsertHooksGetInvoked() { $r = new RecordHookTest(); - + $r->name = 'record'; $r->save(); @@ -83,7 +91,7 @@ public function testSoftDelete() { $r = new SoftDeleteTest(); $r->name = 'something'; - $r->something ='something'; + $r->something = 'something'; $r->save(); $this->assertEqual($r->name, 'something'); @@ -96,7 +104,7 @@ public function testSoftDelete() $r->delete(); $this->assertEqual($r->state(), Doctrine_Record::STATE_CLEAN); $this->assertTrue(strtotime($r->deleted_at) > 0); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } } diff --git a/tests/Record/InheritanceTestCase.php b/tests/Record/InheritanceTestCase.php index d10ca949e..b02504ee2 100644 --- a/tests/Record/InheritanceTestCase.php +++ b/tests/Record/InheritanceTestCase.php @@ -1,22 +1,27 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Record_Inheritance_TestCase extends Doctrine_UnitTestCase { public function prepareTables() @@ -24,6 +29,7 @@ public function prepareTables() $this->tables = array_merge($this->tables, array('SymfonyRecord')); parent::prepareTables(); } + public function prepareData() { parent::prepareData(); @@ -53,7 +59,5 @@ public function testInstantiatingRecordWithAbstractParents() // does it have the expected data? $this->assertEqual($record['name'], 'Test me'); - - } } diff --git a/tests/Record/LockTestCase.php b/tests/Record/LockTestCase.php index b061918cd..fb9a75c1c 100644 --- a/tests/Record/LockTestCase.php +++ b/tests/Record/LockTestCase.php @@ -1,14 +1,23 @@ tables[] = 'rec1'; $this->tables[] = 'rec2'; parent::prepareTables(); - } - - public function prepareData() { } - + } + + public function prepareData() + { + } + public function testDeleteRecords() { $rec1 = new Rec1(); @@ -16,7 +25,7 @@ public function testDeleteRecords() $rec1->Account = new Rec2(); $rec1->Account->address = 'Some address'; $rec1->save(); - + $rec1->delete(); $this->pass(); } diff --git a/tests/Record/SaveBlankRecordTestCase.php b/tests/Record/SaveBlankRecordTestCase.php index 4d7255f76..e36f826ee 100644 --- a/tests/Record/SaveBlankRecordTestCase.php +++ b/tests/Record/SaveBlankRecordTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Record_State_TestCase + * Doctrine_Record_State_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Record_SaveBlankRecord_TestCase extends Doctrine_UnitTestCase { @@ -39,25 +45,26 @@ public function prepareTables() parent::prepareTables(); } - + public function prepareData() - { } + { + } public function testSaveBlankRecord() { $user = new MyUser(); $user->state('TDIRTY'); $user->save(); - + $this->assertTrue(isset($user['id']) && $user['id']); } - + public function testSaveBlankRecord2() { $group = new MyUserGroup(); $group->state('TDIRTY'); $group->save(); - + $this->assertTrue(isset($group['id']) && $group['id']); } -} \ No newline at end of file +} diff --git a/tests/Record/SerializeUnserializeTestCase.php b/tests/Record/SerializeUnserializeTestCase.php index ae07ffc9c..8eaec238e 100644 --- a/tests/Record/SerializeUnserializeTestCase.php +++ b/tests/Record/SerializeUnserializeTestCase.php @@ -20,19 +20,24 @@ */ /** - * Doctrine_Record_SerializeUnserialize_TestCase + * Doctrine_Record_SerializeUnserialize_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Record_SerializeUnserialize_TestCase extends Doctrine_UnitTestCase +class Doctrine_Record_SerializeUnserialize_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { $this->tables[] = 'SerializeTest'; @@ -40,9 +45,10 @@ public function prepareTables() parent::prepareTables(); } - + public function prepareData() - { } + { + } public function testSerializeUnserialize() { @@ -60,13 +66,13 @@ public function testSerializeUnserialize() $object->timestamptest = '2007-08-07 11:55:00'; $object->timetest = '11:55:00'; $object->datetest = '2007-08-07'; - + $object->save(); - - $object_before = clone($object); + + $object_before = clone $object; $serialized = serialize($object); $object_after = unserialize($serialized); - + $this->assertIdentical($object_before->booltest, $object_after->booltest); $this->assertIdentical($object_before->integertest, $object_after->integertest); $this->assertIdentical($object_before->floattest, $object_after->floattest); @@ -80,38 +86,33 @@ public function testSerializeUnserialize() $this->assertIdentical($object_before->timestamptest, $object_after->timestamptest); $this->assertIdentical($object_before->timetest, $object_after->timetest); $this->assertIdentical($object_before->datetest, $object_after->datetest); - } - + public function testSerializeUnserializeRecord() { $test = new TestRecord(); $test->save(); - + $object = new SerializeTest(); $object->objecttest = $test; - + $object->save(); - - $object_before = clone($object); - + + $object_before = clone $object; + $serialized = serialize($object); $object_after = unserialize($serialized); - + $this->assertIdentical(get_class($object_after->objecttest), 'TestRecord'); } - } class TestObject { - private $test_field; - + public function __construct($value) { $this->test_field = $value; } - } - diff --git a/tests/Record/StateTestCase.php b/tests/Record/StateTestCase.php index fd6a136c7..fcec2ee13 100644 --- a/tests/Record/StateTestCase.php +++ b/tests/Record/StateTestCase.php @@ -20,44 +20,51 @@ */ /** - * Doctrine_Record_State_TestCase + * Doctrine_Record_State_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Record_State_TestCase extends Doctrine_UnitTestCase +class Doctrine_Record_State_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { + public function prepareTables() + { $this->tables = array('Entity'); - + parent::prepareTables(); } - public function prepareData() - { } + public function prepareData() + { + } public function testAssigningAutoincId() { $user = new User(); - + $this->assertEqual($user->id, null); - + $user->name = 'zYne'; $user->save(); $this->assertEqual($user->id, 1); - + $user->id = 2; $this->assertEqual($user->id, 2); - + $user->save(); } -} \ No newline at end of file +} diff --git a/tests/Record/SynchronizeTestCase.php b/tests/Record/SynchronizeTestCase.php index 76457457b..421671c28 100644 --- a/tests/Record/SynchronizeTestCase.php +++ b/tests/Record/SynchronizeTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Record_State_TestCase + * Doctrine_Record_State_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Record_Synchronize_TestCase extends Doctrine_UnitTestCase { @@ -38,7 +44,7 @@ public function prepareTables() { parent::prepareTables(); } - + public function prepareData() { $user = new User(); @@ -47,8 +53,8 @@ public function prepareData() $user->Phonenumber[0]->phonenumber = '555 123'; $user->Phonenumber[1]->phonenumber = '555 448'; $user->save(); - - # Create an existing group + + // Create an existing group $group = new Group(); $group->name = 'Group One'; $group->save(); @@ -67,11 +73,11 @@ public function testSynchronizeRecord() // delete a Phonenumber array_pop($userArray['Phonenumber']); - + // add group - $userArray['Group'][]['name'] = 'New Group'; # This is a n-m relationship + $userArray['Group'][]['name'] = 'New Group'; // This is a n-m relationship // add a group which exists - $userArray['Group'][1]['_identifier'] = $this->previous_group; # This is a n-m relationship where the group was made in prepareData + $userArray['Group'][1]['_identifier'] = $this->previous_group; // This is a n-m relationship where the group was made in prepareData $user->synchronizeWithArray($userArray); $this->assertEqual($user->Phonenumber->count(), 1); @@ -82,17 +88,17 @@ public function testSynchronizeRecord() // change Email $userArray['Email']['address'] = 'johndow@mail.com'; try { - $user->synchronizeWithArray($userArray); + $user->synchronizeWithArray($userArray); } catch (Exception $e) { - $this->fail($e->getMessage()); + $this->fail($e->getMessage()); } $this->assertEqual($user->Email->address, 'johndow@mail.com'); try { - $user->save(); - } catch (Exception $e ) { - $this->fail("Failed saving with " . $e->getMessage()); + $user->save(); + } catch (Exception $e) { + $this->fail('Failed saving with '.$e->getMessage()); } } @@ -118,7 +124,7 @@ public function testSynchronizeAddRecord() $userArray['Phonenumber'][] = array('phonenumber' => '333 238'); $user->synchronizeWithArray($userArray); - + $this->assertEqual($user->Phonenumber->count(), 2); $this->assertEqual($user->Phonenumber[1]->phonenumber, '333 238'); $user->save(); @@ -142,9 +148,7 @@ public function testSynchronizeRemoveRecord() { $user = Doctrine_Query::create()->from('User u, u.Email, u.Phonenumber')->fetchOne(); $userArray = $user->toArray(true); - unset($userArray['Phonenumber']); - unset($userArray['Email']); - unset($userArray['email_id']); + unset($userArray['Phonenumber'], $userArray['Email'], $userArray['email_id']); $user->synchronizeWithArray($userArray); $this->assertEqual($user->Phonenumber->count(), 0); diff --git a/tests/Record/ZeroValuesTestCase.php b/tests/Record/ZeroValuesTestCase.php index 16dcdb16d..ffb65cb1c 100644 --- a/tests/Record/ZeroValuesTestCase.php +++ b/tests/Record/ZeroValuesTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Record_State_TestCase + * Doctrine_Record_State_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Record_ZeroValues_TestCase extends Doctrine_UnitTestCase { @@ -64,7 +70,7 @@ public function testZeroValuesMaintained2() $this->assertIdentical($users[0]['is_super_admin'], false); // check for aggregate bug - $this->assertTrue( ! isset($users[0][0])); + $this->assertTrue(!isset($users[0][0])); } public function testZeroValuesMaintained3() @@ -75,5 +81,4 @@ public function testZeroValuesMaintained3() $this->assertIdentical($users[0]['is_super_admin'], false); } - } diff --git a/tests/RecordFilterTestCase.php b/tests/RecordFilterTestCase.php index b089208c3..bb301e20b 100644 --- a/tests/RecordFilterTestCase.php +++ b/tests/RecordFilterTestCase.php @@ -1,13 +1,25 @@ name = "something"; - $e->password = "123"; +/** + * @internal + * + * @coversNothing + */ +class Doctrine_Record_Filter_TestCase extends Doctrine_UnitTestCase +{ + public function prepareData() + { + } + + public function prepareTables() + { + } + public function testValueWrapper() + { + $e = new RecordFilterTest(); + $e->name = 'something'; + $e->password = '123'; $this->assertEqual($e->get('name'), 'SOMETHING'); // test repeated calls @@ -40,6 +52,5 @@ public function testValueWrapper() { $this->assertEqual($e->name, 'SOMETHING'); $this->assertEqual($e->rawGet('name'), 'something'); $this->assertEqual($e->password, '202cb962ac59075b964b07152d234b70'); - } } diff --git a/tests/RecordTestCase.php b/tests/RecordTestCase.php index dc818570b..5d9a57b2f 100644 --- a/tests/RecordTestCase.php +++ b/tests/RecordTestCase.php @@ -20,19 +20,24 @@ */ /** - * Doctrine_Record_TestCase + * Doctrine_Record_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Record_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { $this->tables[] = 'enumTest'; @@ -49,7 +54,7 @@ public function testOne2OneForeign() { $this->conn->clear(); $user = new User(); - $user->name = "Richard Linklater"; + $user->name = 'Richard Linklater'; $rel = $user->getTable()->getRelation('Account'); @@ -61,7 +66,7 @@ public function testOne2OneForeign() $this->assertEqual($account->state(), Doctrine_Record::STATE_TDIRTY); $this->assertEqual($account->entity_id->getOid(), $user->getOid()); $this->assertEqual($account->amount, 1000); - $this->assertEqual($user->name, "Richard Linklater"); + $this->assertEqual($user->name, 'Richard Linklater'); $user->save(); $this->assertEqual($account->entity_id, $user->id); @@ -73,8 +78,7 @@ public function testOne2OneForeign() $this->assertEqual($account->state(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($account->entity_id, $user->id); $this->assertEqual($account->amount, 1000); - $this->assertEqual($user->name, "Richard Linklater"); - + $this->assertEqual($user->name, 'Richard Linklater'); $user = new User(); $user->name = 'John Rambo'; @@ -90,11 +94,9 @@ public function testOne2OneForeign() $this->assertEqual($account->entity_id, $user->id); $this->assertEqual($account->amount, 2000); - $user = $user->getTable()->find($user->id); $this->assertEqual($user->state(), Doctrine_Record::STATE_CLEAN); - $account = $user->Account; $this->assertTrue($account instanceof Account); @@ -103,8 +105,7 @@ public function testOne2OneForeign() $this->assertEqual($account->entity_id, $user->id); $this->assertEqual($account->amount, 2000); - $this->assertEqual($user->name, "John Rambo"); - + $this->assertEqual($user->name, 'John Rambo'); } public function testIssetForPrimaryKey() @@ -133,37 +134,35 @@ public function testNotNullConstraint() } catch (Exception $e) { $this->pass(); } - } public function testGzipType() { $gzip = new GzipTest(); - $gzip->gzip = "compressed"; + $gzip->gzip = 'compressed'; - $this->assertEqual($gzip->gzip, "compressed"); + $this->assertEqual($gzip->gzip, 'compressed'); $gzip->save(); - $this->assertEqual($gzip->gzip, "compressed"); + $this->assertEqual($gzip->gzip, 'compressed'); $gzip->refresh(); - $this->assertEqual($gzip->gzip, "compressed"); + $this->assertEqual($gzip->gzip, 'compressed'); $this->connection->clear(); $gzip = $gzip->getTable()->find($gzip->id); - $this->assertEqual($gzip->gzip, "compressed"); + $this->assertEqual($gzip->gzip, 'compressed'); - $gzip->gzip = "compressed 2"; + $gzip->gzip = 'compressed 2'; - $this->assertEqual($gzip->gzip, "compressed 2"); + $this->assertEqual($gzip->gzip, 'compressed 2'); $gzip->save(); - $this->assertEqual($gzip->gzip, "compressed 2"); + $this->assertEqual($gzip->gzip, 'compressed 2'); $gzip->refresh(); - $this->assertEqual($gzip->gzip, "compressed 2"); + $this->assertEqual($gzip->gzip, 'compressed 2'); } public function testDefaultValues() { - - $test = new FieldNameTest; + $test = new FieldNameTest(); $this->assertEqual($test->someColumn, 'some string'); $this->assertEqual($test->someEnum, 'php'); @@ -172,13 +171,13 @@ public function testDefaultValues() $this->assertEqual($test->someInt, 11); } - public function testToArray() { $query = Doctrine_Query::create() ->select('u.id') ->from('User u') - ->limit(1); + ->limit(1) + ; $user = $query->fetchOne()->toArray(); $this->assertFalse((bool) $user['name']); @@ -189,7 +188,6 @@ public function testToArray() $this->assertTrue(is_array($a)); $this->assertTrue(array_key_exists('name', $a)); - $this->assertEqual($a['name'], null); $this->assertTrue(array_key_exists('id', $a)); $this->assertEqual($a['id'], null); @@ -251,12 +249,11 @@ public function testUpdatingWithNullValue() $user = $this->connection->getTable('User')->find(5); $this->assertEqual($user->name, null); - } public function testSerialize() { - $user = $this->connection->getTable("User")->find(4); + $user = $this->connection->getTable('User')->find(4); $str = serialize($user); $user2 = unserialize($str); @@ -267,18 +264,19 @@ public function testSerialize() public function testCallback() { $user = new User(); - $user->name = " zYne "; + $user->name = ' zYne '; $user->call('trim', 'name'); $this->assertEqual($user->name, 'zYne'); $user->call('substr', 'name', 0, 1); $this->assertEqual($user->name, 'z'); } - public function testCompositePK() { + public function testCompositePK() + { $record = new EntityReference(); - $this->assertEqual($record->getTable()->getIdentifier(), array("entity1","entity2")); + $this->assertEqual($record->getTable()->getIdentifier(), array('entity1', 'entity2')); $this->assertEqual($record->getTable()->getIdentifierType(), Doctrine_Core::IDENTIFIER_COMPOSITE); - $this->assertEqual($record->identifier(), array("entity1" => null, "entity2" => null)); + $this->assertEqual($record->identifier(), array('entity1' => null, 'entity2' => null)); $this->assertEqual($record->state(), Doctrine_Record::STATE_TCLEAN); $record->entity1 = 3; @@ -286,128 +284,125 @@ public function testCompositePK() { $this->assertEqual($record->entity2, 4); $this->assertEqual($record->entity1, 3); $this->assertEqual($record->state(), Doctrine_Record::STATE_TDIRTY); - $this->assertEqual($record->identifier(), array("entity1" => null, "entity2" => null)); + $this->assertEqual($record->identifier(), array('entity1' => null, 'entity2' => null)); $record->save(); $this->assertEqual($record->state(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($record->entity2, 4); $this->assertEqual($record->entity1, 3); - $this->assertEqual($record->identifier(), array("entity1" => 3, "entity2" => 4)); + $this->assertEqual($record->identifier(), array('entity1' => 3, 'entity2' => 4)); $record = $record->getTable()->find($record->identifier()); $this->assertEqual($record->state(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($record->entity2, 4); $this->assertEqual($record->entity1, 3); - $this->assertEqual($record->identifier(), array("entity1" => 3, "entity2" => 4)); + $this->assertEqual($record->identifier(), array('entity1' => 3, 'entity2' => 4)); $record->entity2 = 5; $record->entity1 = 2; $this->assertEqual($record->state(), Doctrine_Record::STATE_DIRTY); $this->assertEqual($record->entity2, 5); $this->assertEqual($record->entity1, 2); - $this->assertEqual($record->identifier(), array("entity1" => 3, "entity2" => 4)); + $this->assertEqual($record->identifier(), array('entity1' => 3, 'entity2' => 4)); $record->save(); $this->assertEqual($record->state(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($record->entity2, 5); $this->assertEqual($record->entity1, 2); - $this->assertEqual($record->identifier(), array("entity1" => 2, "entity2" => 5)); + $this->assertEqual($record->identifier(), array('entity1' => 2, 'entity2' => 5)); $record = $record->getTable()->find($record->identifier()); $this->assertEqual($record->state(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($record->entity2, 5); $this->assertEqual($record->entity1, 2); - $this->assertEqual($record->identifier(), array("entity1" => 2, "entity2" => 5)); + $this->assertEqual($record->identifier(), array('entity1' => 2, 'entity2' => 5)); $record->refresh(); $this->assertEqual($record->state(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($record->entity2, 5); $this->assertEqual($record->entity1, 2); - $this->assertEqual($record->identifier(), array("entity1" => 2, "entity2" => 5)); + $this->assertEqual($record->identifier(), array('entity1' => 2, 'entity2' => 5)); $record = new EntityReference(); $record->entity2 = 6; $record->entity1 = 2; $record->save(); - $coll = $this->connection->query("FROM EntityReference"); + $coll = $this->connection->query('FROM EntityReference'); $this->assertTrue($coll[0] instanceof EntityReference); $this->assertEqual($coll[0]->state(), Doctrine_Record::STATE_CLEAN); $this->assertTrue($coll[1] instanceof EntityReference); $this->assertEqual($coll[1]->state(), Doctrine_Record::STATE_CLEAN); - $coll = $this->connection->query("FROM EntityReference WHERE EntityReference.entity2 = 5"); + $coll = $this->connection->query('FROM EntityReference WHERE EntityReference.entity2 = 5'); $this->assertEqual($coll->count(), 1); } public function testManyToManyTreeStructure() { $this->conn->clear(); - $task = $this->connection->create("Task"); + $task = $this->connection->create('Task'); - $task->name = "Task 1"; - $task->ResourceAlias[0]->name = "Resource 1"; + $task->name = 'Task 1'; + $task->ResourceAlias[0]->name = 'Resource 1'; $this->connection->flush(); $this->assertTrue($task->ResourceAlias[0] instanceof Resource); - $this->assertEqual($task->ResourceAlias[0]->name, "Resource 1"); - $this->assertEqual($this->dbh->query("SELECT COUNT(*) FROM assignment")->fetch(PDO::FETCH_NUM),array(1)); + $this->assertEqual($task->ResourceAlias[0]->name, 'Resource 1'); + $this->assertEqual($this->dbh->query('SELECT COUNT(*) FROM assignment')->fetch(PDO::FETCH_NUM), array(1)); $task = new Task(); $this->assertTrue($task instanceof Task); $this->assertEqual($task->state(), Doctrine_Record::STATE_TCLEAN); $this->assertTrue($task->Subtask[0] instanceof Task); - //$this->assertEqual($task->Subtask[0]->state(), Doctrine_Record::STATE_TDIRTY); + // $this->assertEqual($task->Subtask[0]->state(), Doctrine_Record::STATE_TDIRTY); $this->assertTrue($task->ResourceAlias[0] instanceof Resource); $this->assertEqual($task->ResourceAlias[0]->state(), Doctrine_Record::STATE_TCLEAN); - $task->name = "Task 1"; - $task->ResourceAlias[0]->name = "Resource 1"; - $task->Subtask[0]->name = "Subtask 1"; + $task->name = 'Task 1'; + $task->ResourceAlias[0]->name = 'Resource 1'; + $task->Subtask[0]->name = 'Subtask 1'; - $this->assertEqual($task->name, "Task 1"); - $this->assertEqual($task->ResourceAlias[0]->name, "Resource 1"); + $this->assertEqual($task->name, 'Task 1'); + $this->assertEqual($task->ResourceAlias[0]->name, 'Resource 1'); $this->assertEqual($task->ResourceAlias->count(), 1); - $this->assertEqual($task->Subtask[0]->name, "Subtask 1"); + $this->assertEqual($task->Subtask[0]->name, 'Subtask 1'); $this->connection->flush(); $task = $task->getTable()->find($task->identifier()); - $this->assertEqual($task->name, "Task 1"); - $this->assertEqual($task->ResourceAlias[0]->name, "Resource 1"); + $this->assertEqual($task->name, 'Task 1'); + $this->assertEqual($task->ResourceAlias[0]->name, 'Resource 1'); $this->assertEqual($task->ResourceAlias->count(), 1); - $this->assertEqual($task->Subtask[0]->name, "Subtask 1"); - + $this->assertEqual($task->Subtask[0]->name, 'Subtask 1'); } - public function testGet() { $user = new User(); - $user->name = "Jack Daniels"; - $this->assertEqual($user->name, "Jack Daniels"); + $user->name = 'Jack Daniels'; + $this->assertEqual($user->name, 'Jack Daniels'); $this->assertEqual($user->created, null); $this->assertEqual($user->updated, null); $user->save(); $id = $user->identifier(); $user = $user->getTable()->find($id); - $this->assertEqual($user->name, "Jack Daniels"); + $this->assertEqual($user->name, 'Jack Daniels'); $this->assertEqual($user->created, null); $this->assertEqual($user->updated, null); $this->assertEqual($user->getTable()->getData(), array()); } - - + public function testUnknownFieldGet() { $user = new User(); - $user->name = "Jack Daniels"; + $user->name = 'Jack Daniels'; $user->save(); - + try { $foo = $user->unexistentColumnInThisClass; @@ -425,21 +420,20 @@ public function testUnknownFieldGet() } } - public function testNewOperator() { - $table = $this->connection->getTable("User"); + $table = $this->connection->getTable('User'); - $this->assertEqual($this->connection->getTable("User")->getData(), array()); + $this->assertEqual($this->connection->getTable('User')->getData(), array()); $user = new User(); $this->assertEqual(Doctrine_Lib::getRecordStateAsString($user->state()), Doctrine_Lib::getRecordStateAsString(Doctrine_Record::STATE_TCLEAN)); - $user->name = "John Locke"; + $user->name = 'John Locke'; - $this->assertTrue($user->name,"John Locke"); - $this->assertTrue($user->state() == Doctrine_Record::STATE_TDIRTY); + $this->assertTrue($user->name, 'John Locke'); + $this->assertTrue(Doctrine_Record::STATE_TDIRTY == $user->state()); $user->save(); - $this->assertTrue($user->state() == Doctrine_Record::STATE_CLEAN); - $this->assertTrue($user->name,"John Locke"); + $this->assertTrue(Doctrine_Record::STATE_CLEAN == $user->state()); + $this->assertTrue($user->name, 'John Locke'); } public function testTreeStructure() @@ -447,80 +441,73 @@ public function testTreeStructure() $this->conn->clear(); $e = new Element(); - $fk = $e->getTable()->getRelation("Child"); + $fk = $e->getTable()->getRelation('Child'); $this->assertTrue($fk instanceof Doctrine_Relation_ForeignKey); $this->assertEqual($fk->getType(), Doctrine_Relation::MANY); - $this->assertEqual($fk->getForeign(), "parent_id"); - $this->assertEqual($fk->getLocal(), "id"); + $this->assertEqual($fk->getForeign(), 'parent_id'); + $this->assertEqual($fk->getLocal(), 'id'); - - - $e->name = "parent"; - $e->Child[0]->name = "child 1"; - $e->Child[1]->name = "child 2"; + $e->name = 'parent'; + $e->Child[0]->name = 'child 1'; + $e->Child[1]->name = 'child 2'; $e->Child[1]->Child[0]->name = "child 1's child 1"; $e->Child[1]->Child[1]->name = "child 1's child 1"; - $this->assertEqual($e->name,"parent"); - - $this->assertEqual($e->Child[0]->name,"child 1"); - $this->assertEqual($e->Child[1]->name,"child 2"); - $this->assertEqual($e->Child[1]->Child[0]->name,"child 1's child 1"); - $this->assertEqual($e->Child[1]->Child[1]->name,"child 1's child 1"); - + $this->assertEqual($e->name, 'parent'); + $this->assertEqual($e->Child[0]->name, 'child 1'); + $this->assertEqual($e->Child[1]->name, 'child 2'); + $this->assertEqual($e->Child[1]->Child[0]->name, "child 1's child 1"); + $this->assertEqual($e->Child[1]->Child[1]->name, "child 1's child 1"); $this->connection->flush(); - $elements = $this->connection->query("FROM Element"); + $elements = $this->connection->query('FROM Element'); $this->assertEqual($elements->count(), 5); $e = $e->getTable()->find(1); - $this->assertEqual($e->name,"parent"); + $this->assertEqual($e->name, 'parent'); - $this->assertEqual($e->Child[0]->name,"child 1"); + $this->assertEqual($e->Child[0]->name, 'child 1'); $c = $e->getTable()->find(2); - $this->assertEqual($c->name, "child 1"); + $this->assertEqual($c->name, 'child 1'); $this->assertEqual($e->Child[0]->parent_id, 1); $this->assertEqual($e->Child[0]->Parent->identifier(), $e->identifier()); - $this->assertEqual($e->Child[1]->parent_id, 1); - $this->assertEqual($e->Child[1]->Child[0]->name,"child 1's child 1"); - $this->assertEqual($e->Child[1]->Child[1]->name,"child 1's child 1"); + $this->assertEqual($e->Child[1]->Child[0]->name, "child 1's child 1"); + $this->assertEqual($e->Child[1]->Child[1]->name, "child 1's child 1"); $this->assertEqual($e->Child[1]->Child[0]->parent_id, 3); $this->assertEqual($e->Child[1]->Child[1]->parent_id, 3); - } public function testUniqueKeyComponent() { $e = new TestError(); - $e->message = 'user error'; + $e->message = 'user error'; $e->file_md5 = md5(0); - $e->code = 1; + $e->code = 1; // ADDING NEW RECORD - $this->assertEqual($e->code,1); + $this->assertEqual($e->code, 1); $this->assertEqual($e->file_md5, md5(0)); $this->assertEqual($e->message, 'user error'); $e2 = new TestError(); - $e2->message = 'user error2'; + $e2->message = 'user error2'; $e2->file_md5 = md5(1); - $e2->code = 2; + $e2->code = 2; - $this->assertEqual($e2->code,2); + $this->assertEqual($e2->code, 2); $this->assertEqual($e2->file_md5, md5(1)); $this->assertEqual($e2->message, 'user error2'); - $fk = $e->getTable()->getRelation('Description'); $this->assertTrue($fk instanceof Doctrine_Relation_ForeignKey); - $this->assertEqual($fk->getLocal(),'file_md5'); - $this->assertEqual($fk->getForeign(),'file_md5'); + $this->assertEqual($fk->getLocal(), 'file_md5'); + $this->assertEqual($fk->getForeign(), 'file_md5'); $this->assertTrue($fk->getTable() instanceof Doctrine_Table); $e->Description[0]->description = 'This is the 1st description'; @@ -540,8 +527,7 @@ public function testUniqueKeyComponent() $coll = $this->connection->query('FROM TestError'); $e = $coll[0]; - - $this->assertEqual($e->code,1); + $this->assertEqual($e->code, 1); $this->assertEqual($e->file_md5, md5(0)); $this->assertEqual($e->message, 'user error'); @@ -559,15 +545,14 @@ public function testUniqueKeyComponent() $e->Description[0]->description = '1st changed description'; $e->Description[1]->description = '2nd changed description'; - - $this->assertEqual($e->code,2); - $this->assertEqual($e->message,'changed message'); + $this->assertEqual($e->code, 2); + $this->assertEqual($e->message, 'changed message'); $this->assertEqual($e->Description[0]->description, '1st changed description'); $this->assertEqual($e->Description[1]->description, '2nd changed description'); $e->save(); - $this->assertEqual($e->code,2); - $this->assertEqual($e->message,'changed message'); + $this->assertEqual($e->code, 2); + $this->assertEqual($e->message, 'changed message'); $this->assertEqual($e->Description[0]->description, '1st changed description'); $this->assertEqual($e->Description[1]->description, '2nd changed description'); } @@ -575,13 +560,13 @@ public function testUniqueKeyComponent() public function testInsert() { $user = new User(); - $user->name = "John Locke"; + $user->name = 'John Locke'; $user->save(); $this->assertTrue(is_numeric($user->id) && $user->id > 0); - $this->assertTrue($user->getModified() == array()); - $this->assertTrue($user->state() == Doctrine_Record::STATE_CLEAN); + $this->assertTrue(array() == $user->getModified()); + $this->assertTrue(Doctrine_Record::STATE_CLEAN == $user->state()); $user->delete(); $this->assertEqual($user->state(), Doctrine_Record::STATE_TCLEAN); @@ -589,24 +574,23 @@ public function testInsert() public function testUpdate() { - $user = $this->connection->getTable("User")->find(4); - $user->set("name","Jack Daniels",true); - + $user = $this->connection->getTable('User')->find(4); + $user->set('name', 'Jack Daniels', true); $user->save(); - //print $this->old->name; + // print $this->old->name; $this->assertEqual($user->getModified(), array()); - $this->assertEqual($user->name, "Jack Daniels"); + $this->assertEqual($user->name, 'Jack Daniels'); } public function testCopy() { - $user = $this->connection->getTable("User")->find(4); + $user = $this->connection->getTable('User')->find(4); $new = $user->copy(); $this->assertTrue($new instanceof Doctrine_Record); - $this->assertTrue($new->state() == Doctrine_Record::STATE_TDIRTY); + $this->assertTrue(Doctrine_Record::STATE_TDIRTY == $new->state()); $new = $user->copy(); $new->save(); @@ -619,11 +603,11 @@ public function testCopy() public function testCopyAndModify() { - $user = $this->connection->getTable("User")->find(4); + $user = $this->connection->getTable('User')->find(4); $new = $user->copy(); $this->assertTrue($new instanceof Doctrine_Record); - $this->assertTrue($new->state() == Doctrine_Record::STATE_TDIRTY); + $this->assertTrue(Doctrine_Record::STATE_TDIRTY == $new->state()); $new->loginname = 'jackd'; @@ -664,22 +648,21 @@ public function testReferences() // ADDING REFERENCES - $user->Phonenumber[0]->phonenumber = "123 123"; + $user->Phonenumber[0]->phonenumber = '123 123'; $this->assertEqual($user->Phonenumber->count(), 1); - $user->Phonenumber[1]->phonenumber = "123 123"; + $user->Phonenumber[1]->phonenumber = '123 123'; $this->assertEqual($user->Phonenumber->count(), 2); $user->save(); - $this->assertEqual($user->Phonenumber->count(), 2); unset($user); $user = $this->objTable->find(5); $this->assertEqual($user->Phonenumber->count(), 2); - $user->Phonenumber[3]->phonenumber = "123 123"; + $user->Phonenumber[3]->phonenumber = '123 123'; $user->save(); $this->assertEqual($user->Phonenumber->count(), 3); @@ -698,8 +681,8 @@ public function testReferences() // ADDING REFERENCES WITH STRING KEYS - $user->Phonenumber["home"]->phonenumber = "123 123"; - $user->Phonenumber["work"]->phonenumber = "444 444"; + $user->Phonenumber['home']->phonenumber = '123 123'; + $user->Phonenumber['work']->phonenumber = '444 444'; $user->save(); $this->assertEqual($user->Phonenumber->count(), 2); @@ -710,28 +693,27 @@ public function testReferences() // REPLACING ONE-TO-MANY REFERENCE unset($coll); $coll = new Doctrine_Collection('Phonenumber'); - $coll[0]->phonenumber = "123 123"; - $coll["home"]->phonenumber = "444 444"; - $coll["work"]->phonenumber = "444 444"; + $coll[0]->phonenumber = '123 123'; + $coll['home']->phonenumber = '444 444'; + $coll['work']->phonenumber = '444 444'; $user->Phonenumber = $coll; $user->save(); $this->assertEqual($user->Phonenumber->count(), 3); $user = $this->objTable->find(5); - //$this->assertEqual($user->Phonenumber->count(), 3); - + // $this->assertEqual($user->Phonenumber->count(), 3); // ONE-TO-ONE REFERENCES - $user->Email->address = "drinker@drinkmore.info"; + $user->Email->address = 'drinker@drinkmore.info'; $this->assertTrue($user->Email instanceof Email); - $this->assertEqual($user->Email->address, "drinker@drinkmore.info"); + $this->assertEqual($user->Email->address, 'drinker@drinkmore.info'); $user->save(); $this->assertTrue($user->Email instanceof Email); - $this->assertEqual($user->Email->address, "drinker@drinkmore.info"); + $this->assertEqual($user->Email->address, 'drinker@drinkmore.info'); $this->assertEqual($user->Email->id, $user->email_id); $user = $this->objTable->find(5); @@ -739,26 +721,26 @@ public function testReferences() $this->assertTrue($user->Email instanceof Email); $this->assertEqual($user->Email->id, $user->email_id); $this->assertEqual($user->Email->state(), Doctrine_Record::STATE_CLEAN); - $this->assertEqual($user->Email->address, "drinker@drinkmore.info"); + $this->assertEqual($user->Email->address, 'drinker@drinkmore.info'); $id = $user->Email->id; // REPLACING ONE-TO-ONE REFERENCES - $email = $this->connection->create("Email"); - $email->address = "absolutist@nottodrink.com"; + $email = $this->connection->create('Email'); + $email->address = 'absolutist@nottodrink.com'; $user->Email = $email; $this->assertTrue($user->Email instanceof Email); - $this->assertEqual($user->Email->address, "absolutist@nottodrink.com"); + $this->assertEqual($user->Email->address, 'absolutist@nottodrink.com'); $user->save(); unset($user); $user = $this->objTable->find(5); $this->assertTrue($user->Email instanceof Email); - $this->assertEqual($user->Email->address, "absolutist@nottodrink.com"); + $this->assertEqual($user->Email->address, 'absolutist@nottodrink.com'); - $emails = $this->connection->query("FROM Email WHERE Email.id = $id"); - //$this->assertEqual(count($emails),0); + $emails = $this->connection->query("FROM Email WHERE Email.id = {$id}"); + // $this->assertEqual(count($emails),0); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -767,26 +749,23 @@ public function testReferences() public function testDeleteReference() { $user = $this->objTable->find(5); - $int = $user->Phonenumber->delete(); + $int = $user->Phonenumber->delete(); - $this->assertTrue($user->Phonenumber->count() == 0); + $this->assertTrue(0 == $user->Phonenumber->count()); } - public function testSaveAssociations() { $user = $this->objTable->find(5); - $gf = $this->connection->getTable("Group"); + $gf = $this->connection->getTable('Group'); $this->assertTrue($user->Group instanceof Doctrine_Collection); $this->assertEqual($user->Group->count(), 1); $this->assertEqual($user->Group[0]->id, 3); - // ADDING ASSOCIATED REFERENCES - $group1 = $gf->find(1); $group2 = $gf->find(2); $user->Group[1] = $group1; @@ -797,7 +776,6 @@ public function testSaveAssociations() $user->save(); $coll = $user->Group; - // UNSETTING ASSOCIATED REFERENCES unset($user); $user = $this->objTable->find(5); @@ -811,7 +789,6 @@ public function testSaveAssociations() $user->save(); unset($user); - // CHECKING THE PERSISTENCE OF UNSET ASSOCIATED REFERENCES $this->connection->clear(); $user = $this->objTable->find(5); @@ -819,7 +796,6 @@ public function testSaveAssociations() $this->assertEqual($user->Group[0]->id, 3); $this->assertEqual($gf->findAll()->count(), 3); - // REPLACING OLD ASSOCIATED REFERENCE $user->unlink('Group', 3, true); // you MUST first unlink old relationship $user->Group[1] = $group1; @@ -838,18 +814,17 @@ public function testSaveAssociations() $user = $this->objTable->find(5); $this->assertEqual($user->Group->count(), 0); - // ACCESSING ASSOCIATION OBJECT PROPERTIES $user = new User(); - $this->assertTrue($user->getTable()->getRelation("Groupuser") instanceof Doctrine_Relation_ForeignKey); + $this->assertTrue($user->getTable()->getRelation('Groupuser') instanceof Doctrine_Relation_ForeignKey); $this->assertTrue($user->Groupuser instanceof Doctrine_Collection); $this->assertTrue($user->Groupuser[0] instanceof Groupuser); - $user->name = "Jack Daniels"; - $user->Group[0]->name = "Group #1"; - $user->Group[1]->name = "Group #2"; + $user->name = 'Jack Daniels'; + $user->Group[0]->name = 'Group #1'; + $user->Group[1]->name = 'Group #2'; $t1 = time(); $t2 = time(); $user->Groupuser[0]->added = $t1; @@ -863,38 +838,37 @@ public function testSaveAssociations() $user->refresh(); $this->assertEqual($user->Groupuser[0]->added, $t1); $this->assertEqual($user->Groupuser[1]->added, $t2); - } - public function testCount() { - $user = $this->connection->getTable("User")->find(4); + $user = $this->connection->getTable('User')->find(4); $this->assertTrue(is_integer($user->count())); } public function testGetReference() { - $user = $this->connection->getTable("User")->find(4); + $user = $this->connection->getTable('User')->find(4); $this->assertTrue($user->Email instanceof Doctrine_Record); $this->assertTrue($user->Phonenumber instanceof Doctrine_Collection); $this->assertTrue($user->Group instanceof Doctrine_Collection); - $this->assertTrue($user->Phonenumber->count() == 1); + $this->assertTrue(1 == $user->Phonenumber->count()); } + public function testGetIterator() { - $user = $this->connection->getTable("User")->find(4); + $user = $this->connection->getTable('User')->find(4); $this->assertTrue($user->getIterator() instanceof ArrayIterator); } public function testRefreshRelated() { - $user = $this->connection->getTable("User")->find(4); - $user->Address[0]->address = "Address #1"; - $user->Address[1]->address = "Address #2"; + $user = $this->connection->getTable('User')->find(4); + $user->Address[0]->address = 'Address #1'; + $user->Address[1]->address = 'Address #2'; $user->save(); $this->assertEqual(count($user->Address), 2); Doctrine_Query::create()->delete()->from('EntityAddress')->where('user_id = ? AND address_id = ?', array($user->id, $user->Address[1]->id))->execute(); @@ -907,9 +881,9 @@ public function testRefreshRelated() public function testRefreshDeep() { - $user = $this->connection->getTable("User")->find(4); - $user->Address[0]->address = "Address #1"; - $user->Address[1]->address = "Address #2"; + $user = $this->connection->getTable('User')->find(4); + $user->Address[0]->address = 'Address #1'; + $user->Address[1]->address = 'Address #2'; $user->save(); $this->assertEqual(count($user->Address), 2); @@ -966,7 +940,7 @@ public function testRecordReplaceNoException() $user->replace(); $this->pass(); } catch (Exception $e) { - $this->fail('Doctrine_Record::replace() does not work: ' . $e->getMessage()); + $this->fail('Doctrine_Record::replace() does not work: '.$e->getMessage()); } } @@ -981,7 +955,7 @@ public function testReplaceReplacesAndNotInsertsNewRecord() $user->save(); $id = $user->id; $user->free(); - $count++; + ++$count; $users = Doctrine_Query::create()->from('User u')->execute(); $this->assertEqual($users->count(), $count); @@ -1017,21 +991,21 @@ public function testDeleteReturnBooleanAndThrowsException() $this->assertTrue($user->delete()); try { - // delete() on transient objects should just be ignored. - $user->delete(); + // delete() on transient objects should just be ignored. + $user->delete(); } catch (Exception $e) { - $this->fail(); + $this->fail(); } } - + public function testDoubleIsModified() { $location = new Location2(); $location->lat = '12.345'; - + $location->save(); $location->lat = 12.345; - + $this->assertFalse($location->isModified()); } } diff --git a/tests/Relation/AccessTestCase.php b/tests/Relation/AccessTestCase.php index f3586d6f5..ae6ed6385 100644 --- a/tests/Relation/AccessTestCase.php +++ b/tests/Relation/AccessTestCase.php @@ -1,11 +1,19 @@ conn->clear(); $o1 = new File_Owner(); - $o1->name = "owner1"; + $o1->name = 'owner1'; $o2 = new File_Owner(); - $o2->name = "owner2"; + $o2->name = 'owner2'; $f1 = new Data_File(); $f1->filename = 'file1'; @@ -19,17 +27,17 @@ public function prepareData() { // multiple left join branches test $us = array(); $us[1] = new MyUser(); - $us[1]->name = "user1"; + $us[1]->name = 'user1'; $this->connection->flush(); // OneThings $onethings_gs = array( - array(6,1) + array(6, 1), ); $count = 1; - foreach($onethings_gs as $onething_g) { - for($i=$count;$i<$count+$onething_g[0];$i++) { + foreach ($onethings_gs as $onething_g) { + for ($i = $count; $i < $count + $onething_g[0]; ++$i) { $d = new MyOneThing(); - $d->name = "onething".$i; + $d->name = 'onething'.$i; if ($onething_g[1]) { $us[$onething_g[1]]->MyOneThing->add($d); } @@ -37,9 +45,9 @@ public function prepareData() { $count += $onething_g[0]; } // OtherThings - for($i=0;$i<6;$i++) { + for ($i = 0; $i < 6; ++$i) { $o = new MyOtherThing(); - $o->name = "otherthing".$i; + $o->name = 'otherthing'.$i; $us[1]->MyOtherThing->add($o); } // UserOneThings @@ -70,30 +78,33 @@ public function prepareData() { $this->connection->clear(); } - public function prepareTables() { - $this->tables = array("Data_File", "File_Owner","MyUser", - "MyOneThing", - "MyUserOneThing", - "MyOtherThing", - "MyUserOtherThing"); + public function prepareTables() + { + $this->tables = array('Data_File', 'File_Owner', 'MyUser', + 'MyOneThing', + 'MyUserOneThing', + 'MyOtherThing', + 'MyUserOtherThing'); parent::prepareTables(); } - public function testOneToOneAggregateRelationFetching() { + public function testOneToOneAggregateRelationFetching() + { $coll = $this->connection->query("FROM File_Owner.Data_File WHERE File_Owner.name = 'owner1'"); - $this->assertTrue(count($coll) == 1); + $this->assertTrue(1 == count($coll)); $this->assertTrue($coll[0] instanceof Doctrine_Record); $this->assertEqual($coll[0]->id, 1); } - public function testAccessOneToOneFromForeignSide() { + public function testAccessOneToOneFromForeignSide() + { $check = $this->connection->query("FROM File_Owner WHERE File_Owner.name = 'owner1'"); $owner1 = $this->connection->query("FROM File_Owner.Data_File WHERE File_Owner.name = 'owner1'"); $owner2 = $this->connection->query("FROM File_Owner.Data_File WHERE File_Owner.name = 'owner2'"); - $this->assertTrue(count($check) == 1); + $this->assertTrue(1 == count($check)); - $this->assertTrue(count($owner2) == 1); + $this->assertTrue(1 == count($owner2)); $check = $check[0]; $owner1 = $owner1[0]; @@ -101,7 +112,7 @@ public function testAccessOneToOneFromForeignSide() { $this->assertEqual($owner1->name, 'owner1'); $this->assertEqual($owner1->id, 1); - $check2 = $this->connection->query("FROM File_Owner WHERE File_Owner.id = ".$owner1->get('id')); + $check2 = $this->connection->query('FROM File_Owner WHERE File_Owner.id = '.$owner1->get('id')); $this->assertEqual(1, count($check2)); $check2 = $check2[0]; $this->assertEqual('owner1', $check2->get('name')); @@ -112,19 +123,20 @@ public function testAccessOneToOneFromForeignSide() { $this->assertEqual($owner1->get('id'), $check->get('id')); } - public function testAccessOneToOneFromLocalSide() { + public function testAccessOneToOneFromLocalSide() + { $check = $this->connection->query("FROM Data_File WHERE Data_File.filename = 'file4'"); $file1 = $this->connection->query("FROM Data_File.File_Owner WHERE Data_File.filename = 'file4'"); $file2 = $this->connection->query("FROM Data_File.File_Owner WHERE Data_File.filename = 'file1'"); - $this->assertTrue(count($check) == 1); - $this->assertTrue(count($file1) == 1); - $this->assertTrue(count($file2) == 1); + $this->assertTrue(1 == count($check)); + $this->assertTrue(1 == count($file1)); + $this->assertTrue(1 == count($file2)); $check = $check[0]; $file1 = $file1[0]; $file2 = $file2[0]; - $check2 = $this->connection->query("FROM Data_File WHERE Data_File.id = ".$file1->get('id')); + $check2 = $this->connection->query('FROM Data_File WHERE Data_File.id = '.$file1->get('id')); $this->assertEqual(1, count($check2)); $check2 = $check2[0]; $this->assertEqual('file4', $check2->get('filename')); @@ -135,72 +147,73 @@ public function testAccessOneToOneFromLocalSide() { $this->assertEqual($file1->get('id'), $check->get('id')); } - public function testMultipleLeftJoinBranches() { - $query = "FROM MyUserOtherThing"; + public function testMultipleLeftJoinBranches() + { + $query = 'FROM MyUserOtherThing'; $other = $this->connection->query($query); $check1 = array(); - foreach($other as $oth) { - if ( ! isset($check1[$oth->other_thing_id])) { + foreach ($other as $oth) { + if (!isset($check1[$oth->other_thing_id])) { $check1[$oth->other_thing_id] = array(); } $check1[$oth->other_thing_id][$oth->id] = $oth; } - $query = "FROM MyUserOneThing"; + $query = 'FROM MyUserOneThing'; $ones = $this->connection->query($query); $check2 = array(); - foreach($ones as $one) { - if ( ! isset($check2[$one->one_thing_id])) { + foreach ($ones as $one) { + if (!isset($check2[$one->one_thing_id])) { $check2[$one->one_thing_id] = array(); } $check2[$one->one_thing_id][$one->id] = $one; } - $query = "FROM MyUser a1, + $query = 'FROM MyUser a1, a1.MyOneThing a2, a2.MyUserOneThing a3, a1.MyOtherThing a4, - a4.MyUserOtherThing a5"; + a4.MyUserOtherThing a5'; $users = $this->connection->query($query); - foreach($users as $u) { - $this->assertEqual($u->MyOtherThing->count(), 6, "incorrect count of MyOtherThing"); - foreach($u->MyOtherThing as $o) { + foreach ($users as $u) { + $this->assertEqual($u->MyOtherThing->count(), 6, 'incorrect count of MyOtherThing'); + foreach ($u->MyOtherThing as $o) { $in_check = array_key_exists($o->id, $check1); $wanted_user_thing_count = $in_check ? count($check1[$o->id]) : 0; - $this->assertEqual($o->MyUserOtherThing->count(), $wanted_user_thing_count, "incorrect count of MyUserOtherThing on MyOtherThing"); - foreach($o->MyUserOtherThing as $uo) { - $this->assertEqual($uo->other_thing_id, $o->id, "incorrectly assigned MyOtherThing.id on MyUserOtherThing"); + $this->assertEqual($o->MyUserOtherThing->count(), $wanted_user_thing_count, 'incorrect count of MyUserOtherThing on MyOtherThing'); + foreach ($o->MyUserOtherThing as $uo) { + $this->assertEqual($uo->other_thing_id, $o->id, 'incorrectly assigned MyOtherThing.id on MyUserOtherThing'); if ($in_check) { $wanted_user_thing_exists = array_key_exists($uo->id, $check1[$o->id]); - $this->assertTrue($wanted_user_thing_exists, "MyUserOtherThing incorrectly assigned to MyOtherThing."); + $this->assertTrue($wanted_user_thing_exists, 'MyUserOtherThing incorrectly assigned to MyOtherThing.'); if ($wanted_user_thing_exists) { - $this->assertEqual($uo->other_thing_id, $check1[$o->id][$uo->id]->user_id, "incorrect value of MyUserOtherThing.user_id"); - $this->assertEqual($uo->other_thing_id, $check1[$o->id][$uo->id]->other_thing_id, "incorrect value of MyUserOtherThing.other_thing_id"); + $this->assertEqual($uo->other_thing_id, $check1[$o->id][$uo->id]->user_id, 'incorrect value of MyUserOtherThing.user_id'); + $this->assertEqual($uo->other_thing_id, $check1[$o->id][$uo->id]->other_thing_id, 'incorrect value of MyUserOtherThing.other_thing_id'); } } } } } - $query = "FROM MyUser a1, + $query = 'FROM MyUser a1, a1.MyOtherThing a2, a2.MyUserOtherThing a3, a1.MyOneThing a4, - a4.MyUserOneThing a5"; + a4.MyUserOneThing a5'; $users = $this->connection->query($query); - foreach($users as $u) { - $this->assertEqual($u->MyOneThing->count(), 6, "incorrect count of MyOneThing"); - foreach($u->MyOneThing as $o) { + foreach ($users as $u) { + $this->assertEqual($u->MyOneThing->count(), 6, 'incorrect count of MyOneThing'); + foreach ($u->MyOneThing as $o) { $in_check = array_key_exists($o->id, $check2); $wanted_user_thing_count = $in_check ? count($check2[$o->id]) : 0; - $this->assertEqual($o->MyUserOneThing->count(), $wanted_user_thing_count, "incorrect count of MyUserOneThing on MyOneThing"); - foreach($o->MyUserOneThing as $uo) { - $this->assertEqual($uo->one_thing_id, $o->id, "incorrectly assigned MyOneThing.id on MyUserOneThing"); + $this->assertEqual($o->MyUserOneThing->count(), $wanted_user_thing_count, 'incorrect count of MyUserOneThing on MyOneThing'); + foreach ($o->MyUserOneThing as $uo) { + $this->assertEqual($uo->one_thing_id, $o->id, 'incorrectly assigned MyOneThing.id on MyUserOneThing'); if ($in_check) { $wanted_user_thing_exists = array_key_exists($uo->id, $check2[$o->id]); - $this->assertTrue($wanted_user_thing_exists, "MyUserOneThing incorrectly assigned to MyOneThing."); + $this->assertTrue($wanted_user_thing_exists, 'MyUserOneThing incorrectly assigned to MyOneThing.'); if ($wanted_user_thing_exists) { - $this->assertEqual($uo->one_thing_id, $check2[$o->id][$uo->id]->user_id, "incorrect value of MyUserOneThing.user_id"); - $this->assertEqual($uo->one_thing_id, $check2[$o->id][$uo->id]->one_thing_id, "incorrect value of MyUserOneThing.one_thing_id"); + $this->assertEqual($uo->one_thing_id, $check2[$o->id][$uo->id]->user_id, 'incorrect value of MyUserOneThing.user_id'); + $this->assertEqual($uo->one_thing_id, $check2[$o->id][$uo->id]->one_thing_id, 'incorrect value of MyUserOneThing.one_thing_id'); } } } diff --git a/tests/Relation/CircularSavingTestCase.php b/tests/Relation/CircularSavingTestCase.php index b0b75c5e3..b29dabf09 100644 --- a/tests/Relation/CircularSavingTestCase.php +++ b/tests/Relation/CircularSavingTestCase.php @@ -20,26 +20,33 @@ */ /** - * Doctrine_Relation_CircularSaving_TestCase + * Doctrine_Relation_CircularSaving_TestCase. * - * @package Doctrine * @author Konsta Vesterinen - * @author Jan Schaefer + * @author Jan Schaefer * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Relation_CircularSaving_TestCase extends Doctrine_UnitTestCase { + public function prepareData() + { + } - public function prepareData() - { } - public function prepareTables() + public function prepareTables() { $this->tables = array('NestTest', 'NestReference'); - + parent::prepareTables(); } @@ -59,7 +66,7 @@ public function testMultiplePrimaryKeys() $this->assertEqual(count($coll), 0); } - public function testCircularNonEqualSelfReferencingRelationSaving() + public function testCircularNonEqualSelfReferencingRelationSaving() { $n1 = new NestTest(); $n1->set('name', 'node1'); @@ -86,7 +93,7 @@ public function testCircularNonEqualSelfReferencingRelationSaving() $this->assertEqual(count($coll), 0); } - public function testCircularEqualSelfReferencingRelationSaving() + public function testCircularEqualSelfReferencingRelationSaving() { $n1 = new NestTest(); $n1->set('name', 'node1'); diff --git a/tests/Relation/ColumnAliasesTestCase.php b/tests/Relation/ColumnAliasesTestCase.php index a9c224f1f..6c8da7091 100644 --- a/tests/Relation/ColumnAliasesTestCase.php +++ b/tests/Relation/ColumnAliasesTestCase.php @@ -1,30 +1,38 @@ tables = array( - "ColumnAliasTest2", - "ColumnAliasTest3" - ); - + 'ColumnAliasTest2', + 'ColumnAliasTest3', + ); + parent::prepareTables(); } - + public function prepareData() - { } + { + } - public function testCompoundSave() { + public function testCompoundSave() + { $c2 = new ColumnAliasTest2(); $c2->alias1 = 'foo'; $c2->ColumnAliasTest3->alias1 = 'bar'; $c2->save(); - + $this->assertNotNull($c2->column_alias_test3_id); } - - - public function testHasOneCompoundSave2() { + + public function testHasOneCompoundSave2() + { $c3 = new ColumnAliasTest3(); $c3->alias1 = 'foo'; $c3->ColumnAliasTest2->alias1 = 'bar'; @@ -58,9 +66,9 @@ public function setTableDefinition() $this->hasColumn('column1 as alias1', 'string', 200); $this->hasColumn('column2 as alias2', 'integer', 4); } - + public function setUp() { $this->hasOne('ColumnAliasTest2', array('local' => 'id', 'foreign' => 'column_alias_test3_id')); } -} \ No newline at end of file +} diff --git a/tests/Relation/ManyToMany2TestCase.php b/tests/Relation/ManyToMany2TestCase.php index efe63668d..c01600312 100644 --- a/tests/Relation/ManyToMany2TestCase.php +++ b/tests/Relation/ManyToMany2TestCase.php @@ -20,69 +20,77 @@ */ /** - * Doctrine_Relation_Parser_TestCase + * Doctrine_Relation_Parser_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Relation_ManyToMany2_TestCase extends Doctrine_UnitTestCase +class Doctrine_Relation_ManyToMany2_TestCase extends Doctrine_UnitTestCase { - public function prepareData() + public function prepareData() { } - - public function prepareTables() + + public function prepareTables() { $this->tables = array('TestUser', 'TestMovie', 'TestMovieUserBookmark', 'TestMovieUserVote'); parent::prepareTables(); } - - public function testManyToManyCreateSelectAndUpdate() + + public function testManyToManyCreateSelectAndUpdate() { $user = new TestUser(); $user['name'] = 'tester'; $user->save(); - + $data = new TestMovie(); $data['name'] = 'movie'; - $data['User'] = $user; + $data['User'] = $user; $data['MovieBookmarks'][0] = $user; $data['MovieVotes'][0] = $user; - $data->save(); //All ok here - + $data->save(); // All ok here + $this->conn->clear(); $q = new Doctrine_Query(); $newdata = $q->select('m.*') - ->from('TestMovie m') - ->execute() - ->getFirst(); - $newdata['name'] = 'movie2'; + ->from('TestMovie m') + ->execute() + ->getFirst() + ; + $newdata['name'] = 'movie2'; try { - $newdata->save(); //big failure here + $newdata->save(); // big failure here $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } - } + public function testManyToManyJoinsandSave() { $q = new Doctrine_Query(); $newdata = $q->select('d.*, i.*, u.*, c.*') - ->from('TestMovie d, d.MovieBookmarks i, i.UserVotes u, u.User c') - ->execute() - ->getFirst(); + ->from('TestMovie d, d.MovieBookmarks i, i.UserVotes u, u.User c') + ->execute() + ->getFirst() + ; $newdata['MovieBookmarks'][0]['UserVotes'][0]['User']['name'] = 'user2'; try { $newdata->save(); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } } @@ -115,7 +123,7 @@ public function testManyToManyDirectLinksUpdating() $this->assertEqual($movies->count(), 2); $profiler = new Doctrine_Connection_Profiler(); - + $this->conn->addListener($profiler); $this->assertEqual($users[0]->UserBookmarks->count(), 0); @@ -125,10 +133,10 @@ public function testManyToManyDirectLinksUpdating() $users[0]->save(); $this->assertEqual($users[0]->UserBookmarks->count(), 2); - /** - foreach ($profiler->getAll() as $event) { - print $event->getQuery() . "
"; - } - */ + /* + * foreach ($profiler->getAll() as $event) { + * print $event->getQuery() . "
"; + * } + */ } } diff --git a/tests/Relation/ManyToManyTestCase.php b/tests/Relation/ManyToManyTestCase.php index e46dff3a7..77a0045b1 100644 --- a/tests/Relation/ManyToManyTestCase.php +++ b/tests/Relation/ManyToManyTestCase.php @@ -1,19 +1,30 @@ tables = array('JC1', 'JC2', 'JC3', 'RTC1', 'RTC2', 'M2MTest', 'M2MTest2'); parent::prepareTables(); } - public function testManyToManyRelationWithAliasesAndCustomPKs() { + public function testManyToManyRelationWithAliasesAndCustomPKs() + { $component = new M2MTest2(); try { $rel = $component->getTable()->getRelation('RTC5'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertTrue($rel instanceof Doctrine_Relation_Association); @@ -23,112 +34,118 @@ public function testManyToManyRelationWithAliasesAndCustomPKs() { try { $rel = $component->getTable()->getRelation('JC3'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertEqual($rel->getLocal(), 'oid'); } - public function testJoinComponent() { + + public function testJoinComponent() + { $component = new JC3(); - + try { $rel = $component->getTable()->getRelation('M2MTest2'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { echo $e->getMessage(); $this->fail(); } $this->assertEqual($rel->getForeign(), 'oid'); } - public function testManyToManyRelationFetchingWithAliasesAndCustomPKs2() { + public function testManyToManyRelationFetchingWithAliasesAndCustomPKs2() + { $q = new Doctrine_Query(); try { $q->from('M2MTest2 m INNER JOIN m.JC3'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } try { $q->execute(); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } } - public function testManyToManyHasRelationWithAliases4() { + public function testManyToManyHasRelationWithAliases4() + { try { $component = new M2MTest(); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } } - public function testManyToManyHasRelationWithAliases3() { + public function testManyToManyHasRelationWithAliases3() + { $component = new M2MTest(); try { $rel = $component->getTable()->getRelation('RTC3'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertTrue($rel instanceof Doctrine_Relation_Association); - + $this->assertTrue($component->RTC3 instanceof Doctrine_Collection); } - - public function testManyToManyHasRelationWithAliases() { + public function testManyToManyHasRelationWithAliases() + { $component = new M2MTest(); try { $rel = $component->getTable()->getRelation('RTC1'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertTrue($rel instanceof Doctrine_Relation_Association); - + $this->assertTrue($component->RTC1 instanceof Doctrine_Collection); } - public function testManyToManyHasRelationWithAliases2() { + public function testManyToManyHasRelationWithAliases2() + { $component = new M2MTest(); try { $rel = $component->getTable()->getRelation('RTC2'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertTrue($rel instanceof Doctrine_Relation_Association); - + $this->assertTrue($component->RTC1 instanceof Doctrine_Collection); } - - public function testManyToManyRelationSaving() { + public function testManyToManyRelationSaving() + { $component = new M2MTest(); $component->RTC1[0]->name = '1'; $component->RTC1[1]->name = '2'; $component->name = '2'; - + $count = $this->connection->count(); $component->save(); - $this->assertEqual($this->connection->count(), ($count + 5)); - + $this->assertEqual($this->connection->count(), $count + 5); + $this->assertEqual($component->RTC1->count(), 2); - + $component = $component->getTable()->find($component->id); - + $this->assertEqual($component->RTC1->count(), 2); // check that it doesn't matter saving the other M2M components as well @@ -140,31 +157,31 @@ public function testManyToManyRelationSaving() { $component->save(); - $this->assertEqual($this->connection->count(), ($count + 4)); + $this->assertEqual($this->connection->count(), $count + 4); $this->assertEqual($component->RTC2->count(), 2); $component = $component->getTable()->find($component->id); $this->assertEqual($component->RTC2->count(), 2); - } - public function testManyToManyRelationSaving2() { + public function testManyToManyRelationSaving2() + { $component = new M2MTest(); $component->RTC2[0]->name = '1'; $component->RTC2[1]->name = '2'; $component->name = '2'; - + $count = $this->connection->count(); $component->save(); - $this->assertEqual($this->connection->count(), ($count + 5)); - + $this->assertEqual($this->connection->count(), $count + 5); + $this->assertEqual($component->RTC2->count(), 2); - + $component = $component->getTable()->find($component->id); $this->assertEqual($component->RTC2->count(), 2); @@ -178,24 +195,25 @@ public function testManyToManyRelationSaving2() { $component->save(); - $this->assertEqual($this->connection->count(), ($count + 3)); - + $this->assertEqual($this->connection->count(), $count + 3); + $this->assertEqual($component->RTC1->count(), 2); - + $component = $component->getTable()->find($component->id); - + $this->assertEqual($component->RTC1->count(), 2); } - - public function testManyToManySimpleUpdate() { + + public function testManyToManySimpleUpdate() + { $component = $this->connection->getTable('M2MTest')->find(1); - + $this->assertEqual($component->name, 2); - + $component->name = 'changed name'; - + $component->save(); - + $this->assertEqual($component->name, 'changed name'); } -} \ No newline at end of file +} diff --git a/tests/Relation/NestTestCase.php b/tests/Relation/NestTestCase.php index 1251bed35..82817a565 100644 --- a/tests/Relation/NestTestCase.php +++ b/tests/Relation/NestTestCase.php @@ -20,42 +20,49 @@ */ /** - * Doctrine_Relation_Nest_TestCase + * Doctrine_Relation_Nest_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Relation_Nest_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } public function prepareTables() { $this->tables = array('NestTest', 'NestReference', 'Entity', 'EntityReference'); - + parent::prepareTables(); } - public function testInitJoinTableSelfReferencingInsertingData() + public function testInitJoinTableSelfReferencingInsertingData() { $e = new Entity(); - $e->name = "Entity test"; + $e->name = 'Entity test'; $this->assertTrue($e->Entity[0] instanceof Entity); $this->assertTrue($e->Entity[1] instanceof Entity); $this->assertEqual($e->Entity[0]->state(), Doctrine_Record::STATE_TCLEAN); $this->assertEqual($e->Entity[1]->state(), Doctrine_Record::STATE_TCLEAN); - + $e->Entity[0]->name = 'Friend 1'; $e->Entity[1]->name = 'Friend 2'; - + $e->Entity[0]->Entity[0]->name = 'Friend 1 1'; $e->Entity[0]->Entity[1]->name = 'Friend 1 2'; @@ -78,11 +85,11 @@ public function testInitJoinTableSelfReferencingInsertingData() $e->save(); - $this->assertEqual(($count + 13), $this->conn->count()); + $this->assertEqual($count + 13, $this->conn->count()); } public function testNestRelationsFetchingData() - { + { $this->connection->clear(); $e = $this->conn->queryOne('FROM Entity e LEFT JOIN e.Entity e2 LEFT JOIN e2.Entity e3 WHERE (e.id = 1) ORDER BY e.name, e2.name, e3.name'); @@ -90,7 +97,7 @@ public function testNestRelationsFetchingData() $this->assertTrue($e->Entity[0] instanceof Entity); $this->assertTrue($e->Entity[1] instanceof Entity); - + $this->assertEqual($e->Entity[0]->name, 'Friend 1'); $this->assertEqual($e->Entity[1]->name, 'Friend 2'); @@ -111,12 +118,12 @@ public function testNestRelationsFetchingData() $this->assertEqual(count($result), 6); - //$stmt = $this->dbh->prepare($q); + // $stmt = $this->dbh->prepare($q); - //$stmt->execute(array(18)); - //$result = $stmt->fetchAll(PDO::FETCH_ASSOC); + // $stmt->execute(array(18)); + // $result = $stmt->fetchAll(PDO::FETCH_ASSOC); - //print_r($result); + // print_r($result); $this->connection->clear(); @@ -129,30 +136,30 @@ public function testNestRelationsFetchingData() $this->assertTrue($e->Entity[0] instanceof Entity); $this->assertTrue($e->Entity[1] instanceof Entity); - $this->assertEqual(count($this->conn), ($count + 1)); + $this->assertEqual(count($this->conn), $count + 1); - $this->assertEqual($e->Entity[0]->name, "Friend 1"); - $this->assertEqual($e->Entity[1]->name, "Friend 2"); + $this->assertEqual($e->Entity[0]->name, 'Friend 1'); + $this->assertEqual($e->Entity[1]->name, 'Friend 2'); - $this->assertEqual($e->Entity[0]->Entity[0]->name, "Entity test"); - $this->assertEqual($e->Entity[0]->Entity[1]->name, "Friend 1 1"); + $this->assertEqual($e->Entity[0]->Entity[0]->name, 'Entity test'); + $this->assertEqual($e->Entity[0]->Entity[1]->name, 'Friend 1 1'); - $this->assertEqual(count($this->conn), ($count + 2)); + $this->assertEqual(count($this->conn), $count + 2); - $this->assertEqual($e->Entity[1]->Entity[0]->name, "Entity test"); - $this->assertEqual($e->Entity[1]->Entity[1]->name, "Friend 2 1"); + $this->assertEqual($e->Entity[1]->Entity[0]->name, 'Entity test'); + $this->assertEqual($e->Entity[1]->Entity[1]->name, 'Friend 2 1'); - $this->assertEqual(count($this->conn), ($count + 3)); + $this->assertEqual(count($this->conn), $count + 3); $this->assertEqual($e->Entity[0]->state(), Doctrine_Record::STATE_CLEAN); $this->assertEqual($e->Entity[1]->state(), Doctrine_Record::STATE_CLEAN); - + $coll = $this->connection->query("FROM Entity WHERE Entity.name = 'Friend 1'"); $this->assertEqual($coll->count(), 1); $this->assertEqual($coll[0]->state(), Doctrine_Record::STATE_CLEAN); - - $this->assertEqual($coll[0]->name, "Friend 1"); - + + $this->assertEqual($coll[0]->name, 'Friend 1'); + $query = new Doctrine_Query($this->connection); $query->from('Entity e LEFT JOIN e.Entity e2')->where("e2.name = 'Friend 1 1'"); @@ -165,11 +172,11 @@ public function testNestRelationsFetchingData() public function testNestRelationsParsing() { $nest = new NestTest(); - + $rel = $nest->getTable()->getRelation('Parents'); $this->assertTrue($rel instanceof Doctrine_Relation_Nest); - + $this->assertEqual($rel->getLocal(), 'child_id'); $this->assertEqual($rel->getForeign(), 'parent_id'); } @@ -187,19 +194,19 @@ public function testNestRelationsSaving() $nest->Children[1]->name = 'c 2'; $nest->Children[1]->Parents[]->name = 'n 2'; $nest->save(); - + $this->connection->clear(); } public function testNestRelationsLoading() { $nest = $this->conn->queryOne('FROM NestTest n WHERE n.id = 1'); - + $this->assertEqual($nest->Parents->count(), 3); $this->assertEqual($nest->Children->count(), 2); $this->assertEqual($nest->Children[0]->Children->count(), 2); $this->assertEqual($nest->Children[1]->Parents->count(), 2); - + $this->connection->clear(); } @@ -250,5 +257,4 @@ public function testEqualNestRelationsQuerying() $this->assertEqual($n[0]->Relatives->count(), 5); } - } diff --git a/tests/Relation/OneToManyTestCase.php b/tests/Relation/OneToManyTestCase.php index 5133f47fd..44df16967 100644 --- a/tests/Relation/OneToManyTestCase.php +++ b/tests/Relation/OneToManyTestCase.php @@ -20,26 +20,35 @@ */ /** - * Doctrine_Relation_OneToOne_TestCase + * Doctrine_Relation_OneToOne_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Relation_OneToMany_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() { $this->tables = array('Entity', 'Phonenumber', 'Email', 'Policy', 'PolicyAsset', 'Role', 'Auth'); - + parent::prepareTables(); } + public function testRelationParsing() { $table = $this->conn->getTable('Entity'); @@ -70,49 +79,52 @@ public function testRelationParsing3() $this->assertTrue($rel instanceof Doctrine_Relation_ForeignKey); } - public function testRelationSaving() + + public function testRelationSaving() { $p = new Policy(); $p->policy_number = '123'; - + $a = new PolicyAsset(); $a->value = '123.13'; $p->PolicyAssets[] = $a; $p->save(); - + $this->assertEqual($a->policy_number, '123'); } + public function testRelationSaving2() { $e = new Entity(); $e->name = 'test'; $e->save(); - + $nr = new Phonenumber(); $nr->phonenumber = '1234556'; $nr->save(); $nr->Entity = $e; } - public function testRelationSaving3() + + public function testRelationSaving3() { // create roles and user with role1 and role2 $this->conn->beginTransaction(); $role = new Role(); $role->name = 'role1'; $role->save(); - + $auth = new Auth(); $auth->name = 'auth1'; $auth->Role = $role; $auth->save(); - + $this->conn->commit(); - + $this->conn->clear(); $auths = $this->conn->query('FROM Auth a LEFT JOIN a.Role r'); - $this->assertEqual($auths[0]->Role->name, 'role1'); + $this->assertEqual($auths[0]->Role->name, 'role1'); } } diff --git a/tests/Relation/OneToOneTestCase.php b/tests/Relation/OneToOneTestCase.php index b65f9dcf0..77027886f 100644 --- a/tests/Relation/OneToOneTestCase.php +++ b/tests/Relation/OneToOneTestCase.php @@ -20,24 +20,32 @@ */ /** - * Doctrine_Relation_OneToOne_TestCase + * Doctrine_Relation_OneToOne_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Relation_OneToOne_TestCase extends Doctrine_UnitTestCase +class Doctrine_Relation_OneToOne_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } - public function prepareTables() - { - $this->tables = array('gnatUser','gnatEmail','Email','Entity','Record_City', 'Record_Country', 'SelfRefTest'); - + public function prepareData() + { + } + + public function prepareTables() + { + $this->tables = array('gnatUser', 'gnatEmail', 'Email', 'Entity', 'Record_City', 'Record_Country', 'SelfRefTest'); + parent::prepareTables(); } @@ -46,27 +54,28 @@ public function testOneToOneAggregateRelationWithAliasesIsSupported() $city = new Record_City(); $country = $city->Country; - $this->assertTrue($country instanceof Record_Country); + $this->assertTrue($country instanceof Record_Country); } - + public function testSelfReferentialOneToOneRelationsAreSupported() { $ref = new SelfRefTest(); - + $rel = $ref->getTable()->getRelation('createdBy'); $this->assertEqual($rel->getForeign(), 'id'); $this->assertEqual($rel->getLocal(), 'created_by'); - + $ref->name = 'ref 1'; $ref->createdBy->name = 'ref 2'; - + $ref->save(); } + public function testSelfReferentialOneToOneRelationsAreSupported2() { $this->connection->clear(); - + $ref = $this->conn->queryOne("FROM SelfRefTest s WHERE s.name = 'ref 1'"); $this->assertEqual($ref->name, 'ref 1'); $this->assertEqual($ref->createdBy->name, 'ref 2'); @@ -80,10 +89,10 @@ public function testUnsetRelation() $email->address = 'test@test.com'; $user->Email = $email; $user->save(); - $this->assertTrue($user->Email instanceOf Email); + $this->assertTrue($user->Email instanceof Email); $user->Email = Email::getNullObject(); $user->save(); - $this->assertTrue($user->Email === null); + $this->assertTrue(null === $user->Email); } public function testSavingRelatedObjects() @@ -94,8 +103,7 @@ public function testSavingRelatedObjects() $email->address = 'test3@test.com'; $user->Email = $email; $user->save(); - $this->assertTrue($user->Email instanceOf gnatEmail); + $this->assertTrue($user->Email instanceof gnatEmail); $this->assertEqual($user->foreign_id, $user->Email->id); - } } diff --git a/tests/Relation/OrderByTestCase.php b/tests/Relation/OrderByTestCase.php index 84487c452..462875b13 100644 --- a/tests/Relation/OrderByTestCase.php +++ b/tests/Relation/OrderByTestCase.php @@ -20,22 +20,28 @@ */ /** - * Doctrine_Relation_OrderBy_TestCase + * Doctrine_Relation_OrderBy_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Relation_OrderBy_TestCase extends Doctrine_UnitTestCase +class Doctrine_Relation_OrderBy_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->profiler = new Doctrine_Connection_Profiler(); - $this->conn->addListener($this->profiler); + $this->conn->addListener($this->profiler); $this->tables[] = 'OrderByTest_Article'; $this->tables[] = 'OrderByTest_Friend'; @@ -57,7 +63,8 @@ public function testFullDqlQuery() ->leftJoin('u.Groups g') ->leftJoin('u.Friends f') ->leftJoin('u.ChildrenUsers cu') - ->leftJoin('u.ParentUser pu'); + ->leftJoin('u.ParentUser pu') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT o.id AS o__id FROM order_by_test__user o LEFT JOIN order_by_test__article o2 ON o.id = o2.user_id LEFT JOIN order_by_test__user_group o4 ON (o.id = o4.user_id) LEFT JOIN order_by_test__group o3 ON o3.id = o4.group_id LEFT JOIN order_by_test__friend o6 ON (o.id = o6.user_id1 OR o.id = o6.user_id2) LEFT JOIN order_by_test__user o5 ON (o5.id = o6.user_id2 OR o5.id = o6.user_id1) AND o5.id != o.id LEFT JOIN order_by_test__user o7 ON o.id = o7.parent_user_id LEFT JOIN order_by_test__user o8 ON o.parent_user_id = o8.id ORDER BY o2.title ASC, o3.name ASC, o4.name ASC, o5.login ASC, o6.login ASC, o7.login ASC, o8.id ASC'); } @@ -103,7 +110,8 @@ public function testMasterOrderBy() $q = Doctrine_Core::getTable('OrderByTest_Category') ->createQuery('c') ->select('c.id, p.id') - ->leftJoin('c.Posts p'); + ->leftJoin('c.Posts p') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT o.id AS o__id, o2.id AS o2__id FROM order_by_test__category o LEFT JOIN order_by_test__blog_post o2 ON o.id = o2.category_id ORDER BY o.name ASC, o2.title ASC, o2.is_first DESC'); @@ -122,7 +130,8 @@ public function testOrderByFromQueryComesFirst() ->createQuery('c') ->select('c.id, p.id') ->leftJoin('c.Posts p') - ->orderBy('p.title ASC'); + ->orderBy('p.title ASC') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT o.id AS o__id, o2.id AS o2__id FROM order_by_test__category o LEFT JOIN order_by_test__blog_post o2 ON o.id = o2.category_id ORDER BY o2.title ASC, o.name ASC, o2.is_first DESC'); } @@ -131,7 +140,8 @@ public function testWeirdSort() { $q = Doctrine_Core::getTable('OrderByTest_WeirdSort') ->createQuery('w') - ->select('w.id'); + ->select('w.id') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT o.id AS o__id FROM order_by_test__weird_sort o ORDER BY RAND()'); } @@ -149,8 +159,8 @@ public function setTableDefinition() public function setUp() { $this->hasOne('OrderByTest_User as User', array( - 'local' => 'user_id', - 'foreign' => 'id')); + 'local' => 'user_id', + 'foreign' => 'id')); } } @@ -159,11 +169,11 @@ class OrderByTest_Friend extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('user_id1', 'integer', null, array( - 'primary' => true, - )); + 'primary' => true, + )); $this->hasColumn('user_id2', 'integer', null, array( - 'primary' => true, - )); + 'primary' => true, + )); } } @@ -172,17 +182,17 @@ class OrderByTest_Group extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('name', 'string', 255, array( - 'type' => 'string', - 'length' => '255', - )); + 'type' => 'string', + 'length' => '255', + )); } public function setUp() { $this->hasMany('OrderByTest_User as User', array( - 'refClass' => 'OrderByTest_UserGroup', - 'local' => 'group_id', - 'foreign' => 'user_id')); + 'refClass' => 'OrderByTest_UserGroup', + 'local' => 'group_id', + 'foreign' => 'user_id')); } } @@ -198,22 +208,22 @@ public function setTableDefinition() public function setUp() { $this->hasMany('OrderByTest_Article as Articles', array( - 'local' => 'id', - 'foreign' => 'user_id', - 'orderBy' => 'title ASC')); + 'local' => 'id', + 'foreign' => 'user_id', + 'orderBy' => 'title ASC')); $this->hasMany('OrderByTest_Group as Groups', array( - 'refClass' => 'OrderByTest_UserGroup', - 'local' => 'user_id', - 'foreign' => 'group_id', - 'orderBy' => 'name ASC')); + 'refClass' => 'OrderByTest_UserGroup', + 'local' => 'user_id', + 'foreign' => 'group_id', + 'orderBy' => 'name ASC')); $this->hasMany('OrderByTest_User as Friends', array( - 'refClass' => 'OrderByTest_Friend', - 'local' => 'user_id1', - 'foreign' => 'user_id2', - 'equal' => true, - 'orderBy' => 'username ASC')); + 'refClass' => 'OrderByTest_Friend', + 'local' => 'user_id1', + 'foreign' => 'user_id2', + 'equal' => true, + 'orderBy' => 'username ASC')); $this->hasOne('OrderByTest_User as ParentUser', array( 'local' => 'parent_user_id', @@ -232,15 +242,14 @@ class OrderByTest_UserGroup extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('user_id', 'integer', null, array( - 'primary' => true, - )); + 'primary' => true, + )); $this->hasColumn('group_id', 'integer', null, array( - 'primary' => true, - )); + 'primary' => true, + )); } } - class OrderByTest_Category extends Doctrine_Record { public function setTableDefinition() @@ -254,7 +263,7 @@ public function setUp() { $this->hasMany('OrderByTest_BlogPost as Posts', array( 'local' => 'id', - 'foreign' => 'category_id' + 'foreign' => 'category_id', )); } } @@ -274,7 +283,7 @@ public function setUp() { $this->hasOne('OrderByTest_Category', array( 'local' => 'category_id', - 'foreign' => 'id' + 'foreign' => 'id', )); } } @@ -287,4 +296,4 @@ public function setTableDefinition() $this->hasColumn('title', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Relation/ParserTestCase.php b/tests/Relation/ParserTestCase.php index 9181843ec..ec0298d7b 100644 --- a/tests/Relation/ParserTestCase.php +++ b/tests/Relation/ParserTestCase.php @@ -20,33 +20,40 @@ */ /** - * Doctrine_Relation_Parser_TestCase + * Doctrine_Relation_Parser_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Relation_Parser_TestCase extends Doctrine_UnitTestCase +class Doctrine_Relation_Parser_TestCase extends Doctrine_UnitTestCase { public function testPendingRelations() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); - - $p = array('type' => Doctrine_Relation::ONE, - 'local' => 'email_id'); + + $p = array('type' => Doctrine_Relation::ONE, + 'local' => 'email_id'); $r->bind('Email', $p); - $this->assertEqual($r->getPendingRelation('Email'), array('type' => Doctrine_Relation::ONE, - 'local' => 'email_id', - 'class' => 'Email', - 'alias' => 'Email' - )); + $this->assertEqual($r->getPendingRelation('Email'), array('type' => Doctrine_Relation::ONE, + 'local' => 'email_id', + 'class' => 'Email', + 'alias' => 'Email', + )); } + public function testBindThrowsExceptionIfTypeNotSet() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); @@ -55,56 +62,61 @@ public function testBindThrowsExceptionIfTypeNotSet() try { $r->bind('Email', $p); $this->fail('should throw exception'); - } catch(Doctrine_Relation_Exception $e) { + } catch (Doctrine_Relation_Exception $e) { $this->pass(); } } + public function testRelationParserSupportsLocalColumnGuessing() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); - $d = $r->completeDefinition(array('class' => 'Phonenumber', - 'type' => Doctrine_Relation::MANY, - 'foreign' => 'entity_id')); + $d = $r->completeDefinition(array('class' => 'Phonenumber', + 'type' => Doctrine_Relation::MANY, + 'foreign' => 'entity_id')); $this->assertEqual($d['local'], 'id'); } + public function testRelationParserSupportsLocalColumnGuessing2() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); - $d = $r->completeDefinition(array('class' => 'Email', - 'type' => Doctrine_Relation::ONE, - 'foreign' => 'id')); + $d = $r->completeDefinition(array('class' => 'Email', + 'type' => Doctrine_Relation::ONE, + 'foreign' => 'id')); $this->assertEqual($d['local'], 'email_id'); } + public function testRelationParserSupportsForeignColumnGuessing() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); $d = $r->completeDefinition(array('class' => 'Phonenumber', - 'type' => Doctrine_Relation::MANY, - 'local' => 'id')); + 'type' => Doctrine_Relation::MANY, + 'local' => 'id')); $this->assertEqual($d['foreign'], 'entity_id'); } + public function testRelationParserSupportsForeignColumnGuessing2() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); $d = $r->completeDefinition(array('class' => 'Email', - 'type' => Doctrine_Relation::ONE, - 'local' => 'email_id')); + 'type' => Doctrine_Relation::ONE, + 'local' => 'email_id')); $this->assertEqual($d['foreign'], 'id'); } + public function testRelationParserSupportsGuessingOfBothColumns() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); $d = $r->completeDefinition(array('class' => 'Email', - 'type' => Doctrine_Relation::ONE)); + 'type' => Doctrine_Relation::ONE)); $this->assertEqual($d['foreign'], 'id'); $this->assertEqual($d['local'], 'email_id'); @@ -115,45 +127,49 @@ public function testRelationParserSupportsGuessingOfBothColumns2() $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); $d = $r->completeDefinition(array('class' => 'Phonenumber', - 'type' => Doctrine_Relation::MANY)); + 'type' => Doctrine_Relation::MANY)); $this->assertEqual($d['foreign'], 'entity_id'); $this->assertEqual($d['local'], 'id'); } + public function testRelationParserSupportsForeignColumnGuessingForAssociations() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); - $d = $r->completeAssocDefinition(array('class' => 'Group', - 'type' => Doctrine_Relation::MANY, - 'local' => 'user_id', - 'refClass' => 'GroupUser')); + $d = $r->completeAssocDefinition(array('class' => 'Group', + 'type' => Doctrine_Relation::MANY, + 'local' => 'user_id', + 'refClass' => 'GroupUser')); $this->assertEqual($d['foreign'], 'group_id'); } + public function testRelationParserSupportsLocalColumnGuessingForAssociations() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); - $d = $r->completeAssocDefinition(array('class' => 'Group', - 'type' => Doctrine_Relation::MANY, - 'foreign' => 'group_id', - 'refClass' => 'GroupUser')); + $d = $r->completeAssocDefinition(array('class' => 'Group', + 'type' => Doctrine_Relation::MANY, + 'foreign' => 'group_id', + 'refClass' => 'GroupUser')); $this->assertEqual($d['local'], 'user_id'); } + public function testGetRelationReturnsForeignKeyObjectForOneToOneRelation() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); - $p = array('type' => Doctrine_Relation::ONE, - 'local' => 'email_id'); + $p = array('type' => Doctrine_Relation::ONE, + 'local' => 'email_id'); $r->bind('Email', $p); $rel = $r->getRelation('Email'); - + $this->assertTrue($rel instanceof Doctrine_Relation_LocalKey); } + public function testGetRelationReturnsForeignKeyObjectForOneToManyRelation() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); @@ -165,27 +181,29 @@ public function testGetRelationReturnsForeignKeyObjectForOneToManyRelation() $this->assertTrue($rel instanceof Doctrine_Relation_ForeignKey); } + public function testGetRelationReturnsForeignKeyObjectForManytToManyRelation() { $r = new Doctrine_Relation_Parser($this->conn->getTable('User')); $p = array('type' => Doctrine_Relation::MANY, - 'refClass' => 'GroupUser'); + 'refClass' => 'GroupUser'); $r->bind('Group', $p); $rel = $r->getRelation('Group'); - + $this->assertTrue($rel instanceof Doctrine_Relation_Association); $rel = $r->getRelation('GroupUser'); $this->assertTrue($rel instanceof Doctrine_Relation_ForeignKey); } + public function testGetRelationReturnsForeignKeyObjectForNestRelation() { $r = new Doctrine_Relation_Parser($this->conn->getTable('Entity')); $p = array('type' => Doctrine_Relation::MANY, - 'refClass' => 'EntityReference', - 'local' => 'entity1', - 'foreign' => 'entity2'); + 'refClass' => 'EntityReference', + 'local' => 'entity1', + 'foreign' => 'entity2'); $r->bind('Entity', $p); @@ -195,6 +213,6 @@ public function testGetRelationReturnsForeignKeyObjectForNestRelation() $rel = $r->getRelation('EntityReference'); $this->assertTrue($rel instanceof Doctrine_Relation_ForeignKey); } - + // TODO: BETTER ASSOCIATION TABLE GUESSING } diff --git a/tests/RelationTestCase.php b/tests/RelationTestCase.php index f7d2e1b59..4b36310d4 100644 --- a/tests/RelationTestCase.php +++ b/tests/RelationTestCase.php @@ -20,59 +20,67 @@ */ /** - * Doctrine_Relation_TestCase + * Doctrine_Relation_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Relation_TestCase extends Doctrine_UnitTestCase +class Doctrine_Relation_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } - public function prepareTables() + public function prepareData() + { + } + + public function prepareTables() { $this->tables = array('RelationTest', 'RelationTestChild', 'Group', 'Groupuser', 'User', 'Email', 'Account', 'Phonenumber'); - + parent::prepareTables(); } - public function testInitData() + public function testInitData() { $user = new User(); - + $user->name = 'zYne'; $user->Group[0]->name = 'Some Group'; $user->Group[1]->name = 'Other Group'; $user->Group[2]->name = 'Third Group'; - + $user->Phonenumber[0]->phonenumber = '123 123'; $user->Phonenumber[1]->phonenumber = '234 234'; $user->Phonenumber[2]->phonenumber = '456 456'; - + $user->Email->address = 'someone@some.where'; $user->save(); } - + public function testUnlinkSupportsManyToManyRelations() { $users = Doctrine_Query::create()->from('User u')->where('u.name = ?', array('zYne'))->execute(); - + $user = $users[0]; - + $this->assertEqual($user->Group->count(), 3); - + $user->unlink('Group', array(2, 3, 4), true); - + $this->assertEqual($user->Group->count(), 0); - + $this->conn->clear(); - + $groups = Doctrine_Query::create()->from('Group g')->execute(); $this->assertEqual($groups->count(), 3); @@ -87,35 +95,34 @@ public function testUnlinkSupportsOneToManyRelations() $this->conn->clear(); $users = Doctrine_Query::create()->from('User u')->where('u.name = ?', array('zYne'))->execute(); - + $user = $users[0]; - + $this->assertEqual($user->Phonenumber->count(), 3); - + $user->unlink('Phonenumber', array(1, 2, 3), true); - + $this->assertEqual($user->Phonenumber->count(), 0); - + $this->conn->clear(); - + $phonenumber = Doctrine_Query::create()->from('Phonenumber p')->execute(); $this->assertEqual($phonenumber->count(), 3); $this->assertEqual($phonenumber[0]->entity_id, null); $this->assertEqual($phonenumber[1]->entity_id, null); - $this->assertEqual($phonenumber[2]->entity_id, null); + $this->assertEqual($phonenumber[2]->entity_id, null); } - public function testOneToManyTreeRelationWithConcreteInheritance() { - + public function testOneToManyTreeRelationWithConcreteInheritance() + { $component = new RelationTestChild(); try { $rel = $component->getTable()->getRelation('Children'); $this->pass(); - } catch(Doctrine_Exception $e) { - + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertTrue($rel instanceof Doctrine_Relation_ForeignKey); @@ -124,43 +131,52 @@ public function testOneToManyTreeRelationWithConcreteInheritance() { $this->assertTrue($component->Children[0] instanceof RelationTestChild); } - public function testOneToOneTreeRelationWithConcreteInheritance() { + public function testOneToOneTreeRelationWithConcreteInheritance() + { $component = new RelationTestChild(); - + try { $rel = $component->getTable()->getRelation('Parent'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertTrue($rel instanceof Doctrine_Relation_LocalKey); } - public function testManyToManyRelation() { + + public function testManyToManyRelation() + { $user = new User(); - + // test that join table relations can be initialized even before the association have been initialized try { $user->Groupuser; $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } - //$this->assertTrue($user->getTable()->getRelation('Groupuser') instanceof Doctrine_Relation_ForeignKey); + // $this->assertTrue($user->getTable()->getRelation('Groupuser') instanceof Doctrine_Relation_ForeignKey); $this->assertTrue($user->getTable()->getRelation('Group') instanceof Doctrine_Relation_Association); } - public function testOneToOneLocalKeyRelation() { + + public function testOneToOneLocalKeyRelation() + { $user = new User(); - + $this->assertTrue($user->getTable()->getRelation('Email') instanceof Doctrine_Relation_LocalKey); } - public function testOneToOneForeignKeyRelation() { + + public function testOneToOneForeignKeyRelation() + { $user = new User(); - + $this->assertTrue($user->getTable()->getRelation('Account') instanceof Doctrine_Relation_ForeignKey); } - public function testOneToManyForeignKeyRelation() { + + public function testOneToManyForeignKeyRelation() + { $user = new User(); - + $this->assertTrue($user->getTable()->getRelation('Phonenumber') instanceof Doctrine_Relation_ForeignKey); } } diff --git a/tests/RepositoryTestCase.php b/tests/RepositoryTestCase.php index 50a873cfc..7eede0644 100644 --- a/tests/RepositoryTestCase.php +++ b/tests/RepositoryTestCase.php @@ -1,5 +1,13 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Search_File_TestCase extends Doctrine_UnitTestCase { protected $_search; public function prepareData() - { } + { + } + public function prepareTables() - { } + { + } public function testSearchFileAutoCreatesFileTable() { @@ -48,10 +57,10 @@ public function testSearchFileAutoCreatesFileTable() public function testIndexDirectoryIndexesAllFiles() { - $this->_search->indexDirectory(dirname(__FILE__) . DIRECTORY_SEPARATOR . '_files'); + $this->_search->indexDirectory(dirname(__FILE__).DIRECTORY_SEPARATOR.'_files'); $resultSet = $this->_search->search('dbms'); - + $this->assertEqual(count($resultSet), 1); } } diff --git a/tests/Search/IndexerTestCase.php b/tests/Search/IndexerTestCase.php index f24cfbd04..750918dd9 100644 --- a/tests/Search/IndexerTestCase.php +++ b/tests/Search/IndexerTestCase.php @@ -20,24 +20,32 @@ */ /** - * Doctrine_Search_Indexer_TestCase + * Doctrine_Search_Indexer_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Search_Indexer_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() { $this->tables = array('Doctrine_File', 'Doctrine_File_Index'); - + parent::prepareTables(); } @@ -48,9 +56,9 @@ public function testIndexexCanRecursivelyIndexDirectories() $indexer = new Doctrine_Search_Indexer(); - $indexer->indexDirectory(dirname(__FILE__) . DIRECTORY_SEPARATOR . '_files'); + $indexer->indexDirectory(dirname(__FILE__).DIRECTORY_SEPARATOR.'_files'); } - + public function testIndexerAddsFiles() { $files = Doctrine_Query::create()->from('Doctrine_File')->execute(); @@ -61,7 +69,8 @@ public function testIndexerAddsFiles() public function testSearchingFiles() { $files = Doctrine_Query::create()->select('DISTINCT i.file_id')->from('Doctrine_File_Index i') - ->where('i.keyword = ?', array('database'))->execute(array(), Doctrine_Hydrate::HYDRATE_ARRAY); + ->where('i.keyword = ?', array('database'))->execute(array(), Doctrine_Hydrate::HYDRATE_ARRAY) + ; $this->assertEqual(count($files), 11); } diff --git a/tests/Search/QueryTestCase.php b/tests/Search/QueryTestCase.php index cca457435..48cacfc4d 100644 --- a/tests/Search/QueryTestCase.php +++ b/tests/Search/QueryTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Search_Query_TestCase + * Doctrine_Search_Query_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Search_Query_TestCase extends Doctrine_UnitTestCase { @@ -38,8 +44,10 @@ public function prepareTables() parent::prepareTables(); } + public function prepareData() - { } + { + } public function testInitData() { @@ -64,7 +72,7 @@ public function testParseClauseSupportsAndOperator() $ret = $q->parseClause('doctrine AND orm'); $sql = 'id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?)'; + .'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?)'; $this->assertEqual($ret, $sql); } @@ -145,7 +153,7 @@ public function testParseClauseSupportsNegationOperator() $ret = $q->parseClause('rdbms -doctrine'); $sql = 'id IN (SELECT id FROM search_test_index WHERE keyword = ?) AND ' - . 'id NOT IN (SELECT id FROM search_test_index WHERE keyword = ?)'; + .'id NOT IN (SELECT id FROM search_test_index WHERE keyword = ?)'; $this->assertEqual($ret, $sql); } @@ -156,8 +164,8 @@ public function testParseClauseOrOperator2() $ret = $q->parseClause('rdbms doctrine OR database'); $sql = 'id IN (SELECT id FROM search_test_index WHERE keyword = ?) AND ' - . 'id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'OR keyword = ?'; + .'id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'OR keyword = ?'; $this->assertEqual($ret, $sql); } @@ -168,8 +176,8 @@ public function testParseClauseSupportsNegationOperatorWithOrOperator() $ret = $q->parseClause('rdbms -doctrine OR database'); $sql = 'id IN (SELECT id FROM search_test_index WHERE keyword = ?) AND ' - . 'id NOT IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'OR keyword = ?'; + .'id NOT IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'OR keyword = ?'; $this->assertEqual($ret, $sql); } @@ -180,36 +188,34 @@ public function testSearchSupportsAndOperator() $q->query('doctrine AND orm'); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index ' - . 'WHERE id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index ' + .'WHERE id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getSqlQuery(), $sql); } - public function testSearchSupportsOrOperator() { $q = new Doctrine_Search_Query('SearchTestIndex'); $q->query('doctrine OR orm'); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index ' - . 'WHERE keyword = ? OR keyword = ? ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index ' + .'WHERE keyword = ? OR keyword = ? ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getSqlQuery(), $sql); } - public function testQuerySupportsSingleWordquery() { $q = new Doctrine_Search_Query('SearchTestIndex'); $q->query('doctrine'); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index WHERE keyword = ? GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index WHERE keyword = ? GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getParams(), array('doctrine')); $this->assertEqual($q->getSqlQuery(), $sql); @@ -221,10 +227,10 @@ public function testSearchSupportsMixingOfOperators() $q->query('(doctrine OR orm) AND dbal'); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index ' - . 'WHERE id IN (SELECT id FROM search_test_index WHERE keyword = ? OR keyword = ?) ' - . 'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index ' + .'WHERE id IN (SELECT id FROM search_test_index WHERE keyword = ? OR keyword = ?) ' + .'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getParams(), array('doctrine', 'orm', 'dbal')); $this->assertEqual($q->getSqlQuery(), $sql); @@ -236,9 +242,9 @@ public function testSearchSupportsSingleTermWithQuotes() $q->query("'doctrine orm'"); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index WHERE keyword = ? ' - . 'AND (position + 1) IN (SELECT position FROM search_test_index WHERE keyword = ?) ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index WHERE keyword = ? ' + .'AND (position + 1) IN (SELECT position FROM search_test_index WHERE keyword = ?) ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getParams(), array('doctrine', 'orm')); $this->assertEqual($q->getSqlQuery(), $sql); @@ -250,10 +256,10 @@ public function testSearchSupportsSingleLongTermWithQuotes() $q->query("'doctrine orm dbal'"); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index WHERE keyword = ? ' - . 'AND (position + 1) IN (SELECT position FROM search_test_index WHERE keyword = ?) ' - . 'AND (position + 2) IN (SELECT position FROM search_test_index WHERE keyword = ?) ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index WHERE keyword = ? ' + .'AND (position + 1) IN (SELECT position FROM search_test_index WHERE keyword = ?) ' + .'AND (position + 2) IN (SELECT position FROM search_test_index WHERE keyword = ?) ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getParams(), array('doctrine', 'orm', 'dbal')); $this->assertEqual($q->getSqlQuery(), $sql); @@ -265,10 +271,10 @@ public function testQuerySupportsMultiWordquery() $q->query('doctrine orm'); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index ' - . 'WHERE id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index ' + .'WHERE id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getSqlQuery(), $sql); } @@ -279,39 +285,41 @@ public function testQuerySupportsMultiWordSearchAndSingleLetterWildcards() $q->query('doct?ine orm'); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index ' - . 'WHERE id IN (SELECT id FROM search_test_index WHERE keyword LIKE ?) ' - . 'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index ' + .'WHERE id IN (SELECT id FROM search_test_index WHERE keyword LIKE ?) ' + .'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getParams(), array('doct?ine', 'orm')); $this->assertEqual($q->getSqlQuery(), $sql); } + public function testQuerySupportsMultiWordSearchAndMultiLetterWildcards() { $q = new Doctrine_Search_Query('SearchTestIndex'); $q->query('doc* orm'); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index ' - . 'WHERE id IN (SELECT id FROM search_test_index WHERE keyword LIKE ?) ' - . 'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index ' + .'WHERE id IN (SELECT id FROM search_test_index WHERE keyword LIKE ?) ' + .'AND id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getParams(), array('doc%', 'orm')); $this->assertEqual($q->getSqlQuery(), $sql); } + public function testSearchSupportsMultipleTermsWithQuotes() { $q = new Doctrine_Search_Query('SearchTestIndex'); $q->query("doctrine 'orm database'"); $sql = 'SELECT COUNT(keyword) AS relevance, id ' - . 'FROM search_test_index ' - . 'WHERE id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' - . 'AND id IN (SELECT id FROM search_test_index WHERE keyword = ? ' - . 'AND (position + 1) IN (SELECT position FROM search_test_index WHERE keyword = ?)) ' - . 'GROUP BY id ORDER BY relevance DESC'; + .'FROM search_test_index ' + .'WHERE id IN (SELECT id FROM search_test_index WHERE keyword = ?) ' + .'AND id IN (SELECT id FROM search_test_index WHERE keyword = ? ' + .'AND (position + 1) IN (SELECT position FROM search_test_index WHERE keyword = ?)) ' + .'GROUP BY id ORDER BY relevance DESC'; $this->assertEqual($q->getParams(), array('doctrine', 'orm', 'database')); $this->assertEqual($q->getSqlQuery(), $sql); @@ -324,5 +332,4 @@ public function testSearchReturnsFalseForEmptyStrings() $this->assertFalse($result); } - } diff --git a/tests/Search/QueryWeightTestCase.php b/tests/Search/QueryWeightTestCase.php index de164b382..931c863a2 100644 --- a/tests/Search/QueryWeightTestCase.php +++ b/tests/Search/QueryWeightTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Search_QueryWeight_TestCase + * Doctrine_Search_QueryWeight_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Search_QueryWeight_TestCase extends Doctrine_UnitTestCase { @@ -37,22 +43,22 @@ public function testQuerySupportsMultiWordOrOperatorSearchWithQuotes() $q = new Doctrine_Search_Query('SearchTestIndex'); $q->search("doctrine^2 OR 'dbal database'"); - $sql = 'SELECT foreign_id, SUM(relevancy) AS relevancy_sum ' - . 'FROM (SELECT COUNT(keyword) * 2 AS relevancy, foreign_id ' - . 'FROM search_index ' - . 'WHERE keyword = ? ' - . 'GROUP BY foreign_id ' - . 'UNION ' - . 'SELECT COUNT(keyword) AS relevancy, foreign_id ' - . 'FROM search_index) AS query_alias ' - . 'WHERE keyword = ? AND (position + 1) = (SELECT position FROM search_index WHERE keyword = ?) ' - . 'GROUP BY foreign_id) ' - . 'GROUP BY foreign_id ' - . 'ORDER BY relevancy_sum'; + $sql = 'SELECT foreign_id, SUM(relevancy) AS relevancy_sum ' + .'FROM (SELECT COUNT(keyword) * 2 AS relevancy, foreign_id ' + .'FROM search_index ' + .'WHERE keyword = ? ' + .'GROUP BY foreign_id ' + .'UNION ' + .'SELECT COUNT(keyword) AS relevancy, foreign_id ' + .'FROM search_index) AS query_alias ' + .'WHERE keyword = ? AND (position + 1) = (SELECT position FROM search_index WHERE keyword = ?) ' + .'GROUP BY foreign_id) ' + .'GROUP BY foreign_id ' + .'ORDER BY relevancy_sum'; $this->assertEqual($q->getSqlQuery(), $sql); } - + public function testSearchSupportsMixingOfOperatorsParenthesisAndWeights() { $q = new Doctrine_Search_Query('SearchTestIndex'); @@ -123,7 +129,7 @@ public function testQuerySupportsMultiWordNegationOperatorSearchWithQuotesWeight ) GROUP BY foreign_id ORDER BY relevancy_sum"; - + $this->assertEqual($q->getSqlQuery(), $sql); } } diff --git a/tests/SearchTestCase.php b/tests/SearchTestCase.php index c73245565..0c5e99528 100644 --- a/tests/SearchTestCase.php +++ b/tests/SearchTestCase.php @@ -20,38 +20,47 @@ */ /** - * Doctrine_Search_TestCase + * Doctrine_Search_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Search_TestCase extends Doctrine_UnitTestCase +class Doctrine_Search_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables = array('SearchTest'); - + parent::prepareTables(); } + public function prepareData() - { } + { + } public function testBuildingOfSearchRecordDefinition() { $e = new SearchTest(); - + $this->assertTrue($e->SearchTestIndex instanceof Doctrine_Collection); - + $rel = $e->getTable()->getRelation('SearchTestIndex'); $this->assertIdentical($rel->getLocal(), 'id'); $this->assertIdentical($rel->getForeign(), 'id'); } + public function testSavingEntriesUpdatesIndex() { $e = new SearchTest(); @@ -74,7 +83,8 @@ public function testSearchFromTableObject() $results = Doctrine_Core::getTable('SearchTest')->search('orm'); $this->assertEqual($results[0]['id'], 1); $query = Doctrine_Query::create() - ->from('SearchTest s'); + ->from('SearchTest s') + ; $query = Doctrine_Core::getTable('SearchTest')->search('orm', $query); $this->assertEqual($query->getSqlQuery(), 'SELECT s.id AS s__id, s.title AS s__title, s.content AS s__content FROM search_test s WHERE (s.id IN (SELECT id FROM search_test_index WHERE keyword = ? GROUP BY id))'); $results = $query->fetchArray(); @@ -86,9 +96,10 @@ public function testQuerying() $q = new Doctrine_Query(); $q->select('t.title') - ->from('SearchTest t') - ->innerJoin('t.SearchTestIndex i') - ->where('i.keyword = ?'); + ->from('SearchTest t') + ->innerJoin('t.SearchTestIndex i') + ->where('i.keyword = ?') + ; $array = $q->execute(array('orm'), Doctrine_Core::HYDRATE_ARRAY); @@ -97,23 +108,25 @@ public function testQuerying() $q = new Doctrine_Query(); $q->select('t.title') - ->from('SearchTest t') - ->innerJoin('t.SearchTestIndex i') - ->where('i.keyword = ?'); + ->from('SearchTest t') + ->innerJoin('t.SearchTestIndex i') + ->where('i.keyword = ?') + ; $array = $q->execute(array('007'), Doctrine_Core::HYDRATE_ARRAY); $this->assertEqual($array[0]['title'], '007'); } - + public function testUsingWordRange() { $q = new Doctrine_Query(); $q->select('t.title, i.*') - ->from('SearchTest t') - ->innerJoin('t.SearchTestIndex i') - ->where('i.keyword = ? OR i.keyword = ?'); + ->from('SearchTest t') + ->innerJoin('t.SearchTestIndex i') + ->where('i.keyword = ? OR i.keyword = ?') + ; $array = $q->execute(array('orm', 'framework'), Doctrine_Core::HYDRATE_ARRAY); @@ -125,9 +138,10 @@ public function testQueryingReturnsEmptyArrayForStopKeyword() $q = new Doctrine_Query(); $q->select('t.title') - ->from('SearchTest t') - ->innerJoin('t.SearchTestIndex i') - ->where('i.keyword = ?'); + ->from('SearchTest t') + ->innerJoin('t.SearchTestIndex i') + ->where('i.keyword = ?') + ; $array = $q->execute(array('was'), Doctrine_Core::HYDRATE_ARRAY); @@ -139,9 +153,10 @@ public function testQueryingReturnsEmptyArrayForUnknownKeyword() $q = new Doctrine_Query(); $q->select('t.title') - ->from('SearchTest t') - ->innerJoin('t.SearchTestIndex i') - ->where('i.keyword = ?'); + ->from('SearchTest t') + ->innerJoin('t.SearchTestIndex i') + ->where('i.keyword = ?') + ; $array = $q->execute(array('someunknownword'), Doctrine_Core::HYDRATE_ARRAY); @@ -158,13 +173,14 @@ public function testUpdateIndexInsertsNullValuesForBatchUpdatedEntries() $e->content = 'Some searchable content'; $e->save(); - + $coll = Doctrine_Query::create() - ->from('SearchTestIndex s') - ->orderby('s.id DESC') - ->limit(1) - ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) - ->fetchOne(); + ->from('SearchTestIndex s') + ->orderby('s.id DESC') + ->limit(1) + ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) + ->fetchOne() + ; $this->assertEqual($coll['id'], 3); $this->assertEqual($coll['keyword'], null); @@ -176,25 +192,24 @@ public function testBatchUpdatesUpdateAllPendingEntries() { $e = new SearchTest(); $e->batchUpdateIndex(); - + $coll = Doctrine_Query::create() - ->from('SearchTestIndex s') - ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) - ->execute(); + ->from('SearchTestIndex s') + ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) + ->execute() + ; $coll = $this->conn->fetchAll('SELECT * FROM search_test_index'); - - } public function testThrowExceptionIfInvalidTable() { - try { - $oQuery = new Doctrine_Search_Query(new Doctrine_Query()); - $this->fail('Should throw exception'); - } catch(Doctrine_Search_Exception $exception) { - $this->assertEqual($exception->getMessage(), 'Invalid argument type. Expected instance of Doctrine_Table.'); - } + try { + $oQuery = new Doctrine_Search_Query(new Doctrine_Query()); + $this->fail('Should throw exception'); + } catch (Doctrine_Search_Exception $exception) { + $this->assertEqual($exception->getMessage(), 'Invalid argument type. Expected instance of Doctrine_Table.'); + } } public function testGenerateSearchQueryForWeightedSearch() @@ -213,7 +228,7 @@ public function testStandardAnalyzerCanHandleAccentedCharactersGracefullyWorks() $this->assertEqual($words[2], 'ca'); $this->assertEqual($words[4], 'enormement'); } - + public function testUtf8AnalyzerWorks() { $analyzer = new Doctrine_Search_Analyzer_Utf8(array('encoding' => 'utf-8')); @@ -223,17 +238,17 @@ public function testUtf8AnalyzerWorks() $this->assertEqual($words[2], 'ça'); $this->assertEqual($words[4], 'énormément'); } - + public function testUtf8AnalyzerKnowsToHandleOtherEncodingsWorks() { $analyzer = new Doctrine_Search_Analyzer_Utf8(); // convert our test string to iso8859-15 - $iso = iconv('UTF-8','ISO8859-15', 'un éléphant ça trompe énormément'); + $iso = iconv('UTF-8', 'ISO8859-15', 'un éléphant ça trompe énormément'); $words = $analyzer->analyze($iso, 'ISO8859-15'); $this->assertEqual($words[1], 'éléphant'); $this->assertEqual($words[2], 'ça'); $this->assertEqual($words[4], 'énormément'); } -} \ No newline at end of file +} diff --git a/tests/Sequence/MssqlTestCase.php b/tests/Sequence/MssqlTestCase.php index a86abfaa6..a5214ce13 100644 --- a/tests/Sequence/MssqlTestCase.php +++ b/tests/Sequence/MssqlTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Sequence_Mssql_TestCase + * Doctrine_Sequence_Mssql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Sequence_Mssql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Sequence_Mssql_TestCase extends Doctrine_UnitTestCase { public function testCurrIdExecutesSql() { @@ -38,23 +44,25 @@ public function testCurrIdExecutesSql() $this->assertEqual($this->adapter->pop(), 'DELETE FROM user_seq WHERE id < 0'); - $this->assertEqual($this->adapter->pop(), 'SELECT @@IDENTITY'); + $this->assertEqual($this->adapter->pop(), 'SELECT @@IDENTITY'); $this->assertEqual($this->adapter->pop(), 'SELECT @@VERSION'); $this->assertEqual($this->adapter->pop(), 'SET IDENTITY_INSERT user_seq OFF INSERT INTO user_seq DEFAULT VALUES'); $this->assertEqual($this->adapter->pop(), 'SELECT COUNT(1) FROM user_seq'); } + public function testNextIdExecutesSql() { $id = $this->sequence->nextId('user'); $this->assertEqual($this->adapter->pop(), 'DELETE FROM user_seq WHERE id < 0'); - $this->assertEqual($this->adapter->pop(), 'SELECT @@IDENTITY'); - $this->assertEqual($this->adapter->pop(), 'SELECT @@VERSION'); + $this->assertEqual($this->adapter->pop(), 'SELECT @@IDENTITY'); + $this->assertEqual($this->adapter->pop(), 'SELECT @@VERSION'); $this->assertEqual($this->adapter->pop(), 'SET IDENTITY_INSERT user_seq OFF INSERT INTO user_seq DEFAULT VALUES'); $this->assertEqual($this->adapter->pop(), 'SELECT COUNT(1) FROM user_seq'); } - public function testLastInsertIdCallsPdoLevelEquivalent() + + public function testLastInsertIdCallsPdoLevelEquivalent() { $id = $this->sequence->lastInsertId('user'); diff --git a/tests/Sequence/MysqlTestCase.php b/tests/Sequence/MysqlTestCase.php index 6713c2c11..46f1e75d2 100644 --- a/tests/Sequence/MysqlTestCase.php +++ b/tests/Sequence/MysqlTestCase.php @@ -20,38 +20,46 @@ */ /** - * Doctrine_Sequence_Mysql_TestCase + * Doctrine_Sequence_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Sequence_Mysql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Sequence_Mysql_TestCase extends Doctrine_UnitTestCase { - public function testCurrIdExecutesSql() + public function testCurrIdExecutesSql() { $this->sequence->currId('user'); $this->assertEqual($this->adapter->pop(), 'SELECT MAX(id) FROM user'); } - public function testNextIdExecutesSql() + + public function testNextIdExecutesSql() { $id = $this->sequence->nextId('user'); - + $this->assertEqual($id, 1); $this->assertEqual($this->adapter->pop(), 'DELETE FROM user WHERE id < 1'); $this->assertEqual($this->adapter->pop(), 'LAST_INSERT_ID()'); $this->assertEqual($this->adapter->pop(), 'INSERT INTO user (id) VALUES (NULL)'); } - public function testLastInsertIdCallsPdoLevelEquivalent() + + public function testLastInsertIdCallsPdoLevelEquivalent() { $id = $this->sequence->lastInsertId('user'); - + $this->assertEqual($id, 1); $this->assertEqual($this->adapter->pop(), 'LAST_INSERT_ID()'); diff --git a/tests/Sequence/OracleTestCase.php b/tests/Sequence/OracleTestCase.php index c56233c16..d567dd2a3 100644 --- a/tests/Sequence/OracleTestCase.php +++ b/tests/Sequence/OracleTestCase.php @@ -20,36 +20,43 @@ */ /** - * Doctrine_Sequence_Oracle_TestCase + * Doctrine_Sequence_Oracle_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Sequence_Oracle_TestCase extends Doctrine_UnitTestCase +class Doctrine_Sequence_Oracle_TestCase extends Doctrine_UnitTestCase { - public function testCurrIdExecutesSql() - { + public function testCurrIdExecutesSql() + { $this->sequence->currId('user'); $q = "SELECT (last_number-1) FROM user_sequences WHERE sequence_name='user_seq' OR sequence_name='USER_SEQ'"; $this->assertEqual($this->adapter->pop(), $q); } - public function testNextIdExecutesSql() + + public function testNextIdExecutesSql() { $id = $this->sequence->nextId('user'); $this->assertEqual($this->adapter->pop(), 'SELECT user_seq.nextval FROM DUAL'); - } + public function testLastInsertIdExecutesSql() { $this->sequence->lastInsertId('user'); - + $this->assertEqual($this->adapter->pop(), 'SELECT user_seq.currval FROM DUAL'); } } diff --git a/tests/Sequence/PgsqlTestCase.php b/tests/Sequence/PgsqlTestCase.php index 57d854c2d..8c76b377b 100644 --- a/tests/Sequence/PgsqlTestCase.php +++ b/tests/Sequence/PgsqlTestCase.php @@ -20,36 +20,43 @@ */ /** - * Doctrine_Sequence_Pgsql_TestCase + * Doctrine_Sequence_Pgsql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Sequence_Pgsql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Sequence_Pgsql_TestCase extends Doctrine_UnitTestCase { - public function testCurrIdExecutesSql() - { + public function testCurrIdExecutesSql() + { $this->sequence->currId('user'); - $q = "SELECT last_value FROM user_seq"; + $q = 'SELECT last_value FROM user_seq'; $this->assertEqual($this->adapter->pop(), $q); } - public function testNextIdExecutesSql() + + public function testNextIdExecutesSql() { $id = $this->sequence->nextId('user'); $this->assertEqual($this->adapter->pop(), "SELECT NEXTVAL('user_seq')"); - } + public function testLastInsertIdExecutesSql() { $this->sequence->lastInsertId('user'); - + $this->assertEqual($this->adapter->pop(), "SELECT CURRVAL('user_seq')"); } } diff --git a/tests/Sequence/SqliteTestCase.php b/tests/Sequence/SqliteTestCase.php index 8f0c2b10c..8d69ca9eb 100644 --- a/tests/Sequence/SqliteTestCase.php +++ b/tests/Sequence/SqliteTestCase.php @@ -20,40 +20,48 @@ */ /** - * Doctrine_Sequence_Sqlite_TestCase + * Doctrine_Sequence_Sqlite_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Sequence_Sqlite_TestCase extends Doctrine_UnitTestCase +class Doctrine_Sequence_Sqlite_TestCase extends Doctrine_UnitTestCase { - public function testCurrIdExecutesSql() + public function testCurrIdExecutesSql() { - $this->adapter->forceLastInsertIdFail(false); + $this->adapter->forceLastInsertIdFail(false); $this->sequence->currId('user'); $this->assertEqual($this->adapter->pop(), 'SELECT MAX(id) FROM user_seq'); } - public function testNextIdExecutesSql() + + public function testNextIdExecutesSql() { $id = $this->sequence->nextId('user'); - + $this->assertEqual($id, 1); $this->assertEqual($this->adapter->pop(), 'DELETE FROM user_seq WHERE id < 1'); $this->assertEqual($this->adapter->pop(), 'LAST_INSERT_ID()'); $this->assertEqual($this->adapter->pop(), 'INSERT INTO user_seq (id) VALUES (NULL)'); } - public function testLastInsertIdCallsPdoLevelEquivalent() + + public function testLastInsertIdCallsPdoLevelEquivalent() { $id = $this->sequence->lastInsertId('user'); - + $this->assertEqual($id, 1); $this->assertEqual($this->adapter->pop(), 'LAST_INSERT_ID()'); diff --git a/tests/SequenceTestCase.php b/tests/SequenceTestCase.php index 314373cf6..3f837e9c2 100644 --- a/tests/SequenceTestCase.php +++ b/tests/SequenceTestCase.php @@ -20,48 +20,56 @@ */ /** - * Doctrine_Sequence_TestCase + * Doctrine_Sequence_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Sequence_TestCase extends Doctrine_UnitTestCase +class Doctrine_Sequence_TestCase extends Doctrine_UnitTestCase { - public function prepareData() + public function prepareData() { } - public function prepareTables() + + public function prepareTables() { } + public function testSequencesAreSupportedForRecords() { $this->adapter->forceLastInsertIdFail(); - $r = new CustomSequenceRecord; + $r = new CustomSequenceRecord(); $r->name = 'custom seq'; $r->save(); - - /** - // the last profiled event is transaction commit - $this->assertEqual($this->adapter->pop(), 'COMMIT'); - // query execution - - $this->assertEqual($this->adapter->pop(), 'INSERT INTO custom_sequence_record (name, id) VALUES (?, ?)'); - // query prepare - $this->assertEqual($this->adapter->pop(), 'INSERT INTO custom_sequence_record (name, id) VALUES (?, ?)'); - - // sequence generation (first fails) - $this->assertEqual($this->adapter->pop(), 'INSERT INTO custom_seq_seq (id) VALUES (1)'); - $this->assertEqual($this->adapter->pop(), 'CREATE TABLE custom_seq_seq (id INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)'); - $this->assertEqual($this->adapter->pop(), 'INSERT INTO custom_seq_seq (id) VALUES (NULL)'); - // transaction begin - $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); - $this->assertEqual($this->adapter->pop(), 'CREATE TABLE custom_sequence_record (id INTEGER, name VARCHAR(2147483647), PRIMARY KEY(id))'); - */ + /* + * // the last profiled event is transaction commit + * $this->assertEqual($this->adapter->pop(), 'COMMIT'); + * // query execution + * + * $this->assertEqual($this->adapter->pop(), 'INSERT INTO custom_sequence_record (name, id) VALUES (?, ?)'); + * // query prepare + * $this->assertEqual($this->adapter->pop(), 'INSERT INTO custom_sequence_record (name, id) VALUES (?, ?)'); + * + * // sequence generation (first fails) + * $this->assertEqual($this->adapter->pop(), 'INSERT INTO custom_seq_seq (id) VALUES (1)'); + * $this->assertEqual($this->adapter->pop(), 'CREATE TABLE custom_seq_seq (id INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)'); + * $this->assertEqual($this->adapter->pop(), 'INSERT INTO custom_seq_seq (id) VALUES (NULL)'); + * + * // transaction begin + * $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); + * $this->assertEqual($this->adapter->pop(), 'CREATE TABLE custom_sequence_record (id INTEGER, name VARCHAR(2147483647), PRIMARY KEY(id))'); + */ } } diff --git a/tests/SluggableTestCase.php b/tests/SluggableTestCase.php index 7d2ae39ad..ca41a726e 100644 --- a/tests/SluggableTestCase.php +++ b/tests/SluggableTestCase.php @@ -1,26 +1,32 @@ tables[] = "SluggableItem"; - $this->tables[] = "SluggableItem1"; - $this->tables[] = "SluggableItem2"; - $this->tables[] = "SluggableItem3"; - $this->tables[] = "SluggableItem4"; - $this->tables[] = "SluggableItem5"; - $this->tables[] = "SluggableItem6"; - $this->tables[] = "SluggableItem7"; - $this->tables[] = "SluggableItem8"; - $this->tables[] = "SluggableItem9"; - $this->tables[] = "SluggableItem10"; - $this->tables[] = "SluggableItem11"; - $this->tables[] = "SluggableItem12"; - $this->tables[] = "SluggableItem13"; - $this->tables[] = "SluggableItem14"; - $this->tables[] = "SluggableItem15"; - $this->tables[] = "SluggableItem16"; - $this->tables[] = "SluggableItem17"; + $this->tables[] = 'SluggableItem'; + $this->tables[] = 'SluggableItem1'; + $this->tables[] = 'SluggableItem2'; + $this->tables[] = 'SluggableItem3'; + $this->tables[] = 'SluggableItem4'; + $this->tables[] = 'SluggableItem5'; + $this->tables[] = 'SluggableItem6'; + $this->tables[] = 'SluggableItem7'; + $this->tables[] = 'SluggableItem8'; + $this->tables[] = 'SluggableItem9'; + $this->tables[] = 'SluggableItem10'; + $this->tables[] = 'SluggableItem11'; + $this->tables[] = 'SluggableItem12'; + $this->tables[] = 'SluggableItem13'; + $this->tables[] = 'SluggableItem14'; + $this->tables[] = 'SluggableItem15'; + $this->tables[] = 'SluggableItem16'; + $this->tables[] = 'SluggableItem17'; parent::prepareTables(); } @@ -31,7 +37,7 @@ public function testSluggableWithNoFieldsNoGetUniqueSlugMethod() $item->save(); $this->assertEqual($item->slug, 'result-of-to-string'); } - + public function testSSluggableWithNoFieldsOptionButGetUniqueSlugMethod() { $item = new SluggableItem1(); @@ -51,12 +57,12 @@ public function testSluggableWithFieldsOption() $item->name = 'My item'; $item->save(); $this->assertEqual($item->slug, 'my-item-1'); - $itemTable = Doctrine_Core::getTable('SluggableItem2'); + $itemTable = Doctrine_Core::getTable('SluggableItem2'); $this->assertTrue($index = $itemTable->getIndex('my_item2_sluggable')); $this->assertEqual($index['type'], 'unique'); $this->assertEqual($index['fields'], array('slug')); } - + public function testSluggableUniqueSlugOnUpdate() { parent::prepareTables(); @@ -72,7 +78,7 @@ public function testSluggableUniqueSlugOnUpdate() $item->save(); $this->assertEqual($item->slug, 'New slug'); } - + public function testSluggableWithMultipleFieldsOption() { parent::prepareTables(); @@ -87,7 +93,7 @@ public function testSluggableWithMultipleFieldsOption() $item->save(); $this->assertEqual($item->slug, 'my-item-my-ref-1'); } - + public function testSluggableWithFieldsAndNonUniqueOptions() { parent::prepareTables(); @@ -100,7 +106,7 @@ public function testSluggableWithFieldsAndNonUniqueOptions() $item->save(); $this->assertEqual($item->slug, 'my-item'); } - + public function testSluggableWithUniqueByOption() { parent::prepareTables(); @@ -119,12 +125,12 @@ public function testSluggableWithUniqueByOption() $item->user_id = 1; $item->save(); $this->assertEqual($item->slug, 'my-item-1'); - $itemTable = Doctrine_Core::getTable('SluggableItem5'); + $itemTable = Doctrine_Core::getTable('SluggableItem5'); $this->assertTrue($index = $itemTable->getIndex('my_item5_sluggable')); $this->assertEqual($index['type'], 'unique'); $this->assertEqual($index['fields'], array('slug', 'user_id')); } - + public function testSluggableWithUniqueByOptionAndNullValue() { parent::prepareTables(); @@ -142,7 +148,7 @@ public function testSluggableWithUniqueByOptionAndNullValue() $item->save(); $this->assertEqual($item->slug, 'my-item'); } - + public function testSluggableWithMultipleUniqueByOption() { parent::prepareTables(); @@ -165,15 +171,15 @@ public function testSluggableWithMultipleUniqueByOption() $item->save(); $this->assertEqual($item->slug, 'my-item-1'); } - + public function testSluggableWithFieldsOptionAndNoIndex() { parent::prepareTables(); - $itemTable = Doctrine_Core::getTable('SluggableItem7'); + $itemTable = Doctrine_Core::getTable('SluggableItem7'); $this->assertFalse($itemTable->getIndex('sluggable')); } - - public function testSluggableUniqueSlugOnUpdateWithOptioncanUpdateSlug () + + public function testSluggableUniqueSlugOnUpdateWithOptioncanUpdateSlug() { parent::prepareTables(); $item = new SluggableItem8(); @@ -209,7 +215,7 @@ public function testSluggableWithSoftDeleteFailWithSameSlug() $item0->delete(); // muhaha! I don't actually delete it! // We must have 0 as total of records - + $this->assertEqual(Doctrine_Query::create()->from('SluggableItem9')->count(), 0); $item1 = new SluggableItem9(); @@ -219,47 +225,47 @@ public function testSluggableWithSoftDeleteFailWithSameSlug() Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); } - + public function testSluggableWithColumAggregationInheritance() { - parent::prepareTables(); - $item = new SluggableItem11(); - $item->name = 'My item'; - $item->save(); - $item1 = new SluggableItem12(); - $item1->name = 'My item'; - $item1->save(); - // since this two items resides in the same table, they should not have the same slug - $this->assertNotEqual($item1->slug, $item->slug); + parent::prepareTables(); + $item = new SluggableItem11(); + $item->name = 'My item'; + $item->save(); + $item1 = new SluggableItem12(); + $item1->name = 'My item'; + $item1->save(); + // since this two items resides in the same table, they should not have the same slug + $this->assertNotEqual($item1->slug, $item->slug); } public function testSluggableWithColumAggregationInheritanceAndUniquByType() { - parent::prepareTables(); - $item = new SluggableItem16(); - $item->name = 'My item'; - $item->save(); - $item1 = new SluggableItem17(); - $item1->name = 'My item'; - $item1->save(); - $this->assertEqual($item1->slug, $item->slug); + parent::prepareTables(); + $item = new SluggableItem16(); + $item->name = 'My item'; + $item->save(); + $item1 = new SluggableItem17(); + $item1->name = 'My item'; + $item1->save(); + $this->assertEqual($item1->slug, $item->slug); } public function testSluggableWithConcreteInheritance() { - parent::prepareTables(); - $item = new SluggableItem13(); - $item->name = 'My item'; - $item->save(); - $item1 = new SluggableItem14(); - $item1->name = 'My item'; - $item1->save(); - // this two slugs is in different tables so they should be equal - $this->assertEqual($item->slug,$item1->slug); - $item2 = new SluggableItem14(); - $item2->name = 'My item'; - $item2->save(); - $this->assertNotEqual($item2->slug,$item1->slug); + parent::prepareTables(); + $item = new SluggableItem13(); + $item->name = 'My item'; + $item->save(); + $item1 = new SluggableItem14(); + $item1->name = 'My item'; + $item1->save(); + // this two slugs is in different tables so they should be equal + $this->assertEqual($item->slug, $item1->slug); + $item2 = new SluggableItem14(); + $item2->name = 'My item'; + $item2->save(); + $this->assertNotEqual($item2->slug, $item1->slug); } } @@ -320,10 +326,10 @@ public function setTableDefinition() } public function setUp() - { + { parent::setUp(); $this->actAs('Sluggable', array('unique' => true, - 'fields' => array('name'))); + 'fields' => array('name'))); } } @@ -337,17 +343,16 @@ public function setTableDefinition() } public function setUp() - { + { parent::setUp(); $this->actAs('Sluggable', array('unique' => false, - 'fields' => array('name'))); + 'fields' => array('name'))); } } // Model with multiple fields option class SluggableItem4 extends Doctrine_Record { - public function setTableDefinition() { $this->setTableName('my_item4'); @@ -356,10 +361,10 @@ public function setTableDefinition() } public function setUp() - { + { parent::setUp(); $this->actAs('Sluggable', array('unique' => true, - 'fields' => array('name', 'ref'))); + 'fields' => array('name', 'ref'))); } } @@ -374,11 +379,11 @@ public function setTableDefinition() } public function setUp() - { + { parent::setUp(); - $this->actAs('Sluggable', array('fields' => array('name'), - 'uniqueBy' => array('user_id'), - 'unique' => true + $this->actAs('Sluggable', array('fields' => array('name'), + 'uniqueBy' => array('user_id'), + 'unique' => true, )); } } @@ -386,7 +391,6 @@ public function setUp() // Model with fields and multiple uniqueBy option class SluggableItem6 extends Doctrine_Record { - public function setTableDefinition() { $this->setTableName('my_item6'); @@ -398,11 +402,11 @@ public function setTableDefinition() } public function setUp() - { + { parent::setUp(); - $this->actAs('Sluggable', array('fields' => array('name'), - 'uniqueBy' => array('user_id', 'account_id'), - 'unique' => true + $this->actAs('Sluggable', array('fields' => array('name'), + 'uniqueBy' => array('user_id', 'account_id'), + 'unique' => true, )); } } @@ -410,7 +414,6 @@ public function setUp() // Model with fields option and no index class SluggableItem7 extends Doctrine_Record { - public function setTableDefinition() { $this->setTableName('my_item2'); @@ -418,18 +421,17 @@ public function setTableDefinition() } public function setUp() - { + { parent::setUp(); - $this->actAs('Sluggable', array('fields' => array('name'), - 'uniqueIndex' => false, - 'unique' => true)); + $this->actAs('Sluggable', array('fields' => array('name'), + 'uniqueIndex' => false, + 'unique' => true)); } } // Model with fields option and canUpdateSlug option class SluggableItem8 extends Doctrine_Record { - public function setTableDefinition() { $this->setTableName('my_item8'); @@ -437,18 +439,17 @@ public function setTableDefinition() } public function setUp() - { + { parent::setUp(); - $this->actAs('Sluggable', array('unique' => true, - 'fields' => array('name'), - 'canUpdate' => true)); + $this->actAs('Sluggable', array('unique' => true, + 'fields' => array('name'), + 'canUpdate' => true)); } } // Model usage with mixing of SoftDelete class SluggableItem9 extends Doctrine_Record { - public function setTableDefinition() { $this->setTableName('my_item9'); @@ -456,13 +457,13 @@ public function setTableDefinition() } public function setUp() - { + { parent::setUp(); $this->actAs('SoftDelete'); - $this->actAs('Sluggable', array('unique' => true, - 'uniqueIndex' => true, - 'fields' => array('name'))); + $this->actAs('Sluggable', array('unique' => true, + 'uniqueIndex' => true, + 'fields' => array('name'))); } } @@ -470,101 +471,103 @@ public function setUp() // That inherits form an abstract class abstract class SluggableItem10Abstract extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('my_item10'); - $this->hasColumn('name', 'string', 50); - $this->hasColumn('type', 'integer',1); - $this->setSubclasses(array("SluggableItem11" => array("type" => 0), "SluggableItem12" => array("type" => 1))); - } - public function setUp() - { - parent::setUp(); - - $this->actAs('Sluggable', array('unique' => true, - 'uniqueIndex' => true, - 'fields' => array('name'), - )); - } + public function setTableDefinition() + { + $this->setTableName('my_item10'); + $this->hasColumn('name', 'string', 50); + $this->hasColumn('type', 'integer', 1); + $this->setSubclasses(array('SluggableItem11' => array('type' => 0), 'SluggableItem12' => array('type' => 1))); + } + + public function setUp() + { + parent::setUp(); + + $this->actAs('Sluggable', array('unique' => true, + 'uniqueIndex' => true, + 'fields' => array('name'), + )); + } } class SluggableItem10 extends SluggableItem10Abstract -{} +{ +} // Two classes that extends SluggableItem10 using column aggregation class SluggableItem11 extends SluggableItem10 { - public function setUp() - { - parent::setUp(); - } + public function setUp() + { + parent::setUp(); + } } class SluggableItem12 extends SluggableItem10 { - public function setUp() - { - parent::setUp(); - } + public function setUp() + { + parent::setUp(); + } } // Two classes extending SluggableItem2 using concrete inheritance class SluggableItem13 extends SluggableItem2 { - public function setTableDefinition() - { - parent::setTableDefinition(); - $this->setTableName('my_item13'); - $this->hasColumn('content', 'string', 300); - } + public function setTableDefinition() + { + parent::setTableDefinition(); + $this->setTableName('my_item13'); + $this->hasColumn('content', 'string', 300); + } } class SluggableItem14 extends SluggableItem2 { - public function setTableDefinition() - { - parent::setTableDefinition(); - $this->setTableName('my_item14'); - $this->hasColumn('content', 'string', 300); - } + public function setTableDefinition() + { + parent::setTableDefinition(); + $this->setTableName('my_item14'); + $this->hasColumn('content', 'string', 300); + } } // A fiew models using column aggerigation inheritance and uniqueBy type class SluggableItem15 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('my_item15'); - $this->hasColumn('name', 'string', 50); - $this->hasColumn('type', 'integer',1); - $this->setSubclasses(array("SluggableItem16" => array("type" => 0), "SluggableItem17" => array("type" => 1))); - } - - public function setUp() - { - parent::setUp(); - - $this->actAs('Sluggable', array('unique' => true, - 'uniqueIndex' => true, - 'uniqueBy' => array('type'), - 'fields' => array('name'), - )); - } + public function setTableDefinition() + { + $this->setTableName('my_item15'); + $this->hasColumn('name', 'string', 50); + $this->hasColumn('type', 'integer', 1); + $this->setSubclasses(array('SluggableItem16' => array('type' => 0), 'SluggableItem17' => array('type' => 1))); + } + + public function setUp() + { + parent::setUp(); + + $this->actAs('Sluggable', array('unique' => true, + 'uniqueIndex' => true, + 'uniqueBy' => array('type'), + 'fields' => array('name'), + )); + } } // Two classes that extends SluggableItem15 using column aggregation class SluggableItem16 extends SluggableItem15 { - public function setUp() - { - parent::setUp(); - } + public function setUp() + { + parent::setUp(); + } } class SluggableItem17 extends SluggableItem15 { - public function setUp() - { - parent::setUp(); - } -} \ No newline at end of file + public function setUp() + { + parent::setUp(); + } +} diff --git a/tests/SoftDeleteBCTestCase.php b/tests/SoftDeleteBCTestCase.php index 830c40de2..eadf42d6c 100644 --- a/tests/SoftDeleteBCTestCase.php +++ b/tests/SoftDeleteBCTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_SoftDeleteBC_TestCase + * Doctrine_SoftDeleteBC_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_SoftDeleteBC_TestCase extends Doctrine_UnitTestCase +class Doctrine_SoftDeleteBC_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -41,7 +47,7 @@ public function prepareTables() public function testDoctrineRecordDeleteSetsFlag() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); - + $test = new SoftDeleteBCTest(); $test->name = 'test'; $test->something = 'test'; @@ -50,17 +56,17 @@ public function testDoctrineRecordDeleteSetsFlag() $this->assertTrue($test->deleted); $test->free(); - Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); } public function testDoctrineQueryIsFilteredWithDeleteFlagCondition() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); - + $q = Doctrine_Query::create() - ->from('SoftDeleteBCTest s') - ->where('s.name = ?', array('test')); + ->from('SoftDeleteBCTest s') + ->where('s.name = ?', array('test')) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT s.name AS s__name, s.something AS s__something, s.deleted AS s__deleted FROM soft_delete_bc_test s WHERE (s.name = ? AND (s.deleted = 0))'); $params = $q->getFlattenedParams(); @@ -69,29 +75,30 @@ public function testDoctrineQueryIsFilteredWithDeleteFlagCondition() $test = $q->fetchOne(); $this->assertFalse($test); - + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); } public function testTicket1132() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); - + $test = new SoftDeleteBCTest(); $test->name = 'test1'; $test->something = 'test2'; $test->save(); $q = Doctrine_Query::create() - ->from('SoftDeleteBCTest s') - ->addWhere('s.name = ?') - ->addWhere('s.something = ?'); + ->from('SoftDeleteBCTest s') + ->addWhere('s.name = ?') + ->addWhere('s.something = ?') + ; $results = $q->execute(array('test1', 'test2')); $this->assertEqual($q->getSqlQuery(), 'SELECT s.name AS s__name, s.something AS s__something, s.deleted AS s__deleted FROM soft_delete_bc_test s WHERE (s.name = ? AND s.something = ? AND (s.deleted = 0))'); $this->assertEqual($q->getFlattenedParams(array('test1', 'test2')), array('test1', 'test2')); $this->assertEqual($results->count(), 1); - + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); } @@ -99,20 +106,22 @@ public function testTicket1132() public function testTicket1170() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); - + Doctrine_Query::create() ->delete() ->from('SoftDeleteBCTest s') - ->execute(); + ->execute() + ; $q = Doctrine_Query::create() - ->from('SoftDeleteBCTest s') - ->addWhere('s.name = ?', 'test1') - ->addWhere('s.something = ?', 'test2'); + ->from('SoftDeleteBCTest s') + ->addWhere('s.name = ?', 'test1') + ->addWhere('s.something = ?', 'test2') + ; $this->assertEqual($q->getCountSqlQuery(), 'SELECT COUNT(*) AS num_results FROM soft_delete_bc_test s WHERE s.name = ? AND s.something = ? AND (s.deleted = 0)'); $this->assertEqual($q->count(), 0); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); } -} \ No newline at end of file +} diff --git a/tests/SoftDeleteTestCase.php b/tests/SoftDeleteTestCase.php index 1bae56e9a..b2b7212cb 100644 --- a/tests/SoftDeleteTestCase.php +++ b/tests/SoftDeleteTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_SoftDelete_TestCase + * Doctrine_SoftDelete_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_SoftDelete_TestCase extends Doctrine_UnitTestCase +class Doctrine_SoftDelete_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -55,8 +61,9 @@ public function testDoctrineQueryIsFilteredWithDeleteFlagCondition() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); $q = Doctrine_Query::create() - ->from('SoftDeleteTest s') - ->where('s.name = ?', array('test')); + ->from('SoftDeleteTest s') + ->where('s.name = ?', array('test')) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT s.name AS s__name, s.something AS s__something, s.deleted_at AS s__deleted_at FROM soft_delete_test s WHERE (s.name = ? AND (s.deleted_at IS NULL))'); $params = $q->getFlattenedParams(); @@ -77,9 +84,10 @@ public function testTicket1132() $test->save(); $q = Doctrine_Query::create() - ->from('SoftDeleteTest s') - ->addWhere('s.name = ?') - ->addWhere('s.something = ?'); + ->from('SoftDeleteTest s') + ->addWhere('s.name = ?') + ->addWhere('s.something = ?') + ; $results = $q->execute(array('test1', 'test2')); $this->assertEqual($q->getSqlQuery(), 'SELECT s.name AS s__name, s.something AS s__something, s.deleted_at AS s__deleted_at FROM soft_delete_test s WHERE (s.name = ? AND s.something = ? AND (s.deleted_at IS NULL))'); @@ -96,16 +104,18 @@ public function testTicket1170() Doctrine_Query::create() ->delete() ->from('SoftDeleteTest s') - ->execute(); + ->execute() + ; $q = Doctrine_Query::create() - ->from('SoftDeleteTest s') - ->addWhere('s.name = ?', 'test1') - ->addWhere('s.something = ?', 'test2'); + ->from('SoftDeleteTest s') + ->addWhere('s.name = ?', 'test1') + ->addWhere('s.something = ?', 'test2') + ; $this->assertEqual($q->getCountSqlQuery(), 'SELECT COUNT(*) AS num_results FROM soft_delete_test s WHERE s.name = ? AND s.something = ? AND (s.deleted_at IS NULL)'); $this->assertEqual($q->count(), 0); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); } -} \ No newline at end of file +} diff --git a/tests/Table/NamedQueryTestCase.php b/tests/Table/NamedQueryTestCase.php index 82d105e4f..4f73c412b 100644 --- a/tests/Table/NamedQueryTestCase.php +++ b/tests/Table/NamedQueryTestCase.php @@ -20,26 +20,31 @@ */ /** - * Doctrine_Query_Registry + * Doctrine_Query_Registry. * - * @package Doctrine - * @subpackage Query * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Table_NamedQuery_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables = array('MyFoo'); - + parent::prepareTables(); } - public function prepareData() { + public function prepareData() + { $f1 = new MyFoo(); $f1->name = 'jwage'; $f1->value0 = 0; @@ -55,8 +60,7 @@ public function prepareData() { $f3->value0 = 2; $f3->save(); } - - + public function testNamedQuerySupport() { $table = Doctrine_Core::getTable('MyFoo'); @@ -65,21 +69,20 @@ public function testNamedQuerySupport() $table->createNamedQuery('get.by.id')->getSqlQuery(), 'SELECT m.id AS m__id, m.name AS m__name, m.value0 AS m__value0 FROM my_foo m WHERE (m.id = ?)' ); - + $this->assertEqual( $table->createNamedQuery('get.by.similar.names')->getSqlQuery(), 'SELECT m.id AS m__id, m.value0 AS m__value0 FROM my_foo m WHERE (LOWER(m.name) LIKE LOWER(?))' ); - + $this->assertEqual($table->createNamedQuery('get.by.similar.names')->count(array('%jon%wage%')), 2); - + $items = $table->find('get.by.similar.names', array('%jon%wage%')); - + $this->assertEqual(count($items), 2); } } - class MyFoo extends Doctrine_Record { public function setTableDefinition() @@ -89,7 +92,6 @@ public function setTableDefinition() } } - class MyFooTable extends Doctrine_Table { public function construct() @@ -102,4 +104,4 @@ public function construct() ->where('LOWER(f.name) LIKE LOWER(?)') ); } -} \ No newline at end of file +} diff --git a/tests/Table/RemoveColumnTestCase.php b/tests/Table/RemoveColumnTestCase.php index ef0c3948a..3f9db6d61 100644 --- a/tests/Table/RemoveColumnTestCase.php +++ b/tests/Table/RemoveColumnTestCase.php @@ -20,19 +20,24 @@ */ /** - * Doctrine_TableRemoveColumn_TestCase + * Doctrine_TableRemoveColumn_TestCase. * - * @package Doctrine * @author Dennis Verspuij * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Table_RemoveColumn_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { $this->tables[] = 'RemoveColumnTest'; @@ -47,14 +52,14 @@ protected function _verifyNrColumnsAndFields($table, $nrExpected) $this->assertEqual($nrColumns, count($table->getColumns())); $this->assertEqual($nrColumns, count($table->getFieldNames())); - foreach($table->getFieldNames() as $field) { + foreach ($table->getFieldNames() as $field) { $this->assertTrue($table->hasField($field)); } // the following are trivial because both getColumnNames and // hasColumn use Table::_columns instead of Table::_fieldNames $this->assertEqual($nrColumns, count($table->getColumnNames())); - foreach($table->getColumnNames() as $column) { + foreach ($table->getColumnNames() as $column) { $this->assertTrue($table->hasColumn($column)); } } @@ -74,13 +79,18 @@ public function testAfterRemoveColumn() } } +/** + * @internal + * + * @coversNothing + */ class RemoveColumnTest extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('AA', 'integer', null, array('primary' => true)); $this->hasColumn('bb', 'integer'); - $this->hasColumn('CC', 'string',10); - $this->hasColumn('dd', 'string',10); + $this->hasColumn('CC', 'string', 10); + $this->hasColumn('dd', 'string', 10); } -} \ No newline at end of file +} diff --git a/tests/TableTestCase.php b/tests/TableTestCase.php index 3de7b5ce9..32d471a48 100644 --- a/tests/TableTestCase.php +++ b/tests/TableTestCase.php @@ -20,19 +20,24 @@ */ /** - * Doctrine_Table_TestCase + * Doctrine_Table_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Table_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { $this->tables[] = 'FieldNameTest'; @@ -67,7 +72,7 @@ public function testFieldConversion() $t->someEnum = 'php'; $t->someInt = 1; $t->someArray = array(); - $obj = new StdClass(); + $obj = new stdClass(); $t->someObject = $obj; $this->assertEqual($t->someColumn, 'abc'); @@ -107,38 +112,36 @@ public function testFieldConversion() public function testGetForeignKey() { - $fk = $this->objTable->getRelation("Group"); + $fk = $this->objTable->getRelation('Group'); $this->assertTrue($fk instanceof Doctrine_Relation_Association); $this->assertTrue($fk->getTable() instanceof Doctrine_Table); - $this->assertTrue($fk->getType() == Doctrine_Relation::MANY); - $this->assertTrue($fk->getLocal() == "user_id"); - $this->assertTrue($fk->getForeign() == "group_id"); + $this->assertTrue(Doctrine_Relation::MANY == $fk->getType()); + $this->assertTrue('user_id' == $fk->getLocal()); + $this->assertTrue('group_id' == $fk->getForeign()); - $fk = $this->objTable->getRelation("Email"); + $fk = $this->objTable->getRelation('Email'); $this->assertTrue($fk instanceof Doctrine_Relation_LocalKey); $this->assertTrue($fk->getTable() instanceof Doctrine_Table); - $this->assertTrue($fk->getType() == Doctrine_Relation::ONE); - $this->assertTrue($fk->getLocal() == "email_id"); + $this->assertTrue(Doctrine_Relation::ONE == $fk->getType()); + $this->assertTrue('email_id' == $fk->getLocal()); $this->assertTrue($fk->getForeign() == $fk->getTable()->getIdentifier()); - $fk = $this->objTable->getRelation('Phonenumber'); $this->assertTrue($fk instanceof Doctrine_Relation_ForeignKey); $this->assertTrue($fk->getTable() instanceof Doctrine_Table); - $this->assertTrue($fk->getType() == Doctrine_Relation::MANY); + $this->assertTrue(Doctrine_Relation::MANY == $fk->getType()); $this->assertTrue($fk->getLocal() == $this->objTable->getIdentifier()); - $this->assertTrue($fk->getForeign() == 'entity_id'); - - + $this->assertTrue('entity_id' == $fk->getForeign()); } + public function testGetComponentName() { - $this->assertTrue($this->objTable->getComponentName() == 'User'); + $this->assertTrue('User' == $this->objTable->getComponentName()); } public function testGetTableName() { - $this->assertTrue($this->objTable->tableName == 'entity'); + $this->assertTrue('entity' == $this->objTable->tableName); } public function testGetConnection() @@ -148,7 +151,7 @@ public function testGetConnection() public function testGetData() { - $this->assertTrue($this->objTable->getData() == array()); + $this->assertTrue(array() == $this->objTable->getData()); } public function testSetSequenceName() @@ -162,7 +165,7 @@ public function testCreate() { $record = $this->objTable->create(); $this->assertTrue($record instanceof Doctrine_Record); - $this->assertTrue($record->state() == Doctrine_Record::STATE_TCLEAN); + $this->assertTrue(Doctrine_Record::STATE_TCLEAN == $record->state()); } public function testFind() @@ -173,39 +176,39 @@ public function testFind() try { $record = $this->objTable->find('4'); $this->assertTrue($record instanceof Doctrine_Record); - } catch(Exception $e) { + } catch (Exception $e) { $this->assertTrue(false); } try { $record = $this->objTable->find('4', Doctrine_Core::HYDRATE_ARRAY); $this->assertTrue(is_array($record)); - $this->assertTrue( ! is_object($record)); + $this->assertTrue(!is_object($record)); $this->assertTrue(array_key_exists('id', $record)); $this->assertTrue(array_key_exists('name', $record)); - $this->assertTrue( ! $record instanceof Doctrine_Record); - } catch(Exception $e) { + $this->assertTrue(!$record instanceof Doctrine_Record); + } catch (Exception $e) { $this->assertTrue(false); } try { $record = $this->objTable->find(123); - $this->assertTrue($record === false); - } catch(Exception $e) { + $this->assertTrue(false === $record); + } catch (Exception $e) { $this->assertTrue(false); } try { $record = $this->objTable->find(null); - $this->assertTrue($record === false); - } catch(Exception $e) { + $this->assertTrue(false === $record); + } catch (Exception $e) { $this->assertTrue(false); } try { $record = $this->objTable->find(false); - $this->assertTrue($record === false); - } catch(Exception $e) { + $this->assertTrue(false === $record); + } catch (Exception $e) { $this->assertTrue(false); } } @@ -217,9 +220,9 @@ public function testFindAll() $this->assertTrue($users instanceof Doctrine_Collection); $users = $this->objTable->findAll(Doctrine_Core::HYDRATE_ARRAY); - $this->assertTrue( ! $users instanceof Doctrine_Collection); + $this->assertTrue(!$users instanceof Doctrine_Collection); $this->assertTrue(is_array($users)); - $this->assertTrue( ! is_object($users)); + $this->assertTrue(!is_object($users)); $this->assertEqual(count($users), 8); } @@ -244,8 +247,8 @@ public function testGetProxy() try { $record = $this->objTable->find(123); - } catch(Exception $e) { - $this->assertTrue($e instanceOf Doctrine_Find_Exception); + } catch (Exception $e) { + $this->assertTrue($e instanceof Doctrine_Find_Exception); } } @@ -253,11 +256,10 @@ public function testGetColumns() { $columns = $this->objTable->getColumns(); $this->assertTrue(is_array($columns)); - } public function testApplyInheritance() { - $this->assertEqual($this->objTable->applyInheritance("id = 3"), "id = 3 AND type = ?"); + $this->assertEqual($this->objTable->applyInheritance('id = 3'), 'id = 3 AND type = ?'); } } diff --git a/tests/TaskTestCase.php b/tests/TaskTestCase.php index 7dd644734..64a90f2d6 100644 --- a/tests/TaskTestCase.php +++ b/tests/TaskTestCase.php @@ -20,24 +20,34 @@ */ /** - * Doctrine_Task_TestCase - * + * Doctrine_Task_TestCase. + * * N.B. Invalid task classes are loaded just-in-time to avoid clashes with the CLI tests. Other test-specific * subclasses are declared at the bottom of this file. * - * @package Doctrine * @author Dan Bettles * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Task_TestCase extends Doctrine_UnitTestCase +class Doctrine_Task_TestCase extends Doctrine_UnitTestCase { - public function setUp() {} + public function setUp() + { + } - public function tearDown() {} + public function tearDown() + { + } public function testDerivetasknameReturnsTheNameOfATaskFromItsClassName() { @@ -48,22 +58,22 @@ public function testDerivetasknameReturnsTheNameOfATaskFromItsClassName() /* * PHP 5.3-specific tests - * + * * One would hope that authors of custom tasks would name their tasks manually, but since we can't guarantee * anything, we'll have to _try_ to create a sensible name */ $this->assertEqual('fully-qualified-custom-task', Doctrine_Task::deriveTaskName('fully\qualified\CustomTask')); - //$this->assertEqual('fully-qualified-custom-task', Doctrine_Task::deriveTaskName('fully\qualified\Doctrine_Task_CustomTask')); + // $this->assertEqual('fully-qualified-custom-task', Doctrine_Task::deriveTaskName('fully\qualified\Doctrine_Task_CustomTask')); } public function testNameByDefaultIsDerivedFromTheNameOfTheClass() { $oTask = new Doctrine_Task_TestCase_TestTask001(); - $this->assertEqual('test-case--test-task001', $oTask->taskName); /*@todo Temporary, maybe*/ + $this->assertEqual('test-case--test-task001', $oTask->taskName); /* @todo Temporary, maybe */ $this->assertEqual('test-case--test-task001', $oTask->getTaskName()); } - public function testNameByDefaultIsDerivedFromTheNameOfTheClass_withEmptyTaskNamePropertySetsByChildClass() + public function testNameByDefaultIsDerivedFromTheNameOfTheClassWithEmptyTaskNamePropertySetsByChildClass() { $task = new Doctrine_Task_TestCase_EmptyTaskNameTestTask(); @@ -84,14 +94,15 @@ public function testSettasknameSetsTheNameOfTheTask() } /** - * Loads a PHP fixture from the directory for this test case - * + * Loads a PHP fixture from the directory for this test case. + * * @ignore + * * @param string $basename */ protected function loadPhpFixture($basename) { - require_once(dirname(__FILE__) . '/TaskTestCase/' . $basename); + require_once dirname(__FILE__).'/TaskTestCase/'.$basename; } public function testSettasknameThrowsAnExceptionIfTheTaskNameIsInvalid() @@ -101,8 +112,9 @@ public function testSettasknameThrowsAnExceptionIfTheTaskNameIsInvalid() try { new Doctrine_Task_TestCase_TestTask006(); } catch (InvalidArgumentException $e) { - if ($e->getMessage() == 'The task name "invalid_task_name", in Doctrine_Task_TestCase_TestTask006, is invalid') { + if ('The task name "invalid_task_name", in Doctrine_Task_TestCase_TestTask006, is invalid' == $e->getMessage()) { $this->pass(); + return; } } @@ -110,7 +122,7 @@ public function testSettasknameThrowsAnExceptionIfTheTaskNameIsInvalid() $this->fail(); } - //This gives us a way to set an alternate task name that's in keeping with how we currently set-up tasks + // This gives us a way to set an alternate task name that's in keeping with how we currently set-up tasks public function testDoesNotAutomaticallySetTheNameOfTheTaskIfItWasSetManually() { $oTask = new Doctrine_Task_TestCase_TestTask003(); @@ -134,15 +146,14 @@ public function testThrowsAnExceptionIfTheTaskNameIsInvalid() new $classWithInvalidTaskName(); } catch (InvalidArgumentException $e) { if ($e->getMessage() == "The task name \"{$invalidTaskName}\", in {$classWithInvalidTaskName}, is invalid") { - $numPasses++; + ++$numPasses; } } } if ($numPasses == count($aClassWithInvalidTaskName)) { $this->pass(); - } - else { + } else { $this->fail(); } } @@ -150,7 +161,9 @@ public function testThrowsAnExceptionIfTheTaskNameIsInvalid() class Doctrine_Task_TestCase_TestTask001 extends Doctrine_Task { - public function execute() {} + public function execute() + { + } } class Doctrine_Task_TestCase_TestTask002 extends Doctrine_Task @@ -160,26 +173,34 @@ public function __construct() $this->setTaskName('better-task-name'); } - public function execute() {} + public function execute() + { + } } class Doctrine_Task_TestCase_TestTask003 extends Doctrine_Task { public $taskName = 'better-task-name'; - public function execute() {} + public function execute() + { + } } class Doctrine_Task_TestCase_EmptyTaskNameTestTask extends Doctrine_Task { public $taskName = ''; - public function execute() {} + public function execute() + { + } } class Doctrine_Task_TestCase_OverwrittenGetTaskNameMethodTestTask extends Doctrine_Task { - public function execute() {} + public function execute() + { + } public function getTaskName() { diff --git a/tests/TaskTestCase/TestTask004.php b/tests/TaskTestCase/TestTask004.php index f6a2282b0..1dd5d3e1b 100644 --- a/tests/TaskTestCase/TestTask004.php +++ b/tests/TaskTestCase/TestTask004.php @@ -1,13 +1,14 @@ */ - class Doctrine_Task_TestCase_TestTask004 extends Doctrine_Task { public $taskName = '-invalid-task-name'; - public function execute() {} -} \ No newline at end of file + public function execute() + { + } +} diff --git a/tests/TaskTestCase/TestTask005.php b/tests/TaskTestCase/TestTask005.php index a90581965..ce128976b 100644 --- a/tests/TaskTestCase/TestTask005.php +++ b/tests/TaskTestCase/TestTask005.php @@ -1,13 +1,14 @@ */ - class Doctrine_Task_TestCase_TestTask005 extends Doctrine_Task { public $taskName = 'another invalid task name'; - public function execute() {} -} \ No newline at end of file + public function execute() + { + } +} diff --git a/tests/TaskTestCase/TestTask006.php b/tests/TaskTestCase/TestTask006.php index 4ff1b0b37..919f88fe8 100644 --- a/tests/TaskTestCase/TestTask006.php +++ b/tests/TaskTestCase/TestTask006.php @@ -1,10 +1,9 @@ */ - class Doctrine_Task_TestCase_TestTask006 extends Doctrine_Task { public function __construct() @@ -12,5 +11,7 @@ public function __construct() $this->setTaskName('invalid_task_name'); } - public function execute() {} -} \ No newline at end of file + public function execute() + { + } +} diff --git a/tests/TemplateTestCase.php b/tests/TemplateTestCase.php index 78689b89a..c07145111 100644 --- a/tests/TemplateTestCase.php +++ b/tests/TemplateTestCase.php @@ -20,22 +20,31 @@ */ /** - * Doctrine_Template_TestCase + * Doctrine_Template_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Template_TestCase extends Doctrine_UnitTestCase +class Doctrine_Template_TestCase extends Doctrine_UnitTestCase { public function prepareTables() - { } - public function prepareData() - { } + { + } + + public function prepareData() + { + } public function testAccessingNonExistingImplementationThrowsException() { @@ -47,13 +56,14 @@ public function testAccessingNonExistingImplementationThrowsException() $this->pass(); } } - + public function testAccessingExistingImplementationSupportsAssociations() { $this->manager->setImpl('UserTemplate', 'ConcreteUser') - ->setImpl('GroupUserTemplate', 'ConcreteGroupUser') - ->setImpl('GroupTemplate', 'ConcreteGroup') - ->setImpl('EmailTemplate', 'ConcreteEmail'); + ->setImpl('GroupUserTemplate', 'ConcreteGroupUser') + ->setImpl('GroupTemplate', 'ConcreteGroup') + ->setImpl('EmailTemplate', 'ConcreteEmail') + ; $user = new ConcreteUser(); $group = $user->Group[0]; @@ -62,9 +72,9 @@ public function testAccessingExistingImplementationSupportsAssociations() $this->assertTrue($group->User[0] instanceof ConcreteUser); } + public function testAccessingExistingImplementationSupportsForeignKeyRelations() { - $user = new ConcreteUser(); $this->assertTrue($user->Email[0] instanceof ConcreteEmail); @@ -73,9 +83,8 @@ public function testAccessingExistingImplementationSupportsForeignKeyRelations() public function testShouldCallMethodInTemplate() { $user = new ConcreteUser(); - $this->assertEqual("foo", $user->foo()); + $this->assertEqual('foo', $user->foo()); } - } // move these to ../templates? @@ -86,18 +95,19 @@ public function setTableDefinition() $this->hasColumn('name', 'string'); $this->hasColumn('password', 'string'); } + public function setUp() { $this->hasMany('GroupTemplate as Group', array('local' => 'user_id', - 'foreign' => 'group_id', - 'refClass' => 'GroupUserTemplate')); + 'foreign' => 'group_id', + 'refClass' => 'GroupUserTemplate')); $this->hasMany('EmailTemplate as Email', array('local' => 'id', - 'foreign' => 'user_id')); + 'foreign' => 'user_id')); } - + public function foo() { - return "foo"; + return 'foo'; } } class EmailTemplate extends Doctrine_Template @@ -107,10 +117,11 @@ public function setTableDefinition() $this->hasColumn('address', 'string'); $this->hasColumn('user_id', 'integer'); } + public function setUp() { $this->hasOne('UserTemplate as User', array('local' => 'user_id', - 'foreign' => 'id')); + 'foreign' => 'id')); } } class GroupTemplate extends Doctrine_Template @@ -119,11 +130,12 @@ public function setTableDefinition() { $this->hasColumn('name', 'string'); } + public function setUp() { $this->hasMany('UserTemplate as User', array('local' => 'user_id', - 'foreign' => 'group_id', - 'refClass' => 'GroupUserTemplate')); + 'foreign' => 'group_id', + 'refClass' => 'GroupUserTemplate')); } } class GroupUserTemplate extends Doctrine_Template diff --git a/tests/Ticket/1015TestCase.php b/tests/Ticket/1015TestCase.php index 52830698c..34531f3c4 100644 --- a/tests/Ticket/1015TestCase.php +++ b/tests/Ticket/1015TestCase.php @@ -20,18 +20,25 @@ */ /** - * Doctrine_Ticket_1015_TestCase + * Doctrine_Ticket_1015_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1015_TestCase extends Doctrine_UnitTestCase { - - public function prepareTables() { +class Doctrine_Ticket_1015_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { $this->tables = array(); $this->tables[] = 'T1015_Person'; $this->tables[] = 'T1015_Points'; @@ -42,39 +49,38 @@ public function prepareTables() { public function prepareData() { $person = new T1015_Person(); - $person['name'] = "James"; + $person['name'] = 'James'; $person['T1015_Points']['total'] = 15; $person->save(); } - public function testDoctrineQueryJoinSelect() { - $q = new Doctrine_Query(); $q->select('person.id, points.total') - ->from('T1015_Person person') - ->innerJoin('person.T1015_Points points WITH person.id = 1'); + ->from('T1015_Person person') + ->innerJoin('person.T1015_Points points WITH person.id = 1') + ; $results = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - //var_dump($results); + // var_dump($results); $person = $results[0]; // number of points for person id of 1 should be 15 - $this->assertEqual(15, $person['T1015_Points']['total']); //THIS WILL FAIL - + $this->assertEqual(15, $person['T1015_Points']['total']); // THIS WILL FAIL } public function testDoctrineRawSQLJoinSelect() { $q = new Doctrine_RawSql(); $q->select('{person.id}, {points.total}') - ->from('person person INNER JOIN points points ON person.id = points.person_id AND person.id=1') - ->addComponent('person', 'T1015_Person person') - ->addComponent('points', 'person.T1015_Points points'); + ->from('person person INNER JOIN points points ON person.id = points.person_id AND person.id=1') + ->addComponent('person', 'T1015_Person person') + ->addComponent('points', 'person.T1015_Points points') + ; $results = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - //var_dump($results); + // var_dump($results); $person = $results[0]; // number of points for person id of 1 should be 15 @@ -93,7 +99,7 @@ public function setTableDefinition() public function setUp() { - parent :: setUp(); + parent::setUp(); $this->hasOne('T1015_Points', array('local' => 'id', 'foreign' => 'person_id')); } } @@ -109,7 +115,7 @@ public function setTableDefinition() public function setUp() { - parent :: setUp(); + parent::setUp(); $this->hasOne('T1015_Person', array('local' => 'person_id', 'foreign' => 'id')); } } diff --git a/tests/Ticket/1028TestCase.php b/tests/Ticket/1028TestCase.php index da5a27788..e7e568069 100644 --- a/tests/Ticket/1028TestCase.php +++ b/tests/Ticket/1028TestCase.php @@ -20,25 +20,31 @@ */ /** - * Doctrine_I18nRelation_TestCase + * Doctrine_I18nRelation_TestCase. * - * @package Doctrine * @author Brice Figureau * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1028_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + { + } public function prepareTables() { - $this->tables = array('I18nRelationTest','I18nAuthorTest'); + $this->tables = array('I18nRelationTest', 'I18nAuthorTest'); parent::prepareTables(); } @@ -46,28 +52,25 @@ public function prepareTables() public function testRelationIsNotInOriginalTableAnymore() { $i18n = Doctrine_Core::getTable('I18nRelationTest'); - $relation = NULL; + $relation = null; try { $relation = $i18n->getRelation('I18nAuthorTest'); $this->fail(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->pass(); } } - public function testRelationsAreMovedToTranslationTable() { $translation = Doctrine_Core::getTable('I18nRelationTestTranslation'); - $relation = NULL; + $relation = null; try { $relation = $translation->getRelation('I18nAuthorTest'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertTrue($relation instanceof Doctrine_Relation_LocalKey); } - - -} \ No newline at end of file +} diff --git a/tests/Ticket/1044TestCase.php b/tests/Ticket/1044TestCase.php index 5aa9c540b..0c92a8b60 100644 --- a/tests/Ticket/1044TestCase.php +++ b/tests/Ticket/1044TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1044_TestCase + * Doctrine_Ticket_1044_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1044_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1044_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -56,11 +62,11 @@ public function setTableDefinition() public function setUp() { - $this->hasOne('Ticket_1044_UserProfile as UserProfile', array('local' => 'user_profile_id', - 'foreign' => 'id')); - $this->hasOne('Ticket_1044_UserProfile as UserProfile', array('local' => 'user_profile_id', - 'foreign' => 'id', - 'override' => true)); + $this->hasOne('Ticket_1044_UserProfile as UserProfile', array('local' => 'user_profile_id', + 'foreign' => 'id')); + $this->hasOne('Ticket_1044_UserProfile as UserProfile', array('local' => 'user_profile_id', + 'foreign' => 'id', + 'override' => true)); } } @@ -70,4 +76,4 @@ public function setTableDefinition() { $this->hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1071TestCase.php b/tests/Ticket/1071TestCase.php index d24763cca..09fd9da96 100644 --- a/tests/Ticket/1071TestCase.php +++ b/tests/Ticket/1071TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1071_TestCase + * Doctrine_Ticket_1071_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1071_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1071_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -57,4 +63,4 @@ public function setUp() $this->actAs('Timestampable'); $this->actAs('Versionable', array('tableName' => 'my_custom_table_name')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1072TestCase.php b/tests/Ticket/1072TestCase.php index 7451cbda0..23e3f92a3 100644 --- a/tests/Ticket/1072TestCase.php +++ b/tests/Ticket/1072TestCase.php @@ -4,16 +4,20 @@ * Relation testing (accessing) throws an Doctrine_Record_Exception * with message 'Unknown record property / related component * "payment_detail_id" on "T1072BankTransaction"'. - * + * * It happens if I access the relation, save the record, and access * the relation column (in this order). - * + * * UPDATE: * There are three addition checks for the column value type that * must be NULL and not an object which is not true after accessing * the relation. + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1072_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1072_TestCase extends Doctrine_UnitTestCase { public function prepareData() { @@ -31,15 +35,15 @@ public function testTicket() { $bt = new T1072BankTransaction(); $bt->name = 'Test Bank Transaction'; - + // (additional check: value must be NULL) $this->assertEqual(gettype($bt->payment_detail_id), gettype(null)); - + // If I access this relation... - + if ($bt->T1072PaymentDetail) { } - + // (additional check: value must still be NULL not an object) // [romanb]: This is expected behavior currently. Accessing a related record will create // a new one if there is none yet. This makes it possible to use syntax like: @@ -48,12 +52,12 @@ public function testTicket() // In addition the foreign key field is set to a reference to the new record (ugh..). // No way to change this behavior at the moment for BC reasons. $this->assertEqual(gettype($bt->payment_detail_id), gettype(null)); - + // ...save... // [romanb]: Related T1072PaymentDetail will not be saved because its not modified // (isModified() == false) $bt->save(); - + try { // ...and access the relation column it will throw // an exception here but it shouldn't. @@ -61,18 +65,17 @@ public function testTicket() // object as before. if ($bt->payment_detail_id) { } - + // (additional check: value must still be NULL not an object) // [romanb]: See above. This is an empty object now, same as before. $this->assertEqual(gettype($bt->payment_detail_id), gettype(null)); - + $this->pass(); } catch (Doctrine_Record_Exception $e) { $this->fail($e->getMessage()); } } - - + public function testTicket2() { $bt = new T1072BankTransaction(); @@ -88,12 +91,12 @@ public function testTicket2() $this->assertEqual(gettype($bt->T1072PaymentDetail), 'object'); $this->assertEqual(gettype($bt->T1072PaymentDetail->name), 'string'); $this->assertEqual(gettype($bt->payment_detail_id), gettype(null)); - + $bt->save(); - + // After the object gets saved, the foreign key is finally set $this->assertEqual($bt->payment_detail_id, 1); - + $this->pass(); } catch (Doctrine_Record_Exception $e) { $this->fail($e->getMessage()); @@ -110,12 +113,12 @@ public function setTableDefinition() $this->hasColumn('name', 'string', 255, array('notnull' => true)); $this->option('charset', 'utf8'); } - + public function setUp() { parent::setUp(); $this->hasOne('T1072PaymentDetail', array('local' => 'payment_detail_id', - 'foreign' => 'id')); + 'foreign' => 'id')); } } @@ -127,11 +130,11 @@ public function setTableDefinition() $this->hasColumn('name', 'string', 255, array('notnull' => true)); $this->option('charset', 'utf8'); } - + public function setUp() { parent::setUp(); $this->hasOne('T1072BankTransaction', array('local' => 'id', - 'foreign' => 'payment_detail_id')); + 'foreign' => 'payment_detail_id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1077TestCase.php b/tests/Ticket/1077TestCase.php index d25cc0b57..050c7410d 100644 --- a/tests/Ticket/1077TestCase.php +++ b/tests/Ticket/1077TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1077_TestCase + * Doctrine_Ticket_1077_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1077_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1077_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -60,7 +66,7 @@ public function testAutomaticAccessorsAndMutators() $numbers = new Doctrine_Collection('Phonenumber'); $user->Phonenumbers = $numbers; - + $this->assertIdentical($user->phonenumbersTest, $numbers); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, $orig); @@ -82,7 +88,7 @@ public function testDefiningCustomAccessorsAndMutators() class Ticket_1077_User extends Doctrine_Record { - public $phonenumbersTest = null; + public $phonenumbersTest; public function setTableDefinition() { @@ -92,8 +98,8 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1077_Phonenumber as Phonenumbers', array('local' => 'id', - 'foreign' => 'user_id')); + $this->hasMany('Ticket_1077_Phonenumber as Phonenumbers', array('local' => 'id', + 'foreign' => 'user_id')); } public function usernameAccessor() @@ -114,12 +120,13 @@ public function getPhonenumbers() public function setPhonenumbers($phonenumbers) { $this->phonenumbersTest = $phonenumbers; + return $this->_set('Phonenumbers', $phonenumbers); } public function getUsername($load = true) { - return 'Username: ' . $this->_get('username', $load); + return 'Username: '.$this->_get('username', $load); } public function setPassword($password) @@ -143,7 +150,7 @@ public function setTableDefinition() public function setUp() { - $this->hasOne('Ticket_1077_User as User', array('local' => 'user_id', - 'foreign' => 'id')); + $this->hasOne('Ticket_1077_User as User', array('local' => 'user_id', + 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1099TestCase.php b/tests/Ticket/1099TestCase.php index ef7447167..3f0dab91f 100644 --- a/tests/Ticket/1099TestCase.php +++ b/tests/Ticket/1099TestCase.php @@ -1,4 +1,10 @@ from('T1099_Page p') - ->where('p.type = \'subpage\'') - ->fetchOne(); + ->from('T1099_Page p') + ->where('p.type = \'subpage\'') + ->fetchOne() + ; $this->assertEqual('T1099_SubPage', get_class($child)); $this->assertNotEqual(false, $child->getNode()->getParent()); @@ -46,7 +53,7 @@ public function setUp() { $this->actAs('Doctrine_Template_NestedSet'); $this->setSubclasses(array( - 'T1099_SubPage' => array('type' => 'subpage') + 'T1099_SubPage' => array('type' => 'subpage'), )); parent::setUp(); } @@ -54,4 +61,4 @@ public function setUp() class T1099_SubPage extends T1099_Page { -} \ No newline at end of file +} diff --git a/tests/Ticket/1106TestCase.php b/tests/Ticket/1106TestCase.php index 8bc5d6f8d..fb5ce41f8 100644 --- a/tests/Ticket/1106TestCase.php +++ b/tests/Ticket/1106TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1106_TestCase + * Doctrine_Ticket_1106_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1106_TestCase extends Doctrine_UnitTestCase { @@ -38,48 +44,47 @@ public function prepareTables() { parent::prepareTables(); } - + public function prepareData() { $user = new User(); $user->name = 'John'; $user->Group[0]->name = 'Original Group'; $user->save(); - + $this->user_id = $user['id']; } - + public function testAfterOriginalSave() { $user = Doctrine_Query::create()->from('User u, u.Group')->fetchOne(); $this->assertEqual($user->name, 'John'); $this->assertEqual($user->Group[0]->name, 'Original Group'); } - + public function testModifyRelatedRecord() { $user = Doctrine_Query::create()->from('User u, u.Group')->fetchOne(); - + // Modify Record $user->name = 'Stephen'; $user->Group[0]->name = 'New Group'; - + // Test After change and before save $this->assertEqual($user->name, 'Stephen'); $this->assertEqual($user->Group[0]->name, 'New Group'); - + $user->save(); - + // Test after save $this->assertEqual($user->name, 'Stephen'); $this->assertEqual($user->Group[0]->name, 'New Group'); } - + public function testQueryAfterSave() { $user = Doctrine_Core::getTable('User')->find($this->user_id); $this->assertEqual($user->name, 'Stephen'); $this->assertEqual($user->Group[0]->name, 'New Group'); } - } diff --git a/tests/Ticket/1113TestCase.php b/tests/Ticket/1113TestCase.php index efb8a9d85..14d0389b1 100644 --- a/tests/Ticket/1113TestCase.php +++ b/tests/Ticket/1113TestCase.php @@ -1,12 +1,20 @@ tables = array('VIH_Model_Course', 'VIH_Model_Course_Period', 'VIH_Model_Course_SubjectGroup', 'VIH_Model_Subject', 'VIH_Model_Course_SubjectGroup_Subject', 'VIH_Model_Course_Registration', 'VIH_Model_Course_Registration_Subject'); - + parent::prepareTables(); } @@ -14,35 +22,35 @@ public function testSubjectsCanBeRetrievedWhenReopeningTheRegistrationEvenThough { $course1 = new VIH_Model_Course(); $course1->navn = 'Course 1'; - + $period1 = new VIH_Model_Course_Period(); $period1->name = 'Period 1'; $period1->Course = $course1; $period1->save(); - + $group1 = new VIH_Model_Course_SubjectGroup(); $group1->name = 'SubjectGroup 1'; $group1->Period = $period1; - + $subject1 = new VIH_Model_Subject(); $subject1->identifier = 'Subject 1'; - + $subject2 = new VIH_Model_Subject(); $subject2->identifier = 'Subject 2'; - + $group1->Subjects[] = $subject1; $group1->Subjects[] = $subject2; - + $group1->save(); - + $group1->Subjects[] = $subject1; $group1->Subjects[] = $subject2; $group1->save(); - + $course1->SubjectGroups[] = $group1; - + $course1->save(); - + // saved without Subjects try { $registrar = new VIH_Model_Course_Registration(); @@ -62,7 +70,7 @@ public function testSubjectsCanBeRetrievedWhenReopeningTheRegistrationEvenThough } $reopend->save(); - + try { $subject = $reopend->Subjects[0]; $this->assertTrue(is_object($subject)); @@ -70,7 +78,6 @@ public function testSubjectsCanBeRetrievedWhenReopeningTheRegistrationEvenThough } catch (Doctrine_Record_Exception $e) { $this->fail($e->getMessage()); } - } } @@ -86,11 +93,11 @@ public function setTableDefinition() public function setUp() { $this->hasMany( - 'VIH_Model_Course_SubjectGroup as SubjectGroups', + 'VIH_Model_Course_SubjectGroup as SubjectGroups', array( 'refClass' => 'VIH_Model_Course_SubjectGroup_Subject', - 'local' => 'subject_id', - 'foreign' => 'subject_group_id' + 'local' => 'subject_id', + 'foreign' => 'subject_group_id', ) ); @@ -98,8 +105,8 @@ public function setUp() 'VIH_Model_Course_Registration as Registrations', array( 'refClass' => 'VIH_Model_Course_Registration_Subject', - 'local' => 'subject_id', - 'foreign' => 'registration_id' + 'local' => 'subject_id', + 'foreign' => 'registration_id', ) ); } @@ -116,9 +123,9 @@ public function setTableDefinition() public function setUp() { $this->hasMany('VIH_Model_Course_Period as Periods', array('local' => 'id', - 'foreign' => 'course_id')); + 'foreign' => 'course_id')); $this->hasMany('VIH_Model_Course_SubjectGroup as SubjectGroups', array('local' => 'id', - 'foreign' => 'course_id')); + 'foreign' => 'course_id')); } } @@ -136,7 +143,6 @@ public function setUp() { $this->hasOne('VIH_Model_Course as Course', array('local' => 'course_id', 'foreign' => 'id')); } - } class VIH_Model_Course_Registration extends Doctrine_Record @@ -152,12 +158,12 @@ public function setTableDefinition() public function setUp() { - $this->hasOne('VIH_Model_Course as Course', array('local' => 'kursus_id', - 'foreign' => 'id')); + $this->hasOne('VIH_Model_Course as Course', array('local' => 'kursus_id', + 'foreign' => 'id')); $this->hasMany('VIH_Model_Subject as Subjects', array('refClass' => 'VIH_Model_Course_Registration_Subject', - 'local' => 'registration_id', - 'foreign' => 'subject_id')); + 'local' => 'registration_id', + 'foreign' => 'subject_id')); } } @@ -172,15 +178,15 @@ public function setTableDefinition() public function setUp() { - $this->hasOne('VIH_Model_Course_Period as Period', array('local' => 'period_id', - 'foreign' => 'id')); + $this->hasOne('VIH_Model_Course_Period as Period', array('local' => 'period_id', + 'foreign' => 'id')); - $this->hasOne('VIH_Model_Course as Course', array('local' => 'course_id', - 'foreign' => 'id')); + $this->hasOne('VIH_Model_Course as Course', array('local' => 'course_id', + 'foreign' => 'id')); $this->hasMany('VIH_Model_Subject as Subjects', array('refClass' => 'VIH_Model_Course_SubjectGroup_Subject', - 'local' => 'subject_group_id', - 'foreign' => 'subject_id')); + 'local' => 'subject_group_id', + 'foreign' => 'subject_id')); } } @@ -200,4 +206,4 @@ public function setTableDefinition() $this->hasColumn('registration_id', 'integer', null, array('primary' => true)); $this->hasColumn('subject_id', 'integer', null, array('primary' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1116TestCase.php b/tests/Ticket/1116TestCase.php index e91506ec7..3ed92c160 100644 --- a/tests/Ticket/1116TestCase.php +++ b/tests/Ticket/1116TestCase.php @@ -21,70 +21,74 @@ */ /** - * Doctrine_Ticket_1116_TestCase + * Doctrine_Ticket_1116_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1116_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1116_TestCase extends Doctrine_UnitTestCase { - public function setUp() - { - //switch to a real db to trigger the Exception - $this->dbh = new Doctrine_Adapter_Mock('mysql'); - //$this->dbh = new PDO("mysql:host=localhost;dbname=testing", 'root', 'password'); + public function setUp() + { + // switch to a real db to trigger the Exception + $this->dbh = new Doctrine_Adapter_Mock('mysql'); + // $this->dbh = new PDO("mysql:host=localhost;dbname=testing", 'root', 'password'); - $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh); - $this->conn->export->exportClasses(array('Ticket_1116_User')); - } + $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh); + $this->conn->export->exportClasses(array('Ticket_1116_User')); + } + public function testTicket() + { + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); + $q = new Doctrine_Query(); + $q->select('s.*') + ->from('Ticket_1116_User s') + ->where('s.username = ?', array('test')) + ; - public function testTicket() - { - Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); - $q = new Doctrine_Query(); - $q->select('s.*') - ->from('Ticket_1116_User s') - ->where('s.username = ?', array('test')); + // to see the error switch dbh to a real db, the next line will trigger the error + $test = $q->fetchOne(); // will only fail with "real" mysql + $this->assertFalse($test); - // to see the error switch dbh to a real db, the next line will trigger the error - $test = $q->fetchOne(); //will only fail with "real" mysql - $this->assertFalse($test); + $sql = $q->getSqlQuery(); // just getSql()?!?! and it works ? the params are ok after this call + $params = $q->getFlattenedParams(); + $this->assertEqual(count($params), 1); // now we have array('test',null) very strange ..... - $sql = $q->getSqlQuery(); // just getSql()?!?! and it works ? the params are ok after this call - $params = $q->getFlattenedParams(); - $this->assertEqual(count($params), 1); // now we have array('test',null) very strange ..... + $this->assertEqual($sql, 'SELECT u.id AS u__id, u.username AS u__username, u.deleted_at AS u__deleted_at FROM user u WHERE (u.username = ? AND (u.deleted_at IS NULL))'); + $this->assertEqual($params, array('test')); - $this->assertEqual($sql, "SELECT u.id AS u__id, u.username AS u__username, u.deleted_at AS u__deleted_at FROM user u WHERE (u.username = ? AND (u.deleted_at IS NULL))"); - $this->assertEqual($params, array('test')); - - //now also this works! (always works witch mock only fails with mysql) - $test = $q->fetchOne(); - $this->assertFalse($test); - Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); - } + // now also this works! (always works witch mock only fails with mysql) + $test = $q->fetchOne(); + $this->assertFalse($test); + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); + } } - class Ticket_1116_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('user'); - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('username', 'string', 255); - } + public function setTableDefinition() + { + $this->setTableName('user'); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('username', 'string', 255); + } - - public function setUp() - { - parent::setUp(); - $softdelete0 = new Doctrine_Template_SoftDelete(); - $this->actAs($softdelete0); - } -} \ No newline at end of file + public function setUp() + { + parent::setUp(); + $softdelete0 = new Doctrine_Template_SoftDelete(); + $this->actAs($softdelete0); + } +} diff --git a/tests/Ticket/1118TestCase.php b/tests/Ticket/1118TestCase.php index 44aa90c50..38ec237a2 100644 --- a/tests/Ticket/1118TestCase.php +++ b/tests/Ticket/1118TestCase.php @@ -20,23 +20,29 @@ */ /** - * Doctrine_Ticket_1118_TestCase + * Doctrine_Ticket_1118_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1118_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1118_TestCase extends Doctrine_UnitTestCase { // Test that when a foreign key is detected that it sets the foreign key to the same type and length // of the related table primary key public function testTest() { - $yml = <<buildSchema('test.yml', 'yml'); - // Test that ticket__1118__profile_id is changed to to be integer(4) since the primary key of + // Test that ticket__1118__profile_id is changed to to be integer(4) since the primary key of // the relationship is set to that $this->assertEqual($array['Ticket_1118_User']['columns']['ticket__1118__profile_id']['type'], 'integer'); $this->assertEqual($array['Ticket_1118_User']['columns']['ticket__1118__profile_id']['length'], '4'); @@ -70,4 +76,4 @@ public function testTest() unlink('test.yml'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1121TestCase.php b/tests/Ticket/1121TestCase.php index 32f59a459..8e42a7cdf 100644 --- a/tests/Ticket/1121TestCase.php +++ b/tests/Ticket/1121TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1121_TestCase + * Doctrine_Ticket_1121_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1121_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1121_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -43,11 +49,12 @@ public function testTest() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); $q = Doctrine_Query::create() - ->from('Ticket_1121_User u') - // UserProfile has SoftDelete behavior but because it is aliased as Profile, it tries to + ->from('Ticket_1121_User u') + // UserProfile has SoftDelete behavior but because it is aliased as Profile, it tries to // call the dql callbacks for the query on a class named Profile instead of UserProfile // Code responsible for this is in Doctrine_Query_Abstract::_preQuery() - ->leftJoin('u.Profile p'); + ->leftJoin('u.Profile p') + ; // The condition and params for UserProfile SoftDelete and are not added properly $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t.password AS t__password, t.profile_id AS t__profile_id, t.deleted_at AS t__deleted_at, t2.id AS t2__id, t2.name AS t2__name, t2.about AS t2__about, t2.deleted_at AS t2__deleted_at FROM ticket_1121__user t LEFT JOIN ticket_1121__profile t2 ON t.profile_id = t2.id AND (t2.deleted_at IS NULL) WHERE (t.deleted_at IS NULL)'); @@ -68,8 +75,8 @@ public function setTableDefinition() public function setUp() { $this->actAs('SoftDelete'); - $this->hasOne('Ticket_1121_Profile as Profile', array('local' => 'profile_id', - 'foreign' => 'id')); + $this->hasOne('Ticket_1121_Profile as Profile', array('local' => 'profile_id', + 'foreign' => 'id')); } } @@ -84,7 +91,7 @@ public function setTableDefinition() public function setUp() { $this->actAs('SoftDelete'); - $this->hasOne('Ticket_1121_User as User', array('local' => 'id', - 'foreign' => 'profile_id')); + $this->hasOne('Ticket_1121_User as User', array('local' => 'id', + 'foreign' => 'profile_id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1123TestCase.php b/tests/Ticket/1123TestCase.php index a481f4c0e..97de8ca66 100644 --- a/tests/Ticket/1123TestCase.php +++ b/tests/Ticket/1123TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1123_TestCase + * Doctrine_Ticket_1123_TestCase. * - * @package Doctrine * @author Jfung * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1123_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1123_TestCase extends Doctrine_UnitTestCase { public function testInit() { @@ -58,10 +64,10 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1123_User as Friend', array('local' => 'user1', - 'foreign' => 'user2', - 'refClass' => 'Ticket_1123_UserReference', - 'equal' => true)); + $this->hasMany('Ticket_1123_User as Friend', array('local' => 'user1', + 'foreign' => 'user2', + 'refClass' => 'Ticket_1123_UserReference', + 'equal' => true)); } } @@ -78,4 +84,4 @@ public function setUp() $this->hasOne('Ticket_1123_User as User1', array('local' => 'user1', 'foreign' => 'id', 'onDelete' => 'CASCADE')); $this->hasOne('Ticket_1123_User as User2', array('local' => 'user2', 'foreign' => 'id', 'onDelete' => 'CASCADE')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1124TestCase.php b/tests/Ticket/1124TestCase.php index 1d269e3d5..88e701711 100644 --- a/tests/Ticket/1124TestCase.php +++ b/tests/Ticket/1124TestCase.php @@ -1,12 +1,17 @@ no_alias = self::NO_ALIAS; - $record->somethingElse = self::SOMETHING_ELSE; - $record->tableizedAlias = self::TABLEIZED_ALIAS; + $record->no_alias = self::NO_ALIAS; + $record->somethingElse = self::SOMETHING_ELSE; + $record->tableizedAlias = self::TABLEIZED_ALIAS; $record->ClassifiedAlias = self::CLASSIFIED_ALIAS; - $record->another_Alias = self::ANOTHER_ALIAS; + $record->another_Alias = self::ANOTHER_ALIAS; $record->save(); } - private function assertIsSampleRecord($record) - { - $this->assertNotNull($record); - $this->assertEqual($record->no_alias, self::NO_ALIAS); - $this->assertEqual($record->somethingElse, self::SOMETHING_ELSE); - $this->assertEqual($record->tableizedAlias, self::TABLEIZED_ALIAS); - $this->assertEqual($record->ClassifiedAlias, self::CLASSIFIED_ALIAS); - } + private function assertIsSampleRecord($record) + { + $this->assertNotNull($record); + $this->assertEqual($record->no_alias, self::NO_ALIAS); + $this->assertEqual($record->somethingElse, self::SOMETHING_ELSE); + $this->assertEqual($record->tableizedAlias, self::TABLEIZED_ALIAS); + $this->assertEqual($record->ClassifiedAlias, self::CLASSIFIED_ALIAS); + } public function testFindByUnaliasedColumnWorks() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByNoAlias(self::NO_ALIAS); - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByNoAlias(self::NO_ALIAS); + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -50,10 +55,10 @@ public function testFindByUnaliasedColumnWorks() public function testFindByDisjointlyAliasedColumnWorks() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBysomethingElse(self::SOMETHING_ELSE); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBysomethingElse(self::SOMETHING_ELSE); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -62,10 +67,10 @@ public function testFindByDisjointlyAliasedColumnWorks() public function testFindByDisjointlyAliasedColumnWorks2() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBydisjoint_alias(self::SOMETHING_ELSE); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBydisjoint_alias(self::SOMETHING_ELSE); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -74,10 +79,10 @@ public function testFindByDisjointlyAliasedColumnWorks2() public function testFindByDisjointlyAliasedColumnWorks3() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByDisjointAlias(self::SOMETHING_ELSE); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByDisjointAlias(self::SOMETHING_ELSE); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -86,10 +91,10 @@ public function testFindByDisjointlyAliasedColumnWorks3() public function testFindByTableizedAliasedColumnWorks() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBytableizedAlias(self::TABLEIZED_ALIAS); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBytableizedAlias(self::TABLEIZED_ALIAS); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -98,10 +103,10 @@ public function testFindByTableizedAliasedColumnWorks() public function testFindByTableizedAliasedColumnWorks2() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBytableized_alias(self::TABLEIZED_ALIAS); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBytableized_alias(self::TABLEIZED_ALIAS); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -110,10 +115,10 @@ public function testFindByTableizedAliasedColumnWorks2() public function testFindByClassifiedAliasedColumnWorks() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByClassifiedAlias(self::CLASSIFIED_ALIAS); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByClassifiedAlias(self::CLASSIFIED_ALIAS); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -122,10 +127,10 @@ public function testFindByClassifiedAliasedColumnWorks() public function testFindByAnotherAliasedColumnWorks() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByTest(self::ANOTHER_ALIAS); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByTest(self::ANOTHER_ALIAS); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -134,10 +139,10 @@ public function testFindByAnotherAliasedColumnWorks() public function testFindByAnotherAliasedColumnWorks2() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBytest(self::ANOTHER_ALIAS); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneBytest(self::ANOTHER_ALIAS); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -146,10 +151,10 @@ public function testFindByAnotherAliasedColumnWorks2() public function testFindByAnotherAliasedColumnWorks3() { try { - $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByanother_Alias(self::ANOTHER_ALIAS); // test currently fails - - $this->assertIsSampleRecord($r); - $this->pass(); + $r = Doctrine_Core::getTable('Ticket_1124_Record')->findOneByanother_Alias(self::ANOTHER_ALIAS); // test currently fails + + $this->assertIsSampleRecord($r); + $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -168,4 +173,4 @@ public function setTableDefinition() $this->hasColumn('w00t as ClassifiedAlias', 'integer', 4); $this->hasColumn('test as another_Alias', 'integer', 4); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1125TestCase.php b/tests/Ticket/1125TestCase.php index 1afc04928..fb17e4dc7 100644 --- a/tests/Ticket/1125TestCase.php +++ b/tests/Ticket/1125TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1125_TestCase + * Doctrine_Ticket_1125_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1125_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1125_TestCase extends Doctrine_UnitTestCase { public function setUp() { @@ -40,12 +46,12 @@ public function setUp() public function testTest() { - $fields = array('id' => array('primary' => true, - 'autoincrement' => true, - 'type' => 'integer', - 'length' => 4), - 'name' => array('type' => 'string')); + $fields = array('id' => array('primary' => true, + 'autoincrement' => true, + 'type' => 'integer', + 'length' => 4), + 'name' => array('type' => 'string')); $this->conn->export->createTable('test', $fields); $this->assertEqual($this->dbh->pop(), 'CREATE TABLE test (id INT AUTO_INCREMENT, name TEXT, PRIMARY KEY(id)) ENGINE = INNODB'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1131TestCase.php b/tests/Ticket/1131TestCase.php index 9291329d2..429813e75 100644 --- a/tests/Ticket/1131TestCase.php +++ b/tests/Ticket/1131TestCase.php @@ -20,46 +20,52 @@ */ /** - * Doctrine_Ticket_1280_TestCase + * Doctrine_Ticket_1280_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1131_TestCase extends Doctrine_UnitTestCase { - private $role_one, $role_two; + private $role_one; + private $role_two; public function prepareTables() { - //$this->tables = array(); + // $this->tables = array(); $this->tables[] = 'Ticket_1131_User'; $this->tables[] = 'Ticket_1131_Group'; $this->tables[] = 'Ticket_1131_Role'; parent::prepareTables(); } - - + public function prepareData() { parent::prepareData(); - + $role = new Ticket_1131_Role(); $role->name = 'Role One'; $role->save(); $this->role_one = $role->id; $role->free(); - + $role = new Ticket_1131_Role(); $role->name = 'Role Two'; $role->save(); $this->role_two = $role->id; $role->free(); - + $group = new Ticket_1131_Group(); $group->role_id = $this->role_one; $group->name = 'Core Dev'; @@ -79,30 +85,33 @@ public function testTicket() { $user = Doctrine_Query::create() ->from('Ticket_1131_User u') - ->where('u.id = ?')->fetchOne(array(1)); + ->where('u.id = ?')->fetchOne(array(1)) + ; $this->assertEqual($user->Group->id, 1); $this->assertFalse($user->get('group_id') instanceof Doctrine_Record); } - + public function testTicketWithOverloadingAndTwoQueries() { $orig = Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, true); - + $user = Doctrine_Query::create() ->from('Ticket_1131_User u') - ->where('u.id = ?')->fetchOne(array(1)); - + ->where('u.id = ?')->fetchOne(array(1)) + ; + $user = Doctrine_Query::create() ->from('Ticket_1131_UserWithOverloading u') ->leftJoin('u.Group g') ->leftJoin('u.Role r') - ->addWhere('u.id = ?')->fetchOne(array(1)); - + ->addWhere('u.id = ?')->fetchOne(array(1)) + ; + $this->assertEqual($user->Role->id, 1); $this->assertFalse($user->role_id instanceof Doctrine_Record); - + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, $orig); } } @@ -112,10 +121,10 @@ class Ticket_1131_User extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('group_id', 'integer', 20, array( - 'notnull' => false, 'default' => null + 'notnull' => false, 'default' => null, )); $this->hasColumn('role_id', 'integer', 20, array( - 'notnull' => false, 'default' => null + 'notnull' => false, 'default' => null, )); $this->hasColumn('name', 'string', 255); } @@ -124,9 +133,9 @@ public function setUp() { $this->hasOne('Ticket_1131_Group as Group', array( 'local' => 'group_id', - 'foreign' => 'id' + 'foreign' => 'id', )); - + $this->hasOne('Ticket_1131_Role as Role', array( 'local' => 'role_id', 'foreign' => 'id')); @@ -139,7 +148,7 @@ public function getRole() { return $this->Group->Role; } - + public function getRoleId() { return $this->Group->role_id; @@ -151,7 +160,7 @@ class Ticket_1131_Group extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('role_id', 'integer', 20, array( - 'notnull' => false, 'default' => null + 'notnull' => false, 'default' => null, )); $this->hasColumn('name', 'string', 255); } @@ -161,10 +170,10 @@ public function setUp() $this->hasOne('Ticket_1131_Role as Role', array( 'local' => 'role_id', 'foreign' => 'id')); - + $this->hasMany('Ticket_1131_User as Users', array( 'local' => 'id', - 'foreign' => 'group_id' + 'foreign' => 'group_id', )); } } @@ -180,11 +189,11 @@ public function setUp() { $this->hasMany('Ticket_1131_User as Users', array( 'local' => 'id', - 'foreign' => 'role_id' + 'foreign' => 'role_id', )); $this->hasMany('Ticket_1131_Group as Groups', array( 'local' => 'id', - 'foreign' => 'role_id' + 'foreign' => 'role_id', )); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1133TestCase.php b/tests/Ticket/1133TestCase.php index ddcf50e28..7b7adf67e 100644 --- a/tests/Ticket/1133TestCase.php +++ b/tests/Ticket/1133TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1133_TestCase + * Doctrine_Ticket_1133_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1133_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1133_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -47,9 +53,10 @@ public function testTest() $foo->save(); $q = Doctrine_Query::create() - ->from('Ticket_1133_Foo f') - ->innerJoin('f.Bar b ON b.id = ?', $foo->Bar->id) - ->addWhere('f.name = ?', 'test'); + ->from('Ticket_1133_Foo f') + ->innerJoin('f.Bar b ON b.id = ?', $foo->Bar->id) + ->addWhere('f.name = ?', 'test') + ; $this->assertEqual($q->count(), 1); } @@ -62,16 +69,16 @@ public function testTest2() $foo->save(); $q = Doctrine_Query::create() - ->from('Ticket_1133_Foo f') - ->innerJoin('f.Bar b') - ->addWhere('b.name = ?', 'test2') - ->limit(1) - ->offset(1); + ->from('Ticket_1133_Foo f') + ->innerJoin('f.Bar b') + ->addWhere('b.name = ?', 'test2') + ->limit(1) + ->offset(1) + ; $this->assertEqual($q->count(), 2); $this->assertEqual($q->execute()->count(), 1); } - } class Ticket_1133_Foo extends Doctrine_Record @@ -94,4 +101,4 @@ public function setTableDefinition() { $this->hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1134TestCase.php b/tests/Ticket/1134TestCase.php index 87f2ddcc6..e21ebf69c 100644 --- a/tests/Ticket/1134TestCase.php +++ b/tests/Ticket/1134TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1134_TestCase + * Doctrine_Ticket_1134_TestCase. * - * @package Doctrine * @author Jeff Hansen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1134_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1134_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -38,36 +44,32 @@ public function prepareTables() parent::prepareTables(); } - public function prepareData() { $user = new Ticket_1134_User(); - $user->is_pimp = TRUE; + $user->is_pimp = true; $user->save(); } - public function testAfterOriginalSave() { $user = Doctrine_Query::create()->from('Ticket_1134_User u')->fetchOne(); - $this->assertEqual($user->is_pimp, TRUE); - + $this->assertEqual($user->is_pimp, true); } public function testAfterModification() { $user = Doctrine_Query::create()->from('Ticket_1134_User u')->fetchOne(); - $user->is_pimp = "1"; - $this->assertEqual($user->getModified(), FALSE); - } - + $user->is_pimp = '1'; + $this->assertEqual($user->getModified(), false); + } } class Ticket_1134_User extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('is_pimp', 'boolean', TRUE); + $this->hasColumn('is_pimp', 'boolean', true); } public function setUp() diff --git a/tests/Ticket/1160TestCase.php b/tests/Ticket/1160TestCase.php index 858cf7560..c4d9d6393 100644 --- a/tests/Ticket/1160TestCase.php +++ b/tests/Ticket/1160TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1160_TestCase + * Doctrine_Ticket_1160_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1160_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1160_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -42,6 +48,11 @@ public function testTest() } } +/** + * @internal + * + * @coversNothing + */ class Ticket_1160_Test extends Doctrine_Record { public function setTableDefinition() @@ -50,4 +61,4 @@ public function setTableDefinition() $this->option('type', 'MYISAM'); $this->option('collate', 'latin1_german2_ci'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1175TestCase.php b/tests/Ticket/1175TestCase.php index 10a47e51c..1bbfc902c 100644 --- a/tests/Ticket/1175TestCase.php +++ b/tests/Ticket/1175TestCase.php @@ -6,9 +6,14 @@ * Window - Preferences - PHPeclipse - PHP - Code Templates */ +/** + * @internal + * + * @coversNothing + */ class Doctrine_Ticket_1175_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() + public function prepareTables() { $this->tables[] = 'gImage'; @@ -31,7 +36,7 @@ public function testLeftJoinToInheritanceChildTable() $img = new gUserImage(); $img->filename = 'user image 1'; $u->Images[] = $img; - + $img = new gUserImage(); $img->filename = 'user image 2'; $u->Images[] = $img; @@ -50,19 +55,20 @@ public function testLeftJoinToInheritanceChildTable() $b->save(); - $q = Doctrine_Query::create() - ->from('gUser u') - ->leftJoin('u.Images i') - ->leftJoin('u.Files f') - ->where('u.id = ?', array(1)); - - $this->assertEqual($q->getSqlQuery(), 'SELECT g.id AS g__id, g.first_name AS g__first_name, g.last_name AS g__last_name, g2.id AS g2__id, g2.owner_id AS g2__owner_id, g2.filename AS g2__filename, g2.otype AS g2__otype, g3.id AS g3__id, g3.owner_id AS g3__owner_id, g3.filename AS g3__filename, g3.otype AS g3__otype FROM g_user g LEFT JOIN g_image g2 ON g.id = g2.owner_id AND g2.otype = 1 LEFT JOIN g_file g3 ON g.id = g3.owner_id AND g3.otype = 1 WHERE (g.id = ?)'); - - $u = $q->fetchOne(); - - $this->assertTrue( is_object($u) ); + $q = Doctrine_Query::create() + ->from('gUser u') + ->leftJoin('u.Images i') + ->leftJoin('u.Files f') + ->where('u.id = ?', array(1)) + ; + + $this->assertEqual($q->getSqlQuery(), 'SELECT g.id AS g__id, g.first_name AS g__first_name, g.last_name AS g__last_name, g2.id AS g2__id, g2.owner_id AS g2__owner_id, g2.filename AS g2__filename, g2.otype AS g2__otype, g3.id AS g3__id, g3.owner_id AS g3__owner_id, g3.filename AS g3__filename, g3.otype AS g3__otype FROM g_user g LEFT JOIN g_image g2 ON g.id = g2.owner_id AND g2.otype = 1 LEFT JOIN g_file g3 ON g.id = g3.owner_id AND g3.otype = 1 WHERE (g.id = ?)'); + + $u = $q->fetchOne(); + + $this->assertTrue(is_object($u)); if (is_object($u)) { - $this->assertEqual(count($u->Images),2); + $this->assertEqual(count($u->Images), 2); } else { $this->fail(); } @@ -76,10 +82,10 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('owner_id', 'integer', 4); $this->hasColumn('filename', 'string', 64); - $this->hasColumn('otype','integer',4); + $this->hasColumn('otype', 'integer', 4); $this->setAttribute(Doctrine_Core::ATTR_EXPORT, Doctrine_Core::EXPORT_ALL ^ Doctrine_Core::EXPORT_CONSTRAINTS); - $this->setSubClasses(array('gUserImage' => array('otype' => 1),'gBlogImage' => array('otype' => 2))); + $this->setSubClasses(array('gUserImage' => array('otype' => 1), 'gBlogImage' => array('otype' => 2))); } } @@ -88,7 +94,7 @@ class gUserImage extends gImage public function setUp() { parent::setUp(); - $this->hasOne('gUser as User', array('local' => 'owner_id','foreign' => 'id')); + $this->hasOne('gUser as User', array('local' => 'owner_id', 'foreign' => 'id')); } } @@ -97,9 +103,8 @@ class gBlogImage extends gImage public function setUp() { parent::setUp(); - $this->hasOne('gBlog as Blog', array('local' => 'owner_id','foreign' => 'id')); + $this->hasOne('gBlog as Blog', array('local' => 'owner_id', 'foreign' => 'id')); } - } class gFile extends Doctrine_Record @@ -109,10 +114,10 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('owner_id', 'integer', 4); $this->hasColumn('filename', 'string', 64); - $this->hasColumn('otype','integer',4); + $this->hasColumn('otype', 'integer', 4); $this->setAttribute(Doctrine_Core::ATTR_EXPORT, Doctrine_Core::EXPORT_ALL ^ Doctrine_Core::EXPORT_CONSTRAINTS); - $this->setSubClasses(array('gUserFile' => array('otype' => 1),'gBlogFile' => array('otype' => 2))); + $this->setSubClasses(array('gUserFile' => array('otype' => 1), 'gBlogFile' => array('otype' => 2))); } } @@ -121,7 +126,7 @@ class gUserFile extends gFile public function setUp() { parent::setUp(); - $this->hasOne('gUser as User', array('local' => 'owner_id','foreign' => 'id')); + $this->hasOne('gUser as User', array('local' => 'owner_id', 'foreign' => 'id')); } } @@ -130,13 +135,13 @@ class gBlogFile extends gFile public function setUp() { parent::setUp(); - $this->hasOne('gBlog as Blog', array('local' => 'owner_id','foreign' => 'id')); + $this->hasOne('gBlog as Blog', array('local' => 'owner_id', 'foreign' => 'id')); } } class gBlog extends Doctrine_Record { - public function setTableDefinition() + public function setTableDefinition() { $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('title', 'string', 128); @@ -145,10 +150,9 @@ public function setTableDefinition() public function setUp() { parent::setUp(); - $this->hasMany('gBlogImage as Images', array('local' => 'id','foreign' => 'owner_id')); - $this->hasMany('gBlogFile as Files', array('local' => 'id','foreign' => 'owner_id')); + $this->hasMany('gBlogImage as Images', array('local' => 'id', 'foreign' => 'owner_id')); + $this->hasMany('gBlogFile as Files', array('local' => 'id', 'foreign' => 'owner_id')); } - } class gUser extends Doctrine_Record @@ -158,12 +162,12 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('first_name', 'string', 128); $this->hasColumn('last_name', 'string', 128); - } + } public function setUp() { parent::setUp(); - $this->hasMany('gUserImage as Images', array('local' => 'id','foreign' => 'owner_id')); - $this->hasMany('gUserFile as Files', array('local' => 'id','foreign' => 'owner_id')); + $this->hasMany('gUserImage as Images', array('local' => 'id', 'foreign' => 'owner_id')); + $this->hasMany('gUserFile as Files', array('local' => 'id', 'foreign' => 'owner_id')); } } diff --git a/tests/Ticket/1192TestCase.php b/tests/Ticket/1192TestCase.php index 303f12a41..736bf0f5a 100644 --- a/tests/Ticket/1192TestCase.php +++ b/tests/Ticket/1192TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1192_TestCase + * Doctrine_Ticket_1192_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1192_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1192_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -59,8 +65,9 @@ public function prepareData() public function testTest() { $q = Doctrine_Query::create() - ->from('Ticket_1192_CPK t') - ->groupBy('t.user_id'); + ->from('Ticket_1192_CPK t') + ->groupBy('t.user_id') + ; $this->assertEqual($q->getCountSqlQuery(), 'SELECT COUNT(*) AS num_results FROM ticket_1192__c_p_k t GROUP BY t.user_id'); $count = $q->count(); @@ -73,8 +80,8 @@ class Ticket_1192_CPK extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('user_id', 'integer', 4, array('primary' => true)); - $this->hasColumn('name', 'string', 255); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('user_id', 'integer', 4, array('primary' => true)); + $this->hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1195TestCase.php b/tests/Ticket/1195TestCase.php index ef77112bb..fc4dfc93e 100644 --- a/tests/Ticket/1195TestCase.php +++ b/tests/Ticket/1195TestCase.php @@ -5,37 +5,42 @@ * by Stefan Klug ( stefan.klug (at) gmail.com ) */ +/** + * @internal + * + * @coversNothing + */ class Doctrine_Ticket_1195_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() + public function prepareTables() { - $this->tables = array(); - $this->tables[] = 'T1195_Item'; - $this->tables[] = 'T1195_Ref'; + $this->tables = array(); + $this->tables[] = 'T1195_Item'; + $this->tables[] = 'T1195_Ref'; - parent :: prepareTables(); + parent::prepareTables(); } public function prepareData() { $item = new T1195_Item(); - $item->col1 = "a"; - $item->col2 = "a"; + $item->col1 = 'a'; + $item->col2 = 'a'; $item->save(); $item = new T1195_Item(); - $item->col1 = "a"; - $item->col2 = "b"; + $item->col1 = 'a'; + $item->col2 = 'b'; $item->save(); $item = new T1195_Item(); - $item->col1 = "b"; - $item->col2 = "a"; + $item->col1 = 'b'; + $item->col2 = 'a'; $item->save(); $item = new T1195_Item(); - $item->col1 = "b"; - $item->col2 = "b"; + $item->col1 = 'b'; + $item->col2 = 'b'; $item->save(); $ref = new T1195_Ref(); @@ -45,58 +50,58 @@ public function prepareData() $ref = new T1195_Ref(); $ref->Item = $item; $ref->save(); - } public function testRawSQLaddWhere() { - //this checks for an error in parseDqlQueryPart + // this checks for an error in parseDqlQueryPart - $query = new Doctrine_RawSql(); + $query = new Doctrine_RawSql(); $q = $query->select('{i.*}') - ->addComponent('i', 'T1195_Item i') - ->from('items i') - ->addWhere('i.col1 = ?','a') - ->addWhere('i.col2 = ?','a'); + ->addComponent('i', 'T1195_Item i') + ->from('items i') + ->addWhere('i.col1 = ?', 'a') + ->addWhere('i.col2 = ?', 'a') + ; - $res = $q->execute(); + $res = $q->execute(); $this->assertEqual($res->count(), 1); } public function testRawSQLDistinct() { - $q = new Doctrine_RawSql(); + $q = new Doctrine_RawSql(); $q = $q->select('{i.*}') - ->addComponent('i', 'T1195_Item i') - ->from('ref r') - ->leftJoin('items i ON r.item_id=i.id'); - + ->addComponent('i', 'T1195_Item i') + ->from('ref r') + ->leftJoin('items i ON r.item_id=i.id') + ; - $res = $q->execute(array(),Doctrine_Core::HYDRATE_ARRAY); - $this->assertEqual(sizeof($res), 2); + $res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + $this->assertEqual(sizeof($res), 2); - $q->distinct(); - $res = $q->execute(array(),Doctrine_Core::HYDRATE_ARRAY); - $this->assertEqual(sizeof($res), 1); + $q->distinct(); + $res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + $this->assertEqual(sizeof($res), 1); } - public function testRawSQLCount() + public function testRawSQLCount() { - $q = new Doctrine_RawSql(); + $q = new Doctrine_RawSql(); $q = $q->select('{i.*}') - ->addComponent('i', 'T1195_Item i') - ->from('items i'); + ->addComponent('i', 'T1195_Item i') + ->from('items i') + ; - if ( !method_exists( $q, 'count' )) - { - $this->fail("The query doesn't have a count() method"); - return; - } + if (!method_exists($q, 'count')) { + $this->fail("The query doesn't have a count() method"); - $res = $q->count(); - $this->assertEqual($res, 4); + return; + } + $res = $q->count(); + $this->assertEqual($res, 4); } } @@ -104,7 +109,7 @@ class T1195_Item extends Doctrine_Record { public function setTableDefinition() { - $this->setTableName('items'); + $this->setTableName('items'); $this->hasColumn('id', 'integer', null, array('autoincrement' => true, 'primary' => true, 'notnull' => true)); $this->hasColumn('col1', 'string', 10); $this->hasColumn('col2', 'string', 10); @@ -115,13 +120,13 @@ class T1195_Ref extends Doctrine_Record { public function setTableDefinition() { - $this->setTableName('ref'); + $this->setTableName('ref'); $this->hasColumn('id', 'integer', null, array('autoincrement' => true, 'primary' => true, 'notnull' => true)); $this->hasColumn('item_id', 'integer', null); } public function setUp() { - $this->hasOne('T1195_Item as Item', array('local' => 'item_id', 'foreign' => 'id')); + $this->hasOne('T1195_Item as Item', array('local' => 'item_id', 'foreign' => 'id')); } } diff --git a/tests/Ticket/1205TestCase.php b/tests/Ticket/1205TestCase.php index 775870f8f..446287cf8 100644 --- a/tests/Ticket/1205TestCase.php +++ b/tests/Ticket/1205TestCase.php @@ -1,39 +1,46 @@ id = 1; $user->first_name = 'Slick'; $user->last_name = 'Rick'; $user->save(); - + $address = new Ticket1205TestAddress(); $address->id = 1; $address->user_id = 1; $address->city = 'Anywhere'; - $address->save(); - } - + $address->save(); + } + public function prepareTables() { $this->tables[] = 'Ticket1205TestUser'; $this->tables[] = 'Ticket1205TestAddress'; parent::prepareTables(); - } - + } + public function testTicket() { try { - // Each Address has 1 User - $q = Doctrine_Query::create() + // Each Address has 1 User + $q = Doctrine_Query::create() ->from('Ticket1205TestAddress a') ->innerjoin('a.User u') - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - $this->fail(); + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY) + ; + $this->fail(); } catch (Exception $e) { - $this->pass(); + $this->pass(); } } } @@ -48,33 +55,33 @@ public function postHydrate(Doctrine_Event $event) class Ticket1205TestUser extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('ticket1205_user'); - $this->hasColumn('first_name', 'string', 31); - $this->hasColumn('last_name', 'string', 31); - } + public function setTableDefinition() + { + $this->setTableName('ticket1205_user'); + $this->hasColumn('first_name', 'string', 31); + $this->hasColumn('last_name', 'string', 31); + } - public function setUp() - { - $this->addListener(new Ticket1205HydrationListener()); - $this->hasMany('Ticket1205TestAddress as Addresses', array('local' => 'id', - 'foreign' => 'user_id')); - } + public function setUp() + { + $this->addListener(new Ticket1205HydrationListener()); + $this->hasMany('Ticket1205TestAddress as Addresses', array('local' => 'id', + 'foreign' => 'user_id')); + } } class Ticket1205TestAddress extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('ticket1205_address'); - $this->hasColumn('user_id', 'integer', 4, array('notnull' => true)); - $this->hasColumn('city', 'string', 31); - } + public function setTableDefinition() + { + $this->setTableName('ticket1205_address'); + $this->hasColumn('user_id', 'integer', 4, array('notnull' => true)); + $this->hasColumn('city', 'string', 31); + } - public function setUp() - { - $this->hasOne('Ticket1205TestUser as User', array('local' => 'user_id', - 'foreign' => 'id')); - } -} \ No newline at end of file + public function setUp() + { + $this->hasOne('Ticket1205TestUser as User', array('local' => 'user_id', + 'foreign' => 'id')); + } +} diff --git a/tests/Ticket/1206TestCase.php b/tests/Ticket/1206TestCase.php index 8e050b377..ddaa798db 100644 --- a/tests/Ticket/1206TestCase.php +++ b/tests/Ticket/1206TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1206_TestCase + * Doctrine_Ticket_1206_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1206_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1206_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -60,4 +66,4 @@ public function setUp() { $this->actAs('I18n', array('fields' => array('title', 'body'))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1208TestCase.php b/tests/Ticket/1208TestCase.php index 26d25107e..5714ebfe1 100644 --- a/tests/Ticket/1208TestCase.php +++ b/tests/Ticket/1208TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1208_TestCase + * Doctrine_Ticket_1208_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1208_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1208_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -49,7 +55,8 @@ public function prepareData() public function testTest() { $q = Doctrine_Query::create() - ->from('Ticket_1208_User u'); + ->from('Ticket_1208_User u') + ; $user = $q->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertTrue(isset($user['pre_hydrate'])); @@ -78,4 +85,4 @@ public function postHydrate($event) $data['post_hydrate'] = 'post hydrate value'; $event->data = $data; } -} \ No newline at end of file +} diff --git a/tests/Ticket/1211TestCase.php b/tests/Ticket/1211TestCase.php index fedf557f9..130ddc22e 100644 --- a/tests/Ticket/1211TestCase.php +++ b/tests/Ticket/1211TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1211_TestCase + * Doctrine_Ticket_1211_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1211_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1211_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -38,11 +44,12 @@ public function testTest() $this->conn->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_NONE); $q = Doctrine_Query::create() - ->select('u.*, COS(12.34) as test') - ->from('User u'); + ->select('u.*, COS(12.34) as test') + ->from('User u') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, COS(12.34) AS e__0 FROM entity e WHERE (e.type = 0)'); $this->conn->setAttribute(Doctrine_Core::ATTR_PORTABILITY, $orig); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1213TestCase.php b/tests/Ticket/1213TestCase.php index 4810e71a0..d8b34acee 100644 --- a/tests/Ticket/1213TestCase.php +++ b/tests/Ticket/1213TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1213_TestCase + * Doctrine_Ticket_1213_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1213_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1213_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -43,8 +49,8 @@ public function testTest() { $guid = md5(microtime()); $person = new Doctrine_Ticket_1213_Person(); - $person->Name = "Frank Zappa ".time(); - $person->guid = $guid; + $person->Name = 'Frank Zappa '.time(); + $person->guid = $guid; $person->Birthday->Bday = '1940-12-21'; $person->Birthday->person_guid = $guid; $person->save(); @@ -55,29 +61,29 @@ public function testTest() class Doctrine_Ticket_1213_Birthday extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('person_guid', 'string', 32, array('primary' => true)); - $this->hasColumn('Bday', 'timestamp'); + public function setTableDefinition() + { + $this->hasColumn('person_guid', 'string', 32, array('primary' => true)); + $this->hasColumn('Bday', 'timestamp'); - $this->index('person_guid', array('fields' => array('person_guid'))); - } + $this->index('person_guid', array('fields' => array('person_guid'))); + } } class Doctrine_Ticket_1213_Person extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('guid', 'string', 32, array('primary' => true)); - $this->hasColumn('Name', 'string', 100); + public function setTableDefinition() + { + $this->hasColumn('guid', 'string', 32, array('primary' => true)); + $this->hasColumn('Name', 'string', 100); - $this->index('guid', array('fields' => array('guid'))); - } + $this->index('guid', array('fields' => array('guid'))); + } - public function setUp() - { - $this->hasOne('Doctrine_Ticket_1213_Birthday as Birthday', array('local' => 'guid', - 'foreign' => 'person_guid', - 'owningSide' => true)); - } -} \ No newline at end of file + public function setUp() + { + $this->hasOne('Doctrine_Ticket_1213_Birthday as Birthday', array('local' => 'guid', + 'foreign' => 'person_guid', + 'owningSide' => true)); + } +} diff --git a/tests/Ticket/1225TestCase.php b/tests/Ticket/1225TestCase.php index a2e37d6e8..d001c3333 100644 --- a/tests/Ticket/1225TestCase.php +++ b/tests/Ticket/1225TestCase.php @@ -1,4 +1,10 @@ tables = array('Ticket_1225_Tree'); parent::prepareTables(); } - + public function prepareData() { } - public function testMoveAsSameNodeThrowsException() + public function testMoveAsSameNodeThrowsException() { $root1 = new Ticket_1225_Tree(); $tree = $root1->getTable()->getTree(); @@ -41,7 +47,7 @@ public function testMoveAsSameNodeThrowsException() } try { - $root1->getNode()->moveAsLastChildOf($root1); + $root1->getNode()->moveAsLastChildOf($root1); $this->fail(); } catch (Doctrine_Tree_Exception $e) { $this->pass(); @@ -57,4 +63,4 @@ public function setTableDefinition() $this->actAs('NestedSet'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1228TestCase.php b/tests/Ticket/1228TestCase.php index 2443e7c4e..82c39805c 100644 --- a/tests/Ticket/1228TestCase.php +++ b/tests/Ticket/1228TestCase.php @@ -20,52 +20,58 @@ */ /** - * Doctrine_Template_TestCase + * Doctrine_Template_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1228_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1228_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { - $this->tables[] = "RelA"; - $this->tables[] = "RelB"; - $this->tables[] = "RelC"; - $this->tables[] = "RelD"; - $this->tables[] = "RelE"; + $this->tables[] = 'RelA'; + $this->tables[] = 'RelB'; + $this->tables[] = 'RelC'; + $this->tables[] = 'RelD'; + $this->tables[] = 'RelE'; parent::prepareTables(); } - public function prepareData() + public function prepareData() { // first branch of the 'object hierarchy' $e1 = new RelE(); - $e1->name = "e 1"; + $e1->name = 'e 1'; $e1->save(); - + $d1 = new RelD(); - $d1->name = "d 1"; + $d1->name = 'd 1'; $d1->rel_e_id = $e1->id; $d1->save(); $c1 = new RelC(); - $c1->name = "c 1"; + $c1->name = 'c 1'; $c1->rel_d_id = $d1->id; $c1->save(); $b1 = new RelB(); - $b1->name = "b 1"; + $b1->name = 'b 1'; $b1->rel_c_id = $c1->id; $b1->save(); $a1 = new RelA(); - $a1->name = "a 1"; + $a1->name = 'a 1'; $a1->rel_b_id = $b1->id; $a1->save(); @@ -76,34 +82,33 @@ public function prepareData() $b2->save(); */ $a2 = new RelA(); - $a2->name = "a 2"; + $a2->name = 'a 2'; // uncomment this, too // $a2->rel_b_id = $b2->id; $a2->save(); - $e2 = new RelE(); - $e2->name = "e 2"; + $e2->name = 'e 2'; $e2->save(); // third branch, full depth again $d3 = new RelD(); - $d3->name = "d 3"; + $d3->name = 'd 3'; $d3->rel_e_id = $e2->id; $d3->save(); $c3 = new RelC(); - $c3->name = "c 3"; + $c3->name = 'c 3'; $c3->rel_d_id = $d3->id; $c3->save(); $b3 = new RelB(); - $b3->name = "b 3"; + $b3->name = 'b 3'; $b3->rel_c_id = $c3->id; $b3->save(); $a3 = new RelA(); - $a3->name = "a 3"; + $a3->name = 'a 3'; $a3->rel_b_id = $b3->id; $a3->save(); } @@ -116,14 +121,13 @@ public function testHydrationSkippingRelationIfNotSetOnSiblingDepth3() $q->leftJoin('ab.c abc'); $q->orderBy('a.id ASC'); $res = $q->execute(); - //$res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - - //var_dump($res/*->toArray(true)*/); - + // $res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + + // var_dump($res/*->toArray(true)*/); + $this->assertEqual('a 1', $res->getFirst()->get('name')); $this->assertTrue($res->getFirst()->get('b')->exists()); $this->assertTrue($res->getFirst()->get('b')->get('c')->exists()); - } public function testHydrationSkippingRelationIfNotSetOnSiblingDepth4() @@ -135,17 +139,16 @@ public function testHydrationSkippingRelationIfNotSetOnSiblingDepth4() $q->leftJoin('abc.d abcd'); $q->orderBy('a.id ASC'); $res = $q->execute(); - //$res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - - //var_dump($res/*->toArray(true)*/); - + // $res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + + // var_dump($res/*->toArray(true)*/); + $this->assertEqual('a 1', $res->getFirst()->get('name')); $this->assertTrue($res->getFirst()->get('b')->exists()); $this->assertTrue($res->getFirst()->get('b')->get('c')->exists()); $this->assertTrue($res->getFirst()->get('b')->get('c')->get('d')->exists()); - } - + public function testHydrationSkippingRelationIfNotSetOnSiblingDepth5() { $q = new Doctrine_Query(); @@ -156,85 +159,87 @@ public function testHydrationSkippingRelationIfNotSetOnSiblingDepth5() $q->leftJoin('abcd.e abcde'); $q->orderBy('a.id ASC'); $res = $q->execute(); - //$res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - - //var_dump($res/*->toArray(true)*/); - + // $res = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + + // var_dump($res/*->toArray(true)*/); + $this->assertEqual('a 1', $res->getFirst()->get('name')); $this->assertTrue($res->getFirst()->get('b')->exists()); $this->assertTrue($res->getFirst()->get('b')->get('c')->exists()); $this->assertTrue($res->getFirst()->get('b')->get('c')->get('d')->exists()); $this->assertTrue($res->getFirst()->get('b')->get('c')->get('d')->get('e')->exists()); - } - } -class RelA extends Doctrine_Record { - - public function setTableDefinition() { - $this->setTableName('rel_a'); - $this->hasColumn('name', 'string', 25, array()); - $this->hasColumn('rel_b_id', 'integer', 10, array()); - } - - public function setUp() { - $this->HasOne('RelB as b', array('local' => 'rel_b_id', 'foreign' => 'id')); - } +class RelA extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->setTableName('rel_a'); + $this->hasColumn('name', 'string', 25, array()); + $this->hasColumn('rel_b_id', 'integer', 10, array()); + } + public function setUp() + { + $this->HasOne('RelB as b', array('local' => 'rel_b_id', 'foreign' => 'id')); + } } -class RelB extends Doctrine_Record { - - public function setTableDefinition() { - $this->setTableName('rel_b'); - $this->hasColumn('name', 'string', 25, array()); - $this->hasColumn('rel_c_id', 'integer', 10, array()); - } - - public function setUp() { - $this->HasOne('RelC as c', array('local' => 'rel_c_id', 'foreign' => 'id')); - } +class RelB extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->setTableName('rel_b'); + $this->hasColumn('name', 'string', 25, array()); + $this->hasColumn('rel_c_id', 'integer', 10, array()); + } + public function setUp() + { + $this->HasOne('RelC as c', array('local' => 'rel_c_id', 'foreign' => 'id')); + } } -class RelC extends Doctrine_Record { - - public function setTableDefinition() { - $this->setTableName('rel_c'); - $this->hasColumn('name', 'string', 25, array()); - $this->hasColumn('rel_d_id', 'integer', 10, array()); - } - - public function setUp() { - $this->HasOne('RelD as d', array('local' => 'rel_d_id', 'foreign' => 'id')); - } +class RelC extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->setTableName('rel_c'); + $this->hasColumn('name', 'string', 25, array()); + $this->hasColumn('rel_d_id', 'integer', 10, array()); + } + public function setUp() + { + $this->HasOne('RelD as d', array('local' => 'rel_d_id', 'foreign' => 'id')); + } } -class RelD extends Doctrine_Record { - - public function setTableDefinition() { - $this->setTableName('rel_d'); - $this->hasColumn('name', 'string', 25, array()); - $this->hasColumn('rel_e_id', 'integer', 10, array()); - } - - public function setUp() { - $this->HasOne('RelE as e', array('local' => 'rel_e_id', 'foreign' => 'id')); - } +class RelD extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->setTableName('rel_d'); + $this->hasColumn('name', 'string', 25, array()); + $this->hasColumn('rel_e_id', 'integer', 10, array()); + } + public function setUp() + { + $this->HasOne('RelE as e', array('local' => 'rel_e_id', 'foreign' => 'id')); + } } -class RelE extends Doctrine_Record { - - public function setTableDefinition() { - $this->setTableName('rel_e'); - $this->hasColumn('name', 'string', 25, array()); - } - - public function setUp() { - - } +class RelE extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->setTableName('rel_e'); + $this->hasColumn('name', 'string', 25, array()); + } + public function setUp() + { + } } diff --git a/tests/Ticket/1230TestCase.php b/tests/Ticket/1230TestCase.php index b9340feb1..5c1ddc344 100644 --- a/tests/Ticket/1230TestCase.php +++ b/tests/Ticket/1230TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1230_TestCase + * Doctrine_Ticket_1230_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1230_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1230_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -52,7 +58,8 @@ public function testTicket() $baseQuery = Doctrine_Query::create() ->select('*') ->from('Ticket_1230_Category c') - ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY); + ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) + ; $categoriesTreeObject->setBaseQuery($baseQuery); $categoriesArray = $categoriesTreeObject->fetchTree(); @@ -71,4 +78,4 @@ public function setUp() { $this->actAs('NestedSet'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1236TestCase.php b/tests/Ticket/1236TestCase.php index 17ad19b68..d77cfe263 100644 --- a/tests/Ticket/1236TestCase.php +++ b/tests/Ticket/1236TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1236_TestCase + * Doctrine_Ticket_1236_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1236_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1236_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -62,7 +68,7 @@ public function setTableDefinition() public function setUp() { - $this->actAs('I18n', array('fields' => array('title', 'body'), - 'generateFiles' => false)); + $this->actAs('I18n', array('fields' => array('title', 'body'), + 'generateFiles' => false)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1244TestCase.php b/tests/Ticket/1244TestCase.php index aafcac4d2..f4096669a 100644 --- a/tests/Ticket/1244TestCase.php +++ b/tests/Ticket/1244TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1244_TestCase + * Doctrine_Ticket_1244_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1244_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1244_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -56,10 +62,15 @@ public function testTicket() } } +/** + * @internal + * + * @coversNothing + */ class Ticket_1244_Test extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('test', 'integer', 4, array('range' => array(5, 10))); + $this->hasColumn('test', 'integer', 4, array('range' => array(5, 10))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1250TestCase.php b/tests/Ticket/1250TestCase.php index a126fac62..d00c81949 100644 --- a/tests/Ticket/1250TestCase.php +++ b/tests/Ticket/1250TestCase.php @@ -20,54 +20,62 @@ */ /** - * Doctrine_Ticket_1015_TestCase + * Doctrine_Ticket_1015_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1250_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { - $this->tables[] = 'Doctrine_Ticket_1250_i18n'; - parent::prepareTables(); - } - - public function testTicket() - { - try { - $r = new Doctrine_Ticket_1250_i18n(); - // This is needed since all fields are internationalized. - // Reason for not fixing that is BC. Manual describes this behavior very well - $r->state('TDIRTY'); - $r->Translation['en']->title = 'Title in english'; - $r->Translation['en']->content = 'Content in english'; - $r->Translation['fr']->title = 'Titre en français'; - $r->Translation['en']->content = 'Contenu en français'; - $r->save(); - } catch (Exception $e) { - $this->fail($e->getMessage()); - } - - $this->assertEqual(1, $r->id); - } +class Doctrine_Ticket_1250_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { + $this->tables[] = 'Doctrine_Ticket_1250_i18n'; + parent::prepareTables(); + } + + public function testTicket() + { + try { + $r = new Doctrine_Ticket_1250_i18n(); + // This is needed since all fields are internationalized. + // Reason for not fixing that is BC. Manual describes this behavior very well + $r->state('TDIRTY'); + $r->Translation['en']->title = 'Title in english'; + $r->Translation['en']->content = 'Content in english'; + $r->Translation['fr']->title = 'Titre en français'; + $r->Translation['en']->content = 'Contenu en français'; + $r->save(); + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + + $this->assertEqual(1, $r->id); + } } class Doctrine_Ticket_1250_i18n extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('Doctrine_Ticket_1250_i18n'); - $this->hasColumn('title', 'string', 255); - $this->hasColumn('content', 'string', null); - } + public function setTableDefinition() + { + $this->setTableName('Doctrine_Ticket_1250_i18n'); + $this->hasColumn('title', 'string', 255); + $this->hasColumn('content', 'string', null); + } - public function setUp() - { - parent::setUp(); - $i18n0 = new Doctrine_Template_I18n(array('length' => 5, 'fields' => array(0 => 'title', 1 => 'content'))); - $this->actAs($i18n0); - } -} \ No newline at end of file + public function setUp() + { + parent::setUp(); + $i18n0 = new Doctrine_Template_I18n(array('length' => 5, 'fields' => array(0 => 'title', 1 => 'content'))); + $this->actAs($i18n0); + } +} diff --git a/tests/Ticket/1251TestCase.php b/tests/Ticket/1251TestCase.php index a2c7bcd30..69fe1a145 100644 --- a/tests/Ticket/1251TestCase.php +++ b/tests/Ticket/1251TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_384_TestCase + * Doctrine_Ticket_384_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1251_TestCase extends Doctrine_UnitTestCase { @@ -37,23 +43,21 @@ public function prepareTables() $this->tables[] = 'Ticket_1251_Record'; parent::prepareTables(); } - - + public function testAccessDataNamedField() { $t = new Ticket_1251_Record(); $t->data = 'Foo'; $t->save(); - + $this->assertEqual($t->data, 'Foo'); } } - class Ticket_1251_Record extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('data', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1253TestCase.php b/tests/Ticket/1253TestCase.php index 4d3de0f43..91c19e3b5 100644 --- a/tests/Ticket/1253TestCase.php +++ b/tests/Ticket/1253TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1253_TestCase + * Doctrine_Ticket_1253_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1253_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1253_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -55,8 +61,9 @@ public function testTest() $test->save(); $q = Doctrine_Query::create() - ->from('Ticket_1253_User u') - ->leftJoin('u.Type'); + ->from('Ticket_1253_User u') + ->leftJoin('u.Type') + ; // This will never work because t.type_name is the emulated enum value and t2.name is the actual name $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.name AS t__name, t.type_name AS t__type_name, t2.id AS t2__id, t2.name AS t2__name FROM ticket_1253__user t LEFT JOIN ticket_1253__user_type t2 ON t.type_name = t2.name'); @@ -90,4 +97,4 @@ public function setUp() { $this->hasMany('Ticket_1253_User as User', array('local' => 'name', 'foreign' => 'type_name', 'owningSide' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1254TestCase.php b/tests/Ticket/1254TestCase.php index 192697472..2df5af6f8 100644 --- a/tests/Ticket/1254TestCase.php +++ b/tests/Ticket/1254TestCase.php @@ -20,48 +20,54 @@ */ /** - * Doctrine_Ticket_1254_TestCase + * Doctrine_Ticket_1254_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1254_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1254_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { - $this->tables[] = "RelX"; - $this->tables[] = "RelY"; + $this->tables[] = 'RelX'; + $this->tables[] = 'RelY'; parent::prepareTables(); } - public function prepareData() + public function prepareData() { - Doctrine_Manager::getInstance()->getCurrentConnection()->beginTransaction(); + Doctrine_Manager::getInstance()->getCurrentConnection()->beginTransaction(); $cats = array('cat1', 'cat2'); - $now = time(); + $now = time(); - for ($i = 0; $i < 10; $i++) { - $age = $now - $i * 1000; + for ($i = 0; $i < 10; ++$i) { + $age = $now - $i * 1000; $x = new RelX(); - $x->name = "x $i"; - $x->category = $cats[$i % 2]; - $x->set('created_at', date('Y-m-d H:i:s', $age)); - $x->save(); - - for ($j = 0; $j < 10; $j++) { - $y = new RelY(); - $y->name = "y ".($i * 10 + $j); - $y->rel_x_id = $x->id; - $y->save(); - } - } - + $x->name = "x {$i}"; + $x->category = $cats[$i % 2]; + $x->set('created_at', date('Y-m-d H:i:s', $age)); + $x->save(); + + for ($j = 0; $j < 10; ++$j) { + $y = new RelY(); + $y->name = 'y '.($i * 10 + $j); + $y->rel_x_id = $x->id; + $y->save(); + } + } + Doctrine_Manager::getInstance()->getCurrentConnection()->commit(); } @@ -69,48 +75,47 @@ public function testSubqueryExtractionUsesWrongAliases() { $q = new Doctrine_Query(); $q->from('RelX x'); - $q->leftJoin('x.y xy'); - $q->where('x.created_at IN (SELECT MAX(x2.created_at) latestInCategory FROM RelX x2 WHERE x.category = x2.category)'); - $q->limit(5); + $q->leftJoin('x.y xy'); + $q->where('x.created_at IN (SELECT MAX(x2.created_at) latestInCategory FROM RelX x2 WHERE x.category = x2.category)'); + $q->limit(5); - //echo $sql = $q->getSqlQuery(); + // echo $sql = $q->getSqlQuery(); // echo $sql; $xs = $q->execute(); - // Doctrine_Ticket_1254_TestCase : method testSubqueryExtractionUsesWrongAliases failed on line 76 + // Doctrine_Ticket_1254_TestCase : method testSubqueryExtractionUsesWrongAliases failed on line 76 // This fails sometimes at $this->assertEqual(2, count($xs)); - } - } -class RelX extends Doctrine_Record { - - public function setTableDefinition() { - $this->setTableName('rel_x'); - $this->hasColumn('name', 'string', 25, array()); - $this->hasColumn('category', 'string', 25, array()); - $this->hasColumn('created_at', 'timestamp', null, array()); - } - - public function setUp() { - $this->HasMany('RelY as y', array('local' => 'id', 'foreign' => 'rel_x_id')); - } +class RelX extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->setTableName('rel_x'); + $this->hasColumn('name', 'string', 25, array()); + $this->hasColumn('category', 'string', 25, array()); + $this->hasColumn('created_at', 'timestamp', null, array()); + } + public function setUp() + { + $this->HasMany('RelY as y', array('local' => 'id', 'foreign' => 'rel_x_id')); + } } -class RelY extends Doctrine_Record { - - public function setTableDefinition() { - $this->setTableName('rel_y'); - $this->hasColumn('name', 'string', 25, array()); - $this->hasColumn('rel_x_id', 'integer', 10, array()); - } - - public function setUp() { - - } +class RelY extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->setTableName('rel_y'); + $this->hasColumn('name', 'string', 25, array()); + $this->hasColumn('rel_x_id', 'integer', 10, array()); + } + public function setUp() + { + } } diff --git a/tests/Ticket/1257TestCase.php b/tests/Ticket/1257TestCase.php index 29e769e09..6c6c6c3eb 100644 --- a/tests/Ticket/1257TestCase.php +++ b/tests/Ticket/1257TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1257_TestCase + * Doctrine_Ticket_1257_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1257_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1257_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -48,10 +54,11 @@ public function testTicket() $user->save(); $q = Doctrine_Query::create() - ->select('u.id, u.username') - ->from('Ticket_1257_User u') - ->leftJoin('u.Role r') - ->addSelect('r.id, r.name, r.description'); + ->select('u.id, u.username') + ->from('Ticket_1257_User u') + ->leftJoin('u.Role r') + ->addSelect('r.id, r.name, r.description') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t2.id AS t2__id, t2.name AS t2__name, t2.description AS t2__description FROM ticket_1257__user t LEFT JOIN ticket_1257__role t2 ON t.role_id = t2.id'); $results = $q->fetchArray(); $this->assertEqual($results[0]['Role']['name'], 'Developer'); @@ -85,4 +92,4 @@ public function setUp() { $this->hasMany('Ticket_1257_User as Users', array('local' => 'id', 'foreign' => 'role_id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1276TestCase.php b/tests/Ticket/1276TestCase.php index b56821524..7045ad0e1 100644 --- a/tests/Ticket/1276TestCase.php +++ b/tests/Ticket/1276TestCase.php @@ -20,25 +20,32 @@ */ /** - * Doctrine_Ticket_1276_TestCase + * Doctrine_Ticket_1276_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1276_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1276_TestCase extends Doctrine_UnitTestCase { public function testTest() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS, true); $q = Doctrine_Query::create() - ->from('User u'); + ->from('User u') + ; $users = $q->fetchArray(); $this->assertTrue(is_array($users)); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS, false); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1277TestCase.php b/tests/Ticket/1277TestCase.php index 54878b933..a5fcc8590 100644 --- a/tests/Ticket/1277TestCase.php +++ b/tests/Ticket/1277TestCase.php @@ -20,36 +20,41 @@ */ /** - * Doctrine_Ticket_1277_TestCase + * Doctrine_Ticket_1277_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1277_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1277_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { - $this->tables = array("T1277_User"); + $this->tables = array('T1277_User'); parent::prepareTables(); } - public function prepareData() + public function prepareData() { - $user1 = new T1277_User(); - $user1->username = "User1"; - $user1->email = null; - $user1->save(); - - $user2 = new T1277_User(); - $user2->username = "User2"; - $user2->email = "some@email"; - $user2->save(); - + $user1 = new T1277_User(); + $user1->username = 'User1'; + $user1->email = null; + $user1->save(); + + $user2 = new T1277_User(); + $user2->username = 'User2'; + $user2->email = 'some@email'; + $user2->save(); } /** @@ -59,30 +64,30 @@ public function prepareData() public function testTicket() { $this->conn->getTable('T1277_User')->clear(); // clear identity map - + $q = new Doctrine_Query(); $u = $q->select('u.id')->from('T1277_User u')->where('u.id=1')->fetchOne(); $this->assertEqual(1, $u->id); - $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); - - // In some other part of code I will query this table again and start making modifications to found records: + $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); + + // In some other part of code I will query this table again and start making modifications to found records: $q = new Doctrine_Query(); $users = $q->select('u.*')->from('T1277_User u')->execute(); - + $this->assertEqual(2, count($users)); foreach ($users as $u) { $this->assertEqual(Doctrine_Record::STATE_CLEAN, $u->state()); - - $u->username = 'new username' . $u->id; - $u->email = 'some' . $u->id . '@email'; - - $this->assertEqual("new username" . $u->id, $u->username); - $this->assertEqual("some" . $u->id . "@email", $u->email); + + $u->username = 'new username'.$u->id; + $u->email = 'some'.$u->id.'@email'; + + $this->assertEqual('new username'.$u->id, $u->username); + $this->assertEqual('some'.$u->id.'@email', $u->email); } } - + /** * Tests that: * 1) a record in PROXY state is still in PROXY state when he is queries again but not with all props @@ -93,32 +98,32 @@ public function testTicket() public function testTicket2() { $this->conn->getTable('T1277_User')->clear(); // clear identity map - + $q = new Doctrine_Query(); $u = $q->select('u.id')->from('T1277_User u')->where('u.id=1')->fetchOne(); $this->assertEqual(1, $u->id); - $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); - - // In some other part of code I will query this table again and start making modifications to found records: + $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); + + // In some other part of code I will query this table again and start making modifications to found records: $q = new Doctrine_Query(); $users = $q->select('u.id, u.username')->from('T1277_User u')->execute(); - + $this->assertEqual(2, count($users)); foreach ($users as $u) { $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); - - $u->username = 'new username' . $u->id; // modify - $u->email = 'some' . $u->id . '@email'; // triggers load() to fill uninitialized props - - $this->assertEqual("new username" . $u->id, $u->username); - $this->assertEqual("some" . $u->id . "@email", $u->email); - + + $u->username = 'new username'.$u->id; // modify + $u->email = 'some'.$u->id.'@email'; // triggers load() to fill uninitialized props + + $this->assertEqual('new username'.$u->id, $u->username); + $this->assertEqual('some'.$u->id.'@email', $u->email); + $this->assertEqual(Doctrine_Record::STATE_DIRTY, $u->state()); } } - + /** * Tests that: * 1) a record in PROXY state is still in PROXY state when he is queries again but not with all props @@ -128,14 +133,14 @@ public function testTicket2() public function testTicket3() { $this->conn->getTable('T1277_User')->clear(); // clear identity map - + $q = new Doctrine_Query(); $u = $q->select('u.id')->from('T1277_User u')->where('u.id=1')->fetchOne(); $this->assertEqual(1, $u->id); - $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); - - // In some other part of code I will query this table again and start making modifications to found records: + $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); + + // In some other part of code I will query this table again and start making modifications to found records: $q = new Doctrine_Query(); $users = $q->select('u.id, u.username')->from('T1277_User u')->execute(); @@ -143,20 +148,20 @@ public function testTicket3() foreach ($users as $u) { $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); - - if ($u->id == 1) { - $this->assertEqual("User1", $u->username); + + if (1 == $u->id) { + $this->assertEqual('User1', $u->username); $u->email; // triggers load() } else { - $this->assertEqual("User2", $u->username); - $this->assertEqual("some@email", $u->email); + $this->assertEqual('User2', $u->username); + $this->assertEqual('some@email', $u->email); } - + $this->assertEqual(Doctrine_Record::STATE_CLEAN, $u->state()); } } - - /** + + /* * Fails due to the PROXY concept being flawed by design. * * Tests that: @@ -166,19 +171,19 @@ public function testTicket3() /*public function testTicket4() { $this->conn->getTable('T1277_User')->clear(); // clear identity map - + $q = new Doctrine_Query(); $u = $q->select('u.id, u.username')->from('T1277_User u')->where('u.id=1')->fetchOne(); $this->assertEqual(1, $u->id); $this->assertEqual(Doctrine_Record::STATE_PROXY, $u->state()); - + $u->username = "superman"; - // In some other part of code I will query this table again and start making modifications to found records: + // In some other part of code I will query this table again and start making modifications to found records: $q = new Doctrine_Query(); $users = $q->select('u.*')->from('T1277_User u')->execute(); - + $this->assertEqual(2, count($users)); foreach ($users as $u) { @@ -192,7 +197,6 @@ public function testTicket3() } } }*/ - } // This is the User table where I have 2 records: @@ -201,31 +205,29 @@ public function testTicket3() // #2 User2 some@email class T1277_User extends Doctrine_Record { - public function setTableDefinition () + public function setTableDefinition() { - $this->setTableName("t1277_users"); - - $this->hasColumns (array( + $this->setTableName('t1277_users'); + $this->hasColumns(array( 'id' => array( - 'type' => 'integer', - 'length' => 4, - 'notnull' => true, - 'autoincrement' => true, - 'primary' => true + 'type' => 'integer', + 'length' => 4, + 'notnull' => true, + 'autoincrement' => true, + 'primary' => true, ), 'username' => array( - 'type' => 'string', - 'length' => 50 + 'type' => 'string', + 'length' => 50, ), 'email' => array( - 'type' => 'string', - 'length' => 50, - 'default' => null, + 'type' => 'string', + 'length' => 50, + 'default' => null, ), )); } } - diff --git a/tests/Ticket/1280TestCase.php b/tests/Ticket/1280TestCase.php index b2ba33368..5e3a70df4 100644 --- a/tests/Ticket/1280TestCase.php +++ b/tests/Ticket/1280TestCase.php @@ -20,21 +20,27 @@ */ /** - * Doctrine_Ticket_1280_TestCase + * Doctrine_Ticket_1280_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1280_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { - //$this->tables = array(); + // $this->tables = array(); $this->tables[] = 'Ticket_1280_User'; $this->tables[] = 'Ticket_1280_Group'; parent::prepareTables(); @@ -52,11 +58,11 @@ public function testTicket() $user->save(); $this->assertEqual($user->group_id, $group->id); - + try { $user->Group = null; $user->save(); - + $this->assertEqual($user->group_id, null); $this->pass(); @@ -71,7 +77,7 @@ class Ticket_1280_User extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('group_id', 'integer', 20, array( - 'notnull' => false, 'default' => null + 'notnull' => false, 'default' => null, )); $this->hasColumn('name', 'string', 255); } @@ -80,12 +86,11 @@ public function setUp() { $this->hasOne('Ticket_1280_Group as Group', array( 'local' => 'group_id', - 'foreign' => 'id' + 'foreign' => 'id', )); } } - class Ticket_1280_Group extends Doctrine_Record { public function setTableDefinition() @@ -97,7 +102,7 @@ public function setUp() { $this->hasMany('Ticket_1280_User as Users', array( 'local' => 'id', - 'foreign' => 'group_id' + 'foreign' => 'group_id', )); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1281TestCase.php b/tests/Ticket/1281TestCase.php index d21abbd61..48ea88cc9 100644 --- a/tests/Ticket/1281TestCase.php +++ b/tests/Ticket/1281TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1281_TestCase + * Doctrine_Ticket_1281_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1281_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1281_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -44,4 +50,4 @@ public function testTest() // old values $this->assertEqual($user->getModified(true), array('name' => 'zYne')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1289TestCase.php b/tests/Ticket/1289TestCase.php index 789698991..2423a3343 100644 --- a/tests/Ticket/1289TestCase.php +++ b/tests/Ticket/1289TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1289_TestCase + * Doctrine_Ticket_1289_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1289_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1289_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -63,4 +69,4 @@ public function setUp() { $this->actAs('Versionable'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1296TestCase.php b/tests/Ticket/1296TestCase.php index b84f94754..93012544b 100644 --- a/tests/Ticket/1296TestCase.php +++ b/tests/Ticket/1296TestCase.php @@ -20,59 +20,66 @@ */ /** - * Doctrine_Ticket_1296_TestCase + * Doctrine_Ticket_1296_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1296_TestCase extends Doctrine_UnitTestCase { - public function prepareData() { + public function prepareData() + { $org = new NewTicket_Organization(); $org->name = 'Inc.'; $org->save(); } - + public function prepareTables() { $this->tables = array( - 'NewTicket_Organization', - 'NewTicket_Role' - ); + 'NewTicket_Organization', + 'NewTicket_Role', + ); parent::prepareTables(); } - - public function testAddDuplicateOrganisation () + + public function testAddDuplicateOrganisation() { $this->assertEqual(0, $this->conn->transaction->getTransactionLevel()); $this->assertEqual(0, $this->conn->transaction->getInternalTransactionLevel()); try { $this->conn->beginTransaction(); } catch (Exception $e) { - $this->fail("Transaction failed to start."); + $this->fail('Transaction failed to start.'); } - + $this->assertEqual(1, $this->conn->transaction->getTransactionLevel()); $this->assertEqual(0, $this->conn->transaction->getInternalTransactionLevel()); - + $org = new NewTicket_Organization(); $org->name = 'Inc.'; try { $org->save(); - $this->fail("Unique violation not reported."); + $this->fail('Unique violation not reported.'); } catch (Exception $e) { $this->assertEqual(1, $this->conn->transaction->getTransactionLevel()); $this->assertEqual(0, $this->conn->transaction->getInternalTransactionLevel()); $this->conn->rollback(); } - + $this->assertEqual(0, $this->conn->transaction->getTransactionLevel()); $this->assertEqual(0, $this->conn->transaction->getInternalTransactionLevel()); - + try { $this->assertEqual(0, $this->conn->transaction->getTransactionLevel()); $this->assertEqual(0, $this->conn->transaction->getInternalTransactionLevel()); @@ -86,20 +93,20 @@ public function testAddDuplicateOrganisation () $this->assertEqual(0, $this->conn->transaction->getInternalTransactionLevel()); } - public function testAddRole () + public function testAddRole() { $this->assertEqual(0, $this->conn->transaction->getTransactionLevel()); $this->assertEqual(0, $this->conn->transaction->getInternalTransactionLevel()); - + try { $this->conn->beginTransaction(); } catch (Exception $e) { - $this->fail("Transaction failed to start."); + $this->fail('Transaction failed to start.'); } - + $this->assertEqual(1, $this->conn->transaction->getTransactionLevel()); $this->assertEqual(0, $this->conn->transaction->getInternalTransactionLevel()); - + $r = new NewTicket_Role(); $r->name = 'foo'; try { @@ -123,40 +130,42 @@ public function testAddRole () } } } - -class NewTicket_Organization extends Doctrine_Record { - public function setTableDefinition() { + +class NewTicket_Organization extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', 4, array( - 'autoincrement' => true, - 'notnull' => true, - 'primary' => true - )); + 'autoincrement' => true, + 'notnull' => true, + 'primary' => true, + )); $this->hasColumn('name', 'string', 255, array( - 'notnull' => true, - 'unique' => true - )); + 'notnull' => true, + 'unique' => true, + )); } } -class NewTicket_Role extends Doctrine_Record { - public function setTableDefinition() { +class NewTicket_Role extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', 4, array( - 'autoincrement' => true, - 'notnull' => true, - 'primary' => true - )); + 'autoincrement' => true, + 'notnull' => true, + 'primary' => true, + )); $this->hasColumn('name', 'string', 30, array( - 'notnull' => true, - 'unique' => true - )); + 'notnull' => true, + 'unique' => true, + )); } } -class NewTicket_User { - public function addOrganization ($name) +class NewTicket_User +{ + public function addOrganization($name) { - } } - - \ No newline at end of file diff --git a/tests/Ticket/1304TestCase.php b/tests/Ticket/1304TestCase.php index 3448d7c99..d06c54bcc 100644 --- a/tests/Ticket/1304TestCase.php +++ b/tests/Ticket/1304TestCase.php @@ -20,71 +20,79 @@ */ /** - * Doctrine_Ticket_1304_TestCase + * Doctrine_Ticket_1304_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1304_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { - $this->tables[] = 'Doctrine_Ticket_1304_Slug'; - parent::prepareTables(); - } - - public function testTicket() - { - // run 1 - try { - $r = new Doctrine_Ticket_1304_Slug(); - $r->Translation['en']->title = 'Title'; - $r->Translation['en']->content = 'Content'; - $r->save(); - } catch (Exception $e) { - $this->fail($e->getMessage()); - } - $this->assertEqual('title', $r->Translation['en']->slug); +class Doctrine_Ticket_1304_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { + $this->tables[] = 'Doctrine_Ticket_1304_Slug'; + parent::prepareTables(); + } - // run 2 - try { - $r = new Doctrine_Ticket_1304_Slug(); - $r->Translation['en']->title = 'Title'; - $r->Translation['en']->content = 'Content'; - $r->save(); - } catch (Exception $e) { - $this->fail($e->getMessage()); - } - $this->assertEqual('title-1', $r->Translation['en']->slug); + public function testTicket() + { + // run 1 + try { + $r = new Doctrine_Ticket_1304_Slug(); + $r->Translation['en']->title = 'Title'; + $r->Translation['en']->content = 'Content'; + $r->save(); + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + $this->assertEqual('title', $r->Translation['en']->slug); - // run 3 - try { - $r = new Doctrine_Ticket_1304_Slug(); - $r->Translation['en']->title = 'Title'; - $r->Translation['en']->content = 'Content'; - $r->save(); - } catch (Exception $e) { - $this->fail($e->getMessage()); - } - $this->assertEqual('title-2', $r->Translation['en']->slug); - } + // run 2 + try { + $r = new Doctrine_Ticket_1304_Slug(); + $r->Translation['en']->title = 'Title'; + $r->Translation['en']->content = 'Content'; + $r->save(); + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + $this->assertEqual('title-1', $r->Translation['en']->slug); + + // run 3 + try { + $r = new Doctrine_Ticket_1304_Slug(); + $r->Translation['en']->title = 'Title'; + $r->Translation['en']->content = 'Content'; + $r->save(); + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + $this->assertEqual('title-2', $r->Translation['en']->slug); + } } class Doctrine_Ticket_1304_Slug extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('title', 'string', 255, array('type' => 'string', 'length' => '255')); - $this->hasColumn('content', 'string', null, array('type' => 'string')); - } + public function setTableDefinition() + { + $this->hasColumn('title', 'string', 255, array('type' => 'string', 'length' => '255')); + $this->hasColumn('content', 'string', null, array('type' => 'string')); + } - public function setUp() - { - $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'title', 1 => 'content'))); - $sluggable1 = new Doctrine_Template_Sluggable(array('fields' => array(0 => 'title'), 'indexName' => 'i18n_sluggable_test')); - $i18n0->addChild($sluggable1); - $this->actAs($i18n0); - } -} \ No newline at end of file + public function setUp() + { + $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'title', 1 => 'content'))); + $sluggable1 = new Doctrine_Template_Sluggable(array('fields' => array(0 => 'title'), 'indexName' => 'i18n_sluggable_test')); + $i18n0->addChild($sluggable1); + $this->actAs($i18n0); + } +} diff --git a/tests/Ticket/1305TestCase.php b/tests/Ticket/1305TestCase.php index 0b009da44..af14ecb19 100644 --- a/tests/Ticket/1305TestCase.php +++ b/tests/Ticket/1305TestCase.php @@ -20,50 +20,54 @@ */ /** - * Doctrine_Ticket_1305_TestCase + * Doctrine_Ticket_1305_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1305_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() + public function prepareTables() { $this->tables[] = 'Ticket_1305_Record'; parent::prepareTables(); } - public function testTicket() { $t = new Ticket_1305_Record(); $t->save(); - + $this->assertEqual($t['name'], 'test'); $t->name = 'foo'; $t->save(); - + $this->assertEqual($t['name'], 'foo'); $t->name = null; $t->save(); - + $this->assertEqual($t['name'], 'test'); } } - class Ticket_1305_Record extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('name', 'string', 255, array('notnull' => true, 'default' => 'test')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1307TestCase.php b/tests/Ticket/1307TestCase.php index e8792caf5..a4c533ddf 100644 --- a/tests/Ticket/1307TestCase.php +++ b/tests/Ticket/1307TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1307_TestCase + * Doctrine_Ticket_1307_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1307_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1307_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -53,4 +59,4 @@ public function setTableDefinition() $this->hasColumn('username', 'string', 255); $this->hasColumn('password', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1315TestCase.php b/tests/Ticket/1315TestCase.php index c1cbafe56..f8f1350c2 100644 --- a/tests/Ticket/1315TestCase.php +++ b/tests/Ticket/1315TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1315_TestCase + * Doctrine_Ticket_1315_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1315_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1315_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -40,7 +46,8 @@ public function testTest() try { $q = Doctrine_Query::create() - ->from('User u'); + ->from('User u') + ; $users = $q->execute(); $this->fail(); @@ -52,7 +59,8 @@ public function testTest() try { $q = Doctrine_Query::create() - ->from('User u'); + ->from('User u') + ; $users = $q->execute(); $this->pass(); @@ -66,8 +74,8 @@ public function testTest() class Ticket_1315_Listener extends Doctrine_Record_Listener { - public function preDqlSelect(Doctrine_Event $event) - { - throw new Doctrine_Exception('Test'); - } -} \ No newline at end of file + public function preDqlSelect(Doctrine_Event $event) + { + throw new Doctrine_Exception('Test'); + } +} diff --git a/tests/Ticket/1323TestCase.php b/tests/Ticket/1323TestCase.php index 6b9af9581..0ea154491 100644 --- a/tests/Ticket/1323TestCase.php +++ b/tests/Ticket/1323TestCase.php @@ -1,103 +1,112 @@ tables = array(); - $this->tables[] = "T1323User"; - $this->tables[] = "T1323UserReference"; + $this->tables[] = 'T1323User'; + $this->tables[] = 'T1323UserReference'; parent::prepareTables(); } - - public function prepareData() {} + + public function prepareData() + { + } public function resetData() { - $q = Doctrine_Query::create(); - $q->delete()->from("T1323UserReference")->execute(); - $q = Doctrine_Query::create(); - $q->delete()->from("T1323User")->execute(); - - $m = new T1323User(); - $m->name = "Mother"; - $m->save(); - $f = new T1323User(); - $f->name = "Father"; - $f->save(); - $s = new T1323User(); - $s->name = "Son"; - $s->save(); - $d = new T1323User(); - $d->name = "Daughter"; - $d->save(); - $gf = new T1323User(); - $gf->name = "Grandfather"; - $gf->save(); - $gm = new T1323User(); - $gm->name = "Grandmother"; - $gm->save(); - - $f->Children[] = $s; - $f->Children[] = $d; - - $f->Parents[] = $gf; - $f->Parents[] = $gm; - - $f->save(); - - $m->Children[] = $s; - $m->Children[] = $d; - - $m->save(); + $q = Doctrine_Query::create(); + $q->delete()->from('T1323UserReference')->execute(); + $q = Doctrine_Query::create(); + $q->delete()->from('T1323User')->execute(); + + $m = new T1323User(); + $m->name = 'Mother'; + $m->save(); + $f = new T1323User(); + $f->name = 'Father'; + $f->save(); + $s = new T1323User(); + $s->name = 'Son'; + $s->save(); + $d = new T1323User(); + $d->name = 'Daughter'; + $d->save(); + $gf = new T1323User(); + $gf->name = 'Grandfather'; + $gf->save(); + $gm = new T1323User(); + $gm->name = 'Grandmother'; + $gm->save(); + $f->Children[] = $s; + $f->Children[] = $d; + + $f->Parents[] = $gf; + $f->Parents[] = $gm; + + $f->save(); + + $m->Children[] = $s; + $m->Children[] = $d; + + $m->save(); } - - public function testRelationsAreCorrect() { + + public function testRelationsAreCorrect() + { $this->resetData(); - - $f = Doctrine_Core::getTable("T1323User")->findOneByName("Father"); + + $f = Doctrine_Core::getTable('T1323User')->findOneByName('Father'); $childLinks = $f->childLinks; $this->assertEqual(2, count($childLinks)); $this->assertEqual($f->id, $childLinks[0]->parent_id); $this->assertEqual($f->id, $childLinks[1]->parent_id); - + $parentLinks = $f->parentLinks; $this->assertEqual(2, count($parentLinks)); $this->assertEqual($f->id, $parentLinks[0]->child_id); $this->assertEqual($f->id, $parentLinks[1]->child_id); - - $m = Doctrine_Core::getTable("T1323User")->findOneByName("Mother"); + + $m = Doctrine_Core::getTable('T1323User')->findOneByName('Mother'); $childLinks = $m->childLinks; $this->assertEqual(2, count($childLinks)); $this->assertEqual($m->id, $childLinks[0]->parent_id); $this->assertEqual($m->id, $childLinks[1]->parent_id); - + $parentLinks = $m->parentLinks; $this->assertEqual(0, count($parentLinks)); - - $s = Doctrine_Core::getTable("T1323User")->findOneByName("Son"); + + $s = Doctrine_Core::getTable('T1323User')->findOneByName('Son'); $childLinks = $s->childLinks; $this->assertEqual(0, count($childLinks)); $parentLinks = $s->parentLinks; $this->assertEqual(2, count($parentLinks)); $this->assertEqual($s->id, $parentLinks[0]->child_id); $this->assertEqual($s->id, $parentLinks[1]->child_id); - - $d = Doctrine_Core::getTable("T1323User")->findOneByName("Daughter"); + + $d = Doctrine_Core::getTable('T1323User')->findOneByName('Daughter'); $childLinks = $d->childLinks; $this->assertEqual(0, count($childLinks)); $parentLinks = $d->parentLinks; $this->assertEqual(2, count($parentLinks)); $this->assertEqual($d->id, $parentLinks[0]->child_id); $this->assertEqual($d->id, $parentLinks[1]->child_id); - - $gm = Doctrine_Core::getTable("T1323User")->findOneByName("Grandmother"); + + $gm = Doctrine_Core::getTable('T1323User')->findOneByName('Grandmother'); $childLinks = $gm->childLinks; $this->assertEqual(1, count($childLinks)); $this->assertEqual($gm->id, $childLinks[0]->parent_id); $parentLinks = $gm->parentLinks; $this->assertEqual(0, count($parentLinks)); - - $gf = Doctrine_Core::getTable("T1323User")->findOneByName("Grandfather"); + + $gf = Doctrine_Core::getTable('T1323User')->findOneByName('Grandfather'); $childLinks = $gf->childLinks; $this->assertEqual(1, count($childLinks)); $this->assertEqual($gf->id, $childLinks[0]->parent_id); @@ -105,50 +114,49 @@ public function testRelationsAreCorrect() { $this->assertEqual(0, count($parentLinks)); } - /** - * this test will fail - */ - public function testWithShow() { - $this->resetData(); - - T1323User::showAllRelations(); - $this->runTests(); - } - - /** - * this test will pass - */ - public function testWithoutShow() { - $this->resetData(); - - $this->runTests(); - } - - - public function runTests() { - - // change "Father"'s name... - $f = Doctrine_Core::getTable("T1323User")->findOneByName("Father"); - $f->name = "Dad"; - $f->save(); - - /* just playing; makes no difference: - remove "Dad"'s relation to "Son"... */ - //$s = Doctrine_Core::getTable("T1323User")->findOneByName("Son"); - //$f->unlink("Children", array($s->id)); - //$f->save(); - - $relations = Doctrine_Core::getTable("T1323UserReference")->findAll(); - foreach ($relations as $relation) { - /* never directly touched any relation; so no user should have - himself as parent or child */ - $this->assertNotEqual($relation->parent_id, $relation->child_id); - } + /** + * this test will fail. + */ + public function testWithShow() + { + $this->resetData(); + + T1323User::showAllRelations(); + $this->runTests(); + } + + /** + * this test will pass. + */ + public function testWithoutShow() + { + $this->resetData(); + + $this->runTests(); + } + + public function runTests() + { + // change "Father"'s name... + $f = Doctrine_Core::getTable('T1323User')->findOneByName('Father'); + $f->name = 'Dad'; + $f->save(); + + /* just playing; makes no difference: + remove "Dad"'s relation to "Son"... */ + // $s = Doctrine_Core::getTable("T1323User")->findOneByName("Son"); + // $f->unlink("Children", array($s->id)); + // $f->save(); + + $relations = Doctrine_Core::getTable('T1323UserReference')->findAll(); + foreach ($relations as $relation) { + /* never directly touched any relation; so no user should have + himself as parent or child */ + $this->assertNotEqual($relation->parent_id, $relation->child_id); + } } } - - class T1323User extends Doctrine_Record { public function setTableDefinition() @@ -159,36 +167,37 @@ public function setTableDefinition() public function setUp() { $this->hasMany('T1323User as Parents', array('local' => 'child_id', - 'foreign' => 'parent_id', - 'refClass' => 'T1323UserReference', - 'refClassRelationAlias' => 'childLinks' - )); + 'foreign' => 'parent_id', + 'refClass' => 'T1323UserReference', + 'refClassRelationAlias' => 'childLinks', + )); $this->hasMany('T1323User as Children', array('local' => 'parent_id', - 'foreign' => 'child_id', - 'refClass' => 'T1323UserReference', - 'refClassRelationAlias' => 'parentLinks' - )); + 'foreign' => 'child_id', + 'refClass' => 'T1323UserReference', + 'refClassRelationAlias' => 'parentLinks', + )); } - + /** - * just a little function to show all users and their relations - */ - public static function showAllRelations() { - $users = Doctrine_Core::getTable("T1323User")->findAll(); - - //echo "=========================================
".PHP_EOL; - //echo "list of all existing users and their relations:
".PHP_EOL; - //echo "=========================================

".PHP_EOL.PHP_EOL; - + * just a little function to show all users and their relations. + */ + public static function showAllRelations() + { + $users = Doctrine_Core::getTable('T1323User')->findAll(); + + // echo "=========================================
".PHP_EOL; + // echo "list of all existing users and their relations:
".PHP_EOL; + // echo "=========================================

".PHP_EOL.PHP_EOL; + foreach ($users as $user) { $parents = $user->Parents; $children = $user->Children; - + /*echo "user: "; echo $user->name; echo PHP_EOL."
"; - + echo "parents:"; echo PHP_EOL."
"; foreach ($parents as $parent) { @@ -196,7 +205,7 @@ public static function showAllRelations() { echo PHP_EOL."
"; } echo PHP_EOL."
"; - + echo "children:"; echo PHP_EOL."
"; foreach ($children as $child) { @@ -214,12 +223,8 @@ class T1323UserReference extends Doctrine_Record { public function setTableDefinition() { - //$this->hasColumn('id', 'integer', null, array('primary' => true, 'autoincrement' => true)); + // $this->hasColumn('id', 'integer', null, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('parent_id', 'integer', null, array('primary' => true)); $this->hasColumn('child_id', 'integer', null, array('primary' => true)); } } - - - -?> diff --git a/tests/Ticket/1323b2TestCase.php b/tests/Ticket/1323b2TestCase.php index b3db0cf95..c6ea05c70 100644 --- a/tests/Ticket/1323b2TestCase.php +++ b/tests/Ticket/1323b2TestCase.php @@ -1,96 +1,106 @@ tables = array(); - $this->tables[] = "Concept"; - $this->tables[] = "ConceptRelation"; +/** + * @internal + * + * @coversNothing + */ +class Doctrine_Ticket_1323b2_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { + $this->tables = array(); + $this->tables[] = 'Concept'; + $this->tables[] = 'ConceptRelation'; parent::prepareTables(); } - public function prepareData() {} - + public function prepareData() + { + } + /** - * setting some polyhierarchical relations + * setting some polyhierarchical relations. */ public function resetData() { $q = Doctrine_Query::create(); - $q->delete()->from("ConceptRelation")->execute(); + $q->delete()->from('ConceptRelation')->execute(); $q = Doctrine_Query::create(); - $q->delete()->from("Concept")->execute(); + $q->delete()->from('Concept')->execute(); - $concepts = array("Woodworking", "Metalworking", - "Submetalworking 1", "Submetalworking 2", - "Subwoodworking 1", "Subwoodworking 2", - "Surfaceworking", - "drilled", "welded", "turned"); + $concepts = array('Woodworking', 'Metalworking', + 'Submetalworking 1', 'Submetalworking 2', + 'Subwoodworking 1', 'Subwoodworking 2', + 'Surfaceworking', + 'drilled', 'welded', 'turned'); - foreach ($concepts as $concept) { + foreach ($concepts as $concept) { $c = new Concept(); $c->identifier = $concept; - $c->status = "approved"; - $c->source = "test"; - $c->created = "today"; - $c->creator = "me"; - $c->creationIdentifier = "nothing"; + $c->status = 'approved'; + $c->source = 'test'; + $c->created = 'today'; + $c->creator = 'me'; + $c->creationIdentifier = 'nothing'; $c->save(); } - $w = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Woodworking"); - $sw1 = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Subwoodworking 1"); - $sw2 = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Subwoodworking 2"); - $m = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Metalworking"); - $sm1 = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Submetalworking 1"); - $sm2 = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Submetalworking 2"); - $d = Doctrine_Core::getTable("Concept")->findOneByIdentifier("drilled"); - $wd = Doctrine_Core::getTable("Concept")->findOneByIdentifier("welded"); - $t = Doctrine_Core::getTable("Concept")->findOneByIdentifier("turned"); - $s = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Surfaceworking"); - + $w = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Woodworking'); + $sw1 = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Subwoodworking 1'); + $sw2 = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Subwoodworking 2'); + $m = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Metalworking'); + $sm1 = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Submetalworking 1'); + $sm2 = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Submetalworking 2'); + $d = Doctrine_Core::getTable('Concept')->findOneByIdentifier('drilled'); + $wd = Doctrine_Core::getTable('Concept')->findOneByIdentifier('welded'); + $t = Doctrine_Core::getTable('Concept')->findOneByIdentifier('turned'); + $s = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Surfaceworking'); + $w->narrowerConcepts[] = $sw1; $w->narrowerConcepts[] = $sw2; $w->save(); - + $sw1->narrowerConcepts[] = $s; $sw1->narrowerConcepts[] = $d; $sw1->narrowerConcepts[] = $t; $sw1->save(); - + $sw2->narrowerConcepts[] = $d; $sw2->save(); - + $m->narrowerConcepts[] = $sm1; $m->narrowerConcepts[] = $sm2; $m->save(); - + $sm1->narrowerConcepts[] = $wd; $sm1->narrowerConcepts[] = $s; $sm1->save(); - + $sm2->narrowerConcepts[] = $t; $sm2->save(); - + $s->narrowerConcepts[] = $t; $s->narrowerConcepts[] = $d; $s->save(); } /** - * this test will fail ... - */ - public function testFAIL() { + * this test will fail ... + */ + public function testFAIL() + { $this->resetData(); ConceptRelation::showAllRelations(); - //lets count all relations + // lets count all relations $relCount = ConceptRelation::countAll(); - - $oRecord = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Surfaceworking"); - $oRecord->identifier = "MySurfaceworking"; + + $oRecord = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Surfaceworking'); + $oRecord->identifier = 'MySurfaceworking'; $oRecord->save(); - + ConceptRelation::showAllRelations(); - + // we did not change any relations, so we assume this test to be passed $this->assertEqual(ConceptRelation::countAll(), $relCount); // -> where do the additional relations come from ??? @@ -99,118 +109,110 @@ public function testFAIL() { /* * ... while this test is ok (since we dont save anything) */ - public function testOK() { + public function testOK() + { $this->resetData(); - + ConceptRelation::showAllRelations(); - //lets count all relations + // lets count all relations $relCount = ConceptRelation::countAll(); - - $oRecord = Doctrine_Core::getTable("Concept")->findOneByIdentifier("Surfaceworking"); - $oRecord->identifier = "MySurfaceworking"; + + $oRecord = Doctrine_Core::getTable('Concept')->findOneByIdentifier('Surfaceworking'); + $oRecord->identifier = 'MySurfaceworking'; // $oRecord->save(); --> only this line differs !!! - + ConceptRelation::showAllRelations(); - + // we did not change any relations, so we assume this test to be passed $this->assertEqual(ConceptRelation::countAll(), $relCount); } } - - - - - - - /** - * This class has been auto-generated by the Doctrine ORM Framework + * This class has been auto-generated by the Doctrine ORM Framework. */ class BaseConcept extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('concepts'); - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true, 'type' => 'integer', 'length' => '4')); - $this->hasColumn('vok_id as vokId', 'integer', 4, array('type' => 'integer', 'length' => '4')); - $this->hasColumn('identifier', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); - $this->hasColumn('status', 'string', 20, array('notnull' => true, 'type' => 'string', 'length' => '20')); - $this->hasColumn('source', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); - $this->hasColumn('created_on as created', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); - $this->hasColumn('creator', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); - $this->hasColumn('creation_identifier as creationIdentifier', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); - - $this->option('type', 'INNODB'); - $this->option('collate', 'utf8_unicode_ci'); - $this->option('charset', 'utf8'); - } - - public function setUp() - { - $this->hasMany('Concept as broaderConcepts', array('refClass' => 'ConceptRelation', - 'local' => 'concept_id', - 'foreign' => 'parent_concept_id', - 'refClassRelationAlias' => 'broaderLinks')); - - - $this->hasMany('Concept as narrowerConcepts', array('refClass' => 'ConceptRelation', - 'local' => 'parent_concept_id', - 'foreign' => 'concept_id', - 'refClassRelationAlias' => 'narrowerLinks')); - } + public function setTableDefinition() + { + $this->setTableName('concepts'); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true, 'type' => 'integer', 'length' => '4')); + $this->hasColumn('vok_id as vokId', 'integer', 4, array('type' => 'integer', 'length' => '4')); + $this->hasColumn('identifier', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); + $this->hasColumn('status', 'string', 20, array('notnull' => true, 'type' => 'string', 'length' => '20')); + $this->hasColumn('source', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); + $this->hasColumn('created_on as created', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); + $this->hasColumn('creator', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); + $this->hasColumn('creation_identifier as creationIdentifier', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); + + $this->option('type', 'INNODB'); + $this->option('collate', 'utf8_unicode_ci'); + $this->option('charset', 'utf8'); + } + + public function setUp() + { + $this->hasMany('Concept as broaderConcepts', array('refClass' => 'ConceptRelation', + 'local' => 'concept_id', + 'foreign' => 'parent_concept_id', + 'refClassRelationAlias' => 'broaderLinks')); + + $this->hasMany('Concept as narrowerConcepts', array('refClass' => 'ConceptRelation', + 'local' => 'parent_concept_id', + 'foreign' => 'concept_id', + 'refClassRelationAlias' => 'narrowerLinks')); + } } /** - * This class has been auto-generated by the Doctrine ORM Framework + * This class has been auto-generated by the Doctrine ORM Framework. */ class BaseConceptRelation extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('concepts_x_concepts'); - $this->hasColumn('concept_id as conceptId', 'integer', 4, array('type' => 'integer', 'notnull' => true, 'length' => '4', 'primary' => true)); - $this->hasColumn('parent_concept_id as conceptIdParent', 'integer', 4, array('type' => 'integer', 'notnull' => true, 'length' => '4', 'primary' => true)); - - $this->option('type', 'INNODB'); - $this->option('collate', 'utf8_unicode_ci'); - $this->option('charset', 'utf8'); - } - - public function setUp() - { - $this->hasOne('Concept as concept', array('local' => 'concept_id', - 'foreign' => 'id')); - - $this->hasOne('Concept as broaderConcept', array('local' => 'parent_concept_id', - 'foreign' => 'id')); - } -} + public function setTableDefinition() + { + $this->setTableName('concepts_x_concepts'); + $this->hasColumn('concept_id as conceptId', 'integer', 4, array('type' => 'integer', 'notnull' => true, 'length' => '4', 'primary' => true)); + $this->hasColumn('parent_concept_id as conceptIdParent', 'integer', 4, array('type' => 'integer', 'notnull' => true, 'length' => '4', 'primary' => true)); + + $this->option('type', 'INNODB'); + $this->option('collate', 'utf8_unicode_ci'); + $this->option('charset', 'utf8'); + } + public function setUp() + { + $this->hasOne('Concept as concept', array('local' => 'concept_id', + 'foreign' => 'id')); + + $this->hasOne('Concept as broaderConcept', array('local' => 'parent_concept_id', + 'foreign' => 'id')); + } +} /** - * This class has been auto-generated by the Doctrine ORM Framework + * This class has been auto-generated by the Doctrine ORM Framework. */ class Concept extends BaseConcept { - } /** - * This class has been auto-generated by the Doctrine ORM Framework + * This class has been auto-generated by the Doctrine ORM Framework. */ class ConceptRelation extends BaseConceptRelation { - public static function showAllRelations() { + public static function showAllRelations() + { /*$relations = Doctrine_Core::getTable("ConceptRelation")->findAll(); foreach ($relations as $relation) { echo $relation->broaderConcept->identifier."(".$relation->conceptIdParent.")->".$relation->concept->identifier."(".$relation->conceptId.")\n
"; } echo "\n\n

";*/ } - - public static function countAll() { - return Doctrine_Core::getTable("ConceptRelation")->count(); + + public static function countAll() + { + return Doctrine_Core::getTable('ConceptRelation')->count(); } } -?> diff --git a/tests/Ticket/1325TestCase.php b/tests/Ticket/1325TestCase.php index d1847e46e..5176fe39a 100644 --- a/tests/Ticket/1325TestCase.php +++ b/tests/Ticket/1325TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1325_TestCase + * Doctrine_Ticket_1325_TestCase. * - * @package Doctrine * @author Andrea Baron * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1325_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1325_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -44,10 +50,11 @@ public function testShouldInsertWithoutAlias() $elem = new Ticket_1325_TableName_NoAlias(); $elem->id = 1; $elem->save(); - + $res = Doctrine_Query::create() ->from('Ticket_1325_TableName_NoAlias') - ->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY); + ->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY) + ; $now = time(); $time = strtotime($res['event_date']); @@ -59,10 +66,11 @@ public function testShouldInsertWithAlias() $elem = new Ticket_1325_TableName_Aliased(); $elem->id = 1; $elem->save(); - + $res = Doctrine_Query::create() ->from('Ticket_1325_TableName_Aliased') - ->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY); + ->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY) + ; $now = time(); $time = strtotime($res['eventDate']); @@ -94,4 +102,4 @@ public function setUp() { $this->actAs(new Doctrine_Template_Timestampable(array('created' => array('name' => 'event_date', 'alias' => 'eventDate', 'type' => 'timestamp'), 'updated' => array('disabled' => true)))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1326TestCase.php b/tests/Ticket/1326TestCase.php index 6fa1240af..e9398e425 100644 --- a/tests/Ticket/1326TestCase.php +++ b/tests/Ticket/1326TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1326_TestCase + * Doctrine_Ticket_1326_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1326_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1326_TestCase extends Doctrine_UnitTestCase { public function createTestData() { @@ -61,4 +67,4 @@ public function testTest() $nbDeleted = Doctrine_Query::create()->delete()->from('User')->where('loginname = ?', array('foo2'))->execute(); $this->assertEqual($nbDeleted, 1); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1335TestCase.php b/tests/Ticket/1335TestCase.php index 5ad21b0ef..532504737 100644 --- a/tests/Ticket/1335TestCase.php +++ b/tests/Ticket/1335TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1335_TestCase + * Doctrine_Ticket_1335_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1335_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1335_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -42,4 +48,4 @@ public function testTest() $this->pass(); } } -} \ No newline at end of file +} diff --git a/tests/Ticket/1338TestCase.php b/tests/Ticket/1338TestCase.php index 95fe70dc8..7f56b992f 100644 --- a/tests/Ticket/1338TestCase.php +++ b/tests/Ticket/1338TestCase.php @@ -20,34 +20,41 @@ */ /** - * Doctrine_Ticket_1338_TestCase + * Doctrine_Ticket_1338_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1338_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1338_TestCase extends Doctrine_UnitTestCase { public function testTest() { $q = Doctrine_Query::create() - ->from('User u'); + ->from('User u') + ; $users = $q->execute(); $array = $users->toKeyValueArray('id', 'name'); $this->assertEqual($array, array( - 4 => 'zYne', - 5 => 'Arnold Schwarzenegger', - 6 => 'Michael Caine', - 7 => 'Takeshi Kitano', - 8 => 'Sylvester Stallone', - 9 => 'Kurt Russell', - 10 => 'Jean Reno', - 11 => 'Edward Furlong', + 4 => 'zYne', + 5 => 'Arnold Schwarzenegger', + 6 => 'Michael Caine', + 7 => 'Takeshi Kitano', + 8 => 'Sylvester Stallone', + 9 => 'Kurt Russell', + 10 => 'Jean Reno', + 11 => 'Edward Furlong', )); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1341TestCase.php b/tests/Ticket/1341TestCase.php index 8927d4970..483b8c7e2 100644 --- a/tests/Ticket/1341TestCase.php +++ b/tests/Ticket/1341TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1341_TestCase + * Doctrine_Ticket_1341_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1341_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1341_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -49,19 +55,19 @@ public function testTest() $user->save(); $this->pass(); $this->assertEqual($user->toArray(true), array( - 'id' => '1', - 'username' => 'jwage', - 'password' => 'changeme', - 'Profile' => - array( 'id' => '1', - 'name' => 'Jonathan H. Wage', - 'user_id' => '1', - ), + 'username' => 'jwage', + 'password' => 'changeme', + 'Profile' => array( + 'id' => '1', + 'name' => 'Jonathan H. Wage', + 'user_id' => '1', + ), )); $q = Doctrine_Query::create() ->from('Ticket_1341_User u') - ->leftJoin('u.Profile p'); + ->leftJoin('u.Profile p') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t.password AS t__password, t2.id AS t2__id, t2.name AS t2__name, t2.userid AS t2__userid FROM ticket_1341__user t LEFT JOIN ticket_1341__profile t2 ON t.id = t2.userid'); } catch (Exception $e) { $this->fail($e->getMessage()); @@ -95,4 +101,4 @@ public function setUp() { $this->hasOne('Ticket_1341_User as User', array('local' => 'user_id', 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1351TestCase.php b/tests/Ticket/1351TestCase.php index 8a7a6b27a..171f2e04d 100644 --- a/tests/Ticket/1351TestCase.php +++ b/tests/Ticket/1351TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1351_TestCase + * Doctrine_Ticket_1351_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1351_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1351_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -40,7 +46,7 @@ public function prepareTables() public function testTest() { - $yml = <<from('Ticket_1351_Article a, a.Translation t') - ->fetchArray(); + ->from('Ticket_1351_Article a, a.Translation t') + ->fetchArray() + ; $this->assertEqual($results[0]['Translation']['en']['title'], 'Test title english'); } } @@ -76,4 +83,4 @@ public function setUp() $i18n0->addChild($searchable1); $this->actAs($i18n0); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1365TestCase.php b/tests/Ticket/1365TestCase.php index b2df3b6a3..b4723f2b6 100644 --- a/tests/Ticket/1365TestCase.php +++ b/tests/Ticket/1365TestCase.php @@ -21,25 +21,31 @@ */ /** - * Doctrine_Ticket_1365_TestCase + * Doctrine_Ticket_1365_TestCase. * - * @package Doctrine * @author David Stendardi + * * @category Query - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.10.4 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1365_TestCase extends Doctrine_UnitTestCase { public function testInit() - { + { $this->dbh = new Doctrine_Adapter_Mock('mysql'); $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh); $this->conn->setCharset('utf8'); $this->conn->setAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM, true); - } + } public function prepareData() { @@ -52,7 +58,7 @@ public function prepareTables() $this->tables[] = 'T1365_Skill'; $this->tables[] = 'T1365_PersonHasSkill'; - parent :: prepareTables(); + parent::prepareTables(); } public function testTicket() @@ -61,25 +67,25 @@ public function testTicket() ->select('s.*, phs.*') ->from('T1365_Skill s') ->leftJoin('s.T1365_PersonHasSkill phs') - ->where('phs.value0 > phs.value1'); + ->where('phs.value0 > phs.value1') + ; $this->assertEqual( $q->getSqlQuery(), - 'SELECT l.id AS l__id, l.name AS l__name, ' . - 'l2.id AS l2__id, l2.fk_person_id AS l2__fk_person_id, l2.fk_skill_id AS l2__fk_skill_id, l2.value0 AS l2__value0, l2.value1 AS l2__value1 ' . - 'FROM la__skill l LEFT JOIN la__person_has_skill l2 ON l.id = l2.fk_skill_id ' . + 'SELECT l.id AS l__id, l.name AS l__name, '. + 'l2.id AS l2__id, l2.fk_person_id AS l2__fk_person_id, l2.fk_skill_id AS l2__fk_skill_id, l2.value0 AS l2__value0, l2.value1 AS l2__value1 '. + 'FROM la__skill l LEFT JOIN la__person_has_skill l2 ON l.id = l2.fk_skill_id '. 'WHERE (l2.value0 > l2.value1)' ); } } - class T1365_Person extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('la__person'); - + $this->hasColumn('name', 'string', 255); } @@ -89,13 +95,12 @@ public function setUp() } } - class T1365_Skill extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('la__skill'); - + $this->hasColumn('name', 'string', 255); } @@ -105,37 +110,36 @@ public function setUp() } } - class T1365_PersonHasSkill extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('la__person_has_skill'); - + $this->hasColumn('fk_person_id', 'integer', 8, array( - 'type' => 'integer', 'length' => '8' + 'type' => 'integer', 'length' => '8', )); $this->hasColumn('fk_skill_id', 'integer', 8, array( - 'type' => 'integer', 'length' => '8' + 'type' => 'integer', 'length' => '8', )); $this->hasColumn('value0', 'enum', 3, array( 'type' => 'enum', 'values' => array( - 0 => '0', 1 => '1', 2 => '2', 3 => '3' - ), 'default' => 0, 'notnull' => true, 'length' => '3' + 0 => '0', 1 => '1', 2 => '2', 3 => '3', + ), 'default' => 0, 'notnull' => true, 'length' => '3', )); $this->hasColumn('value1', 'enum', 3, array( 'type' => 'enum', 'values' => array( - 0 => '0', 1 => '1', 2 => '2', 3 => '3' - ), 'default' => 0, 'notnull' => true, 'length' => '3' + 0 => '0', 1 => '1', 2 => '2', 3 => '3', + ), 'default' => 0, 'notnull' => true, 'length' => '3', )); } - + public function setUp() { $this->hasOne('T1365_Person', array('local' => 'fk_person_id', 'foreign' => 'id')); $this->hasOne('T1365_Skill', array('local' => 'fk_skill_id', 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1372TestCase.php b/tests/Ticket/1372TestCase.php index c818141cf..6e8e72ee8 100644 --- a/tests/Ticket/1372TestCase.php +++ b/tests/Ticket/1372TestCase.php @@ -20,29 +20,34 @@ */ /** - * Doctrine_Ticket_1372_TestCase + * Doctrine_Ticket_1372_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1372_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1372_TestCase extends Doctrine_UnitTestCase { /* Test array of SQL queries to ensure uniqueness of queries */ public function testExportSql() { $drivers = array('mysql', - 'sqlite', - 'pgsql', - 'oracle', - 'mssql'); + 'sqlite', + 'pgsql', + 'oracle', + 'mssql'); - foreach ($drivers as $driver) - { + foreach ($drivers as $driver) { $dbh = new Doctrine_Adapter_Mock($driver); $conn = Doctrine_Manager::getInstance()->connection($dbh, $driver); diff --git a/tests/Ticket/1380TestCase.php b/tests/Ticket/1380TestCase.php index ba81cd433..3f7f9bb78 100644 --- a/tests/Ticket/1380TestCase.php +++ b/tests/Ticket/1380TestCase.php @@ -20,25 +20,32 @@ */ /** - * Doctrine_Ticket_1380_TestCase + * Doctrine_Ticket_1380_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1380_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1380_TestCase extends Doctrine_UnitTestCase { public function testTest() { $q = Doctrine_Query::create() ->select('u.*, COUNT(p.id) as num_phonenumbers') ->from('User u') - ->leftJoin('u.Phonenumber p'); + ->leftJoin('u.Phonenumber p') + ; $users = $q->fetchArray(); $this->assertTrue(isset($users[0]['num_phonenumbers'])); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1381TestCase.php b/tests/Ticket/1381TestCase.php index dee34ab11..935550b39 100644 --- a/tests/Ticket/1381TestCase.php +++ b/tests/Ticket/1381TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1381_TestCase + * Doctrine_Ticket_1381_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1381_TestCase extends Doctrine_UnitTestCase { @@ -39,14 +45,13 @@ public function prepareTables() parent::prepareTables(); } - - + public function prepareData() { $a = new T1381_Article(); $a->title = 'When cleanData worked as expected!'; $a->save(); - + $c = new T1381_Comment(); $c->article_id = $a->id; $c->body = 'Yeah! It will work one day.'; @@ -56,12 +61,12 @@ public function prepareData() $c->article_id = $a->id; $c->body = 'It will!'; $c->save(); - + // Cleaning up IdentityMap Doctrine_Core::getTable('T1381_Article')->clear(); Doctrine_Core::getTable('T1381_Comment')->clear(); } - + public function testTicket() { try { @@ -71,7 +76,7 @@ public function testTicket() // This should result in false, since we didn't fetch for this column $this->assertFalse(array_key_exists('ArticleTitle', $items[0]['T1381_Article'])); - + // We fetch for data including new columns $dql = 'SELECT c.*, a.title as ArticleTitle FROM T1381_Comment c INNER JOIN c.T1381_Article a WHERE c.id = ?'; $items = Doctrine_Query::create()->query($dql, array(1), Doctrine_Core::HYDRATE_ARRAY); @@ -83,7 +88,6 @@ public function testTicket() } } - public function testTicketInverse() { try { @@ -110,7 +114,7 @@ public function testTicketInverse() // Assert that new calculated column with different content do not override the already fetched one $this->assertTrue(array_key_exists('ArticleTitle', $items[0])); - + // Assert that our existent component still has the column, even after new hydration on same object $this->assertTrue(array_key_exists('ArticleTitle', $comment)); $this->assertTrue($comment, 'When cleanData worked as expected!'); @@ -120,41 +124,43 @@ public function testTicketInverse() } } - class T1381_Article extends Doctrine_Record { - public function setTableDefinition() { + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('title', 'string', 255, array('notnull' => true)); } - - public function setUp() { + + public function setUp() + { $this->hasMany( 'T1381_Comment', array( 'local' => 'id', - 'foreign' => 'article_id' + 'foreign' => 'article_id', ) ); } } - class T1381_Comment extends Doctrine_Record { - public function setTableDefinition() { + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('body', 'string', null, array('notnull' => true)); $this->hasColumn('article_id', 'integer', null, array('notnull' => true)); } - public function setUp() { + public function setUp() + { $this->hasOne( 'T1381_Article', array( 'local' => 'article_id', - 'foreign' => 'id' + 'foreign' => 'id', ) ); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1383TestCase.php b/tests/Ticket/1383TestCase.php index 6c1d7c11b..a0a7b0e28 100644 --- a/tests/Ticket/1383TestCase.php +++ b/tests/Ticket/1383TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1383_TestCase + * Doctrine_Ticket_1383_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1383_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1383_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -45,7 +51,7 @@ public function testTest() $orig = Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_VALIDATE); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); try { - $brand = new Ticket_1383_Brand; + $brand = new Ticket_1383_Brand(); $brand->name = 'The Great Brand'; $brand->Ticket_1383_Brand_Image[0]->name = 'imagename'; $brand->Ticket_1383_Brand_Image[0]->owner_id = 1; @@ -61,14 +67,15 @@ public function testTest() class Ticket_1383_Image extends Doctrine_Record { - public function setTableDefinition() { + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('owner_id', 'integer', null, array('notnull' => true)); $this->hasColumn('owner_type', 'integer', 5, array('notnull' => true)); $this->hasColumn('name', 'string', 128, array('notnull' => true, 'unique' => true)); $this->setSubclasses(array( - 'Ticket_1383_Brand_Image' => array('owner_type' => 0) + 'Ticket_1383_Brand_Image' => array('owner_type' => 0), )); } } @@ -79,18 +86,20 @@ class Ticket_1383_Brand_Image extends Ticket_1383_Image class Ticket_1383_Brand extends Doctrine_Record { - public function setTableDefinition() { + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('primary' => true, 'autoincrement' => true)); $this->hasColumn('name', 'string', 255, array('notnull' => true)); } - - public function setUp() { + + public function setUp() + { $this->hasMany( 'Ticket_1383_Brand_Image', array( 'local' => 'id', - 'foreign' => 'owner_id' + 'foreign' => 'owner_id', ) ); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1385TestCase.php b/tests/Ticket/1385TestCase.php index 9914658e3..a8ab11883 100644 --- a/tests/Ticket/1385TestCase.php +++ b/tests/Ticket/1385TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1385_TestCase + * Doctrine_Ticket_1385_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1385_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1385_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -94,4 +100,4 @@ public function setTableDefinition() $this->hasColumn('password', 'string', 255); $this->hasColumn('email_address', 'string', 255, array('email')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1390TestCase.php b/tests/Ticket/1390TestCase.php index 07c416043..87a068191 100644 --- a/tests/Ticket/1390TestCase.php +++ b/tests/Ticket/1390TestCase.php @@ -20,25 +20,31 @@ */ /** - * Doctrine_Ticket_1390_TestCase + * Doctrine_Ticket_1390_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1390_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1390_TestCase extends Doctrine_UnitTestCase { public function testTest() { $user = new User(); - + $record1 = $user->getTable()->find(4); $record2 = Doctrine_Core::getTable('User')->find(4); $this->assertIdentical($record1, $record2); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1395TestCase.php b/tests/Ticket/1395TestCase.php index f20a829a4..70b695174 100644 --- a/tests/Ticket/1395TestCase.php +++ b/tests/Ticket/1395TestCase.php @@ -20,18 +20,24 @@ */ /** - * Doctrine_Ticket_1395_TestCase + * Doctrine_Ticket_1395_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1395_TestCase extends Doctrine_UnitTestCase -{ +{ public function prepareTables() { $this->tables = array(); @@ -41,10 +47,10 @@ public function prepareTables() public function prepareData() { - $myModel = new T1395_MyModel(); - $myModel->dt_created = '2005-10-01'; - $myModel->id = 0; - $myModel->save(); + $myModel = new T1395_MyModel(); + $myModel->dt_created = '2005-10-01'; + $myModel->id = 0; + $myModel->save(); } public function testTicket() @@ -57,7 +63,7 @@ public function testTicket() } catch (Doctrine_Exception $e) { $this->fail($e->getMessage()); } - } + } } class T1395_MyModel extends Doctrine_Record @@ -72,7 +78,6 @@ public function setUp() { $this->addListener(new T1395_Listener()); } - } class T1395_Listener extends Doctrine_Record_Listener @@ -80,18 +85,18 @@ class T1395_Listener extends Doctrine_Record_Listener public function preHydrate(Doctrine_Event $event) { $data = $event->data; - + // Calculate days since creation $days = (strtotime('now') - strtotime($data['dt_created'])) / (24 * 60 * 60); $data['days_old'] = number_format($days, 2); self::addSomeData($data); - + $event->data = $data; } - + public static function addSomeData(&$data) { $data['dt_created_tx'] = date('M d, Y', strtotime($data['dt_created'])); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1400TestCase.php b/tests/Ticket/1400TestCase.php index 5a4fc5bad..f8884e2a3 100644 --- a/tests/Ticket/1400TestCase.php +++ b/tests/Ticket/1400TestCase.php @@ -20,26 +20,32 @@ */ /** - * Doctrine_Ticket_1400_TestCase + * Doctrine_Ticket_1400_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1400_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1400_TestCase extends Doctrine_UnitTestCase { public function testTest() { $q = Doctrine_Query::create() - ->from('User u') - ->where('u.id IN (SELECT u2.id FROM User u2 GROUP BY u2.id HAVING MAX(u2.version))') - ->orderBy('u.loginname asc'); + ->from('User u') + ->where('u.id IN (SELECT u2.id FROM User u2 GROUP BY u2.id HAVING MAX(u2.version))') + ->orderBy('u.loginname asc') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id IN (SELECT e2.id AS e2__id FROM entity e2 WHERE (e2.type = 0) GROUP BY e2.id HAVING MAX(e2.version) ) AND (e.type = 0)) ORDER BY e.loginname asc'); - } -} \ No newline at end of file +} diff --git a/tests/Ticket/1417TestCase.php b/tests/Ticket/1417TestCase.php index 137fe469f..0dd8c9a53 100644 --- a/tests/Ticket/1417TestCase.php +++ b/tests/Ticket/1417TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1417_TestCase + * Doctrine_Ticket_1417_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1417_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1417_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -52,4 +58,4 @@ public function testTest() $this->assertEqual($user->getLastModified(), array('name' => 'jon')); $this->assertEqual($user->getLastModified(true), array('name' => 'jwagejon')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1419TestCase.php b/tests/Ticket/1419TestCase.php index e18b07662..8ebcfb49f 100644 --- a/tests/Ticket/1419TestCase.php +++ b/tests/Ticket/1419TestCase.php @@ -20,35 +20,43 @@ */ /** - * Doctrine_Ticket_1419_TestCase + * Doctrine_Ticket_1419_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1419_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1419_TestCase extends Doctrine_UnitTestCase { public function testTest() { $user = Doctrine_Query::create() - ->from('User u') - ->leftJoin('u.Phonenumber p') - ->where('u.id = ?', 4) - ->fetchOne(); + ->from('User u') + ->leftJoin('u.Phonenumber p') + ->where('u.id = ?', 4) + ->fetchOne() + ; $user->Phonenumber[0]->phonenumber = '6155139185'; $user->save(); $user->free(); $user = Doctrine_Query::create() - ->from('User u') - ->leftJoin('u.Phonenumber p') - ->where('u.id = ?', 4) - ->fetchOne(); + ->from('User u') + ->leftJoin('u.Phonenumber p') + ->where('u.id = ?', 4) + ->fetchOne() + ; $this->assertTrue($user->Phonenumber->getLast()->id); $this->assertEqual($user->Phonenumber->getLast()->phonenumber, '6155139185'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1436TestCase.php b/tests/Ticket/1436TestCase.php index 43ce87771..7452a8e8e 100644 --- a/tests/Ticket/1436TestCase.php +++ b/tests/Ticket/1436TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1436_TestCase + * Doctrine_Ticket_1436_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1436_TestCase extends Doctrine_UnitTestCase { @@ -40,48 +46,49 @@ public function prepareTables() { parent::prepareTables(); } - + public function prepareData() { $user = new User(); $user->name = 'John'; $user->save(); - - # Create existing groups + + // Create existing groups $group = new Group(); $group->name = 'Group One'; $group->save(); $this->group_one = $group['id']; - + $group = new Group(); $group->name = 'Group Two'; $group->save(); $this->group_two = $group['id']; - + $group = new Group(); $group->name = 'Group Three'; $group->save(); $this->group_three = $group['id']; } - + public function testSynchronizeAddMNLinks() { $user = Doctrine_Query::create()->from('User u')->fetchOne(); $userArray = array( 'Group' => array( $this->group_one, - $this->group_two - ) + $this->group_two, + ), ); $user->synchronizeWithArray($userArray); try { - $user->save(); - } catch (Exception $e ) { - $this->fail("Failed saving with " . $e->getMessage()); + $user->save(); + } catch (Exception $e) { + $this->fail('Failed saving with '.$e->getMessage()); } } + public function testSynchronizeAddMNLinksAfterSave() { $user = Doctrine_Query::create()->from('User u, u.Group g')->fetchOne(); @@ -89,29 +96,30 @@ public function testSynchronizeAddMNLinksAfterSave() $this->assertEqual($user->Group[1]->name, 'Group Two'); $this->assertTrue(!isset($user->Group[2])); } + public function testSynchronizeChangeMNLinks() { $user = Doctrine_Query::create()->from('User u, u.Group g')->fetchOne(); $userArray = array( 'Group' => array( $this->group_two, - $this->group_three - ) + $this->group_three, + ), ); - + $user->synchronizeWithArray($userArray); - + $this->assertTrue(!isset($user->Groups)); - + try { - $user->save(); - } catch (Exception $e ) { - $this->fail("Failed saving with " . $e->getMessage()); + $user->save(); + } catch (Exception $e) { + $this->fail('Failed saving with '.$e->getMessage()); } - + $user->refresh(); $user->loadReference('Group'); - + $this->assertEqual($user->Group[0]->name, 'Group Two'); $this->assertEqual($user->Group[1]->name, 'Group Three'); $this->assertTrue(!isset($user->Group[2])); @@ -129,8 +137,8 @@ public function testFromArray() public function testSynchronizeMNRecordsDontDeleteAfterUnlink() { $group = Doctrine_Core::getTable('Group')->find($this->group_one); - + $this->assertTrue(!empty($group)); $this->assertEqual($group->name, 'Group One'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1441TestCase.php b/tests/Ticket/1441TestCase.php index 1e5258f20..b0fe4a69a 100644 --- a/tests/Ticket/1441TestCase.php +++ b/tests/Ticket/1441TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1441_TestCase + * Doctrine_Ticket_1441_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1441_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1441_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -51,8 +57,9 @@ public function testTest() Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); $q = Doctrine_Query::create() ->update('Ticket_1441_User u') - ->set('u.password', '?', 'test') - ->where('u.username = ?', 'jwage'); + ->set('u.password', '?', 'test') + ->where('u.username = ?', 'jwage') + ; $q->execute(); @@ -74,4 +81,4 @@ public function setUp() { $this->actAs('Timestampable'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1449TestCase.php b/tests/Ticket/1449TestCase.php index c62033c88..b48fc9a7e 100644 --- a/tests/Ticket/1449TestCase.php +++ b/tests/Ticket/1449TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1449_TestCase + * Doctrine_Ticket_1449_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1449_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1449_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -56,10 +62,10 @@ public function testTest() ->from('Ticket_1449_Document d') ->leftJoin('d.Attachments a') ->limit(1) - ->fetchOne(); + ->fetchOne() + ; $this->assertEqual($document->state(), 4); - foreach ($document->Attachments as $attachment) - { + foreach ($document->Attachments as $attachment) { $this->assertEqual($attachment->state(), 4); } } @@ -75,8 +81,8 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1449_Attachment as Attachments', array('local' => 'id', - 'foreign' => 'document_id')); + $this->hasMany('Ticket_1449_Attachment as Attachments', array('local' => 'id', + 'foreign' => 'document_id')); } } @@ -90,7 +96,7 @@ public function setTableDefinition() public function setUp() { - $this->hasOne('Ticket_1449_Document as Document', array('local' => 'document_id', - 'foreign' => 'id')); + $this->hasOne('Ticket_1449_Document as Document', array('local' => 'document_id', + 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1452TestCase.php b/tests/Ticket/1452TestCase.php index 7e721332f..1a773df7b 100644 --- a/tests/Ticket/1452TestCase.php +++ b/tests/Ticket/1452TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1452_TestCase + * Doctrine_Ticket_1452_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1452_TestCase extends Doctrine_UnitTestCase { @@ -44,7 +50,7 @@ public function testFindByIdAutomaticallyLoadsRelationsForInstanceTranslation() $description = 'En dansk beskrivelse'; try { - $item = new Model_Product; + $item = new Model_Product(); $item->name = $name; $item->Translation['DK']->description = $description; $item->Translation['EN']->description = 'Some english description'; @@ -63,15 +69,15 @@ public function testFindByIdAutomaticallyLoadsRelationsForInstanceTranslation() class Model_Product extends Doctrine_Record { - public function setTableDefinition () + public function setTableDefinition() { $this->hasColumn('name', 'string', 30); $this->hasColumn('description', 'string', 65555); $this->hasColumn('price', 'integer', 20); } - public function setUp () + public function setUp() { $this->actAs('I18n', array('fields' => array('description'))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1454TestCase.php b/tests/Ticket/1454TestCase.php index c5dc4d19d..95fda6697 100644 --- a/tests/Ticket/1454TestCase.php +++ b/tests/Ticket/1454TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1454_TestCase + * Doctrine_Ticket_1454_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1454_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1454_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -38,8 +44,9 @@ public function testTest() ->from('User u') ->leftJoin('u.Phonenumber p') ->where('p.id = (SELECT MAX(p2.id) FROM Phonenumber p2 LIMIT 1)') - ->orWhere('p.id = (SELECT MIN(p3.id) FROM Phonenumber p3 LIMIT 1)'); - + ->orWhere('p.id = (SELECT MIN(p3.id) FROM Phonenumber p3 LIMIT 1)') + ; + $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, p.id AS p__id, p.phonenumber AS p__phonenumber, p.entity_id AS p__entity_id FROM entity e LEFT JOIN phonenumber p ON e.id = p.entity_id WHERE (p.id = (SELECT MAX(p2.id) AS p2__0 FROM phonenumber p2 LIMIT 1) OR p.id = (SELECT MIN(p3.id) AS p3__0 FROM phonenumber p3 LIMIT 1) AND (e.type = 0))'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1461TestCase.php b/tests/Ticket/1461TestCase.php index 698c4a142..62c2de13e 100644 --- a/tests/Ticket/1461TestCase.php +++ b/tests/Ticket/1461TestCase.php @@ -20,59 +20,68 @@ */ /** - * Doctrine_Ticket_1461_TestCase + * Doctrine_Ticket_1461_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1461_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1461_TestCase extends Doctrine_UnitTestCase { public function testFetchArraySupportsTwoAggregates() { $q = new Doctrine_Query(); $q->select("u.*, p.*, CONCAT(u.name, '_1') concat1, CONCAT(u.name, '_2') concat2") - ->from('User u') - ->innerJoin('u.Phonenumber p') - ->where("u.name = 'zYne'"); - + ->from('User u') + ->innerJoin('u.Phonenumber p') + ->where("u.name = 'zYne'") + ; + $users = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertEqual($users[0]['concat1'], 'zYne_1'); $this->assertEqual($users[0]['concat2'], 'zYne_2'); } - + public function testFetchArraySupportsTwoAggregatesInRelation() { $q = new Doctrine_Query(); $q->select("u.*, p.*, CONCAT(p.phonenumber, '_1') concat1, CONCAT(p.phonenumber, '_2') concat2") - ->from('User u') - ->innerJoin('u.Phonenumber p') - ->where("u.name = 'zYne'"); - + ->from('User u') + ->innerJoin('u.Phonenumber p') + ->where("u.name = 'zYne'") + ; + $users = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertEqual($users[0]['concat2'], '123 123_2'); - + $this->assertEqual($users[0]['concat1'], '123 123_1'); - } + } public function testFetchArraySupportsTwoAggregatesInRelationAndRoot() { $q = new Doctrine_Query(); $q->select("u.*, p.*, CONCAT(u.name, '_1') concat1, CONCAT(u.name, '_2') concat2, CONCAT(p.phonenumber, '_3') concat3, CONCAT(p.phonenumber, '_3') concat4") - ->from('User u') - ->innerJoin('u.Phonenumber p') - ->where("u.name = 'zYne'"); - + ->from('User u') + ->innerJoin('u.Phonenumber p') + ->where("u.name = 'zYne'") + ; + $users = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); $this->assertEqual($users[0]['concat1'], 'zYne_1'); @@ -80,7 +89,7 @@ public function testFetchArraySupportsTwoAggregatesInRelationAndRoot() $this->assertEqual($users[0]['concat2'], 'zYne_2'); $this->assertEqual($users[0]['concat3'], '123 123_3'); - + $this->assertTrue(isset($users[0]['concat4'])); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1464TestCase.php b/tests/Ticket/1464TestCase.php index 92ec63fff..f19c8a17d 100644 --- a/tests/Ticket/1464TestCase.php +++ b/tests/Ticket/1464TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1464_TestCase + * Doctrine_Ticket_1464_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1464_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1464_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -63,4 +69,4 @@ public function setTableDefinition() $this->hasColumn('username', 'string', 255); $this->hasColumn('created_at', 'timestamp'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1465TestCase.php b/tests/Ticket/1465TestCase.php index 01c7fc207..c949101c2 100644 --- a/tests/Ticket/1465TestCase.php +++ b/tests/Ticket/1465TestCase.php @@ -20,27 +20,34 @@ */ /** - * Doctrine_Ticket_1465_TestCase + * Doctrine_Ticket_1465_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1465_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1465_TestCase extends Doctrine_UnitTestCase { public function testTest() { try { $q = Doctrine_Query::create() - ->from('User u, Phonenumber p'); + ->from('User u, Phonenumber p') + ; $users = $q->fetchArray(); $this->fail(); } catch (Exception $e) { $this->pass(); } } -} \ No newline at end of file +} diff --git a/tests/Ticket/1467TestCase.php b/tests/Ticket/1467TestCase.php index 5a7666281..244924d32 100644 --- a/tests/Ticket/1467TestCase.php +++ b/tests/Ticket/1467TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1467_TestCase + * Doctrine_Ticket_1467_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1467_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1467_TestCase extends Doctrine_UnitTestCase { public function testTicket() { @@ -39,14 +45,14 @@ public function testTicket() ->select('pic.id') ->from('T1467_Picture pic') ->innerJoin('pic.Items ite') - ->innerJoin('ite.Puzzles puz'); + ->innerJoin('ite.Puzzles puz') + ; $this->assertEqual($q->getDql(), 'SELECT pic.id FROM T1467_Picture pic INNER JOIN pic.Items ite INNER JOIN ite.Puzzles puz'); $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id FROM t1467__picture t INNER JOIN t1467__item_picture t3 ON (t.id = t3.picture_id) INNER JOIN t1467__item t2 ON t2.id = t3.item_id INNER JOIN t1467__item_puzzle t5 ON (t2.id = t5.item_id) INNER JOIN t1467__puzzle t4 ON t4.id = t5.puzzle_id'); } } - class T1467_Item extends Doctrine_Record { public function setTableDefinition() @@ -59,18 +65,17 @@ public function setUp() $this->hasMany('T1467_Picture as Pictures', array( 'refClass' => 'T1467_ItemPicture', 'local' => 'item_id', - 'foreign' => 'picture_id' + 'foreign' => 'picture_id', )); $this->hasMany('T1467_Puzzle as Puzzles', array( 'refClass' => 'T1467_ItemPuzzle', 'local' => 'item_id', - 'foreign' => 'puzzle_id' + 'foreign' => 'puzzle_id', )); } } - class T1467_Picture extends Doctrine_Record { public function setTableDefinition() @@ -83,12 +88,11 @@ public function setUp() $this->hasMany('T1467_Item as Items', array( 'refClass' => 'T1467_ItemPicture', 'local' => 'picture_id', - 'foreign' => 'item_id' + 'foreign' => 'item_id', )); } } - class T1467_Puzzle extends Doctrine_Record { public function setTableDefinition() @@ -101,12 +105,11 @@ public function setUp() $this->hasMany('T1467_Item as Items', array( 'refClass' => 'T1467_ItemPicture', 'local' => 'puzzle_id', - 'foreign' => 'item_id' + 'foreign' => 'item_id', )); } } - class T1467_ItemPicture extends Doctrine_Record { public function setTableDefinition() @@ -116,7 +119,6 @@ public function setTableDefinition() } } - class T1467_ItemPuzzle extends Doctrine_Record { public function setTableDefinition() @@ -124,4 +126,4 @@ public function setTableDefinition() $this->hasColumn('item_id', 'integer', null, array('primary' => true)); $this->hasColumn('puzzle_id', 'integer', null, array('primary' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1480TestCase.php b/tests/Ticket/1480TestCase.php index c912e72b1..cdd14f502 100644 --- a/tests/Ticket/1480TestCase.php +++ b/tests/Ticket/1480TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1480_TestCase + * Doctrine_Ticket_1480_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1480_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1480_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -44,7 +50,8 @@ public function testSubQueryWithSoftDeleteTestCase() Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); $q = Doctrine_Query::create() ->from('Foo f') - ->addWhere('f.id IN (SELECT b.user_id FROM Bar b)'); + ->addWhere('f.id IN (SELECT b.user_id FROM Bar b)') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT f.id AS f__id, f.name AS f__name, f.password AS f__password, f.deleted_at AS f__deleted_at FROM foo f WHERE (f.id IN (SELECT b.user_id AS b__user_id FROM bar b) AND (f.deleted_at IS NULL))'); $this->assertEqual(count($q->getFlattenedParams()), 0); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); @@ -74,4 +81,4 @@ public function setTableDefinition() $this->setTableName('bar'); $this->hasColumn('user_id', 'integer'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1483TestCase.php b/tests/Ticket/1483TestCase.php index 4c963e185..f0dd9d6ba 100644 --- a/tests/Ticket/1483TestCase.php +++ b/tests/Ticket/1483TestCase.php @@ -20,52 +20,58 @@ */ /** - * Doctrine_Ticket_1483_TestCase + * Doctrine_Ticket_1483_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1483_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1483_TestCase extends Doctrine_UnitTestCase { public function testTest() { $q = Doctrine_Query::create() ->from('Ticket_1483_User u') - ->leftJoin('u.Groups g WITH g.id = (SELECT g2.id FROM Ticket_1483_Group g2 WHERE (g2.name = \'Test\' OR g2.name = \'Test2\'))'); + ->leftJoin('u.Groups g WITH g.id = (SELECT g2.id FROM Ticket_1483_Group g2 WHERE (g2.name = \'Test\' OR g2.name = \'Test2\'))') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t2.id AS t2__id, t2.name AS t2__name FROM ticket_1483__user t LEFT JOIN ticket_1483__user_group t3 ON (t.id = t3.user_id) LEFT JOIN ticket_1483__group t2 ON t2.id = t3.group_id AND (t2.id = (SELECT t4.id AS t4__id FROM ticket_1483__group t4 WHERE (t4.name = \'Test\' OR t4.name = \'Test2\')))'); - } - + public function testTest2() { $q = Doctrine_Query::create() ->from('Ticket_1483_User u') - ->leftJoin('u.Groups g WITH g.id = (SELECT g2.id FROM Ticket_1483_Group g2 WHERE (g2.name = \'Test\' OR (g2.name = \'Test2\')))'); + ->leftJoin('u.Groups g WITH g.id = (SELECT g2.id FROM Ticket_1483_Group g2 WHERE (g2.name = \'Test\' OR (g2.name = \'Test2\')))') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t2.id AS t2__id, t2.name AS t2__name FROM ticket_1483__user t LEFT JOIN ticket_1483__user_group t3 ON (t.id = t3.user_id) LEFT JOIN ticket_1483__group t2 ON t2.id = t3.group_id AND (t2.id = (SELECT t4.id AS t4__id FROM ticket_1483__group t4 WHERE (t4.name = \'Test\' OR t4.name = \'Test2\')))'); - } - + public function testTest3() { $q = Doctrine_Query::create() ->from('Ticket_1483_User u') - ->leftJoin('u.Groups g WITH g.id = (SELECT g2.id FROM Ticket_1483_Group g2 WHERE ((g2.name = \'Test\' AND g2.name = \'Test2\') OR (g2.name = \'Test2\')))'); + ->leftJoin('u.Groups g WITH g.id = (SELECT g2.id FROM Ticket_1483_Group g2 WHERE ((g2.name = \'Test\' AND g2.name = \'Test2\') OR (g2.name = \'Test2\')))') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t2.id AS t2__id, t2.name AS t2__name FROM ticket_1483__user t LEFT JOIN ticket_1483__user_group t3 ON (t.id = t3.user_id) LEFT JOIN ticket_1483__group t2 ON t2.id = t3.group_id AND (t2.id = (SELECT t4.id AS t4__id FROM ticket_1483__group t4 WHERE ((t4.name = \'Test\' AND t4.name = \'Test2\') OR t4.name = \'Test2\')))'); - } public function testTest4() { $q = Doctrine_Query::create() ->from('Ticket_1483_User u') - ->leftJoin('u.Groups g WITH g.id = (SELECT COUNT(*) FROM Ticket_1483_Group)'); + ->leftJoin('u.Groups g WITH g.id = (SELECT COUNT(*) FROM Ticket_1483_Group)') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t2.id AS t2__id, t2.name AS t2__name FROM ticket_1483__user t LEFT JOIN ticket_1483__user_group t3 ON (t.id = t3.user_id) LEFT JOIN ticket_1483__group t2 ON t2.id = t3.group_id AND (t2.id = (SELECT COUNT(*) AS t4__0 FROM ticket_1483__group t4))'); - } } @@ -78,9 +84,9 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1483_Group as Groups', array('local' => 'user_id', - 'foreign' => 'group_id', - 'refClass' => 'Ticket_1483_UserGroup')); + $this->hasMany('Ticket_1483_Group as Groups', array('local' => 'user_id', + 'foreign' => 'group_id', + 'refClass' => 'Ticket_1483_UserGroup')); } } @@ -93,13 +99,12 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1483_User as Users', array('local' => 'group_id', - 'foreign' => 'user_id', - 'refClass' => 'Ticket_1483_UserGroup')); + $this->hasMany('Ticket_1483_User as Users', array('local' => 'group_id', + 'foreign' => 'user_id', + 'refClass' => 'Ticket_1483_UserGroup')); } } - class Ticket_1483_UserGroup extends Doctrine_Record { public function setTableDefinition() @@ -107,4 +112,4 @@ public function setTableDefinition() $this->hasColumn('user_id', 'integer'); $this->hasColumn('group_id', 'integer'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1488TestCase.php b/tests/Ticket/1488TestCase.php index 5207cef81..fb025e9b0 100644 --- a/tests/Ticket/1488TestCase.php +++ b/tests/Ticket/1488TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1488_TestCase + * Doctrine_Ticket_1488_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1488_TestCase extends Doctrine_UnitTestCase { @@ -36,7 +42,8 @@ public function testTest() { $q = Doctrine_Query::create() ->from('T1488_Class1 c1') - ->leftJoin('c1.Classes2 c2 WITH c2.value BETWEEN c1.min AND c1.max'); + ->leftJoin('c1.Classes2 c2 WITH c2.value BETWEEN c1.min AND c1.max') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.min AS t__min, t.max AS t__max, t2.id AS t2__id, t2.value AS t2__value FROM t1488__class1 t LEFT JOIN t1488__relation t3 ON (t.id = t3.c1_id) LEFT JOIN t1488__class2 t2 ON t2.id = t3.c2_id AND (t2.value BETWEEN t.min AND t.max)'); } } @@ -51,9 +58,9 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('T1488_Class2 as Classes2', array('local' => 'c1_id', - 'foreign' => 'c2_id', - 'refClass' => 'T1488_Relation')); + $this->hasMany('T1488_Class2 as Classes2', array('local' => 'c1_id', + 'foreign' => 'c2_id', + 'refClass' => 'T1488_Relation')); } } @@ -66,13 +73,12 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('T1488_Class1 as Classes1', array('local' => 'c2_id', - 'foreign' => 'c1_id', - 'refClass' => 'T1488_Relation')); + $this->hasMany('T1488_Class1 as Classes1', array('local' => 'c2_id', + 'foreign' => 'c1_id', + 'refClass' => 'T1488_Relation')); } } - class T1488_Relation extends Doctrine_Record { public function setTableDefinition() @@ -80,4 +86,4 @@ public function setTableDefinition() $this->hasColumn('c1_id', 'integer'); $this->hasColumn('c2_id', 'integer'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1494TestCase.php b/tests/Ticket/1494TestCase.php index 3892252a9..b935c73e6 100644 --- a/tests/Ticket/1494TestCase.php +++ b/tests/Ticket/1494TestCase.php @@ -20,25 +20,32 @@ */ /** - * Doctrine_Ticket_1494_TestCase + * Doctrine_Ticket_1494_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1494_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1494_TestCase extends Doctrine_UnitTestCase { public function testTest() { $q = Doctrine_Query::create() ->select('u.*, CONCAT(u.id, u.name) as custom') - ->from('User u INDEXBY custom'); + ->from('User u INDEXBY custom') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id, CONCAT(e.id, e.name) AS e__0 FROM entity e WHERE (e.type = 0)'); $results = $q->fetchArray(); $this->assertEqual($results['4zYne']['name'], 'zYne'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1500TestCase.php b/tests/Ticket/1500TestCase.php index 83fcb96e1..c6184ccd7 100644 --- a/tests/Ticket/1500TestCase.php +++ b/tests/Ticket/1500TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1500_TestCase + * Doctrine_Ticket_1500_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1500_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1500_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -53,17 +59,19 @@ public function prepareData() $user = new T1500_User(); $user->groupId = $group->id; $user->name = 'guilhermeblanco'; - $user->save(); + $user->save(); } public function testTicket() { $q = Doctrine_Query::create() - ->from('T1500_User u')->innerJoin('u.Group g')->where('u.id = 1'); + ->from('T1500_User u')->innerJoin('u.Group g')->where('u.id = 1') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.user_id AS t__user_id, t.group_id AS t__group_id, t.name AS t__name, t2.group_id AS t2__group_id, t2.name AS t2__name FROM t1500__user t INNER JOIN t1500__group t2 ON t.group_id = t2.group_id WHERE (t.user_id = 1)'); $q = Doctrine_Query::create() - ->from('T1500_Group g')->innerJoin('g.Users u')->where('g.id = 1'); + ->from('T1500_Group g')->innerJoin('g.Users u')->where('g.id = 1') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.group_id AS t__group_id, t.name AS t__name, t2.user_id AS t2__user_id, t2.group_id AS t2__group_id, t2.name AS t2__name FROM t1500__group t INNER JOIN t1500__user t2 ON t.group_id = t2.group_id WHERE (t.group_id = 1)'); } } @@ -95,4 +103,4 @@ public function setUp() { $this->hasMany('T1500_User as Users', array('local' => 'id', 'foreign' => 'groupId')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1507TestCase.php b/tests/Ticket/1507TestCase.php index 7153cdeeb..366d630cb 100644 --- a/tests/Ticket/1507TestCase.php +++ b/tests/Ticket/1507TestCase.php @@ -20,76 +20,82 @@ */ /** - * Doctrine_Ticket_1500_TestCase + * Doctrine_Ticket_1500_TestCase. * - * @package Doctrine * @author David Zülke * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category ? - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1507_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1507_TestCase extends Doctrine_UnitTestCase { - public function testInitiallyEmpty() - { - $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); - - $this->assertEqual(null, $c->getParam('foo')); - $this->assertEqual(null, $c->getParam('foo', 'bar')); - $this->assertEqual(null, $c->getParams()); - $this->assertEqual(null, $c->getParams('bar')); - $this->assertEqual(array(), $c->getParamNamespaces()); - } - - public function testSetGetParamWithNamespace() - { - $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); - - $c->setParam('foo', 'bar', 'namespace'); - - $this->assertEqual(array('foo' => 'bar'), $c->getParams('namespace')); - $this->assertEqual('bar', $c->getParam('foo', 'namespace')); - - $this->assertEqual(array('namespace'), $c->getParamNamespaces()); - } - - public function testSetGetParamWithoutNamespace() - { - $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); - - $c->setParam('foo', 'bar'); - - $this->assertEqual(array('foo' => 'bar'), $c->getParams()); - $this->assertEqual('bar', $c->getParam('foo')); - - $this->assertEqual(array($c->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE)), $c->getParamNamespaces()); - } - - public function testSetGetParamWithNamespaceParent() - { - $p = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); - $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); - $c->setParent($p); - - $p->setParam('foo', 'bar', 'namespace'); - - $this->assertEqual('bar', $c->getParam('foo', 'namespace')); - } - - public function testSetGetParamWithoutNamespaceParent() - { - $p = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); - $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); - $c->setParent($p); - - $p->setParam('foo', 'bar'); - - $this->assertEqual('bar', $c->getParam('foo')); - } + public function testInitiallyEmpty() + { + $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); + + $this->assertEqual(null, $c->getParam('foo')); + $this->assertEqual(null, $c->getParam('foo', 'bar')); + $this->assertEqual(null, $c->getParams()); + $this->assertEqual(null, $c->getParams('bar')); + $this->assertEqual(array(), $c->getParamNamespaces()); + } + + public function testSetGetParamWithNamespace() + { + $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); + + $c->setParam('foo', 'bar', 'namespace'); + + $this->assertEqual(array('foo' => 'bar'), $c->getParams('namespace')); + $this->assertEqual('bar', $c->getParam('foo', 'namespace')); + + $this->assertEqual(array('namespace'), $c->getParamNamespaces()); + } + + public function testSetGetParamWithoutNamespace() + { + $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); + + $c->setParam('foo', 'bar'); + + $this->assertEqual(array('foo' => 'bar'), $c->getParams()); + $this->assertEqual('bar', $c->getParam('foo')); + + $this->assertEqual(array($c->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE)), $c->getParamNamespaces()); + } + + public function testSetGetParamWithNamespaceParent() + { + $p = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); + $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); + $c->setParent($p); + + $p->setParam('foo', 'bar', 'namespace'); + + $this->assertEqual('bar', $c->getParam('foo', 'namespace')); + } + + public function testSetGetParamWithoutNamespaceParent() + { + $p = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); + $c = new Doctrine_Ticket_1507_TestCase_TestConfigurable(); + $c->setParent($p); + + $p->setParam('foo', 'bar'); + + $this->assertEqual('bar', $c->getParam('foo')); + } } class Doctrine_Ticket_1507_TestCase_TestConfigurable extends Doctrine_Configurable { -} \ No newline at end of file +} diff --git a/tests/Ticket/1513TestCase.php b/tests/Ticket/1513TestCase.php index b2d1405bf..0dbb49679 100644 --- a/tests/Ticket/1513TestCase.php +++ b/tests/Ticket/1513TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1513_TestCase + * Doctrine_Ticket_1513_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1513_TestCase extends Doctrine_UnitTestCase { @@ -36,7 +42,8 @@ public function testTest() { $q = Doctrine_Query::create() ->from('T1513_Class2 c2') - ->leftJoin('c2.Classes1 c1 WITH (c1.max - c1.min) > 50'); + ->leftJoin('c2.Classes1 c1 WITH (c1.max - c1.min) > 50') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.value AS t__value, t2.id AS t2__id, t2.min AS t2__min, t2.max AS t2__max FROM t1513__class2 t LEFT JOIN t1513__relation t3 ON (t.id = t3.c2_id) LEFT JOIN t1513__class1 t2 ON t2.id = t3.c1_id AND ((t2.max - t2.min) > 50)'); } } @@ -51,9 +58,9 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('T1513_Class2 as Classes2', array('local' => 'c1_id', - 'foreign' => 'c2_id', - 'refClass' => 'T1513_Relation')); + $this->hasMany('T1513_Class2 as Classes2', array('local' => 'c1_id', + 'foreign' => 'c2_id', + 'refClass' => 'T1513_Relation')); } } @@ -66,13 +73,12 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('T1513_Class1 as Classes1', array('local' => 'c2_id', - 'foreign' => 'c1_id', - 'refClass' => 'T1513_Relation')); + $this->hasMany('T1513_Class1 as Classes1', array('local' => 'c2_id', + 'foreign' => 'c1_id', + 'refClass' => 'T1513_Relation')); } } - class T1513_Relation extends Doctrine_Record { public function setTableDefinition() @@ -80,4 +86,4 @@ public function setTableDefinition() $this->hasColumn('c1_id', 'integer'); $this->hasColumn('c2_id', 'integer'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1520TestCase.php b/tests/Ticket/1520TestCase.php index 95b4cd33b..3c3b79ae2 100644 --- a/tests/Ticket/1520TestCase.php +++ b/tests/Ticket/1520TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1520_TestCase + * Doctrine_Ticket_1520_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1520_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1520_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -63,4 +69,4 @@ public function setTableDefinition() $this->hasColumn('title', 'string', 255); $this->hasColumn('price', 'decimal'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1522TestCase.php b/tests/Ticket/1522TestCase.php index 4c2b4ea1d..d60eab962 100644 --- a/tests/Ticket/1522TestCase.php +++ b/tests/Ticket/1522TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1522_TestCase + * Doctrine_Ticket_1522_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1522_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1522_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -52,6 +58,7 @@ public function setTableDefinition() public function setEncryptedPassword($value) { $this->use_encrypted_password = true; + return $this->_set('password', md5($value)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1523TestCase.php b/tests/Ticket/1523TestCase.php index 62759aa6f..751ba7985 100644 --- a/tests/Ticket/1523TestCase.php +++ b/tests/Ticket/1523TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1523_TestCase + * Doctrine_Ticket_1523_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1523_TestCase extends Doctrine_UnitTestCase { @@ -42,38 +48,40 @@ public function prepareTables() public function testTest() { $q = Doctrine_Query::create() - ->from('Ticket_1523_User u') - ->innerJoin('u.Ticket_1523_Group g') - ->where('EXISTS (SELECT uu.id FROM Ticket_1523_User uu WHERE uu.id = u.id)') - ->orderBy('u.code ASC'); + ->from('Ticket_1523_User u') + ->innerJoin('u.Ticket_1523_Group g') + ->where('EXISTS (SELECT uu.id FROM Ticket_1523_User uu WHERE uu.id = u.id)') + ->orderBy('u.code ASC') + ; - $pager = new Doctrine_Pager($q, 1, 10); - $pager->execute(array()); - $this->assertEqual($pager->getQuery()->getSqlQuery(), 'SELECT t.id AS t__id, t.code AS t__code, t2.id AS t2__id, t2.tmp_id AS t2__tmp_id FROM ticket_1523__user t INNER JOIN ticket_1523__group t2 ON t.id = t2.tmp_id WHERE t.id IN (SELECT DISTINCT t3.id FROM ticket_1523__user t3 INNER JOIN ticket_1523__group t4 ON t3.id = t4.tmp_id WHERE EXISTS (SELECT t5.id AS t3__id FROM ticket_1523__user t5 WHERE (t5.id = t3.id)) ORDER BY t3.code ASC LIMIT 10) AND (EXISTS (SELECT t3.id AS t3__id FROM ticket_1523__user t3 WHERE (t3.id = t.id))) ORDER BY t.code ASC'); + $pager = new Doctrine_Pager($q, 1, 10); + $pager->execute(array()); + $this->assertEqual($pager->getQuery()->getSqlQuery(), 'SELECT t.id AS t__id, t.code AS t__code, t2.id AS t2__id, t2.tmp_id AS t2__tmp_id FROM ticket_1523__user t INNER JOIN ticket_1523__group t2 ON t.id = t2.tmp_id WHERE t.id IN (SELECT DISTINCT t3.id FROM ticket_1523__user t3 INNER JOIN ticket_1523__group t4 ON t3.id = t4.tmp_id WHERE EXISTS (SELECT t5.id AS t3__id FROM ticket_1523__user t5 WHERE (t5.id = t3.id)) ORDER BY t3.code ASC LIMIT 10) AND (EXISTS (SELECT t3.id AS t3__id FROM ticket_1523__user t3 WHERE (t3.id = t.id))) ORDER BY t.code ASC'); } } class Ticket_1523_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'primary' => true)); - $this->hasColumn('code', 'string', 64, array('type' => 'string', 'length' => '64', 'notnull' => true)); - } - public function setUp() - { - $this->hasMany('Ticket_1523_Group', array( - 'local' => 'id', - 'foreign' => 'tmp_id', - )); - } + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'primary' => true)); + $this->hasColumn('code', 'string', 64, array('type' => 'string', 'length' => '64', 'notnull' => true)); + } + + public function setUp() + { + $this->hasMany('Ticket_1523_Group', array( + 'local' => 'id', + 'foreign' => 'tmp_id', + )); + } } class Ticket_1523_Group extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'primary' => true, )); - $this->hasColumn('tmp_id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'notnull' => true)); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'primary' => true)); + $this->hasColumn('tmp_id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'notnull' => true)); + } +} diff --git a/tests/Ticket/1524TestCase.php b/tests/Ticket/1524TestCase.php index 0e64df98a..42a277a58 100644 --- a/tests/Ticket/1524TestCase.php +++ b/tests/Ticket/1524TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1524_TestCase + * Doctrine_Ticket_1524_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1524_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1524_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -46,4 +52,4 @@ public function validate($value) { return true; } -} \ No newline at end of file +} diff --git a/tests/Ticket/1527TestCase.php b/tests/Ticket/1527TestCase.php index 8751aca90..02f693301 100644 --- a/tests/Ticket/1527TestCase.php +++ b/tests/Ticket/1527TestCase.php @@ -20,21 +20,27 @@ */ /** - * Doctrine_Ticket_1527_TestCase + * Doctrine_Ticket_1527_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1527_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1527_TestCase extends Doctrine_UnitTestCase { public function testTest() { - $yml = <<buildSchema($yml, 'yml'); $this->assertEqual($schema['Ticket_1527_User']['columns']['username']['extra']['test'], '123'); - $path = dirname(__FILE__) . '/../tmp'; + $path = dirname(__FILE__).'/../tmp'; $import->importSchema($yml, 'yml', $path); - - require_once($path . '/generated/BaseTicket_1527_User.php'); - require_once($path . '/Ticket_1527_User.php'); + + require_once $path.'/generated/BaseTicket_1527_User.php'; + require_once $path.'/Ticket_1527_User.php'; $username = Doctrine_Core::getTable('Ticket_1527_User')->getDefinitionOf('username'); $this->assertEqual($username['extra']['test'], '123'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1537TestCase.php b/tests/Ticket/1537TestCase.php index 7f8ce4b8c..9ffc186ce 100644 --- a/tests/Ticket/1537TestCase.php +++ b/tests/Ticket/1537TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1537_TestCase + * Doctrine_Ticket_1537_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1537_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1537_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -45,7 +51,8 @@ public function testTest() ->update('Ticket_1537_User u') ->set('password', '?', 'changeme') ->set('email_address', '?', 'jonwage@gmail.com') - ->where('username = ?', 'jwage'); + ->where('username = ?', 'jwage') + ; $this->assertEqual($q->getSqlQuery(), 'UPDATE ticket_1537__user SET password = ?, email_address = ?, updated_at = ? WHERE (username = ?)'); $params = $q->getFlattenedParams(); @@ -73,4 +80,4 @@ public function setUp() { $this->actAs('Timestampable'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1540TestCase.php b/tests/Ticket/1540TestCase.php index df133f74d..952dbe801 100644 --- a/tests/Ticket/1540TestCase.php +++ b/tests/Ticket/1540TestCase.php @@ -20,37 +20,45 @@ */ /** - * Doctrine_Ticket_1540_TestCase + * Doctrine_Ticket_1540_TestCase. * - * @package Doctrine * @author Andrea Baron * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0.2 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1540_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1540_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables[] = 'Ticket_1540_TableName'; parent::prepareTables(); } - - public function testShouldNotConvertToAmpersandsInSelect() + + public function testShouldNotConvertToAmpersandsInSelect() { $q = Doctrine_Query::create() - ->select('if(1 AND 2, 1, 2)') - ->from('Ticket_1540_TableName t'); + ->select('if(1 AND 2, 1, 2)') + ->from('Ticket_1540_TableName t') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT if(1 AND 2, 1, 2) AS t__0 FROM ticket_1540__table_name t'); } - + public function testShouldNotConvertToAmpersandsInWhere() { $q = Doctrine_Query::create() ->from('Ticket_1540_TableName t') - ->where('if(1 AND 2, 1, 2)', 1); + ->where('if(1 AND 2, 1, 2)', 1) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id FROM ticket_1540__table_name t WHERE (if(1 AND 2, 1, 2))'); } } @@ -64,6 +72,5 @@ public function setTableDefinition() public function setUp() { - } -} \ No newline at end of file +} diff --git a/tests/Ticket/1543TestCase.php b/tests/Ticket/1543TestCase.php index e380f1522..c5be59772 100644 --- a/tests/Ticket/1543TestCase.php +++ b/tests/Ticket/1543TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1543_TestCase + * Doctrine_Ticket_1543_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1543_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1543_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -66,4 +72,4 @@ public function setUp() { $this->actAs('Timestampable'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1545TestCase.php b/tests/Ticket/1545TestCase.php index a0757c835..485892c3f 100644 --- a/tests/Ticket/1545TestCase.php +++ b/tests/Ticket/1545TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1545_TestCase + * Doctrine_Ticket_1545_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1545_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1545_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -70,22 +76,22 @@ class Ticket_1545_FooFilter extends Doctrine_Record_Filter { public function init() { - } public function filterGet(Doctrine_Record $record, $name) { - if ($name == 'b') { + if ('b' == $name) { return $record->a; - } else if ($name == 'custom') { + } + if ('custom' == $name) { return $record->a; } } public function filterSet(Doctrine_Record $record, $name, $value) { - if ($name == 'custom') { - return $record->a = $value . '2'; + if ('custom' == $name) { + return $record->a = $value.'2'; } } -} \ No newline at end of file +} diff --git a/tests/Ticket/1558TestCase.php b/tests/Ticket/1558TestCase.php index a6386ea0e..dceb6cf3a 100644 --- a/tests/Ticket/1558TestCase.php +++ b/tests/Ticket/1558TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1558_TestCase + * Doctrine_Ticket_1558_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1558_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1558_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -42,7 +48,8 @@ public function testTest() ->orWhereIn('u.id', array(1)) ->andWhereIn('u.id', array(1)) ->whereIn('u.id', array()) - ->orWhereIn('u.id', array()); + ->orWhereIn('u.id', array()) + ; $this->assertEqual($q->getSqlQuery(), 'SELECT e.id AS e__id, e.name AS e__name, e.loginname AS e__loginname, e.password AS e__password, e.type AS e__type, e.created AS e__created, e.updated AS e__updated, e.email_id AS e__email_id FROM entity e WHERE (e.id IN (?) OR e.id IN (?) OR e.id IN (?) AND e.id IN (?) AND (e.type = 0))'); $results = $q->execute(); $this->pass(); @@ -50,4 +57,4 @@ public function testTest() $this->fail($e->getMessage()); } } -} \ No newline at end of file +} diff --git a/tests/Ticket/1562TestCase.php b/tests/Ticket/1562TestCase.php index d90376687..53da029a4 100644 --- a/tests/Ticket/1562TestCase.php +++ b/tests/Ticket/1562TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1562_TestCase + * Doctrine_Ticket_1562_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1562_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1562_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -56,7 +62,7 @@ public function testTest() try { $table->getTestAccessor2(); } catch (Exception $e) { - if ($e->getMessage() == 'Test') { + if ('Test' == $e->getMessage()) { $this->pass(); } else { $this->fail('Exception thrown should have had a message of test'); @@ -81,7 +87,6 @@ public function setUp() class Ticket_1562_UserTable extends Doctrine_Table { - } class Ticket_1562_Template extends Doctrine_Template @@ -100,4 +105,4 @@ public function getTestAccessor2TableProxy() { throw new Doctrine_Exception('Test'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1567TestCase.php b/tests/Ticket/1567TestCase.php index 6fde50ef7..0c0aeeff2 100644 --- a/tests/Ticket/1567TestCase.php +++ b/tests/Ticket/1567TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1567_TestCase + * Doctrine_Ticket_1567_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1567_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1567_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -50,7 +56,7 @@ public function testTest() $query->from('Ticket_1567_Project p'); $query->addWhere('p.user_id = ?', 1); $query->addWhere('p.deleted = ?', true); - + $this->assertEqual($query->count(), 1); $this->assertEqual($query->execute()->count(), 1); } @@ -69,4 +75,4 @@ public function setUp() { $this->actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1604TestCase.php b/tests/Ticket/1604TestCase.php index f8c8f6ffb..296041c5e 100644 --- a/tests/Ticket/1604TestCase.php +++ b/tests/Ticket/1604TestCase.php @@ -20,16 +20,22 @@ */ /** - * Doctrine_Ticket_1589_TestCase + * Doctrine_Ticket_1589_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 - * @version $Revision$ + * + * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1604_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1604_TestCase extends Doctrine_UnitTestCase { public function testExport() { @@ -37,21 +43,21 @@ public function testExport() $sql = $conn->export->exportClassesSql(array('Ticket_1604_User', 'Ticket_1604_EmailAdresses')); $def = array( - "CREATE TABLE ticket_1604__user (id BIGINT AUTO_INCREMENT, name VARCHAR(30), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB", - "CREATE TABLE ticket_1604__email_adresses (id BIGINT AUTO_INCREMENT, user_id BIGINT, address VARCHAR(30), INDEX user_id_idx (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB", - "ALTER TABLE ticket_1604__email_adresses ADD CONSTRAINT ticket_1604__email_adresses_user_id_ticket_1604__user_id FOREIGN KEY (user_id) REFERENCES ticket_1604__user(id)" + 'CREATE TABLE ticket_1604__user (id BIGINT AUTO_INCREMENT, name VARCHAR(30), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB', + 'CREATE TABLE ticket_1604__email_adresses (id BIGINT AUTO_INCREMENT, user_id BIGINT, address VARCHAR(30), INDEX user_id_idx (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = INNODB', + 'ALTER TABLE ticket_1604__email_adresses ADD CONSTRAINT ticket_1604__email_adresses_user_id_ticket_1604__user_id FOREIGN KEY (user_id) REFERENCES ticket_1604__user(id)', ); - + $this->assertEqual($sql, $def); } } - + class Ticket_1604_User extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('name', 'string', 30); - + $this->option('type', 'INNODB'); $this->option('collate', 'utf8_unicode_ci'); $this->option('charset', 'utf8'); @@ -59,7 +65,7 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1604_EmailAdresses as emailAdresses', array('local' => 'id', 'foreign' => 'userId', "onDelete" => "CASCADE")); + $this->hasMany('Ticket_1604_EmailAdresses as emailAdresses', array('local' => 'id', 'foreign' => 'userId', 'onDelete' => 'CASCADE')); } } @@ -69,14 +75,14 @@ public function setTableDefinition() { $this->hasColumn('user_id as userId', 'integer'); $this->hasColumn('address', 'string', 30); - + $this->option('type', 'INNODB'); $this->option('collate', 'utf8_unicode_ci'); $this->option('charset', 'utf8'); } - + public function setUp() { - $this->hasOne('Ticket_1604_User as user', array('local' => 'userId', 'foreign' => 'id')); + $this->hasOne('Ticket_1604_User as user', array('local' => 'userId', 'foreign' => 'id')); } } diff --git a/tests/Ticket/1617TestCase.php b/tests/Ticket/1617TestCase.php index fc36a8bd9..1cda03ef1 100644 --- a/tests/Ticket/1617TestCase.php +++ b/tests/Ticket/1617TestCase.php @@ -20,16 +20,22 @@ */ /** - * Doctrine_Ticket_1617_TestCase + * Doctrine_Ticket_1617_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1617_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1617_TestCase extends Doctrine_UnitTestCase { public function testBuildSchema() { @@ -38,4 +44,4 @@ public function testBuildSchema() $this->assertEqual($array['term']['columns']['language']['name'], 'lang as language'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1619TestCase.php b/tests/Ticket/1619TestCase.php index e83fb710a..a3b861147 100644 --- a/tests/Ticket/1619TestCase.php +++ b/tests/Ticket/1619TestCase.php @@ -20,58 +20,62 @@ */ /** - * Doctrine_Ticket_1619_TestCase + * Doctrine_Ticket_1619_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1619_TestCase extends Doctrine_UnitTestCase { - - public function prepareTables() - { - $this->tables[] = 'Ticket_1619_Article'; - parent::prepareTables(); - } +class Doctrine_Ticket_1619_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { + $this->tables[] = 'Ticket_1619_Article'; + parent::prepareTables(); + } - public function testTest() - { - $a = new Ticket_1619_Article(); - $a->Translation['fr']->name = 'article'; - $a->Translation['fr']->description = 'article'; - $a->Translation['en']->name = 'english article'; - $a->Translation['en']->description = 'english description'; - $a->save(); - - $b = new Ticket_1619_Article(); - $a->Translation['fr']->name = 'maison'; - $a->Translation['fr']->description = 'habitation'; - $a->Translation['en']->name = 'english house'; - $a->Translation['en']->description = 'english big house'; - $a->save(); - } + public function testTest() + { + $a = new Ticket_1619_Article(); + $a->Translation['fr']->name = 'article'; + $a->Translation['fr']->description = 'article'; + $a->Translation['en']->name = 'english article'; + $a->Translation['en']->description = 'english description'; + $a->save(); + + $b = new Ticket_1619_Article(); + $a->Translation['fr']->name = 'maison'; + $a->Translation['fr']->description = 'habitation'; + $a->Translation['en']->name = 'english house'; + $a->Translation['en']->description = 'english big house'; + $a->save(); + } } class Ticket_1619_Article extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('article'); - $this->hasColumn('id', 'integer', 3, array('type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '3')); - $this->hasColumn('name', 'string', 60, array('type' => 'string', 'length' => '60')); - $this->hasColumn('description', 'string', 4000, array('type' => 'string', 'length' => '4000')); - } + public function setTableDefinition() + { + $this->setTableName('article'); + $this->hasColumn('id', 'integer', 3, array('type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '3')); + $this->hasColumn('name', 'string', 60, array('type' => 'string', 'length' => '60')); + $this->hasColumn('description', 'string', 4000, array('type' => 'string', 'length' => '4000')); + } - public function setUp() - { - $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'name', 1 => 'description'))); - $searchable1 = new Doctrine_Template_Searchable(array('fields' => array(0 => 'name'))); - $i18n0->addChild($searchable1); - $this->actAs($i18n0); - } + public function setUp() + { + $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'name', 1 => 'description'))); + $searchable1 = new Doctrine_Template_Searchable(array('fields' => array(0 => 'name'))); + $i18n0->addChild($searchable1); + $this->actAs($i18n0); + } } - - diff --git a/tests/Ticket/1621TestCase.php b/tests/Ticket/1621TestCase.php index 532905f60..088b3e7d8 100644 --- a/tests/Ticket/1621TestCase.php +++ b/tests/Ticket/1621TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1621_TestCase + * Doctrine_Ticket_1621_TestCase. * - * @package Doctrine * @author floriank * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 - * @version $Revision$ + * + * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1621_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1621_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -43,73 +49,71 @@ public function prepareTables() $this->tables[] = 'Ticket_1621_GroupUser'; parent::prepareTables(); } - + public function prepareData() { - } - public function testRelationAliases() { - // this should go to $this->prepareData(), but i need + public function testRelationAliases() + { + // this should go to $this->prepareData(), but i need // it to fail in a test()-method try { $group = new Ticket_1621_Group(); $group->name = 'group1'; $group->save(); - + $group2 = new Ticket_1621_Group(); $group2->name = 'group2'; $group2->save(); - + $user = new Ticket_1621_User(); - $user->name = "floriank"; + $user->name = 'floriank'; $user->groups[] = $group; - $user->emailAddresses[0]->address = "floriank@localhost"; + $user->emailAddresses[0]->address = 'floriank@localhost'; $user->save(); - + $user2 = new Ticket_1621_User(); - $user2->name = "test2"; - $user2->emailAddresses[0]->address = "test2@localhost"; + $user2->name = 'test2'; + $user2->emailAddresses[0]->address = 'test2@localhost'; $user2->save(); - + $user3 = new Ticket_1621_User(); - $user3->name = "test3"; - $user3->emailAddresses[0]->address = "test3@localhost"; + $user3->name = 'test3'; + $user3->emailAddresses[0]->address = 'test3@localhost'; $user3->save(); - + $user4 = new Ticket_1621_User(); - $user4->name = "test"; + $user4->name = 'test'; $user4->groups[] = $group2; $user4->children[] = $user2; $user4->parents[] = $user3; - $user4->emailAddresses[0]->address = "test@localhost"; + $user4->emailAddresses[0]->address = 'test@localhost'; $user4->save(); } catch (Exception $e) { $this->fail($e); } - - - - //here is the testcode + + // here is the testcode try { $user = Doctrine_Core::getTable('Ticket_1621_User')->findOneByName('floriank'); $newChild = Doctrine_Core::getTable('Ticket_1621_User')->findOneByName('test'); $newFriend = Doctrine_Core::getTable('Ticket_1621_User')->findOneByName('test2'); $newGroup = Doctrine_Core::getTable('Ticket_1621_Group')->findOneByName('group2'); - + $user->children[] = $newChild; $user->groups[] = $newGroup; $user->friends[] = $newFriend; - + $user->save(); - + $this->assertEqual(count($user->children), 1); } catch (Exception $e) { $this->fail($e); } } } - + class Ticket_1621_User extends Doctrine_Record { public function setTableDefinition() @@ -120,33 +124,33 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1621_User as parents', - array('local' => 'parentId', - 'refClass' => 'Ticket_1621_UserReference', - 'foreign' => 'childId', - 'refClassRelationAlias' => 'childrenLinks' - )); - - $this->hasMany('Ticket_1621_User as children', - array('local' => 'childId', - 'foreign' => 'parentId', - 'refClass' => 'Ticket_1621_UserReference', - 'refClassRelationAlias' => 'parentLinks' - )); - - $this->hasMany('Ticket_1621_User as friends', - array('local' => 'leftId', - 'foreign' => 'rightId', - 'equal' => 'true', - 'refClass' => 'Ticket_1621_UserReferenceFriends', - 'refClassRelationAlias' => 'friendLinks' - )); - + $this->hasMany('Ticket_1621_User as parents', + array('local' => 'parentId', + 'refClass' => 'Ticket_1621_UserReference', + 'foreign' => 'childId', + 'refClassRelationAlias' => 'childrenLinks', + )); + + $this->hasMany('Ticket_1621_User as children', + array('local' => 'childId', + 'foreign' => 'parentId', + 'refClass' => 'Ticket_1621_UserReference', + 'refClassRelationAlias' => 'parentLinks', + )); + + $this->hasMany('Ticket_1621_User as friends', + array('local' => 'leftId', + 'foreign' => 'rightId', + 'equal' => 'true', + 'refClass' => 'Ticket_1621_UserReferenceFriends', + 'refClassRelationAlias' => 'friendLinks', + )); + $this->hasMany('Ticket_1621_EmailAdresses as emailAddresses', array('local' => 'id', 'foreign' => 'userId')); - $this->hasMany('Ticket_1621_Group as groups', array('local' => 'userId', - 'foreign' => 'groupId', - 'refClass' => 'Ticket_1621_GroupUser')); + $this->hasMany('Ticket_1621_Group as groups', array('local' => 'userId', + 'foreign' => 'groupId', + 'refClass' => 'Ticket_1621_GroupUser')); } } @@ -174,15 +178,15 @@ public function setTableDefinition() { $this->hasColumn('user_id as userId', 'integer', null); $this->hasColumn('address', 'string', 30); - + $this->option('type', 'INNODB'); $this->option('collate', 'utf8_unicode_ci'); $this->option('charset', 'utf8'); } - + public function setUp() { - $this->hasOne('Ticket_1621_User as user', array('local' => 'userId', 'foreign' => 'id')); + $this->hasOne('Ticket_1621_User as user', array('local' => 'userId', 'foreign' => 'id')); } } @@ -195,9 +199,9 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1621_User as users', array('local' => 'groupId', - 'foreign' => 'userId', - 'refClass' => 'Ticket_1621_GroupUser')); + $this->hasMany('Ticket_1621_User as users', array('local' => 'groupId', + 'foreign' => 'userId', + 'refClass' => 'Ticket_1621_GroupUser')); $this->setTableName('my_group'); } @@ -210,4 +214,4 @@ public function setTableDefinition() $this->hasColumn('user_id as userId', 'integer', null, array('primary' => true)); $this->hasColumn('group_id as groupId', 'integer', null, array('primary' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1621bTestCase.php b/tests/Ticket/1621bTestCase.php index 808289033..b8f5ad575 100644 --- a/tests/Ticket/1621bTestCase.php +++ b/tests/Ticket/1621bTestCase.php @@ -20,20 +20,26 @@ */ /** - * Doctrine_Ticket_1621b_TestCase + * Doctrine_Ticket_1621b_TestCase. * - * @package Doctrine * @author floriank * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 - * @version $Revision$ + * + * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1621b_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1621b_TestCase extends Doctrine_UnitTestCase { - const LANG = "deu"; - + public const LANG = 'deu'; + public function prepareTables() { $this->tables = array(); @@ -46,7 +52,7 @@ public function prepareTables() $this->tables[] = 'Ticket_1621b_ConceptHierarchicalRelation'; parent::prepareTables(); } - + public function prepareData() { $lang = new Ticket_1621b_Language(); @@ -55,229 +61,208 @@ public function prepareData() $lang->Translation['de']->description = 'Die Sprache Deutsch'; $lang->Translation['en']->display = 'german'; $lang->Translation['en']->description = 'The german language'; - - $lang->save(); - + + $lang->save(); + $lang = new Ticket_1621b_Language(); $lang->id = 'eng'; $lang->Translation['de']->display = 'Englisch'; $lang->Translation['de']->description = 'Die Sprache Englisch'; $lang->Translation['en']->display = 'german'; $lang->Translation['en']->description = 'The english language'; - + $lang->save(); - - - - - $plant = new Ticket_1621b_Concept(); - $plant->identifier = "1"; - + + $plant = new Ticket_1621b_Concept(); + $plant->identifier = '1'; + $pref_de = new Ticket_1621b_PrefTerm(); - $pref_de->lexicalValue = "Pflanze"; - $pref_de->langId = "deu"; - + $pref_de->lexicalValue = 'Pflanze'; + $pref_de->langId = 'deu'; + $pref_en = new Ticket_1621b_PrefTerm(); - $pref_en->lexicalValue = "plant"; - $pref_en->langId = "eng"; - + $pref_en->lexicalValue = 'plant'; + $pref_en->langId = 'eng'; + $plant->preferedTerm = $pref_de; $plant->preferedTerms[] = $pref_en; - + $plant->save(); - - - - - $tree = new Ticket_1621b_Concept(); - $tree->identifier = "1.1"; - + + $tree = new Ticket_1621b_Concept(); + $tree->identifier = '1.1'; + $pref_de = new Ticket_1621b_PrefTerm(); - $pref_de->lexicalValue = "Baum"; - $pref_de->langId = "deu"; - + $pref_de->lexicalValue = 'Baum'; + $pref_de->langId = 'deu'; + $pref_en = new Ticket_1621b_PrefTerm(); - $pref_en->lexicalValue = "tree"; - $pref_en->langId = "eng"; - + $pref_en->lexicalValue = 'tree'; + $pref_en->langId = 'eng'; + $alt = new Ticket_1621b_AltTerm(); - $alt->lexicalValue = "bush"; - $alt->langId = "eng"; - + $alt->lexicalValue = 'bush'; + $alt->langId = 'eng'; + $tree->preferedTerm = $pref_de; $tree->preferedTerms[] = $pref_en; $tree->altTerms[] = $alt; - + $tree->broaderConcepts[] = $plant; - + $tree->save(); - - - - - $oak = new Ticket_1621b_Concept(); - $oak->identifier = "1.1"; - + + $oak = new Ticket_1621b_Concept(); + $oak->identifier = '1.1'; + $pref_de = new Ticket_1621b_PrefTerm(); - $pref_de->lexicalValue = "Eiche"; - $pref_de->langId = "deu"; - + $pref_de->lexicalValue = 'Eiche'; + $pref_de->langId = 'deu'; + $pref_en = new Ticket_1621b_PrefTerm(); - $pref_en->lexicalValue = "oak"; - $pref_en->langId = "eng"; - + $pref_en->lexicalValue = 'oak'; + $pref_en->langId = 'eng'; + $oak->preferedTerm = $pref_de; $oak->preferedTerms[] = $pref_en; - + $oak->broaderConcepts[] = $tree; - + $oak->save(); } - public function testInheritance() + public function testInheritance() { try { - $q = Doctrine_Query::create() - ->from("Ticket_1621b_Concept c") - ->innerJoin('c.preferedTerm p') - ->leftJoin('c.narrowerConcepts n') - ->where('c.id = ?', 2); - $rs = $q->fetchOne(); - - $this->assertEqual($rs->preferedTerm->lexicalValue, "Baum"); + $q = Doctrine_Query::create() + ->from('Ticket_1621b_Concept c') + ->innerJoin('c.preferedTerm p') + ->leftJoin('c.narrowerConcepts n') + ->where('c.id = ?', 2) + ; + $rs = $q->fetchOne(); + + $this->assertEqual($rs->preferedTerm->lexicalValue, 'Baum'); } catch (Exception $e) { - $this->fail($e); + $this->fail($e); } } } - - class Ticket_1621b_Concept extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array('unsigned' => true, 'primary' => true, 'autoincrement' => true, 'type' => 'integer', 'length' => '4')); - $this->hasColumn('identifier', 'string', 255, array('type' => 'string', 'length' => '255')); - } - - public function setUp() - { - $this->hasOne('Ticket_1621b_CurrentLanguagePrefTerm as preferedTerm', array('local' => 'id', - 'foreign' => 'conceptId', - 'onDelete' => 'CASCADE')); - - $this->hasMany('Ticket_1621b_PrefTerm as preferedTerms', array('local' => 'id', - 'foreign' => 'conceptId', - 'onDelete' => 'CASCADE')); - - $this->hasMany('Ticket_1621b_AltTerm as altTerms', array('local' => 'id', - 'foreign' => 'conceptId', - 'onDelete' => 'CASCADE')); - - $this->hasMany('Ticket_1621b_Concept as broaderConcepts', array('refClass' => 'Ticket_1621b_ConceptHierarchicalRelation', - 'refClassRelationAlias' => 'narrowerLinks', - 'local' => 'conceptIdSource', - 'foreign' => 'conceptIdTarget')); - - $this->hasMany('Ticket_1621b_Concept as narrowerConcepts', array('refClass' => 'Ticket_1621b_ConceptHierarchicalRelation', - 'refClassRelationAlias' => 'broaderLinks', - 'local' => 'conceptIdTarget', - 'foreign' => 'conceptIdSource')); - } -} + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('unsigned' => true, 'primary' => true, 'autoincrement' => true, 'type' => 'integer', 'length' => '4')); + $this->hasColumn('identifier', 'string', 255, array('type' => 'string', 'length' => '255')); + } + + public function setUp() + { + $this->hasOne('Ticket_1621b_CurrentLanguagePrefTerm as preferedTerm', array('local' => 'id', + 'foreign' => 'conceptId', + 'onDelete' => 'CASCADE')); + $this->hasMany('Ticket_1621b_PrefTerm as preferedTerms', array('local' => 'id', + 'foreign' => 'conceptId', + 'onDelete' => 'CASCADE')); + $this->hasMany('Ticket_1621b_AltTerm as altTerms', array('local' => 'id', + 'foreign' => 'conceptId', + 'onDelete' => 'CASCADE')); + + $this->hasMany('Ticket_1621b_Concept as broaderConcepts', array('refClass' => 'Ticket_1621b_ConceptHierarchicalRelation', + 'refClassRelationAlias' => 'narrowerLinks', + 'local' => 'conceptIdSource', + 'foreign' => 'conceptIdTarget')); + + $this->hasMany('Ticket_1621b_Concept as narrowerConcepts', array('refClass' => 'Ticket_1621b_ConceptHierarchicalRelation', + 'refClassRelationAlias' => 'broaderLinks', + 'local' => 'conceptIdTarget', + 'foreign' => 'conceptIdSource')); + } +} class Ticket_1621b_Term extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array('unsigned' => true, 'primary' => true, 'autoincrement' => true, 'type' => 'integer', 'length' => '4')); - $this->hasColumn('concept_id as conceptId', 'integer', 4, array('type' => 'integer', 'unsigned' => true, 'length' => '4')); - $this->hasColumn('lexical_value as lexicalValue', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); - $this->hasColumn('type', 'string', 20, array('notnull' => true, 'type' => 'string', 'length' => '20')); - $this->hasColumn('lang_id as langId', 'string', 3, array('notnull' => true, 'type' => 'string', 'length' => '3')); - - $this->setSubClasses(array('Ticket_1621b_AltTerm' => array('type' => 'alt'), 'Ticket_1621b_PrefTerm' => array('type' => 'pref'), 'Ticket_1621b_CurrentLanguagePrefTerm' => array('langId' => Doctrine_Ticket_1621b_TestCase::LANG))); - } - - public function setUp() - { - $this->hasOne('Ticket_1621b_Concept as concept', array('local' => 'conceptId', - 'foreign' => 'id')); - $this->hasOne('Ticket_1621b_Language as language', array('local' => 'langId', - 'foreign' => 'id')); - } -} + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('unsigned' => true, 'primary' => true, 'autoincrement' => true, 'type' => 'integer', 'length' => '4')); + $this->hasColumn('concept_id as conceptId', 'integer', 4, array('type' => 'integer', 'unsigned' => true, 'length' => '4')); + $this->hasColumn('lexical_value as lexicalValue', 'string', 255, array('notnull' => true, 'type' => 'string', 'length' => '255')); + $this->hasColumn('type', 'string', 20, array('notnull' => true, 'type' => 'string', 'length' => '20')); + $this->hasColumn('lang_id as langId', 'string', 3, array('notnull' => true, 'type' => 'string', 'length' => '3')); + + $this->setSubClasses(array('Ticket_1621b_AltTerm' => array('type' => 'alt'), 'Ticket_1621b_PrefTerm' => array('type' => 'pref'), 'Ticket_1621b_CurrentLanguagePrefTerm' => array('langId' => Doctrine_Ticket_1621b_TestCase::LANG))); + } + public function setUp() + { + $this->hasOne('Ticket_1621b_Concept as concept', array('local' => 'conceptId', + 'foreign' => 'id')); + $this->hasOne('Ticket_1621b_Language as language', array('local' => 'langId', + 'foreign' => 'id')); + } +} class Ticket_1621b_AltTerm extends Ticket_1621b_Term { - public function setUp() - { - parent::setUp(); - } + public function setUp() + { + parent::setUp(); + } } - - class Ticket_1621b_PrefTerm extends Ticket_1621b_Term { - public function setUp() - { - parent::setUp(); - } + public function setUp() + { + parent::setUp(); + } } - class Ticket_1621b_CurrentLanguagePrefTerm extends Ticket_1621b_PrefTerm { - public function setUp() - { - parent::setUp(); - } + public function setUp() + { + parent::setUp(); + } } - - class Ticket_1621b_Language extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'string', 3, array('type' => 'string', 'primary' => true, 'length' => '3')); - $this->hasColumn('display', 'string', 50, array('type' => 'string', 'notnull' => true, 'length' => '50')); - $this->hasColumn('description', 'string', 50, array('type' => 'string', 'length' => '50')); - } - - public function setUp() - { - $this->hasMany('Ticket_1621b_Term', array('local' => 'id', - 'foreign' => 'langId')); - - $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'display', 1 => 'description'))); - $this->actAs($i18n0); - } + public function setTableDefinition() + { + $this->hasColumn('id', 'string', 3, array('type' => 'string', 'primary' => true, 'length' => '3')); + $this->hasColumn('display', 'string', 50, array('type' => 'string', 'notnull' => true, 'length' => '50')); + $this->hasColumn('description', 'string', 50, array('type' => 'string', 'length' => '50')); + } + + public function setUp() + { + $this->hasMany('Ticket_1621b_Term', array('local' => 'id', + 'foreign' => 'langId')); + + $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'display', 1 => 'description'))); + $this->actAs($i18n0); + } } class Ticket_1621b_ConceptHierarchicalRelation extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array('unsigned' => true, 'primary' => true, 'autoincrement' => true, 'type' => 'integer', 'length' => '4')); - $this->hasColumn('concept_id_s as conceptIdSource', 'integer', 4, array('type' => 'integer', 'unsigned' => true, 'length' => '4')); - $this->hasColumn('concept_id_t as conceptIdTarget', 'integer', 4, array('type' => 'integer', 'unsigned' => true, 'length' => '4')); - } - - public function setUp() - { - $this->hasOne('Ticket_1621b_Concept as hierarchieTarget', array('local' => 'conceptIdTarget', - 'foreign' => 'id')); - - $this->hasOne('Ticket_1621b_Concept as hierarchieSource', array('local' => 'conceptIdSource', - 'foreign' => 'id')); - } -} - + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('unsigned' => true, 'primary' => true, 'autoincrement' => true, 'type' => 'integer', 'length' => '4')); + $this->hasColumn('concept_id_s as conceptIdSource', 'integer', 4, array('type' => 'integer', 'unsigned' => true, 'length' => '4')); + $this->hasColumn('concept_id_t as conceptIdTarget', 'integer', 4, array('type' => 'integer', 'unsigned' => true, 'length' => '4')); + } + public function setUp() + { + $this->hasOne('Ticket_1621b_Concept as hierarchieTarget', array('local' => 'conceptIdTarget', + 'foreign' => 'id')); + $this->hasOne('Ticket_1621b_Concept as hierarchieSource', array('local' => 'conceptIdSource', + 'foreign' => 'id')); + } +} diff --git a/tests/Ticket/1622TestCase.php b/tests/Ticket/1622TestCase.php index c53a03539..a5f5e59fc 100644 --- a/tests/Ticket/1622TestCase.php +++ b/tests/Ticket/1622TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1622_TestCase + * Doctrine_Ticket_1622_TestCase. * - * @package Doctrine * @author floriank * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 - * @version $Revision$ + * + * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1622_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1622_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -39,29 +45,30 @@ public function prepareTables() $this->tables[] = 'Ticket_1622_UserReference'; parent::prepareTables(); } - + public function prepareData() { - $user = new Ticket_1622_User(); - $user->name = "floriank"; - $user->save(); - - $user2 = new Ticket_1622_User(); - $user2->name = "test"; - $user2->parents[] = $user; - $user2->save(); + $user = new Ticket_1622_User(); + $user->name = 'floriank'; + $user->save(); + + $user2 = new Ticket_1622_User(); + $user2->name = 'test'; + $user2->parents[] = $user; + $user2->save(); } - public function testUnlink() { + public function testUnlink() + { $user = Doctrine_Core::getTable('Ticket_1622_User')->findOneByName('floriank'); $child = Doctrine_Core::getTable('Ticket_1622_User')->findOneByName('test'); - + $user->unlink('children', $child->id); - + $this->assertTrue($user->hasReference('children')); $this->assertTrue($user->hasRelation('children')); $this->assertEqual(count($user->children), 0); - + $user->save(); $user->refresh(); @@ -69,7 +76,7 @@ public function testUnlink() { $this->assertEqual(count($user->children), 0); } } - + class Ticket_1622_User extends Doctrine_Record { public function setTableDefinition() @@ -80,19 +87,19 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1622_User as parents', - array('local' => 'parent_id', - 'refClass' => 'Ticket_1622_UserReference', - 'foreign' => 'child_id', - 'refClassRelationAlias' => 'childrenLinks' - )); - - $this->hasMany('Ticket_1622_User as children', - array('local' => 'child_id', - 'foreign' => 'parent_id', - 'refClass' => 'Ticket_1622_UserReference', - 'refClassRelationAlias' => 'parentLinks' - )); + $this->hasMany('Ticket_1622_User as parents', + array('local' => 'parent_id', + 'refClass' => 'Ticket_1622_UserReference', + 'foreign' => 'child_id', + 'refClassRelationAlias' => 'childrenLinks', + )); + + $this->hasMany('Ticket_1622_User as children', + array('local' => 'child_id', + 'foreign' => 'parent_id', + 'refClass' => 'Ticket_1622_UserReference', + 'refClassRelationAlias' => 'parentLinks', + )); } } diff --git a/tests/Ticket/1623TestCase.php b/tests/Ticket/1623TestCase.php index 62566505d..86e98c876 100644 --- a/tests/Ticket/1623TestCase.php +++ b/tests/Ticket/1623TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1623_TestCase + * Doctrine_Ticket_1623_TestCase. * - * @package Doctrine * @author floriank * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 - * @version $Revision$ + * + * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1623_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1623_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -39,18 +45,18 @@ public function prepareTables() $this->tables[] = 'Ticket_1623_UserReference'; parent::prepareTables(); } - + public function prepareData() { $firstUser = null; $oldUser = null; - - for ($i = 1; $i <= 20; $i++) { + + for ($i = 1; $i <= 20; ++$i) { $userI = $user = new Ticket_1623_User(); - $userI->name = "test$i"; - for ($j = 1; $j <= 20; $j++) { + $userI->name = "test{$i}"; + for ($j = 1; $j <= 20; ++$j) { $userJ = new Ticket_1623_User(); - $userJ->name = "test$i-$j"; + $userJ->name = "test{$i}-{$j}"; $userI->children[] = $userJ; $userJ->save(); } @@ -59,7 +65,7 @@ public function prepareData() } $user = new Ticket_1623_User(); - $user->name = "floriank"; + $user->name = 'floriank'; foreach ($floriankChilds as $child) { $user->children[] = $child; } @@ -69,22 +75,22 @@ public function prepareData() public function testPerformance() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + $newChild = new Ticket_1623_User(); $newChild->name = 'myChild'; $newChild->save(); - + $user = Doctrine_Core::getTable('Ticket_1623_User')->findOneByName('floriank'); $user->children[] = $newChild; - + $start = microtime(true); $user->save(); $end = microtime(true); $diff = $end - $start; - //assuming save() should not take longer than one second + // assuming save() should not take longer than one second $this->assertTrue($diff < 1); } - + public function testImplicitSave() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); @@ -92,22 +98,22 @@ public function testImplicitSave() $newChild = new Ticket_1623_User(); $newChild->name = 'myGrandGrandChild'; - + $user = Doctrine_Core::getTable('Ticket_1623_User')->findOneByName('floriank'); $user->children[0]->children[0]->children[] = $newChild; - + $user->save(); - + $user = Doctrine_Core::getTable('Ticket_1623_User')->findByName('myGrandGrandChild'); - //as of Doctrine's default behaviour $newChild should have - //been implicitly saved with $user->save() + // as of Doctrine's default behaviour $newChild should have + // been implicitly saved with $user->save() $this->assertEqual($user->count(), 0); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_CASCADE_SAVES, true); } } - + class Ticket_1623_User extends Doctrine_Record { public function setTableDefinition() @@ -118,38 +124,38 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_1623_User as parents', - array('local' => 'parentId', - 'refClass' => 'Ticket_1623_UserReference', - 'foreign' => 'childId', - 'refClassRelationAlias' => 'childrenLinks' - )); - - $this->hasMany('Ticket_1623_User as children', - array('local' => 'childId', - 'foreign' => 'parentId', - 'refClass' => 'Ticket_1623_UserReference', - 'refClassRelationAlias' => 'parentLinks' - )); + $this->hasMany('Ticket_1623_User as parents', + array('local' => 'parentId', + 'refClass' => 'Ticket_1623_UserReference', + 'foreign' => 'childId', + 'refClassRelationAlias' => 'childrenLinks', + )); + + $this->hasMany('Ticket_1623_User as children', + array('local' => 'childId', + 'foreign' => 'parentId', + 'refClass' => 'Ticket_1623_UserReference', + 'refClassRelationAlias' => 'parentLinks', + )); } - + protected function validate() { - // lets get some silly load in the validation: + // lets get some silly load in the validation: // we do not want any child or parent to have the name 'caesar' - $unwantedName = false; + $unwantedName = false; foreach ($this->children as $child) { - if ($child->name == 'caesar') { + if ('caesar' == $child->name) { $unwantedName = true; } } - + foreach ($this->children as $child) { - if ($child->name == 'caesar') { + if ('caesar' == $child->name) { $unwantedName = true; } } - + if ($unwantedName) { $this->errorStack()->add('children', 'no child should have the name \'caesar\''); } @@ -163,4 +169,4 @@ public function setTableDefinition() $this->hasColumn('parent_id as parentId', 'integer', null, array('primary' => true)); $this->hasColumn('child_id as childId', 'integer', null, array('primary' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1628TestCase.php b/tests/Ticket/1628TestCase.php index d2ca7863f..120145fcb 100644 --- a/tests/Ticket/1628TestCase.php +++ b/tests/Ticket/1628TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1628_TestCase + * Doctrine_Ticket_1628_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1628_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1628_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -41,15 +47,15 @@ public function testTest() // Boolean values $code = trim($builder->buildAttributes(array('use_dql_callbacks' => true))); - $this->assertEqual($code, "\$this->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true);"); + $this->assertEqual($code, '$this->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true);'); $code = trim($builder->buildAttributes(array('use_dql_callbacks' => false))); - $this->assertEqual($code, "\$this->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false);"); + $this->assertEqual($code, '$this->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false);'); // Constant values $code = trim($builder->buildAttributes(array('model_loading' => 'conservative'))); - $this->assertEqual($code, "\$this->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);"); + $this->assertEqual($code, '$this->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING, Doctrine_Core::MODEL_LOADING_CONSERVATIVE);'); $code = trim($builder->buildAttributes(array('export' => array('all', 'constraints')))); - $this->assertEqual($code, "\$this->setAttribute(Doctrine_Core::ATTR_EXPORT, Doctrine_Core::EXPORT_ALL ^ Doctrine_Core::EXPORT_CONSTRAINTS);"); + $this->assertEqual($code, '$this->setAttribute(Doctrine_Core::ATTR_EXPORT, Doctrine_Core::EXPORT_ALL ^ Doctrine_Core::EXPORT_CONSTRAINTS);'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1629TestCase.php b/tests/Ticket/1629TestCase.php index a31814fbd..7f60f84c2 100644 --- a/tests/Ticket/1629TestCase.php +++ b/tests/Ticket/1629TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1629_TestCase + * Doctrine_Ticket_1629_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1629_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1629_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -52,10 +58,11 @@ public function testTest() $q = Doctrine_Query::create() ->from('Ticket_1629_User u') - ->leftJoin('u.Phonenumbers p'); - + ->leftJoin('u.Phonenumbers p') + ; + $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t.password AS t__password, t.deleted_at AS t__deleted_at, t2.id AS t2__id, t2.user_id AS t2__user_id, t2.phonenumber AS t2__phonenumber, t2.deleted_at AS t2__deleted_at FROM ticket_1629__user t LEFT JOIN ticket_1629__phonenumber t2 ON t.id = t2.user_id AND (t2.deleted_at IS NULL) WHERE (t.deleted_at IS NULL)'); - + $users = $q->fetchArray(); $this->assertEqual(count($users), 1); $this->assertEqual(count($users[0]['Phonenumbers']), 0); @@ -92,4 +99,4 @@ public function setUp() $this->actAs('SoftDelete'); $this->hasOne('Ticket_1629_User as User', array('local' => 'user_id', 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1630TestCase.php b/tests/Ticket/1630TestCase.php index 3acb4bbb3..e0fcbcbb7 100644 --- a/tests/Ticket/1630TestCase.php +++ b/tests/Ticket/1630TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1630_TestCase + * Doctrine_Ticket_1630_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1630_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1630_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -55,16 +61,17 @@ public function prepareData() public function testTest() { $cacheConn = Doctrine_Manager::getInstance()->openConnection('sqlite::memory:', 'cache', false); - $cacheDriver = new Doctrine_Cache_Db(array('tableName' => 'cache', 'connection' => $cacheConn)); - $cacheDriver->createTable(); + $cacheDriver = new Doctrine_Cache_Db(array('tableName' => 'cache', 'connection' => $cacheConn)); + $cacheDriver->createTable(); $currentCacheDriver = $this->conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE); - $this->conn->setAttribute(Doctrine_Core::ATTR_QUERY_CACHE, $cacheDriver); + $this->conn->setAttribute(Doctrine_Core::ATTR_QUERY_CACHE, $cacheDriver); try { $q = Doctrine_Query::create() ->from('Ticket_1630_BlogPost p') - ->leftJoin('p.Translation t INDEXBY t.lang'); + ->leftJoin('p.Translation t INDEXBY t.lang') + ; $results = $q->execute(); $results = $q->execute(); @@ -90,4 +97,4 @@ public function setUp() $i18n = new Doctrine_Template_I18n(array('fields' => array('title'))); $this->actAs($i18n); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1636TestCase.php b/tests/Ticket/1636TestCase.php index 448c268b6..7e7cac551 100644 --- a/tests/Ticket/1636TestCase.php +++ b/tests/Ticket/1636TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1636_TestCase + * Doctrine_Ticket_1636_TestCase. * - * @package Doctrine * @author Eugene Janusov * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1636_TestCase extends Doctrine_UnitTestCase { @@ -44,18 +50,18 @@ public function prepareTables() public function prepareData() { - for ($i = 1; $i <= 2; $i++) { + for ($i = 1; $i <= 2; ++$i) { $fileType = new Ticket_1636_FileType(); $fileType->id = $i; - $fileType->name = 'Type ' . $i; + $fileType->name = 'Type '.$i; $fileType->save(); } - for ($i = 1; $i <= 10; $i++) { + for ($i = 1; $i <= 10; ++$i) { $file = new Ticket_1636_File(); $file->id = $i; $file->type_id = 1; - $file->filename = 'File ' . $i; + $file->filename = 'File '.$i; $file->save(); } } @@ -74,7 +80,8 @@ public function testResultCacheShouldStoreRelatedComponentsData() ->innerJoin('f.type t') ->where('f.type_id = ?') ->orderBy('f.id DESC') - ->limit(2); + ->limit(2) + ; // Execute query first time. // Results should be placed into memcache. @@ -84,16 +91,18 @@ public function testResultCacheShouldStoreRelatedComponentsData() // Results should be getted from memcache. $files = $query->execute(array(1)); - if (count($files)) - foreach ($files as $file) + if (count($files)) { + foreach ($files as $file) { $justForTest = $file->type->id; + } + } $executeQueryCount = 0; foreach ($profiler as $event) { - if ($event->getName() == 'execute') { - $executeQueryCount++; - //echo $event->getQuery(), "\n"; + if ('execute' == $event->getName()) { + ++$executeQueryCount; + // echo $event->getQuery(), "\n"; } } @@ -102,8 +111,8 @@ public function testResultCacheShouldStoreRelatedComponentsData() } } -class Ticket_1636_FileType extends Doctrine_Record { - +class Ticket_1636_FileType extends Doctrine_Record +{ public function setTableDefinition() { static $columns = array( @@ -113,13 +122,13 @@ public function setTableDefinition() 'unsigned' => true, 'notnull' => true, 'primary' => true, - 'autoinc' => true + 'autoinc' => true, ), 'name' => array( 'type' => 'string', 'length' => 32, - 'notnull' => true - ) + 'notnull' => true, + ), ); $this->setTableName('files_types'); @@ -130,14 +139,13 @@ public function setUp() { $this->hasMany('Ticket_1636_File as files', array( 'local' => 'id', - 'foreign' => 'type_id' + 'foreign' => 'type_id', )); } - } -class Ticket_1636_File extends Doctrine_Record { - +class Ticket_1636_File extends Doctrine_Record +{ public function setTableDefinition() { static $columns = array( @@ -147,18 +155,18 @@ public function setTableDefinition() 'unsigned' => true, 'notnull' => true, 'primary' => true, - 'autoinc' => true + 'autoinc' => true, ), 'type_id' => array( 'type' => 'integer', 'length' => 4, - 'notnull' => true + 'notnull' => true, ), 'filename' => array( 'type' => 'string', 'length' => 255, - 'notnull' => true - ) + 'notnull' => true, + ), ); $this->setTableName('files'); @@ -169,8 +177,7 @@ public function setUp() { $this->hasOne('Ticket_1636_FileType as type', array( 'local' => 'type_id', - 'foreign' => 'id' + 'foreign' => 'id', )); } - -} \ No newline at end of file +} diff --git a/tests/Ticket/1641TestCase.php b/tests/Ticket/1641TestCase.php index 780d358df..418e34f6b 100644 --- a/tests/Ticket/1641TestCase.php +++ b/tests/Ticket/1641TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1641_TestCase + * Doctrine_Ticket_1641_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1641_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1641_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -46,9 +52,9 @@ public function prepareData() $user = new T1641_User(); $user->name = 'guilhermeblanco'; - $user->save(); + $user->save(); - $user->delete(); + $user->delete(); } public function testTicket() @@ -58,7 +64,7 @@ public function testTicket() $table = Doctrine_Core::getTable('T1641_User'); $this->assertEqual($table->createQuery()->getCountSqlQuery(), 'SELECT COUNT(*) AS num_results FROM t1641__user t WHERE (t.deleted_at IS NULL)'); - + $this->assertEqual($table->count(), 1); $this->assertEqual($table->createQuery()->execute()->count(), 1); $this->assertEqual($table->createQuery()->count(), 1); @@ -79,4 +85,4 @@ public function setUp() { $this->actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1652TestCase.php b/tests/Ticket/1652TestCase.php index 783720a13..95656dc2a 100644 --- a/tests/Ticket/1652TestCase.php +++ b/tests/Ticket/1652TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_1652_TestCase + * Doctrine_Ticket_1652_TestCase. * - * @package Doctrine * @author floriank * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1652_TestCase extends Doctrine_UnitTestCase { @@ -41,27 +47,28 @@ public function prepareTables() public function prepareData() { - $user = new Ticket_1652_User(); - $user->id = 1; - $user->name = "floriank"; - $user->save(); + $user = new Ticket_1652_User(); + $user->id = 1; + $user->name = 'floriank'; + $user->save(); } - public function testValidate() { + public function testValidate() + { $doctrine = new ReflectionClass('Doctrine_Core'); if ($doctrine->hasConstant('VALIDATE_USER')) { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_USER); } else { - //I only want my overridden Record->validate()-methods for validation + // I only want my overridden Record->validate()-methods for validation Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, - Doctrine_Core::VALIDATE_ALL & - ~Doctrine_Core::VALIDATE_LENGTHS & - ~Doctrine_Core::VALIDATE_CONSTRAINTS & - ~Doctrine_Core::VALIDATE_TYPES); + Doctrine_Core::VALIDATE_ALL & + ~Doctrine_Core::VALIDATE_LENGTHS & + ~Doctrine_Core::VALIDATE_CONSTRAINTS & + ~Doctrine_Core::VALIDATE_TYPES); } $user = Doctrine_Core::getTable('Ticket_1652_User')->findOneById(1); - $user->name = "test"; + $user->name = 'test'; if ($user->isValid()) { try { $user->save(); @@ -73,7 +80,7 @@ public function testValidate() { $user = Doctrine_Core::getTable('Ticket_1652_User')->findOneById(1); $this->assertNotEqual($user->name, 'test'); - //reset validation to default for further testcases + // reset validation to default for further testcases Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } } @@ -86,9 +93,11 @@ public function setTableDefinition() $this->hasColumn('name', 'string', 30); } - protected function validate() { - if ($this->name == "test") { - $this->getErrorStack()->add("badName", "No testnames allowed!"); + protected function validate() + { + if ('test' == $this->name) { + $this->getErrorStack()->add('badName', 'No testnames allowed!'); + return false; } } diff --git a/tests/Ticket/1653TestCase.php b/tests/Ticket/1653TestCase.php index fe95c6521..e177d8146 100644 --- a/tests/Ticket/1653TestCase.php +++ b/tests/Ticket/1653TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1653_TestCase + * Doctrine_Ticket_1653_TestCase. * - * @package Doctrine * @author floriank * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 - * @version $Revision$ + * + * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1653_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1653_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -39,28 +45,27 @@ public function prepareTables() $this->tables[] = 'Ticket_1653_Email'; parent::prepareTables(); } - + public function prepareData() { - } public function testValidate() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + $user = new Ticket_1653_User(); $mail = new Ticket_1653_Email(); - + $user->id = 1; - $user->name = "floriank"; + $user->name = 'floriank'; $user->emails[] = $mail; - - //explicit call of isValid() should return false since $mail->address is null + + // explicit call of isValid() should return false since $mail->address is null $this->assertFalse($user->isValid(true)); - //reset validation to default for further testcases + // reset validation to default for further testcases Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } @@ -87,18 +92,19 @@ public function setTableDefinition() { $this->hasColumn('name', 'string', 255); } - + public function setUp() { $this->hasMany('Ticket_1653_Email as emails', array('local' => 'id', - 'foreign' => 'user_id', - 'cascade' => array('delete'))); + 'foreign' => 'user_id', + 'cascade' => array('delete'))); } - + protected function validate() { - if ($this->name == "test") { - $this->getErrorStack()->add("badName", "No testnames allowed!"); + if ('test' == $this->name) { + $this->getErrorStack()->add('badName', 'No testnames allowed!'); + return false; } } @@ -111,11 +117,11 @@ public function setTableDefinition() $this->hasColumn('user_id', 'integer'); $this->hasColumn('address', 'string', 255, array('notnull' => true)); } - + public function setUp() { $this->hasOne('Ticket_1653_User as user', array('local' => 'user_id', - 'foreign' => 'id', - 'cascade' => array('delete'))); + 'foreign' => 'id', + 'cascade' => array('delete'))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1658TestCase.php b/tests/Ticket/1658TestCase.php index 49cd59b52..0a3e08773 100644 --- a/tests/Ticket/1658TestCase.php +++ b/tests/Ticket/1658TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1658_TestCase + * Doctrine_Ticket_1658_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1658_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1658_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -74,4 +80,4 @@ public function setPassword($password) { throw new Doctrine_Exception('Set password called'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1674TestCase.php b/tests/Ticket/1674TestCase.php index 0edfe8c39..87b14799a 100644 --- a/tests/Ticket/1674TestCase.php +++ b/tests/Ticket/1674TestCase.php @@ -20,27 +20,34 @@ */ /** - * Doctrine_Ticket_1674_TestCase + * Doctrine_Ticket_1674_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1674_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1674_TestCase extends Doctrine_UnitTestCase { public function testTest() { - $users = Doctrine_Query::create() + $users = Doctrine_Query::create() ->from('User u') ->leftJoin('u.Phonenumber p') ->having('COUNT(p.id) > 0') ->groupBy('u.id') ->limit(1) - ->execute(); + ->execute() + ; $xml = $users->exportTo('xml'); diff --git a/tests/Ticket/1703TestCase.php b/tests/Ticket/1703TestCase.php index 5fab692db..f146d4aa1 100644 --- a/tests/Ticket/1703TestCase.php +++ b/tests/Ticket/1703TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Template_TestCase + * Doctrine_Template_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1703_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1703_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -47,41 +53,40 @@ public function testSerialization() $foo = serialize($revision); $this->assertEqual(1, $revision->content_id); } - } class Ticket_1703_Content extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'autoincrement' => true, 'primary' => true, 'length' => '4')); - $this->hasColumn('content', 'string', null, array('type' => 'string')); - } + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'autoincrement' => true, 'primary' => true, 'length' => '4')); + $this->hasColumn('content', 'string', null, array('type' => 'string')); + } - public function setUp() - { - $this->hasMany('Ticket_1703_Revision as revision', array('local' => 'id', - 'foreign' => 'content_id')); - } + public function setUp() + { + $this->hasMany('Ticket_1703_Revision as revision', array('local' => 'id', + 'foreign' => 'content_id')); + } } class Ticket_1703_Revision extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('revision', 'integer', 4, array('type' => 'integer', 'notnull' => true, 'default' => 1, 'length' => '4', 'primary' => true)); - $this->hasColumn('user_name', 'string', 255, array('type' => 'string', 'notnull' => true, 'length' => '255')); - $this->hasColumn('comment', 'string', 255, array('type' => 'string', 'length' => '255')); - $this->hasColumn('content_id', 'integer', 4, array('type' => 'integer', 'primary' => true, 'length' => '4')); - } + public function setTableDefinition() + { + $this->hasColumn('revision', 'integer', 4, array('type' => 'integer', 'notnull' => true, 'default' => 1, 'length' => '4', 'primary' => true)); + $this->hasColumn('user_name', 'string', 255, array('type' => 'string', 'notnull' => true, 'length' => '255')); + $this->hasColumn('comment', 'string', 255, array('type' => 'string', 'length' => '255')); + $this->hasColumn('content_id', 'integer', 4, array('type' => 'integer', 'primary' => true, 'length' => '4')); + } - public function setUp() - { - $this->hasOne('Ticket_1703_Content as contentStorage', array('local' => 'content_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + public function setUp() + { + $this->hasOne('Ticket_1703_Content as contentStorage', array('local' => 'content_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); - $timestampable0 = new Doctrine_Template_Timestampable(array('update' => array('disabled' => true))); - $this->actAs($timestampable0); - } -} \ No newline at end of file + $timestampable0 = new Doctrine_Template_Timestampable(array('update' => array('disabled' => true))); + $this->actAs($timestampable0); + } +} diff --git a/tests/Ticket/1706TestCase.php b/tests/Ticket/1706TestCase.php index 49a0d37f8..5deff1627 100644 --- a/tests/Ticket/1706TestCase.php +++ b/tests/Ticket/1706TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1706_TestCase + * Doctrine_Ticket_1706_TestCase. * - * @package Doctrine * @author David Abdemoulaie * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1706_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1706_TestCase extends Doctrine_UnitTestCase { public function testCachedResultsAreSpecificToDsn() { @@ -61,12 +67,13 @@ public function testCachedResultsAreSpecificToDsn() $user = new Ticket_1706_User(); $user->name = 'Bob'; $user->save(); - + $manager->setCurrentConnection('conn_1'); $u1 = Doctrine_Query::create() ->from('Ticket_1706_User u') ->useResultCache() - ->execute(); + ->execute() + ; $this->assertEqual(1, count($u1)); $this->assertEqual('Allen', $u1[0]->name); @@ -75,7 +82,8 @@ public function testCachedResultsAreSpecificToDsn() $u2 = Doctrine_Query::create() ->from('Ticket_1706_User u') ->useResultCache() - ->execute(); + ->execute() + ; $this->assertEqual(1, count($u2)); $this->assertEqual('Bob', $u2[0]->name); diff --git a/tests/Ticket/1713TestCase.php b/tests/Ticket/1713TestCase.php index 142a09742..0a92d5f35 100644 --- a/tests/Ticket/1713TestCase.php +++ b/tests/Ticket/1713TestCase.php @@ -1,8 +1,11 @@ query('FROM Parent1713 m'); - - foreach ($records as $rec) { - $this->assertEqual(get_class($rec), $rec['title']); + + foreach ($records as $rec) { + $this->assertEqual(get_class($rec), $rec['title']); } } } class Parent1713 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('mytable'); - $this->hasColumn('id', 'integer', 4, array ( - 'primary' => true, - 'autoincrement' => true, - 'notnull' => true, - )); - - $this->hasColumn('title', 'string', 255, array ()); - $this->hasColumn('PHP_TYPE as phpType', 'integer', 11, array ()); - - $this->setSubclasses( - array('Child1713A' => array('phpType' => 1)) - ); - } - - public function setUp() - { - - } + public function setTableDefinition() + { + $this->setTableName('mytable'); + $this->hasColumn('id', 'integer', 4, array( + 'primary' => true, + 'autoincrement' => true, + 'notnull' => true, + )); + + $this->hasColumn('title', 'string', 255, array()); + $this->hasColumn('PHP_TYPE as phpType', 'integer', 11, array()); + + $this->setSubclasses( + array('Child1713A' => array('phpType' => 1)) + ); + } + + public function setUp() + { + } } class Child1713A extends Parent1713 { - -} \ No newline at end of file +} diff --git a/tests/Ticket/1716TestCase.php b/tests/Ticket/1716TestCase.php index bbd6d3c96..6c3075bb4 100644 --- a/tests/Ticket/1716TestCase.php +++ b/tests/Ticket/1716TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1716_TestCase + * Doctrine_Ticket_1716_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1716_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1716_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -69,4 +75,4 @@ public function setUp() { $this->actAs('Timestampable'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1725TestCase.php b/tests/Ticket/1725TestCase.php index 2dab9d646..f551e3254 100644 --- a/tests/Ticket/1725TestCase.php +++ b/tests/Ticket/1725TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1725_TestCase + * Doctrine_Ticket_1725_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1725_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1725_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -68,7 +74,7 @@ public function setUp() $this->actAs('Timestampable'); $this->actAs('SoftDelete'); $this->actAs('Versionable', array( - 'generateRelations' => false, - 'deleteVersions' => false)); + 'generateRelations' => false, + 'deleteVersions' => false)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1727/models1/Ticket_1727_Model1.php b/tests/Ticket/1727/models1/Ticket_1727_Model1.php index f305b7740..effac8eed 100644 --- a/tests/Ticket/1727/models1/Ticket_1727_Model1.php +++ b/tests/Ticket/1727/models1/Ticket_1727_Model1.php @@ -1,8 +1,9 @@ hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1727/models1/Ticket_1727_Model2.php b/tests/Ticket/1727/models1/Ticket_1727_Model2.php index 5e494d45f..c7d97175f 100644 --- a/tests/Ticket/1727/models1/Ticket_1727_Model2.php +++ b/tests/Ticket/1727/models1/Ticket_1727_Model2.php @@ -1,8 +1,9 @@ hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1727/models2/Ticket_1727_Model3.php b/tests/Ticket/1727/models2/Ticket_1727_Model3.php index 7ef4ea10a..90a5b2b99 100644 --- a/tests/Ticket/1727/models2/Ticket_1727_Model3.php +++ b/tests/Ticket/1727/models2/Ticket_1727_Model3.php @@ -1,8 +1,9 @@ hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1727/models2/Ticket_1727_Model4.php b/tests/Ticket/1727/models2/Ticket_1727_Model4.php index 6fd09f2ec..2b202a3f3 100644 --- a/tests/Ticket/1727/models2/Ticket_1727_Model4.php +++ b/tests/Ticket/1727/models2/Ticket_1727_Model4.php @@ -1,8 +1,9 @@ hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1727TestCase.php b/tests/Ticket/1727TestCase.php index 968de753e..6b9c0cfde 100644 --- a/tests/Ticket/1727TestCase.php +++ b/tests/Ticket/1727TestCase.php @@ -20,50 +20,56 @@ */ /** - * Doctrine_Ticket_1727_TestCase + * Doctrine_Ticket_1727_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1727_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1727_TestCase extends Doctrine_UnitTestCase { public function testTest() { - $models1 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models1', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); - $models2 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models1', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models1 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models1', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models2 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models1', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); $this->assertEqual($models1, $models2); - $models1 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models1'); - $models2 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models1'); + $models1 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models1'); + $models2 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models1'); $this->assertEqual($models1, $models2); - $models1 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models1', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); - $models2 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models1', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models1 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models1', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models2 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models1', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); $this->assertEqual($models1, $models2); - $models1 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models2', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); - $models2 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models2', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models1 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models2', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models2 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models2', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); $this->assertEqual($models1, $models2); - $models1 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models2'); - $models2 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models2'); + $models1 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models2'); + $models2 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models2'); $this->assertEqual($models1, $models2); - $models1 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models2', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); - $models2 = Doctrine_Core::loadModels(dirname(__FILE__) . '/1727/models2', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models1 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models2', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models2 = Doctrine_Core::loadModels(dirname(__FILE__).'/1727/models2', Doctrine_Core::MODEL_LOADING_CONSERVATIVE); $this->assertEqual($models1, $models2); - $models1 = Doctrine_Core::loadModels(array(dirname(__FILE__) . '/1727/models1', dirname(__FILE__) . '/1727/models2')); - $models2 = Doctrine_Core::loadModels(array(dirname(__FILE__) . '/1727/models1', dirname(__FILE__) . '/1727/models2')); + $models1 = Doctrine_Core::loadModels(array(dirname(__FILE__).'/1727/models1', dirname(__FILE__).'/1727/models2')); + $models2 = Doctrine_Core::loadModels(array(dirname(__FILE__).'/1727/models1', dirname(__FILE__).'/1727/models2')); $this->assertEqual($models1, $models2); - $models1 = Doctrine_Core::loadModels(array(dirname(__FILE__) . '/1727/models1', dirname(__FILE__) . '/1727/models2'), Doctrine_Core::MODEL_LOADING_CONSERVATIVE); - $models2 = Doctrine_Core::loadModels(array(dirname(__FILE__) . '/1727/models1', dirname(__FILE__) . '/1727/models2'), Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models1 = Doctrine_Core::loadModels(array(dirname(__FILE__).'/1727/models1', dirname(__FILE__).'/1727/models2'), Doctrine_Core::MODEL_LOADING_CONSERVATIVE); + $models2 = Doctrine_Core::loadModels(array(dirname(__FILE__).'/1727/models1', dirname(__FILE__).'/1727/models2'), Doctrine_Core::MODEL_LOADING_CONSERVATIVE); $this->assertEqual($models1, $models2); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1729TestCase.php b/tests/Ticket/1729TestCase.php index 6cb39c7aa..f4e862930 100644 --- a/tests/Ticket/1729TestCase.php +++ b/tests/Ticket/1729TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1729_TestCase + * Doctrine_Ticket_1729_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1729_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1729_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -55,7 +61,8 @@ public function testTest() $q = Doctrine_Query::create() ->select('u.id') - ->from('Ticket_1729_User u'); + ->from('Ticket_1729_User u') + ; $this->assertEqual($q->count(), 1); $results = $q->execute(); $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id FROM ticket_1729__user t WHERE (t.deleted_at IS NULL)'); @@ -77,4 +84,4 @@ public function setUp() { $this->actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1745TestCase.php b/tests/Ticket/1745TestCase.php index 057442a0d..a12c6e2e8 100644 --- a/tests/Ticket/1745TestCase.php +++ b/tests/Ticket/1745TestCase.php @@ -20,20 +20,27 @@ */ /** - * Doctrine_Ticket_1745_TestCase + * Doctrine_Ticket_1745_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1745_TestCase extends Doctrine_UnitTestCase { - - public function prepareTables() { +class Doctrine_Ticket_1745_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { $this->tables = array('locality'); - + parent::prepareTables(); } @@ -43,37 +50,40 @@ public function prepareData() $locality->postal_code = '1920'; $locality->city = 'Martigny'; $locality->save(); - + $locality = new Locality(); $locality->postal_code = '1965'; $locality->city = 'Savièse'; $locality->save(); - + $locality = new Locality(); $locality->postal_code = '2300'; $locality->city = 'Neuchâtel'; $locality->save(); } - + public function testSearchable() { - $query = Doctrine_Query::create() - ->from('Locality l'); - $query = Doctrine_Core::getTable('Locality')->search('martigny', $query); - $results = $query->fetchArray(); - $this->assertEqual($results[0]['city'], 'Martigny'); - - $query = Doctrine_Query::create() - ->from('Locality l'); - $query = Doctrine_Core::getTable('Locality')->search('saviese', $query); - $results = $query->fetchArray(); - $this->assertEqual($results[0]['city'], 'Savièse'); - - $query = Doctrine_Query::create() - ->from('Locality l'); - $query = Doctrine_Core::getTable('Locality')->search('neuchatel', $query); - $results = $query->fetchArray(); - $this->assertEqual($results[0]['city'], 'Neuchâtel'); + $query = Doctrine_Query::create() + ->from('Locality l') + ; + $query = Doctrine_Core::getTable('Locality')->search('martigny', $query); + $results = $query->fetchArray(); + $this->assertEqual($results[0]['city'], 'Martigny'); + + $query = Doctrine_Query::create() + ->from('Locality l') + ; + $query = Doctrine_Core::getTable('Locality')->search('saviese', $query); + $results = $query->fetchArray(); + $this->assertEqual($results[0]['city'], 'Savièse'); + + $query = Doctrine_Query::create() + ->from('Locality l') + ; + $query = Doctrine_Core::getTable('Locality')->search('neuchatel', $query); + $results = $query->fetchArray(); + $this->assertEqual($results[0]['city'], 'Neuchâtel'); } } @@ -81,15 +91,15 @@ class Locality extends Doctrine_Record { public function setTableDefinition() { - $this->setTableName('locality'); - $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '4')); - $this->hasColumn('postal_code', 'string', 6, array('type' => 'string', 'notnull' => true, 'length' => '6')); - $this->hasColumn('city', 'string', 120, array('type' => 'string', 'notnull' => true, 'length' => '120')); + $this->setTableName('locality'); + $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '4')); + $this->hasColumn('postal_code', 'string', 6, array('type' => 'string', 'notnull' => true, 'length' => '6')); + $this->hasColumn('city', 'string', 120, array('type' => 'string', 'notnull' => true, 'length' => '120')); } public function setUp() { - $searchable0 = new Doctrine_Template_Searchable(array('fields' => array(0 => 'city'))); - $this->actAs($searchable0); + $searchable0 = new Doctrine_Template_Searchable(array('fields' => array(0 => 'city'))); + $this->actAs($searchable0); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1762TestCase.php b/tests/Ticket/1762TestCase.php index be14c19c2..cbd614ec8 100644 --- a/tests/Ticket/1762TestCase.php +++ b/tests/Ticket/1762TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1762_TestCase + * Doctrine_Ticket_1762_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1762_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1762_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -43,7 +49,8 @@ public function testTest() $query = Doctrine_Query::create() ->from('User2 u') ->leftJoin('u.Roles') - ->orderBy('u.id'); + ->orderBy('u.id') + ; $pager = new Doctrine_Pager($query, 1, 20); $records = $pager->execute($conn); @@ -63,9 +70,9 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Role2 as Roles', array('refClass' => 'UserRole2', - 'local' => 'user_id', - 'foreign' => 'role_id')); + $this->hasMany('Role2 as Roles', array('refClass' => 'UserRole2', + 'local' => 'user_id', + 'foreign' => 'role_id')); } } @@ -78,9 +85,9 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('User2 as Users', array('refClass' => 'UserRole2', - 'local' => 'role_id', - 'foreign' => 'User_id')); + $this->hasMany('User2 as Users', array('refClass' => 'UserRole2', + 'local' => 'role_id', + 'foreign' => 'User_id')); } } @@ -91,4 +98,4 @@ public function setTableDefinition() $this->hasColumn('user_id', 'integer', null, array('primary' => true)); $this->hasColumn('role_id', 'integer', null, array('primary' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1763TestCase.php b/tests/Ticket/1763TestCase.php index 2f42e7f41..2878dd244 100644 --- a/tests/Ticket/1763TestCase.php +++ b/tests/Ticket/1763TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1763_TestCase + * Doctrine_Ticket_1763_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1763_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1763_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -72,12 +78,12 @@ class Ticket_1763_User extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('email_address', 'string', 255, array('unique' => true, - 'notnull' => true, - 'email' => true)); - $this->hasColumn('username', 'string', 255, array('unique' => true, - 'notnull' => true)); + $this->hasColumn('email_address', 'string', 255, array('unique' => true, + 'notnull' => true, + 'email' => true)); + $this->hasColumn('username', 'string', 255, array('unique' => true, + 'notnull' => true)); $this->hasColumn('password', 'string', 255); - $this->hasColumn('ip_address','string', 255, array('notnull' => true, 'ip' => true)); + $this->hasColumn('ip_address', 'string', 255, array('notnull' => true, 'ip' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1764TestCase.php b/tests/Ticket/1764TestCase.php index 89ccc48cb..92cfb0640 100644 --- a/tests/Ticket/1764TestCase.php +++ b/tests/Ticket/1764TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1764_TestCase + * Doctrine_Ticket_1764_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1764_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1764_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -63,4 +69,4 @@ public function setTableDefinition() $this->hasColumn('password', 'string', 255); $this->hasColumn('rate', 'decimal', null, array('notnull' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1768TestCase.php b/tests/Ticket/1768TestCase.php index 8423fd07e..3a46b5212 100644 --- a/tests/Ticket/1768TestCase.php +++ b/tests/Ticket/1768TestCase.php @@ -1,17 +1,25 @@ from('Ticket_1768_Foo f') - ->where('f.bar = ?', 1); + ->where('f.bar = ?', 1) + ; $queryTwo = Doctrine_Query::create() ->from('Ticket_1768_Foo f') - ->where('f.bar = ?', 2); + ->where('f.bar = ?', 2) + ; - //Result hashes should be different + // Result hashes should be different $this->assertNotEqual($queryOne->calculateResultCacheHash(), $queryTwo->calculateResultCacheHash()); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1783TestCase.php b/tests/Ticket/1783TestCase.php index 39d34a2c7..3f9bed65d 100644 --- a/tests/Ticket/1783TestCase.php +++ b/tests/Ticket/1783TestCase.php @@ -1,15 +1,21 @@ tables[] = 'Ticket_1783'; parent::prepareTables(); } - + public function testValidateLargeIntegers() { - $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); $test = new Ticket_1783(); @@ -29,4 +35,4 @@ public function setTableDefinition() { $this->hasColumn('bigint', 'integer', null, array('type' => 'integer', 'unsigned' => true)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1793TestCase.php b/tests/Ticket/1793TestCase.php index 60c20df5b..9a8cf62bb 100644 --- a/tests/Ticket/1793TestCase.php +++ b/tests/Ticket/1793TestCase.php @@ -20,35 +20,41 @@ */ /** - * Doctrine_Ticket_1793_TestCase + * Doctrine_Ticket_1793_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1793_TestCase extends Doctrine_UnitTestCase { public function prepareData() { - $order1 = new Ticket_1793_Order; + $order1 = new Ticket_1793_Order(); $order1->status = 'new'; $order1->save(); /* The enum column can be changed if the value isn't equal to that of one of the column aggregation's keyValue's: */ - $order2 = new Ticket_1793_Order; + $order2 = new Ticket_1793_Order(); $order2->status = 'shipped'; // 'shipped' isn't one of the column aggregation keyValue's $order2->save(); // Same as $order2 - $order3 = new Ticket_1793_Order; + $order3 = new Ticket_1793_Order(); $order3->status = 'shipped'; $order3->save(); - $order4 = new Ticket_1793_Order; + $order4 = new Ticket_1793_Order(); $order4->status = 'new'; $order4->save(); } @@ -63,41 +69,41 @@ public function testTicket() { // Doesn't work: $order1 = Doctrine_Core::getTable('Ticket_1793_Order')->find(1); - //echo $order1->status; // 'new' + // echo $order1->status; // 'new' $order1->status = 'completed'; $order1->save(); $this->assertEqual($order1->status, 'completed'); // Works because previous status was not one of the column aggregation's keyValue's $order2 = Doctrine_Core::getTable('Ticket_1793_Order')->find(2); - //echo $order2->status; // 'shipping' + // echo $order2->status; // 'shipping' $order2->status = 'new'; $order2->save(); $this->assertEqual($order2->status, 'new'); // This works because it reuses $order2 from above: - //echo $order2->status; // 'new' + // echo $order2->status; // 'new' $order2->status = 'completed'; $order2->save(); $this->assertEqual($order2->status, 'completed'); // Works because previous status was not one of the column aggregation's keyValue's $order3 = Doctrine_Core::getTable('Ticket_1793_Order')->find(3); - //echo $order2->status; // 'shipping' + // echo $order2->status; // 'shipping' $order3->status = 'new'; $order3->save(); $this->assertEqual($order3->status, 'new'); // Now this doesn't work because it's re-finding order #3 instead of re-using $order3. $order3 = Doctrine_Core::getTable('Ticket_1793_Order')->find(3); - //echo $order3->status; // 'new' + // echo $order3->status; // 'new' $order3->status = 'completed'; $order3->save(); $this->assertEqual($order3->status, 'completed'); /* Changing the table name to Ticket_1793_OrdersNew still fails. */ $order4 = Doctrine_Core::getTable('Ticket_1793_OrdersNew')->find(4); - //echo $order4->status; // 'new' + // echo $order4->status; // 'new' $order4->status = 'completed'; $order4->save(); $this->assertEqual($order4->status, 'completed'); @@ -107,32 +113,29 @@ public function testTicket() ->update('Ticket_1793_Order o') ->set('o.status', '?', 'completed') ->where('o.id = ?', 1) - ->execute(); + ->execute() + ; $order1 = Doctrine_Core::getTable('Ticket_1793_Order')->find(1); $this->assertEqual($order1->status, 'completed'); } - } class Ticket_1793_Order extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('ticket_1793_orders'); - $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'unsigned' => '1', 'primary' => true, 'autoincrement' => true, 'length' => '4')); - $this->hasColumn('status', 'enum', null, array('type' => 'enum', 'values' => array(0 => 'new', 1 => 'completed', 2 => 'shipped'))); - - $this->setSubClasses(array('Ticket_1793_OrdersNew' => array('status' => 'new'), 'Ticket_1793_OrdersCompleted' => array('status' => 'completed'))); - } + public function setTableDefinition() + { + $this->setTableName('ticket_1793_orders'); + $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'unsigned' => '1', 'primary' => true, 'autoincrement' => true, 'length' => '4')); + $this->hasColumn('status', 'enum', null, array('type' => 'enum', 'values' => array(0 => 'new', 1 => 'completed', 2 => 'shipped'))); + $this->setSubClasses(array('Ticket_1793_OrdersNew' => array('status' => 'new'), 'Ticket_1793_OrdersCompleted' => array('status' => 'completed'))); + } } class Ticket_1793_OrdersCompleted extends Ticket_1793_Order { - } class Ticket_1793_OrdersNew extends Ticket_1793_Order { - -} \ No newline at end of file +} diff --git a/tests/Ticket/1795TestCase.php b/tests/Ticket/1795TestCase.php index 28472b773..5ab0e5491 100644 --- a/tests/Ticket/1795TestCase.php +++ b/tests/Ticket/1795TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1795_TestCase + * Doctrine_Ticket_1795_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1795_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1795_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -74,4 +80,4 @@ public function customMethod() { return 'custom method'; } -} \ No newline at end of file +} diff --git a/tests/Ticket/1799TestCase.php b/tests/Ticket/1799TestCase.php index 0fe8b7945..e704c14a3 100644 --- a/tests/Ticket/1799TestCase.php +++ b/tests/Ticket/1799TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1799_TestCase + * Doctrine_Ticket_1799_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1799_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1799_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -55,6 +61,11 @@ public function testTest() } } +/** + * @internal + * + * @coversNothing + */ class Ticket_1799_Test extends Doctrine_Record { public function setTableDefinition() @@ -66,4 +77,4 @@ public function setUp() { $this->actAs('Geographical'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1808TestCase.php b/tests/Ticket/1808TestCase.php index 384bbb4d2..24e0dc21f 100644 --- a/tests/Ticket/1808TestCase.php +++ b/tests/Ticket/1808TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1808_TestCase + * Doctrine_Ticket_1808_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1808_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1808_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -51,6 +57,6 @@ public function testTest() $this->assertIdentical($user, $user2); $test = $userTable->findOneByNameAndLoginnameAndEmailId($user->name, $user->loginname, $user->email_id, Doctrine_Core::HYDRATE_ARRAY); - $this->assertTrue(is_array($test)); + $this->assertTrue(is_array($test)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1818TestCase.php b/tests/Ticket/1818TestCase.php index 81ceca04f..ff7cf06b4 100644 --- a/tests/Ticket/1818TestCase.php +++ b/tests/Ticket/1818TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1818_TestCase + * Doctrine_Ticket_1818_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1818_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1818_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -67,18 +73,16 @@ public function setTableDefinition() public function setUp() { $this->hasOne('Ticket_1818_Bar as Bar', array('local' => 'bar_id', - 'foreign' => 'id')); + 'foreign' => 'id')); } } class Ticket_1818_BarB extends Ticket_1818_Bar { - } class Ticket_1818_BarA extends Ticket_1818_Bar { - } class Ticket_1818_Bar extends Doctrine_Record @@ -93,6 +97,6 @@ public function setTableDefinition() public function setUp() { $this->hasMany('Ticket_1818_Foo as Foos', array('local' => 'id', - 'foreign' => 'bar_id')); + 'foreign' => 'bar_id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1821TestCase.php b/tests/Ticket/1821TestCase.php index cbe3130d7..02d2fcd30 100644 --- a/tests/Ticket/1821TestCase.php +++ b/tests/Ticket/1821TestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_Ticket_1821_TestCase + * Doctrine_Ticket_1821_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Andrea Baron + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1821_TestCase extends Doctrine_UnitTestCase { @@ -42,107 +49,113 @@ public function prepareTables() ); parent::prepareTables(); } - + public function prepareData() { - } - + public function execTest($klass) { - //stores old validation setting + // stores old validation setting $validation = Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_VALIDATE); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + $record = new $klass(); - $record->name = 'test'; - try { - $record->save(); - } - catch(Exception $e) { - $this->fail( - 'Failed to execute validation with class = "' . $klass - . '". Exception message is: ' . $e->getMessage() - ); - } - $this->pass(); - - Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, $validation); + $record->name = 'test'; + try { + $record->save(); + } catch (Exception $e) { + $this->fail( + 'Failed to execute validation with class = "'.$klass + .'". Exception message is: '.$e->getMessage() + ); + } + $this->pass(); + + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_VALIDATE, $validation); } - + public function testShouldAllowNotUsingAliases() { $this->execTest('Doctrine_Ticket_1821_Record'); } - + public function testShouldAllowUsingAliasesOnId() { $this->execTest('Doctrine_Ticket_1821_Record_ID_Aliased'); } - + public function testShouldAllowUsingAliasesOnColumn() { $this->execTest('Doctrine_Ticket_1821_Record_Column_Aliased'); } - + public function testShouldAllowUsingAliasesOnBoth() { $this->execTest('Doctrine_Ticket_1821_Record_Full_Aliased'); } } - -class Doctrine_Ticket_1821_Record_Full_Aliased extends Doctrine_Record { - public function setTableDefinition() { + +class Doctrine_Ticket_1821_Record_Full_Aliased extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('user_id as id', 'integer', 4, array( - 'autoincrement' => true, - 'notnull' => true, - 'primary' => true - )); + 'autoincrement' => true, + 'notnull' => true, + 'primary' => true, + )); $this->hasColumn('user_name as name', 'string', 255, array( - 'notnull' => true, - 'unique' => true - )); + 'notnull' => true, + 'unique' => true, + )); } } -class Doctrine_Ticket_1821_Record_ID_Aliased extends Doctrine_Record { - public function setTableDefinition() { +class Doctrine_Ticket_1821_Record_ID_Aliased extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('user_id as id', 'integer', 4, array( - 'autoincrement' => true, - 'notnull' => true, - 'primary' => true - )); + 'autoincrement' => true, + 'notnull' => true, + 'primary' => true, + )); $this->hasColumn('name', 'string', 255, array( - 'notnull' => true, - 'unique' => true - )); + 'notnull' => true, + 'unique' => true, + )); } } -class Doctrine_Ticket_1821_Record_Column_Aliased extends Doctrine_Record { - public function setTableDefinition() { +class Doctrine_Ticket_1821_Record_Column_Aliased extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', 4, array( - 'autoincrement' => true, - 'notnull' => true, - 'primary' => true - )); + 'autoincrement' => true, + 'notnull' => true, + 'primary' => true, + )); $this->hasColumn('user_name as name', 'string', 255, array( - 'notnull' => true, - 'unique' => true - )); + 'notnull' => true, + 'unique' => true, + )); } } -class Doctrine_Ticket_1821_Record extends Doctrine_Record { - public function setTableDefinition() { +class Doctrine_Ticket_1821_Record extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', 4, array( - 'autoincrement' => true, - 'notnull' => true, - 'primary' => true - )); + 'autoincrement' => true, + 'notnull' => true, + 'primary' => true, + )); $this->hasColumn('name', 'string', 255, array( - 'notnull' => true, - 'unique' => true - )); + 'notnull' => true, + 'unique' => true, + )); } } diff --git a/tests/Ticket/1824TestCase.php b/tests/Ticket/1824TestCase.php index 41fd4e0fc..d212b1097 100644 --- a/tests/Ticket/1824TestCase.php +++ b/tests/Ticket/1824TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1824_TestCase + * Doctrine_Ticket_1824_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1824_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1824_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -47,6 +53,11 @@ public function testTest() } } +/** + * @internal + * + * @coversNothing + */ class Ticket_1824_Test extends Doctrine_Record { public function setTableDefinition() @@ -59,4 +70,4 @@ public function setUp() { $this->actAs('I18n', array('fields' => array('test'))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1830TestCase.php b/tests/Ticket/1830TestCase.php index b9eacf83e..07c81d6cc 100644 --- a/tests/Ticket/1830TestCase.php +++ b/tests/Ticket/1830TestCase.php @@ -1,6 +1,10 @@ manager->closeConnection($this->connection); + parent::run($reporter, $filter); + $this->manager->closeConnection($this->connection); } - public function prepareData() + public function prepareData() { } - - public function prepareTables() + + public function prepareTables() { try { $this->conn->exec('DROP TABLE ticket_1830__article_translation'); - } catch(Doctrine_Connection_Exception $e) { + } catch (Doctrine_Connection_Exception $e) { } $this->tables = array('Ticket_1830_Article'); parent::prepareTables(); @@ -53,22 +57,20 @@ public function testDuplicatedParamsInSubQuery() $article->Translation['en']->title = 'Node5'; $article->save($this->connection); - try - { + try { $q = Doctrine_Core::getTable('Ticket_1830_Article') ->createQuery('a') ->select('a.*, t.*') ->leftJoin('a.Translation t') ->addWhere('a.id = ? OR a.id = ?', array(2, 3)) ->orderBy('a.id DESC') - ->limit(1); + ->limit(1) + ; $results = $q->execute(); $this->assertEqual(count($results), 1); $this->assertEqual($results[0]->id, 3); - } - catch (Exception $e) - { - $this->fail($e->getMessage()); + } catch (Exception $e) { + $this->fail($e->getMessage()); } $this->connection->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); @@ -92,4 +94,4 @@ public function setUp() $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'title'))); $this->actAs($i18n0); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1841TestCase.php b/tests/Ticket/1841TestCase.php index 889ef230a..19a733b95 100644 --- a/tests/Ticket/1841TestCase.php +++ b/tests/Ticket/1841TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1841_TestCase + * Doctrine_Ticket_1841_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1841_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1841_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -58,4 +64,4 @@ public function setTableDefinition() $this->hasColumn('username', 'string', 255); $this->hasColumn('password', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1843TestCase.php b/tests/Ticket/1843TestCase.php index 9ecf575ad..9a1e65693 100644 --- a/tests/Ticket/1843TestCase.php +++ b/tests/Ticket/1843TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1843_TestCase + * Doctrine_Ticket_1843_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1843_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1843_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -49,19 +55,19 @@ public function testTest() $user->save(); $check = array( - 'preSave' => 1, - 'preInsert' => 1, - 'postInsert' => 1, - 'postSave' => 1, + 'preSave' => 1, + 'preInsert' => 1, + 'postInsert' => 1, + 'postSave' => 1, ); $this->assertEqual($check, $user->hooks); $user->hooks = array(); $check = array( - 'preSave' => 1, - 'preUpdate' => 1, - 'postUpdate' => 1, - 'postSave' => 1, + 'preSave' => 1, + 'preUpdate' => 1, + 'postUpdate' => 1, + 'postSave' => 1, ); $user->username = 'test'; $user->save(); @@ -83,42 +89,49 @@ public function setTableDefinition() public function preSave($event) { - $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__]:0; + $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__] : 0; $this->hooks[__FUNCTION__] = $num + 1; } + public function postSave($event) { - $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__]:0; + $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__] : 0; $this->hooks[__FUNCTION__] = $num + 1; } + public function preInsert($event) { - $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__]:0; + $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__] : 0; $this->hooks[__FUNCTION__] = $num + 1; } + public function postInsert($event) { - $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__]:0; + $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__] : 0; $this->hooks[__FUNCTION__] = $num + 1; } + public function preUpdate($event) { - $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__]:0; + $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__] : 0; $this->hooks[__FUNCTION__] = $num + 1; } + public function postUpdate($event) { - $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__]:0; + $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__] : 0; $this->hooks[__FUNCTION__] = $num + 1; } + public function preDelete($event) { - $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__]:0; + $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__] : 0; $this->hooks[__FUNCTION__] = $num + 1; } + public function postDelete($event) { - $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__]:0; + $num = isset($this->hooks[__FUNCTION__]) ? $this->hooks[__FUNCTION__] : 0; $this->hooks[__FUNCTION__] = $num + 1; } @@ -126,4 +139,4 @@ public function setUp() { $this->actAs('Timestampable'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1858TestCase.php b/tests/Ticket/1858TestCase.php index 367786131..14b1f1a71 100644 --- a/tests/Ticket/1858TestCase.php +++ b/tests/Ticket/1858TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1858_TestCase + * Doctrine_Ticket_1858_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1858_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1858_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -40,17 +46,18 @@ public function prepareTables() public function testTest() { - $foo_id = 1234; + $foo_id = 1234; $adjustment = -3; $query = Doctrine_Query::create() ->update('T1858_Foo') ->set( - 'quantity','GREATEST(CAST(quantity AS SIGNED) + :adjustment,0)', + 'quantity', 'GREATEST(CAST(quantity AS SIGNED) + :adjustment,0)', array(':adjustment' => $adjustment) ) - ->where('id = :id', array(':id' => $foo_id)); - + ->where('id = :id', array(':id' => $foo_id)) + ; + $this->assertEqual($query->getSqlQuery(), 'UPDATE t1858__foo SET quantity = GREATEST(CAST(quantity AS SIGNED + :adjustment,0)) WHERE (id = :id)'); } } @@ -63,4 +70,4 @@ public function setTableDefinition() { $this->hasColumn('quantity', 'integer'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1860TestCase.php b/tests/Ticket/1860TestCase.php index 4aa16903d..2925055a4 100644 --- a/tests/Ticket/1860TestCase.php +++ b/tests/Ticket/1860TestCase.php @@ -20,24 +20,30 @@ */ /** - * Doctrine_Ticket_1860_TestCase + * Doctrine_Ticket_1860_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1860_TestCase extends Doctrine_UnitTestCase { public function prepareData() { // Create 10 users and mark them as deleted. - for ($i=0; $i<10; $i++) { - $user = new Ticket_1860_User; - $user->username = 'user' . $i; - $user->password = md5('user' . $i); + for ($i = 0; $i < 10; ++$i) { + $user = new Ticket_1860_User(); + $user->username = 'user'.$i; + $user->password = md5('user'.$i); $user->save(); $user->delete(); } @@ -55,13 +61,15 @@ public function testTicket() $query1 = Doctrine_Query::create() ->select('u.*') - ->from('Ticket_1860_User u'); + ->from('Ticket_1860_User u') + ; $this->assertEqual(count($query1->fetchArray()), 0); $query2 = Doctrine_Query::create() ->select('u.*') - ->from('Ticket_1860_User u'); + ->from('Ticket_1860_User u') + ; // Defining initial variables $currentPage = 1; @@ -72,25 +80,25 @@ public function testTicket() $this->assertEqual(count($pager->execute()->toArray()), 0); $this->assertEqual($pager->getQuery()->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t.password AS t__password, t.deleted_at AS t__deleted_at FROM ticket_1860_users t WHERE (t.deleted_at IS NULL) LIMIT 5'); - + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); } } class Ticket_1860_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('ticket_1860_users'); + public function setTableDefinition() + { + $this->setTableName('ticket_1860_users'); - $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'unsigned' => '1', 'primary' => true, 'autoincrement' => true, 'length' => '4')); - $this->hasColumn('username', 'string', 45, array('type' => 'string', 'notnull' => true, 'unique' => true, 'length' => '45')); - $this->hasColumn('password', 'string', 45, array('type' => 'string', 'notnull' => true, 'length' => '45')); - } + $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'unsigned' => '1', 'primary' => true, 'autoincrement' => true, 'length' => '4')); + $this->hasColumn('username', 'string', 45, array('type' => 'string', 'notnull' => true, 'unique' => true, 'length' => '45')); + $this->hasColumn('password', 'string', 45, array('type' => 'string', 'notnull' => true, 'length' => '45')); + } - public function setUp() - { - $softdelete0 = new Doctrine_Template_SoftDelete(); - $this->actAs($softdelete0); - } + public function setUp() + { + $softdelete0 = new Doctrine_Template_SoftDelete(); + $this->actAs($softdelete0); + } } diff --git a/tests/Ticket/1865TestCase.php b/tests/Ticket/1865TestCase.php index 1a7d4a427..e86a190f7 100644 --- a/tests/Ticket/1865TestCase.php +++ b/tests/Ticket/1865TestCase.php @@ -20,23 +20,29 @@ */ /** - * Doctrine_Ticket_1865_TestCase + * Doctrine_Ticket_1865_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1865_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1865_TestCase extends Doctrine_UnitTestCase { - - public function prepareData() + public function prepareData() { } - public function prepareTables() + + public function prepareTables() { $this->tables[] = 'Ticket_1865_User'; $this->tables[] = 'Ticket_1865_Profile'; @@ -51,11 +57,11 @@ public function testSaveWithRelated() $user->password = '!'; $user->Profile; $user->save(); - + $this->assertNotEqual($user->Profile->id, null); // Ticket_1865_Profile is saved $user->delete(); } - + public function testSaveWithRelatedWithPreInsert() { $user = new Ticket_1865_User(); @@ -63,42 +69,45 @@ public function testSaveWithRelatedWithPreInsert() $user->loginname = 'world'; $user->password = '!'; $user->save(); // $user->Ticket_1865_Profile must be called in Ticket_1865_User::preInsert - + $this->assertNotEqual($user->Profile->id, null); // Ticket_1865_Profile is NOT saved - test failure $user->delete(); } } -class Ticket_1865_Profile extends Doctrine_Record +class Ticket_1865_Profile extends Doctrine_Record { - public function setUp() + public function setUp() { $this->hasOne('Ticket_1865_User as User', array('local' => 'id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); } - public function setTableDefinition() + + public function setTableDefinition() { - $this->hasColumn('id', 'integer',20, array('autoincrement', 'primary')); + $this->hasColumn('id', 'integer', 20, array('autoincrement', 'primary')); $this->hasColumn('user_id', 'integer', 20, array('notnull', 'unique')); - $this->hasColumn('icq', 'string', 9, array('notnull')); + $this->hasColumn('icq', 'string', 9, array('notnull')); } } -class Ticket_1865_User extends Doctrine_Record +class Ticket_1865_User extends Doctrine_Record { - public function setUp() + public function setUp() { $this->hasOne('Ticket_1865_Profile as Profile', array('local' => 'id', 'foreign' => 'user_id')); } - public function setTableDefinition() + + public function setTableDefinition() { - $this->hasColumn('id', 'integer',20, array('autoincrement', 'primary')); - $this->hasColumn('name', 'string',50); - $this->hasColumn('loginname', 'string',20, array('unique')); - $this->hasColumn('password', 'string',16); + $this->hasColumn('id', 'integer', 20, array('autoincrement', 'primary')); + $this->hasColumn('name', 'string', 50); + $this->hasColumn('loginname', 'string', 20, array('unique')); + $this->hasColumn('password', 'string', 16); } + public function preInsert($event) { $this->Profile; $this->Profile->icq = ''; } -} \ No newline at end of file +} diff --git a/tests/Ticket/1875TestCase.php b/tests/Ticket/1875TestCase.php index bb76ac8ed..5a1f73f04 100644 --- a/tests/Ticket/1875TestCase.php +++ b/tests/Ticket/1875TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1875_TestCase + * Doctrine_Ticket_1875_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1875_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1875_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -58,4 +64,4 @@ public function setTableDefinition() $this->hasColumn('name', 'string', 255); $this->hasColumn('amount', 'decimal', 4, array('scale' => 2)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1876TestCase.php b/tests/Ticket/1876TestCase.php index b4d76b04c..dcd1ff27a 100644 --- a/tests/Ticket/1876TestCase.php +++ b/tests/Ticket/1876TestCase.php @@ -20,15 +20,22 @@ */ /** - * Doctrine_Ticket_1821_TestCase + * Doctrine_Ticket_1821_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Andrea Baron + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_1876_TestCase extends Doctrine_UnitTestCase { @@ -36,102 +43,112 @@ public function prepareTables() { $this->tables = array( 'T1876_Recipe', - 'T1876_Company', - 'T1876_RecipeIngredient', + 'T1876_Company', + 'T1876_RecipeIngredient', ); parent::prepareTables(); } - + public function prepareData() { - for ($i = 0; $i < 2; $i++) { + for ($i = 0; $i < 2; ++$i) { $company = new T1876_Company(); - $company->name = 'Test Company ' . ($i + 1); + $company->name = 'Test Company '.($i + 1); $company->save(); } - - for ($i = 0; $i < 10; $i++) { + + for ($i = 0; $i < 10; ++$i) { $recipe = new T1876_Recipe(); - - $recipe->name = 'test ' . $i; - $recipe->company_id = ($i % 3 == 0) ? 1 : 2; + + $recipe->name = 'test '.$i; + $recipe->company_id = (0 == $i % 3) ? 1 : 2; $recipe->RecipeIngredients[]->name = 'test'; - + $recipe->save(); - - if ($i % 2 == 0) { - $recipe->delete(); + + if (0 == $i % 2) { + $recipe->delete(); } } } - + public function testTicket() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); - + try { $q = Doctrine_Query::create() ->from('T1876_Recipe r') ->leftJoin('r.Company c') ->leftJoin('r.RecipeIngredients') - ->addWhere('c.id = ?', 2); - + ->addWhere('c.id = ?', 2) + ; + $this->assertEqual( - $q->getCountSqlQuery(), - 'SELECT COUNT(*) AS num_results ' . - 'FROM (SELECT t.id FROM t1876__recipe t ' . - 'LEFT JOIN t1876__company t2 ON t.company_id = t2.id AND (t2.deleted_at IS NULL) ' . - 'LEFT JOIN t1876__recipe_ingredient t3 ON t.id = t3.recipe_id AND (t3.deleted_at IS NULL) ' . - 'WHERE t2.id = ? AND (t.deleted_at IS NULL) ' . + $q->getCountSqlQuery(), + 'SELECT COUNT(*) AS num_results '. + 'FROM (SELECT t.id FROM t1876__recipe t '. + 'LEFT JOIN t1876__company t2 ON t.company_id = t2.id AND (t2.deleted_at IS NULL) '. + 'LEFT JOIN t1876__recipe_ingredient t3 ON t.id = t3.recipe_id AND (t3.deleted_at IS NULL) '. + 'WHERE t2.id = ? AND (t.deleted_at IS NULL) '. 'GROUP BY t.id) dctrn_count_query' ); $this->assertEqual($q->count(), 3); } catch (Exception $e) { $this->fail($e->getMessage()); } - + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); } } - -class T1876_Recipe extends Doctrine_Record { - public function setTableDefinition() { + +class T1876_Recipe extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('autoincrement' => true, 'primary' => true)); $this->hasColumn('company_id', 'integer', null); $this->hasColumn('name', 'string', 255); } - - public function setUp() { + + public function setUp() + { $this->hasOne('T1876_Company as Company', array('local' => 'company_id', 'foreign' => 'id')); $this->hasMany('T1876_RecipeIngredient as RecipeIngredients', array('local' => 'id', 'foreign' => 'recipe_id')); - + $this->actAs('SoftDelete'); } } -class T1876_Company extends Doctrine_Record { - public function setTableDefinition() { +class T1876_Company extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('autoincrement' => true, 'primary' => true)); $this->hasColumn('name', 'string', 255); } - - public function setUp() { + + public function setUp() + { $this->hasMany('T1876_Recipe as Recipes', array('local' => 'id', 'foreign' => 'company_id')); - + $this->actAs('SoftDelete'); } } -class T1876_RecipeIngredient extends Doctrine_Record { - public function setTableDefinition() { +class T1876_RecipeIngredient extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('autoincrement' => true, 'primary' => true)); $this->hasColumn('recipe_id', 'integer', null); $this->hasColumn('name', 'string', 255); } - - public function setUp() { + + public function setUp() + { $this->hasOne('T1876_Recipe as Recipe', array('local' => 'recipe_id', 'foreign' => 'id')); - + $this->actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1876bTestCase.php b/tests/Ticket/1876bTestCase.php index ed16a1a74..df350be73 100644 --- a/tests/Ticket/1876bTestCase.php +++ b/tests/Ticket/1876bTestCase.php @@ -1,5 +1,10 @@ manager->closeConnection($this->connection); + parent::run($reporter, $filter); + $this->manager->closeConnection($this->connection); } - public function prepareData() + public function prepareData() { } - - public function prepareTables() + + public function prepareTables() { try { $this->conn->exec('DROP TABLE t1876b_recipe_ingredient'); $this->conn->exec('DROP TABLE t1876b_recipe'); $this->conn->exec('DROP TABLE t1876b_company'); - } catch(Doctrine_Connection_Exception $e) { + } catch (Doctrine_Connection_Exception $e) { } - + $this->tables = array( - 'T1876b_Recipe', 'T1876b_Company', 'T1876b_RecipeIngredient' + 'T1876b_Recipe', 'T1876b_Company', 'T1876b_RecipeIngredient', ); - + parent::prepareTables(); } @@ -42,22 +47,22 @@ public function testDuplicatedParamsInSubQuery() { $this->connection->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true); - for ($i = 0; $i < 2; $i++) { + for ($i = 0; $i < 2; ++$i) { $company = new T1876b_Company(); - $company->name = 'Test Company ' . ($i + 1); + $company->name = 'Test Company '.($i + 1); $company->save($this->connection); } - - for ($i = 0; $i < 10; $i++) { + + for ($i = 0; $i < 10; ++$i) { $recipe = new T1876b_Recipe(); - - $recipe->name = 'test ' . $i; - $recipe->company_id = ($i % 3 == 0) ? 1 : 2; + + $recipe->name = 'test '.$i; + $recipe->company_id = (0 == $i % 3) ? 1 : 2; $recipe->RecipeIngredients[]->name = 'test'; - + $recipe->save($this->connection); - - if ($i % 2 == 0) { + + if (0 == $i % 2) { $recipe->delete($this->connection); } } @@ -67,16 +72,17 @@ public function testDuplicatedParamsInSubQuery() ->from('T1876b_Recipe r') ->leftJoin('r.Company c') ->leftJoin('r.RecipeIngredients') - ->addWhere('c.id = ?', 2); - + ->addWhere('c.id = ?', 2) + ; + $this->assertEqual( - $q->getCountSqlQuery(), + $q->getCountSqlQuery(), 'SELECT COUNT(*) AS num_results FROM (' - . 'SELECT t.id FROM t1876b__recipe t ' - . 'LEFT JOIN t1876b__company t2 ON t.company_id = t2.id AND t2.deleted_at IS NULL ' - . 'LEFT JOIN t1876b__recipe_ingredient t3 ON t.id = t3.recipe_id AND t3.deleted_at IS NULL ' - . 'WHERE t2.id = ? AND (t.deleted_at IS NULL) GROUP BY t.id' - . ') dctrn_count_query' + .'SELECT t.id FROM t1876b__recipe t ' + .'LEFT JOIN t1876b__company t2 ON t.company_id = t2.id AND t2.deleted_at IS NULL ' + .'LEFT JOIN t1876b__recipe_ingredient t3 ON t.id = t3.recipe_id AND t3.deleted_at IS NULL ' + .'WHERE t2.id = ? AND (t.deleted_at IS NULL) GROUP BY t.id' + .') dctrn_count_query' ); $this->assertEqual($q->count(), 3); } catch (Exception $e) { @@ -87,45 +93,53 @@ public function testDuplicatedParamsInSubQuery() } } - -class T1876b_Recipe extends Doctrine_Record { - public function setTableDefinition() { +class T1876b_Recipe extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('autoincrement' => true, 'primary' => true)); $this->hasColumn('company_id', 'integer', null); $this->hasColumn('name', 'string', 255); } - - public function setUp() { + + public function setUp() + { $this->hasOne('T1876b_Company as Company', array('local' => 'company_id', 'foreign' => 'id')); $this->hasMany('T1876b_RecipeIngredient as RecipeIngredients', array('local' => 'id', 'foreign' => 'recipe_id')); - + $this->actAs('SoftDelete'); } } -class T1876b_Company extends Doctrine_Record { - public function setTableDefinition() { +class T1876b_Company extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('autoincrement' => true, 'primary' => true)); $this->hasColumn('name', 'string', 255); } - - public function setUp() { + + public function setUp() + { $this->hasMany('T1876b_Recipe as Recipes', array('local' => 'id', 'foreign' => 'company_id')); - + $this->actAs('SoftDelete'); } } -class T1876b_RecipeIngredient extends Doctrine_Record { - public function setTableDefinition() { +class T1876b_RecipeIngredient extends Doctrine_Record +{ + public function setTableDefinition() + { $this->hasColumn('id', 'integer', null, array('autoincrement' => true, 'primary' => true)); $this->hasColumn('recipe_id', 'integer', null); $this->hasColumn('name', 'string', 255); } - - public function setUp() { + + public function setUp() + { $this->hasOne('T1876b_Recipe as Recipe', array('local' => 'recipe_id', 'foreign' => 'id')); - + $this->actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1923TestCase.php b/tests/Ticket/1923TestCase.php index fbec054fd..32bfa2ffd 100644 --- a/tests/Ticket/1923TestCase.php +++ b/tests/Ticket/1923TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1923_TestCase + * Doctrine_Ticket_1923_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1923_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1923_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -70,4 +76,4 @@ public function setTableDefinition() $this->index('username2', array('fields' => array('username' => array('sorting' => 'DESC')))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1935TestCase.php b/tests/Ticket/1935TestCase.php index cc8d9470e..1e3d5877a 100644 --- a/tests/Ticket/1935TestCase.php +++ b/tests/Ticket/1935TestCase.php @@ -1,5 +1,10 @@ connection->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true); - try - { + try { $q = Doctrine_Query::create()->select('COUNT(a.id) as num_records') ->from('Ticket_1935_Article a') ->having('num_records > 1') - ; - //$results = $q->execute(); + ; + // $results = $q->execute(); $this->assertEqual($q->getSqlQuery(), 'SELECT COUNT(`t`.`id`) AS `t__0` FROM `ticket_1935_article` `t` HAVING `t__0` > 1'); - } - catch(Exception $e) - { + } catch (Exception $e) { $this->fail($e->getMessage()); } diff --git a/tests/Ticket/1940TestCase.php b/tests/Ticket/1940TestCase.php index c5a9f1cba..1f77fc930 100644 --- a/tests/Ticket/1940TestCase.php +++ b/tests/Ticket/1940TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1940_TestCase + * Doctrine_Ticket_1940_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1940_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1940_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -56,33 +62,33 @@ public function testTest() class Ticket_1940_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('username', 'string', 255); - $this->hasColumn('password', 'string', 255); - $this->hasColumn('email_address', 'string', 255); + public function setTableDefinition() + { + $this->hasColumn('username', 'string', 255); + $this->hasColumn('password', 'string', 255); + $this->hasColumn('email_address', 'string', 255); - $this->hasMutator('password', 'customSetPassword'); - $this->hasAccessor('username', 'customGetUsername'); - } + $this->hasMutator('password', 'customSetPassword'); + $this->hasAccessor('username', 'customGetUsername'); + } public function getEmailAddress() { - return $this->_get('email_address') . '-modified'; + return $this->_get('email_address').'-modified'; } public function setEmailAddress($emailAddress) { - $this->_set('email_address', $emailAddress . '-modified'); + $this->_set('email_address', $emailAddress.'-modified'); } - public function customGetUsername() - { - return $this->_get('username').'-modified'; - } + public function customGetUsername() + { + return $this->_get('username').'-modified'; + } - public function customSetPassword($value) - { - return $this->_set('password', md5($value)); - } -} \ No newline at end of file + public function customSetPassword($value) + { + return $this->_set('password', md5($value)); + } +} diff --git a/tests/Ticket/1958TestCase.php b/tests/Ticket/1958TestCase.php index 45a4d57ae..7cbebff05 100644 --- a/tests/Ticket/1958TestCase.php +++ b/tests/Ticket/1958TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1958_TestCase + * Doctrine_Ticket_1958_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1958_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1958_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -59,4 +65,4 @@ public function setTableDefinition() $this->hasColumn('password', 'string', 255); $this->hasColumn('foo', 'integer', 4, array('notnull' => true, 'default' => '0', 'unsigned' => 1)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/1986TestCase.php b/tests/Ticket/1986TestCase.php index e92e3cf87..3c56d7c22 100644 --- a/tests/Ticket/1986TestCase.php +++ b/tests/Ticket/1986TestCase.php @@ -20,92 +20,97 @@ */ /** - * Doctrine_Ticket_1986_TestCase + * Doctrine_Ticket_1986_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1986_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1986_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { - } + public function prepareData() + { + } - public function prepareTables() - { - $this->tables = array('Testing_Ticket_1986_1','Testing_Ticket_1986_2','Testing_Ticket_1986Link'); - parent::prepareTables(); - } + public function prepareTables() + { + $this->tables = array('Testing_Ticket_1986_1', 'Testing_Ticket_1986_2', 'Testing_Ticket_1986Link'); + parent::prepareTables(); + } - public function testTicket() - { - // this works - $t1 = new Testing_Ticket_1986_1(); - $t1->get('others'); - $t1->save(); - try { - $t1->get('others'); - } catch(Doctrine_Exception $e) { - $this->fail("after save".$e->getMessage()); - } - // this not: relation is not accessed before save and is gone afterwards - $t2 = new Testing_Ticket_1986_1(); - $t2->save(); - try { - $t2->get('others'); - } catch(Doctrine_Exception $e) { - $this->fail($e->getMessage()); - } - } - + public function testTicket() + { + // this works + $t1 = new Testing_Ticket_1986_1(); + $t1->get('others'); + $t1->save(); + try { + $t1->get('others'); + } catch (Doctrine_Exception $e) { + $this->fail('after save'.$e->getMessage()); + } + // this not: relation is not accessed before save and is gone afterwards + $t2 = new Testing_Ticket_1986_1(); + $t2->save(); + try { + $t2->get('others'); + } catch (Doctrine_Exception $e) { + $this->fail($e->getMessage()); + } + } } class Testing_Ticket_1986_1 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('testing_ticket_1986_1'); - $this->hasColumn('name', 'string', 64, array()); - } - public function setUp() - { - $this->hasMany('Testing_Ticket_1986_2 as others', array('refClass' => 'Testing_Ticket_1986Link', 'local' => 'id_1', 'foreign' => 'id_2')); - } + public function setTableDefinition() + { + $this->setTableName('testing_ticket_1986_1'); + $this->hasColumn('name', 'string', 64, array()); + } + + public function setUp() + { + $this->hasMany('Testing_Ticket_1986_2 as others', array('refClass' => 'Testing_Ticket_1986Link', 'local' => 'id_1', 'foreign' => 'id_2')); + } } class Testing_Ticket_1986_2 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('testing_ticket_1986_2'); - $this->hasColumn('value', 'string', 64, array()); - } + public function setTableDefinition() + { + $this->setTableName('testing_ticket_1986_2'); + $this->hasColumn('value', 'string', 64, array()); + } - public function setUp() - { - $this->hasMany('Testing_Ticket_1986_1', array('refClass' => 'Testing_Ticket_1986Link', 'local' => 'id_2', 'foreign' => 'id_1')); - } + public function setUp() + { + $this->hasMany('Testing_Ticket_1986_1', array('refClass' => 'Testing_Ticket_1986Link', 'local' => 'id_2', 'foreign' => 'id_1')); + } } class Testing_Ticket_1986Link extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('testing_ticket_1986_link'); - $this->hasColumn('id_1', 'integer', null, array()); - $this->hasColumn('id_2', 'integer', null, array()); - } - - public function setUp() { - // setup relations - $this->hasOne('Testing_Ticket_1986_1 as rel1', array('local' => 'id_1', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - $this->hasOne('Testing_Ticket_1986_2 as rel2', array('local' => 'id_2', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - } - + public function setTableDefinition() + { + $this->setTableName('testing_ticket_1986_link'); + $this->hasColumn('id_1', 'integer', null, array()); + $this->hasColumn('id_2', 'integer', null, array()); + } + + public function setUp() + { + // setup relations + $this->hasOne('Testing_Ticket_1986_1 as rel1', array('local' => 'id_1', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + $this->hasOne('Testing_Ticket_1986_2 as rel2', array('local' => 'id_2', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } } - \ No newline at end of file diff --git a/tests/Ticket/1991TestCase.php b/tests/Ticket/1991TestCase.php index 717a516db..886a13943 100644 --- a/tests/Ticket/1991TestCase.php +++ b/tests/Ticket/1991TestCase.php @@ -20,18 +20,25 @@ */ /** - * Doctrine_Ticket_1015_TestCase + * Doctrine_Ticket_1015_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1991_TestCase extends Doctrine_UnitTestCase { - - public function prepareTables() { +class Doctrine_Ticket_1991_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { $this->tables = array(); $this->tables[] = 'NewTag'; @@ -43,24 +50,22 @@ public function prepareData() $tag = new NewTag(); $tag->name = 'name'; $tag->save(); - + $tag = new NewTag(); $tag->name = 'foobar'; - $tag->save(); + $tag->save(); } - public function testHydratation() { $q = new Doctrine_Query(); - $q->select('t.name')->from('NewTag t INDEXBY t.name'); + $q->select('t.name')->from('NewTag t INDEXBY t.name'); try { $results = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); } catch (Exception $e) { $this->fail($e->getMessage()); } } - } class NewTag extends Doctrine_Record diff --git a/tests/Ticket/1992TestCase.php b/tests/Ticket/1992TestCase.php index c7691df8f..2a9eb8e68 100644 --- a/tests/Ticket/1992TestCase.php +++ b/tests/Ticket/1992TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_1992_TestCase + * Doctrine_Ticket_1992_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_1992_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_1992_TestCase extends Doctrine_UnitTestCase { protected $person; protected $profile1; @@ -46,15 +52,15 @@ public function prepareTables() public function prepareData() { - $this->person = new Ticket_1992_Person(); - $this->person->nummer = '1'; - $this->profile1 = new Ticket_1992_Profile(); - $this->profile1->name = 'test 2'; - $this->person->Profile[] = $this->profile1; - $this->profile2 = new Ticket_1992_Profile(); - $this->profile2->name = 'test 2'; - $this->person->Profile[] = $this->profile2; - $this->person->save(); + $this->person = new Ticket_1992_Person(); + $this->person->nummer = '1'; + $this->profile1 = new Ticket_1992_Profile(); + $this->profile1->name = 'test 2'; + $this->person->Profile[] = $this->profile1; + $this->profile2 = new Ticket_1992_Profile(); + $this->profile2->name = 'test 2'; + $this->person->Profile[] = $this->profile2; + $this->person->save(); } public function testTest() @@ -64,7 +70,8 @@ public function testTest() $person = Doctrine_Query::create() ->from('Ticket_1992_Person p') ->innerJoin('p.Profile pr') - ->fetchOne(); + ->fetchOne() + ; $this->assertEqual($person['nummer'], 1); $this->assertEqual(count($person['Profile']), 2); @@ -73,7 +80,8 @@ public function testTest() $person = Doctrine_Query::create() ->from('Ticket_1992_Person p') ->innerJoin('p.Profile pr') - ->fetchOne(); + ->fetchOne() + ; $this->assertEqual($person['nummer'], 1); $this->assertEqual(count($person['Profile']), 1); @@ -82,13 +90,15 @@ public function testTest() $person = Doctrine_Query::create() ->from('Ticket_1992_Person p') ->innerJoin('p.Profile pr') - ->fetchOne(); + ->fetchOne() + ; $this->assertEqual($person, false); $person = Doctrine_Query::create() ->from('Ticket_1992_Person p') ->leftJoin('p.Profile pr') - ->fetchOne(); + ->fetchOne() + ; $this->assertEqual($person['nummer'], 1); $this->assertEqual(count($person['Profile']), 0); @@ -96,7 +106,8 @@ public function testTest() $person = Doctrine_Query::create() ->from('Ticket_1992_Person p') - ->fetchOne(); + ->fetchOne() + ; $this->assertEqual($person, false); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); @@ -107,7 +118,7 @@ class Ticket_1992_Person extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('nummer', 'string', 16, array('type' => 'string', 'length' => 16, 'primary' => true)); + $this->hasColumn('nummer', 'string', 16, array('type' => 'string', 'length' => 16, 'primary' => true)); } public function setUp() @@ -121,7 +132,7 @@ class Ticket_1992_Profile extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'unsigned' => 1, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'unsigned' => 1, 'primary' => true, 'autoincrement' => true)); $this->hasColumn('name', 'string'); } @@ -137,11 +148,11 @@ class Ticket_1992_PersonProfile extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('person_nummer', 'string', 16, array('type' => 'string', 'length' => 16, 'notnull' => true)); - $this->hasColumn('profile_id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'unsigned' => 1, 'notnull' => true)); + $this->hasColumn('profile_id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'unsigned' => 1, 'notnull' => true)); } public function setUp() { $this->actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2007TestCase.php b/tests/Ticket/2007TestCase.php index 27a458dff..3dae905de 100644 --- a/tests/Ticket/2007TestCase.php +++ b/tests/Ticket/2007TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_2007_TestCase + * Doctrine_Ticket_2007_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2007_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2007_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -51,36 +57,35 @@ public function setTableDefinition() { $this->setTableName('faq'); $this->hasColumn('id_faq', 'integer', 4, array( - 'primary' => true, - 'type' => 'integer', - 'length' => '4', - )); + 'primary' => true, + 'type' => 'integer', + 'length' => '4', + )); $this->hasColumn('n_clicks', 'integer', 4, array( - 'unsigned' => '1', - 'notnull' => true, - 'default' => 0, - 'type' => 'integer', - 'length' => '4', - )); + 'unsigned' => '1', + 'notnull' => true, + 'default' => 0, + 'type' => 'integer', + 'length' => '4', + )); $this->hasColumn('title', 'string', 255, array( - 'type' => 'string', - 'length' => '255', - )); + 'type' => 'string', + 'length' => '255', + )); $this->hasColumn('description', 'string', null, array( - 'type' => 'string', - )); + 'type' => 'string', + )); } public function setUp() { $searchable0 = new Doctrine_Template_Searchable(array( - 'fields' => - array( - 0 => 'title', - 1 => 'description', - ), - 'batchUpdates' => true, - )); + 'fields' => array( + 0 => 'title', + 1 => 'description', + ), + 'batchUpdates' => true, + )); $this->actAs($searchable0); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2015TestCase.php b/tests/Ticket/2015TestCase.php index 0597827e0..28c63d1f5 100644 --- a/tests/Ticket/2015TestCase.php +++ b/tests/Ticket/2015TestCase.php @@ -20,46 +20,52 @@ */ /** - * Doctrine_Ticket_2015_TestCase + * Doctrine_Ticket_2015_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2015_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2015_TestCase extends Doctrine_UnitTestCase { public function prepareData() { $deer = new mkAnimal(); $deer->title = 'Cervus Elaphus'; $deer->save(); - + $beech = new mkPlant(); $beech->title = 'Fagus sylvatica'; $beech->save(); } - + public function testColumnAggregation() { $animal = Doctrine_Core::getTable('mkNode')->findOneById(1); $this->assertTrue($animal instanceof mkAnimal); - + $plant = Doctrine_Core::getTable('mkOrganism')->findOneById(2); $this->assertTrue($plant instanceof mkPlant); } - + public function prepareTables() { $this->tables = array( 'mkNode', 'mkOrganism', - 'mkAnimal' + 'mkAnimal', ); - + parent::prepareTables(); } } @@ -73,19 +79,19 @@ public function setTableDefinition() $this->hasColumn('title', 'string', 255); $this->hasColumn('type', 'string', 50); $this->hasColumn('sub_type', 'string', 50); - + $this->setSubclasses(array( 'mkOrganism' => array( - 'type' => 'organism' + 'type' => 'organism', ), 'mkAnimal' => array( - 'type' => 'organism', - 'sub_type' => 'animal' + 'type' => 'organism', + 'sub_type' => 'animal', ), 'mkPlant' => array( - 'type' => 'organism', - 'sub_type' => 'plant' - ) + 'type' => 'organism', + 'sub_type' => 'plant', + ), )); } } @@ -100,4 +106,4 @@ class mkAnimal extends mkOrganism class mkPlant extends mkOrganism { -} \ No newline at end of file +} diff --git a/tests/Ticket/2032TestCase.php b/tests/Ticket/2032TestCase.php index 8d482a58c..72fc920f4 100644 --- a/tests/Ticket/2032TestCase.php +++ b/tests/Ticket/2032TestCase.php @@ -1,51 +1,59 @@ -. - */ - -/** - * Doctrine_Ticket_2032_TestCase - * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.doctrine-project.org - * @since 1.1 - * @version $Revision$ - */ -class Doctrine_Ticket_2032_TestCase extends Doctrine_UnitTestCase -{ - /** - * Tests non-spaced orderby parameters - */ - public function testNonSpacedOrderByIsParsedCorrectly() - { - $q = Doctrine_Query::create() - ->select('u.*') - ->from('User u') - ->orderby('u.name,u.id,u.password'); - - try { - $u = $q->execute(); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->getMessage()); - } - } -} \ No newline at end of file +. + */ + +/** + * Doctrine_Ticket_2032_TestCase. + * + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * + * @category Object Relational Mapping + * + * @see www.doctrine-project.org + * @since 1.1 + * + * @version $Revision$ + * + * @internal + * + * @coversNothing + */ +class Doctrine_Ticket_2032_TestCase extends Doctrine_UnitTestCase +{ + /** + * Tests non-spaced orderby parameters. + */ + public function testNonSpacedOrderByIsParsedCorrectly() + { + $q = Doctrine_Query::create() + ->select('u.*') + ->from('User u') + ->orderby('u.name,u.id,u.password') + ; + + try { + $u = $q->execute(); + $this->pass(); + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + } +} diff --git a/tests/Ticket/2105TestCase.php b/tests/Ticket/2105TestCase.php index 54ed879f6..18297d9be 100644 --- a/tests/Ticket/2105TestCase.php +++ b/tests/Ticket/2105TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_2105_TestCase + * Doctrine_Ticket_2105_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2105_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2105_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -45,32 +51,32 @@ public function testQuery() ->select('a.id, t.lang') ->from('Ticket_2105_Article a') ->innerJoin('a.Translation t WITH t.name != ?', 'test') - ; + ; $q->execute(); - //echo $q->getSqlQuery().PHP_EOL; - + // echo $q->getSqlQuery().PHP_EOL; + $this->assertEqual( - $q->getSqlQuery(), + $q->getSqlQuery(), 'SELECT t.id AS t__id, t2.id AS t2__id, t2.lang AS t2__lang '. 'FROM ticket_2105__article t '. 'INNER JOIN ticket_2105__article_translation t2 '. 'ON t.id = t2.id AND (t2.name != ?)' ); - + // we need to modify the query here - it can be anything, I've chosen addSelect $q->addSelect('t.name'); $q->execute(); - //echo $q->getSqlQuery().PHP_EOL; - + // echo $q->getSqlQuery().PHP_EOL; + $this->assertEqual( - $q->getSqlQuery(), + $q->getSqlQuery(), 'SELECT t.id AS t__id, t2.id AS t2__id, t2.lang AS t2__lang, t2.name AS t2__name '. 'FROM ticket_2105__article t '. 'INNER JOIN ticket_2105__article_translation t2 '. 'ON t.id = t2.id AND (t2.name != ?)' ); - - //$this->pass(); + + // $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -89,4 +95,4 @@ public function setUp() $i18n = new Doctrine_Template_I18n(array('fields' => array(0 => 'name'))); $this->actAs($i18n); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2123TestCase.php b/tests/Ticket/2123TestCase.php index 32f22aeeb..ee7c4dacd 100644 --- a/tests/Ticket/2123TestCase.php +++ b/tests/Ticket/2123TestCase.php @@ -20,24 +20,31 @@ */ /** - * Doctrine_Ticket_2123_TestCase + * Doctrine_Ticket_2123_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2123_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2123_TestCase extends Doctrine_UnitTestCase { public function testCheckingRelatedExistsOnCollectionThrowsException() { try { $user = Doctrine_Core::getTable('User') ->createQuery('u') - ->fetchOne(); + ->fetchOne() + ; $user->relatedExists('Phonenumber'); } catch (Exception $e) { $this->pass(); @@ -58,4 +65,4 @@ public function testClearRelatedReference() $user->clearRelated('Email'); $this->assertEqual($user->hasReference('Email'), false); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2158TestCase.php b/tests/Ticket/2158TestCase.php index 02d40cdd0..172b77d79 100644 --- a/tests/Ticket/2158TestCase.php +++ b/tests/Ticket/2158TestCase.php @@ -1,33 +1,37 @@ tables[] = "T2158_Model1"; - $this->tables[] = "T2158_Model2"; + $this->tables[] = 'T2158_Model1'; + $this->tables[] = 'T2158_Model2'; parent::prepareTables(); } public function prepareData() { - $this->myModel = new T2158_Model1(); - $this->myModel->save(); + $this->myModel = new T2158_Model1(); + $this->myModel->save(); } public function testInit() { - } // This produces a failing test public function testTest() { - $q = Doctrine_Core::getTable('T2158_Model2')->createQuery('m2')->leftJoin('m2.Relation m1 ON m2.id = m1.m2_id'); - $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t2.id AS t2__id, t2.title AS t2__title, t2.m2_id AS t2__m2_id FROM t2158__model2 t LEFT JOIN t2158__model1 t2 ON (t.id = t2.m2_id)'); - //$rs = $q->execute(); + $q = Doctrine_Core::getTable('T2158_Model2')->createQuery('m2')->leftJoin('m2.Relation m1 ON m2.id = m1.m2_id'); + $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t2.id AS t2__id, t2.title AS t2__title, t2.m2_id AS t2__m2_id FROM t2158__model2 t LEFT JOIN t2158__model1 t2 ON (t.id = t2.m2_id)'); + // $rs = $q->execute(); } } @@ -45,14 +49,13 @@ class T2158_Model2 extends Doctrine_Record public function setTableDefinition() { } - public function setUp() { $this->hasMany('T2158_Model1 as Relation', array( - 'local' => 'id', - 'foreign' => 'm2_id' - ) + 'local' => 'id', + 'foreign' => 'm2_id', + ) ); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2159TestCase.php b/tests/Ticket/2159TestCase.php index 0f417068a..ef03d580f 100644 --- a/tests/Ticket/2159TestCase.php +++ b/tests/Ticket/2159TestCase.php @@ -20,22 +20,29 @@ */ /** - * Doctrine_Ticket_2159_TestCase + * Doctrine_Ticket_2159_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2159_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2159_TestCase extends Doctrine_UnitTestCase { public function testTest() { $q = Doctrine_Core::getTable('User') - ->createQuery('u'); + ->createQuery('u') + ; $sql = 'SELECT COUNT(*) AS num_results FROM entity e WHERE (e.type = 0)'; $this->assertEqual($q->getCountSqlQuery(), $sql); @@ -55,4 +62,4 @@ public function testTest() $count3 = $q->count(); $this->assertEqual($count2, $count3); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2160TestCase.php b/tests/Ticket/2160TestCase.php index 22d71f3d5..5a1da5250 100644 --- a/tests/Ticket/2160TestCase.php +++ b/tests/Ticket/2160TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_2160_TestCase + * Doctrine_Ticket_2160_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_2160_TestCase extends Doctrine_UnitTestCase { @@ -42,4 +48,4 @@ public function testGermanCharactersAreConvertedCorrectly() $this->assertEqual(Doctrine_Inflector::urlize('ölig'), 'oelig'); $this->assertEqual(Doctrine_Inflector::urlize('Fuß'), 'fuss'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2184TestCase.php b/tests/Ticket/2184TestCase.php index 41cc4ed7d..21327fec4 100644 --- a/tests/Ticket/2184TestCase.php +++ b/tests/Ticket/2184TestCase.php @@ -20,20 +20,26 @@ */ /** - * Doctrine_Ticket_2184_TestCase + * Doctrine_Ticket_2184_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2184_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2184_TestCase extends Doctrine_UnitTestCase { public function testTest() { $this->assertEqual(Doctrine_Inflector::classify('test_do$llar_sign'), 'TestDollarSign'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2190TestCase.php b/tests/Ticket/2190TestCase.php index e5a119493..7d98a3cb1 100644 --- a/tests/Ticket/2190TestCase.php +++ b/tests/Ticket/2190TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_2190_TestCase + * Doctrine_Ticket_2190_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2190_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2190_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -57,7 +63,7 @@ public function testTest() $article->body = str_repeat('a', 257); $article->save(); - for ($i = 1; $i <= 5; $i++) { + for ($i = 1; $i <= 5; ++$i) { $article = new Ticket_2190_Article(); $article->name = 'test'; $article->body = str_repeat('a', 300); @@ -81,4 +87,4 @@ public function setUp() { $this->actAs('Sluggable', array('indexName' => 'ticket_2190_slug_idx', 'fields' => array('body'))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2204TestCase.php b/tests/Ticket/2204TestCase.php index 35f78420c..a61815adc 100644 --- a/tests/Ticket/2204TestCase.php +++ b/tests/Ticket/2204TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_2204_TestCase + * Doctrine_Ticket_2204_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2204_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2204_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -59,4 +65,4 @@ public function setTableDefinition() { $this->hasColumn('test_decimal', 'decimal', 9, array('scale' => 6)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2229TestCase.php b/tests/Ticket/2229TestCase.php index 0912d0852..48a60bffb 100644 --- a/tests/Ticket/2229TestCase.php +++ b/tests/Ticket/2229TestCase.php @@ -20,43 +20,48 @@ */ /** - * Doctrine_Ticket_2xxx_TestCase + * Doctrine_Ticket_2xxx_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2229_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2229_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { - $this->tables[] = 'Ticket_2229_SlugBug'; - parent::prepareTables(); - } - - public function testTicket() - { - $d = new Ticket_2229_SlugBug(); - $d->name = 'String with UpperLowerCase'; - $d->save(); - $this->assertEqual($d->slug, 'string-with-upperlowercase'); - - $d = new Ticket_2229_SlugBug(); - $d->name = 'Custom name OPACs'; - $d->save(); - $this->assertEqual($d->slug, 'custom-name-opacs'); - - $d = new Ticket_2229_SlugBug(); - $d->name = 'Présentation unifiée OPACs'; - $d->save(); - $this->assertEqual($d->slug, 'presentation-unifiee-opacs'); - } -} + public function prepareTables() + { + $this->tables[] = 'Ticket_2229_SlugBug'; + parent::prepareTables(); + } + + public function testTicket() + { + $d = new Ticket_2229_SlugBug(); + $d->name = 'String with UpperLowerCase'; + $d->save(); + $this->assertEqual($d->slug, 'string-with-upperlowercase'); + $d = new Ticket_2229_SlugBug(); + $d->name = 'Custom name OPACs'; + $d->save(); + $this->assertEqual($d->slug, 'custom-name-opacs'); + + $d = new Ticket_2229_SlugBug(); + $d->name = 'Présentation unifiée OPACs'; + $d->save(); + $this->assertEqual($d->slug, 'presentation-unifiee-opacs'); + } +} class Ticket_2229_SlugBug extends Doctrine_Record { @@ -66,11 +71,11 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 11, array('primary' => true, 'notnull' => true, 'autoincrement' => true)); $this->hasColumn('name', 'string'); } - + public function setUp() { - parent::setUp(); - $this->actAs('Sluggable', array('unique' => true, - 'fields' => array('name'))); + parent::setUp(); + $this->actAs('Sluggable', array('unique' => true, + 'fields' => array('name'))); } } diff --git a/tests/Ticket/2251TestCase.php b/tests/Ticket/2251TestCase.php index 21b6cae6d..4bf614137 100644 --- a/tests/Ticket/2251TestCase.php +++ b/tests/Ticket/2251TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_2251_TestCase + * Doctrine_Ticket_2251_TestCase. * - * @package Doctrine * @author Daniel Cousineau * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_2251_TestCase extends Doctrine_UnitTestCase { @@ -45,19 +51,18 @@ public function testEmptyStringLengthSQLExport() 'sqlite', 'pgsql', 'oracle', - 'mssql' + 'mssql', ); - + $expected = array( - 'mysql' => 'CREATE TABLE test_string_length (id BIGINT AUTO_INCREMENT, test_string TEXT, PRIMARY KEY(id)) ENGINE = INNODB', - 'sqlite' => 'CREATE TABLE test_string_length (id INTEGER PRIMARY KEY AUTOINCREMENT, test_string TEXT)', - 'pgsql' => 'CREATE TABLE test_string_length (id BIGSERIAL, test_string TEXT, PRIMARY KEY(id))', - 'oracle' => 'CREATE TABLE test_string_length (id NUMBER(20), test_string CLOB, PRIMARY KEY(id))', - 'mssql' => 'CREATE TABLE test_string_length (id INT NOT NULL identity, test_string TEXT NULL, PRIMARY KEY([id]))' + 'mysql' => 'CREATE TABLE test_string_length (id BIGINT AUTO_INCREMENT, test_string TEXT, PRIMARY KEY(id)) ENGINE = INNODB', + 'sqlite' => 'CREATE TABLE test_string_length (id INTEGER PRIMARY KEY AUTOINCREMENT, test_string TEXT)', + 'pgsql' => 'CREATE TABLE test_string_length (id BIGSERIAL, test_string TEXT, PRIMARY KEY(id))', + 'oracle' => 'CREATE TABLE test_string_length (id NUMBER(20), test_string CLOB, PRIMARY KEY(id))', + 'mssql' => 'CREATE TABLE test_string_length (id INT NOT NULL identity, test_string TEXT NULL, PRIMARY KEY([id]))', ); - foreach ($drivers as $driver) - { + foreach ($drivers as $driver) { $dbh = new Doctrine_Adapter_Mock($driver); $conn = Doctrine_Manager::getInstance()->connection($dbh, $driver); @@ -66,8 +71,7 @@ public function testEmptyStringLengthSQLExport() $this->assertEqual($sql, $expected[$driver]); - unset($conn); - unset($dbh); + unset($conn, $dbh); } } } @@ -76,12 +80,12 @@ class Ticket_2251_TestStringLength extends Doctrine_Record { public function setTableDefinition() { - $this->setTableName('test_string_length'); - $this->hasColumn('test_string', 'string'); + $this->setTableName('test_string_length'); + $this->hasColumn('test_string', 'string'); } public function setUp() { parent::setUp(); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2292TestCase.php b/tests/Ticket/2292TestCase.php index a5db98d34..29c054c30 100644 --- a/tests/Ticket/2292TestCase.php +++ b/tests/Ticket/2292TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_2292_TestCase + * Doctrine_Ticket_2292_TestCase. * - * @package Doctrine * @author Miloslav Kmeť * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2292_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2292_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -39,16 +45,16 @@ public function prepareTables() $this->tables[] = 'mkContent'; parent::prepareTables(); } - + public function prepareData() { } - + public function testOwningSideRelationToArray() { $article = new mkArticle(); - - $this->assertEqual($article->content->toArray(false), array('id'=>null, 'body'=>null)); + + $this->assertEqual($article->content->toArray(false), array('id' => null, 'body' => null)); } } @@ -60,12 +66,12 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'autoincrement' => true, 'primary' => true, 'length' => 4)); $this->hasColumn('title', 'string', 200); } - + public function setup() { - $this->hasOne('mkContent as content', array('local'=>'id', - 'foreign'=>'id', - 'owningSide' => false)); + $this->hasOne('mkContent as content', array('local' => 'id', + 'foreign' => 'id', + 'owningSide' => false)); } } @@ -77,12 +83,11 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'autoincrement' => false, 'primary' => true, 'length' => 4)); $this->hasColumn('body', 'string'); } - + public function setup() { - $this->hasOne('mkArticle as article', array('local'=>'id', - 'foreign'=>'id', - 'owningSide' => true)); + $this->hasOne('mkArticle as article', array('local' => 'id', + 'foreign' => 'id', + 'owningSide' => true)); } } - diff --git a/tests/Ticket/2295TestCase.php b/tests/Ticket/2295TestCase.php index 8dd0a968f..fc876ec12 100644 --- a/tests/Ticket/2295TestCase.php +++ b/tests/Ticket/2295TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_2295_TestCase + * Doctrine_Ticket_2295_TestCase. * - * @package Doctrine * @author Miloslav Kmeť * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_2295_TestCase extends Doctrine_UnitTestCase { @@ -53,4 +59,4 @@ public function construct() { $this->mapValue('test'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2298TestCase.php b/tests/Ticket/2298TestCase.php index 7c19d9898..f0c3e2cfa 100644 --- a/tests/Ticket/2298TestCase.php +++ b/tests/Ticket/2298TestCase.php @@ -1,27 +1,34 @@ from('Address a') - ->where("a.address = '(a) and c'"); + ->where("a.address = '(a) and c'") + ; $this->assertEqual($q->getSqlQuery(), "SELECT a.id AS a__id, a.address AS a__address FROM address a WHERE (a.address = '(a) and c')"); $q = Doctrine_Query::create() ->from('Address a') - ->where("a.address = ' or what'"); + ->where("a.address = ' or what'") + ; $this->assertEqual($q->getSqlQuery(), "SELECT a.id AS a__id, a.address AS a__address FROM address a WHERE (a.address = ' or what')"); $q = Doctrine_Query::create() ->from('Address a') - ->where("a.address = ' or 6spaces'"); - $this->assertEqual($q->getSqlQuery(), "SELECT a.id AS a__id, a.address AS a__address FROM address a WHERE (a.address = ' or 6spaces')"); + ->where("a.address = ' or 6spaces'") + ; + $this->assertEqual($q->getSqlQuery(), "SELECT a.id AS a__id, a.address AS a__address FROM address a WHERE (a.address = ' or 6spaces')"); } - - public function testEscapedQuotes() + public function testEscapedQuotes() { $tokenizer = new Doctrine_Query_Tokenizer(); $delimiters = array(' ', '+', '-', '*', '/', '<', '>', '=', '>=', '<=', '&', '|'); @@ -29,36 +36,33 @@ public function testEscapedQuotes() $res = $tokenizer->bracketExplode("'a string with AND in the middle'", ' AND '); $this->assertEqual($res, array("'a string with AND in the middle'")); - $res = $tokenizer->bracketExplode("'o\' AND string'", ' AND '); - $this->assertEqual($res, array("'o\' AND string'")); + $res = $tokenizer->bracketExplode("'o\\' AND string'", ' AND '); + $this->assertEqual($res, array("'o\\' AND string'")); - $res = $tokenizer->sqlExplode("('John O\'Connor (West) as name'+' ') + 'b'", $delimiters); - $this->assertEqual($res, array("('John O\'Connor (West) as name'+' ')", '', '', "'b'")); + $res = $tokenizer->sqlExplode("('John O\\'Connor (West) as name'+' ') + 'b'", $delimiters); + $this->assertEqual($res, array("('John O\\'Connor (West) as name'+' ')", '', '', "'b'")); $res = $tokenizer->sqlExplode("'(Word) and' term", $delimiters); $this->assertEqual($res, array("'(Word) and'", 'term')); } - - public function testAdditionalTokenizerFeatures() + public function testAdditionalTokenizerFeatures() { - // These tests all pass with the old tokenizer, they were developed wile - // working on the patch - $tokenizer = new Doctrine_Query_Tokenizer(); - $delimiters = array(' ', '+', '-', '*', '/', '<', '>', '=', '>=', '<=', '&', '|'); + // These tests all pass with the old tokenizer, they were developed wile + // working on the patch + $tokenizer = new Doctrine_Query_Tokenizer(); + $delimiters = array(' ', '+', '-', '*', '/', '<', '>', '=', '>=', '<=', '&', '|'); - $res = $tokenizer->bracketExplode("(age < 20 AND age > 18) AND email LIKE 'John@example.com'", ' AND ', '(', ')'); - $this->assertEqual($res, array("(age < 20 AND age > 18)","email LIKE 'John@example.com'")); + $res = $tokenizer->bracketExplode("(age < 20 AND age > 18) AND email LIKE 'John@example.com'", ' AND ', '(', ')'); + $this->assertEqual($res, array('(age < 20 AND age > 18)', "email LIKE 'John@example.com'")); - $res = $tokenizer->sqlExplode("sentence OR 'term'", ' OR '); - $this->assertEqual($res, array("sentence", "'term'")); + $res = $tokenizer->sqlExplode("sentence OR 'term'", ' OR '); + $this->assertEqual($res, array('sentence', "'term'")); $res = $tokenizer->clauseExplode("'a + b'+c", $delimiters); - $this->assertEqual($res, array(array("'a + b'",'+'), array('c', ''))); + $this->assertEqual($res, array(array("'a + b'", '+'), array('c', ''))); $res = $tokenizer->quoteExplode('"a"."b"', ' '); $this->assertEqual($res, array('"a"."b"')); } } - -?> \ No newline at end of file diff --git a/tests/Ticket/2334TestCase.php b/tests/Ticket/2334TestCase.php index ab458797b..41512dbf6 100644 --- a/tests/Ticket/2334TestCase.php +++ b/tests/Ticket/2334TestCase.php @@ -20,15 +20,21 @@ */ /** - * Ticket_2334_TestMSSQLUnsignedInt + * Ticket_2334_TestMSSQLUnsignedInt. * - * @package Doctrine * @author Daniel Cousineau * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_2334_TestCase extends Doctrine_UnitTestCase { @@ -37,6 +43,7 @@ public function prepareTables() $this->tables[] = 'Ticket_2334_TestMSSQLUnsignedInt'; parent::prepareTables(); } + public function testMSSQLUnsignedInt() { $dbh = new Doctrine_Adapter_Mock('mssql'); @@ -47,21 +54,20 @@ public function testMSSQLUnsignedInt() $this->assertEqual($sql, 'CREATE TABLE test_string_length (id INT NOT NULL identity, test_int BIGINT NULL, PRIMARY KEY([id]))'); - unset($conn); - unset($dbh); + unset($conn, $dbh); } } class Ticket_2334_TestMSSQLUnsignedInt extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('test_string_length'); - $this->hasColumn('test_int', 'int', null, array('unsigned' => true)); - } + public function setTableDefinition() + { + $this->setTableName('test_string_length'); + $this->hasColumn('test_int', 'int', null, array('unsigned' => true)); + } - public function setUp() - { - parent::setUp(); - } -} \ No newline at end of file + public function setUp() + { + parent::setUp(); + } +} diff --git a/tests/Ticket/2355TestCase.php b/tests/Ticket/2355TestCase.php index c661703ca..406e2e8ef 100644 --- a/tests/Ticket/2355TestCase.php +++ b/tests/Ticket/2355TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_2355_TestCase + * Doctrine_Ticket_2355_TestCase. * - * @package Doctrine * @author Fabien Pennequin * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2355_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2355_TestCase extends Doctrine_UnitTestCase { public function setUp() { @@ -51,7 +57,7 @@ public function prepareTables() public function testImport() { - $yml = <<hasColumn('title', 'string', 255, array( - 'type' => 'string', - 'notnull' => true, - 'notblank' => true, - 'length' => '255', - )); + 'type' => 'string', + 'notnull' => true, + 'notblank' => true, + 'length' => '255', + )); } } @@ -139,58 +145,56 @@ class Episode extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('season', 'integer', 1, array( - 'type' => 'integer', - 'length' => 1, - 'notnull' => true, - 'notblank' => true, - )); + 'type' => 'integer', + 'length' => 1, + 'notnull' => true, + 'notblank' => true, + )); $this->hasColumn('number', 'integer', 1, array( - 'type' => 'integer', - 'length' => 1, - 'notnull' => true, - 'notblank' => true, - )); + 'type' => 'integer', + 'length' => 1, + 'notnull' => true, + 'notblank' => true, + )); $this->hasColumn('title_us', 'string', 100, array( - 'type' => 'string', - 'notnull' => true, - 'notblank' => true, - 'length' => '100', - )); + 'type' => 'string', + 'notnull' => true, + 'notblank' => true, + 'length' => '100', + )); $this->hasColumn('title_fr', 'string', 100, array( - 'type' => 'string', - 'length' => '100', - )); - + 'type' => 'string', + 'length' => '100', + )); $this->index('episode', array( - 'fields' => - array( - 0 => 'season', - 1 => 'number', - ), - 'type' => 'unique', - )); + 'fields' => array( + 0 => 'season', + 1 => 'number', + ), + 'type' => 'unique', + )); } public function setUp() { $this->hasMany('Writer as Writers', array( - 'refClass' => 'WriterEpisode', - 'local' => 'episode_id', - 'foreign' => 'writer_id')); + 'refClass' => 'WriterEpisode', + 'local' => 'episode_id', + 'foreign' => 'writer_id')); $this->hasMany('Director as Directors', array( - 'refClass' => 'DirectorEpisode', - 'local' => 'episode_id', - 'foreign' => 'director_id')); + 'refClass' => 'DirectorEpisode', + 'local' => 'episode_id', + 'foreign' => 'director_id')); $this->hasMany('WriterEpisode', array( - 'local' => 'id', - 'foreign' => 'episode_id')); + 'local' => 'id', + 'foreign' => 'episode_id')); $this->hasMany('DirectorEpisode', array( - 'local' => 'id', - 'foreign' => 'episode_id')); + 'local' => 'id', + 'foreign' => 'episode_id')); } } @@ -199,24 +203,24 @@ class Writer extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('name', 'string', 150, array( - 'type' => 'string', - 'notnull' => true, - 'notblank' => true, - 'unique' => true, - 'length' => '150', - )); + 'type' => 'string', + 'notnull' => true, + 'notblank' => true, + 'unique' => true, + 'length' => '150', + )); } public function setUp() { $this->hasMany('Episode', array( - 'refClass' => 'WriterEpisode', - 'local' => 'writer_id', - 'foreign' => 'episode_id')); + 'refClass' => 'WriterEpisode', + 'local' => 'writer_id', + 'foreign' => 'episode_id')); $this->hasMany('WriterEpisode', array( - 'local' => 'id', - 'foreign' => 'writer_id')); + 'local' => 'id', + 'foreign' => 'writer_id')); } } @@ -225,26 +229,26 @@ class WriterEpisode extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('episode_id', 'integer', null, array( - 'type' => 'integer', - 'primary' => true, - )); + 'type' => 'integer', + 'primary' => true, + )); $this->hasColumn('writer_id', 'integer', null, array( - 'type' => 'integer', - 'primary' => true, - )); + 'type' => 'integer', + 'primary' => true, + )); } public function setUp() { $this->hasOne('Writer', array( - 'local' => 'writer_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + 'local' => 'writer_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); $this->hasOne('Episode', array( - 'local' => 'episode_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + 'local' => 'episode_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); } } @@ -253,24 +257,24 @@ class Director extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('name', 'string', 150, array( - 'type' => 'string', - 'notnull' => true, - 'notblank' => true, - 'unique' => true, - 'length' => '150', - )); + 'type' => 'string', + 'notnull' => true, + 'notblank' => true, + 'unique' => true, + 'length' => '150', + )); } public function setUp() { $this->hasMany('Episode', array( - 'refClass' => 'DirectorEpisode', - 'local' => 'director_id', - 'foreign' => 'episode_id')); + 'refClass' => 'DirectorEpisode', + 'local' => 'director_id', + 'foreign' => 'episode_id')); $this->hasMany('DirectorEpisode', array( - 'local' => 'id', - 'foreign' => 'director_id')); + 'local' => 'id', + 'foreign' => 'director_id')); } } @@ -279,25 +283,25 @@ class DirectorEpisode extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('episode_id', 'integer', null, array( - 'type' => 'integer', - 'primary' => true, - )); + 'type' => 'integer', + 'primary' => true, + )); $this->hasColumn('director_id', 'integer', null, array( - 'type' => 'integer', - 'primary' => true, - )); + 'type' => 'integer', + 'primary' => true, + )); } public function setUp() { $this->hasOne('Director', array( - 'local' => 'director_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + 'local' => 'director_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); $this->hasOne('Episode', array( - 'local' => 'episode_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + 'local' => 'episode_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2367TestCase.php b/tests/Ticket/2367TestCase.php index da14a6503..1565b6577 100644 --- a/tests/Ticket/2367TestCase.php +++ b/tests/Ticket/2367TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_2367_TestCase + * Doctrine_Ticket_2367_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2367_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2367_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -42,12 +48,12 @@ public function testTest() { $article = new Ticket_2367_Article(); $article->fromArray(array( - 'Translation' => array( - 'en' => array( - 'content' => 'article content', - ), - 'fr' => array( - 'content' => 'contenu de l\'article')))); + 'Translation' => array( + 'en' => array( + 'content' => 'article content', + ), + 'fr' => array( + 'content' => 'contenu de l\'article')))); $article->save(); $article->delete(); $check = (bool) Doctrine_Core::getTable('Ticket_2367_ArticleTranslation')->count(); @@ -60,7 +66,7 @@ class Ticket_2367_Article extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('id', 'integer', 2, array('type' => 'integer', 'primary' => true, - 'autoincrement' => true, 'unsigned' => true, 'length' => '2')); + 'autoincrement' => true, 'unsigned' => true, 'length' => '2')); $this->hasColumn('content', 'string', 100, array('type' => 'string', 'length' => '100')); $this->option('type', 'MyISAM'); @@ -68,10 +74,10 @@ public function setTableDefinition() public function setUp() { - $i18n0 = new Doctrine_Template_I18n(array( - 'appLevelDelete' => true, - 'fields' => array( - 0 => 'content'))); - $this->actAs($i18n0); + $i18n0 = new Doctrine_Template_I18n(array( + 'appLevelDelete' => true, + 'fields' => array( + 0 => 'content'))); + $this->actAs($i18n0); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2375/models1/Ticket_2375_Model1.php b/tests/Ticket/2375/models1/Ticket_2375_Model1.php index 179ab5620..fd5387502 100755 --- a/tests/Ticket/2375/models1/Ticket_2375_Model1.php +++ b/tests/Ticket/2375/models1/Ticket_2375_Model1.php @@ -1,8 +1,9 @@ hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2375/models1/Ticket_2375_Model2.php b/tests/Ticket/2375/models1/Ticket_2375_Model2.php index 43588e5f1..0b2ee581e 100755 --- a/tests/Ticket/2375/models1/Ticket_2375_Model2.php +++ b/tests/Ticket/2375/models1/Ticket_2375_Model2.php @@ -6,4 +6,4 @@ public function setTableDefinition() { $this->hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2375/models2/Ticket_2375_Model3.php b/tests/Ticket/2375/models2/Ticket_2375_Model3.php index 98b70534f..df474a974 100755 --- a/tests/Ticket/2375/models2/Ticket_2375_Model3.php +++ b/tests/Ticket/2375/models2/Ticket_2375_Model3.php @@ -1,8 +1,9 @@ hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2375/models2/Ticket_2375_Model4.php b/tests/Ticket/2375/models2/Ticket_2375_Model4.php index ff46e5364..e3761ba20 100755 --- a/tests/Ticket/2375/models2/Ticket_2375_Model4.php +++ b/tests/Ticket/2375/models2/Ticket_2375_Model4.php @@ -6,4 +6,4 @@ public function setTableDefinition() { $this->hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2375/models2/Ticket_2375_Model5.php b/tests/Ticket/2375/models2/Ticket_2375_Model5.php index a5b98514d..172d75962 100755 --- a/tests/Ticket/2375/models2/Ticket_2375_Model5.php +++ b/tests/Ticket/2375/models2/Ticket_2375_Model5.php @@ -14,4 +14,4 @@ public function setTableDefinition() { $this->hasColumn('name', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2375TestCase.php b/tests/Ticket/2375TestCase.php index 8d10be404..aeaf9f5da 100644 --- a/tests/Ticket/2375TestCase.php +++ b/tests/Ticket/2375TestCase.php @@ -20,27 +20,33 @@ */ /** - * Doctrine_Ticket_2375_TestCase + * Doctrine_Ticket_2375_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_2375_TestCase extends Doctrine_UnitTestCase { public function testTest() { - $models1Dir = dirname(__FILE__) . '/2375/models1'; - $models2Dir = dirname(__FILE__) . '/2375/models2'; + $models1Dir = dirname(__FILE__).'/2375/models1'; + $models2Dir = dirname(__FILE__).'/2375/models2'; // try loading a couple initial models $models1 = Doctrine_Core::loadModels($models1Dir); - //$models2 = Doctrine_Core::loadModels($models2Dir); + // $models2 = Doctrine_Core::loadModels($models2Dir); // make sure two models were loaded $this->assertEqual(2, count($models1)); @@ -53,8 +59,8 @@ public function testTest() $loadedModels = Doctrine_Core::getLoadedModelFiles(); // make sure the paths are correct - $this->assertEqual($loadedModels['Ticket_2375_Model1'], $models1Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model1.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model2'], $models1Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model2.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model1'], $models1Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model1.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model2'], $models1Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model2.php'); // try loading a few more models @@ -70,12 +76,12 @@ public function testTest() $loadedModels = Doctrine_Core::getLoadedModelFiles(); // make sure the paths are correct - $this->assertEqual($loadedModels['Ticket_2375_Model1'], $models1Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model1.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model2'], $models1Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model2.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model3'], $models2Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model3.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model4'], $models2Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model4.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model5'], $models2Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model5.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model6'], $models2Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model5.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model1'], $models1Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model1.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model2'], $models1Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model2.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model3'], $models2Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model3.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model4'], $models2Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model4.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model5'], $models2Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model5.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model6'], $models2Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model5.php'); // try loading the first models again @@ -89,11 +95,11 @@ public function testTest() $loadedModels = Doctrine_Core::getLoadedModelFiles(); // make sure the paths are correct - $this->assertEqual($loadedModels['Ticket_2375_Model1'], $models1Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model1.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model2'], $models1Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model2.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model3'], $models2Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model3.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model4'], $models2Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model4.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model5'], $models2Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model5.php'); - $this->assertEqual($loadedModels['Ticket_2375_Model6'], $models2Dir . DIRECTORY_SEPARATOR . 'Ticket_2375_Model5.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model1'], $models1Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model1.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model2'], $models1Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model2.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model3'], $models2Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model3.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model4'], $models2Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model4.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model5'], $models2Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model5.php'); + $this->assertEqual($loadedModels['Ticket_2375_Model6'], $models2Dir.DIRECTORY_SEPARATOR.'Ticket_2375_Model5.php'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2377TestCase.php b/tests/Ticket/2377TestCase.php index b60f8affb..20a590939 100644 --- a/tests/Ticket/2377TestCase.php +++ b/tests/Ticket/2377TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_2355_TestCase + * Doctrine_Ticket_2355_TestCase. * - * @package Doctrine * @author Jacek Dębowczyk * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2377_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2377_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -42,20 +48,20 @@ public function prepareTables() public function testSynchronize() { try { - $author = new Ticket_2377_Author(); - $article = new Ticket_2377_Article(); - $article->Author = $author; - - $array = $article->toArray(true); - - $article2 = new Ticket_2377_Article(); - $article2->synchronizeWithArray($array); + $author = new Ticket_2377_Author(); + $article = new Ticket_2377_Article(); + $article->Author = $author; + + $array = $article->toArray(true); - $this->assertTrue($article2->Author instanceof Ticket_2377_Author); + $article2 = new Ticket_2377_Article(); + $article2->synchronizeWithArray($array); + + $this->assertTrue($article2->Author instanceof Ticket_2377_Author); $this->pass(); } catch (Exception $e) { - $this->fail(); + $this->fail(); } } } @@ -66,9 +72,9 @@ public function setTableDefinition() { $this->setTableName('author'); $this->hasColumn('id', 'integer', 2, - array('type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '2')); + array('type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '2')); $this->hasColumn('name', 'string', 2, - array('type' => 'string', 'length' => '100')); + array('type' => 'string', 'length' => '100')); } public function setUp() @@ -83,15 +89,15 @@ public function setTableDefinition() { $this->setTableName('article'); $this->hasColumn('id', 'integer', 2, - array('type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '2')); + array('type' => 'integer', 'primary' => true, 'autoincrement' => true, 'length' => '2')); $this->hasColumn('author_id', 'integer', 2, - array('type' => 'integer', 'unsigned' => true, 'length' => '2')); + array('type' => 'integer', 'unsigned' => true, 'length' => '2')); $this->hasColumn('content', 'string', 100, - array('type' => 'string', 'length' => '100')); + array('type' => 'string', 'length' => '100')); } public function setUp() { $this->hasOne('Ticket_2377_Author as Author', array('local' => 'author_id', 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/2398TestCase.php b/tests/Ticket/2398TestCase.php index 8689c38bd..74d4a4008 100644 --- a/tests/Ticket/2398TestCase.php +++ b/tests/Ticket/2398TestCase.php @@ -20,30 +20,36 @@ */ /** - * Doctrine_Ticket_1015_TestCase + * Doctrine_Ticket_1015_TestCase. * - * @package Doctrine * @author Russ Flynn * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_2398_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_2398_TestCase extends Doctrine_UnitTestCase { // Since this file is the subject of the test, we need to add some utf-8 chars to mess up // the non-binary-safe count. - private $randomUtf8 = "øåæØÅÆØÅæøåøæØÅæøåØÆØåøÆØÅøæøåøæøåÅØÆØ"; - + private $randomUtf8 = 'øåæØÅÆØÅæøåøæØÅæøåØÆØåøÆØÅøæøåøæøåÅØÆØ'; + public function testIsValidLength() { $binaryValue = fread(fopen(__FILE__, 'r'), filesize(__FILE__)); - //Should pass with size the same size as maximum size - $this->assertTrue(Doctrine_Validator::validateLength($binaryValue, "blob", filesize(__FILE__))); - - //Should fail with maximum size 1 less than actual file size - $this->assertFalse(Doctrine_Validator::validateLength($binaryValue, "blob", filesize(__FILE__) -1)); + // Should pass with size the same size as maximum size + $this->assertTrue(Doctrine_Validator::validateLength($binaryValue, 'blob', filesize(__FILE__))); + + // Should fail with maximum size 1 less than actual file size + $this->assertFalse(Doctrine_Validator::validateLength($binaryValue, 'blob', filesize(__FILE__) - 1)); } } diff --git a/tests/Ticket/255TestCase.php b/tests/Ticket/255TestCase.php index d13530d51..e4f3df4fc 100644 --- a/tests/Ticket/255TestCase.php +++ b/tests/Ticket/255TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_255_TestCase + * Doctrine_Ticket_255_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_255_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_255_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -81,4 +87,4 @@ public function setTableDefinition() $this->unique(array('username', 'email_address')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/381TestCase.php b/tests/Ticket/381TestCase.php index d88ba3b9a..4bf5cb99e 100644 --- a/tests/Ticket/381TestCase.php +++ b/tests/Ticket/381TestCase.php @@ -20,25 +20,34 @@ */ /** - * Doctrine_Ticket381_TestCase + * Doctrine_Ticket381_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_381_TestCase extends Doctrine_UnitTestCase { +class Doctrine_Ticket_381_TestCase extends Doctrine_UnitTestCase +{ + public function prepareData() + { + } - public function prepareData() - { } - public function prepareTables() { + public function prepareTables() + { $this->tables = array('Book'); parent::prepareTables(); } - + public function testTicket() { $obj = new Book(); @@ -48,6 +57,7 @@ public function testTicket() $this->assertEqual($obj->get('name'), 'yes'); $obj->save(); } + public function testTicket2() { $obj = new Book(); diff --git a/tests/Ticket/384TestCase.php b/tests/Ticket/384TestCase.php index 35a906d9c..54b322d18 100644 --- a/tests/Ticket/384TestCase.php +++ b/tests/Ticket/384TestCase.php @@ -20,37 +20,43 @@ */ /** - * Doctrine_Ticket_384_TestCase + * Doctrine_Ticket_384_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_384_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_384_TestCase extends Doctrine_UnitTestCase { public function prepareData() { - $oResume = new ticket384_Resume; - $oResume->title = 'titre'; - $oResume->KnownLanguages[0]->comments = 'foo'; - $oResume->KnownLanguages[0]->Language->label = "Enlish"; - $oResume->KnownLanguages[0]->Level->label = "Fluent"; - $oResume->save(); + $oResume = new ticket384_Resume(); + $oResume->title = 'titre'; + $oResume->KnownLanguages[0]->comments = 'foo'; + $oResume->KnownLanguages[0]->Language->label = 'Enlish'; + $oResume->KnownLanguages[0]->Level->label = 'Fluent'; + $oResume->save(); } public function prepareTables() { - $this->tables = array(); - $this->tables[] = 'ticket384_Resume'; - $this->tables[] = 'ticket384_ResumeHasLanguage'; - $this->tables[] = 'ticket384_LanguageLevel'; - $this->tables[] = 'ticket384_Language'; - - parent :: prepareTables(); + $this->tables = array(); + $this->tables[] = 'ticket384_Resume'; + $this->tables[] = 'ticket384_ResumeHasLanguage'; + $this->tables[] = 'ticket384_LanguageLevel'; + $this->tables[] = 'ticket384_Language'; + + parent::prepareTables(); } public function testTicket() @@ -59,148 +65,148 @@ public function testTicket() // simple query with deep relations $q->addSelect('Resume.id, Level.id, Level.label') - ->from('ticket384_Resume Resume') - ->leftJoin('Resume.KnownLanguages KnownLanguages') - ->leftJoin('KnownLanguages.Level Level') - ->leftJoin('KnownLanguages.Language Language'); - + ->from('ticket384_Resume Resume') + ->leftJoin('Resume.KnownLanguages KnownLanguages') + ->leftJoin('KnownLanguages.Level Level') + ->leftJoin('KnownLanguages.Language Language') + ; + try { // get the wrong resultset $aResult = $q->fetchArray(); $this->fail(); } catch (Doctrine_Query_Exception $e) { $this->pass(); - } + } $q->free(); - + // now correct // we have to select at least KnownLanguages.id in order to get the Levels, // which are only reachable through the KnownLanguages, hydrated properly. $q = new Doctrine_Query(); $q->addSelect('Resume.id, Level.id, Level.label, KnownLanguages.id') - ->from('ticket384_Resume Resume') - ->leftJoin('Resume.KnownLanguages KnownLanguages') - ->leftJoin('KnownLanguages.Level Level') - ->leftJoin('KnownLanguages.Language Language'); - + ->from('ticket384_Resume Resume') + ->leftJoin('Resume.KnownLanguages KnownLanguages') + ->leftJoin('KnownLanguages.Level Level') + ->leftJoin('KnownLanguages.Language Language') + ; + $aResult = $q->fetchArray(); // should be setted - $bSuccess = isset($aResult[0]['KnownLanguages'][0]['Level']); + $bSuccess = isset($aResult[0]['KnownLanguages'][0]['Level']); $this->assertTrue($bSuccess); - - if ( ! $bSuccess) - { - $this->fail('fetchArray doesnt hydrate nested child relations, if parent doesnt have a column selected'); - } + + if (!$bSuccess) { + $this->fail('fetchArray doesnt hydrate nested child relations, if parent doesnt have a column selected'); + } } } class ticket384_Resume extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('resume'); - $this->hasColumn('id', 'integer', 8, array ( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); - - $this->hasColumn('title', 'string', 255); - } - - public function setUp() - { - $this->hasMany('ticket384_ResumeHasLanguage as KnownLanguages', array('local' => 'id', 'foreign' => 'resume_id')); - } + public function setTableDefinition() + { + $this->setTableName('resume'); + $this->hasColumn('id', 'integer', 8, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); + + $this->hasColumn('title', 'string', 255); + } + + public function setUp() + { + $this->hasMany('ticket384_ResumeHasLanguage as KnownLanguages', array('local' => 'id', 'foreign' => 'resume_id')); + } } class ticket384_ResumeHasLanguage extends Doctrine_Record -{ - public function setTableDefinition() - { - $this->setTableName('resume_has_language'); - $this->hasColumn('id', 'integer', 8, array ( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); - - $this->hasColumn('resume_id', 'integer', 8, array ( - 'notnull' => true, - 'unsigned' => true, - )); - - $this->hasColumn('language_id', 'integer', 2, array ( - 'unsigned' => true, - )); - - $this->hasColumn('language_level_id', 'integer', 2, array ( - 'unsigned' => true, - )); - - $this->hasColumn('comments', 'string', 4000, array ()); - - } - - public function setUp() - { - $this->hasOne('ticket384_Resume as Resume', array('local' => 'resume_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE', - 'onUpdate' => 'CASCADE')); - - $this->hasOne('ticket384_Language as Language', array('local' => 'language_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE', - 'onUpdate' => 'CASCADE')); - - $this->hasOne('ticket384_LanguageLevel as Level', array('local' => 'language_level_id', - 'foreign' => 'id', - 'onDelete' => 'SET NULL', - 'onUpdate' => 'CASCADE')); - } +{ + public function setTableDefinition() + { + $this->setTableName('resume_has_language'); + $this->hasColumn('id', 'integer', 8, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); + + $this->hasColumn('resume_id', 'integer', 8, array( + 'notnull' => true, + 'unsigned' => true, + )); + + $this->hasColumn('language_id', 'integer', 2, array( + 'unsigned' => true, + )); + + $this->hasColumn('language_level_id', 'integer', 2, array( + 'unsigned' => true, + )); + + $this->hasColumn('comments', 'string', 4000, array()); + } + + public function setUp() + { + $this->hasOne('ticket384_Resume as Resume', array('local' => 'resume_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + 'onUpdate' => 'CASCADE')); + + $this->hasOne('ticket384_Language as Language', array('local' => 'language_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + 'onUpdate' => 'CASCADE')); + + $this->hasOne('ticket384_LanguageLevel as Level', array('local' => 'language_level_id', + 'foreign' => 'id', + 'onDelete' => 'SET NULL', + 'onUpdate' => 'CASCADE')); + } } class ticket384_Language extends Doctrine_Record -{ - public function setTableDefinition() - { - $this->setTableName('language'); - $this->hasColumn('id', 'integer', 2, array( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); - - $this->hasColumn('label', 'string', 100, array ('notnull' => true)); - } - - public function setUp() - { - $this->hasMany('ticket384_Resume as Resumes', array('local' => 'id', 'foreign' => 'language_id')); - $this->hasMany('ticket384_ResumeHasLanguage as ResumeKnownLanguages', array('local' => 'id', 'foreign' => 'language_id')); - } +{ + public function setTableDefinition() + { + $this->setTableName('language'); + $this->hasColumn('id', 'integer', 2, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); + + $this->hasColumn('label', 'string', 100, array('notnull' => true)); + } + + public function setUp() + { + $this->hasMany('ticket384_Resume as Resumes', array('local' => 'id', 'foreign' => 'language_id')); + $this->hasMany('ticket384_ResumeHasLanguage as ResumeKnownLanguages', array('local' => 'id', 'foreign' => 'language_id')); + } } class ticket384_LanguageLevel extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('language_level'); - $this->hasColumn('id', 'integer', 2, array ( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); - - $this->hasColumn('label', 'string', 100, array ('notnull' => true)); - } - - public function setUp() - { - $this->hasMany('ticket384_ResumeHasLanguage as ResumeKnownLanguages', array( - 'local' => 'id', - 'foreign' => 'language_level_id')); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('language_level'); + $this->hasColumn('id', 'integer', 2, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); + + $this->hasColumn('label', 'string', 100, array('notnull' => true)); + } + + public function setUp() + { + $this->hasMany('ticket384_ResumeHasLanguage as ResumeKnownLanguages', array( + 'local' => 'id', + 'foreign' => 'language_level_id')); + } +} diff --git a/tests/Ticket/424BTestCase.php b/tests/Ticket/424BTestCase.php index e1fa22915..e2339884e 100644 --- a/tests/Ticket/424BTestCase.php +++ b/tests/Ticket/424BTestCase.php @@ -20,22 +20,29 @@ */ /** - * Doctrine_Ticket424B_TestCase + * Doctrine_Ticket424B_TestCase. * * This test case tests many-many relationship with non-autoincrement primary key * - * @package Doctrine * @author Tamcy <7am.online@gmail.com> * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_424B_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } public function prepareTables() { @@ -50,6 +57,7 @@ protected function newGroup($code, $name) $group->id = $code; $group->name = $name; $group->save(); + return $group; } @@ -59,11 +67,12 @@ protected function newUser($code, $name, $groups) $u->id = $code; $u->name = $name; - foreach ($groups as $idx=>$group) { + foreach ($groups as $idx => $group) { $u->Group[$idx] = $group; } $u->save(); + return $u; } @@ -73,9 +82,9 @@ public function testManyManyRelationWithAliasColumns() $groupB = $this->newGroup(2, 'Group B'); $groupC = $this->newGroup(3, 'Group C'); - $john = $this->newUser(1, 'John', array($groupA, $groupB)); + $john = $this->newUser(1, 'John', array($groupA, $groupB)); $peter = $this->newUser(2, 'Peter', array($groupA, $groupC)); - $alan = $this->newUser(3, 'Alan', array($groupB, $groupC)); + $alan = $this->newUser(3, 'Alan', array($groupB, $groupC)); $q = Doctrine_Query::create(); $gu = $q->from('mmrGroupUser_B')->execute(); @@ -89,11 +98,11 @@ public function testManyManyRelationWithAliasColumns() // Query by join $q = Doctrine_Query::create() ->from('mmrUser_B u, u.Group g') - ->where('g.name = ?', array($groupA->name)); + ->where('g.name = ?', array($groupA->name)) + ; $userOfGroupAByName = $q->execute(); $this->assertEqual(count($userOfGroupAByName), 2); - } } diff --git a/tests/Ticket/424CTestCase.php b/tests/Ticket/424CTestCase.php index f629a1fda..577506bd7 100644 --- a/tests/Ticket/424CTestCase.php +++ b/tests/Ticket/424CTestCase.php @@ -20,23 +20,29 @@ */ /** - * Doctrine_Ticket424B_TestCase + * Doctrine_Ticket424B_TestCase. * * This test case tests many-many relationship with non-autoincrement, alias primary key * - * @package Doctrine * @author Tamcy <7am.online@gmail.com> * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_424C_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } public function prepareTables() { @@ -50,6 +56,7 @@ protected function newGroup($code, $name) $group->id = $code; $group->name = $name; $group->save(); + return $group; } @@ -58,39 +65,41 @@ protected function newUser($code, $name, $groups) $u = new mmrUser_C(); $u->id = $code; $u->name = $name; - foreach ($groups as $idx=>$group) { + foreach ($groups as $idx => $group) { $u->Group[$idx] = $group; } $u->save(); + return $u; } public function testManyManyRelationWithAliasColumns() { - $groupA = $this->newGroup(1, 'Group A'); - $groupB = $this->newGroup(2, 'Group B'); - $groupC = $this->newGroup(3, 'Group C'); + $groupA = $this->newGroup(1, 'Group A'); + $groupB = $this->newGroup(2, 'Group B'); + $groupC = $this->newGroup(3, 'Group C'); - $john = $this->newUser(1, 'John', array($groupA, $groupB)); - $peter = $this->newUser(2, 'Peter', array($groupA, $groupC)); - $alan = $this->newUser(3, 'Alan', array($groupB, $groupC)); + $john = $this->newUser(1, 'John', array($groupA, $groupB)); + $peter = $this->newUser(2, 'Peter', array($groupA, $groupC)); + $alan = $this->newUser(3, 'Alan', array($groupB, $groupC)); - $q = Doctrine_Query::create(); - $gu = $q->from('mmrGroupUser_C')->execute(); - $this->assertEqual(count($gu), 6); + $q = Doctrine_Query::create(); + $gu = $q->from('mmrGroupUser_C')->execute(); + $this->assertEqual(count($gu), 6); - // Direct query - $q = Doctrine_Query::create(); - $gu = $q->from('mmrGroupUser_C')->where('group_id = ?', $groupA->id)->execute(); - $this->assertEqual(count($gu), 2); + // Direct query + $q = Doctrine_Query::create(); + $gu = $q->from('mmrGroupUser_C')->where('group_id = ?', $groupA->id)->execute(); + $this->assertEqual(count($gu), 2); - // Query by join - $q = Doctrine_Query::create() + // Query by join + $q = Doctrine_Query::create() ->from('mmrUser_C u, u.Group g') - ->where('g.name = ?', array($groupA->name)); + ->where('g.name = ?', array($groupA->name)) + ; - $userOfGroupAByName = $q->execute(); + $userOfGroupAByName = $q->execute(); - $this->assertEqual(count($userOfGroupAByName), 2); + $this->assertEqual(count($userOfGroupAByName), 2); } } diff --git a/tests/Ticket/428TestCase.php b/tests/Ticket/428TestCase.php index 4a155d802..43237f55a 100644 --- a/tests/Ticket/428TestCase.php +++ b/tests/Ticket/428TestCase.php @@ -1,25 +1,31 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_428_TestCase extends Doctrine_UnitTestCase { private $_albums; - + public function prepareData() { } - public function testInitData() + public function testInitData() { // Since the tests do a $this->objTable()->clear() before each method call // using the User model is not recommended for this test @@ -35,12 +41,12 @@ public function testInitData() $this->_albums = $albums; } - public function testAggregateValueMappingSupportsLeftJoins() + public function testAggregateValueMappingSupportsLeftJoins() { foreach ($this->_albums as $album) { $album->clearRelated(); } - + $q = new Doctrine_Query(); $q->select('a.name, COUNT(s.id) count')->from('Album a')->leftJoin('a.Song s')->groupby('a.id'); @@ -53,4 +59,4 @@ public function testAggregateValueMappingSupportsLeftJoins() $this->fail('count aggregate value should be available'); } } -} \ No newline at end of file +} diff --git a/tests/Ticket/438TestCase.php b/tests/Ticket/438TestCase.php index 71fb3b66f..88ad1be61 100644 --- a/tests/Ticket/438TestCase.php +++ b/tests/Ticket/438TestCase.php @@ -20,140 +20,149 @@ */ /** - * Doctrine_Ticket_438_TestCase + * Doctrine_Ticket_438_TestCase. * - * @package Doctrine * @author Tamcy <7am.online@gmail.com> * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_438_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } public function prepareTables() { - $this->tables = array('T438_Student', 'T438_Course', 'T438_StudentCourse'); - parent::prepareTables(); + $this->tables = array('T438_Student', 'T438_Course', 'T438_StudentCourse'); + parent::prepareTables(); } protected function newCourse($id, $name) { - $course = new T438_Course(); - $course->id = $id; - $course->name = $name; - $course->save(); - return $course; + $course = new T438_Course(); + $course->id = $id; + $course->name = $name; + $course->save(); + + return $course; } protected function newStudent($id, $name) { - $u = new T438_Student(); - $u->id = $id; - $u->name = $name; - $u->save(); - return $u; + $u = new T438_Student(); + $u->id = $id; + $u->name = $name; + $u->save(); + + return $u; } protected function newStudentCourse($student, $course) { - $sc = new T438_StudentCourse; - $sc->student_id = $student->id; - $sc->course_id = $course->id; - $sc->save(); - return $sc; + $sc = new T438_StudentCourse(); + $sc->student_id = $student->id; + $sc->course_id = $course->id; + $sc->save(); + + return $sc; } public function testTicket() { - $student1 = $this->newStudent('07090002', 'First Student'); - $course1 = $this->newCourse('MATH001', 'Maths'); - $course2 = $this->newCourse('ENG002', 'English Literature'); - - $this->newStudentCourse($student1, $course1); - $this->newStudentCourse($student1, $course2); - - - // 1. Fetch relationship on demand (multiple queries) - $q = new Doctrine_Query(); - $q->from('T438_StudentCourse sc') - ->where('sc.student_id = ? AND sc.course_id = ?',array('07090002', 'MATH001')); - - $record = $q->execute()->getFirst(); - $this->assertEqual($record->student_id, '07090002'); - $this->assertEqual($record->course_id, 'MATH001'); - - $this->assertEqual($record->get('Student')->id, '07090002'); - $this->assertEqual($record->get('Course')->id, 'MATH001'); - - // 2. Fetch relationship in single query - $q = new Doctrine_Query(); - $coll = $q->select('sc.*, s.*, c.*') - ->from('T438_StudentCourse sc, sc.Student s, sc.Course c') - ->where('sc.student_id = ? AND sc.course_id = ?',array('07090002', 'MATH001')) - ->execute(); - - $record = $coll->getFirst(); - $this->assertEqual($record->student_id, '07090002'); - $this->assertEqual($record->course_id, 'MATH001'); - - $this->assertEqual($record->get('Student')->id, '07090002'); - $this->assertEqual($record->get('Course')->id, 'MATH001'); + $student1 = $this->newStudent('07090002', 'First Student'); + $course1 = $this->newCourse('MATH001', 'Maths'); + $course2 = $this->newCourse('ENG002', 'English Literature'); + + $this->newStudentCourse($student1, $course1); + $this->newStudentCourse($student1, $course2); + + // 1. Fetch relationship on demand (multiple queries) + $q = new Doctrine_Query(); + $q->from('T438_StudentCourse sc') + ->where('sc.student_id = ? AND sc.course_id = ?', array('07090002', 'MATH001')) + ; + + $record = $q->execute()->getFirst(); + $this->assertEqual($record->student_id, '07090002'); + $this->assertEqual($record->course_id, 'MATH001'); + + $this->assertEqual($record->get('Student')->id, '07090002'); + $this->assertEqual($record->get('Course')->id, 'MATH001'); + + // 2. Fetch relationship in single query + $q = new Doctrine_Query(); + $coll = $q->select('sc.*, s.*, c.*') + ->from('T438_StudentCourse sc, sc.Student s, sc.Course c') + ->where('sc.student_id = ? AND sc.course_id = ?', array('07090002', 'MATH001')) + ->execute() + ; + + $record = $coll->getFirst(); + $this->assertEqual($record->student_id, '07090002'); + $this->assertEqual($record->course_id, 'MATH001'); + + $this->assertEqual($record->get('Student')->id, '07090002'); + $this->assertEqual($record->get('Course')->id, 'MATH001'); } } - class T438_Student extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('t438_student_record'); - - $this->hasColumn('s_id as id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('s_name as name', 'varchar', 50, array ()); - } - - public function setUp() - { - $this->hasMany('T438_Course as StudyCourses', array('refClass' => 'T438_StudentCourse', 'local' => 'sc_student_id', 'foreign' => 'sc_course_id')); - } -} + public function setTableDefinition() + { + $this->setTableName('t438_student_record'); + $this->hasColumn('s_id as id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('s_name as name', 'varchar', 50, array()); + } + + public function setUp() + { + $this->hasMany('T438_Course as StudyCourses', array('refClass' => 'T438_StudentCourse', 'local' => 'sc_student_id', 'foreign' => 'sc_course_id')); + } +} class T438_Course extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('t438_course'); - - $this->hasColumn('c_id as id', 'varchar', 20, array ( 'primary' => true,)); - $this->hasColumn('c_name as name', 'varchar', 50, array ()); - } - - public function setUp() - { - $this->hasMany('T438_Student as Students', array('refClass' => 'T438_StudentCourse', 'local' => 'sc_course_id', 'foreign' => 'sc_student_id')); - } + public function setTableDefinition() + { + $this->setTableName('t438_course'); + + $this->hasColumn('c_id as id', 'varchar', 20, array('primary' => true)); + $this->hasColumn('c_name as name', 'varchar', 50, array()); + } + + public function setUp() + { + $this->hasMany('T438_Student as Students', array('refClass' => 'T438_StudentCourse', 'local' => 'sc_course_id', 'foreign' => 'sc_student_id')); + } } class T438_StudentCourse extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('t438_student_course'); - - $this->hasColumn('sc_student_id as student_id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('sc_course_id as course_id', 'varchar', 20, array ( 'primary' => true,)); - $this->hasColumn('sc_remark as remark', 'varchar', 500, array ()); - } - - public function setUp() - { - $this->hasOne('T438_Student as Student', array('local' => 'sc_student_id', 'foreign' => 's_id')); - $this->hasOne('T438_Course as Course', array('local' => 'sc_course_id', 'foreign' => 'c_id')); - } + public function setTableDefinition() + { + $this->setTableName('t438_student_course'); + + $this->hasColumn('sc_student_id as student_id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('sc_course_id as course_id', 'varchar', 20, array('primary' => true)); + $this->hasColumn('sc_remark as remark', 'varchar', 500, array()); + } + + public function setUp() + { + $this->hasOne('T438_Student as Student', array('local' => 'sc_student_id', 'foreign' => 's_id')); + $this->hasOne('T438_Course as Course', array('local' => 'sc_course_id', 'foreign' => 'c_id')); + } } diff --git a/tests/Ticket/480TestCase.php b/tests/Ticket/480TestCase.php index 9059a8e7f..08b19611d 100644 --- a/tests/Ticket/480TestCase.php +++ b/tests/Ticket/480TestCase.php @@ -20,46 +20,49 @@ */ /** - * Doctrine_Ticket_480_TestCase + * Doctrine_Ticket_480_TestCase. * - * @package Doctrine * @author Miloslav Kmet * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ - class stComment extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('st_comment'); - $this->hasColumn('title', 'string', 100, array()); - $this->hasColumn('body', 'string', 1000, array()); - - } + public function setTableDefinition() + { + $this->setTableName('st_comment'); + $this->hasColumn('title', 'string', 100, array()); + $this->hasColumn('body', 'string', 1000, array()); + } } -class Doctrine_Ticket_480_TestCase extends Doctrine_UnitTestCase +/** + * @internal + * + * @coversNothing + */ +class Doctrine_Ticket_480_TestCase extends Doctrine_UnitTestCase { - - public function testInit() - { - $this->dbh = new Doctrine_Adapter_Mock('oracle'); - $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh); - } - - public function testTicket() - { - $this->conn->export->exportClasses(array('stComment')); - $queries = $this->dbh->getAll(); - - // (2nd|1st except transaction init.) executed query must be CREATE TABLE or CREATE SEQUENCE, not CREATE TRIGGER - // Trigger can be created after both CREATE TABLE and CREATE SEQUENCE - $this->assertFalse(preg_match('~^CREATE TRIGGER.*~', $queries[1])); - $this->assertFalse(preg_match('~^CREATE TRIGGER.*~', $queries[2])); + public function testInit() + { + $this->dbh = new Doctrine_Adapter_Mock('oracle'); + $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh); + } - } -} \ No newline at end of file + public function testTicket() + { + $this->conn->export->exportClasses(array('stComment')); + $queries = $this->dbh->getAll(); + + // (2nd|1st except transaction init.) executed query must be CREATE TABLE or CREATE SEQUENCE, not CREATE TRIGGER + // Trigger can be created after both CREATE TABLE and CREATE SEQUENCE + $this->assertFalse(preg_match('~^CREATE TRIGGER.*~', $queries[1])); + $this->assertFalse(preg_match('~^CREATE TRIGGER.*~', $queries[2])); + } +} diff --git a/tests/Ticket/486TestCase.php b/tests/Ticket/486TestCase.php index 5ff54a35e..5c541fd0c 100755 --- a/tests/Ticket/486TestCase.php +++ b/tests/Ticket/486TestCase.php @@ -20,24 +20,30 @@ */ /** - * Doctrine_Ticket_486_TestCase + * Doctrine_Ticket_486_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_486_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_486_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { + public function prepareTables() + { $this->tables = array('Country', 'State', 'Resort'); parent::prepareTables(); } - public function prepareData() { // Countries @@ -72,7 +78,6 @@ public function prepareData() $r7 = $this->createResort($s8, 'Hilton'); } - public function testLimitSubqueryQuoteIdentifier() { // Change the quote identifier @@ -83,7 +88,8 @@ public function testLimitSubqueryQuoteIdentifier() ->select('c.id') ->from('Country c, c.State.Resort r') ->where('r.id = 3') - ->limit(1); + ->limit(1) + ; $this->assertEqual('SELECT "c"."id" AS "c__id" FROM "country" "c" LEFT JOIN "state" "s" ON "c"."id" = "s"."country_id" LEFT JOIN "resort" "r" ON "s"."id" = "r"."state_id" WHERE "c"."id" IN (SELECT DISTINCT "c2"."id" FROM "country" "c2" LEFT JOIN "state" "s2" ON "c2"."id" = "s2"."country_id" LEFT JOIN "resort" "r2" ON "s2"."id" = "r2"."state_id" WHERE "r2"."id" = 3 LIMIT 1) AND ("r"."id" = 3)', $q->getSqlQuery()); @@ -91,7 +97,6 @@ public function testLimitSubqueryQuoteIdentifier() $this->getConnection()->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, $curQuoteIdentifier); } - public function createCountry($name) { $tmp = new Country(); @@ -101,7 +106,6 @@ public function createCountry($name) return $tmp; } - public function createState($country, $name) { $tmp = new State(); @@ -112,7 +116,6 @@ public function createState($country, $name) return $tmp; } - public function createResort($state, $name) { $tmp = new Resort(); @@ -124,7 +127,6 @@ public function createResort($state, $name) } } - class Country extends Doctrine_Record { public function setTableDefinition() @@ -132,14 +134,12 @@ public function setTableDefinition() $this->hasColumn('name', 'string', 255); } - public function setUp() { $this->hasMany('State', array('local' => 'id', 'foreign' => 'country_id')); } } - class State extends Doctrine_Record { public function setTableDefinition() @@ -148,7 +148,6 @@ public function setTableDefinition() $this->hasColumn('name', 'string', 255); } - public function setUp() { $this->hasOne('Country', array('local' => 'country_id', 'foreign' => 'id')); @@ -156,7 +155,6 @@ public function setUp() } } - class Resort extends Doctrine_Record { public function setTableDefinition() @@ -165,9 +163,8 @@ public function setTableDefinition() $this->hasColumn('name', 'string', 255); } - public function setUp() { $this->hasOne('State', array('local' => 'state_id', 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/565TestCase.php b/tests/Ticket/565TestCase.php index 59da2e972..c6f3c0b76 100644 --- a/tests/Ticket/565TestCase.php +++ b/tests/Ticket/565TestCase.php @@ -20,16 +20,22 @@ */ /** - * Doctrine_Ticket_565_TestCase + * Doctrine_Ticket_565_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_565_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_565_TestCase extends Doctrine_UnitTestCase { } diff --git a/tests/Ticket/574TestCase.php b/tests/Ticket/574TestCase.php index 22862171d..bb88351ac 100644 --- a/tests/Ticket/574TestCase.php +++ b/tests/Ticket/574TestCase.php @@ -20,66 +20,66 @@ */ /** - * Doctrine_Ticket_574_TestCase + * Doctrine_Ticket_574_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_574_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_574_TestCase extends Doctrine_UnitTestCase { - /** - * prepareData - */ + /** + * prepareData. + */ public function prepareData() { - for($i=0; $i < 10; $i++) - { - $oAuthor = new Author; - $oAuthor->book_id = $i; - $oAuthor->name = "Author $i"; - $oAuthor->save(); - } + for ($i = 0; $i < 10; ++$i) { + $oAuthor = new Author(); + $oAuthor->book_id = $i; + $oAuthor->name = "Author {$i}"; + $oAuthor->save(); + } } - + /** - * prepareTables + * prepareTables. */ - public function prepareTables() { - $this->tables = array(); - $this->tables[] = 'Author'; - $this->tables[] = 'Book'; - - parent :: prepareTables(); + $this->tables = array(); + $this->tables[] = 'Author'; + $this->tables[] = 'Book'; + + parent::prepareTables(); } - - + /** - * Test the existence expected indexes + * Test the existence expected indexes. */ - public function testTicket() { $q = new Doctrine_Query(); // simple query with 1 column selected $cAuthors = $q->select('book_id')->from('Author')->groupBy('book_id')->where('book_id = 2')->execute(); - + // simple query, with 1 join and all columns selected $cAuthors = $q->from('Author, Author.Book')->execute(); - - foreach($cAuthors as $oAuthor) - { - if ( ! $oAuthor->name) - { - $this->fail('Querying the same table multiple times triggers hydration/caching(?) bug'); - } - } + + foreach ($cAuthors as $oAuthor) { + if (!$oAuthor->name) { + $this->fail('Querying the same table multiple times triggers hydration/caching(?) bug'); + } + } } -} \ No newline at end of file +} diff --git a/tests/Ticket/576TestCase.php b/tests/Ticket/576TestCase.php index e10d6f4d0..ac75599b4 100644 --- a/tests/Ticket/576TestCase.php +++ b/tests/Ticket/576TestCase.php @@ -1,17 +1,22 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_576_TestCase extends Doctrine_UnitTestCase { public function prepareTables() @@ -20,7 +25,9 @@ public function prepareTables() parent::prepareTables(); } - public function prepareData() { } + public function prepareData() + { + } public function testInit() { @@ -43,7 +50,8 @@ public function testBug() $data = Doctrine_Query::create() ->select('name') ->from('Entity') - ->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY); + ->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY) + ; $user->hydrate($data); $this->assertEqual($user->name, 'myname'); diff --git a/tests/Ticket/583TestCase.php b/tests/Ticket/583TestCase.php index 13851fcb1..e4afed7f4 100644 --- a/tests/Ticket/583TestCase.php +++ b/tests/Ticket/583TestCase.php @@ -1,17 +1,22 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_583_TestCase extends Doctrine_UnitTestCase { public function prepareTables() @@ -20,7 +25,9 @@ public function prepareTables() parent::prepareTables(); } - public function prepareData() { } + public function prepareData() + { + } public function testBug() { diff --git a/tests/Ticket/585TestCase.php b/tests/Ticket/585TestCase.php index 9c2ed8f5c..4cbf353e8 100644 --- a/tests/Ticket/585TestCase.php +++ b/tests/Ticket/585TestCase.php @@ -19,6 +19,11 @@ * . */ +/** + * @internal + * + * @coversNothing + */ class Doctrine_Ticket_585_TestCase extends Doctrine_UnitTestCase { private function doTestWithAllColumnsAliased($hydrateType, $expectedKeys) @@ -44,7 +49,7 @@ private function doTestWithAllColumnsAliased($hydrateType, $expectedKeys) } } - public function test_hydrateScalar_withAllColumnsAliased_thenResultsHasAllRecords() + public function testHydrateScalarWithAllColumnsAliasedThenResultsHasAllRecords() { $hydrateType = Doctrine_Core::HYDRATE_SCALAR; $expectedKeys = array('u_aliasId', 'u_aliasName'); @@ -52,7 +57,7 @@ public function test_hydrateScalar_withAllColumnsAliased_thenResultsHasAllRecord $this->doTestWithAllColumnsAliased($hydrateType, $expectedKeys); } - public function test_hydrateArrayShallow_withAllColumnsAliased_thenResultsHasAllRecords() + public function testHydrateArrayShallowWithAllColumnsAliasedThenResultsHasAllRecords() { $hydrateType = Doctrine_Core::HYDRATE_ARRAY_SHALLOW; $expectedKeys = array('aliasId', 'aliasName'); @@ -60,7 +65,7 @@ public function test_hydrateArrayShallow_withAllColumnsAliased_thenResultsHasAll $this->doTestWithAllColumnsAliased($hydrateType, $expectedKeys); } - public function test_hydrateArray_withAllColumnsAliased_thenResultsHasAllRecords() + public function testHydrateArrayWithAllColumnsAliasedThenResultsHasAllRecords() { $hydrateType = Doctrine_Core::HYDRATE_ARRAY; $expectedKeys = array('aliasId', 'aliasName'); diff --git a/tests/Ticket/587TestCase.php b/tests/Ticket/587TestCase.php index 4e2250eff..d6c4c02e7 100644 --- a/tests/Ticket/587TestCase.php +++ b/tests/Ticket/587TestCase.php @@ -1,17 +1,22 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_587_TestCase extends Doctrine_UnitTestCase { public function prepareTables() @@ -19,6 +24,7 @@ public function prepareTables() $this->tables = array_merge($this->tables, array('BookmarkUser', 'Bookmark', 'Page')); parent::prepareTables(); } + public function prepareData() { parent::prepareData(); diff --git a/tests/Ticket/626BTestCase.php b/tests/Ticket/626BTestCase.php index 6f550a493..85b849fd1 100644 --- a/tests/Ticket/626BTestCase.php +++ b/tests/Ticket/626BTestCase.php @@ -1,159 +1,166 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_626B_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } public function prepareTables() { - $this->tables = array('T626_Group', 'T626B_Student', 'T626_Course', 'T626B_StudentCourse'); - parent::prepareTables(); + $this->tables = array('T626_Group', 'T626B_Student', 'T626_Course', 'T626B_StudentCourse'); + parent::prepareTables(); } protected function newCourse($id, $name) { - $course = new T626_Course(); - $course->id = $id; - $course->name = $name; - $course->save(); - return $course; + $course = new T626_Course(); + $course->id = $id; + $course->name = $name; + $course->save(); + + return $course; } protected function newGroup($id, $name) { - $group = new T626_Group(); - $group->id = $id; - $group->name = $name; - $group->save(); - return $group; + $group = new T626_Group(); + $group->id = $id; + $group->name = $name; + $group->save(); + + return $group; } protected function newStudent($id, $name, $group) { - $u = new T626B_Student(); - $u->id = $id; - $u->name = $name; - $u->group_id = $group->id; - $u->save(); - return $u; + $u = new T626B_Student(); + $u->id = $id; + $u->name = $name; + $u->group_id = $group->id; + $u->save(); + + return $u; } protected function newStudentCourse($student, $course) { - $sc = new T626B_StudentCourse; - $sc->student_id = $student->id; - $sc->course_id = $course->id; - $sc->save(); - return $sc; + $sc = new T626B_StudentCourse(); + $sc->student_id = $student->id; + $sc->course_id = $course->id; + $sc->save(); + + return $sc; } public function testTicket() { - $group1 = $this->newGroup('1', 'Group 1'); - $student1 = $this->newStudent('07090002', 'First Student', $group1); - $course1 = $this->newCourse('MATH001', 'Maths'); - $course2 = $this->newCourse('ENG002', 'English Literature'); - - $this->newStudentCourse($student1, $course1); - $this->newStudentCourse($student1, $course2); - - try { - $group = $student1->get('Group'); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->__toString()); - } - - try { - $courses = $student1->get('StudyCourses'); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->__toString()); - } - + $group1 = $this->newGroup('1', 'Group 1'); + $student1 = $this->newStudent('07090002', 'First Student', $group1); + $course1 = $this->newCourse('MATH001', 'Maths'); + $course2 = $this->newCourse('ENG002', 'English Literature'); + + $this->newStudentCourse($student1, $course1); + $this->newStudentCourse($student1, $course2); + + try { + $group = $student1->get('Group'); + $this->pass(); + } catch (Exception $e) { + $this->fail($e->__toString()); + } + + try { + $courses = $student1->get('StudyCourses'); + $this->pass(); + } catch (Exception $e) { + $this->fail($e->__toString()); + } } } - class T626B_Student extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T626B_Student_record'); - - $this->hasColumn('s_id as id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('s_g_id as group_id', 'varchar', 30, array ('notnull'=>true)); - $this->hasColumn('s_name as name', 'varchar', 50, array ()); - } - - public function setUp() - { - $this->hasMany('T626_Course as StudyCourses', array('refClass' => 'T626B_StudentCourse', 'local' => 'sc_student_id', 'foreign' => 'sc_course_id')); - $this->hasOne('T626_Group as Group', array('local' => 's_g_id', 'foreign' => 'g_id')); - } + public function setTableDefinition() + { + $this->setTableName('T626B_Student_record'); + + $this->hasColumn('s_id as id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('s_g_id as group_id', 'varchar', 30, array('notnull' => true)); + $this->hasColumn('s_name as name', 'varchar', 50, array()); + } + + public function setUp() + { + $this->hasMany('T626_Course as StudyCourses', array('refClass' => 'T626B_StudentCourse', 'local' => 'sc_student_id', 'foreign' => 'sc_course_id')); + $this->hasOne('T626_Group as Group', array('local' => 's_g_id', 'foreign' => 'g_id')); + } } class T626_Group extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T626B_Student_group'); - - $this->hasColumn('g_id as id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('g_name as name', 'varchar', 50, array ()); - } - - public function setUp() - { - $this->hasMany('T626B_Student as Students', - array('local' => 'g_id', 'foreign' => 's_id')); - } -} + public function setTableDefinition() + { + $this->setTableName('T626B_Student_group'); + $this->hasColumn('g_id as id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('g_name as name', 'varchar', 50, array()); + } + + public function setUp() + { + $this->hasMany('T626B_Student as Students', + array('local' => 'g_id', 'foreign' => 's_id')); + } +} class T626_Course extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T626_course'); - - $this->hasColumn('c_id as id', 'varchar', 20, array ( 'primary' => true,)); - $this->hasColumn('c_name as name', 'varchar', 50, array ()); - } - - public function setUp() - { - $this->hasMany('T626B_Student as Students', array('refClass' => 'T626B_StudentCourse', 'local' => 'sc_course_id', 'foreign' => 'sc_student_id')); - } + public function setTableDefinition() + { + $this->setTableName('T626_course'); + + $this->hasColumn('c_id as id', 'varchar', 20, array('primary' => true)); + $this->hasColumn('c_name as name', 'varchar', 50, array()); + } + + public function setUp() + { + $this->hasMany('T626B_Student as Students', array('refClass' => 'T626B_StudentCourse', 'local' => 'sc_course_id', 'foreign' => 'sc_student_id')); + } } class T626B_StudentCourse extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T626B_Student_course'); - - $this->hasColumn('sc_student_id as student_id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('sc_course_id as course_id', 'varchar', 20, array ( 'primary' => true,)); - $this->hasColumn('sc_remark as remark', 'varchar', 500, array ()); - } - - public function setUp() - { - $this->hasOne('T626B_Student as Student', array('local' => 'sc_student_id', 'foreign' => 's_id')); - $this->hasOne('T626_Course as Course', array('local' => 'sc_course_id', 'foreign' => 'c_id')); - } + public function setTableDefinition() + { + $this->setTableName('T626B_Student_course'); + + $this->hasColumn('sc_student_id as student_id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('sc_course_id as course_id', 'varchar', 20, array('primary' => true)); + $this->hasColumn('sc_remark as remark', 'varchar', 500, array()); + } + + public function setUp() + { + $this->hasOne('T626B_Student as Student', array('local' => 'sc_student_id', 'foreign' => 's_id')); + $this->hasOne('T626_Course as Course', array('local' => 'sc_course_id', 'foreign' => 'c_id')); + } } diff --git a/tests/Ticket/626CTestCase.php b/tests/Ticket/626CTestCase.php index 117a785d3..7445fcce1 100644 --- a/tests/Ticket/626CTestCase.php +++ b/tests/Ticket/626CTestCase.php @@ -1,85 +1,93 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_626C_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } public function prepareTables() { - $this->tables = array('T626C_Student1', 'T626C_Student2'); - parent::prepareTables(); + $this->tables = array('T626C_Student1', 'T626C_Student2'); + parent::prepareTables(); } protected function newStudent($cls, $id, $name) { - $u = new $cls; - $u->id = $id; - $u->name = $name; - $u->save(); - return $u; + $u = new $cls(); + $u->id = $id; + $u->name = $name; + $u->save(); + + return $u; } public function testFieldNames() { - $student1 = $this->newStudent('T626C_Student1', '07090002', 'First Student'); + $student1 = $this->newStudent('T626C_Student1', '07090002', 'First Student'); - try { - $students = Doctrine_Query::create() - ->from('T626C_Student1 s INDEXBY s.id') - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->__toString()); - } + try { + $students = Doctrine_Query::create() + ->from('T626C_Student1 s INDEXBY s.id') + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY) + ; + $this->pass(); + } catch (Exception $e) { + $this->fail($e->__toString()); + } } public function testColNames() { - $student1 = $this->newStudent('T626C_Student2', '07090002', 'First Student'); + $student1 = $this->newStudent('T626C_Student2', '07090002', 'First Student'); - try { - $students = Doctrine_Query::create() - ->from('T626C_Student2 s INDEXBY s.id') - ->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->__toString()); - } + try { + $students = Doctrine_Query::create() + ->from('T626C_Student2 s INDEXBY s.id') + ->execute(array(), Doctrine_Core::HYDRATE_ARRAY) + ; + $this->pass(); + } catch (Exception $e) { + $this->fail($e->__toString()); + } } } - class T626C_Student1 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T626C_Student_record_1'); + public function setTableDefinition() + { + $this->setTableName('T626C_Student_record_1'); - $this->hasColumn('s_id as id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('s_name as name', 'varchar', 50, array ()); - } + $this->hasColumn('s_id as id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('s_name as name', 'varchar', 50, array()); + } } class T626C_Student2 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T626C_Student_record_2'); + public function setTableDefinition() + { + $this->setTableName('T626C_Student_record_2'); - $this->hasColumn('id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('name', 'varchar', 50, array ()); - } -} \ No newline at end of file + $this->hasColumn('id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('name', 'varchar', 50, array()); + } +} diff --git a/tests/Ticket/626DTestCase.php b/tests/Ticket/626DTestCase.php index ab157d00f..7a3da77c3 100644 --- a/tests/Ticket/626DTestCase.php +++ b/tests/Ticket/626DTestCase.php @@ -1,58 +1,64 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_626D_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } public function prepareTables() { - $this->tables = array('T626D_Student1'); - parent::prepareTables(); + $this->tables = array('T626D_Student1'); + parent::prepareTables(); } protected function newStudent($cls, $id, $name) { - $u = new $cls; - $u->id = $id; - $u->name = $name; - $u->save(); - return $u; + $u = new $cls(); + $u->id = $id; + $u->name = $name; + $u->save(); + + return $u; } public function testFieldNames() { - $student1 = $this->newStudent('T626D_Student1', '07090002', 'First Student'); - - try { - $student = Doctrine_Core::getTable('T626D_Student1')->find('07090002'); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->__toString()); - } + $student1 = $this->newStudent('T626D_Student1', '07090002', 'First Student'); + + try { + $student = Doctrine_Core::getTable('T626D_Student1')->find('07090002'); + $this->pass(); + } catch (Exception $e) { + $this->fail($e->__toString()); + } } } - class T626D_Student1 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T626D_Student_record_1'); + public function setTableDefinition() + { + $this->setTableName('T626D_Student_record_1'); - $this->hasColumn('s_id as id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('s_name as name', 'varchar', 50, array ()); - } + $this->hasColumn('s_id as id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('s_name as name', 'varchar', 50, array()); + } } diff --git a/tests/Ticket/632TestCase.php b/tests/Ticket/632TestCase.php index ba435f18a..c51b804bb 100644 --- a/tests/Ticket/632TestCase.php +++ b/tests/Ticket/632TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_632_TestCase + * Doctrine_Ticket_632_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_632_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_632_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -57,7 +63,8 @@ public function testTest() ->from('Ticket_632_User u, u.Groups g') ->where('u.username = ?', 'jwage') ->limit(1) - ->fetchOne(); + ->fetchOne() + ; $this->assertEqual($user->Groups->count(), 3); unset($user->Groups[2]); $this->assertEqual($user->Groups->count(), 2); @@ -79,9 +86,9 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_632_Group as Groups', array('local' => 'user_id', - 'foreign' => 'group_id', - 'refClass' => 'Ticket_632_UserGroup')); + $this->hasMany('Ticket_632_Group as Groups', array('local' => 'user_id', + 'foreign' => 'group_id', + 'refClass' => 'Ticket_632_UserGroup')); } } @@ -94,9 +101,9 @@ public function setTableDefinition() public function setUp() { - $this->hasMany('Ticket_632_User as Users', array('local' => 'group_id', - 'foreign' => 'user_id', - 'refClass' => 'Ticket_632_UserGroup')); + $this->hasMany('Ticket_632_User as Users', array('local' => 'group_id', + 'foreign' => 'user_id', + 'refClass' => 'Ticket_632_UserGroup')); } } @@ -110,10 +117,10 @@ public function setTableDefinition() public function setUp() { - $this->hasOne('Ticket_632_User as User', array('local' => 'user_id', - 'foreign' => 'id')); + $this->hasOne('Ticket_632_User as User', array('local' => 'user_id', + 'foreign' => 'id')); $this->hasOne('Ticket_632_Group as Group', array('local' => 'group_id', - 'foreign' => 'id')); + 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/638TestCase.php b/tests/Ticket/638TestCase.php index 49f8684e4..9dfbb49e3 100644 --- a/tests/Ticket/638TestCase.php +++ b/tests/Ticket/638TestCase.php @@ -1,161 +1,156 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_638_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } public function prepareTables() { - $this->tables = array('T638_Student', 'T638_Course', 'T638_StudentCourse'); - parent::prepareTables(); + $this->tables = array('T638_Student', 'T638_Course', 'T638_StudentCourse'); + parent::prepareTables(); } protected function newCourse($id, $name) { - $course = new T638_Course(); - $course->id = $id; - $course->name = $name; - $course->save(); - return $course; + $course = new T638_Course(); + $course->id = $id; + $course->name = $name; + $course->save(); + + return $course; } protected function newStudent($id, $name) { - $u = new T638_Student(); - $u->id = $id; - $u->name = $name; - $u->group_id = 1; - $u->save(); - return $u; + $u = new T638_Student(); + $u->id = $id; + $u->name = $name; + $u->group_id = 1; + $u->save(); + + return $u; } protected function newStudentCourse($student, $course) { - $sc = new T638_StudentCourse; - $sc->student_id = $student->id; - $sc->course_id = $course->id; - $sc->save(); - return $sc; + $sc = new T638_StudentCourse(); + $sc->student_id = $student->id; + $sc->course_id = $course->id; + $sc->save(); + + return $sc; } public function testTicket() { - $student1 = $this->newStudent('07090002', 'First Student'); - $course1 = $this->newCourse('MATH001', 'Maths'); - $course2 = $this->newCourse('ENG002', 'English Literature'); - - $sc = new T638_StudentCourse; - $sc->set('Student', $student1); - $sc->set('Course', $course1); - - if ($student1->get('id') instanceof T638_StudentCourse) - { - $this->fail('Student Id incorrectly replaced!'); - } - else - { - $this->pass(); - } - - if ($student1->get('id') != '07090002') - { - $this->fail('Student Id is not correct after assignment!'); - } - else - { - $this->pass(); - } - - if ($course1->get('id') instanceof T638_StudentCourse) - { - $this->fail('Course Id incorrectly replaced!'); - } - else - { - $this->pass(); - } - - if ($course1->get('id') != 'MATH001') - { - $this->fail('Course Id is not correct after assignment!'); - } - else - { - $this->pass(); - } - - $this->assertEqual($sc->get('student_id'), '07090002'); - $this->assertEqual($sc->get('course_id'), 'MATH001'); - $this->assertIdentical($sc->get('Student'), $student1); - $this->assertIdentical($sc->get('Course'), $course1); + $student1 = $this->newStudent('07090002', 'First Student'); + $course1 = $this->newCourse('MATH001', 'Maths'); + $course2 = $this->newCourse('ENG002', 'English Literature'); + + $sc = new T638_StudentCourse(); + $sc->set('Student', $student1); + $sc->set('Course', $course1); + + if ($student1->get('id') instanceof T638_StudentCourse) { + $this->fail('Student Id incorrectly replaced!'); + } else { + $this->pass(); + } + + if ('07090002' != $student1->get('id')) { + $this->fail('Student Id is not correct after assignment!'); + } else { + $this->pass(); + } + + if ($course1->get('id') instanceof T638_StudentCourse) { + $this->fail('Course Id incorrectly replaced!'); + } else { + $this->pass(); + } + + if ('MATH001' != $course1->get('id')) { + $this->fail('Course Id is not correct after assignment!'); + } else { + $this->pass(); + } + + $this->assertEqual($sc->get('student_id'), '07090002'); + $this->assertEqual($sc->get('course_id'), 'MATH001'); + $this->assertIdentical($sc->get('Student'), $student1); + $this->assertIdentical($sc->get('Course'), $course1); } } - class T638_Student extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T638_student'); - - $this->hasColumn('s_id as id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('s_g_id as group_id', 'varchar', 30, array ('notnull'=>true)); - $this->hasColumn('s_name as name', 'varchar', 50, array ('notnull'=>true)); - } - - public function setUp() - { - } + public function setTableDefinition() + { + $this->setTableName('T638_student'); + + $this->hasColumn('s_id as id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('s_g_id as group_id', 'varchar', 30, array('notnull' => true)); + $this->hasColumn('s_name as name', 'varchar', 50, array('notnull' => true)); + } + + public function setUp() + { + } } class T638_Course extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T638_course'); - - $this->hasColumn('c_id as id', 'varchar', 20, array ( 'primary' => true,)); - $this->hasColumn('c_name as name', 'varchar', 50, array ('notnull'=>true)); - } - - public function setUp() - { - } - - public function set($fieldName, $value, $load = true) - { - parent::set($fieldName, $value, $load); - } + public function setTableDefinition() + { + $this->setTableName('T638_course'); + + $this->hasColumn('c_id as id', 'varchar', 20, array('primary' => true)); + $this->hasColumn('c_name as name', 'varchar', 50, array('notnull' => true)); + } + + public function setUp() + { + } + + public function set($fieldName, $value, $load = true) + { + parent::set($fieldName, $value, $load); + } } class T638_StudentCourse extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T638_Student_course'); - - $this->hasColumn('sc_student_id as student_id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('sc_course_id as course_id', 'varchar', 20, array ( 'primary' => true,)); - $this->hasColumn('sc_remark as remark', 'varchar', 500, array ('notnull'=>true)); - } - - public function setUp() - { - $this->hasOne('T638_Student as Student', array('local' => 'sc_student_id', 'foreign' => 's_id')); - $this->hasOne('T638_Course as Course', array('local' => 'sc_course_id', 'foreign' => 'c_id')); - } -} + public function setTableDefinition() + { + $this->setTableName('T638_Student_course'); + + $this->hasColumn('sc_student_id as student_id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('sc_course_id as course_id', 'varchar', 20, array('primary' => true)); + $this->hasColumn('sc_remark as remark', 'varchar', 500, array('notnull' => true)); + } + public function setUp() + { + $this->hasOne('T638_Student as Student', array('local' => 'sc_student_id', 'foreign' => 's_id')); + $this->hasOne('T638_Course as Course', array('local' => 'sc_course_id', 'foreign' => 'c_id')); + } +} diff --git a/tests/Ticket/642TestCase.php b/tests/Ticket/642TestCase.php index 10e0dc4df..a729ba431 100644 --- a/tests/Ticket/642TestCase.php +++ b/tests/Ticket/642TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_642_TestCase + * Doctrine_Ticket_642_TestCase. * - * @package Doctrine * @author Guilherme Blanco * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_642_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_642_TestCase extends Doctrine_UnitTestCase { public function testInit() { @@ -38,7 +44,6 @@ public function testInit() $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh); } - public function testTest() { $this->conn->export->exportClasses(array('stDummyObj')); @@ -46,20 +51,17 @@ public function testTest() // Default was not being defined, even if notnull was set $this->assertEqual("CREATE TABLE st_dummy_obj (id BIGINT AUTO_INCREMENT, startdate DATETIME DEFAULT '0000-00-00 00:00:00' NOT NULL, PRIMARY KEY(id)) ENGINE = INNODB", $queries[1]); - } + } } - class stDummyObj extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('st_dummy_obj'); $this->hasColumn('startDate', 'timestamp', null, array( - 'notnull' => true, - 'default' => '0000-00-00 00:00:00' + 'notnull' => true, + 'default' => '0000-00-00 00:00:00', )); } } - -?> \ No newline at end of file diff --git a/tests/Ticket/668TestCase.php b/tests/Ticket/668TestCase.php index 6c60bdbeb..683897163 100755 --- a/tests/Ticket/668TestCase.php +++ b/tests/Ticket/668TestCase.php @@ -20,40 +20,47 @@ */ /** - * Doctrine_Ticket_668_TestCase + * Doctrine_Ticket_668_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_668_TestCase extends Doctrine_UnitTestCase { - - public function prepareTables() { - $this->tables = array(); - $this->tables[] = 'T668_User'; - parent::prepareTables(); +class Doctrine_Ticket_668_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { + $this->tables = array(); + $this->tables[] = 'T668_User'; + parent::prepareTables(); } - - public function prepareData() {} - + public function prepareData() + { + } public function testTicket() { $query = Doctrine_Query::create() - ->select('u.id') - ->from('T668_User u') - ->where("u.name LIKE '%foo OR bar%'"); + ->select('u.id') + ->from('T668_User u') + ->where("u.name LIKE '%foo OR bar%'") + ; $this->assertEqual("SELECT u.id FROM T668_User u WHERE u.name LIKE '%foo OR bar%'", $query->getDql()); $this->assertEqual($query->getSqlQuery(), "SELECT t.id AS t__id FROM t668_user t WHERE (t.name LIKE '%foo OR bar%')"); } } - class T668_User extends Doctrine_Record { public function setTableDefinition() @@ -62,4 +69,4 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); $this->hasColumn('name', 'string', 100); } -} \ No newline at end of file +} diff --git a/tests/Ticket/673TestCase.php b/tests/Ticket/673TestCase.php index 452a67654..63e41b371 100644 --- a/tests/Ticket/673TestCase.php +++ b/tests/Ticket/673TestCase.php @@ -1,71 +1,78 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_673_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { } + public function prepareData() + { + } public function prepareTables() { - $this->tables = array('T673_Student'); - parent::prepareTables(); + $this->tables = array('T673_Student'); + parent::prepareTables(); } public function testTicket() { - $q = Doctrine_Query::create() - ->update('T673_Student s') - ->set('s.foo', 's.foo + 1') - ->where('s.id = 2'); - - $this->assertTrue(preg_match_all('/(s_foo)/', $q->getSqlQuery(), $m) === 2); - $this->assertTrue(preg_match_all('/(s_id)/', $q->getSqlQuery(), $m) === 1); - - try { - $q->execute(); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->__toString()); - } + $q = Doctrine_Query::create() + ->update('T673_Student s') + ->set('s.foo', 's.foo + 1') + ->where('s.id = 2') + ; + + $this->assertTrue(2 === preg_match_all('/(s_foo)/', $q->getSqlQuery(), $m)); + $this->assertTrue(1 === preg_match_all('/(s_id)/', $q->getSqlQuery(), $m)); + + try { + $q->execute(); + $this->pass(); + } catch (Exception $e) { + $this->fail($e->__toString()); + } + + $q = Doctrine_Query::create() + ->delete() + ->from('T673_Student s') + ->where('s.name = ? AND s.foo < ?', 'foo', 3) + ; - $q = Doctrine_Query::create() - ->delete() - ->from('T673_Student s') - ->where('s.name = ? AND s.foo < ?', 'foo', 3); - - $this->assertTrue(preg_match_all('/(s_name)/', $q->getSqlQuery(), $m) === 1); - $this->assertTrue(preg_match_all('/(s_foo)/', $q->getSqlQuery(), $m) === 1); + $this->assertTrue(1 === preg_match_all('/(s_name)/', $q->getSqlQuery(), $m)); + $this->assertTrue(1 === preg_match_all('/(s_foo)/', $q->getSqlQuery(), $m)); - try { - $q->execute(); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->__toString()); - } + try { + $q->execute(); + $this->pass(); + } catch (Exception $e) { + $this->fail($e->__toString()); + } } } - class T673_Student extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T673_Student_record'); + public function setTableDefinition() + { + $this->setTableName('T673_Student_record'); - $this->hasColumn('s_id as id', 'varchar', 30, array ( 'primary' => true,)); - $this->hasColumn('s_foo as foo', 'integer', 4, array ('notnull'=>true)); - $this->hasColumn('s_name as name', 'varchar', 50, array ()); - } + $this->hasColumn('s_id as id', 'varchar', 30, array('primary' => true)); + $this->hasColumn('s_foo as foo', 'integer', 4, array('notnull' => true)); + $this->hasColumn('s_name as name', 'varchar', 50, array()); + } } diff --git a/tests/Ticket/697TestCase.php b/tests/Ticket/697TestCase.php index 2c9fdcd9c..5d43fde12 100644 --- a/tests/Ticket/697TestCase.php +++ b/tests/Ticket/697TestCase.php @@ -1,19 +1,25 @@ save(); $this->assertEqual(1, $p->id); $u = new T697_User(); - $u['name']='Fernandes'; - $u['password']='Doctrine RULES'; + $u['name'] = 'Fernandes'; + $u['password'] = 'Doctrine RULES'; $u->save(); $this->assertEqual(2, $u->id); } @@ -44,8 +50,9 @@ public function setTableDefinition() } } -//Class table inheritance -class T697_User extends T697_Person { +// Class table inheritance +class T697_User extends T697_Person +{ public function setTableDefinition() { $this->hasColumn('password', 'string', 30); diff --git a/tests/Ticket/736TestCase.php b/tests/Ticket/736TestCase.php index 1b802b9a5..114a9cec7 100644 --- a/tests/Ticket/736TestCase.php +++ b/tests/Ticket/736TestCase.php @@ -1,28 +1,34 @@ + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_736_TestCase extends Doctrine_UnitTestCase { - public function prepareData() - { + public function prepareData() + { $delegate = new T736_ModuleDelegate(); - $delegate->content = "Lorem Ipsum and so on..."; + $delegate->content = 'Lorem Ipsum and so on...'; $delegate->save(); $module = new T736_Module(); $module->moduledelegateid = $delegate->id; - + $delegate->parent = $module; $delegate->save(); } - + public function prepareTables() { $this->tables = array(); @@ -33,15 +39,13 @@ public function prepareTables() public function testForHydrationOverwrintingLocalInstancesWhenItShouldnt() { - $module = Doctrine_Core::getTable("T736_Module")->find(1); - $module->moduledata->content = "foo"; + $module = Doctrine_Core::getTable('T736_Module')->find(1); + $module->moduledata->content = 'foo'; $module->moduledata->save(); - $this->assertTrue($module->moduledata->content == "foo"); // should be "foo" is "Lorem Ipsum and so on..." - + $this->assertTrue('foo' == $module->moduledata->content); // should be "foo" is "Lorem Ipsum and so on..." } } - class T736_Module extends Doctrine_Record { public function setTableDefinition() @@ -54,23 +58,21 @@ public function setUp() { $this->addListener(new T736_ModuleLoaderListener()); } - } class T736_ModuleDelegate extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn("moduleid", "integer", 4, array()); - $this->hasColumn("content", "string", 2000); + $this->hasColumn('moduleid', 'integer', 4, array()); + $this->hasColumn('content', 'string', 2000); } - + public function setUp() { - $this->hasOne("T736_Module as parent", array('local' => 'moduleid', 'foreign' => 'id')); + $this->hasOne('T736_Module as parent', array('local' => 'moduleid', 'foreign' => 'id')); } - - + public function preUpdate($event) { $this->parent->lastchange = date('Y-m-d H:i:s', time()); @@ -78,21 +80,18 @@ public function preUpdate($event) } } - class T736_ModuleLoaderListener extends Doctrine_Record_Listener { public function postHydrate(Doctrine_Event $event) { $contents = $event->data; - $delegate = Doctrine_Core::getTable("T736_ModuleDelegate")->find($contents["moduledelegateid"], ($contents instanceof Doctrine_Record) ? Doctrine_Core::HYDRATE_RECORD :Doctrine_Core::HYDRATE_ARRAY ); - if ($contents instanceof Doctrine_Record) - { - $contents->mapValue("moduledata", $delegate); + $delegate = Doctrine_Core::getTable('T736_ModuleDelegate')->find($contents['moduledelegateid'], ($contents instanceof Doctrine_Record) ? Doctrine_Core::HYDRATE_RECORD : Doctrine_Core::HYDRATE_ARRAY); + if ($contents instanceof Doctrine_Record) { + $contents->mapValue('moduledata', $delegate); $delegate->parent = $contents; } else { - $contents["moduledata"] = $delegate; + $contents['moduledata'] = $delegate; } $event->data = $contents; } } -?> diff --git a/tests/Ticket/741TestCase.php b/tests/Ticket/741TestCase.php index e44221d36..69d39df9e 100644 --- a/tests/Ticket/741TestCase.php +++ b/tests/Ticket/741TestCase.php @@ -1,11 +1,15 @@ save(); $this->assertEqual($moo->amount, 0); } - } class Parent741 extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array ( - 'primary' => true, - 'autoincrement' => true, - 'notnull' => true, - )); + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array( + 'primary' => true, + 'autoincrement' => true, + 'notnull' => true, + )); - $this->hasColumn('amount', 'integer'); - } + $this->hasColumn('amount', 'integer'); + } - public function setUp() - { - $this->hasMany('Child741 as Cows', array('local' => 'id', 'foreign' => 'moo_id')); - } + public function setUp() + { + $this->hasMany('Child741 as Cows', array('local' => 'id', 'foreign' => 'moo_id')); + } } class Child741 extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array ( - 'primary' => true, - 'autoincrement' => true, - 'notnull' => true, - )); + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array( + 'primary' => true, + 'autoincrement' => true, + 'notnull' => true, + )); - $this->hasColumn('moo_id', 'integer'); - } + $this->hasColumn('moo_id', 'integer'); + } - public function setUp() - { - $this->hasOne('Parent741 as Moo', array('local' => 'moo_id', 'foreign' => 'id')); - } + public function setUp() + { + $this->hasOne('Parent741 as Moo', array('local' => 'moo_id', 'foreign' => 'id')); + } - public function postInsert($e) - { - $this->Moo->state(Doctrine_Record::STATE_DIRTY); - //echo "State: ". $this->Moo->state() . " \t Amount: " . $this->Moo->amount . "\n"; - $this->Moo->amount = 0; - //echo "State: ". $this->Moo->state() . " \t Amount: " . $this->Moo->amount . "\n"; - $this->Moo->save(); - //echo "State: ". $this->Moo->state() . " \t Amount: " . $this->Moo->amount . "\n"; - $this->Moo->refresh(); - //echo "State: ". $this->Moo->state() . " \t Amount: " . $this->Moo->amount . "\n"; - /* - This outputs the following - State: 6 Amount: 1000 - State: 6 Amount: 0 - State: 6 Amount: 0 - State: 3 Amount: 1000 + public function postInsert($e) + { + $this->Moo->state(Doctrine_Record::STATE_DIRTY); + // echo "State: ". $this->Moo->state() . " \t Amount: " . $this->Moo->amount . "\n"; + $this->Moo->amount = 0; + // echo "State: ". $this->Moo->state() . " \t Amount: " . $this->Moo->amount . "\n"; + $this->Moo->save(); + // echo "State: ". $this->Moo->state() . " \t Amount: " . $this->Moo->amount . "\n"; + $this->Moo->refresh(); + // echo "State: ". $this->Moo->state() . " \t Amount: " . $this->Moo->amount . "\n"; + /* + This outputs the following + State: 6 Amount: 1000 + State: 6 Amount: 0 + State: 6 Amount: 0 + State: 3 Amount: 1000 - */ - } -} \ No newline at end of file + */ + } +} diff --git a/tests/Ticket/749TestCase.php b/tests/Ticket/749TestCase.php index a25bdac26..6ebf0f11a 100644 --- a/tests/Ticket/749TestCase.php +++ b/tests/Ticket/749TestCase.php @@ -1,13 +1,15 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ * * This test case demonstrates a problem with column aggregation inheritance @@ -20,8 +22,11 @@ * This test case should not probably be applied to trunk and possibly not * to 0.10 branch. I'm not sure it's even possible to fix in 0.9 but it is * an issue that keeps arising for me so it seemed worth a test case. + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_749_TestCase extends Doctrine_UnitTestCase { public function prepareTables() @@ -30,7 +35,7 @@ public function prepareTables() parent::prepareTables(); } - public function prepareData() + public function prepareData() { $record = new Record749(); $record['title'] = 'Test Record 1'; @@ -46,13 +51,12 @@ public function prepareData() public function testSelectDataFromSubclassAsCollection() { $records = Doctrine_Query::create()->query('FROM Record749 r ORDER BY r.title', array()); - + $this->verifyRecords($records); } - + public function testSelectDataFromParentClassAsCollection() { - $records = Doctrine_Query::create()->query('FROM Parent749 p ORDER BY p.title', array()); $this->verifyRecords($records); } @@ -61,10 +65,11 @@ public function testSelectDataFromParentClassAsCollection() * This method is used by both tests, as the collection of records should * be identical for both of them if things are working properly. */ - private function verifyRecords ($records) { + private function verifyRecords($records) + { $expected_values = array( - array('title'=>'Test Record 1', 'content'=>'Test Content 1'), - array('title'=>'Test Record 2', 'content'=>'Test Content 2'), + array('title' => 'Test Record 1', 'content' => 'Test Content 1'), + array('title' => 'Test Record 2', 'content' => 'Test Content 2'), ); foreach ($records as $record) { @@ -74,70 +79,68 @@ private function verifyRecords ($records) { try { $this->assertEqual($record['Related']['content'], $expected['content']); } catch (Exception $e) { - $this->fail('Caught exception when trying to get related content: ' . $e->getMessage()); + $this->fail('Caught exception when trying to get related content: '.$e->getMessage()); } - } + } } } class Parent749 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('mytable'); - $this->hasColumn('id', 'integer', 4, array ( - 'primary' => true, - 'autoincrement' => true, - 'notnull' => true, - )); - - $this->hasColumn('title', 'string', 255, array ()); - $this->hasColumn('type', 'integer', 11, array ()); - - $this->setSubclasses(array('Record749' => array('type' => 1))); - } - - public function setUp() - { - } + public function setTableDefinition() + { + $this->setTableName('mytable'); + $this->hasColumn('id', 'integer', 4, array( + 'primary' => true, + 'autoincrement' => true, + 'notnull' => true, + )); + + $this->hasColumn('title', 'string', 255, array()); + $this->hasColumn('type', 'integer', 11, array()); + + $this->setSubclasses(array('Record749' => array('type' => 1))); + } + + public function setUp() + { + } } class Record749 extends Parent749 { - public function setTableDefinition() - { - parent::setTableDefinition(); - $this->setTableName('mytable'); - } - - public function setUp() - { - parent::setUp(); - $this->hasOne('RelatedRecord749 as Related', array('local' => 'id', - 'foreign' => 'record_id')); - } + public function setTableDefinition() + { + parent::setTableDefinition(); + $this->setTableName('mytable'); + } + + public function setUp() + { + parent::setUp(); + $this->hasOne('RelatedRecord749 as Related', array('local' => 'id', + 'foreign' => 'record_id')); + } } class RelatedRecord749 extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array ( - 'primary' => true, - 'autoincrement' => true, - 'notnull' => true, - )); - - $this->hasColumn('content', 'string', 255, array ()); - $this->hasColumn('record_id', 'integer', null, array ('unique' => true,)); - } - - public function setUp() - { - $this->hasOne('Record749 as Record', array('local' => 'record_id', - 'foreign' => 'id', - 'onDelete' => 'cascade')); - } + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array( + 'primary' => true, + 'autoincrement' => true, + 'notnull' => true, + )); + + $this->hasColumn('content', 'string', 255, array()); + $this->hasColumn('record_id', 'integer', null, array('unique' => true)); + } + public function setUp() + { + $this->hasOne('Record749 as Record', array('local' => 'record_id', + 'foreign' => 'id', + 'onDelete' => 'cascade')); + } } - diff --git a/tests/Ticket/753TestCase.php b/tests/Ticket/753TestCase.php index 42f4ef068..dcb9798e1 100644 --- a/tests/Ticket/753TestCase.php +++ b/tests/Ticket/753TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_753_TestCase + * Doctrine_Ticket_753_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_753_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_753_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -60,4 +66,4 @@ public function setTableDefinition() $this->hasColumn('username'); $this->hasColumn('password'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/7745TestCase.php b/tests/Ticket/7745TestCase.php index 5917c8c2d..8e1b15bd2 100644 --- a/tests/Ticket/7745TestCase.php +++ b/tests/Ticket/7745TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_7745_TestCase + * Doctrine_Ticket_7745_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_7745_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_7745_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -53,7 +59,7 @@ public function testDqlCallbacks() $test1->name = 'test'; $test1->RecordTest2 = $test2; $test1->save(); - + $id = $test2->id; $test2->free(); @@ -61,7 +67,8 @@ public function testDqlCallbacks() ->createQuery('a') ->select('a.id') ->where('a.id = ?', $id) - ->fetchOne(); + ->fetchOne() + ; $test2->load(); @@ -83,7 +90,7 @@ public function setUp() { $this->hasOne('RecordTest2', array( 'local' => 'record_test2_id', - 'foreign' => 'id' + 'foreign' => 'id', )); } } @@ -99,7 +106,7 @@ public function setUp() { $this->hasMany('RecordTest1', array( 'local' => 'id', - 'foreign' => 'record_test2_id' + 'foreign' => 'record_test2_id', )); } } @@ -111,6 +118,6 @@ public function preDqlSelect(Doctrine_Event $event) $params = $event->getParams(); $alias = $params['alias']; - $event->getQuery()->leftJoin($alias . '.RecordTest1'); + $event->getQuery()->leftJoin($alias.'.RecordTest1'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/786TestCase.php b/tests/Ticket/786TestCase.php index e328eae53..64949a773 100644 --- a/tests/Ticket/786TestCase.php +++ b/tests/Ticket/786TestCase.php @@ -20,39 +20,44 @@ */ /** - * Doctrine_Ticket_786_TestCase + * Doctrine_Ticket_786_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_786_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_786_TestCase extends Doctrine_UnitTestCase { - public function testConflictingQueriesHydration() - { - // Query for the User with Phonenumbers joined in - // So you can access User->Phonenumber instanceof Doctrine_Collection - $query = new Doctrine_Query(); - $query->from('User u, u.Phonenumber p'); - - $user1 = $query->execute()->getFirst(); - - // Now query for the same data, without the Phonenumber - $query = new Doctrine_Query(); - $query->from('User u'); - - $user2 = $query->execute()->getFirst(); - - // Now if we try and see if Phonenumber is present in $user1 after the 2nd query - if ( ! isset($user1->Phonenumber)) + public function testConflictingQueriesHydration() { - $this->fail('Phonenumber overwritten by 2nd query hydrating'); - } else { - $this->pass(); + // Query for the User with Phonenumbers joined in + // So you can access User->Phonenumber instanceof Doctrine_Collection + $query = new Doctrine_Query(); + $query->from('User u, u.Phonenumber p'); + + $user1 = $query->execute()->getFirst(); + + // Now query for the same data, without the Phonenumber + $query = new Doctrine_Query(); + $query->from('User u'); + + $user2 = $query->execute()->getFirst(); + + // Now if we try and see if Phonenumber is present in $user1 after the 2nd query + if (!isset($user1->Phonenumber)) { + $this->fail('Phonenumber overwritten by 2nd query hydrating'); + } else { + $this->pass(); + } } - } } diff --git a/tests/Ticket/832TestCase.php b/tests/Ticket/832TestCase.php index 61123b704..53d7a25a1 100644 --- a/tests/Ticket/832TestCase.php +++ b/tests/Ticket/832TestCase.php @@ -20,23 +20,30 @@ */ /** - * Doctrine_Ticket_832_TestCase + * Doctrine_Ticket_832_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_832_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_832_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $manager = Doctrine_Manager::getInstance(); $manager->setImpl('Ticket_832_UserTemplate', 'Ticket_832_User') - ->setImpl('Ticket_832_EmailTemplate', 'Ticket_832_Email'); + ->setImpl('Ticket_832_EmailTemplate', 'Ticket_832_Email') + ; $this->tables[] = 'Ticket_832_User'; $this->tables[] = 'Ticket_832_Email'; @@ -64,6 +71,7 @@ public function setTableDefinition() { $this->hasColumn('name', 'string'); } + public function setUp() { $this->hasMany('Ticket_832_EmailTemplate as Email', array('local' => 'id', 'foreign' => 'user_id')); @@ -77,6 +85,7 @@ public function setTableDefinition() $this->hasColumn('address', 'string'); $this->hasColumn('user_id', 'integer'); } + public function setUp() { $this->hasOne('Ticket_832_UserTemplate as User', array('local' => 'user_id', 'foreign' => 'id')); @@ -97,4 +106,4 @@ public function setUp() { $this->actAs('Ticket_832_EmailTemplate'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/838TestCase.php b/tests/Ticket/838TestCase.php index 7c7e0e850..426062a84 100644 --- a/tests/Ticket/838TestCase.php +++ b/tests/Ticket/838TestCase.php @@ -1,15 +1,20 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_838_TestCase extends Doctrine_UnitTestCase { public function prepareTables() @@ -20,11 +25,10 @@ public function prepareTables() public function prepareData() { - } - + /** - * Test that the old root is placed correctly under the new root + * Test that the old root is placed correctly under the new root. */ public function testMoveRoot() { @@ -32,42 +36,42 @@ public function testMoveRoot() $node->name = 'oldroot'; $tree = $this->conn->getTable('NestedSetTest_SingleRootNode')->getTree(); $tree->createRoot($node); - + $oldRoot = $node->copy(); // detach the node, so that it can be inserted as a new node $oldRoot->getNode()->detach(); - + $node->getNode()->delete(); - + $this->assertTrue($oldRoot !== $node); $this->assertEqual(0, $oldRoot['lft']); $this->assertEqual(0, $oldRoot['rgt']); $this->assertEqual(0, $oldRoot['level']); - + $newRoot = new NestedSetTest_SingleRootNode(); $newRoot->name = 'newroot'; $tree->createRoot($newRoot); $this->assertEqual(1, $newRoot['lft']); $this->assertEqual(2, $newRoot['rgt']); $this->assertEqual(0, $newRoot['level']); - + $oldRoot->getNode()->insertAsFirstChildOf($newRoot); - + $this->assertEqual(2, $oldRoot['lft']); $this->assertEqual(3, $oldRoot['rgt']); $this->assertEqual(1, $oldRoot['level']); - + $newRoot->refresh(); - + $this->assertEqual(1, $newRoot['lft']); $this->assertEqual(4, $newRoot['rgt']); $this->assertEqual(0, $newRoot['level']); - + $children = $newRoot->getNode()->getChildren(); $oldRoot = $children[0]; - + $this->assertEqual(2, $oldRoot['lft']); $this->assertEqual(3, $oldRoot['rgt']); $this->assertEqual(1, $oldRoot['level']); } -} \ No newline at end of file +} diff --git a/tests/Ticket/867TestCase.php b/tests/Ticket/867TestCase.php index 99f174934..a162c23f9 100644 --- a/tests/Ticket/867TestCase.php +++ b/tests/Ticket/867TestCase.php @@ -20,66 +20,71 @@ */ /** - * Doctrine_Ticket_867_TestCase + * Doctrine_Ticket_867_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_867_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_867_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { - $this->tables[] = 'T867_Section'; - parent::prepareTables(); - } - - public function testTicket() - { - try { - $s = new T867_Section(); - $s->name = 'Test name'; - $s->Translation['en']->title = 'Test title'; - $s->Translation['en']->summary = 'Test summary'; - $s->save(); - - $this->assertTrue($s->id > 0); - $this->assertEqual($s->name, 'Test name'); - $this->assertEqual($s->Translation['en']->title, 'Test title'); - $this->assertEqual($s->Translation['en']->summary, 'Test summary'); - $this->assertEqual($s->Translation->getTable()->getOption('type'), $s->getTable()->getOption('type')); - $this->assertEqual($s->Translation->getTable()->getOption('collate'), $s->getTable()->getOption('collate')); - $this->assertEqual($s->Translation->getTable()->getOption('charset'), $s->getTable()->getOption('charset')); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->getMessage()); - } - } -} + public function prepareTables() + { + $this->tables[] = 'T867_Section'; + parent::prepareTables(); + } + public function testTicket() + { + try { + $s = new T867_Section(); + $s->name = 'Test name'; + $s->Translation['en']->title = 'Test title'; + $s->Translation['en']->summary = 'Test summary'; + $s->save(); + + $this->assertTrue($s->id > 0); + $this->assertEqual($s->name, 'Test name'); + $this->assertEqual($s->Translation['en']->title, 'Test title'); + $this->assertEqual($s->Translation['en']->summary, 'Test summary'); + $this->assertEqual($s->Translation->getTable()->getOption('type'), $s->getTable()->getOption('type')); + $this->assertEqual($s->Translation->getTable()->getOption('collate'), $s->getTable()->getOption('collate')); + $this->assertEqual($s->Translation->getTable()->getOption('charset'), $s->getTable()->getOption('charset')); + $this->pass(); + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + } +} class T867_Section extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('section'); - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('name', 'string', 60, array('notnull' => true)); - $this->hasColumn('title', 'string', 60, array('notnull' => true)); - $this->hasColumn('summary', 'string', 255); - - $this->option('type', 'INNODB'); - $this->option('collate', 'utf8_unicode_ci'); - $this->option('charset', 'utf8'); - } - - public function setUp() - { - parent::setUp(); - $this->actAs('I18n', array('fields' => array( 0 => 'title', 1 => 'summary', ), 'className' => '%CLASS%_i18n')); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('section'); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 60, array('notnull' => true)); + $this->hasColumn('title', 'string', 60, array('notnull' => true)); + $this->hasColumn('summary', 'string', 255); + + $this->option('type', 'INNODB'); + $this->option('collate', 'utf8_unicode_ci'); + $this->option('charset', 'utf8'); + } + + public function setUp() + { + parent::setUp(); + $this->actAs('I18n', array('fields' => array(0 => 'title', 1 => 'summary'), 'className' => '%CLASS%_i18n')); + } +} diff --git a/tests/Ticket/876TestCase.php b/tests/Ticket/876TestCase.php index 0ba4ef10b..674a427a4 100644 --- a/tests/Ticket/876TestCase.php +++ b/tests/Ticket/876TestCase.php @@ -1,17 +1,21 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_876_TestCase extends Doctrine_UnitTestCase { public function prepareTables() @@ -21,121 +25,121 @@ public function prepareTables() parent::prepareTables(); } - public function prepareData() + public function prepareData() { } public function newPerson($name) { - // Creating sfGuardUser - $guardUser = new sfGuardUser(); + // Creating sfGuardUser + $guardUser = new sfGuardUser(); - $guardUser->set('name', $name); + $guardUser->set('name', $name); - $guardUser->save(); + $guardUser->save(); - // Creating the Person - $person = new Person(); + // Creating the Person + $person = new Person(); - $person->set('name', $name); - $person->set('sf_guard_user_id', $guardUser['id']); + $person->set('name', $name); + $person->set('sf_guard_user_id', $guardUser['id']); - $person->save(); + $person->save(); - return $person; + return $person; } public function newProfile($name, $person) { - $profile = new Profile(); + $profile = new Profile(); - $profile->set('name', $name); - $profile->set('person_id', $person['id']); + $profile->set('name', $name); + $profile->set('person_id', $person['id']); - $profile->save(); + $profile->save(); - return $profile; + return $profile; } - public function testBug() + public function testBug() { - $person = $this->newPerson('Fixe'); - $profile = $this->newProfile('Work', $person); - - $guardUser = $person->get('sfGuardUser'); - $id = $guardUser->get('id'); - - $guardUser->free(); - - $query = new Doctrine_Query(); - - $query->select('s.*, p.*, ps.*'); - $query->from('sfGuardUser s'); - $query->innerJoin('s.Person p'); - $query->leftJoin('p.Profiles ps'); - $query->where('s.id = ?', $id); - - $user = $query->fetchOne(); - $array = $user->toArray(true); - - $this->assertEqual($array['id'], 1); - $this->assertEqual($array['name'], 'Fixe'); - $this->assertTrue(isset($array['Person']['Profiles'][0])); + $person = $this->newPerson('Fixe'); + $profile = $this->newProfile('Work', $person); + + $guardUser = $person->get('sfGuardUser'); + $id = $guardUser->get('id'); + + $guardUser->free(); + + $query = new Doctrine_Query(); + + $query->select('s.*, p.*, ps.*'); + $query->from('sfGuardUser s'); + $query->innerJoin('s.Person p'); + $query->leftJoin('p.Profiles ps'); + $query->where('s.id = ?', $id); + + $user = $query->fetchOne(); + $array = $user->toArray(true); + + $this->assertEqual($array['id'], 1); + $this->assertEqual($array['name'], 'Fixe'); + $this->assertTrue(isset($array['Person']['Profiles'][0])); } } class Person extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('person'); - $this->hasColumn('id', 'integer', 11, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('name', 'string', 255); - $this->hasColumn('sf_guard_user_id', 'integer', 4); - } - - public function setUp() - { - parent::setUp(); - $this->hasMany('Profile as Profiles', array('local' => 'id', - 'foreign' => 'person_id')); - $this->hasOne('sfGuardUser', array('local' => 'sf_guard_user_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); - } + public function setTableDefinition() + { + $this->setTableName('person'); + $this->hasColumn('id', 'integer', 11, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 255); + $this->hasColumn('sf_guard_user_id', 'integer', 4); + } + + public function setUp() + { + parent::setUp(); + $this->hasMany('Profile as Profiles', array('local' => 'id', + 'foreign' => 'person_id')); + $this->hasOne('sfGuardUser', array('local' => 'sf_guard_user_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); + } } class Profile extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('profile'); - $this->hasColumn('id', 'integer', 11, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('name', 'string', 150); - $this->hasColumn('person_id', 'integer', 11); - } - - public function setUp() - { - parent::setUp(); - $this->hasOne('Person', array('local' => 'person_id', - 'foreign' => 'id')); - } + public function setTableDefinition() + { + $this->setTableName('profile'); + $this->hasColumn('id', 'integer', 11, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 150); + $this->hasColumn('person_id', 'integer', 11); + } + + public function setUp() + { + parent::setUp(); + $this->hasOne('Person', array('local' => 'person_id', + 'foreign' => 'id')); + } } class sfGuardUser extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('sf_guard_user'); - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('name', 'string', 128, array('notnull' => true, 'unique' => true)); - } - - public function setUp() - { - parent::setUp(); - $this->hasOne('Person', array('local' => 'id', - 'foreign' => 'sf_guard_user_id')); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('sf_guard_user'); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 128, array('notnull' => true, 'unique' => true)); + } + + public function setUp() + { + parent::setUp(); + $this->hasOne('Person', array('local' => 'id', + 'foreign' => 'sf_guard_user_id')); + } +} diff --git a/tests/Ticket/889TestCase.php b/tests/Ticket/889TestCase.php index ab246b5d8..4b60f5c52 100644 --- a/tests/Ticket/889TestCase.php +++ b/tests/Ticket/889TestCase.php @@ -20,38 +20,44 @@ */ /** - * Doctrine_Ticket_889_TestCase + * Doctrine_Ticket_889_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_889_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_889_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { - $this->tables[] = "Ticket_889"; - $this->tables[] = "Ticket_889_Relationship"; + $this->tables[] = 'Ticket_889'; + $this->tables[] = 'Ticket_889_Relationship'; parent::prepareTables(); } - public function prepareData() - { } - - public function testManyTreeRelationWithSelfRelation_Children() { + public function prepareData() + { + } + public function testManyTreeRelationWithSelfRelationChildren() + { $component = new Ticket_889(); try { $rel = $component->getTable()->getRelation('Children'); $this->pass(); - } catch(Doctrine_Exception $e) { - + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertEqual(get_class($rel), 'Doctrine_Relation_Nest'); @@ -60,16 +66,15 @@ public function testManyTreeRelationWithSelfRelation_Children() { $this->assertTrue($component->Children[0] instanceof Ticket_889); } - public function testManyTreeRelationWithSelfRelation_Parents() { - + public function testManyTreeRelationWithSelfRelationParents() + { $component = new Ticket_889(); try { $rel = $component->getTable()->getRelation('Parents'); $this->pass(); - } catch(Doctrine_Exception $e) { - + } catch (Doctrine_Exception $e) { $this->fail(); } $this->assertEqual(get_class($rel), 'Doctrine_Relation_Nest'); @@ -78,21 +83,21 @@ public function testManyTreeRelationWithSelfRelation_Parents() { $this->assertTrue($component->Parents[0] instanceof Ticket_889); } - public function testInitData() + public function testInitData() { $test = new Ticket_889(); - $test->table_name = 'Feature'; - $test->save(); - - $test3 = new Ticket_889(); - $test3->table_name = 'Application'; - $test3->save(); - - $test2 = new Ticket_889(); - $test2->table_name = 'Module'; - $test2->Children[0] = $test; - $test2->Parents[0] = $test3; - $test2->save(); + $test->table_name = 'Feature'; + $test->save(); + + $test3 = new Ticket_889(); + $test3->table_name = 'Application'; + $test3->save(); + + $test2 = new Ticket_889(); + $test2->table_name = 'Module'; + $test2->Children[0] = $test; + $test2->Parents[0] = $test3; + $test2->save(); } } @@ -107,53 +112,51 @@ public function setTableDefinition() $this->option('type', 'INNODB'); // set character set - $this->option('charset', 'utf8'); + $this->option('charset', 'utf8'); // id $this->hasColumn( - 'id', - 'integer', - 10, - array( 'primary' => true, - 'unsigned' => true, - 'autoincrement' => true - ) - ); + 'id', + 'integer', + 10, + array('primary' => true, + 'unsigned' => true, + 'autoincrement' => true, + ) + ); // table_name - $this->hasColumn( - 'table_name', - 'string', - 100, - array( 'notnull' => true, - 'notblank' =>true, - 'unique' => true - ) - ); - + $this->hasColumn( + 'table_name', + 'string', + 100, + array('notnull' => true, + 'notblank' => true, + 'unique' => true, + ) + ); } public function setUp() { // Ticket_889_Relationship child_id - $this->hasMany( - 'Ticket_889 as Parents', - array( 'local' => 'child_id', - 'foreign' => 'parent_id', - 'refClass' => 'Ticket_889_Relationship' - ) - ); + $this->hasMany( + 'Ticket_889 as Parents', + array('local' => 'child_id', + 'foreign' => 'parent_id', + 'refClass' => 'Ticket_889_Relationship', + ) + ); // Ticket_889_Relationship parent_id $this->hasMany( - 'Ticket_889 as Children', - array( 'local' => 'parent_id', - 'foreign' => 'child_id', - 'refClass' => 'Ticket_889_Relationship' - ) - ); - - } + 'Ticket_889 as Children', + array('local' => 'parent_id', + 'foreign' => 'child_id', + 'refClass' => 'Ticket_889_Relationship', + ) + ); + } } class Ticket_889_Relationship extends Doctrine_Record @@ -166,38 +169,38 @@ public function setTableDefinition() // set table type $this->option('type', 'INNODB'); - // set character set - $this->option('charset', 'utf8'); + // set character set + $this->option('charset', 'utf8'); // parent_id $this->hasColumn( - 'parent_id', - 'integer', - 10, - array( 'primary' => true, - 'unsigned' => true - ) - ); + 'parent_id', + 'integer', + 10, + array('primary' => true, + 'unsigned' => true, + ) + ); // child_id $this->hasColumn( - 'child_id', - 'integer', - 10, - array( 'primary' => true, - 'unsigned' => true - ) - ); + 'child_id', + 'integer', + 10, + array('primary' => true, + 'unsigned' => true, + ) + ); } public function setUp() { - $this->hasOne('Ticket_889 as Parent', array('local' => 'parent_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + $this->hasOne('Ticket_889 as Parent', array('local' => 'parent_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); - $this->hasOne('Ticket_889 as Child', array('local' => 'child_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + $this->hasOne('Ticket_889 as Child', array('local' => 'child_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/894TestCase.php b/tests/Ticket/894TestCase.php index d4b36995f..31761b098 100644 --- a/tests/Ticket/894TestCase.php +++ b/tests/Ticket/894TestCase.php @@ -20,41 +20,48 @@ */ /** - * Doctrine_Ticket_894_TestCase + * Doctrine_Ticket_894_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_894_TestCase extends Doctrine_UnitTestCase { - - public function prepareTables() { - $this->tables = array(); - $this->tables[] = 'T894_Day'; - parent::prepareTables(); +class Doctrine_Ticket_894_TestCase extends Doctrine_UnitTestCase +{ + public function prepareTables() + { + $this->tables = array(); + $this->tables[] = 'T894_Day'; + parent::prepareTables(); } - - public function prepareData() {} - + public function prepareData() + { + } public function testTicket() { $beginNumber = 1; $endNumber = 3; $query = Doctrine_Query::create() - ->from('T894_Day d') - ->where('d.number BETWEEN ? AND ?', array($beginNumber, $endNumber)); + ->from('T894_Day d') + ->where('d.number BETWEEN ? AND ?', array($beginNumber, $endNumber)) + ; $this->assertEqual(' FROM T894_Day d WHERE d.number BETWEEN ? AND ?', $query->getDql()); $this->assertTrue(strstr($query->getSqlQuery(), 'BETWEEN ? AND ?')); } } - class T894_Day extends Doctrine_Record { public function setTableDefinition() @@ -63,4 +70,4 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); $this->hasColumn('number', 'integer'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/904TestCase.php b/tests/Ticket/904TestCase.php index 292517793..99f8d250c 100644 --- a/tests/Ticket/904TestCase.php +++ b/tests/Ticket/904TestCase.php @@ -20,55 +20,61 @@ */ /** - * Doctrine_Ticket_904_TestCase + * Doctrine_Ticket_904_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_904_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_904_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { - $this->tables[] = 'T904_Section'; - parent::prepareTables(); - } - - public function testTicket() - { - try { - $s = new T904_Section(); - $s->state('TDIRTY'); - $s->Translation['en']->title = 'Test title'; - $s->Translation['en']->summary = 'Test summary'; - $s->save(); - - $this->assertTrue($s->id > 0); - $this->assertEqual($s->Translation['en']->title, 'Test title'); - $this->assertEqual($s->Translation['en']->summary, 'Test summary'); - $this->pass(); - } catch (Exception $e) { - $this->fail($e->getMessage()); - } - } + public function prepareTables() + { + $this->tables[] = 'T904_Section'; + parent::prepareTables(); + } + + public function testTicket() + { + try { + $s = new T904_Section(); + $s->state('TDIRTY'); + $s->Translation['en']->title = 'Test title'; + $s->Translation['en']->summary = 'Test summary'; + $s->save(); + + $this->assertTrue($s->id > 0); + $this->assertEqual($s->Translation['en']->title, 'Test title'); + $this->assertEqual($s->Translation['en']->summary, 'Test summary'); + $this->pass(); + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + } } class T904_Section extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('title', 'string', 60, array('notnull' => true)); - $this->hasColumn('summary', 'string', 255); - } - - public function setUp() - { - parent::setUp(); - $this->actAs('I18n', array('fields' => array( 0 => 'title', 1 => 'summary', ), 'className' => '%CLASS%_i18n')); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('title', 'string', 60, array('notnull' => true)); + $this->hasColumn('summary', 'string', 255); + } + + public function setUp() + { + parent::setUp(); + $this->actAs('I18n', array('fields' => array(0 => 'title', 1 => 'summary'), 'className' => '%CLASS%_i18n')); + } +} diff --git a/tests/Ticket/912TestCase.php b/tests/Ticket/912TestCase.php index 1b940ebb6..b9f835755 100644 --- a/tests/Ticket/912TestCase.php +++ b/tests/Ticket/912TestCase.php @@ -20,264 +20,249 @@ */ /** - * Doctrine_Ticket_912_TestCase + * Doctrine_Ticket_912_TestCase. * - * @package Doctrine * @author David Stendardi + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_912_TestCase extends Doctrine_UnitTestCase { - - /** - * prepareData - */ - +class Doctrine_Ticket_912_TestCase extends Doctrine_UnitTestCase +{ + /** + * prepareData. + */ public function prepareData() { - $oResume = new ticket912_Resume; - $oResume->title = 'titre'; - $oResume->Person->name = 'David'; - $oResume->KnownLanguages[0]->comments = 'foo'; - $oResume->KnownLanguages[0]->Language->label = "Enlish"; - $oResume->KnownLanguages[0]->Level->label = "Fluent"; - $oResume->save(); + $oResume = new ticket912_Resume(); + $oResume->title = 'titre'; + $oResume->Person->name = 'David'; + $oResume->KnownLanguages[0]->comments = 'foo'; + $oResume->KnownLanguages[0]->Language->label = 'Enlish'; + $oResume->KnownLanguages[0]->Level->label = 'Fluent'; + $oResume->save(); } - + /** - * prepareTables + * prepareTables. */ - public function prepareTables() { - $this->tables = array(); - $this->tables[] = 'ticket912_Resume'; - $this->tables[] = 'ticket912_Person'; - $this->tables[] = 'ticket912_ResumeHasLanguage'; - $this->tables[] = 'ticket912_LanguageLevel'; - $this->tables[] = 'ticket912_Language'; - - parent :: prepareTables(); + $this->tables = array(); + $this->tables[] = 'ticket912_Resume'; + $this->tables[] = 'ticket912_Person'; + $this->tables[] = 'ticket912_ResumeHasLanguage'; + $this->tables[] = 'ticket912_LanguageLevel'; + $this->tables[] = 'ticket912_Language'; + + parent::prepareTables(); } - - + /** - * Test the existence expected indexes + * Test the existence expected indexes. */ - public function testTicket() { $q = new Doctrine_Query(); // simple query with deep relations $q->addSelect('Resume.id, Person.id, Person.name, KnownLanguages.id, Level.label, Language.label') - ->from('ticket912_Resume Resume') - ->leftJoin('Resume.Person Person') - ->leftJoin('Resume.KnownLanguages KnownLanguages') - ->leftJoin('KnownLanguages.Level Level') - ->leftJoin('KnownLanguages.Language Language'); - + ->from('ticket912_Resume Resume') + ->leftJoin('Resume.Person Person') + ->leftJoin('Resume.KnownLanguages KnownLanguages') + ->leftJoin('KnownLanguages.Level Level') + ->leftJoin('KnownLanguages.Language Language') + ; + $aResult = $q->fetchArray(); // should be setted.. - $issetLevel = isset($aResult[0]['KnownLanguages'][0]['Level']); + $issetLevel = isset($aResult[0]['KnownLanguages'][0]['Level']); $issetLanguage = isset($aResult[0]['KnownLanguages'][0]['Language']); - + $this->assertTrue($issetLevel); $this->assertTrue($issetLanguage); - } } - /** - * This class has been auto-generated by the Doctrine ORM Framework + * This class has been auto-generated by the Doctrine ORM Framework. */ - class ticket912_Resume extends Doctrine_Record { - /** - * setTableDefinition - */ - - public function setTableDefinition() - { - $this->setTableName('resume'); - $this->hasColumn('id', 'integer', 8, array ( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); + /** + * setTableDefinition. + */ + public function setTableDefinition() + { + $this->setTableName('resume'); + $this->hasColumn('id', 'integer', 8, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); - $this->hasColumn('person_id', 'integer', 8, array('unsigned' => true)); - $this->hasColumn('title', 'string', 255); - } + $this->hasColumn('person_id', 'integer', 8, array('unsigned' => true)); + $this->hasColumn('title', 'string', 255); + } - /** - * setUp - */ - - public function setUp() - { - $this->hasMany('ticket912_ResumeHasLanguage as KnownLanguages', array('local' => 'id', 'foreign' => 'resume_id')); - - $this->hasOne('ticket912_Person as Person', array( - 'local' => 'person_id', - 'foreign' => 'id', - 'onDelete' => 'SET NULL', - 'onUpdate' => 'CASCADE' - )); - } + /** + * setUp. + */ + public function setUp() + { + $this->hasMany('ticket912_ResumeHasLanguage as KnownLanguages', array('local' => 'id', 'foreign' => 'resume_id')); + + $this->hasOne('ticket912_Person as Person', array( + 'local' => 'person_id', + 'foreign' => 'id', + 'onDelete' => 'SET NULL', + 'onUpdate' => 'CASCADE', + )); + } } /** - * First level one to one relation class Language + * First level one to one relation class Language. */ class ticket912_Person extends Doctrine_Record -{ - /** - * setTableDefinition - */ - - public function setTableDefinition() - { - $this->setTableName('person'); - $this->hasColumn('id', 'integer', 8, array ( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); +{ + /** + * setTableDefinition. + */ + public function setTableDefinition() + { + $this->setTableName('person'); + $this->hasColumn('id', 'integer', 8, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); - $this->hasColumn('name', 'string', 255, array ()); - } + $this->hasColumn('name', 'string', 255, array()); + } } - /** - * Second level one to many relation class ResumeHasLanguageLanguage + * Second level one to many relation class ResumeHasLanguageLanguage. */ - class ticket912_ResumeHasLanguage extends Doctrine_Record { - /** - * setTableDefinition - */ - - public function setTableDefinition() - { - $this->setTableName('resume_has_language'); - $this->hasColumn('id', 'integer', 8, array ( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); + /** + * setTableDefinition. + */ + public function setTableDefinition() + { + $this->setTableName('resume_has_language'); + $this->hasColumn('id', 'integer', 8, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); - $this->hasColumn('resume_id', 'integer', 8, array ( - 'notnull' => true, - 'unsigned' => true, - )); + $this->hasColumn('resume_id', 'integer', 8, array( + 'notnull' => true, + 'unsigned' => true, + )); - $this->hasColumn('language_id', 'integer', 2, array ( - 'unsigned' => true, - )); + $this->hasColumn('language_id', 'integer', 2, array( + 'unsigned' => true, + )); - $this->hasColumn('language_level_id', 'integer', 2, array ( - 'unsigned' => true, - )); - - $this->hasColumn('comments', 'string', 4000, array ()); + $this->hasColumn('language_level_id', 'integer', 2, array( + 'unsigned' => true, + )); - } + $this->hasColumn('comments', 'string', 4000, array()); + } - /** - * setUp - */ - - public function setUp() - { - $this->hasOne('ticket912_Resume as Resume', array('local' => 'resume_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE', - 'onUpdate' => 'CASCADE')); + /** + * setUp. + */ + public function setUp() + { + $this->hasOne('ticket912_Resume as Resume', array('local' => 'resume_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + 'onUpdate' => 'CASCADE')); - $this->hasOne('ticket912_Language as Language', array('local' => 'language_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE', - 'onUpdate' => 'CASCADE')); + $this->hasOne('ticket912_Language as Language', array('local' => 'language_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + 'onUpdate' => 'CASCADE')); - $this->hasOne('ticket912_LanguageLevel as Level', array('local' => 'language_level_id', - 'foreign' => 'id', - 'onDelete' => 'SET NULL', - 'onUpdate' => 'CASCADE')); - } + $this->hasOne('ticket912_LanguageLevel as Level', array('local' => 'language_level_id', + 'foreign' => 'id', + 'onDelete' => 'SET NULL', + 'onUpdate' => 'CASCADE')); + } } - - /** - * Third level one to one relation class Language + * Third level one to one relation class Language. */ class ticket912_Language extends Doctrine_Record { - /** - * setTableDefinition - */ - - public function setTableDefinition() - { - $this->setTableName('language'); - $this->hasColumn('id', 'integer', 2, array( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); + /** + * setTableDefinition. + */ + public function setTableDefinition() + { + $this->setTableName('language'); + $this->hasColumn('id', 'integer', 2, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); - $this->hasColumn('label', 'string', 100, array ('notnull' => true)); - } + $this->hasColumn('label', 'string', 100, array('notnull' => true)); + } - /** - * setup - */ - - public function setUp() - { - $this->hasMany('ticket912_Resume as Resumes', array('local' => 'id', 'foreign' => 'language_id')); - $this->hasMany('ticket912_ResumeHasLanguage as ResumeKnownLanguages', array('local' => 'id', 'foreign' => 'language_id')); - } + /** + * setup. + */ + public function setUp() + { + $this->hasMany('ticket912_Resume as Resumes', array('local' => 'id', 'foreign' => 'language_id')); + $this->hasMany('ticket912_ResumeHasLanguage as ResumeKnownLanguages', array('local' => 'id', 'foreign' => 'language_id')); + } } /** - * Third level one to one relation class Language + * Third level one to one relation class Language. */ - class ticket912_LanguageLevel extends Doctrine_Record { - /** - * setTableDefinition - */ - - public function setTableDefinition() - { - $this->setTableName('language_level'); - $this->hasColumn('id', 'integer', 2, array ( - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true, - )); + /** + * setTableDefinition. + */ + public function setTableDefinition() + { + $this->setTableName('language_level'); + $this->hasColumn('id', 'integer', 2, array( + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true, + )); - $this->hasColumn('label', 'string', 100, array ('notnull' => true)); - } + $this->hasColumn('label', 'string', 100, array('notnull' => true)); + } - /** - * setUp - */ - - public function setUp() - { - $this->hasMany('ticket912_ResumeHasLanguage as ResumeKnownLanguages', array( - 'local' => 'id', - 'foreign' => 'language_level_id')); - } -} \ No newline at end of file + /** + * setUp. + */ + public function setUp() + { + $this->hasMany('ticket912_ResumeHasLanguage as ResumeKnownLanguages', array( + 'local' => 'id', + 'foreign' => 'language_level_id')); + } +} diff --git a/tests/Ticket/915TestCase.php b/tests/Ticket/915TestCase.php index c73ca976a..a34540298 100644 --- a/tests/Ticket/915TestCase.php +++ b/tests/Ticket/915TestCase.php @@ -20,28 +20,37 @@ */ /** - * Doctrine_Ticket_915_TestCase + * Doctrine_Ticket_915_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_915_TestCase extends Doctrine_UnitTestCase { - public function prepareData() { } + public function prepareData() + { + } + public function prepareTables() { $this->tables[] = 'Account'; - parent::prepareTables(); + parent::prepareTables(); } public function testBug() { - $yml = <<setFormat("yml"); + $import->setFormat('yml'); // try to import garbled records (with incorrect field names, // e.g. "Amount" instead of "amount") and expect that doctrine @@ -72,4 +81,4 @@ public function testBug() $this->pass(); } } -} \ No newline at end of file +} diff --git a/tests/Ticket/923TestCase.php b/tests/Ticket/923TestCase.php index f16090e9f..71da16308 100644 --- a/tests/Ticket/923TestCase.php +++ b/tests/Ticket/923TestCase.php @@ -20,18 +20,24 @@ */ /** - * Doctrine_Ticket923_TestCase + * Doctrine_Ticket923_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_923_TestCase extends Doctrine_UnitTestCase { - +class Doctrine_Ticket_923_TestCase extends Doctrine_UnitTestCase +{ public function prepareData() { $d = new T923_Diagnostic(); @@ -59,7 +65,8 @@ public function prepareData() $d->save(); } - public function prepareTables() { + public function prepareTables() + { $this->tables[] = 'T923_Diagnostic'; parent::prepareTables(); } @@ -67,17 +74,18 @@ public function prepareTables() { public function testTicket() { try { - $q = new Doctrine_Query(); - $result = $q->select('d.*') - ->from('T923_Diagnostic d') - ->where('d.diag_timestamp >= ? AND d.diag_timestamp <= ?', array('2008-03-27 00:00:00', '2008-03-27 23:00:00')) - ->addWhere('d.id_type = ?', array('101')) - ->orderBy('d.diag_timestamp') - ->limit(20) - ->offset(0) - ->execute(); - - $this->assertEqual($result->count(), 3); + $q = new Doctrine_Query(); + $result = $q->select('d.*') + ->from('T923_Diagnostic d') + ->where('d.diag_timestamp >= ? AND d.diag_timestamp <= ?', array('2008-03-27 00:00:00', '2008-03-27 23:00:00')) + ->addWhere('d.id_type = ?', array('101')) + ->orderBy('d.diag_timestamp') + ->limit(20) + ->offset(0) + ->execute() + ; + + $this->assertEqual($result->count(), 3); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -86,17 +94,17 @@ public function testTicket() class T923_Diagnostic extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('diagnostics'); - $this->hasColumn('id_type', 'integer', 4); - $this->hasColumn('id', 'integer', 4); - $this->hasColumn('diagnostic_id', 'integer', 4); - $this->hasColumn('operator_id', 'integer', 4); - $this->hasColumn('diag_timestamp', 'timestamp', null); - } + public function setTableDefinition() + { + $this->setTableName('diagnostics'); + $this->hasColumn('id_type', 'integer', 4); + $this->hasColumn('id', 'integer', 4); + $this->hasColumn('diagnostic_id', 'integer', 4); + $this->hasColumn('operator_id', 'integer', 4); + $this->hasColumn('diag_timestamp', 'timestamp', null); + } - public function setUp() - { - } -} \ No newline at end of file + public function setUp() + { + } +} diff --git a/tests/Ticket/927TestCase.php b/tests/Ticket/927TestCase.php index 3a485e895..67dcd1edc 100644 --- a/tests/Ticket/927TestCase.php +++ b/tests/Ticket/927TestCase.php @@ -20,20 +20,26 @@ */ /** - * Doctrine_Ticket_927_TestCase + * Doctrine_Ticket_927_TestCase. * - * @package Doctrine * @author David Stendardi + * * @category Query - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.10.4 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_927_TestCase extends Doctrine_UnitTestCase { public function prepareData() { - $oEmail = new Email; + $oEmail = new Email(); $oEmail->address = 'david.stendardi@adenclassifieds.com'; $oEmail->save(); } @@ -43,21 +49,22 @@ public function prepareTables() $this->tables = array(); $this->tables[] = 'Email'; - parent :: prepareTables(); + parent::prepareTables(); } public function testTicket() { - $q = new Doctrine_Query(); + $q = new Doctrine_Query(); - try { - // simple query with deep relations - $q->update('Email') - ->set('address', '?', 'new@doctrine.org') - ->where('address = ?', 'david.stendardi@adenclassifieds.com') - ->execute(); - } catch (Exception $e) { - $this->fail('Query :: set do not support values containing dot. Exception: ' . $e->getMessage()); - } + try { + // simple query with deep relations + $q->update('Email') + ->set('address', '?', 'new@doctrine.org') + ->where('address = ?', 'david.stendardi@adenclassifieds.com') + ->execute() + ; + } catch (Exception $e) { + $this->fail('Query :: set do not support values containing dot. Exception: '.$e->getMessage()); + } } -} \ No newline at end of file +} diff --git a/tests/Ticket/929TestCase.php b/tests/Ticket/929TestCase.php index 30729caa7..ed5b686e1 100644 --- a/tests/Ticket/929TestCase.php +++ b/tests/Ticket/929TestCase.php @@ -20,29 +20,35 @@ */ /** - * Doctrine_Ticket_929_TestCase + * Doctrine_Ticket_929_TestCase. * - * @package Doctrine * @author David Stendardi + * * @category Hydration - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_929_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_929_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { - $oPerson = new T929_Person; + { + $oPerson = new T929_Person(); $oPerson->name = 'Jonathan'; $oPerson->Country->code = 'us'; $oPerson->Country->Translation['fr']->name = 'Etats Unis'; - $oPerson->Country->Translation['en']->name = 'United states'; + $oPerson->Country->Translation['en']->name = 'United states'; $oPerson->save(); parent::prepareData(); } - + public function prepareTables() { $this->tables = array(); @@ -53,10 +59,10 @@ public function prepareTables() parent::prepareTables(); } - + public function testTicket() { - try { + try { $q = new Doctrine_Query(); $r = $q ->from('T929_Person P') @@ -66,9 +72,10 @@ public function testTicket() ->leftJoin('J.Category C') ->leftJoin('C.Translation T2 WITH T2.lang = ?', 'fr') ->where('P.name = ?', 'Jonathan') - ->fetchOne(); + ->fetchOne() + ; } catch (Exception $e) { - $this->fail($e->getMessage()); + $this->fail($e->getMessage()); } } } @@ -89,13 +96,13 @@ public function setUp() $this->hasOne('T929_Country as Country', array( 'local' => 'country_id', 'foreign' => 'id', - 'onDelete' => 'CASCADE' + 'onDelete' => 'CASCADE', )); $this->hasMany('T929_JobPosition as JobPositions', array( 'local' => 'id', 'foreign' => 'person_id', - 'onDelete' => 'CASCADE' + 'onDelete' => 'CASCADE', )); } } @@ -116,7 +123,7 @@ public function setUp() $this->hasMany('T929_Person as Persons', array( 'local' => 'id', 'foreign' => 'country_id', - 'onDelete' => 'CASCADE' + 'onDelete' => 'CASCADE', )); $this->actAs('I18n', array('fields' => array('name'))); @@ -140,13 +147,13 @@ public function setUp() $this->hasOne('T929_Person as Person', array( 'local' => 'person_id', 'foreign' => 'id', - 'onDelete' => 'CASCADE' + 'onDelete' => 'CASCADE', )); $this->hasOne('T929_JobCategory as Category', array( 'local' => 'job_category_id', 'foreign' => 'id', - 'onDelete' => 'CASCADE' + 'onDelete' => 'CASCADE', )); } } @@ -167,9 +174,9 @@ public function setUp() $this->hasMany('T929_JobPosition as Positions', array( 'local' => 'id', 'foreign' => 'job_category_id', - 'onDelete' => 'CASCADE' + 'onDelete' => 'CASCADE', )); $this->actAs('I18n', array('fields' => array('name'))); } -} \ No newline at end of file +} diff --git a/tests/Ticket/930TestCase.php b/tests/Ticket/930TestCase.php index 95799c25d..b3e3e5513 100644 --- a/tests/Ticket/930TestCase.php +++ b/tests/Ticket/930TestCase.php @@ -20,152 +20,149 @@ */ /** - * Doctrine_Ticket_930_TestCase + * Doctrine_Ticket_930_TestCase. * - * @package Doctrine * @author David Stendardi + * * @category Hydration - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_930_TestCase extends Doctrine_UnitTestCase { - - /** - * prepareData - */ - - public function prepareData() - { - $oPerson = new T930_Person; - $oPerson->name = 'David'; - - $oCategory = new T930_JobCategory; - $oCategory->code = '1234'; - $oCategory->Translation['fr']->name = 'Developpement'; - $oCategory->Translation['en']->name = 'Development'; - - $oPerson->JobPositions[0]->name = 'Webdeveloper'; - $oPerson->JobPositions[0]->Category = $oCategory; - - $oPerson->JobPositions[1]->name = 'Webmaster'; - $oPerson->JobPositions[1]->Category = $oCategory; - - $oPerson->save(); - - } - - /** - * prepareTables - */ - - public function prepareTables() - { - $this->tables = array(); - $this->tables[] = 'T930_Person'; - $this->tables[] = 'T930_JobPosition'; - $this->tables[] = 'T930_JobCategory'; - - parent :: prepareTables(); - } - - - /** - * Test the existence expected indexes - */ - - public function testTicket() - { - $queryCountBefore = $this->conn->count(); - try { - $q = new Doctrine_Query(); - $r = $q - ->select('P.id, J.name, C.code, T.name') - ->from('T930_Person P') - ->leftJoin('P.JobPositions J') - ->leftJoin('J.Category C') - ->leftJoin('C.Translation T WITH T.lang = ?', 'fr') - ->fetchArray(); - } catch (Exception $e) { - $this->fail($e->getMessage()); +class Doctrine_Ticket_930_TestCase extends Doctrine_UnitTestCase +{ + /** + * prepareData. + */ + public function prepareData() + { + $oPerson = new T930_Person(); + $oPerson->name = 'David'; + + $oCategory = new T930_JobCategory(); + $oCategory->code = '1234'; + $oCategory->Translation['fr']->name = 'Developpement'; + $oCategory->Translation['en']->name = 'Development'; + + $oPerson->JobPositions[0]->name = 'Webdeveloper'; + $oPerson->JobPositions[0]->Category = $oCategory; + + $oPerson->JobPositions[1]->name = 'Webmaster'; + $oPerson->JobPositions[1]->Category = $oCategory; + + $oPerson->save(); + } + + /** + * prepareTables. + */ + public function prepareTables() + { + $this->tables = array(); + $this->tables[] = 'T930_Person'; + $this->tables[] = 'T930_JobPosition'; + $this->tables[] = 'T930_JobCategory'; + + parent::prepareTables(); + } + + /** + * Test the existence expected indexes. + */ + public function testTicket() + { + $queryCountBefore = $this->conn->count(); + try { + $q = new Doctrine_Query(); + $r = $q + ->select('P.id, J.name, C.code, T.name') + ->from('T930_Person P') + ->leftJoin('P.JobPositions J') + ->leftJoin('J.Category C') + ->leftJoin('C.Translation T WITH T.lang = ?', 'fr') + ->fetchArray() + ; + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + $this->assertEqual($queryCountBefore + 1, $this->conn->count()); + $this->assertTrue(isset($r[0]['JobPositions'][0]['Category']['Translation']['fr']['name'])); + $this->assertTrue(isset($r[0]['JobPositions'][1]['Category']['Translation']['fr']['name'])); + $this->assertEqual($queryCountBefore + 1, $this->conn->count()); } - $this->assertEqual($queryCountBefore + 1, $this->conn->count()); - $this->assertTrue(isset($r[0]['JobPositions'][0]['Category']['Translation']['fr']['name'])); - $this->assertTrue(isset($r[0]['JobPositions'][1]['Category']['Translation']['fr']['name'])); - $this->assertEqual($queryCountBefore + 1, $this->conn->count()); - } } class T930_Person extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T930_person'); - $this->hasColumn('name', 'string', 200); - } - - public function setUp() - { - parent :: setUp(); - - $this->hasMany('T930_JobPosition as JobPositions', array( - 'local' => 'id', - 'foreign' => 'person_id', - 'onDelete' => 'CASCADE' - )); - } -} + public function setTableDefinition() + { + $this->setTableName('T930_person'); + $this->hasColumn('name', 'string', 200); + } + public function setUp() + { + parent::setUp(); + + $this->hasMany('T930_JobPosition as JobPositions', array( + 'local' => 'id', + 'foreign' => 'person_id', + 'onDelete' => 'CASCADE', + )); + } +} class T930_JobPosition extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('T930_address'); - $this->hasColumn('name', 'string', 200); - $this->hasColumn('person_id', 'integer'); - $this->hasColumn('job_category_id', 'integer'); - } - - public function setUp() - { - parent :: setUp(); - $this->hasOne('T930_Person as Person', array( - 'local' => 'person_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE' - )); - - $this->hasOne('T930_JobCategory as Category', array( - 'local' => 'job_category_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE' - )); - } + public function setTableDefinition() + { + $this->setTableName('T930_address'); + $this->hasColumn('name', 'string', 200); + $this->hasColumn('person_id', 'integer'); + $this->hasColumn('job_category_id', 'integer'); + } + + public function setUp() + { + parent::setUp(); + $this->hasOne('T930_Person as Person', array( + 'local' => 'person_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + )); + + $this->hasOne('T930_JobCategory as Category', array( + 'local' => 'job_category_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + )); + } } class T930_JobCategory extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('job_category'); - $this->hasColumn('code', 'integer', 4); - $this->hasColumn('name', 'string', 200); - } - - public function setUp() - { - parent :: setUp(); - $this->hasMany('T930_JobPosition as Positions', array( - 'local' => 'id', - 'foreign' => 'job_category_id', - 'onDelete' => 'CASCADE' - )); - - $this->actAs('I18n', array('fields' => array('name'))); - } -} - - + public function setTableDefinition() + { + $this->setTableName('job_category'); + $this->hasColumn('code', 'integer', 4); + $this->hasColumn('name', 'string', 200); + } + public function setUp() + { + parent::setUp(); + $this->hasMany('T930_JobPosition as Positions', array( + 'local' => 'id', + 'foreign' => 'job_category_id', + 'onDelete' => 'CASCADE', + )); + $this->actAs('I18n', array('fields' => array('name'))); + } +} diff --git a/tests/Ticket/932TestCase.php b/tests/Ticket/932TestCase.php index 6798947b3..3344cb1a4 100644 --- a/tests/Ticket/932TestCase.php +++ b/tests/Ticket/932TestCase.php @@ -1,40 +1,45 @@ tables[] = "UserNoAutoIncrement"; - parent::prepareTables(); - } + public function prepareTables() + { + $this->tables[] = 'UserNoAutoIncrement'; + parent::prepareTables(); + } - public function prepareData() - { - } + public function prepareData() + { + } - public function testInit() - { - $this->dbh = new Doctrine_Adapter_Mock('pgsql'); - $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh); - $this->assertEqual(Doctrine_Core::IDENTIFIER_NATURAL, $this->conn->getTable('UserNoAutoIncrement')->getIdentifierType()); - } + public function testInit() + { + $this->dbh = new Doctrine_Adapter_Mock('pgsql'); + $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh); + $this->assertEqual(Doctrine_Core::IDENTIFIER_NATURAL, $this->conn->getTable('UserNoAutoIncrement')->getIdentifierType()); + } - public function testCreateNewUserNoAutoIncrement() - { - $newUser = new UserNoAutoIncrement(); - $newUser->id = 1; - $newUser->display_name = "Mah Name"; - $newUser->save(); - $this->assertEqual(Doctrine_Record::STATE_CLEAN, $newUser->state()); - $this->assertEqual(1, $newUser->id); - } + public function testCreateNewUserNoAutoIncrement() + { + $newUser = new UserNoAutoIncrement(); + $newUser->id = 1; + $newUser->display_name = 'Mah Name'; + $newUser->save(); + $this->assertEqual(Doctrine_Record::STATE_CLEAN, $newUser->state()); + $this->assertEqual(1, $newUser->id); + } } class UserNoAutoIncrement extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => false, 'notnull' => true)); - $this->hasColumn('display_name', 'string', 255, array('notnull' => true)); - } + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => false, 'notnull' => true)); + $this->hasColumn('display_name', 'string', 255, array('notnull' => true)); + } } diff --git a/tests/Ticket/935TestCase.php b/tests/Ticket/935TestCase.php index ace72df87..11a6e0ca5 100644 --- a/tests/Ticket/935TestCase.php +++ b/tests/Ticket/935TestCase.php @@ -20,18 +20,24 @@ */ /** - * Doctrine_Ticket935_TestCase + * Doctrine_Ticket935_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_935_TestCase extends Doctrine_UnitTestCase { - +class Doctrine_Ticket_935_TestCase extends Doctrine_UnitTestCase +{ public function prepareData() { $d = new EnumUpdateBug(); @@ -39,7 +45,8 @@ public function prepareData() $d->save(); } - public function prepareTables() { + public function prepareTables() + { $this->tables[] = 'EnumUpdateBug'; parent::prepareTables(); } @@ -47,37 +54,39 @@ public function prepareTables() { public function testTicket() { try { - $q = new Doctrine_Query(); - $q->update('EnumUpdateBug') - ->set('bla_id', '?', 5) - ->set('separator', '?', 'pipe') - ->where('id = 1') - ->execute(); + $q = new Doctrine_Query(); + $q->update('EnumUpdateBug') + ->set('bla_id', '?', 5) + ->set('separator', '?', 'pipe') + ->where('id = 1') + ->execute() + ; } catch (Exception $e) { $this->fail($e->getMessage()); } - + $q = new Doctrine_Query(); $row = $q->select('a.*') - ->from('EnumUpdateBug a') - ->where('a.id = 1') - ->fetchOne(); - + ->from('EnumUpdateBug a') + ->where('a.id = 1') + ->fetchOne() + ; + $this->assertEqual($row->bla_id, 5); } } class EnumUpdateBug extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('enumupdatebug'); - $this->hasColumn('id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); - $this->hasColumn('bla_id', 'integer', 2, array('unsigned' => true)); - $this->hasColumn('separator', 'enum', 1, array('values' => array( 0 => 'comma', 1 => 'pipe', ))); - } + public function setTableDefinition() + { + $this->setTableName('enumupdatebug'); + $this->hasColumn('id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); + $this->hasColumn('bla_id', 'integer', 2, array('unsigned' => true)); + $this->hasColumn('separator', 'enum', 1, array('values' => array(0 => 'comma', 1 => 'pipe'))); + } - public function setUp() - { - } -} \ No newline at end of file + public function setUp() + { + } +} diff --git a/tests/Ticket/941TestCase.php b/tests/Ticket/941TestCase.php index 2a66a147b..ca1d5e163 100644 --- a/tests/Ticket/941TestCase.php +++ b/tests/Ticket/941TestCase.php @@ -2,186 +2,180 @@ /** * @author Donald Ball + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_941_TestCase extends Doctrine_UnitTestCase { - - public function prepareTables() - { - $this->tables = array('Site', 'Variable', 'SiteVarvalue'); - parent::prepareTables(); - } - - public function prepareData() - { - $site = new Site(); - $site->site_id = 1; - $site->site_domain = 'site1'; - $site->save(); - - $site = new Site(); - $site->site_id = 2; - $site->site_domain = 'site2'; - $site->save(); - - $var = new Variable(); - $var->variable_id = 1; - $var->variable_name = 'var1'; - $var->save(); - - $var = new Variable(); - $var->variable_id = 2; - $var->variable_name = 'var2'; - $var->save(); - - $varval = new SiteVarvalue(); - $varval->site_id = 1; - $varval->variable_id = 1; - $varval->varvalue_value = 'val1 dom1 var1'; - $varval->save(); - - $varval = new SiteVarvalue(); - $varval->site_id = 1; - $varval->variable_id = 2; - $varval->varvalue_value = 'val2 dom1 var2'; - $varval->save(); - - $varval = new SiteVarvalue(); - $varval->site_id = 2; - $varval->variable_id = 1; - $varval->varvalue_value = 'val3 dom2 var1'; - $varval->save(); - - $varval = new SiteVarvalue(); - $varval->site_id = 2; - $varval->variable_id = 2; - $varval->varvalue_value = 'val4 dom2 var2'; - $varval->save(); - } - - public function testTicket() - { - $query = new Doctrine_Query(); - $query = $query->from('Site s LEFT JOIN s.Variables v LEFT JOIN v.Values vv WITH vv.site_id = s.site_id'); - - $sites = $query->execute(); - - $this->assertEqual('site1', $sites[0]->site_domain); - $this->assertEqual(2, count($sites)); - - // this is important for the understanding of the behavior - $this->assertIdentical($sites[0]->Variables[0], $sites[1]->Variables[0]); - $this->assertIdentical($sites[0]->Variables[1], $sites[1]->Variables[1]); - $this->assertEqual(2, count($sites[0]->Variables[0]->Values)); - $this->assertEqual(2, count($sites[1]->Variables[0]->Values)); - $this->assertEqual(2, count($sites[0]->Variables[1]->Values)); - $this->assertEqual(2, count($sites[1]->Variables[1]->Values)); - // Here we see that there can be only one Values on each Variable object. Hence - // they end up with 2 objects each. - $this->assertEqual('val1 dom1 var1', $sites[0]->Variables[0]->Values[0]->varvalue_value); - $this->assertEqual('val3 dom2 var1', $sites[0]->Variables[0]->Values[1]->varvalue_value); - $this->assertEqual('val2 dom1 var2', $sites[0]->Variables[1]->Values[0]->varvalue_value); - $this->assertEqual('val4 dom2 var2', $sites[0]->Variables[1]->Values[1]->varvalue_value); - - $this->assertEqual('var1', $sites[0]->Variables[0]->variable_name); - $this->assertEqual('var1', $sites[1]->Variables[0]->variable_name); - - $this->assertEqual('var2', $sites[0]->Variables[1]->variable_name); - $this->assertEqual('var2', $sites[1]->Variables[1]->variable_name); - - - // now array hydration - - $sites = $query->fetchArray(); - - $this->assertEqual('site1', $sites[0]['site_domain']); - $this->assertEqual('site2', $sites[1]['site_domain']); - $this->assertEqual(2, count($sites)); - - // this is important for the understanding of the behavior - $this->assertEqual(1, count($sites[0]['Variables'][0]['Values'])); - $this->assertEqual(1, count($sites[1]['Variables'][0]['Values'])); - $this->assertEqual(1, count($sites[0]['Variables'][1]['Values'])); - $this->assertEqual(1, count($sites[1]['Variables'][1]['Values'])); - // Here we see that the Values collection of the *same* Variable object can have - // different contents when hydrating arrays - $this->assertEqual('val1 dom1 var1', $sites[0]['Variables'][0]['Values'][0]['varvalue_value']); - $this->assertEqual('val3 dom2 var1', $sites[1]['Variables'][0]['Values'][0]['varvalue_value']); - // Here we see that the Values collection of the *same* Variable object can have - // different contents when hydrating arrays - $this->assertEqual('val2 dom1 var2', $sites[0]['Variables'][1]['Values'][0]['varvalue_value']); - $this->assertEqual('val4 dom2 var2', $sites[1]['Variables'][1]['Values'][0]['varvalue_value']); - - $this->assertEqual('var1', $sites[0]['Variables'][0]['variable_name']); - $this->assertEqual('var1', $sites[1]['Variables'][0]['variable_name']); - - $this->assertEqual('var2', $sites[0]['Variables'][1]['variable_name']); - $this->assertEqual('var2', $sites[1]['Variables'][1]['variable_name']); - - } - + public function prepareTables() + { + $this->tables = array('Site', 'Variable', 'SiteVarvalue'); + parent::prepareTables(); + } + + public function prepareData() + { + $site = new Site(); + $site->site_id = 1; + $site->site_domain = 'site1'; + $site->save(); + + $site = new Site(); + $site->site_id = 2; + $site->site_domain = 'site2'; + $site->save(); + + $var = new Variable(); + $var->variable_id = 1; + $var->variable_name = 'var1'; + $var->save(); + + $var = new Variable(); + $var->variable_id = 2; + $var->variable_name = 'var2'; + $var->save(); + + $varval = new SiteVarvalue(); + $varval->site_id = 1; + $varval->variable_id = 1; + $varval->varvalue_value = 'val1 dom1 var1'; + $varval->save(); + + $varval = new SiteVarvalue(); + $varval->site_id = 1; + $varval->variable_id = 2; + $varval->varvalue_value = 'val2 dom1 var2'; + $varval->save(); + + $varval = new SiteVarvalue(); + $varval->site_id = 2; + $varval->variable_id = 1; + $varval->varvalue_value = 'val3 dom2 var1'; + $varval->save(); + + $varval = new SiteVarvalue(); + $varval->site_id = 2; + $varval->variable_id = 2; + $varval->varvalue_value = 'val4 dom2 var2'; + $varval->save(); + } + + public function testTicket() + { + $query = new Doctrine_Query(); + $query = $query->from('Site s LEFT JOIN s.Variables v LEFT JOIN v.Values vv WITH vv.site_id = s.site_id'); + + $sites = $query->execute(); + + $this->assertEqual('site1', $sites[0]->site_domain); + $this->assertEqual(2, count($sites)); + + // this is important for the understanding of the behavior + $this->assertIdentical($sites[0]->Variables[0], $sites[1]->Variables[0]); + $this->assertIdentical($sites[0]->Variables[1], $sites[1]->Variables[1]); + $this->assertEqual(2, count($sites[0]->Variables[0]->Values)); + $this->assertEqual(2, count($sites[1]->Variables[0]->Values)); + $this->assertEqual(2, count($sites[0]->Variables[1]->Values)); + $this->assertEqual(2, count($sites[1]->Variables[1]->Values)); + // Here we see that there can be only one Values on each Variable object. Hence + // they end up with 2 objects each. + $this->assertEqual('val1 dom1 var1', $sites[0]->Variables[0]->Values[0]->varvalue_value); + $this->assertEqual('val3 dom2 var1', $sites[0]->Variables[0]->Values[1]->varvalue_value); + $this->assertEqual('val2 dom1 var2', $sites[0]->Variables[1]->Values[0]->varvalue_value); + $this->assertEqual('val4 dom2 var2', $sites[0]->Variables[1]->Values[1]->varvalue_value); + + $this->assertEqual('var1', $sites[0]->Variables[0]->variable_name); + $this->assertEqual('var1', $sites[1]->Variables[0]->variable_name); + + $this->assertEqual('var2', $sites[0]->Variables[1]->variable_name); + $this->assertEqual('var2', $sites[1]->Variables[1]->variable_name); + + // now array hydration + + $sites = $query->fetchArray(); + + $this->assertEqual('site1', $sites[0]['site_domain']); + $this->assertEqual('site2', $sites[1]['site_domain']); + $this->assertEqual(2, count($sites)); + + // this is important for the understanding of the behavior + $this->assertEqual(1, count($sites[0]['Variables'][0]['Values'])); + $this->assertEqual(1, count($sites[1]['Variables'][0]['Values'])); + $this->assertEqual(1, count($sites[0]['Variables'][1]['Values'])); + $this->assertEqual(1, count($sites[1]['Variables'][1]['Values'])); + // Here we see that the Values collection of the *same* Variable object can have + // different contents when hydrating arrays + $this->assertEqual('val1 dom1 var1', $sites[0]['Variables'][0]['Values'][0]['varvalue_value']); + $this->assertEqual('val3 dom2 var1', $sites[1]['Variables'][0]['Values'][0]['varvalue_value']); + // Here we see that the Values collection of the *same* Variable object can have + // different contents when hydrating arrays + $this->assertEqual('val2 dom1 var2', $sites[0]['Variables'][1]['Values'][0]['varvalue_value']); + $this->assertEqual('val4 dom2 var2', $sites[1]['Variables'][1]['Values'][0]['varvalue_value']); + + $this->assertEqual('var1', $sites[0]['Variables'][0]['variable_name']); + $this->assertEqual('var1', $sites[1]['Variables'][0]['variable_name']); + + $this->assertEqual('var2', $sites[0]['Variables'][1]['variable_name']); + $this->assertEqual('var2', $sites[1]['Variables'][1]['variable_name']); + } } abstract class BaseSite extends Doctrine_Record { - - public function setTableDefinition() - { - $this->setTableName('_site'); - $this->hasColumn('site_id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('site_domain', 'string', 255, array('notnull' => true)); - } - - public function setUp() - { - parent::setUp(); - $this->hasMany('Variable as Variables', array('refClass' => 'SiteVarvalue', - 'local' => 'site_id', - 'foreign' => 'variable_id')); - } - + public function setTableDefinition() + { + $this->setTableName('_site'); + $this->hasColumn('site_id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('site_domain', 'string', 255, array('notnull' => true)); + } + + public function setUp() + { + parent::setUp(); + $this->hasMany('Variable as Variables', array('refClass' => 'SiteVarvalue', + 'local' => 'site_id', + 'foreign' => 'variable_id')); + } } abstract class BaseVariable extends Doctrine_Record { - - public function setTableDefinition() - { - $this->setTableName('_variable'); - $this->hasColumn('variable_id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('variable_name', 'string', 100, array('notnull' => true)); - } - - public function setUp() - { - parent::setUp(); - $this->hasMany('Site as Sites', array('refClass' => 'SiteVarvalue', - 'local' => 'variable_id', - 'foreign' => 'site_id')); - - $this->hasMany('SiteVarvalue as Values', array('local' => 'variable_id', - 'foreign' => 'variable_id')); - } - + public function setTableDefinition() + { + $this->setTableName('_variable'); + $this->hasColumn('variable_id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('variable_name', 'string', 100, array('notnull' => true)); + } + + public function setUp() + { + parent::setUp(); + $this->hasMany('Site as Sites', array('refClass' => 'SiteVarvalue', + 'local' => 'variable_id', + 'foreign' => 'site_id')); + + $this->hasMany('SiteVarvalue as Values', array('local' => 'variable_id', + 'foreign' => 'variable_id')); + } } abstract class BaseSiteVarvalue extends Doctrine_Record { - - public function setTableDefinition() - { - $this->setTableName('_site_varvalue'); - $this->hasColumn('varvalue_id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('site_id', 'integer', 4, array('notnull' => true)); - $this->hasColumn('variable_id', 'integer', 4, array('notnull' => true)); - $this->hasColumn('varvalue_value', 'string', null, array('notnull' => true)); - } - - public function setUp() - { - parent::setUp(); - $this->hasOne('Variable as Variables', array('local' => 'variable_id', - 'foreign' => 'variable_id')); - } - + public function setTableDefinition() + { + $this->setTableName('_site_varvalue'); + $this->hasColumn('varvalue_id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('site_id', 'integer', 4, array('notnull' => true)); + $this->hasColumn('variable_id', 'integer', 4, array('notnull' => true)); + $this->hasColumn('varvalue_value', 'string', null, array('notnull' => true)); + } + + public function setUp() + { + parent::setUp(); + $this->hasOne('Variable as Variables', array('local' => 'variable_id', + 'foreign' => 'variable_id')); + } } class Site extends BaseSite { diff --git a/tests/Ticket/950TestCase.php b/tests/Ticket/950TestCase.php index fdafb9867..8b8ef61b0 100755 --- a/tests/Ticket/950TestCase.php +++ b/tests/Ticket/950TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_950_TestCase + * Doctrine_Ticket_950_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_950_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_950_TestCase extends Doctrine_UnitTestCase { public function testInit() { @@ -40,7 +46,7 @@ public function testInit() public function testTest() { - $sql = $this->conn->export->exportClassesSql(array('Ticket_950_AdresseRecord','Ticket_950_CountryRecord')); + $sql = $this->conn->export->exportClassesSql(array('Ticket_950_AdresseRecord', 'Ticket_950_CountryRecord')); $this->assertEqual(count($sql), 3); $this->assertEqual($sql[0], 'CREATE TABLE country_record (id BIGINT NOT NULL AUTO_INCREMENT, iso VARCHAR(2) NOT NULL, name VARCHAR(80), printable_name VARCHAR(80), iso3 VARCHAR(3), numcode BIGINT, INDEX iso_idx (iso), PRIMARY KEY(id)) ENGINE = INNODB'); $this->assertEqual($sql[1], 'CREATE TABLE adresse_record (id BIGINT NOT NULL AUTO_INCREMENT, adresse VARCHAR(255), cp VARCHAR(60), ville VARCHAR(255), pays VARCHAR(2), INDEX pays_idx (pays), PRIMARY KEY(id)) ENGINE = INNODB'); @@ -50,39 +56,39 @@ public function testTest() class Ticket_950_AdresseRecord extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('adresse_record'); - $this->hasColumn('id', 'integer', 20, array('notnull' => true, - 'primary' => true, - 'autoincrement' => true)); + public function setTableDefinition() + { + $this->setTableName('adresse_record'); + $this->hasColumn('id', 'integer', 20, array('notnull' => true, + 'primary' => true, + 'autoincrement' => true)); - $this->hasColumn('adresse', 'string', 255); - $this->hasColumn('cp', 'string', 60); - $this->hasColumn('ville', 'string', 255); - $this->hasColumn('pays', 'string', 2); - } + $this->hasColumn('adresse', 'string', 255); + $this->hasColumn('cp', 'string', 60); + $this->hasColumn('ville', 'string', 255); + $this->hasColumn('pays', 'string', 2); + } - public function setUp() - { - $this->hasOne('Ticket_950_CountryRecord as Country', array('local' => 'pays', 'foreign' => 'iso')); - } + public function setUp() + { + $this->hasOne('Ticket_950_CountryRecord as Country', array('local' => 'pays', 'foreign' => 'iso')); + } } class Ticket_950_CountryRecord extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('country_record'); - $this->hasColumn('id', 'integer', 11, array('notnull' => true, - 'primary' => true, - 'autoincrement' => true)); + public function setTableDefinition() + { + $this->setTableName('country_record'); + $this->hasColumn('id', 'integer', 11, array('notnull' => true, + 'primary' => true, + 'autoincrement' => true)); - $this->hasColumn('iso', 'string', 2, array('notnull' => true)); + $this->hasColumn('iso', 'string', 2, array('notnull' => true)); - $this->hasColumn('name', 'string', 80); - $this->hasColumn('printable_name', 'string', 80); - $this->hasColumn('iso3', 'string', 3); - $this->hasColumn('numcode', 'integer', 10); - } -} \ No newline at end of file + $this->hasColumn('name', 'string', 80); + $this->hasColumn('printable_name', 'string', 80); + $this->hasColumn('iso3', 'string', 3); + $this->hasColumn('numcode', 'integer', 10); + } +} diff --git a/tests/Ticket/952TestCase.php b/tests/Ticket/952TestCase.php index 7b9c220ca..65c861921 100644 --- a/tests/Ticket/952TestCase.php +++ b/tests/Ticket/952TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_952_TestCase + * Doctrine_Ticket_952_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_952_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_952_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -52,8 +58,9 @@ public function testTest() Doctrine_Manager::connection()->setListener($profiler); $q = Doctrine_Query::create() - ->from('Ticket_952_Parent p') - ->leftJoin('p.Children c'); + ->from('Ticket_952_Parent p') + ->leftJoin('p.Children c') + ; $parents = $q->execute(); $this->assertEqual($parents[0]['Children'][0]['Parent']->name, 'Parent'); // Invoked additional queries $this->assertEqual($profiler->count(), 1); @@ -85,4 +92,4 @@ public function setUp() { $this->hasOne('Ticket_952_Parent as Parent', array('local' => 'parent_id', 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/963TestCase.php b/tests/Ticket/963TestCase.php index 88902e872..877ccdd36 100644 --- a/tests/Ticket/963TestCase.php +++ b/tests/Ticket/963TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_963_TestCase + * Doctrine_Ticket_963_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_963_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_963_TestCase extends Doctrine_UnitTestCase { public function testInit() { @@ -44,39 +50,39 @@ public function testExportSql() $this->assertEqual(count($sql), 3); $this->assertEqual($sql[0], 'CREATE TABLE ticket_963__user (id BIGINT AUTO_INCREMENT, username VARCHAR(255), password VARCHAR(255), PRIMARY KEY(id)) ENGINE = INNODB'); $this->assertEqual($sql[1], 'CREATE TABLE ticket_963__email (user_id INT, address2 VARCHAR(255), PRIMARY KEY(user_id)) ENGINE = INNODB'); - $this->assertEqual($test = isset($sql[2]) ? $sql[2]:null, 'ALTER TABLE ticket_963__email ADD CONSTRAINT ticket_963__email_user_id_ticket_963__user_id FOREIGN KEY (user_id) REFERENCES ticket_963__user(id) ON DELETE CASCADE'); + $this->assertEqual($test = isset($sql[2]) ? $sql[2] : null, 'ALTER TABLE ticket_963__email ADD CONSTRAINT ticket_963__email_user_id_ticket_963__user_id FOREIGN KEY (user_id) REFERENCES ticket_963__user(id) ON DELETE CASCADE'); } } class Ticket_963_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('username', 'string', 255); - $this->hasColumn('password', 'string', 255); - } + public function setTableDefinition() + { + $this->hasColumn('username', 'string', 255); + $this->hasColumn('password', 'string', 255); + } - public function setUp() - { - $this->hasOne('Ticket_963_Email as Email', array('local' => 'id', - 'foreign' => 'user_id')); - } + public function setUp() + { + $this->hasOne('Ticket_963_Email as Email', array('local' => 'id', + 'foreign' => 'user_id')); + } } class Ticket_963_Email extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('user_id', 'integer', 4, array('primary' => true)); - $this->hasColumn('address2', 'string', 255); - } + public function setTableDefinition() + { + $this->hasColumn('user_id', 'integer', 4, array('primary' => true)); + $this->hasColumn('address2', 'string', 255); + } - public function setUp() - { - $this->hasOne('Ticket_963_User as User', array( - 'local' => 'user_id', - 'foreign' => 'id', - 'owningSide' => true, - 'onDelete' => 'CASCADE')); - } -} \ No newline at end of file + public function setUp() + { + $this->hasOne('Ticket_963_User as User', array( + 'local' => 'user_id', + 'foreign' => 'id', + 'owningSide' => true, + 'onDelete' => 'CASCADE')); + } +} diff --git a/tests/Ticket/966TestCase.php b/tests/Ticket/966TestCase.php index 2a1d56de2..c8551523b 100644 --- a/tests/Ticket/966TestCase.php +++ b/tests/Ticket/966TestCase.php @@ -2,193 +2,185 @@ /** * @author Donald Ball + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_966_TestCase extends Doctrine_UnitTestCase { + public function prepareTables() + { + $this->tables = array('Semester', 'Course', 'Weekday', 'CourseWeekday'); + parent::prepareTables(); + } - public function prepareTables() - { - $this->tables = array('Semester', 'Course', 'Weekday', 'CourseWeekday'); - parent::prepareTables(); - } + public function prepareData() + { + $semester = new Semester(); + $semester['name'] = 'Semester'; + $semester->save(); + + foreach (array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') as $name) { + $weekday = new Weekday(); + $weekday['name'] = $name; + $weekday->save(); + } - public function prepareData() - { - $semester = new Semester(); - $semester['name'] = 'Semester'; - $semester->save(); + for ($i = 0; $i < 3; ++$i) { + $course = new Course(); + $course['name'] = 'Course '.$i; + $course['Semester'] = $semester; + $course->save(); + for ($w = 3; $w < 6; ++$w) { + $cw = new CourseWeekday(); + $cw['Course'] = $course; + $cw['weekday_id'] = $w; + $cw->save(); + } + } + } - foreach (array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday') as $name) + public function testArrayHydration() { - $weekday = new Weekday(); - $weekday['name'] = $name; - $weekday->save(); + $query = Doctrine_Query::create() + ->from('Semester s') + ->leftJoin('s.Courses c') + ->leftJoin('c.Weekdays cw') + ; + + $semesters = $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + $semester = $semesters[0]; + + $this->assertAllWeekdaysArePopulated($semester); } - for ($i=0; $i<3; $i++) + public function testObjectHydration() { - $course = new Course(); - $course['name'] = 'Course ' . $i; - $course['Semester'] = $semester; - $course->save(); - for ($w = 3; $w <6; $w++) - { - $cw = new CourseWeekday(); - $cw['Course'] = $course; - $cw['weekday_id'] = $w; - $cw->save(); - } - } - } - - public function testArrayHydration() - { - $query = Doctrine_Query::create() - ->from('Semester s') - ->leftJoin('s.Courses c') - ->leftJoin('c.Weekdays cw'); - - $semesters = $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - $semester = $semesters[0]; - - $this->assertAllWeekdaysArePopulated($semester); - } - - public function testObjectHydration() - { - $query = Doctrine_Query::create() - ->from('Semester s') - ->leftJoin('s.Courses c') - ->leftJoin('c.Weekdays cw'); - - $semester = $query->execute()->getFirst(); - - $weekdayOids = array(); - foreach ($semester->Courses as $course) { - foreach ($course->Weekdays as $weekday) { - if ( ! in_array($weekday->getOid(), $weekdayOids)) { - $weekdayOids[] = $weekday->getOid(); + $query = Doctrine_Query::create() + ->from('Semester s') + ->leftJoin('s.Courses c') + ->leftJoin('c.Weekdays cw') + ; + + $semester = $query->execute()->getFirst(); + + $weekdayOids = array(); + foreach ($semester->Courses as $course) { + foreach ($course->Weekdays as $weekday) { + if (!in_array($weekday->getOid(), $weekdayOids)) { + $weekdayOids[] = $weekday->getOid(); + } + $this->assertTrue(is_numeric($weekday->id)); + $this->assertTrue(is_string($weekday->name)); } - $this->assertTrue(is_numeric($weekday->id)); - $this->assertTrue(is_string($weekday->name)); } + // should be only 3 weekday objects in total + $this->assertEqual(3, count($weekdayOids)); + + $queryCountBefore = $this->conn->count(); + $this->assertAllWeekdaysArePopulated($semester); + $this->assertEqual($queryCountBefore, $this->conn->count()); } - // should be only 3 weekday objects in total - $this->assertEqual(3, count($weekdayOids)); - - $queryCountBefore = $this->conn->count(); - $this->assertAllWeekdaysArePopulated($semester); - $this->assertEqual($queryCountBefore, $this->conn->count()); - } - - public function testLazyObjectHydration() - { - // clear identity maps to make sure we're starting with a clean plate - $this->conn->getTable('Course')->clear(); - $this->conn->getTable('Weekday')->clear(); - $this->conn->getTable('Semester')->clear(); - $query = Doctrine_Query::create()->from('Semester s'); - - $semester = $query->execute()->getFirst(); - $queryCountBefore = $this->conn->count(); - $this->assertAllWeekdaysArePopulated($semester); - // expecting 4 additional queries: 1 to fetch the courses for the only semester and - // 1 for each weekday collection for each of the three courses. - $this->assertEqual($queryCountBefore + 4, $this->conn->count()); - } - - private function assertAllWeekdaysArePopulated($semester) - { - foreach ($semester['Courses'] as $course) + + public function testLazyObjectHydration() { - foreach ($course['Weekdays'] as $weekday) - { - $this->assertTrue(is_numeric($weekday['id'])); - $this->assertTrue(is_string($weekday['name'])); - } + // clear identity maps to make sure we're starting with a clean plate + $this->conn->getTable('Course')->clear(); + $this->conn->getTable('Weekday')->clear(); + $this->conn->getTable('Semester')->clear(); + $query = Doctrine_Query::create()->from('Semester s'); + + $semester = $query->execute()->getFirst(); + $queryCountBefore = $this->conn->count(); + $this->assertAllWeekdaysArePopulated($semester); + // expecting 4 additional queries: 1 to fetch the courses for the only semester and + // 1 for each weekday collection for each of the three courses. + $this->assertEqual($queryCountBefore + 4, $this->conn->count()); } - } + private function assertAllWeekdaysArePopulated($semester) + { + foreach ($semester['Courses'] as $course) { + foreach ($course['Weekdays'] as $weekday) { + $this->assertTrue(is_numeric($weekday['id'])); + $this->assertTrue(is_string($weekday['name'])); + } + } + } } class Semester extends Doctrine_Record { + public function setTableDefinition() + { + $this->setTableName('semester'); + $this->hasColumn('id', 'integer', 4, array('primary' => 'true', 'autoincrement' => 'true')); + $this->hasColumn('name', 'string', 255, array('notnull' => true)); + } - public function setTableDefinition() - { - $this->setTableName('semester'); - $this->hasColumn('id', 'integer', 4, array('primary'=>'true', 'autoincrement'=>'true')); - $this->hasColumn('name', 'string', 255, array('notnull' => true)); - } - - public function setUp() - { - parent::setUp(); - $this->hasMany('Course as Courses', array('local'=>'id', 'foreign'=>'semester_id')); - } - + public function setUp() + { + parent::setUp(); + $this->hasMany('Course as Courses', array('local' => 'id', 'foreign' => 'semester_id')); + } } class Weekday extends Doctrine_Record { + public function setTableDefinition() + { + $this->setTableName('weekday'); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 9, array('notnull' => true, 'unique' => true)); + } - public function setTableDefinition() - { - $this->setTableName('weekday'); - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('name', 'string', 9, array('notnull' => true, 'unique' => true)); - } - - public function setUp() - { - // need to make the many-many bidirectional in order for the lazy-loading test to work. - // lazy-loading the weekdays ($course['Weekdays']) doesnt work when the relation is - // set up unidirectional. this is true for all many-many relations. - $this->hasMany('Course as courses', - array('refClass'=>'CourseWeekday', 'local'=>'weekday_id', 'foreign'=>'course_id')); - } + public function setUp() + { + // need to make the many-many bidirectional in order for the lazy-loading test to work. + // lazy-loading the weekdays ($course['Weekdays']) doesnt work when the relation is + // set up unidirectional. this is true for all many-many relations. + $this->hasMany('Course as courses', + array('refClass' => 'CourseWeekday', 'local' => 'weekday_id', 'foreign' => 'course_id')); + } } class Course extends Doctrine_Record { + public function setTableDefinition() + { + $this->setTableName('course'); + $this->hasColumn('id', 'integer', 4, array('primary' => 'true', 'autoincrement' => 'true')); + $this->hasColumn('semester_id', 'integer', 4, array('notnull' => true)); + $this->hasColumn('name', 'string', 255, array('notnull' => true)); + } - public function setTableDefinition() - { - $this->setTableName('course'); - $this->hasColumn('id', 'integer', 4, array('primary'=>'true', 'autoincrement'=>'true')); - $this->hasColumn('semester_id', 'integer', 4, array('notnull'=>true)); - $this->hasColumn('name', 'string', 255, array('notnull' => true)); - } - - public function setUp() - { - parent::setUp(); - $this->hasOne('Semester', array('local' => 'semester_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); - $this->hasMany('Weekday as Weekdays', - array('refClass'=>'CourseWeekday', 'local'=>'course_id', 'foreign'=>'weekday_id')); - } - + public function setUp() + { + parent::setUp(); + $this->hasOne('Semester', array('local' => 'semester_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); + $this->hasMany('Weekday as Weekdays', + array('refClass' => 'CourseWeekday', 'local' => 'course_id', 'foreign' => 'weekday_id')); + } } class CourseWeekday extends Doctrine_Record { + public function setTableDefinition() + { + $this->setTableName('course_weekday'); + // Poor form to have an id on a join table, but that's what we were doing + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('course_id', 'integer', 4, array('notnull' => true)); + $this->hasColumn('weekday_id', 'integer', 4, array('notnull' => true)); + } - public function setTableDefinition() - { - $this->setTableName('course_weekday'); - # Poor form to have an id on a join table, but that's what we were doing - $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); - $this->hasColumn('course_id', 'integer', 4, array('notnull' => true)); - $this->hasColumn('weekday_id', 'integer', 4, array('notnull' => true)); - } - - public function setUp() - { - parent::setUp(); - $this->hasOne('Course', array('local'=>'course_id', 'foreign'=>'id', 'onDelete'=>'CASCADE')); - $this->hasOne('Weekday', array('local'=>'weekday_id', 'foreign'=>'id', 'onDelete'=>'CASCADE')); - } - + public function setUp() + { + parent::setUp(); + $this->hasOne('Course', array('local' => 'course_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + $this->hasOne('Weekday', array('local' => 'weekday_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } } diff --git a/tests/Ticket/969TestCase.php b/tests/Ticket/969TestCase.php index fa639f56e..6947f1053 100644 --- a/tests/Ticket/969TestCase.php +++ b/tests/Ticket/969TestCase.php @@ -20,137 +20,127 @@ */ /** - * Doctrine_Ticket_969_TestCase + * Doctrine_Ticket_969_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_969_TestCase extends Doctrine_UnitTestCase { - +class Doctrine_Ticket_969_TestCase extends Doctrine_UnitTestCase +{ public function prepareData() { - $d = new T1(); - $d->t1_id = 1; - $d->t2_id = 1; - $d->save(); - - $d = new T2(); - $d->t2_id = 1; - $d->hello_id = 10; - $d->save(); - - for ($i = 0; $i < 10; $i++) - { - $t3 = new T3(); - $t3->hello_id = 10; - $t3->save(); - } + $d = new T1(); + $d->t1_id = 1; + $d->t2_id = 1; + $d->save(); + + $d = new T2(); + $d->t2_id = 1; + $d->hello_id = 10; + $d->save(); + + for ($i = 0; $i < 10; ++$i) { + $t3 = new T3(); + $t3->hello_id = 10; + $t3->save(); + } } - public function prepareTables() { - $this->tables = array(); - $this->tables[] = 'T1'; - $this->tables[] = 'T2'; - $this->tables[] = 'T3'; - - parent::prepareTables(); + public function prepareTables() + { + $this->tables = array(); + $this->tables[] = 'T1'; + $this->tables[] = 'T2'; + $this->tables[] = 'T3'; + + parent::prepareTables(); } public function testTicket() { - $q = new Doctrine_Query; - $result = $q->select('a.*, b.*, c.*') - ->from('T1 a') - ->leftJoin('a.T2 b') - ->leftJoin('b.T3 c') - ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) - ->fetchOne(); - - // there are 10 rows in T3, and they all have hello_id = 10, so we should have 10 rows here - $this->assertEqual(10, count($result["T2"]["T3"])); - - // now with object hydration. - $q = new Doctrine_Query; - $result = $q->select('a.*, b.*, c.*') - ->from('T1 a') - ->leftJoin('a.T2 b') - ->leftJoin('b.T3 c') - ->fetchOne(); - - // test that no additional queries are executed when accessing the relations (lazy-loading). - $queryCountBefore = $this->conn->count(); - // there are 10 rows in T3, and they all have hello_id = 10, so we should have 10 rows here - $this->assertEqual(10, count($result["T2"]["T3"])); - $this->assertEqual($queryCountBefore, $this->conn->count()); + $q = new Doctrine_Query(); + $result = $q->select('a.*, b.*, c.*') + ->from('T1 a') + ->leftJoin('a.T2 b') + ->leftJoin('b.T3 c') + ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) + ->fetchOne() + ; + + // there are 10 rows in T3, and they all have hello_id = 10, so we should have 10 rows here + $this->assertEqual(10, count($result['T2']['T3'])); + + // now with object hydration. + $q = new Doctrine_Query(); + $result = $q->select('a.*, b.*, c.*') + ->from('T1 a') + ->leftJoin('a.T2 b') + ->leftJoin('b.T3 c') + ->fetchOne() + ; + + // test that no additional queries are executed when accessing the relations (lazy-loading). + $queryCountBefore = $this->conn->count(); + // there are 10 rows in T3, and they all have hello_id = 10, so we should have 10 rows here + $this->assertEqual(10, count($result['T2']['T3'])); + $this->assertEqual($queryCountBefore, $this->conn->count()); } } class T1 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('t1'); - $this->hasColumn('t1_id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); - $this->hasColumn('t2_id', 'integer', 3); - } + public function setTableDefinition() + { + $this->setTableName('t1'); + $this->hasColumn('t1_id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); + $this->hasColumn('t2_id', 'integer', 3); + } - public function setUp() - { - parent :: setUp(); - $this->hasOne('T2', array('local' => 't2_id', 'foreign' => 't2_id')); - } + public function setUp() + { + parent::setUp(); + $this->hasOne('T2', array('local' => 't2_id', 'foreign' => 't2_id')); + } } class T2 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('t2'); - $this->hasColumn('t2_id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); - $this->hasColumn('hello_id', 'integer', 3); - } + public function setTableDefinition() + { + $this->setTableName('t2'); + $this->hasColumn('t2_id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); + $this->hasColumn('hello_id', 'integer', 3); + } - public function setUp() - { - parent :: setUp(); - $this->hasMany('T3', array('local' => 'hello_id', 'foreign' => 'hello_id')); - } + public function setUp() + { + parent::setUp(); + $this->hasMany('T3', array('local' => 'hello_id', 'foreign' => 'hello_id')); + } } class T3 extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('t3'); - $this->hasColumn('t3_id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); - $this->hasColumn('hello_id', 'integer', 3); - } + public function setTableDefinition() + { + $this->setTableName('t3'); + $this->hasColumn('t3_id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); + $this->hasColumn('hello_id', 'integer', 3); + } - public function setUp() - { - parent :: setUp(); - } + public function setUp() + { + parent::setUp(); + } } - - - - - - - - - - - - - - - - - - diff --git a/tests/Ticket/973TestCase.php b/tests/Ticket/973TestCase.php index 231d44084..a6188aeb2 100755 --- a/tests/Ticket/973TestCase.php +++ b/tests/Ticket/973TestCase.php @@ -20,33 +20,42 @@ */ /** - * Doctrine_Ticket_973_TestCase + * Doctrine_Ticket_973_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_973_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() { + public function prepareTables() + { $this->tables = array(); $this->tables[] = 'T973_Day'; parent::prepareTables(); } - public function prepareData() {} - + public function prepareData() + { + } public function testTicket() { - $query = Doctrine_Query::create() - ->from('T973_Day d') - ->where('d.id IN(46)'); + $query = Doctrine_Query::create() + ->from('T973_Day d') + ->where('d.id IN(46)') + ; $this->assertEqual(' FROM T973_Day d WHERE d.id IN(46)', $query->getDql()); $this->assertEqual($query->getSqlQuery(), 'SELECT t.id AS t__id, t.number AS t__number FROM t973_days t WHERE (d.id IN(46))'); } @@ -60,4 +69,4 @@ public function setTableDefinition() $this->hasColumn('id', 'integer', 3, array('autoincrement' => true, 'unsigned' => true, 'primary' => true, 'notnull' => true)); $this->hasColumn('number', 'integer'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/982TestCase.php b/tests/Ticket/982TestCase.php index d541ccd11..87eed7d18 100644 --- a/tests/Ticket/982TestCase.php +++ b/tests/Ticket/982TestCase.php @@ -2,6 +2,11 @@ /* * Test to ensure LocalKey Relations allow 0 for id value */ +/** + * @internal + * + * @coversNothing + */ class Doctrine_Ticket_982_TestCase extends Doctrine_UnitTestCase { protected $myModelOne; @@ -10,60 +15,59 @@ class Doctrine_Ticket_982_TestCase extends Doctrine_UnitTestCase public function prepareTables() { $this->tables = array(); - $this->tables[] = "T982_MyModel"; + $this->tables[] = 'T982_MyModel'; parent::prepareTables(); } public function prepareData() { - $myModelZero = new T982_MyModel(); - $myModelZero->id = 0; - $myModelZero->parentid = 0; - $myModelZero->save(); - $this->assertIdentical(0, $myModelZero->id); - - $this->myModelOne = new T982_MyModel(); - $this->myModelOne->id = 1; - $this->myModelOne->parentid = 0; - $this->myModelOne->save(); - - $this->myModelTwo = new T982_MyModel(); - $this->myModelTwo->id = 2; - $this->myModelTwo->parentid = 1; - $this->myModelTwo->save(); + $myModelZero = new T982_MyModel(); + $myModelZero->id = 0; + $myModelZero->parentid = 0; + $myModelZero->save(); + $this->assertIdentical(0, $myModelZero->id); + + $this->myModelOne = new T982_MyModel(); + $this->myModelOne->id = 1; + $this->myModelOne->parentid = 0; + $this->myModelOne->save(); + + $this->myModelTwo = new T982_MyModel(); + $this->myModelTwo->id = 2; + $this->myModelTwo->parentid = 1; + $this->myModelTwo->save(); } public function testTicket() { $this->conn->getTable('T982_MyModel')->clear(); - + $myModelZero = $this->conn->getTable('T982_MyModel')->find(0); - - $this->assertIdentical($myModelZero->id, '0'); - $this->assertIdentical($myModelZero->parentid, '0'); - $this->assertTrue($myModelZero->parent->exists()); - $this->assertTrue(ctype_digit((string) $myModelZero->parent->id)); - $this->assertIdentical($myModelZero, $myModelZero->parent); - $this->assertIdentical($myModelZero->parent->id, '0'); - $this->assertIdentical($myModelZero->parent->parentid, '0'); - + + $this->assertIdentical($myModelZero->id, '0'); + $this->assertIdentical($myModelZero->parentid, '0'); + $this->assertTrue($myModelZero->parent->exists()); + $this->assertTrue(ctype_digit((string) $myModelZero->parent->id)); + $this->assertIdentical($myModelZero, $myModelZero->parent); + $this->assertIdentical($myModelZero->parent->id, '0'); + $this->assertIdentical($myModelZero->parent->parentid, '0'); + $myModelOne = $this->conn->getTable('T982_MyModel')->find(1); - + $this->assertIdentical($myModelOne->id, '1'); - $this->assertIdentical($myModelOne->parentid, '0'); - $this->assertTrue($myModelOne->parent->exists()); - $this->assertTrue(ctype_digit((string) $myModelOne->parent->id)); - $this->assertIdentical($myModelOne->parent->id, '0'); - $this->assertIdentical($myModelOne->parent->parentid, '0'); - - $myModelTwo = $this->conn->getTable('T982_MyModel')->find(2); + $this->assertIdentical($myModelOne->parentid, '0'); + $this->assertTrue($myModelOne->parent->exists()); + $this->assertTrue(ctype_digit((string) $myModelOne->parent->id)); + $this->assertIdentical($myModelOne->parent->id, '0'); + $this->assertIdentical($myModelOne->parent->parentid, '0'); + + $myModelTwo = $this->conn->getTable('T982_MyModel')->find(2); $this->assertIdentical($myModelTwo->id, '2'); - $this->assertIdentical($myModelTwo->parentid, '1'); - $this->assertIdentical($myModelTwo->parent->id, '1'); - $this->assertIdentical($myModelTwo->parent->parentid, '0'); - - } + $this->assertIdentical($myModelTwo->parentid, '1'); + $this->assertIdentical($myModelTwo->parent->id, '1'); + $this->assertIdentical($myModelTwo->parent->parentid, '0'); + } } class T982_MyModel extends Doctrine_Record @@ -78,5 +82,4 @@ public function setUp() { $this->hasOne('T982_MyModel as parent', array('local' => 'parentid', 'foreign' => 'id')); } - -} \ No newline at end of file +} diff --git a/tests/Ticket/987TestCase.php b/tests/Ticket/987TestCase.php index c1de260c3..a6b54920c 100644 --- a/tests/Ticket/987TestCase.php +++ b/tests/Ticket/987TestCase.php @@ -20,52 +20,58 @@ */ /** - * Doctrine_Ticket_987_TestCase + * Doctrine_Ticket_987_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_987_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_987_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { - $this->tables[] = 'Ticket_987_Person'; - parent::prepareTables(); - } + public function prepareTables() + { + $this->tables[] = 'Ticket_987_Person'; + parent::prepareTables(); + } - public function testTest() - { - $person = new Ticket_987_Person(); - $person->gender = 'male'; - $person->firstname = 'jon'; - $person->lastname = 'wage'; - $person->save(); + public function testTest() + { + $person = new Ticket_987_Person(); + $person->gender = 'male'; + $person->firstname = 'jon'; + $person->lastname = 'wage'; + $person->save(); - // creating the query - $q = Doctrine_Query::create(); - $q->from('Ticket_987_Person p'); + // creating the query + $q = Doctrine_Query::create(); + $q->from('Ticket_987_Person p'); - // creating the view - $view = new Doctrine_View($q, 'view_person2person_type'); - $view->create(); + // creating the view + $view = new Doctrine_View($q, 'view_person2person_type'); + $view->create(); - // creating the query - $q = Doctrine_Query::create(); - $q->from('Ticket_987_Person p'); + // creating the query + $q = Doctrine_Query::create(); + $q->from('Ticket_987_Person p'); - // creating view object for querying - $view = new Doctrine_View($q, 'view_person2person_type'); + // creating view object for querying + $view = new Doctrine_View($q, 'view_person2person_type'); - // executes view - $coll = $view->execute(); + // executes view + $coll = $view->execute(); - $this->assertEqual($coll->count(), 1); - } + $this->assertEqual($coll->count(), 1); + } } class Ticket_987_Person extends Doctrine_Record @@ -73,9 +79,9 @@ class Ticket_987_Person extends Doctrine_Record public function setTableDefinition() { $this->setTableName('person'); - $this->hasColumn('id', 'integer', 11, array('primary' => true, 'notnull' => true, 'autoincrement' => true) ); - $this->hasColumn('gender', 'integer', 1, array('notblank' => true, 'primary' => false, 'notnull' => true, 'autoincrement' => false) ); - $this->hasColumn('firstname', 'string', 30, array('notblank' => true, 'primary' => false, 'notnull' => true, 'autoincrement' => false) ); - $this->hasColumn('lastname', 'string', 30, array('notblank' => true, 'primary' => false, 'notnull' => true, 'autoincrement' => false) ); + $this->hasColumn('id', 'integer', 11, array('primary' => true, 'notnull' => true, 'autoincrement' => true)); + $this->hasColumn('gender', 'integer', 1, array('notblank' => true, 'primary' => false, 'notnull' => true, 'autoincrement' => false)); + $this->hasColumn('firstname', 'string', 30, array('notblank' => true, 'primary' => false, 'notnull' => true, 'autoincrement' => false)); + $this->hasColumn('lastname', 'string', 30, array('notblank' => true, 'primary' => false, 'notnull' => true, 'autoincrement' => false)); } -} \ No newline at end of file +} diff --git a/tests/Ticket/990TestCase.php b/tests/Ticket/990TestCase.php index 1d150f617..d0e165de7 100644 --- a/tests/Ticket/990TestCase.php +++ b/tests/Ticket/990TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_990_TestCase + * Doctrine_Ticket_990_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_990_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_990_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -39,15 +45,15 @@ public function prepareTables() } public function testOverwriteIdentityMap() - { + { $person = new Ticket_990_Person(); $person->firstname = 'John'; $person->save(); - + $person->firstname = 'Alice'; - + $person = Doctrine_Core::getTable('Ticket_990_Person')->find($person->id); - + $this->assertEqual('John', $person->firstname); } @@ -60,41 +66,40 @@ public function testDontOverwriteIdentityMap() $user = Doctrine_Core::getTable('User')->find($user->id); $this->assertEqual($user->name, 'test'); - $person = new Ticket_990_Person(); $person->firstname = 'John'; - $person->save(); - + $person->save(); + $person->firstname = 'Alice'; - + $this->assertEqual(Doctrine_Record::STATE_DIRTY, $person->state()); $this->assertTrue($person->isModified()); $this->assertEqual(array('firstname' => 'Alice'), $person->getModified()); - + $person = Doctrine_Core::getTable('Ticket_990_Person')->find($person->id); - + $this->assertEqual('Alice', $person->firstname); $this->assertEqual(Doctrine_Record::STATE_DIRTY, $person->state()); $this->assertTrue($person->isModified()); $this->assertEqual(array('firstname' => 'Alice'), $person->getModified()); - + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, true); } public function testRefreshAlwaysOverwrites() { Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, false); - + $person = new Ticket_990_Person(); $person->firstname = 'John'; $person->save(); - + $person->firstname = 'Alice'; - + $person->refresh(); - + $this->assertEqual('John', $person->firstname); - + Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, true); } } @@ -104,8 +109,8 @@ class Ticket_990_Person extends Doctrine_Record public function setTableDefinition() { $this->setTableName('person'); - $this->hasColumn('id', 'integer', 11, array('primary' => true, 'notnull' => true, 'autoincrement' => true) ); + $this->hasColumn('id', 'integer', 11, array('primary' => true, 'notnull' => true, 'autoincrement' => true)); $this->hasColumn('firstname', 'string'); $this->hasColumn('lastname', 'string'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/AyoubTestCase.php b/tests/Ticket/AyoubTestCase.php index ca1f6a5aa..f33f4e16d 100644 --- a/tests/Ticket/AyoubTestCase.php +++ b/tests/Ticket/AyoubTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_Ayoub_TestCase + * Doctrine_Ticket_Ayoub_TestCase. * - * @package Doctrine * @author pascal borreli * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_Ayoub_TestCase extends Doctrine_UnitTestCase { @@ -45,7 +51,7 @@ public function testTest() $placeName = 'Place Name'; try { - $sura = new Ticket_Ayoub_Sura; + $sura = new Ticket_Ayoub_Sura(); $sura->Translation['transliteration']->name = $name; $sura->Ticket_Ayoub_Place->Translation['transliteration']->name = $placeName; $sura->Ticket_Ayoub_Place->state('TDIRTY'); @@ -64,48 +70,48 @@ public function testTest() class Ticket_Ayoub_Sura extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('Ticket_Ayoub_Sura'); - $this->hasColumn('id', 'integer', null, array('type' => 'integer', 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('name', 'string', 255, array('type' => 'string', 'length' => '255')); - $this->hasColumn('revelation_order', 'integer', null, array('type' => 'integer')); - $this->hasColumn('is_mekka', 'boolean', null, array('type' => 'boolean')); - $this->hasColumn('ayat_number', 'integer', null, array('type' => 'integer')); - $this->hasColumn('place_id', 'integer', null, array('type' => 'integer')); + public function setTableDefinition() + { + $this->setTableName('Ticket_Ayoub_Sura'); + $this->hasColumn('id', 'integer', null, array('type' => 'integer', 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 255, array('type' => 'string', 'length' => '255')); + $this->hasColumn('revelation_order', 'integer', null, array('type' => 'integer')); + $this->hasColumn('is_mekka', 'boolean', null, array('type' => 'boolean')); + $this->hasColumn('ayat_number', 'integer', null, array('type' => 'integer')); + $this->hasColumn('place_id', 'integer', null, array('type' => 'integer')); - $this->option('collate', 'utf8_unicode_ci'); - $this->option('charset', 'utf8'); - } + $this->option('collate', 'utf8_unicode_ci'); + $this->option('charset', 'utf8'); + } - public function setUp() - { - $this->hasOne('Ticket_Ayoub_Place', array('local' => 'place_id', - 'foreign' => 'id')); + public function setUp() + { + $this->hasOne('Ticket_Ayoub_Place', array('local' => 'place_id', + 'foreign' => 'id')); - $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'name'), 'length' => '20')); - $this->actAs($i18n0); - } + $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'name'), 'length' => '20')); + $this->actAs($i18n0); + } } class Ticket_Ayoub_Place extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('Ticket_Ayoub_Place'); - $this->hasColumn('id', 'integer', null, array('type' => 'integer', 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('name', 'string', 255, array('type' => 'string', 'length' => '255')); + public function setTableDefinition() + { + $this->setTableName('Ticket_Ayoub_Place'); + $this->hasColumn('id', 'integer', null, array('type' => 'integer', 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 255, array('type' => 'string', 'length' => '255')); - $this->option('collate', 'utf8_unicode_ci'); - $this->option('charset', 'utf8'); - } + $this->option('collate', 'utf8_unicode_ci'); + $this->option('charset', 'utf8'); + } - public function setUp() - { - $this->hasMany('Ticket_Ayoub_Sura', array('local' => 'id', - 'foreign' => 'place_id')); + public function setUp() + { + $this->hasMany('Ticket_Ayoub_Sura', array('local' => 'id', + 'foreign' => 'place_id')); - $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'name'), 'length' => '20')); - $this->actAs($i18n0); - } -} \ No newline at end of file + $i18n0 = new Doctrine_Template_I18n(array('fields' => array(0 => 'name'), 'length' => '20')); + $this->actAs($i18n0); + } +} diff --git a/tests/Ticket/DC101TestCase.php b/tests/Ticket/DC101TestCase.php index ad4b700f1..566d17118 100644 --- a/tests/Ticket/DC101TestCase.php +++ b/tests/Ticket/DC101TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC101_TestCase + * Doctrine_Ticket_DC101_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC101_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC101_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -54,7 +60,7 @@ public function setUp() { $this->hasOne('Ticket_DC101_Profile as Profile', array( 'local' => 'id', - 'foreign' => 'user_id' + 'foreign' => 'user_id', )); } } @@ -72,7 +78,7 @@ public function setUp() $this->hasOne('Ticket_DC101_User as User', array( 'local' => 'user_id', 'foreign' => 'id', - 'foreignKeyName' => 'user_id_fk' + 'foreignKeyName' => 'user_id_fk', )); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC112TestCase.php b/tests/Ticket/DC112TestCase.php index b480cc839..699c365ad 100644 --- a/tests/Ticket/DC112TestCase.php +++ b/tests/Ticket/DC112TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_DDC47_TestCase + * Doctrine_Ticket_DDC47_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC112_TestCase extends Doctrine_UnitTestCase { @@ -38,7 +44,8 @@ public function testResultCacheSetHash() $q1 = Doctrine_Query::create() ->from('User u') - ->useResultCache($cacheDriver, 3600, 'test1'); + ->useResultCache($cacheDriver, 3600, 'test1') + ; $coll = $q1->execute(); @@ -52,7 +59,8 @@ public function testResultCacheSetHash() $q2 = Doctrine_Query::create() ->from('User u') - ->useResultCache($cacheDriver, 3600, 'test2'); + ->useResultCache($cacheDriver, 3600, 'test2') + ; $coll = $q2->execute(); $this->assertTrue($cacheDriver->contains('test1')); @@ -69,7 +77,8 @@ public function testResultCacheSetHash() $q = Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver) - ->setResultCacheHash('testing'); + ->setResultCacheHash('testing') + ; $coll = $q->execute(); $this->assertTrue($cacheDriver->contains('testing')); @@ -82,18 +91,20 @@ public function testResultCacheSetHash() public function testDeleteByRegex() { $cacheDriver = new Doctrine_Cache_Array(array( - 'prefix' => 'test_' + 'prefix' => 'test_', )); Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver, 3600, 'doctrine_query_one') - ->execute(); + ->execute() + ; Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver, 3600, 'doctrine_query_two') - ->execute(); + ->execute() + ; $count = $cacheDriver->deleteByRegex('/test_doctrine_query_.*/'); $this->assertEqual($count, 2); @@ -104,18 +115,20 @@ public function testDeleteByRegex() public function testDeleteByPrefix() { $cacheDriver = new Doctrine_Cache_Array(array( - 'prefix' => 'test_' + 'prefix' => 'test_', )); Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver, 3600, 'doctrine_query_one') - ->execute(); + ->execute() + ; Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver, 3600, 'doctrine_query_two') - ->execute(); + ->execute() + ; $count = $cacheDriver->deleteByPrefix('test_'); $this->assertEqual($count, 2); @@ -130,12 +143,14 @@ public function testDeleteBySuffix() Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver, 3600, 'one_query') - ->execute(); + ->execute() + ; Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver, 3600, 'two_query') - ->execute(); + ->execute() + ; $count = $cacheDriver->deleteBySuffix('_query'); $this->assertEqual($count, 2); @@ -150,12 +165,14 @@ public function testDeleteWithWildcard() Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver, 3600, 'user_query_one') - ->execute(); + ->execute() + ; Doctrine_Query::create() ->from('User u') ->useResultCache($cacheDriver, 3600, 'user_query_two') - ->execute(); + ->execute() + ; $count = $cacheDriver->delete('user_query_*'); $this->assertEqual($count, 2); diff --git a/tests/Ticket/DC136TestCase.php b/tests/Ticket/DC136TestCase.php index 9af22ea8d..c43d1a5e5 100644 --- a/tests/Ticket/DC136TestCase.php +++ b/tests/Ticket/DC136TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC136_TestCase + * Doctrine_Ticket_DC136_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC136_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC136_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -63,4 +69,4 @@ public function setTableDefinition() $this->hasColumn('username', 'string', 255); $this->hasColumn('password', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC141TestCase.php b/tests/Ticket/DC141TestCase.php index 7b1fe9543..093e49207 100644 --- a/tests/Ticket/DC141TestCase.php +++ b/tests/Ticket/DC141TestCase.php @@ -20,24 +20,31 @@ */ /** - * Doctrine_Ticket_DC141_TestCase + * Doctrine_Ticket_DC141_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC141_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC141_TestCase extends Doctrine_UnitTestCase { public function testTest() { $q = Doctrine_Core::getTable('User') ->createQuery('u') - ->where('u.name LIKE :name OR u.email_id = :email_id', array(':email_id' => 2, ':name' => '%zYne%')); + ->where('u.name LIKE :name OR u.email_id = :email_id', array(':email_id' => 2, ':name' => '%zYne%')) + ; $users = $q->fetchArray(); $this->assertEqual(count($users), 2); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC147TestCase.php b/tests/Ticket/DC147TestCase.php index 2b0eb5487..50848414b 100644 --- a/tests/Ticket/DC147TestCase.php +++ b/tests/Ticket/DC147TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC147_TestCase + * Doctrine_Ticket_DC147_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC147_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC147_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -43,7 +49,7 @@ public function prepareTables() public function testInlineMultiple() { - $yml = <<from('DC147_Product p, p.MultipleValues v, v.Multiple m') - ->where('p.name = ?', 'book3'); + ->where('p.name = ?', 'book3') + ; $product = $query->fetchOne(); @@ -90,7 +97,8 @@ public function testInlineMultiple() $query = new Doctrine_Query(); $query->from('DC147_Product p, p.MultipleValues v, v.Multiple m') - ->where('p.name = ?', 'book4'); + ->where('p.name = ?', 'book4') + ; $product = $query->fetchOne(); @@ -123,9 +131,9 @@ public function setTableDefinition() public function setUp() { $this->hasOne('DC147_Site as Site', array('local' => 'site_id', - 'foreign' => 'id')); + 'foreign' => 'id')); $this->hasMany('DC147_MultipleValue as MultipleValues', array('local' => 'id', - 'foreign' => 'product_id')); + 'foreign' => 'product_id')); } } class DC147_Site extends Doctrine_Record @@ -138,7 +146,7 @@ public function setTableDefinition() public function setUp() { $this->hasMany('DC147_Product as Products', array('local' => 'id', - 'foreign' => 'site_id')); + 'foreign' => 'site_id')); } } class DC147_Multiple extends Doctrine_Record @@ -151,7 +159,7 @@ public function setTableDefinition() public function setUp() { $this->hasMany('DC147_MultipleValue as MultipleValues', array('local' => 'id', - 'foreign' => 'multiple_id')); + 'foreign' => 'multiple_id')); } } class DC147_MultipleValue extends Doctrine_Record @@ -166,9 +174,9 @@ public function setTableDefinition() public function setUp() { $this->hasOne('DC147_Multiple as Multiple', array('local' => 'multiple_id', - 'foreign' => 'id')); + 'foreign' => 'id')); $this->hasOne('DC147_Product as Product', array('local' => 'product_id', - 'foreign' => 'id')); + 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC14TestCase.php b/tests/Ticket/DC14TestCase.php index 9d9bc1f1e..51f70844b 100644 --- a/tests/Ticket/DC14TestCase.php +++ b/tests/Ticket/DC14TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC14_TestCase + * Doctrine_Ticket_DC14_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC14_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC14_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -42,7 +48,8 @@ public function testTest() { $q = Doctrine_Core::getTable('Ticket_DC14_Search') ->createQuery('s') - ->where("? NOT BETWEEN s.date_from AND s.date_to", '1985-09-01 00:00:00'); + ->where('? NOT BETWEEN s.date_from AND s.date_to', '1985-09-01 00:00:00') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.name AS t__name, t.date_from AS t__date_from, t.date_to AS t__date_to FROM ticket__d_c14__search t WHERE (? NOT BETWEEN t.date_from AND t.date_to)'); } @@ -56,4 +63,4 @@ public function setTableDefinition() $this->hasColumn('date_from', 'timestamp'); $this->hasColumn('date_to', 'timestamp'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC169TestCase.php b/tests/Ticket/DC169TestCase.php index 16ef70375..7325f749c 100644 --- a/tests/Ticket/DC169TestCase.php +++ b/tests/Ticket/DC169TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC169_TestCase + * Doctrine_Ticket_DC169_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC169_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC169_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -74,10 +80,10 @@ public function setTableDefinition() public function setUp() { $this->actAs('Timestampable'); - + $this->hasOne('Ticket_DC169_Profile as Profile', array( 'local' => 'id', - 'foreign' => 'user_id' + 'foreign' => 'user_id', )); } } @@ -94,7 +100,7 @@ public function setUp() { $this->hasOne('Ticket_DC169_User as User', array( 'local' => 'user_id', - 'foreign' => 'id' + 'foreign' => 'id', )); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC171TestCase.php b/tests/Ticket/DC171TestCase.php index 27fece420..08d0384c9 100644 --- a/tests/Ticket/DC171TestCase.php +++ b/tests/Ticket/DC171TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC171_TestCase + * Doctrine_Ticket_DC171_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC171_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC171_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -66,4 +72,4 @@ public function setUp() { $this->actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC187TestCase.php b/tests/Ticket/DC187TestCase.php index efc02987e..8007b9886 100644 --- a/tests/Ticket/DC187TestCase.php +++ b/tests/Ticket/DC187TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC187_TestCase + * Doctrine_Ticket_DC187_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC187_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC187_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -85,7 +91,7 @@ public function setTableDefinition() $this->unique( array('username', 'email'), - array('where' => "deleted_at IS NULL"), + array('where' => 'deleted_at IS NULL'), false ); } @@ -94,4 +100,4 @@ public function setUp() { $this->actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC198TestCase.php b/tests/Ticket/DC198TestCase.php index 94a56687a..a51d24abe 100644 --- a/tests/Ticket/DC198TestCase.php +++ b/tests/Ticket/DC198TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_DC198_TestCase + * Doctrine_Ticket_DC198_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC198_TestCase extends Doctrine_UnitTestCase { @@ -46,7 +52,7 @@ public function prepareTables() { $this->tables[] = 'Ticket_DC198_User'; $this->tables[] = 'Ticket_DC198_Email'; - + parent::prepareTables(); } @@ -66,7 +72,6 @@ public function testRemoveEmail() $e = Doctrine_Query::create()->from('Ticket_DC198_Email')->fetchOne(); $this->assertFalse($e); } - } class Ticket_DC198_Email extends Doctrine_Record @@ -74,19 +79,19 @@ class Ticket_DC198_Email extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('user_id', 'integer', null, array( - 'type' => 'integer', - )); + 'type' => 'integer', + )); $this->hasColumn('address', 'string', 150, array( - 'type' => 'string', - 'length' => '150', - )); + 'type' => 'string', + 'length' => '150', + )); } public function setUp() { $this->hasOne('Ticket_DC198_User', array( - 'local' => 'user_id', - 'foreign' => 'id')); + 'local' => 'user_id', + 'foreign' => 'id')); } } @@ -95,15 +100,15 @@ class Ticket_DC198_User extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('name', 'string', 150, array( - 'type' => 'string', - 'length' => '150', - )); + 'type' => 'string', + 'length' => '150', + )); } public function setUp() { $this->hasOne('Ticket_DC198_Email as email', array( - 'local' => 'id', - 'foreign' => 'user_id')); + 'local' => 'id', + 'foreign' => 'user_id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC217TestCase.php b/tests/Ticket/DC217TestCase.php index 80408cca8..b18fe3dcc 100644 --- a/tests/Ticket/DC217TestCase.php +++ b/tests/Ticket/DC217TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC217_TestCase + * Doctrine_Ticket_DC217_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC217_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC217_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -42,7 +48,7 @@ public function testTest() { $o = new Ticket_DC217_Industry(); $o->name = 'test'; - //$o->parent_id = null; + // $o->parent_id = null; $o->save(); } } @@ -52,33 +58,33 @@ class Ticket_DC217_Industry extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('id', 'integer', 4, array( - 'type' => 'integer', - 'primary' => true, - 'autoincrement' => true, - 'length' => '4', - )); + 'type' => 'integer', + 'primary' => true, + 'autoincrement' => true, + 'length' => '4', + )); $this->hasColumn('parent_id', 'integer', 4, array( - 'type' => 'integer', - 'notnull' => false, - 'length' => '4', - )); + 'type' => 'integer', + 'notnull' => false, + 'length' => '4', + )); $this->hasColumn('name', 'string', 30, array( - 'type' => 'string', - 'notnull' => true, - 'length' => '30', - )); + 'type' => 'string', + 'notnull' => true, + 'length' => '30', + )); } public function setUp() { $this->hasOne('Ticket_DC217_Industry as ParentIndustry', array( - 'local' => 'parent_id', - 'foreign' => 'id')); + 'local' => 'parent_id', + 'foreign' => 'id')); $this->hasMany('Ticket_DC217_Industry as ChildIndustries', array( - 'local' => 'id', - 'foreign' => 'parent_id')); + 'local' => 'id', + 'foreign' => 'parent_id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC221/TestMigration.php b/tests/Ticket/DC221/TestMigration.php index 4bd0fa35d..66b665438 100644 --- a/tests/Ticket/DC221/TestMigration.php +++ b/tests/Ticket/DC221/TestMigration.php @@ -5,4 +5,4 @@ class TestMigration extends Doctrine_Migration_Base public function migrate($direction) { } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC221TestCase.php b/tests/Ticket/DC221TestCase.php index 6d7c8ca97..bcaee791d 100644 --- a/tests/Ticket/DC221TestCase.php +++ b/tests/Ticket/DC221TestCase.php @@ -20,22 +20,28 @@ */ /** - * Doctrine_Ticket_DC221_TestCase + * Doctrine_Ticket_DC221_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC221_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC221_TestCase extends Doctrine_UnitTestCase { public function testTest() { - $migration1 = new Doctrine_Migration(dirname(__FILE__) . '/DC221'); - $migration2 = new Doctrine_Migration(dirname(__FILE__) . '/DC221'); + $migration1 = new Doctrine_Migration(dirname(__FILE__).'/DC221'); + $migration2 = new Doctrine_Migration(dirname(__FILE__).'/DC221'); $this->assertEqual($migration1->getMigrationClasses(), $migration2->getMigrationClasses()); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC236TestCase.php b/tests/Ticket/DC236TestCase.php index 0f6f97fc6..aaf8d47d3 100644 --- a/tests/Ticket/DC236TestCase.php +++ b/tests/Ticket/DC236TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC236_TestCase + * Doctrine_Ticket_DC236_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC236_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC236_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -72,9 +78,9 @@ class Ticket_DC236_File extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('name', 'string', 255, array( - 'type' => 'string', - 'length' => '255', - )); + 'type' => 'string', + 'length' => '255', + )); } public function setUp() @@ -82,4 +88,4 @@ public function setUp() $nestedset0 = new Doctrine_Template_NestedSet(); $this->actAs($nestedset0); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC238TestCase.php b/tests/Ticket/DC238TestCase.php index 0a782d915..296022e17 100644 --- a/tests/Ticket/DC238TestCase.php +++ b/tests/Ticket/DC238TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_DC238_TestCase + * Doctrine_Ticket_DC238_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC238_TestCase extends Doctrine_UnitTestCase { @@ -48,7 +54,8 @@ public function testTest() $cacheDriver = new Doctrine_Cache_Array(); $q = Doctrine_Core::getTable('Ticket_DC238_User') ->createQuery('u') - ->useResultCache($cacheDriver, 3600, 'user_query'); + ->useResultCache($cacheDriver, 3600, 'user_query') + ; $this->assertEqual(0, $profiler->count()); @@ -71,4 +78,4 @@ public function setTableDefinition() $this->hasColumn('username', 'string', 255); $this->hasColumn('password', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC23TestCase.php b/tests/Ticket/DC23TestCase.php index 20de702d7..968825e04 100644 --- a/tests/Ticket/DC23TestCase.php +++ b/tests/Ticket/DC23TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC23_TestCase + * Doctrine_Ticket_DC23_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC23_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC23_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -45,7 +51,7 @@ public function prepareTables() public function testTest() { - $yml = <<from('Ticket_DC23_User u') ->leftJoin('u.Contact c') ->leftJoin('c.Phonenumbers p') - ->leftJoin('c.Address a'); + ->leftJoin('c.Address a') + ; $results = $q->fetchArray(); $this->assertTrue(isset($results[0]['Contact']['address_id'])); @@ -98,7 +105,8 @@ public function testTest() $q = Doctrine_Query::create() ->from('Ticket_DC23_BlogPost p') - ->leftJoin('p.Translation t'); + ->leftJoin('p.Translation t') + ; $results = $q->fetchArray(); $this->assertEqual(count($results[0]['Translation']), 1); @@ -138,10 +146,10 @@ public function setTableDefinition() public function setUp() { $this->hasOne('Ticket_DC23_Contact as Contact', array( - 'local' => 'contact_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE' - ) + 'local' => 'contact_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + ) ); } } @@ -157,16 +165,16 @@ public function setTableDefinition() public function setUp() { $this->hasOne('Ticket_DC23_Address as Address', array( - 'local' => 'address_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE' - ) + 'local' => 'address_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + ) ); $this->hasMany('Ticket_DC23_Phonenumber as Phonenumbers', array( - 'local' => 'id', - 'foreign' => 'contact_id' - ) + 'local' => 'id', + 'foreign' => 'contact_id', + ) ); } } @@ -190,10 +198,10 @@ public function setTableDefinition() public function setUp() { $this->hasOne('Ticket_DC23_Contact as Contact', array( - 'local' => 'contact_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE' - ) + 'local' => 'contact_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + ) ); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC23bTestCase.php b/tests/Ticket/DC23bTestCase.php index 682844ff2..04b02e37e 100644 --- a/tests/Ticket/DC23bTestCase.php +++ b/tests/Ticket/DC23bTestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC23b_TestCase + * Doctrine_Ticket_DC23b_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC23b_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC23b_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -43,7 +49,7 @@ public function prepareTables() public function testInlineSite() { - $yml = <<from('Ticket_Product p, p.Site s') - ->where('p.name = ?', 'book'); + ->where('p.name = ?', 'book') + ; $product = $query->execute()->getFirst(); @@ -69,7 +76,7 @@ public function testInlineSite() $this->pass(); } catch (Exception $e) { - //echo $e->getMessage(); + // echo $e->getMessage(); $this->fail(); } @@ -78,7 +85,7 @@ public function testInlineSite() public function testMultiple() { - $yml = <<from('Ticket_Product p, p.MultipleValues v, v.Multiple m') - ->where('p.name = ?', 'book2'); + ->where('p.name = ?', 'book2') + ; $product = $query->fetchOne(); @@ -123,7 +131,7 @@ public function testMultiple() public function testInlineMultiple() { - $yml = <<from('Ticket_Product p, p.MultipleValues v, v.Multiple m') - ->where('p.name = ?', 'book3'); + ->where('p.name = ?', 'book3') + ; $product = $query->fetchOne(); @@ -175,9 +184,9 @@ public function setTableDefinition() public function setUp() { $this->hasOne('Ticket_Site as Site', array('local' => 'site_id', - 'foreign' => 'id')); + 'foreign' => 'id')); $this->hasMany('Ticket_MultipleValue as MultipleValues', array('local' => 'id', - 'foreign' => 'product_id')); + 'foreign' => 'product_id')); } } class Ticket_Site extends Doctrine_Record @@ -190,7 +199,7 @@ public function setTableDefinition() public function setUp() { $this->hasMany('Ticket_Product as Products', array('local' => 'id', - 'foreign' => 'site_id')); + 'foreign' => 'site_id')); } } class Ticket_Multiple extends Doctrine_Record @@ -203,7 +212,7 @@ public function setTableDefinition() public function setUp() { $this->hasMany('Ticket_MultipleValue as MultipleValues', array('local' => 'id', - 'foreign' => 'multiple_id')); + 'foreign' => 'multiple_id')); } } class Ticket_MultipleValue extends Doctrine_Record @@ -218,9 +227,9 @@ public function setTableDefinition() public function setUp() { $this->hasOne('Ticket_Multiple as Multiple', array('local' => 'multiple_id', - 'foreign' => 'id')); + 'foreign' => 'id')); $this->hasOne('Ticket_Product as Product', array('local' => 'product_id', - 'foreign' => 'id')); + 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC240TestCase.php b/tests/Ticket/DC240TestCase.php index a3458f255..1e09f6157 100644 --- a/tests/Ticket/DC240TestCase.php +++ b/tests/Ticket/DC240TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC240_TestCase + * Doctrine_Ticket_DC240_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC240_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC240_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -44,10 +50,11 @@ public function prepareTables() public function testTest() { $q = Doctrine_Query::create() - ->from('Ticket_DC240_User u') - ->leftJoin('u.Roles r') - ->leftJoin('r.Parents p') - ->orderBy('username ASC'); + ->from('Ticket_DC240_User u') + ->leftJoin('u.Roles r') + ->leftJoin('r.Parents p') + ->orderBy('username ASC') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.username AS t__username, t.password AS t__password, t2.id AS t2__id, t2.name AS t2__name, t4.id AS t4__id, t4.name AS t4__name FROM ticket__d_c240__user t LEFT JOIN ticket__d_c240__user_role t3 ON (t.id = t3.id_user) LEFT JOIN ticket__d_c240__role t2 ON t2.id = t3.id_role LEFT JOIN ticket__d_c240__role_reference t5 ON (t2.id = t5.id_role_child) LEFT JOIN ticket__d_c240__role t4 ON t4.id = t5.id_role_parent ORDER BY t.username ASC, t3.position ASC, t5.position DESC'); } @@ -55,61 +62,61 @@ public function testTest() class Ticket_DC240_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('username', 'string', 64, array('notnull' => true)); - $this->hasColumn('password', 'string', 128, array('notnull' => true)); - } - - public function setUp() - { - $this->hasMany('Ticket_DC240_Role as Roles', array('local' => 'id_user', 'foreign' => 'id_role', 'refClass' => 'Ticket_DC240_UserRole', 'orderBy' => 'position ASC')); - } + public function setTableDefinition() + { + $this->hasColumn('username', 'string', 64, array('notnull' => true)); + $this->hasColumn('password', 'string', 128, array('notnull' => true)); + } + + public function setUp() + { + $this->hasMany('Ticket_DC240_Role as Roles', array('local' => 'id_user', 'foreign' => 'id_role', 'refClass' => 'Ticket_DC240_UserRole', 'orderBy' => 'position ASC')); + } } class Ticket_DC240_Role extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('name', 'string', 64); - } - - public function setUp() - { - $this->hasMany('Ticket_DC240_User as Users', array('local' => 'id_role', 'foreign' => 'id_user', 'refClass' => 'Ticket_DC240_UserRole', 'orderBy' => 'position ASC')); - $this->hasMany('Ticket_DC240_Role as Parents', array('local' => 'id_role_child', 'foreign' => 'id_role_parent', 'refClass' => 'Ticket_DC240_RoleReference', 'orderBy' => 'position DESC')); - $this->hasMany('Ticket_DC240_Role as Children', array('local' => 'id_role_parent', 'foreign' => 'id_role_child', 'refClass' => 'Ticket_DC240_RoleReference', 'orderBy' => 'position ASC')); - } + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 64); + } + + public function setUp() + { + $this->hasMany('Ticket_DC240_User as Users', array('local' => 'id_role', 'foreign' => 'id_user', 'refClass' => 'Ticket_DC240_UserRole', 'orderBy' => 'position ASC')); + $this->hasMany('Ticket_DC240_Role as Parents', array('local' => 'id_role_child', 'foreign' => 'id_role_parent', 'refClass' => 'Ticket_DC240_RoleReference', 'orderBy' => 'position DESC')); + $this->hasMany('Ticket_DC240_Role as Children', array('local' => 'id_role_parent', 'foreign' => 'id_role_child', 'refClass' => 'Ticket_DC240_RoleReference', 'orderBy' => 'position ASC')); + } } class Ticket_DC240_UserRole extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id_user', 'integer', null, array('primary' => true)); - $this->hasColumn('id_role', 'integer', null, array('primary' => true)); - $this->hasColumn('position', 'integer', null, array('notnull' => true)); - } - - public function setUp() - { - $this->hasOne('Ticket_DC240_User as User', array('local' => 'id_user', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - $this->hasOne('Ticket_DC240_Role as Role', array('local' => 'id_role', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - } + public function setTableDefinition() + { + $this->hasColumn('id_user', 'integer', null, array('primary' => true)); + $this->hasColumn('id_role', 'integer', null, array('primary' => true)); + $this->hasColumn('position', 'integer', null, array('notnull' => true)); + } + + public function setUp() + { + $this->hasOne('Ticket_DC240_User as User', array('local' => 'id_user', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + $this->hasOne('Ticket_DC240_Role as Role', array('local' => 'id_role', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } } class Ticket_DC240_RoleReference extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id_role_parent', 'integer', null, array('primary' => true)); - $this->hasColumn('id_role_child', 'integer', null, array('primary' => true)); - $this->hasColumn('position', 'integer', null, array('notnull' => true)); - } - - public function setUp() - { - $this->hasOne('Ticket_DC240_Role as Parent', array('local' => 'id_role_parent', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - $this->hasOne('Ticket_DC240_Role as Child', array('local' => 'id_role_child', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->hasColumn('id_role_parent', 'integer', null, array('primary' => true)); + $this->hasColumn('id_role_child', 'integer', null, array('primary' => true)); + $this->hasColumn('position', 'integer', null, array('notnull' => true)); + } + + public function setUp() + { + $this->hasOne('Ticket_DC240_Role as Parent', array('local' => 'id_role_parent', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + $this->hasOne('Ticket_DC240_Role as Child', array('local' => 'id_role_child', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } +} diff --git a/tests/Ticket/DC241TestCase.php b/tests/Ticket/DC241TestCase.php index c31059c01..165044466 100644 --- a/tests/Ticket/DC241TestCase.php +++ b/tests/Ticket/DC241TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC241_TestCase + * Doctrine_Ticket_DC241_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC241_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC241_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -42,15 +48,16 @@ public function prepareTables() public function testTest() { $q = Doctrine_Query::create() - ->from('Ticket_DC241_Poll p') - ->leftJoin('p.Answers pa ON pa.votes = ?', 100) - ->addWhere('p.id = ?', 200) - ->addWhere('p.id = ?', 300) - ->addWhere('p.id = ?', 400) - ->addWhere('p.id = ?', 400) - ->groupBy('p.id') - ->having('p.id > ?', 300) - ->limit(10); + ->from('Ticket_DC241_Poll p') + ->leftJoin('p.Answers pa ON pa.votes = ?', 100) + ->addWhere('p.id = ?', 200) + ->addWhere('p.id = ?', 300) + ->addWhere('p.id = ?', 400) + ->addWhere('p.id = ?', 400) + ->groupBy('p.id') + ->having('p.id > ?', 300) + ->limit(10) + ; $this->assertEqual($q->getCountSqlQuery(), 'SELECT COUNT(*) AS num_results FROM (SELECT t.id FROM ticket__d_c241__poll t LEFT JOIN module_polls_answers m ON (m.votes = ?) WHERE t.id = ? AND t.id = ? AND t.id = ? AND t.id = ? GROUP BY t.id HAVING t.id > ?) dctrn_count_query'); @@ -65,32 +72,32 @@ public function testTest() class Ticket_DC241_Poll extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id_category', 'integer', null, array('notnull' => true)); - $this->hasColumn('question', 'string', 256); - } - - public function setUp() - { - $this->hasMany('Ticket_DC241_PollAnswer as Answers', array('local' => 'id', 'foreign' => 'id_poll', 'orderBy' => 'position')); - } + public function setTableDefinition() + { + $this->hasColumn('id_category', 'integer', null, array('notnull' => true)); + $this->hasColumn('question', 'string', 256); + } + + public function setUp() + { + $this->hasMany('Ticket_DC241_PollAnswer as Answers', array('local' => 'id', 'foreign' => 'id_poll', 'orderBy' => 'position')); + } } class Ticket_DC241_PollAnswer extends Doctrine_Record { - public function setTableDefinition() - { - $this->setTableName('module_polls_answers'); - - $this->hasColumn('id_poll', 'integer', null, array('notnull' => true)); - $this->hasColumn('answer', 'string', 256); - $this->hasColumn('votes', 'integer', null, array('notnull' => true, 'default' => 0)); - $this->hasColumn('position', 'integer'); - } - - public function setUp() - { - $this->hasOne('Ticket_DC241_Poll as Poll', array('local' => 'id_poll', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('module_polls_answers'); + + $this->hasColumn('id_poll', 'integer', null, array('notnull' => true)); + $this->hasColumn('answer', 'string', 256); + $this->hasColumn('votes', 'integer', null, array('notnull' => true, 'default' => 0)); + $this->hasColumn('position', 'integer'); + } + + public function setUp() + { + $this->hasOne('Ticket_DC241_Poll as Poll', array('local' => 'id_poll', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } +} diff --git a/tests/Ticket/DC242TestCase.php b/tests/Ticket/DC242TestCase.php index d744899c9..3c1e27824 100644 --- a/tests/Ticket/DC242TestCase.php +++ b/tests/Ticket/DC242TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC242_TestCase + * Doctrine_Ticket_DC242_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC242_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC242_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -57,14 +63,14 @@ public function testTest() $user = new Ticket_DC242_User(); $user->fromArray(array( - 'username' => 'test', - 'password' => 'test', - 'Roles' => array(1, 2, 3), + 'username' => 'test', + 'password' => 'test', + 'Roles' => array(1, 2, 3), )); $user->save(); $user->fromArray(array( - 'Roles' => array(1, 3), + 'Roles' => array(1, 3), )); $user->save(); $user->refresh(true); @@ -76,59 +82,59 @@ public function testTest() class Ticket_DC242_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('username', 'string', 64, array('notnull' => true)); - $this->hasColumn('password', 'string', 128, array('notnull' => true)); - } + public function setTableDefinition() + { + $this->hasColumn('username', 'string', 64, array('notnull' => true)); + $this->hasColumn('password', 'string', 128, array('notnull' => true)); + } - public function setUp() - { - $this->hasMany('Ticket_DC242_Role as Roles', array('local' => 'id_user', 'foreign' => 'id_role', 'refClass' => 'Ticket_DC242_UserRole')); - } + public function setUp() + { + $this->hasMany('Ticket_DC242_Role as Roles', array('local' => 'id_user', 'foreign' => 'id_role', 'refClass' => 'Ticket_DC242_UserRole')); + } } class Ticket_DC242_Role extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('name', 'string', 64); - } + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 64); + } - public function setUp() - { - $this->hasMany('Ticket_DC242_User as Users', array('local' => 'id_role', 'foreign' => 'id_user', 'refClass' => 'Ticket_DC242_UserRole')); - $this->hasMany('Ticket_DC242_Role as Parents', array('local' => 'id_role_child', 'foreign' => 'id_role_parent', 'refClass' => 'Ticket_DC242_RoleReference')); - $this->hasMany('Ticket_DC242_Role as Children', array('local' => 'id_role_parent', 'foreign' => 'id_role_child', 'refClass' => 'Ticket_DC242_RoleReference')); - } + public function setUp() + { + $this->hasMany('Ticket_DC242_User as Users', array('local' => 'id_role', 'foreign' => 'id_user', 'refClass' => 'Ticket_DC242_UserRole')); + $this->hasMany('Ticket_DC242_Role as Parents', array('local' => 'id_role_child', 'foreign' => 'id_role_parent', 'refClass' => 'Ticket_DC242_RoleReference')); + $this->hasMany('Ticket_DC242_Role as Children', array('local' => 'id_role_parent', 'foreign' => 'id_role_child', 'refClass' => 'Ticket_DC242_RoleReference')); + } } class Ticket_DC242_UserRole extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id_user', 'integer', null, array('primary' => true)); - $this->hasColumn('id_role', 'integer', null, array('primary' => true)); - } + public function setTableDefinition() + { + $this->hasColumn('id_user', 'integer', null, array('primary' => true)); + $this->hasColumn('id_role', 'integer', null, array('primary' => true)); + } - public function setUp() - { - $this->hasOne('Ticket_DC242_User as User', array('local' => 'id_user', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - $this->hasOne('Ticket_DC242_Role as Role', array('local' => 'id_role', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - } + public function setUp() + { + $this->hasOne('Ticket_DC242_User as User', array('local' => 'id_user', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + $this->hasOne('Ticket_DC242_Role as Role', array('local' => 'id_role', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } } class Ticket_DC242_RoleReference extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('id_role_parent', 'integer', null, array('primary' => true)); - $this->hasColumn('id_role_child', 'integer', null, array('primary' => true)); - } + public function setTableDefinition() + { + $this->hasColumn('id_role_parent', 'integer', null, array('primary' => true)); + $this->hasColumn('id_role_child', 'integer', null, array('primary' => true)); + } - public function setUp() - { - $this->hasOne('Ticket_DC242_Role as Parent', array('local' => 'id_role_parent', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - $this->hasOne('Ticket_DC242_Role as Child', array('local' => 'id_role_child', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - } -} \ No newline at end of file + public function setUp() + { + $this->hasOne('Ticket_DC242_Role as Parent', array('local' => 'id_role_parent', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + $this->hasOne('Ticket_DC242_Role as Child', array('local' => 'id_role_child', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } +} diff --git a/tests/Ticket/DC24TestCase.php b/tests/Ticket/DC24TestCase.php index 424443366..5a0d16f91 100644 --- a/tests/Ticket/DC24TestCase.php +++ b/tests/Ticket/DC24TestCase.php @@ -20,67 +20,70 @@ */ /** - * Doctrine_Ticket_DC24_TestCase + * Doctrine_Ticket_DC24_TestCase. * - * @package Doctrine * @author Tomasz Jędrzejewski * @author Jacek Jędrzejewski * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC24_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC24_TestCase extends Doctrine_UnitTestCase { - - public function prepareTables() - { + public function prepareTables() + { $this->tables = array('ticket_DC24_master', 'ticket_DC24_servant'); parent::prepareTables(); - } // end prepareTables(); - - public function prepareData() - { - $servant = new Ticket_DC24_Servant; - $servant->bar = 6; - $servant->save(); - - $servantId = $servant->identifier(); - - $master = new Ticket_DC24_Master; - $master->foo = 6; - $master->servant_id = $servantId['id']; - $master->save(); - } // end prepareData(); - - public function testTest() - { - try - { - $master = Doctrine_Query::create() - ->select('m.*, s.bar AS joe') - ->from('Ticket_DC24_Master m') - ->innerJoin('m.Ticket_DC24_Servant s') - ->where('m.id = 1') - ->fetchOne(); - - $master->foo = 5; - $master->save(); - + } // end prepareTables(); + + public function prepareData() + { + $servant = new Ticket_DC24_Servant(); + $servant->bar = 6; + $servant->save(); + + $servantId = $servant->identifier(); + + $master = new Ticket_DC24_Master(); + $master->foo = 6; + $master->servant_id = $servantId['id']; + $master->save(); + } // end prepareData(); + + public function testTest() + { + try { + $master = Doctrine_Query::create() + ->select('m.*, s.bar AS joe') + ->from('Ticket_DC24_Master m') + ->innerJoin('m.Ticket_DC24_Servant s') + ->where('m.id = 1') + ->fetchOne() + ; + + $master->foo = 5; + $master->save(); + $master2 = Doctrine_Query::create() - ->select('m.*') - ->from('Ticket_DC24_Master m') - ->where('m.id = 1') - ->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY); + ->select('m.*') + ->from('Ticket_DC24_Master m') + ->where('m.id = 1') + ->fetchOne(array(), Doctrine_Core::HYDRATE_ARRAY) + ; $this->assertEqual($master2['servant_id'], 1); - } - catch(Exception $e) - { - $this->fail($e->getMessage()); - } - } // end testTest(); - + } catch (Exception $e) { + $this->fail($e->getMessage()); + } + } // end testTest(); } // end Doctrine_Ticket_DC24_TestCase; class Ticket_DC24_Master extends Doctrine_Record @@ -88,28 +91,28 @@ class Ticket_DC24_Master extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('id', 'integer', 4, array( - 'type' => 'integer', - 'primary' => true, - 'autoincrement' => true, - 'length' => '4', - )); + 'type' => 'integer', + 'primary' => true, + 'autoincrement' => true, + 'length' => '4', + )); $this->hasColumn('foo', 'integer', 4, array( - 'type' => 'integer', - 'notnull' => true, - 'length' => '4', - )); + 'type' => 'integer', + 'notnull' => true, + 'length' => '4', + )); $this->hasColumn('servant_id', 'integer', 4, array( - 'type' => 'integer', - //'notnull' => true, - 'length' => '4', - )); + 'type' => 'integer', + // 'notnull' => true, + 'length' => '4', + )); } // end setTableDefinition(); public function setUp() { $this->hasOne('Ticket_DC24_Servant', array( - 'local' => 'servant_id', - 'foreign' => 'id')); + 'local' => 'servant_id', + 'foreign' => 'id')); } // end setUp(); } // end Ticket_DC24_Master; @@ -118,22 +121,22 @@ class Ticket_DC24_Servant extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('id', 'integer', 4, array( - 'type' => 'integer', - 'primary' => true, - 'autoincrement' => true, - 'length' => '4', - )); + 'type' => 'integer', + 'primary' => true, + 'autoincrement' => true, + 'length' => '4', + )); $this->hasColumn('bar', 'integer', 4, array( - 'type' => 'integer', - 'notnull' => true, - 'length' => '4', - )); + 'type' => 'integer', + 'notnull' => true, + 'length' => '4', + )); } // end setTableDefinition(); - - public function setUp() - { - $this->hasMany('Ticket_DC24_Master as Masters', array( - 'local' => 'id', - 'foreign' => 'servant_id')); - } // end setUp(); -} // end Ticket_DC24_Servant; \ No newline at end of file + + public function setUp() + { + $this->hasMany('Ticket_DC24_Master as Masters', array( + 'local' => 'id', + 'foreign' => 'servant_id')); + } // end setUp(); +} // end Ticket_DC24_Servant; diff --git a/tests/Ticket/DC25TestCase.php b/tests/Ticket/DC25TestCase.php index ed167a9a4..741c1b309 100644 --- a/tests/Ticket/DC25TestCase.php +++ b/tests/Ticket/DC25TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC25_TestCase + * Doctrine_Ticket_DC25_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC25_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC25_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -45,7 +51,8 @@ public function testTest() $q = Doctrine_Core::getTable('Ticket_DC25_Article') ->createQuery('a') ->leftJoin('a.Tags t1') - ->leftJoin('a.Tags t2'); + ->leftJoin('a.Tags t2') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.name AS t__name, t2.id AS t2__id, t2.name AS t2__name, t4.id AS t4__id, t4.name AS t4__name FROM ticket__d_c25__article t LEFT JOIN ticket__d_c25__article_tag t3 ON (t.id = t3.article_id) LEFT JOIN ticket__d_c25__tag t2 ON t2.id = t3.tag_id LEFT JOIN ticket__d_c25__article_tag t5 ON (t.id = t5.article_id) LEFT JOIN ticket__d_c25__tag t4 ON t4.id = t5.tag_id'); } @@ -63,7 +70,7 @@ public function setUp() $this->hasMany('Ticket_DC25_Tag as Tags', array( 'local' => 'article_id', 'foreign' => 'tag_id', - 'refClass' => 'Ticket_DC25_ArticleTag' + 'refClass' => 'Ticket_DC25_ArticleTag', )); } } @@ -80,7 +87,7 @@ public function setUp() $this->hasMany('Ticket_DC25_Article as Article', array( 'local' => 'tag_id', 'foreign' => 'article_id', - 'refClass' => 'Ticket_DC25_ArticleTag' + 'refClass' => 'Ticket_DC25_ArticleTag', )); } } @@ -92,4 +99,4 @@ public function setTableDefinition() $this->hasColumn('article_id', 'integer'); $this->hasColumn('tag_id', 'integer'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC266TestCase.php b/tests/Ticket/DC266TestCase.php index 66323dd86..b03231885 100644 --- a/tests/Ticket/DC266TestCase.php +++ b/tests/Ticket/DC266TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC266_TestCase + * Doctrine_Ticket_DC266_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC266_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC266_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -55,7 +61,7 @@ public function setTableDefinition() public function setUp() { $this->actAs('I18n', array( - 'fields' => array('title') + 'fields' => array('title'), )); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC267TestCase.php b/tests/Ticket/DC267TestCase.php index 9c3f63303..7c1395d99 100644 --- a/tests/Ticket/DC267TestCase.php +++ b/tests/Ticket/DC267TestCase.php @@ -20,33 +20,41 @@ */ /** - * Doctrine_Ticket_DC267_TestCase + * Doctrine_Ticket_DC267_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC267_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC267_TestCase extends Doctrine_UnitTestCase { public function testTest() { $q = Doctrine_Query::create() - ->select ('u.*, COUNT(e.id) as num_emails') + ->select('u.*, COUNT(e.id) as num_emails') ->from('User u') ->leftJoin('u.Email e') - ->groupBy('u.id'); + ->groupBy('u.id') + ; $res = $q->fetchArray(); $this->assertEqual($res[0]['num_emails'], '1'); $q = Doctrine_Query::create() - ->select ('u.*, e.*, e.address as my_address') + ->select('u.*, e.*, e.address as my_address') ->from('User u') - ->leftJoin('u.Email e'); + ->leftJoin('u.Email e') + ; $res = $q->fetchArray(); @@ -54,4 +62,4 @@ public function testTest() $this->assertEqual($res[0]['my_address'], 'zYne@example.com'); $this->assertEqual($res[1]['my_address'], 'arnold@example.com'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC276TestCase.php b/tests/Ticket/DC276TestCase.php index 438b573a7..f6e8ceac8 100644 --- a/tests/Ticket/DC276TestCase.php +++ b/tests/Ticket/DC276TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC276_TestCase + * Doctrine_Ticket_DC276_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC276_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC276_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -45,7 +51,8 @@ public function testTest() ->from('Ticket_DC276_Post p, p.Comments c') ->select('p.*, c.*, COUNT(c.id) AS comment_count') ->groupBy('p.id') - ->having('comment_count <= p.max_comments'); + ->having('comment_count <= p.max_comments') + ; $this->assertEqual($q->getSqlQuery(), 'SELECT t.id AS t__id, t.content AS t__content, t.max_comments AS t__max_comments, t2.id AS t2__id, t2.post_id AS t2__post_id, t2.content AS t2__content, COUNT(t2.id) AS t2__0 FROM ticket__d_c276__post t LEFT JOIN ticket__d_c276__comment t2 ON t.id = t2.post_id GROUP BY t.id HAVING t2__0 <= t.max_comments'); $q->execute(); } @@ -56,19 +63,19 @@ class Ticket_DC276_Post extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('content', 'string', 1000, array( - 'type' => 'string', - 'length' => '1000', - )); + 'type' => 'string', + 'length' => '1000', + )); $this->hasColumn('max_comments', 'integer', null, array( - 'type' => 'integer', - )); + 'type' => 'integer', + )); } public function setUp() { $this->hasOne('Ticket_DC276_Comment as Comments', array( - 'local' => 'id', - 'foreign' => 'post_id')); + 'local' => 'id', + 'foreign' => 'post_id')); } } @@ -77,18 +84,18 @@ class Ticket_DC276_Comment extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('post_id', 'integer', null, array( - 'type' => 'integer', - )); + 'type' => 'integer', + )); $this->hasColumn('content', 'string', 100, array( - 'type' => 'string', - 'length' => '100', - )); + 'type' => 'string', + 'length' => '100', + )); } public function setUp() { $this->hasMany('Ticket_DC276_Post', array( - 'local' => 'post_id', - 'foreign' => 'id')); + 'local' => 'post_id', + 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC28TestCase.php b/tests/Ticket/DC28TestCase.php index 02fed656b..e3db23605 100644 --- a/tests/Ticket/DC28TestCase.php +++ b/tests/Ticket/DC28TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC28_TestCase + * Doctrine_Ticket_DC28_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC28_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC28_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -45,33 +51,33 @@ public function testQuery() ->select('a.id, t.lang') ->from('Ticket_DC28_Tree a') ->innerJoin('a.Translation t WITH t.name != ?', 'test') - ; + ; $q->execute(); - //echo $q->getSqlQuery().PHP_EOL; - + // echo $q->getSqlQuery().PHP_EOL; + $this->assertEqual( - $q->getSqlQuery(), + $q->getSqlQuery(), 'SELECT t.id AS t__id, t2.id AS t2__id, t2.lang AS t2__lang '. 'FROM ticket__d_c28__tree t '. 'INNER JOIN ticket__d_c28__tree_translation t2 '. 'ON t.id = t2.id AND (t2.name != ?)' ); - - //echo $q->getSqlQuery().PHP_EOL; + + // echo $q->getSqlQuery().PHP_EOL; $tree_table = Doctrine_Core::getTable('Ticket_DC28_Tree'); $tree = $tree_table->getTree(); $tree->setBaseQuery($q); - //echo $q->getSqlQuery().PHP_EOL; - + // echo $q->getSqlQuery().PHP_EOL; + $this->assertEqual( - $q->getSqlQuery(), + $q->getSqlQuery(), 'SELECT t.id AS t__id, t.lft AS t__lft, t.rgt AS t__rgt, t.level AS t__level, t2.id AS t2__id, t2.lang AS t2__lang '. 'FROM ticket__d_c28__tree t '. 'INNER JOIN ticket__d_c28__tree_translation t2 '. 'ON t.id = t2.id AND (t2.name != ?)' ); - - //$this->pass(); + + // $this->pass(); } catch (Exception $e) { $this->fail($e->getMessage()); } @@ -91,4 +97,4 @@ public function setUp() $this->actAs($i18n); $this->actAs('NestedSet'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC292TestCase.php b/tests/Ticket/DC292TestCase.php index e0ecb5f14..23c7416e6 100644 --- a/tests/Ticket/DC292TestCase.php +++ b/tests/Ticket/DC292TestCase.php @@ -20,29 +20,35 @@ */ /** - * Doctrine_Ticket_DC292_TestCase + * Doctrine_Ticket_DC292_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC292_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC292_TestCase extends Doctrine_UnitTestCase { public function testTest() { - $dir = dirname(__FILE__) . '/DC292/migrations'; - if ( ! is_dir($dir)) { + $dir = dirname(__FILE__).'/DC292/migrations'; + if (!is_dir($dir)) { mkdir($dir, 0777, true); } $migration = new Doctrine_Migration($dir); - $diff = new Doctrine_Migration_Diff(dirname(__FILE__) . '/DC292/from.yml', dirname(__FILE__) . '/DC292/to.yml', $migration); + $diff = new Doctrine_Migration_Diff(dirname(__FILE__).'/DC292/from.yml', dirname(__FILE__).'/DC292/to.yml', $migration); $changes = $diff->generateChanges(); $this->assertEqual(2, count($changes['created_columns']['article'])); $this->assertTrue(isset($changes['created_columns']['article']['created_at'])); $this->assertTrue(isset($changes['created_columns']['article']['updated_at'])); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC300TestCase.php b/tests/Ticket/DC300TestCase.php index c567c4a64..a75e66973 100644 --- a/tests/Ticket/DC300TestCase.php +++ b/tests/Ticket/DC300TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_DC300_TestCase + * Doctrine_Ticket_DC300_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC300_TestCase extends Doctrine_UnitTestCase { @@ -63,65 +69,64 @@ public function prepareTables() public function testRefTableEntriesOnManyToManyRelationsWithSynchronizeWithArray() { - $u1 = Doctrine_Core::getTable('Ticket_DC300_User')->find(1); + $u1 = Doctrine_Core::getTable('Ticket_DC300_User')->find(1); - // update the groups user (id 1) is linked to - $u1->synchronizeWithArray(array( - 'Groups' => array( - array('name' => 'group1 update'), - array('name' => 'group2 update') - ) - )); - $u1->save(); + // update the groups user (id 1) is linked to + $u1->synchronizeWithArray(array( + 'Groups' => array( + array('name' => 'group1 update'), + array('name' => 'group2 update'), + ), + )); + $u1->save(); - // update the user-objects with real data from database - $u1->loadReference('Groups'); + // update the user-objects with real data from database + $u1->loadReference('Groups'); - // check wether the two database-entries in RefTable exists - $this->assertEqual(count($u1->Groups), 2); + // check wether the two database-entries in RefTable exists + $this->assertEqual(count($u1->Groups), 2); } - } class Ticket_DC300_Group extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('name', 'string', 255); - } - - public function setUp() - { - $this->hasMany('Ticket_DC300_User as Users', array( - 'local' => 'group_id', - 'foreign' => 'user_id', - 'refClass' => 'Ticket_DC300_UserGroup' - )); - } + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 255); + } + + public function setUp() + { + $this->hasMany('Ticket_DC300_User as Users', array( + 'local' => 'group_id', + 'foreign' => 'user_id', + 'refClass' => 'Ticket_DC300_UserGroup', + )); + } } class Ticket_DC300_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('name', 'string', 255); - } + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 255); + } - public function setUp() - { - $this->hasMany('Ticket_DC300_Group as Groups', array( - 'local' => 'user_id', - 'foreign' => 'group_id', - 'refClass' => 'Ticket_DC300_UserGroup' - )); - } + public function setUp() + { + $this->hasMany('Ticket_DC300_Group as Groups', array( + 'local' => 'user_id', + 'foreign' => 'group_id', + 'refClass' => 'Ticket_DC300_UserGroup', + )); + } } class Ticket_DC300_UserGroup extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('user_id', 'integer'); - $this->hasColumn('group_id', 'integer'); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->hasColumn('user_id', 'integer'); + $this->hasColumn('group_id', 'integer'); + } +} diff --git a/tests/Ticket/DC302TestCase.php b/tests/Ticket/DC302TestCase.php index c71e70752..6dbe626e9 100644 --- a/tests/Ticket/DC302TestCase.php +++ b/tests/Ticket/DC302TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC302_TestCase + * Doctrine_Ticket_DC302_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC302_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC302_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -40,52 +46,54 @@ public function prepareTables() $this->tables[] = 'Ticket_DC302_UserRole'; parent::prepareTables(); } - + public function prepareData() { $role1 = new Ticket_DC302_Role(); $role1->name = 'admin'; // id: 1 $role1->save(); - + $role2 = new Ticket_DC302_Role(); $role2->name = 'publisher'; // id: 2 $role2->save(); - + $role3 = new Ticket_DC302_Role(); $role3->name = 'reviewer'; // id: 3 $role3->save(); - + $role4 = new Ticket_DC302_Role(); $role4->name = 'mod'; // id: 4 $role4->save(); - + // reviewer inherits from admin, mod, publisher - in that order $role3->Parents[] = $role1; $role3->Parents[] = $role4; $role3->Parents[] = $role2; $role3->save(); - + // update positions $query = Doctrine_Query::create() ->update('Ticket_DC302_RoleReference') ->set('position', '?', 0) ->where('id_role_child = ?', 3) ->andWhere('id_role_parent = ?', 1) - ->execute(); + ->execute() + ; $query = Doctrine_Query::create() ->update('Ticket_DC302_RoleReference') ->set('position', '?', 1) ->where('id_role_child = ?', 3) ->andWhere('id_role_parent = ?', 4) - ->execute(); + ->execute() + ; $query = Doctrine_Query::create() ->update('Ticket_DC302_RoleReference') ->set('position', '?', 2) ->where('id_role_child = ?', 3) ->andWhere('id_role_parent = ?', 2) - ->execute(); - - + ->execute() + ; + $user = new Ticket_DC302_User(); $user->username = 'test'; $user->password = 'test'; @@ -97,23 +105,25 @@ public function prepareData() ->set('position', '?', 0) ->where('id_user = ?', 1) ->andWhere('id_role = ?', 4) - ->execute(); + ->execute() + ; $query = Doctrine_Query::create() ->update('Ticket_DC302_UserRole') ->set('position', '?', 1) ->where('id_user = ?', 1) ->andWhere('id_role = ?', 2) - ->execute(); + ->execute() + ; } - + public function testTest() { $profiler = new Doctrine_Connection_Profiler(); $this->conn->addListener($profiler); - $role = Doctrine_Core::getTable('Ticket_DC302_Role')->find(3); - $parents = $role->Parents->toArray(); - + $role = Doctrine_Core::getTable('Ticket_DC302_Role')->find(3); + $parents = $role->Parents->toArray(); + $this->assertEqual($parents[1]['Ticket_DC302_RoleReference'][0]['position'], 1); $events = $profiler->getAll(); @@ -128,7 +138,7 @@ public function setTableDefinition() { $this->hasColumn('name', 'string', 64); } - + public function setUp() { $this->hasMany('Ticket_DC302_User as Users', array('local' => 'id_role', 'foreign' => 'id_user', 'refClass' => 'Ticket_DC302_UserRole')); @@ -145,7 +155,7 @@ public function setTableDefinition() $this->hasColumn('id_role_child', 'integer', null, array('primary' => true)); $this->hasColumn('position', 'integer', null, array('notnull' => true, 'default' => 0)); } - + public function setUp() { $this->hasOne('Ticket_DC302_Role as Parent', array('local' => 'id_role_parent', 'foreign' => 'id', 'onDelete' => 'CASCADE')); @@ -160,7 +170,7 @@ public function setTableDefinition() $this->hasColumn('username', 'string', 64, array('notnull' => true)); $this->hasColumn('password', 'string', 128, array('notnull' => true)); } - + public function setUp() { $this->hasMany('Ticket_DC302_Role as Roles', array('local' => 'id_user', 'foreign' => 'id_role', 'refClass' => 'Ticket_DC302_UserRole', 'orderBy' => 'position')); @@ -175,10 +185,10 @@ public function setTableDefinition() $this->hasColumn('id_role', 'integer', null, array('primary' => true)); $this->hasColumn('position', 'integer', null, array('notnull' => true, 'default' => 0)); } - + public function setUp() { $this->hasOne('Ticket_DC302_User as User', array('local' => 'id_user', 'foreign' => 'id', 'onDelete' => 'CASCADE')); $this->hasOne('Ticket_DC302_Role as Role', array('local' => 'id_role', 'foreign' => 'id', 'onDelete' => 'CASCADE')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC317TestCase.php b/tests/Ticket/DC317TestCase.php index 70f33b881..857308727 100644 --- a/tests/Ticket/DC317TestCase.php +++ b/tests/Ticket/DC317TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC317_TestCase + * Doctrine_Ticket_DC317_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC317_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC317_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -46,7 +52,7 @@ public function testTest() $page->save(); $tree = Doctrine_Core::getTable('Ticket_DC317_Page')->getTree(); - $tree->createRoot( $page ); + $tree->createRoot($page); $this->assertEqual($page->topic, 'my-topic'); @@ -60,15 +66,15 @@ class Ticket_DC317_Page extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('topic', 'string', 32, array( - 'type' => 'string', - 'notnull' => true, - 'length' => '32', - )); + 'type' => 'string', + 'notnull' => true, + 'length' => '32', + )); $this->hasColumn('title', 'string', 255, array( - 'type' => 'string', - 'notnull' => true, - 'length' => '255', - )); + 'type' => 'string', + 'notnull' => true, + 'length' => '255', + )); $this->option('type', 'InnoDB'); $this->option('collate', 'utf8_unicode_ci'); @@ -78,9 +84,9 @@ public function setTableDefinition() public function setUp() { $nestedset0 = new Doctrine_Template_NestedSet(array( - 'hasManyRoots' => true, - 'rootColumnName' => 'topic', - )); + 'hasManyRoots' => true, + 'rootColumnName' => 'topic', + )); $this->actAs($nestedset0); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC36TestCase.php b/tests/Ticket/DC36TestCase.php index e1f9eef12..83d2b804d 100644 --- a/tests/Ticket/DC36TestCase.php +++ b/tests/Ticket/DC36TestCase.php @@ -20,16 +20,22 @@ */ /** - * Doctrine_Ticket_DC36_TestCase + * Doctrine_Ticket_DC36_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC36_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC36_TestCase extends Doctrine_UnitTestCase { -} \ No newline at end of file +} diff --git a/tests/Ticket/DC399TestCase.php b/tests/Ticket/DC399TestCase.php index 53d0d4c49..62bfbfe0a 100644 --- a/tests/Ticket/DC399TestCase.php +++ b/tests/Ticket/DC399TestCase.php @@ -20,46 +20,51 @@ */ /** - * Doctrine_Template_TestCase + * Doctrine_Template_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.phpdoctrine.org + * + * @see www.phpdoctrine.org * @since 1.2 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC399_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC399_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { - parent::prepareTables(); + parent::prepareTables(); } - public function prepareData() + + public function prepareData() { - $user = new User(); - $user->name = "sacho"; - $user->Phonenumber[0]->phonenumber = "1234567"; - $user->Phonenumber[1]->phonenumber = "123123123"; - $user->Phonenumber[2]->phonenumber = "345345345"; + $user = new User(); + $user->name = 'sacho'; + $user->Phonenumber[0]->phonenumber = '1234567'; + $user->Phonenumber[1]->phonenumber = '123123123'; + $user->Phonenumber[2]->phonenumber = '345345345'; - $user->save(); + $user->save(); } public function testUnlinkCausesDeleteAfterSave() { - $user = Doctrine_Core::getTable("User")->findOneByName("sacho"); - $user->refreshRelated("Phonenumber"); - - //Unlinking(even with now=true) removes the connection between User and Phonenumber, but does not delete the phone number - //Only updates phonenumber's user_id to null - //However, if we unlink and then save the $user, the phonenumber is deleted from the database + $user = Doctrine_Core::getTable('User')->findOneByName('sacho'); + $user->refreshRelated('Phonenumber'); - $phone_id = $user->Phonenumber[0]->id; - $user->unlink("Phonenumber", $user->Phonenumber[0]->id); - $user->save(); + // Unlinking(even with now=true) removes the connection between User and Phonenumber, but does not delete the phone number + // Only updates phonenumber's user_id to null + // However, if we unlink and then save the $user, the phonenumber is deleted from the database - $phone = Doctrine_Core::getTable("Phonenumber")->find($phone_id); - $this->assertEqual($phone_id, $phone->id); - } + $phone_id = $user->Phonenumber[0]->id; + $user->unlink('Phonenumber', $user->Phonenumber[0]->id); + $user->save(); -} \ No newline at end of file + $phone = Doctrine_Core::getTable('Phonenumber')->find($phone_id); + $this->assertEqual($phone_id, $phone->id); + } +} diff --git a/tests/Ticket/DC39TestCase.php b/tests/Ticket/DC39TestCase.php index 4467a5445..c8ede80e4 100644 --- a/tests/Ticket/DC39TestCase.php +++ b/tests/Ticket/DC39TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_DC39_TestCase + * Doctrine_Ticket_DC39_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC39_TestCase extends Doctrine_UnitTestCase { @@ -62,53 +68,52 @@ public function prepareTables() public function testOneToManyRelationsWithSynchronizeWithArray() { - // link group (id 2) with users (id 1,2) - $group = Doctrine_Core::getTable('Ticket_DC39_Group')->find(2); - $group->synchronizeWithArray(array( - 'Users' => array(1, 2) - )); - $group->save(); + // link group (id 2) with users (id 1,2) + $group = Doctrine_Core::getTable('Ticket_DC39_Group')->find(2); + $group->synchronizeWithArray(array( + 'Users' => array(1, 2), + )); + $group->save(); - // update the user-objects with real data from database - $user1 = Doctrine_Core::getTable('Ticket_DC39_User')->find(1); - $user2 = Doctrine_Core::getTable('Ticket_DC39_User')->find(2); + // update the user-objects with real data from database + $user1 = Doctrine_Core::getTable('Ticket_DC39_User')->find(1); + $user2 = Doctrine_Core::getTable('Ticket_DC39_User')->find(2); - // compare the group_id (should be 2) with the group_id set through $group->synchronizeWithArray - $this->assertEqual($group->Users[0]->group_id, 2); - $this->assertEqual($group->Users[1]->group_id, 2); + // compare the group_id (should be 2) with the group_id set through $group->synchronizeWithArray + $this->assertEqual($group->Users[0]->group_id, 2); + $this->assertEqual($group->Users[1]->group_id, 2); } - } class Ticket_DC39_Group extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('name', 'string', 255); - } - - public function setUp() - { - $this->hasMany('Ticket_DC39_User as Users', array( - 'local' => 'id', - 'foreign' => 'group_id' - )); - } + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 255); + } + + public function setUp() + { + $this->hasMany('Ticket_DC39_User as Users', array( + 'local' => 'id', + 'foreign' => 'group_id', + )); + } } class Ticket_DC39_User extends Doctrine_Record { - public function setTableDefinition() - { - $this->hasColumn('group_id', 'integer'); - $this->hasColumn('name', 'string', 255); - } + public function setTableDefinition() + { + $this->hasColumn('group_id', 'integer'); + $this->hasColumn('name', 'string', 255); + } - public function setUp() - { - $this->hasOne('Ticket_DC39_Group as Group', array( - 'local' => 'group_id', - 'foreign' => 'id' - )); - } -} \ No newline at end of file + public function setUp() + { + $this->hasOne('Ticket_DC39_Group as Group', array( + 'local' => 'group_id', + 'foreign' => 'id', + )); + } +} diff --git a/tests/Ticket/DC437TestCase.php b/tests/Ticket/DC437TestCase.php index dfd9daad3..1ee950ccd 100644 --- a/tests/Ticket/DC437TestCase.php +++ b/tests/Ticket/DC437TestCase.php @@ -20,21 +20,27 @@ */ /** - * Doctrine_Ticket_DC437_TestCase + * Doctrine_Ticket_DC437_TestCase. * - * @package Doctrine * @author Eugene Janusov * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC437_TestCase extends Doctrine_UnitTestCase { private function prepareConnections() { - // Establish two new individual connections + // Establish two new individual connections $dsn = 'sqlite::memory:'; $dbh = new PDO($dsn); $this->manager->openConnection($dbh, 'conn1', false); @@ -59,16 +65,16 @@ public function prepareTables() */ foreach (array('conn1', 'conn2') as $dbConnName) { $dbConn = $this->manager->getConnection($dbConnName); - foreach ($this->tables as $componentName) { - $this->manager->bindComponent($componentName, $dbConn->getName()); - } - $dbConn->export->exportClasses($this->tables); + foreach ($this->tables as $componentName) { + $this->manager->bindComponent($componentName, $dbConn->getName()); + } + $dbConn->export->exportClasses($this->tables); } } public function prepareData() { - $conn1 = $this->manager->getConnection('conn1'); + $conn1 = $this->manager->getConnection('conn1'); $conn2 = $this->manager->getConnection('conn2'); // Create 1 record using conn1, and 2 records using conn2 @@ -92,7 +98,7 @@ public function testConnectionQuery() * connection. */ - $conn1 = $this->manager->getConnection('conn1'); + $conn1 = $this->manager->getConnection('conn1'); $conn2 = $this->manager->getConnection('conn2'); $dql = 'FROM Doctrine_Ticket_DC437_Record'; @@ -104,19 +110,19 @@ public function testConnectionQuery() } } -class Doctrine_Ticket_DC437_Record extends Doctrine_Record { - +class Doctrine_Ticket_DC437_Record extends Doctrine_Record +{ public function setTableDefinition() { $this->setTableName('dc437records'); $this->hasColumn('id', 'integer', 5, array( - 'unsigned' => true, - 'notnull' => true, - 'primary' => true, - 'autoincrement' => true + 'unsigned' => true, + 'notnull' => true, + 'primary' => true, + 'autoincrement' => true, )); $this->hasColumn('test', 'string'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC521TestCase.php b/tests/Ticket/DC521TestCase.php index 4c5dbeef5..6c2219b3f 100644 --- a/tests/Ticket/DC521TestCase.php +++ b/tests/Ticket/DC521TestCase.php @@ -25,19 +25,18 @@ public function setTableDefinition() { $this->setTableName('dc521_test_model'); $this->hasColumn('id', 'integer', null, array( - 'type' => 'integer', - 'primary' => true, - 'autoincrement' => true, - )); + 'type' => 'integer', + 'primary' => true, + 'autoincrement' => true, + )); $this->hasColumn('data', 'string', null, array( - 'type' => 'string', - )); + 'type' => 'string', + )); } public function setUp() { parent::setUp(); - } } @@ -47,47 +46,52 @@ public function setTableDefinition() { $this->setTableName('dc521_idonly_test_model'); $this->hasColumn('id', 'integer', null, array( - 'type' => 'integer', - 'primary' => true, - 'autoincrement' => true, - )); + 'type' => 'integer', + 'primary' => true, + 'autoincrement' => true, + )); } public function setUp() { parent::setUp(); - } } /** - * Doctrine_Ticket_DC521_TestCase + * Doctrine_Ticket_DC521_TestCase. * - * @package Doctrine * @author Gergely Kis * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC521_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC521_TestCase extends Doctrine_UnitTestCase { public function init() { Doctrine_Manager::connection('pgsql://test:test@localhost/doctrine', 'Pgsql'); - $this->driverName = 'Pgsql'; - parent::init(); + $this->driverName = 'Pgsql'; + parent::init(); $this->prepareTables(); } - + public function setUp() { - $this->driverName = 'Pgsql'; + $this->driverName = 'Pgsql'; Doctrine_Manager::connection('pgsql://test:test@localhost/doctrine', 'Pgsql'); - parent::setUp(); + parent::setUp(); } - + public function testEmptyPgsqlAutoIncrementField() { $m = new DC521TestModel(); @@ -101,7 +105,7 @@ public function testIdOnlyPgsqlAutoIncrementField() $m->save(); $this->assertEqual($m->id, 1); } - + public function testIdOnlyPgsqlAutoIncrementFieldWithDefinedValue() { $m = new DC521IdOnlyTestModel(); @@ -109,7 +113,7 @@ public function testIdOnlyPgsqlAutoIncrementFieldWithDefinedValue() $m->save(); $this->assertEqual($m->id, 9999); } - + public function testPgsqlAutoIncrementFieldWithDefinedValue() { $m = new DC521TestModel(); @@ -117,27 +121,27 @@ public function testPgsqlAutoIncrementFieldWithDefinedValue() $m->save(); $this->assertEqual($m->id, 9999); } - + public function testPgsqlAutoIncrementFieldWithDefinedValueAndData() { $m = new DC521TestModel(); $this->assertEqual($m->id, null); $m->id = 111111; - $m->data = "testdata"; + $m->data = 'testdata'; $m->save(); $this->assertEqual($m->id, 111111); } - - public function prepareTables() + + public function prepareTables() { $this->tables = array('DC521TestModel', 'DC521IdOnlyTestModel'); parent::prepareTables(); } - + public function tearDown() { Doctrine_Manager::resetInstance(); - $this->driverName = null; - parent::tearDown(); + $this->driverName = null; + parent::tearDown(); } } diff --git a/tests/Ticket/DC56TestCase.php b/tests/Ticket/DC56TestCase.php index 8313b5c9c..1810c6a1b 100644 --- a/tests/Ticket/DC56TestCase.php +++ b/tests/Ticket/DC56TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC56_TestCase + * Doctrine_Ticket_DC56_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC56_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC56_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -59,11 +65,11 @@ public function setUp() { $this->actAs('Geographical', array( 'latitude' => array( - 'name' => 'lat' + 'name' => 'lat', ), 'longitude' => array( - 'name' => 'long' - ) + 'name' => 'long', + ), )); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC57TestCase.php b/tests/Ticket/DC57TestCase.php index f8f3f8023..2be1a942b 100644 --- a/tests/Ticket/DC57TestCase.php +++ b/tests/Ticket/DC57TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC57_TestCase + * Doctrine_Ticket_DC57_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC57_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC57_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -55,7 +61,7 @@ public function testOldDates() $test = new Ticket_DC57_Article(); $test->timestamp = '1776-07-04'; $test->save(); - + $test->timestamp = '1492-09-01'; $this->assertTrue($test->isModified()); } @@ -69,4 +75,4 @@ public function setTableDefinition() $this->hasColumn('date', 'date'); $this->hasColumn('timestamp', 'timestamp'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC63TestCase.php b/tests/Ticket/DC63TestCase.php index df4b91e73..ff832eb92 100644 --- a/tests/Ticket/DC63TestCase.php +++ b/tests/Ticket/DC63TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC63_TestCase + * Doctrine_Ticket_DC63_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC63_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC63_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -59,4 +65,4 @@ public function setTableDefinition() $this->setColumnOptions(array('password'), array('primary' => false)); $this->setColumnOption('username', 'notnull', true); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC64TestCase.php b/tests/Ticket/DC64TestCase.php index e7100456d..43732e151 100644 --- a/tests/Ticket/DC64TestCase.php +++ b/tests/Ticket/DC64TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC64_TestCase + * Doctrine_Ticket_DC64_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC64_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC64_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -72,7 +78,7 @@ public function setUp() { $this->actAs('Sluggable', array( 'provider' => array($this, 'provideSlug'), - 'builder' => array($this, 'formatSlug') + 'builder' => array($this, 'formatSlug'), )); } @@ -88,6 +94,6 @@ public static function formatSlug($slug) public static function provideSlug(Doctrine_Record $record) { - return 'jwage ' . $record->title; + return 'jwage '.$record->title; } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC69TestCase.php b/tests/Ticket/DC69TestCase.php index bec2ffe0c..9937cdbd5 100644 --- a/tests/Ticket/DC69TestCase.php +++ b/tests/Ticket/DC69TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC69_TestCase + * Doctrine_Ticket_DC69_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC69_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC69_TestCase extends Doctrine_UnitTestCase { public function testTest() { @@ -38,8 +44,9 @@ public function testTest() $user = Doctrine_Core::getTable('User') ->createQuery('u') ->limit(1) - ->fetchOne(); - $user->link('Email', 4); + ->fetchOne() + ; + $user->link('Email', 4); $user->save(); $this->pass(); } catch (Exception $e) { @@ -47,4 +54,4 @@ public function testTest() } $this->assertEqual($user->Email->id, 4); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC709TestCase.php b/tests/Ticket/DC709TestCase.php index d34c0d52e..a425e539c 100644 --- a/tests/Ticket/DC709TestCase.php +++ b/tests/Ticket/DC709TestCase.php @@ -20,28 +20,34 @@ */ /** - * Doctrine_Ticket_DC709_TestCase + * Doctrine_Ticket_DC709_TestCase. * - * @package Doctrine * @author John Kary * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC709_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC709_TestCase extends Doctrine_UnitTestCase { public function testTest() { $dbh = new Doctrine_Adapter_Mock('mysql'); - + $conn = Doctrine_Manager::getInstance()->connection($dbh, 'mysql', false); $sql = $conn->export->createTableSql('mytable', array( - 'name' => array('type' => 'string', 'length' => 255, 'comment' => "This comment isn't breaking") + 'name' => array('type' => 'string', 'length' => 255, 'comment' => "This comment isn't breaking"), )); $this->assertEqual($sql[0], "CREATE TABLE mytable (name VARCHAR(255) COMMENT 'This comment isn''t breaking') ENGINE = INNODB"); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC74TestCase.php b/tests/Ticket/DC74TestCase.php index 22fc6abd5..f7d410df3 100644 --- a/tests/Ticket/DC74TestCase.php +++ b/tests/Ticket/DC74TestCase.php @@ -20,64 +20,76 @@ */ /** - * Doctrine_Ticket_DC74_TestCase + * Doctrine_Ticket_DC74_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC74_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC74_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables[] = 'Ticket_DC74_Test'; parent::prepareTables(); } - + public function prepareData() { - $r = new Ticket_DC74_Test(); - $r->test1 = 'test1'; - $r->test2 = 'test2'; - $r->save(); - - // following clear should be done automatically, as noted in DC73 ticket - $r->getTable()->clear(); + $r = new Ticket_DC74_Test(); + $r->test1 = 'test1'; + $r->test2 = 'test2'; + $r->save(); + + // following clear should be done automatically, as noted in DC73 ticket + $r->getTable()->clear(); } public function testTest() { - // we are selecting "id" and "test1" fields and ommiting "test2" - $r1 = Doctrine_Query::create() - ->select('id, test1') - ->from('Ticket_DC74_Test') - ->fetchOne(); - - // so we have object in PROXY state - $this->assertEqual(Doctrine_Record::STATE_PROXY, $r1->state()); + // we are selecting "id" and "test1" fields and ommiting "test2" + $r1 = Doctrine_Query::create() + ->select('id, test1') + ->from('Ticket_DC74_Test') + ->fetchOne() + ; - // now we are modifing one of loaded properties "test1" - $r1->test1 = 'testx'; - - // so record is in DIRTY state - $this->assertEqual(Doctrine_Record::STATE_DIRTY, $r1->state()); - - // when accessing to not loaded field "test2" no additional loading - // currently such loading is performed is executed only in PROXY state - $this->assertEqual('test2', $r1->test2); + // so we have object in PROXY state + $this->assertEqual(Doctrine_Record::STATE_PROXY, $r1->state()); + + // now we are modifing one of loaded properties "test1" + $r1->test1 = 'testx'; + + // so record is in DIRTY state + $this->assertEqual(Doctrine_Record::STATE_DIRTY, $r1->state()); + + // when accessing to not loaded field "test2" no additional loading + // currently such loading is performed is executed only in PROXY state + $this->assertEqual('test2', $r1->test2); } } +/** + * @internal + * + * @coversNothing + */ class Ticket_DC74_Test extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('id', 'integer', 4, array('primary', 'notnull', 'autoincrement')); + $this->hasColumn('id', 'integer', 4, array('primary', 'notnull', 'autoincrement')); $this->hasColumn('test1', 'string', 255); $this->hasColumn('test2', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC794TestCase.php b/tests/Ticket/DC794TestCase.php index bab8382f7..f31010224 100644 --- a/tests/Ticket/DC794TestCase.php +++ b/tests/Ticket/DC794TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC794_TestCase + * Doctrine_Ticket_DC794_TestCase. * - * @package Doctrine * @author Enrico Stahn * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC794_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC794_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -41,7 +47,7 @@ public function prepareTables() public function testTest() { $table = Doctrine_Core::getTable('Ticket_DC794_Model'); - + $this->assertEqual($table->buildFindByWhere('IdOrigenOportunidadClienteOrId'), '(dctrn_find.idOrigenOportunidadCliente = ? OR dctrn_find.id = ?)'); $this->assertEqual($table->buildFindByWhere('IdAndIdOrIdOrigenOportunidadCliente'), 'dctrn_find.id = ? AND (dctrn_find.id = ? OR dctrn_find.idOrigenOportunidadCliente = ?)'); $this->assertEqual($table->buildFindByWhere('UsernameOrIdOrIdOrigenOportunidadCliente'), '(dctrn_find.Username = ? OR dctrn_find.id = ? OR dctrn_find.idOrigenOportunidadCliente = ?)'); @@ -62,4 +68,4 @@ public function setTableDefinition() $this->hasColumn('Username', 'string', 255); $this->hasColumn('password', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC7TestCase.php b/tests/Ticket/DC7TestCase.php index 44279e234..00c456ca6 100644 --- a/tests/Ticket/DC7TestCase.php +++ b/tests/Ticket/DC7TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC7_TestCase + * Doctrine_Ticket_DC7_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC7_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC7_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -40,7 +46,7 @@ public function prepareTables() public function prepareData() { - for ($i = 0; $i < 10; $i++) { + for ($i = 0; $i < 10; ++$i) { $user = new Ticket_DC7_User(); $user->username = $i; $user->password = $i; @@ -52,14 +58,15 @@ public function testOnDemandHydration() { $q = Doctrine_Core::getTable('Ticket_DC7_User') ->createQuery('u') - ->setHydrationMode(Doctrine_Core::HYDRATE_ON_DEMAND); + ->setHydrationMode(Doctrine_Core::HYDRATE_ON_DEMAND) + ; $results = $q->execute(); $this->assertEqual(get_class($results), 'Doctrine_Collection_OnDemand'); $count = 0; foreach ($results as $result) { - $count++; + ++$count; } $this->assertEqual($count, 10); } @@ -72,4 +79,4 @@ public function setTableDefinition() $this->hasColumn('username', 'string', 255); $this->hasColumn('password', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC825TestCase.php b/tests/Ticket/DC825TestCase.php index 3cb04c756..010d1f3c0 100644 --- a/tests/Ticket/DC825TestCase.php +++ b/tests/Ticket/DC825TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC825_TestCase + * Doctrine_Ticket_DC825_TestCase. * - * @package Doctrine * @author Enrico Stahn * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC825_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC825_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { @@ -49,14 +55,14 @@ public function testTest() $user->delete(); $version = $user->getAuditLog()->getVersion($user, 2, Doctrine_Core::HYDRATE_RECORD); - $versionTable = $version[0]->getTable(); - $versionTableColumns = $versionTable->getColumnNames(); - $recordTableColumns = $user->getTable()->getColumnNames(); + $versionTable = $version[0]->getTable(); + $versionTableColumns = $versionTable->getColumnNames(); + $recordTableColumns = $user->getTable()->getColumnNames(); $this->assertFalse(in_array('id', $versionTableColumns)); $this->assertTrue(in_array('model_id', $versionTableColumns)); $this->assertTrue(count($versionTableColumns) == count($recordTableColumns)); - $this->assertTrue(count(array_diff($versionTableColumns, $recordTableColumns)) == 0); + $this->assertTrue(0 == count(array_diff($versionTableColumns, $recordTableColumns))); Doctrine_Manager::getInstance()->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, false); } @@ -81,8 +87,8 @@ public function setUp() $this->actAs('Timestampable'); $this->actAs('SoftDelete'); $this->actAs('Versionable', array( - 'auditLog' => true, - 'generateRelations' => false, - 'deleteVersions' => false)); + 'auditLog' => true, + 'generateRelations' => false, + 'deleteVersions' => false)); } } diff --git a/tests/Ticket/DC828TestCase.php b/tests/Ticket/DC828TestCase.php index 8fb370e7a..75d04eb43 100644 --- a/tests/Ticket/DC828TestCase.php +++ b/tests/Ticket/DC828TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_DC828_TestCase + * Doctrine_Ticket_DC828_TestCase. * - * @package Doctrine * @author Enrico Stahn * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC828_TestCase extends Doctrine_UnitTestCase { diff --git a/tests/Ticket/DC82TestCase.php b/tests/Ticket/DC82TestCase.php index 72f212a73..e532d3c69 100644 --- a/tests/Ticket/DC82TestCase.php +++ b/tests/Ticket/DC82TestCase.php @@ -20,27 +20,33 @@ */ /** - * Doctrine_Ticket_DC82_TestCase + * Doctrine_Ticket_DC82_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC82_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC82_TestCase extends Doctrine_UnitTestCase { public function testTest() { $this->dbh = new Doctrine_Adapter_Mock('pgsql'); $this->conn = $this->manager->openConnection($this->dbh); - + $sql = $this->conn->export->exportClassesSql(array('Ticket_DC82_Article')); $this->assertEqual($sql, array( - "CREATE UNIQUE INDEX model_unique_title ON ticket__d_c82__article (title) WHERE deleted = false", - "CREATE TABLE ticket__d_c82__article (id BIGSERIAL, title VARCHAR(128) NOT NULL UNIQUE, deleted BOOLEAN DEFAULT 'false' NOT NULL, PRIMARY KEY(id))" + 'CREATE UNIQUE INDEX model_unique_title ON ticket__d_c82__article (title) WHERE deleted = false', + "CREATE TABLE ticket__d_c82__article (id BIGSERIAL, title VARCHAR(128) NOT NULL UNIQUE, deleted BOOLEAN DEFAULT 'false' NOT NULL, PRIMARY KEY(id))", )); } } @@ -51,6 +57,6 @@ public function setTableDefinition() { $this->hasColumn('title', 'string', 128, array('notnull', 'unique' => array('where' => 'deleted = false'))); $this->hasColumn('deleted', 'boolean', 1, array('notnull', 'default' => false)); - $this->index('model_unique_title', array('fields' => array('title'), 'where' => 'deleted = false', 'type' => 'unique' )); + $this->index('model_unique_title', array('fields' => array('title'), 'where' => 'deleted = false', 'type' => 'unique')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC840TestCase.php b/tests/Ticket/DC840TestCase.php index 89805466e..c82ffce07 100644 --- a/tests/Ticket/DC840TestCase.php +++ b/tests/Ticket/DC840TestCase.php @@ -20,20 +20,26 @@ */ /** - * Doctrine_Ticket_DC840_TestCase + * Doctrine_Ticket_DC840_TestCase. * - * @package Doctrine * @author Enrico Stahn * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC840_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC840_TestCase extends Doctrine_UnitTestCase { private $sqlStackCounter = 0; - + public function prepareTables() { $this->tables[] = 'Ticket_DC840_Model'; @@ -59,7 +65,7 @@ public function testTest() ->andWhere('modified_at >= ?', '2010-01-01') ; $q->execute(); - + $expected = "SELECT [t].[id] AS [t__id] FROM [ticket__d_c840__model] [t] WHERE ([t].[password] = 'abc' AND [t].[modified_at] > '2010-01-01' AND [t].[modified_at] < '2010-01-01' AND [t].[modified_at] <> '2010-01-01' AND [t].[modified_at] <= '2010-01-01' AND [t].[modified_at] >= '2010-01-01')"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); @@ -81,4 +87,4 @@ public function setTableDefinition() $this->hasColumn('username', 'string', 255); $this->hasColumn('password', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC841TestCase.php b/tests/Ticket/DC841TestCase.php index 89528b1eb..7c90efa65 100644 --- a/tests/Ticket/DC841TestCase.php +++ b/tests/Ticket/DC841TestCase.php @@ -20,20 +20,26 @@ */ /** - * Doctrine_Ticket_DC841_TestCase + * Doctrine_Ticket_DC841_TestCase. * - * @package Doctrine * @author Enrico Stahn * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC841_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC841_TestCase extends Doctrine_UnitTestCase { private $sqlStackCounter = 0; - + public function prepareTables() { $this->tables[] = 'Ticket_DC841_Model'; @@ -45,7 +51,7 @@ public function testInit() $this->dbh = new Doctrine_Adapter_Mock('mssql'); $this->conn = Doctrine_Manager::getInstance()->openConnection($this->dbh, 'DC841'); } - + public function testSelect() { Doctrine_Core::getTable('Ticket_DC841_Model') @@ -54,28 +60,30 @@ public function testSelect() ->andWhere('t.foo = ?', 't.foo = ?') ->andWhere('t.foo <> ?', 'bar') ->andWhere('t.foo LIKE ?', 'foo') - ->execute(); + ->execute() + ; $expected = "SELECT [t].[id] AS [t__id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo] FROM [ticket__d_c841__model] [t] WHERE ([t].[username] <> 'foo' AND [t].[foo] = 't.foo = ?' AND [t].[foo] <> 'bar' AND [t].[foo] LIKE 'foo')"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); $this->assertEqual($expected, $sql); } - + public function testSelectJoinWith() { Doctrine_Core::getTable('Ticket_DC841_Model') ->createQuery('t') ->leftJoin('t.Ticket_DC841_Model WITH t.id = ?', array(30)) ->where('t.username = ?', 'foo') - ->execute(); + ->execute() + ; $expected = "SELECT [t].[id] AS [t__id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo], [t2].[id] AS [t2__id], [t2].[username] AS [t2__username], [t2].[password] AS [t2__password], [t2].[foo] AS [t2__foo] FROM [ticket__d_c841__model] [t] LEFT JOIN [ticket__d_c841__model] [t2] ON [t].[id] = [t2].[id] AND ([t].[id] = 30) WHERE ([t].[username] = 'foo')"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); $this->assertEqual($expected, $sql); } - + public function testSelectWithStaticParameter() { return; // doesn't work @@ -83,42 +91,44 @@ public function testSelectWithStaticParameter() ->createQuery('t') ->where('t.username = ?', 'foo') ->andWhere("t.foo = 't.foo = ?'") - ->andWhere("t.password = ?", 'test') - ->execute(); + ->andWhere('t.password = ?', 'test') + ->execute() + ; $expected = "SELECT [t].[id] AS [t__id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo] FROM [ticket__d_c841__model] [t] WHERE ([t].[username] = 'foo' AND [t].[foo] = 't.foo = ?' AND [t].[password] = 'test')"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); $this->assertEqual($expected, $sql); } - + public function testSelectWithIn() { Doctrine_Core::getTable('Ticket_DC841_Model') ->createQuery('t') ->whereIn('t.username', array('foo', 'bar')) - ->execute(); + ->execute() + ; $expected = "SELECT [t].[id] AS [t__id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo] FROM [ticket__d_c841__model] [t] WHERE ([t].[username] IN ('foo', 'bar'))"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); $this->assertEqual($expected, $sql); } - + public function testInsert() { try { - $o = new Ticket_DC841_Model(); - $o->username = 'abc'; - $o->password = 'abc'; - $o->foo = 'abc'; - $o->save(); + $o = new Ticket_DC841_Model(); + $o->username = 'abc'; + $o->password = 'abc'; + $o->foo = 'abc'; + $o->save(); } catch (Doctrine_Connection_Exception $e) { // Ignore: Couldn't get last insert identifier. } - $this->sqlStackCounter += 1; - + ++$this->sqlStackCounter; + $expected = "INSERT INTO [ticket__d_c841__model] ([username], [password], [foo]) VALUES ('abc', 'abc', 'abc')"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); @@ -135,7 +145,7 @@ public function testUpdate() $o->state(Doctrine_Record::STATE_CLEAN); $this->sqlStackCounter += 7; - + $o->password = 'foobar'; $o->save(); @@ -155,10 +165,10 @@ public function testDelete() $o->state(Doctrine_Record::STATE_CLEAN); $this->sqlStackCounter += 5; - + $o->delete(); - $expected = "DELETE FROM [ticket__d_c841__model] WHERE [id] = 33"; + $expected = 'DELETE FROM [ticket__d_c841__model] WHERE [id] = 33'; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); $this->assertEqual($expected, $sql); @@ -179,11 +189,11 @@ public function setTableDefinition() $this->hasColumn('password', 'string', 255); $this->hasColumn('foo', 'string', 255); } - + public function setUp() { $this->hasOne('Ticket_DC841_Model', array( - 'local' => 'id', - 'foreign' => 'id')); + 'local' => 'id', + 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC843TestCase.php b/tests/Ticket/DC843TestCase.php index e51a2cad0..ff69abe8b 100644 --- a/tests/Ticket/DC843TestCase.php +++ b/tests/Ticket/DC843TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_DC843_TestCase + * Doctrine_Ticket_DC843_TestCase. * - * @package Doctrine * @author Enrico Stahn * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC843_TestCase extends Doctrine_UnitTestCase { @@ -62,7 +68,8 @@ public function testQuery() ->createQuery('t') ->where('t.username = ?', 'foo') ->andWhere('t.foo = ?', 'bar') - ->execute(); + ->execute() + ; $expected = "SELECT [t].[model_id] AS [t__model_id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo] FROM [ticket__d_c843__model] [t] WHERE ([t].[username] = 'foo' AND [t].[foo] LIKE 'bar')"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); @@ -76,7 +83,8 @@ public function testQueryWithLike() ->createQuery('t') ->where('t.username LIKE ?', 'foo') ->andWhere('t.foo = ?', 'bar') - ->execute(); + ->execute() + ; $expected = "SELECT [t].[model_id] AS [t__model_id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo] FROM [ticket__d_c843__model] [t] WHERE ([t].[username] LIKE 'foo' AND [t].[foo] LIKE 'bar')"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); @@ -90,7 +98,8 @@ public function testQueryWithNull() ->createQuery('t') ->where('t.username LIKE ?', 'foo') ->andWhere('t.foo IS NULL') - ->execute(); + ->execute() + ; $expected = "SELECT [t].[model_id] AS [t__model_id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo] FROM [ticket__d_c843__model] [t] WHERE ([t].[username] LIKE 'foo' AND [t].[foo] IS NULL)"; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); diff --git a/tests/Ticket/DC848TestCase.php b/tests/Ticket/DC848TestCase.php index 62f33edef..aa4241f8b 100644 --- a/tests/Ticket/DC848TestCase.php +++ b/tests/Ticket/DC848TestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Ticket_DC848_TestCase + * Doctrine_Ticket_DC848_TestCase. * - * @package Doctrine * @author Steffen Zeidler * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2.4 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_DC848_TestCase extends Doctrine_UnitTestCase { @@ -40,7 +46,6 @@ public function testIso8601Timestamp() $this->assertTrue($timestampValidator->validate($timestamp)); } - public function testMysqlTimestamp() { $timestamp = '2010-03-02 22:08:56'; @@ -48,5 +53,4 @@ public function testMysqlTimestamp() $this->assertTrue($timestampValidator->validate($timestamp)); } - -} \ No newline at end of file +} diff --git a/tests/Ticket/DC86TestCase.php b/tests/Ticket/DC86TestCase.php index fda614f28..29b700d2e 100644 --- a/tests/Ticket/DC86TestCase.php +++ b/tests/Ticket/DC86TestCase.php @@ -20,60 +20,71 @@ */ /** - * Doctrine_Ticket_DC86_TestCase + * Doctrine_Ticket_DC86_TestCase. * - * @package Doctrine * @author Jacek Dębowczyk * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC86_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC86_TestCase extends Doctrine_UnitTestCase { public function prepareTables() { $this->tables[] = 'Ticket_DC86_Test'; parent::prepareTables(); } - + public function prepareData() { - $r = new Ticket_DC86_Test(); - $r->id = 1; - $r->date = date('Y-m-d h:i:s', strtotime("- 10 week")); - $r->save(); + $r = new Ticket_DC86_Test(); + $r->id = 1; + $r->date = date('Y-m-d h:i:s', strtotime('- 10 week')); + $r->save(); - $r = new Ticket_DC86_Test(); - $r->id = 2; - $r->date = date('Y-m-d h:i:s', strtotime("- 5 week")); - $r->save(); + $r = new Ticket_DC86_Test(); + $r->id = 2; + $r->date = date('Y-m-d h:i:s', strtotime('- 5 week')); + $r->save(); - $r = new Ticket_DC86_Test(); - $r->id = 3; - $r->date = date('Y-m-d h:i:s', strtotime("+ 1 week")); - $r->save(); + $r = new Ticket_DC86_Test(); + $r->id = 3; + $r->date = date('Y-m-d h:i:s', strtotime('+ 1 week')); + $r->save(); } public function testTest() { - $past = Doctrine_Query::create()->from('Ticket_DC86_Test')->addWhere('date < now()')->orderBy('date')->execute(); - $this->assertEqual(2, count($past)); - $this->assertEqual(1, $past[0]->id); - $this->assertEqual(2, $past[1]->id); + $past = Doctrine_Query::create()->from('Ticket_DC86_Test')->addWhere('date < now()')->orderBy('date')->execute(); + $this->assertEqual(2, count($past)); + $this->assertEqual(1, $past[0]->id); + $this->assertEqual(2, $past[1]->id); - $future = Doctrine_Query::create()->from('Ticket_DC86_Test')->addWhere('date > now()')->orderBy('date')->execute(); - $this->assertEqual(1, count($future)); - $this->assertEqual(3, $future[0]->id); + $future = Doctrine_Query::create()->from('Ticket_DC86_Test')->addWhere('date > now()')->orderBy('date')->execute(); + $this->assertEqual(1, count($future)); + $this->assertEqual(3, $future[0]->id); } } +/** + * @internal + * + * @coversNothing + */ class Ticket_DC86_Test extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('id', 'integer', 4, array('primary', 'notnull')); + $this->hasColumn('id', 'integer', 4, array('primary', 'notnull')); $this->hasColumn('date', 'timestamp'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/DC879TestCase.php b/tests/Ticket/DC879TestCase.php index 22b3430e4..39fbd9699 100644 --- a/tests/Ticket/DC879TestCase.php +++ b/tests/Ticket/DC879TestCase.php @@ -20,16 +20,22 @@ */ /** -* Doctrine_Ticket_DC879_TestCase -* -* @package Doctrine -* @author Enrico Stahn -* @license http://www.opensource.org/licenses/lgpl-license.php LGPL -* @category Object Relational Mapping -* @link www.doctrine-project.org -* @since 1.0 -* @version $Revision$ -*/ + * Doctrine_Ticket_DC879_TestCase. + * + * @author Enrico Stahn + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * + * @category Object Relational Mapping + * + * @see www.doctrine-project.org + * @since 1.0 + * + * @version $Revision$ + * + * @internal + * + * @coversNothing + */ class Doctrine_Ticket_DC879_TestCase extends Doctrine_UnitTestCase { private $sqlStackCounter = 0; @@ -49,11 +55,12 @@ public function testInit() public function testWhere() { Doctrine_Core::getTable('Ticket_DC879_Model') - ->createQuery('t') - ->where('foo = DATE_PART("month", foo)') - ->execute(); + ->createQuery('t') + ->where('foo = DATE_PART("month", foo)') + ->execute() + ; - $expected = "SELECT [t].[model_id] AS [t__model_id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo] FROM [ticket__d_c879__model] [t] WHERE ([t].[foo] = DATEPART(month, [t].[foo]))"; + $expected = 'SELECT [t].[model_id] AS [t__model_id], [t].[username] AS [t__username], [t].[password] AS [t__password], [t].[foo] AS [t__foo] FROM [ticket__d_c879__model] [t] WHERE ([t].[foo] = DATEPART(month, [t].[foo]))'; $sql = current(array_slice($this->dbh->getAll(), $this->sqlStackCounter++, 1)); $this->assertEqual($expected, $sql); diff --git a/tests/Ticket/DC95TestCase.php b/tests/Ticket/DC95TestCase.php index 247e0378d..d84fdb29b 100644 --- a/tests/Ticket/DC95TestCase.php +++ b/tests/Ticket/DC95TestCase.php @@ -20,17 +20,23 @@ */ /** - * Doctrine_Ticket_DC95_TestCase + * Doctrine_Ticket_DC95_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Ticket_DC95_TestCase extends Doctrine_UnitTestCase +class Doctrine_Ticket_DC95_TestCase extends Doctrine_UnitTestCase { public function testClassDoesNotExistBeforeImport() { @@ -42,7 +48,7 @@ public function testClassDoesNotExistBeforeImport() public function testClassExistsAfterImport() { - Doctrine_Core::setModelsDirectory(dirname(__FILE__) . '/DC95/models'); + Doctrine_Core::setModelsDirectory(dirname(__FILE__).'/DC95/models'); $import = new Doctrine_Import_Schema(); $import->setOptions(array( @@ -50,10 +56,10 @@ public function testClassExistsAfterImport() 'baseClassesDirectory' => null, 'baseClassPrefix' => 'Base_', 'classPrefix' => 'DC95_', - 'classPrefixFiles' => true + 'classPrefixFiles' => true, )); - $modelsPath = dirname(__FILE__) . '/DC95/models'; - $import->importSchema(dirname(__FILE__) . '/DC95/schema.yml', 'yml', $modelsPath); + $modelsPath = dirname(__FILE__).'/DC95/models'; + $import->importSchema(dirname(__FILE__).'/DC95/schema.yml', 'yml', $modelsPath); /* $this->assertTrue(file_exists($modelsPath . '/DC95/Base/Article.php')); @@ -63,6 +69,6 @@ public function testClassExistsAfterImport() */ Doctrine_Core::setModelsDirectory(null); - Doctrine_Lib::removeDirectories(dirname(__FILE__) . '/DC95/models'); + Doctrine_Lib::removeDirectories(dirname(__FILE__).'/DC95/models'); } -} \ No newline at end of file +} diff --git a/tests/Ticket/NewTicketTestCase.php b/tests/Ticket/NewTicketTestCase.php index 8e99fc39a..e62466a9d 100644 --- a/tests/Ticket/NewTicketTestCase.php +++ b/tests/Ticket/NewTicketTestCase.php @@ -20,14 +20,20 @@ */ /** - * Doctrine_I18nRelation_TestCase + * Doctrine_I18nRelation_TestCase. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Ticket_NewTicket_TestCase extends Doctrine_UnitTestCase { @@ -71,8 +77,8 @@ public function prepareData() public function prepareTables() { - $this->tables = array('Testing_AttributeDefinition','Testing_Attribute', 'Testing_Product', - 'Testing_ProductAttribute'); + $this->tables = array('Testing_AttributeDefinition', 'Testing_Attribute', 'Testing_Product', + 'Testing_ProductAttribute'); parent::prepareTables(); } @@ -96,24 +102,24 @@ public function testTicket() // This query works perfect $r1 = $q1->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - //var_dump($r1); + // var_dump($r1); // This query throws an exception!!! $r2 = $q2->execute(array(), Doctrine_Core::HYDRATE_ARRAY); - //$r2 = $q2->execute(); - //var_dump($r2); + // $r2 = $q2->execute(); + // var_dump($r2); } - } class Testing_AttributeDefinition extends Doctrine_Record { - public function setTableDefinition() + public function setTableDefinition() { $this->setTableName('testing__attribute_definitions'); - $this->hasColumn('id', 'integer', 4, - array('primary'=>true,'autoincrement'=>true)); - $this->hasColumn('name', 'string', 64, array('notnull'=>true)); + $this->hasColumn('id', 'integer', 4, + array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 64, array('notnull' => true)); } + public function setUp() { } @@ -121,25 +127,26 @@ public function setUp() class Testing_Attribute extends Doctrine_Record { - public function setTableDefinition() + public function setTableDefinition() { $this->setTableName('testing__attributes'); - $this->hasColumn('id', 'integer', 4, - array('primary'=>true,'autoincrement'=>true)); - $this->hasColumn('attribute_definition_id', 'integer', 4, - array('notnull'=>true)); - $this->hasColumn('value', 'string', 255, array('notnull'=>false)); + $this->hasColumn('id', 'integer', 4, + array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('attribute_definition_id', 'integer', 4, + array('notnull' => true)); + $this->hasColumn('value', 'string', 255, array('notnull' => false)); } + public function setUp() { $this->hasOne( - 'Testing_AttributeDefinition as Definition', - array( - 'local' => 'attribute_definition_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE' - ) + 'Testing_AttributeDefinition as Definition', + array( + 'local' => 'attribute_definition_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + ) ); } } @@ -149,23 +156,23 @@ class Testing_Product extends Doctrine_Record public function setTableDefinition() { $this->setTableName('testing__products'); - $this->hasColumn('id', 'integer', 4, - array('primary'=>true,'autoincrement'=>true)); + $this->hasColumn('id', 'integer', 4, + array('primary' => true, 'autoincrement' => true)); $this->hasColumn('name', 'string', 40, - array('notnull'=>true)); + array('notnull' => true)); } + public function setUp() { - - $this->hasMany( - 'Testing_Attribute as Attributes', - array( - 'local' => 'product_id', - 'foreign' => 'attribute_id', - 'refClass' => 'Testing_ProductAttribute', - 'onDelete' => 'CASCADE', - ) - ); + $this->hasMany( + 'Testing_Attribute as Attributes', + array( + 'local' => 'product_id', + 'foreign' => 'attribute_id', + 'refClass' => 'Testing_ProductAttribute', + 'onDelete' => 'CASCADE', + ) + ); } } @@ -175,29 +182,29 @@ public function setTableDefinition() { $this->setTableName('testing__products_attributes'); - $this->hasColumn('product_id', 'integer', 4, array('primary'=>true, - 'notnull'=>true)); + $this->hasColumn('product_id', 'integer', 4, array('primary' => true, + 'notnull' => true)); $this->hasColumn('attribute_id', 'integer', 4, - array('primary'=>true, 'notnull'=>true)); + array('primary' => true, 'notnull' => true)); } + public function setUp() { $this->hasOne( - 'Testing_Product as Product', - array( - 'local' => 'product_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE' - ) + 'Testing_Product as Product', + array( + 'local' => 'product_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + ) ); $this->hasOne( - 'Testing_Attribute as Attribute', - array( - 'local' => 'attribute_id', - 'foreign' => 'id', - 'onDelete' => 'RESTRICT' - ) + 'Testing_Attribute as Attribute', + array( + 'local' => 'attribute_id', + 'foreign' => 'id', + 'onDelete' => 'RESTRICT', + ) ); } - -} \ No newline at end of file +} diff --git a/tests/Ticket/NjeroTestCase.php b/tests/Ticket/NjeroTestCase.php index 754e3cd55..e49bce976 100644 --- a/tests/Ticket/NjeroTestCase.php +++ b/tests/Ticket/NjeroTestCase.php @@ -1,20 +1,27 @@ * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ - class Doctrine_Ticket_Njero_TestCase extends Doctrine_UnitTestCase { - public function prepareData() { } - + public function prepareData() + { + } + public function prepareTables() { $this->tables[] = 'CoverageCodeN'; @@ -28,62 +35,62 @@ public function prepareTables() public function testHasOneMultiLevelRelations() { - $policy_code = new PolicyCodeN(); - $policy_code->code = 1; - $policy_code->description = "Special Policy"; - $policy_code->save(); - - $coverage_code = new CoverageCodeN(); - $coverage_code->code = 1; - $coverage_code->description = "Full Coverage"; - $coverage_code->save(); - - $coverage_code = new CoverageCodeN(); - $coverage_code->code = 3; # note we skip 2 - $coverage_code->description = "Partial Coverage"; - $coverage_code->save(); + $policy_code = new PolicyCodeN(); + $policy_code->code = 1; + $policy_code->description = 'Special Policy'; + $policy_code->save(); + + $coverage_code = new CoverageCodeN(); + $coverage_code->code = 1; + $coverage_code->description = 'Full Coverage'; + $coverage_code->save(); + + $coverage_code = new CoverageCodeN(); + $coverage_code->code = 3; // note we skip 2 + $coverage_code->description = 'Partial Coverage'; + $coverage_code->save(); + + $liability_code = new LiabilityCodeN(); + $liability_code->code = 1; + $liability_code->description = 'Limited Territory'; + $liability_code->save(); - $liability_code = new LiabilityCodeN(); - $liability_code->code = 1; - $liability_code->description = "Limited Territory"; - $liability_code->save(); + $rate = new RateN(); + $rate->policy_code = 1; + $rate->coverage_code = 3; + $rate->liability_code = 1; + $rate->total_rate = 123.45; + $rate->save(); - $rate = new RateN(); - $rate->policy_code = 1; - $rate->coverage_code = 3; - $rate->liability_code = 1; - $rate->total_rate = 123.45; - $rate->save(); - - $policy = new PolicyN(); - $policy->rate_id = 1; - $policy->policy_number = "123456789"; - $policy->save(); - - $q = new Doctrine_Query(); + $policy = new PolicyN(); + $policy->rate_id = 1; + $policy->policy_number = '123456789'; + $policy->save(); - # If I use - # $p = $q->from('PolicyN p') - # this test passes, but there is another issue just not reflected in this test yet, see "in my app" note below + $q = new Doctrine_Query(); - $q->from('PolicyN p, p.RateN r, r.PolicyCodeN y, r.CoverageCodeN c, r.LiabilityCodeN l') - ->where('(p.id = ?)', array('1')); + // If I use + // $p = $q->from('PolicyN p') + // this test passes, but there is another issue just not reflected in this test yet, see "in my app" note below - $p = $q->execute()->getFirst(); + $q->from('PolicyN p, p.RateN r, r.PolicyCodeN y, r.CoverageCodeN c, r.LiabilityCodeN l') + ->where('(p.id = ?)', array('1')) + ; - $this->assertEqual($p->rate_id, 1); - $this->assertEqual($p->RateN->id, 1); - $this->assertEqual($p->RateN->policy_code, 1); - $this->assertEqual($p->RateN->coverage_code, 3); # fail - $this->assertEqual($p->RateN->liability_code, 1); + $p = $q->execute()->getFirst(); - $c = $p->RateN->coverage_code; - $c2 = $p->RateN->CoverageCodeN->code; - $c3 = $p->RateN->coverage_code; + $this->assertEqual($p->rate_id, 1); + $this->assertEqual($p->RateN->id, 1); + $this->assertEqual($p->RateN->policy_code, 1); + $this->assertEqual($p->RateN->coverage_code, 3); // fail + $this->assertEqual($p->RateN->liability_code, 1); - $this->assertEqual($c, $c2); # fail - $this->assertEqual($c, $c3); # in my app this fails as well, but I can't reproduce this - #echo "Values " . serialize(array($c, $c2, $c3)); + $c = $p->RateN->coverage_code; + $c2 = $p->RateN->CoverageCodeN->code; + $c3 = $p->RateN->coverage_code; + $this->assertEqual($c, $c2); // fail + $this->assertEqual($c, $c3); // in my app this fails as well, but I can't reproduce this + // echo "Values " . serialize(array($c, $c2, $c3)); } } diff --git a/tests/TokenizerTestCase.php b/tests/TokenizerTestCase.php index 4e7e7f4d5..b20f3c586 100644 --- a/tests/TokenizerTestCase.php +++ b/tests/TokenizerTestCase.php @@ -21,94 +21,104 @@ /** * Doctrine_Tokenizer_TestCase - * This class tests the functinality of Doctrine_Tokenizer component + * This class tests the functinality of Doctrine_Tokenizer component. * - * @package Doctrine * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1181 $ + * * @author Konsta Vesterinen + * + * @internal + * + * @coversNothing */ class Doctrine_Tokenizer_TestCase extends Doctrine_UnitTestCase { public function prepareData() - { } + { + } + public function prepareTables() - { } + { + } public function testSqlExplode() { $tokenizer = new Doctrine_Query_Tokenizer(); - $str = "word1 word2 word3"; - $a = $tokenizer->sqlExplode($str); + $str = 'word1 word2 word3'; + $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "word2", "word3")); + $this->assertEqual($a, array('word1', 'word2', 'word3')); - $str = "word1 (word2 word3)"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "(word2 word3)")); + $str = 'word1 (word2 word3)'; + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', '(word2 word3)')); $str = "word1 'word2 word3'"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "'word2 word3'")); + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', "'word2 word3'")); $str = "word1 'word2 word3'"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "'word2 word3'")); + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', "'word2 word3'")); - $str = "word1 \"word2 word3\""; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "\"word2 word3\"")); + $str = 'word1 "word2 word3"'; + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', '"word2 word3"')); - $str = "word1 ((word2) word3)"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "((word2) word3)")); + $str = 'word1 ((word2) word3)'; + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', '((word2) word3)')); $str = "word1 ( (word2) 'word3')"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "( (word2) 'word3')")); + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', "( (word2) 'word3')")); $str = "word1 ( \"(word2) 'word3')"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "( \"(word2) 'word3')")); + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', "( \"(word2) 'word3')")); $str = "word1 ( ''(word2) 'word3')"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "( ''(word2) 'word3')")); + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', "( ''(word2) 'word3')")); $str = "word1 ( '()()'(word2) 'word3')"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "( '()()'(word2) 'word3')")); + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', "( '()()'(word2) 'word3')")); $str = "word1 'word2)() word3'"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "'word2)() word3'")); + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', "'word2)() word3'")); - $str = "word1 (word2() word3)"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "(word2() word3)")); + $str = 'word1 (word2() word3)'; + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', '(word2() word3)')); - $str = "word1 \"word2)() word3\""; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("word1", "\"word2)() word3\"")); + $str = 'word1 "word2)() word3"'; + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('word1', '"word2)() word3"')); $str = "something (subquery '')"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("something", "(subquery '')")); + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('something', "(subquery '')")); - $str = "something (( ))"; - $a = $tokenizer->sqlExplode($str); - $this->assertEqual($a, array("something", "(( ))")); + $str = 'something (( ))'; + $a = $tokenizer->sqlExplode($str); + $this->assertEqual($a, array('something', '(( ))')); } public function testSqlExplode2() { $tokenizer = new Doctrine_Query_Tokenizer(); $str = 'rdbms (dbal OR database)'; - $a = $tokenizer->sqlExplode($str, ' OR '); + $a = $tokenizer->sqlExplode($str, ' OR '); $this->assertEqual($a, array('rdbms (dbal OR database)')); } @@ -118,29 +128,29 @@ public function testBracketExplode() $tokenizer = new Doctrine_Query_Tokenizer(); $str = 'foo.field AND bar.field'; - $a = $tokenizer->bracketExplode($str, array(' \&\& ', ' AND '), '(', ')'); + $a = $tokenizer->bracketExplode($str, array(' \&\& ', ' AND '), '(', ')'); $this->assertEqual($a, array('foo.field', 'bar.field')); // delimiters should be case insensitive $str = 'foo.field and bar.field'; - $a = $tokenizer->bracketExplode($str, array(' \&\& ', ' AND '), '(', ')'); + $a = $tokenizer->bracketExplode($str, array(' \&\& ', ' AND '), '(', ')'); $this->assertEqual($a, array('foo.field', 'bar.field')); // test the JOIN splitter as used in Doctrine_Query_From::parse() $str = 'foo.field join bar.field'; - $a = $tokenizer->bracketExplode($str, 'JOIN'); + $a = $tokenizer->bracketExplode($str, 'JOIN'); $this->assertEqual($a, array('foo.field', 'bar.field')); // test that table names including the split string are unaffected $str = 'foojointable.field join bar.field'; - $a = $tokenizer->bracketExplode($str, 'JOIN'); + $a = $tokenizer->bracketExplode($str, 'JOIN'); $this->assertEqual($a, array('foojointable.field', 'bar.field')); } public function testQuoteExplodedShouldQuoteArray() { $tokenizer = new Doctrine_Query_Tokenizer(); - $term = $tokenizer->quoteExplode("test", array("'test'", "test2")); - $this->assertEqual($term[0], "test"); + $term = $tokenizer->quoteExplode('test', array("'test'", 'test2')); + $this->assertEqual($term[0], 'test'); } -} \ No newline at end of file +} diff --git a/tests/Transaction/MssqlTestCase.php b/tests/Transaction/MssqlTestCase.php index 2d1f0ed7b..48ce430e5 100644 --- a/tests/Transaction/MssqlTestCase.php +++ b/tests/Transaction/MssqlTestCase.php @@ -20,43 +20,51 @@ */ /** - * Doctrine_Transaction_Mssql_TestCase + * Doctrine_Transaction_Mssql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Transaction_Mssql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Transaction_Mssql_TestCase extends Doctrine_UnitTestCase { - public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() + public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() { try { $this->transaction->setIsolation('unknown'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); } } - public function testSetIsolationExecutesSql() + + public function testSetIsolationExecutesSql() { $this->transaction->setIsolation('READ UNCOMMITTED'); $this->transaction->setIsolation('READ COMMITTED'); $this->transaction->setIsolation('REPEATABLE READ'); - $this->transaction->setIsolation('SERIALIZABLE'); + $this->transaction->setIsolation('SERIALIZABLE'); $this->assertEqual($this->adapter->pop(), 'SET TRANSACTION ISOLATION LEVEL SERIALIZABLE'); $this->assertEqual($this->adapter->pop(), 'SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'); $this->assertEqual($this->adapter->pop(), 'SET TRANSACTION ISOLATION LEVEL READ COMMITTED'); $this->assertEqual($this->adapter->pop(), 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED'); } - public function testSetIsolationSupportsSnapshotMode() + + public function testSetIsolationSupportsSnapshotMode() { $this->transaction->setIsolation('SNAPSHOT'); $this->assertEqual($this->adapter->pop(), 'SET TRANSACTION ISOLATION LEVEL SNAPSHOT'); } -} \ No newline at end of file +} diff --git a/tests/Transaction/MysqlTestCase.php b/tests/Transaction/MysqlTestCase.php index 413f6ab61..cad2f467e 100644 --- a/tests/Transaction/MysqlTestCase.php +++ b/tests/Transaction/MysqlTestCase.php @@ -20,53 +20,64 @@ */ /** - * Doctrine_Transaction_Mysql_TestCase + * Doctrine_Transaction_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Transaction_Mysql_TestCase extends Doctrine_UnitTestCase { - public function testCreateSavePointExecutesSql() + public function testCreateSavePointExecutesSql() { $this->transaction->beginTransaction('mypoint'); $this->assertEqual($this->adapter->pop(), 'SAVEPOINT mypoint'); } - public function testReleaseSavePointExecutesSql() + + public function testReleaseSavePointExecutesSql() { $this->transaction->commit('mypoint'); $this->assertEqual($this->adapter->pop(), 'RELEASE SAVEPOINT mypoint'); } - public function testRollbackSavePointExecutesSql() + + public function testRollbackSavePointExecutesSql() { $this->transaction->beginTransaction('mypoint'); $this->transaction->rollback('mypoint'); $this->assertEqual($this->adapter->pop(), 'ROLLBACK TO SAVEPOINT mypoint'); } - public function testGetIsolationExecutesSql() + + public function testGetIsolationExecutesSql() { $this->transaction->getIsolation(); $this->assertEqual($this->adapter->pop(), 'SELECT @@tx_isolation'); } - public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() + + public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() { try { $this->transaction->setIsolation('unknown'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); } } - public function testSetIsolationExecutesSql() + + public function testSetIsolationExecutesSql() { $this->transaction->setIsolation('READ UNCOMMITTED'); diff --git a/tests/Transaction/OracleTestCase.php b/tests/Transaction/OracleTestCase.php index 97600f5d7..0a5580683 100644 --- a/tests/Transaction/OracleTestCase.php +++ b/tests/Transaction/OracleTestCase.php @@ -20,45 +20,55 @@ */ /** - * Doctrine_Transaction_Mysql_TestCase + * Doctrine_Transaction_Mysql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Transaction_Oracle_TestCase extends Doctrine_UnitTestCase { - public function testCreateSavePointExecutesSql() + public function testCreateSavePointExecutesSql() { $this->transaction->beginTransaction('mypoint'); - + $this->assertEqual($this->adapter->pop(), 'SAVEPOINT mypoint'); } - public function testReleaseSavePointAlwaysReturnsTrue() + + public function testReleaseSavePointAlwaysReturnsTrue() { $this->assertEqual($this->transaction->commit('mypoint'), true); } - public function testRollbackSavePointExecutesSql() + + public function testRollbackSavePointExecutesSql() { $this->transaction->beginTransaction('mypoint'); $this->transaction->rollback('mypoint'); $this->assertEqual($this->adapter->pop(), 'ROLLBACK TO SAVEPOINT mypoint'); } - public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() + + public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() { try { $this->transaction->setIsolation('unknown'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); } } - public function testSetIsolationExecutesSql() + + public function testSetIsolationExecutesSql() { $this->transaction->setIsolation('READ UNCOMMITTED'); $this->transaction->setIsolation('READ COMMITTED'); diff --git a/tests/Transaction/PgsqlTestCase.php b/tests/Transaction/PgsqlTestCase.php index cc7526b67..4a77b5dfd 100644 --- a/tests/Transaction/PgsqlTestCase.php +++ b/tests/Transaction/PgsqlTestCase.php @@ -20,47 +20,57 @@ */ /** - * Doctrine_Transaction_Pgsql_TestCase + * Doctrine_Transaction_Pgsql_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Transaction_Pgsql_TestCase extends Doctrine_UnitTestCase +class Doctrine_Transaction_Pgsql_TestCase extends Doctrine_UnitTestCase { - public function testCreateSavePointExecutesSql() + public function testCreateSavePointExecutesSql() { $this->transaction->beginTransaction('mypoint'); - + $this->assertEqual($this->adapter->pop(), 'SAVEPOINT mypoint'); } - public function testReleaseSavePointExecutesSql() + + public function testReleaseSavePointExecutesSql() { $this->transaction->commit('mypoint'); $this->assertEqual($this->adapter->pop(), 'RELEASE SAVEPOINT mypoint'); } - public function testRollbackSavePointExecutesSql() + + public function testRollbackSavePointExecutesSql() { $this->transaction->beginTransaction('mypoint'); $this->transaction->rollback('mypoint'); $this->assertEqual($this->adapter->pop(), 'ROLLBACK TO SAVEPOINT mypoint'); } - public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() + + public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() { try { $this->transaction->setIsolation('unknown'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); } } - public function testSetIsolationExecutesSql() + + public function testSetIsolationExecutesSql() { $this->transaction->setIsolation('READ UNCOMMITTED'); diff --git a/tests/Transaction/SqliteTestCase.php b/tests/Transaction/SqliteTestCase.php index 7e68c0aa5..60c0dc2b8 100644 --- a/tests/Transaction/SqliteTestCase.php +++ b/tests/Transaction/SqliteTestCase.php @@ -20,34 +20,41 @@ */ /** - * Doctrine_Transaction_Sqlite_TestCase + * Doctrine_Transaction_Sqlite_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Transaction_Sqlite_TestCase extends Doctrine_UnitTestCase +class Doctrine_Transaction_Sqlite_TestCase extends Doctrine_UnitTestCase { - public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() + public function testSetIsolationThrowsExceptionOnUnknownIsolationMode() { try { $this->transaction->setIsolation('unknown'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); } } - public function testSetIsolationExecutesSql() + + public function testSetIsolationExecutesSql() { $this->transaction->setIsolation('READ UNCOMMITTED'); $this->transaction->setIsolation('READ COMMITTED'); $this->transaction->setIsolation('REPEATABLE READ'); - $this->transaction->setIsolation('SERIALIZABLE'); - + $this->transaction->setIsolation('SERIALIZABLE'); + $this->assertEqual($this->adapter->pop(), 'PRAGMA read_uncommitted = 1'); $this->assertEqual($this->adapter->pop(), 'PRAGMA read_uncommitted = 1'); $this->assertEqual($this->adapter->pop(), 'PRAGMA read_uncommitted = 1'); diff --git a/tests/TransactionTestCase.php b/tests/TransactionTestCase.php index f9d8ca2d6..0ec5cd65a 100644 --- a/tests/TransactionTestCase.php +++ b/tests/TransactionTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Transaction_TestCase + * Doctrine_Transaction_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Transaction_TestCase extends Doctrine_UnitTestCase { @@ -47,7 +53,7 @@ public function testCreateSavepointListenersGetInvoked() $this->transaction->beginTransaction('point'); $this->pass(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->fail(); } @@ -61,7 +67,7 @@ public function testCommitSavepointListenersGetInvoked() $this->transaction->commit('point'); $this->pass(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->fail(); } @@ -94,7 +100,7 @@ public function testRollbackSavepointListenersGetInvoked() $this->transaction->rollback('point'); $this->pass(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->fail(); } @@ -108,12 +114,12 @@ public function testRollbackSavepointListenersGetInvoked() $this->conn->setListener($this->listener); } - public function testCreateSavepointIsOnlyImplementedAtDriverLevel() + public function testCreateSavepointIsOnlyImplementedAtDriverLevel() { try { $this->transaction->beginTransaction('savepoint'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); } } @@ -128,22 +134,22 @@ public function testReleaseSavepointIsOnlyImplementedAtDriverLevel() } } - public function testRollbackSavepointIsOnlyImplementedAtDriverLevel() + public function testRollbackSavepointIsOnlyImplementedAtDriverLevel() { try { $this->transaction->rollback('savepoint'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); - } + } } - public function testSetIsolationIsOnlyImplementedAtDriverLevel() + public function testSetIsolationIsOnlyImplementedAtDriverLevel() { try { $this->transaction->setIsolation('READ UNCOMMITTED'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); } } @@ -153,16 +159,16 @@ public function testGetIsolationIsOnlyImplementedAtDriverLevel() try { $this->transaction->GetIsolation('READ UNCOMMITTED'); $this->fail(); - } catch(Doctrine_Transaction_Exception $e) { + } catch (Doctrine_Transaction_Exception $e) { $this->pass(); } } - public function testTransactionLevelIsInitiallyZero() + public function testTransactionLevelIsInitiallyZero() { $this->assertEqual($this->transaction->getTransactionLevel(), 0); } - + public function testSubsequentTransactionsAfterRollback() { try { @@ -183,29 +189,28 @@ public function testSubsequentTransactionsAfterRollback() $this->assertEqual(0, $this->transaction->getTransactionLevel()); $this->assertEqual(0, $this->transaction->getInternalTransactionLevel()); } - + $i = 0; while ($i < 5) { $this->assertEqual(0, $this->transaction->getTransactionLevel()); - $this->transaction->beginTransaction(); + $this->transaction->beginTransaction(); $this->assertEqual(1, $this->transaction->getTransactionLevel()); - try { - if ($i == 0) { - throw new Exception(); - } - $this->transaction->commit(); - } - catch (Exception $e) { - $this->transaction->rollback(); + try { + if (0 == $i) { + throw new Exception(); + } + $this->transaction->commit(); + } catch (Exception $e) { + $this->transaction->rollback(); $this->assertEqual(0, $this->transaction->getTransactionLevel()); - } - ++$i; - } + } + ++$i; + } } - public function testGetStateReturnsStateConstant() + public function testGetStateReturnsStateConstant() { - $this->assertEqual($this->transaction->getState(), Doctrine_Transaction::STATE_SLEEP); + $this->assertEqual($this->transaction->getState(), Doctrine_Transaction::STATE_SLEEP); } public function testCommittingWithNoActiveTransactionThrowsException() @@ -218,7 +223,7 @@ public function testCommittingWithNoActiveTransactionThrowsException() } } - public function testExceptionIsThrownWhenUsingRollbackOnNotActiveTransaction() + public function testExceptionIsThrownWhenUsingRollbackOnNotActiveTransaction() { try { $this->transaction->rollback(); @@ -228,11 +233,11 @@ public function testExceptionIsThrownWhenUsingRollbackOnNotActiveTransaction() } } - public function testBeginTransactionStartsNewTransaction() + public function testBeginTransactionStartsNewTransaction() { - $this->transaction->beginTransaction(); + $this->transaction->beginTransaction(); - $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); + $this->assertEqual($this->adapter->pop(), 'BEGIN TRANSACTION'); } public function testCommitMethodCommitsCurrentTransaction() @@ -241,13 +246,14 @@ public function testCommitMethodCommitsCurrentTransaction() $this->assertEqual($this->adapter->pop(), 'COMMIT'); } + public function testNestedTransaction() { $conn = Doctrine_Manager::connection(); - + try { $conn->beginTransaction(); - + // Create new client $user = new User(); $user->set('name', 'Test User'); @@ -259,11 +265,11 @@ public function testNestedTransaction() $phonenumber->set('phonenumber', '123 123'); $phonenumber->save(); - $conn->commit(); + $conn->commit(); } catch (Exception $e) { $conn->rollback(); } - + $this->assertTrue($user->id > 0); $this->assertTrue($phonenumber->id > 0); } @@ -277,9 +283,8 @@ public function testAddDuplicateRecordToTransactionShouldSkipSecond() $transaction->addInvalid($user); $this->assertEqual(1, count($transaction->getInvalid())); } - } -class TransactionListener extends Doctrine_EventListener +class TransactionListener extends Doctrine_EventListener { protected $_messages = array(); @@ -289,6 +294,7 @@ public function preTransactionCommit(Doctrine_Event $event) $event->skipOperation(); } + public function postTransactionCommit(Doctrine_Event $event) { $this->_messages[] = __FUNCTION__; @@ -300,6 +306,7 @@ public function preTransactionRollback(Doctrine_Event $event) $event->skipOperation(); } + public function postTransactionRollback(Doctrine_Event $event) { $this->_messages[] = __FUNCTION__; @@ -311,20 +318,21 @@ public function preTransactionBegin(Doctrine_Event $event) $event->skipOperation(); } + public function postTransactionBegin(Doctrine_Event $event) - { + { $this->_messages[] = __FUNCTION__; } - public function preSavepointCommit(Doctrine_Event $event) - { + { $this->_messages[] = __FUNCTION__; $event->skipOperation(); } + public function postSavepointCommit(Doctrine_Event $event) - { + { $this->_messages[] = __FUNCTION__; } @@ -334,23 +342,24 @@ public function preSavepointRollback(Doctrine_Event $event) $event->skipOperation(); } + public function postSavepointRollback(Doctrine_Event $event) - { + { $this->_messages[] = __FUNCTION__; } public function preSavepointCreate(Doctrine_Event $event) - { + { $this->_messages[] = __FUNCTION__; $event->skipOperation(); } public function postSavepointCreate(Doctrine_Event $event) - { + { $this->_messages[] = __FUNCTION__; } - + public function pop() { return array_pop($this->_messages); diff --git a/tests/TreeStructureTestCase.php b/tests/TreeStructureTestCase.php index c61c42795..9be0c2c55 100644 --- a/tests/TreeStructureTestCase.php +++ b/tests/TreeStructureTestCase.php @@ -20,31 +20,36 @@ */ /** - * Doctrine_TreeStructure_TestCase + * Doctrine_TreeStructure_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_TreeStructure_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() - { + public function prepareTables() + { // we don't need the standard tables here $this->tables = array('TreeLeaf'); parent::prepareTables(); } - + public function prepareData() { - } - public function testSelfReferentialRelationship() + public function testSelfReferentialRelationship() { $component = new TreeLeaf(); @@ -52,12 +57,13 @@ public function testSelfReferentialRelationship() $rel = $component->getTable()->getRelation('Parent'); $rel = $component->getTable()->getRelation('Children'); $this->pass(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $this->fail(); } } - public function testLocalAndForeignKeysAreSetCorrectly() { + public function testLocalAndForeignKeysAreSetCorrectly() + { $component = new TreeLeaf(); $rel = $component->getTable()->getRelation('Parent'); @@ -69,7 +75,7 @@ public function testLocalAndForeignKeysAreSetCorrectly() { $this->assertEqual($rel->getForeign(), 'parent_id'); } - public function testTreeLeafRelationships() + public function testTreeLeafRelationships() { /* structure: * @@ -88,16 +94,16 @@ public function testTreeLeafRelationships() $o1->save(); $o2 = new TreeLeaf(); - $o2->name = 'o2'; + $o2->name = 'o2'; $o2->Parent = $o1; $o2->save(); $o3 = new TreeLeaf(); - $o3->name = 'o3'; + $o3->name = 'o3'; $o3->Parent = $o1; $o3->save(); - //$o1->refresh(); + // $o1->refresh(); $o4 = new TreeLeaf(); $o4->name = 'o4'; @@ -107,22 +113,22 @@ public function testTreeLeafRelationships() $this->assertTrue(isset($o2->Parent)); $this->assertTrue($o2->Parent === $o1); $this->assertFalse(isset($o4->Parent)); - - $this->assertTrue(count($o1->Children) == 2); - $this->assertTrue(count($o1->get('Children')) == 2); - $this->assertTrue(count($o4->Children) == 0); + $this->assertTrue(2 == count($o1->Children)); + $this->assertTrue(2 == count($o1->get('Children'))); + + $this->assertTrue(0 == count($o4->Children)); } + public function testTreeStructureFetchingWorksWithDql() { $q = new Doctrine_Query(); $q->select('l.*, c.*') - ->from('TreeLeaf l, l.Children c') - ->where('l.parent_id IS NULL') - ->groupby('l.id, c.id'); + ->from('TreeLeaf l, l.Children c') + ->where('l.parent_id IS NULL') + ->groupby('l.id, c.id') + ; $coll = $q->execute(); - } } - diff --git a/tests/UnitOfWorkTestCase.php b/tests/UnitOfWorkTestCase.php index b9cf2346a..9ebd55777 100644 --- a/tests/UnitOfWorkTestCase.php +++ b/tests/UnitOfWorkTestCase.php @@ -20,32 +20,41 @@ */ /** - * Doctrine_UnitOfWork_TestCase + * Doctrine_UnitOfWork_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_UnitOfWork_TestCase extends Doctrine_UnitTestCase { - private $correct = array('Task', 'ResourceType', 'Resource', 'Assignment', 'ResourceReference'); - private $correct2 = array ( - 0 => 'Resource', - 1 => 'Task', - 2 => 'ResourceType', - 3 => 'Assignment', - 4 => 'ResourceReference', - ); - public function testbuildFlushTree() { +class Doctrine_UnitOfWork_TestCase extends Doctrine_UnitTestCase +{ + private $correct = array('Task', 'ResourceType', 'Resource', 'Assignment', 'ResourceReference'); + private $correct2 = array( + 0 => 'Resource', + 1 => 'Task', + 2 => 'ResourceType', + 3 => 'Assignment', + 4 => 'ResourceReference', + ); + + public function testbuildFlushTree() + { $task = new Task(); $tree = $this->unitOfWork->buildFlushTree(array('Task')); $this->assertEqual($tree, array('Task')); - $tree = $this->unitOfWork->buildFlushTree(array('Task','Resource')); + $tree = $this->unitOfWork->buildFlushTree(array('Task', 'Resource')); $this->assertEqual($tree, array('Task', 'Resource', 'Assignment')); $tree = $this->unitOfWork->buildFlushTree(array('Task', 'Assignment', 'Resource')); @@ -54,86 +63,108 @@ public function testbuildFlushTree() { $tree = $this->unitOfWork->buildFlushTree(array('Assignment', 'Task', 'Resource')); $this->assertEqual($tree, array('Resource', 'Task', 'Assignment')); } - public function testbuildFlushTree2() { - $this->correct = array('Forum_Category','Forum_Board','Forum_Thread'); + + public function testbuildFlushTree2() + { + $this->correct = array('Forum_Category', 'Forum_Board', 'Forum_Thread'); $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board')); $this->assertEqual($tree, array('Forum_Board')); - - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category','Forum_Board')); + + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category', 'Forum_Board')); $this->assertEqual($tree, array('Forum_Category', 'Forum_Board')); } - public function testBuildFlushTree3() { - $this->correct = array('Forum_Category','Forum_Board','Forum_Thread','Forum_Entry'); - - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry','Forum_Board')); - $this->assertEqual($tree, array('Forum_Entry','Forum_Board')); - - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board','Forum_Entry')); - $this->assertEqual($tree, array('Forum_Board','Forum_Entry')); + + public function testBuildFlushTree3() + { + $this->correct = array('Forum_Category', 'Forum_Board', 'Forum_Thread', 'Forum_Entry'); + + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry', 'Forum_Board')); + $this->assertEqual($tree, array('Forum_Entry', 'Forum_Board')); + + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board', 'Forum_Entry')); + $this->assertEqual($tree, array('Forum_Board', 'Forum_Entry')); } - public function testBuildFlushTree4() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread','Forum_Board')); + + public function testBuildFlushTree4() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread', 'Forum_Board')); + $this->assertEqual($tree, array('Forum_Board', 'Forum_Thread')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board', 'Forum_Thread')); $this->assertEqual($tree, array('Forum_Board', 'Forum_Thread')); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board','Forum_Thread')); - $this->assertEqual($tree, array('Forum_Board','Forum_Thread')); } - public function testBuildFlushTree5() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board','Forum_Thread','Forum_Entry')); - $this->assertEqual($tree, array('Forum_Board','Forum_Thread','Forum_Entry')); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board','Forum_Entry','Forum_Thread')); - $this->assertEqual($tree, array('Forum_Board','Forum_Thread','Forum_Entry')); + + public function testBuildFlushTree5() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board', 'Forum_Thread', 'Forum_Entry')); + $this->assertEqual($tree, array('Forum_Board', 'Forum_Thread', 'Forum_Entry')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board', 'Forum_Entry', 'Forum_Thread')); + $this->assertEqual($tree, array('Forum_Board', 'Forum_Thread', 'Forum_Entry')); } - public function testBuildFlushTree6() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry','Forum_Board','Forum_Thread')); - $this->assertEqual($tree, array('Forum_Board','Forum_Thread','Forum_Entry')); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry','Forum_Thread','Forum_Board')); - $this->assertEqual($tree, array('Forum_Board','Forum_Thread','Forum_Entry')); + + public function testBuildFlushTree6() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry', 'Forum_Board', 'Forum_Thread')); + $this->assertEqual($tree, array('Forum_Board', 'Forum_Thread', 'Forum_Entry')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry', 'Forum_Thread', 'Forum_Board')); + $this->assertEqual($tree, array('Forum_Board', 'Forum_Thread', 'Forum_Entry')); } - public function testBuildFlushTree7() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread','Forum_Board','Forum_Entry')); - $this->assertEqual($tree, array('Forum_Board','Forum_Thread','Forum_Entry')); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread','Forum_Entry','Forum_Board')); - $this->assertEqual($tree, array('Forum_Board','Forum_Thread','Forum_Entry')); + + public function testBuildFlushTree7() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread', 'Forum_Board', 'Forum_Entry')); + $this->assertEqual($tree, array('Forum_Board', 'Forum_Thread', 'Forum_Entry')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread', 'Forum_Entry', 'Forum_Board')); + $this->assertEqual($tree, array('Forum_Board', 'Forum_Thread', 'Forum_Entry')); } - public function testBuildFlushTree8() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board','Forum_Thread','Forum_Category')); - $this->assertEqual($tree, array('Forum_Category','Forum_Board','Forum_Thread')); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category','Forum_Thread','Forum_Board')); - $this->assertEqual($tree, array('Forum_Category','Forum_Board','Forum_Thread')); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread','Forum_Board','Forum_Category')); - $this->assertEqual($tree, array('Forum_Category','Forum_Board','Forum_Thread')); + + public function testBuildFlushTree8() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board', 'Forum_Thread', 'Forum_Category')); + $this->assertEqual($tree, array('Forum_Category', 'Forum_Board', 'Forum_Thread')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category', 'Forum_Thread', 'Forum_Board')); + $this->assertEqual($tree, array('Forum_Category', 'Forum_Board', 'Forum_Thread')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread', 'Forum_Board', 'Forum_Category')); + $this->assertEqual($tree, array('Forum_Category', 'Forum_Board', 'Forum_Thread')); } - public function testBuildFlushTree9() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board','Forum_Thread','Forum_Category','Forum_Entry')); + + public function testBuildFlushTree9() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board', 'Forum_Thread', 'Forum_Category', 'Forum_Entry')); $this->assertEqual($tree, $this->correct); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board','Forum_Thread','Forum_Entry','Forum_Category')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board', 'Forum_Thread', 'Forum_Entry', 'Forum_Category')); $this->assertEqual($tree, $this->correct); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board','Forum_Category','Forum_Thread','Forum_Entry')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Board', 'Forum_Category', 'Forum_Thread', 'Forum_Entry')); $this->assertEqual($tree, $this->correct); } - public function testBuildFlushTree10() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry','Forum_Thread','Forum_Board','Forum_Category')); + + public function testBuildFlushTree10() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry', 'Forum_Thread', 'Forum_Board', 'Forum_Category')); $this->assertEqual($tree, $this->correct); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry','Forum_Thread','Forum_Category','Forum_Board')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry', 'Forum_Thread', 'Forum_Category', 'Forum_Board')); $this->assertEqual($tree, $this->correct); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry','Forum_Category','Forum_Board','Forum_Thread')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Entry', 'Forum_Category', 'Forum_Board', 'Forum_Thread')); $this->assertEqual($tree, $this->correct); } - public function testBuildFlushTree11() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread','Forum_Category','Forum_Board','Forum_Entry')); + + public function testBuildFlushTree11() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread', 'Forum_Category', 'Forum_Board', 'Forum_Entry')); $this->assertEqual($tree, $this->correct); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread','Forum_Entry','Forum_Category','Forum_Board')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread', 'Forum_Entry', 'Forum_Category', 'Forum_Board')); $this->assertEqual($tree, $this->correct); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread','Forum_Board','Forum_Entry','Forum_Category')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Thread', 'Forum_Board', 'Forum_Entry', 'Forum_Category')); $this->assertEqual($tree, $this->correct); } - public function testBuildFlushTree12() { - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category','Forum_Entry','Forum_Board','Forum_Thread')); + + public function testBuildFlushTree12() + { + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category', 'Forum_Entry', 'Forum_Board', 'Forum_Thread')); $this->assertEqual($tree, $this->correct); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category','Forum_Thread','Forum_Entry','Forum_Board')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category', 'Forum_Thread', 'Forum_Entry', 'Forum_Board')); $this->assertEqual($tree, $this->correct); - $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category','Forum_Board','Forum_Thread','Forum_Entry')); + $tree = $this->unitOfWork->buildFlushTree(array('Forum_Category', 'Forum_Board', 'Forum_Thread', 'Forum_Entry')); $this->assertEqual($tree, $this->correct); } } diff --git a/tests/UnsortedTestCase.php b/tests/UnsortedTestCase.php index 097fe42fa..0a2a050d0 100644 --- a/tests/UnsortedTestCase.php +++ b/tests/UnsortedTestCase.php @@ -4,26 +4,31 @@ * Tests in this file are unsorted, and should be placed in an appropriate * test file. If you are unsure where to put a unit test, place them in here * and hopefully someone else will move them. + * + * @internal + * + * @coversNothing */ -class Doctrine_UnsortedTestCase extends Doctrine_UnitTestCase { - public function testCascadingInsert() - { - $package = new Package(); - $package->description = 'Package'; +class Doctrine_UnsortedTestCase extends Doctrine_UnitTestCase +{ + public function testCascadingInsert() + { + $package = new Package(); + $package->description = 'Package'; - $packageverison = new PackageVersion(); - $packageverison->description = 'Version'; + $packageverison = new PackageVersion(); + $packageverison->description = 'Version'; - $packageverisonnotes = new PackageVersionNotes(); - $packageverisonnotes->description = 'Notes'; + $packageverisonnotes = new PackageVersionNotes(); + $packageverisonnotes->description = 'Notes'; - $package->Version[0] = $packageverison; - $package->Version[0]->Note[0] = $packageverisonnotes; + $package->Version[0] = $packageverison; + $package->Version[0]->Note[0] = $packageverisonnotes; - $package->save(); + $package->save(); - $this->assertNotNull($package->id); - $this->assertNotNull($package->Version[0]->id); - $this->assertNotNull($package->Version[0]->Note[0]->id); - } + $this->assertNotNull($package->id); + $this->assertNotNull($package->Version[0]->id); + $this->assertNotNull($package->Version[0]->Note[0]->id); + } } diff --git a/tests/Validator/ForeignKeysTestCase.php b/tests/Validator/ForeignKeysTestCase.php index c26d12ffc..07c06ee2d 100644 --- a/tests/Validator/ForeignKeysTestCase.php +++ b/tests/Validator/ForeignKeysTestCase.php @@ -1,11 +1,16 @@ tables = array('TestPerson', 'TestAddress'); - + parent::prepareTables(); } @@ -13,24 +18,24 @@ public function testForeignKeyIsValidIfLocalRelationIsSet() { $person = new TestPerson(); $address = new TestAddress(); - + $address->Person = $person; - + $table = $address->getTable(); $errors = $table->validateField('person_id', $address->person_id, $address); - + $this->assertEqual(0, $errors->count()); } - + public function testForeignKeyIsValidIfForeignRelationIsSet() { $person = new TestPerson(); $person->Addresses[0] = new TestAddress(); - + $address = $person->Addresses[0]; $table = $address->getTable(); $errors = $table->validateField('person_id', $address->person_id, $address); - + $this->assertEqual(0, $errors->count()); } @@ -41,7 +46,7 @@ public function testSynchronizedForeignKeyIsValidIfLocalRelationIsSet() $address = $person->Addresses[0]; $table = $address->getTable(); - + $errors = $table->validateField('person_id', $address->person_id, $address); $this->assertEqual(0, $errors->count()); } @@ -66,7 +71,7 @@ public function setTableDefinition() $this->hasColumn('last_name', 'string'); $this->hasColumn('favorite_color_id', 'integer'); } - + public function setUp() { $this->hasMany('TestAddress as Addresses', array('local' => 'id', 'foreign' => 'person_id')); @@ -77,16 +82,16 @@ class TestAddress extends Doctrine_Record { public function setTableDefinition() { - $this->hasColumn('id', 'integer', null, array('primary' => true, 'notnull'=> true, 'autoincrement' => true)); + $this->hasColumn('id', 'integer', null, array('primary' => true, 'notnull' => true, 'autoincrement' => true)); $this->hasColumn('person_id', 'integer', null, array('notnull' => true)); $this->hasColumn('street', 'string'); $this->hasColumn('city', 'string'); $this->hasColumn('state', 'string'); $this->hasColumn('zip', 'string'); } - + public function setUp() { $this->hasOne('TestPerson as Person', array('local' => 'person_id', 'foreign' => 'id')); } -} \ No newline at end of file +} diff --git a/tests/Validator/FutureTestCase.php b/tests/Validator/FutureTestCase.php index a8fffa17d..9d8b89163 100644 --- a/tests/Validator/FutureTestCase.php +++ b/tests/Validator/FutureTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Validator_FutureTestCase + * Doctrine_Validator_FutureTestCase. * - * @package Doctrine * @author Roman Borschel * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Validator_Future_TestCase extends Doctrine_UnitTestCase { @@ -40,30 +46,29 @@ public function prepareTables() public function prepareData() { - } - + public function testValidFutureDates() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + // one year ahead $user1 = new ValidatorTest_DateModel(); $user1->death = date('Y-m-d', time() + 365 * 24 * 60 * 60); $this->assertTrue($user1->trySave()); - + // one month ahead $user1 = new ValidatorTest_DateModel(); $user1->death = date('Y-m-d', time() + 30 * 24 * 60 * 60); $this->assertTrue($user1->trySave()); - + // one day ahead $user1->death = date('Y-m-d', time() + 24 * 60 * 60); $this->assertTrue($user1->trySave()); - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - + public function testInvalidFutureDates() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); @@ -71,14 +76,13 @@ public function testInvalidFutureDates() $user1 = new ValidatorTest_DateModel(); $user1->death = date('Y-m-d', 42); $this->assertFalse($user1->trySave()); - + $user1->death = date('Y-m-d', time()); $this->assertFalse($user1->trySave()); - + $user1->death = date('Y-m-d', time() + 60); $this->assertFalse($user1->trySave()); - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - } diff --git a/tests/Validator/PastTestCase.php b/tests/Validator/PastTestCase.php index d14fd7625..5104f2093 100644 --- a/tests/Validator/PastTestCase.php +++ b/tests/Validator/PastTestCase.php @@ -20,15 +20,21 @@ */ /** - * Doctrine_Validator_FutureTestCase + * Doctrine_Validator_FutureTestCase. * - * @package Doctrine * @author Roman Borschel * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ class Doctrine_Validator_Past_TestCase extends Doctrine_UnitTestCase { @@ -40,45 +46,43 @@ public function prepareTables() public function prepareData() { - } - + public function testInvalidPastDates() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + // one year ahead $user1 = new ValidatorTest_DateModel(); $user1->birthday = date('Y-m-d', time() + 365 * 24 * 60 * 60); $this->assertFalse($user1->trySave()); - + // one month ahead $user1 = new ValidatorTest_DateModel(); $user1->birthday = date('Y-m-d', time() + 30 * 24 * 60 * 60); $this->assertFalse($user1->trySave()); - + // one day ahead $user1->birthday = date('Y-m-d', time() + 24 * 60 * 60); $this->assertFalse($user1->trySave()); - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - + public function testValidPastDates() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + $user1 = new ValidatorTest_DateModel(); $user1->birthday = date('Y-m-d', 42); $this->assertTrue($user1->trySave()); - - $user1->birthday = date('Y-m-d', mktime(0,0,0,6,3,1981)); + + $user1->birthday = date('Y-m-d', mktime(0, 0, 0, 6, 3, 1981)); $this->assertTrue($user1->trySave()); - - $user1->birthday = date('Y-m-d', mktime(0,0,0,3,9,1983)); + + $user1->birthday = date('Y-m-d', mktime(0, 0, 0, 3, 9, 1983)); $this->assertTrue($user1->trySave()); - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - } diff --git a/tests/ValidatorTestCase.php b/tests/ValidatorTestCase.php index 92943fa29..dde63003b 100644 --- a/tests/ValidatorTestCase.php +++ b/tests/ValidatorTestCase.php @@ -22,22 +22,27 @@ /** * Doctrine_Validator_TestCase * TestCase for Doctrine's validation component. - * + * * @todo More tests to cover the full interface of Doctrine_Validator_ErrorStack. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_Validator_TestCase extends Doctrine_UnitTestCase +class Doctrine_Validator_TestCase extends Doctrine_UnitTestCase { - public function prepareTables() + public function prepareTables() { - $this->tables[] = 'ValidatorTest'; $this->tables[] = 'ValidatorTest_Person'; $this->tables[] = 'ValidatorTest_FootballPlayer'; @@ -50,7 +55,7 @@ public function prepareTables() parent::prepareTables(); } - public function testIsValidType() + public function testIsValidType() { $var = '123'; $this->assertTrue(Doctrine_Validator::isValidType($var, 'string')); @@ -114,7 +119,7 @@ public function testIsValidType() $this->assertFalse(Doctrine_Validator::isValidType($var, 'float')); $this->assertTrue(Doctrine_Validator::isValidType($var, 'array')); $this->assertFalse(Doctrine_Validator::isValidType($var, 'object')); - + $var = new Exception(); $this->assertFalse(Doctrine_Validator::isValidType($var, 'string')); $this->assertFalse(Doctrine_Validator::isValidType($var, 'integer')); @@ -123,13 +128,13 @@ public function testIsValidType() $this->assertTrue(Doctrine_Validator::isValidType($var, 'object')); } - public function testValidate2() + public function testValidate2() { $test = new ValidatorTest(); - $test->mymixed = "message"; + $test->mymixed = 'message'; $test->myrange = 1; $test->myregexp = '123a'; - + $validator = new Doctrine_Validator(); $validator->validateRecord($test); @@ -146,15 +151,15 @@ public function testValidate2() $test->save(); } - public function testValidate() + public function testValidate() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); $user = $this->connection->getTable('User')->find(4); $set = array('password' => 'this is an example of too long password', - 'loginname' => 'this is an example of too long loginname', - 'name' => 'valid name', - 'created' => 'invalid'); + 'loginname' => 'this is an example of too long loginname', + 'name' => 'valid name', + 'created' => 'invalid'); $user->setArray($set); $email = $user->Email; $email->address = 'zYne@invalid'; @@ -164,7 +169,6 @@ public function testValidate() $validator = new Doctrine_Validator(); $validator->validateRecord($user); - $stack = $user->errorStack(); $this->assertTrue($stack instanceof Doctrine_Validator_ErrorStack); @@ -185,35 +189,34 @@ public function testValidate() } /** - * Tests the Email validator. (Doctrine_Validator_Email) + * Tests the Email validator. (Doctrine_Validator_Email). */ - public function testIsValidEmail() + public function testIsValidEmail() { - $validator = new Doctrine_Validator_Email(); - $this->assertFalse($validator->validate("example@example")); - $this->assertFalse($validator->validate("example@@example")); - $this->assertFalse($validator->validate("example@example.")); - $this->assertFalse($validator->validate("example@e..")); + $this->assertFalse($validator->validate('example@example')); + $this->assertFalse($validator->validate('example@@example')); + $this->assertFalse($validator->validate('example@example.')); + $this->assertFalse($validator->validate('example@e..')); - $this->assertTrue($validator->validate("null+doctrine@pookey.co.uk")); - $this->assertTrue($validator->validate("null@pookey.co.uk")); - $this->assertTrue($validator->validate("null@pookey.com")); - $this->assertTrue($validator->validate("null@users.doctrine.pengus.net")); + $this->assertTrue($validator->validate('null+doctrine@pookey.co.uk')); + $this->assertTrue($validator->validate('null@pookey.co.uk')); + $this->assertTrue($validator->validate('null@pookey.com')); + $this->assertTrue($validator->validate('null@users.doctrine.pengus.net')); } /** * Tests saving records with invalid attributes. */ - public function testSave() + public function testSave() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - $user = $this->connection->getTable("User")->find(4); + $user = $this->connection->getTable('User')->find(4); try { - $user->name = "this is an example of too long name not very good example but an example nevertheless"; + $user->name = 'this is an example of too long name not very good example but an example nevertheless'; $user->save(); - } catch(Doctrine_Validator_Exception $e) { + } catch (Doctrine_Validator_Exception $e) { $this->assertEqual($e->count(), 1); $invalidRecords = $e->getInvalidRecords(); $this->assertEqual(count($invalidRecords), 1); @@ -222,23 +225,23 @@ public function testSave() } try { - $user = $this->connection->create("User"); - $user->Email->address = "jackdaniels@drinkmore.info..."; - $user->name = "this is an example of too long user name not very good example but an example nevertheless"; + $user = $this->connection->create('User'); + $user->Email->address = 'jackdaniels@drinkmore.info...'; + $user->name = 'this is an example of too long user name not very good example but an example nevertheless'; $user->save(); $this->fail(); } catch (Doctrine_Validator_Exception $e) { $this->pass(); $a = $e->getInvalidRecords(); - //var_dump($a[1]->getErrorStack()); + // var_dump($a[1]->getErrorStack()); $this->assertTrue(is_array($a)); - //var_dump(array_search($user, $a)); + // var_dump(array_search($user, $a)); $emailStack = $user->Email->errorStack(); - $userStack = $user->errorStack(); + $userStack = $user->errorStack(); $this->assertTrue(in_array('email', $emailStack['address'])); $this->assertTrue(in_array('length', $userStack['name'])); } - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } @@ -246,17 +249,17 @@ public function testSave() * Tests whether the validate() callback works correctly * in descendants of Doctrine_Record. */ - public function testValidationHooks() + public function testValidationHooks() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + // Tests validate() and validateOnInsert() $user = new User(); - try { + try { $user->name = "I'm not The Saint"; - $user->password = "1234"; + $user->password = '1234'; $user->save(); - } catch(Doctrine_Validator_Exception $e) { + } catch (Doctrine_Validator_Exception $e) { $this->assertEqual($e->count(), 1); $invalidRecords = $e->getInvalidRecords(); $this->assertEqual(count($invalidRecords), 1); @@ -267,25 +270,25 @@ public function testValidationHooks() $this->assertTrue(in_array('notTheSaint', $stack['name'])); // validate() hook constraint $this->assertTrue(in_array('pwNotTopSecret', $stack['password'])); // validateOnInsert() hook constraint } - + // Tests validateOnUpdate() - $user = $this->connection->getTable("User")->find(4); + $user = $this->connection->getTable('User')->find(4); try { - $user->name = "The Saint"; // Set correct name - $user->password = "Top Secret"; // Set correct password - $user->loginname = "Somebody"; // Wrong login name! + $user->name = 'The Saint'; // Set correct name + $user->password = 'Top Secret'; // Set correct password + $user->loginname = 'Somebody'; // Wrong login name! $user->save(); $this->fail(); - } catch(Doctrine_Validator_Exception $e) { + } catch (Doctrine_Validator_Exception $e) { $invalidRecords = $e->getInvalidRecords(); $this->assertEqual(count($invalidRecords), 1); - + $stack = $invalidRecords[0]->errorStack(); - + $this->assertEqual($stack->count(), 1); $this->assertTrue(in_array('notNobody', $stack['loginname'])); // validateOnUpdate() hook constraint } - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } @@ -293,13 +296,13 @@ public function testValidationHooks() * Tests whether the validateOnInsert() callback works correctly * in descendants of Doctrine_Record. */ - public function testHookValidateOnInsert() + public function testHookValidateOnInsert() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + $user = new User(); - $user->password = "1234"; - + $user->password = '1234'; + try { $user->save(); $this->fail(); @@ -307,7 +310,7 @@ public function testHookValidateOnInsert() $errors = $user->errorStack(); $this->assertTrue(in_array('pwNotTopSecret', $errors['password'])); } - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } @@ -315,15 +318,15 @@ public function testHookValidateOnInsert() public function testIssue() { $this->manager->setAttribute(Doctrine_Core::ATTR_VLD, true); - + try { $person = new ValidatorTest_Person(); $person->name = ''; // will raise a validation exception since name must be 'notblank' $person->is_football_player = true; - + $person->ValidatorTest_FootballPlayer->team_name = 'liverpool'; $person->ValidatorTest_FootballPlayer->goals_count = 2; - + $person->save(); } catch(Doctrine_Validator_Exception $e) { @@ -331,55 +334,54 @@ public function testIssue() //var_dump($person->getErrorStack()); //var_dump($person->ValidatorTest_FootballPlayer->getErrorStack()); } - + $this->manager->setAttribute(Doctrine_Core::ATTR_VLD, false); } */ - // @todo move to a separate test file (tests/Validator/UniqueTestCase) . + // @todo move to a separate test file (tests/Validator/UniqueTestCase) . public function testSetSameUniqueValueOnSameRecordThrowsNoException() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + $r = new ValidatorTest_Person(); $r->identifier = '1234'; $r->save(); - + $r = $this->connection->getTable('ValidatorTest_Person')->findAll()->getFirst(); $r->identifier = 1234; try { - $r->save(); - } - catch (Doctrine_Validator_Exception $e) { - $this->fail("Validator exception raised without reason!"); + $r->save(); + } catch (Doctrine_Validator_Exception $e) { + $this->fail('Validator exception raised without reason!'); } - + $r->delete(); // clean up - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - + public function testSetSameUniqueValueOnDifferentRecordThrowsException() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); - + $r = new ValidatorTest_Person(); $r->identifier = '1234'; $r->save(); - + $r = new ValidatorTest_Person(); $r->identifier = 1234; try { $r->save(); - $this->fail("No validator exception thrown on unique validation."); + $this->fail('No validator exception thrown on unique validation.'); } catch (Doctrine_Validator_Exception $e) { $this->pass(); } - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - + public function testValidationOnManyToManyRelations() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); @@ -393,9 +395,9 @@ public function testValidationOnManyToManyRelations() $s = $dve->getInvalidRecords(); $this->assertEqual(1, count($dve->getInvalidRecords())); $invalids = $dve->getInvalidRecords(); - //var_dump($invalids[0]->getErrorStack()); - //echo "

"; - //var_dump($invalids[1]->getErrorStack()); + // var_dump($invalids[0]->getErrorStack()); + // echo "

"; + // var_dump($invalids[1]->getErrorStack()); $stack = $client->ValidatorTest_AddressModel[0]->getErrorStack(); $this->assertTrue(in_array('notnull', $stack['address1'])); @@ -407,10 +409,10 @@ public function testValidationOnManyToManyRelations() $this->assertTrue(in_array('notnull', $stack['zip'])); $this->assertTrue(in_array('notblank', $stack['zip'])); } - + $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - + public function testSaveInTransactionThrowsValidatorException() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); @@ -436,7 +438,7 @@ public function testSaveInTransactionThrowsValidatorException() $this->assertTrue(in_array('usstate', $stack['state'])); $this->assertTrue(in_array('notnull', $stack['zip'])); $this->assertTrue(in_array('notblank', $stack['zip'])); - } + } $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } @@ -470,7 +472,7 @@ public function testNoValidationOnExpressions() $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } - + public function testValidationIsTriggeredOnFlush() { $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL); @@ -484,11 +486,10 @@ public function testValidationIsTriggeredOnFlush() $r->identifier = 5678; try { $this->conn->flush(); - $this->fail("No validator exception thrown on unique validation, triggered by flush()."); + $this->fail('No validator exception thrown on unique validation, triggered by flush().'); } catch (Doctrine_Validator_Exception $e) { $this->pass(); } $this->manager->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_NONE); } } - diff --git a/tests/ValueHolderTestCase.php b/tests/ValueHolderTestCase.php index 88bef702d..7122118dc 100644 --- a/tests/ValueHolderTestCase.php +++ b/tests/ValueHolderTestCase.php @@ -1,32 +1,42 @@ valueHolder->data[0] = 'first'; - + $this->assertEqual($this->valueHolder->data[0], 'first'); $this->assertEqual($this->valueHolder[0], 'first'); $this->assertEqual($this->valueHolder->get(0), 'first'); $this->valueHolder->data['key'] = 'second'; - + $this->assertEqual($this->valueHolder->data['key'], 'second'); $this->assertEqual($this->valueHolder->key, 'second'); $this->assertEqual($this->valueHolder['key'], 'second'); $this->assertEqual($this->valueHolder->get('key'), 'second'); } - public function testSimpleQuery() { + + public function testSimpleQuery() + { $q = new Doctrine_Query($this->connection); - $q->from("User"); + $q->from('User'); $users = $q->execute(array(), Doctrine_Core::FETCH_VHOLDER); $this->assertEqual($users->count(), 8); - - } - public function testQueryWithOneToManyRelation() { + + public function testQueryWithOneToManyRelation() + { $q = new Doctrine_Query($this->connection); - $q->from("User.Phonenumber"); + $q->from('User.Phonenumber'); $users = $q->execute(array(), Doctrine_Core::FETCH_VHOLDER); $this->assertEqual($users->count(), 8); $this->assertTrue($users[0] instanceof Doctrine_ValueHolder); @@ -39,20 +49,24 @@ public function testQueryWithOneToManyRelation() { $this->assertEqual(count($users[3]->Phonenumber), 1); $this->assertEqual(count($users[4]->Phonenumber), 3); } - public function testDelete() { + + public function testDelete() + { $f = false; try { $this->valueHolder->delete(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $f = true; } $this->assertTrue($f); } - public function testSave() { + + public function testSave() + { $f = false; try { $this->valueHolder->save(); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { $f = true; } $this->assertTrue($f); diff --git a/tests/ViewTestCase.php b/tests/ViewTestCase.php index fe0d53bba..47b57cb73 100644 --- a/tests/ViewTestCase.php +++ b/tests/ViewTestCase.php @@ -20,19 +20,24 @@ */ /** - * Doctrine_View_TestCase + * Doctrine_View_TestCase. * - * @package Doctrine * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @category Object Relational Mapping - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * + * @internal + * + * @coversNothing */ -class Doctrine_View_TestCase extends Doctrine_UnitTestCase +class Doctrine_View_TestCase extends Doctrine_UnitTestCase { - public function testCreateView() { $query = new Doctrine_Query($this->connection); @@ -50,7 +55,7 @@ public function testCreateView() try { $view->create(); - } catch(Exception $e) { + } catch (Exception $e) { $success = false; } $this->assertTrue($success); @@ -66,13 +71,13 @@ public function testCreateView() $success = true; try { $view->drop(); - } catch(Exception $e) { + } catch (Exception $e) { $success = false; } $this->assertTrue($success); } - public function testConstructor() + public function testConstructor() { } } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 2bb1704da..03c7655d7 100755 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -4,7 +4,7 @@ // Debug Diagnosic process attacher sleep time needed to link process // More info about that: http://bugs.php.net/bugs-generating-backtrace-win32.php -//sleep(10); +// sleep(10); error_reporting(E_ALL | E_STRICT); ini_set('max_execution_time', 900); @@ -12,11 +12,11 @@ define('DOCTRINE_DIR', $_SERVER['DOCTRINE_DIR']); -require_once(DOCTRINE_DIR . '/lib/Doctrine/Core.php'); +require_once DOCTRINE_DIR.'/lib/Doctrine/Core.php'; spl_autoload_register(array('Doctrine_Core', 'autoload')); spl_autoload_register(array('Doctrine_Core', 'modelsAutoload')); -require_once(DOCTRINE_DIR . '/tests/DoctrineTest.php'); +require_once DOCTRINE_DIR.'/tests/DoctrineTest.php'; spl_autoload_register(array('DoctrineTest', 'autoload')); diff --git a/tests/index.php b/tests/index.php index fd3a33263..5d3e528b2 100755 --- a/tests/index.php +++ b/tests/index.php @@ -1,2 +1,3 @@ table($direction, 'migration_phonenumber', array('id' => array('type' => 'integer', 'length' => 20, 'autoincrement' => true, 'primary' => true), 'user_id' => array('type' => 'integer', 'length' => 2147483647), 'phonenumber' => array('type' => 'string', 'length' => 2147483647)), array('indexes' => array(), 'primary' => array(0 => 'id'))); } -} \ No newline at end of file +} diff --git a/tests/migration_classes/2_add_user.class.php b/tests/migration_classes/2_add_user.class.php index cfee4a4fc..ce735f445 100644 --- a/tests/migration_classes/2_add_user.class.php +++ b/tests/migration_classes/2_add_user.class.php @@ -1,11 +1,11 @@ table($direction, 'migration_user', array('id' => array('type' => 'integer', 'length' => 20, 'autoincrement' => true, 'primary' => true), 'username' => array('type' => 'string', 'length' => 255), 'password' => array('type' => 'string', 'length' => 255)), array('indexes' => array(), 'primary' => array(0 => 'id'))); + $this->table($direction, 'migration_user', array('id' => array('type' => 'integer', 'length' => 20, 'autoincrement' => true, 'primary' => true), 'username' => array('type' => 'string', 'length' => 255), 'password' => array('type' => 'string', 'length' => 255)), array('indexes' => array(), 'primary' => array(0 => 'id'))); } -} \ No newline at end of file +} diff --git a/tests/migration_classes/3_add_profile.class.php b/tests/migration_classes/3_add_profile.class.php index f29fea186..356e23fed 100644 --- a/tests/migration_classes/3_add_profile.class.php +++ b/tests/migration_classes/3_add_profile.class.php @@ -1,11 +1,11 @@ table($direction, 'migration_profile', array('id' => array('type' => 'integer', 'length' => 20, 'autoincrement' => true, 'primary' => true), 'name' => array('type' => 'string', 'length' => 255)), array('indexes' => array(), 'primary' => array(0 => 'id'))); + $this->table($direction, 'migration_profile', array('id' => array('type' => 'integer', 'length' => 20, 'autoincrement' => true, 'primary' => true), 'name' => array('type' => 'string', 'length' => 255)), array('indexes' => array(), 'primary' => array(0 => 'id'))); } -} \ No newline at end of file +} diff --git a/tests/migration_classes/4_drop_profile.class.php b/tests/migration_classes/4_drop_profile.class.php index 2cedecc98..447612c3f 100644 --- a/tests/migration_classes/4_drop_profile.class.php +++ b/tests/migration_classes/4_drop_profile.class.php @@ -1,12 +1,12 @@ table($direction, 'migration_profile', array('id' => array('type' => 'integer', 'length' => 20, 'autoincrement' => true, 'primary' => true), 'name' => array('type' => 'string', 'length' => 255)), array('indexes' => array(), 'primary' => array(0 => 'id'))); + $direction = 'up' == $direction ? 'down' : 'up'; + $this->table($direction, 'migration_profile', array('id' => array('type' => 'integer', 'length' => 20, 'autoincrement' => true, 'primary' => true), 'name' => array('type' => 'string', 'length' => 255)), array('indexes' => array(), 'primary' => array(0 => 'id'))); } -} \ No newline at end of file +} diff --git a/tests/migration_classes/5_test.class.php b/tests/migration_classes/5_test.class.php index 23046eb28..a342dd45e 100644 --- a/tests/migration_classes/5_test.class.php +++ b/tests/migration_classes/5_test.class.php @@ -5,4 +5,4 @@ class Test5 extends Doctrine_Migration_Base public function migrate($direction) { } -} \ No newline at end of file +} diff --git a/tests/migration_classes/6_test.class.php b/tests/migration_classes/6_test.class.php index c810b9523..198adc24c 100644 --- a/tests/migration_classes/6_test.class.php +++ b/tests/migration_classes/6_test.class.php @@ -5,4 +5,4 @@ class Test6 extends Doctrine_Migration_Base public function migrate($direction) { } -} \ No newline at end of file +} diff --git a/tests/migration_classes/7_test.class.php b/tests/migration_classes/7_test.class.php index ddb22eb6a..7a16caf53 100644 --- a/tests/migration_classes/7_test.class.php +++ b/tests/migration_classes/7_test.class.php @@ -5,4 +5,4 @@ class Test7 extends Doctrine_Migration_Base public function migrate($direction) { } -} \ No newline at end of file +} diff --git a/tests/migration_classes/8_test.class.php b/tests/migration_classes/8_test.class.php index 71c01924c..632560a53 100644 --- a/tests/migration_classes/8_test.class.php +++ b/tests/migration_classes/8_test.class.php @@ -5,4 +5,4 @@ class Test8 extends Doctrine_Migration_Base public function migrate($direction) { } -} \ No newline at end of file +} diff --git a/tests/migration_classes/9_test.class.php b/tests/migration_classes/9_test.class.php index b02dfef50..45767e51b 100644 --- a/tests/migration_classes/9_test.class.php +++ b/tests/migration_classes/9_test.class.php @@ -5,4 +5,4 @@ class Test9 extends Doctrine_Migration_Base public function migrate($direction) { } -} \ No newline at end of file +} diff --git a/tests/models/Account.php b/tests/models/Account.php index 6863cae85..c05fae51a 100644 --- a/tests/models/Account.php +++ b/tests/models/Account.php @@ -1,10 +1,10 @@ hasColumn('entity_id', 'integer'); $this->hasColumn('amount', 'integer'); } } - diff --git a/tests/models/Address.php b/tests/models/Address.php index 9d423c30f..033483eb2 100644 --- a/tests/models/Address.php +++ b/tests/models/Address.php @@ -1,13 +1,16 @@ hasMany('User', array('local' => 'address_id', - 'foreign' => 'user_id', - 'refClass' => 'EntityAddress')); + $this->hasMany('User', array('local' => 'address_id', + 'foreign' => 'user_id', + 'refClass' => 'EntityAddress')); } - public function setTableDefinition() { + + public function setTableDefinition() + { $this->hasColumn('address', 'string', 200); } } diff --git a/tests/models/Album.php b/tests/models/Album.php index 65cad1b2d..edcf5659f 100644 --- a/tests/models/Album.php +++ b/tests/models/Album.php @@ -1,17 +1,18 @@ hasMany('Song', array('local' => 'id', 'foreign' => 'album_id')); $this->hasOne('User', array('local' => 'user_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); } + public function setTableDefinition() { $this->hasColumn('user_id', 'integer'); - $this->hasColumn('name', 'string',20); + $this->hasColumn('name', 'string', 20); } } - diff --git a/tests/models/App.php b/tests/models/App.php index 44f99bbf9..0a7043ca1 100644 --- a/tests/models/App.php +++ b/tests/models/App.php @@ -1,19 +1,23 @@ hasColumn('name', 'string', 32); $this->hasColumn('user_id', 'integer', 11); $this->hasColumn('app_category_id', 'integer', 11); } - public function setUp() { + + public function setUp() + { $this->hasOne('User', array( - 'local' => 'user_id', 'foreign' => 'id' + 'local' => 'user_id', 'foreign' => 'id', )); $this->hasOne('App_Category as Category', array( 'local' => 'app_category_id', - 'foreign' => 'id' + 'foreign' => 'id', )); - } + } } - diff --git a/tests/models/App_Category.php b/tests/models/App_Category.php index 4f6ff96f5..8438cc47d 100644 --- a/tests/models/App_Category.php +++ b/tests/models/App_Category.php @@ -1,18 +1,23 @@ hasColumn('name', 'string', 32); $this->hasColumn('parent_id', 'integer'); } - public function setUp() { + + public function setUp() + { $this->hasMany('App', array( 'local' => 'id', - 'foreign' => 'app_category_id' + 'foreign' => 'app_category_id', )); $this->hasMany('App_Category as Parent', array( 'local' => 'parent_id', - 'foreign' => 'id' + 'foreign' => 'id', )); } } diff --git a/tests/models/App_User.php b/tests/models/App_User.php index 6642e866f..ffefa7672 100644 --- a/tests/models/App_User.php +++ b/tests/models/App_User.php @@ -1,6 +1,9 @@ hasColumn('first_name', 'string', 32); $this->hasColumn('last_name', 'string', 32); $this->hasColumn('email', 'string', 128, 'email'); @@ -9,10 +12,12 @@ public function setTableDefinition() { $this->hasColumn('country', 'string', 2, 'country'); $this->hasColumn('zipcode', 'string', 9, 'nospace'); } - public function setUp() { + + public function setUp() + { $this->hasMany('App', array( 'local' => 'id', - 'foreign' => 'user_id' + 'foreign' => 'user_id', )); - } + } } diff --git a/tests/models/Assignment.php b/tests/models/Assignment.php index 3d2f8b722..1de1c8966 100644 --- a/tests/models/Assignment.php +++ b/tests/models/Assignment.php @@ -1,8 +1,10 @@ hasColumn('task_id', 'integer'); - $this->hasColumn('resource_id', 'integer'); - } -} +class Assignment extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('task_id', 'integer'); + $this->hasColumn('resource_id', 'integer'); + } +} diff --git a/tests/models/Auth.php b/tests/models/Auth.php index 23df462ae..c6c1afc99 100644 --- a/tests/models/Auth.php +++ b/tests/models/Auth.php @@ -1,14 +1,15 @@ hasColumn('roleid', 'integer', 10); $this->hasColumn('name', 'string', 50); } - public function setUp() + + public function setUp() { $this->hasOne('Role', array('local' => 'roleid', 'foreign' => 'id')); } } - diff --git a/tests/models/Author.php b/tests/models/Author.php index 1b48b80a3..994b245b3 100644 --- a/tests/models/Author.php +++ b/tests/models/Author.php @@ -1,15 +1,17 @@ hasOne('Book', array('local' => 'book_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); } + public function setTableDefinition() { $this->hasColumn('book_id', 'integer'); - $this->hasColumn('name', 'string',20); + $this->hasColumn('name', 'string', 20); } } diff --git a/tests/models/BadlyNamed__Class.php b/tests/models/BadlyNamed__Class.php index 75c793370..354de7696 100644 --- a/tests/models/BadlyNamed__Class.php +++ b/tests/models/BadlyNamed__Class.php @@ -1,8 +1,12 @@ setTableName('bar'); - $this->hasColumn('name', 'string', 200); + $this->setTableName('bar'); + $this->hasColumn('name', 'string', 200); } + public function setUp() { $this->hasMany('FooRecord as Foo', array('local' => 'barId', 'foreign' => 'fooId', 'refClass' => 'FooBarRecord')); diff --git a/tests/models/BaseSymfonyRecord.php b/tests/models/BaseSymfonyRecord.php index e8a45d68e..cefece166 100644 --- a/tests/models/BaseSymfonyRecord.php +++ b/tests/models/BaseSymfonyRecord.php @@ -1,4 +1,5 @@ hasColumn('name', 'string', 30); } - } diff --git a/tests/models/Blog.php b/tests/models/Blog.php index 00acbb1b1..5d91cdb17 100644 --- a/tests/models/Blog.php +++ b/tests/models/Blog.php @@ -1,10 +1,11 @@ actAs('Taggable'); @@ -14,7 +15,7 @@ class Taggable extends Doctrine_Template { public function setUp() { - //$this->hasMany('[Component]TagTemplate as Tag'); + // $this->hasMany('[Component]TagTemplate as Tag'); } } class TagTemplate extends Doctrine_Record @@ -27,6 +28,6 @@ public function setTableDefinition() public function setUp() { - //$this->hasOne('[Component]', array('onDelete' => 'CASCADE')); + // $this->hasOne('[Component]', array('onDelete' => 'CASCADE')); } } diff --git a/tests/models/BlogTag.php b/tests/models/BlogTag.php index 313d80e5c..b9fe49d80 100644 --- a/tests/models/BlogTag.php +++ b/tests/models/BlogTag.php @@ -1,4 +1,5 @@ -hasColumn('name', 'string', 100); $this->hasColumn('description', 'string'); } + public function setUp() { $this->hasOne('Blog', array('onDelete' => 'CASCADE')); diff --git a/tests/models/BoardWithPosition.php b/tests/models/BoardWithPosition.php index e7a201ab4..aabc70d05 100644 --- a/tests/models/BoardWithPosition.php +++ b/tests/models/BoardWithPosition.php @@ -1,10 +1,15 @@ hasColumn('position', 'integer'); $this->hasColumn('category_id', 'integer'); } - public function setUp() { + + public function setUp() + { $this->hasOne('CategoryWithPosition as Category', array('local' => 'category_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); } } diff --git a/tests/models/Book.php b/tests/models/Book.php index cb28ec4f8..7003bd76b 100644 --- a/tests/models/Book.php +++ b/tests/models/Book.php @@ -1,16 +1,18 @@ hasMany('Author', array('local' => 'id', 'foreign' => 'book_id')); $this->hasOne('User', array('local' => 'user_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); } + public function setTableDefinition() { $this->hasColumn('user_id', 'integer'); - $this->hasColumn('name', 'string',20); + $this->hasColumn('name', 'string', 20); } } diff --git a/tests/models/Bookmark.php b/tests/models/Bookmark.php index a4e6437e4..95d9c9e67 100644 --- a/tests/models/Bookmark.php +++ b/tests/models/Bookmark.php @@ -1,4 +1,5 @@ hasMany('Bookmark as Bookmarks', - array('local' => 'id', - 'foreign' => 'user_id')); + $this->hasMany('Bookmark as Bookmarks', + array('local' => 'id', + 'foreign' => 'user_id')); } + public function setTableDefinition() { $this->hasColumn('name', 'string', 30); diff --git a/tests/models/BooleanTest.php b/tests/models/BooleanTest.php index 748a6fa2b..29de57ee6 100644 --- a/tests/models/BooleanTest.php +++ b/tests/models/BooleanTest.php @@ -1,6 +1,14 @@ hasColumn('is_working', 'boolean'); $this->hasColumn('is_working_notnull', 'boolean', 1, array('default' => false, 'notnull' => true)); } diff --git a/tests/models/CPK_Association.php b/tests/models/CPK_Association.php index 880512992..3a1cf5d4a 100644 --- a/tests/models/CPK_Association.php +++ b/tests/models/CPK_Association.php @@ -1,6 +1,9 @@ hasColumn('test1_id', 'integer', 11, array('primary' => true)); $this->hasColumn('test2_id', 'integer', 11, array('primary' => true)); } diff --git a/tests/models/CPK_Test.php b/tests/models/CPK_Test.php index afb0ac549..4cb2fbfc2 100644 --- a/tests/models/CPK_Test.php +++ b/tests/models/CPK_Test.php @@ -1,13 +1,23 @@ hasColumn('name', 'string', 255); } - public function setUp() { + + public function setUp() + { $this->hasMany('CPK_Test2 as Test', array( 'local' => 'test1_id', 'foreign' => 'test2_id', - 'refClass' => 'CPK_Association' + 'refClass' => 'CPK_Association', )); } } diff --git a/tests/models/CPK_Test2.php b/tests/models/CPK_Test2.php index 27d56aeba..b6c488668 100644 --- a/tests/models/CPK_Test2.php +++ b/tests/models/CPK_Test2.php @@ -1,13 +1,18 @@ hasColumn('name', 'string', 255); } - public function setUp() { + + public function setUp() + { $this->hasMany('CPK_Test as Test', array( 'local' => 'test2_id', 'foreign' => 'test1_id', - 'refClass' => 'CPK_Association' + 'refClass' => 'CPK_Association', )); } } diff --git a/tests/models/CascadeDeleteRelatedTest.php b/tests/models/CascadeDeleteRelatedTest.php index 15c34f295..6f7e446a2 100644 --- a/tests/models/CascadeDeleteRelatedTest.php +++ b/tests/models/CascadeDeleteRelatedTest.php @@ -1,4 +1,10 @@ hasColumn('name', 'string'); $this->hasColumn('cscd_id', 'integer'); } + public function setUp() { - $this->hasOne('CascadeDeleteTest', array('local' => 'cscd_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE', - 'onUpdate' => 'SET NULL')); + $this->hasOne('CascadeDeleteTest', array('local' => 'cscd_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + 'onUpdate' => 'SET NULL')); $this->hasMany('CascadeDeleteRelatedTest2 as Related', - array('local' => 'id', - 'foreign' => 'cscd_id')); + array('local' => 'id', + 'foreign' => 'cscd_id')); } } diff --git a/tests/models/CascadeDeleteRelatedTest2.php b/tests/models/CascadeDeleteRelatedTest2.php index 46049e104..df82c5275 100644 --- a/tests/models/CascadeDeleteRelatedTest2.php +++ b/tests/models/CascadeDeleteRelatedTest2.php @@ -1,4 +1,5 @@ hasColumn('name', 'string'); $this->hasColumn('cscd_id', 'integer'); } + public function setUp() { $this->hasOne('CascadeDeleteRelatedTest', array('local' => 'cscd_id', - 'foreign' => 'id', - 'onDelete' => 'SET NULL')); + 'foreign' => 'id', + 'onDelete' => 'SET NULL')); } } diff --git a/tests/models/CascadeDeleteTest.php b/tests/models/CascadeDeleteTest.php index 9cd6698d3..6c7dd1ce8 100644 --- a/tests/models/CascadeDeleteTest.php +++ b/tests/models/CascadeDeleteTest.php @@ -1,14 +1,21 @@ hasColumn('name', 'string'); } + public function setUp() { - $this->hasMany('CascadeDeleteRelatedTest as Related', - array('local' => 'id', - 'foreign' => 'cscd_id')); + $this->hasMany('CascadeDeleteRelatedTest as Related', + array('local' => 'id', + 'foreign' => 'cscd_id')); } } diff --git a/tests/models/CategoryWithPosition.php b/tests/models/CategoryWithPosition.php index d205e3922..a8f533999 100644 --- a/tests/models/CategoryWithPosition.php +++ b/tests/models/CategoryWithPosition.php @@ -1,10 +1,15 @@ hasColumn('position', 'integer'); $this->hasColumn('name', 'string', 255); } - public function setUp() { - $this->hasMany('BoardWithPosition as Boards', array('local' => 'id' , 'foreign' => 'category_id')); - } + + public function setUp() + { + $this->hasMany('BoardWithPosition as Boards', array('local' => 'id', 'foreign' => 'category_id')); + } } diff --git a/tests/models/CheckConstraintTest.php b/tests/models/CheckConstraintTest.php index a1ed16357..70ecc21ef 100644 --- a/tests/models/CheckConstraintTest.php +++ b/tests/models/CheckConstraintTest.php @@ -1,4 +1,10 @@ setTableName('clients'); + $this->setTableName('clients'); - $this->hasColumn('id', 'integer', 4, array('notnull' => true, - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true)); - $this->hasColumn('short_name', 'string', 32, array('notnull' => true, 'notblank', 'unique' => true)); - } + $this->hasColumn('id', 'integer', 4, array('notnull' => true, + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true)); + $this->hasColumn('short_name', 'string', 32, array('notnull' => true, 'notblank', 'unique' => true)); + } - public function setUp() + public function setUp() { - $this->hasMany('AddressModel', array('local' => 'client_id', 'foreign' => 'address_id', 'refClass' => 'ClientToAddressModel')); - } + $this->hasMany('AddressModel', array('local' => 'client_id', 'foreign' => 'address_id', 'refClass' => 'ClientToAddressModel')); + } } -class ClientToAddressModel extends Doctrine_Record +class ClientToAddressModel extends Doctrine_Record { - public function setTableDefinition() + public function setTableDefinition() { - $this->setTableName('clients_to_addresses'); + $this->setTableName('clients_to_addresses'); - $this->hasColumn('client_id', 'integer', 11, array('primary' => true)); - $this->hasColumn('address_id', 'integer', 11, array('primary' => true)); - } + $this->hasColumn('client_id', 'integer', 11, array('primary' => true)); + $this->hasColumn('address_id', 'integer', 11, array('primary' => true)); + } - public function construct() + public function construct() { - } + } - public function setUp() + public function setUp() { - $this->hasOne('ClientModel', array('local' => 'client_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - $this->hasOne('AddressModel', array('local' => 'address_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - } + $this->hasOne('ClientModel', array('local' => 'client_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + $this->hasOne('AddressModel', array('local' => 'address_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } } -class AddressModel extends Doctrine_Record +class AddressModel extends Doctrine_Record { - public function setTableDefinition() + public function setTableDefinition() { - $this->setTableName('addresses'); - - $this->hasColumn('id', 'integer', 11, array('autoincrement' => true, - 'primary' => true - )); - $this->hasColumn('address1', 'string', 255, array('notnull' => true, 'notblank')); - $this->hasColumn('address2', 'string', 255, array('notnull' => true)); - $this->hasColumn('city', 'string', 255, array('notnull' => true, 'notblank')); - $this->hasColumn('state', 'string', 10, array('notnull' => true, 'notblank', 'usstate')); - $this->hasColumn('zip', 'string', 15, array('notnull' => true, 'notblank', 'regexp' => '/^[0-9-]*$/')); - } - - public function setUp() + $this->setTableName('addresses'); + + $this->hasColumn('id', 'integer', 11, array('autoincrement' => true, + 'primary' => true, + )); + $this->hasColumn('address1', 'string', 255, array('notnull' => true, 'notblank')); + $this->hasColumn('address2', 'string', 255, array('notnull' => true)); + $this->hasColumn('city', 'string', 255, array('notnull' => true, 'notblank')); + $this->hasColumn('state', 'string', 10, array('notnull' => true, 'notblank', 'usstate')); + $this->hasColumn('zip', 'string', 15, array('notnull' => true, 'notblank', 'regexp' => '/^[0-9-]*$/')); + } + + public function setUp() { - $this->hasMany('ClientModel', array('local' => 'address_id', 'foreign' => 'client_id', 'refClass' => 'ClientToAddressModel')); - } + $this->hasMany('ClientModel', array('local' => 'address_id', 'foreign' => 'client_id', 'refClass' => 'ClientToAddressModel')); + } } diff --git a/tests/models/ColumnAliasTest.php b/tests/models/ColumnAliasTest.php index 5f8e96713..2b38304bb 100644 --- a/tests/models/ColumnAliasTest.php +++ b/tests/models/ColumnAliasTest.php @@ -1,4 +1,10 @@ hasColumn('another_column as anotherField', 'string', 50); $this->hasColumn('book_id as bookId', 'integer', 4); } + public function setUp() { $this->hasOne('Book as book', array('local' => 'book_id', 'foreign' => 'id')); diff --git a/tests/models/ConcreteEmail.php b/tests/models/ConcreteEmail.php index 875d794c5..fdccfd806 100644 --- a/tests/models/ConcreteEmail.php +++ b/tests/models/ConcreteEmail.php @@ -1,4 +1,5 @@ hasColumn('age', 'integer'); - + parent::setTableDefinition(); } } diff --git a/tests/models/ConcreteUser.php b/tests/models/ConcreteUser.php index 3c0a2f604..ab786991d 100644 --- a/tests/models/ConcreteUser.php +++ b/tests/models/ConcreteUser.php @@ -1,4 +1,5 @@ actAs('UserTemplate'); } } - diff --git a/tests/models/CoverageCodeN.php b/tests/models/CoverageCodeN.php index 5012fd362..6f48104b8 100644 --- a/tests/models/CoverageCodeN.php +++ b/tests/models/CoverageCodeN.php @@ -1,11 +1,12 @@ setTableName('coverage_codes'); - $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('code', 'integer', 4, array ( 'notnull' => true, 'notblank' => true,)); - $this->hasColumn('description', 'string', 4000, array ( 'notnull' => true, 'notblank' => true,)); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('coverage_codes'); + $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('code', 'integer', 4, array('notnull' => true, 'notblank' => true)); + $this->hasColumn('description', 'string', 4000, array('notnull' => true, 'notblank' => true)); + } +} diff --git a/tests/models/CustomPK.php b/tests/models/CustomPK.php index e136136de..bd0f30e1a 100644 --- a/tests/models/CustomPK.php +++ b/tests/models/CustomPK.php @@ -1,7 +1,10 @@ hasColumn('uid', 'integer',11, 'autoincrement|primary'); - $this->hasColumn('name', 'string',255); + +class CustomPK extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('uid', 'integer', 11, 'autoincrement|primary'); + $this->hasColumn('name', 'string', 255); } } diff --git a/tests/models/CustomSequenceRecord.php b/tests/models/CustomSequenceRecord.php index 4dd147fff..7373acc2e 100644 --- a/tests/models/CustomSequenceRecord.php +++ b/tests/models/CustomSequenceRecord.php @@ -1,9 +1,10 @@ hasColumn('id', 'integer', null, array('primary', 'sequence' => 'custom_seq')); $this->hasColumn('name', 'string'); } } - diff --git a/tests/models/Data_File.php b/tests/models/Data_File.php index 2b6c21be1..e42a54854 100644 --- a/tests/models/Data_File.php +++ b/tests/models/Data_File.php @@ -1,10 +1,15 @@ hasColumn('filename', 'string'); $this->hasColumn('file_owner_id', 'integer'); } - public function setUp() { + + public function setUp() + { $this->hasOne('File_Owner', array('local' => 'file_owner_id', 'foreign' => 'id')); } } diff --git a/tests/models/DateTest.php b/tests/models/DateTest.php index 424664198..9f770a234 100644 --- a/tests/models/DateTest.php +++ b/tests/models/DateTest.php @@ -1,7 +1,14 @@ hasColumn('date', 'date', 20); + +/** + * @internal + * + * @coversNothing + */ +class DateTest extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('date', 'date', 20); } } - diff --git a/tests/models/Description.php b/tests/models/Description.php index fd9bada28..f97d5b54a 100644 --- a/tests/models/Description.php +++ b/tests/models/Description.php @@ -1,8 +1,10 @@ hasColumn('description', 'string',3000); - $this->hasColumn('file_md5', 'string',32); + +class Description extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('description', 'string', 3000); + $this->hasColumn('file_md5', 'string', 32); } } - diff --git a/tests/models/Element.php b/tests/models/Element.php index 36c49e150..5a5c24d18 100644 --- a/tests/models/Element.php +++ b/tests/models/Element.php @@ -1,14 +1,18 @@ hasColumn('name', 'string', 100); $this->hasColumn('parent_id', 'integer'); } - public function setUp() { - $this->hasMany('Element as Child', array('local' => 'id', - 'foreign' => 'parent_id')); - $this->hasOne('Element as Parent', array('local' => 'parent_id', - 'foreign' => 'id')); + + public function setUp() + { + $this->hasMany('Element as Child', array('local' => 'id', + 'foreign' => 'parent_id')); + $this->hasOne('Element as Parent', array('local' => 'parent_id', + 'foreign' => 'id')); } } - diff --git a/tests/models/Email.php b/tests/models/Email.php index 702f6dc07..f1b91d04b 100644 --- a/tests/models/Email.php +++ b/tests/models/Email.php @@ -1,8 +1,9 @@ hasColumn('address', 'string', 150, 'email|unique'); } -} \ No newline at end of file +} diff --git a/tests/models/Entity.php b/tests/models/Entity.php index 1b74263f0..217b6b2b9 100644 --- a/tests/models/Entity.php +++ b/tests/models/Entity.php @@ -1,26 +1,28 @@ hasOne('Email', array('local' => 'email_id', 'onDelete' => 'CASCADE')); $this->hasMany('Phonenumber', array('local' => 'id', 'foreign' => 'entity_id')); $this->hasOne('Account', array('foreign' => 'entity_id', 'onDelete' => 'CASCADE')); - $this->hasMany('Entity', array('local' => 'entity1', + $this->hasMany('Entity', array('local' => 'entity1', 'refClass' => 'EntityReference', 'foreign' => 'entity2', - 'equal' => true)); + 'equal' => true)); } - public function setTableDefinition() + + public function setTableDefinition() { - $this->hasColumn('id', 'integer',20, array('autoincrement', 'primary')); - $this->hasColumn('name', 'string',50); - $this->hasColumn('loginname', 'string',20, array('unique')); - $this->hasColumn('password', 'string',16); - $this->hasColumn('type', 'integer',1); - $this->hasColumn('created', 'integer',11); - $this->hasColumn('updated', 'integer',11); + $this->hasColumn('id', 'integer', 20, array('autoincrement', 'primary')); + $this->hasColumn('name', 'string', 50); + $this->hasColumn('loginname', 'string', 20, array('unique')); + $this->hasColumn('password', 'string', 16); + $this->hasColumn('type', 'integer', 1); + $this->hasColumn('created', 'integer', 11); + $this->hasColumn('updated', 'integer', 11); $this->hasColumn('email_id', 'integer'); - $this->setSubclasses(array("User" => array("type" => 0), "Group" => array("type" => 1))); + $this->setSubclasses(array('User' => array('type' => 0), 'Group' => array('type' => 1))); } } diff --git a/tests/models/EntityAddress.php b/tests/models/EntityAddress.php index c9e7af5a4..f7a7ffe1e 100644 --- a/tests/models/EntityAddress.php +++ b/tests/models/EntityAddress.php @@ -1,7 +1,8 @@ hasColumn('user_id', 'integer', null, array('primary' => true)); $this->hasColumn('address_id', 'integer', null, array('primary' => true)); diff --git a/tests/models/EntityReference.php b/tests/models/EntityReference.php index 093dd0554..2b442eb7f 100644 --- a/tests/models/EntityReference.php +++ b/tests/models/EntityReference.php @@ -1,11 +1,11 @@ hasColumn('entity1', 'integer', null, 'primary'); $this->hasColumn('entity2', 'integer', null, 'primary'); - //$this->setPrimaryKey(array('entity1', 'entity2')); + // $this->setPrimaryKey(array('entity1', 'entity2')); } } - diff --git a/tests/models/EnumTest.php b/tests/models/EnumTest.php index 12b12abed..043df5d10 100644 --- a/tests/models/EnumTest.php +++ b/tests/models/EnumTest.php @@ -1,11 +1,20 @@ hasColumn('status', 'enum', 11, array('values' => array('open', 'verified', 'closed'))); $this->hasColumn('text', 'string'); } - public function setUp() { + + public function setUp() + { $this->hasMany('EnumTest2 as Enum2', array('local' => 'id', 'foreign' => 'enum_test_id')); $this->hasMany('EnumTest3 as Enum3', array('local' => 'text', 'foreign' => 'text')); } diff --git a/tests/models/EnumTest2.php b/tests/models/EnumTest2.php index 5c7325921..388d37535 100644 --- a/tests/models/EnumTest2.php +++ b/tests/models/EnumTest2.php @@ -1,7 +1,9 @@ hasColumn('status', 'enum', 11, array('values' => array('open', 'verified', 'closed'))); $this->hasColumn('enum_test_id', 'integer'); } diff --git a/tests/models/EnumTest3.php b/tests/models/EnumTest3.php index 0dc93a76e..485692501 100644 --- a/tests/models/EnumTest3.php +++ b/tests/models/EnumTest3.php @@ -1,7 +1,9 @@ hasColumn('text', 'string', 10, array('primary' => true)); } } diff --git a/tests/models/EventListenerChainTest.php b/tests/models/EventListenerChainTest.php index 8a235deba..82c81be21 100644 --- a/tests/models/EventListenerChainTest.php +++ b/tests/models/EventListenerChainTest.php @@ -1,21 +1,28 @@ hasColumn('name', 'string', 100); } - public function setUp() { + + public function setUp() + { $chain = new Doctrine_EventListener_Chain(); $chain->add(new Doctrine_EventListener_TestA()); $chain->add(new Doctrine_EventListener_TestB()); } } -class Doctrine_EventListener_TestA extends Doctrine_EventListener +class Doctrine_EventListener_TestA extends Doctrine_EventListener { - } -class Doctrine_EventListener_TestB extends Doctrine_EventListener +class Doctrine_EventListener_TestB extends Doctrine_EventListener { - } diff --git a/tests/models/EventListenerTest.php b/tests/models/EventListenerTest.php index f18e810f6..3a8360f67 100644 --- a/tests/models/EventListenerTest.php +++ b/tests/models/EventListenerTest.php @@ -1,16 +1,30 @@ hasColumn("name", "string", 100); - $this->hasColumn("password", "string", 8); + +/** + * @internal + * + * @coversNothing + */ +class EventListenerTest extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 100); + $this->hasColumn('password', 'string', 8); } - public function setUp() { - //$this->attribute(Doctrine_Core::ATTR_LISTENER, new Doctrine_EventListener_AccessorInvoker()); + + public function setUp() + { + // $this->attribute(Doctrine_Core::ATTR_LISTENER, new Doctrine_EventListener_AccessorInvoker()); } - public function getName($name) { + + public function getName($name) + { return strtoupper($name); } - public function setPassword($password) { + + public function setPassword($password) + { return md5($password); } } diff --git a/tests/models/FieldNameTest.php b/tests/models/FieldNameTest.php index e8612b707..db6dc4e1c 100644 --- a/tests/models/FieldNameTest.php +++ b/tests/models/FieldNameTest.php @@ -1,12 +1,18 @@ hasColumn('someColumn', 'string', 200, array('default' => 'some string')); $this->hasColumn('someEnum', 'enum', 4, array('default' => 'php', 'values' => array('php', 'java', 'python'))); $this->hasColumn('someArray', 'array', 100, array('default' => array())); - $this->hasColumn('someObject', 'object', 200, array('default' => new stdClass)); + $this->hasColumn('someObject', 'object', 200, array('default' => new stdClass())); $this->hasColumn('someInt', 'integer', 20, array('default' => 11)); } } diff --git a/tests/models/File_Owner.php b/tests/models/File_Owner.php index 707f994a4..1c58ae0e2 100644 --- a/tests/models/File_Owner.php +++ b/tests/models/File_Owner.php @@ -1,9 +1,14 @@ hasColumn('name', 'string', 255); } - public function setUp() { + + public function setUp() + { $this->hasOne('Data_File', array('local' => 'id', 'foreign' => 'file_owner_id')); } } diff --git a/tests/models/FilterTest.php b/tests/models/FilterTest.php index c29a474cd..ef334167c 100644 --- a/tests/models/FilterTest.php +++ b/tests/models/FilterTest.php @@ -1,9 +1,19 @@ hasColumn('name', 'string',100); + +/** + * @internal + * + * @coversNothing + */ +class FilterTest extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 100); } - public function setUp() { + + public function setUp() + { $this->hasMany('FilterTest2 as filtered', array('local' => 'id', 'foreign' => 'test1_id', 'onDelete' => 'CASCADE')); } } diff --git a/tests/models/FilterTest2.php b/tests/models/FilterTest2.php index 4ceb5e52d..47eadf5ea 100644 --- a/tests/models/FilterTest2.php +++ b/tests/models/FilterTest2.php @@ -1,7 +1,10 @@ hasColumn('name', 'string',100); + +class FilterTest2 extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 100); $this->hasColumn('test1_id', 'integer'); } } diff --git a/tests/models/FooBarRecord.php b/tests/models/FooBarRecord.php index d32ec1cd5..f10afec6a 100644 --- a/tests/models/FooBarRecord.php +++ b/tests/models/FooBarRecord.php @@ -1,4 +1,5 @@ hasColumn('name', 'string', 200); } + public function setUp() { $this->hasOne('FooRecord', array('local' => 'id', 'foreign' => 'id')); diff --git a/tests/models/FooLocallyOwned.php b/tests/models/FooLocallyOwned.php index a30a229f4..5378d9463 100644 --- a/tests/models/FooLocallyOwned.php +++ b/tests/models/FooLocallyOwned.php @@ -1,4 +1,5 @@ hasColumn('name', 'string', 200); } } - diff --git a/tests/models/FooRecord.php b/tests/models/FooRecord.php index 2e39dd781..65296b641 100644 --- a/tests/models/FooRecord.php +++ b/tests/models/FooRecord.php @@ -1,43 +1,44 @@ setTableName('foo'); - + $this->hasColumn('name', 'string', 200, array('notnull' => true)); $this->hasColumn('parent_id', 'integer'); $this->hasColumn('local_foo', 'integer'); } + public function setUp() { - $this->hasMany('FooRecord as FooFriend', array('local' => 'foo1', - 'foreign' => 'foo2', - 'equal' => true, - 'refClass' => 'FooReferenceRecord', - )); - - $this->hasMany('FooRecord as FooParents', array('local' => 'foo1', - 'foreign' => 'foo2', - 'refClass' => 'FooReferenceRecord', - 'onDelete' => 'RESTRICT', - )); - - $this->hasMany('FooRecord as FooChildren', array('local' => 'foo2', - 'foreign' => 'foo1', - 'refClass' => 'FooReferenceRecord', - )); + $this->hasMany('FooRecord as FooFriend', array('local' => 'foo1', + 'foreign' => 'foo2', + 'equal' => true, + 'refClass' => 'FooReferenceRecord', + )); + + $this->hasMany('FooRecord as FooParents', array('local' => 'foo1', + 'foreign' => 'foo2', + 'refClass' => 'FooReferenceRecord', + 'onDelete' => 'RESTRICT', + )); + + $this->hasMany('FooRecord as FooChildren', array('local' => 'foo2', + 'foreign' => 'foo1', + 'refClass' => 'FooReferenceRecord', + )); $this->hasMany('FooRecord as Children', array('local' => 'id', 'foreign' => 'parent_id')); $this->hasOne('FooRecord as Parent', array('local' => 'parent_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); $this->hasOne('FooForeignlyOwnedWithPk', array('local' => 'id', 'foreign' => 'id', 'constraint' => true)); $this->hasOne('FooLocallyOwned', array('local' => 'local_foo', 'onDelete' => 'RESTRICT')); - - $this->hasMany('BarRecord as Bar', array('local' => 'fooId', - 'foreign' => 'barId', - 'refClass' => 'FooBarRecord', - 'onUpdate' => 'RESTRICT')); + $this->hasMany('BarRecord as Bar', array('local' => 'fooId', + 'foreign' => 'barId', + 'refClass' => 'FooBarRecord', + 'onUpdate' => 'RESTRICT')); } } diff --git a/tests/models/FooReferenceRecord.php b/tests/models/FooReferenceRecord.php index fb378065f..465ca3835 100644 --- a/tests/models/FooReferenceRecord.php +++ b/tests/models/FooReferenceRecord.php @@ -1,10 +1,11 @@ setTableName('foo_reference'); - + $this->hasColumn('foo1', 'integer', null, array('primary' => true)); $this->hasColumn('foo2', 'integer', null, array('primary' => true)); } diff --git a/tests/models/ForeignKeyTest.php b/tests/models/ForeignKeyTest.php index f6ccb41ee..d8708a143 100644 --- a/tests/models/ForeignKeyTest.php +++ b/tests/models/ForeignKeyTest.php @@ -1,4 +1,10 @@ hasColumn('parent_id', 'integer'); $this->hasOne('ForeignKeyTest as Parent', - array('local' => 'parent_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE', - 'onUpdate' => 'RESTRICT') - ); + array('local' => 'parent_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + 'onUpdate' => 'RESTRICT') + ); $this->hasMany('ForeignKeyTest as Children', array( - 'local' => 'id', 'foreign' => 'parent_id', 'cascade' => array('delete'))); + 'local' => 'id', 'foreign' => 'parent_id', 'cascade' => array('delete'))); $this->option('type', 'INNODB'); - } } diff --git a/tests/models/ForeignKeyTest2.php b/tests/models/ForeignKeyTest2.php index 9a0f0b7ce..8e7c2ce01 100644 --- a/tests/models/ForeignKeyTest2.php +++ b/tests/models/ForeignKeyTest2.php @@ -1,13 +1,14 @@ hasColumn('name', 'string', null); $this->hasColumn('foreignkey', 'integer'); - + $this->hasOne('ForeignKeyTest', array( - 'local' => 'foreignKey', 'foreign' => 'id' + 'local' => 'foreignKey', 'foreign' => 'id', )); } } diff --git a/tests/models/Forum_Board.php b/tests/models/Forum_Board.php index 6bb679fc9..7c0a47661 100644 --- a/tests/models/Forum_Board.php +++ b/tests/models/Forum_Board.php @@ -1,13 +1,17 @@ hasColumn('category_id', 'integer', 10); $this->hasColumn('name', 'string', 100); $this->hasColumn('description', 'string', 5000); } - public function setUp() { + + public function setUp() + { $this->hasOne('Forum_Category as Category', array('local' => 'category_id', 'foreign' => 'id')); - $this->hasMany('Forum_Thread as Threads', array('local' => 'id', 'foreign' => 'board_id')); - } + $this->hasMany('Forum_Thread as Threads', array('local' => 'id', 'foreign' => 'board_id')); + } } - diff --git a/tests/models/Forum_Category.php b/tests/models/Forum_Category.php index 72ec9bf06..a1cc589df 100644 --- a/tests/models/Forum_Category.php +++ b/tests/models/Forum_Category.php @@ -1,25 +1,30 @@ hasColumn('root_category_id', 'integer', 10); $this->hasColumn('parent_category_id', 'integer', 10); $this->hasColumn('name', 'string', 50); $this->hasColumn('description', 'string', 99999); } - public function setUp() { + + public function setUp() + { $this->hasMany('Forum_Category as Subcategory', array( 'local' => 'id', - 'foreign' => 'parent_category_id' + 'foreign' => 'parent_category_id', )); - + $this->hasOne('Forum_Category as Parent', array( 'local' => 'parent_category_id', - 'foreign' => 'id' + 'foreign' => 'id', )); $this->hasOne('Forum_Category as Rootcategory', array( 'local' => 'root_category_id', - 'foreign' => 'id' + 'foreign' => 'id', )); } } diff --git a/tests/models/Forum_Entry.php b/tests/models/Forum_Entry.php index 91817dec0..eac2bf3d2 100644 --- a/tests/models/Forum_Entry.php +++ b/tests/models/Forum_Entry.php @@ -1,16 +1,20 @@ hasColumn('author', 'string', 50); + +class Forum_Entry extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('author', 'string', 50); $this->hasColumn('topic', 'string', 100); $this->hasColumn('message', 'string', 99999); $this->hasColumn('parent_entry_id', 'integer', 10); $this->hasColumn('thread_id', 'integer', 10); $this->hasColumn('date', 'integer', 10); } - public function setUp() { - $this->hasOne('Forum_Entry as Parent', array('local' => 'id', 'foreign' => 'parent_entry_id')); + + public function setUp() + { + $this->hasOne('Forum_Entry as Parent', array('local' => 'id', 'foreign' => 'parent_entry_id')); $this->hasOne('Forum_Thread as Thread', array('local' => 'thread_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); } } - diff --git a/tests/models/Forum_Thread.php b/tests/models/Forum_Thread.php index afac222c7..6391bb3e4 100644 --- a/tests/models/Forum_Thread.php +++ b/tests/models/Forum_Thread.php @@ -1,13 +1,17 @@ hasColumn('board_id', 'integer', 10); $this->hasColumn('updated', 'integer', 10); $this->hasColumn('closed', 'integer', 1); } - public function setUp() { + + public function setUp() + { $this->hasOne('Forum_Board as Board', array('local' => 'board_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); $this->hasMany('Forum_Entry as Entries', array('local' => 'id', 'foreign' => 'thread_id')); } } - diff --git a/tests/models/Group.php b/tests/models/Group.php index 07e9dee08..e1a00f50b 100644 --- a/tests/models/Group.php +++ b/tests/models/Group.php @@ -1,10 +1,12 @@ Doctrine_Connection // won't initialize grouptable when Doctrine_Connection->getTable('Group') is called -class GroupTable { } +class GroupTable +{ +} class Group extends Entity { @@ -18,4 +20,3 @@ public function setUp() )); } } - diff --git a/tests/models/GroupUser.php b/tests/models/GroupUser.php index e7acea16c..c3f197ae5 100644 --- a/tests/models/GroupUser.php +++ b/tests/models/GroupUser.php @@ -1,13 +1,14 @@ hasColumn('added', 'integer'); $this->hasColumn('group_id', 'integer'); $this->hasColumn('user_id', 'integer'); } - + public function setUp() { $this->hasOne('Group', array('local' => 'group_id', 'foreign' => 'id')); diff --git a/tests/models/GzipTest.php b/tests/models/GzipTest.php index 64dc9996d..00b576ffb 100644 --- a/tests/models/GzipTest.php +++ b/tests/models/GzipTest.php @@ -1,6 +1,14 @@ hasColumn('gzip', 'gzip', 100000); } } diff --git a/tests/models/I18nRelationTest.php b/tests/models/I18nRelationTest.php index 95f271f24..e2f8a3cfb 100644 --- a/tests/models/I18nRelationTest.php +++ b/tests/models/I18nRelationTest.php @@ -1,4 +1,10 @@ hasColumn('title', 'string', 200); $this->hasColumn('author_id', 'integer', 4); } + public function setUp() { $this->hasOne('I18nAuthorTest', array('local' => 'author_id', - 'foreign' => 'id')); + 'foreign' => 'id')); $this->actAs('I18n', array('fields' => array('author_id', 'title'))); } } -class I18nAuthorTest extends Doctrine_Record +/** + * @internal + * + * @coversNothing + */ +class I18nAuthorTest extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); } + public function setUp() { $this->hasMany('I18nRelationTest', array('local' => 'id', - 'foreign' => 'author_id')); + 'foreign' => 'author_id')); } -} \ No newline at end of file +} diff --git a/tests/models/I18nTest.php b/tests/models/I18nTest.php index cb8e579c2..9265c6819 100644 --- a/tests/models/I18nTest.php +++ b/tests/models/I18nTest.php @@ -1,4 +1,10 @@ hasColumn('name', 'string', 200); $this->hasColumn('title', 'string', 200); } + public function setUp() { $this->actAs('I18n', array('fields' => array('name', 'title'))); diff --git a/tests/models/InheritanceDeal.php b/tests/models/InheritanceDeal.php index c1f40e3b6..91d585488 100644 --- a/tests/models/InheritanceDeal.php +++ b/tests/models/InheritanceDeal.php @@ -1,16 +1,17 @@ setTableName('inheritance_deal'); - - $this->hasColumn('id', 'integer', 4, array ( 'primary' => true, 'autoincrement' => true,)); - $this->hasColumn('name', 'string', 255, array ()); + + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 255, array()); } - + public function setUp() { $this->hasMany('InheritanceUser as Users', array('refClass' => 'InheritanceDealUser', 'local' => 'entity_id', 'foreign' => 'user_id')); } -} \ No newline at end of file +} diff --git a/tests/models/InheritanceDealUser.php b/tests/models/InheritanceDealUser.php index ba60b8633..007695d3c 100644 --- a/tests/models/InheritanceDealUser.php +++ b/tests/models/InheritanceDealUser.php @@ -1,17 +1,18 @@ setTableName('inheritance_entity_user'); - $this->hasColumn('type', 'integer', 4, array ( 'primary' => true,)); - $this->hasColumn('user_id', 'integer', 4, array ( 'primary' => true,)); - $this->hasColumn('entity_id', 'integer', 4, array ( 'primary' => true,)); + $this->hasColumn('type', 'integer', 4, array('primary' => true)); + $this->hasColumn('user_id', 'integer', 4, array('primary' => true)); + $this->hasColumn('entity_id', 'integer', 4, array('primary' => true)); } public function setUp() - { + { } } @@ -23,8 +24,8 @@ public function setTableDefinition() $this->setTableName('inheritance_entity_user'); - $this->hasColumn('user_id', 'integer', 4, array ( 'primary' => true,)); - $this->hasColumn('entity_id', 'integer', 4, array ( 'primary' => true,)); + $this->hasColumn('user_id', 'integer', 4, array('primary' => true)); + $this->hasColumn('entity_id', 'integer', 4, array('primary' => true)); } public function setUp() @@ -33,8 +34,8 @@ public function setUp() $this->hasOne('InheritanceUser as User', array('local' => 'user_id', 'foreign' => 'id')); $this->hasOne('InheritanceDeal as Deal', array('local' => 'entity_id', 'foreign' => 'id')); - $this->setInheritanceMap(array ( - 'type' => 1, + $this->setInheritanceMap(array( + 'type' => 1, )); } -} \ No newline at end of file +} diff --git a/tests/models/InheritanceUser.php b/tests/models/InheritanceUser.php index fa9dacfe8..f4ac436c6 100644 --- a/tests/models/InheritanceUser.php +++ b/tests/models/InheritanceUser.php @@ -1,16 +1,17 @@ setTableName('inheritance_user'); - $this->hasColumn('id', 'integer', 4, array ( 'primary' => true, 'autoincrement' => true,)); - $this->hasColumn('username', 'string', 128, array ( 'notnull' => true,)); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('username', 'string', 128, array('notnull' => true)); } public function setUp() { $this->hasMany('InheritanceDeal as Deals', array('refClass' => 'InheritanceDealUser', 'local' => 'user_id', 'foreign' => 'entity_id')); } -} \ No newline at end of file +} diff --git a/tests/models/JC1.php b/tests/models/JC1.php index 6c5183426..c72e9e282 100644 --- a/tests/models/JC1.php +++ b/tests/models/JC1.php @@ -1,8 +1,10 @@ hasColumn('c1_id', 'integer'); $this->hasColumn('c2_id', 'integer'); } } - diff --git a/tests/models/JC2.php b/tests/models/JC2.php index 7f6c27cc4..934c1bb50 100644 --- a/tests/models/JC2.php +++ b/tests/models/JC2.php @@ -1,8 +1,10 @@ hasColumn('c1_id', 'integer'); $this->hasColumn('c2_id', 'integer'); } } - diff --git a/tests/models/JC3.php b/tests/models/JC3.php index a3d68cc5d..1e0989738 100644 --- a/tests/models/JC3.php +++ b/tests/models/JC3.php @@ -1,8 +1,10 @@ hasColumn('c1_id', 'integer'); $this->hasColumn('c2_id', 'integer'); } } - diff --git a/tests/models/LiabilityCodeN.php b/tests/models/LiabilityCodeN.php index fc729554e..205cebfb5 100644 --- a/tests/models/LiabilityCodeN.php +++ b/tests/models/LiabilityCodeN.php @@ -1,11 +1,12 @@ setTableName('liability_codes'); - $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('code', 'integer', 4, array ( 'notnull' => true, 'notblank' => true,)); - $this->hasColumn('description', 'string', 4000, array ( 'notnull' => true, 'notblank' => true,)); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('liability_codes'); + $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('code', 'integer', 4, array('notnull' => true, 'notblank' => true)); + $this->hasColumn('description', 'string', 4000, array('notnull' => true, 'notblank' => true)); + } +} diff --git a/tests/models/Location.php b/tests/models/Location.php index 4cd8611d8..9ed4e3032 100644 --- a/tests/models/Location.php +++ b/tests/models/Location.php @@ -1,10 +1,11 @@ hasColumn('lat', 'double', 10, array ()); - $this->hasColumn('lon', 'double', 10, array ()); + $this->hasColumn('lat', 'double', 10, array()); + $this->hasColumn('lon', 'double', 10, array()); } public function setUp() diff --git a/tests/models/Location2.php b/tests/models/Location2.php index 80ad551cf..f21edcfb1 100644 --- a/tests/models/Location2.php +++ b/tests/models/Location2.php @@ -1,4 +1,5 @@ hasColumn('name', 'string', 50, array()); $this->hasColumn('id', 'integer', 10, array('primary' => true)); $this->hasColumn('culture', 'string', 2); } - + public function setUp() { $this->hasOne('Location as Location', array('local' => 'id')); diff --git a/tests/models/Log_Entry.php b/tests/models/Log_Entry.php index 670af073e..773ad9e3c 100644 --- a/tests/models/Log_Entry.php +++ b/tests/models/Log_Entry.php @@ -1,13 +1,17 @@ hasColumn('stamp', 'timestamp'); $this->hasColumn('status_id', 'integer'); } - - public function setUp() { + + public function setUp() + { $this->hasOne('Log_Status', array( - 'local' => 'status_id', 'foreign' => 'id' + 'local' => 'status_id', 'foreign' => 'id', )); } } diff --git a/tests/models/Log_Status.php b/tests/models/Log_Status.php index e8540e858..3deeae114 100644 --- a/tests/models/Log_Status.php +++ b/tests/models/Log_Status.php @@ -1,6 +1,9 @@ hasColumn('name', 'string', 255); } } diff --git a/tests/models/M2MTest.php b/tests/models/M2MTest.php index 63e1f20f8..930054fc5 100644 --- a/tests/models/M2MTest.php +++ b/tests/models/M2MTest.php @@ -1,16 +1,23 @@ hasColumn('name', 'string', 200); $this->hasColumn('child_id', 'integer'); } - public function setUp() { + public function setUp() + { $this->hasMany('RTC1 as RTC1', array('local' => 'c1_id', 'foreign' => 'c1_id', 'refClass' => 'JC1')); $this->hasMany('RTC2 as RTC2', array('local' => 'c1_id', 'foreign' => 'c1_id', 'refClass' => 'JC1')); $this->hasMany('RTC3 as RTC3', array('local' => 'c1_id', 'foreign' => 'c1_id', 'refClass' => 'JC2')); $this->hasMany('RTC3 as RTC4', array('local' => 'c1_id', 'foreign' => 'c1_id', 'refClass' => 'JC1')); - } } - diff --git a/tests/models/M2MTest2.php b/tests/models/M2MTest2.php index 80d0bef30..bdcb628e7 100644 --- a/tests/models/M2MTest2.php +++ b/tests/models/M2MTest2.php @@ -1,11 +1,15 @@ hasColumn('oid', 'integer', 11, array('autoincrement' => true, 'primary' => true)); $this->hasColumn('name', 'string', 20); } - public function setUp() { + + public function setUp() + { $this->hasMany('RTC4 as RTC5', array('local' => 'c1_id', 'foreign' => 'c1_id', 'refClass' => 'JC3')); } } - diff --git a/tests/models/MigrationTest.php b/tests/models/MigrationTest.php index f042df011..4ec0b2679 100644 --- a/tests/models/MigrationTest.php +++ b/tests/models/MigrationTest.php @@ -1,8 +1,14 @@ hasColumn('field1', 'string'); } -} \ No newline at end of file +} diff --git a/tests/models/MyGroup.php b/tests/models/MyGroup.php index dfc6b76ff..313ba7dd9 100644 --- a/tests/models/MyGroup.php +++ b/tests/models/MyGroup.php @@ -1,17 +1,18 @@ setTableName('my_group'); - $this->hasColumn('id', 'integer', 4, array ( 'primary' => true, 'autoincrement' => true,)); - $this->hasColumn('name', 'string', 255, array ( 'notnull' => true,)); - $this->hasColumn('description', 'string', 4000, array ()); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('name', 'string', 255, array('notnull' => true)); + $this->hasColumn('description', 'string', 4000, array()); } public function setUp() { $this->hasMany('MyUser as users', array('refClass' => 'MyUserGroup', 'local' => 'group_id', 'foreign' => 'user_id')); - } + } } diff --git a/tests/models/MyOneThing.php b/tests/models/MyOneThing.php index f16866520..a4c604720 100644 --- a/tests/models/MyOneThing.php +++ b/tests/models/MyOneThing.php @@ -1,17 +1,21 @@ hasColumn('name', 'string'); $this->hasColumn('user_id', 'integer'); } - public function setUp() { - $this->hasMany('MyUserOneThing', array( - 'local' => 'id', 'foreign' => 'one_thing_id' + public function setUp() + { + $this->hasMany('MyUserOneThing', array( + 'local' => 'id', 'foreign' => 'one_thing_id', )); - + $this->hasOne('MyUser', array( - 'local' => 'user_id', 'foreign' => 'id' + 'local' => 'user_id', 'foreign' => 'id', )); } } diff --git a/tests/models/MyOtherThing.php b/tests/models/MyOtherThing.php index 5b48c7c3a..571bf7227 100644 --- a/tests/models/MyOtherThing.php +++ b/tests/models/MyOtherThing.php @@ -1,16 +1,21 @@ hasColumn('name', 'string'); $this->hasColumn('user_id', 'integer'); } - public function setUp() { - $this->hasMany('MyUserOtherThing', array( - 'local' => 'id', 'foreign' => 'other_thing_id' + + public function setUp() + { + $this->hasMany('MyUserOtherThing', array( + 'local' => 'id', 'foreign' => 'other_thing_id', )); - + $this->hasOne('MyUser', array( - 'local' => 'user_id', 'foreign' => 'id' + 'local' => 'user_id', 'foreign' => 'id', )); } } diff --git a/tests/models/MyUser.php b/tests/models/MyUser.php index 6ad34275d..276db6cef 100644 --- a/tests/models/MyUser.php +++ b/tests/models/MyUser.php @@ -1,19 +1,20 @@ hasColumn('name', 'string'); } - + public function setUp() { - $this->hasMany('MyOneThing', array( - 'local' => 'id', 'foreign' => 'user_id' - )); + $this->hasMany('MyOneThing', array( + 'local' => 'id', 'foreign' => 'user_id', + )); - $this->hasMany('MyOtherThing', array( - 'local' => 'id', 'foreign' => 'user_id' - )); + $this->hasMany('MyOtherThing', array( + 'local' => 'id', 'foreign' => 'user_id', + )); } -} \ No newline at end of file +} diff --git a/tests/models/MyUser2.php b/tests/models/MyUser2.php index 8e98a59eb..6c7349717 100644 --- a/tests/models/MyUser2.php +++ b/tests/models/MyUser2.php @@ -1,23 +1,24 @@ setTableName('my_user'); - $this->hasColumn('id', 'integer', 4, array ( 'primary' => true, 'autoincrement' => true,)); - $this->hasColumn('username', 'string', 128, array ( 'notnull' => true,)); - $this->hasColumn('algorithm', 'string', 128, array ( 'default' => 'sha1', 'notnull' => true,)); - $this->hasColumn('salt', 'string', 128, array ( 'notnull' => true,)); - $this->hasColumn('password', 'string', 128, array ( 'notnull' => true,)); - $this->hasColumn('created_at', 'timestamp', null, array ()); - $this->hasColumn('last_login', 'timestamp', null, array ()); - $this->hasColumn('is_active', 'boolean', null, array ( 'default' => 1, 'notnull' => true,)); - $this->hasColumn('is_super_admin', 'boolean', null, array ( 'default' => 0, 'notnull' => true,)); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('username', 'string', 128, array('notnull' => true)); + $this->hasColumn('algorithm', 'string', 128, array('default' => 'sha1', 'notnull' => true)); + $this->hasColumn('salt', 'string', 128, array('notnull' => true)); + $this->hasColumn('password', 'string', 128, array('notnull' => true)); + $this->hasColumn('created_at', 'timestamp', null, array()); + $this->hasColumn('last_login', 'timestamp', null, array()); + $this->hasColumn('is_active', 'boolean', null, array('default' => 1, 'notnull' => true)); + $this->hasColumn('is_super_admin', 'boolean', null, array('default' => 0, 'notnull' => true)); } public function setUp() { $this->hasMany('MyGroup as groups', array('refClass' => 'MyUserGroup', 'local' => 'user_id', 'foreign' => 'group_id')); - } + } } diff --git a/tests/models/MyUserGroup.php b/tests/models/MyUserGroup.php index 6e33ac875..2bbc0ba50 100644 --- a/tests/models/MyUserGroup.php +++ b/tests/models/MyUserGroup.php @@ -1,15 +1,16 @@ setTableName('my_user_group'); - - $this->hasColumn('id', 'integer', 4, array ( 'primary' => true, 'autoincrement' => true,)); - $this->hasColumn('group_id', 'integer', 4, array ()); - $this->hasColumn('user_id', 'integer', 4, array ()); + + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('group_id', 'integer', 4, array()); + $this->hasColumn('user_id', 'integer', 4, array()); } - + public function setUp() { $this->hasOne('MyGroup as MyGroup', array('local' => 'group_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); diff --git a/tests/models/MyUserOneThing.php b/tests/models/MyUserOneThing.php index a6d81a2c6..690e64134 100644 --- a/tests/models/MyUserOneThing.php +++ b/tests/models/MyUserOneThing.php @@ -1,19 +1,21 @@ hasColumn('user_id', 'integer'); $this->hasColumn('one_thing_id', 'integer'); } - - + public function setUp() { $this->hasOne('MyUser', array( - 'local' => 'user_id', 'foreign' => 'id' + 'local' => 'user_id', 'foreign' => 'id', )); - + $this->hasOne('MyOneThing', array( - 'local' => 'one_thing_id', 'foreign' => 'id' + 'local' => 'one_thing_id', 'foreign' => 'id', )); } } diff --git a/tests/models/MyUserOtherThing.php b/tests/models/MyUserOtherThing.php index 788a4b393..9ab081f4b 100644 --- a/tests/models/MyUserOtherThing.php +++ b/tests/models/MyUserOtherThing.php @@ -1,19 +1,21 @@ hasColumn('user_id', 'integer'); $this->hasColumn('other_thing_id', 'integer'); } - - + public function setUp() { $this->hasOne('MyUser', array( - 'local' => 'user_id', 'foreign' => 'id' + 'local' => 'user_id', 'foreign' => 'id', )); - + $this->hasOne('MyOtherThing', array( - 'local' => 'other_thing_id', 'foreign' => 'id' + 'local' => 'other_thing_id', 'foreign' => 'id', )); } } diff --git a/tests/models/MysqlGroup.php b/tests/models/MysqlGroup.php index d1f0cc5b5..fad434420 100644 --- a/tests/models/MysqlGroup.php +++ b/tests/models/MysqlGroup.php @@ -1,17 +1,18 @@ hasColumn('name', 'string', null); } - + public function setUp() { $this->hasMany('MysqlUser', array( - 'local' => 'group_id', + 'local' => 'group_id', 'foreign' => 'user_id', - 'refClass' => 'MysqlGroupMember' + 'refClass' => 'MysqlGroupMember', )); } } diff --git a/tests/models/MysqlGroupMember.php b/tests/models/MysqlGroupMember.php index 351994293..8c09b8018 100644 --- a/tests/models/MysqlGroupMember.php +++ b/tests/models/MysqlGroupMember.php @@ -1,10 +1,10 @@ hasColumn('group_id', 'integer', null, array('primary' => true)); $this->hasColumn('user_id', 'integer', null, array('primary' => true)); } } - diff --git a/tests/models/MysqlIndexTestRecord.php b/tests/models/MysqlIndexTestRecord.php index ae917d7dd..915b1185e 100644 --- a/tests/models/MysqlIndexTestRecord.php +++ b/tests/models/MysqlIndexTestRecord.php @@ -1,17 +1,17 @@ hasColumn('name', 'string', null); $this->hasColumn('code', 'integer', 4); $this->hasColumn('content', 'string', 4000); - $this->index('content', array('fields' => array('content'), 'type' => 'fulltext')); + $this->index('content', array('fields' => array('content'), 'type' => 'fulltext')); $this->index('namecode', array('fields' => array('name', 'code'), - 'type' => 'unique')); + 'type' => 'unique')); $this->option('type', 'MYISAM'); - } } diff --git a/tests/models/MysqlTestRecord.php b/tests/models/MysqlTestRecord.php index 44bd8f582..c511ebd60 100644 --- a/tests/models/MysqlTestRecord.php +++ b/tests/models/MysqlTestRecord.php @@ -1,7 +1,8 @@ hasColumn('name', 'string', null, 'primary'); $this->hasColumn('code', 'integer', null, 'primary'); diff --git a/tests/models/MysqlUser.php b/tests/models/MysqlUser.php index 938201c48..a93c750cb 100644 --- a/tests/models/MysqlUser.php +++ b/tests/models/MysqlUser.php @@ -1,17 +1,18 @@ hasColumn('name', 'string', null); } - + public function setUp() { $this->hasMany('MysqlGroup', array( 'local' => 'user_id', 'foreign' => 'group_id', - 'refClass' => 'MysqlGroupMember' + 'refClass' => 'MysqlGroupMember', )); } } diff --git a/tests/models/NestReference.php b/tests/models/NestReference.php index 0f2d05888..d6a9697c2 100644 --- a/tests/models/NestReference.php +++ b/tests/models/NestReference.php @@ -1,7 +1,8 @@ hasColumn('parent_id', 'integer', 4, 'primary'); $this->hasColumn('child_id', 'integer', 4, 'primary'); diff --git a/tests/models/NestTest.php b/tests/models/NestTest.php index f1bdea67a..288ebf30b 100644 --- a/tests/models/NestTest.php +++ b/tests/models/NestTest.php @@ -1,22 +1,29 @@ hasColumn('name', 'string'); } + public function setUp() { $this->hasMany('NestTest as Parents', array('local' => 'child_id', - 'refClass' => 'NestReference', - 'foreign' => 'parent_id')); + 'refClass' => 'NestReference', + 'foreign' => 'parent_id')); $this->hasMany('NestTest as Children', array('local' => 'parent_id', - 'refClass' => 'NestReference', - 'foreign' => 'child_id')); - + 'refClass' => 'NestReference', + 'foreign' => 'child_id')); + $this->hasMany('NestTest as Relatives', array('local' => 'child_id', - 'refClass' => 'NestReference', - 'foreign' => 'parent_id', - 'equal' => true)); + 'refClass' => 'NestReference', + 'foreign' => 'parent_id', + 'equal' => true)); } } diff --git a/tests/models/NestedSetTest_SingleRootNode.php b/tests/models/NestedSetTest_SingleRootNode.php index 1aea10b8f..ea0812b0f 100644 --- a/tests/models/NestedSetTest_SingleRootNode.php +++ b/tests/models/NestedSetTest_SingleRootNode.php @@ -1,9 +1,10 @@ actAs('NestedSet'); $this->hasColumn('name', 'string', 50, array('notnull')); } - } diff --git a/tests/models/NestedSet_MultiRootNode.php b/tests/models/NestedSet_MultiRootNode.php index ca907b6b7..a0e54dbe6 100644 --- a/tests/models/NestedSet_MultiRootNode.php +++ b/tests/models/NestedSet_MultiRootNode.php @@ -1,10 +1,11 @@ actAs('NestedSet', array('hasManyRoots' => true, 'rootColumnName' => 'root_id')); $this->hasColumn('name', 'string', 50, array('notnull')); $this->hasColumn('root_id', 'integer', 4); } - } diff --git a/tests/models/NestedSet_Timestampable_MultiRootNode.php b/tests/models/NestedSet_Timestampable_MultiRootNode.php index 995d94c71..1904e641e 100644 --- a/tests/models/NestedSet_Timestampable_MultiRootNode.php +++ b/tests/models/NestedSet_Timestampable_MultiRootNode.php @@ -1,7 +1,9 @@ actAs('NestedSet', array('hasManyRoots' => true, 'rootColumnName' => 'root_id')); $this->actAs('Timestampable'); $this->hasColumn('name', 'string', 50, array('notnull')); diff --git a/tests/models/NotNullTest.php b/tests/models/NotNullTest.php index 786d213a2..032c58e57 100644 --- a/tests/models/NotNullTest.php +++ b/tests/models/NotNullTest.php @@ -1,7 +1,15 @@ hasColumn('name', 'string', 100, 'notnull'); - $this->hasColumn('type', 'integer', 11); + $this->hasColumn('type', 'integer', 11); } } diff --git a/tests/models/ORM_AccessControl.php b/tests/models/ORM_AccessControl.php index 4ae702d58..5c423355e 100644 --- a/tests/models/ORM_AccessControl.php +++ b/tests/models/ORM_AccessControl.php @@ -1,14 +1,16 @@ hasColumn('name', 'string', 255); } - public function setUp() + + public function setUp() { $this->hasMany('ORM_AccessGroup as accessGroups', array( - 'local' => 'accessControlID', 'foreign' => 'accessGroupID', 'refClass' => 'ORM_AccessControlsGroups' + 'local' => 'accessControlID', 'foreign' => 'accessGroupID', 'refClass' => 'ORM_AccessControlsGroups', )); } } diff --git a/tests/models/ORM_AccessControlsGroups.php b/tests/models/ORM_AccessControlsGroups.php index 218b219c3..1f0c69ee1 100644 --- a/tests/models/ORM_AccessControlsGroups.php +++ b/tests/models/ORM_AccessControlsGroups.php @@ -1,9 +1,10 @@ hasColumn('accessControlID', 'integer', 11, array('primary' => true)); + $this->hasColumn('accessControlID', 'integer', 11, array('primary' => true)); $this->hasColumn('accessGroupID', 'integer', 11, array('primary' => true)); } } diff --git a/tests/models/ORM_AccessGroup.php b/tests/models/ORM_AccessGroup.php index ed264e19b..a0e608db9 100644 --- a/tests/models/ORM_AccessGroup.php +++ b/tests/models/ORM_AccessGroup.php @@ -1,14 +1,16 @@ hasColumn('name', 'string', 255); } - public function setUp() + + public function setUp() { $this->hasMany('ORM_AccessControl as accessControls', array( - 'local' => 'accessGroupID', 'foreign' => 'accessControlID', 'refClass' => 'ORM_AccessControlsGroups' + 'local' => 'accessGroupID', 'foreign' => 'accessControlID', 'refClass' => 'ORM_AccessControlsGroups', )); } } diff --git a/tests/models/ORM_TestEntry.php b/tests/models/ORM_TestEntry.php index b6516e754..891dcd65d 100644 --- a/tests/models/ORM_TestEntry.php +++ b/tests/models/ORM_TestEntry.php @@ -1,17 +1,21 @@ setTableName('test_entries'); $this->hasColumn('id', 'integer', 11, 'autoincrement|primary'); - $this->hasColumn('name', 'string', 255); + $this->hasColumn('name', 'string', 255); $this->hasColumn('stamp', 'timestamp'); - $this->hasColumn('amount', 'float'); - $this->hasColumn('itemID', 'integer'); - } - - public function setUp() { + $this->hasColumn('amount', 'float'); + $this->hasColumn('itemID', 'integer'); + } + + public function setUp() + { $this->hasOne('ORM_TestItem', array( - 'local' => 'itemID', 'foreign' => 'id' + 'local' => 'itemID', 'foreign' => 'id', )); - } + } } diff --git a/tests/models/ORM_TestItem.php b/tests/models/ORM_TestItem.php index c81182ba0..522d6f3d6 100644 --- a/tests/models/ORM_TestItem.php +++ b/tests/models/ORM_TestItem.php @@ -1,15 +1,18 @@ setTableName('test_items'); $this->hasColumn('id', 'integer', 11, 'autoincrement|primary'); - $this->hasColumn('name', 'string', 255); - } - - public function setUp() { + $this->hasColumn('name', 'string', 255); + } + public function setUp() + { $this->hasOne('ORM_TestEntry', array( - 'local' => 'id', 'foreign' => 'itemID' + 'local' => 'id', 'foreign' => 'itemID', )); - } + } } diff --git a/tests/models/Package.php b/tests/models/Package.php index 56375017f..f26d97ce4 100644 --- a/tests/models/Package.php +++ b/tests/models/Package.php @@ -1,6 +1,9 @@ hasColumn('description', 'string', 255); } diff --git a/tests/models/PackageVersion.php b/tests/models/PackageVersion.php index c3684a4c2..034b8a56d 100644 --- a/tests/models/PackageVersion.php +++ b/tests/models/PackageVersion.php @@ -1,14 +1,18 @@ hasColumn('package_id', 'integer'); $this->hasColumn('description', 'string', 255); } + public function setUp() { $this->hasOne('Package', array('local' => 'package_id', 'foreign' => 'id')); $this->hasMany('PackageVersionNotes as Note', array( - 'local' => 'id', 'foreign' => 'package_version_id' + 'local' => 'id', 'foreign' => 'package_version_id', )); } } diff --git a/tests/models/PackageVersionNotes.php b/tests/models/PackageVersionNotes.php index b9325c999..de743aee3 100644 --- a/tests/models/PackageVersionNotes.php +++ b/tests/models/PackageVersionNotes.php @@ -1,15 +1,17 @@ hasColumn('package_version_id', 'integer'); $this->hasColumn('description', 'string', 255); } + public function setUp() { $this->hasOne('PackageVersion', array( - 'local' => 'package_version_id', 'foreign' => 'id' + 'local' => 'package_version_id', 'foreign' => 'id', )); } } diff --git a/tests/models/Page.php b/tests/models/Page.php index 02f00fc42..dff9b2fae 100644 --- a/tests/models/Page.php +++ b/tests/models/Page.php @@ -1,12 +1,12 @@ hasMany('Bookmark as Bookmarks', - array('local' => 'id', - 'foreign' => 'page_id')); + $this->hasMany('Bookmark as Bookmarks', + array('local' => 'id', + 'foreign' => 'page_id')); } public function setTableDefinition() diff --git a/tests/models/Phonenumber.php b/tests/models/Phonenumber.php index 23b178dc4..5f929b46b 100644 --- a/tests/models/Phonenumber.php +++ b/tests/models/Phonenumber.php @@ -1,23 +1,25 @@ hasColumn('phonenumber', 'string',20); + $this->hasColumn('phonenumber', 'string', 20); $this->hasColumn('entity_id', 'integer'); } - public function setUp() + + public function setUp() { - $this->hasOne('Entity', array('local' => 'entity_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); - - $this->hasOne('Group', array('local' => 'entity_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); - - $this->hasOne('User', array('local' => 'entity_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + $this->hasOne('Entity', array('local' => 'entity_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); + + $this->hasOne('Group', array('local' => 'entity_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); + + $this->hasOne('User', array('local' => 'entity_id', + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); } } diff --git a/tests/models/Photo.php b/tests/models/Photo.php index af2c5023f..96f2d236f 100644 --- a/tests/models/Photo.php +++ b/tests/models/Photo.php @@ -1,13 +1,18 @@ hasMany('Tag', array( 'local' => 'photo_id', 'foreign' => 'tag_id', - 'refClass' => 'Phototag' + 'refClass' => 'Phototag', )); } - public function setTableDefinition() { + + public function setTableDefinition() + { $this->hasColumn('name', 'string', 100); } } diff --git a/tests/models/Phototag.php b/tests/models/Phototag.php index cfae09360..f0c58ea4e 100644 --- a/tests/models/Phototag.php +++ b/tests/models/Phototag.php @@ -1,6 +1,9 @@ hasColumn('photo_id', 'integer', 11, array('primary' => true)); $this->hasColumn('tag_id', 'integer', 11, array('primary' => true)); } diff --git a/tests/models/PluginSymfonyRecord.php b/tests/models/PluginSymfonyRecord.php index 5cd72f599..3dafb6000 100644 --- a/tests/models/PluginSymfonyRecord.php +++ b/tests/models/PluginSymfonyRecord.php @@ -1,5 +1,6 @@ hasColumn('policy_number', 'integer', 11, array('unique' => true)); } - + public function setUp() { $this->hasMany('PolicyAsset as PolicyAssets', array('local' => 'policy_number', - 'foreign' => 'policy_number')); + 'foreign' => 'policy_number')); $this->index('policy_number_index', array('fields' => array('policy_number'))); } } diff --git a/tests/models/PolicyAsset.php b/tests/models/PolicyAsset.php index f68da7a02..806095f9c 100644 --- a/tests/models/PolicyAsset.php +++ b/tests/models/PolicyAsset.php @@ -1,16 +1,17 @@ hasColumn('policy_number', 'integer', 11); - $this->hasColumn('value', 'float', 10, array ('notblank' => true,)); + $this->hasColumn('value', 'float', 10, array('notblank' => true)); } public function setUp() { - $this->hasOne('Policy', array('foreign' => 'policy_number', - 'local' => 'policy_number')); + $this->hasOne('Policy', array('foreign' => 'policy_number', + 'local' => 'policy_number')); $this->index('policy_number_index', array('fields' => array('policy_number'))); } } diff --git a/tests/models/PolicyCodeN.php b/tests/models/PolicyCodeN.php index f1fbcc22e..9729c74be 100644 --- a/tests/models/PolicyCodeN.php +++ b/tests/models/PolicyCodeN.php @@ -1,11 +1,12 @@ setTableName('policy_codes'); - $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('code', 'integer', 4, array ( 'notnull' => true, 'notblank' => true,)); - $this->hasColumn('description', 'string', 4000, array ( 'notnull' => true, 'notblank' => true,)); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('policy_codes'); + $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('code', 'integer', 4, array('notnull' => true, 'notblank' => true)); + $this->hasColumn('description', 'string', 4000, array('notnull' => true, 'notblank' => true)); + } +} diff --git a/tests/models/PolicyN.php b/tests/models/PolicyN.php index a14bdb38a..6e4387f6f 100644 --- a/tests/models/PolicyN.php +++ b/tests/models/PolicyN.php @@ -1,16 +1,17 @@ setTableName('policies'); - $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('rate_id', 'integer', 4, array ( )); - $this->hasColumn('policy_number', 'integer', 4, array ( 'unique' => true, )); - } - - public function setUp() - { - $this->hasOne('RateN', array('local' => 'rate_id', 'foreign' => 'id' )); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('policies'); + $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('rate_id', 'integer', 4, array()); + $this->hasColumn('policy_number', 'integer', 4, array('unique' => true)); + } + + public function setUp() + { + $this->hasOne('RateN', array('local' => 'rate_id', 'foreign' => 'id')); + } +} diff --git a/tests/models/QueryTest_Board.php b/tests/models/QueryTest_Board.php index 339da86d4..f9950495d 100644 --- a/tests/models/QueryTest_Board.php +++ b/tests/models/QueryTest_Board.php @@ -1,4 +1,5 @@ hasColumn('id', 'integer', 4, array('primary', 'autoincrement', 'notnull')); $this->hasColumn('categoryId as categoryId', 'integer', 4, - array('notnull')); + array('notnull')); $this->hasColumn('name as name', 'string', 100, - array('notnull', 'unique')); + array('notnull', 'unique')); $this->hasColumn('lastEntryId as lastEntryId', 'integer', 4, - array('default' => 0)); + array('default' => 0)); $this->hasColumn('position as position', 'integer', 4, - array('default' => 0, 'notnull')); + array('default' => 0, 'notnull')); } /** @@ -23,10 +24,10 @@ public function setTableDefinition() public function setUp() { $this->hasOne('QueryTest_Category as category', array( - 'local' => 'categoryId', 'foreign' => 'id' + 'local' => 'categoryId', 'foreign' => 'id', )); $this->hasOne('QueryTest_Entry as lastEntry', array( - 'local' => 'lastEntryId', 'foreign' => 'id', 'onDelete' => 'CASCADE' + 'local' => 'lastEntryId', 'foreign' => 'id', 'onDelete' => 'CASCADE', )); } } diff --git a/tests/models/QueryTest_Category.php b/tests/models/QueryTest_Category.php index d271224f0..dab867f1e 100644 --- a/tests/models/QueryTest_Category.php +++ b/tests/models/QueryTest_Category.php @@ -1,11 +1,12 @@ hasColumn('id', 'integer', 4, array('primary', 'autoincrement', 'notnull')); $this->hasColumn('rootCategoryId as rootCategoryId', 'integer', 4, - array('notnull', 'default' => 0)); + array('notnull', 'default' => 0)); $this->hasColumn('parentCategoryId as parentCategoryId', 'integer', 4, - array('notnull', 'default' => 0)); + array('notnull', 'default' => 0)); $this->hasColumn('name as name', 'string', 50, - array('notnull', 'unique')); + array('notnull', 'unique')); $this->hasColumn('position as position', 'integer', 4, - array('default' => 0, 'notnull')); + array('default' => 0, 'notnull')); } /** @@ -31,13 +32,13 @@ public function setTableDefinition() public function setUp() { $this->hasMany('QueryTest_Category as subCategories', array( - 'local' => 'id', 'foreign' => 'parentCategoryId' + 'local' => 'id', 'foreign' => 'parentCategoryId', )); $this->hasOne('QueryTest_Category as rootCategory', array( - 'local' => 'rootCategoryId', 'foreign' => 'id' + 'local' => 'rootCategoryId', 'foreign' => 'id', )); $this->hasMany('QueryTest_Board as boards', array( - 'local' => 'id', 'foreign' => 'categoryId', 'onDelete' => 'CASCADE' + 'local' => 'id', 'foreign' => 'categoryId', 'onDelete' => 'CASCADE', )); } } diff --git a/tests/models/QueryTest_Entry.php b/tests/models/QueryTest_Entry.php index ef61cad93..7db94e81d 100644 --- a/tests/models/QueryTest_Entry.php +++ b/tests/models/QueryTest_Entry.php @@ -1,16 +1,17 @@ hasColumn('id', 'integer', 4, array('primary', 'autoincrement', 'notnull')); $this->hasColumn('authorId', 'integer', 4, - array('notnull')); + array('notnull')); $this->hasColumn('date', 'integer', 4, - array('notnull')); + array('notnull')); } /** @@ -19,7 +20,7 @@ public function setTableDefinition() public function setUp() { $this->hasOne('QueryTest_User as author', array( - 'local' => 'authorId', 'foreign' => 'id' + 'local' => 'authorId', 'foreign' => 'id', )); } } diff --git a/tests/models/QueryTest_Item.php b/tests/models/QueryTest_Item.php index 797f4c04f..e5fd2a41f 100644 --- a/tests/models/QueryTest_Item.php +++ b/tests/models/QueryTest_Item.php @@ -1,4 +1,5 @@ hasColumn('quantity', 'integer'); } } - diff --git a/tests/models/QueryTest_Rank.php b/tests/models/QueryTest_Rank.php index dd74b9844..eafbfeb5c 100644 --- a/tests/models/QueryTest_Rank.php +++ b/tests/models/QueryTest_Rank.php @@ -1,23 +1,24 @@ hasColumn('title as title', 'string', 100, - array('notnull')); + array('notnull')); $this->hasColumn('color as color', 'string', 20, - array('notnull', 'regexp' => '/^[a-zA-Z\-]{3,}|#[0-9a-fA-F]{6}$/D')); + array('notnull', 'regexp' => '/^[a-zA-Z\-]{3,}|#[0-9a-fA-F]{6}$/D')); $this->hasColumn('icon as icon', 'string', 50, - array('notnull', 'default' => ' ', 'regexp' => '/^[a-zA-Z0-9_\-]+\.(jpg|gif|png)$/D')); + array('notnull', 'default' => ' ', 'regexp' => '/^[a-zA-Z0-9_\-]+\.(jpg|gif|png)$/D')); } public function setUp() { $this->hasMany('QueryTest_User as users', array( - 'local' => 'rankId', 'foreign' => 'userId', 'refClass' => 'QueryTest_UserRank' + 'local' => 'rankId', 'foreign' => 'userId', 'refClass' => 'QueryTest_UserRank', )); } } diff --git a/tests/models/QueryTest_Subscription.php b/tests/models/QueryTest_Subscription.php index 8f4b2058a..f65896d30 100644 --- a/tests/models/QueryTest_Subscription.php +++ b/tests/models/QueryTest_Subscription.php @@ -1,8 +1,10 @@ hasColumn('id', 'integer', 4, array('primary', 'autoincrement', 'notnull')); + { + $this->hasColumn('id', 'integer', 4, array('primary', 'autoincrement', 'notnull')); $this->hasColumn('begin', 'date'); $this->hasColumn('end', 'date'); } diff --git a/tests/models/QueryTest_User.php b/tests/models/QueryTest_User.php index 7ae19eca6..63c38cc31 100644 --- a/tests/models/QueryTest_User.php +++ b/tests/models/QueryTest_User.php @@ -1,11 +1,11 @@ hasColumn('username as username', 'string', 50, - array('notnull')); + array('notnull')); $this->hasColumn('visibleRankId', 'integer', 4); $this->hasColumn('subscriptionId', 'integer', 4); } @@ -16,15 +16,15 @@ public function setTableDefinition() public function setUp() { $this->hasOne('QueryTest_Rank as visibleRank', array( - 'local' => 'visibleRankId', 'foreign' => 'id' + 'local' => 'visibleRankId', 'foreign' => 'id', )); - + $this->hasOne('QueryTest_Subscription', array( - 'local' => 'subscriptionId', 'foreign' => 'id' + 'local' => 'subscriptionId', 'foreign' => 'id', )); $this->hasMany('QueryTest_Rank as ranks', array( - 'local' => 'userId', 'foreign' => 'rankId', 'refClass' => 'QueryTest_UserRank' + 'local' => 'userId', 'foreign' => 'rankId', 'refClass' => 'QueryTest_UserRank', )); } } diff --git a/tests/models/QueryTest_UserRank.php b/tests/models/QueryTest_UserRank.php index 3711aff57..c907c4e69 100644 --- a/tests/models/QueryTest_UserRank.php +++ b/tests/models/QueryTest_UserRank.php @@ -1,8 +1,9 @@ hasColumn('rankId', 'integer', 4, array('primary' => true)); $this->hasColumn('userId', 'integer', 4, array('primary' => true)); } diff --git a/tests/models/RTC1.php b/tests/models/RTC1.php index 2c43dd7d4..3f3bd19b1 100644 --- a/tests/models/RTC1.php +++ b/tests/models/RTC1.php @@ -1,10 +1,14 @@ hasColumn('name', 'string', 200); } - public function setUp() { + + public function setUp() + { $this->hasMany('M2MTest as RTC1', array('local' => 'c1_id', 'foreign' => 'c2_id', 'refClass' => 'JC1')); } } - diff --git a/tests/models/RTC2.php b/tests/models/RTC2.php index c36ca5c67..1430c9077 100644 --- a/tests/models/RTC2.php +++ b/tests/models/RTC2.php @@ -1,10 +1,14 @@ hasColumn('name', 'string', 200); } - public function setUp() { + + public function setUp() + { $this->hasMany('M2MTest as RTC2', array('local' => 'c1_id', 'foreign' => 'c2_id', 'refClass' => 'JC1')); } } - diff --git a/tests/models/RTC3.php b/tests/models/RTC3.php index ca674122d..62458eeb8 100644 --- a/tests/models/RTC3.php +++ b/tests/models/RTC3.php @@ -1,11 +1,15 @@ hasColumn('name', 'string', 200); } - public function setUp() { + + public function setUp() + { $this->hasMany('M2MTest as RTC3', array('local' => 'c1_id', 'foreign' => 'c2_id', 'refClass' => 'JC2')); $this->hasMany('M2MTest as RTC4', array('local' => 'c1_id', 'foreign' => 'c2_id', 'refClass' => 'JC1')); } } - diff --git a/tests/models/RTC4.php b/tests/models/RTC4.php index 51df7ae7c..ac442e9f6 100644 --- a/tests/models/RTC4.php +++ b/tests/models/RTC4.php @@ -1,10 +1,15 @@ hasColumn('oid', 'integer', 11, array('autoincrement', 'primary')); + +class RTC4 extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('oid', 'integer', 11, array('autoincrement', 'primary')); $this->hasColumn('name', 'string', 20); } - public function setUp() { + + public function setUp() + { $this->hasMany('M2MTest2', array('local' => 'c1_id', 'foreign' => 'c2_id', 'refClass' => 'JC3')); } } diff --git a/tests/models/RateN.php b/tests/models/RateN.php index abe7b0956..6cbc1a9cf 100644 --- a/tests/models/RateN.php +++ b/tests/models/RateN.php @@ -1,20 +1,21 @@ setTableName('rates'); - $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); - $this->hasColumn('policy_code', 'integer', 4, array ( 'notnull' => true, 'notblank' => true,)); - $this->hasColumn('coverage_code', 'integer', 4, array ( 'notnull' => true, 'notblank' => true,)); - $this->hasColumn('liability_code', 'integer', 4, array ( 'notnull' => true, 'notblank' => true,)); - $this->hasColumn('total_rate', 'float', null, array ( 'notnull' => true, 'notblank' => true,)); - } - - public function setUp() - { - $this->hasOne('PolicyCodeN', array('local' => 'policy_code', 'foreign' => 'code' )); - $this->hasOne('CoverageCodeN', array('local' => 'coverage_code', 'foreign' => 'code' )); - $this->hasOne('LiabilityCodeN', array('local' => 'liability_code', 'foreign' => 'code' )); - } -} \ No newline at end of file + public function setTableDefinition() + { + $this->setTableName('rates'); + $this->hasColumn('id', 'integer', 4, array('notnull' => true, 'primary' => true, 'autoincrement' => true)); + $this->hasColumn('policy_code', 'integer', 4, array('notnull' => true, 'notblank' => true)); + $this->hasColumn('coverage_code', 'integer', 4, array('notnull' => true, 'notblank' => true)); + $this->hasColumn('liability_code', 'integer', 4, array('notnull' => true, 'notblank' => true)); + $this->hasColumn('total_rate', 'float', null, array('notnull' => true, 'notblank' => true)); + } + + public function setUp() + { + $this->hasOne('PolicyCodeN', array('local' => 'policy_code', 'foreign' => 'code')); + $this->hasOne('CoverageCodeN', array('local' => 'coverage_code', 'foreign' => 'code')); + $this->hasOne('LiabilityCodeN', array('local' => 'liability_code', 'foreign' => 'code')); + } +} diff --git a/tests/models/Rec1.php b/tests/models/Rec1.php index 29c653b75..b2ba27f4f 100644 --- a/tests/models/Rec1.php +++ b/tests/models/Rec1.php @@ -1,9 +1,10 @@ hasColumn('first_name', 'string', 128, array ()); + $this->hasColumn('first_name', 'string', 128, array()); } public function setUp() @@ -11,5 +12,3 @@ public function setUp() $this->hasOne('Rec2 as Account', array('local' => 'id', 'foreign' => 'user_id', 'onDelete' => 'CASCADE')); } } - - diff --git a/tests/models/Rec2.php b/tests/models/Rec2.php index 317a18ed0..2fc5b8559 100644 --- a/tests/models/Rec2.php +++ b/tests/models/Rec2.php @@ -1,15 +1,15 @@ hasColumn('user_id', 'integer', 10, array ( 'unique' => true,)); - $this->hasColumn('address', 'string', 150, array ()); + $this->hasColumn('user_id', 'integer', 10, array('unique' => true)); + $this->hasColumn('address', 'string', 150, array()); } public function setUp() { $this->hasOne('Rec1 as User', array('local' => 'id', 'foreign' => 'user_id', 'onDelete' => 'CASCADE')); } - } diff --git a/tests/models/RecordFilterTest.php b/tests/models/RecordFilterTest.php index 521448d34..9d31c3c7b 100644 --- a/tests/models/RecordFilterTest.php +++ b/tests/models/RecordFilterTest.php @@ -1,16 +1,25 @@ hasColumn("name", "string", 200); - $this->hasColumn("password", "string", 32); + $this->hasColumn('name', 'string', 200); + $this->hasColumn('password', 'string', 32); } - public function setPassword($password) { + + public function setPassword($password) + { return md5($password); } - public function getName($name) { + + public function getName($name) + { return strtoupper($name); } } diff --git a/tests/models/RecordHookTest.php b/tests/models/RecordHookTest.php index b725cb1a4..e021ea84e 100644 --- a/tests/models/RecordHookTest.php +++ b/tests/models/RecordHookTest.php @@ -1,4 +1,10 @@ hasColumn('name', 'string', null, array('primary' => true)); } + public function preSave($event) { $this->_messages[] = __FUNCTION__; } + public function postSave($event) { $this->_messages[] = __FUNCTION__; } + public function preInsert($event) { $this->_messages[] = __FUNCTION__; } + public function postInsert($event) { $this->_messages[] = __FUNCTION__; } + public function preUpdate($event) { $this->_messages[] = __FUNCTION__; } + public function postUpdate($event) { $this->_messages[] = __FUNCTION__; } + public function preDelete($event) { $this->_messages[] = __FUNCTION__; } + public function postDelete($event) { $this->_messages[] = __FUNCTION__; } + public function pop() { return array_pop($this->_messages); diff --git a/tests/models/Record_City.php b/tests/models/Record_City.php index 41ec82d5c..268cc7c6e 100644 --- a/tests/models/Record_City.php +++ b/tests/models/Record_City.php @@ -1,18 +1,22 @@ hasColumn('name', 'string', 200); $this->hasColumn('country_id', 'integer'); $this->hasColumn('district_id', 'integer'); } - - public function setUp() { + + public function setUp() + { $this->hasOne('Record_Country as Country', array( - 'local' => 'country_id', 'foreign' => 'id' + 'local' => 'country_id', 'foreign' => 'id', )); $this->hasOne('Record_District as District', array( - 'local' => 'district_id', 'foreign' => 'id' + 'local' => 'district_id', 'foreign' => 'id', )); } } diff --git a/tests/models/Record_Country.php b/tests/models/Record_Country.php index 256468c82..e01e075eb 100644 --- a/tests/models/Record_Country.php +++ b/tests/models/Record_Country.php @@ -1,14 +1,17 @@ hasColumn('name', 'string', 200); } - public function setUp() { + + public function setUp() + { $this->hasMany('Record_City as City', array( 'local' => 'id', - 'foreign' => 'country_id' + 'foreign' => 'country_id', )); } } - - diff --git a/tests/models/Record_District.php b/tests/models/Record_District.php index a56ccf8b3..221ce5057 100644 --- a/tests/models/Record_District.php +++ b/tests/models/Record_District.php @@ -1,6 +1,9 @@ hasColumn('name', 'string', 200); - } + } } diff --git a/tests/models/RelationTest.php b/tests/models/RelationTest.php index 2932d7ca0..d85c41cec 100644 --- a/tests/models/RelationTest.php +++ b/tests/models/RelationTest.php @@ -1,16 +1,27 @@ hasColumn('name', 'string', 200); $this->hasColumn('parent_id', 'integer'); } } -class RelationTestChild extends RelationTest +/** + * @internal + * + * @coversNothing + */ +class RelationTestChild extends RelationTest { - public function setUp() + public function setUp() { $this->hasOne('RelationTest as Parent', array( 'local' => 'parent_id', diff --git a/tests/models/Resource.php b/tests/models/Resource.php index fca10fa73..b28c7d212 100644 --- a/tests/models/Resource.php +++ b/tests/models/Resource.php @@ -1,14 +1,19 @@ hasMany('Task as TaskAlias', array('local' => 'resource_id', - 'foreign' => 'task_id', - 'refClass' => 'Assignment')); - $this->hasMany('ResourceType as Type', array('local' => 'resource_id', - 'foreign' => 'type_id', - 'refClass' => 'ResourceReference')); - } - public function setTableDefinition() { - $this->hasColumn('name', 'string',100); - } + +class Resource extends Doctrine_Record +{ + public function setUp() + { + $this->hasMany('Task as TaskAlias', array('local' => 'resource_id', + 'foreign' => 'task_id', + 'refClass' => 'Assignment')); + $this->hasMany('ResourceType as Type', array('local' => 'resource_id', + 'foreign' => 'type_id', + 'refClass' => 'ResourceReference')); + } + + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 100); + } } diff --git a/tests/models/ResourceReference.php b/tests/models/ResourceReference.php index aec7795b2..f9a0a7897 100644 --- a/tests/models/ResourceReference.php +++ b/tests/models/ResourceReference.php @@ -1,8 +1,10 @@ hasColumn('type_id', 'integer'); - $this->hasColumn('resource_id', 'integer'); + +class ResourceReference extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('type_id', 'integer'); + $this->hasColumn('resource_id', 'integer'); } } - diff --git a/tests/models/ResourceType.php b/tests/models/ResourceType.php index 5b24e3b8c..89fe2fd01 100644 --- a/tests/models/ResourceType.php +++ b/tests/models/ResourceType.php @@ -1,12 +1,16 @@ hasMany('Resource as ResourceAlias', array('local' => 'type_id', - 'foreign' => 'resource_id', - 'refClass' => 'ResourceReference')); + +class ResourceType extends Doctrine_Record +{ + public function setUp() + { + $this->hasMany('Resource as ResourceAlias', array('local' => 'type_id', + 'foreign' => 'resource_id', + 'refClass' => 'ResourceReference')); } - public function setTableDefinition() { - $this->hasColumn('type', 'string',100); + + public function setTableDefinition() + { + $this->hasColumn('type', 'string', 100); } } - diff --git a/tests/models/Role.php b/tests/models/Role.php index 44e46e9a6..660b5c288 100644 --- a/tests/models/Role.php +++ b/tests/models/Role.php @@ -1,13 +1,14 @@ hasColumn('name', 'string', 20, array('unique' => true)); } - public function setUp() + + public function setUp() { $this->hasMany('Auth', array('local' => 'id', 'foreign' => 'roleid')); } } - diff --git a/tests/models/SearchTest.php b/tests/models/SearchTest.php index 132c5765e..d8e904ca8 100644 --- a/tests/models/SearchTest.php +++ b/tests/models/SearchTest.php @@ -1,4 +1,10 @@ hasColumn('title', 'string', 100); $this->hasColumn('content', 'string'); } + public function setUp() { - $options = array('generateFiles' => false, - 'fields' => array('title', 'content')); + $options = array('generateFiles' => false, + 'fields' => array('title', 'content')); $this->actAs('Searchable', $options); } diff --git a/tests/models/SelfRefTest.php b/tests/models/SelfRefTest.php index fdf9dd3e1..2c795c8d6 100644 --- a/tests/models/SelfRefTest.php +++ b/tests/models/SelfRefTest.php @@ -1,14 +1,20 @@ hasColumn('name', 'string', 50); $this->hasColumn('created_by', 'integer'); } + public function setUp() { $this->hasOne('SelfRefTest as createdBy', array('local' => 'created_by')); } } - diff --git a/tests/models/SequenceRecord.php b/tests/models/SequenceRecord.php index 673f133bb..54df35b7e 100644 --- a/tests/models/SequenceRecord.php +++ b/tests/models/SequenceRecord.php @@ -1,5 +1,7 @@ hasColumn('id', 'integer', null, array('primary', 'sequence')); diff --git a/tests/models/SerializeTest.php b/tests/models/SerializeTest.php index cc16ec4c1..67e0824cb 100644 --- a/tests/models/SerializeTest.php +++ b/tests/models/SerializeTest.php @@ -1,10 +1,16 @@ setTableName('serialize_test'); - + $this->hasColumn('booltest', 'boolean'); $this->hasColumn('integertest', 'integer', 4, array('unsigned' => true)); $this->hasColumn('floattest', 'float'); @@ -16,16 +22,15 @@ public function setTableDefinition() $this->hasColumn('timestamptest', 'timestamp'); $this->hasColumn('timetest', 'time'); $this->hasColumn('datetest', 'date'); - $this->hasColumn('enumtest', 'enum', 4, - array( - 'values' => array( - 'php', - 'java', - 'python' - ) - ) + $this->hasColumn('enumtest', 'enum', 4, + array( + 'values' => array( + 'php', + 'java', + 'python', + ), + ) ); $this->hasColumn('gziptest', 'gzip'); } - } diff --git a/tests/models/SoftDeleteBCTest.php b/tests/models/SoftDeleteBCTest.php index 68137e8de..ca242906c 100644 --- a/tests/models/SoftDeleteBCTest.php +++ b/tests/models/SoftDeleteBCTest.php @@ -1,10 +1,16 @@ setTableName('soft_delete_bc_test'); - + $this->hasColumn('name', 'string', null, array('primary' => true)); $this->hasColumn('something', 'string', '25', array('notnull' => true, 'unique' => true)); } @@ -13,4 +19,4 @@ public function setUp() { $this->actAs('SoftDelete', array('name' => 'deleted', 'type' => 'boolean')); } -} \ No newline at end of file +} diff --git a/tests/models/SoftDeleteTest.php b/tests/models/SoftDeleteTest.php index 21e432fd0..d97ce33c5 100644 --- a/tests/models/SoftDeleteTest.php +++ b/tests/models/SoftDeleteTest.php @@ -1,4 +1,10 @@ actAs('SoftDelete'); } -} \ No newline at end of file +} diff --git a/tests/models/Song.php b/tests/models/Song.php index b9df96689..88f1ba9fe 100644 --- a/tests/models/Song.php +++ b/tests/models/Song.php @@ -1,16 +1,18 @@ hasOne('Album', array('local' => 'album_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE')); + 'foreign' => 'id', + 'onDelete' => 'CASCADE')); } + public function setTableDefinition() { $this->hasColumn('album_id', 'integer'); - $this->hasColumn('genre', 'string',20); - $this->hasColumn('title', 'string',30); + $this->hasColumn('genre', 'string', 20); + $this->hasColumn('title', 'string', 30); } } diff --git a/tests/models/SymfonyRecord.php b/tests/models/SymfonyRecord.php index 782f023d3..83e467c7f 100644 --- a/tests/models/SymfonyRecord.php +++ b/tests/models/SymfonyRecord.php @@ -1,9 +1,9 @@ hasMany('Photo', array( 'local' => 'tag_id', 'foreign' => 'photo_id', - 'refClass' => 'Phototag' + 'refClass' => 'Phototag', )); } - public function setTableDefinition() { + + public function setTableDefinition() + { $this->hasColumn('tag', 'string', 100); } } diff --git a/tests/models/Task.php b/tests/models/Task.php index 3874d4775..61ea332eb 100644 --- a/tests/models/Task.php +++ b/tests/models/Task.php @@ -1,13 +1,18 @@ hasMany('Resource as ResourceAlias', array('local' => 'task_id', - 'foreign' => 'resource_id', - 'refClass' => 'Assignment')); - $this->hasMany('Task as Subtask', array('local' => 'id', 'foreign' => 'parent_id')); - } - public function setTableDefinition() { - $this->hasColumn('name', 'string',100); - $this->hasColumn('parent_id', 'integer'); - } -} + +class Task extends Doctrine_Record +{ + public function setUp() + { + $this->hasMany('Resource as ResourceAlias', array('local' => 'task_id', + 'foreign' => 'resource_id', + 'refClass' => 'Assignment')); + $this->hasMany('Task as Subtask', array('local' => 'id', 'foreign' => 'parent_id')); + } + + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 100); + $this->hasColumn('parent_id', 'integer'); + } +} diff --git a/tests/models/TestError.php b/tests/models/TestError.php index 2cf523d53..264432cec 100644 --- a/tests/models/TestError.php +++ b/tests/models/TestError.php @@ -1,13 +1,17 @@ hasMany('Description', array('local' => 'file_md5', - 'foreign' => 'file_md5')); + +class TestError extends Doctrine_Record +{ + public function setUp() + { + $this->hasMany('Description', array('local' => 'file_md5', + 'foreign' => 'file_md5')); } - public function setTableDefinition() { - $this->hasColumn('message', 'string',200); - $this->hasColumn('code', 'integer',11); - $this->hasColumn('file_md5', 'string',32, 'primary'); + + public function setTableDefinition() + { + $this->hasColumn('message', 'string', 200); + $this->hasColumn('code', 'integer', 11); + $this->hasColumn('file_md5', 'string', 32, 'primary'); } } - diff --git a/tests/models/TestMovie.php b/tests/models/TestMovie.php index 482c6c542..69e586d89 100644 --- a/tests/models/TestMovie.php +++ b/tests/models/TestMovie.php @@ -1,27 +1,27 @@ hasOne('TestUser as User', - array('local' => 'user_id', - 'foreign' => 'id')); + $this->hasOne('TestUser as User', + array('local' => 'user_id', + 'foreign' => 'id')); - $this->hasMany('TestUser as MovieBookmarks', - array('local' => 'movie_id', - 'foreign' => 'user_id', - 'refClass' => 'TestMovieUserBookmark')); + $this->hasMany('TestUser as MovieBookmarks', + array('local' => 'movie_id', + 'foreign' => 'user_id', + 'refClass' => 'TestMovieUserBookmark')); - $this->hasMany('TestUser as MovieVotes', - array('local' => 'movie_id', - 'foreign' => 'user_id', - 'refClass' => 'TestMovieUserVote')); + $this->hasMany('TestUser as MovieVotes', + array('local' => 'movie_id', + 'foreign' => 'user_id', + 'refClass' => 'TestMovieUserVote')); } - public function setTableDefinition() + public function setTableDefinition() { - $this->hasColumn('user_id', 'integer', null); + $this->hasColumn('user_id', 'integer', null); $this->hasColumn('name', 'string', 30); } } diff --git a/tests/models/TestMovieUserBookmark.php b/tests/models/TestMovieUserBookmark.php index 3d84a036b..f72cd9f4f 100644 --- a/tests/models/TestMovieUserBookmark.php +++ b/tests/models/TestMovieUserBookmark.php @@ -1,10 +1,10 @@ hasColumn('user_id', 'integer', null, array('primary' => true)); $this->hasColumn('movie_id', 'integer', null, array('primary' => true)); } } - diff --git a/tests/models/TestMovieUserVote.php b/tests/models/TestMovieUserVote.php index 244f1f54a..7ad233a3b 100644 --- a/tests/models/TestMovieUserVote.php +++ b/tests/models/TestMovieUserVote.php @@ -1,7 +1,9 @@ hasColumn('vote', 'string', 30); $this->hasColumn('user_id', 'integer', null, array('primary' => true)); $this->hasColumn('movie_id', 'integer', null, array('primary' => true)); diff --git a/tests/models/TestRecord.php b/tests/models/TestRecord.php index 9e1e445e5..0219bbdad 100644 --- a/tests/models/TestRecord.php +++ b/tests/models/TestRecord.php @@ -1,5 +1,6 @@ hasMany('TestMovie as UserBookmarks', - array('local' => 'user_id', - 'foreign' => 'movie_id', - 'refClass' => 'TestMovieUserBookmark')); - - $this->hasMany('TestMovie as UserVotes', - array('local' => 'user_id', - 'foreign' => 'movie_id', - 'refClass' => 'TestMovieUserVote')); + $this->hasMany('TestMovie as UserBookmarks', + array('local' => 'user_id', + 'foreign' => 'movie_id', + 'refClass' => 'TestMovieUserBookmark')); + $this->hasMany('TestMovie as UserVotes', + array('local' => 'user_id', + 'foreign' => 'movie_id', + 'refClass' => 'TestMovieUserVote')); } - public function setTableDefinition() + + public function setTableDefinition() { $this->hasColumn('name', 'string', 30); } diff --git a/tests/models/TreeLeaf.php b/tests/models/TreeLeaf.php index 0c7c0f5a5..3781ffdb6 100644 --- a/tests/models/TreeLeaf.php +++ b/tests/models/TreeLeaf.php @@ -1,20 +1,21 @@ hasColumn('name', 'string'); + $this->hasColumn('name', 'string'); $this->hasColumn('parent_id', 'integer'); } - public function setUp() + public function setUp() { $this->hasOne('TreeLeaf as Parent', array( - 'local' => 'parent_id', 'foreign' => 'id' + 'local' => 'parent_id', 'foreign' => 'id', )); - + $this->hasMany('TreeLeaf as Children', array( - 'local' => 'id', 'foreign' => 'parent_id' + 'local' => 'id', 'foreign' => 'parent_id', )); } } diff --git a/tests/models/UnderscoreColumn.php b/tests/models/UnderscoreColumn.php index 93c647452..70b95956c 100644 --- a/tests/models/UnderscoreColumn.php +++ b/tests/models/UnderscoreColumn.php @@ -1,4 +1,5 @@ setTableName('_test_'); $this->hasColumn('_underscore_', 'string', 255); } -} \ No newline at end of file +} diff --git a/tests/models/User.php b/tests/models/User.php index 9cd73295b..58a1ac6d4 100644 --- a/tests/models/User.php +++ b/tests/models/User.php @@ -1,54 +1,57 @@ Doctrine_Connection // won't initialize grouptable when Doctrine_Connection->getTable('User') is called -class UserTable extends Doctrine_Table { } +class UserTable extends Doctrine_Table +{ +} class User extends Entity { - public function setUp() + public function setUp() { parent::setUp(); $this->hasMany('Address', array( - 'local' => 'user_id', + 'local' => 'user_id', 'foreign' => 'address_id', 'refClass' => 'EntityAddress', )); $this->hasMany('Address as Addresses', array( - 'local' => 'user_id', + 'local' => 'user_id', 'foreign' => 'address_id', 'refClass' => 'EntityAddress', )); $this->hasMany('Album', array('local' => 'id', 'foreign' => 'user_id')); $this->hasMany('Book', array('local' => 'id', 'foreign' => 'user_id')); $this->hasMany('Group', array( - 'local' => 'user_id', + 'local' => 'user_id', 'foreign' => 'group_id', 'refClass' => 'Groupuser', )); } /** Custom validation */ - public function validate() + public function validate() { // Allow only one name! - if ($this->name !== 'The Saint') { + if ('The Saint' !== $this->name) { $this->errorStack()->add('name', 'notTheSaint'); } } - public function validateOnInsert() + + public function validateOnInsert() { - if ($this->password !== 'Top Secret') { + if ('Top Secret' !== $this->password) { $this->errorStack()->add('password', 'pwNotTopSecret'); } } - public function validateOnUpdate() + + public function validateOnUpdate() { - if ($this->loginname !== 'Nobody') { + if ('Nobody' !== $this->loginname) { $this->errorStack()->add('loginname', 'notNobody'); } } } - diff --git a/tests/models/ValidatorTest.php b/tests/models/ValidatorTest.php index 052d6bc51..b049d9867 100644 --- a/tests/models/ValidatorTest.php +++ b/tests/models/ValidatorTest.php @@ -1,12 +1,20 @@ hasColumn('mymixed', 'string', 100); $this->hasColumn('mystring', 'string', 100, array('notnull', 'unique')); $this->hasColumn('myarray', 'array', 1000); $this->hasColumn('myobject', 'object', 1000); $this->hasColumn('myinteger', 'integer', 11); - $this->hasColumn('myrange', 'integer', 11, array('range' => array(4,123))); + $this->hasColumn('myrange', 'integer', 11, array('range' => array(4, 123))); $this->hasColumn('myregexp', 'string', 5, array('regexp' => '/^[0-9]+$/')); $this->hasColumn('myemail', 'string', 100, array('email')); diff --git a/tests/models/ValidatorTest_AddressModel.php b/tests/models/ValidatorTest_AddressModel.php index bbaab3147..11fbfa735 100644 --- a/tests/models/ValidatorTest_AddressModel.php +++ b/tests/models/ValidatorTest_AddressModel.php @@ -1,18 +1,21 @@ hasColumn("id", "integer", 11, array('autoincrement' => true, - 'primary' => true - )); - $this->hasColumn('address1', 'string', 255, array('notnull' => true, 'notblank')); - $this->hasColumn('address2', 'string', 255, array('notnull' => true)); - $this->hasColumn('city', 'string', 255, array('notnull' => true, 'notblank')); - $this->hasColumn('state', 'string', 10, array('notnull' => true, 'notblank', 'usstate')); - $this->hasColumn('zip', 'string', 15, array('notnull' => true, 'notblank', 'regexp' => '/^[0-9-]*$/')); - } +class ValidatorTest_AddressModel extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 11, array('autoincrement' => true, + 'primary' => true, + )); + $this->hasColumn('address1', 'string', 255, array('notnull' => true, 'notblank')); + $this->hasColumn('address2', 'string', 255, array('notnull' => true)); + $this->hasColumn('city', 'string', 255, array('notnull' => true, 'notblank')); + $this->hasColumn('state', 'string', 10, array('notnull' => true, 'notblank', 'usstate')); + $this->hasColumn('zip', 'string', 15, array('notnull' => true, 'notblank', 'regexp' => '/^[0-9-]*$/')); + } - public function setUp() { - $this->hasMany('ValidatorTest_ClientModel', array('local' => 'address_id', 'foreign' => 'client_id', 'refClass' => 'ValidatorTest_ClientToAddressModel')); - } + public function setUp() + { + $this->hasMany('ValidatorTest_ClientModel', array('local' => 'address_id', 'foreign' => 'client_id', 'refClass' => 'ValidatorTest_ClientToAddressModel')); + } } diff --git a/tests/models/ValidatorTest_ClientModel.php b/tests/models/ValidatorTest_ClientModel.php index e0e12d716..6f7e4542e 100644 --- a/tests/models/ValidatorTest_ClientModel.php +++ b/tests/models/ValidatorTest_ClientModel.php @@ -1,15 +1,18 @@ hasColumn('id', 'integer', 4, array('notnull' => true, - 'primary' => true, - 'autoincrement' => true, - 'unsigned' => true)); - $this->hasColumn('short_name', 'string', 32, array('notnull' => true, 'notblank', 'unique' => true)); - } +class ValidatorTest_ClientModel extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('id', 'integer', 4, array('notnull' => true, + 'primary' => true, + 'autoincrement' => true, + 'unsigned' => true)); + $this->hasColumn('short_name', 'string', 32, array('notnull' => true, 'notblank', 'unique' => true)); + } - public function setUp() { - $this->hasMany("ValidatorTest_AddressModel", array('local' => 'client_id', 'foreign' => 'address_id', 'refClass' => 'ValidatorTest_ClientToAddressModel')); - } + public function setUp() + { + $this->hasMany('ValidatorTest_AddressModel', array('local' => 'client_id', 'foreign' => 'address_id', 'refClass' => 'ValidatorTest_ClientToAddressModel')); + } } diff --git a/tests/models/ValidatorTest_ClientToAddressModel.php b/tests/models/ValidatorTest_ClientToAddressModel.php index 249260f12..39d2e7195 100644 --- a/tests/models/ValidatorTest_ClientToAddressModel.php +++ b/tests/models/ValidatorTest_ClientToAddressModel.php @@ -1,19 +1,18 @@ hasColumn("client_id", "integer", 11, array('primary' => true)); - $this->hasColumn("address_id", "integer", 11, array('primary' => true)); - } - - public function construct() - { - - } + public function setTableDefinition() + { + $this->hasColumn('client_id', 'integer', 11, array('primary' => true)); + $this->hasColumn('address_id', 'integer', 11, array('primary' => true)); + } - public function setUp() - { + public function construct() + { + } - } -} \ No newline at end of file + public function setUp() + { + } +} diff --git a/tests/models/ValidatorTest_DateModel.php b/tests/models/ValidatorTest_DateModel.php index 0aaf1d5eb..b5f182936 100644 --- a/tests/models/ValidatorTest_DateModel.php +++ b/tests/models/ValidatorTest_DateModel.php @@ -1,6 +1,9 @@ hasColumn('birthday', 'date', null, array('past')); $this->hasColumn('death', 'date', null, array('future')); } diff --git a/tests/models/ValidatorTest_FootballPlayer.php b/tests/models/ValidatorTest_FootballPlayer.php index e5a1693d7..cb14bd8ce 100644 --- a/tests/models/ValidatorTest_FootballPlayer.php +++ b/tests/models/ValidatorTest_FootballPlayer.php @@ -1,8 +1,11 @@ hasColumn('person_id', 'string', 255); - $this->hasColumn('team_name', 'string', 255); - $this->hasColumn('goals_count', 'integer', 4); - } + +class ValidatorTest_FootballPlayer extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('person_id', 'string', 255); + $this->hasColumn('team_name', 'string', 255); + $this->hasColumn('goals_count', 'integer', 4); + } } diff --git a/tests/models/ValidatorTest_Person.php b/tests/models/ValidatorTest_Person.php index 4e109bcb0..4fc2f9563 100644 --- a/tests/models/ValidatorTest_Person.php +++ b/tests/models/ValidatorTest_Person.php @@ -1,13 +1,17 @@ hasColumn('identifier', 'integer', 4, array('notblank', 'unique')); - $this->hasColumn('is_football_player', 'boolean'); - } - - public function setUp() { - $this->hasOne('ValidatorTest_FootballPlayer', array( - 'local' => 'id', 'foreign' => 'person_id', 'onDelete' => 'CASCADE' - )); - } + +class ValidatorTest_Person extends Doctrine_Record +{ + public function setTableDefinition() + { + $this->hasColumn('identifier', 'integer', 4, array('notblank', 'unique')); + $this->hasColumn('is_football_player', 'boolean'); + } + + public function setUp() + { + $this->hasOne('ValidatorTest_FootballPlayer', array( + 'local' => 'id', 'foreign' => 'person_id', 'onDelete' => 'CASCADE', + )); + } } diff --git a/tests/models/VersioningTest.php b/tests/models/VersioningTest.php index 8219d1bcf..a9f4a2a26 100644 --- a/tests/models/VersioningTest.php +++ b/tests/models/VersioningTest.php @@ -1,42 +1,49 @@ hasColumn('name', 'string'); $this->hasColumn('version', 'integer'); } + public function setUp() { $this->actAs('Versionable'); } } -class VersioningTest2 extends Doctrine_Record +class VersioningTest2 extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('name', 'string'); $this->hasColumn('version', 'integer'); } + public function setUp() { $this->actAs('Versionable', array('auditLog' => false)); } } -class VersioningTest3 extends Doctrine_Record +class VersioningTest3 extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('name', 'string'); $this->hasColumn('version', 'integer'); } + public function setUp() { - - $this->actAs('Versionable', array('tableName' => 'tbl_prefix_comments_version', - 'className' => 'VersioningTestClass')); - + $this->actAs('Versionable', array('tableName' => 'tbl_prefix_comments_version', + 'className' => 'VersioningTestClass')); } -} \ No newline at end of file +} diff --git a/tests/models/ZeroValueTest.php b/tests/models/ZeroValueTest.php index 5976148e7..73fe5b354 100644 --- a/tests/models/ZeroValueTest.php +++ b/tests/models/ZeroValueTest.php @@ -1,19 +1,26 @@ hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true,)); - $this->hasColumn('username', 'string', 128, array('notnull' => true,)); - $this->hasColumn('algorithm', 'string', 128, array('default' => 'sha1', 'notnull' => true,)); - $this->hasColumn('salt', 'string', 128, array('notnull' => true,)); - $this->hasColumn('password', 'string', 128, array('notnull' => true,)); + $this->hasColumn('id', 'integer', 4, array('primary' => true, 'autoincrement' => true)); + $this->hasColumn('username', 'string', 128, array('notnull' => true)); + $this->hasColumn('algorithm', 'string', 128, array('default' => 'sha1', 'notnull' => true)); + $this->hasColumn('salt', 'string', 128, array('notnull' => true)); + $this->hasColumn('password', 'string', 128, array('notnull' => true)); $this->hasColumn('created_at', 'timestamp', null, array()); $this->hasColumn('last_login', 'timestamp', null, array()); - $this->hasColumn('is_active', 'boolean', null, array('default' => true, 'notnull' => true,)); - $this->hasColumn('is_super_admin', 'boolean', null, array('default' => false, 'notnull' => true,)); + $this->hasColumn('is_active', 'boolean', null, array('default' => true, 'notnull' => true)); + $this->hasColumn('is_super_admin', 'boolean', null, array('default' => false, 'notnull' => true)); } - public function setUp() - { } + public function setUp() + { + } } diff --git a/tests/models/export/Cms_Category.php b/tests/models/export/Cms_Category.php index 71db71650..52042e517 100644 --- a/tests/models/export/Cms_Category.php +++ b/tests/models/export/Cms_Category.php @@ -1,21 +1,21 @@ hasMany('Cms_CategoryLanguages as langs', array('local' => 'id', 'foreign' => 'category_id')); - } - - public function setTableDefinition() + $this->hasMany('Cms_CategoryLanguages as langs', array('local' => 'id', 'foreign' => 'category_id')); + } + + public function setTableDefinition() { - $this->hasColumn('created', 'timestamp'); - $this->hasColumn('parent', 'integer', 11); - $this->hasColumn('position', 'integer', 3); - $this->hasColumn('active', 'integer', 11); - $this->option('collate', 'utf8_unicode_ci'); - $this->option('charset', 'utf8'); - $this->option('type', 'INNODB'); - $this->index('index_parent', array('fields' => array('parent'))); - } + $this->hasColumn('created', 'timestamp'); + $this->hasColumn('parent', 'integer', 11); + $this->hasColumn('position', 'integer', 3); + $this->hasColumn('active', 'integer', 11); + $this->option('collate', 'utf8_unicode_ci'); + $this->option('charset', 'utf8'); + $this->option('type', 'INNODB'); + $this->index('index_parent', array('fields' => array('parent'))); + } } diff --git a/tests/models/export/Cms_CategoryLanguages.php b/tests/models/export/Cms_CategoryLanguages.php index 80a5a805e..dd40d500a 100644 --- a/tests/models/export/Cms_CategoryLanguages.php +++ b/tests/models/export/Cms_CategoryLanguages.php @@ -1,21 +1,22 @@ setAttribute(Doctrine_Core::ATTR_COLL_KEY, 'language_id'); - $this->hasOne('Cms_Category as category', array('local' => 'category_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); - } - - public function setTableDefinition() - { - $this->hasColumn('name', 'string',256); - $this->hasColumn('category_id', 'integer',11); - $this->hasColumn('language_id', 'integer',11); - $this->option('collate', 'utf8_unicode_ci'); - $this->option('charset', 'utf8'); - $this->option('type', 'INNODB'); - $this->index('index_category', array('fields' => array('category_id'))); - $this->index('index_language', array('fields' => array('language_id'))); - } + $this->setAttribute(Doctrine_Core::ATTR_COLL_KEY, 'language_id'); + $this->hasOne('Cms_Category as category', array('local' => 'category_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); + } + + public function setTableDefinition() + { + $this->hasColumn('name', 'string', 256); + $this->hasColumn('category_id', 'integer', 11); + $this->hasColumn('language_id', 'integer', 11); + $this->option('collate', 'utf8_unicode_ci'); + $this->option('charset', 'utf8'); + $this->option('type', 'INNODB'); + $this->index('index_category', array('fields' => array('category_id'))); + $this->index('index_language', array('fields' => array('language_id'))); + } } diff --git a/tests/models/gnatEmail.php b/tests/models/gnatEmail.php index 209ef6fd3..d19468933 100644 --- a/tests/models/gnatEmail.php +++ b/tests/models/gnatEmail.php @@ -1,10 +1,9 @@ hasColumn('address', 'string', 150); } - - } diff --git a/tests/models/gnatUser.php b/tests/models/gnatUser.php index e6a66915b..31ed6267c 100644 --- a/tests/models/gnatUser.php +++ b/tests/models/gnatUser.php @@ -1,19 +1,20 @@ -hasColumn('name', 'string', 150); - $this->hasColumn('foreign_id', 'integer', 10, array ('unique' => true,)); + $this->hasColumn('foreign_id', 'integer', 10, array('unique' => true)); } - + public function setUp() { parent::setUp(); - $this->hasOne('gnatEmail as Email', array('local'=> 'foreign_id', 'foreign'=>'id', 'onDelete'=>'CASCADE')); + $this->hasOne('gnatEmail as Email', array('local' => 'foreign_id', 'foreign' => 'id', 'onDelete' => 'CASCADE')); } - } - diff --git a/tests/models/mmrGroupUser_B.php b/tests/models/mmrGroupUser_B.php index 8d246383b..00f96eb70 100644 --- a/tests/models/mmrGroupUser_B.php +++ b/tests/models/mmrGroupUser_B.php @@ -1,7 +1,8 @@ hasColumn('user_id', 'string', 30, array('primary' => true)); $this->hasColumn('group_id', 'string', 30, array('primary' => true)); diff --git a/tests/models/mmrGroupUser_C.php b/tests/models/mmrGroupUser_C.php index 656e44df1..75fb4bd43 100644 --- a/tests/models/mmrGroupUser_C.php +++ b/tests/models/mmrGroupUser_C.php @@ -1,8 +1,8 @@ hasColumn('user_id', 'string', 30, array('primary' => true)); $this->hasColumn('group_id', 'string', 30, array('primary' => true)); diff --git a/tests/models/mmrGroup_B.php b/tests/models/mmrGroup_B.php index f45eb8aa7..a7f9c76e8 100644 --- a/tests/models/mmrGroup_B.php +++ b/tests/models/mmrGroup_B.php @@ -1,14 +1,18 @@ hasMany('mmrUser_B', array('local' => 'group_id', - 'foreign' => 'user_id', - 'refClass' => 'mmrGroupUser_B')); + 'foreign' => 'user_id', + 'refClass' => 'mmrGroupUser_B')); } - public function setTableDefinition() { + + public function setTableDefinition() + { // Works when - $this->hasColumn('id', 'string', 30, array ( 'primary' => true)); + $this->hasColumn('id', 'string', 30, array('primary' => true)); $this->hasColumn('name', 'string', 30); } } diff --git a/tests/models/mmrGroup_C.php b/tests/models/mmrGroup_C.php index 6b8f865ff..6b437bef2 100644 --- a/tests/models/mmrGroup_C.php +++ b/tests/models/mmrGroup_C.php @@ -1,13 +1,15 @@ hasMany('mmrUser_C', array('local' => 'group_id', - 'foreign' => 'user_id', - 'refClass' => 'mmrGroupUser_C')); + 'foreign' => 'user_id', + 'refClass' => 'mmrGroupUser_C')); } - public function setTableDefinition() + + public function setTableDefinition() { $this->hasColumn('g_id as id', 'string', 30, array('primary' => true)); $this->hasColumn('name', 'string', 30); diff --git a/tests/models/mmrUser_B.php b/tests/models/mmrUser_B.php index dcdca013e..9f1b92a7a 100644 --- a/tests/models/mmrUser_B.php +++ b/tests/models/mmrUser_B.php @@ -1,18 +1,18 @@ hasMany('mmrGroup_B as Group', array('local' => 'user_id', - 'foreign' => 'group_id', - 'refClass' => 'mmrGroupUser_B')); - + $this->hasMany('mmrGroup_B as Group', array('local' => 'user_id', + 'foreign' => 'group_id', + 'refClass' => 'mmrGroupUser_B')); } - public function setTableDefinition() + public function setTableDefinition() { - // Works when - $this->hasColumn('id', 'string', 30, array ( 'primary' => true)); + // Works when + $this->hasColumn('id', 'string', 30, array('primary' => true)); $this->hasColumn('name', 'string', 30); } } diff --git a/tests/models/mmrUser_C.php b/tests/models/mmrUser_C.php index ed2671634..8150f63fc 100644 --- a/tests/models/mmrUser_C.php +++ b/tests/models/mmrUser_C.php @@ -1,12 +1,12 @@ hasMany('mmrGroup_C as Group', array('local' => 'user_id', - 'foreign' => 'group_id', - 'refClass' => 'mmrGroupUser_C')); - + $this->hasMany('mmrGroup_C as Group', array('local' => 'user_id', + 'foreign' => 'group_id', + 'refClass' => 'mmrGroupUser_C')); } public function setTableDefinition() @@ -16,4 +16,3 @@ public function setTableDefinition() $this->hasColumn('name', 'string', 30); } } - diff --git a/tests/mysql_migration_classes/001_mysql_add_table.php b/tests/mysql_migration_classes/001_mysql_add_table.php index b0a3b8d5d..4b36df3e0 100644 --- a/tests/mysql_migration_classes/001_mysql_add_table.php +++ b/tests/mysql_migration_classes/001_mysql_add_table.php @@ -1,4 +1,5 @@ createTable('migration_test', array('field1' => array('type' => 'string'))); $this->addColumn('migration_test', 'field2', 'integer'); } - + public function down() { $this->dropTable('migration_test'); } -} \ No newline at end of file +} diff --git a/tests/mysql_migration_classes/002_mysql_change_column.php b/tests/mysql_migration_classes/002_mysql_change_column.php index abada1416..2364353d1 100644 --- a/tests/mysql_migration_classes/002_mysql_change_column.php +++ b/tests/mysql_migration_classes/002_mysql_change_column.php @@ -1,13 +1,14 @@ renameColumn('migration_test','field2','field3'); + $this->renameColumn('migration_test', 'field2', 'field3'); } - + public function down() { - $this->renameColumn('migration_test','field3','field2'); - } -} \ No newline at end of file + $this->renameColumn('migration_test', 'field3', 'field2'); + } +} diff --git a/tests/run.php b/tests/run.php index 2b32582de..6e6d46976 100644 --- a/tests/run.php +++ b/tests/run.php @@ -11,7 +11,7 @@ '2015', '2292', '1783', // Known bug integer validation with numbers greater than PHP_INT_MAX. - 'DC521' // PostgreSQL specific error + 'DC521', // PostgreSQL specific error ); $test = new DoctrineTest(); @@ -39,14 +39,13 @@ // Ticket Tests $tickets = new GroupTest('Tickets Tests', 'tickets'); -$ticketTestCases = glob(dirname(__FILE__) . '/Ticket/*TestCase.php'); +$ticketTestCases = glob(dirname(__FILE__).'/Ticket/*TestCase.php'); -foreach ($ticketTestCases as $testCase) -{ +foreach ($ticketTestCases as $testCase) { $fileInfo = pathinfo($testCase); $name = str_replace('TestCase', '', $fileInfo['filename']); - if ( ! in_array($name, $excludeTickets)) { + if (!in_array($name, $excludeTickets)) { $name = sprintf('Doctrine_Ticket_%s_TestCase', $name); $tickets->addTestCase(new $name()); } @@ -195,13 +194,13 @@ $test->addTestCase($db); // Event Listener Tests -$event_listener = new GroupTest('EventListener Tests','event_listener'); +$event_listener = new GroupTest('EventListener Tests', 'event_listener'); $event_listener->addTestCase(new Doctrine_EventListener_TestCase()); $event_listener->addTestCase(new Doctrine_EventListener_Chain_TestCase()); $test->addTestCase($event_listener); // Query Tests -$query_tests = new GroupTest('Query Tests','query'); +$query_tests = new GroupTest('Query Tests', 'query'); $query_tests->addTestCase(new Doctrine_Query_TestCase()); $query_tests->addTestCase(new Doctrine_Query_Condition_TestCase()); $query_tests->addTestCase(new Doctrine_Query_MultiJoin_TestCase()); @@ -318,4 +317,4 @@ $test->addTestCase($unsorted); */ -exit($test->run() ? 0 : 1); \ No newline at end of file +exit($test->run() ? 0 : 1); diff --git a/tests/unsolved.php b/tests/unsolved.php index e10461a6b..f8099b8d2 100644 --- a/tests/unsolved.php +++ b/tests/unsolved.php @@ -1,14 +1,14 @@ "; +echo '
';
 
 $manager = Doctrine_Manager::getInstance();
 $dbh = Doctrine_Db::getConnection('sqlite::memory:');