diff --git a/lib/Doctrine/Access.php b/lib/Doctrine/Access.php index f066e7f4a..9bd8c2b9d 100644 --- a/lib/Doctrine/Access.php +++ b/lib/Doctrine/Access.php @@ -20,23 +20,19 @@ */ /** - * Provides array access and property overload interface for Doctrine subclasses + * Provides array access and property overload interface for Doctrine subclasses. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Access - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 - * @return Doctrine_Access + * @param array $array An array of key => value pairs + * @return Doctrine_Access */ public function setArray(array $array) { @@ -48,12 +44,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 +54,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 +64,10 @@ 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 +75,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 +88,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 +103,76 @@ 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 + * @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 + * @param mixed $offset The offset to check + * @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..cb22c7129 100644 --- a/lib/Doctrine/Adapter/Exception.php +++ b/lib/Doctrine/Adapter/Exception.php @@ -20,15 +20,12 @@ */ /** - * Doctrine_Adapter exception class + * Doctrine_Adapter exception class. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Adapter - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..3e0101d4e 100644 --- a/lib/Doctrine/Adapter/Interface.php +++ b/lib/Doctrine/Adapter/Interface.php @@ -20,28 +20,35 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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..74edcb8fd 100644 --- a/lib/Doctrine/Adapter/Mock.php +++ b/lib/Doctrine/Adapter/Mock.php @@ -22,53 +22,48 @@ /** * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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 +71,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 +81,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 +91,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 +103,9 @@ 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 +117,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 +127,18 @@ 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 +153,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 +163,28 @@ 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 +196,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 +210,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 +244,7 @@ public function beginTransaction() } /** - * Commit a transaction - * - * @return void + * Commit a transaction. */ public function commit() { @@ -265,9 +252,7 @@ public function commit() } /** - * Rollback a transaction - * - * @return void + * Rollback a transaction. */ public function rollBack() { @@ -276,20 +261,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..75a930df7 100644 --- a/lib/Doctrine/Adapter/Oracle.php +++ b/lib/Doctrine/Adapter/Oracle.php @@ -20,34 +20,28 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision$ + * + * @see www.doctrine-project.org */ - 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 +56,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 +76,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 +97,59 @@ 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 + * @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 + * @param string $query * @return Doctrine_Adapter_Statement_Oracle $stmt */ public function query($query) @@ -163,56 +161,53 @@ public function query($query) } /** - * 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 "'" . 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 +215,9 @@ public function commit() } /** - * Rollback a transaction + * Rollback a transaction. * - * @return boolean + * @return bool */ public function rollBack() { @@ -230,39 +225,42 @@ public function rollBack() } /** - * Set connection attribute + * Set connection 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) { 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..a4183c830 100644 --- a/lib/Doctrine/Adapter/Statement.php +++ b/lib/Doctrine/Adapter/Statement.php @@ -20,112 +20,81 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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..664758e0b 100644 --- a/lib/Doctrine/Adapter/Statement/Interface.php +++ b/lib/Doctrine/Adapter/Statement/Interface.php @@ -20,107 +20,96 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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. - * - * @return boolean Returns TRUE on success or FALSE on failure. + * @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 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 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. + * @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. + * @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,54 +117,48 @@ 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. - * @return boolean Returns TRUE on success or FALSE on failure. + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed + * @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 + * @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); + public function fetch( + $fetchStyle = Doctrine_Core::FETCH_BOTH, + $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, + $cursorOffset = null + ); /** - * 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. + * Returns an array containing all of the result set rows. * + * @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); @@ -184,43 +167,42 @@ 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. - * - * @return string returns a single column in the next row of a result set. + * @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 */ 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. - * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @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 */ 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. - * - * @return array Associative meta data array with the following structure: + * @param int $column the 0-indexed column in the result set + * @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 +215,46 @@ 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 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/Mock.php b/lib/Doctrine/Adapter/Statement/Mock.php index 3b7a2ac49..ca245e6ad 100644 --- a/lib/Doctrine/Adapter/Statement/Mock.php +++ b/lib/Doctrine/Adapter/Statement/Mock.php @@ -20,77 +20,73 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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. - * - * @return boolean Returns TRUE on success or FALSE on failure. + * @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 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 +98,24 @@ 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 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. + * @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. + * @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 +123,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 +137,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 +151,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 +165,42 @@ 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) - { + public function fetch( + $fetchStyle = Doctrine_Core::FETCH_BOTH, + $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 +209,7 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH) } /** - * execute + * execute. * * Executes a prepared statement * @@ -238,30 +219,29 @@ 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. - * @return boolean Returns TRUE on success or FALSE on failure. + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed + * @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. - * - * @return string returns a single column in the next row of a result set. + * @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 */ public function fetchColumn($columnIndex = 0) { @@ -269,18 +249,17 @@ 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. - * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @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 */ public function fetchObject($className = 'stdClass', $args = array()) { @@ -288,7 +267,7 @@ public function fetchObject($className = 'stdClass', $args = array()) } /** - * nextRowset + * nextRowset. * * Advances to the next rowset in a multi-rowset statement handle * @@ -297,7 +276,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 +284,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 +294,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 +302,12 @@ 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. - * - * @return array Associative meta data array with the following structure: + * @param int $column the 0-indexed column in the result set + * @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 +318,48 @@ 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..b2812e669 100644 --- a/lib/Doctrine/Adapter/Statement/Oracle.php +++ b/lib/Doctrine/Adapter/Statement/Oracle.php @@ -22,64 +22,59 @@ /** * 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 - * @since 1.0 - * @version $Rev$ + * + * @see www.doctrine-project.org */ 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 +82,34 @@ 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. - * - * @return boolean Returns TRUE on success or FALSE on failure. + * @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 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 +117,31 @@ 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 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. + * @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. + * @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 +149,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 +177,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 +248,101 @@ 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. - * @return boolean Returns TRUE on success or FALSE on failure. + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed + * @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 - * - * @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. + * Returns an array containing all of the result set rows. * + * @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 +352,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 +374,73 @@ 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. - * - * @return string returns a single column in the next row of a result set. + * @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 */ 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. - * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @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 */ 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 - * - * @param integer $column The 0-indexed column in the result set. + * Returns metadata for a column in a result set. * - * @return array Associative meta data array with the following structure: + * @param int $column the 0-indexed column in the result set + * @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 +453,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 +469,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 +500,31 @@ 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) { 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 +532,52 @@ public function getAttribute($attribute) } /** - * Set the default fetch mode for this statement + * 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) { - 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..44316989c 100644 --- a/lib/Doctrine/AuditLog.php +++ b/lib/Doctrine/AuditLog.php @@ -20,45 +20,40 @@ */ /** - * Doctrine_AuditLog + * Doctrine_AuditLog. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage AuditLog - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +67,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 +81,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 +95,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']); + $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 Doctrine_Record $record - * @param integer $version - * @param integer $hydrationMode - * @param boolean $asCollection - * @return array An array or Doctrine_Collection or a Doctrine_Record + * @param int $version + * @param int $hydrationMode + * @param bool $asCollection + * @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..f0cdd93ea 100644 --- a/lib/Doctrine/AuditLog/Listener.php +++ b/lib/Doctrine/AuditLog/Listener.php @@ -20,46 +20,36 @@ */ /** - * Doctrine_AuditLog_Listener + * Doctrine_AuditLog_Listener. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage AuditLog - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +57,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 +73,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 +122,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 +132,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..f8d8a93fd 100644 --- a/lib/Doctrine/AuditLog/Listener/Microtime.php +++ b/lib/Doctrine/AuditLog/Listener/Microtime.php @@ -20,30 +20,23 @@ */ /** - * Doctrine_AuditLog_Listener + * Doctrine_AuditLog_Listener. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage AuditLog - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +48,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 +58,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 +68,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..c523b64c4 100644 --- a/lib/Doctrine/Builder.php +++ b/lib/Doctrine/Builder.php @@ -20,14 +20,10 @@ */ /** - * 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 +31,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..89f8d715d 100644 --- a/lib/Doctrine/Cache/Apc.php +++ b/lib/Doctrine/Cache/Apc.php @@ -20,37 +20,33 @@ */ /** - * APC Cache Driver + * APC Cache Driver. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cache - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 + * @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 +55,27 @@ 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 + * @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) - * @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) { @@ -87,10 +84,10 @@ 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 + * @param string $id cache id + * @return bool true if no problem */ protected function _doDelete($id) { @@ -98,7 +95,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 +105,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..4fef1fd63 100644 --- a/lib/Doctrine/Cache/Array.php +++ b/lib/Doctrine/Cache/Array.php @@ -20,29 +20,25 @@ */ /** - * Array cache driver + * Array cache driver. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cache - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 + * @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) @@ -50,14 +46,15 @@ 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 + * @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 +63,12 @@ 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 +79,10 @@ 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 + * @param string $id cache id + * @return bool true if no problem */ protected function _doDelete($id) { @@ -97,7 +94,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 +102,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..ef394fa3a 100644 --- a/lib/Doctrine/Cache/Db.php +++ b/lib/Doctrine/Cache/Db.php @@ -20,14 +20,10 @@ */ /** - * Database cache driver + * Database cache driver. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cache - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 1.0 - * @version $Revision: 7490 $ * @author Konsta Vesterinen * @author Jonathan H. Wage */ @@ -35,30 +31,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 +59,24 @@ 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 + * @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 +84,58 @@ 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 + * @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) - * @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, $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 +146,20 @@ 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 + * @param string $id cache id + * @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 +167,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); @@ -198,35 +189,36 @@ public function createTable() * Convert hex data to binary data. If passed data is not hex then * it is returned as is. * - * @param string $hex + * @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..9de58b1f5 100644 --- a/lib/Doctrine/Cache/Driver.php +++ b/lib/Doctrine/Cache/Driver.php @@ -20,28 +20,22 @@ */ /** - * Abstract cache driver class + * Abstract cache driver class. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cache - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +43,32 @@ 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 - * @return mixed option value + * @param mixed $option the option name + * @return mixed option value */ public function getOption($option) { - if ( ! isset($this->_options[$option])) { + if (!isset($this->_options[$option])) { return null; } @@ -80,68 +76,71 @@ 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 + * @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 + * @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) - * @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) { $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 + * @param string $id cache id + * @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 + * @param string $regex + * @return int $count The number of deleted cache entries */ public function deleteByRegex($regex) { @@ -150,19 +149,20 @@ 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 + * @param string $prefix + * @return int $count The number of deleted cache entries */ public function deleteByPrefix($prefix) { @@ -170,20 +170,21 @@ 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 + * @param string $suffix + * @return int $count The number of deleted cache entries */ public function deleteBySuffix($suffix) { @@ -192,89 +193,91 @@ 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 + * @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 + * @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) - * @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 */ 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 + * @param string $id cache id + * @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..3aeede3b8 100644 --- a/lib/Doctrine/Cache/Exception.php +++ b/lib/Doctrine/Cache/Exception.php @@ -20,17 +20,13 @@ */ /** - * Doctrine cache exception class + * Doctrine cache exception class. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cache - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..ea01ac354 100644 --- a/lib/Doctrine/Cache/Interface.php +++ b/lib/Doctrine/Cache/Interface.php @@ -20,51 +20,47 @@ */ /** - * Doctrine cache driver interface + * Doctrine cache driver interface. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cache - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 + * @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 + * @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 + * @param string $id cache id + * @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..28e1a35fd 100644 --- a/lib/Doctrine/Cache/Memcache.php +++ b/lib/Doctrine/Cache/Memcache.php @@ -20,38 +20,34 @@ */ /** - * Memcache cache driver + * Memcache cache driver. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cache - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +55,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,9 +69,9 @@ 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 + * @param string $id cache id * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) @@ -84,10 +80,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 + * @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 +92,12 @@ 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) { @@ -116,10 +112,10 @@ 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 + * @param string $id cache id + * @return bool true if no problem */ protected function _doDelete($id) { @@ -127,7 +123,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 +142,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..d739e4b07 100644 --- a/lib/Doctrine/Cache/Xcache.php +++ b/lib/Doctrine/Cache/Xcache.php @@ -20,14 +20,10 @@ */ /** - * Xcache cache driver + * Xcache cache driver. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cache - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 1.0 - * @version $Revision: $ * @author Dmitry Bakaleinik (dima@snaiper.net) * @author Konsta Vesterinen * @author Jonathan H. Wage @@ -35,13 +31,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,9 +45,9 @@ 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 + * @param string $id cache id * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) @@ -60,10 +56,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 + * @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 +68,12 @@ 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) { @@ -86,10 +82,10 @@ 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 + * @param string $id cache id + * @return bool true if no problem */ protected function _doDelete($id) { @@ -97,7 +93,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 +101,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 +109,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 +124,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..bcfc3e5a3 100644 --- a/lib/Doctrine/Cli.php +++ b/lib/Doctrine/Cli.php @@ -20,31 +20,27 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 2761 $ + * @see www.doctrine-project.org + * * @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 +53,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 +65,7 @@ class Doctrine_Cli private $_taskInstance; /** - * __construct + * __construct. * * @param array [$config=array()] * @param object|null [$formatter=null] Doctrine_Cli_Formatter @@ -81,9 +77,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 +107,14 @@ public function getFormatter() } /** - * Returns the specified value from the config, or the default value, if specified - * - * @param string $name - * @return mixed + * Returns the specified value from the config, or the default value, if specified. + * + * @param string $name * @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,13 +126,13 @@ 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] @@ -164,9 +156,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 +164,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 +174,9 @@ public function getRegisteredTasks() } /** - * Returns TRUE if the specified Task-class is registered, or FALSE otherwise - * - * @param string $className + * Returns TRUE if the specified Task-class is registered, or FALSE otherwise. + * + * @param string $className * @return bool */ public function taskClassIsRegistered($className) @@ -195,10 +185,10 @@ 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 @@ -208,6 +198,7 @@ public function taskNameIsRegistered($taskName, &$className = null) foreach ($this->getRegisteredTasks() as $currClassName => $task) { if ($task->getTaskName() == $taskName) { $className = $currClassName; + return true; } } @@ -233,8 +224,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 +233,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 +260,24 @@ 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 + * + * @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 +297,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 +317,24 @@ protected function includeDoctrineTaskClasses($directory) } /** - * Registers the specified _included_ task-class - * - * @param string $className + * 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 +342,25 @@ public function registerTaskClass($className) } /** - * Returns TRUE if the specified class is a Task, or FALSE otherwise - * - * @param string $className + * 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 string $className + * @param object $cli Doctrine_Cli * @return object Doctrine_Task */ protected function createTaskInstance($className, Doctrine_Cli $cli) @@ -377,8 +369,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 +383,22 @@ 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 +406,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 +424,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 +435,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 +450,32 @@ 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 - * @return void + * @param array $args Array of arguments for this task being executed * @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 +485,16 @@ protected function _run(array $args) } /** - * Executes the task with the specified _prepared_ arguments - * - * @param object $task Doctrine_Task - * @param array $preparedArguments + * Executes the task with the specified _prepared_ arguments. + * + * @param object $task Doctrine_Task * @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 +503,58 @@ 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 +562,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 +590,7 @@ public function printTasks($taskName = null, $full = false) } /** - * @param array $argumentsDescriptions - * @param array $config - * @param object $formatter Doctrine_Cli_Formatter + * @param object $formatter Doctrine_Cli_Formatter * @return string */ protected function assembleArgumentList(array $argumentsDescriptions, array $config, Doctrine_Cli_Formatter $formatter) @@ -613,8 +598,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 +613,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 +632,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..aa8a020db 100644 --- a/lib/Doctrine/Cli/AnsiColorFormatter.php +++ b/lib/Doctrine/Cli/AnsiColorFormatter.php @@ -29,29 +29,24 @@ /** * 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 - * @since 1.0 - * @version $Revision: 4252 $ + * + * @see www.doctrine-project.org */ 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. @@ -69,20 +64,19 @@ public function setStyle($name, $options = array()) * * @param string The test to style * @param mixed An array of options or a style name - * * @return string The styled text */ 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 +84,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 +103,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 +117,13 @@ 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) - * - * @return string The truncated string + * @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 +133,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); } /** @@ -150,11 +145,10 @@ public function excerpt($text, $size = null) * - non tty consoles * * @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..77a790f46 100644 --- a/lib/Doctrine/Cli/Exception.php +++ b/lib/Doctrine/Cli/Exception.php @@ -20,15 +20,12 @@ */ /** - * Cli exception class + * Cli exception class. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Cli - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..6248e96ab 100644 --- a/lib/Doctrine/Cli/Formatter.php +++ b/lib/Doctrine/Cli/Formatter.php @@ -29,28 +29,23 @@ /** * 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 - * @since 1.0 - * @version $Revision: 2761 $ + * + * @see www.doctrine-project.org */ 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; } @@ -61,7 +56,6 @@ function __construct($maxLineSize = 65) * @param string The test to style * @param mixed An array of parameters * @param stream A stream (default to STDOUT) - * * @return string The formatted text */ public function format($text = '', $parameters = array(), $stream = STDOUT) @@ -74,24 +68,25 @@ 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) - * - * @return string The truncated string + * @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 +102,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..586bf46c2 100644 --- a/lib/Doctrine/Collection.php +++ b/lib/Doctrine/Collection.php @@ -23,86 +23,81 @@ * 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 - * @since 1.0 - * @version $Revision: 7686 $ + * @see www.doctrine-project.org + * * @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 +107,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 +117,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 +127,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 +136,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 +149,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 +159,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 +175,33 @@ 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 + * @param string $column * @return Doctrine_Collection $this */ public function setKeyColumn($column) @@ -229,7 +212,7 @@ public function setKeyColumn($column) } /** - * Get the name of the key column + * Get the name of the key column. * * @return string */ @@ -239,7 +222,7 @@ public function getKeyColumn() } /** - * Get all the records as an array + * Get all the records as an array. * * @return array */ @@ -249,7 +232,7 @@ public function getData() } /** - * Get the first record in the collection + * Get the first record in the collection. * * @return Doctrine_Record */ @@ -259,7 +242,7 @@ public function getFirst() } /** - * Get the last record in the collection + * Get the last record in the collection. * * @return Doctrine_Record */ @@ -269,7 +252,7 @@ public function getLast() } /** - * Get the last record in the collection + * Get the last record in the collection. * * @return Doctrine_Record */ @@ -279,7 +262,7 @@ public function end() } /** - * Get the current key + * Get the current key. * * @return Doctrine_Record */ @@ -289,7 +272,7 @@ public function key() } /** - * Sort by key + * Sort by key. * * @return Doctrine_Collection */ @@ -301,35 +284,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 +319,24 @@ 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 - * @return boolean + * @param mixed $key the key of the element + * @return bool */ public function contains($key) { @@ -364,10 +344,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 +352,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 +364,24 @@ 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 +398,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 +414,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 +430,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 +456,17 @@ 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 - * @return boolean + * @param Doctrine_Record $record record to be added + * @param string $key optional key for the record + * @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 +479,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 +495,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 +513,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 +522,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 +534,32 @@ 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 + * @param mixed|null $name + * @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 +568,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 +607,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 +623,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 +637,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 +652,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 +671,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 +681,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 +693,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 +701,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 +718,19 @@ 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 + * @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 +739,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 +760,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 +779,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 +797,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 +828,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 +868,21 @@ 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 + * @param Doctrine_Record $a + * @param Doctrine_Record $b + * @return int */ protected function compareRecords($a, $b) { @@ -923,14 +895,14 @@ 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 +930,14 @@ 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 +964,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 +997,6 @@ public function delete(Doctrine_Connection $conn = null, $clearColl = true) /** * Clears the collection. - * - * @return void */ public function clear() { @@ -1037,13 +1007,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 +1025,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 +1048,7 @@ public function __toString() } /** - * Returns the relation object + * Returns the relation object. * * @return Doctrine_Relation */ @@ -1090,19 +1059,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..3121fe2e6 100644 --- a/lib/Doctrine/Collection/Exception.php +++ b/lib/Doctrine/Collection/Exception.php @@ -20,15 +20,12 @@ */ /** - * Collection exception class + * Collection exception class. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Collection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..cbad90744 100644 --- a/lib/Doctrine/Collection/Iterator.php +++ b/lib/Doctrine/Collection/Iterator.php @@ -21,72 +21,64 @@ /** * Doctrine_Collection_Iterator - * iterates through Doctrine_Collection + * iterates through Doctrine_Collection. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Collection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +86,7 @@ public function key() } /** - * returns the current record + * returns the current record. * * @return Doctrine_Record */ @@ -104,16 +96,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..54ee0b5ac 100644 --- a/lib/Doctrine/Collection/Iterator/Expandable.php +++ b/lib/Doctrine/Collection/Iterator/Expandable.php @@ -20,14 +20,10 @@ */ /** - * Expandable collection iterator class + * Expandable collection iterator class. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Collection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 1.0 - * @version $Revision: 7490 $ * @author Konsta Vesterinen */ class Doctrine_Collection_Iterator_Expandable extends Doctrine_Collection_Iterator @@ -36,14 +32,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 +49,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..17d98af0d 100644 --- a/lib/Doctrine/Collection/Iterator/Normal.php +++ b/lib/Doctrine/Collection/Iterator/Normal.php @@ -20,23 +20,19 @@ */ /** - * Doctrine_Collection_Iterator_Normal + * Doctrine_Collection_Iterator_Normal. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Collection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..1a80465bd 100644 --- a/lib/Doctrine/Collection/Iterator/Offset.php +++ b/lib/Doctrine/Collection/Iterator/Offset.php @@ -20,18 +20,15 @@ */ /** - * Doctrine_Collection_Iterator_Normal + * Doctrine_Collection_Iterator_Normal. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Collection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..c9f2b7493 100644 --- a/lib/Doctrine/Collection/Offset.php +++ b/lib/Doctrine/Collection/Offset.php @@ -23,24 +23,17 @@ * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * @see www.doctrine-project.org + * * @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 +41,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..4c722a12f 100644 --- a/lib/Doctrine/Collection/OnDemand.php +++ b/lib/Doctrine/Collection/OnDemand.php @@ -21,14 +21,10 @@ /** * Doctrine_Collection_OnDemand - * iterates through Doctrine_Records hydrating one at a time + * iterates through Doctrine_Records hydrating one at a time. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Collection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 1.1 - * @version $Revision$ * @author Geoff Davis */ class Doctrine_Collection_OnDemand implements Iterator @@ -55,16 +51,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 +70,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..a4269ba00 100644 --- a/lib/Doctrine/Column.php +++ b/lib/Doctrine/Column.php @@ -21,28 +21,24 @@ /** * 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 - * @since 1.0 + * + * @see www.doctrine-project.org */ 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 +48,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 +61,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 +95,22 @@ 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 +122,9 @@ public function enumValue($index) } /** - * enumIndex + * enumIndex. * * @param string $field - * @param mixed $value - * @return mixed */ public function enumIndex($field, $value) { @@ -142,23 +134,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..9e6e458cb 100644 --- a/lib/Doctrine/Compiler.php +++ b/lib/Doctrine/Compiler.php @@ -21,118 +21,115 @@ /** * 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. - * @since 1.0 - * @version $Revision: 7677 $ + * + * @see www.phpdoctrine. */ 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. * - * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation + * @param mixed|null $target * @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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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..7c9371662 100644 --- a/lib/Doctrine/Configurable.php +++ b/lib/Doctrine/Configurable.php @@ -21,54 +21,51 @@ /** * Doctrine_Configurable - * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection + * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Configurable - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +74,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 +116,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 +134,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 +162,13 @@ 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 +179,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 +218,16 @@ public function setEventListener($listener) } /** - * addRecordListener + * addRecordListener. * - * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener + * @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 +236,33 @@ 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 + * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener + * @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 +272,16 @@ public function setRecordListener($listener) } /** - * addListener + * addListener. * - * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener + * @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 +290,33 @@ 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 + * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener + * @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 +326,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 +339,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 +357,7 @@ public function unsetAttribute($attribute) /** * getAttributes - * returns all attributes as an array + * returns all attributes as an array. * * @return array */ @@ -364,7 +367,7 @@ public function getAttributes() } /** - * Set the charset + * Set the charset. * * @param string $charset */ @@ -374,9 +377,7 @@ public function setCharset($charset) } /** - * Get the charset - * - * @return mixed + * Get the charset. */ public function getCharset() { @@ -384,7 +385,7 @@ public function getCharset() } /** - * Set the collate + * Set the collate. * * @param string $collate */ @@ -394,7 +395,7 @@ public function setCollate($collate) } /** - * Get the collate + * Get the collate. * * @return mixed $collate */ @@ -405,10 +406,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 +415,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..3e6de0c0f 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,62 @@ * 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 - * @since 1.0 - * @version $Revision$ + * @see www.doctrine-project.org + * * @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 +126,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 +214,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 +227,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 +237,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 +261,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 +292,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 +305,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 +313,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 +324,13 @@ 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 +349,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 +359,11 @@ public function getName() } /** - * setName + * setName. * * Sets the name of the connection * * @param string $name - * @return void */ public function setName($name) { @@ -381,11 +371,9 @@ public function setName($name) } /** - * getDriverName + * getDriverName. * * Gets the name of the instance driver - * - * @return void */ public function getDriverName() { @@ -394,16 +382,17 @@ 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 +400,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 +412,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 +431,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 +444,9 @@ public function getDbh() /** * connect - * connects into database + * connects into database. * - * @return boolean + * @return bool */ public function connect() { @@ -469,37 +458,41 @@ 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->dbh = new PDO( + $this->options['dsn'], + $this->options['username'], + !$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 +501,33 @@ 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 - * @return boolean whether or not this drivers supports given feature + * @param string $feature the name of the 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 +542,24 @@ 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 +572,47 @@ 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. * - * @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 + * @param string $table The table to delete data from + * @param array $identifier an associateve array containing identifier column-value pairs + * @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 +620,9 @@ 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 +633,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 +653,8 @@ 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 +675,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 +709,9 @@ 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 - * - * @return string quoted identifier string + * @param string $str identifier name to be quoted + * @param bool $checkOption check the 'quote_identifier' option + * @return string quoted identifier string */ public function quoteIdentifier($str, $checkOption = true) { @@ -734,20 +719,20 @@ 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 - * - * @return string quoted identifier string + * @param array $arr identifiers array to be quoted + * @param bool $checkOption check the 'quote_identifier' option + * @return string quoted identifier string */ public function quoteMultipleIdentifier($arr, $checkOption = true) { @@ -761,12 +746,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 +759,10 @@ public function convertBooleans($item) /** * quote - * quotes given input parameter + * quotes given input parameter. * - * @param mixed $input parameter to be quoted - * @param string $type + * @param mixed $input parameter to be quoted + * @param string $type * @return string */ public function quote($input, $type = null) @@ -787,21 +771,20 @@ 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 +793,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 +805,10 @@ 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 +817,10 @@ 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 +829,11 @@ 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 +842,10 @@ 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 +854,10 @@ 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 +868,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 +876,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 +894,7 @@ public function query($query, array $params = array(), $hydrationMode = null) } /** - * prepare + * prepare. * * @param string $statement */ @@ -925,15 +909,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 +926,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 +936,33 @@ 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 string $query + * @param int $limit + * @param int $offset * @return Doctrine_Connection_Statement */ public function select($query, $limit = 0, $offset = 0) @@ -982,15 +970,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 - * - * @param string $query sql query - * @param array $params query parameters + * standaloneQuery. * + * @param string $query sql query + * @param array $params query parameters * @return PDOStatement|Doctrine_Adapter_Statement */ public function standaloneQuery($query, $params = array()) @@ -999,10 +987,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 */ public function execute($query, array $params = array()) @@ -1010,69 +998,70 @@ 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 */ public function rethrowException(Exception $e, $invoker, $query = null) @@ -1081,20 +1070,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 +1092,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 +1102,9 @@ 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 +1113,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 +1129,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 +1146,7 @@ public function getTable($name) } /** - * returns an array of all initialized tables + * returns an array of all initialized tables. * * @return array */ @@ -1169,7 +1157,7 @@ public function getTables() /** * returns an iterator that iterators through all - * initialized table objects + * initialized table objects. * * * foreach ($conn as $index => $table) { @@ -1177,20 +1165,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 +1186,10 @@ 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 - * @return boolean + * @param $table a Doctrine_Table object to be added into registry + * @return bool */ public function addTable(Doctrine_Table $table) { @@ -1217,11 +1205,12 @@ 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 +1230,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 +1248,7 @@ public function flush() /** * clear - * clears all repositories - * - * @return void + * clears all repositories. */ public function clear() { @@ -1274,9 +1260,7 @@ public function clear() /** * evictTables - * evicts all tables - * - * @return void + * evicts all tables. */ public function evictTables() { @@ -1286,9 +1270,7 @@ public function evictTables() /** * close - * closes the connection - * - * @return void + * closes the connection. */ public function close() { @@ -1305,9 +1287,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 +1298,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 +1311,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 +1323,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 +1337,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 +1351,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 +1367,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 +1375,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 +1383,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 +1400,9 @@ 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 +1422,10 @@ 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 +1442,9 @@ 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 +1452,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 +1474,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 +1486,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 +1508,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 +1529,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 +1559,7 @@ public function getTmpConnection($info) } /** - * modifyLimitQuery + * modifyLimitQuery. * * Some dbms require specific functionality for this. Check the other connection adapters for examples * @@ -1594,14 +1576,19 @@ public function modifyLimitQuery($query, $limit = false, $offset = false, $isMan * * @return string */ - public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = false, - $offset = false, $isManip = false) - { + public function modifyLimitSubquery( + Doctrine_Table $rootTable, + $query, + $limit = 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 +1596,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 +1609,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 +1621,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,23 +1635,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 - * @return string $fkName + * @param Doctrine_Relation $relation Relation object to generate the foreign key name for + * @return string $fkName */ public function generateUniqueRelationForeignKeyName(Doctrine_Relation $relation) { @@ -1683,10 +1667,10 @@ 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 +1689,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 +1715,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..cc5c5261a 100644 --- a/lib/Doctrine/Connection/Common.php +++ b/lib/Doctrine/Connection/Common.php @@ -20,37 +20,31 @@ */ /** - * 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 + * @param string $query * @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..7f554d381 100644 --- a/lib/Doctrine/Connection/Db2.php +++ b/lib/Doctrine/Connection/Db2.php @@ -20,45 +20,40 @@ */ /** - * Doctrine_Connection_Db2 + * Doctrine_Connection_Db2. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Connection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string the modified query + * @param string $query query to modify + * @param int $limit limit the number of rows + * @param int $offset start reading from given offset + * @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..a489d9761 100644 --- a/lib/Doctrine/Connection/Exception.php +++ b/lib/Doctrine/Connection/Exception.php @@ -20,68 +20,64 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Connection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +86,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 +96,14 @@ 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 - * - * @return string error message, or false if the error code was - * not recognized + * @param mixed|null $value + * @return string error message, or false if the error code was + * not recognized */ public function errorMessage($value = null) { @@ -118,13 +114,13 @@ 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 - * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * @param array $errorInfo error info array + * @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..3acf13ba5 100644 --- a/lib/Doctrine/Connection/Mock.php +++ b/lib/Doctrine/Connection/Mock.php @@ -20,32 +20,26 @@ */ /** - * 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 - * @since 1.0 + * + * @see www.doctrine-project.org */ 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..4ddb0e516 100644 --- a/lib/Doctrine/Connection/Module.php +++ b/lib/Doctrine/Connection/Module.php @@ -20,36 +20,32 @@ */ /** - * Doctrine_Connection_Module + * Doctrine_Connection_Module. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Connection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +57,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 +68,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..be121fb0b 100644 --- a/lib/Doctrine/Connection/Mssql.php +++ b/lib/Doctrine/Connection/Mssql.php @@ -20,50 +20,43 @@ */ /** - * 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 - * @since 1.0 + * + * @see www.doctrine-project.org */ 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 +65,21 @@ 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 - * - * @return string quoted identifier string + * @param string $identifier identifier name to be quoted + * @param bool $checkOption check the 'quote_identifier' option + * @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 +89,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 +139,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 +171,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 +188,17 @@ 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 $field + * @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 +216,22 @@ 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 - * @return array version information + * @param bool $native determines if the raw version string should be returned + * @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 +250,41 @@ 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 +292,15 @@ 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 +313,26 @@ 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 +340,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 +353,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..6172792a5 100644 --- a/lib/Doctrine/Connection/Mssql/Exception.php +++ b/lib/Doctrine/Connection/Mssql/Exception.php @@ -20,56 +20,53 @@ */ /** - * 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 - * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * @param array $errorInfo error info array + * @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..b1c5bbbe5 100644 --- a/lib/Doctrine/Connection/Mysql.php +++ b/lib/Doctrine/Connection/Mysql.php @@ -20,68 +20,63 @@ */ /** - * 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 - * @since 1.0 + * + * @see www.doctrine-project.org */ 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 +91,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 +116,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 +138,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: * @@ -193,8 +186,7 @@ public function setCharset($charset) * part of unique index they may not be null. * * 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 +203,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..9887bcc8c 100644 --- a/lib/Doctrine/Connection/Mysql/Exception.php +++ b/lib/Doctrine/Connection/Mysql/Exception.php @@ -20,67 +20,64 @@ */ /** - * 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 - * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * @param array $errorInfo error info array + * @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..4643feb92 100644 --- a/lib/Doctrine/Connection/Oracle.php +++ b/lib/Doctrine/Connection/Oracle.php @@ -20,121 +20,121 @@ */ /** - * Doctrine_Connection_Oracle + * Doctrine_Connection_Oracle. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Connection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string the modified query + * @param string $query query to modify + * @param int $limit limit the number of rows + * @param int $offset start reading from given offset + * @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) - { + public function modifyLimitSubquery( + Doctrine_Table $rootTable, + $query, + $limit = 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 +146,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..adcb3fa7d 100644 --- a/lib/Doctrine/Connection/Oracle/Exception.php +++ b/lib/Doctrine/Connection/Oracle/Exception.php @@ -20,61 +20,58 @@ */ /** - * 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 - * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * @param array $errorInfo error info array + * @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..ac502a608 100644 --- a/lib/Doctrine/Connection/Pgsql.php +++ b/lib/Doctrine/Connection/Pgsql.php @@ -20,71 +20,62 @@ */ /** - * 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 - * @since 1.0 + * + * @see www.doctrine-project.org */ 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 +87,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 +102,56 @@ 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 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 + * @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 + * @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 +159,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 +182,15 @@ 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 +200,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 +218,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..62cfd3c1e 100644 --- a/lib/Doctrine/Connection/Pgsql/Exception.php +++ b/lib/Doctrine/Connection/Pgsql/Exception.php @@ -20,89 +20,68 @@ */ /** - * Doctrine_Connection_Pgsql_Exception + * Doctrine_Connection_Pgsql_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Connection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 - * @since 1.0 + * @param array $errorInfo error info array + * * @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..4226ff37f 100644 --- a/lib/Doctrine/Connection/Profiler.php +++ b/lib/Doctrine/Connection/Profiler.php @@ -20,80 +20,77 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision$ + * + * @see www.doctrine-project.org */ 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 +101,8 @@ public function __call($m, $a) } /** - * get + * get. * - * @param mixed $key * @return Doctrine_Event|null */ public function get($key) @@ -114,12 +110,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 +127,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 +176,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..8ae6ef395 100644 --- a/lib/Doctrine/Connection/Profiler/Exception.php +++ b/lib/Doctrine/Connection/Profiler/Exception.php @@ -20,16 +20,12 @@ */ /** - * Doctrine_Connection_Profiler_Exception + * Doctrine_Connection_Profiler_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Connection - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..efa8f155f 100644 --- a/lib/Doctrine/Connection/Sqlite.php +++ b/lib/Doctrine/Connection/Sqlite.php @@ -20,61 +20,53 @@ */ /** - * 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 - * @since 1.0 + * + * @see www.doctrine-project.org */ 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 +74,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 +91,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 +107,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 +121,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..9067e747b 100644 --- a/lib/Doctrine/Connection/Sqlite/Exception.php +++ b/lib/Doctrine/Connection/Sqlite/Exception.php @@ -20,59 +20,57 @@ */ /** - * 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..330f8efb5 100644 --- a/lib/Doctrine/Connection/Statement.php +++ b/lib/Doctrine/Connection/Statement.php @@ -20,58 +20,54 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 1532 $ + * + * @see www.doctrine-project.org */ 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 +88,22 @@ public function getQuery() /** * 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 + * 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) { - 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 +111,20 @@ 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 $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. + * @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 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 +139,28 @@ 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 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. + * @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. + * @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 +169,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 +182,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 +195,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 +208,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 +216,9 @@ 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. - * @return boolean Returns TRUE on success or FALSE on failure. + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = array()) { @@ -240,11 +227,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 +239,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 +256,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 +275,35 @@ 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) - { + public function fetch( + $fetchMode = Doctrine_Core::FETCH_BOTH, + $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 +313,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,28 +324,27 @@ public function fetch($fetchMode = Doctrine_Core::FETCH_BOTH, /** * fetchAll - * 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. + * Returns an array containing all of the result set rows. * + * @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) - { + public function fetchAll( + $fetchMode = Doctrine_Core::FETCH_BOTH, + $columnIndex = null + ) { $event = new Doctrine_Event($this, Doctrine_Event::STMT_FETCHALL, $this->getQuery()); $event->fetchMode = $fetchMode; $event->columnIndex = $columnIndex; $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 +363,10 @@ 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. - * - * @return string returns a single column in the next row of a result set. + * @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 */ public function fetchColumn($columnIndex = 0) { @@ -401,11 +380,10 @@ 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. - * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @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 */ public function fetchObject($className = 'stdClass', $args = array()) { @@ -414,11 +392,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 +407,10 @@ public function getAttribute($attribute) /** * getColumnMeta - * Returns metadata for a column in a result set - * - * @param integer $column The 0-indexed column in the result set. + * Returns metadata for a column in a result set. * - * @return array Associative meta data array with the following structure: + * @param int $column the 0-indexed column in the result set + * @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 +427,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 +451,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 +460,11 @@ 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 +473,12 @@ public function setAttribute($attribute, $value) /** * setFetchMode - * Set the default fetch mode for this statement + * 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) { diff --git a/lib/Doctrine/Connection/UnitOfWork.php b/lib/Doctrine/Connection/UnitOfWork.php index 9627d6d19..fbb0a359a 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,8 @@ * * 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 - * @since 1.0 - * @version $Revision: 7684 $ + * @see www.doctrine-project.org + * * @author Konsta Vesterinen * @author Roman Borschel */ @@ -42,9 +38,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 +47,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 +62,7 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $isValid = true; - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->saveRelatedLocalKeys($record); switch ($state) { @@ -101,12 +94,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 +121,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 +141,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 +157,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 +171,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 +187,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 +205,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 +215,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 +231,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 +240,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 +254,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 +279,36 @@ 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 +319,40 @@ 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 +366,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 +380,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 +394,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 +410,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 +420,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 +434,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 +456,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 +479,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 +498,10 @@ 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 +509,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 +534,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 +547,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 +569,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 +630,14 @@ 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 +645,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 +664,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 +683,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 +699,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 +714,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 +731,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 +741,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 +768,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 +800,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 +831,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 +841,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 +861,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 +874,7 @@ private function _formatDataSet(Doctrine_Record $record) continue; } - if ( ! array_key_exists($fieldName, $array)) { + if (!array_key_exists($fieldName, $array)) { continue; } @@ -915,7 +893,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 +912,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..99ef76188 100644 --- a/lib/Doctrine/Core.php +++ b/lib/Doctrine/Core.php @@ -20,499 +20,501 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision$ + * + * @see www.doctrine-project.org */ 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 +523,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 +533,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 +547,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 +557,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 +581,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 +591,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 +605,6 @@ public static function loadModel($className, $path = null) * naming convention autoloading. * * @param string $directory - * @return void */ public static function setModelsDirectory($directory) { @@ -615,9 +613,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 +623,40 @@ 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); + $it = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($dir), + 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 +664,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 +698,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 +717,18 @@ 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,10 +740,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 + * @param string $models + * @return array $models */ public static function initializeModels($models) { @@ -769,9 +769,7 @@ public static function initializeModels($models) } } - $models = self::filterInvalidModels($models); - - return $models; + return self::filterInvalidModels($models); } /** @@ -779,14 +777,14 @@ 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 +794,10 @@ 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 - * @return boolean + * @param mixed $class Can be a string named after the class, an instance of the class, or an instance of the class reflected + * @return bool */ public static function isValidModelClass($class) { @@ -815,8 +813,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 +823,9 @@ 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 + * @param string $tableName * @return Doctrine_Connection */ public static function getConnectionByTableName($tableName) @@ -839,7 +836,7 @@ public static function getConnectionByTableName($tableName) $table = Doctrine_Core::getTable($name); if ($table->getTableName() == $tableName) { - return $table->getConnection(); + return $table->getConnection(); } } @@ -847,12 +844,12 @@ 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 boolean + * @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 * @throws Exception */ public static function generateModelsFromDb($directory, array $connections = array(), array $options = array()) @@ -864,19 +861,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 +886,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 +901,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 +911,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,7 +921,7 @@ 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 * @return array $sql @@ -959,11 +952,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 +965,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 +975,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 +985,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 +999,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') { @@ -1026,10 +1014,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. - * @return bool true - * @throws new Doctrine_Migration_Exception + * @param string $migrationsPath Path to migrations directory which contains your migration classes + * @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 +1027,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,11 +1040,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 + * @param string $migrationsPath + * @throws new Doctrine_Migration_Exception */ public static function generateMigrationsFromDb($migrationsPath) { @@ -1066,12 +1053,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,12 +1068,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 - * @return array $changes + * @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 +1083,9 @@ 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 + * @param string $componentName * @return Doctrine_Table */ public static function getTable($componentName) @@ -1110,12 +1096,11 @@ 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 + * @param string $target + * @param array $includedDrivers * @throws Doctrine_Exception - * @return void */ public static function compile($target = null, $includedDrivers = array()) { @@ -1124,15 +1109,15 @@ 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 + * @param string $className + * @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 +1126,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 +1143,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 +1152,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 +1165,10 @@ 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 + * @param string $className + * @return bool */ public static function extensionsAutoload($className) { @@ -1192,10 +1177,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 +1194,35 @@ public static function extensionsAutoload($className) } /** - * dumps a given variable + * dumps a given variable. * - * @param mixed $var a variable of any type - * @param boolean $output whether to output the content - * @param string $indent indention string + * @param mixed $var a variable of any type + * @param bool $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..06566cee6 100644 --- a/lib/Doctrine/Data.php +++ b/lib/Doctrine/Data.php @@ -20,23 +20,19 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 2552 $ + * + * @see www.doctrine-project.org */ class Doctrine_Data { /** - * formats + * formats. * * array of formats data can be in * @@ -45,7 +41,7 @@ class Doctrine_Data protected $_formats = array('csv', 'yml', 'xml'); /** - * format + * format. * * the default and current format we are working with * @@ -54,16 +50,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 +68,7 @@ class Doctrine_Data protected $_models = array(); /** - * _exportIndividualFiles + * _exportIndividualFiles. * * whether or not to export data to individual files instead of 1 * @@ -83,12 +79,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 +91,9 @@ public function setFormat($format) } /** - * getFormat + * getFormat. * * Get the current format we are working with - * - * @return void */ public function getFormat() { @@ -108,11 +101,9 @@ public function getFormat() } /** - * getFormats + * getFormats. * * Get array of available formats - * - * @return void */ public function getFormats() { @@ -120,11 +111,9 @@ public function getFormats() } /** - * setDirectory + * setDirectory. * * Set the array/string of directories or yml file paths - * - * @return void */ public function setDirectory($directory) { @@ -132,11 +121,9 @@ public function setDirectory($directory) } /** - * getDirectory + * getDirectory. * * Get directory for dumping/loading data from and to - * - * @return void */ public function getDirectory() { @@ -144,12 +131,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 +143,9 @@ public function setModels($models) } /** - * getModels + * getModels. * * Get the array of specified models to work with - * - * @return void */ public function getModels() { @@ -169,15 +153,16 @@ public function getModels() } /** - * _exportIndividualFiles + * _exportIndividualFiles. * * Set/Get whether or not to export individual files * - * @return bool $_exportIndividualFiles + * @param mixed|null $bool + * @return bool $_exportIndividualFiles */ public function exportIndividualFiles($bool = null) { - if ($bool !== null) { + if (null !== $bool) { $this->_exportIndividualFiles = $bool; } @@ -195,7 +180,7 @@ public function getCharset() } /** - * exportData + * exportData. * * Interface for exporting data to fixtures files from Doctrine models * @@ -203,7 +188,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 +200,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 +219,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 +235,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 +257,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..91a922f28 100644 --- a/lib/Doctrine/Data/Exception.php +++ b/lib/Doctrine/Data/Exception.php @@ -20,15 +20,12 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 2552 $ + * + * @see www.doctrine-project.org */ 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..53da48080 100644 --- a/lib/Doctrine/Data/Export.php +++ b/lib/Doctrine/Data/Export.php @@ -20,23 +20,18 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 2552 $ + * + * @see www.doctrine-project.org */ class Doctrine_Data_Export extends Doctrine_Data { /** - * constructor + * constructor. * - * @param string $directory - * @return void + * @param string $directory */ public function __construct($directory) { @@ -44,18 +39,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 +57,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 +87,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 +97,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 +109,45 @@ 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 +156,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 +170,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 +182,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..d836fc4af 100644 --- a/lib/Doctrine/Data/Import.php +++ b/lib/Doctrine/Data/Import.php @@ -20,69 +20,66 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 2552 $ + * + * @see www.doctrine-project.org */ 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)) { - $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), - RecursiveIteratorIterator::LEAVES_ONLY); + } elseif (is_dir($dir)) { + $it = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($dir), + RecursiveIteratorIterator::LEAVES_ONLY + ); $filesOrdered = array(); foreach ($it as $file) { $filesOrdered[] = $file; @@ -103,15 +100,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 +114,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 +125,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 +148,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 +163,114 @@ 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 Doctrine_Record $record - * @param string $relationName - * @param string $referringRowKey + * @param string $rowKey + * @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 +280,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 +298,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 +323,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 +333,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 +351,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 +373,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..4a82f76f1 100644 --- a/lib/Doctrine/DataDict.php +++ b/lib/Doctrine/DataDict.php @@ -20,14 +20,10 @@ */ /** - * Doctrine_DataDict + * Doctrine_DataDict. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage DataDict - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 1.0 - * @version $Revision: 7490 $ * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) */ @@ -35,20 +31,21 @@ 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..4e4efc3ba 100644 --- a/lib/Doctrine/DataDict/Exception.php +++ b/lib/Doctrine/DataDict/Exception.php @@ -20,15 +20,12 @@ */ /** - * Doctrine_DataDict_Exception + * Doctrine_DataDict_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage DataDict - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..9a641b3b4 100644 --- a/lib/Doctrine/DataDict/Mssql.php +++ b/lib/Doctrine/DataDict/Mssql.php @@ -20,16 +20,12 @@ */ /** - * @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 - * @since 1.0 + * + * @see www.doctrine-project.org */ class Doctrine_DataDict_Mssql extends Doctrine_DataDict { @@ -37,9 +33,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 @@ -52,18 +48,18 @@ class Doctrine_DataDict_Mssql 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($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 +70,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 +98,83 @@ 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 - * @return array containing the various possible types, length, sign, fixed + * @param array $field native field description + * @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 +182,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 +234,16 @@ 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 +253,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..f7b5f4ac5 100644 --- a/lib/Doctrine/DataDict/Mysql.php +++ b/lib/Doctrine/DataDict/Mysql.php @@ -20,101 +20,97 @@ */ /** - * @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 - * @since 1.0 + * + * @see www.doctrine-project.org */ 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 @@ -127,45 +123,48 @@ class Doctrine_DataDict_Mysql 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($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 +173,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 +242,36 @@ 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 +280,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 +303,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 +332,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 +361,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 +376,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 +414,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 +433,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 +455,37 @@ 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 +499,33 @@ 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..00fec49ff 100644 --- a/lib/Doctrine/DataDict/Oracle.php +++ b/lib/Doctrine/DataDict/Oracle.php @@ -20,13 +20,9 @@ */ /** - * @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 - * @since 1.0 + * + * @see www.doctrine-project.org */ class Doctrine_DataDict_Oracle extends Doctrine_DataDict { @@ -34,9 +30,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 +45,18 @@ 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 +65,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 +113,35 @@ 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 - * @return array containing the various possible types, length, sign, fixed + * @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 +150,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 +161,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 +184,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 +221,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..5a47f08c0 100644 --- a/lib/Doctrine/DataDict/Pgsql.php +++ b/lib/Doctrine/DataDict/Pgsql.php @@ -20,327 +20,323 @@ */ /** - * @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 - * @since 1.0 + * + * @see www.doctrine-project.org */ 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 @@ -353,24 +349,24 @@ class Doctrine_DataDict_Pgsql 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.'); } // 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 +376,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 +387,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 +430,32 @@ 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 - * - * @param array $field native field description + * Maps a native array description of a field to a portable Doctrine datatype and length. * + * @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 +464,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 +516,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 +531,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 +598,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 +621,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 @@ -634,50 +637,50 @@ public function getPortableDeclaration(array $field) * 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 - * @return string parsed boolean value + * @param string $value boolean value to be parsed + * @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..d5b7bdf59 100644 --- a/lib/Doctrine/DataDict/Sqlite.php +++ b/lib/Doctrine/DataDict/Sqlite.php @@ -20,14 +20,10 @@ */ /** - * @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 - * @since 1.0 + * + * @see www.doctrine-project.org */ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict { @@ -35,9 +31,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 +46,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 +70,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 +116,22 @@ 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 +145,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 +154,7 @@ public function getPortableDeclaration(array $field) $fixed = null; $type = array(); - if ( ! isset($field['name'])) { + if (!isset($field['name'])) { $field['name'] = ''; } @@ -199,9 +206,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 +217,7 @@ public function getPortableDeclaration(array $field) } elseif (strstr($dbType, 'text')) { $type[] = 'clob'; } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } break; @@ -251,24 +259,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 +290,39 @@ 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' : ''; $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..ef12ffcd3 100644 --- a/lib/Doctrine/Event.php +++ b/lib/Doctrine/Event.php @@ -20,122 +20,119 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision$ + * + * @see www.doctrine-project.org */ 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 +141,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 +206,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 +217,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 +233,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 +246,11 @@ 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 +261,24 @@ 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 - * @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) { - $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 +287,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 +311,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 +322,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 +334,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 +343,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 +356,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..0bc908781 100644 --- a/lib/Doctrine/EventListener.php +++ b/lib/Doctrine/EventListener.php @@ -21,99 +21,143 @@ /** * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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..910cc71e6 100644 --- a/lib/Doctrine/EventListener/Chain.php +++ b/lib/Doctrine/EventListener/Chain.php @@ -22,39 +22,33 @@ /** * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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 +57,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 +80,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 +92,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 +103,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 +114,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 +125,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 +136,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 +147,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 +158,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 +169,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 +180,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 +191,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 +202,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 +213,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 +225,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 +237,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 +249,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 +261,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 +273,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 +285,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 +297,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 +308,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 +332,7 @@ public function preConnect(Doctrine_Event $event) } public function preQuery(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preQuery($event); } @@ -419,7 +346,7 @@ public function postQuery(Doctrine_Event $event) } public function prePrepare(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->prePrepare($event); } @@ -447,7 +374,7 @@ public function postExec(Doctrine_Event $event) } public function preError(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preError($event); } @@ -461,7 +388,7 @@ public function postError(Doctrine_Event $event) } public function preFetch(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preFetch($event); } @@ -475,7 +402,7 @@ public function postFetch(Doctrine_Event $event) } public function preFetchAll(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preFetchAll($event); } @@ -501,4 +428,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..ecc42990f 100644 --- a/lib/Doctrine/EventListener/Exception.php +++ b/lib/Doctrine/EventListener/Exception.php @@ -20,15 +20,12 @@ */ /** - * Doctrine_EventListener_Exception + * Doctrine_EventListener_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage EventListener - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..c3c937949 100644 --- a/lib/Doctrine/EventListener/Interface.php +++ b/lib/Doctrine/EventListener/Interface.php @@ -21,48 +21,55 @@ /** * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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..6cedb2a57 100644 --- a/lib/Doctrine/Exception.php +++ b/lib/Doctrine/Exception.php @@ -20,64 +20,60 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Exception - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 - * - * @return string error message + * @param mixed|null $value + * @return string error message */ public function errorMessage($value = null) { @@ -88,5 +84,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..22d0b60a2 100644 --- a/lib/Doctrine/Export.php +++ b/lib/Doctrine/Export.php @@ -20,39 +20,32 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7653 $ + * + * @see www.doctrine-project.org */ 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 +56,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 +65,21 @@ 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 +87,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 +98,39 @@ 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 - * @return string SQL that is used for dropping an index + * @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 */ 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 +140,10 @@ 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 +152,10 @@ 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 + * @param string $sequenceName name of the sequence to be dropped + * @throws Doctrine_Connection_Exception if something fails at database level */ public function dropSequenceSql($sequenceName) { @@ -180,10 +164,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 +173,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 +183,65 @@ 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 +249,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 +275,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 +291,17 @@ 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 +310,18 @@ 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 +329,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 +347,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 +374,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 +391,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 +425,6 @@ public function createConstraintSql($table, $name, $definition) * 'last_login' => array() * ) * ) - * @return void */ public function createIndex($table, $name, array $definition) { @@ -459,79 +432,79 @@ 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 +517,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 +532,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 +550,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 @@ -665,7 +575,6 @@ public function alterTableSql($name, array $changes, $check = false) * Text value with the default COLLATION for this field. * unique * unique constraint - * * @return string */ public function getFieldDeclarationList(array $fields) @@ -675,6 +584,7 @@ public function getFieldDeclarationList(array $fields) $queryFields[] = $query; } + return implode(', ', $queryFields); } @@ -682,10 +592,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 @@ -710,44 +620,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 +661,67 @@ 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 +733,30 @@ 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 +778,7 @@ public function getIndexFieldDeclarationList(array $fields) $ret[] = $this->conn->quoteIdentifier($definition); } } + return implode(', ', $ret); } @@ -891,8 +793,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 +806,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) * @@ -937,13 +839,12 @@ public function getTemporaryTableQuery() * omitting the ON DELETE or ON UPDATE clause. * * 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 +855,31 @@ 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 +891,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 +902,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 +941,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 +953,9 @@ 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 +966,9 @@ 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 +977,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 +985,13 @@ 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 +1002,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 +1151,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 +1168,38 @@ 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 +1210,18 @@ 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 - * @return array an array of sql strings + * @param Doctrine_Table $table the table in which the generators belong to + * @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 +1237,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 +1245,29 @@ 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. * - * @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 exportTable(Doctrine_Table $table) { @@ -1379,9 +1275,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..1c29cf93c 100644 --- a/lib/Doctrine/Export/Exception.php +++ b/lib/Doctrine/Export/Exception.php @@ -20,15 +20,12 @@ */ /** - * Doctrine_Export_Exception + * Doctrine_Export_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Export - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..448dc36f8 100644 --- a/lib/Doctrine/Export/Mssql.php +++ b/lib/Doctrine/Export/Mssql.php @@ -20,77 +20,73 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7660 $ + * + * @see www.doctrine-project.org */ 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 +99,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 +118,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 +126,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 +139,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 +196,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 +218,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 +238,7 @@ public function alterTable($name, array $changes, $check = false) } } - if ( ! $query && ! $postQueries) { + if (!$query && !$postQueries) { return false; } @@ -318,7 +246,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 +257,93 @@ 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 $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 */ 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 - * - * @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); } // 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 +354,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 +402,50 @@ 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..2bb73ce0c 100644 --- a/lib/Doctrine/Export/Mysql.php +++ b/lib/Doctrine/Export/Mysql.php @@ -20,104 +20,97 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7653 $ + * + * @see www.doctrine-project.org */ 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 + * @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 +125,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 +164,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 +200,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 +223,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 @@ -254,55 +247,52 @@ public function createTableSql($name, array $fields, array $options = array()) * unique constraint * 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 +305,14 @@ 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. - * - * - * 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 + * @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 */ 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 +324,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 +333,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 +376,62 @@ 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 + * 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( + * @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 + * ); + * @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 +443,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 @@ -584,109 +510,103 @@ public function createSequence($sequenceName, $start = 1, array $options = 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 +626,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 +634,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,14 +645,14 @@ public function getIndexFieldDeclarationList(array $fields) } $declFields[] = $fieldString; } + return implode(', ', $declFields); } /** * Returns a character set declaration. * - * @param string $charset A character set - * + * @param string $charset A character set * @return string A character set declaration */ public function getCharsetFieldDeclaration($charset) @@ -743,8 +663,7 @@ public function getCharsetFieldDeclaration($charset) /** * Returns a collation declaration. * - * @param string $collation A collation - * + * @param string $collation A collation * @return string A collation declaration */ public function getCollationFieldDeclaration($collation) @@ -757,63 +676,62 @@ 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..bcee3d2ef 100644 --- a/lib/Doctrine/Export/Oracle.php +++ b/lib/Doctrine/Export/Oracle.php @@ -20,59 +20,53 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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 + * @param string $name name of the database that should be created + * @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 + * @param string $name name of the database that should be dropped + * @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 + * @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 */ 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 +118,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 +130,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 +181,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 +205,14 @@ 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 +224,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 +255,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 +269,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 +295,90 @@ 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 - * - * @param string $table Name of the table we are commenting - * @param string $comment The comment for the 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 * @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 - * - * @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 + * 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 * @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 +391,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 +406,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 +416,108 @@ 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 - * - * @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', - * ); + * 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', + * ); * @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 + * @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..69c74c315 100644 --- a/lib/Doctrine/Export/Pgsql.php +++ b/lib/Doctrine/Export/Pgsql.php @@ -20,46 +20,36 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7680 $ + * + * @see www.doctrine-project.org */ 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 + * @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 +57,20 @@ 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 +82,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 +110,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 +144,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 +161,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 +193,11 @@ 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. - * - * - * 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. + * @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 * @throws Doctrine_Connection_Exception - * @return boolean */ public function alterTable($name, array $changes, $check = false) { @@ -277,90 +205,88 @@ 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. * - * @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', - * ); + * @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 + * @param unknown_type $name * @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 +296,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..1950919fe 100644 --- a/lib/Doctrine/Export/Reporter.php +++ b/lib/Doctrine/Export/Reporter.php @@ -20,15 +20,11 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ class Doctrine_Export_Reporter implements IteratorAggregate { @@ -44,9 +40,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..41252433e 100644 --- a/lib/Doctrine/Export/Schema.php +++ b/lib/Doctrine/Export/Schema.php @@ -20,40 +20,36 @@ */ /** - * Doctrine_Export_Schema - * + * Doctrine_Export_Schema. + * * Used for exporting a schema to a yaml file * - * @package Doctrine - * @subpackage Export - * @link www.doctrine-project.org - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @version $Revision: 1838 $ + * @see www.doctrine-project.org + * * @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 +58,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 +84,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 +95,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..9ace9891a 100644 --- a/lib/Doctrine/Export/Sqlite.php +++ b/lib/Doctrine/Export/Sqlite.php @@ -20,66 +20,60 @@ */ /** - * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * + * @see www.doctrine-project.org */ 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 @@ -98,28 +92,25 @@ public function createDatabase($databaseFile) * ) * ) * @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 +120,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 +135,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 +146,78 @@ public function getIndexFieldDeclarationList(array $fields) } $declFields[] = $fieldString; } + return implode(', ', $declFields); } /** - * 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. * - * @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 +231,20 @@ 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 +256,45 @@ 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', - * ); - * @return boolean + * @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 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 +302,21 @@ 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 +327,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 +336,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 +369,44 @@ 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..9c0eee043 100644 --- a/lib/Doctrine/Expression.php +++ b/lib/Doctrine/Expression.php @@ -22,15 +22,11 @@ /** * 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 - * @since 1.0 - * @version $Revision: 7490 $ + * @see www.doctrine-project.org + * * @author Konsta Vesterinen */ class Doctrine_Expression @@ -42,18 +38,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 +58,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 +75,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 +85,39 @@ 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 + * @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 +126,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 +142,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..fcac1bdd6 100644 --- a/lib/Doctrine/Expression/Driver.php +++ b/lib/Doctrine/Expression/Driver.php @@ -20,14 +20,10 @@ */ /** - * Doctrine_Expression_Driver + * Doctrine_Expression_Driver. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Expression - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 1.0 - * @version $Revision$ * @author Konsta Vesterinen */ class Doctrine_Expression_Driver extends Doctrine_Connection_Module @@ -44,7 +40,7 @@ public function getIdentifiers($columns) /** * regexp - * returns the regular expression operator + * returns the regular expression operator. * * @return string */ @@ -54,66 +50,71 @@ public function regexp() } /** - * Returns the average value of a column + * Returns the average value of a column. * - * @param string $column the column to use - * @return string generated sql including an AVG aggregate function + * @param string $column the column to use + * @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 + * @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 + * @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,85 +129,84 @@ 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.')'; } /** * Returns the remainder of the division operation * $expression1 / $expression2. * - * @param string $expression1 - * @param string $expression2 + * @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 +214,12 @@ 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 +227,25 @@ 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 +261,12 @@ 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 + * @param string $value + * @return string SQL soundex function with given parameter */ public function soundex($value) { @@ -274,41 +274,41 @@ 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 +319,8 @@ public function concat() public function not($expression) { $expression = $this->getIdentifier($expression); - return 'NOT(' . $expression . ')'; + + return 'NOT('.$expression.')'; } /** @@ -330,7 +331,7 @@ 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 */ @@ -340,11 +341,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).')'; } /** @@ -374,7 +375,7 @@ public function add(array $args) */ public function sub(array $args) { - return $this->basicMath('-', $args ); + return $this->basicMath('-', $args); } /** @@ -410,87 +411,93 @@ public function div(array $args) /** * Returns the SQL to check if two values are equal. * - * @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 eq($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' = ' . $value2; + + return $value1.' = '.$value2; } /** * Returns the SQL to check if two values are unequal. * - * @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 neq($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 greater 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 gt($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 greater 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 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 +509,49 @@ 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 + * @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 + * @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'; } /** @@ -554,9 +564,9 @@ public function isNotNull($expression) * http://www.w3schools.com/sql/sql_between.asp. If you want complete database * 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 $expression the value to compare to + * @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 +574,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 +589,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 +617,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 +635,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..6f682698d 100644 --- a/lib/Doctrine/Expression/Exception.php +++ b/lib/Doctrine/Expression/Exception.php @@ -20,15 +20,12 @@ */ /** - * Doctrine_Expression_Exception + * Doctrine_Expression_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Expression - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..48ebda4e3 100644 --- a/lib/Doctrine/Expression/Mock.php +++ b/lib/Doctrine/Expression/Mock.php @@ -21,15 +21,12 @@ /** * Doctrine_Expression_Mock - * Mock driver that is used for testing purposes + * Mock driver that is used for testing purposes. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Expression - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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..2a451bafb 100644 --- a/lib/Doctrine/Expression/Mssql.php +++ b/lib/Doctrine/Expression/Mssql.php @@ -20,14 +20,10 @@ */ /** - * Doctrine_Expression_Mssql + * Doctrine_Expression_Mssql. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Expression - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 1.0 - * @version $Revision: 7490 $ * @author Konsta Vesterinen */ class Doctrine_Expression_Mssql extends Doctrine_Expression_Driver @@ -37,10 +33,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 +49,34 @@ 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. * - * @return string to call a function to get a substring + * @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,15 +86,14 @@ public function guid() } /** - * Returns the length of a text field - * - * @param string $column + * Returns the length of a text field. * + * @param string $column * @return string */ public function length($column) { - return 'LEN (' . $column . ')'; + return 'LEN ('.$column.')'; } /** @@ -121,15 +115,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..0bb4b4635 100644 --- a/lib/Doctrine/Expression/Mysql.php +++ b/lib/Doctrine/Expression/Mysql.php @@ -20,20 +20,16 @@ */ /** - * Doctrine_Expression_Mysql + * Doctrine_Expression_Mysql. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Expression - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +39,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 +49,23 @@ 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 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 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) * @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 +73,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 +89,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 +106,52 @@ 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 + * @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..6d7c82e4b 100644 --- a/lib/Doctrine/Expression/Oracle.php +++ b/lib/Doctrine/Expression/Oracle.php @@ -20,50 +20,46 @@ */ /** - * Doctrine_Expression_Sqlite + * Doctrine_Expression_Sqlite. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Expression - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link 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 +67,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 +83,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 +93,7 @@ public function random() } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -105,4 +101,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..37e529d59 100644 --- a/lib/Doctrine/Expression/Pgsql.php +++ b/lib/Doctrine/Expression/Pgsql.php @@ -20,14 +20,10 @@ */ /** - * Doctrine_Expression_Pgsql + * Doctrine_Expression_Pgsql. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Expression - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org - * @since 1.0 - * @version $Revision: 7685 $ * @author Konsta Vesterinen */ class Doctrine_Expression_Pgsql extends Doctrine_Expression_Driver @@ -54,7 +50,7 @@ public function md5($column) { $column = $this->getIdentifier($column); - return 'MD5(' . $column . ')'; + return 'MD5('.$column.')'; } /** @@ -62,73 +58,77 @@ 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 + * @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.')'; } /** * PostgreSQLs DATE_PART( ,