diff --git a/lib/Doctrine/Access.php b/lib/Doctrine/Access.php index f066e7f4a..91ca06d9e 100644 --- a/lib/Doctrine/Access.php +++ b/lib/Doctrine/Access.php @@ -20,23 +20,25 @@ */ /** - * Provides array access and property overload interface for Doctrine subclasses + * Provides array access and property overload interface for Doctrine subclasses. * - * @package Doctrine - * @subpackage Access * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Access extends Doctrine_Locator_Injectable implements ArrayAccess { /** - * Set an entire aray to the data + * Set an entire aray to the data. + * + * @param array $array An array of key => value pairs * - * @param array $array An array of key => value pairs - * @return Doctrine_Access + * @return Doctrine_Access */ public function setArray(array $array) { @@ -48,12 +50,9 @@ public function setArray(array $array) } /** - * Set key and value to data + * Set key and value to data. * * @see set, offsetSet - * @param $name - * @param $value - * @return void */ public function __set($name, $value) { @@ -61,11 +60,9 @@ public function __set($name, $value) } /** - * Get key from data + * Get key from data. * * @see get, offsetGet - * @param mixed $name - * @return mixed */ public function __get($name) { @@ -73,10 +70,11 @@ public function __get($name) } /** - * Check if key exists in data + * Check if key exists in data. * - * @param string $name - * @return boolean whether or not this object contains $name + * @param string $name + * + * @return bool whether or not this object contains $name */ public function __isset($name) { @@ -84,12 +82,11 @@ public function __isset($name) } /** - * Remove key from data + * Remove key from data. * - * @param string $name - * @return void + * @param string $name */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function __unset($name) { return $this->remove($name); @@ -98,16 +95,13 @@ public function __unset($name) /** * @return bool */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetExists($offset) { return $this->contains($offset); } - /** - * @return mixed - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetGet($offset) { // array notation with no index was causing 'undefined variable: $offset' notices in php7, @@ -116,84 +110,78 @@ public function offsetGet($offset) if (!isset($offset)) { return $this->get(null); } + return $this->get($offset); } - /** - * @return void - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetSet($offset, $value) { - if ( ! isset($offset)) { + if (!isset($offset)) { $this->add($value); } else { $this->set($offset, $value); } } - /** - * @return void - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetUnset($offset) { $this->remove($offset); } /** - * Remove the element with the specified offset + * Remove the element with the specified offset. * * @param mixed $offset The offset to remove + * * @return bool True if removed otherwise false */ public function remove($offset) { - throw new Doctrine_Exception('Remove is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Remove is not supported for '.get_class($this)); } /** - * Return the element with the specified offset + * Return the element with the specified offset. * - * @param mixed $offset The offset to return - * @return mixed + * @param mixed $offset The offset to return */ public function get($offset) { - throw new Doctrine_Exception('Get is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Get is not supported for '.get_class($this)); } /** - * Set the offset to the value + * Set the offset to the value. * * @param mixed $offset The offset to set - * @param mixed $value The value to set the offset to - * + * @param mixed $value The value to set the offset to */ public function set($offset, $value) { - throw new Doctrine_Exception('Set is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Set is not supported for '.get_class($this)); } /** - * Check if the specified offset exists + * Check if the specified offset exists. * * @param mixed $offset The offset to check - * @return boolean True if exists otherwise false + * + * @return bool True if exists otherwise false */ public function contains($offset) { - throw new Doctrine_Exception('Contains is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Contains is not supported for '.get_class($this)); } /** - * Add the value + * Add the value. * * @param mixed $value The value to add - * @return void */ public function add($value) { - throw new Doctrine_Exception('Add is not supported for ' . get_class($this)); + throw new Doctrine_Exception('Add is not supported for '.get_class($this)); } } diff --git a/lib/Doctrine/Adapter/Exception.php b/lib/Doctrine/Adapter/Exception.php index 9fed8319c..f13ef4860 100644 --- a/lib/Doctrine/Adapter/Exception.php +++ b/lib/Doctrine/Adapter/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Adapter exception class + * Doctrine_Adapter exception class. * - * @package Doctrine - * @subpackage Adapter * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Adapter_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Adapter/Interface.php b/lib/Doctrine/Adapter/Interface.php index 73c322f1e..b79c46701 100644 --- a/lib/Doctrine/Adapter/Interface.php +++ b/lib/Doctrine/Adapter/Interface.php @@ -20,28 +20,39 @@ */ /** - * This adapter interface should be implemented by all custom adapters + * This adapter interface should be implemented by all custom adapters. * * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Adapter - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ interface Doctrine_Adapter_Interface { public function prepare($prepareString); + public function query($queryString); + public function quote($input); + public function exec($statement); + public function lastInsertId(); + public function beginTransaction(); + public function commit(); + public function rollBack(); + public function errorCode(); + public function errorInfo(); + public function setAttribute($attribute, $value); + public function getAttribute($attribute); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Adapter/Mock.php b/lib/Doctrine/Adapter/Mock.php index fddce61df..c1640d9fb 100644 --- a/lib/Doctrine/Adapter/Mock.php +++ b/lib/Doctrine/Adapter/Mock.php @@ -22,53 +22,52 @@ /** * Doctrine mock connection adapter. This class is used for special testing purposes. * - * @package Doctrine - * @subpackage Adapter * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Adapter_Mock implements Doctrine_Adapter_Interface, Countable { /** - * Name of the dbms to mock + * Name of the dbms to mock. * * @var string */ private $_name; /** - * Array of queries executed through this instance of the mock adapter + * Array of queries executed through this instance of the mock adapter. * - * @var array $queries + * @var array */ private $_queries = array(); /** - * Array of exceptions thrown + * Array of exceptions thrown. * - * @var array $exceptions + * @var array */ private $_exception = array(); /** - * Bool true/false variable for whether or not the last insert failed + * Bool true/false variable for whether or not the last insert failed. * - * @var boolean $lastInsertIdFail + * @var bool */ private $_lastInsertIdFail = false; /** - * Doctrine mock adapter constructor + * Doctrine mock adapter constructor. * * * $conn = new Doctrine_Adapter_Mock('mysql'); * * - * @param string $name - * @return void + * @param string $name */ public function __construct($name = null) { @@ -76,7 +75,7 @@ public function __construct($name = null) } /** - * Get the name of the dbms used in this instance of the mock adapter + * Get the name of the dbms used in this instance of the mock adapter. * * @return string $name Name of the dbms */ @@ -86,7 +85,7 @@ public function getName() } /** - * Pop the last executed query from the array of executed queries and return it + * Pop the last executed query from the array of executed queries and return it. * * @return string $sql Last executed sql string */ @@ -96,12 +95,11 @@ public function pop() } /** - * Force an exception in to the array of exceptions + * Force an exception in to the array of exceptions. * - * @param string $name Name of exception - * @param string $message Message for the exception - * @param integer $code Code of the exception - * @return void + * @param string $name Name of exception + * @param string $message Message for the exception + * @param int $code Code of the exception */ public function forceException($name, $message = '', $code = 0) { @@ -109,9 +107,10 @@ public function forceException($name, $message = '', $code = 0) } /** - * Prepare a query statement + * Prepare a query statement. + * + * @param string $query Query to prepare * - * @param string $query Query to prepare * @return Doctrine_Adapter_Statement_Mock $mock Mock prepared statement */ public function prepare($query) @@ -123,10 +122,9 @@ public function prepare($query) } /** - * Add query to the stack of executed queries + * Add query to the stack of executed queries. * - * @param string $query - * @return void + * @param string $query */ public function addQuery($query) { @@ -134,18 +132,19 @@ public function addQuery($query) } /** - * Fake the execution of query and add it to the stack of executed queries + * Fake the execution of query and add it to the stack of executed queries. + * + * @param string $query * - * @param string $query * @return Doctrine_Adapter_Statement_Mock $stmt */ public function query($query) { $this->_queries[] = $query; - $e = $this->_exception; + $e = $this->_exception; - if ( ! empty($e)) { + if (!empty($e)) { $name = $e[0]; $this->_exception = array(); @@ -160,7 +159,7 @@ public function query($query) } /** - * Get all the executed queries + * Get all the executed queries. * * @return array $queries Array of all executed queries */ @@ -170,29 +169,29 @@ public function getAll() } /** - * Quote a value for the dbms + * Quote a value for the dbms. + * + * @param string $input * - * @param string $input * @return string $quoted */ public function quote($input) { - return "'" . addslashes($input) . "'"; + return "'".addslashes($input)."'"; } /** - * Execute a raw sql statement + * Execute a raw sql statement. * - * @param string $statement - * @return void + * @param string $statement */ public function exec($statement) { $this->_queries[] = $statement; - $e = $this->_exception; + $e = $this->_exception; - if ( ! empty($e)) { + if (!empty($e)) { $name = $e[0]; $this->_exception = array(); @@ -204,10 +203,9 @@ public function exec($statement) } /** - * Force last insert to be failed + * Force last insert to be failed. * - * @param boolean $fail - * @return void + * @param bool $fail */ public function forceLastInsertIdFail($fail = true) { @@ -219,35 +217,33 @@ public function forceLastInsertIdFail($fail = true) } /** - * Get the id of the last inserted record + * Get the id of the last inserted record. * - * @return integer $id + * @return int $id */ public function lastInsertId() { $this->_queries[] = 'LAST_INSERT_ID()'; if ($this->_lastInsertIdFail) { return null; - } else { - return 1; } + + return 1; } /** - * Get the number of queries executed + * Get the number of queries executed. * - * @return integer $count + * @return int $count */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_queries); } /** - * Begin a transaction - * - * @return void + * Begin a transaction. */ public function beginTransaction() { @@ -255,9 +251,7 @@ public function beginTransaction() } /** - * Commit a transaction - * - * @return void + * Commit a transaction. */ public function commit() { @@ -265,9 +259,7 @@ public function commit() } /** - * Rollback a transaction - * - * @return void + * Rollback a transaction. */ public function rollBack() { @@ -276,20 +268,24 @@ public function rollBack() public function getAttribute($attribute) { - if ($attribute == Doctrine_Core::ATTR_DRIVER_NAME) { + if (Doctrine_Core::ATTR_DRIVER_NAME == $attribute) { return strtolower($this->_name); } } public function errorCode() - { } + { + } public function errorInfo() - { } + { + } public function setAttribute($attribute, $value) - { } + { + } public function sqliteCreateFunction() - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Adapter/Oracle.php b/lib/Doctrine/Adapter/Oracle.php index a820bec0c..40c014f88 100644 --- a/lib/Doctrine/Adapter/Oracle.php +++ b/lib/Doctrine/Adapter/Oracle.php @@ -20,34 +20,32 @@ */ /** - * Custom Doctrine connection adapter for oracle + * Custom Doctrine connection adapter for oracle. * - * @package Doctrine - * @subpackage Adapter * @author Konsta Vesterinen * @author vadik56 * @author Miloslav Kmet * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ - class Doctrine_Adapter_Oracle implements Doctrine_Adapter_Interface { /** - * execution mode + * execution mode. */ protected $executeMode = OCI_COMMIT_ON_SUCCESS; /** - * Resource representing connection to database + * Resource representing connection to database. */ protected $connection = false; - - protected $attributes = array(Doctrine_Core::ATTR_DRIVER_NAME => "oci8", - Doctrine_Core::ATTR_ERRMODE => Doctrine_Core::ERRMODE_SILENT); + protected $attributes = array(Doctrine_Core::ATTR_DRIVER_NAME => 'oci8', + Doctrine_Core::ATTR_ERRMODE => Doctrine_Core::ERRMODE_SILENT); /** * User-provided configuration. @@ -62,15 +60,15 @@ class Doctrine_Adapter_Oracle implements Doctrine_Adapter_Interface * @var array */ protected $config = array( - 'dbname' => null, - 'username' => null, - 'password' => null, - 'charset' => null, - 'persistent' => false + 'dbname' => null, + 'username' => null, + 'password' => null, + 'charset' => null, + 'persistent' => false, ); /** - * Doctrine Oracle adapter constructor + * Doctrine Oracle adapter constructor. * * * $conn = new Doctrine_Adapter_Oracle(array('dbname'=>'db','username'=>'usr','password'=>'pass')); @@ -82,17 +80,16 @@ class Doctrine_Adapter_Oracle implements Doctrine_Adapter_Interface * Doctrine_Manager::connection(array('oracle:dbname=SID;charset=NLS_CHARACTERSET;persistent=true','usr', 'pass'),"doctrine_connection_name") * * - * @param string $name - * @return void + * @param mixed|null $username + * @param mixed|null $password */ public function __construct($config = array(), $username = null, $password = null) { - if (is_string($config)) - { - $config = str_replace("oracle:","",$config); - $parts = explode(";", $config); - foreach($parts as $part) { - $e = explode("=", $part); + if (is_string($config)) { + $config = str_replace('oracle:', '', $config); + $parts = explode(';', $config); + foreach ($parts as $part) { + $e = explode('=', $part); $key = array_shift($e); $this->config[$key] = implode('=', $e); } @@ -104,54 +101,53 @@ public function __construct($config = array(), $username = null, $password = nul $this->config['password'] = $password; } } else { - if ( ! isset($config['password']) || ! isset($config['username'])) { + if (!isset($config['password']) || !isset($config['username'])) { throw new Doctrine_Adapter_Exception('config array must have at least a username and a password'); } $this->config['username'] = $config['username']; $this->config['password'] = $config['password']; - $this->config['dbname'] = $config['dbname']; - - if (isset($config['charset'])) { - $this->config['charset'] = $config['charset']; - } - - if (isset($config['persistent'])) { - $this->config['persistent'] = $config['persistent']; + $this->config['dbname'] = $config['dbname']; + + if (isset($config['charset'])) { + $this->config['charset'] = $config['charset']; } - } + if (isset($config['persistent'])) { + $this->config['persistent'] = $config['persistent']; + } + } - if ($this->config['persistent'] == 'true'){ - $this->connection = @oci_pconnect($this->config['username'], $this->config['password'], - $this->config['dbname'], $this->config['charset']); - } else { - $this->connection = @oci_new_connect($this->config['username'], $this->config['password'], - $this->config['dbname'], $this->config['charset']); + if ('true' == $this->config['persistent']) { + $this->connection = @oci_pconnect($this->config['username'], $this->config['password'], + $this->config['dbname'], $this->config['charset']); + } else { + $this->connection = @oci_new_connect($this->config['username'], $this->config['password'], + $this->config['dbname'], $this->config['charset']); } - if ($this->connection === false) { + if (false === $this->connection) { throw new Doctrine_Adapter_Exception(sprintf("Unable to Connect to :'%s' as '%s'", $this->config['dbname'], $this->config['username'])); } } /** - * Prepare a query statement + * Prepare a query statement. * * @param string $query Query to prepare + * * @return Doctrine_Adapter_Statement_Oracle $stmt prepared statement */ public function prepare($query) { - $stmt = new Doctrine_Adapter_Statement_Oracle($this, $query, $this->executeMode); - - return $stmt; + return new Doctrine_Adapter_Statement_Oracle($this, $query, $this->executeMode); } /** - * Execute query and return results as statement object + * Execute query and return results as statement object. * * @param string $query + * * @return Doctrine_Adapter_Statement_Oracle $stmt */ public function query($query) @@ -163,56 +159,54 @@ public function query($query) } /** - * Quote a value for the dbms + * Quote a value for the dbms. * * @param string $input + * * @return string $quoted */ public function quote($input) { - return "'" . str_replace("'","''",$input) . "'"; + return "'".str_replace("'", "''", $input)."'"; } /** - * Execute a raw sql statement + * Execute a raw sql statement. * * @param string $statement - * @return void */ public function exec($statement) { $stmt = new Doctrine_Adapter_Statement_Oracle($this, $statement, $this->executeMode); $stmt->execute(); - $count = $stmt->rowCount(); - return $count; + return $stmt->rowCount(); } /** - * Get the id of the last inserted record + * Get the id of the last inserted record. * - * @return integer $id + * @return int $id */ public function lastInsertId() { - throw new Doctrine_Adapter_Exception("unsupported"); + throw new Doctrine_Adapter_Exception('unsupported'); } /** - * Begin a transaction + * Begin a transaction. * - * @return boolean + * @return bool */ public function beginTransaction() { - $this->executeMode = OCI_DEFAULT; - return true; + $this->executeMode = OCI_DEFAULT; + + return true; } /** - * Commit a transaction - * - * @return void + * Commit a transaction. */ public function commit() { @@ -220,9 +214,9 @@ public function commit() } /** - * Rollback a transaction + * Rollback a transaction. * - * @return boolean + * @return bool */ public function rollBack() { @@ -230,39 +224,43 @@ public function rollBack() } /** - * Set connection attribute + * Set connection attribute. + * + * @param int $attribute + * @param mixed $value the value of given attribute * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value) { switch ($attribute) { case Doctrine_Core::ATTR_DRIVER_NAME: - //TODO throw an error since driver name can not be changed + // TODO throw an error since driver name can not be changed case Doctrine_Core::ATTR_ERRMODE: - break; + break; case Doctrine_Core::ATTR_CASE: - if ($value == Doctrine_Core::CASE_NATURAL) { + if (Doctrine_Core::CASE_NATURAL == $value) { break; - } else { - throw new Doctrine_Adapter_Exception("Unsupported Option for ATTR_CASE: $value"); } + throw new Doctrine_Adapter_Exception("Unsupported Option for ATTR_CASE: {$value}"); default: - throw new Doctrine_Adapter_Exception("Unsupported Attribute: $attribute"); + throw new Doctrine_Adapter_Exception("Unsupported Attribute: {$attribute}"); + return false; } $this->attributes[$attribute] = $value; + return true; } /** - * Retrieve a statement attribute + * Retrieve a statement attribute. + * + * @param int $attribute * - * @param integer $attribute * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute) { @@ -270,7 +268,7 @@ public function getAttribute($attribute) } /** - * Returns established OCI connection handler + * Returns established OCI connection handler. * * @return resource OCI connection handler */ @@ -278,15 +276,15 @@ public function getConnection() { return $this->connection; } - + /** - * Returns current user name - * + * Returns current user name. + * * @return string current user name */ public function getUserName() { - return $this->config['username']; + return $this->config['username']; } public function errorCode() @@ -296,6 +294,7 @@ public function errorCode() } else { $error = @oci_error(); } + return $error['code']; } @@ -306,14 +305,15 @@ public function errorInfo() } else { $error = @oci_error(); } + return $error['message']; } - public function __destruct() - { - if (is_resource($this->connection)) { - @oci_rollback($this->connection); - @oci_close($this->connection); - } + public function __destruct() + { + if (is_resource($this->connection)) { + @oci_rollback($this->connection); + @oci_close($this->connection); + } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Adapter/Statement.php b/lib/Doctrine/Adapter/Statement.php index 19cf96d9c..e4197c678 100644 --- a/lib/Doctrine/Adapter/Statement.php +++ b/lib/Doctrine/Adapter/Statement.php @@ -20,112 +20,85 @@ */ /** - * Doctrine_Adapter_Statement + * Doctrine_Adapter_Statement. * * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Adapter - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ abstract class Doctrine_Adapter_Statement { /** - * bindValue + * bindValue. * - * @param string $no - * @param string $value - * @return void + * @param string $no + * @param string $value */ public function bindValue($no, $value) - { } + { + } /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. - * - * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for - * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value - * specifies the row to fetch relative to the cursor position before - * Doctrine_Adapter_Statement_Interface->fetch() was called. - * - * @return mixed */ public function fetch() - { } + { + } /** - * nextRowSet - * - * @return void + * nextRowSet. */ public function nextRowset() - { } + { + } /** - * execute() - * - * @return void + * execute(). */ public function execute() - { } + { + } /** - * errorCode - * - * @return void + * errorCode. */ public function errorCode() - { } + { + } /** - * errorInfo - * - * @return void + * errorInfo. */ public function errorInfo() - { } + { + } /** - * rowCount - * - * @return void + * rowCount. */ public function rowCount() - { } + { + } /** - * setFetchMode + * setFetchMode. * - * @param string $mode - * @return void + * @param string $mode */ public function setFetchMode($mode) - { } + { + } /** - * columnCount - * - * @return void + * columnCount. */ public function columnCount() - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Adapter/Statement/Interface.php b/lib/Doctrine/Adapter/Statement/Interface.php index e35fd5687..885f316fe 100644 --- a/lib/Doctrine/Adapter/Statement/Interface.php +++ b/lib/Doctrine/Adapter/Statement/Interface.php @@ -20,107 +20,103 @@ */ /** - * Interface for Doctrine adapter statements + * Interface for Doctrine adapter statements. * * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Adapter - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ interface Doctrine_Adapter_Statement_Interface { /** - * Bind a column to a PHP variable - * - * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. - * If using the column name, be aware that the name should match - * the case of the column, as returned by the driver. - * @param string $param Name of the PHP variable to which the column will be bound. - * @param integer $type Data type of the parameter, specified by the Doctrine_Core::PARAM_* constants. - * @return boolean Returns TRUE on success or FALSE on failure + * Bind a column to a PHP variable. + * + * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. + * If using the column name, be aware that the name should match + * the case of the column, as returned by the driver. + * @param string $param name of the PHP variable to which the column will be bound + * @param int $type data type of the parameter, specified by the Doctrine_Core::PARAM_* constants + * + * @return bool Returns TRUE on success or FALSE on failure */ public function bindColumn($column, $param, $type = null); /** - * Binds a value to a corresponding named or question mark + * Binds a value to a corresponding named or question mark * placeholder in the SQL statement that was use to prepare the statement. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter - * - * @param mixed $value The value to bind to the parameter. - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. + * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, + * this will be a parameter name of the form :name. For a prepared statement + * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $value the value to bind to the parameter + * @param int $type explicit data type for the parameter using the Doctrine_Core::PARAM_* constants * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindValue($param, $value, $type = null); /** - * Binds a PHP variable to a corresponding named or question mark placeholder in the + * Binds a PHP variable to a corresponding named or question mark placeholder in the * SQL statement that was use to prepare the statement. Unlike Doctrine_Adapter_Statement_Interface->bindValue(), - * the variable is bound as a reference and will only be evaluated at the time + * the variable is bound as a reference and will only be evaluated at the time * that Doctrine_Adapter_Statement_Interface->execute() is called. * - * Most parameters are input parameters, that is, parameters that are - * used in a read-only fashion to build up the query. Some drivers support the invocation + * Most parameters are input parameters, that is, parameters that are + * used in a read-only fashion to build up the query. Some drivers support the invocation * of stored procedures that return data as output parameters, and some also as input/output * parameters that both send in data and are updated to receive it. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $variable name of the PHP variable to bind to the SQL statement parameter + * @param int $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return + * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the + * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. + * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter + * from a stored procedure, you must explicitly set the length. * - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. - * - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return - * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the - * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. - * - * @param integer $length Length of the data type. To indicate that a parameter is an OUT parameter - * from a stored procedure, you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array()); /** * Closes the cursor, enabling the statement to be executed again. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function closeCursor(); - /** - * Returns the number of columns in the result set + /** + * Returns the number of columns in the result set. * - * @return integer Returns the number of columns in the result set represented - * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, - * this method should return 0. + * @return int Returns the number of columns in the result set represented + * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, + * this method should return 0. */ public function columnCount(); /** - * Fetch the SQLSTATE associated with the last operation on the statement handle + * Fetch the SQLSTATE associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorCode() - * @return string error code string + * + * @return string error code string */ public function errorCode(); /** - * Fetch extended error information associated with the last operation on the statement handle + * Fetch extended error information associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorInfo() - * @return array error info array + * + * @return array error info array */ public function errorInfo(); /** - * Executes a prepared statement + * Executes a prepared statement. * * If the prepared statement included parameter markers, you must either: * call PDOStatement->bindParam() to bind PHP variables to the parameter markers: @@ -128,53 +124,47 @@ public function errorInfo(); * if any, of their associated parameter markers or pass an array of input-only * parameter values * + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed * - * @param array $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = null); /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. - * - * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for - * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value - * specifies the row to fetch relative to the cursor position before - * Doctrine_Adapter_Statement_Interface->fetch() was called. * - * @return mixed + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH + * @param int $cursorOrientation For a PDOStatement object representing a scrollable cursor, + * this value determines which row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to + * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your + * Doctrine_Adapter_Statement_Interface object, + * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you + * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). + * @param int $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the + * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies + * the absolute number of the row in the result set that shall be fetched. + * + * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for + * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value + * specifies the row to fetch relative to the cursor position before + * Doctrine_Adapter_Statement_Interface->fetch() was called. */ public function fetch($fetchStyle = Doctrine_Core::FETCH_BOTH, - $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, - $cursorOffset = null); + $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, + $cursorOffset = null); /** - * Returns an array containing all of the result set rows + * Returns an array containing all of the result set rows. * - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is - * Doctrine_Core::FETCH_COLUMN. Defaults to 0. + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH * * @return array */ @@ -184,43 +174,45 @@ public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH); * Returns a single column from the next row of a * result set or FALSE if there are no more rows. * - * @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no - * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() - * fetches the first column. + * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no + * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() + * fetches the first column. * - * @return string returns a single column in the next row of a result set. + * @return string returns a single column in the next row of a result set */ public function fetchColumn($columnIndex = 0); /** * Fetches the next row and returns it as an object. * - * Fetches the next row and returns it as an object. This function is an alternative to + * Fetches the next row and returns it as an object. This function is an alternative to * Doctrine_Adapter_Statement_Interface->fetch() with Doctrine_Core::FETCH_CLASS or Doctrine_Core::FETCH_OBJ style. * - * @param string $className Name of the created class, defaults to stdClass. - * @param array $args Elements of this array are passed to the constructor. + * @param string $className name of the created class, defaults to stdClass + * @param array $args elements of this array are passed to the constructor * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @return mixed an instance of the required class with property names that correspond + * to the column names or FALSE in case of an error */ public function fetchObject($className = 'stdClass', $args = array()); /** - * Retrieve a statement attribute + * Retrieve a statement attribute. + * + * @param int $attribute * - * @param integer $attribute * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute); /** - * Returns metadata for a column in a result set + * Returns metadata for a column in a result set. * - * @param integer $column The 0-indexed column in the result set. + * @param int $column the 0-indexed column in the result set * - * @return array Associative meta data array with the following structure: + * @return array Associative meta data array with the following structure: * * native_type The PHP native type used to represent the column value. * driver:decl_ type The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta(). @@ -233,44 +225,48 @@ public function getAttribute($attribute); public function getColumnMeta($column); /** - * Advances to the next rowset in a multi-rowset statement handle - * - * Some database servers support stored procedures that return more than one rowset - * (also known as a result set). The nextRowset() method enables you to access the second - * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a + * Advances to the next rowset in a multi-rowset statement handle. + * + * Some database servers support stored procedures that return more than one rowset + * (also known as a result set). The nextRowset() method enables you to access the second + * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a * different set of columns from the preceding rowset. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function nextRowset(); /** - * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement + * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement * executed by the corresponding object. * - * If the last SQL statement executed by the associated Statement object was a SELECT statement, - * some databases may return the number of rows returned by that statement. However, - * this behaviour is not guaranteed for all databases and should not be + * If the last SQL statement executed by the associated Statement object was a SELECT statement, + * some databases may return the number of rows returned by that statement. However, + * this behaviour is not guaranteed for all databases and should not be * relied on for portable applications. * - * @return integer Returns the number of rows. + * @return int returns the number of rows */ public function rowCount(); /** - * Set a statement attribute + * Set a statement attribute. * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @param int $attribute + * @param mixed $value the value of given attribute + * + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value); /** - * Set the default fetch mode for this statement + * Set the default fetch mode for this statement. + * + * @param int $mode the fetch mode must be one of the Doctrine_Core::FETCH_* constants + * @param mixed|null $arg1 + * @param mixed|null $arg2 * - * @param integer $mode The fetch mode must be one of the Doctrine_Core::FETCH_* constants. - * @return boolean Returns 1 on success or FALSE on failure. + * @return bool returns 1 on success or FALSE on failure */ public function setFetchMode($mode, $arg1 = null, $arg2 = null); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Adapter/Statement/Mock.php b/lib/Doctrine/Adapter/Statement/Mock.php index 3b7a2ac49..4891870fa 100644 --- a/lib/Doctrine/Adapter/Statement/Mock.php +++ b/lib/Doctrine/Adapter/Statement/Mock.php @@ -20,77 +20,79 @@ */ /** - * Mock connection adapter statement class. Used for special testing purposes + * Mock connection adapter statement class. Used for special testing purposes. * - * @package Doctrine - * @subpackage Adapter * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Adapter_Statement_Mock implements Doctrine_Adapter_Statement_Interface { /** - * Variable which stores instance of Doctrine_Adapter_Mock + * Variable which stores instance of Doctrine_Adapter_Mock. * * @var Doctrine_Adapter_Mock */ private $_mock; /** - * queryString + * queryString. * * @var string */ public $queryString; /** - * Constructor for mock adapter statements. Accepts instance of Doctrine_Adapter_Mock + * Constructor for mock adapter statements. Accepts instance of Doctrine_Adapter_Mock. * * @param Doctrine_Adapter_Mock $mock */ public function __construct($mock) { - $this->_mock = $mock; + $this->_mock = $mock; } /** - * bindColumn + * bindColumn. * * Bind a column to a PHP variable * - * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. - * If using the column name, be aware that the name should match - * the case of the column, as returned by the driver. - * @param string $param Name of the PHP variable to which the column will be bound. - * @param integer $type Data type of the parameter, specified by the Doctrine_Core::PARAM_* constants. - * @return boolean Returns TRUE on success or FALSE on failure + * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. + * If using the column name, be aware that the name should match + * the case of the column, as returned by the driver. + * @param string $param name of the PHP variable to which the column will be bound + * @param int $type data type of the parameter, specified by the Doctrine_Core::PARAM_* constants + * + * @return bool Returns TRUE on success or FALSE on failure */ public function bindColumn($column, $param, $type = null) - { } + { + } /** - * bindValue + * bindValue. * * Binds a value to a corresponding named or question mark * placeholder in the SQL statement that was use to prepare the statement. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter - * - * @param mixed $value The value to bind to the parameter. - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. + * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, + * this will be a parameter name of the form :name. For a prepared statement + * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $value the value to bind to the parameter + * @param int $type explicit data type for the parameter using the Doctrine_Core::PARAM_* constants * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindValue($param, $value, $type = null) - { } + { + } /** - * bindParam + * bindParam. * * Binds a PHP variable to a corresponding named or question mark placeholder in the * SQL statement that was use to prepare the statement. Unlike Doctrine_Adapter_Statement_Interface->bindValue(), @@ -102,32 +104,25 @@ public function bindValue($param, $value, $type = null) * of stored procedures that return data as output parameters, and some also as input/output * parameters that both send in data and are updated to receive it. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $variable name of the PHP variable to bind to the SQL statement parameter + * @param int $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return + * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the + * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. + * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter + * from a stored procedure, you must explicitly set the length. * - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. - * - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return - * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the - * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. - * - * @param integer $length Length of the data type. To indicate that a parameter is an OUT parameter - * from a stored procedure, you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array()) { - } /** - * closeCursor + * closeCursor. * * Closes the cursor, enabling the statement to be executed again. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function closeCursor() { @@ -135,13 +130,13 @@ public function closeCursor() } /** - * columnCount + * columnCount. * * Returns the number of columns in the result set * - * @return integer Returns the number of columns in the result set represented - * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, - * this method should return 0. + * @return int Returns the number of columns in the result set represented + * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, + * this method should return 0. */ public function columnCount() { @@ -149,12 +144,13 @@ public function columnCount() } /** - * errorCode + * errorCode. * * Fetch the SQLSTATE associated with the last operation on the statement handle * * @see Doctrine_Adapter_Interface::errorCode() - * @return string error code string + * + * @return string error code string */ public function errorCode() { @@ -162,12 +158,13 @@ public function errorCode() } /** - * errorInfo + * errorInfo. * * Fetch extended error information associated with the last operation on the statement handle * * @see Doctrine_Adapter_Interface::errorInfo() - * @return array error info array + * + * @return array error info array */ public function errorInfo() { @@ -175,51 +172,41 @@ public function errorInfo() } /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. + * + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH + * @param int $cursorOrientation For a PDOStatement object representing a scrollable cursor, + * this value determines which row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to + * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your + * Doctrine_Adapter_Statement_Interface object, + * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you + * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). + * @param int $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the + * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies + * the absolute number of the row in the result set that shall be fetched. * * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value * specifies the row to fetch relative to the cursor position before * Doctrine_Adapter_Statement_Interface->fetch() was called. - * - * @return mixed */ public function fetch($fetchStyle = Doctrine_Core::FETCH_BOTH, - $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, - $cursorOffset = null) + $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, + $cursorOffset = null) { return array(); } /** - * fetchAll + * fetchAll. * * Returns an array containing all of the result set rows * - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is - * Doctrine_Core::FETCH_COLUMN. Defaults to 0. - * * @return array */ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH) @@ -228,7 +215,7 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH) } /** - * execute + * execute. * * Executes a prepared statement * @@ -238,30 +225,31 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH) * if any, of their associated parameter markers or pass an array of input-only * parameter values * + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed * - * @param array $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = null) { if (is_object($this->_mock)) { $this->_mock->addQuery($this->queryString); } + return true; } /** - * fetchColumn + * fetchColumn. * * Returns a single column from the next row of a * result set or FALSE if there are no more rows. * - * @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no - * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() - * fetches the first column. + * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no + * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() + * fetches the first column. * - * @return string returns a single column in the next row of a result set. + * @return string returns a single column in the next row of a result set */ public function fetchColumn($columnIndex = 0) { @@ -269,18 +257,18 @@ public function fetchColumn($columnIndex = 0) } /** - * fetchObject + * fetchObject. * * Fetches the next row and returns it as an object. * * Fetches the next row and returns it as an object. This function is an alternative to * Doctrine_Adapter_Statement_Interface->fetch() with Doctrine_Core::FETCH_CLASS or Doctrine_Core::FETCH_OBJ style. * - * @param string $className Name of the created class, defaults to stdClass. - * @param array $args Elements of this array are passed to the constructor. + * @param string $className name of the created class, defaults to stdClass + * @param array $args elements of this array are passed to the constructor * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @return mixed an instance of the required class with property names that correspond + * to the column names or FALSE in case of an error */ public function fetchObject($className = 'stdClass', $args = array()) { @@ -288,7 +276,7 @@ public function fetchObject($className = 'stdClass', $args = array()) } /** - * nextRowset + * nextRowset. * * Advances to the next rowset in a multi-rowset statement handle * @@ -297,7 +285,7 @@ public function fetchObject($className = 'stdClass', $args = array()) * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a * different set of columns from the preceding rowset. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function nextRowset() { @@ -305,7 +293,7 @@ public function nextRowset() } /** - * rowCount + * rowCount. * * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement * executed by the corresponding object. @@ -315,7 +303,7 @@ public function nextRowset() * this behaviour is not guaranteed for all databases and should not be * relied on for portable applications. * - * @return integer Returns the number of rows. + * @return int returns the number of rows */ public function rowCount() { @@ -323,13 +311,13 @@ public function rowCount() } /** - * getColumnMeta + * getColumnMeta. * * Returns metadata for a column in a result set * - * @param integer $column The 0-indexed column in the result set. + * @param int $column the 0-indexed column in the result set * - * @return array Associative meta data array with the following structure: + * @return array Associative meta data array with the following structure: * * native_type The PHP native type used to represent the column value. * driver:decl_ type The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta(). @@ -340,40 +328,50 @@ public function rowCount() * pdo_type The type of this column as represented by the PDO::PARAM_* constants. */ public function getColumnMeta($column) - { } + { + } /** - * getAttribute + * getAttribute. * * Retrieve a statement attribute * - * @param integer $attribute + * @param int $attribute + * * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute) - { } + { + } /** - * setAttribute + * setAttribute. * * Set a statement attribute * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @param int $attribute + * @param mixed $value the value of given attribute + * + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value) - { } + { + } /** - * setFetchMode + * setFetchMode. * * Set the default fetch mode for this statement * - * @param integer $mode The fetch mode must be one of the Doctrine_Core::FETCH_* constants. - * @return boolean Returns 1 on success or FALSE on failure. + * @param int $mode the fetch mode must be one of the Doctrine_Core::FETCH_* constants + * @param mixed|null $arg1 + * @param mixed|null $arg2 + * + * @return bool returns 1 on success or FALSE on failure */ public function setFetchMode($mode, $arg1 = null, $arg2 = null) - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Adapter/Statement/Oracle.php b/lib/Doctrine/Adapter/Statement/Oracle.php index 0198f78f1..e6f70185c 100644 --- a/lib/Doctrine/Adapter/Statement/Oracle.php +++ b/lib/Doctrine/Adapter/Statement/Oracle.php @@ -22,64 +22,63 @@ /** * Oracle connection adapter statement class. * - * @package Doctrine - * @subpackage Adapter * @author Konsta Vesterinen * @author vadik56 * @author Miloslav Kmet * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Rev$ */ class Doctrine_Adapter_Statement_Oracle implements Doctrine_Adapter_Statement_Interface { /** - * @var string $queryString actual query string + * @var string actual query string */ public $queryString; - + /** - * @var resource $connection OCI connection handler + * @var resource OCI connection handler */ protected $connection; - + /** - * @var resource $statement OCI prepared statement + * @var resource OCI prepared statement */ protected $statement; - + /** - * @var integer $executeMode OCI statement execution mode + * @var int OCI statement execution mode */ protected $executeMode = OCI_COMMIT_ON_SUCCESS; /** - * @var array $bindParams Array of parameters bounded to a statement + * @var array Array of parameters bounded to a statement */ protected $bindParams = array(); /** - * @var array $attributes Array of attributes + * @var array Array of attributes */ protected $attributes = array(); /** - * @var array $ociErrors Array of errors + * @var array Array of errors */ protected $ociErrors = array(); - + /** - * the constructor - * - * @param Doctrine_Adapter_Oracle $connection - * @param string $query Query string to be executed - * @param integer $executeMode OCI execute mode + * the constructor. + * + * @param string $query Query string to be executed + * @param int $executeMode OCI execute mode */ - public function __construct( Doctrine_Adapter_Oracle $connection, $query, $executeMode) + public function __construct(Doctrine_Adapter_Oracle $connection, $query, $executeMode) { - $this->connection = $connection->getConnection(); - $this->queryString = $query; + $this->connection = $connection->getConnection(); + $this->queryString = $query; $this->executeMode = $executeMode; $this->attributes[Doctrine_Core::ATTR_ERRMODE] = $connection->getAttribute(Doctrine_Core::ATTR_ERRMODE); @@ -87,36 +86,36 @@ public function __construct( Doctrine_Adapter_Oracle $connection, $query, $execu } /** - * Bind a column to a PHP variable - * - * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. - * If using the column name, be aware that the name should match - * the case of the column, as returned by the driver. - * @param string $param Name of the PHP variable to which the column will be bound. - * @param integer $type Data type of the parameter, specified by the Doctrine_Core::PARAM_* constants. - * @return boolean Returns TRUE on success or FALSE on failure + * Bind a column to a PHP variable. + * + * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. + * If using the column name, be aware that the name should match + * the case of the column, as returned by the driver. + * @param string $param name of the PHP variable to which the column will be bound + * @param int $type data type of the parameter, specified by the Doctrine_Core::PARAM_* constants + * + * @return bool Returns TRUE on success or FALSE on failure */ public function bindColumn($column, $param, $type = null) { - throw new Doctrine_Adapter_Exception("Unsupported"); + throw new Doctrine_Adapter_Exception('Unsupported'); } /** - * Binds a value to a corresponding named or question mark + * Binds a value to a corresponding named or question mark * placeholder in the SQL statement that was use to prepare the statement. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter - * - * @param mixed $value The value to bind to the parameter. - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. + * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, + * this will be a parameter name of the form :name. For a prepared statement + * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $value the value to bind to the parameter + * @param int $type explicit data type for the parameter using the Doctrine_Core::PARAM_* constants * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindValue($param, $value, $type = null) { - /** + /* * need to store the value internally since binding is done by reference */ $this->bindParams[] = $value; @@ -124,38 +123,32 @@ public function bindValue($param, $value, $type = null) } /** - * Binds a PHP variable to a corresponding named or question mark placeholder in the + * Binds a PHP variable to a corresponding named or question mark placeholder in the * SQL statement that was use to prepare the statement. Unlike Doctrine_Adapter_Statement_Interface->bindValue(), - * the variable is bound as a reference and will only be evaluated at the time + * the variable is bound as a reference and will only be evaluated at the time * that Doctrine_Adapter_Statement_Interface->execute() is called. * - * Most parameters are input parameters, that is, parameters that are - * used in a read-only fashion to build up the query. Some drivers support the invocation + * Most parameters are input parameters, that is, parameters that are + * used in a read-only fashion to build up the query. Some drivers support the invocation * of stored procedures that return data as output parameters, and some also as input/output * parameters that both send in data and are updated to receive it. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $variable name of the PHP variable to bind to the SQL statement parameter + * @param int $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return + * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the + * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. + * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter + * from a stored procedure, you must explicitly set the length. * - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. - * - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return - * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the - * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. - * - * @param integer $length Length of the data type. To indicate that a parameter is an OUT parameter - * from a stored procedure, you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array()) { - if ($driverOptions || $length ) { + if ($driverOptions || $length) { throw new Doctrine_Adapter_Exception('Unsupported parameters:$length, $driverOptions'); } - if ($length === null) { + if (null === $length) { $oci_length = -1; } $oci_type = SQLT_CHR; @@ -163,26 +156,27 @@ public function bindParam($column, &$variable, $type = null, $length = null, $dr switch ($type) { case Doctrine_Core::PARAM_STR: $oci_type = SQLT_CHR; - break; + break; } if (is_integer($column)) { - $variable_name = ":oci_b_var_$column"; + $variable_name = ":oci_b_var_{$column}"; } else { $variable_name = $column; } - //print "Binding $variable to $variable_name".PHP_EOL; + // print "Binding $variable to $variable_name".PHP_EOL; $status = @oci_bind_by_name($this->statement, $variable_name, $variable, $oci_length, $oci_type); - if ($status === false) { - $this->handleError(); + if (false === $status) { + $this->handleError(); } + return $status; } /** * Closes the cursor, enabling the statement to be executed again. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function closeCursor() { @@ -190,64 +184,70 @@ public function closeCursor() if (is_resource($this->statement)) { return oci_free_statement($this->statement); } + return true; } - /** - * Returns the number of columns in the result set + /** + * Returns the number of columns in the result set. * - * @return integer Returns the number of columns in the result set represented - * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, - * this method should return 0. + * @return int Returns the number of columns in the result set represented + * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, + * this method should return 0. */ public function columnCount() { - return oci_num_fields ( $this->statement ); + return oci_num_fields($this->statement); } /** - * Fetch the SQLSTATE associated with the last operation on the statement handle + * Fetch the SQLSTATE associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorCode() - * @return string error code string + * + * @return string error code string */ public function errorCode() { $oci_error = $this->getOciError(); + return $oci_error['code']; } /** - * Fetch extended error information associated with the last operation on the statement handle + * Fetch extended error information associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorInfo() - * @return array error info array + * + * @return array error info array */ public function errorInfo() { $oci_error = $this->getOciError(); - return $oci_error['message'] . " : " . $oci_error['sqltext']; + + return $oci_error['message'].' : '.$oci_error['sqltext']; } private function getOciError() { if (is_resource($this->statement)) { - $oci_error = oci_error ($this->statement); + $oci_error = oci_error($this->statement); } else { - $oci_error = oci_error (); + $oci_error = oci_error(); } if ($oci_error) { - //store the error + // store the error $this->oci_errors[] = $oci_error; - } else if (count($this->ociErrors) > 0) { - $oci_error = $this->ociErrors[count($this->ociErrors)-1]; + } elseif (count($this->ociErrors) > 0) { + $oci_error = $this->ociErrors[count($this->ociErrors) - 1]; } + return $oci_error; } /** - * Executes a prepared statement + * Executes a prepared statement. * * If the prepared statement included parameter markers, you must either: * call PDOStatement->bindParam() to bind PHP variables to the parameter markers: @@ -255,107 +255,103 @@ private function getOciError() * if any, of their associated parameter markers or pass an array of input-only * parameter values * + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed * - * @param array $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = null) { if (is_array($params)) { foreach ($params as $var => $value) { - $this->bindValue($var+1, $value); + $this->bindValue($var + 1, $value); } } - $result = @oci_execute($this->statement , $this->executeMode ); + $result = @oci_execute($this->statement, $this->executeMode); - if ($result === false) { + if (false === $result) { $this->handleError(); + return false; - } + } + return true; } /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. - * - * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for - * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value - * specifies the row to fetch relative to the cursor position before - * Doctrine_Adapter_Statement_Interface->fetch() was called. * - * @return mixed + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH + * @param int $cursorOrientation For a PDOStatement object representing a scrollable cursor, + * this value determines which row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to + * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your + * Doctrine_Adapter_Statement_Interface object, + * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you + * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). + * @param int $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the + * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies + * the absolute number of the row in the result set that shall be fetched. + * + * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for + * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value + * specifies the row to fetch relative to the cursor position before + * Doctrine_Adapter_Statement_Interface->fetch() was called. */ public function fetch($fetchStyle = Doctrine_Core::FETCH_BOTH, $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, $cursorOffset = null) { switch ($fetchStyle) { case Doctrine_Core::FETCH_BOTH : return oci_fetch_array($this->statement, OCI_BOTH + OCI_RETURN_NULLS + OCI_RETURN_LOBS); - break; + break; case Doctrine_Core::FETCH_ASSOC : return oci_fetch_array($this->statement, OCI_ASSOC + OCI_RETURN_NULLS + OCI_RETURN_LOBS); - break; + break; case Doctrine_Core::FETCH_NUM : return oci_fetch_array($this->statement, OCI_NUM + OCI_RETURN_NULLS + OCI_RETURN_LOBS); - break; + break; case Doctrine_Core::FETCH_OBJ: return oci_fetch_object($this->statement, OCI_NUM + OCI_RETURN_NULLS + OCI_RETURN_LOBS); - break; + break; default: - throw new Doctrine_Adapter_Exception("This type of fetch is not supported: ".$fetchStyle); -/* - case Doctrine_Core::FETCH_BOUND: - case Doctrine_Core::FETCH_CLASS: - case FETCH_CLASSTYPE: - case FETCH_COLUMN: - case FETCH_FUNC: - case FETCH_GROUP: - case FETCH_INTO: - case FETCH_LAZY: - case FETCH_NAMED: - case FETCH_SERIALIZE: - case FETCH_UNIQUE: - case FETCH_ORI_ABS: - case FETCH_ORI_FIRST: - case FETCH_ORI_LAST: - case FETCH_ORI_NEXT: - case FETCH_ORI_PRIOR: - case FETCH_ORI_REL: -*/ + throw new Doctrine_Adapter_Exception('This type of fetch is not supported: '.$fetchStyle); + /* + case Doctrine_Core::FETCH_BOUND: + case Doctrine_Core::FETCH_CLASS: + case FETCH_CLASSTYPE: + case FETCH_COLUMN: + case FETCH_FUNC: + case FETCH_GROUP: + case FETCH_INTO: + case FETCH_LAZY: + case FETCH_NAMED: + case FETCH_SERIALIZE: + case FETCH_UNIQUE: + case FETCH_ORI_ABS: + case FETCH_ORI_FIRST: + case FETCH_ORI_LAST: + case FETCH_ORI_NEXT: + case FETCH_ORI_PRIOR: + case FETCH_ORI_REL: + */ } } /** - * Returns an array containing all of the result set rows + * Returns an array containing all of the result set rows. * - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is - * Doctrine_Core::FETCH_COLUMN. Defaults to 0. + * @param int $fetchStyle Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH * * @return array */ - public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH, $colnum=0) + public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH, $colnum = 0) { $fetchColumn = false; $skip = 0; @@ -365,19 +361,19 @@ public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH, $colnum=0) $int = $fetchStyle & Doctrine_Core::FETCH_COLUMN; - if ($fetchStyle == Doctrine_Core::FETCH_BOTH) { + if (Doctrine_Core::FETCH_BOTH == $fetchStyle) { $flags = OCI_BOTH; $numberOfRows = @oci_fetch_all($this->statement, $data, $skip, $maxrows, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC + OCI_RETURN_LOBS); - } else if ($fetchStyle == Doctrine_Core::FETCH_ASSOC) { + } elseif (Doctrine_Core::FETCH_ASSOC == $fetchStyle) { $numberOfRows = @oci_fetch_all($this->statement, $data, $skip, $maxrows, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC + OCI_RETURN_LOBS); - } else if ($fetchStyle == Doctrine_Core::FETCH_NUM) { + } elseif (Doctrine_Core::FETCH_NUM == $fetchStyle) { $numberOfRows = @oci_fetch_all($this->statement, $data, $skip, $maxrows, OCI_FETCHSTATEMENT_BY_ROW + OCI_NUM + OCI_RETURN_LOBS); - } else if ($fetchStyle == Doctrine_Core::FETCH_COLUMN) { - while ($row = @oci_fetch_array ($this->statement, OCI_NUM+OCI_RETURN_LOBS)) { + } elseif (Doctrine_Core::FETCH_COLUMN == $fetchStyle) { + while ($row = @oci_fetch_array($this->statement, OCI_NUM + OCI_RETURN_LOBS)) { $data[] = $row[$colnum]; } } else { - throw new Doctrine_Adapter_Exception("Unsupported mode: '" . $fetchStyle . "' "); + throw new Doctrine_Adapter_Exception("Unsupported mode: '".$fetchStyle."' "); } return $data; @@ -387,75 +383,76 @@ public function fetchAll($fetchStyle = Doctrine_Core::FETCH_BOTH, $colnum=0) * Returns a single column from the next row of a * result set or FALSE if there are no more rows. * - * @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no - * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() - * fetches the first column. + * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no + * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() + * fetches the first column. * - * @return string returns a single column in the next row of a result set. + * @return string returns a single column in the next row of a result set */ public function fetchColumn($columnIndex = 0) { - if ( ! is_integer($columnIndex)) { - $this->handleError(array('message'=>"columnIndex parameter should be numeric")); + if (!is_integer($columnIndex)) { + $this->handleError(array('message' => 'columnIndex parameter should be numeric')); return false; } $row = $this->fetch(Doctrine_Core::FETCH_NUM); + return isset($row[$columnIndex]) ? $row[$columnIndex] : false; } /** * Fetches the next row and returns it as an object. * - * Fetches the next row and returns it as an object. This function is an alternative to + * Fetches the next row and returns it as an object. This function is an alternative to * Doctrine_Adapter_Statement_Interface->fetch() with Doctrine_Core::FETCH_CLASS or Doctrine_Core::FETCH_OBJ style. * - * @param string $className Name of the created class, defaults to stdClass. - * @param array $args Elements of this array are passed to the constructor. + * @param string $className name of the created class, defaults to stdClass + * @param array $args elements of this array are passed to the constructor * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @return mixed an instance of the required class with property names that correspond + * to the column names or FALSE in case of an error */ public function fetchObject($className = 'stdClass', $args = array()) { $row = $this->fetch(Doctrine_Core::FETCH_ASSOC); - if ($row === false) { + if (false === $row) { return false; } - $instantiation_code = "\$object = new $className("; - $firstParam=true; - foreach ($args as $index=>$value) { - if ( ! $firstParam ) { - $instantiation_code = $instantiation_code . ","; + $instantiation_code = "\$object = new {$className}("; + $firstParam = true; + foreach ($args as $index => $value) { + if (!$firstParam) { + $instantiation_code = $instantiation_code.','; } else { - $firstParam= false; + $firstParam = false; } - if ( is_string($index)) { - $instantiation_code = $instantiation_code . " \$args['$index']"; + if (is_string($index)) { + $instantiation_code = $instantiation_code." \$args['{$index}']"; } else { - $instantiation_code = $instantiation_code . "\$args[$index]"; + $instantiation_code = $instantiation_code."\$args[{$index}]"; } } - $instantiation_code = $instantiation_code . ");"; + $instantiation_code = $instantiation_code.');'; eval($instantiation_code); - //initialize instance of $className class + // initialize instance of $className class foreach ($row as $col => $value) { - $object->$col = $value; + $object->{$col} = $value; } return $object; } /** - * Returns metadata for a column in a result set + * Returns metadata for a column in a result set. * - * @param integer $column The 0-indexed column in the result set. + * @param int $column the 0-indexed column in the result set * - * @return array Associative meta data array with the following structure: + * @return array Associative meta data array with the following structure: * * native_type The PHP native type used to represent the column value. * driver:decl_ type The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta(). @@ -468,14 +465,14 @@ public function fetchObject($className = 'stdClass', $args = array()) public function getColumnMeta($column) { if (is_integer($column)) { - $internal_column = $column +1; + $internal_column = $column + 1; } else { $internal_column = $column; } $data = array(); $data['native_type'] = oci_field_type($this->statement, $internal_column); - $data['flags'] = ""; + $data['flags'] = ''; $data['len'] = oci_field_size($this->statement, $internal_column); $data['name'] = oci_field_name($this->statement, $internal_column); $data['precision'] = oci_field_precision($this->statement, $internal_column); @@ -484,30 +481,30 @@ public function getColumnMeta($column) } /** - * Advances to the next rowset in a multi-rowset statement handle - * - * Some database servers support stored procedures that return more than one rowset - * (also known as a result set). The nextRowset() method enables you to access the second - * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a + * Advances to the next rowset in a multi-rowset statement handle. + * + * Some database servers support stored procedures that return more than one rowset + * (also known as a result set). The nextRowset() method enables you to access the second + * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a * different set of columns from the preceding rowset. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function nextRowset() { - throw new Doctrine_Adapter_Exception("Unsupported"); + throw new Doctrine_Adapter_Exception('Unsupported'); } /** - * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement + * rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement * executed by the corresponding object. * - * If the last SQL statement executed by the associated Statement object was a SELECT statement, - * some databases may return the number of rows returned by that statement. However, - * this behaviour is not guaranteed for all databases and should not be + * If the last SQL statement executed by the associated Statement object was a SELECT statement, + * some databases may return the number of rows returned by that statement. However, + * this behaviour is not guaranteed for all databases and should not be * relied on for portable applications. * - * @return integer Returns the number of rows. + * @return int returns the number of rows */ public function rowCount() { @@ -515,29 +512,32 @@ public function rowCount() } /** - * Set a statement attribute + * Set a statement attribute. + * + * @param int $attribute + * @param mixed $value the value of given attribute * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value) { switch ($attribute) { - case Doctrine_Core::ATTR_ERRMODE; - break; + case Doctrine_Core::ATTR_ERRMODE: + break; default: - throw new Doctrine_Adapter_Exception("Unsupported Attribute: $attribute"); + throw new Doctrine_Adapter_Exception("Unsupported Attribute: {$attribute}"); } $this->attributes[$attribute] = $value; } /** - * Retrieve a statement attribute + * Retrieve a statement attribute. + * + * @param int $attribute * - * @param integer $attribute * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute) { @@ -545,53 +545,54 @@ public function getAttribute($attribute) } /** - * Set the default fetch mode for this statement + * Set the default fetch mode for this statement. + * + * @param int $mode the fetch mode must be one of the Doctrine_Core::FETCH_* constants + * @param mixed|null $arg1 + * @param mixed|null $arg2 * - * @param integer $mode The fetch mode must be one of the Doctrine_Core::FETCH_* constants. - * @return boolean Returns 1 on success or FALSE on failure. + * @return bool returns 1 on success or FALSE on failure */ public function setFetchMode($mode, $arg1 = null, $arg2 = null) { - throw new Doctrine_Adapter_Exception("Unsupported"); + throw new Doctrine_Adapter_Exception('Unsupported'); } - private function handleError($params=array()) + private function handleError($params = array()) { - switch ($this->attributes[Doctrine_Core::ATTR_ERRMODE]) { case Doctrine_Core::ERRMODE_EXCEPTION: if (isset($params['message'])) { throw new Doctrine_Adapter_Exception($params['message']); - } else { - throw new Doctrine_Adapter_Exception($this->errorInfo()); } - - break; + throw new Doctrine_Adapter_Exception($this->errorInfo()); + break; case Doctrine_Core::ERRMODE_WARNING: case Doctrine_Core::ERRMODE_SILENT: - break; + break; } } /** - * Parse actual query from queryString and returns OCI statement handler + * Parse actual query from queryString and returns OCI statement handler. + * * @param string Query string to parse, if NULL, $this->queryString is used - * - * @return resource OCI statement handler + * @param mixed|null $query + * + * @return resource OCI statement handler */ - private function parseQuery($query=null) + private function parseQuery($query = null) { if (is_null($query)) { $query = $this->queryString; } $bind_index = 1; // Replace ? bind-placeholders with :oci_b_var_ variables - $query = preg_replace_callback("/(\?)/", function($m) use(&$bind_index) { return ":oci_b_var_". $bind_index++; } , $query); + $query = preg_replace_callback('/(\\?)/', function ($m) use (&$bind_index) { return ':oci_b_var_'.$bind_index++; }, $query); - $this->statement = @oci_parse($this->connection, $query); + $this->statement = @oci_parse($this->connection, $query); - if ( $this->statement == false ) - { + if (false == $this->statement) { throw new Doctrine_Adapter_Exception($this->getOciError()); } diff --git a/lib/Doctrine/AuditLog.php b/lib/Doctrine/AuditLog.php index 763b882c7..fc8a65fce 100644 --- a/lib/Doctrine/AuditLog.php +++ b/lib/Doctrine/AuditLog.php @@ -20,45 +20,45 @@ */ /** - * Doctrine_AuditLog + * Doctrine_AuditLog. * - * @package Doctrine - * @subpackage AuditLog * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_AuditLog extends Doctrine_Record_Generator { /** - * Array of AuditLog Options + * Array of AuditLog Options. * * @var array */ - protected $_options = array('className' => '%CLASS%Version', - 'version' => array('name' => 'version', - 'alias' => null, - 'type' => 'integer', - 'length' => 8, - 'options' => array('primary' => true)), - 'tableName' => false, - 'generateFiles' => false, - 'table' => false, - 'pluginTable' => false, - 'children' => array(), - 'auditLog' => true, - 'deleteVersions' => true, - 'cascadeDelete' => true, - 'excludeFields' => array(), - 'appLevelDelete' => false); + protected $_options = array('className' => '%CLASS%Version', + 'version' => array('name' => 'version', + 'alias' => null, + 'type' => 'integer', + 'length' => 8, + 'options' => array('primary' => true)), + 'tableName' => false, + 'generateFiles' => false, + 'table' => false, + 'pluginTable' => false, + 'children' => array(), + 'auditLog' => true, + 'deleteVersions' => true, + 'cascadeDelete' => true, + 'excludeFields' => array(), + 'appLevelDelete' => false); /** - * Accepts array of options to configure the AuditLog + * Accepts array of options to configure the AuditLog. * - * @param array $options An array of options - * @return void + * @param array $options An array of options */ public function __construct(array $options = array()) { @@ -72,9 +72,7 @@ public function buildRelation() } /** - * Set the table definition for the audit log table - * - * @return void + * Set the table definition for the audit log table. */ public function setTableDefinition() { @@ -88,13 +86,11 @@ public function setTableDefinition() if (in_array($column, $this->_options['excludeFields'])) { continue; } - unset($definition['autoincrement']); - unset($definition['sequence']); - unset($definition['unique']); + unset($definition['autoincrement'], $definition['sequence'], $definition['unique']); $fieldName = $this->_options['table']->getFieldName($column); if ($fieldName != $column) { - $name = $column . ' as ' . $fieldName; + $name = $column.' as '.$fieldName; } else { $name = $fieldName; } @@ -104,67 +100,68 @@ public function setTableDefinition() // the version column should be part of the primary key definition $this->hasColumn( - $this->_options['version']['name'], + $this->_options['version']['name'], $this->_options['version']['type'], $this->_options['version']['length'], $this->_options['version']['options']); } /** - * Get array of information for the passed record and the specified version + * Get array of information for the passed record and the specified version. + * + * @param int $version + * @param int $hydrationMode + * @param bool $asCollection * - * @param Doctrine_Record $record - * @param integer $version - * @param integer $hydrationMode - * @param boolean $asCollection - * @return array An array or Doctrine_Collection or a Doctrine_Record + * @return array An array or Doctrine_Collection or a Doctrine_Record */ public function getVersion(Doctrine_Record $record, $version, $hydrationMode = Doctrine_Core::HYDRATE_ARRAY, $asCollection = true) { $className = $this->_options['className']; - $method = ($asCollection) ? 'execute' : 'fetchOne'; + $method = ($asCollection) ? 'execute' : 'fetchOne'; $q = Doctrine_Core::getTable($className) - ->createQuery(); + ->createQuery() + ; $values = array(); foreach ((array) $this->_options['table']->getIdentifier() as $id) { - $conditions[] = $className . '.' . $id . ' = ?'; + $conditions[] = $className.'.'.$id.' = ?'; $values[] = $record->get($id); } - $where = implode(' AND ', $conditions) . ' AND ' . $className . '.' . $this->_options['version']['name'] . ' = ?'; + $where = implode(' AND ', $conditions).' AND '.$className.'.'.$this->_options['version']['name'].' = ?'; $values[] = $version; $q->where($where); - return $q->$method($values, $hydrationMode); + return $q->{$method}($values, $hydrationMode); } /** - * Get the max version number for a given Doctrine_Record + * Get the max version number for a given Doctrine_Record. * - * @param Doctrine_Record $record - * @return Integer $versionnumber + * @return int $versionnumber */ public function getMaxVersion(Doctrine_Record $record) { $className = $this->_options['className']; - $select = 'MAX(' . $className . '.' . $this->_options['version']['name'] . ') max_version'; + $select = 'MAX('.$className.'.'.$this->_options['version']['name'].') max_version'; foreach ((array) $this->_options['table']->getIdentifier() as $id) { - $conditions[] = $className . '.' . $id . ' = ?'; + $conditions[] = $className.'.'.$id.' = ?'; $values[] = $record->get($id); } $q = Doctrine_Core::getTable($className) ->createQuery() ->select($select) - ->where(implode(' AND ',$conditions)); + ->where(implode(' AND ', $conditions)) + ; $result = $q->execute($values, Doctrine_Core::HYDRATE_ARRAY); - return isset($result[0]['max_version']) ? $result[0]['max_version']:0; + return isset($result[0]['max_version']) ? $result[0]['max_version'] : 0; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/AuditLog/Listener.php b/lib/Doctrine/AuditLog/Listener.php index d2631e7a3..6b745428a 100644 --- a/lib/Doctrine/AuditLog/Listener.php +++ b/lib/Doctrine/AuditLog/Listener.php @@ -20,46 +20,41 @@ */ /** - * Doctrine_AuditLog_Listener + * Doctrine_AuditLog_Listener. * - * @package Doctrine - * @subpackage AuditLog * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_AuditLog_Listener extends Doctrine_Record_Listener { /** - * Instance of Doctrine_Auditlog + * Instance of Doctrine_Auditlog. * * @var Doctrine_AuditLog */ protected $_auditLog; /** - * Instantiate AuditLog listener and set the Doctrine_AuditLog instance to the class - * - * @param Doctrine_AuditLog $auditLog - * @return void + * Instantiate AuditLog listener and set the Doctrine_AuditLog instance to the class. */ - public function __construct(Doctrine_AuditLog $auditLog) + public function __construct(Doctrine_AuditLog $auditLog) { $this->_auditLog = $auditLog; } /** - * Pre insert event hook for incrementing version number - * - * @param Doctrine_Event $event - * @return void + * Pre insert event hook for incrementing version number. */ public function preInsert(Doctrine_Event $event) { $version = $this->_auditLog->getOption('version'); - $name = $version['alias'] === null ? $version['name'] : $version['alias']; + $name = null === $version['alias'] ? $version['name'] : $version['alias']; $record = $event->getInvoker(); $record->set($name, $this->_getInitialVersion($record)); @@ -67,17 +62,14 @@ public function preInsert(Doctrine_Event $event) /** * Post insert event hook which creates the new version record - * This will only insert a version record if the auditLog is enabled - * - * @param Doctrine_Event $event - * @return void + * This will only insert a version record if the auditLog is enabled. */ - public function postInsert(Doctrine_Event $event) + public function postInsert(Doctrine_Event $event) { if ($this->_auditLog->getOption('auditLog')) { $class = $this->_auditLog->getOption('className'); - $record = $event->getInvoker(); + $record = $event->getInvoker(); $version = new $class(); $version->merge($record->toArray(), false); $version->save(); @@ -86,49 +78,45 @@ public function postInsert(Doctrine_Event $event) /** * Pre delete event hook deletes all related versions - * This will only delete version records if the auditLog is enabled - * - * @param Doctrine_Event $event - * @return void + * This will only delete version records if the auditLog is enabled. */ public function preDelete(Doctrine_Event $event) { if ($this->_auditLog->getOption('auditLog')) { - $className = $this->_auditLog->getOption('className'); + $className = $this->_auditLog->getOption('className'); $version = $this->_auditLog->getOption('version'); - $name = $version['alias'] === null ? $version['name'] : $version['alias']; - $event->getInvoker()->set($name, null); + $name = null === $version['alias'] ? $version['name'] : $version['alias']; + $event->getInvoker()->set($name, null); if ($this->_auditLog->getOption('deleteVersions')) { - $q = Doctrine_Core::getTable($className) - ->createQuery('obj') - ->delete(); - foreach ((array) $this->_auditLog->getOption('table')->getIdentifier() as $id) { - $conditions[] = 'obj.' . $id . ' = ?'; - $values[] = $event->getInvoker()->get($id); - } + $q = Doctrine_Core::getTable($className) + ->createQuery('obj') + ->delete() + ; + foreach ((array) $this->_auditLog->getOption('table')->getIdentifier() as $id) { + $conditions[] = 'obj.'.$id.' = ?'; + $values[] = $event->getInvoker()->get($id); + } - $rows = $q->where(implode(' AND ', $conditions)) - ->execute($values); - } + $rows = $q->where(implode(' AND ', $conditions)) + ->execute($values) + ; + } } } /** * Pre update event hook for inserting new version record - * This will only insert a version record if the auditLog is enabled - * - * @param Doctrine_Event $event - * @return void + * This will only insert a version record if the auditLog is enabled. */ public function preUpdate(Doctrine_Event $event) { if ($this->_auditLog->getOption('auditLog')) { - $class = $this->_auditLog->getOption('className'); + $class = $this->_auditLog->getOption('className'); $record = $event->getInvoker(); $version = $this->_auditLog->getOption('version'); - $name = $version['alias'] === null ? $version['name'] : $version['alias']; + $name = null === $version['alias'] ? $version['name'] : $version['alias']; $record->set($name, $this->_getNextVersion($record)); @@ -139,10 +127,9 @@ public function preUpdate(Doctrine_Event $event) } /** - * Get the initial version number for the audit log + * Get the initial version number for the audit log. * - * @param Doctrine_Record $record - * @return integer $initialVersion + * @return int $initialVersion */ protected function _getInitialVersion(Doctrine_Record $record) { @@ -150,15 +137,14 @@ protected function _getInitialVersion(Doctrine_Record $record) } /** - * Get the next version number for the audit log + * Get the next version number for the audit log. * - * @param Doctrine_Record $record - * @return integer $nextVersion + * @return int $nextVersion */ protected function _getNextVersion(Doctrine_Record $record) { - if ($this->_auditLog->getOption('auditLog')) { - return ($this->_auditLog->getMaxVersion($record) + 1); - } + if ($this->_auditLog->getOption('auditLog')) { + return $this->_auditLog->getMaxVersion($record) + 1; + } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/AuditLog/Listener/Microtime.php b/lib/Doctrine/AuditLog/Listener/Microtime.php index 081a27fff..65f7871e2 100644 --- a/lib/Doctrine/AuditLog/Listener/Microtime.php +++ b/lib/Doctrine/AuditLog/Listener/Microtime.php @@ -20,30 +20,28 @@ */ /** - * Doctrine_AuditLog_Listener + * Doctrine_AuditLog_Listener. * - * @package Doctrine - * @subpackage AuditLog * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Lukas Smith */ class Doctrine_AuditLog_Listener_Microtime extends Doctrine_AuditLog_Listener { /** - * The numher of digits to use from the float microtime value + * The numher of digits to use from the float microtime value. * * @var int */ protected $accuracy = 10; /** - * Instantiate AuditLog listener and set the Doctrine_AuditLog instance to the class - * - * @param Doctrine_AuditLog $auditLog - * @return void + * Instantiate AuditLog listener and set the Doctrine_AuditLog instance to the class. */ public function __construct(Doctrine_AuditLog $auditLog) { @@ -55,10 +53,9 @@ public function __construct(Doctrine_AuditLog $auditLog) } /** - * Get the initial version number for the audit log + * Get the initial version number for the audit log. * - * @param Doctrine_Record $record - * @return integer $initialVersion + * @return int $initialVersion */ protected function _getInitialVersion(Doctrine_Record $record) { @@ -66,10 +63,9 @@ protected function _getInitialVersion(Doctrine_Record $record) } /** - * Get the next version number for the audit log + * Get the next version number for the audit log. * - * @param Doctrine_Record $record - * @return integer $nextVersion + * @return int $nextVersion */ protected function _getNextVersion(Doctrine_Record $record) { @@ -77,15 +73,15 @@ protected function _getNextVersion(Doctrine_Record $record) } /** - * Compute a version out of microtime(true) + * Compute a version out of microtime(true). * * @return string $version */ protected function _microtime() { $version = microtime(true) - 1073741824; // 31 bits - $version = str_replace('.', '', (string)$version); + $version = str_replace('.', '', (string) $version); + return substr($version, 0, $this->accuracy); } - -} \ No newline at end of file +} diff --git a/lib/Doctrine/Builder.php b/lib/Doctrine/Builder.php index 9f6ac88a7..c566b54fc 100644 --- a/lib/Doctrine/Builder.php +++ b/lib/Doctrine/Builder.php @@ -20,14 +20,16 @@ */ /** - * Base class for any code builders/generators for Doctrine + * Base class for any code builders/generators for Doctrine. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Builder - * @link www.doctrine-project.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 4593 $ + * * @author Jonathan H. Wage */ class Doctrine_Builder @@ -35,22 +37,20 @@ class Doctrine_Builder /** * Special function for var_export() * The normal code which is returned is malformed and does not follow Doctrine standards - * So we do some string replacing to clean it up + * So we do some string replacing to clean it up. * * @param string $var - * @return void */ public function varExport($var) { $export = var_export($var, true); - $export = str_replace("\n", PHP_EOL . str_repeat(' ', 50), $export); + $export = str_replace("\n", PHP_EOL.str_repeat(' ', 50), $export); $export = str_replace(' ', ' ', $export); $export = str_replace('array (', 'array(', $export); $export = str_replace('array( ', 'array(', $export); $export = str_replace(',)', ')', $export); $export = str_replace(', )', ')', $export); - $export = str_replace(' ', ' ', $export); - return $export; + return str_replace(' ', ' ', $export); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Apc.php b/lib/Doctrine/Cache/Apc.php index 079676da4..50244fd65 100644 --- a/lib/Doctrine/Cache/Apc.php +++ b/lib/Doctrine/Cache/Apc.php @@ -20,38 +20,40 @@ */ /** - * APC Cache Driver + * APC Cache Driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Cache_Apc extends Doctrine_Cache_Driver { /** - * constructor + * constructor. * - * @param array $options associative array of cache driver options + * @param array $options associative array of cache driver options */ public function __construct($options = array()) { - if ( ! extension_loaded('apc')) { + if (!extension_loaded('apc')) { throw new Doctrine_Cache_Exception('The apc extension must be loaded for using this backend !'); } parent::__construct($options); } /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { @@ -59,26 +61,29 @@ protected function _doFetch($id, $testCacheValidity = true) } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) { $found = false; apc_fetch($id, $found); + return $found; } /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false) { @@ -87,10 +92,11 @@ protected function _doSave($id, $data, $lifeTime = false) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { @@ -98,7 +104,7 @@ protected function _doDelete($id) } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ @@ -108,8 +114,9 @@ protected function _getCacheKeys() $keys = array(); foreach ($ci['cache_list'] as $entry) { - $keys[] = $entry['info']; + $keys[] = $entry['info']; } + return $keys; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Array.php b/lib/Doctrine/Cache/Array.php index 50188e892..26e9aa976 100644 --- a/lib/Doctrine/Cache/Array.php +++ b/lib/Doctrine/Cache/Array.php @@ -20,43 +20,47 @@ */ /** - * Array cache driver + * Array cache driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Cache_Array extends Doctrine_Cache_Driver { /** - * @var array $data an array of cached data + * @var array an array of cached data */ protected $data = array(); /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { if (isset($this->data[$id])) { return $this->data[$id]; } + return false; } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) @@ -66,12 +70,13 @@ protected function _doContains($id) /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) + * + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false) { @@ -82,10 +87,11 @@ protected function _doSave($id, $data, $lifeTime = false) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { @@ -97,7 +103,7 @@ protected function _doDelete($id) } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ @@ -105,4 +111,4 @@ protected function _getCacheKeys() { return array_keys($this->data); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Db.php b/lib/Doctrine/Cache/Db.php index 4fa89c54b..36275b72c 100644 --- a/lib/Doctrine/Cache/Db.php +++ b/lib/Doctrine/Cache/Db.php @@ -20,14 +20,15 @@ */ /** - * Database cache driver + * Database cache driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ @@ -35,30 +36,25 @@ class Doctrine_Cache_Db extends Doctrine_Cache_Driver { /** * Configure Database cache driver. Specify instance of Doctrine_Connection - * and tableName to store cache in - * - * @param array $_options an array of options + * and tableName to store cache in. */ public function __construct($options = array()) { - if ( ! isset($options['connection']) || - ! ($options['connection'] instanceof Doctrine_Connection)) { - + if (!isset($options['connection']) + || !($options['connection'] instanceof Doctrine_Connection)) { throw new Doctrine_Cache_Exception('Connection option not set.'); } - if ( ! isset($options['tableName']) || - ! is_string($options['tableName'])) { - - throw new Doctrine_Cache_Exception('Table name option not set.'); + if (!isset($options['tableName']) + || !is_string($options['tableName'])) { + throw new Doctrine_Cache_Exception('Table name option not set.'); } - $this->_options = $options; } /** - * Get the connection object associated with this cache driver + * Get the connection object associated with this cache driver. * * @return Doctrine_Connection $connection */ @@ -68,24 +64,25 @@ public function getConnection() } /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { - $sql = 'SELECT data, expire FROM ' . $this->_options['tableName'] - . ' WHERE id = ?'; + $sql = 'SELECT data, expire FROM '.$this->_options['tableName'] + .' WHERE id = ?'; if ($testCacheValidity) { - $sql .= " AND (expire is null OR expire > '" . date('Y-m-d H:i:s') . "')"; + $sql .= " AND (expire is null OR expire > '".date('Y-m-d H:i:s')."')"; } $result = $this->getConnection()->execute($sql, array($id))->fetchAll(Doctrine_Core::FETCH_NUM); - if ( ! isset($result[0])) { + if (!isset($result[0])) { return false; } @@ -93,57 +90,60 @@ protected function _doFetch($id, $testCacheValidity = true) } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) { - $sql = 'SELECT id, expire FROM ' . $this->_options['tableName'] - . ' WHERE id = ?'; + $sql = 'SELECT id, expire FROM '.$this->_options['tableName'] + .' WHERE id = ?'; $result = $this->getConnection()->fetchOne($sql, array($id)); - if (isset($result[0] )) { + if (isset($result[0])) { return time(); } + return false; } /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false, $saveKey = true) { if ($this->contains($id)) { - //record is in database, do update - $sql = 'UPDATE ' . $this->_options['tableName'] - . ' SET data = ?, expire=? ' - . ' WHERE id = ?'; + // record is in database, do update + $sql = 'UPDATE '.$this->_options['tableName'] + .' SET data = ?, expire=? ' + .' WHERE id = ?'; if ($lifeTime) { $expire = date('Y-m-d H:i:s', time() + $lifeTime); } else { - $expire = NULL; + $expire = null; } $params = array(bin2hex(serialize($data)), $expire, $id); } else { - //record is not in database, do insert - $sql = 'INSERT INTO ' . $this->_options['tableName'] - . ' (id, data, expire) VALUES (?, ?, ?)'; + // record is not in database, do insert + $sql = 'INSERT INTO '.$this->_options['tableName'] + .' (id, data, expire) VALUES (?, ?, ?)'; if ($lifeTime) { $expire = date('Y-m-d H:i:s', time() + $lifeTime); } else { - $expire = NULL; + $expire = null; } $params = array($id, bin2hex(serialize($data)), $expire); @@ -154,21 +154,21 @@ protected function _doSave($id, $data, $lifeTime = false, $saveKey = true) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { - $sql = 'DELETE FROM ' . $this->_options['tableName'] . ' WHERE id = ?'; + $sql = 'DELETE FROM '.$this->_options['tableName'].' WHERE id = ?'; + return $this->getConnection()->exec($sql, array($id)); } /** - * Create the cache table - * - * @return void + * Create the cache table. */ public function createTable() { @@ -176,19 +176,19 @@ public function createTable() $fields = array( 'id' => array( - 'type' => 'string', - 'length' => 255 + 'type' => 'string', + 'length' => 255, ), 'data' => array( - 'type' => 'blob' + 'type' => 'blob', ), 'expire' => array( - 'type' => 'timestamp' - ) + 'type' => 'timestamp', + ), ); $options = array( - 'primary' => array('id') + 'primary' => array('id'), ); $this->getConnection()->export->createTable($name, $fields, $options); @@ -199,34 +199,36 @@ public function createTable() * it is returned as is. * * @param string $hex + * * @return string $binary */ protected function _hex2bin($hex) { - if ( ! is_string($hex)) { + if (!is_string($hex)) { return null; } - if ( ! ctype_xdigit($hex)) { + if (!ctype_xdigit($hex)) { return $hex; } - return pack("H*", $hex); + return pack('H*', $hex); } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ protected function _getCacheKeys() { - $sql = 'SELECT id FROM ' . $this->_options['tableName']; + $sql = 'SELECT id FROM '.$this->_options['tableName']; $keys = array(); $results = $this->getConnection()->execute($sql)->fetchAll(Doctrine_Core::FETCH_NUM); - for ($i = 0, $count = count($results); $i < $count; $i++) { + for ($i = 0, $count = count($results); $i < $count; ++$i) { $keys[] = $results[$i][0]; } + return $keys; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Driver.php b/lib/Doctrine/Cache/Driver.php index 5bbf61d7b..7b74998d2 100644 --- a/lib/Doctrine/Cache/Driver.php +++ b/lib/Doctrine/Cache/Driver.php @@ -20,28 +20,27 @@ */ /** - * Abstract cache driver class + * Abstract cache driver class. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ abstract class Doctrine_Cache_Driver implements Doctrine_Cache_Interface { /** - * @var array $_options an array of options + * @var array an array of options */ protected $_options = array(); /** - * Configure cache driver with an array of options - * - * @param array $_options an array of options + * Configure cache driver with an array of options. */ public function __construct($options = array()) { @@ -49,30 +48,34 @@ public function __construct($options = array()) } /** - * Set option name and value + * Set option name and value. * - * @param mixed $option the option name - * @param mixed $value option value - * @return boolean TRUE on success, FALSE on failure + * @param mixed $option the option name + * @param mixed $value option value + * + * @return bool TRUE on success, FALSE on failure */ public function setOption($option, $value) { if (isset($this->_options[$option])) { $this->_options[$option] = $value; + return true; } + return false; } /** - * Get value of option + * Get value of option. + * + * @param mixed $option the option name * - * @param mixed $option the option name - * @return mixed option value + * @return mixed option value */ public function getOption($option) { - if ( ! isset($this->_options[$option])) { + if (!isset($this->_options[$option])) { return null; } @@ -80,68 +83,76 @@ public function getOption($option) } /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ public function fetch($id, $testCacheValidity = true) { $key = $this->_getKey($id); + return $this->_doFetch($key, $testCacheValidity); } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ public function contains($id) { $key = $this->_getKey($id); + return $this->_doContains($key); } /** - * Save some string datas into a cache record + * Save some string datas into a cache record. + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ public function save($id, $data, $lifeTime = false) { $key = $this->_getKey($id); + return $this->_doSave($key, $data, $lifeTime); } /** - * Remove a cache record + * Remove a cache record. * * Note: This method accepts wildcards with the * character * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ public function delete($id) { $key = $this->_getKey($id); - if (strpos($key, '*') !== false) { - return $this->deleteByRegex('/' . str_replace('*', '.*', $key) . '/'); + if (false !== strpos($key, '*')) { + return $this->deleteByRegex('/'.str_replace('*', '.*', $key).'/'); } return $this->_doDelete($key); } /** - * Delete cache entries where the key matches a PHP regular expressions + * Delete cache entries where the key matches a PHP regular expressions. * * @param string $regex - * @return integer $count The number of deleted cache entries + * + * @return int $count The number of deleted cache entries */ public function deleteByRegex($regex) { @@ -150,19 +161,21 @@ public function deleteByRegex($regex) if (is_array($keys)) { foreach ($keys as $key) { if (preg_match($regex, $key)) { - $count++; + ++$count; $this->delete($key); } } } + return $count; } /** - * Delete cache entries where the key has the passed prefix + * Delete cache entries where the key has the passed prefix. * * @param string $prefix - * @return integer $count The number of deleted cache entries + * + * @return int $count The number of deleted cache entries */ public function deleteByPrefix($prefix) { @@ -170,20 +183,22 @@ public function deleteByPrefix($prefix) $keys = $this->_getCacheKeys(); if (is_array($keys)) { foreach ($keys as $key) { - if (strpos($key, $prefix) === 0) { - $count++; + if (0 === strpos($key, $prefix)) { + ++$count; $this->delete($key); } } } + return $count; } /** - * Delete cache entries where the key has the passed suffix + * Delete cache entries where the key has the passed suffix. * * @param string $suffix - * @return integer $count The number of deleted cache entries + * + * @return int $count The number of deleted cache entries */ public function deleteBySuffix($suffix) { @@ -192,89 +207,96 @@ public function deleteBySuffix($suffix) if (is_array($keys)) { foreach ($keys as $key) { if (substr($key, -1 * strlen($suffix)) == $suffix) { - $count++; + ++$count; $this->delete($key); } } } + return $count; } /** - * Delete all cache entries from the cache driver - * - * @return integer $count The number of deleted cache entries + * Delete all cache entries from the cache driver. + * + * @return int $count The number of deleted cache entries */ - public function deleteAll() + public function deleteAll() { $count = 0; if (is_array($keys = $this->_getCacheKeys())) { foreach ($keys as $key) { - $count++; + ++$count; $this->delete($key); } } + return $count; } /** - * Get the hash key passing its suffix + * Get the hash key passing its suffix. * - * @param string $id The hash key suffix - * @return string Hash key to be used by drivers + * @param string $id The hash key suffix + * + * @return string Hash key to be used by drivers */ protected function _getKey($id) { $prefix = isset($this->_options['prefix']) ? $this->_options['prefix'] : ''; - if ( ! $prefix || strpos($id, $prefix) === 0) { + if (!$prefix || 0 === strpos($id, $prefix)) { return $id; - } else { - return $prefix . $id; } + + return $prefix.$id; } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ abstract protected function _getCacheKeys(); /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ abstract protected function _doFetch($id, $testCacheValidity = true); /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ abstract protected function _doContains($id); /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ abstract protected function _doSave($id, $data, $lifeTime = false); /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ abstract protected function _doDelete($id); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Exception.php b/lib/Doctrine/Cache/Exception.php index 1fa224e8d..998a51710 100644 --- a/lib/Doctrine/Cache/Exception.php +++ b/lib/Doctrine/Cache/Exception.php @@ -20,17 +20,18 @@ */ /** - * Doctrine cache exception class + * Doctrine cache exception class. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Cache_Exception extends Doctrine_Exception { -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Interface.php b/lib/Doctrine/Cache/Interface.php index d6e103f49..1274cf75f 100644 --- a/lib/Doctrine/Cache/Interface.php +++ b/lib/Doctrine/Cache/Interface.php @@ -20,51 +20,56 @@ */ /** - * Doctrine cache driver interface + * Doctrine cache driver interface. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ interface Doctrine_Cache_Interface { /** - * Fetch a cache record from this cache driver instance + * Fetch a cache record from this cache driver instance. * - * @param string $id cache id - * @param boolean $testCacheValidity if set to false, the cache validity won't be tested - * @return mixed Returns either the cached data or false + * @param string $id cache id + * @param bool $testCacheValidity if set to false, the cache validity won't be tested + * + * @return mixed Returns either the cached data or false */ public function fetch($id, $testCacheValidity = true); /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ public function contains($id); /** - * Save a cache record and add the key to the index of cached keys + * Save a cache record and add the key to the index of cached keys. * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) + * + * @return bool true if no problem */ public function save($id, $data, $lifeTime = false); /** - * Remove a cache record + * Remove a cache record. * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ public function delete($id); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Memcache.php b/lib/Doctrine/Cache/Memcache.php index f366c204d..ab0afa8cf 100644 --- a/lib/Doctrine/Cache/Memcache.php +++ b/lib/Doctrine/Cache/Memcache.php @@ -20,38 +20,39 @@ */ /** - * Memcache cache driver + * Memcache cache driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Cache_Memcache extends Doctrine_Cache_Driver { /** - * @var Memcache $_memcache memcache object + * @var Memcache memcache object */ - protected $_memcache = null; + protected $_memcache; /** - * constructor + * constructor. * - * @param array $options associative array of cache driver options + * @param array $options associative array of cache driver options */ public function __construct($options = array()) { - if ( ! extension_loaded('memcache')) { + if (!extension_loaded('memcache')) { throw new Doctrine_Cache_Exception('In order to use Memcache driver, the memcache extension must be loaded.'); } parent::__construct($options); if (isset($options['servers'])) { - $value= $options['servers']; + $value = $options['servers']; if (isset($value['host'])) { // in this case, $value seems to be a simple associative array (one server only) $value = array(0 => $value); // let's transform it into a classical array of associative arrays @@ -59,13 +60,13 @@ public function __construct($options = array()) $this->setOption('servers', $value); } - $this->_memcache = new Memcache; + $this->_memcache = new Memcache(); foreach ($this->_options['servers'] as $server) { - if ( ! array_key_exists('persistent', $server)) { + if (!array_key_exists('persistent', $server)) { $server['persistent'] = true; } - if ( ! array_key_exists('port', $server)) { + if (!array_key_exists('port', $server)) { $server['port'] = 11211; } $this->_memcache->addServer($server['host'], $server['port'], $server['persistent']); @@ -73,10 +74,11 @@ public function __construct($options = array()) } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id - * @return mixed Returns either the cached data or false + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { @@ -84,9 +86,10 @@ protected function _doFetch($id, $testCacheValidity = true) } /** - * Test if a cache is available or not (for the given id) + * Test if a cache is available or not (for the given id). * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) @@ -96,12 +99,13 @@ protected function _doContains($id) /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false) { @@ -116,10 +120,11 @@ protected function _doSave($id, $data, $lifeTime = false) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { @@ -127,7 +132,7 @@ protected function _doDelete($id) } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ @@ -146,6 +151,7 @@ protected function _getCacheKeys() } } } + return $keys; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cache/Xcache.php b/lib/Doctrine/Cache/Xcache.php index 6415277e3..a24161e29 100644 --- a/lib/Doctrine/Cache/Xcache.php +++ b/lib/Doctrine/Cache/Xcache.php @@ -20,14 +20,15 @@ */ /** - * Xcache cache driver + * Xcache cache driver. * - * @package Doctrine - * @subpackage Cache * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: $ + * * @author Dmitry Bakaleinik (dima@snaiper.net) * @author Konsta Vesterinen * @author Jonathan H. Wage @@ -35,13 +36,13 @@ class Doctrine_Cache_Xcache extends Doctrine_Cache_Driver { /** - * constructor + * constructor. * - * @param array $options associative array of cache driver options + * @param array $options associative array of cache driver options */ public function __construct($options = array()) { - if ( ! extension_loaded('xcache') ) { + if (!extension_loaded('xcache')) { throw new Doctrine_Cache_Exception('In order to use Xcache driver, the xcache extension must be loaded.'); } @@ -49,10 +50,11 @@ public function __construct($options = array()) } /** - * Test if a cache record exists for the passed id + * Test if a cache record exists for the passed id. * * @param string $id cache id - * @return mixed Returns either the cached data or false + * + * @return mixed Returns either the cached data or false */ protected function _doFetch($id, $testCacheValidity = true) { @@ -60,9 +62,10 @@ protected function _doFetch($id, $testCacheValidity = true) } /** - * Test if a cache is available or not (for the given id) + * Test if a cache is available or not (for the given id). * * @param string $id cache id + * * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ protected function _doContains($id) @@ -72,12 +75,13 @@ protected function _doContains($id) /** * Save a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::save() + * drivers and used in Doctrine_Cache_Driver::save(). + * + * @param string $id cache id + * @param string $data data to cache + * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) * - * @param string $id cache id - * @param string $data data to cache - * @param int $lifeTime if != false, set a specific lifetime for this cache record (null => infinite lifeTime) - * @return boolean true if no problem + * @return bool true if no problem */ protected function _doSave($id, $data, $lifeTime = false) { @@ -86,10 +90,11 @@ protected function _doSave($id, $data, $lifeTime = false) /** * Remove a cache record directly. This method is implemented by the cache - * drivers and used in Doctrine_Cache_Driver::delete() + * drivers and used in Doctrine_Cache_Driver::delete(). * * @param string $id cache id - * @return boolean true if no problem + * + * @return bool true if no problem */ protected function _doDelete($id) { @@ -97,7 +102,7 @@ protected function _doDelete($id) } /** - * Fetch an array of all keys stored in cache + * Fetch an array of all keys stored in cache. * * @return array Returns the array of cache keys */ @@ -105,7 +110,7 @@ protected function _getCacheKeys() { $this->checkAuth(); $keys = array(); - for ($i = 0, $count = xcache_count(XC_TYPE_VAR); $i < $count; $i++) { + for ($i = 0, $count = xcache_count(XC_TYPE_VAR); $i < $count; ++$i) { $entries = xcache_list(XC_TYPE_VAR, $i); if (is_array($entries['cache_list'])) { foreach ($entries['cache_list'] as $entry) { @@ -113,14 +118,14 @@ protected function _getCacheKeys() } } } + return $keys; } /** - * Checks that xcache.admin.enable_auth is Off + * Checks that xcache.admin.enable_auth is Off. * * @throws Doctrine_Cache_Exception When xcache.admin.enable_auth is On - * @return void */ protected function checkAuth() { @@ -128,4 +133,4 @@ protected function checkAuth() throw new Doctrine_Cache_Exception('To use all features of Doctrine_Cache_Xcache, you must set "xcache.admin.enable_auth" to "Off" in your php.ini.'); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cli.php b/lib/Doctrine/Cli.php index f6cd3dd4f..93ca97ab3 100644 --- a/lib/Doctrine/Cli.php +++ b/lib/Doctrine/Cli.php @@ -20,31 +20,32 @@ */ /** - * Command line interface class - * + * Command line interface class. + * * Interface for easily executing Doctrine_Task classes from a command line interface * - * @package Doctrine - * @subpackage Cli * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Cli { /** - * The name of the Doctrine Task base class - * + * The name of the Doctrine Task base class. + * * @var string */ - const TASK_BASE_CLASS = 'Doctrine_Task'; + public const TASK_BASE_CLASS = 'Doctrine_Task'; /** * @var string */ - protected $_scriptName = null; + protected $_scriptName; /** * @var array @@ -57,8 +58,8 @@ class Doctrine_Cli private $_formatter; /** - * An array, keyed on class name, containing task instances - * + * An array, keyed on class name, containing task instances. + * * @var array */ private $_registeredTask = array(); @@ -69,7 +70,7 @@ class Doctrine_Cli private $_taskInstance; /** - * __construct + * __construct. * * @param array [$config=array()] * @param object|null [$formatter=null] Doctrine_Cli_Formatter @@ -81,9 +82,6 @@ public function __construct(array $config = array(), Doctrine_Cli_Formatter $for $this->includeAndRegisterTaskClasses(); } - /** - * @param array $config - */ public function setConfig(array $config) { $this->_config = $config; @@ -114,15 +112,15 @@ public function getFormatter() } /** - * Returns the specified value from the config, or the default value, if specified - * + * Returns the specified value from the config, or the default value, if specified. + * * @param string $name - * @return mixed + * * @throws OutOfBoundsException If the element does not exist in the config */ - public function getConfigValue($name/*, $defaultValue*/) + public function getConfigValue($name/* , $defaultValue */) { - if (! isset($this->_config[$name])) { + if (!isset($this->_config[$name])) { if (func_num_args() > 1) { return func_get_arg(1); } @@ -134,16 +132,17 @@ public function getConfigValue($name/*, $defaultValue*/) } /** - * Returns TRUE if the element in the config has the specified value, or FALSE otherwise - * + * Returns TRUE if the element in the config has the specified value, or FALSE otherwise. + * * If $value is not passed, this method will return TRUE if the specified element has _any_ value, or FALSE if the * element is not set - * + * * For strict checking, set $strict to TRUE - the default is FALSE - * + * * @param string $name * @param mixed [$value=null] * @param bool [$strict=false] + * * @return bool */ public function hasConfigValue($name, $value = null, $strict = false) @@ -164,9 +163,7 @@ public function hasConfigValue($name, $value = null, $strict = false) } /** - * Sets the array of registered tasks - * - * @param array $registeredTask + * Sets the array of registered tasks. */ public function setRegisteredTasks(array $registeredTask) { @@ -174,8 +171,8 @@ public function setRegisteredTasks(array $registeredTask) } /** - * Returns an array containing the registered tasks - * + * Returns an array containing the registered tasks. + * * @return array */ public function getRegisteredTasks() @@ -184,9 +181,10 @@ public function getRegisteredTasks() } /** - * Returns TRUE if the specified Task-class is registered, or FALSE otherwise - * + * Returns TRUE if the specified Task-class is registered, or FALSE otherwise. + * * @param string $className + * * @return bool */ public function taskClassIsRegistered($className) @@ -195,12 +193,13 @@ public function taskClassIsRegistered($className) } /** - * Returns TRUE if a task with the specified name is registered, or FALSE otherwise - * + * Returns TRUE if a task with the specified name is registered, or FALSE otherwise. + * * If a matching task is found, $className is set with the name of the implementing class - * + * * @param string $taskName * @param string|null [&$className=null] + * * @return bool */ public function taskNameIsRegistered($taskName, &$className = null) @@ -208,6 +207,7 @@ public function taskNameIsRegistered($taskName, &$className = null) foreach ($this->getRegisteredTasks() as $currClassName => $task) { if ($task->getTaskName() == $taskName) { $className = $currClassName; + return true; } } @@ -233,8 +233,8 @@ public function getTaskInstance() /** * Called by the constructor, this method includes and registers Doctrine core Tasks and then registers all other - * loaded Task classes - * + * loaded Task classes. + * * The second round of registering will pick-up loaded custom Tasks. Methods are provided that will allow users to * register Tasks loaded after creating an instance of Doctrine_Cli. */ @@ -242,23 +242,23 @@ protected function includeAndRegisterTaskClasses() { $this->includeAndRegisterDoctrineTaskClasses(); - //Always autoregister custom tasks _unless_ we've been explicitly asked not to + // Always autoregister custom tasks _unless_ we've been explicitly asked not to if ($this->getConfigValue('autoregister_custom_tasks', true)) { $this->registerIncludedTaskClasses(); } } /** - * Includes and registers Doctrine-style tasks from the specified directory / directories - * + * Includes and registers Doctrine-style tasks from the specified directory / directories. + * * If no directory is given it looks in the default Doctrine/Task folder for the core tasks - * + * * @param mixed [$directories=null] Can be a string path or array of paths */ protected function includeAndRegisterDoctrineTaskClasses($directories = null) { if (is_null($directories)) { - $directories = Doctrine_Core::getPath() . DIRECTORY_SEPARATOR . 'Doctrine' . DIRECTORY_SEPARATOR . 'Task'; + $directories = Doctrine_Core::getPath().DIRECTORY_SEPARATOR.'Doctrine'.DIRECTORY_SEPARATOR.'Task'; } foreach ((array) $directories as $directory) { @@ -269,24 +269,26 @@ protected function includeAndRegisterDoctrineTaskClasses($directories = null) } /** - * Attempts to include Doctrine-style Task-classes from the specified directory - and nothing more besides - * + * Attempts to include Doctrine-style Task-classes from the specified directory - and nothing more besides. + * * Returns an array containing the names of Task classes included - * + * * This method effectively makes two assumptions: * - The directory contains only _Task_ class-files * - The class files, and the class in each, follow the Doctrine naming conventions - * + * * This means that a file called "Foo.php", say, will be expected to contain a Task class called * "Doctrine_Task_Foo". Hence the method's name, "include*Doctrine*TaskClasses". - * + * * @param string $directory + * * @return array $taskClassesIncluded + * * @throws InvalidArgumentException If the directory does not exist */ protected function includeDoctrineTaskClasses($directory) { - if (! is_dir($directory)) { + if (!is_dir($directory)) { throw new InvalidArgumentException("The directory \"{$directory}\" does not exist"); } @@ -306,17 +308,17 @@ protected function includeDoctrineTaskClasses($directory) */ $matched = (bool) preg_match('/^([A-Z].*?)\.php$/', $baseName, $matches); - if ( ! ($matched && (strpos($baseName, '.inc') === false))) { + if (!($matched && (false === strpos($baseName, '.inc')))) { continue; } - $expectedClassName = self::TASK_BASE_CLASS . '_' . $matches[1]; + $expectedClassName = self::TASK_BASE_CLASS.'_'.$matches[1]; - if ( ! class_exists($expectedClassName)) { - require_once($file->getPathName()); + if (!class_exists($expectedClassName)) { + require_once $file->getPathName(); } - //So was the expected class included, and is it a task? If so, we'll let the calling function know. + // So was the expected class included, and is it a task? If so, we'll let the calling function know. if (class_exists($expectedClassName, false) && $this->classIsTask($expectedClassName)) { $taskClassesIncluded[] = $expectedClassName; } @@ -326,24 +328,25 @@ protected function includeDoctrineTaskClasses($directory) } /** - * Registers the specified _included_ task-class - * + * Registers the specified _included_ task-class. + * * @param string $className + * * @throws InvalidArgumentException If the class does not exist or the task-name is blank - * @throws DomainException If the class is not a Doctrine Task + * @throws DomainException If the class is not a Doctrine Task */ public function registerTaskClass($className) { - //Simply ignore registered classes + // Simply ignore registered classes if ($this->taskClassIsRegistered($className)) { return; } - if ( ! class_exists($className/*, false*/)) { + if (!class_exists($className/* , false */)) { throw new InvalidArgumentException("The task class \"{$className}\" does not exist"); } - if ( ! $this->classIsTask($className)) { + if (!$this->classIsTask($className)) { throw new DomainException("The class \"{$className}\" is not a Doctrine Task"); } @@ -351,24 +354,27 @@ public function registerTaskClass($className) } /** - * Returns TRUE if the specified class is a Task, or FALSE otherwise - * + * Returns TRUE if the specified class is a Task, or FALSE otherwise. + * * @param string $className + * * @return bool */ protected function classIsTask($className) { $reflectionClass = new ReflectionClass($className); + return (bool) $reflectionClass->isSubclassOf(self::TASK_BASE_CLASS); } /** - * Creates, and returns, a new instance of the specified Task class - * + * Creates, and returns, a new instance of the specified Task class. + * * Displays a message, and returns FALSE, if there were problems instantiating the class - * + * * @param string $className - * @param object $cli Doctrine_Cli + * @param object $cli Doctrine_Cli + * * @return object Doctrine_Task */ protected function createTaskInstance($className, Doctrine_Cli $cli) @@ -377,8 +383,8 @@ protected function createTaskInstance($className, Doctrine_Cli $cli) } /** - * Registers all loaded classes - by default - or the specified loaded Task classes - * + * Registers all loaded classes - by default - or the specified loaded Task classes. + * * This method will skip registered task classes, so it can be safely called many times over */ public function registerIncludedTaskClasses() @@ -391,26 +397,23 @@ public function registerIncludedTaskClasses() } /** - * Notify the formatter of a message + * Notify the formatter of a message. * - * @param string $notification The notification message - * @param string $style Style to format the notification with(INFO, ERROR) - * @return void + * @param string $notification The notification message + * @param string $style Style to format the notification with(INFO, ERROR) */ public function notify($notification = null, $style = 'HEADER') { $formatter = $this->getFormatter(); - echo( - $formatter->format($this->getTaskInstance()->getTaskName(), 'INFO') . ' - ' . - $formatter->format($notification, $style) . "\n" - ); + echo + $formatter->format($this->getTaskInstance()->getTaskName(), 'INFO').' - '. + $formatter->format($notification, $style)."\n"; } /** - * Formats, and then returns, the message in the specified exception + * Formats, and then returns, the message in the specified exception. * - * @param Exception $exception * @return string */ protected function formatExceptionMessage(Exception $exception) @@ -418,20 +421,17 @@ protected function formatExceptionMessage(Exception $exception) $message = $exception->getMessage(); if (Doctrine_Core::debug()) { - $message .= "\n" . $exception->getTraceAsString(); + $message .= "\n".$exception->getTraceAsString(); } - return $this->getFormatter()->format($message, 'ERROR') . "\n"; + return $this->getFormatter()->format($message, 'ERROR')."\n"; } /** - * Notify the formatter of an exception - * + * Notify the formatter of an exception. + * * N.B. This should really only be called by Doctrine_Cli::run(). Exceptions should be thrown when errors occur: * it's up to Doctrine_Cli::run() to determine how those exceptions are reported. - * - * @param Exception $exception - * @return void */ protected function notifyException(Exception $exception) { @@ -439,11 +439,10 @@ protected function notifyException(Exception $exception) } /** - * Public function to run the loaded task with the passed arguments + * Public function to run the loaded task with the passed arguments. * - * @param array $args - * @return void * @throws Doctrine_Cli_Exception + * * @todo Should know more about what we're attempting to run so feedback can be improved. Continue refactoring. */ public function run(array $args) @@ -451,14 +450,14 @@ public function run(array $args) try { $this->_run($args); } catch (Exception $exception) { - //Do not rethrow exceptions by default + // Do not rethrow exceptions by default if ($this->getConfigValue('rethrow_exceptions', false)) { throw new $exception($this->formatExceptionMessage($exception)); } $this->notifyException($exception); - //User error + // User error if ($exception instanceof Doctrine_Cli_Exception) { $this->printTasks(); } @@ -466,30 +465,33 @@ public function run(array $args) } /** - * Run the actual task execution with the passed arguments + * Run the actual task execution with the passed arguments. + * + * @param array $args Array of arguments for this task being executed * - * @param array $args Array of arguments for this task being executed - * @return void * @throws Doctrine_Cli_Exception If the requested task has not been registered or if required arguments are missing + * * @todo Continue refactoring for testing */ protected function _run(array $args) - { + { $this->_scriptName = $args[0]; - + $requestedTaskName = isset($args[1]) ? $args[1] : null; - - if ( ! $requestedTaskName || $requestedTaskName == 'help') { - $this->printTasks(null, $requestedTaskName == 'help' ? true : false); + + if (!$requestedTaskName || 'help' == $requestedTaskName) { + $this->printTasks(null, 'help' == $requestedTaskName ? true : false); + return; } - - if ($requestedTaskName && isset($args[2]) && $args[2] === 'help') { + + if ($requestedTaskName && isset($args[2]) && 'help' === $args[2]) { $this->printTasks($requestedTaskName, true); + return; } - if (! $this->taskNameIsRegistered($requestedTaskName, $taskClassName)) { + if (!$this->taskNameIsRegistered($requestedTaskName, $taskClassName)) { throw new Doctrine_Cli_Exception("The task \"{$requestedTaskName}\" has not been registered"); } @@ -499,17 +501,17 @@ protected function _run(array $args) } /** - * Executes the task with the specified _prepared_ arguments - * + * Executes the task with the specified _prepared_ arguments. + * * @param object $task Doctrine_Task - * @param array $preparedArguments + * * @throws Doctrine_Cli_Exception If required arguments are missing */ protected function executeTask(Doctrine_Task $task, array $preparedArguments) { $task->setArguments($preparedArguments); - if (! $task->validate()) { + if (!$task->validate()) { throw new Doctrine_Cli_Exception('Required arguments missing'); } @@ -518,56 +520,59 @@ protected function executeTask(Doctrine_Task $task, array $preparedArguments) /** * Prepare the raw arguments for execution. Combines with the required and optional argument - * list in order to determine a complete array of arguments for the task + * list in order to determine a complete array of arguments for the task. + * + * @param array $args Array of raw arguments * - * @param array $args Array of raw arguments * @return array $prepared Array of prepared arguments + * * @todo Continue refactoring for testing */ protected function prepareArgs(array $args) { $taskInstance = $this->getTaskInstance(); - + $args = array_values($args); - + // First lets load populate an array with all the possible arguments. required and optional $prepared = array(); - + $requiredArguments = $taskInstance->getRequiredArguments(); foreach ($requiredArguments as $key => $arg) { $prepared[$arg] = null; } - + $optionalArguments = $taskInstance->getOptionalArguments(); foreach ($optionalArguments as $key => $arg) { $prepared[$arg] = null; } - + // If we have a config array then lets try and fill some of the arguments with the config values foreach ($this->getConfig() as $key => $value) { if (array_key_exists($key, $prepared)) { $prepared[$key] = $value; } } - + // Now lets fill in the entered arguments to the prepared array $copy = $args; foreach ($prepared as $key => $value) { - if ( ! $value && !empty($copy)) { + if (!$value && !empty($copy)) { $prepared[$key] = $copy[0]; unset($copy[0]); $copy = array_values($copy); } } - + return $prepared; } /** - * Prints an index of all the available tasks in the CLI instance - * + * Prints an index of all the available tasks in the CLI instance. + * * @param string|null [$taskName=null] * @param bool [$full=false] + * * @todo Continue refactoring for testing */ public function printTasks($taskName = null, $full = false) @@ -575,27 +580,27 @@ public function printTasks($taskName = null, $full = false) $formatter = $this->getFormatter(); $config = $this->getConfig(); - $taskIndex = $formatter->format('Doctrine Command Line Interface', 'HEADER') . "\n\n"; + $taskIndex = $formatter->format('Doctrine Command Line Interface', 'HEADER')."\n\n"; foreach ($this->getRegisteredTasks() as $task) { if ($taskName && (strtolower($taskName) != strtolower($task->getTaskName()))) { continue; } - $taskIndex .= $formatter->format($this->_scriptName . ' ' . $task->getTaskName(), 'INFO'); + $taskIndex .= $formatter->format($this->_scriptName.' '.$task->getTaskName(), 'INFO'); if ($full) { - $taskIndex .= ' - ' . $task->getDescription() . "\n"; + $taskIndex .= ' - '.$task->getDescription()."\n"; $args = ''; $args .= $this->assembleArgumentList($task->getRequiredArgumentsDescriptions(), $config, $formatter); $args .= $this->assembleArgumentList($task->getOptionalArgumentsDescriptions(), $config, $formatter); if ($args) { - $taskIndex .= "\n" . $formatter->format('Arguments:', 'HEADER') . "\n" . $args; + $taskIndex .= "\n".$formatter->format('Arguments:', 'HEADER')."\n".$args; } } - + $taskIndex .= "\n"; } @@ -603,9 +608,8 @@ public function printTasks($taskName = null, $full = false) } /** - * @param array $argumentsDescriptions - * @param array $config * @param object $formatter Doctrine_Cli_Formatter + * * @return string */ protected function assembleArgumentList(array $argumentsDescriptions, array $config, Doctrine_Cli_Formatter $formatter) @@ -613,8 +617,8 @@ protected function assembleArgumentList(array $argumentsDescriptions, array $con $argumentList = ''; foreach ($argumentsDescriptions as $name => $description) { - $argumentList .= $formatter->format($name, 'ERROR') . ' - '; - + $argumentList .= $formatter->format($name, 'ERROR').' - '; + if (isset($config[$name])) { $argumentList .= $formatter->format($config[$name], 'COMMENT'); } else { @@ -628,10 +632,10 @@ protected function assembleArgumentList(array $argumentsDescriptions, array $con } /** - * Used by Doctrine_Cli::loadTasks() and Doctrine_Cli::getLoadedTasks() to re-create their pre-refactoring behaviour - * + * Used by Doctrine_Cli::loadTasks() and Doctrine_Cli::getLoadedTasks() to re-create their pre-refactoring behaviour. + * * @ignore - * @param array $registeredTask + * * @return array */ private function createOldStyleTaskList(array $registeredTask) @@ -647,33 +651,36 @@ private function createOldStyleTaskList(array $registeredTask) } /** - * Old method retained for backwards compatibility - * + * Old method retained for backwards compatibility. + * * @deprecated + * + * @param mixed|null $directory */ public function loadTasks($directory = null) { $this->includeAndRegisterDoctrineTaskClasses($directory); + return $this->createOldStyleTaskList($this->getRegisteredTasks()); } /** - * Old method retained for backwards compatibility - * + * Old method retained for backwards compatibility. + * * @deprecated */ protected function _getTaskClassFromArgs(array $args) { - return self::TASK_BASE_CLASS . '_' . Doctrine_Inflector::classify(str_replace('-', '_', $args[1])); + return self::TASK_BASE_CLASS.'_'.Doctrine_Inflector::classify(str_replace('-', '_', $args[1])); } /** - * Old method retained for backwards compatibility - * + * Old method retained for backwards compatibility. + * * @deprecated */ public function getLoadedTasks() { return $this->createOldStyleTaskList($this->getRegisteredTasks()); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cli/AnsiColorFormatter.php b/lib/Doctrine/Cli/AnsiColorFormatter.php index cca3afb7d..a443baa5a 100644 --- a/lib/Doctrine/Cli/AnsiColorFormatter.php +++ b/lib/Doctrine/Cli/AnsiColorFormatter.php @@ -29,29 +29,28 @@ /** * Doctrine_AnsiColorFormatter provides methods to colorize text to be displayed on a console. - * This class was taken from the symfony-project source + * This class was taken from the symfony-project source. * - * @package Doctrine - * @subpackage Cli * @author Fabien Potencier * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 4252 $ */ class Doctrine_Cli_AnsiColorFormatter extends Doctrine_Cli_Formatter { - protected - $_styles = array( - 'HEADER' => array('fg' => 'black', 'bold' => true), - 'ERROR' => array('bg' => 'red', 'fg' => 'white', 'bold' => true), - 'INFO' => array('fg' => 'green', 'bold' => true), - 'COMMENT' => array('fg' => 'yellow'), - ), - $_options = array('bold' => 1, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, 'conceal' => 8), - $_foreground = array('black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'white' => 37), - $_background = array('black' => 40, 'red' => 41, 'green' => 42, 'yellow' => 43, 'blue' => 44, 'magenta' => 45, 'cyan' => 46, 'white' => 47); + protected $_styles = array( + 'HEADER' => array('fg' => 'black', 'bold' => true), + 'ERROR' => array('bg' => 'red', 'fg' => 'white', 'bold' => true), + 'INFO' => array('fg' => 'green', 'bold' => true), + 'COMMENT' => array('fg' => 'yellow'), + ); + protected $_options = array('bold' => 1, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, 'conceal' => 8); + protected $_foreground = array('black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'white' => 37); + protected $_background = array('black' => 40, 'red' => 41, 'green' => 42, 'yellow' => 43, 'blue' => 44, 'magenta' => 45, 'cyan' => 46, 'white' => 47); /** * Sets a new style. @@ -74,15 +73,15 @@ public function setStyle($name, $options = array()) */ public function format($text = '', $parameters = array(), $stream = STDOUT) { - if ( ! $this->supportsColors($stream)) { + if (!$this->supportsColors($stream)) { return $text; } - if ( ! is_array($parameters) && 'NONE' == $parameters) { + if (!is_array($parameters) && 'NONE' == $parameters) { return $text; } - if ( ! is_array($parameters) && isset($this->_styles[$parameters])) { + if (!is_array($parameters) && isset($this->_styles[$parameters])) { $parameters = $this->_styles[$parameters]; } @@ -90,11 +89,11 @@ public function format($text = '', $parameters = array(), $stream = STDOUT) if (isset($parameters['fg'])) { $codes[] = $this->_foreground[$parameters['fg']]; } - + if (isset($parameters['bg'])) { $codes[] = $this->_background[$parameters['bg']]; } - + foreach ($this->_options as $option => $value) { if (isset($parameters[$option]) && $parameters[$option]) { $codes[] = $value; @@ -109,7 +108,8 @@ public function format($text = '', $parameters = array(), $stream = STDOUT) * * @param string The section name * @param string The text message - * @param integer The maximum size allowed for a line (65 by default) + * @param int The maximum size allowed for a line (65 by default) + * @param mixed|null $size */ public function formatSection($section, $text, $size = null) { @@ -122,13 +122,14 @@ public function formatSection($section, $text, $size = null) * Truncates a line. * * @param string The text - * @param integer The maximum size of the returned string (65 by default) + * @param int The maximum size of the returned string (65 by default) + * @param mixed|null $size * * @return string The truncated string */ public function excerpt($text, $size = null) { - if ( ! $size) { + if (!$size) { $size = $this->size; } @@ -138,7 +139,7 @@ public function excerpt($text, $size = null) $subsize = floor(($size - 3) / 2); - return substr($text, 0, $subsize) . $this->format('...', 'INFO').substr($text, -$subsize); + return substr($text, 0, $subsize).$this->format('...', 'INFO').substr($text, -$subsize); } /** @@ -151,10 +152,10 @@ public function excerpt($text, $size = null) * * @param mixed A stream * - * @return Boolean true if the stream supports colorization, false otherwise + * @return bool true if the stream supports colorization, false otherwise */ public function supportsColors($stream) { return DIRECTORY_SEPARATOR != '\\' && function_exists('posix_isatty') && @posix_isatty($stream); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Cli/Exception.php b/lib/Doctrine/Cli/Exception.php index a8c441072..2f12ddf21 100644 --- a/lib/Doctrine/Cli/Exception.php +++ b/lib/Doctrine/Cli/Exception.php @@ -20,15 +20,17 @@ */ /** - * Cli exception class + * Cli exception class. * - * @package Doctrine - * @subpackage Cli * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Cli_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Cli/Formatter.php b/lib/Doctrine/Cli/Formatter.php index 4ba794505..486729ff3 100644 --- a/lib/Doctrine/Cli/Formatter.php +++ b/lib/Doctrine/Cli/Formatter.php @@ -29,15 +29,15 @@ /** * Doctrine_Cli_Formatter provides methods to format text to be displayed on a console. - * This class was taken from the symfony-project source + * This class was taken from the symfony-project source. * - * @package Doctrine - * @subpackage Cli * @author Fabien Potencier * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ */ class Doctrine_Cli_Formatter @@ -45,12 +45,11 @@ class Doctrine_Cli_Formatter protected $_size = 65; /** - * __construct + * __construct. * - * @param string $maxLineSize - * @return void + * @param string $maxLineSize */ - function __construct($maxLineSize = 65) + public function __construct($maxLineSize = 65) { $this->_size = $maxLineSize; } @@ -74,24 +73,26 @@ public function format($text = '', $parameters = array(), $stream = STDOUT) * * @param string The section name * @param string The text message - * @param integer The maximum size allowed for a line (65 by default) + * @param int The maximum size allowed for a line (65 by default) + * @param mixed|null $size */ public function formatSection($section, $text, $size = null) { - return sprintf(">> %-$9s %s", $section, $this->excerpt($text, $size)); + return sprintf('>> %-$9s %s', $section, $this->excerpt($text, $size)); } /** * Truncates a line. * * @param string The text - * @param integer The maximum size of the returned string (65 by default) + * @param int The maximum size of the returned string (65 by default) + * @param mixed|null $size * * @return string The truncated string */ public function excerpt($text, $size = null) { - if ( ! $size) { + if (!$size) { $size = $this->_size; } @@ -107,10 +108,10 @@ public function excerpt($text, $size = null) /** * Sets the maximum line size. * - * @param integer The maximum line size for a message + * @param int The maximum line size for a message */ public function setMaxLineSize($size) { $this->_size = $size; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Collection.php b/lib/Doctrine/Collection.php index 25b7ca441..8095b7d19 100644 --- a/lib/Doctrine/Collection.php +++ b/lib/Doctrine/Collection.php @@ -23,86 +23,86 @@ * Doctrine_Collection * Collection of Doctrine_Record objects. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7686 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection extends Doctrine_Access implements Countable, IteratorAggregate, Serializable { /** - * @var array $data an array containing the records of this collection + * @var array an array containing the records of this collection */ protected $data = array(); /** - * @var Doctrine_Table $table each collection has only records of specified table + * @var Doctrine_Table each collection has only records of specified table */ protected $_table; /** - * @var array $_snapshot a snapshot of the fetched data + * @var array a snapshot of the fetched data */ protected $_snapshot = array(); /** - * @var Doctrine_Record $reference collection can belong to a record + * @var Doctrine_Record collection can belong to a record */ protected $reference; /** - * @var string $referenceField the reference field of the collection + * @var string the reference field of the collection */ protected $referenceField; /** - * @var Doctrine_Relation the record this collection is related to, if any + * @var Doctrine_Relation the record this collection is related to, if any */ protected $relation; /** - * @var string $keyColumn the name of the column that is used for collection key mapping + * @var string the name of the column that is used for collection key mapping */ protected $keyColumn; /** - * @var Doctrine_Null $null used for extremely fast null value testing + * @var Doctrine_Null used for extremely fast null value testing */ protected static $null; /** - * constructor + * constructor. * * @param Doctrine_Table|string $table + * @param mixed|null $keyColumn */ public function __construct($table, $keyColumn = null) { - if ( ! ($table instanceof Doctrine_Table)) { + if (!($table instanceof Doctrine_Table)) { $table = Doctrine_Core::getTable($table); } $this->_table = $table; - if ($keyColumn === null) { + if (null === $keyColumn) { $keyColumn = $table->getBoundQueryPart('indexBy'); } - if ($keyColumn === null) { - $keyColumn = $table->getAttribute(Doctrine_Core::ATTR_COLL_KEY); + if (null === $keyColumn) { + $keyColumn = $table->getAttribute(Doctrine_Core::ATTR_COLL_KEY); } - if ($keyColumn !== null) { + if (null !== $keyColumn) { $this->keyColumn = $keyColumn; } } /** - * Initializes the null object for this collection - * - * @return void + * Initializes the null object for this collection. */ public static function initNullObject(Doctrine_Null $null) { @@ -112,7 +112,7 @@ public static function initNullObject(Doctrine_Null $null) public static function create($table, $keyColumn = null, $class = null) { if (is_null($class)) { - if ( ! $table instanceof Doctrine_Table) { + if (!$table instanceof Doctrine_Table) { $table = Doctrine_Core::getTable($table); } $class = $table->getAttribute(Doctrine_Core::ATTR_COLLECTION_CLASS); @@ -122,7 +122,7 @@ public static function create($table, $keyColumn = null, $class = null) } /** - * Get the table this collection belongs to + * Get the table this collection belongs to. * * @return Doctrine_Table */ @@ -132,9 +132,8 @@ public function getTable() } /** - * Set the data for the Doctrin_Collection instance + * Set the data for the Doctrin_Collection instance. * - * @param array $data * @return Doctrine_Collection */ public function setData(array $data) @@ -142,9 +141,8 @@ public function setData(array $data) $this->data = $data; } - /** - * This method is automatically called when this Doctrine_Collection is serialized + * This method is automatically called when this Doctrine_Collection is serialized. * * @return string */ @@ -156,9 +154,7 @@ public function serialize() } /** - * This method is automatically called everytime a Doctrine_Collection object is unserialized - * - * @return void + * This method is automatically called everytime a Doctrine_Collection object is unserialized. */ public function unserialize($serialized) { @@ -168,20 +164,15 @@ public function unserialize($serialized) } /** - * Serializes the current instance for php 7.4+ + * Serializes the current instance for php 7.4+. * * @return array */ - public function __serialize() { - + public function __serialize() + { $vars = get_object_vars($this); - unset($vars['reference']); - unset($vars['referenceField']); - unset($vars['relation']); - unset($vars['expandable']); - unset($vars['expanded']); - unset($vars['generator']); + unset($vars['reference'], $vars['referenceField'], $vars['relation'], $vars['expandable'], $vars['expanded'], $vars['generator']); $vars['_table'] = $vars['_table']->getComponentName(); @@ -189,36 +180,34 @@ public function __serialize() { } /** - * Unserializes a Doctrine_Collection instance for php 7.4+ - * - * @param string $serialized A serialized Doctrine_Collection instance + * Unserializes a Doctrine_Collection instance for php 7.4+. */ public function __unserialize($data) { - $manager = Doctrine_Manager::getInstance(); - $connection = $manager->getCurrentConnection(); - + $manager = Doctrine_Manager::getInstance(); + $connection = $manager->getCurrentConnection(); foreach ($data as $name => $values) { - $this->$name = $values; + $this->{$name} = $values; } $this->_table = $connection->getTable($this->_table); $keyColumn = isset($array['keyColumn']) ? $array['keyColumn'] : null; - if ($keyColumn === null) { + if (null === $keyColumn) { $keyColumn = $this->_table->getBoundQueryPart('indexBy'); } - if ($keyColumn !== null) { + if (null !== $keyColumn) { $this->keyColumn = $keyColumn; } } /** - * Sets the key column for this collection + * Sets the key column for this collection. * * @param string $column + * * @return Doctrine_Collection $this */ public function setKeyColumn($column) @@ -229,7 +218,7 @@ public function setKeyColumn($column) } /** - * Get the name of the key column + * Get the name of the key column. * * @return string */ @@ -239,7 +228,7 @@ public function getKeyColumn() } /** - * Get all the records as an array + * Get all the records as an array. * * @return array */ @@ -249,7 +238,7 @@ public function getData() } /** - * Get the first record in the collection + * Get the first record in the collection. * * @return Doctrine_Record */ @@ -259,7 +248,7 @@ public function getFirst() } /** - * Get the last record in the collection + * Get the last record in the collection. * * @return Doctrine_Record */ @@ -269,7 +258,7 @@ public function getLast() } /** - * Get the last record in the collection + * Get the last record in the collection. * * @return Doctrine_Record */ @@ -279,7 +268,7 @@ public function end() } /** - * Get the current key + * Get the current key. * * @return Doctrine_Record */ @@ -289,7 +278,7 @@ public function key() } /** - * Sort by key + * Sort by key. * * @return Doctrine_Collection */ @@ -301,35 +290,32 @@ public function ksort() } /** - * Sets a reference pointer - * - * @return void + * Sets a reference pointer. */ public function setReference(Doctrine_Record $record, Doctrine_Relation $relation) { $this->reference = $record; - $this->relation = $relation; + $this->relation = $relation; - if ($relation instanceof Doctrine_Relation_ForeignKey || - $relation instanceof Doctrine_Relation_LocalKey) { + if ($relation instanceof Doctrine_Relation_ForeignKey + || $relation instanceof Doctrine_Relation_LocalKey) { $this->referenceField = $relation->getForeignFieldName(); $value = $record->get($relation->getLocalFieldName()); foreach ($this->data as $record) { - if ($value !== null) { + if (null !== $value) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); } } } elseif ($relation instanceof Doctrine_Relation_Association) { - } } /** - * Get reference to Doctrine_Record instance + * Get reference to Doctrine_Record instance. * * @return Doctrine_Record $reference */ @@ -339,24 +325,25 @@ public function getReference() } /** - * Removes a specified collection element + * Removes a specified collection element. * - * @param mixed $key - * @return boolean + * @return bool */ public function remove($key) { $removed = $this->data[$key]; unset($this->data[$key]); + return $removed; } /** - * Whether or not this collection contains a specified element + * Whether or not this collection contains a specified element. + * + * @param mixed $key the key of the element * - * @param mixed $key the key of the element - * @return boolean + * @return bool */ public function contains($key) { @@ -364,10 +351,7 @@ public function contains($key) } /** - * Search a Doctrine_Record instance - * - * @param string $Doctrine_Record - * @return void + * Search a Doctrine_Record instance. */ public function search(Doctrine_Record $record) { @@ -375,7 +359,7 @@ public function search(Doctrine_Record $record) } /** - * Gets a record for given key + * Gets a record for given key. * * There are two special cases: * @@ -387,24 +371,25 @@ public function search(Doctrine_Record $record) * * Collection also maps referential information to newly created records * - * @param mixed $key the key of the element - * @return Doctrine_Record return a specified record + * @param mixed $key the key of the element + * + * @return Doctrine_Record return a specified record */ public function get($key) { - if ( ! isset($this->data[$key])) { + if (!isset($this->data[$key])) { $record = $this->_table->create(); if (isset($this->referenceField)) { $value = $this->reference->get($this->relation->getLocalFieldName()); - if ($value !== null) { + if (null !== $value) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); } } - if ($key === null) { + if (null === $key) { $this->data[] = $record; } else { $this->data[$key] = $record; @@ -421,9 +406,9 @@ public function get($key) } /** - * Get array of primary keys for all the records in the collection + * Get array of primary keys for all the records in the collection. * - * @return array an array containing all primary keys + * @return array an array containing all primary keys */ public function getPrimaryKeys() { @@ -437,11 +422,12 @@ public function getPrimaryKeys() $list[] = $record->getIncremented(); } } + return $list; } /** - * Get all keys of the data in the collection + * Get all keys of the data in the collection. * * @return array */ @@ -452,22 +438,21 @@ public function getKeys() /** * Gets the number of records in this collection - * This class implements interface countable + * This class implements interface countable. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->data); } /** - * Set a Doctrine_Record instance to the collection + * Set a Doctrine_Record instance to the collection. * - * @param integer $key + * @param int $key * @param Doctrine_Record $record - * @return void */ public function set($key, $record) { @@ -479,17 +464,18 @@ public function set($key, $record) } /** - * Adds a record to collection + * Adds a record to collection. + * + * @param Doctrine_Record $record record to be added + * @param string $key optional key for the record * - * @param Doctrine_Record $record record to be added - * @param string $key optional key for the record - * @return boolean + * @return bool */ public function add($record, $key = null) { if (isset($this->referenceField)) { $value = $this->reference->get($this->relation->getLocalFieldName()); - if ($value !== null) { + if (null !== $value) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); @@ -502,7 +488,7 @@ public function add($record, $key = null) } } } - /** + /* * for some weird reason in_array cannot be used here (php bug ?) * * if used it results in fatal error : [ nesting level too deep ] @@ -518,12 +504,13 @@ public function add($record, $key = null) return false; } $this->data[$key] = $record; + return true; } if (isset($this->keyColumn)) { $value = $record->get($this->keyColumn); - if ($value === null) { + if (null === $value) { throw new Doctrine_Collection_Exception("Couldn't create collection index. Record field '".$this->keyColumn."' was null."); } $this->data[$value] = $record; @@ -535,9 +522,8 @@ public function add($record, $key = null) } /** - * Merges collection into $this and returns merged collection + * Merges collection into $this and returns merged collection. * - * @param Doctrine_Collection $coll * @return Doctrine_Collection */ public function merge(Doctrine_Collection $coll) @@ -545,7 +531,7 @@ public function merge(Doctrine_Collection $coll) $localBase = $this->getTable()->getComponentName(); $otherBase = $coll->getTable()->getComponentName(); - if ($otherBase != $localBase && !is_subclass_of($otherBase, $localBase) ) { + if ($otherBase != $localBase && !is_subclass_of($otherBase, $localBase)) { throw new Doctrine_Collection_Exception("Can't merge collections with incompatible record types"); } @@ -557,32 +543,31 @@ public function merge(Doctrine_Collection $coll) } /** - * Load all relationships or the named relationship passed + * Load all relationships or the named relationship passed. * - * @param mixed $name - * @return boolean + * @return bool */ public function loadRelated($name = null) { $list = array(); $query = $this->_table->createQuery(); - if ( ! isset($name)) { + if (!isset($name)) { foreach ($this->data as $record) { $value = $record->getIncremented(); - if ($value !== null) { + if (null !== $value) { $list[] = $value; } } - $query->where($this->_table->getComponentName() . '.id IN (' . substr(str_repeat("?, ", count($list)),0,-2) . ')'); - if ( ! $list) { - $query->where($this->_table->getComponentName() . '.id IN (' . substr(str_repeat("?, ", count($list)),0,-2) . ')', $list); + $query->where($this->_table->getComponentName().'.id IN ('.substr(str_repeat('?, ', count($list)), 0, -2).')'); + if (!$list) { + $query->where($this->_table->getComponentName().'.id IN ('.substr(str_repeat('?, ', count($list)), 0, -2).')', $list); } return $query; } - $rel = $this->_table->getRelation($name); + $rel = $this->_table->getRelation($name); if ($rel instanceof Doctrine_Relation_LocalKey || $rel instanceof Doctrine_Relation_ForeignKey) { foreach ($this->data as $record) { @@ -591,36 +576,34 @@ public function loadRelated($name = null) } else { foreach ($this->data as $record) { $value = $record->getIncremented(); - if ($value !== null) { + if (null !== $value) { $list[] = $value; } } } - if ( ! $list) { + if (!$list) { return; } - $dql = $rel->getRelationDql(count($list), 'collection'); + $dql = $rel->getRelationDql(count($list), 'collection'); - $coll = $query->query($dql, $list); + $coll = $query->query($dql, $list); $this->populateRelated($name, $coll); } /** - * Populate the relationship $name for all records in the passed collection + * Populate the relationship $name for all records in the passed collection. * * @param string $name - * @param Doctrine_Collection $coll - * @return void */ public function populateRelated($name, Doctrine_Collection $coll) { - $rel = $this->_table->getRelation($name); - $table = $rel->getTable(); + $rel = $this->_table->getRelation($name); + $table = $rel->getTable(); $foreign = $rel->getForeign(); - $local = $rel->getLocal(); + $local = $rel->getLocal(); if ($rel instanceof Doctrine_Relation_LocalKey) { foreach ($this->data as $key => $record) { @@ -632,7 +615,7 @@ public function populateRelated($name, Doctrine_Collection $coll) } } elseif ($rel instanceof Doctrine_Relation_ForeignKey) { foreach ($this->data as $key => $record) { - if ( ! $record->exists()) { + if (!$record->exists()) { continue; } $sub = Doctrine_Collection::create($table); @@ -648,11 +631,11 @@ public function populateRelated($name, Doctrine_Collection $coll) } } elseif ($rel instanceof Doctrine_Relation_Association) { $identifier = $this->_table->getIdentifier(); - $asf = $rel->getAssociationFactory(); - $name = $table->getComponentName(); + $asf = $rel->getAssociationFactory(); + $name = $table->getComponentName(); foreach ($this->data as $key => $record) { - if ( ! $record->exists()) { + if (!$record->exists()) { continue; } $sub = Doctrine_Collection::create($table); @@ -662,13 +645,12 @@ public function populateRelated($name, Doctrine_Collection $coll) } } $this->data[$key]->setRelated($name, $sub); - } } } /** - * Get normal iterator - an iterator that will not expand this collection + * Get normal iterator - an iterator that will not expand this collection. * * @return Doctrine_Iterator_Normal $iterator */ @@ -678,7 +660,7 @@ public function getNormalIterator() } /** - * Takes a snapshot from this collection + * Takes a snapshot from this collection. * * snapshots are used for diff processing, for example * when a fetched collection has three elements, then two of those @@ -697,9 +679,9 @@ public function takeSnapshot() } /** - * Gets the data of the last snapshot + * Gets the data of the last snapshot. * - * @return array returns the data in last snapshot + * @return array returns the data in last snapshot */ public function getSnapshot() { @@ -707,7 +689,7 @@ public function getSnapshot() } /** - * Processes the difference of the last snapshot and the current data + * Processes the difference of the last snapshot and the current data. * * an example: * Snapshot with the objects 1, 2 and 4 @@ -719,7 +701,7 @@ public function getSnapshot() */ public function processDiff() { - foreach (array_udiff($this->_snapshot, $this->data, array($this, "compareRecords")) as $record) { + foreach (array_udiff($this->_snapshot, $this->data, array($this, 'compareRecords')) as $record) { $record->delete(); } @@ -727,16 +709,15 @@ public function processDiff() } /** - * Mimics the result of a $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY); + * Mimics the result of a $query->execute(array(), Doctrine_Core::HYDRATE_ARRAY);. * - * @param boolean $deep + * @param bool $deep */ public function toArray($deep = true, $prefixKey = false) { $data = array(); foreach ($this as $key => $record) { - - $key = $prefixKey ? get_class($record) . '_' .$key:$key; + $key = $prefixKey ? get_class($record).'_'.$key : $key; $data[$key] = $record->toArray($deep, $prefixKey); } @@ -745,18 +726,20 @@ public function toArray($deep = true, $prefixKey = false) } /** - * Build an array made up of the values from the 2 specified columns + * Build an array made up of the values from the 2 specified columns. * * @param string $key * @param string $value + * * @return array $result */ public function toKeyValueArray($key, $value) { $result = array(); foreach ($this as $record) { - $result[$record->$key] = $record->$value; + $result[$record->{$key}] = $record->{$value}; } + return $result; } @@ -765,7 +748,7 @@ public function toHierarchy() $collection = $this; $table = $collection->getTable(); - if ( ! $table->isTree() || ! $table->hasColumn('level')) { + if (!$table->isTree() || !$table->hasColumn('level')) { throw new Doctrine_Exception('Cannot hydrate model that does not implements Tree behavior with `level` column'); } @@ -786,13 +769,13 @@ public function toHierarchy() $l = count($stack); // Check if we're dealing with different levels - while($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { + while ($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { array_pop($stack->data); - $l--; + --$l; } // Stack is empty (we are inspecting the root) - if ($l == 0) { + if (0 == $l) { // Assigning the root child $i = count($trees); $trees[$i] = $item; @@ -805,14 +788,14 @@ public function toHierarchy() } } } + return $trees; } /** - * Populate a Doctrine_Collection from an array of data + * Populate a Doctrine_Collection from an array of data. * * @param string $array - * @return void */ public function fromArray($array, $deep = true) { @@ -823,7 +806,7 @@ public function fromArray($array, $deep = true) } /** - * synchronizes a Doctrine_Collection with data from an array + * synchronizes a Doctrine_Collection with data from an array. * * it expects an array representation of a Doctrine_Collection similar to the return * value of the toArray() method. It will create Dectrine_Records that don't exist @@ -854,39 +837,37 @@ public function synchronizeFromArray(array $array) } /** - * Export a Doctrine_Collection to one of the supported Doctrine_Parser formats + * Export a Doctrine_Collection to one of the supported Doctrine_Parser formats. * * @param string $type * @param string $deep - * @return void */ public function exportTo($type, $deep = true) { - if ($type == 'array') { + if ('array' == $type) { return $this->toArray($deep); - } else { - return Doctrine_Parser::dump($this->toArray($deep, true), $type); } + + return Doctrine_Parser::dump($this->toArray($deep, true), $type); } /** - * Import data to a Doctrine_Collection from one of the supported Doctrine_Parser formats + * Import data to a Doctrine_Collection from one of the supported Doctrine_Parser formats. * * @param string $type * @param string $data - * @return void */ public function importFrom($type, $data) { - if ($type == 'array') { + if ('array' == $type) { return $this->fromArray($data); - } else { - return $this->fromArray(Doctrine_Parser::load($data, $type)); } + + return $this->fromArray(Doctrine_Parser::load($data, $type)); } /** - * Perform a delete diff between the last snapshot and the current data + * Perform a delete diff between the last snapshot and the current data. * * @return array $diff */ @@ -896,21 +877,22 @@ public function getDeleteDiff() } /** - * Perform a insert diff between the last snapshot and the current data + * Perform a insert diff between the last snapshot and the current data. * * @return array $diff */ public function getInsertDiff() { - return array_udiff($this->data, $this->_snapshot, array($this, "compareRecords")); + return array_udiff($this->data, $this->_snapshot, array($this, 'compareRecords')); } /** - * Compares two records. To be used on _snapshot diffs using array_udiff + * Compares two records. To be used on _snapshot diffs using array_udiff. * * @param Doctrine_Record $a * @param Doctrine_Record $b - * @return integer + * + * @return int */ protected function compareRecords($a, $b) { @@ -923,14 +905,15 @@ protected function compareRecords($a, $b) /** * Saves all records of this collection and processes the - * difference of the last snapshot and the current data + * difference of the last snapshot and the current data. + * + * @param Doctrine_Connection $conn optional connection parameter * - * @param Doctrine_Connection $conn optional connection parameter * @return Doctrine_Collection */ public function save(Doctrine_Connection $conn = null, $processDiff = true) { - if ($conn == null) { + if (null == $conn) { $conn = $this->_table->getConnection(); } @@ -958,14 +941,15 @@ public function save(Doctrine_Connection $conn = null, $processDiff = true) /** * Replaces all records of this collection and processes the - * difference of the last snapshot and the current data + * difference of the last snapshot and the current data. + * + * @param Doctrine_Connection $conn optional connection parameter * - * @param Doctrine_Connection $conn optional connection parameter * @return Doctrine_Collection */ public function replace(Doctrine_Connection $conn = null, $processDiff = true) { - if ($conn == null) { + if (null == $conn) { $conn = $this->_table->getConnection(); } @@ -992,13 +976,13 @@ public function replace(Doctrine_Connection $conn = null, $processDiff = true) } /** - * Deletes all records from this collection + * Deletes all records from this collection. * * @return Doctrine_Collection */ public function delete(Doctrine_Connection $conn = null, $clearColl = true) { - if ($conn == null) { + if (null == $conn) { $conn = $this->_table->getConnection(); } @@ -1025,8 +1009,6 @@ public function delete(Doctrine_Connection $conn = null, $clearColl = true) /** * Clears the collection. - * - * @return void */ public function clear() { @@ -1037,13 +1019,11 @@ public function clear() * Frees the resources used by the collection. * WARNING: After invoking free() the collection is no longer considered to * be in a useable state. Subsequent usage may result in unexpected behavior. - * - * @return void */ public function free($deep = false) { foreach ($this->getData() as $key => $record) { - if ( ! ($record instanceof Doctrine_Null)) { + if (!($record instanceof Doctrine_Null)) { $record->free($deep); } } @@ -1057,19 +1037,20 @@ public function free($deep = false) } /** - * Get collection data iterator + * Get collection data iterator. * * @return Iterator */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { $data = $this->data; + return new ArrayIterator($data); } /** - * Returns a string representation of this object + * Returns a string representation of this object. * * @return string $string */ @@ -1079,7 +1060,7 @@ public function __toString() } /** - * Returns the relation object + * Returns the relation object. * * @return Doctrine_Relation */ @@ -1090,19 +1071,21 @@ public function getRelation() /** * checks if one of the containing records is modified - * returns true if modified, false otherwise + * returns true if modified, false otherwise. * - * @return boolean + * @return bool */ - final public function isModified() { + final public function isModified() + { $dirty = (count($this->getInsertDiff()) > 0 || count($this->getDeleteDiff()) > 0); - if ( ! $dirty) { - foreach($this as $record) { + if (!$dirty) { + foreach ($this as $record) { if ($dirty = $record->isModified()) { break; } } } + return $dirty; } } diff --git a/lib/Doctrine/Collection/Exception.php b/lib/Doctrine/Collection/Exception.php index 5b217fb21..e71bc9a3c 100644 --- a/lib/Doctrine/Collection/Exception.php +++ b/lib/Doctrine/Collection/Exception.php @@ -20,15 +20,17 @@ */ /** - * Collection exception class + * Collection exception class. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Collection/Iterator.php b/lib/Doctrine/Collection/Iterator.php index 3fdc79cd0..9b3287a1d 100644 --- a/lib/Doctrine/Collection/Iterator.php +++ b/lib/Doctrine/Collection/Iterator.php @@ -21,72 +21,69 @@ /** * Doctrine_Collection_Iterator - * iterates through Doctrine_Collection + * iterates through Doctrine_Collection. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Collection_Iterator implements Iterator { /** - * @var Doctrine_Collection $collection + * @var Doctrine_Collection */ protected $collection; /** - * @var array $keys + * @var array */ protected $keys; - /** - * @var mixed $key - */ protected $key; /** - * @var integer $index + * @var int */ protected $index; /** - * @var integer $count + * @var int */ protected $count; /** - * constructor - * @var Doctrine_Collection $collection + * constructor. + * + * @var Doctrine_Collection */ public function __construct($collection) { $this->collection = $collection; - $this->keys = $this->collection->getKeys(); - $this->count = $this->collection->count(); + $this->keys = $this->collection->getKeys(); + $this->count = $this->collection->count(); } /** - * rewinds the iterator - * - * @return void + * rewinds the iterator. */ public function rewind() { $this->index = 0; $i = $this->index; if (isset($this->keys[$i])) { - $this->key = $this->keys[$i]; + $this->key = $this->keys[$i]; } } /** - * returns the current key + * returns the current key. * - * @return integer + * @return int */ public function key() { @@ -94,7 +91,7 @@ public function key() } /** - * returns the current record + * returns the current record. * * @return Doctrine_Record */ @@ -104,16 +101,14 @@ public function current() } /** - * advances the internal pointer - * - * @return void + * advances the internal pointer. */ public function next() { - $this->index++; + ++$this->index; $i = $this->index; if (isset($this->keys[$i])) { - $this->key = $this->keys[$i]; + $this->key = $this->keys[$i]; } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Collection/Iterator/Expandable.php b/lib/Doctrine/Collection/Iterator/Expandable.php index 7c18c5c58..1fbb941fb 100644 --- a/lib/Doctrine/Collection/Iterator/Expandable.php +++ b/lib/Doctrine/Collection/Iterator/Expandable.php @@ -20,14 +20,15 @@ */ /** - * Expandable collection iterator class + * Expandable collection iterator class. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Iterator_Expandable extends Doctrine_Collection_Iterator @@ -36,14 +37,16 @@ public function valid() { if ($this->index < $this->count) { return true; - } elseif ($this->index == $this->count) { - $coll = $this->collection->expand($this->index); + } + if ($this->index == $this->count) { + $coll = $this->collection->expand($this->index); if ($coll instanceof Doctrine_Collection) { $count = count($coll); if ($count > 0) { - $this->keys = array_merge($this->keys, $coll->getKeys()); + $this->keys = array_merge($this->keys, $coll->getKeys()); $this->count += $count; + return true; } } @@ -51,4 +54,4 @@ public function valid() return false; } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Collection/Iterator/Normal.php b/lib/Doctrine/Collection/Iterator/Normal.php index 540bdad63..498bc490d 100644 --- a/lib/Doctrine/Collection/Iterator/Normal.php +++ b/lib/Doctrine/Collection/Iterator/Normal.php @@ -20,23 +20,24 @@ */ /** - * Doctrine_Collection_Iterator_Normal + * Doctrine_Collection_Iterator_Normal. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Iterator_Normal extends Doctrine_Collection_Iterator { /** - * @return boolean whether or not the iteration will continue + * @return bool whether or not the iteration will continue */ public function valid() { - return ($this->index < $this->count); + return $this->index < $this->count; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Collection/Iterator/Offset.php b/lib/Doctrine/Collection/Iterator/Offset.php index 181b73f21..8b8a16bfc 100644 --- a/lib/Doctrine/Collection/Iterator/Offset.php +++ b/lib/Doctrine/Collection/Iterator/Offset.php @@ -20,18 +20,20 @@ */ /** - * Doctrine_Collection_Iterator_Normal + * Doctrine_Collection_Iterator_Normal. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Iterator_Offset extends Doctrine_Collection_Iterator { public function valid() - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Collection/Offset.php b/lib/Doctrine/Collection/Offset.php index d8516a8f1..51b332104 100644 --- a/lib/Doctrine/Collection/Offset.php +++ b/lib/Doctrine/Collection/Offset.php @@ -23,24 +23,22 @@ * Doctrine_Collection_Offset * Collection of Doctrine_Record objects. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Collection_Offset extends Doctrine_Collection { /** - * @var integer $limit + * @var int */ private $limit; - /** - * @param Doctrine_Table $table - */ public function __construct(Doctrine_Table $table) { parent::__construct($table); @@ -48,7 +46,7 @@ public function __construct(Doctrine_Table $table) } /** - * @return integer + * @return int */ public function getLimit() { diff --git a/lib/Doctrine/Collection/OnDemand.php b/lib/Doctrine/Collection/OnDemand.php index ab2e81134..272eb0bdf 100644 --- a/lib/Doctrine/Collection/OnDemand.php +++ b/lib/Doctrine/Collection/OnDemand.php @@ -21,14 +21,15 @@ /** * Doctrine_Collection_OnDemand - * iterates through Doctrine_Records hydrating one at a time + * iterates through Doctrine_Records hydrating one at a time. * - * @package Doctrine - * @subpackage Collection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision$ + * * @author Geoff Davis */ class Doctrine_Collection_OnDemand implements Iterator @@ -55,16 +56,16 @@ private function _hydrateCurrent() $record = $this->_hydrator->hydrateResultSet($this->_stmt); if ($record instanceof Doctrine_Collection) { $this->_current = $record->getFirst(); - } else if (is_array($record) && count($record) == 0) { + } elseif (is_array($record) && 0 == count($record)) { $this->_current = null; - } else if (is_array($record) && isset($record[0])) { + } elseif (is_array($record) && isset($record[0])) { $this->_current = $record[0]; } else { $this->_current = $record; } } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function rewind() { $this->index = 0; @@ -74,32 +75,33 @@ public function rewind() $this->_hydrateCurrent(); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function key() { return $this->index; } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function current() { return $this->_current; } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function next() { $this->_current = null; - $this->index++; + ++$this->index; $this->_hydrateCurrent(); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function valid() { - if ( ! is_null($this->_current) && $this->_current !== false) { + if (!is_null($this->_current) && false !== $this->_current) { return true; } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Column.php b/lib/Doctrine/Column.php index fafb97adb..fde9d7206 100644 --- a/lib/Doctrine/Column.php +++ b/lib/Doctrine/Column.php @@ -21,28 +21,28 @@ /** * Doctrine_Column - * This class represents a database column + * This class represents a database column. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Column * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision: 7663 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Column extends Doctrine_Access implements IteratorAggregate, Countable { /** - * @var array $_definition @see getDefinition() + * @var array @see getDefinition() */ protected $_definition = array( - 'type' => null, - 'length' => 0, - ); + 'type' => null, + 'length' => 0, + ); /** - * @var array $definition @see getDefinition() + * @var array @see getDefinition() */ public function __construct(array $definition = array()) { @@ -52,10 +52,11 @@ public function __construct(array $definition = array()) /** * Returns the definition of the column. * - * Keys can be: + * Keys can be: * string type, * integer length, * array values (only for enum fields, maps integer indexes to mixed values), + * * @return array */ public function getDefinition() @@ -64,35 +65,33 @@ public function getDefinition() } /** - * contains + * contains. * - * @return boolean + * @return bool */ - public function contains($name) + public function contains($name) { return isset($this->_definition[$name]); } /** - * get + * get. * * @param string $name - * @return mixed */ public function get($name) { - if ( ! isset($this->_definition[$name])) { + if (!isset($this->_definition[$name])) { return null; } - + return $this->_definition[$name]; } /** - * set + * set. * * @param string $name - * @return void */ public function set($name, $value) { @@ -100,23 +99,23 @@ public function set($name, $value) } /** - * @param string $field * @return array */ public function getEnumValues() { if (isset($this->_definition['values'])) { return $this->_definition['values']; - } else { - return array(); } + + return array(); } /** * Retrieves an enum value. * - * @param integer $index - * @return string integer ($index) if not present + * @param int $index + * + * @return string integer ($index) if not present */ public function enumValue($index) { @@ -128,11 +127,9 @@ public function enumValue($index) } /** - * enumIndex + * enumIndex. * * @param string $field - * @param mixed $value - * @return mixed */ public function enumIndex($field, $value) { @@ -142,23 +139,23 @@ public function enumIndex($field, $value) } /** - * count + * count. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_definition); } /** - * getIterator + * getIterator. * * @return ArrayIterator */ - #[\ReturnTypeWillChange] - public function getIterator() + #[ReturnTypeWillChange] + public function getIterator() { return new ArrayIterator($this->_definition); } diff --git a/lib/Doctrine/Compiler.php b/lib/Doctrine/Compiler.php index 9379316ea..07b5fec54 100644 --- a/lib/Doctrine/Compiler.php +++ b/lib/Doctrine/Compiler.php @@ -21,14 +21,14 @@ /** * Doctrine_Compiler - * This class can be used for compiling the entire Doctrine framework into a single file + * This class can be used for compiling the entire Doctrine framework into a single file. * - * @package Doctrine - * @subpackage Compiler * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpllicense.php LGPL - * @link www.phpdoctrine. + * + * @see www.phpdoctrine. * @since 1.0 + * * @version $Revision: 7677 $ */ class Doctrine_Compiler @@ -36,103 +36,106 @@ class Doctrine_Compiler /** * method for making a single file of most used doctrine runtime components * including the compiled file instead of multiple files (in worst - * cases dozens of files) can improve performance by an order of magnitude + * cases dozens of files) can improve performance by an order of magnitude. + * + * @param mixed|null $target * - * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation * @return $target Path the compiled file was written to + * + * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation */ public static function compile($target = null, $includedDrivers = array()) { - if ( ! is_array($includedDrivers)) { + if (!is_array($includedDrivers)) { $includedDrivers = array($includedDrivers); } - + $excludedDrivers = array(); - + // If we have an array of specified drivers then lets determine which drivers we should exclude - if ( ! empty($includedDrivers)) { + if (!empty($includedDrivers)) { $drivers = array('db2', - 'mssql', - 'mysql', - 'oracle', - 'pgsql', - 'sqlite'); - + 'mssql', + 'mysql', + 'oracle', + 'pgsql', + 'sqlite'); + $excludedDrivers = array_diff($drivers, $includedDrivers); } - + $path = Doctrine_Core::getPath(); - $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path . '/Doctrine'), RecursiveIteratorIterator::LEAVES_ONLY); + $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path.'/Doctrine'), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $e = explode('.', $file->getFileName()); - - //@todo what is a versioning file? do we have these anymore? None - //exists in my version of doctrine from svn. + + // @todo what is a versioning file? do we have these anymore? None + // exists in my version of doctrine from svn. // we don't want to require versioning files - if (end($e) === 'php' && strpos($file->getFileName(), '.inc') === false - && strpos($file->getFileName(), 'sfYaml') === false) { + if ('php' === end($e) && false === strpos($file->getFileName(), '.inc') + && false === strpos($file->getFileName(), 'sfYaml')) { require_once $file->getPathName(); } } $classes = array_merge(get_declared_classes(), get_declared_interfaces()); - $ret = array(); + $ret = array(); foreach ($classes as $class) { $e = explode('_', $class); - if ($e[0] !== 'Doctrine') { + if ('Doctrine' !== $e[0]) { continue; } - + // Exclude drivers - if ( ! empty($excludedDrivers)) { + if (!empty($excludedDrivers)) { foreach ($excludedDrivers as $excludedDriver) { $excludedDriver = ucfirst($excludedDriver); - + if (in_array($excludedDriver, $e)) { - continue(2); + continue 2; } } } - - $refl = new ReflectionClass($class); - $file = $refl->getFileName(); - + + $refl = new ReflectionClass($class); + $file = $refl->getFileName(); + $lines = file($file); $start = $refl->getStartLine() - 1; - $end = $refl->getEndLine(); + $end = $refl->getEndLine(); - $ret = array_merge($ret, array_slice($lines, $start, ($end - $start))); + $ret = array_merge($ret, array_slice($lines, $start, $end - $start)); } - if ($target == null) { - $target = $path . DIRECTORY_SEPARATOR . 'Doctrine.compiled.php'; + if (null == $target) { + $target = $path.DIRECTORY_SEPARATOR.'Doctrine.compiled.php'; } // first write the 'compiled' data to a text file, so // that we can use php_strip_whitespace (which only works on files) $fp = @fopen($target, 'w'); - if ($fp === false) { - throw new Doctrine_Compiler_Exception("Couldn't write compiled data. Failed to open $target"); + if (false === $fp) { + throw new Doctrine_Compiler_Exception("Couldn't write compiled data. Failed to open {$target}"); } - - fwrite($fp, " * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Compiler_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Configurable.php b/lib/Doctrine/Configurable.php index 5a3493e81..992745423 100644 --- a/lib/Doctrine/Configurable.php +++ b/lib/Doctrine/Configurable.php @@ -21,54 +21,56 @@ /** * Doctrine_Configurable - * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection + * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection. * - * @package Doctrine - * @subpackage Configurable * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ abstract class Doctrine_Configurable extends Doctrine_Locator_Injectable { /** - * @var array $attributes an array of containing all attributes + * @var array an array of containing all attributes */ protected $attributes = array(); /** - * @var Doctrine_Configurable $parent the parent of this component + * @var Doctrine_Configurable the parent of this component */ protected $parent; /** - * @var array $_impl an array containing concrete implementations for class templates - * keys as template names and values as names of the concrete - * implementation classes + * @var array an array containing concrete implementations for class templates + * keys as template names and values as names of the concrete + * implementation classes */ protected $_impl = array(); /** - * @var array $_params an array of user defined parameters + * @var array an array of user defined parameters */ protected $_params = array(); /** * setAttribute - * sets a given attribute + * sets a given attribute. * * * $manager->setAttribute(Doctrine_Core::ATTR_PORTABILITY, Doctrine_Core::PORTABILITY_ALL); * * - * @param mixed $attribute either a Doctrine_Core::ATTR_* integer constant or a string - * corresponding to a constant - * @param mixed $value the value of the attribute + * @param mixed $attribute either a Doctrine_Core::ATTR_* integer constant or a string + * corresponding to a constant + * @param mixed $value the value of the attribute + * * @see Doctrine_Core::ATTR_* constants - * @throws Doctrine_Exception if the value is invalid - * @return void + * + * @throws Doctrine_Exception if the value is invalid */ public function setAttribute($attribute, $value) { @@ -77,39 +79,39 @@ public function setAttribute($attribute, $value) $this->setEventListener($value); break; case Doctrine_Core::ATTR_COLL_KEY: - if ( ! ($this instanceof Doctrine_Table)) { - throw new Doctrine_Exception("This attribute can only be set at table level."); + if (!($this instanceof Doctrine_Table)) { + throw new Doctrine_Exception('This attribute can only be set at table level.'); } - if ($value !== null && ! $this->hasField($value)) { - throw new Doctrine_Exception("Couldn't set collection key attribute. No such field '$value'."); + if (null !== $value && !$this->hasField($value)) { + throw new Doctrine_Exception("Couldn't set collection key attribute. No such field '{$value}'."); } break; case Doctrine_Core::ATTR_CACHE: case Doctrine_Core::ATTR_RESULT_CACHE: case Doctrine_Core::ATTR_QUERY_CACHE: case Doctrine_Core::ATTR_TABLE_CACHE: - if ($value !== null) { - if ( ! ($value instanceof Doctrine_Cache_Interface)) { + if (null !== $value) { + if (!($value instanceof Doctrine_Cache_Interface)) { throw new Doctrine_Exception('Cache driver should implement Doctrine_Cache_Interface'); } } break; case Doctrine_Core::ATTR_SEQCOL_NAME: - if ( ! is_string($value)) { + if (!is_string($value)) { throw new Doctrine_Exception('Sequence column name attribute only accepts string values'); } break; case Doctrine_Core::ATTR_FIELD_CASE: - if ($value != 0 && $value != CASE_LOWER && $value != CASE_UPPER) + if (0 != $value && CASE_LOWER != $value && CASE_UPPER != $value) { throw new Doctrine_Exception('Field case attribute should be either 0, CASE_LOWER or CASE_UPPER constant.'); + } break; case Doctrine_Core::ATTR_SEQNAME_FORMAT: case Doctrine_Core::ATTR_IDXNAME_FORMAT: case Doctrine_Core::ATTR_TBLNAME_FORMAT: case Doctrine_Core::ATTR_FKNAME_FORMAT: if ($this instanceof Doctrine_Table) { - throw new Doctrine_Exception('Sequence / index name format attributes cannot be set' - . 'at table level (only at connection or global level).'); + throw new Doctrine_Exception('Sequence / index name format attributes cannot be setat table level (only at connection or global level).'); } break; } @@ -119,13 +121,13 @@ public function setAttribute($attribute, $value) public function getParams($namespace = null) { - if ($namespace == null) { - $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); - } + if (null == $namespace) { + $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); + } - if ( ! isset($this->_params[$namespace])) { - return null; - } + if (!isset($this->_params[$namespace])) { + return null; + } return $this->_params[$namespace]; } @@ -137,25 +139,26 @@ public function getParamNamespaces() public function setParam($name, $value, $namespace = null) { - if ($namespace == null) { - $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); - } + if (null == $namespace) { + $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); + } - $this->_params[$namespace][$name] = $value; + $this->_params[$namespace][$name] = $value; - return $this; + return $this; } public function getParam($name, $namespace = null) { - if ($namespace == null) { - $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); - } + if (null == $namespace) { + $namespace = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE); + } - if ( ! isset($this->_params[$namespace][$name])) { + if (!isset($this->_params[$namespace][$name])) { if (isset($this->parent)) { return $this->parent->getParam($name, $namespace); } + return null; } @@ -164,13 +167,14 @@ public function getParam($name, $namespace = null) /** * setImpl - * binds given class to given template name + * binds given class to given template name. * * this method is the base of Doctrine dependency injection * - * @param string $template name of the class template - * @param string $class name of the class to be bound - * @return Doctrine_Configurable this object + * @param string $template name of the class template + * @param string $class name of the class to be bound + * + * @return Doctrine_Configurable this object */ public function setImpl($template, $class) { @@ -181,36 +185,38 @@ public function setImpl($template, $class) /** * getImpl - * returns the implementation for given class + * returns the implementation for given class. * - * @return string name of the concrete implementation + * @return string name of the concrete implementation */ public function getImpl($template) { - if ( ! isset($this->_impl[$template])) { + if (!isset($this->_impl[$template])) { if (isset($this->parent)) { return $this->parent->getImpl($template); } + return null; } + return $this->_impl[$template]; } - public function hasImpl($template) { - if ( ! isset($this->_impl[$template])) { + if (!isset($this->_impl[$template])) { if (isset($this->parent)) { return $this->parent->hasImpl($template); } + return false; } + return true; } /** * @param Doctrine_EventListener $listener - * @return void */ public function setEventListener($listener) { @@ -218,16 +224,17 @@ public function setEventListener($listener) } /** - * addRecordListener + * addRecordListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * @param mixed|null $name + * + * @return Doctrine_Configurable this object */ public function addRecordListener($listener, $name = null) { - if ( ! isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]) || - ! ($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] instanceof Doctrine_Record_Listener_Chain)) { - + if (!isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]) + || !($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] instanceof Doctrine_Record_Listener_Chain)) { $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER] = new Doctrine_Record_Listener_Chain(); } $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]->add($listener, $name); @@ -236,31 +243,34 @@ public function addRecordListener($listener, $name = null) } /** - * getListener + * getListener. * * @return Doctrine_EventListener_Interface|Doctrine_Overloadable */ public function getRecordListener() { - if ( ! isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER])) { + if (!isset($this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER])) { if (isset($this->parent)) { return $this->parent->getRecordListener(); } + return null; } + return $this->attributes[Doctrine_Core::ATTR_RECORD_LISTENER]; } /** - * setListener + * setListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * + * @return Doctrine_Configurable this object */ public function setRecordListener($listener) { - if ( ! ($listener instanceof Doctrine_Record_Listener_Interface) - && ! ($listener instanceof Doctrine_Overloadable) + if (!($listener instanceof Doctrine_Record_Listener_Interface) + && !($listener instanceof Doctrine_Overloadable) ) { throw new Doctrine_Exception("Couldn't set eventlistener. Record listeners should implement either Doctrine_Record_Listener_Interface or Doctrine_Overloadable"); } @@ -270,16 +280,17 @@ public function setRecordListener($listener) } /** - * addListener + * addListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * @param mixed|null $name + * + * @return Doctrine_Configurable this object */ public function addListener($listener, $name = null) { - if ( ! isset($this->attributes[Doctrine_Core::ATTR_LISTENER]) || - ! ($this->attributes[Doctrine_Core::ATTR_LISTENER] instanceof Doctrine_EventListener_Chain)) { - + if (!isset($this->attributes[Doctrine_Core::ATTR_LISTENER]) + || !($this->attributes[Doctrine_Core::ATTR_LISTENER] instanceof Doctrine_EventListener_Chain)) { $this->attributes[Doctrine_Core::ATTR_LISTENER] = new Doctrine_EventListener_Chain(); } $this->attributes[Doctrine_Core::ATTR_LISTENER]->add($listener, $name); @@ -288,31 +299,34 @@ public function addListener($listener, $name = null) } /** - * getListener + * getListener. * * @return Doctrine_EventListener_Interface|Doctrine_Overloadable */ public function getListener() { - if ( ! isset($this->attributes[Doctrine_Core::ATTR_LISTENER])) { + if (!isset($this->attributes[Doctrine_Core::ATTR_LISTENER])) { if (isset($this->parent)) { return $this->parent->getListener(); } + return null; } + return $this->attributes[Doctrine_Core::ATTR_LISTENER]; } /** - * setListener + * setListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Configurable this object + * + * @return Doctrine_Configurable this object */ public function setListener($listener) { - if ( ! ($listener instanceof Doctrine_EventListener_Interface) - && ! ($listener instanceof Doctrine_Overloadable) + if (!($listener instanceof Doctrine_EventListener_Interface) + && !($listener instanceof Doctrine_Overloadable) ) { throw new Doctrine_EventListener_Exception("Couldn't set eventlistener. EventListeners should implement either Doctrine_EventListener_Interface or Doctrine_Overloadable"); } @@ -322,10 +336,9 @@ public function setListener($listener) } /** - * returns the value of an attribute + * returns the value of an attribute. * - * @param integer $attribute - * @return mixed + * @param int $attribute */ public function getAttribute($attribute) { @@ -336,14 +349,14 @@ public function getAttribute($attribute) if (isset($this->parent)) { return $this->parent->getAttribute($attribute); } + return null; } /** - * Unset an attribute from this levels attributes + * Unset an attribute from this levels attributes. * - * @param integer $attribute - * @return void + * @param int $attribute */ public function unsetAttribute($attribute) { @@ -354,7 +367,7 @@ public function unsetAttribute($attribute) /** * getAttributes - * returns all attributes as an array + * returns all attributes as an array. * * @return array */ @@ -364,7 +377,7 @@ public function getAttributes() } /** - * Set the charset + * Set the charset. * * @param string $charset */ @@ -374,9 +387,7 @@ public function setCharset($charset) } /** - * Get the charset - * - * @return mixed + * Get the charset. */ public function getCharset() { @@ -384,7 +395,7 @@ public function getCharset() } /** - * Set the collate + * Set the collate. * * @param string $collate */ @@ -394,7 +405,7 @@ public function setCollate($collate) } /** - * Get the collate + * Get the collate. * * @return mixed $collate */ @@ -405,10 +416,7 @@ public function getCollate() /** * sets a parent for this configurable component - * the parent must be configurable component itself - * - * @param Doctrine_Configurable $component - * @return void + * the parent must be configurable component itself. */ public function setParent(Doctrine_Configurable $component) { @@ -417,7 +425,7 @@ public function setParent(Doctrine_Configurable $component) /** * getParent - * returns the parent of this component + * returns the parent of this component. * * @return Doctrine_Configurable */ diff --git a/lib/Doctrine/Connection.php b/lib/Doctrine/Connection.php index 73a7e5fa7..c262f26a6 100644 --- a/lib/Doctrine/Connection.php +++ b/lib/Doctrine/Connection.php @@ -20,7 +20,7 @@ */ /** - * Doctrine_Connection + * Doctrine_Connection. * * A wrapper layer on top of PDO / Doctrine_Adapter * @@ -44,66 +44,67 @@ * is divided into modules. For a full list of connection modules see * Doctrine_Connection::$_modules * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Lukas Smith (MDB2 library) */ abstract class Doctrine_Connection extends Doctrine_Configurable implements Countable, IteratorAggregate, Serializable { /** - * @var $dbh the database handler + * @var the database handler */ protected $dbh; /** - * @var array $tables an array containing all the initialized Doctrine_Table objects - * keys representing Doctrine_Table component names and values as Doctrine_Table objects + * @var array an array containing all the initialized Doctrine_Table objects + * keys representing Doctrine_Table component names and values as Doctrine_Table objects */ - protected $tables = array(); + protected $tables = array(); /** - * $_name + * $_name. * * Name of the connection * - * @var string $_name + * @var string */ protected $_name; /** * The name of this connection driver. * - * @var string $driverName + * @var string */ protected $driverName; /** - * @var boolean $isConnected whether or not a connection has been established + * @var bool whether or not a connection has been established */ - protected $isConnected = false; + protected $isConnected = false; /** - * @var array $supported an array containing all features this driver supports, - * keys representing feature names and values as - * one of the following (true, false, 'emulated') + * @var array an array containing all features this driver supports, + * keys representing feature names and values as + * one of the following (true, false, 'emulated') */ - protected $supported = array(); + protected $supported = array(); /** - * @var array $pendingAttributes An array of pending attributes. When setting attributes - * no connection is needed. When connected all the pending - * attributes are passed to the underlying adapter (usually PDO) instance. + * @var array An array of pending attributes. When setting attributes + * no connection is needed. When connected all the pending + * attributes are passed to the underlying adapter (usually PDO) instance. */ - protected $pendingAttributes = array(); + protected $pendingAttributes = array(); /** - * @var array $modules an array containing all modules - * transaction Doctrine_Transaction driver, handles savepoint and transaction isolation abstraction + * @var array an array containing all modules + * transaction Doctrine_Transaction driver, handles savepoint and transaction isolation abstraction * * expression Doctrine_Expression_Driver, handles expression abstraction * @@ -130,86 +131,87 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @see Doctrine_Formatter */ private $modules = array('transaction' => false, - 'expression' => false, - 'dataDict' => false, - 'export' => false, - 'import' => false, - 'sequence' => false, - 'unitOfWork' => false, - 'formatter' => false, - 'util' => false, - ); - - /** - * @var array $properties an array of connection properties - */ - protected $properties = array('sql_comments' => array(array('start' => '--', 'end' => "\n", 'escape' => false), - array('start' => '/*', 'end' => '*/', 'escape' => false)), - 'identifier_quoting' => array('start' => '"', 'end' => '"','escape' => '"'), - 'string_quoting' => array('start' => "'", - 'end' => "'", - 'escape' => false, - 'escape_pattern' => false), - 'wildcards' => array('%', '_'), - 'varchar_max_length' => 255, - 'sql_file_delimiter' => ";\n", - 'max_identifier_length' => 64, - ); - - /** - * @var array $serverInfo + 'expression' => false, + 'dataDict' => false, + 'export' => false, + 'import' => false, + 'sequence' => false, + 'unitOfWork' => false, + 'formatter' => false, + 'util' => false, + ); + + /** + * @var array an array of connection properties + */ + protected $properties = array('sql_comments' => array(array('start' => '--', 'end' => "\n", 'escape' => false), + array('start' => '/*', 'end' => '*/', 'escape' => false)), + 'identifier_quoting' => array('start' => '"', 'end' => '"', 'escape' => '"'), + 'string_quoting' => array('start' => "'", + 'end' => "'", + 'escape' => false, + 'escape_pattern' => false), + 'wildcards' => array('%', '_'), + 'varchar_max_length' => 255, + 'sql_file_delimiter' => ";\n", + 'max_identifier_length' => 64, + ); + + /** + * @var array */ protected $serverInfo = array(); - protected $options = array(); + protected $options = array(); /** - * @var array $supportedDrivers an array containing all supported drivers + * @var array an array containing all supported drivers */ - private static $supportedDrivers = array( - 'Mysql', - 'Pgsql', - 'Oracle', - 'Mssql', - 'Sqlite', - ); + private static $supportedDrivers = array( + 'Mysql', + 'Pgsql', + 'Oracle', + 'Mssql', + 'Sqlite', + ); protected $_count = 0; /** - * @var array $_userFkNames array of foreign key names that have been used + * @var array array of foreign key names that have been used */ protected $_usedNames = array( 'foreign_keys' => array(), - 'indexes' => array() + 'indexes' => array(), ); /** - * @var Doctrine_Cache_Interface The cache driver used for caching tables. + * @var Doctrine_Cache_Interface the cache driver used for caching tables */ protected $_tableCache; protected $_tableCacheTTL; protected $exported; /** - * the constructor + * the constructor. * - * @param Doctrine_Manager $manager the manager object - * @param PDO|Doctrine_Adapter_Interface $adapter database driver + * @param Doctrine_Manager $manager the manager object + * @param PDO|Doctrine_Adapter_Interface $adapter database driver + * @param mixed|null $user + * @param mixed|null $pass */ public function __construct(Doctrine_Manager $manager, $adapter, $user = null, $pass = null) { if (is_object($adapter)) { - if ( ! ($adapter instanceof PDO) && ! in_array('Doctrine_Adapter_Interface', class_implements($adapter))) { + if (!($adapter instanceof PDO) && !in_array('Doctrine_Adapter_Interface', class_implements($adapter))) { throw new Doctrine_Connection_Exception('First argument should be an instance of PDO or implement Doctrine_Adapter_Interface'); } $this->dbh = $adapter; $this->isConnected = true; - - } else if (is_array($adapter)) { + } elseif (is_array($adapter)) { $this->pendingAttributes[Doctrine_Core::ATTR_DRIVER_NAME] = $adapter['scheme']; - $this->options['dsn'] = $adapter['dsn']; + $this->options['dsn'] = $adapter['dsn']; $this->options['username'] = $adapter['user']; $this->options['password'] = $adapter['pass']; @@ -217,7 +219,6 @@ public function __construct(Doctrine_Manager $manager, $adapter, $user = null, $ if (isset($adapter['other'])) { $this->options['other'] = array(Doctrine_Core::ATTR_PERSISTENT => $adapter['persistent']); } - } $this->setParent($manager); @@ -231,9 +232,9 @@ public function __construct(Doctrine_Manager $manager, $adapter, $user = null, $ } /** - * Check wherther the connection to the database has been made yet + * Check wherther the connection to the database has been made yet. * - * @return boolean + * @return bool */ public function isConnected() { @@ -241,24 +242,21 @@ public function isConnected() } /** - * getOptions + * getOptions. * * Get array of all options - * - * @return void */ public function getOptions() { - return $this->options; + return $this->options; } /** - * getOption + * getOption. * * Retrieves option * * @param string $option - * @return void */ public function getOption($option) { @@ -268,31 +266,30 @@ public function getOption($option) } /** - * setOption + * setOption. * * Set option value * * @param string $option - * @return void */ public function setOption($option, $value) { - return $this->options[$option] = $value; + return $this->options[$option] = $value; } /** * getAttribute - * retrieves a database connection attribute + * retrieves a database connection attribute. * - * @param integer $attribute - * @return mixed + * @param int $attribute */ public function getAttribute($attribute) { if ($attribute >= 100 && $attribute < 1000) { - if ( ! isset($this->attributes[$attribute])) { + if (!isset($this->attributes[$attribute])) { return parent::getAttribute($attribute); } + return $this->attributes[$attribute]; } @@ -300,10 +297,10 @@ public function getAttribute($attribute) try { return $this->dbh->getAttribute($attribute); } catch (Exception $e) { - throw new Doctrine_Connection_Exception('Attribute ' . $attribute . ' not found.'); + throw new Doctrine_Connection_Exception('Attribute '.$attribute.' not found.'); } } else { - if ( ! isset($this->pendingAttributes[$attribute])) { + if (!isset($this->pendingAttributes[$attribute])) { $this->connect(); $this->getAttribute($attribute); } @@ -313,7 +310,7 @@ public function getAttribute($attribute) } /** - * returns an array of available PDO drivers + * returns an array of available PDO drivers. */ public static function getAvailableDrivers() { @@ -321,7 +318,7 @@ public static function getAvailableDrivers() } /** - * Returns an array of supported drivers by Doctrine + * Returns an array of supported drivers by Doctrine. * * @return array $supportedDrivers */ @@ -332,14 +329,14 @@ public static function getSupportedDrivers() /** * setAttribute - * sets an attribute + * sets an attribute. * * @todo why check for >= 100? has this any special meaning when creating * attributes? * - * @param integer $attribute - * @param mixed $value - * @return boolean + * @param int $attribute + * + * @return bool */ public function setAttribute($attribute, $value) { @@ -358,9 +355,9 @@ public function setAttribute($attribute, $value) /** * getName - * returns the name of this driver + * returns the name of this driver. * - * @return string the name of this driver + * @return string the name of this driver */ public function getName() { @@ -368,12 +365,11 @@ public function getName() } /** - * setName + * setName. * * Sets the name of the connection * * @param string $name - * @return void */ public function setName($name) { @@ -381,11 +377,9 @@ public function setName($name) } /** - * getDriverName + * getDriverName. * * Gets the name of the instance driver - * - * @return void */ public function getDriverName() { @@ -394,16 +388,19 @@ public function getDriverName() /** * __get - * lazy loads given module and returns it + * lazy loads given module and returns it. * * @see Doctrine_DataDict * @see Doctrine_Expression_Driver * @see Doctrine_Export * @see Doctrine_Transaction * @see Doctrine_Connection::$modules all availible modules - * @param string $name the name of the module to get - * @throws Doctrine_Connection_Exception if trying to get an unknown module - * @return Doctrine_Connection_Module connection module + * + * @param string $name the name of the module to get + * + * @return Doctrine_Connection_Module connection module + * + * @throws Doctrine_Connection_Exception if trying to get an unknown module */ public function __get($name) { @@ -411,10 +408,10 @@ public function __get($name) return $this->properties[$name]; } - if ( ! isset($this->modules[$name])) { - throw new Doctrine_Connection_Exception('Unknown module / property ' . $name); + if (!isset($this->modules[$name])) { + throw new Doctrine_Connection_Exception('Unknown module / property '.$name); } - if ($this->modules[$name] === false) { + if (false === $this->modules[$name]) { switch ($name) { case 'unitOfWork': $this->modules[$name] = new Doctrine_Connection_UnitOfWork($this); @@ -423,16 +420,16 @@ public function __get($name) $this->modules[$name] = new Doctrine_Formatter($this); break; default: - $class = 'Doctrine_' . ucwords($name) . '_' . $this->getDriverName(); + $class = 'Doctrine_'.ucwords($name).'_'.$this->getDriverName(); $this->modules[$name] = new $class($this); - } + } } return $this->modules[$name]; } /** - * returns the manager that created this connection + * returns the manager that created this connection. * * @return Doctrine_Manager */ @@ -442,9 +439,9 @@ public function getManager() } /** - * returns the database handler of which this connection uses + * returns the database handler of which this connection uses. * - * @return PDO the database handler + * @return PDO the database handler */ public function getDbh() { @@ -455,9 +452,9 @@ public function getDbh() /** * connect - * connects into database + * connects into database. * - * @return boolean + * @return bool */ public function connect() { @@ -469,37 +466,37 @@ public function connect() $this->getListener()->preConnect($event); - $e = explode(':', $this->options['dsn']); + $e = explode(':', $this->options['dsn']); $found = false; if (extension_loaded('pdo')) { if (in_array($e[0], self::getAvailableDrivers())) { try { $this->dbh = new PDO($this->options['dsn'], $this->options['username'], - (!$this->options['password'] ? '':$this->options['password']), $this->options['other']); + !$this->options['password'] ? '' : $this->options['password'], $this->options['other']); $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { - throw new Doctrine_Connection_Exception('PDO Connection Error: ' . $e->getMessage()); + throw new Doctrine_Connection_Exception('PDO Connection Error: '.$e->getMessage()); } $found = true; } } - if ( ! $found) { - $class = 'Doctrine_Adapter_' . ucwords($e[0]); + if (!$found) { + $class = 'Doctrine_Adapter_'.ucwords($e[0]); if (class_exists($class)) { $this->dbh = new $class($this->options['dsn'], $this->options['username'], $this->options['password'], $this->options); } else { - throw new Doctrine_Connection_Exception("Couldn't locate driver named " . $e[0]); + throw new Doctrine_Connection_Exception("Couldn't locate driver named ".$e[0]); } } // attach the pending attributes to adapter - foreach($this->pendingAttributes as $attr => $value) { + foreach ($this->pendingAttributes as $attr => $value) { // some drivers don't support setting this so we just skip it - if ($attr == Doctrine_Core::ATTR_DRIVER_NAME) { + if (Doctrine_Core::ATTR_DRIVER_NAME == $attr) { continue; } $this->dbh->setAttribute($attr, $value); @@ -508,34 +505,34 @@ public function connect() $this->isConnected = true; $this->getListener()->postConnect($event); + return true; } public function incrementQueryCount() { - $this->_count++; + ++$this->_count; } /** - * converts given driver name - * - * @param + * converts given driver name. */ public function driverName($name) { } /** - * supports + * supports. + * + * @param string $feature the name of the feature * - * @param string $feature the name of the feature - * @return boolean whether or not this drivers supports given feature + * @return bool whether or not this drivers supports given feature */ public function supports($feature) { - return (isset($this->supported[$feature]) - && ($this->supported[$feature] === 'emulated' - || $this->supported[$feature])); + return isset($this->supported[$feature]) + && ('emulated' === $this->supported[$feature] + || $this->supported[$feature]); } /** @@ -550,26 +547,25 @@ public function supports($feature) * of queries inside a transaction to assure the atomicity of the operation. * * @param string name of the table on which the REPLACE query will - * be executed. - * + * be executed * @param array an associative array that describes the fields and the * values that will be inserted or updated in the specified table. The * indexes of the array are the names of all the fields of the table. * * The values of the array are values to be assigned to the specified field. - * - * @param array $keys an array containing all key fields (primary key fields - * or unique index fields) for this table + * @param array $keys an array containing all key fields (primary key fields + * or unique index fields) for this table * * the uniqueness of a row will be determined according to * the provided key fields * * this method will fail if no key fields are specified * - * @throws Doctrine_Connection_Exception if this driver doesn't support replace - * @throws Doctrine_Connection_Exception if some of the key values was null - * @throws Doctrine_Connection_Exception if there were no key fields - * @throws PDOException if something fails at PDO level + * @throws Doctrine_Connection_Exception if this driver doesn't support replace + * @throws Doctrine_Connection_Exception if some of the key values was null + * @throws Doctrine_Connection_Exception if there were no key fields + * @throws PDOException if something fails at PDO level + * * @ return integer number of rows affected */ public function replace(Doctrine_Table $table, array $fields, array $keys) @@ -582,47 +578,49 @@ public function replace(Doctrine_Table $table, array $fields, array $keys) foreach ($fields as $fieldName => $value) { if (in_array($fieldName, $keys)) { - if ($value !== null) { - $condition[] = $table->getColumnName($fieldName) . ' = ?'; + if (null !== $value) { + $condition[] = $table->getColumnName($fieldName).' = ?'; $conditionValues[] = $value; } } } $affectedRows = 0; - if ( ! empty($condition) && ! empty($conditionValues)) { - $query = 'DELETE FROM ' . $this->quoteIdentifier($table->getTableName()) - . ' WHERE ' . implode(' AND ', $condition); + if (!empty($condition) && !empty($conditionValues)) { + $query = 'DELETE FROM '.$this->quoteIdentifier($table->getTableName()) + .' WHERE '.implode(' AND ', $condition); $affectedRows = $this->exec($query, $conditionValues); } $this->insert($table, $fields); - $affectedRows++; + ++$affectedRows; return $affectedRows; } /** - * deletes table row(s) matching the specified identifier + * deletes table row(s) matching the specified identifier. + * + * @param string $table The table to delete data from + * @param array $identifier an associateve array containing identifier column-value pairs * - * @throws Doctrine_Connection_Exception if something went wrong at the database level - * @param string $table The table to delete data from - * @param array $identifier An associateve array containing identifier column-value pairs. - * @return integer The number of affected rows + * @return int The number of affected rows + * + * @throws Doctrine_Connection_Exception if something went wrong at the database level */ public function delete(Doctrine_Table $table, array $identifier) { $tmp = array(); foreach (array_keys($identifier) as $id) { - $tmp[] = $this->quoteIdentifier($table->getColumnName($id)) . ' = ?'; + $tmp[] = $this->quoteIdentifier($table->getColumnName($id)).' = ?'; } $query = 'DELETE FROM ' - . $this->quoteIdentifier($table->getTableName()) - . ' WHERE ' . implode(' AND ', $tmp); + .$this->quoteIdentifier($table->getTableName()) + .' WHERE '.implode(' AND ', $tmp); return $this->exec($query, array_values($identifier)); } @@ -630,11 +628,11 @@ public function delete(Doctrine_Table $table, array $identifier) /** * Updates table row(s) with specified data. * - * @throws Doctrine_Connection_Exception if something went wrong at the database level - * @param Doctrine_Table $table The table to insert data into - * @param array $values An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param Doctrine_Table $table The table to insert data into + * + * @return int the number of affected rows. Boolean false if empty value array was given, + * + * @throws Doctrine_Connection_Exception if something went wrong at the database level */ public function update(Doctrine_Table $table, array $fields, array $identifier) { @@ -645,19 +643,19 @@ public function update(Doctrine_Table $table, array $fields, array $identifier) $set = array(); foreach ($fields as $fieldName => $value) { if ($value instanceof Doctrine_Expression) { - $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)) . ' = ' . $value->getSql(); + $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)).' = '.$value->getSql(); unset($fields[$fieldName]); } else { - $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)) . ' = ?'; + $set[] = $this->quoteIdentifier($table->getColumnName($fieldName)).' = ?'; } } $params = array_merge(array_values($fields), array_values($identifier)); - $sql = 'UPDATE ' . $this->quoteIdentifier($table->getTableName()) - . ' SET ' . implode(', ', $set) - . ' WHERE ' . implode(' = ? AND ', $this->quoteMultipleIdentifier($table->getIdentifierColumnNames())) - . ' = ?'; + $sql = 'UPDATE '.$this->quoteIdentifier($table->getTableName()) + .' SET '.implode(', ', $set) + .' WHERE '.implode(' = ? AND ', $this->quoteMultipleIdentifier($table->getIdentifierColumnNames())) + .' = ?'; return $this->exec($sql, $params); } @@ -665,10 +663,9 @@ public function update(Doctrine_Table $table, array $fields, array $identifier) /** * Inserts a table row with specified data. * - * @param Doctrine_Table $table The table to insert data into. - * @param array $values An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param Doctrine_Table $table the table to insert data into + * + * @return int the number of affected rows. Boolean false if empty value array was given, */ public function insert(Doctrine_Table $table, array $fields) { @@ -689,15 +686,15 @@ public function insert(Doctrine_Table $table, array $fields) } // build the statement - $query = 'INSERT INTO ' . $this->quoteIdentifier($tableName) - . ' (' . implode(', ', $cols) . ')' - . ' VALUES (' . implode(', ', $a) . ')'; + $query = 'INSERT INTO '.$this->quoteIdentifier($tableName) + .' ('.implode(', ', $cols).')' + .' VALUES ('.implode(', ', $a).')'; return $this->exec($query, array_values($fields)); } /** - * Quote a string so it can be safely used as a table or column name + * Quote a string so it can be safely used as a table or column name. * * Delimiting style depends on which database driver is being used. * @@ -723,10 +720,10 @@ public function insert(Doctrine_Table $table, array $fields) * InterBase doesn't seem to be able to use delimited identifiers * via PHP 4. They work fine under PHP 5. * - * @param string $str identifier name to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param string $str identifier name to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteIdentifier($str, $checkOption = true) { @@ -734,20 +731,21 @@ public function quoteIdentifier($str, $checkOption = true) if (strpos($str, '.')) { $e = explode('.', $str); - return $this->formatter->quoteIdentifier($e[0], $checkOption) . '.' - . $this->formatter->quoteIdentifier($e[1], $checkOption); + return $this->formatter->quoteIdentifier($e[0], $checkOption).'.' + .$this->formatter->quoteIdentifier($e[1], $checkOption); } + return $this->formatter->quoteIdentifier($str, $checkOption); } /** * quoteMultipleIdentifier - * Quotes multiple identifier strings + * Quotes multiple identifier strings. * - * @param array $arr identifiers array to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param array $arr identifiers array to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteMultipleIdentifier($arr, $checkOption = true) { @@ -761,12 +759,11 @@ public function quoteMultipleIdentifier($arr, $checkOption = true) /** * convertBooleans * some drivers need the boolean values to be converted into integers - * when using DQL API + * when using DQL API. * * This method takes care of that conversion * * @param array $item - * @return void */ public function convertBooleans($item) { @@ -775,10 +772,11 @@ public function convertBooleans($item) /** * quote - * quotes given input parameter + * quotes given input parameter. * - * @param mixed $input parameter to be quoted + * @param mixed $input parameter to be quoted * @param string $type + * * @return string */ public function quote($input, $type = null) @@ -787,21 +785,21 @@ public function quote($input, $type = null) } /** - * Set the date/time format for the current connection + * Set the date/time format for the current connection. * * @param string time format - * - * @return void + * @param mixed|null $format */ public function setDateFormat($format = null) { } /** - * fetchAll + * fetchAll. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchAll($statement, array $params = array()) @@ -810,12 +808,11 @@ public function fetchAll($statement, array $params = array()) } /** - * fetchOne + * fetchOne. * - * @param string $statement sql query to be executed - * @param array $params prepared statement params - * @param int $colnum 0-indexed column number to retrieve - * @return mixed + * @param string $statement sql query to be executed + * @param array $params prepared statement params + * @param int $colnum 0-indexed column number to retrieve */ public function fetchOne($statement, array $params = array(), $colnum = 0) { @@ -823,10 +820,11 @@ public function fetchOne($statement, array $params = array(), $colnum = 0) } /** - * fetchRow + * fetchRow. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchRow($statement, array $params = array()) @@ -835,10 +833,11 @@ public function fetchRow($statement, array $params = array()) } /** - * fetchArray + * fetchArray. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchArray($statement, array $params = array()) @@ -847,11 +846,12 @@ public function fetchArray($statement, array $params = array()) } /** - * fetchColumn + * fetchColumn. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params + * @param int $colnum 0-indexed column number to retrieve * - * @param string $statement sql query to be executed - * @param array $params prepared statement params - * @param int $colnum 0-indexed column number to retrieve * @return array */ public function fetchColumn($statement, array $params = array(), $colnum = 0) @@ -860,10 +860,11 @@ public function fetchColumn($statement, array $params = array(), $colnum = 0) } /** - * fetchAssoc + * fetchAssoc. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchAssoc($statement, array $params = array()) @@ -872,10 +873,11 @@ public function fetchAssoc($statement, array $params = array()) } /** - * fetchBoth + * fetchBoth. + * + * @param string $statement sql query to be executed + * @param array $params prepared statement params * - * @param string $statement sql query to be executed - * @param array $params prepared statement params * @return array */ public function fetchBoth($statement, array $params = array()) @@ -886,7 +888,7 @@ public function fetchBoth($statement, array $params = array()) /** * query * queries the database using Doctrine Query Language - * returns a collection of Doctrine_Record objects + * returns a collection of Doctrine_Record objects. * * * $users = $conn->query('SELECT u.* FROM User u'); @@ -894,11 +896,13 @@ public function fetchBoth($statement, array $params = array()) * $users = $conn->query('SELECT u.* FROM User u WHERE u.name LIKE ?', array('someone')); * * - * @param string $query DQL query - * @param array $params query parameters - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string $query DQL query + * @param array $params query parameters + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @see Doctrine_Query - * @return Doctrine_Collection Collection of Doctrine_Record objects + * + * @return Doctrine_Collection Collection of Doctrine_Record objects */ public function query($query, array $params = array(), $hydrationMode = null) { @@ -910,7 +914,7 @@ public function query($query, array $params = array(), $hydrationMode = null) } /** - * prepare + * prepare. * * @param string $statement */ @@ -925,15 +929,16 @@ public function prepare($statement) $stmt = false; - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $stmt = $this->dbh->prepare($statement); } $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postPrepare($event); return new Doctrine_Connection_Statement($this, $stmt); - } catch(Doctrine_Adapter_Exception $e) { - } catch(PDOException $e) { } + } catch (Doctrine_Adapter_Exception $e) { + } catch (PDOException $e) { + } $this->rethrowException($e, $this, $statement); } @@ -941,7 +946,7 @@ public function prepare($statement) /** * query * queries the database using Doctrine Query Language and returns - * the first record found + * the first record found. * * * $user = $conn->queryOne('SELECT u.* FROM User u WHERE u.id = ?', array(1)); @@ -951,30 +956,34 @@ public function prepare($statement) * ); * * - * @param string $query DQL query - * @param array $params query parameters + * @param string $query DQL query + * @param array $params query parameters + * * @see Doctrine_Query - * @return Doctrine_Record|false Doctrine_Record object on success, - * boolean false on failure + * + * @return Doctrine_Record|false Doctrine_Record object on success, + * boolean false on failure */ public function queryOne($query, array $params = array()) { $parser = Doctrine_Query::create(); $coll = $parser->query($query, $params); - if ( ! $coll->contains(0)) { + if (!$coll->contains(0)) { return false; } + return $coll[0]; } /** * queries the database with limit and offset - * added to the query and returns a Doctrine_Connection_Statement object + * added to the query and returns a Doctrine_Connection_Statement object. * * @param string $query - * @param integer $limit - * @param integer $offset + * @param int $limit + * @param int $offset + * * @return Doctrine_Connection_Statement */ public function select($query, $limit = 0, $offset = 0) @@ -982,14 +991,15 @@ public function select($query, $limit = 0, $offset = 0) if ($limit > 0 || $offset > 0) { $query = $this->modifyLimitQuery($query, $limit, $offset); } + return $this->execute($query); } /** - * standaloneQuery + * standaloneQuery. * - * @param string $query sql query - * @param array $params query parameters + * @param string $query sql query + * @param array $params query parameters * * @return PDOStatement|Doctrine_Adapter_Statement */ @@ -999,9 +1009,10 @@ public function standaloneQuery($query, $params = array()) } /** - * execute - * @param string $query sql query - * @param array $params query parameters + * execute. + * + * @param string $query sql query + * @param array $params query parameters * * @return PDOStatement|Doctrine_Adapter_Statement */ @@ -1010,68 +1021,71 @@ public function execute($query, array $params = array()) $this->connect(); try { - if ( ! empty($params)) { + if (!empty($params)) { $stmt = $this->prepare($query); $stmt->execute($params); return $stmt; - } else { - $event = new Doctrine_Event($this, Doctrine_Event::CONN_QUERY, $query, $params); - - $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->preQuery($event); + } + $event = new Doctrine_Event($this, Doctrine_Event::CONN_QUERY, $query, $params); - if ( ! $event->skipOperation) { - $stmt = $this->dbh->query($query); - $this->_count++; - } - $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postQuery($event); + $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->preQuery($event); - return $stmt; + if (!$event->skipOperation) { + $stmt = $this->dbh->query($query); + ++$this->_count; } + $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postQuery($event); + + return $stmt; } catch (Doctrine_Adapter_Exception $e) { - } catch (PDOException $e) { } + } catch (PDOException $e) { + } $this->rethrowException($e, $this, $query); } /** - * exec - * @param string $query sql query - * @param array $params query parameters + * exec. * - * @return integer + * @param string $query sql query + * @param array $params query parameters + * + * @return int */ public function exec($query, array $params = array()) { $this->connect(); try { - if ( ! empty($params)) { + if (!empty($params)) { $stmt = $this->prepare($query); $stmt->execute($params); return $stmt->rowCount(); - } else { - $event = new Doctrine_Event($this, Doctrine_Event::CONN_EXEC, $query, $params); - - $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->preExec($event); - if ( ! $event->skipOperation) { - $count = $this->dbh->exec($query); + } + $event = new Doctrine_Event($this, Doctrine_Event::CONN_EXEC, $query, $params); - $this->_count++; - } - $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postExec($event); + $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->preExec($event); + if (!$event->skipOperation) { + $count = $this->dbh->exec($query); - return $count; + ++$this->_count; } + $this->getAttribute(Doctrine_Core::ATTR_LISTENER)->postExec($event); + + return $count; } catch (Doctrine_Adapter_Exception $e) { - } catch (PDOException $e) { } + } catch (PDOException $e) { + } $this->rethrowException($e, $this, $query); } /** - * rethrowException + * rethrowException. + * + * @param mixed|null $query * * @throws Doctrine_Connection_Exception */ @@ -1081,20 +1095,20 @@ public function rethrowException(Exception $e, $invoker, $query = null) $this->getListener()->preError($event); - $name = 'Doctrine_Connection_' . $this->driverName . '_Exception'; + $name = 'Doctrine_Connection_'.$this->driverName.'_Exception'; $message = $e->getMessage(); if ($query) { $message .= sprintf('. Failing Query: "%s"', $query); } - $exc = new $name($message, (int) $e->getCode()); - if ( ! isset($e->errorInfo) || ! is_array($e->errorInfo)) { + $exc = new $name($message, (int) $e->getCode()); + if (!isset($e->errorInfo) || !is_array($e->errorInfo)) { $e->errorInfo = array(null, null, null, null); } $exc->processErrorInfo($e->errorInfo); - if ($this->getAttribute(Doctrine_Core::ATTR_THROW_EXCEPTIONS)) { + if ($this->getAttribute(Doctrine_Core::ATTR_THROW_EXCEPTIONS)) { throw $exc; } @@ -1103,10 +1117,9 @@ public function rethrowException(Exception $e, $invoker, $query = null) /** * hasTable - * whether or not this connection has table $name initialized + * whether or not this connection has table $name initialized. * - * @param mixed $name - * @return boolean + * @return bool */ public function hasTable($name) { @@ -1114,9 +1127,10 @@ public function hasTable($name) } /** - * returns a table object for given component name + * returns a table object for given component name. + * + * @param string $name component name * - * @param string $name component name * @return Doctrine_Table */ public function getTable($name) @@ -1125,10 +1139,10 @@ public function getTable($name) return $this->tables[$name]; } - $hasTableCache = $this->_tableCache !== false && ($this->_tableCache || $this->getAttribute(Doctrine_Core::ATTR_TABLE_CACHE)); + $hasTableCache = false !== $this->_tableCache && ($this->_tableCache || $this->getAttribute(Doctrine_Core::ATTR_TABLE_CACHE)); if ($hasTableCache) { $tableCacheDriver = $this->getTableCacheDriver(); - $hash = md5($name . 'DOCTRINE_TABLE_CACHE_SALT'); + $hash = md5($name.'DOCTRINE_TABLE_CACHE_SALT'); $cached = $tableCacheDriver->fetch($hash); if ($cached) { @@ -1141,8 +1155,8 @@ public function getTable($name) $class = sprintf($this->getAttribute(Doctrine_Core::ATTR_TABLE_CLASS_FORMAT), $name); - if (class_exists($class, $this->getAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES)) && - in_array('Doctrine_Table', class_parents($class))) { + if (class_exists($class, $this->getAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES)) + && in_array('Doctrine_Table', class_parents($class))) { $table = new $class($name, $this, true); } else { $tableClass = $this->getAttribute(Doctrine_Core::ATTR_TABLE_CLASS); @@ -1158,7 +1172,7 @@ public function getTable($name) } /** - * returns an array of all initialized tables + * returns an array of all initialized tables. * * @return array */ @@ -1169,7 +1183,7 @@ public function getTables() /** * returns an iterator that iterators through all - * initialized table objects + * initialized table objects. * * * foreach ($conn as $index => $table) { @@ -1177,20 +1191,20 @@ public function getTables() * } * * - * @return ArrayIterator SPL ArrayIterator object + * @return ArrayIterator SPL ArrayIterator object */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->tables); } /** - * returns the count of initialized table objects + * returns the count of initialized table objects. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return $this->_count; @@ -1198,10 +1212,11 @@ public function count() /** * addTable - * adds a Doctrine_Table object into connection registry + * adds a Doctrine_Table object into connection registry. + * + * @param $table a Doctrine_Table object to be added into registry * - * @param $table a Doctrine_Table object to be added into registry - * @return boolean + * @return bool */ public function addTable(Doctrine_Table $table) { @@ -1217,11 +1232,13 @@ public function addTable(Doctrine_Table $table) /** * create - * creates a record + * creates a record. * * create creates a record - * @param string $name component name - * @return Doctrine_Record Doctrine_Record object + * + * @param string $name component name + * + * @return Doctrine_Record Doctrine_Record object */ public function create($name) { @@ -1241,10 +1258,9 @@ public function createQuery() /** * flush * saves all the records from all tables - * this operation is isolated using a transaction + * this operation is isolated using a transaction. * - * @throws PDOException if something went wrong at database level - * @return void + * @throws PDOException if something went wrong at database level */ public function flush() { @@ -1260,9 +1276,7 @@ public function flush() /** * clear - * clears all repositories - * - * @return void + * clears all repositories. */ public function clear() { @@ -1274,9 +1288,7 @@ public function clear() /** * evictTables - * evicts all tables - * - * @return void + * evicts all tables. */ public function evictTables() { @@ -1286,9 +1298,7 @@ public function evictTables() /** * close - * closes the connection - * - * @return void + * closes the connection. */ public function close() { @@ -1305,9 +1315,9 @@ public function close() } /** - * get the current transaction nesting level + * get the current transaction nesting level. * - * @return integer + * @return int */ public function getTransactionLevel() { @@ -1316,9 +1326,9 @@ public function getTransactionLevel() /** * errorCode - * Fetch the SQLSTATE associated with the last operation on the database handle + * Fetch the SQLSTATE associated with the last operation on the database handle. * - * @return integer + * @return int */ public function errorCode() { @@ -1329,7 +1339,7 @@ public function errorCode() /** * errorInfo - * Fetch extended error information associated with the last operation on the database handle + * Fetch extended error information associated with the last operation on the database handle. * * @return array */ @@ -1341,13 +1351,13 @@ public function errorInfo() } /** - * getResultCacheDriver + * getResultCacheDriver. * * @return Doctrine_Cache_Interface */ public function getResultCacheDriver() { - if ( ! $this->getAttribute(Doctrine_Core::ATTR_RESULT_CACHE)) { + if (!$this->getAttribute(Doctrine_Core::ATTR_RESULT_CACHE)) { throw new Doctrine_Exception('Result Cache driver not initialized.'); } @@ -1355,13 +1365,13 @@ public function getResultCacheDriver() } /** - * getQueryCacheDriver + * getQueryCacheDriver. * * @return Doctrine_Cache_Interface */ public function getQueryCacheDriver() { - if ( ! $this->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE)) { + if (!$this->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE)) { throw new Doctrine_Exception('Query Cache driver not initialized.'); } @@ -1369,13 +1379,13 @@ public function getQueryCacheDriver() } /** - * getQueryCacheDriver + * getQueryCacheDriver. * * @return Doctrine_Cache_Interface */ public function getTableCacheDriver() { - if ( ! $this->getAttribute(Doctrine_Core::ATTR_TABLE_CACHE)) { + if (!$this->getAttribute(Doctrine_Core::ATTR_TABLE_CACHE)) { throw new Doctrine_Exception('Query Cache driver not initialized.'); } @@ -1385,7 +1395,7 @@ public function getTableCacheDriver() /** * Gets the life span of the table cache the Query object is using. * - * @return integer The life span in seconds. + * @return int the life span in seconds */ public function getTableCacheLifeSpan() { @@ -1393,7 +1403,7 @@ public function getTableCacheLifeSpan() } /** - * lastInsertId + * lastInsertId. * * Returns the ID of the last inserted row, or the last value from a sequence object, * depending on the underlying driver. @@ -1401,8 +1411,8 @@ public function getTableCacheLifeSpan() * Note: This method may not return a meaningful or consistent result across different drivers, * because the underlying database may not even support the notion of auto-increment fields or sequences. * - * @param string $table name of the table into which a new row was inserted - * @param string $field name of the field into which a new row was inserted + * @param string $table name of the table into which a new row was inserted + * @param string $field name of the field into which a new row was inserted */ public function lastInsertId($table = null, $field = null) { @@ -1418,9 +1428,11 @@ public function lastInsertId($table = null, $field = null) * * Listeners: onPreTransactionBegin, onTransactionBegin * - * @param string $savepoint name of a savepoint to set - * @throws Doctrine_Transaction_Exception if the transaction fails at database level - * @return integer current transaction nesting level + * @param string $savepoint name of a savepoint to set + * + * @return int current transaction nesting level + * + * @throws Doctrine_Transaction_Exception if the transaction fails at database level */ public function beginTransaction($savepoint = null) { @@ -1440,10 +1452,12 @@ public function beginInternalTransaction($savepoint = null) * * Listeners: onPreTransactionCommit, onTransactionCommit * - * @param string $savepoint name of a savepoint to release - * @throws Doctrine_Transaction_Exception if the transaction fails at PDO level - * @throws Doctrine_Validator_Exception if the transaction fails due to record validations - * @return boolean false if commit couldn't be performed, true otherwise + * @param string $savepoint name of a savepoint to release + * + * @return bool false if commit couldn't be performed, true otherwise + * + * @throws Doctrine_Transaction_Exception if the transaction fails at PDO level + * @throws Doctrine_Validator_Exception if the transaction fails due to record validations */ public function commit($savepoint = null) { @@ -1460,9 +1474,11 @@ public function commit($savepoint = null) * this method can be listened with onPreTransactionRollback and onTransactionRollback * eventlistener methods * - * @param string $savepoint name of a savepoint to rollback to - * @throws Doctrine_Transaction_Exception if the rollback operation fails at database level - * @return boolean false if rollback couldn't be performed, true otherwise + * @param string $savepoint name of a savepoint to rollback to + * + * @return bool false if rollback couldn't be performed, true otherwise + * + * @throws Doctrine_Transaction_Exception if the rollback operation fails at database level */ public function rollback($savepoint = null) { @@ -1470,15 +1486,15 @@ public function rollback($savepoint = null) } /** - * createDatabase + * createDatabase. * * Issue create database command for this instance of Doctrine_Connection * - * @return string Doctrine_Exception catched in case of failure + * @return string Doctrine_Exception catched in case of failure */ public function createDatabase() { - if ( ! $dsn = $this->getOption('dsn')) { + if (!$dsn = $this->getOption('dsn')) { throw new Doctrine_Connection_Exception('You must create your Doctrine_Connection by using a valid Doctrine style dsn in order to use the create/drop database functionality'); } @@ -1492,7 +1508,8 @@ public function createDatabase() // the tmp connection try { $tmpConnection->export->createDatabase($info['dbname']); - } catch (Exception $e) {} + } catch (Exception $e) { + } // Close the temporary connection used to issue the drop database command $this->getManager()->closeConnection($tmpConnection); @@ -1503,15 +1520,15 @@ public function createDatabase() } /** - * dropDatabase + * dropDatabase. * * Issue drop database command for this instance of Doctrine_Connection * - * @return string success string. Doctrine_Exception if operation failed + * @return string success string. Doctrine_Exception if operation failed */ public function dropDatabase() { - if ( ! $dsn = $this->getOption('dsn')) { + if (!$dsn = $this->getOption('dsn')) { throw new Doctrine_Connection_Exception('You must create your Doctrine_Connection by using a valid Doctrine style dsn in order to use the create/drop database functionality'); } @@ -1525,19 +1542,19 @@ public function dropDatabase() // the tmp connection try { $tmpConnection->export->dropDatabase($info['dbname']); - } catch (Exception $e) {} + } catch (Exception $e) { + } // Close the temporary connection used to issue the drop database command $this->getManager()->closeConnection($tmpConnection); - if (isset($e)) { throw $e; } } /** - * getTmpConnection + * getTmpConnection. * * Create a temporary connection to the database with the user credentials. * This is so the user can make a connection to a db server. Some dbms allow @@ -1546,24 +1563,23 @@ public function dropDatabase() * This value is set in the Doctrine_Export_{DRIVER} classes if required * * @param string $info - * @return void */ public function getTmpConnection($info) { - $pdoDsn = $info['scheme'] . ':'; + $pdoDsn = $info['scheme'].':'; if ($info['unix_socket']) { - $pdoDsn .= 'unix_socket=' . $info['unix_socket'] . ';'; + $pdoDsn .= 'unix_socket='.$info['unix_socket'].';'; } - $pdoDsn .= 'host=' . $info['host']; + $pdoDsn .= 'host='.$info['host']; if ($info['port']) { - $pdoDsn .= ';port=' . $info['port']; + $pdoDsn .= ';port='.$info['port']; } if (isset($this->export->tmpConnectionDatabase) && $this->export->tmpConnectionDatabase) { - $pdoDsn .= ';dbname=' . $this->export->tmpConnectionDatabase; + $pdoDsn .= ';dbname='.$this->export->tmpConnectionDatabase; } $username = $this->getOption('username'); @@ -1577,7 +1593,7 @@ public function getTmpConnection($info) } /** - * modifyLimitQuery + * modifyLimitQuery. * * Some dbms require specific functionality for this. Check the other connection adapters for examples * @@ -1595,13 +1611,14 @@ public function modifyLimitQuery($query, $limit = false, $offset = false, $isMan * @return string */ public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = false, - $offset = false, $isManip = false) + $offset = false, $isManip = false) { return $this->modifyLimitQuery($query, $limit, $offset, $isManip); } /** - * returns a string representation of this object + * returns a string representation of this object. + * * @return string */ public function __toString() @@ -1609,9 +1626,8 @@ public function __toString() return Doctrine_Lib::getConnectionAsString($this); } - /** - * Serialize. Remove database connection(pdo) since it cannot be serialized + * Serialize. Remove database connection(pdo) since it cannot be serialized. * * @return string $serialized */ @@ -1623,10 +1639,9 @@ public function serialize() } /** - * Unserialize. Recreate connection from serialized content + * Unserialize. Recreate connection from serialized content. * * @param string $serialized - * @return void */ public function unserialize($serialized) { @@ -1636,7 +1651,7 @@ public function unserialize($serialized) } /** - * Serialize. Remove database connection(pdo) since it cannot be serialized for PHP 7.4+ + * Serialize. Remove database connection(pdo) since it cannot be serialized for PHP 7.4+. * * @return array */ @@ -1650,22 +1665,22 @@ public function __serialize() } /** - * Unserialize. Recreate connection from serialized content PHP 7.4+ + * Unserialize. Recreate connection from serialized content PHP 7.4+. * * @param array $data - * @return void */ public function __unserialize($data) { foreach ($data as $name => $values) { - $this->$name = $values; + $this->{$name} = $values; } } /** - * Get/generate a unique foreign key name for a relationship + * Get/generate a unique foreign key name for a relationship. + * + * @param Doctrine_Relation $relation Relation object to generate the foreign key name for * - * @param Doctrine_Relation $relation Relation object to generate the foreign key name for * @return string $fkName */ public function generateUniqueRelationForeignKeyName(Doctrine_Relation $relation) @@ -1683,10 +1698,11 @@ public function generateUniqueRelationForeignKeyName(Doctrine_Relation $relation } /** - * Get/generate unique index name for a table name and set of fields + * Get/generate unique index name for a table name and set of fields. + * + * @param string $tableName The name of the table the index exists + * @param string $fields The fields that makes up the index * - * @param string $tableName The name of the table the index exists - * @param string $fields The fields that makes up the index * @return string $indexName The name of the generated index */ public function generateUniqueIndexName($tableName, $fields) @@ -1705,8 +1721,8 @@ protected function _generateUniqueName($type, $parts, $key, $format = '%s', $max if (isset($this->_usedNames[$type][$key])) { return $this->_usedNames[$type][$key]; } - if ($maxLength === null) { - $maxLength = $this->properties['max_identifier_length']; + if (null === $maxLength) { + $maxLength = $this->properties['max_identifier_length']; } $generated = implode('_', $parts); @@ -1731,7 +1747,7 @@ protected function _generateUniqueName($type, $parts, $key, $format = '%s', $max if (is_numeric($end)) { unset($e[count($e) - 1]); $fkName = implode('_', $e); - $name = $fkName . '_' . ++$end; + $name = $fkName.'_'.++$end; } else { $name .= '_1'; } diff --git a/lib/Doctrine/Connection/Common.php b/lib/Doctrine/Connection/Common.php index 36f7e286c..d63e53d7c 100644 --- a/lib/Doctrine/Connection/Common.php +++ b/lib/Doctrine/Connection/Common.php @@ -20,37 +20,38 @@ */ /** - * standard connection, the parent of pgsql, mysql and sqlite + * standard connection, the parent of pgsql, mysql and sqlite. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Connection - * @link www.doctrine-project.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Common extends Doctrine_Connection { /** - * Adds an driver-specific LIMIT clause to the query + * Adds an driver-specific LIMIT clause to the query. * * @param string $query - * @param mixed $limit - * @param mixed $offset + * * @return string */ - public function modifyLimitQuery($query, $limit = false,$offset = false,$isManip=false) + public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { $limit = (int) $limit; $offset = (int) $offset; if ($limit && $offset) { - $query .= ' LIMIT ' . $limit . ' OFFSET ' . $offset; - } elseif ($limit && ! $offset) { - $query .= ' LIMIT ' . $limit; - } elseif ( ! $limit && $offset) { - $query .= ' LIMIT 999999999999 OFFSET ' . $offset; + $query .= ' LIMIT '.$limit.' OFFSET '.$offset; + } elseif ($limit && !$offset) { + $query .= ' LIMIT '.$limit; + } elseif (!$limit && $offset) { + $query .= ' LIMIT 999999999999 OFFSET '.$offset; } return $query; diff --git a/lib/Doctrine/Connection/Db2.php b/lib/Doctrine/Connection/Db2.php index ad9d1505d..dee23d4bc 100644 --- a/lib/Doctrine/Connection/Db2.php +++ b/lib/Doctrine/Connection/Db2.php @@ -20,45 +20,46 @@ */ /** - * Doctrine_Connection_Db2 + * Doctrine_Connection_Db2. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Db2 extends Doctrine_Connection_Common { /** - * Adds an driver-specific LIMIT clause to the query + * Adds an driver-specific LIMIT clause to the query. + * + * @param string $query query to modify + * @param int $limit limit the number of rows + * @param int $offset start reading from given offset * - * @param string $query query to modify - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string the modified query + * @return string the modified query */ public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { - if ($limit <= 0) + if ($limit <= 0) { return $query; + } - if ($offset == 0) { - return $query . ' FETCH FIRST '. (int)$limit .' ROWS ONLY'; - } else { - $sqlPieces = explode('from', $query); - $select = $sqlPieces[0]; - $table = $sqlPieces[1]; + if (0 == $offset) { + return $query.' FETCH FIRST '.(int) $limit.' ROWS ONLY'; + } + $sqlPieces = explode('from', $query); + $select = $sqlPieces[0]; + $table = $sqlPieces[1]; - $col = explode('select', $select); + $col = explode('select', $select); - $sql = 'WITH OFFSET AS(' . $select . ', ROW_NUMBER() ' . - 'OVER(ORDER BY ' . $col[1] . ') AS doctrine_rownum FROM ' . $table . ')' . - $select . 'FROM OFFSET WHERE doctrine_rownum BETWEEN ' . (int)$offset . - 'AND ' . ((int)$offset + (int)$limit - 1); - return $sql; - } + return 'WITH OFFSET AS('.$select.', ROW_NUMBER() '. + 'OVER(ORDER BY '.$col[1].') AS doctrine_rownum FROM '.$table.')'. + $select.'FROM OFFSET WHERE doctrine_rownum BETWEEN '.(int) $offset. + 'AND '.((int) $offset + (int) $limit - 1); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Exception.php b/lib/Doctrine/Connection/Exception.php index 43e6161db..796a4b6f8 100644 --- a/lib/Doctrine/Connection/Exception.php +++ b/lib/Doctrine/Connection/Exception.php @@ -20,68 +20,70 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Exception extends Doctrine_Exception { /** - * @var array $errorMessages an array containing messages for portable error codes + * @var array an array containing messages for portable error codes */ - static protected $errorMessages = array( - Doctrine_Core::ERR => 'unknown error', - Doctrine_Core::ERR_ALREADY_EXISTS => 'already exists', - Doctrine_Core::ERR_CANNOT_CREATE => 'can not create', - Doctrine_Core::ERR_CANNOT_ALTER => 'can not alter', - Doctrine_Core::ERR_CANNOT_REPLACE => 'can not replace', - Doctrine_Core::ERR_CANNOT_DELETE => 'can not delete', - Doctrine_Core::ERR_CANNOT_DROP => 'can not drop', - Doctrine_Core::ERR_CONSTRAINT => 'constraint violation', - Doctrine_Core::ERR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint', - Doctrine_Core::ERR_DIVZERO => 'division by zero', - Doctrine_Core::ERR_INVALID => 'invalid', - Doctrine_Core::ERR_INVALID_DATE => 'invalid date or time', - Doctrine_Core::ERR_INVALID_NUMBER => 'invalid number', - Doctrine_Core::ERR_MISMATCH => 'mismatch', - Doctrine_Core::ERR_NODBSELECTED => 'no database selected', - Doctrine_Core::ERR_NOSUCHFIELD => 'no such field', - Doctrine_Core::ERR_NOSUCHTABLE => 'no such table', - Doctrine_Core::ERR_NOT_CAPABLE => 'Doctrine backend not capable', - Doctrine_Core::ERR_NOT_FOUND => 'not found', - Doctrine_Core::ERR_NOT_LOCKED => 'not locked', - Doctrine_Core::ERR_SYNTAX => 'syntax error', - Doctrine_Core::ERR_UNSUPPORTED => 'not supported', - Doctrine_Core::ERR_VALUE_COUNT_ON_ROW => 'value count on row', - Doctrine_Core::ERR_INVALID_DSN => 'invalid DSN', - Doctrine_Core::ERR_CONNECT_FAILED => 'connect failed', - Doctrine_Core::ERR_NEED_MORE_DATA => 'insufficient data supplied', - Doctrine_Core::ERR_EXTENSION_NOT_FOUND=> 'extension not found', - Doctrine_Core::ERR_NOSUCHDB => 'no such database', - Doctrine_Core::ERR_ACCESS_VIOLATION => 'insufficient permissions', - Doctrine_Core::ERR_LOADMODULE => 'error while including on demand module', - Doctrine_Core::ERR_TRUNCATED => 'truncated', - Doctrine_Core::ERR_DEADLOCK => 'deadlock detected', - ); + protected static $errorMessages = array( + Doctrine_Core::ERR => 'unknown error', + Doctrine_Core::ERR_ALREADY_EXISTS => 'already exists', + Doctrine_Core::ERR_CANNOT_CREATE => 'can not create', + Doctrine_Core::ERR_CANNOT_ALTER => 'can not alter', + Doctrine_Core::ERR_CANNOT_REPLACE => 'can not replace', + Doctrine_Core::ERR_CANNOT_DELETE => 'can not delete', + Doctrine_Core::ERR_CANNOT_DROP => 'can not drop', + Doctrine_Core::ERR_CONSTRAINT => 'constraint violation', + Doctrine_Core::ERR_CONSTRAINT_NOT_NULL => 'null value violates not-null constraint', + Doctrine_Core::ERR_DIVZERO => 'division by zero', + Doctrine_Core::ERR_INVALID => 'invalid', + Doctrine_Core::ERR_INVALID_DATE => 'invalid date or time', + Doctrine_Core::ERR_INVALID_NUMBER => 'invalid number', + Doctrine_Core::ERR_MISMATCH => 'mismatch', + Doctrine_Core::ERR_NODBSELECTED => 'no database selected', + Doctrine_Core::ERR_NOSUCHFIELD => 'no such field', + Doctrine_Core::ERR_NOSUCHTABLE => 'no such table', + Doctrine_Core::ERR_NOT_CAPABLE => 'Doctrine backend not capable', + Doctrine_Core::ERR_NOT_FOUND => 'not found', + Doctrine_Core::ERR_NOT_LOCKED => 'not locked', + Doctrine_Core::ERR_SYNTAX => 'syntax error', + Doctrine_Core::ERR_UNSUPPORTED => 'not supported', + Doctrine_Core::ERR_VALUE_COUNT_ON_ROW => 'value count on row', + Doctrine_Core::ERR_INVALID_DSN => 'invalid DSN', + Doctrine_Core::ERR_CONNECT_FAILED => 'connect failed', + Doctrine_Core::ERR_NEED_MORE_DATA => 'insufficient data supplied', + Doctrine_Core::ERR_EXTENSION_NOT_FOUND => 'extension not found', + Doctrine_Core::ERR_NOSUCHDB => 'no such database', + Doctrine_Core::ERR_ACCESS_VIOLATION => 'insufficient permissions', + Doctrine_Core::ERR_LOADMODULE => 'error while including on demand module', + Doctrine_Core::ERR_TRUNCATED => 'truncated', + Doctrine_Core::ERR_DEADLOCK => 'deadlock detected', + ); /** * @see Doctrine_Core::ERR_* constants * @since 1.0 - * @var integer $portableCode portable error code + * + * @var int portable error code */ protected $portableCode; /** * getPortableCode - * returns portable error code + * returns portable error code. * - * @return integer portable error code + * @return int portable error code */ public function getPortableCode() { @@ -90,9 +92,9 @@ public function getPortableCode() /** * getPortableMessage - * returns portable error message + * returns portable error message. * - * @return string portable error message + * @return string portable error message */ public function getPortableMessage() { @@ -100,14 +102,15 @@ public function getPortableMessage() } /** - * Return a textual error message for a Doctrine error code + * Return a textual error message for a Doctrine error code. * * @param int|array integer error code, * null to get the current error code-message map, * or an array with a new error code-message map + * @param mixed|null $value * - * @return string error message, or false if the error code was - * not recognized + * @return string error message, or false if the error code was + * not recognized */ public function errorMessage($value = null) { @@ -118,13 +121,16 @@ public function errorMessage($value = null) /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Connection/Mock.php b/lib/Doctrine/Connection/Mock.php index e101a2dc4..220059754 100644 --- a/lib/Doctrine/Connection/Mock.php +++ b/lib/Doctrine/Connection/Mock.php @@ -20,32 +20,30 @@ */ /** - * Doctrine_Connection_Mysql + * Doctrine_Connection_Mysql. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Mock extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Mock'; /** - * the constructor + * the constructor. * - * @param Doctrine_Manager $manager - * @param PDO|Doctrine_Adapter $adapter database handler + * @param PDO|Doctrine_Adapter $adapter database handler */ public function __construct(Doctrine_Manager $manager, $adapter) { - } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Module.php b/lib/Doctrine/Connection/Module.php index a6c27a917..d8b572c84 100644 --- a/lib/Doctrine/Connection/Module.php +++ b/lib/Doctrine/Connection/Module.php @@ -20,36 +20,37 @@ */ /** - * Doctrine_Connection_Module + * Doctrine_Connection_Module. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Module { /** - * @var Doctrine_Connection $conn Doctrine_Connection object, every connection - * module holds an instance of Doctrine_Connection + * @var Doctrine_Connection Doctrine_Connection object, every connection + * module holds an instance of Doctrine_Connection */ protected $conn; /** - * @var string $moduleName the name of this module + * @var string the name of this module */ protected $moduleName; /** - * @param Doctrine_Connection $conn Doctrine_Connection object, every connection - * module holds an instance of Doctrine_Connection + * @param Doctrine_Connection $conn Doctrine_Connection object, every connection + * module holds an instance of Doctrine_Connection */ public function __construct($conn = null) { - if ( ! ($conn instanceof Doctrine_Connection)) { + if (!($conn instanceof Doctrine_Connection)) { $conn = Doctrine_Manager::getInstance()->getCurrentConnection(); } $this->conn = $conn; @@ -61,7 +62,7 @@ public function __construct($conn = null) /** * getConnection - * returns the connection object this module uses + * returns the connection object this module uses. * * @return Doctrine_Connection */ @@ -72,12 +73,12 @@ public function getConnection() /** * getModuleName - * returns the name of this module + * returns the name of this module. * - * @return string the name of this module + * @return string the name of this module */ public function getModuleName() { return $this->moduleName; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Mssql.php b/lib/Doctrine/Connection/Mssql.php index ecce33f10..f83458983 100644 --- a/lib/Doctrine/Connection/Mssql.php +++ b/lib/Doctrine/Connection/Mssql.php @@ -20,50 +20,47 @@ */ /** - * Doctrine_Connection_Mssql + * Doctrine_Connection_Mssql. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7690 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Mssql extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Mssql'; /** - * the constructor - * - * @param Doctrine_Manager $manager - * @param PDO $pdo database handle + * the constructor. */ public function __construct(Doctrine_Manager $manager, $adapter) { // initialize all driver options $this->supported = array( - 'sequences' => 'emulated', - 'indexes' => true, - 'affected_rows' => true, - 'transactions' => true, - 'summary_functions' => true, - 'order_by_text' => true, - 'current_id' => 'emulated', - 'limit_queries' => 'emulated', - 'LOBs' => true, - 'replace' => 'emulated', - 'sub_selects' => true, - 'auto_increment' => true, - 'primary_key' => true, - 'result_introspection' => true, - 'prepared_statements' => 'emulated', - ); + 'sequences' => 'emulated', + 'indexes' => true, + 'affected_rows' => true, + 'transactions' => true, + 'summary_functions' => true, + 'order_by_text' => true, + 'current_id' => 'emulated', + 'limit_queries' => 'emulated', + 'LOBs' => true, + 'replace' => 'emulated', + 'sub_selects' => true, + 'auto_increment' => true, + 'primary_key' => true, + 'result_introspection' => true, + 'prepared_statements' => 'emulated', + ); $this->properties['varchar_max_length'] = 8000; @@ -72,22 +69,22 @@ public function __construct(Doctrine_Manager $manager, $adapter) /** * quoteIdentifier - * Quote a string so it can be safely used as a table / column name + * Quote a string so it can be safely used as a table / column name. * * Quoting style depends on which database driver is being used. * - * @param string $identifier identifier name to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param string $identifier identifier name to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteIdentifier($identifier, $checkOption = false) { - if ($checkOption && ! $this->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { + if ($checkOption && !$this->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { return $identifier; } - if (strpos($identifier, '.') !== false) { + if (false !== strpos($identifier, '.')) { $parts = explode('.', $identifier); $quotedParts = array(); foreach ($parts as $p) { @@ -97,43 +94,42 @@ public function quoteIdentifier($identifier, $checkOption = false) return implode('.', $quotedParts); } - return '[' . trim($identifier, '[]') . ']'; + return '['.trim($identifier, '[]').']'; } /** * Adds an adapter-specific LIMIT clause to the SELECT statement. - * Inspired by Doctrine2 DBAL + * Inspired by Doctrine2 DBAL. * * @param string $query - * @param mixed $limit - * @param mixed $offset - * @param boolean $isSubQuery - * @param Doctrine_Query $queryOrigin - * @link https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Platforms/MsSqlPlatform.php#L607 - * @link http://www.toosweettobesour.com/2010/09/16/doctrine-1-2-mssql-alternative-limitpaging/ + * @param bool $isSubQuery + * + * @see https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Platforms/MsSqlPlatform.php#L607 + * @see http://www.toosweettobesour.com/2010/09/16/doctrine-1-2-mssql-alternative-limitpaging/ + * * @return string */ public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false, $isSubQuery = false, Doctrine_Query $queryOrigin = null) { - if ($limit === false || !($limit > 0)) { + if (false === $limit || !($limit > 0)) { return $query; } $orderby = stristr($query, 'ORDER BY'); - if ($offset !== false && $orderby === false) { - throw new Doctrine_Connection_Exception("OFFSET cannot be used in MSSQL without ORDER BY due to emulation reasons."); + if (false !== $offset && false === $orderby) { + throw new Doctrine_Connection_Exception('OFFSET cannot be used in MSSQL without ORDER BY due to emulation reasons.'); } $limit = intval($limit); $offset = intval($offset); if ($offset < 0) { - throw new Doctrine_Connection_Exception("LIMIT argument offset=$offset is not valid"); + throw new Doctrine_Connection_Exception("LIMIT argument offset={$offset} is not valid"); } - if ($offset == 0) { - $query = preg_replace('/^SELECT( DISTINCT)?\s/i', 'SELECT\1 TOP ' . $limit . ' ', $query); + if (0 == $offset) { + $query = preg_replace('/^SELECT( DISTINCT)?\s/i', 'SELECT\1 TOP '.$limit.' ', $query); } else { $over = stristr($query, 'ORDER BY'); @@ -148,33 +144,31 @@ public function modifyLimitQuery($query, $limit = false, $offset = false, $isMan $query = substr($query, strlen('SELECT ')); $select = 'SELECT'; - if (0 === strpos($query, 'DISTINCT')) - { - $query = substr($query, strlen('DISTINCT ')); - $select .= ' DISTINCT'; + if (0 === strpos($query, 'DISTINCT')) { + $query = substr($query, strlen('DISTINCT ')); + $select .= ' DISTINCT'; } $start = $offset + 1; $end = $offset + $limit; - $query = "SELECT * FROM ($select ROW_NUMBER() OVER ($over) AS [DOCTRINE_ROWNUM], $query) AS [doctrine_tbl] WHERE [DOCTRINE_ROWNUM] BETWEEN $start AND $end"; + $query = "SELECT * FROM ({$select} ROW_NUMBER() OVER ({$over}) AS [DOCTRINE_ROWNUM], {$query}) AS [doctrine_tbl] WHERE [DOCTRINE_ROWNUM] BETWEEN {$start} AND {$end}"; } return $query; } - /** - * Parse an OrderBy-Statement into chunks + * Parse an OrderBy-Statement into chunks. * * @param string $orderby */ private function parseOrderBy($orderby) { $matches = array(); - $chunks = array(); - $tokens = array(); - $parsed = str_ireplace('ORDER BY', '', $orderby); + $chunks = array(); + $tokens = array(); + $parsed = str_ireplace('ORDER BY', '', $orderby); preg_match_all('/(\w+\(.+?\)\s+(ASC|DESC)),?/', $orderby, $matches); @@ -182,13 +176,13 @@ private function parseOrderBy($orderby) foreach ($matchesWithExpressions as $match) { $chunks[] = $match; - $parsed = str_replace($match, '##' . (count($chunks) - 1) . '##', $parsed); + $parsed = str_replace($match, '##'.(count($chunks) - 1).'##', $parsed); } $tokens = preg_split('/,/', $parsed); - for ($i = 0, $iMax = count($tokens); $i < $iMax; $i++) { - $tokens[$i] = trim(preg_replace_callback('/##(\d+)##/', function($m) { return $chunks[$m[1]]; }, $tokens[$i])); + for ($i = 0, $iMax = count($tokens); $i < $iMax; ++$i) { + $tokens[$i] = trim(preg_replace_callback('/##(\d+)##/', function ($m) { return $chunks[$m[1]]; }, $tokens[$i])); } return $tokens; @@ -199,17 +193,18 @@ private function parseOrderBy($orderby) * This method fix this issue by wrap the given term (column) into a CAST directive. * * @see DC-828 - * @param Doctrine_Table $table + * * @param string $field - * @param string $term The term which will changed if it's necessary, depending to the field type. + * @param string $term the term which will changed if it's necessary, depending to the field type + * * @return string */ public function modifyOrderByColumn(Doctrine_Table $table, $field, $term) { $def = $table->getDefinitionOf($field); - if ($def['type'] == 'string' && $def['length'] === NULL) { - $term = 'CAST(' . $term . ' AS varchar(8000))'; + if ('string' == $def['type'] && null === $def['length']) { + $term = 'CAST('.$term.' AS varchar(8000))'; } return $term; @@ -227,22 +222,23 @@ public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = } /** - * return version information about the server + * return version information about the server. + * + * @param bool $native determines if the raw version string should be returned * - * @param bool $native determines if the raw version string should be returned - * @return array version information + * @return array version information */ public function getServerVersion($native = false) { if ($this->serverInfo) { $serverInfo = $this->serverInfo; } else { - $query = 'SELECT @@VERSION'; + $query = 'SELECT @@VERSION'; $serverInfo = $this->fetchOne($query); } // cache server_info $this->serverInfo = $serverInfo; - if ( ! $native) { + if (!$native) { if (preg_match('/([0-9]+)\.([0-9]+)\.([0-9]+)/', $serverInfo, $tmp)) { $serverInfo = array( 'major' => $tmp[1], @@ -261,40 +257,42 @@ public function getServerVersion($native = false) ); } } + return $serverInfo; } /** * Checks if there's a sequence that exists. * - * @param string $seq_name The sequence name to verify. - * @return boolean The value if the table exists or not + * @return bool The value if the table exists or not */ public function checkSequence($seqName) { - $query = 'SELECT * FROM ' . $seqName; + $query = 'SELECT * FROM '.$seqName; try { $this->exec($query); - } catch(Doctrine_Connection_Exception $e) { - if ($e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if (Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { return false; } throw $e; } + return true; } /** - * execute - * @param string $query sql query - * @param array $params query parameters + * execute. + * + * @param string $query sql query + * @param array $params query parameters * * @return PDOStatement|Doctrine_Adapter_Statement */ public function execute($query, array $params = array()) { - if(! empty($params)) { + if (!empty($params)) { $query = $this->replaceBoundParamsWithInlineValuesInQuery($query, $params); } @@ -302,15 +300,16 @@ public function execute($query, array $params = array()) } /** - * execute - * @param string $query sql query - * @param array $params query parameters + * execute. + * + * @param string $query sql query + * @param array $params query parameters * * @return PDOStatement|Doctrine_Adapter_Statement */ public function exec($query, array $params = array()) { - if(! empty($params)) { + if (!empty($params)) { $query = $this->replaceBoundParamsWithInlineValuesInQuery($query, $params); } @@ -323,30 +322,27 @@ public function exec($query, array $params = array()) * Workaround for http://bugs.php.net/36561 * * @param string $query - * @param array $params */ protected function replaceBoundParamsWithInlineValuesInQuery($query, array $params) { - foreach($params as $key => $value) { + foreach ($params as $key => $value) { $re = '/(?<=WHERE|VALUES|SET|JOIN)(.*?)(\?)/'; $query = preg_replace($re, "\\1##{$key}##", $query, 1); } $self = $this; - $query = preg_replace_callback('/##(\d+)##/', function($m) use ($params, $self) { + + return preg_replace_callback('/##(\d+)##/', function ($m) use ($params, $self) { return (null === $params[$m[1]]) ? 'NULL' : $self->quote($params[$m[1]]); }, $query); - - return $query; } /** * Inserts a table row with specified data. * - * @param Doctrine_Table $table The table to insert data into. - * @param array $values An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param Doctrine_Table $table the table to insert data into + * + * @return int the number of affected rows. Boolean false if empty value array was given, */ public function insert(Doctrine_Table $table, array $fields) { @@ -354,11 +350,11 @@ public function insert(Doctrine_Table $table, array $fields) $settingNullIdentifier = false; $fields = array_change_key_case($fields); - foreach($identifiers as $identifier) { + foreach ($identifiers as $identifier) { $lcIdentifier = strtolower($identifier); - if(array_key_exists($lcIdentifier, $fields)) { - if(is_null($fields[$lcIdentifier])) { + if (array_key_exists($lcIdentifier, $fields)) { + if (is_null($fields[$lcIdentifier])) { $settingNullIdentifier = true; unset($fields[$lcIdentifier]); } @@ -367,9 +363,9 @@ public function insert(Doctrine_Table $table, array $fields) // MSSQL won't allow the setting of identifier columns to null, so insert a default record and then update it if ($settingNullIdentifier) { - $count = $this->exec('INSERT INTO ' . $this->quoteIdentifier($table->getTableName()) . ' DEFAULT VALUES'); + $count = $this->exec('INSERT INTO '.$this->quoteIdentifier($table->getTableName()).' DEFAULT VALUES'); - if(! $count) { + if (!$count) { return $count; } diff --git a/lib/Doctrine/Connection/Mssql/Exception.php b/lib/Doctrine/Connection/Mssql/Exception.php index f961f2dcc..992713b30 100644 --- a/lib/Doctrine/Connection/Mssql/Exception.php +++ b/lib/Doctrine/Connection/Mssql/Exception.php @@ -20,56 +20,61 @@ */ /** - * Doctrine_Connection_Mssql_Exception + * Doctrine_Connection_Mssql_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Connection_Mssql_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorCodeMap an array that is used for determining portable - * error code from a native database error code + * @var array an array that is used for determining portable + * error code from a native database error code */ protected static $errorCodeMap = array( - 110 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - 155 => Doctrine_Core::ERR_NOSUCHFIELD, - 170 => Doctrine_Core::ERR_SYNTAX, - 207 => Doctrine_Core::ERR_NOSUCHFIELD, - 208 => Doctrine_Core::ERR_NOSUCHTABLE, - 245 => Doctrine_Core::ERR_INVALID_NUMBER, - 515 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - 547 => Doctrine_Core::ERR_CONSTRAINT, - 1913 => Doctrine_Core::ERR_ALREADY_EXISTS, - 2627 => Doctrine_Core::ERR_CONSTRAINT, - 2714 => Doctrine_Core::ERR_ALREADY_EXISTS, - 3701 => Doctrine_Core::ERR_NOSUCHTABLE, - 8134 => Doctrine_Core::ERR_DIVZERO, - ); + 110 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + 155 => Doctrine_Core::ERR_NOSUCHFIELD, + 170 => Doctrine_Core::ERR_SYNTAX, + 207 => Doctrine_Core::ERR_NOSUCHFIELD, + 208 => Doctrine_Core::ERR_NOSUCHTABLE, + 245 => Doctrine_Core::ERR_INVALID_NUMBER, + 515 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + 547 => Doctrine_Core::ERR_CONSTRAINT, + 1913 => Doctrine_Core::ERR_ALREADY_EXISTS, + 2627 => Doctrine_Core::ERR_CONSTRAINT, + 2714 => Doctrine_Core::ERR_ALREADY_EXISTS, + 3701 => Doctrine_Core::ERR_NOSUCHTABLE, + 8134 => Doctrine_Core::ERR_DIVZERO, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { $code = $errorInfo[1]; if (isset(self::$errorCodeMap[$code])) { $this->portableCode = self::$errorCodeMap[$code]; + return true; } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Mysql.php b/lib/Doctrine/Connection/Mysql.php index 7a7e59c16..89b22e5b0 100644 --- a/lib/Doctrine/Connection/Mysql.php +++ b/lib/Doctrine/Connection/Mysql.php @@ -20,68 +20,67 @@ */ /** - * Doctrine_Connection_Mysql + * Doctrine_Connection_Mysql. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Mysql extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Mysql'; /** - * the constructor + * the constructor. * - * @param Doctrine_Manager $manager - * @param PDO|Doctrine_Adapter $adapter database handler + * @param PDO|Doctrine_Adapter $adapter database handler */ public function __construct(Doctrine_Manager $manager, $adapter) { $this->setAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_TYPE, 'INNODB'); $this->supported = array( - 'sequences' => 'emulated', - 'indexes' => true, - 'affected_rows' => true, - 'transactions' => true, - 'savepoints' => false, - 'summary_functions' => true, - 'order_by_text' => true, - 'current_id' => 'emulated', - 'limit_queries' => true, - 'LOBs' => true, - 'replace' => true, - 'sub_selects' => true, - 'auto_increment' => true, - 'primary_key' => true, - 'result_introspection' => true, - 'prepared_statements' => 'emulated', - 'identifier_quoting' => true, - 'pattern_escaping' => true - ); + 'sequences' => 'emulated', + 'indexes' => true, + 'affected_rows' => true, + 'transactions' => true, + 'savepoints' => false, + 'summary_functions' => true, + 'order_by_text' => true, + 'current_id' => 'emulated', + 'limit_queries' => true, + 'LOBs' => true, + 'replace' => true, + 'sub_selects' => true, + 'auto_increment' => true, + 'primary_key' => true, + 'result_introspection' => true, + 'prepared_statements' => 'emulated', + 'identifier_quoting' => true, + 'pattern_escaping' => true, + ); $this->properties['string_quoting'] = array('start' => "'", - 'end' => "'", - 'escape' => '\\', - 'escape_pattern' => '\\'); + 'end' => "'", + 'escape' => '\\', + 'escape_pattern' => '\\'); $this->properties['identifier_quoting'] = array('start' => '`', - 'end' => '`', - 'escape' => '`'); + 'end' => '`', + 'escape' => '`'); $this->properties['sql_comments'] = array( - array('start' => '-- ', 'end' => "\n", 'escape' => false), - array('start' => '#', 'end' => "\n", 'escape' => false), - array('start' => '/*', 'end' => '*/', 'escape' => false), - ); + array('start' => '-- ', 'end' => "\n", 'escape' => false), + array('start' => '#', 'end' => "\n", 'escape' => false), + array('start' => '/*', 'end' => '*/', 'escape' => false), + ); $this->properties['varchar_max_length'] = 255; @@ -96,22 +95,22 @@ public function __construct(Doctrine_Manager $manager, $adapter) /** * Overrides connect Method, to add specific attributes * PDO emulate prepares is required to avoid bugs on mysql < 5.1 - * when trying to prepare DROP DATABASE or CREATE DATABASE statements + * when trying to prepare DROP DATABASE or CREATE DATABASE statements. * * @see Doctrine_Connection :: connect(); - * @return boolean connected + * + * @return bool connected */ - public function connect() - { - $connected = parent::connect(); - $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); - - return $connected; - } - - + public function connect() + { + $connected = parent::connect(); + $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, true); + + return $connected; + } + /** - * returns the name of the connected database + * returns the name of the connected database. * * @return string */ @@ -121,13 +120,13 @@ public function getDatabaseName() } /** - * Set the charset on the current connection + * Set the charset on the current connection. * * @param string charset */ public function setCharset($charset) { - $query = 'SET NAMES ' . $this->quote($charset); + $query = 'SET NAMES '.$this->quote($charset); $this->exec($query); parent::setCharset($charset); } @@ -143,15 +142,13 @@ public function setCharset($charset) * emulated through this method for other DBMS using standard types of * queries inside a transaction to assure the atomicity of the operation. * - * @access public - * - * @param string $table name of the table on which the REPLACE query will - * be executed. - * @param array $fields associative array that describes the fields and the - * values that will be inserted or updated in the specified table. The - * indexes of the array are the names of all the fields of the table. The - * values of the array are also associative arrays that describe the - * values and other properties of the table fields. + * @param string $table name of the table on which the REPLACE query will + * be executed + * @param array $fields associative array that describes the fields and the + * values that will be inserted or updated in the specified table. The + * indexes of the array are the names of all the fields of the table. The + * values of the array are also associative arrays that describe the + * values and other properties of the table fields. * * Here follows a list of field properties that need to be specified: * @@ -194,7 +191,7 @@ public function setCharset($charset) * * Default: 0 * - * @return integer the number of affected rows + * @return int the number of affected rows */ public function replace(Doctrine_Table $table, array $fields, array $keys) { @@ -211,8 +208,8 @@ public function replace(Doctrine_Table $table, array $fields, array $keys) $params[] = $value; } - $query = 'REPLACE INTO ' . $this->quoteIdentifier($table->getTableName()) . ' (' . implode(',', $columns) . ') VALUES (' . implode(',', $values) . ')'; + $query = 'REPLACE INTO '.$this->quoteIdentifier($table->getTableName()).' ('.implode(',', $columns).') VALUES ('.implode(',', $values).')'; return $this->exec($query, $params); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Mysql/Exception.php b/lib/Doctrine/Connection/Mysql/Exception.php index 65412b6b7..a4b2b7b3f 100644 --- a/lib/Doctrine/Connection/Mysql/Exception.php +++ b/lib/Doctrine/Connection/Mysql/Exception.php @@ -20,67 +20,72 @@ */ /** - * Doctrine_Connection_Mysql_Exception + * Doctrine_Connection_Mysql_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Connection_Mysql_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorCodeMap an array that is used for determining portable - * error code from a native database error code + * @var array an array that is used for determining portable + * error code from a native database error code */ protected static $errorCodeMap = array( - 1004 => Doctrine_Core::ERR_CANNOT_CREATE, - 1005 => Doctrine_Core::ERR_CANNOT_CREATE, - 1006 => Doctrine_Core::ERR_CANNOT_CREATE, - 1007 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1008 => Doctrine_Core::ERR_CANNOT_DROP, - 1022 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1044 => Doctrine_Core::ERR_ACCESS_VIOLATION, - 1046 => Doctrine_Core::ERR_NODBSELECTED, - 1048 => Doctrine_Core::ERR_CONSTRAINT, - 1049 => Doctrine_Core::ERR_NOSUCHDB, - 1050 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1051 => Doctrine_Core::ERR_NOSUCHTABLE, - 1054 => Doctrine_Core::ERR_NOSUCHFIELD, - 1061 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1062 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1064 => Doctrine_Core::ERR_SYNTAX, - 1091 => Doctrine_Core::ERR_NOT_FOUND, - 1100 => Doctrine_Core::ERR_NOT_LOCKED, - 1136 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - 1142 => Doctrine_Core::ERR_ACCESS_VIOLATION, - 1146 => Doctrine_Core::ERR_NOSUCHTABLE, - 1216 => Doctrine_Core::ERR_CONSTRAINT, - 1217 => Doctrine_Core::ERR_CONSTRAINT, - 1451 => Doctrine_Core::ERR_CONSTRAINT, - ); + 1004 => Doctrine_Core::ERR_CANNOT_CREATE, + 1005 => Doctrine_Core::ERR_CANNOT_CREATE, + 1006 => Doctrine_Core::ERR_CANNOT_CREATE, + 1007 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1008 => Doctrine_Core::ERR_CANNOT_DROP, + 1022 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1044 => Doctrine_Core::ERR_ACCESS_VIOLATION, + 1046 => Doctrine_Core::ERR_NODBSELECTED, + 1048 => Doctrine_Core::ERR_CONSTRAINT, + 1049 => Doctrine_Core::ERR_NOSUCHDB, + 1050 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1051 => Doctrine_Core::ERR_NOSUCHTABLE, + 1054 => Doctrine_Core::ERR_NOSUCHFIELD, + 1061 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1062 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1064 => Doctrine_Core::ERR_SYNTAX, + 1091 => Doctrine_Core::ERR_NOT_FOUND, + 1100 => Doctrine_Core::ERR_NOT_LOCKED, + 1136 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + 1142 => Doctrine_Core::ERR_ACCESS_VIOLATION, + 1146 => Doctrine_Core::ERR_NOSUCHTABLE, + 1216 => Doctrine_Core::ERR_CONSTRAINT, + 1217 => Doctrine_Core::ERR_CONSTRAINT, + 1451 => Doctrine_Core::ERR_CONSTRAINT, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { $code = $errorInfo[1]; if (isset(self::$errorCodeMap[$code])) { $this->portableCode = self::$errorCodeMap[$code]; + return true; } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Oracle.php b/lib/Doctrine/Connection/Oracle.php index 6649abfb6..478ba7d54 100644 --- a/lib/Doctrine/Connection/Oracle.php +++ b/lib/Doctrine/Connection/Oracle.php @@ -20,121 +20,123 @@ */ /** - * Doctrine_Connection_Oracle + * Doctrine_Connection_Oracle. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7664 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Oracle extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Oracle'; public function __construct(Doctrine_Manager $manager, $adapter) { $this->supported = array( - 'sequences' => true, - 'indexes' => true, - 'summary_functions' => true, - 'order_by_text' => true, - 'current_id' => true, - 'affected_rows' => true, - 'transactions' => true, - 'savepoints' => true, - 'limit_queries' => true, - 'LOBs' => true, - 'replace' => 'emulated', - 'sub_selects' => true, - 'auto_increment' => false, // implementation is broken - 'primary_key' => true, - 'result_introspection' => true, - 'prepared_statements' => true, - 'identifier_quoting' => true, - 'pattern_escaping' => true, - ); - - $this->properties['sql_file_delimiter'] = "\n/\n"; - $this->properties['number_max_precision'] = 38; + 'sequences' => true, + 'indexes' => true, + 'summary_functions' => true, + 'order_by_text' => true, + 'current_id' => true, + 'affected_rows' => true, + 'transactions' => true, + 'savepoints' => true, + 'limit_queries' => true, + 'LOBs' => true, + 'replace' => 'emulated', + 'sub_selects' => true, + 'auto_increment' => false, // implementation is broken + 'primary_key' => true, + 'result_introspection' => true, + 'prepared_statements' => true, + 'identifier_quoting' => true, + 'pattern_escaping' => true, + ); + + $this->properties['sql_file_delimiter'] = "\n/\n"; + $this->properties['number_max_precision'] = 38; $this->properties['max_identifier_length'] = 30; parent::__construct($manager, $adapter); - + // moving properties to params to make them changeable by user - // VARCHAR2 allowed length is 4000 BYTE. For UTF8 strings is better to use 1000 CHAR + // VARCHAR2 allowed length is 4000 BYTE. For UTF8 strings is better to use 1000 CHAR $this->setParam('varchar2_max_length', 4000); // Oracle's default unit for char data types is BYTE. For UTF8 string it is better to use CHAR $this->setParam('char_unit', null); } /** - * Sets up the date/time format - * + * Sets up the date/time format. */ public function setDateFormat($format = 'YYYY-MM-DD HH24:MI:SS') { - $this->exec('ALTER SESSION SET NLS_DATE_FORMAT = "' . $format . '"'); + $this->exec('ALTER SESSION SET NLS_DATE_FORMAT = "'.$format.'"'); } /** - * Adds an driver-specific LIMIT clause to the query + * Adds an driver-specific LIMIT clause to the query. + * + * @param string $query query to modify + * @param int $limit limit the number of rows + * @param int $offset start reading from given offset * - * @param string $query query to modify - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @return string the modified query + * @return string the modified query */ public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { return $this->_createLimitSubquery($query, $limit, $offset); } - + private function _createLimitSubquery($query, $limit, $offset, $column = null) { $limit = (int) $limit; $offset = (int) $offset; if (preg_match('/^\s*SELECT/i', $query)) { - if ( ! preg_match('/\sFROM\s/i', $query)) { - $query .= " FROM dual"; + if (!preg_match('/\sFROM\s/i', $query)) { + $query .= ' FROM dual'; } if ($limit > 0) { $max = $offset + $limit; - $column = $column === null ? '*' : $this->quoteIdentifier($column); + $column = null === $column ? '*' : $this->quoteIdentifier($column); if ($offset > 0) { $min = $offset + 1; $query = 'SELECT '.$this->quoteIdentifier('b').'.'.$column.' FROM ( '. 'SELECT '.$this->quoteIdentifier('a').'.*, ROWNUM AS doctrine_rownum FROM ( ' - . $query . ' ) ' . $this->quoteIdentifier('a') . ' '. - ' ) ' . $this->quoteIdentifier('b') . ' '. - 'WHERE doctrine_rownum BETWEEN ' . $min . ' AND ' . $max; + .$query.' ) '.$this->quoteIdentifier('a').' '. + ' ) '.$this->quoteIdentifier('b').' '. + 'WHERE doctrine_rownum BETWEEN '.$min.' AND '.$max; } else { - $query = 'SELECT a.'.$column.' FROM ( ' . $query .' ) a WHERE ROWNUM <= ' . $max; + $query = 'SELECT a.'.$column.' FROM ( '.$query.' ) a WHERE ROWNUM <= '.$max; } } } + return $query; } - + /** * Creates the SQL for Oracle that can be used in the subquery for the limit-subquery * algorithm. */ public function modifyLimitSubquery(Doctrine_Table $rootTable, $query, $limit = false, - $offset = false, $isManip = false) + $offset = false, $isManip = false) { // NOTE: no composite key support $columnNames = $rootTable->getIdentifierColumnNames(); if (count($columnNames) > 1) { - throw new Doctrine_Connection_Exception("Composite keys in LIMIT queries are " - . "currently not supported."); + throw new Doctrine_Connection_Exception('Composite keys in LIMIT queries are currently not supported.'); } $column = $columnNames[0]; + return $this->_createLimitSubquery($query, $limit, $offset, $column); } @@ -146,17 +148,19 @@ public function getTmpConnection($info) /** * Override quote behaviour for boolean to fix issues with quoting of * boolean values. + * + * @param mixed|null $type */ public function quote($input, $type = null) { - if ($type === 'boolean') { - if ($input === null) { + if ('boolean' === $type) { + if (null === $input) { return null; - } else { - return $input ? 1 : 0; } - } else { - return parent::quote($input, $type); + + return $input ? 1 : 0; } + + return parent::quote($input, $type); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Oracle/Exception.php b/lib/Doctrine/Connection/Oracle/Exception.php index 9a8721ca8..77c1577f2 100644 --- a/lib/Doctrine/Connection/Oracle/Exception.php +++ b/lib/Doctrine/Connection/Oracle/Exception.php @@ -20,61 +20,66 @@ */ /** - * Doctrine_Connection_Oracle_Exception + * Doctrine_Connection_Oracle_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Connection_Oracle_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorCodeMap an array that is used for determining portable - * error code from a native database error code + * @var array an array that is used for determining portable + * error code from a native database error code */ protected static $errorCodeMap = array( - 1 => Doctrine_Core::ERR_CONSTRAINT, - 900 => Doctrine_Core::ERR_SYNTAX, - 904 => Doctrine_Core::ERR_NOSUCHFIELD, - 913 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - 921 => Doctrine_Core::ERR_SYNTAX, - 923 => Doctrine_Core::ERR_SYNTAX, - 942 => Doctrine_Core::ERR_NOSUCHTABLE, - 955 => Doctrine_Core::ERR_ALREADY_EXISTS, - 1400 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - 1401 => Doctrine_Core::ERR_INVALID, - 1407 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - 1418 => Doctrine_Core::ERR_NOT_FOUND, - 1476 => Doctrine_Core::ERR_DIVZERO, - 1722 => Doctrine_Core::ERR_INVALID_NUMBER, - 2289 => Doctrine_Core::ERR_NOSUCHTABLE, - 2291 => Doctrine_Core::ERR_CONSTRAINT, - 2292 => Doctrine_Core::ERR_CONSTRAINT, - 2449 => Doctrine_Core::ERR_CONSTRAINT, - ); + 1 => Doctrine_Core::ERR_CONSTRAINT, + 900 => Doctrine_Core::ERR_SYNTAX, + 904 => Doctrine_Core::ERR_NOSUCHFIELD, + 913 => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + 921 => Doctrine_Core::ERR_SYNTAX, + 923 => Doctrine_Core::ERR_SYNTAX, + 942 => Doctrine_Core::ERR_NOSUCHTABLE, + 955 => Doctrine_Core::ERR_ALREADY_EXISTS, + 1400 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + 1401 => Doctrine_Core::ERR_INVALID, + 1407 => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + 1418 => Doctrine_Core::ERR_NOT_FOUND, + 1476 => Doctrine_Core::ERR_DIVZERO, + 1722 => Doctrine_Core::ERR_INVALID_NUMBER, + 2289 => Doctrine_Core::ERR_NOSUCHTABLE, + 2291 => Doctrine_Core::ERR_CONSTRAINT, + 2292 => Doctrine_Core::ERR_CONSTRAINT, + 2449 => Doctrine_Core::ERR_CONSTRAINT, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { $code = $errorInfo[1]; if (isset(self::$errorCodeMap[$code])) { $this->portableCode = self::$errorCodeMap[$code]; + return true; } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Pgsql.php b/lib/Doctrine/Connection/Pgsql.php index 2fbc19d86..0fa53589c 100644 --- a/lib/Doctrine/Connection/Pgsql.php +++ b/lib/Doctrine/Connection/Pgsql.php @@ -20,71 +20,66 @@ */ /** - * Doctrine_Connection_Pgsql + * Doctrine_Connection_Pgsql. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Pgsql extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Pgsql'; /** - * the constructor - * - * @param Doctrine_Manager $manager - * @param PDO $pdo database handle + * the constructor. */ public function __construct(Doctrine_Manager $manager, $adapter) { // initialize all driver options $this->supported = array( - 'sequences' => true, - 'indexes' => true, - 'affected_rows' => true, - 'summary_functions' => true, - 'order_by_text' => true, - 'transactions' => true, - 'savepoints' => true, - 'current_id' => true, - 'limit_queries' => true, - 'LOBs' => true, - 'replace' => 'emulated', - 'sub_selects' => true, - 'auto_increment' => 'emulated', - 'primary_key' => true, - 'result_introspection' => true, - 'prepared_statements' => true, - 'identifier_quoting' => true, - 'pattern_escaping' => true, - ); + 'sequences' => true, + 'indexes' => true, + 'affected_rows' => true, + 'summary_functions' => true, + 'order_by_text' => true, + 'transactions' => true, + 'savepoints' => true, + 'current_id' => true, + 'limit_queries' => true, + 'LOBs' => true, + 'replace' => 'emulated', + 'sub_selects' => true, + 'auto_increment' => 'emulated', + 'primary_key' => true, + 'result_introspection' => true, + 'prepared_statements' => true, + 'identifier_quoting' => true, + 'pattern_escaping' => true, + ); $this->properties['string_quoting'] = array('start' => "'", - 'end' => "'", - 'escape' => "'", - 'escape_pattern' => '\\'); + 'end' => "'", + 'escape' => "'", + 'escape_pattern' => '\\'); $this->properties['identifier_quoting'] = array('start' => '"', - 'end' => '"', - 'escape' => '"'); + 'end' => '"', + 'escape' => '"'); parent::__construct($manager, $adapter); } /** - * Set the charset on the current connection + * Set the charset on the current connection. * * @param string charset - * - * @return void */ public function setCharset($charset) { @@ -96,12 +91,11 @@ public function setCharset($charset) /** * convertBoolean * some drivers need the boolean values to be converted into integers - * when using DQL API + * when using DQL API. * * This method takes care of that conversion * * @param array $item - * @return void */ public function convertBooleans($item) { @@ -112,55 +106,58 @@ public function convertBooleans($item) } } } else { - if (is_bool($item) || is_numeric($item)) { - $item = ($item) ? 'true' : 'false'; - } + if (is_bool($item) || is_numeric($item)) { + $item = ($item) ? 'true' : 'false'; + } } + return $item; } /** - * Changes a query string for various DBMS specific reasons + * Changes a query string for various DBMS specific reasons. + * + * @param string $query query to modify + * @param int $limit limit the number of rows + * @param int $offset start reading from given offset + * @param bool $isManip if the query is a DML query * - * @param string $query query to modify - * @param integer $limit limit the number of rows - * @param integer $offset start reading from given offset - * @param boolean $isManip if the query is a DML query - * @return string modified query + * @return string modified query */ public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { if ($limit > 0) { $query = rtrim($query); - if (substr($query, -1) == ';') { + if (';' == substr($query, -1)) { $query = substr($query, 0, -1); } if ($isManip) { $manip = preg_replace('/^(DELETE FROM|UPDATE).*$/', '\\1', $query); - $from = $match[2]; + $from = $match[2]; $where = $match[3]; - $query = $manip . ' ' . $from . ' WHERE ctid=(SELECT ctid FROM ' - . $from . ' ' . $where . ' LIMIT ' . (int)$limit . ')'; - + $query = $manip.' '.$from.' WHERE ctid=(SELECT ctid FROM ' + .$from.' '.$where.' LIMIT '.(int) $limit.')'; } else { - if ( ! empty($limit)) { - $query .= ' LIMIT ' . (int)$limit; + if (!empty($limit)) { + $query .= ' LIMIT '.(int) $limit; } - if ( ! empty($offset)) { - $query .= ' OFFSET ' . (int)$offset; + if (!empty($offset)) { + $query .= ' OFFSET '.(int) $offset; } } } + return $query; } /** - * return version information about the server + * return version information about the server. * - * @param string $native determines if the raw version string should be returned - * @return array|string an array or string with version information + * @param string $native determines if the raw version string should be returned + * + * @return array|string an array or string with version information */ public function getServerVersion($native = false) { @@ -168,7 +165,7 @@ public function getServerVersion($native = false) $serverInfo = $this->fetchOne($query); - if ( ! $native) { + if (!$native) { $tmp = explode('.', $serverInfo, 3); if (empty($tmp[2]) && isset($tmp[1]) @@ -191,16 +188,16 @@ public function getServerVersion($native = false) ); } } + return $serverInfo; } /** * Inserts a table row with specified data. * - * @param Doctrine_Table $table The table to insert data into. - * @param array $values An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param Doctrine_Table $table the table to insert data into + * + * @return int the number of affected rows. Boolean false if empty value array was given, */ public function insert(Doctrine_Table $table, array $fields) { @@ -210,16 +207,16 @@ public function insert(Doctrine_Table $table, array $fields) $cols = array(); // the query VALUES will contain either expresions (eg 'NOW()') or ? $a = array(); - + foreach ($fields as $fieldName => $value) { - if ($table->isIdentifier($fieldName) - && $table->isIdentifierAutoincrement() - && $value == null) { - // Autoincrement fields should not be added to the insert statement - // if their value is null - unset($fields[$fieldName]); - continue; - } + if ($table->isIdentifier($fieldName) + && $table->isIdentifierAutoincrement() + && null == $value) { + // Autoincrement fields should not be added to the insert statement + // if their value is null + unset($fields[$fieldName]); + continue; + } $cols[] = $this->quoteIdentifier($table->getColumnName($fieldName)); if ($value instanceof Doctrine_Expression) { $a[] = $value->getSql(); @@ -228,19 +225,19 @@ public function insert(Doctrine_Table $table, array $fields) $a[] = '?'; } } - - if (count($fields) == 0) { - // Real fix #1786 and #2327 (default values when table is just 'id' as PK) - return $this->exec('INSERT INTO ' . $this->quoteIdentifier($tableName) - . ' ' - . ' VALUES (DEFAULT)'); + + if (0 == count($fields)) { + // Real fix #1786 and #2327 (default values when table is just 'id' as PK) + return $this->exec('INSERT INTO '.$this->quoteIdentifier($tableName) + .' ' + .' VALUES (DEFAULT)'); } // build the statement - $query = 'INSERT INTO ' . $this->quoteIdentifier($tableName) - . ' (' . implode(', ', $cols) . ')' - . ' VALUES (' . implode(', ', $a) . ')'; + $query = 'INSERT INTO '.$this->quoteIdentifier($tableName) + .' ('.implode(', ', $cols).')' + .' VALUES ('.implode(', ', $a).')'; return $this->exec($query, array_values($fields)); - } + } } diff --git a/lib/Doctrine/Connection/Pgsql/Exception.php b/lib/Doctrine/Connection/Pgsql/Exception.php index 46e366b84..011c2804e 100644 --- a/lib/Doctrine/Connection/Pgsql/Exception.php +++ b/lib/Doctrine/Connection/Pgsql/Exception.php @@ -20,89 +20,75 @@ */ /** - * Doctrine_Connection_Pgsql_Exception + * Doctrine_Connection_Pgsql_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org + * * @author Konsta Vesterinen * @author Paul Cooper (PEAR MDB2 Pgsql driver) * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Connection_Pgsql_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorRegexps an array that is used for determining portable - * error code from a native database error message + * @var array an array that is used for determining portable + * error code from a native database error message */ protected static $errorRegexps = array( - '/parser: parse error at or near/i' - => Doctrine_Core::ERR_SYNTAX, - '/syntax error at/' - => Doctrine_Core::ERR_SYNTAX, - '/column reference .* is ambiguous/i' - => Doctrine_Core::ERR_SYNTAX, - '/column .* (of relation .*)?does not exist/i' - => Doctrine_Core::ERR_NOSUCHFIELD, - '/attribute .* not found|relation .* does not have attribute/i' - => Doctrine_Core::ERR_NOSUCHFIELD, - '/column .* specified in USING clause does not exist in (left|right) table/i' - => Doctrine_Core::ERR_NOSUCHFIELD, - '/(relation|sequence|table).*does not exist|class .* not found/i' - => Doctrine_Core::ERR_NOSUCHTABLE, - '/index .* does not exist/' - => Doctrine_Core::ERR_NOT_FOUND, - '/relation .* already exists/i' - => Doctrine_Core::ERR_ALREADY_EXISTS, - '/(divide|division) by zero$/i' - => Doctrine_Core::ERR_DIVZERO, - '/pg_atoi: error in .*: can\'t parse /i' - => Doctrine_Core::ERR_INVALID_NUMBER, - '/invalid input syntax for( type)? (integer|numeric)/i' - => Doctrine_Core::ERR_INVALID_NUMBER, - '/value .* is out of range for type \w*int/i' - => Doctrine_Core::ERR_INVALID_NUMBER, - '/integer out of range/i' - => Doctrine_Core::ERR_INVALID_NUMBER, - '/value too long for type character/i' - => Doctrine_Core::ERR_INVALID, - '/permission denied/' - => Doctrine_Core::ERR_ACCESS_VIOLATION, - '/violates [\w ]+ constraint/' - => Doctrine_Core::ERR_CONSTRAINT, - '/referential integrity violation/' - => Doctrine_Core::ERR_CONSTRAINT, - '/violates not-null constraint/' - => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - '/more expressions than target columns/i' - => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - ); + '/parser: parse error at or near/i' => Doctrine_Core::ERR_SYNTAX, + '/syntax error at/' => Doctrine_Core::ERR_SYNTAX, + '/column reference .* is ambiguous/i' => Doctrine_Core::ERR_SYNTAX, + '/column .* (of relation .*)?does not exist/i' => Doctrine_Core::ERR_NOSUCHFIELD, + '/attribute .* not found|relation .* does not have attribute/i' => Doctrine_Core::ERR_NOSUCHFIELD, + '/column .* specified in USING clause does not exist in (left|right) table/i' => Doctrine_Core::ERR_NOSUCHFIELD, + '/(relation|sequence|table).*does not exist|class .* not found/i' => Doctrine_Core::ERR_NOSUCHTABLE, + '/index .* does not exist/' => Doctrine_Core::ERR_NOT_FOUND, + '/relation .* already exists/i' => Doctrine_Core::ERR_ALREADY_EXISTS, + '/(divide|division) by zero$/i' => Doctrine_Core::ERR_DIVZERO, + '/pg_atoi: error in .*: can\'t parse /i' => Doctrine_Core::ERR_INVALID_NUMBER, + '/invalid input syntax for( type)? (integer|numeric)/i' => Doctrine_Core::ERR_INVALID_NUMBER, + '/value .* is out of range for type \w*int/i' => Doctrine_Core::ERR_INVALID_NUMBER, + '/integer out of range/i' => Doctrine_Core::ERR_INVALID_NUMBER, + '/value too long for type character/i' => Doctrine_Core::ERR_INVALID, + '/permission denied/' => Doctrine_Core::ERR_ACCESS_VIOLATION, + '/violates [\w ]+ constraint/' => Doctrine_Core::ERR_CONSTRAINT, + '/referential integrity violation/' => Doctrine_Core::ERR_CONSTRAINT, + '/violates not-null constraint/' => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + '/more expressions than target columns/i' => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. * * the portable error code is added at the end of array * - * @param array $errorInfo error info array + * @param array $errorInfo error info array + * * @since 1.0 * @see Doctrine_Core::ERR_* constants * @see Doctrine_Connection::$portableCode - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { foreach (self::$errorRegexps as $regexp => $code) { if (preg_match($regexp, $errorInfo[2])) { $this->portableCode = $code; + return true; } } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Profiler.php b/lib/Doctrine/Connection/Profiler.php index 4f1d7cd5c..db4aec2aa 100644 --- a/lib/Doctrine/Connection/Profiler.php +++ b/lib/Doctrine/Connection/Profiler.php @@ -20,80 +20,81 @@ */ /** - * Doctrine_Connection_Profiler + * Doctrine_Connection_Profiler. * - * @package Doctrine - * @subpackage Connection * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Connection_Profiler implements Doctrine_Overloadable, IteratorAggregate, Countable { /** - * @param array $listeners an array containing all availible listeners + * @param array $listeners an array containing all availible listeners */ - private $listeners = array('query', - 'prepare', - 'commit', - 'rollback', - 'connect', - 'begintransaction', - 'exec', - 'execute'); + private $listeners = array('query', + 'prepare', + 'commit', + 'rollback', + 'connect', + 'begintransaction', + 'exec', + 'execute'); /** - * @param array $events an array containing all listened events + * @param array $events an array containing all listened events */ - private $events = array(); + private $events = array(); /** - * @param array $eventSequences an array containing sequences of all listened events as keys + * @param array $eventSequences an array containing sequences of all listened events as keys */ private $eventSequences = array(); /** - * constructor + * constructor. */ - public function __construct() { - + public function __construct() + { } /** - * setFilterQueryType + * setFilterQueryType. * - * @param integer $filter - * @return boolean + * @return bool */ - public function setFilterQueryType() { - + public function setFilterQueryType() + { } + /** * method overloader * this method is used for invoking different listeners, for the full - * list of availible listeners, see Doctrine_EventListener + * list of availible listeners, see Doctrine_EventListener. + * + * @param string $m the name of the method + * @param array $a method arguments * - * @param string $m the name of the method - * @param array $a method arguments * @see Doctrine_EventListener - * @return boolean + * + * @return bool */ public function __call($m, $a) { // first argument should be an instance of Doctrine_Event - if ( ! ($a[0] instanceof Doctrine_Event)) { + if (!($a[0] instanceof Doctrine_Event)) { throw new Doctrine_Connection_Profiler_Exception("Couldn't listen event. Event should be an instance of Doctrine_Event."); } - - if (substr($m, 0, 3) === 'pre') { + if ('pre' === substr($m, 0, 3)) { // pre-event listener found $a[0]->start(); $eventSequence = $a[0]->getSequence(); - if ( ! isset($this->eventSequences[$eventSequence])) { + if (!isset($this->eventSequences[$eventSequence])) { $this->events[] = $a[0]; $this->eventSequences[$eventSequence] = true; } @@ -104,9 +105,8 @@ public function __call($m, $a) } /** - * get + * get. * - * @param mixed $key * @return Doctrine_Event|null */ public function get($key) @@ -114,12 +114,13 @@ public function get($key) if (isset($this->events[$key])) { return $this->events[$key]; } + return null; } /** * getAll - * returns all profiled events as an array + * returns all profiled events as an array. * * @return Doctrine_Event[] All events in an array */ @@ -130,39 +131,39 @@ public function getAll() /** * getIterator - * returns an iterator that iterates through the logged events + * returns an iterator that iterates through the logged events. * * @return ArrayIterator */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->events); } /** - * count + * count. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->events); } /** - * pop the last event from the event stack + * pop the last event from the event stack. * * @return Doctrine_Event|null */ public function pop() { $event = array_pop($this->events); - if ($event !== null) - { + if (null !== $event) { unset($this->eventSequences[$event->getSequence()]); } + return $event; } @@ -179,6 +180,7 @@ public function lastEvent() } end($this->events); + return current($this->events); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Profiler/Exception.php b/lib/Doctrine/Connection/Profiler/Exception.php index 75809c793..d446f08b1 100644 --- a/lib/Doctrine/Connection/Profiler/Exception.php +++ b/lib/Doctrine/Connection/Profiler/Exception.php @@ -20,16 +20,17 @@ */ /** - * Doctrine_Connection_Profiler_Exception + * Doctrine_Connection_Profiler_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1345 $ + * * @author Konsta Vesterinen */ class Doctrine_Connection_Profiler_Exception extends Doctrine_Exception { -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Sqlite.php b/lib/Doctrine/Connection/Sqlite.php index 6a29b654e..1eb38a57b 100644 --- a/lib/Doctrine/Connection/Sqlite.php +++ b/lib/Doctrine/Connection/Sqlite.php @@ -20,61 +20,57 @@ */ /** - * Doctrine_Connection_Sqlite + * Doctrine_Connection_Sqlite. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Connection_Sqlite extends Doctrine_Connection_Common { /** - * @var string $driverName the name of this connection driver + * @var string the name of this connection driver */ protected $driverName = 'Sqlite'; /** - * the constructor - * - * @param Doctrine_Manager $manager - * @param PDO $pdo database handle + * the constructor. */ public function __construct(Doctrine_Manager $manager, $adapter) { - $this->supported = array('sequences' => 'emulated', - 'indexes' => true, - 'affected_rows' => true, - 'summary_functions' => true, - 'order_by_text' => true, - 'current_id' => 'emulated', - 'limit_queries' => true, - 'LOBs' => true, - 'replace' => true, - 'transactions' => true, - 'savepoints' => false, - 'sub_selects' => true, - 'auto_increment' => true, - 'primary_key' => true, - 'result_introspection' => false, // not implemented - 'prepared_statements' => 'emulated', - 'identifier_quoting' => true, - 'pattern_escaping' => false, - ); + $this->supported = array('sequences' => 'emulated', + 'indexes' => true, + 'affected_rows' => true, + 'summary_functions' => true, + 'order_by_text' => true, + 'current_id' => 'emulated', + 'limit_queries' => true, + 'LOBs' => true, + 'replace' => true, + 'transactions' => true, + 'savepoints' => false, + 'sub_selects' => true, + 'auto_increment' => true, + 'primary_key' => true, + 'result_introspection' => false, // not implemented + 'prepared_statements' => 'emulated', + 'identifier_quoting' => true, + 'pattern_escaping' => false, + ); parent::__construct($manager, $adapter); if ($this->isConnected) { - // PHP8.1 require default to true to keep BC // https://www.php.net/manual/en/migration81.incompatible.php#migration81.incompatible.pdo.sqlite // Can be overwritten by user later $this->dbh->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true); - $this->dbh->sqliteCreateFunction('mod', array('Doctrine_Expression_Sqlite', 'modImpl'), 2); + $this->dbh->sqliteCreateFunction('mod', array('Doctrine_Expression_Sqlite', 'modImpl'), 2); $this->dbh->sqliteCreateFunction('concat', array('Doctrine_Expression_Sqlite', 'concatImpl')); $this->dbh->sqliteCreateFunction('md5', 'md5', 1); $this->dbh->sqliteCreateFunction('now', array('Doctrine_Expression_Sqlite', 'nowImpl'), 0); @@ -82,12 +78,13 @@ public function __construct(Doctrine_Manager $manager, $adapter) } /** - * initializes database functions missing in sqlite + * initializes database functions missing in sqlite. * * @see Doctrine_Expression - * @return boolean + * + * @return bool */ - public function connect() + public function connect() { if ($this->isConnected) { return; @@ -98,14 +95,14 @@ public function connect() $connected = parent::connect(); - if(!$hasConfigureStringify) { + if (!$hasConfigureStringify) { // PHP8.1 require default to true to keep BC // https://www.php.net/manual/en/migration81.incompatible.php#migration81.incompatible.pdo.sqlite // Can be overwritten by user later $this->dbh->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true); } - $this->dbh->sqliteCreateFunction('mod', array('Doctrine_Expression_Sqlite', 'modImpl'), 2); + $this->dbh->sqliteCreateFunction('mod', array('Doctrine_Expression_Sqlite', 'modImpl'), 2); $this->dbh->sqliteCreateFunction('concat', array('Doctrine_Expression_Sqlite', 'concatImpl')); $this->dbh->sqliteCreateFunction('md5', 'md5', 1); $this->dbh->sqliteCreateFunction('now', array('Doctrine_Expression_Sqlite', 'nowImpl'), 0); @@ -114,13 +111,11 @@ public function connect() } /** - * createDatabase - * - * @return void + * createDatabase. */ public function createDatabase() { - if ( ! $dsn = $this->getOption('dsn')) { + if (!$dsn = $this->getOption('dsn')) { throw new Doctrine_Connection_Exception('You must create your Doctrine_Connection by using a valid Doctrine style dsn in order to use the create/drop database functionality'); } @@ -130,18 +125,16 @@ public function createDatabase() } /** - * dropDatabase - * - * @return void + * dropDatabase. */ public function dropDatabase() { - if ( ! $dsn = $this->getOption('dsn')) { + if (!$dsn = $this->getOption('dsn')) { throw new Doctrine_Connection_Exception('You must create your Doctrine_Connection by using a valid Doctrine style dsn in order to use the create/drop database functionality'); } - + $info = $this->getManager()->parseDsn($dsn); $this->export->dropDatabase($info['database']); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Sqlite/Exception.php b/lib/Doctrine/Connection/Sqlite/Exception.php index cf4838e29..658c7c2ad 100644 --- a/lib/Doctrine/Connection/Sqlite/Exception.php +++ b/lib/Doctrine/Connection/Sqlite/Exception.php @@ -20,59 +20,63 @@ */ /** - * Doctrine_Connection_Sqlite_Exception + * Doctrine_Connection_Sqlite_Exception. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Connection_Sqlite_Exception extends Doctrine_Connection_Exception { /** - * @var array $errorRegexps an array that is used for determining portable - * error code from a native database error message + * @var array an array that is used for determining portable + * error code from a native database error message */ protected static $errorRegexps = array( - '/^no such table:/' => Doctrine_Core::ERR_NOSUCHTABLE, - '/^no such index:/' => Doctrine_Core::ERR_NOT_FOUND, - '/^(table|index) .* already exists$/' => Doctrine_Core::ERR_ALREADY_EXISTS, - '/PRIMARY KEY must be unique/i' => Doctrine_Core::ERR_CONSTRAINT, - '/is not unique/' => Doctrine_Core::ERR_CONSTRAINT, - '/columns .* are not unique/i' => Doctrine_Core::ERR_CONSTRAINT, - '/uniqueness constraint failed/' => Doctrine_Core::ERR_CONSTRAINT, - '/may not be NULL/' => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, - '/^no such column:/' => Doctrine_Core::ERR_NOSUCHFIELD, - '/column not present in both tables/i' => Doctrine_Core::ERR_NOSUCHFIELD, - '/^near ".*": syntax error$/' => Doctrine_Core::ERR_SYNTAX, - '/[0-9]+ values for [0-9]+ columns/i' => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, - ); + '/^no such table:/' => Doctrine_Core::ERR_NOSUCHTABLE, + '/^no such index:/' => Doctrine_Core::ERR_NOT_FOUND, + '/^(table|index) .* already exists$/' => Doctrine_Core::ERR_ALREADY_EXISTS, + '/PRIMARY KEY must be unique/i' => Doctrine_Core::ERR_CONSTRAINT, + '/is not unique/' => Doctrine_Core::ERR_CONSTRAINT, + '/columns .* are not unique/i' => Doctrine_Core::ERR_CONSTRAINT, + '/uniqueness constraint failed/' => Doctrine_Core::ERR_CONSTRAINT, + '/may not be NULL/' => Doctrine_Core::ERR_CONSTRAINT_NOT_NULL, + '/^no such column:/' => Doctrine_Core::ERR_NOSUCHFIELD, + '/column not present in both tables/i' => Doctrine_Core::ERR_NOSUCHFIELD, + '/^near ".*": syntax error$/' => Doctrine_Core::ERR_SYNTAX, + '/[0-9]+ values for [0-9]+ columns/i' => Doctrine_Core::ERR_VALUE_COUNT_ON_ROW, + ); /** * This method checks if native error code/message can be * converted into a portable code and then adds this - * portable error code to $portableCode field + * portable error code to $portableCode field. + * + * @param array $errorInfo error info array * - * @param array $errorInfo error info array * @since 1.0 * @see Doctrine_Core::ERR_* constants * @see Doctrine_Connection::$portableCode - * @return boolean whether or not the error info processing was successfull - * (the process is successfull if portable error code was found) + * + * @return bool whether or not the error info processing was successfull + * (the process is successfull if portable error code was found) */ public function processErrorInfo(array $errorInfo) { foreach (self::$errorRegexps as $regexp => $code) { if (preg_match($regexp, $errorInfo[2])) { - $this->portableCode = $code; + return true; } } + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Connection/Statement.php b/lib/Doctrine/Connection/Statement.php index 4c0e86fac..9f3d75dfd 100644 --- a/lib/Doctrine/Connection/Statement.php +++ b/lib/Doctrine/Connection/Statement.php @@ -20,58 +20,58 @@ */ /** - * Doctrine_Connection_Statement + * Doctrine_Connection_Statement. * - * @package Doctrine - * @subpackage Connection * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1532 $ */ class Doctrine_Connection_Statement implements Doctrine_Adapter_Statement_Interface { /** - * @var Doctrine_Connection $conn Doctrine_Connection object, every connection - * statement holds an instance of Doctrine_Connection + * @var Doctrine_Connection Doctrine_Connection object, every connection + * statement holds an instance of Doctrine_Connection */ protected $_conn; /** - * @var mixed $_stmt PDOStatement object, boolean false or Doctrine_Adapter_Statement object + * @var mixed PDOStatement object, boolean false or Doctrine_Adapter_Statement object */ protected $_stmt; /** - * constructor + * constructor. * - * @param Doctrine_Connection $conn Doctrine_Connection object, every connection - * statement holds an instance of Doctrine_Connection - * @param mixed $stmt + * @param Doctrine_Connection $conn Doctrine_Connection object, every connection + * statement holds an instance of Doctrine_Connection */ public function __construct(Doctrine_Connection $conn, $stmt) { $this->_conn = $conn; $this->_stmt = $stmt; - if ($stmt === false) { + if (false === $stmt) { throw new Doctrine_Exception('Unknown statement object given.'); } } + /** - * destructor + * destructor. * * make sure that the cursor is closed - * */ public function __destruct() { $this->closeCursor(); } + /** * getConnection - * returns the connection object this statement uses + * returns the connection object this statement uses. * * @return Doctrine_Connection */ @@ -92,23 +92,23 @@ public function getQuery() /** * bindColumn - * Bind a column to a PHP variable + * Bind a column to a PHP variable. * - * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. - * If using the column name, be aware that the name should match - * the case of the column, as returned by the driver. + * @param mixed $column Number of the column (1-indexed) or name of the column in the result set. + * If using the column name, be aware that the name should match + * the case of the column, as returned by the driver. + * @param string $param name of the PHP variable to which the column will be bound + * @param int $type data type of the parameter, specified by the Doctrine_Core::PARAM_* constants * - * @param string $param Name of the PHP variable to which the column will be bound. - * @param integer $type Data type of the parameter, specified by the Doctrine_Core::PARAM_* constants. - * @return boolean Returns TRUE on success or FALSE on failure + * @return bool Returns TRUE on success or FALSE on failure */ public function bindColumn($column, $param, $type = null) { - if ($type === null) { + if (null === $type) { return $this->_stmt->bindColumn($column, $param); - } else { - return $this->_stmt->bindColumn($column, $param, $type); } + + return $this->_stmt->bindColumn($column, $param, $type); } /** @@ -116,22 +116,21 @@ public function bindColumn($column, $param, $type = null) * Binds a value to a corresponding named or question mark * placeholder in the SQL statement that was use to prepare the statement. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, + * this will be a parameter name of the form :name. For a prepared statement + * using question mark placeholders, this will be the 1-indexed position of the parameter + * @param mixed $value the value to bind to the parameter + * @param int $type explicit data type for the parameter using the Doctrine_Core::PARAM_* constants * - * @param mixed $value The value to bind to the parameter. - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. - * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindValue($param, $value, $type = null) { - if ($type === null) { + if (null === $type) { return $this->_stmt->bindValue($param, $value); - } else { - return $this->_stmt->bindValue($param, $value, $type); } + + return $this->_stmt->bindValue($param, $value, $type); } /** @@ -146,35 +145,29 @@ public function bindValue($param, $value, $type = null) * of stored procedures that return data as output parameters, and some also as input/output * parameters that both send in data and are updated to receive it. * - * @param mixed $param Parameter identifier. For a prepared statement using named placeholders, - * this will be a parameter name of the form :name. For a prepared statement - * using question mark placeholders, this will be the 1-indexed position of the parameter - * - * @param mixed $variable Name of the PHP variable to bind to the SQL statement parameter. + * @param mixed $variable name of the PHP variable to bind to the SQL statement parameter + * @param int $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return + * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the + * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. + * @param int $length Length of the data type. To indicate that a parameter is an OUT parameter + * from a stored procedure, you must explicitly set the length. * - * @param integer $type Explicit data type for the parameter using the Doctrine_Core::PARAM_* constants. To return - * an INOUT parameter from a stored procedure, use the bitwise OR operator to set the - * Doctrine_Core::PARAM_INPUT_OUTPUT bits for the data_type parameter. - * - * @param integer $length Length of the data type. To indicate that a parameter is an OUT parameter - * from a stored procedure, you must explicitly set the length. - * @param mixed $driverOptions - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function bindParam($column, &$variable, $type = null, $length = null, $driverOptions = array()) { - if ($type === null) { + if (null === $type) { return $this->_stmt->bindParam($column, $variable); - } else { - return $this->_stmt->bindParam($column, $variable, $type, $length, $driverOptions); } + + return $this->_stmt->bindParam($column, $variable, $type, $length, $driverOptions); } /** * closeCursor * Closes the cursor, enabling the statement to be executed again. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function closeCursor() { @@ -183,11 +176,11 @@ public function closeCursor() /** * columnCount - * Returns the number of columns in the result set + * Returns the number of columns in the result set. * - * @return integer Returns the number of columns in the result set represented - * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, - * this method should return 0. + * @return int Returns the number of columns in the result set represented + * by the Doctrine_Adapter_Statement_Interface object. If there is no result set, + * this method should return 0. */ public function columnCount() { @@ -196,10 +189,11 @@ public function columnCount() /** * errorCode - * Fetch the SQLSTATE associated with the last operation on the statement handle + * Fetch the SQLSTATE associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorCode() - * @return string error code string + * + * @return string error code string */ public function errorCode() { @@ -208,10 +202,11 @@ public function errorCode() /** * errorInfo - * Fetch extended error information associated with the last operation on the statement handle + * Fetch extended error information associated with the last operation on the statement handle. * * @see Doctrine_Adapter_Interface::errorInfo() - * @return array error info array + * + * @return array error info array */ public function errorInfo() { @@ -220,7 +215,7 @@ public function errorInfo() /** * execute - * Executes a prepared statement + * Executes a prepared statement. * * If the prepared statement included parameter markers, you must either: * call PDOStatement->bindParam() to bind PHP variables to the parameter markers: @@ -228,10 +223,10 @@ public function errorInfo() * if any, of their associated parameter markers or pass an array of input-only * parameter values * + * @param array $params an array of values with as many elements as there are + * bound parameters in the SQL statement being executed * - * @param array $params An array of values with as many elements as there are - * bound parameters in the SQL statement being executed. - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function execute($params = array()) { @@ -240,11 +235,10 @@ public function execute($params = array()) $this->_conn->getListener()->preStmtExecute($event); $result = true; - if ( ! $event->skipOperation) { - + if (!$event->skipOperation) { if ($this->_conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL) { foreach ($params as $key => $value) { - if ($value === '') { + if ('' === $value) { $params[$key] = null; } } @@ -253,8 +247,8 @@ public function execute($params = array()) if ($params) { $pos = 0; foreach ($params as $key => $value) { - $pos++; - $param = is_numeric($key) ? $pos : $key; + ++$pos; + $param = is_numeric($key) ? $pos : $key; if (is_resource($value)) { $this->_stmt->bindParam($param, $params[$key], Doctrine_Core::PARAM_LOB); } else { @@ -270,10 +264,10 @@ public function execute($params = array()) $this->_conn->getListener()->postStmtExecute($event); - //fix a possible "ORA-01000: maximum open cursors exceeded" when many non-SELECTs are executed and the profiling is enabled + // fix a possible "ORA-01000: maximum open cursors exceeded" when many non-SELECTs are executed and the profiling is enabled if ('Oracle' == $this->getConnection()->getDriverName()) { $queryBeginningSubstring = strtoupper(substr(ltrim($this->_stmt->queryString), 0, 6)); - if ($queryBeginningSubstring != 'SELECT' && substr($queryBeginningSubstring, 0, 4) != 'WITH' ){ + if ('SELECT' != $queryBeginningSubstring && 'WITH' != substr($queryBeginningSubstring, 0, 4)) { $this->closeCursor(); } } @@ -289,40 +283,34 @@ public function execute($params = array()) } /** - * fetch + * fetch. * * @see Doctrine_Core::FETCH_* constants - * @param integer $fetchStyle Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $cursorOrientation For a PDOStatement object representing a scrollable cursor, - * this value determines which row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to - * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your - * Doctrine_Adapter_Statement_Interface object, - * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you - * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). - * - * @param integer $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the - * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies - * the absolute number of the row in the result set that shall be fetched. + * + * @param int $cursorOrientation For a PDOStatement object representing a scrollable cursor, + * this value determines which row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to + * Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your + * Doctrine_Adapter_Statement_Interface object, + * you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you + * prepare the SQL statement with Doctrine_Adapter_Interface->prepare(). + * @param int $cursorOffset For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the + * $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies + * the absolute number of the row in the result set that shall be fetched. * * For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for * which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value * specifies the row to fetch relative to the cursor position before * Doctrine_Adapter_Statement_Interface->fetch() was called. - * - * @return mixed */ public function fetch($fetchMode = Doctrine_Core::FETCH_BOTH, - $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, - $cursorOffset = null) + $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, + $cursorOffset = null) { $event = new Doctrine_Event($this, Doctrine_Event::STMT_FETCH, $this->getQuery()); // null value is not an integer - if(null === $cursorOffset) { + if (null === $cursorOffset) { $cursorOffset = 0; } @@ -332,7 +320,7 @@ public function fetch($fetchMode = Doctrine_Core::FETCH_BOTH, $data = $this->_conn->getListener()->preFetch($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $data = $this->_stmt->fetch($fetchMode, $cursorOrientation, $cursorOffset); } @@ -343,19 +331,18 @@ public function fetch($fetchMode = Doctrine_Core::FETCH_BOTH, /** * fetchAll - * Returns an array containing all of the result set rows + * Returns an array containing all of the result set rows. * - * @param integer $fetchMode Controls how the next row will be returned to the caller. - * This value must be one of the Doctrine_Core::FETCH_* constants, - * defaulting to Doctrine_Core::FETCH_BOTH - * - * @param integer $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is - * Doctrine_Core::FETCH_COLUMN. Defaults to 0. + * @param int $fetchMode Controls how the next row will be returned to the caller. + * This value must be one of the Doctrine_Core::FETCH_* constants, + * defaulting to Doctrine_Core::FETCH_BOTH + * @param int $columnIndex Returns the indicated 0-indexed column when the value of $fetchStyle is + * Doctrine_Core::FETCH_COLUMN. Defaults to 0. * * @return array */ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH, - $columnIndex = null) + $columnIndex = null) { $event = new Doctrine_Event($this, Doctrine_Event::STMT_FETCHALL, $this->getQuery()); $event->fetchMode = $fetchMode; @@ -363,8 +350,8 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH, $this->_conn->getListener()->preFetchAll($event); - if ( ! $event->skipOperation) { - if ($columnIndex !== null) { + if (!$event->skipOperation) { + if (null !== $columnIndex) { $data = $this->_stmt->fetchAll($fetchMode, $columnIndex); } else { $data = $this->_stmt->fetchAll($fetchMode); @@ -383,11 +370,11 @@ public function fetchAll($fetchMode = Doctrine_Core::FETCH_BOTH, * Returns a single column from the next row of a * result set or FALSE if there are no more rows. * - * @param integer $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no - * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() - * fetches the first column. + * @param int $columnIndex 0-indexed number of the column you wish to retrieve from the row. If no + * value is supplied, Doctrine_Adapter_Statement_Interface->fetchColumn() + * fetches the first column. * - * @return string returns a single column in the next row of a result set. + * @return string returns a single column in the next row of a result set */ public function fetchColumn($columnIndex = 0) { @@ -401,11 +388,11 @@ public function fetchColumn($columnIndex = 0) * Fetches the next row and returns it as an object. This function is an alternative to * Doctrine_Adapter_Statement_Interface->fetch() with Doctrine_Core::FETCH_CLASS or Doctrine_Core::FETCH_OBJ style. * - * @param string $className Name of the created class, defaults to stdClass. - * @param array $args Elements of this array are passed to the constructor. + * @param string $className name of the created class, defaults to stdClass + * @param array $args elements of this array are passed to the constructor * - * @return mixed an instance of the required class with property names that correspond - * to the column names or FALSE in case of an error. + * @return mixed an instance of the required class with property names that correspond + * to the column names or FALSE in case of an error */ public function fetchObject($className = 'stdClass', $args = array()) { @@ -414,11 +401,13 @@ public function fetchObject($className = 'stdClass', $args = array()) /** * getAttribute - * Retrieve a statement attribute + * Retrieve a statement attribute. + * + * @param int $attribute * - * @param integer $attribute * @see Doctrine_Core::ATTR_* constants - * @return mixed the attribute value + * + * @return mixed the attribute value */ public function getAttribute($attribute) { @@ -427,11 +416,11 @@ public function getAttribute($attribute) /** * getColumnMeta - * Returns metadata for a column in a result set + * Returns metadata for a column in a result set. * - * @param integer $column The 0-indexed column in the result set. + * @param int $column the 0-indexed column in the result set * - * @return array Associative meta data array with the following structure: + * @return array Associative meta data array with the following structure: * * native_type The PHP native type used to represent the column value. * driver:decl_ type The SQL type used to represent the column value in the database. If the column in the result set is the result of a function, this value is not returned by PDOStatement->getColumnMeta(). @@ -448,14 +437,14 @@ public function getColumnMeta($column) /** * nextRowset - * Advances to the next rowset in a multi-rowset statement handle + * Advances to the next rowset in a multi-rowset statement handle. * * Some database servers support stored procedures that return more than one rowset * (also known as a result set). The nextRowset() method enables you to access the second * and subsequent rowsets associated with a PDOStatement object. Each rowset can have a * different set of columns from the preceding rowset. * - * @return boolean Returns TRUE on success or FALSE on failure. + * @return bool returns TRUE on success or FALSE on failure */ public function nextRowset() { @@ -472,7 +461,7 @@ public function nextRowset() * this behaviour is not guaranteed for all databases and should not be * relied on for portable applications. * - * @return integer Returns the number of rows. + * @return int returns the number of rows */ public function rowCount() { @@ -481,11 +470,12 @@ public function rowCount() /** * setAttribute - * Set a statement attribute + * Set a statement attribute. * - * @param integer $attribute - * @param mixed $value the value of given attribute - * @return boolean Returns TRUE on success or FALSE on failure. + * @param int $attribute + * @param mixed $value the value of given attribute + * + * @return bool returns TRUE on success or FALSE on failure */ public function setAttribute($attribute, $value) { @@ -494,10 +484,13 @@ public function setAttribute($attribute, $value) /** * setFetchMode - * Set the default fetch mode for this statement + * Set the default fetch mode for this statement. + * + * @param int $mode the fetch mode must be one of the Doctrine_Core::FETCH_* constants + * @param mixed|null $arg1 + * @param mixed|null $arg2 * - * @param integer $mode The fetch mode must be one of the Doctrine_Core::FETCH_* constants. - * @return boolean Returns 1 on success or FALSE on failure. + * @return bool returns 1 on success or FALSE on failure */ public function setFetchMode($mode, $arg1 = null, $arg2 = null) { diff --git a/lib/Doctrine/Connection/UnitOfWork.php b/lib/Doctrine/Connection/UnitOfWork.php index 9627d6d19..bdda47b5e 100644 --- a/lib/Doctrine/Connection/UnitOfWork.php +++ b/lib/Doctrine/Connection/UnitOfWork.php @@ -20,7 +20,7 @@ */ /** - * Doctrine_Connection_UnitOfWork + * Doctrine_Connection_UnitOfWork. * * Note: This class does not have the semantics of a real "Unit of Work" in 0.10/1.0. * Database operations are not queued. All changes to objects are immediately written @@ -28,12 +28,13 @@ * * Referential integrity is currently not always ensured. * - * @package Doctrine - * @subpackage Connection * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7684 $ + * * @author Konsta Vesterinen * @author Roman Borschel */ @@ -42,9 +43,6 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module /** * Saves the given record and all associated records. * (The save() operation is always cascaded in 0.10/1.0). - * - * @param Doctrine_Record $record - * @return void */ public function saveGraph(Doctrine_Record $record, $replace = false) { @@ -54,7 +52,7 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $conn->connect(); $state = $record->state(); - if ($state === Doctrine_Record::STATE_LOCKED || $state === Doctrine_Record::STATE_TLOCKED) { + if (Doctrine_Record::STATE_LOCKED === $state || Doctrine_Record::STATE_TLOCKED === $state) { return false; } @@ -69,7 +67,7 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $isValid = true; - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->saveRelatedLocalKeys($record); switch ($state) { @@ -101,12 +99,12 @@ public function saveGraph(Doctrine_Record $record, $replace = false) foreach ($record->getPendingDeletes() as $pendingDelete) { $pendingDelete->delete(); } - + foreach ($record->getPendingUnlinks() as $alias => $ids) { - if ($ids === false) { + if (false === $ids) { $record->unlinkInDb($alias, array()); $aliasesUnlinkInDb[] = $alias; - } else if ($ids) { + } elseif ($ids) { $record->unlinkInDb($alias, array_keys($ids)); $aliasesUnlinkInDb[] = $alias; } @@ -128,10 +126,10 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $alias = $fk->getAlias(); if ($record->hasReference($alias)) { - $obj = $record->$alias; + $obj = $record->{$alias}; // check that the related object is not an instance of Doctrine_Null - if ($obj && ! ($obj instanceof Doctrine_Null)) { + if ($obj && !($obj instanceof Doctrine_Null)) { $processDiff = !in_array($alias, $aliasesUnlinkInDb); $obj->save($conn, $processDiff); } @@ -148,7 +146,7 @@ public function saveGraph(Doctrine_Record $record, $replace = false) $conn->commit(); } catch (Exception $e) { // Make sure we roll back our internal transaction - //$record->state($state); + // $record->state($state); $conn->rollback(); throw $e; } @@ -164,12 +162,13 @@ public function saveGraph(Doctrine_Record $record, $replace = false) * * this event can be listened by the onPreDelete and onDelete listeners * - * @return boolean true on success, false on failure + * @return bool true on success, false on failure */ public function delete(Doctrine_Record $record) { $deletions = array(); $this->_collectDeletions($record, $deletions); + return $this->_executeDeletions($deletions); } @@ -177,11 +176,11 @@ public function delete(Doctrine_Record $record) * Collects all records that need to be deleted by applying defined * application-level delete cascades. * - * @param array $deletions Map of the records to delete. Keys=Oids Values=Records. + * @param array $deletions Map of the records to delete. Keys=Oids Values=Records. */ private function _collectDeletions(Doctrine_Record $record, array &$deletions) { - if ( ! $record->exists()) { + if (!$record->exists()) { return; } @@ -193,7 +192,7 @@ private function _collectDeletions(Doctrine_Record $record, array &$deletions) * Executes the deletions for all collected records during a delete operation * (usually triggered through $record->delete()). * - * @param array $deletions Map of the records to delete. Keys=Oids Values=Records. + * @param array $deletions Map of the records to delete. Keys=Oids Values=Records. */ private function _executeDeletions(array $deletions) { @@ -211,7 +210,7 @@ private function _executeDeletions(array $deletions) try { $this->conn->beginInternalTransaction(); - for ($i = count($executionOrder) - 1; $i >= 0; $i--) { + for ($i = count($executionOrder) - 1; $i >= 0; --$i) { $className = $executionOrder[$i]; $table = $this->conn->getTable($className); @@ -221,7 +220,7 @@ private function _executeDeletions(array $deletions) foreach ($deletions as $oid => $record) { if ($record->getTable()->getComponentName() == $className) { $veto = $this->_preDelete($record); - if ( ! $veto) { + if (!$veto) { $identifierMaps[] = $record->identifier(); $deletedRecords[] = $record; unset($deletions[$oid]); @@ -237,7 +236,7 @@ private function _executeDeletions(array $deletions) $params = array(); $columnNames = array(); foreach ($identifierMaps as $idMap) { - foreach($idMap as $fieldName => $value) { + foreach ($idMap as $fieldName => $value) { $params[] = $value; $columnNames[] = $table->getColumnName($fieldName); } @@ -246,7 +245,7 @@ private function _executeDeletions(array $deletions) // delete $tableName = $table->getTableName(); - $sql = "DELETE FROM " . $this->conn->quoteIdentifier($tableName) . " WHERE "; + $sql = 'DELETE FROM '.$this->conn->quoteIdentifier($tableName).' WHERE '; if ($table->isIdentifierComposite()) { $sql .= $this->_buildSqlCompositeKeyCondition($columnNames, count($identifierMaps)); @@ -260,7 +259,7 @@ private function _executeDeletions(array $deletions) foreach ($deletedRecords as $record) { // currently just for bc! $this->_deleteCTIParents($table, $record); - //-- + // -- $record->state(Doctrine_Record::STATE_TCLEAN); $record->getTable()->removeRecord($record); $this->_postDelete($record); @@ -285,38 +284,38 @@ private function _executeDeletions(array $deletions) * Builds the SQL condition to target multiple records who have a single-column * primary key. * - * @param Doctrine_Table $table The table from which the records are going to be deleted. - * @param integer $numRecords The number of records that are going to be deleted. - * @return string The SQL condition "pk = ? OR pk = ? OR pk = ? ..." + * @param int $numRecords the number of records that are going to be deleted + * + * @return string The SQL condition "pk = ? OR pk = ? OR pk = ? ..." */ private function _buildSqlSingleKeyCondition($columnNames, $numRecords) { $idColumn = $this->conn->quoteIdentifier($columnNames[0]); - return implode(' OR ', array_fill(0, $numRecords, "$idColumn = ?")); + + return implode(' OR ', array_fill(0, $numRecords, "{$idColumn} = ?")); } /** * Builds the SQL condition to target multiple records who have a composite primary key. * - * @param Doctrine_Table $table The table from which the records are going to be deleted. - * @param integer $numRecords The number of records that are going to be deleted. - * @return string The SQL condition "(pk1 = ? AND pk2 = ?) OR (pk1 = ? AND pk2 = ?) ..." + * @param int $numRecords the number of records that are going to be deleted + * + * @return string The SQL condition "(pk1 = ? AND pk2 = ?) OR (pk1 = ? AND pk2 = ?) ..." */ private function _buildSqlCompositeKeyCondition($columnNames, $numRecords) { - $singleCondition = ""; + $singleCondition = ''; foreach ($columnNames as $columnName) { $columnName = $this->conn->quoteIdentifier($columnName); - if ($singleCondition === "") { - $singleCondition .= "($columnName = ?"; + if ('' === $singleCondition) { + $singleCondition .= "({$columnName} = ?"; } else { - $singleCondition .= " AND $columnName = ?"; + $singleCondition .= " AND {$columnName} = ?"; } } - $singleCondition .= ")"; - $fullCondition = implode(' OR ', array_fill(0, $numRecords, $singleCondition)); + $singleCondition .= ')'; - return $fullCondition; + return implode(' OR ', array_fill(0, $numRecords, $singleCondition)); } /** @@ -327,42 +326,41 @@ private function _buildSqlCompositeKeyCondition($columnNames, $numRecords) * Exception: many-valued relations are always (re-)fetched from the database to * make sure we have all of them. * - * @param Doctrine_Record The record for which the delete operation will be cascaded. - * @throws PDOException If something went wrong at database level - * @return void + * @param Doctrine_Record the record for which the delete operation will be cascaded + * + * @throws PDOException If something went wrong at database level */ - protected function _cascadeDelete(Doctrine_Record $record, array &$deletions) - { - foreach ($record->getTable()->getRelations() as $relation) { - if ($relation->isCascadeDelete()) { - $fieldName = $relation->getAlias(); - // if it's a xToOne relation and the related object is already loaded - // we don't need to refresh. - if ( ! ($relation->getType() == Doctrine_Relation::ONE && isset($record->$fieldName))) { - $record->refreshRelated($relation->getAlias()); - } - $relatedObjects = $record->get($relation->getAlias()); - if ($relatedObjects instanceof Doctrine_Record && $relatedObjects->exists() - && ! isset($deletions[$relatedObjects->getOid()])) { - $this->_collectDeletions($relatedObjects, $deletions); - } else if ($relatedObjects instanceof Doctrine_Collection && count($relatedObjects) > 0) { - // cascade the delete to the other objects - foreach ($relatedObjects as $object) { - if ( ! isset($deletions[$object->getOid()])) { - $this->_collectDeletions($object, $deletions); - } - } - } - } - } - } + protected function _cascadeDelete(Doctrine_Record $record, array &$deletions) + { + foreach ($record->getTable()->getRelations() as $relation) { + if ($relation->isCascadeDelete()) { + $fieldName = $relation->getAlias(); + // if it's a xToOne relation and the related object is already loaded + // we don't need to refresh. + if (!(Doctrine_Relation::ONE == $relation->getType() && isset($record->{$fieldName}))) { + $record->refreshRelated($relation->getAlias()); + } + $relatedObjects = $record->get($relation->getAlias()); + if ($relatedObjects instanceof Doctrine_Record && $relatedObjects->exists() + && !isset($deletions[$relatedObjects->getOid()])) { + $this->_collectDeletions($relatedObjects, $deletions); + } elseif ($relatedObjects instanceof Doctrine_Collection && count($relatedObjects) > 0) { + // cascade the delete to the other objects + foreach ($relatedObjects as $object) { + if (!isset($deletions[$object->getOid()])) { + $this->_collectDeletions($object, $deletions); + } + } + } + } + } + } /** * saveRelatedForeignKeys - * saves all related (through ForeignKey) records to $record + * saves all related (through ForeignKey) records to $record. * - * @throws PDOException if something went wrong at database level - * @param Doctrine_Record $record + * @throws PDOException if something went wrong at database level */ public function saveRelatedForeignKeys(Doctrine_Record $record) { @@ -376,13 +374,12 @@ public function saveRelatedForeignKeys(Doctrine_Record $record) return $saveLater; } - + /** * saveRelatedLocalKeys - * saves all related (through LocalKey) records to $record + * saves all related (through LocalKey) records to $record. * - * @throws PDOException if something went wrong at database level - * @param Doctrine_Record $record + * @throws PDOException if something went wrong at database level */ public function saveRelatedLocalKeys(Doctrine_Record $record) { @@ -391,7 +388,7 @@ public function saveRelatedLocalKeys(Doctrine_Record $record) foreach ($record->getReferences() as $k => $v) { $rel = $record->getTable()->getRelation($k); - + $local = $rel->getLocal(); $foreign = $rel->getForeign(); @@ -405,10 +402,10 @@ public function saveRelatedLocalKeys(Doctrine_Record $record) $id = array_values($obj->identifier()); - if ( ! empty($id)) { + if (!empty($id)) { foreach ((array) $rel->getLocal() as $k => $columnName) { $field = $record->getTable()->getFieldName($columnName); - + if (isset($id[$k]) && $id[$k] && $record->getTable()->hasField($field)) { $record->set($field, $id[$k]); } @@ -421,7 +418,7 @@ public function saveRelatedLocalKeys(Doctrine_Record $record) } /** - * saveAssociations + * saveAssociations. * * this method takes a diff of one-to-many / many-to-many original and * current collections and applies the changes @@ -431,9 +428,7 @@ public function saveRelatedLocalKeys(Doctrine_Record $record) * 3, 4 and 5, this method would first destroy the associations to 1 and 2 and then * save new associations to 4 and 5 * - * @throws Doctrine_Connection_Exception if something went wrong at database level - * @param Doctrine_Record $record - * @return void + * @throws Doctrine_Connection_Exception if something went wrong at database level */ public function saveAssociations(Doctrine_Record $record) { @@ -447,9 +442,9 @@ public function saveAssociations(Doctrine_Record $record) $assocTable = $rel->getAssociationTable(); foreach ($v->getDeleteDiff() as $r) { - $query = 'DELETE FROM ' . $assocTable->getTableName() - . ' WHERE ' . $rel->getForeignRefColumnName() . ' = ?' - . ' AND ' . $rel->getLocalRefColumnName() . ' = ?'; + $query = 'DELETE FROM '.$assocTable->getTableName() + .' WHERE '.$rel->getForeignRefColumnName().' = ?' + .' AND '.$rel->getLocalRefColumnName().' = ?'; $this->conn->execute($query, array($r->getIncremented(), $record->getIncremented())); } @@ -469,7 +464,7 @@ public function saveAssociations(Doctrine_Record $record) /** * Invokes preDelete event listeners. * - * @return boolean Whether a listener has used it's veto (don't delete!). + * @return bool whether a listener has used it's veto (don't delete!) */ private function _preDelete(Doctrine_Record $record) { @@ -492,10 +487,9 @@ private function _postDelete(Doctrine_Record $record) /** * saveAll - * persists all the pending records from all tables + * persists all the pending records from all tables. * - * @throws PDOException if something went wrong at database level - * @return void + * @throws PDOException if something went wrong at database level */ public function saveAll() { @@ -512,10 +506,11 @@ public function saveAll() } /** - * updates given record + * updates given record. * - * @param Doctrine_Record $record record to be updated - * @return boolean whether or not the update was successful + * @param Doctrine_Record $record record to be updated + * + * @return bool whether or not the update was successful */ public function update(Doctrine_Record $record) { @@ -523,12 +518,12 @@ public function update(Doctrine_Record $record) if ($record->isValid(false, false)) { $table = $record->getTable(); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $identifier = $record->identifier(); if ($table->getOption('joinedParents')) { // currrently just for bc! $this->_updateCTIRecord($table, $record); - //-- + // -- } else { $array = $record->getPrepared(); $this->conn->update($table, $array, $identifier); @@ -548,12 +543,11 @@ public function update(Doctrine_Record $record) * Inserts a record into database. * * This method inserts a transient record in the database, and adds it - * to the identity map of its correspondent table. It proxies to @see + * to the identity map of its correspondent table. It proxies to @see * processSingleInsert(), trigger insert hooks and validation of data * if required. * - * @param Doctrine_Record $record - * @return boolean false if record is not valid + * @return bool false if record is not valid */ public function insert(Doctrine_Record $record) { @@ -562,11 +556,11 @@ public function insert(Doctrine_Record $record) if ($record->isValid(false, false)) { $table = $record->getTable(); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { if ($table->getOption('joinedParents')) { // just for bc! $this->_insertCTIRecord($table, $record); - //-- + // -- } else { $this->processSingleInsert($record); } @@ -584,52 +578,47 @@ public function insert(Doctrine_Record $record) /** * Replaces a record into database. * - * @param Doctrine_Record $record - * @return boolean false if record is not valid + * @return bool false if record is not valid */ public function replace(Doctrine_Record $record) { if ($record->exists()) { return $this->update($record); - } else { - if ($record->isValid()) { - $this->_assignSequence($record); + } + if ($record->isValid()) { + $this->_assignSequence($record); - $saveEvent = $record->invokeSaveHooks('pre', 'save'); - $insertEvent = $record->invokeSaveHooks('pre', 'insert'); + $saveEvent = $record->invokeSaveHooks('pre', 'save'); + $insertEvent = $record->invokeSaveHooks('pre', 'insert'); - $table = $record->getTable(); - $identifier = (array) $table->getIdentifier(); - $data = $record->getPrepared(); + $table = $record->getTable(); + $identifier = (array) $table->getIdentifier(); + $data = $record->getPrepared(); - foreach ($data as $key => $value) { - if ($value instanceof Doctrine_Expression) { - $data[$key] = $value->getSql(); - } + foreach ($data as $key => $value) { + if ($value instanceof Doctrine_Expression) { + $data[$key] = $value->getSql(); } + } - $result = $this->conn->replace($table, $data, $identifier); + $result = $this->conn->replace($table, $data, $identifier); - $record->invokeSaveHooks('post', 'insert', $insertEvent); - $record->invokeSaveHooks('post', 'save', $saveEvent); + $record->invokeSaveHooks('post', 'insert', $insertEvent); + $record->invokeSaveHooks('post', 'save', $saveEvent); - $this->_assignIdentifier($record); + $this->_assignIdentifier($record); - return true; - } else { - return false; - } + return true; } + + return false; } /** * Inserts a transient record in its table. * - * This method inserts the data of a single record in its assigned table, + * This method inserts the data of a single record in its assigned table, * assigning to it the autoincrement primary key (if any is defined). - * - * @param Doctrine_Record $record - * @return void */ public function processSingleInsert(Doctrine_Record $record) { @@ -650,14 +639,15 @@ public function processSingleInsert(Doctrine_Record $record) /** * buildFlushTree - * builds a flush tree that is used in transactions + * builds a flush tree that is used in transactions. * * The returned array has all the initialized components in * 'correct' order. Basically this means that the records of those * components can be saved safely in the order specified by the returned array. * - * @param array $tables an array of Doctrine_Table objects or component names - * @return array an array of component names in flushing order + * @param array $tables an array of Doctrine_Table objects or component names + * + * @return array an array of component names in flushing order */ public function buildFlushTree(array $tables) { @@ -665,7 +655,7 @@ public function buildFlushTree(array $tables) // can contain strings or table objects... $classesToOrder = array(); foreach ($tables as $table) { - if ( ! ($table instanceof Doctrine_Table)) { + if (!($table instanceof Doctrine_Table)) { $table = $this->conn->getTable($table, false); } $classesToOrder[] = $table->getComponentName(); @@ -684,8 +674,8 @@ public function buildFlushTree(array $tables) $index = array_search($currentClass, $flushList); - if ($index === false) { - //echo "adding $currentClass to flushlist"; + if (false === $index) { + // echo "adding $currentClass to flushlist"; $flushList[] = $currentClass; $index = max(array_keys($flushList)); } @@ -703,7 +693,7 @@ public function buildFlushTree(array $tables) foreach ($rels as $rel) { $relatedClassName = $rel->getTable()->getComponentName(); - if ( ! in_array($relatedClassName, $classesToOrder)) { + if (!in_array($relatedClassName, $classesToOrder)) { continue; } @@ -719,7 +709,7 @@ public function buildFlushTree(array $tables) // the related component needs to come after this component in // the list (since it holds the fk) - if ($relatedCompIndex !== false) { + if (false !== $relatedCompIndex) { // the component is already in the list if ($relatedCompIndex >= $index) { // it's already in the right place @@ -734,12 +724,11 @@ public function buildFlushTree(array $tables) } else { $flushList[] = $relatedClassName; } - - } else if ($rel instanceof Doctrine_Relation_LocalKey) { + } elseif ($rel instanceof Doctrine_Relation_LocalKey) { // the related component needs to come before the current component // in the list (since this component holds the fk). - if ($relatedCompIndex !== false) { + if (false !== $relatedCompIndex) { // already in flush list if ($relatedCompIndex <= $index) { // it's in the right place @@ -752,9 +741,9 @@ public function buildFlushTree(array $tables) array_splice($flushList, $index, 0, $relatedClassName); } else { array_unshift($flushList, $relatedClassName); - $index++; + ++$index; } - } else if ($rel instanceof Doctrine_Relation_Association) { + } elseif ($rel instanceof Doctrine_Relation_Association) { // the association class needs to come after both classes // that are connected through it in the list (since it holds // both fks) @@ -762,16 +751,16 @@ public function buildFlushTree(array $tables) $assocTable = $rel->getAssociationFactory(); $assocClassName = $assocTable->getComponentName(); - if ($relatedCompIndex !== false) { + if (false !== $relatedCompIndex) { unset($flushList[$relatedCompIndex]); } array_splice($flushList, $index, 0, $relatedClassName); - $index++; + ++$index; $index3 = array_search($assocClassName, $flushList); - if ($index3 !== false) { + if (false !== $index3) { if ($index3 >= $index) { continue; } @@ -789,7 +778,6 @@ public function buildFlushTree(array $tables) return array_values($flushList); } - /* The following is all the Class Table Inheritance specific code. Support dropped for 0.10/1.0. */ @@ -822,7 +810,7 @@ private function _insertCTIRecord(Doctrine_Table $table, Doctrine_Record $record $classes[] = $component; foreach ($classes as $k => $parent) { - if ($k === 0) { + if (0 === $k) { $rootRecord = new $parent(); $rootRecord->merge($dataSet[$parent]); $this->processSingleInsert($rootRecord); @@ -853,7 +841,7 @@ private function _updateCTIRecord(Doctrine_Table $table, Doctrine_Record $record foreach ($record as $field => $value) { if ($value instanceof Doctrine_Record) { - if ( ! $value->exists()) { + if (!$value->exists()) { $value->save(); } $record->set($field, $value->getIncremented()); @@ -863,7 +851,7 @@ private function _updateCTIRecord(Doctrine_Table $table, Doctrine_Record $record foreach ($classes as $class) { $parentTable = $this->conn->getTable($class); - if ( ! array_key_exists($class, $dataSet)) { + if (!array_key_exists($class, $dataSet)) { continue; } @@ -883,11 +871,11 @@ private function _formatDataSet(Doctrine_Record $record) $array = $record->getPrepared(); foreach ($table->getColumns() as $columnName => $definition) { - if ( ! isset($dataSet[$component])) { + if (!isset($dataSet[$component])) { $dataSet[$component] = array(); } - if ( isset($definition['owner']) && ! isset($dataSet[$definition['owner']])) { + if (isset($definition['owner']) && !isset($dataSet[$definition['owner']])) { $dataSet[$definition['owner']] = array(); } @@ -896,7 +884,7 @@ private function _formatDataSet(Doctrine_Record $record) continue; } - if ( ! array_key_exists($fieldName, $array)) { + if (!array_key_exists($fieldName, $array)) { continue; } @@ -915,7 +903,7 @@ protected function _assignSequence(Doctrine_Record $record, &$fields = null) $table = $record->getTable(); $seq = $table->sequenceName; - if ( ! empty($seq)) { + if (!empty($seq)) { $id = $this->conn->sequence->nextId($seq); $seqName = $table->getIdentifier(); if ($fields) { @@ -934,22 +922,22 @@ protected function _assignIdentifier(Doctrine_Record $record) $identifier = $table->getIdentifier(); $seq = $table->sequenceName; - if (empty($seq) && !is_array($identifier) && - $table->getIdentifierType() != Doctrine_Core::IDENTIFIER_NATURAL) { + if (empty($seq) && !is_array($identifier) + && Doctrine_Core::IDENTIFIER_NATURAL != $table->getIdentifierType()) { $id = false; - if ($record->$identifier == null) { + if (null == $record->{$identifier}) { if (($driver = strtolower($this->conn->getDriverName())) == 'pgsql') { - $seq = $table->getTableName() . '_' . $table->getColumnName($identifier); - } elseif ($driver == 'oracle' || $driver == 'mssql') { + $seq = $table->getTableName().'_'.$table->getColumnName($identifier); + } elseif ('oracle' == $driver || 'mssql' == $driver) { $seq = $table->getTableName(); } - + $id = $this->conn->sequence->lastInsertId($seq); } else { - $id = $record->$identifier; + $id = $record->{$identifier}; } - if ( ! $id) { + if (!$id) { throw new Doctrine_Connection_Exception("Couldn't get last insert identifier."); } $record->assignIdentifier($id); diff --git a/lib/Doctrine/Core.php b/lib/Doctrine/Core.php index 382bf9510..bebfba2e9 100644 --- a/lib/Doctrine/Core.php +++ b/lib/Doctrine/Core.php @@ -20,499 +20,505 @@ */ /** - * The base core class of Doctrine + * The base core class of Doctrine. * - * @package Doctrine * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Core { /** - * VERSION - */ - const VERSION = '1.2.4'; - - /** - * ERROR CONSTANTS - */ - const ERR = -1; - const ERR_SYNTAX = -2; - const ERR_CONSTRAINT = -3; - const ERR_NOT_FOUND = -4; - const ERR_ALREADY_EXISTS = -5; - const ERR_UNSUPPORTED = -6; - const ERR_MISMATCH = -7; - const ERR_INVALID = -8; - const ERR_NOT_CAPABLE = -9; - const ERR_TRUNCATED = -10; - const ERR_INVALID_NUMBER = -11; - const ERR_INVALID_DATE = -12; - const ERR_DIVZERO = -13; - const ERR_NODBSELECTED = -14; - const ERR_CANNOT_CREATE = -15; - const ERR_CANNOT_DELETE = -16; - const ERR_CANNOT_DROP = -17; - const ERR_NOSUCHTABLE = -18; - const ERR_NOSUCHFIELD = -19; - const ERR_NEED_MORE_DATA = -20; - const ERR_NOT_LOCKED = -21; - const ERR_VALUE_COUNT_ON_ROW = -22; - const ERR_INVALID_DSN = -23; - const ERR_CONNECT_FAILED = -24; - const ERR_EXTENSION_NOT_FOUND = -25; - const ERR_NOSUCHDB = -26; - const ERR_ACCESS_VIOLATION = -27; - const ERR_CANNOT_REPLACE = -28; - const ERR_CONSTRAINT_NOT_NULL = -29; - const ERR_DEADLOCK = -30; - const ERR_CANNOT_ALTER = -31; - const ERR_MANAGER = -32; - const ERR_MANAGER_PARSE = -33; - const ERR_LOADMODULE = -34; - const ERR_INSUFFICIENT_DATA = -35; - const ERR_CLASS_NAME = -36; - - /** - * PDO derived constants - */ - const CASE_LOWER = 2; - const CASE_NATURAL = 0; - const CASE_UPPER = 1; - const CURSOR_FWDONLY = 0; - const CURSOR_SCROLL = 1; - const ERRMODE_EXCEPTION = 2; - const ERRMODE_SILENT = 0; - const ERRMODE_WARNING = 1; - const FETCH_ASSOC = 2; - const FETCH_BOTH = 4; - const FETCH_BOUND = 6; - const FETCH_CLASS = 8; - const FETCH_CLASSTYPE = 262144; - const FETCH_COLUMN = 7; - const FETCH_FUNC = 10; - const FETCH_GROUP = 65536; - const FETCH_INTO = 9; - const FETCH_LAZY = 1; - const FETCH_NAMED = 11; - const FETCH_NUM = 3; - const FETCH_OBJ = 5; - const FETCH_ORI_ABS = 4; - const FETCH_ORI_FIRST = 2; - const FETCH_ORI_LAST = 3; - const FETCH_ORI_NEXT = 0; - const FETCH_ORI_PRIOR = 1; - const FETCH_ORI_REL = 5; - const FETCH_SERIALIZE = 524288; - const FETCH_UNIQUE = 196608; - const NULL_EMPTY_STRING = 1; - const NULL_NATURAL = 0; - const NULL_TO_STRING = NULL; - const PARAM_BOOL = 5; - const PARAM_INPUT_OUTPUT = -2147483648; - const PARAM_INT = 1; - const PARAM_LOB = 3; - const PARAM_NULL = 0; - const PARAM_STMT = 4; - const PARAM_STR = 2; - - /** - * ATTRIBUTE CONSTANTS - */ - - /** - * PDO derived attributes - */ - const ATTR_AUTOCOMMIT = 0; - const ATTR_PREFETCH = 1; - const ATTR_TIMEOUT = 2; - const ATTR_ERRMODE = 3; - const ATTR_SERVER_VERSION = 4; - const ATTR_CLIENT_VERSION = 5; - const ATTR_SERVER_INFO = 6; - const ATTR_CONNECTION_STATUS = 7; - const ATTR_CASE = 8; - const ATTR_CURSOR_NAME = 9; - const ATTR_CURSOR = 10; - const ATTR_ORACLE_NULLS = 11; - const ATTR_PERSISTENT = 12; - const ATTR_STATEMENT_CLASS = 13; - const ATTR_FETCH_TABLE_NAMES = 14; - const ATTR_FETCH_CATALOG_NAMES = 15; - const ATTR_DRIVER_NAME = 16; - const ATTR_STRINGIFY_FETCHES = 17; - const ATTR_MAX_COLUMN_LEN = 18; - - /** - * Doctrine constants - */ - const ATTR_LISTENER = 100; - const ATTR_QUOTE_IDENTIFIER = 101; - const ATTR_FIELD_CASE = 102; - const ATTR_IDXNAME_FORMAT = 103; - const ATTR_SEQNAME_FORMAT = 104; - const ATTR_SEQCOL_NAME = 105; - const ATTR_CMPNAME_FORMAT = 118; - const ATTR_DBNAME_FORMAT = 117; - const ATTR_TBLCLASS_FORMAT = 119; - const ATTR_TBLNAME_FORMAT = 120; - const ATTR_FKNAME_FORMAT = 171; - const ATTR_EXPORT = 140; - const ATTR_DECIMAL_PLACES = 141; - - const ATTR_PORTABILITY = 106; - const ATTR_VALIDATE = 107; - const ATTR_COLL_KEY = 108; - const ATTR_QUERY_LIMIT = 109; - const ATTR_DEFAULT_TABLE_TYPE = 112; - const ATTR_DEF_TEXT_LENGTH = 113; - const ATTR_DEF_VARCHAR_LENGTH = 114; - const ATTR_DEF_TABLESPACE = 115; - const ATTR_EMULATE_DATABASE = 116; - const ATTR_USE_NATIVE_ENUM = 117; - const ATTR_DEFAULT_SEQUENCE = 133; - - const ATTR_FETCHMODE = 118; - const ATTR_NAME_PREFIX = 121; - const ATTR_CREATE_TABLES = 122; - const ATTR_COLL_LIMIT = 123; - - const ATTR_CACHE = 150; - const ATTR_RESULT_CACHE = 150; - const ATTR_CACHE_LIFESPAN = 151; - const ATTR_RESULT_CACHE_LIFESPAN = 151; - const ATTR_LOAD_REFERENCES = 153; - const ATTR_RECORD_LISTENER = 154; - const ATTR_THROW_EXCEPTIONS = 155; - const ATTR_DEFAULT_PARAM_NAMESPACE = 156; - const ATTR_QUERY_CACHE = 157; - const ATTR_QUERY_CACHE_LIFESPAN = 158; - const ATTR_AUTOLOAD_TABLE_CLASSES = 160; - const ATTR_MODEL_LOADING = 161; - const ATTR_RECURSIVE_MERGE_FIXTURES = 162; - const ATTR_USE_DQL_CALLBACKS = 164; - const ATTR_AUTO_ACCESSOR_OVERRIDE = 165; - const ATTR_AUTO_FREE_QUERY_OBJECTS = 166; - const ATTR_DEFAULT_TABLE_CHARSET = 167; - const ATTR_DEFAULT_TABLE_COLLATE = 168; - const ATTR_DEFAULT_IDENTIFIER_OPTIONS = 169; - const ATTR_DEFAULT_COLUMN_OPTIONS = 170; - const ATTR_HYDRATE_OVERWRITE = 172; - const ATTR_QUERY_CLASS = 173; - const ATTR_CASCADE_SAVES = 174; - const ATTR_COLLECTION_CLASS = 175; - const ATTR_TABLE_CLASS = 176; - const ATTR_USE_NATIVE_SET = 177; - const ATTR_MODEL_CLASS_PREFIX = 178; - const ATTR_TABLE_CLASS_FORMAT = 179; - const ATTR_MAX_IDENTIFIER_LENGTH = 180; - const ATTR_USE_TABLE_REPOSITORY = 181; - const ATTR_USE_TABLE_IDENTITY_MAP = 182; - const ATTR_TABLE_CACHE = 183; - const ATTR_TABLE_CACHE_LIFESPAN = 184; - - - /** - * LIMIT CONSTANTS - */ - - /** - * constant for row limiting - */ - const LIMIT_ROWS = 1; - const QUERY_LIMIT_ROWS = 1; - - /** - * constant for record limiting - */ - const LIMIT_RECORDS = 2; - const QUERY_LIMIT_RECORDS = 2; - - /** - * FETCHMODE CONSTANTS - */ - - - /** - * PORTABILITY CONSTANTS + * VERSION. + */ + public const VERSION = '1.2.4'; + + /** + * ERROR CONSTANTS. + */ + public const ERR = -1; + public const ERR_SYNTAX = -2; + public const ERR_CONSTRAINT = -3; + public const ERR_NOT_FOUND = -4; + public const ERR_ALREADY_EXISTS = -5; + public const ERR_UNSUPPORTED = -6; + public const ERR_MISMATCH = -7; + public const ERR_INVALID = -8; + public const ERR_NOT_CAPABLE = -9; + public const ERR_TRUNCATED = -10; + public const ERR_INVALID_NUMBER = -11; + public const ERR_INVALID_DATE = -12; + public const ERR_DIVZERO = -13; + public const ERR_NODBSELECTED = -14; + public const ERR_CANNOT_CREATE = -15; + public const ERR_CANNOT_DELETE = -16; + public const ERR_CANNOT_DROP = -17; + public const ERR_NOSUCHTABLE = -18; + public const ERR_NOSUCHFIELD = -19; + public const ERR_NEED_MORE_DATA = -20; + public const ERR_NOT_LOCKED = -21; + public const ERR_VALUE_COUNT_ON_ROW = -22; + public const ERR_INVALID_DSN = -23; + public const ERR_CONNECT_FAILED = -24; + public const ERR_EXTENSION_NOT_FOUND = -25; + public const ERR_NOSUCHDB = -26; + public const ERR_ACCESS_VIOLATION = -27; + public const ERR_CANNOT_REPLACE = -28; + public const ERR_CONSTRAINT_NOT_NULL = -29; + public const ERR_DEADLOCK = -30; + public const ERR_CANNOT_ALTER = -31; + public const ERR_MANAGER = -32; + public const ERR_MANAGER_PARSE = -33; + public const ERR_LOADMODULE = -34; + public const ERR_INSUFFICIENT_DATA = -35; + public const ERR_CLASS_NAME = -36; + + /** + * PDO derived constants. + */ + public const CASE_LOWER = 2; + public const CASE_NATURAL = 0; + public const CASE_UPPER = 1; + public const CURSOR_FWDONLY = 0; + public const CURSOR_SCROLL = 1; + public const ERRMODE_EXCEPTION = 2; + public const ERRMODE_SILENT = 0; + public const ERRMODE_WARNING = 1; + public const FETCH_ASSOC = 2; + public const FETCH_BOTH = 4; + public const FETCH_BOUND = 6; + public const FETCH_CLASS = 8; + public const FETCH_CLASSTYPE = 262144; + public const FETCH_COLUMN = 7; + public const FETCH_FUNC = 10; + public const FETCH_GROUP = 65536; + public const FETCH_INTO = 9; + public const FETCH_LAZY = 1; + public const FETCH_NAMED = 11; + public const FETCH_NUM = 3; + public const FETCH_OBJ = 5; + public const FETCH_ORI_ABS = 4; + public const FETCH_ORI_FIRST = 2; + public const FETCH_ORI_LAST = 3; + public const FETCH_ORI_NEXT = 0; + public const FETCH_ORI_PRIOR = 1; + public const FETCH_ORI_REL = 5; + public const FETCH_SERIALIZE = 524288; + public const FETCH_UNIQUE = 196608; + public const NULL_EMPTY_STRING = 1; + public const NULL_NATURAL = 0; + public const NULL_TO_STRING = null; + public const PARAM_BOOL = 5; + public const PARAM_INPUT_OUTPUT = -2147483648; + public const PARAM_INT = 1; + public const PARAM_LOB = 3; + public const PARAM_NULL = 0; + public const PARAM_STMT = 4; + public const PARAM_STR = 2; + + /** + * ATTRIBUTE CONSTANTS. + */ + + /** + * PDO derived attributes. + */ + public const ATTR_AUTOCOMMIT = 0; + public const ATTR_PREFETCH = 1; + public const ATTR_TIMEOUT = 2; + public const ATTR_ERRMODE = 3; + public const ATTR_SERVER_VERSION = 4; + public const ATTR_CLIENT_VERSION = 5; + public const ATTR_SERVER_INFO = 6; + public const ATTR_CONNECTION_STATUS = 7; + public const ATTR_CASE = 8; + public const ATTR_CURSOR_NAME = 9; + public const ATTR_CURSOR = 10; + public const ATTR_ORACLE_NULLS = 11; + public const ATTR_PERSISTENT = 12; + public const ATTR_STATEMENT_CLASS = 13; + public const ATTR_FETCH_TABLE_NAMES = 14; + public const ATTR_FETCH_CATALOG_NAMES = 15; + public const ATTR_DRIVER_NAME = 16; + public const ATTR_STRINGIFY_FETCHES = 17; + public const ATTR_MAX_COLUMN_LEN = 18; + + /** + * Doctrine constants. + */ + public const ATTR_LISTENER = 100; + public const ATTR_QUOTE_IDENTIFIER = 101; + public const ATTR_FIELD_CASE = 102; + public const ATTR_IDXNAME_FORMAT = 103; + public const ATTR_SEQNAME_FORMAT = 104; + public const ATTR_SEQCOL_NAME = 105; + public const ATTR_CMPNAME_FORMAT = 118; + public const ATTR_DBNAME_FORMAT = 117; + public const ATTR_TBLCLASS_FORMAT = 119; + public const ATTR_TBLNAME_FORMAT = 120; + public const ATTR_FKNAME_FORMAT = 171; + public const ATTR_EXPORT = 140; + public const ATTR_DECIMAL_PLACES = 141; + + public const ATTR_PORTABILITY = 106; + public const ATTR_VALIDATE = 107; + public const ATTR_COLL_KEY = 108; + public const ATTR_QUERY_LIMIT = 109; + public const ATTR_DEFAULT_TABLE_TYPE = 112; + public const ATTR_DEF_TEXT_LENGTH = 113; + public const ATTR_DEF_VARCHAR_LENGTH = 114; + public const ATTR_DEF_TABLESPACE = 115; + public const ATTR_EMULATE_DATABASE = 116; + public const ATTR_USE_NATIVE_ENUM = 117; + public const ATTR_DEFAULT_SEQUENCE = 133; + + public const ATTR_FETCHMODE = 118; + public const ATTR_NAME_PREFIX = 121; + public const ATTR_CREATE_TABLES = 122; + public const ATTR_COLL_LIMIT = 123; + + public const ATTR_CACHE = 150; + public const ATTR_RESULT_CACHE = 150; + public const ATTR_CACHE_LIFESPAN = 151; + public const ATTR_RESULT_CACHE_LIFESPAN = 151; + public const ATTR_LOAD_REFERENCES = 153; + public const ATTR_RECORD_LISTENER = 154; + public const ATTR_THROW_EXCEPTIONS = 155; + public const ATTR_DEFAULT_PARAM_NAMESPACE = 156; + public const ATTR_QUERY_CACHE = 157; + public const ATTR_QUERY_CACHE_LIFESPAN = 158; + public const ATTR_AUTOLOAD_TABLE_CLASSES = 160; + public const ATTR_MODEL_LOADING = 161; + public const ATTR_RECURSIVE_MERGE_FIXTURES = 162; + public const ATTR_USE_DQL_CALLBACKS = 164; + public const ATTR_AUTO_ACCESSOR_OVERRIDE = 165; + public const ATTR_AUTO_FREE_QUERY_OBJECTS = 166; + public const ATTR_DEFAULT_TABLE_CHARSET = 167; + public const ATTR_DEFAULT_TABLE_COLLATE = 168; + public const ATTR_DEFAULT_IDENTIFIER_OPTIONS = 169; + public const ATTR_DEFAULT_COLUMN_OPTIONS = 170; + public const ATTR_HYDRATE_OVERWRITE = 172; + public const ATTR_QUERY_CLASS = 173; + public const ATTR_CASCADE_SAVES = 174; + public const ATTR_COLLECTION_CLASS = 175; + public const ATTR_TABLE_CLASS = 176; + public const ATTR_USE_NATIVE_SET = 177; + public const ATTR_MODEL_CLASS_PREFIX = 178; + public const ATTR_TABLE_CLASS_FORMAT = 179; + public const ATTR_MAX_IDENTIFIER_LENGTH = 180; + public const ATTR_USE_TABLE_REPOSITORY = 181; + public const ATTR_USE_TABLE_IDENTITY_MAP = 182; + public const ATTR_TABLE_CACHE = 183; + public const ATTR_TABLE_CACHE_LIFESPAN = 184; + + /** + * LIMIT CONSTANTS. + */ + + /** + * constant for row limiting. + */ + public const LIMIT_ROWS = 1; + public const QUERY_LIMIT_ROWS = 1; + + /** + * constant for record limiting. + */ + public const LIMIT_RECORDS = 2; + public const QUERY_LIMIT_RECORDS = 2; + + /** + * FETCHMODE CONSTANTS. + */ + + /** + * PORTABILITY CONSTANTS. */ /** * Portability: turn off all portability features. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_NONE = 0; + public const PORTABILITY_NONE = 0; /** * Portability: convert names of tables and fields to case defined in the * "field_case" option when using the query*(), fetch*() methods. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_FIX_CASE = 1; + public const PORTABILITY_FIX_CASE = 1; /** * Portability: right trim the data output by query*() and fetch*(). + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_RTRIM = 2; + public const PORTABILITY_RTRIM = 2; /** * Portability: force reporting the number of rows deleted. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_DELETE_COUNT = 4; + public const PORTABILITY_DELETE_COUNT = 4; /** * Portability: convert empty values to null strings in data output by * query*() and fetch*(). + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_EMPTY_TO_NULL = 8; + public const PORTABILITY_EMPTY_TO_NULL = 8; /** - * Portability: removes database/table qualifiers from associative indexes + * Portability: removes database/table qualifiers from associative indexes. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_FIX_ASSOC_FIELD_NAMES = 16; + public const PORTABILITY_FIX_ASSOC_FIELD_NAMES = 16; /** - * Portability: makes Doctrine_Expression throw exception for unportable RDBMS expressions + * Portability: makes Doctrine_Expression throw exception for unportable RDBMS expressions. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_EXPR = 32; + public const PORTABILITY_EXPR = 32; /** * Portability: turn on all portability features. + * * @see self::ATTR_PORTABILITY */ - const PORTABILITY_ALL = 63; + public const PORTABILITY_ALL = 63; /** - * LOCKMODE CONSTANTS + * LOCKMODE CONSTANTS. */ /** - * mode for optimistic locking + * mode for optimistic locking. */ - const LOCK_OPTIMISTIC = 0; + public const LOCK_OPTIMISTIC = 0; /** - * mode for pessimistic locking + * mode for pessimistic locking. */ - const LOCK_PESSIMISTIC = 1; + public const LOCK_PESSIMISTIC = 1; /** - * EXPORT CONSTANTS + * EXPORT CONSTANTS. */ /** - * EXPORT_NONE + * EXPORT_NONE. */ - const EXPORT_NONE = 0; + public const EXPORT_NONE = 0; /** - * EXPORT_TABLES + * EXPORT_TABLES. */ - const EXPORT_TABLES = 1; + public const EXPORT_TABLES = 1; /** - * EXPORT_CONSTRAINTS + * EXPORT_CONSTRAINTS. */ - const EXPORT_CONSTRAINTS = 2; + public const EXPORT_CONSTRAINTS = 2; /** - * EXPORT_PLUGINS + * EXPORT_PLUGINS. */ - const EXPORT_PLUGINS = 4; + public const EXPORT_PLUGINS = 4; /** - * EXPORT_ALL + * EXPORT_ALL. */ - const EXPORT_ALL = 7; + public const EXPORT_ALL = 7; /** - * HYDRATION CONSTANTS + * HYDRATION CONSTANTS. */ /** - * HYDRATE_RECORD + * HYDRATE_RECORD. */ - const HYDRATE_RECORD = 2; + public const HYDRATE_RECORD = 2; /** - * HYDRATE_ARRAY + * HYDRATE_ARRAY. */ - const HYDRATE_ARRAY = 3; + public const HYDRATE_ARRAY = 3; /** - * HYDRATE_NONE + * HYDRATE_NONE. */ - const HYDRATE_NONE = 4; + public const HYDRATE_NONE = 4; /** - * HYDRATE_SCALAR + * HYDRATE_SCALAR. */ - const HYDRATE_SCALAR = 5; + public const HYDRATE_SCALAR = 5; /** - * HYDRATE_SINGLE_SCALAR + * HYDRATE_SINGLE_SCALAR. */ - const HYDRATE_SINGLE_SCALAR = 6; + public const HYDRATE_SINGLE_SCALAR = 6; /** - * HYDRATE_ON_DEMAND + * HYDRATE_ON_DEMAND. */ - const HYDRATE_ON_DEMAND = 7; + public const HYDRATE_ON_DEMAND = 7; /** - * HYDRATE_ARRAY_HIERARCHY + * HYDRATE_ARRAY_HIERARCHY. */ - const HYDRATE_ARRAY_HIERARCHY = 8; + public const HYDRATE_ARRAY_HIERARCHY = 8; /** - * HYDRATE_RECORD_HIERARCHY + * HYDRATE_RECORD_HIERARCHY. */ - const HYDRATE_RECORD_HIERARCHY = 9; + public const HYDRATE_RECORD_HIERARCHY = 9; /** - * HYDRATE_ARRAY_SHALLOW + * HYDRATE_ARRAY_SHALLOW. */ - const HYDRATE_ARRAY_SHALLOW = 10; + public const HYDRATE_ARRAY_SHALLOW = 10; /** - * VALIDATION CONSTANTS + * VALIDATION CONSTANTS. */ - const VALIDATE_NONE = 0; + public const VALIDATE_NONE = 0; /** - * VALIDATE_LENGTHS + * VALIDATE_LENGTHS. */ - const VALIDATE_LENGTHS = 1; + public const VALIDATE_LENGTHS = 1; /** - * VALIDATE_TYPES + * VALIDATE_TYPES. */ - const VALIDATE_TYPES = 2; + public const VALIDATE_TYPES = 2; /** - * VALIDATE_CONSTRAINTS + * VALIDATE_CONSTRAINTS. */ - const VALIDATE_CONSTRAINTS = 4; + public const VALIDATE_CONSTRAINTS = 4; /** - * VALIDATE_ALL + * VALIDATE_ALL. */ - const VALIDATE_ALL = 7; + public const VALIDATE_ALL = 7; /** - * VALIDATE_USER + * VALIDATE_USER. */ - const VALIDATE_USER = 8; + public const VALIDATE_USER = 8; /** - * IDENTIFIER_AUTOINC + * IDENTIFIER_AUTOINC. * * constant for auto_increment identifier */ - const IDENTIFIER_AUTOINC = 1; + public const IDENTIFIER_AUTOINC = 1; /** - * IDENTIFIER_SEQUENCE + * IDENTIFIER_SEQUENCE. * * constant for sequence identifier */ - const IDENTIFIER_SEQUENCE = 2; + public const IDENTIFIER_SEQUENCE = 2; /** - * IDENTIFIER_NATURAL + * IDENTIFIER_NATURAL. * * constant for normal identifier */ - const IDENTIFIER_NATURAL = 3; + public const IDENTIFIER_NATURAL = 3; /** - * IDENTIFIER_COMPOSITE + * IDENTIFIER_COMPOSITE. * * constant for composite identifier */ - const IDENTIFIER_COMPOSITE = 4; + public const IDENTIFIER_COMPOSITE = 4; /** - * MODEL_LOADING_AGGRESSIVE + * MODEL_LOADING_AGGRESSIVE. * * Constant for agressive model loading * Will require_once() all found model files */ - const MODEL_LOADING_AGGRESSIVE = 1; + public const MODEL_LOADING_AGGRESSIVE = 1; /** - * MODEL_LOADING_CONSERVATIVE + * MODEL_LOADING_CONSERVATIVE. * * Constant for conservative model loading * Will not require_once() found model files inititally instead it will build an array * and reference it in autoload() when a class is needed it will require_once() it */ - const MODEL_LOADING_CONSERVATIVE = 2; + public const MODEL_LOADING_CONSERVATIVE = 2; /** - * MODEL_LOADING_PEAR + * MODEL_LOADING_PEAR. * * Constant for pear model loading * Will simply store the path passed to Doctrine_Core::loadModels() * and Doctrine_Core::autoload() will check there */ - const MODEL_LOADING_PEAR = 3; + public const MODEL_LOADING_PEAR = 3; /** - * Path to Doctrine root + * Path to Doctrine root. * - * @var string $path doctrine root directory + * @var string doctrine root directory */ private static $_path; /** - * Path to the Doctrine extensions directory + * Path to the Doctrine extensions directory. * - * @var string $extensionsPath + * @var string */ private static $_extensionsPath; /** - * Debug bool true/false option + * Debug bool true/false option. * - * @var boolean $_debug + * @var bool */ private static $_debug = false; /** - * Array of all the loaded models and the path to each one for autoloading + * Array of all the loaded models and the path to each one for autoloading. * * @var array */ private static $_loadedModelFiles = array(); /** - * Array of all the loaded validators + * Array of all the loaded validators. * * @var array */ private static $_validators = array(); /** - * Path to the models directory + * Path to the models directory. * * @var string */ private static $_modelsDirectory; /** - * __construct + * __construct. * - * @return void * @throws Doctrine_Exception */ public function __construct() @@ -521,7 +527,7 @@ public function __construct() } /** - * Returns an array of all the loaded models and the path where each of them exists + * Returns an array of all the loaded models and the path where each of them exists. * * @return array */ @@ -531,14 +537,13 @@ public static function getLoadedModelFiles() } /** - * Turn on/off the debugging setting + * Turn on/off the debugging setting. * * @param string $bool - * @return void */ public static function debug($bool = null) { - if ($bool !== null) { + if (null !== $bool) { self::$_debug = (bool) $bool; } @@ -546,10 +551,9 @@ public static function debug($bool = null) } /** - * Set the path to your core Doctrine libraries + * Set the path to your core Doctrine libraries. * * @param string $path The path to your Doctrine libraries - * @return void */ public static function setPath($path) { @@ -557,24 +561,23 @@ public static function setPath($path) } /** - * Get the root path to Doctrine + * Get the root path to Doctrine. * * @return string */ public static function getPath() { - if ( ! self::$_path) { - self::$_path = realpath(dirname(__FILE__) . '/..'); + if (!self::$_path) { + self::$_path = realpath(dirname(__FILE__).'/..'); } return self::$_path; } /** - * Set the path to autoload extension classes from + * Set the path to autoload extension classes from. * * @param string $extensionsPath - * @return void */ public static function setExtensionsPath($extensionsPath) { @@ -582,7 +585,7 @@ public static function setExtensionsPath($extensionsPath) } /** - * Get the path to load extension classes from + * Get the path to load extension classes from. * * @return string $extensionsPath */ @@ -592,9 +595,9 @@ public static function getExtensionsPath() } /** - * Load an individual model name and path in to the model loading registry + * Load an individual model name and path in to the model loading registry. * - * @return null + * @param mixed|null $path */ public static function loadModel($className, $path = null) { @@ -606,7 +609,6 @@ public static function loadModel($className, $path = null) * naming convention autoloading. * * @param string $directory - * @return void */ public static function setModelsDirectory($directory) { @@ -615,9 +617,8 @@ public static function setModelsDirectory($directory) /** * Get the directory where your models are located for PEAR style naming - * convention autoloading + * convention autoloading. * - * @return void * @author Jonathan Wage */ public static function getModelsDirectory() @@ -626,38 +627,38 @@ public static function getModelsDirectory() } /** - * Recursively load all models from a directory or array of directories + * Recursively load all models from a directory or array of directories. * - * @param string $directory Path to directory of models or array of directory paths - * @param integer $modelLoading Pass value of Doctrine_Core::ATTR_MODEL_LOADING to force a certain style of model loading - * Allowed Doctrine_Core::MODEL_LOADING_AGGRESSIVE(default) or Doctrine_Core::MODEL_LOADING_CONSERVATIVE - * @param string $classPrefix The class prefix of the models to load. This is useful if the class name and file name are not the same + * @param string $directory Path to directory of models or array of directory paths + * @param int $modelLoading Pass value of Doctrine_Core::ATTR_MODEL_LOADING to force a certain style of model loading + * Allowed Doctrine_Core::MODEL_LOADING_AGGRESSIVE(default) or Doctrine_Core::MODEL_LOADING_CONSERVATIVE + * @param string $classPrefix The class prefix of the models to load. This is useful if the class name and file name are not the same */ public static function loadModels($directory, $modelLoading = null, $classPrefix = null) { $manager = Doctrine_Manager::getInstance(); - $modelLoading = $modelLoading === null ? $manager->getAttribute(Doctrine_Core::ATTR_MODEL_LOADING) : $modelLoading; - $classPrefix = $classPrefix === null ? $manager->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) : $classPrefix; + $modelLoading = null === $modelLoading ? $manager->getAttribute(Doctrine_Core::ATTR_MODEL_LOADING) : $modelLoading; + $classPrefix = null === $classPrefix ? $manager->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) : $classPrefix; $loadedModels = array(); - if ($directory !== null) { + if (null !== $directory) { foreach ((array) $directory as $dir) { $dir = rtrim($dir, '/'); - if ( ! is_dir($dir)) { + if (!is_dir($dir)) { throw new Doctrine_Exception('You must pass a valid path to a directory containing Doctrine models'); } $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), - RecursiveIteratorIterator::LEAVES_ONLY); + RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $e = explode('.', $file->getFileName()); - if (end($e) === 'php' && strpos($file->getFileName(), '.inc') === false) { - if ($modelLoading == Doctrine_Core::MODEL_LOADING_PEAR) { - $className = str_replace($dir . DIRECTORY_SEPARATOR, null, $file->getPathName()); + if ('php' === end($e) && false === strpos($file->getFileName(), '.inc')) { + if (Doctrine_Core::MODEL_LOADING_PEAR == $modelLoading) { + $className = str_replace($dir.DIRECTORY_SEPARATOR, null, $file->getPathName()); $className = str_replace(DIRECTORY_SEPARATOR, '_', $className); $className = substr($className, 0, strpos($className, '.')); } else { @@ -665,17 +666,17 @@ public static function loadModels($directory, $modelLoading = null, $classPrefix } if ($classPrefix && $classPrefix != substr($className, 0, strlen($classPrefix))) { - $className = $classPrefix . $className; + $className = $classPrefix.$className; } - if ( ! class_exists($className, false)) { - if ($modelLoading == Doctrine_Core::MODEL_LOADING_CONSERVATIVE || $modelLoading == Doctrine_Core::MODEL_LOADING_PEAR) { + if (!class_exists($className, false)) { + if (Doctrine_Core::MODEL_LOADING_CONSERVATIVE == $modelLoading || Doctrine_Core::MODEL_LOADING_PEAR == $modelLoading) { self::loadModel($className, $file->getPathName()); $loadedModels[$className] = $className; } else { $declaredBefore = get_declared_classes(); - require_once($file->getPathName()); + require_once $file->getPathName(); $declaredAfter = get_declared_classes(); if (defined('HHVM_VERSION')) { @@ -699,12 +700,12 @@ public static function loadModels($directory, $modelLoading = null, $classPrefix $previouslyLoaded = array_keys(self::$_loadedModelFiles, $file->getPathName()); - if ( ! empty($previouslyLoaded)) { + if (!empty($previouslyLoaded)) { $previouslyLoaded = array_combine(array_values($previouslyLoaded), array_values($previouslyLoaded)); $loadedModels = array_merge($loadedModels, $previouslyLoaded); } } - } else if (self::isValidModelClass($className)) { + } elseif (self::isValidModelClass($className)) { $loadedModels[$className] = $className; } } @@ -718,17 +719,19 @@ public static function loadModels($directory, $modelLoading = null, $classPrefix } /** - * Get all the loaded models, you can provide an array of classes or it will use get_declared_classes() + * Get all the loaded models, you can provide an array of classes or it will use get_declared_classes(). * * Will filter through an array of classes and return the Doctrine_Records out of them. * If you do not specify $classes it will return all of the currently loaded Doctrine_Records * * @param classes Array of classes to filter through, otherwise uses get_declared_classes() - * @return array $loadedModels + * @param mixed|null $classes + * + * @return array $loadedModels */ public static function getLoadedModels($classes = null) { - if ($classes === null) { + if (null === $classes) { $classes = get_declared_classes(); $classes = array_merge($classes, array_keys(self::$_loadedModelFiles)); } @@ -740,9 +743,10 @@ public static function getLoadedModels($classes = null) * Initialize all models so everything is present and loaded in to memory * This will also inheritently initialize any model behaviors and add * the models generated by Doctrine generators and add them to the $models - * array + * array. * * @param string $models + * * @return array $models */ public static function initializeModels($models) @@ -769,9 +773,7 @@ public static function initializeModels($models) } } - $models = self::filterInvalidModels($models); - - return $models; + return self::filterInvalidModels($models); } /** @@ -779,14 +781,15 @@ public static function initializeModels($models) * This will inflect the class, causing it to be loaded in to memory. * * @param classes Array of classes to filter through, otherwise uses get_declared_classes() - * @return array $loadedModels + * + * @return array $loadedModels */ public static function filterInvalidModels($classes) { $validModels = array(); foreach ((array) $classes as $name) { - if (self::isValidModelClass($name) && ! in_array($name, $validModels)) { + if (self::isValidModelClass($name) && !in_array($name, $validModels)) { $validModels[] = $name; } } @@ -796,10 +799,11 @@ public static function filterInvalidModels($classes) /** * Checks if what is passed is a valid Doctrine_Record - * Will load class in to memory in order to inflect it and find out information about the class + * Will load class in to memory in order to inflect it and find out information about the class. + * + * @param mixed $class Can be a string named after the class, an instance of the class, or an instance of the class reflected * - * @param mixed $class Can be a string named after the class, an instance of the class, or an instance of the class reflected - * @return boolean + * @return bool */ public static function isValidModelClass($class) { @@ -815,8 +819,7 @@ public static function isValidModelClass($class) // Skip the following classes // - abstract classes // - not a subclass of Doctrine_Record - if ( ! $class->isAbstract() && $class->isSubclassOf('Doctrine_Record')) { - + if (!$class->isAbstract() && $class->isSubclassOf('Doctrine_Record')) { return true; } } @@ -826,9 +829,10 @@ public static function isValidModelClass($class) /** * Get the connection object for a table by the actual table name - * FIXME: I think this method is flawed because a individual connections could have the same table name + * FIXME: I think this method is flawed because a individual connections could have the same table name. * * @param string $tableName + * * @return Doctrine_Connection */ public static function getConnectionByTableName($tableName) @@ -839,7 +843,7 @@ public static function getConnectionByTableName($tableName) $table = Doctrine_Core::getTable($name); if ($table->getTableName() == $tableName) { - return $table->getConnection(); + return $table->getConnection(); } } @@ -847,12 +851,14 @@ public static function getConnectionByTableName($tableName) } /** - * Method for importing existing schema to Doctrine_Record classes + * Method for importing existing schema to Doctrine_Record classes. + * + * @param string $directory Directory to write your models to + * @param array $connections Array of connection names to generate models for + * @param array $options Array of options + * + * @return bool * - * @param string $directory Directory to write your models to - * @param array $connections Array of connection names to generate models for - * @param array $options Array of options - * @return boolean * @throws Exception */ public static function generateModelsFromDb($directory, array $connections = array(), array $options = array()) @@ -864,19 +870,18 @@ public static function generateModelsFromDb($directory, array $connections = arr * Generates models from database to temporary location then uses those models to generate a yaml schema file. * This should probably be fixed. We should write something to generate a yaml schema file directly from the database. * - * @param string $yamlPath Path to write oyur yaml schema file to - * @param array $connections Array of connection names to generate yaml for - * @param array $options Array of options - * @return void + * @param string $yamlPath Path to write oyur yaml schema file to + * @param array $connections Array of connection names to generate yaml for + * @param array $options Array of options */ public static function generateYamlFromDb($yamlPath, array $connections = array(), array $options = array()) { - $directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'tmp_doctrine_models'; + $directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'tmp_doctrine_models'; - $options['generateBaseClasses'] = isset($options['generateBaseClasses']) ? $options['generateBaseClasses']:false; + $options['generateBaseClasses'] = isset($options['generateBaseClasses']) ? $options['generateBaseClasses'] : false; $result = Doctrine_Core::generateModelsFromDb($directory, $connections, $options); - if ( empty($result) && ! is_dir($directory)) { + if (empty($result) && !is_dir($directory)) { throw new Doctrine_Exception('No models generated from your databases'); } @@ -890,12 +895,11 @@ public static function generateYamlFromDb($yamlPath, array $connections = array( } /** - * Generate a yaml schema file from an existing directory of models + * Generate a yaml schema file from an existing directory of models. * - * @param string $yamlPath Path to your yaml schema files + * @param string $yamlPath Path to your yaml schema files * @param string $directory Directory to generate your models in - * @param array $options Array of options to pass to the schema importer - * @return void + * @param array $options Array of options to pass to the schema importer */ public static function generateModelsFromYaml($yamlPath, $directory, $options = array()) { @@ -906,10 +910,9 @@ public static function generateModelsFromYaml($yamlPath, $directory, $options = } /** - * Creates database tables for the models in the specified directory + * Creates database tables for the models in the specified directory. * * @param string $directory Directory containing your models - * @return void */ public static function createTablesFromModels($directory = null) { @@ -917,10 +920,9 @@ public static function createTablesFromModels($directory = null) } /** - * Creates database tables for the models in the supplied array + * Creates database tables for the models in the supplied array. * * @param array $array An array of models to be exported - * @return void */ public static function createTablesFromArray($array) { @@ -928,9 +930,10 @@ public static function createTablesFromArray($array) } /** - * Generate a array of sql for the passed array of models + * Generate a array of sql for the passed array of models. + * + * @param array $array * - * @param array $array * @return array $sql */ public static function generateSqlFromArray($array) @@ -942,7 +945,8 @@ public static function generateSqlFromArray($array) * Generate a sql string to create the tables from all loaded models * or the models found in the passed directory. * - * @param string $directory + * @param string $directory + * * @return string $build String of sql queries. One query per line */ public static function generateSqlFromModels($directory = null) @@ -959,11 +963,10 @@ public static function generateSqlFromModels($directory = null) } /** - * Generate yaml schema file for the models in the specified directory + * Generate yaml schema file for the models in the specified directory. * - * @param string $yamlPath Path to your yaml schema files + * @param string $yamlPath Path to your yaml schema files * @param string $directory Directory to generate your models in - * @return void */ public static function generateYamlFromModels($yamlPath, $directory) { @@ -973,10 +976,9 @@ public static function generateYamlFromModels($yamlPath, $directory) } /** - * Creates databases for connections + * Creates databases for connections. * * @param string $specifiedConnections Array of connections you wish to create the database for - * @return void */ public static function createDatabases($specifiedConnections = array()) { @@ -984,10 +986,9 @@ public static function createDatabases($specifiedConnections = array()) } /** - * Drops databases for connections + * Drops databases for connections. * * @param string $specifiedConnections Array of connections you wish to drop the database for - * @return void */ public static function dropDatabases($specifiedConnections = array()) { @@ -995,11 +996,10 @@ public static function dropDatabases($specifiedConnections = array()) } /** - * Dump data to a yaml fixtures file + * Dump data to a yaml fixtures file. * - * @param string $yamlPath Path to write the yaml data fixtures to + * @param string $yamlPath Path to write the yaml data fixtures to * @param string $individualFiles Whether or not to dump data to individual fixtures files - * @return void */ public static function dumpData($yamlPath, $individualFiles = false) { @@ -1010,11 +1010,10 @@ public static function dumpData($yamlPath, $individualFiles = false) /** * Load data from a yaml fixtures file. - * The output of dumpData can be fed to loadData + * The output of dumpData can be fed to loadData. * * @param string $yamlPath Path to your yaml data fixtures - * @param string $append Whether or not to append the data - * @return void + * @param string $append Whether or not to append the data */ public static function loadData($yamlPath, $append = false, $charset = 'UTF-8') { @@ -1027,8 +1026,10 @@ public static function loadData($yamlPath, $append = false, $charset = 'UTF-8') * Migrate database to specified $to version. Migrates from current to latest if you do not specify. * * @param string $migrationsPath Path to migrations directory which contains your migration classes - * @param string $to Version you wish to migrate to. + * @param string $to version you wish to migrate to + * * @return bool true + * * @throws new Doctrine_Migration_Exception */ public static function migrate($migrationsPath, $to = null) @@ -1039,9 +1040,9 @@ public static function migrate($migrationsPath, $to = null) } /** - * Generate new migration class skeleton + * Generate new migration class skeleton. * - * @param string $className Name of the Migration class to generate + * @param string $className Name of the Migration class to generate * @param string $migrationsPath Path to directory which contains your migration classes */ public static function generateMigrationClass($className, $migrationsPath) @@ -1052,10 +1053,10 @@ public static function generateMigrationClass($className, $migrationsPath) } /** - * Generate a set of migration classes from an existing database + * Generate a set of migration classes from an existing database. * * @param string $migrationsPath - * @return void + * * @throws new Doctrine_Migration_Exception */ public static function generateMigrationsFromDb($migrationsPath) @@ -1066,12 +1067,11 @@ public static function generateMigrationsFromDb($migrationsPath) } /** - * Generate a set of migration classes from an existing set of models + * Generate a set of migration classes from an existing set of models. * - * @param string $migrationsPath Path to your Doctrine migration classes - * @param string $modelsPath Path to your Doctrine model classes - * @param integer $modelLoading Style of model loading to use for loading the models in order to generate migrations - * @return void + * @param string $migrationsPath Path to your Doctrine migration classes + * @param string $modelsPath Path to your Doctrine model classes + * @param int $modelLoading Style of model loading to use for loading the models in order to generate migrations */ public static function generateMigrationsFromModels($migrationsPath, $modelsPath = null, $modelLoading = null) { @@ -1082,11 +1082,12 @@ public static function generateMigrationsFromModels($migrationsPath, $modelsPath /** * Generate a set of migration classes by generating differences between two sets - * of schema information + * of schema information. + * + * @param string $migrationsPath Path to your Doctrine migration classes + * @param string $from From schema information + * @param string $to To schema information * - * @param string $migrationsPath Path to your Doctrine migration classes - * @param string $from From schema information - * @param string $to To schema information * @return array $changes */ public static function generateMigrationsFromDiff($migrationsPath, $from, $to) @@ -1097,9 +1098,10 @@ public static function generateMigrationsFromDiff($migrationsPath, $from, $to) } /** - * Get the Doctrine_Table object for the passed model + * Get the Doctrine_Table object for the passed model. * * @param string $componentName + * * @return Doctrine_Table */ public static function getTable($componentName) @@ -1110,12 +1112,12 @@ public static function getTable($componentName) /** * Method for making a single file of most used doctrine runtime components * including the compiled file instead of multiple files (in worst - * cases dozens of files) can improve performance by an order of magnitude + * cases dozens of files) can improve performance by an order of magnitude. * * @param string $target * @param array $includedDrivers + * * @throws Doctrine_Exception - * @return void */ public static function compile($target = null, $includedDrivers = array()) { @@ -1124,15 +1126,16 @@ public static function compile($target = null, $includedDrivers = array()) /** * simple autoload function - * returns true if the class was loaded, otherwise false + * returns true if the class was loaded, otherwise false. * * @param string $className - * @return boolean + * + * @return bool */ public static function autoload($className) { - if (strpos($className, 'sfYaml') === 0) { - require dirname(__FILE__) . '/Parser/sfYaml/' . $className . '.php'; + if (0 === strpos($className, 'sfYaml')) { + require dirname(__FILE__).'/Parser/sfYaml/'.$className.'.php'; return true; } @@ -1141,7 +1144,7 @@ public static function autoload($className) return false; } - $class = self::getPath() . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; + $class = self::getPath().DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $className).'.php'; if (file_exists($class)) { require $class; @@ -1158,7 +1161,7 @@ public static function modelsAutoload($className) return false; } - if ( ! self::$_modelsDirectory) { + if (!self::$_modelsDirectory) { $loadedModels = self::$_loadedModelFiles; if (isset($loadedModels[$className]) && file_exists($loadedModels[$className])) { @@ -1167,7 +1170,7 @@ public static function modelsAutoload($className) return true; } } else { - $class = self::$_modelsDirectory . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; + $class = self::$_modelsDirectory.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $className).'.php'; if (file_exists($class)) { require $class; @@ -1180,10 +1183,11 @@ public static function modelsAutoload($className) } /** - * Load classes from the Doctrine extensions directory/path + * Load classes from the Doctrine extensions directory/path. * * @param string $className - * @return boolean + * + * @return bool */ public static function extensionsAutoload($className) { @@ -1192,10 +1196,11 @@ public static function extensionsAutoload($className) } $extensions = Doctrine_Manager::getInstance() - ->getExtensions(); + ->getExtensions() + ; foreach ($extensions as $name => $path) { - $class = $path . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; + $class = $path.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $className).'.php'; if (file_exists($class)) { require $class; @@ -1208,36 +1213,36 @@ public static function extensionsAutoload($className) } /** - * dumps a given variable + * dumps a given variable. + * + * @param mixed $var a variable of any type + * @param bool $output whether to output the content + * @param string $indent indention string * - * @param mixed $var a variable of any type - * @param boolean $output whether to output the content - * @param string $indent indention string * @return void|string */ - public static function dump($var, $output = true, $indent = "") + public static function dump($var, $output = true, $indent = '') { $ret = array(); switch (gettype($var)) { case 'array': $ret[] = 'Array('; - $indent .= " "; + $indent .= ' '; foreach ($var as $k => $v) { - - $ret[] = $indent . $k . ' : ' . self::dump($v, false, $indent); + $ret[] = $indent.$k.' : '.self::dump($v, false, $indent); } - $indent = substr($indent,0, -4); - $ret[] = $indent . ")"; + $indent = substr($indent, 0, -4); + $ret[] = $indent.')'; break; case 'object': - $ret[] = 'Object(' . get_class($var) . ')'; + $ret[] = 'Object('.get_class($var).')'; break; default: $ret[] = var_export($var, true); } if ($output) { - print implode("\n", $ret); + echo implode("\n", $ret); } return implode("\n", $ret); diff --git a/lib/Doctrine/Data.php b/lib/Doctrine/Data.php index b9bcd118d..46cc8d210 100644 --- a/lib/Doctrine/Data.php +++ b/lib/Doctrine/Data.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Data + * Doctrine_Data. * * Base Doctrine_Data class for dumping and loading data to and from fixtures files. * Support formats are based on what formats are available in Doctrine_Parser such as yaml, xml, json, etc. * - * @package Doctrine - * @subpackage Data * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2552 $ */ class Doctrine_Data { /** - * formats + * formats. * * array of formats data can be in * @@ -45,7 +45,7 @@ class Doctrine_Data protected $_formats = array('csv', 'yml', 'xml'); /** - * format + * format. * * the default and current format we are working with * @@ -54,16 +54,16 @@ class Doctrine_Data protected $_format = 'yml'; /** - * directory + * directory. * * array of directory/yml paths or single directory/yml file * * @var string */ - protected $_directory = null; + protected $_directory; /** - * models + * models. * * specified array of models to use * @@ -72,7 +72,7 @@ class Doctrine_Data protected $_models = array(); /** - * _exportIndividualFiles + * _exportIndividualFiles. * * whether or not to export data to individual files instead of 1 * @@ -83,12 +83,11 @@ class Doctrine_Data protected $_charset = 'UTF-8'; /** - * setFormat + * setFormat. * * Set the current format we are working with * * @param string $format - * @return void */ public function setFormat($format) { @@ -96,11 +95,9 @@ public function setFormat($format) } /** - * getFormat + * getFormat. * * Get the current format we are working with - * - * @return void */ public function getFormat() { @@ -108,11 +105,9 @@ public function getFormat() } /** - * getFormats + * getFormats. * * Get array of available formats - * - * @return void */ public function getFormats() { @@ -120,11 +115,9 @@ public function getFormats() } /** - * setDirectory + * setDirectory. * * Set the array/string of directories or yml file paths - * - * @return void */ public function setDirectory($directory) { @@ -132,11 +125,9 @@ public function setDirectory($directory) } /** - * getDirectory + * getDirectory. * * Get directory for dumping/loading data from and to - * - * @return void */ public function getDirectory() { @@ -144,12 +135,11 @@ public function getDirectory() } /** - * setModels + * setModels. * * Set the array of specified models to work with * * @param string $models - * @return void */ public function setModels($models) { @@ -157,11 +147,9 @@ public function setModels($models) } /** - * getModels + * getModels. * * Get the array of specified models to work with - * - * @return void */ public function getModels() { @@ -169,15 +157,17 @@ public function getModels() } /** - * _exportIndividualFiles + * _exportIndividualFiles. * * Set/Get whether or not to export individual files * + * @param mixed|null $bool + * * @return bool $_exportIndividualFiles */ public function exportIndividualFiles($bool = null) { - if ($bool !== null) { + if (null !== $bool) { $this->_exportIndividualFiles = $bool; } @@ -195,7 +185,7 @@ public function getCharset() } /** - * exportData + * exportData. * * Interface for exporting data to fixtures files from Doctrine models * @@ -203,7 +193,6 @@ public function getCharset() * @param string $format * @param string $models * @param string $_exportIndividualFiles - * @return void */ public function exportData($directory, $format = 'yml', $models = array(), $_exportIndividualFiles = false) { @@ -216,14 +205,13 @@ public function exportData($directory, $format = 'yml', $models = array(), $_exp } /** - * importData + * importData. * * Interface for importing data from fixture files to Doctrine models * * @param string $directory * @param string $format * @param string $models - * @return void */ public function importData($directory, $format = 'yml', $models = array(), $append = false, $charset = 'UTF-8') { @@ -236,13 +224,11 @@ public function importData($directory, $format = 'yml', $models = array(), $appe } /** - * isRelation + * isRelation. * * Check if a fieldName on a Doctrine_Record is a relation, if it is we return that relationData * - * @param string $Doctrine_Record * @param string $fieldName - * @return void */ public function isRelation(Doctrine_Record $record, $fieldName) { @@ -254,19 +240,17 @@ public function isRelation(Doctrine_Record $record, $fieldName) if ($relationData['local'] === $fieldName) { return $relationData; } - } return false; } /** - * purge + * purge. * * Purge all data for loaded models or for the passed array of Doctrine_Records * * @param string $models - * @return void */ public function purge($models = null) { @@ -278,7 +262,7 @@ public function purge($models = null) $connections = array(); foreach ($models as $model) { - $connections[Doctrine_Core::getTable($model)->getConnection()->getName()][] = $model; + $connections[Doctrine_Core::getTable($model)->getConnection()->getName()][] = $model; } foreach ($connections as $connection => $models) { diff --git a/lib/Doctrine/Data/Exception.php b/lib/Doctrine/Data/Exception.php index a59755781..42cc76309 100644 --- a/lib/Doctrine/Data/Exception.php +++ b/lib/Doctrine/Data/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Data_Exception + * Doctrine_Data_Exception. * - * @package Doctrine - * @subpackage Data * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2552 $ */ class Doctrine_Data_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Data/Export.php b/lib/Doctrine/Data/Export.php index 41dedfa82..9966c05c1 100644 --- a/lib/Doctrine/Data/Export.php +++ b/lib/Doctrine/Data/Export.php @@ -20,23 +20,22 @@ */ /** - * Doctrine_Data_Export + * Doctrine_Data_Export. * - * @package Doctrine - * @subpackage Data * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2552 $ */ class Doctrine_Data_Export extends Doctrine_Data { /** - * constructor + * constructor. * - * @param string $directory - * @return void + * @param string $directory */ public function __construct($directory) { @@ -44,18 +43,16 @@ public function __construct($directory) } /** - * doExport + * doExport. * - * FIXME: This function has ugly hacks in it for temporarily disabling INDEXBY query parts of tables + * FIXME: This function has ugly hacks in it for temporarily disabling INDEXBY query parts of tables * to export. * * Update from jwage: I am not sure if their is any other better solution for this. It may be the correct - * solution to disable the indexBy settings for tables when exporting data fixtures. Maybe a better idea - * would be to extract this functionality to a pair of functions to enable/disable the index by settings - * so simply turn them on and off when they need to query for the translations standalone and don't need + * solution to disable the indexBy settings for tables when exporting data fixtures. Maybe a better idea + * would be to extract this functionality to a pair of functions to enable/disable the index by settings + * so simply turn them on and off when they need to query for the translations standalone and don't need * it to be indexed by the lang. - * - * @return void */ public function doExport() { @@ -64,25 +61,25 @@ public function doExport() $data = array(); - // for situation when the $models array is empty, but the $specifiedModels array isn't + // for situation when the $models array is empty, but the $specifiedModels array isn't if (empty($models)) { - $models = $specifiedModels; + $models = $specifiedModels; } $models = Doctrine_Core::initializeModels($models); // temporarily disable indexBy query parts of selected and related tables $originalIndexBy = array(); - foreach ($models AS $name) { - $table = Doctrine_Core::getTable($name); - if ( !is_null($indexBy = $table->getBoundQueryPart('indexBy'))) { - $originalIndexBy[$name] = $indexBy; - $table->bindQueryPart('indexBy', null); - } + foreach ($models as $name) { + $table = Doctrine_Core::getTable($name); + if (!is_null($indexBy = $table->getBoundQueryPart('indexBy'))) { + $originalIndexBy[$name] = $indexBy; + $table->bindQueryPart('indexBy', null); + } } - foreach ($models AS $name) { - if ( ! empty($specifiedModels) AND ! in_array($name, $specifiedModels)) { + foreach ($models as $name) { + if (!empty($specifiedModels) and !in_array($name, $specifiedModels)) { continue; } @@ -94,7 +91,7 @@ public function doExport() } // Restore the temporarily disabled indexBy query parts - foreach($originalIndexBy AS $name => $indexBy) { + foreach ($originalIndexBy as $name => $indexBy) { Doctrine_Core::getTable($name)->bindQueryPart('indexBy', $indexBy); } @@ -104,12 +101,9 @@ public function doExport() } /** - * dumpData + * dumpData. * * Dump the prepared data to the fixtures files - * - * @param string $array - * @return void */ public function dumpData(array $data) { @@ -119,44 +113,46 @@ public function dumpData(array $data) if ($this->exportIndividualFiles()) { if (is_array($directory)) { throw new Doctrine_Data_Exception('You must specify a single path to a folder in order to export individual files.'); - } else if ( ! is_dir($directory) && is_file($directory)) { + } + if (!is_dir($directory) && is_file($directory)) { $directory = dirname($directory); } foreach ($data as $className => $classData) { - if ( ! empty($classData)) { + if (!empty($classData)) { Doctrine_Parser::dump(array($className => $classData), $format, $directory.DIRECTORY_SEPARATOR.$className.'.'.$format); } } } else { if (is_dir($directory)) { - $directory .= DIRECTORY_SEPARATOR . 'data.' . $format; + $directory .= DIRECTORY_SEPARATOR.'data.'.$format; } - if ( ! empty($data)) { + if (!empty($data)) { return Doctrine_Parser::dump($data, $format, $directory); } } } /** - * prepareData + * prepareData. * * Prepare the raw data to be exported with the parser * - * @param string $data + * @param string $data + * * @return array */ public function prepareData($data) { $preparedData = array(); - foreach ($data AS $className => $classData) { + foreach ($data as $className => $classData) { $preparedData[$className] = array(); $keyType = $classData->getTable()->getIdentifierType(); foreach ($classData as $record) { $className = get_class($record); - $recordKey = $className . '_' . implode('_', $record->identifier()); + $recordKey = $className.'_'.implode('_', $record->identifier()); $preparedData[$className][$recordKey] = array(); // skip single primary keys, we need to maintain composite primary keys @@ -165,11 +161,11 @@ public function prepareData($data) $recordData = $record->toArray(false); foreach ($recordData as $key => $value) { - if ( ! is_array($keys)) { - $keys = array($keys); + if (!is_array($keys)) { + $keys = array($keys); } - if ($keyType !== Doctrine_Core::IDENTIFIER_NATURAL && count($keys) <= 1 && in_array($key, $keys)) { + if (Doctrine_Core::IDENTIFIER_NATURAL !== $keyType && count($keys) <= 1 && in_array($key, $keys)) { continue; } @@ -179,11 +175,11 @@ public function prepareData($data) } if ($relation = $this->isRelation($record, $key)) { - if ( ! $value) { + if (!$value) { continue; } $relationAlias = $relation['alias']; - $relationRecord = $record->$relationAlias; + $relationRecord = $record->{$relationAlias}; // If collection then get first so we have an instance of the related record if ($relationRecord instanceof Doctrine_Collection) { @@ -191,23 +187,23 @@ public function prepareData($data) } // If relation is null or does not exist then continue - if ($relationRecord instanceof Doctrine_Null || ! $relationRecord) { + if ($relationRecord instanceof Doctrine_Null || !$relationRecord) { continue; } // Get class name for relation $relationClassName = get_class($relationRecord); - $relationValue = $relationClassName . '_' . $value; + $relationValue = $relationClassName.'_'.$value; $preparedData[$className][$recordKey][$relationAlias] = $relationValue; - } else if ($record->getTable()->hasField($key)) { + } elseif ($record->getTable()->hasField($key)) { $preparedData[$className][$recordKey][$key] = $value; } } } } - + return $preparedData; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Data/Import.php b/lib/Doctrine/Data/Import.php index 23d0f6079..20fc08f6c 100644 --- a/lib/Doctrine/Data/Import.php +++ b/lib/Doctrine/Data/Import.php @@ -20,69 +20,68 @@ */ /** - * Doctrine_Data_Import + * Doctrine_Data_Import. * - * @package Doctrine - * @package Data * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2552 $ */ class Doctrine_Data_Import extends Doctrine_Data { /** - * Array of imported objects for processing and saving + * Array of imported objects for processing and saving. * * @var array */ protected $_importedObjects = array(); /** - * Array of the raw data parsed from yaml + * Array of the raw data parsed from yaml. * * @var array */ protected $_rows = array(); /** - * Optionally pass the directory/path to the yaml for importing + * Optionally pass the directory/path to the yaml for importing. * * @param string $directory - * @return void */ public function __construct($directory = null) { - if ($directory !== null) { + if (null !== $directory) { $this->setDirectory($directory); } } /** - * Do the parsing of the yaml files and return the final parsed array + * Do the parsing of the yaml files and return the final parsed array. * * @return array $array */ public function doParsing() { $recursiveMerge = Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_RECURSIVE_MERGE_FIXTURES); - $mergeFunction = $recursiveMerge === true ? 'array_merge_recursive':'array_merge'; + $mergeFunction = true === $recursiveMerge ? 'array_merge_recursive' : 'array_merge'; $directory = $this->getDirectory(); $array = array(); - if ($directory !== null) { + if (null !== $directory) { foreach ((array) $directory as $dir) { $e = explode('.', $dir); // If they specified a specific yml file - if (end($e) == 'yml') { + if ('yml' == end($e)) { $array = $mergeFunction($array, Doctrine_Parser::load($dir, $this->getFormat(), $this->getCharset())); // If they specified a directory - } else if (is_dir($dir)) { + } elseif (is_dir($dir)) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), - RecursiveIteratorIterator::LEAVES_ONLY); + RecursiveIteratorIterator::LEAVES_ONLY); $filesOrdered = array(); foreach ($it as $file) { $filesOrdered[] = $file; @@ -103,15 +102,13 @@ public function doParsing() } /** - * Do the importing of the data parsed from the fixtures - * - * @return void + * Do the importing of the data parsed from the fixtures. */ public function doImport($append = false) { $array = $this->doParsing(); - if ( ! $append) { + if (!$append) { $this->purge(array_reverse(array_keys($array))); } @@ -119,9 +116,7 @@ public function doImport($append = false) } /** - * Recursively loop over all data fixtures and build the array of className rows - * - * @return void + * Recursively loop over all data fixtures and build the array of className rows. */ protected function _buildRows($className, $data) { @@ -132,14 +127,14 @@ protected function _buildRows($className, $data) $this->_rows[$className][$rowKey] = $row; foreach ((array) $row as $key => $value) { - if ($table->hasRelation($key) && is_array($value) && ! $table->hasTemplate('Doctrine_Template_I18n')) { + if ($table->hasRelation($key) && is_array($value) && !$table->hasTemplate('Doctrine_Template_I18n')) { // Skip associative arrays defining keys to relationships - if ( ! isset($value[0]) || (isset($value[0]) && is_array($value[0]))) { + if (!isset($value[0]) || (isset($value[0]) && is_array($value[0]))) { $rel = $table->getRelation($key); $relClassName = $rel->getTable()->getOption('name'); - $relRowKey = $rowKey . '_' . $relClassName; + $relRowKey = $rowKey.'_'.$relClassName; - if ($rel->getType() == Doctrine_Relation::ONE) { + if (Doctrine_Relation::ONE == $rel->getType()) { $val = array($relRowKey => $value); $this->_rows[$className][$rowKey][$key] = $relRowKey; } else { @@ -155,14 +150,12 @@ protected function _buildRows($className, $data) } /** - * Build the rows for nested set models - * - * @return void + * Build the rows for nested set models. */ protected function _buildNestedSetRows($className, $data) { foreach ($data as $rowKey => $row) { - $children = isset($row['children']) ? $row['children']:array(); + $children = isset($row['children']) ? $row['children'] : array(); unset($row['children']); $this->_rows[$className][$rowKey] = $row; @@ -172,123 +165,116 @@ protected function _buildNestedSetRows($className, $data) /** * Get the unsaved object for a specified row key and validate that it is the valid object class - * for the passed record and relation name + * for the passed record and relation name. + * + * @param string $rowKey + * @param string $relationName + * @param string $referringRowKey * - * @param string $rowKey - * @param Doctrine_Record $record - * @param string $relationName - * @param string $referringRowKey * @return Doctrine_Record + * * @throws Doctrine_Data_Exception */ protected function _getImportedObject($rowKey, Doctrine_Record $record, $relationName, $referringRowKey) { $relation = $record->getTable()->getRelation($relationName); - $rowKey = $this->_getRowKeyPrefix($relation->getTable()) . $rowKey; + $rowKey = $this->_getRowKeyPrefix($relation->getTable()).$rowKey; - if ( ! isset($this->_importedObjects[$rowKey])) { - throw new Doctrine_Data_Exception( - sprintf('Invalid row key specified: %s, referred to in %s', $rowKey, $referringRowKey) - ); + if (!isset($this->_importedObjects[$rowKey])) { + throw new Doctrine_Data_Exception(sprintf('Invalid row key specified: %s, referred to in %s', $rowKey, $referringRowKey)); } $relatedRowKeyObject = $this->_importedObjects[$rowKey]; $relationClass = $relation->getClass(); - if ( ! $relatedRowKeyObject instanceof $relationClass) { - throw new Doctrine_Data_Exception(sprintf( - 'Class referred to in "%s" is expected to be "%s" and "%s" was given', - $referringRowKey, $relation->getClass(), get_class($relatedRowKeyObject) - )); + if (!$relatedRowKeyObject instanceof $relationClass) { + throw new Doctrine_Data_Exception(sprintf('Class referred to in "%s" is expected to be "%s" and "%s" was given', $referringRowKey, $relation->getClass(), get_class($relatedRowKeyObject))); } return $relatedRowKeyObject; } /** - * Process a row and make all the appropriate relations between the imported data + * Process a row and make all the appropriate relations between the imported data. * * @param string $rowKey * @param string $row - * @return void */ protected function _processRow($rowKey, $row) { $obj = $this->_importedObjects[$rowKey]; foreach ((array) $row as $key => $value) { - if (method_exists($obj, 'set' . Doctrine_Inflector::classify($key))) { - $func = 'set' . Doctrine_Inflector::classify($key); - $obj->$func($value); - } else if ($obj->getTable()->hasField($key)) { - if ($obj->getTable()->getTypeOf($key) == 'object') { + if (method_exists($obj, 'set'.Doctrine_Inflector::classify($key))) { + $func = 'set'.Doctrine_Inflector::classify($key); + $obj->{$func}($value); + } elseif ($obj->getTable()->hasField($key)) { + if ('object' == $obj->getTable()->getTypeOf($key)) { $value = unserialize($value); } $obj->set($key, $value); - } else if ($obj->getTable()->hasRelation($key)) { + } elseif ($obj->getTable()->hasRelation($key)) { if (is_array($value)) { - if (isset($value[0]) && ! is_array($value[0])) { + if (isset($value[0]) && !is_array($value[0])) { foreach ($value as $link) { - if ($obj->getTable()->getRelation($key)->getType() === Doctrine_Relation::ONE) { + if (Doctrine_Relation::ONE === $obj->getTable()->getRelation($key)->getType()) { $obj->set($key, $this->_getImportedObject($link, $obj, $key, $rowKey)); - } else if ($obj->getTable()->getRelation($key)->getType() === Doctrine_Relation::MANY) { - $relation = $obj->$key; + } elseif (Doctrine_Relation::MANY === $obj->getTable()->getRelation($key)->getType()) { + $relation = $obj->{$key}; $relation[] = $this->_getImportedObject($link, $obj, $key, $rowKey); } } } else { - $obj->$key->fromArray($value); + $obj->{$key}->fromArray($value); } } else { $obj->set($key, $this->_getImportedObject($value, $obj, $key, $rowKey)); } } else { try { - $obj->$key = $value; + $obj->{$key} = $value; } catch (Exception $e) { // used for Doctrine plugin methods (Doctrine_Template) - if (is_callable(array($obj, 'set' . Doctrine_Inflector::classify($key)))) { - $func = 'set' . Doctrine_Inflector::classify($key); - $obj->$func($value); + if (is_callable(array($obj, 'set'.Doctrine_Inflector::classify($key)))) { + $func = 'set'.Doctrine_Inflector::classify($key); + $obj->{$func}($value); } else { - throw new Doctrine_Data_Exception('Invalid fixture element "'. $key . '" under "' . $rowKey . '"'); + throw new Doctrine_Data_Exception('Invalid fixture element "'.$key.'" under "'.$rowKey.'"'); } } } } } - /** - * NestedSet fixtures may come in a 'natural' format with nested children listed under a 'children' - * key or in a raw, non-nested format with lft/rgt values. - * - * This method returns true if the given $data is a nested set in 'natural' form. - * - * @param $className - * @param $data - * @return boolean - */ + /** + * NestedSet fixtures may come in a 'natural' format with nested children listed under a 'children' + * key or in a raw, non-nested format with lft/rgt values. + * + * This method returns true if the given $data is a nested set in 'natural' form. + * + * @return bool + */ protected function _hasNaturalNestedSetFormat($className, array &$data) { if (Doctrine_Core::getTable($className)->isTree()) { - if (isset($data['NestedSet']) && $data['NestedSet'] == true) { + if (isset($data['NestedSet']) && true == $data['NestedSet']) { unset($data['NestedSet']); + return true; - } else { - $first = current($data); - return array_key_exists('children', $first); } - } else { - return false; + $first = current($data); + + return array_key_exists('children', $first); } + + return false; } /** - * Perform the loading of the data from the passed array + * Perform the loading of the data from the passed array. * * @param string $array - * @return void */ protected function _loadData(array $array) { @@ -298,7 +284,7 @@ protected function _loadData(array $array) $rows = array(); foreach ($array as $className => $data) { - if ( ! empty($specifiedModels) && !in_array($className, $specifiedModels)) { + if (!empty($specifiedModels) && !in_array($className, $specifiedModels)) { continue; } @@ -316,14 +302,14 @@ protected function _loadData(array $array) foreach ($this->_rows as $className => $classRows) { $rowKeyPrefix = $this->_getRowKeyPrefix(Doctrine_Core::getTable($className)); foreach ($classRows as $rowKey => $row) { - $rowKey = $rowKeyPrefix . $rowKey; + $rowKey = $rowKeyPrefix.$rowKey; $buildRows[$rowKey] = $row; $this->_importedObjects[$rowKey] = new $className(); $this->_importedObjects[$rowKey]->state('TDIRTY'); } } - foreach($buildRows as $rowKey => $row) { + foreach ($buildRows as $rowKey => $row) { $this->_processRow($rowKey, $row); } @@ -341,7 +327,6 @@ protected function _loadData(array $array) $connection->beginTransaction(); foreach ($tree as $model) { foreach ($this->_importedObjects as $obj) { - if ($obj instanceof $model) { $obj->save(); } @@ -352,18 +337,17 @@ protected function _loadData(array $array) } /** - * Load nested set data for models with nested set enabled + * Load nested set data for models with nested set enabled. * * @param string $model * @param string $nestedSetData * @param string $parent - * @return void */ protected function _loadNestedSetData($model, $nestedSetData, $parent = null) { - foreach($nestedSetData AS $rowKey => $nestedSet) { + foreach ($nestedSetData as $rowKey => $nestedSet) { $children = array(); - $data = array(); + $data = array(); if (array_key_exists('children', $nestedSet)) { $children = (array) $nestedSet['children']; @@ -371,20 +355,20 @@ protected function _loadNestedSetData($model, $nestedSetData, $parent = null) unset($nestedSet['children']); } - $rowKey = $this->_getRowKeyPrefix(Doctrine_Core::getTable($model)) . $rowKey; + $rowKey = $this->_getRowKeyPrefix(Doctrine_Core::getTable($model)).$rowKey; $record = $this->_importedObjects[$rowKey]; // remove this nested set from _importedObjects so it's not processed in the save routine for normal objects unset($this->_importedObjects[$rowKey]); - if ( ! $parent) { + if (!$parent) { $record->save(); // save, so that createRoot can do: root id = id Doctrine_Core::getTable($model)->getTree()->createRoot($record); } else { $parent->getNode()->addChild($record); } - if (is_array($children) AND !empty($children)) { + if (is_array($children) and !empty($children)) { $this->_loadNestedSetData($model, $children, $record); } } @@ -393,7 +377,6 @@ protected function _loadNestedSetData($model, $nestedSetData, $parent = null) /** * Returns the prefix to use when indexing an object from the supplied table. * - * @param Doctrine_Table $table * @return string */ protected function _getRowKeyPrefix(Doctrine_Table $table) diff --git a/lib/Doctrine/DataDict.php b/lib/Doctrine/DataDict.php index 6b759259e..25bca80a8 100644 --- a/lib/Doctrine/DataDict.php +++ b/lib/Doctrine/DataDict.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_DataDict + * Doctrine_DataDict. * - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) */ @@ -35,20 +36,22 @@ class Doctrine_DataDict extends Doctrine_Connection_Module { /** * parseBoolean - * parses a literal boolean value and returns - * proper sql equivalent + * parses a literal boolean value and returns + * proper sql equivalent. * - * @param string $value boolean value to be parsed - * @return string parsed boolean value + * @param string $value boolean value to be parsed + * + * @return string parsed boolean value */ public function parseBoolean($value) { // parse booleans - if ($value == 'true') { + if ('true' == $value) { $value = 1; - } elseif ($value == 'false') { + } elseif ('false' == $value) { $value = 0; } + return $value; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/DataDict/Exception.php b/lib/Doctrine/DataDict/Exception.php index 41d07b4f6..edfad298c 100644 --- a/lib/Doctrine/DataDict/Exception.php +++ b/lib/Doctrine/DataDict/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_DataDict_Exception + * Doctrine_DataDict_Exception. * - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_DataDict_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/DataDict/Mssql.php b/lib/Doctrine/DataDict/Mssql.php index 59220b3a1..762badac8 100644 --- a/lib/Doctrine/DataDict/Mssql.php +++ b/lib/Doctrine/DataDict/Mssql.php @@ -20,15 +20,15 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @author Frank M. Kromann (PEAR MDB2 Mssql driver) * @author David Coallier (PEAR MDB2 Mssql driver) + * * @version $Revision: 7660 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Mssql extends Doctrine_DataDict @@ -37,9 +37,9 @@ class Doctrine_DataDict_Mssql extends Doctrine_DataDict * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -53,17 +53,18 @@ class Doctrine_DataDict_Mssql extends Doctrine_DataDict * Boolean flag that indicates whether this field is constrained * to not be set to null. * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration($field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } switch ($field['type']) { case 'enum': - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + // no break case 'array': case 'object': case 'text': @@ -74,25 +75,27 @@ public function getNativeDeclaration($field) $length = !empty($field['length']) ? $field['length'] : false; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || 'char' == $field['type']) ? true : false; return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$this->conn->varchar_max_length.')') : (($length && $length <= $this->conn->varchar_max_length) ? 'VARCHAR('.$length.')' : 'TEXT'); case 'clob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 8000) { return 'VARCHAR('.$length.')'; } - } - return 'TEXT'; + } + + return 'TEXT'; case 'blob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 8000) { - return "VARBINARY($length)"; + return "VARBINARY({$length})"; } } + return 'IMAGE'; case 'integer': case 'int': @@ -100,79 +103,84 @@ public function getNativeDeclaration($field) case 'boolean': return 'BIT'; case 'date': - return 'CHAR(' . strlen('YYYY-MM-DD') . ')'; + return 'CHAR('.strlen('YYYY-MM-DD').')'; case 'time': - return 'CHAR(' . strlen('HH:MM:SS') . ')'; + return 'CHAR('.strlen('HH:MM:SS').')'; case 'timestamp': - return 'CHAR(' . strlen('YYYY-MM-DD HH:MM:SS') . ')'; + return 'CHAR('.strlen('YYYY-MM-DD HH:MM:SS').')'; case 'float': return 'FLOAT'; case 'decimal': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'DECIMAL('.$length.','.$scale.')'; } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to a MDB2 datatype and length + * Maps a native array description of a field to a MDB2 datatype and length. + * + * @param array $field native field description * - * @param array $field native field description - * @return array containing the various possible types, length, sign, fixed + * @return array containing the various possible types, length, sign, fixed */ public function getPortableDeclaration($field) { - $db_type = preg_replace('/[\d\(\)]/','', strtolower($field['type']) ); - $length = (isset($field['length']) && $field['length'] > 0) ? $field['length'] : null; + $db_type = preg_replace('/[\d\(\)]/', '', strtolower($field['type'])); + $length = (isset($field['length']) && $field['length'] > 0) ? $field['length'] : null; $type = array(); // todo: unsigned handling seems to be missing $unsigned = $fixed = null; - if ( ! isset($field['name'])) + if (!isset($field['name'])) { $field['name'] = ''; + } switch ($db_type) { case 'bit': $type[0] = 'boolean'; - break; + break; case 'tinyint': case 'smallint': case 'bigint': case 'int': $type[0] = 'integer'; - if ($length == 1) { + if (1 == $length) { $type[] = 'boolean'; } - break; - case 'date': - $type[0] = 'date'; - break; + break; + case 'date': + $type[0] = 'date'; + break; case 'datetime': case 'timestamp': case 'smalldatetime': $type[0] = 'timestamp'; - break; + break; case 'float': case 'real': case 'numeric': $type[0] = 'float'; - break; + break; case 'decimal': case 'money': case 'smallmoney': $type[0] = 'decimal'; - break; + break; case 'text': case 'varchar': case 'ntext': case 'nvarchar': $fixed = false; + // no break case 'char': case 'nchar': $type[0] = 'string'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^[is|has]/', $field['name'])) { $type = array_reverse($type); @@ -180,45 +188,45 @@ public function getPortableDeclaration($field) } elseif (strstr($db_type, 'text')) { $type[] = 'clob'; } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } - break; + break; case 'image': case 'varbinary': $type[] = 'blob'; $length = null; - break; + break; case 'uniqueidentifier': $type[] = 'string'; $length = 36; - break; + break; case 'sql_variant': case 'sysname': case 'binary': $type[] = 'string'; $length = null; - break; + break; default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - return array('type' => $type, - 'length' => $length, - 'unsigned' => $unsigned, - 'fixed' => $fixed); + return array('type' => $type, + 'length' => $length, + 'unsigned' => $unsigned, + 'fixed' => $fixed); } /** * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param string $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: + * @param string $name name the field to be declared + * @param string $field associative array with the name of the properties + * of the field being declared as array indexes. + * Currently, the types of supported field + * properties are as follows: * * unsigned * Boolean flag that indicates whether the field @@ -232,16 +240,17 @@ public function getPortableDeclaration($field) * notnull * Boolean flag that indicates whether this field is * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getIntegerDeclaration($name, $field) { $default = $autoinc = ''; - if ( ! empty($field['autoincrement'])) { + if (!empty($field['autoincrement'])) { $autoinc = ' identity'; } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : 0; } @@ -251,23 +260,22 @@ public function getIntegerDeclaration($name, $field) // Name the constraint if a name has been supplied if (array_key_exists('defaultConstraintName', $field)) { - $default .= ' CONSTRAINT ' . $field['defaultConstraintName']; + $default .= ' CONSTRAINT '.$field['defaultConstraintName']; } - $default .= ' DEFAULT ' . $value; + $default .= ' DEFAULT '.$value; } - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ' NULL'; - //$unsigned = (isset($field['unsigned']) && $field['unsigned']) ? ' UNSIGNED' : ''; + // $unsigned = (isset($field['unsigned']) && $field['unsigned']) ? ' UNSIGNED' : ''; // MSSQL does not support the UNSIGNED keyword $unsigned = ''; - $comment = (isset($field['comment']) && $field['comment']) - ? " COMMENT " . $this->conn->quote($field['comment'], 'text') : ''; + $comment = (isset($field['comment']) && $field['comment']) + ? ' COMMENT '.$this->conn->quote($field['comment'], 'text') : ''; $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $this->getNativeDeclaration($field) . $unsigned - . $default . $notnull . $autoinc . $comment; + return $name.' '.$this->getNativeDeclaration($field).$unsigned + .$default.$notnull.$autoinc.$comment; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/DataDict/Mysql.php b/lib/Doctrine/DataDict/Mysql.php index 3bb9d26cc..067a26171 100644 --- a/lib/Doctrine/DataDict/Mysql.php +++ b/lib/Doctrine/DataDict/Mysql.php @@ -20,101 +20,101 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7635 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Mysql extends Doctrine_DataDict { protected $keywords = array( - 'ADD', 'ALL', 'ALTER', - 'ANALYZE', 'AND', 'AS', - 'ASC', 'ASENSITIVE', 'BEFORE', - 'BETWEEN', 'BIGINT', 'BINARY', - 'BLOB', 'BOTH', 'BY', 'BIT', - 'CALL', 'CASCADE', 'CASE', - 'CHANGE', 'CHAR', 'CHARACTER', - 'CHECK', 'COLLATE', 'COLUMN', - 'CONDITION', 'CONNECTION', 'CONSTRAINT', - 'CONTINUE', 'CONVERT', 'CREATE', - 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', - 'DATABASE', 'DATABASES', 'DAY_HOUR', - 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', - 'DEC', 'DECIMAL', 'DECLARE', - 'DEFAULT', 'DELAYED', 'DELETE', - 'DESC', 'DESCRIBE', 'DETERMINISTIC', - 'DISTINCT', 'DISTINCTROW', 'DIV', - 'DOUBLE', 'DROP', 'DUAL', - 'EACH', 'ELSE', 'ELSEIF', - 'ENCLOSED', 'ESCAPED', 'EXISTS', - 'EXIT', 'EXPLAIN', 'FALSE', - 'FETCH', 'FLOAT', 'FLOAT4', - 'FLOAT8', 'FOR', 'FORCE', - 'FOREIGN', 'FROM', 'FULLTEXT', - 'GRANT', 'GROUP', 'HAVING', - 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', - 'HOUR_SECOND', 'IF', 'IGNORE', - 'IN', 'INDEX', 'INFILE', - 'INNER', 'INOUT', 'INSENSITIVE', - 'INSERT', 'INT', 'INT1', - 'INT2', 'INT3', 'INT4', - 'INT8', 'INTEGER', 'INTERVAL', - 'INTO', 'IS', 'ITERATE', - 'JOIN', 'KEY', 'KEYS', - 'KILL', 'LEADING', 'LEAVE', - 'LEFT', 'LIKE', 'LIMIT', - 'LINES', 'LOAD', 'LOCALTIME', - 'LOCALTIMESTAMP', 'LOCK', 'LONG', - 'LONGBLOB', 'LONGTEXT', 'LOOP', - 'LOW_PRIORITY', 'MATCH', 'MEDIUMBLOB', - 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', - 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', - 'MODIFIES', 'NATURAL', 'NOT', - 'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC', - 'ON', 'OPTIMIZE', 'OPTION', - 'OPTIONALLY', 'OR', 'ORDER', - 'OUT', 'OUTER', 'OUTFILE', - 'PRECISION', 'PRIMARY', 'PROCEDURE', - 'PURGE', 'RAID0', 'READ', - 'READS', 'REAL', 'REFERENCES', - 'REGEXP', 'RELEASE', 'RENAME', - 'REPEAT', 'REPLACE', 'REQUIRE', - 'RESTRICT', 'RETURN', 'REVOKE', - 'RIGHT', 'RLIKE', 'SCHEMA', - 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', - 'SENSITIVE', 'SEPARATOR', 'SET', - 'SHOW', 'SMALLINT', 'SONAME', - 'SPATIAL', 'SPECIFIC', 'SQL', - 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', - 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', - 'SSL', 'STARTING', 'STRAIGHT_JOIN', - 'TABLE', 'TERMINATED', 'THEN', - 'TINYBLOB', 'TINYINT', 'TINYTEXT', - 'TO', 'TRAILING', 'TRIGGER', - 'TRUE', 'UNDO', 'UNION', - 'UNIQUE', 'UNLOCK', 'UNSIGNED', - 'UPDATE', 'USAGE', 'USE', - 'USING', 'UTC_DATE', 'UTC_TIME', - 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', - 'VARCHAR', 'VARCHARACTER', 'VARYING', - 'WHEN', 'WHERE', 'WHILE', - 'WITH', 'WRITE', 'X509', - 'XOR', 'YEAR_MONTH', 'ZEROFILL' - ); + 'ADD', 'ALL', 'ALTER', + 'ANALYZE', 'AND', 'AS', + 'ASC', 'ASENSITIVE', 'BEFORE', + 'BETWEEN', 'BIGINT', 'BINARY', + 'BLOB', 'BOTH', 'BY', 'BIT', + 'CALL', 'CASCADE', 'CASE', + 'CHANGE', 'CHAR', 'CHARACTER', + 'CHECK', 'COLLATE', 'COLUMN', + 'CONDITION', 'CONNECTION', 'CONSTRAINT', + 'CONTINUE', 'CONVERT', 'CREATE', + 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME', + 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', + 'DATABASE', 'DATABASES', 'DAY_HOUR', + 'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', + 'DEC', 'DECIMAL', 'DECLARE', + 'DEFAULT', 'DELAYED', 'DELETE', + 'DESC', 'DESCRIBE', 'DETERMINISTIC', + 'DISTINCT', 'DISTINCTROW', 'DIV', + 'DOUBLE', 'DROP', 'DUAL', + 'EACH', 'ELSE', 'ELSEIF', + 'ENCLOSED', 'ESCAPED', 'EXISTS', + 'EXIT', 'EXPLAIN', 'FALSE', + 'FETCH', 'FLOAT', 'FLOAT4', + 'FLOAT8', 'FOR', 'FORCE', + 'FOREIGN', 'FROM', 'FULLTEXT', + 'GRANT', 'GROUP', 'HAVING', + 'HIGH_PRIORITY', 'HOUR_MICROSECOND', 'HOUR_MINUTE', + 'HOUR_SECOND', 'IF', 'IGNORE', + 'IN', 'INDEX', 'INFILE', + 'INNER', 'INOUT', 'INSENSITIVE', + 'INSERT', 'INT', 'INT1', + 'INT2', 'INT3', 'INT4', + 'INT8', 'INTEGER', 'INTERVAL', + 'INTO', 'IS', 'ITERATE', + 'JOIN', 'KEY', 'KEYS', + 'KILL', 'LEADING', 'LEAVE', + 'LEFT', 'LIKE', 'LIMIT', + 'LINES', 'LOAD', 'LOCALTIME', + 'LOCALTIMESTAMP', 'LOCK', 'LONG', + 'LONGBLOB', 'LONGTEXT', 'LOOP', + 'LOW_PRIORITY', 'MATCH', 'MEDIUMBLOB', + 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', + 'MINUTE_MICROSECOND', 'MINUTE_SECOND', 'MOD', + 'MODIFIES', 'NATURAL', 'NOT', + 'NO_WRITE_TO_BINLOG', 'NULL', 'NUMERIC', + 'ON', 'OPTIMIZE', 'OPTION', + 'OPTIONALLY', 'OR', 'ORDER', + 'OUT', 'OUTER', 'OUTFILE', + 'PRECISION', 'PRIMARY', 'PROCEDURE', + 'PURGE', 'RAID0', 'READ', + 'READS', 'REAL', 'REFERENCES', + 'REGEXP', 'RELEASE', 'RENAME', + 'REPEAT', 'REPLACE', 'REQUIRE', + 'RESTRICT', 'RETURN', 'REVOKE', + 'RIGHT', 'RLIKE', 'SCHEMA', + 'SCHEMAS', 'SECOND_MICROSECOND', 'SELECT', + 'SENSITIVE', 'SEPARATOR', 'SET', + 'SHOW', 'SMALLINT', 'SONAME', + 'SPATIAL', 'SPECIFIC', 'SQL', + 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', + 'SQL_BIG_RESULT', 'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', + 'SSL', 'STARTING', 'STRAIGHT_JOIN', + 'TABLE', 'TERMINATED', 'THEN', + 'TINYBLOB', 'TINYINT', 'TINYTEXT', + 'TO', 'TRAILING', 'TRIGGER', + 'TRUE', 'UNDO', 'UNION', + 'UNIQUE', 'UNLOCK', 'UNSIGNED', + 'UPDATE', 'USAGE', 'USE', + 'USING', 'UTC_DATE', 'UTC_TIME', + 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', + 'VARCHAR', 'VARCHARACTER', 'VARYING', + 'WHEN', 'WHERE', 'WHILE', + 'WITH', 'WRITE', 'X509', + 'XOR', 'YEAR_MONTH', 'ZEROFILL', + ); /** * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -128,44 +128,48 @@ class Doctrine_DataDict_Mysql extends Doctrine_DataDict * Boolean flag that indicates whether this field is constrained * to not be set to null. * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration($field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } switch ($field['type']) { case 'char': - $length = ( ! empty($field['length'])) ? $field['length'] : false; + $length = (!empty($field['length'])) ? $field['length'] : false; return $length ? 'CHAR('.$length.')' : 'CHAR(255)'; case 'enum': if ($this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) { $values = array(); foreach ($field['values'] as $value) { - $values[] = $this->conn->quote($value, 'varchar'); + $values[] = $this->conn->quote($value, 'varchar'); } + return 'ENUM('.implode(', ', $values).')'; - } else { - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; } + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + + // no break case 'set': if ($this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_SET)) { $values = array(); foreach ($field['values'] as $value) { $values[] = $this->conn->quote($value, 'varchar'); } + return 'SET('.implode(', ', $values).')'; - } else { - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; } + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + + // no break case 'varchar': case 'string': case 'gzip': - if ( ! isset($field['length'])) { + if (!isset($field['length'])) { if (array_key_exists('default', $field)) { $field['length'] = $this->conn->varchar_max_length; } else { @@ -174,52 +178,63 @@ public function getNativeDeclaration($field) } $length = ($field['length'] <= $this->conn->varchar_max_length) ? $field['length'] : false; - $fixed = (isset($field['fixed'])) ? $field['fixed'] : false; + $fixed = (isset($field['fixed'])) ? $field['fixed'] : false; - return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR(255)') - : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT'); + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)') + : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); case 'array': case 'object': case 'clob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 255) { return 'TINYTEXT'; - } elseif ($length <= 65532) { + } + if ($length <= 65532) { return 'TEXT'; - } elseif ($length <= 16777215) { + } + if ($length <= 16777215) { return 'MEDIUMTEXT'; } } + return 'LONGTEXT'; case 'blob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 255) { return 'TINYBLOB'; - } elseif ($length <= 65532) { + } + if ($length <= 65532) { return 'BLOB'; - } elseif ($length <= 16777215) { + } + if ($length <= 16777215) { return 'MEDIUMBLOB'; } } + return 'LONGBLOB'; case 'integer': case 'int': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 1) { return 'TINYINT'; - } elseif ($length == 2) { + } + if (2 == $length) { return 'SMALLINT'; - } elseif ($length == 3) { + } + if (3 == $length) { return 'MEDIUMINT'; - } elseif ($length == 4) { + } + if (4 == $length) { return 'INT'; - } elseif ($length > 4) { + } + if ($length > 4) { return 'BIGINT'; } } + return 'INT'; case 'boolean': return 'TINYINT(1)'; @@ -232,32 +247,37 @@ public function getNativeDeclaration($field) case 'float': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'FLOAT('.$length.', '.$scale.')'; case 'double': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'DOUBLE('.$length.', '.$scale.')'; case 'decimal': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'DECIMAL('.$length.', '.$scale.')'; case 'bit': return 'BIT'; } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to a MDB2 datatype and length + * Maps a native array description of a field to a MDB2 datatype and length. + * + * @param array $field native field description * - * @param array $field native field description * @return array containing the various possible types, length, sign, fixed */ public function getPortableDeclaration(array $field) { $dbType = strtolower($field['type']); $dbType = strtok($dbType, '(), '); - if ($dbType == 'national') { + if ('national' == $dbType) { $dbType = strtok('(), '); } if (isset($field['length'])) { @@ -266,14 +286,14 @@ public function getPortableDeclaration(array $field) } else { $length = strtok('(), '); $decimal = strtok('(), '); - if ( ! $decimal ) { + if (!$decimal) { $decimal = null; } } $type = array(); $unsigned = $fixed = null; - if ( ! isset($field['name'])) { + if (!isset($field['name'])) { $field['name'] = ''; } @@ -289,28 +309,28 @@ public function getPortableDeclaration(array $field) } $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 1; - break; + break; case 'smallint': $type[] = 'integer'; $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 2; - break; + break; case 'mediumint': $type[] = 'integer'; $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 3; - break; + break; case 'int': case 'integer': $type[] = 'integer'; $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 4; - break; + break; case 'bigint': $type[] = 'integer'; $unsigned = preg_match('/ unsigned/i', $field['type']); $length = 8; - break; + break; case 'tinytext': case 'mediumtext': case 'longtext': @@ -318,24 +338,25 @@ public function getPortableDeclaration(array $field) case 'text': case 'varchar': $fixed = false; + // no break case 'string': case 'char': $type[] = 'string'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); } } elseif (strstr($dbType, 'text')) { $type[] = 'clob'; - if ($decimal == 'binary') { + if ('binary' == $decimal) { $type[] = 'blob'; } } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } - break; + break; case 'enum': $type[] = 'enum'; preg_match_all('/\'((?:\'\'|[^\'])*)\'/', $field['type'], $matches); @@ -346,7 +367,7 @@ public function getPortableDeclaration(array $field) $value = str_replace('\'\'', '\'', $value); $length = max($length, strlen($value)); } - if ($length == '1' && count($matches[1]) == 2) { + if ('1' == $length && 2 == count($matches[1])) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); @@ -361,35 +382,36 @@ public function getPortableDeclaration(array $field) $fixed = false; $type[] = 'text'; $type[] = 'integer'; - break; + break; case 'date': $type[] = 'date'; $length = null; - break; + break; case 'datetime': case 'timestamp': $type[] = 'timestamp'; $length = null; - break; + break; case 'time': $type[] = 'time'; $length = null; - break; + break; case 'float': case 'double': case 'real': $type[] = 'float'; $unsigned = preg_match('/ unsigned/i', $field['type']); - break; + break; case 'unknown': case 'decimal': - if ($decimal !== null) { + if (null !== $decimal) { $scale = $decimal; } + // no break case 'numeric': $type[] = 'decimal'; $unsigned = preg_match('/ unsigned/i', $field['type']); - break; + break; case 'tinyblob': case 'mediumblob': case 'longblob': @@ -398,15 +420,15 @@ public function getPortableDeclaration(array $field) case 'varbinary': $type[] = 'blob'; $length = null; - break; + break; case 'year': $type[] = 'integer'; $type[] = 'date'; $length = null; - break; + break; case 'bit': $type[] = 'bit'; - break; + break; case 'geometry': case 'geometrycollection': case 'point': @@ -417,20 +439,21 @@ public function getPortableDeclaration(array $field) case 'multipolygon': $type[] = 'blob'; $length = null; - break; + break; default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - $length = ((int) $length == 0) ? null : (int) $length; - $def = array('type' => $type, 'length' => $length, 'unsigned' => $unsigned, 'fixed' => $fixed); - if ($values !== null) { + $length = (0 == (int) $length) ? null : (int) $length; + $def = array('type' => $type, 'length' => $length, 'unsigned' => $unsigned, 'fixed' => $fixed); + if (null !== $values) { $def['values'] = $values; } - if ($scale !== null) { + if (null !== $scale) { $def['scale'] = $scale; } + return $def; } @@ -438,37 +461,39 @@ public function getPortableDeclaration(array $field) * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET * of a field declaration to be used in statements like CREATE TABLE. * - * @param string $charset name of the charset - * @return string DBMS specific SQL code portion needed to set the CHARACTER SET - * of a field declaration. + * @param string $charset name of the charset + * + * @return string DBMS specific SQL code portion needed to set the CHARACTER SET + * of a field declaration */ public function getCharsetFieldDeclaration($charset) { - return 'CHARACTER SET ' . $charset; + return 'CHARACTER SET '.$charset; } /** * Obtain DBMS specific SQL code portion needed to set the COLLATION * of a field declaration to be used in statements like CREATE TABLE. * - * @param string $collation name of the collation - * @return string DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration. + * @param string $collation name of the collation + * + * @return string DBMS specific SQL code portion needed to set the COLLATION + * of a field declaration */ public function getCollationFieldDeclaration($collation) { - return 'COLLATE ' . $collation; + return 'COLLATE '.$collation; } /** * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param string $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: + * @param string $name name the field to be declared + * @param string $field associative array with the name of the properties + * of the field being declared as array indexes. + * Currently, the types of supported field + * properties are as follows: * * unsigned * Boolean flag that indicates whether the field @@ -482,33 +507,34 @@ public function getCollationFieldDeclaration($collation) * notnull * Boolean flag that indicates whether this field is * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getIntegerDeclaration($name, $field) { $unique = (isset($field['unique']) && $field['unique']) ? ' UNIQUE' : ''; $default = $autoinc = ''; - if ( ! empty($field['autoincrement'])) { + if (!empty($field['autoincrement'])) { $autoinc = ' AUTO_INCREMENT'; } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : 0; } - $default = ' DEFAULT ' . (is_null($field['default']) + $default = ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'])); } - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; + $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; $unsigned = (isset($field['unsigned']) && $field['unsigned']) ? ' UNSIGNED' : ''; - $comment = (isset($field['comment']) && $field['comment']) - ? " COMMENT " . $this->conn->quote($field['comment'], 'text') : ''; + $comment = (isset($field['comment']) && $field['comment']) + ? ' COMMENT '.$this->conn->quote($field['comment'], 'text') : ''; $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $this->getNativeDeclaration($field) . $unsigned - . $default . $unique . $notnull . $autoinc . $comment; + return $name.' '.$this->getNativeDeclaration($field).$unsigned + .$default.$unique.$notnull.$autoinc.$comment; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/DataDict/Oracle.php b/lib/Doctrine/DataDict/Oracle.php index c47a296d4..b7efae5f9 100644 --- a/lib/Doctrine/DataDict/Oracle.php +++ b/lib/Doctrine/DataDict/Oracle.php @@ -20,12 +20,12 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Oracle extends Doctrine_DataDict @@ -34,9 +34,9 @@ class Doctrine_DataDict_Oracle extends Doctrine_DataDict * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -49,17 +49,19 @@ class Doctrine_DataDict_Oracle extends Doctrine_DataDict * notnull * Boolean flag that indicates whether this field is constrained * to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration(array $field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } switch ($field['type']) { case 'enum': - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + // no break case 'string': case 'array': case 'object': @@ -68,36 +70,42 @@ public function getNativeDeclaration(array $field) case 'varchar': $length = !empty($field['length']) ? $field['length'] : false; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; - + $fixed = ((isset($field['fixed']) && $field['fixed']) || 'char' == $field['type']) ? true : false; + $unit = $this->conn->getParam('char_unit'); - $unit = ! is_null($unit) ? ' '.$unit : ''; + $unit = !is_null($unit) ? ' '.$unit : ''; if ($length && $length <= $this->conn->getParam('varchar2_max_length')) { return $fixed ? 'CHAR('.$length.$unit.')' : 'VARCHAR2('.$length.$unit.')'; } + // no break case 'clob': return 'CLOB'; case 'blob': return 'BLOB'; case 'integer': case 'int': - $length = (!empty($field['length'])) ? $field['length'] : false; - if ( $length && $length <= $this->conn->number_max_precision) { - if ($length <= 1) { - return 'NUMBER(3)'; // TINYINT, unsigned max. 256 - } elseif ($length == 2) { - return 'NUMBER(5)'; // SMALLINT, unsigend max. 65.536 - } elseif ($length == 3) { - return 'NUMBER(8)'; // MEDIUMINT, unsigned max. 16.777.216 - } elseif ($length == 4) { - return 'NUMBER(10)'; // INTEGER, unsigend max. 4.294.967.296 - } elseif ($length <= 8) { - return 'NUMBER(20)'; // BIGINT, unsigend max. 18.446.744.073.709.551.616 - } else { - return 'INTEGER'; - } - } + $length = (!empty($field['length'])) ? $field['length'] : false; + if ($length && $length <= $this->conn->number_max_precision) { + if ($length <= 1) { + return 'NUMBER(3)'; // TINYINT, unsigned max. 256 + } + if (2 == $length) { + return 'NUMBER(5)'; // SMALLINT, unsigend max. 65.536 + } + if (3 == $length) { + return 'NUMBER(8)'; // MEDIUMINT, unsigned max. 16.777.216 + } + if (4 == $length) { + return 'NUMBER(10)'; // INTEGER, unsigend max. 4.294.967.296 + } + if ($length <= 8) { + return 'NUMBER(20)'; // BIGINT, unsigend max. 18.446.744.073.709.551.616 + } + + return 'INTEGER'; + } + return 'INTEGER'; case 'boolean': return 'NUMBER(1)'; @@ -110,33 +118,37 @@ public function getNativeDeclaration(array $field) return 'NUMBER'; case 'decimal': $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'NUMBER(*,'.$scale.')'; default: } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to a doctrine datatype and length + * Maps a native array description of a field to a doctrine datatype and length. + * + * @param array $field native field description * - * @param array $field native field description * @return array containing the various possible types, length, sign, fixed + * * @throws Doctrine_DataDict_Oracle_Exception */ public function getPortableDeclaration(array $field) { - if ( ! isset($field['data_type'])) { + if (!isset($field['data_type'])) { throw new Doctrine_DataDict_Exception('Native oracle definition must have a data_type key specified'); } - + $dbType = strtolower($field['data_type']); $type = array(); $length = $unsigned = $fixed = null; - if ( ! empty($field['data_length'])) { - $length = (int)$field['data_length']; + if (!empty($field['data_length'])) { + $length = (int) $field['data_length']; } - if ( ! isset($field['column_name'])) { + if (!isset($field['column_name'])) { $field['column_name'] = ''; } @@ -145,7 +157,7 @@ public function getPortableDeclaration(array $field) case 'pls_integer': case 'binary_integer': $type[] = 'integer'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/i', $field['column_name'])) { $type = array_reverse($type); @@ -156,16 +168,17 @@ public function getPortableDeclaration(array $field) case 'varchar2': case 'nvarchar2': $fixed = false; + // no break case 'char': case 'nchar': $type[] = 'string'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/i', $field['column_name'])) { $type = array_reverse($type); } } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } break; @@ -178,32 +191,33 @@ public function getPortableDeclaration(array $field) $type[] = 'float'; break; case 'number': - if ( ! empty($field['data_scale'])) { + if (!empty($field['data_scale'])) { $type[] = 'decimal'; } else { $type[] = 'integer'; - if ((int)$length == '1') { + if ('1' == (int) $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/i', $field['column_name'])) { $type = array_reverse($type); } else { - $length = 1; //TINYINT + $length = 1; // TINYINT } - } elseif ( ! is_null($length) && (int)$length <= 3) { // TINYINT + } elseif (!is_null($length) && (int) $length <= 3) { // TINYINT $length = 1; - } elseif ( ! is_null($length) && (int)$length <= 5) { // SMALLINT + } elseif (!is_null($length) && (int) $length <= 5) { // SMALLINT $length = 2; - } elseif ( ! is_null($length) && (int)$length <= 8) { // MEDIUMINT + } elseif (!is_null($length) && (int) $length <= 8) { // MEDIUMINT $length = 3; - } elseif ( ! is_null($length) && (int)$length <= 10) { // INT + } elseif (!is_null($length) && (int) $length <= 10) { // INT $length = 4; - } elseif ( ! is_null($length) && (int)$length <= 20) { //BIGINT + } elseif (!is_null($length) && (int) $length <= 20) { // BIGINT $length = 8; } } break; case 'long': $type[] = 'string'; + // no break case 'clob': case 'nclob': $type[] = 'clob'; @@ -214,17 +228,17 @@ public function getPortableDeclaration(array $field) case 'bfile': $type[] = 'blob'; $length = null; - break; + break; case 'rowid': case 'urowid': default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - return array('type' => $type, - 'length' => $length, - 'unsigned' => $unsigned, - 'fixed' => $fixed); + return array('type' => $type, + 'length' => $length, + 'unsigned' => $unsigned, + 'fixed' => $fixed); } } diff --git a/lib/Doctrine/DataDict/Pgsql.php b/lib/Doctrine/DataDict/Pgsql.php index da1cc9e54..c8a554bc5 100644 --- a/lib/Doctrine/DataDict/Pgsql.php +++ b/lib/Doctrine/DataDict/Pgsql.php @@ -20,327 +20,327 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Paul Cooper * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7641 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Pgsql extends Doctrine_DataDict { /** - * @param array $reservedKeyWords an array of reserved keywords by pgsql + * @param array $reservedKeyWords an array of reserved keywords by pgsql */ protected static $reservedKeyWords = array( - 'abort', - 'absolute', - 'access', - 'action', - 'add', - 'after', - 'aggregate', - 'all', - 'alter', - 'analyse', - 'analyze', - 'and', - 'any', - 'as', - 'asc', - 'assertion', - 'assignment', - 'at', - 'authorization', - 'backward', - 'before', - 'begin', - 'between', - 'bigint', - 'binary', - 'bit', - 'boolean', - 'both', - 'by', - 'cache', - 'called', - 'cascade', - 'case', - 'cast', - 'chain', - 'char', - 'character', - 'characteristics', - 'check', - 'checkpoint', - 'class', - 'close', - 'cluster', - 'coalesce', - 'collate', - 'column', - 'comment', - 'commit', - 'committed', - 'constraint', - 'constraints', - 'conversion', - 'convert', - 'copy', - 'create', - 'createdb', - 'createuser', - 'cross', - 'current_date', - 'current_time', - 'current_timestamp', - 'current_user', - 'cursor', - 'cycle', - 'database', - 'day', - 'deallocate', - 'dec', - 'decimal', - 'declare', - 'default', - 'deferrable', - 'deferred', - 'definer', - 'delete', - 'delimiter', - 'delimiters', - 'desc', - 'distinct', - 'do', - 'domain', - 'double', - 'drop', - 'each', - 'else', - 'encoding', - 'encrypted', - 'end', - 'escape', - 'except', - 'exclusive', - 'execute', - 'exists', - 'explain', - 'external', - 'extract', - 'false', - 'fetch', - 'float', - 'for', - 'force', - 'foreign', - 'forward', - 'freeze', - 'from', - 'full', - 'function', - 'get', - 'global', - 'grant', - 'group', - 'handler', - 'having', - 'hour', - 'ilike', - 'immediate', - 'immutable', - 'implicit', - 'in', - 'increment', - 'index', - 'inherits', - 'initially', - 'inner', - 'inout', - 'input', - 'insensitive', - 'insert', - 'instead', - 'int', - 'integer', - 'intersect', - 'interval', - 'into', - 'invoker', - 'is', - 'isnull', - 'isolation', - 'join', - 'key', - 'lancompiler', - 'language', - 'leading', - 'left', - 'level', - 'like', - 'limit', - 'listen', - 'load', - 'local', - 'localtime', - 'localtimestamp', - 'location', - 'lock', - 'match', - 'maxvalue', - 'minute', - 'minvalue', - 'mode', - 'month', - 'move', - 'names', - 'national', - 'natural', - 'nchar', - 'new', - 'next', - 'no', - 'nocreatedb', - 'nocreateuser', - 'none', - 'not', - 'nothing', - 'notify', - 'notnull', - 'null', - 'nullif', - 'numeric', - 'of', - 'off', - 'offset', - 'oids', - 'old', - 'on', - 'only', - 'operator', - 'option', - 'or', - 'order', - 'out', - 'outer', - 'overlaps', - 'overlay', - 'owner', - 'partial', - 'password', - 'path', - 'pendant', - 'placing', - 'position', - 'precision', - 'prepare', - 'primary', - 'prior', - 'privileges', - 'procedural', - 'procedure', - 'read', - 'real', - 'recheck', - 'references', - 'reindex', - 'relative', - 'rename', - 'replace', - 'reset', - 'restrict', - 'returns', - 'revoke', - 'right', - 'rollback', - 'row', - 'rule', - 'schema', - 'scroll', - 'second', - 'security', - 'select', - 'sequence', - 'serializable', - 'session', - 'session_user', - 'set', - 'setof', - 'share', - 'show', - 'similar', - 'simple', - 'smallint', - 'some', - 'stable', - 'start', - 'statement', - 'statistics', - 'stdin', - 'stdout', - 'storage', - 'strict', - 'substring', - 'sysid', - 'table', - 'temp', - 'template', - 'temporary', - 'then', - 'time', - 'timestamp', - 'to', - 'toast', - 'trailing', - 'transaction', - 'treat', - 'trigger', - 'trim', - 'true', - 'truncate', - 'trusted', - 'type', - 'unencrypted', - 'union', - 'unique', - 'unknown', - 'unlisten', - 'until', - 'update', - 'usage', - 'user', - 'using', - 'vacuum', - 'valid', - 'validator', - 'values', - 'varchar', - 'varying', - 'verbose', - 'version', - 'view', - 'volatile', - 'when', - 'where', - 'with', - 'without', - 'work', - 'write', - 'year', - 'zone' - ); + 'abort', + 'absolute', + 'access', + 'action', + 'add', + 'after', + 'aggregate', + 'all', + 'alter', + 'analyse', + 'analyze', + 'and', + 'any', + 'as', + 'asc', + 'assertion', + 'assignment', + 'at', + 'authorization', + 'backward', + 'before', + 'begin', + 'between', + 'bigint', + 'binary', + 'bit', + 'boolean', + 'both', + 'by', + 'cache', + 'called', + 'cascade', + 'case', + 'cast', + 'chain', + 'char', + 'character', + 'characteristics', + 'check', + 'checkpoint', + 'class', + 'close', + 'cluster', + 'coalesce', + 'collate', + 'column', + 'comment', + 'commit', + 'committed', + 'constraint', + 'constraints', + 'conversion', + 'convert', + 'copy', + 'create', + 'createdb', + 'createuser', + 'cross', + 'current_date', + 'current_time', + 'current_timestamp', + 'current_user', + 'cursor', + 'cycle', + 'database', + 'day', + 'deallocate', + 'dec', + 'decimal', + 'declare', + 'default', + 'deferrable', + 'deferred', + 'definer', + 'delete', + 'delimiter', + 'delimiters', + 'desc', + 'distinct', + 'do', + 'domain', + 'double', + 'drop', + 'each', + 'else', + 'encoding', + 'encrypted', + 'end', + 'escape', + 'except', + 'exclusive', + 'execute', + 'exists', + 'explain', + 'external', + 'extract', + 'false', + 'fetch', + 'float', + 'for', + 'force', + 'foreign', + 'forward', + 'freeze', + 'from', + 'full', + 'function', + 'get', + 'global', + 'grant', + 'group', + 'handler', + 'having', + 'hour', + 'ilike', + 'immediate', + 'immutable', + 'implicit', + 'in', + 'increment', + 'index', + 'inherits', + 'initially', + 'inner', + 'inout', + 'input', + 'insensitive', + 'insert', + 'instead', + 'int', + 'integer', + 'intersect', + 'interval', + 'into', + 'invoker', + 'is', + 'isnull', + 'isolation', + 'join', + 'key', + 'lancompiler', + 'language', + 'leading', + 'left', + 'level', + 'like', + 'limit', + 'listen', + 'load', + 'local', + 'localtime', + 'localtimestamp', + 'location', + 'lock', + 'match', + 'maxvalue', + 'minute', + 'minvalue', + 'mode', + 'month', + 'move', + 'names', + 'national', + 'natural', + 'nchar', + 'new', + 'next', + 'no', + 'nocreatedb', + 'nocreateuser', + 'none', + 'not', + 'nothing', + 'notify', + 'notnull', + 'null', + 'nullif', + 'numeric', + 'of', + 'off', + 'offset', + 'oids', + 'old', + 'on', + 'only', + 'operator', + 'option', + 'or', + 'order', + 'out', + 'outer', + 'overlaps', + 'overlay', + 'owner', + 'partial', + 'password', + 'path', + 'pendant', + 'placing', + 'position', + 'precision', + 'prepare', + 'primary', + 'prior', + 'privileges', + 'procedural', + 'procedure', + 'read', + 'real', + 'recheck', + 'references', + 'reindex', + 'relative', + 'rename', + 'replace', + 'reset', + 'restrict', + 'returns', + 'revoke', + 'right', + 'rollback', + 'row', + 'rule', + 'schema', + 'scroll', + 'second', + 'security', + 'select', + 'sequence', + 'serializable', + 'session', + 'session_user', + 'set', + 'setof', + 'share', + 'show', + 'similar', + 'simple', + 'smallint', + 'some', + 'stable', + 'start', + 'statement', + 'statistics', + 'stdin', + 'stdout', + 'storage', + 'strict', + 'substring', + 'sysid', + 'table', + 'temp', + 'template', + 'temporary', + 'then', + 'time', + 'timestamp', + 'to', + 'toast', + 'trailing', + 'transaction', + 'treat', + 'trigger', + 'trim', + 'true', + 'truncate', + 'trusted', + 'type', + 'unencrypted', + 'union', + 'unique', + 'unknown', + 'unlisten', + 'until', + 'update', + 'usage', + 'user', + 'using', + 'vacuum', + 'valid', + 'validator', + 'values', + 'varchar', + 'varying', + 'verbose', + 'version', + 'view', + 'volatile', + 'when', + 'where', + 'with', + 'without', + 'work', + 'write', + 'year', + 'zone', + ); /** * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -354,23 +354,24 @@ class Doctrine_DataDict_Pgsql extends Doctrine_DataDict * Boolean flag that indicates whether this field is constrained * to not be set to null. * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration(array $field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } // Postgres enum type by name containing enum - if (strpos($field['type'], 'enum') !== false){ - $field['type'] = 'enum'; + if (false !== strpos($field['type'], 'enum')) { + $field['type'] = 'enum'; } switch ($field['type']) { case 'enum': - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + // no break case 'char': case 'string': case 'array': @@ -380,10 +381,10 @@ public function getNativeDeclaration(array $field) // TODO: what is the maximum VARCHAR length in pgsql ? $length = (isset($field['length']) && $field['length'] && $field['length'] < 10000) ? $field['length'] : null; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || 'char' == $field['type']) ? true : false; - return $fixed ? ($length ? 'CHAR(' . $length . ')' : 'CHAR('.$this->conn->varchar_max_length.')') - : ($length ? 'VARCHAR(' .$length . ')' : 'TEXT'); + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$this->conn->varchar_max_length.')') + : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); case 'clob': return 'TEXT'; @@ -391,31 +392,35 @@ public function getNativeDeclaration(array $field) return 'BYTEA'; case 'integer': case 'int': - if ( ! empty($field['autoincrement'])) { - if ( ! empty($field['length'])) { + if (!empty($field['autoincrement'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length > 4) { return 'BIGSERIAL'; } } + return 'SERIAL'; } - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 2) { return 'SMALLINT'; - } elseif ($length == 3 || $length == 4) { + } + if (3 == $length || 4 == $length) { return 'INT'; - } elseif ($length > 4) { + } + if ($length > 4) { return 'BIGINT'; } } + return 'INT'; - case 'inet': - return 'INET'; + case 'inet': + return 'INET'; case 'bit': case 'varbit': - return 'VARBIT'; + return 'VARBIT'; case 'boolean': return 'BOOLEAN'; case 'date': @@ -430,31 +435,33 @@ public function getNativeDeclaration(array $field) case 'decimal': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'NUMERIC('.$length.','.$scale.')'; } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to a portable Doctrine datatype and length + * Maps a native array description of a field to a portable Doctrine datatype and length. * - * @param array $field native field description + * @param array $field native field description * * @return array containing the various possible types, length, sign, fixed */ public function getPortableDeclaration(array $field) { $length = (isset($field['length'])) ? $field['length'] : null; - if ($length == '-1' && isset($field['atttypmod'])) { + if ('-1' == $length && isset($field['atttypmod'])) { $length = $field['atttypmod'] - 4; } - if ((int)$length <= 0) { + if ((int) $length <= 0) { $length = null; } $type = array(); $unsigned = $fixed = null; - if ( ! isset($field['name'])) { + if (!isset($field['name'])) { $field['name'] = ''; } @@ -463,25 +470,25 @@ public function getPortableDeclaration(array $field) // Default from field for enum support $default = isset($field['default']) ? $field['default'] : null; $enumName = null; - if (strpos($dbType, 'enum') !== false){ + if (false !== strpos($dbType, 'enum')) { $enumName = $dbType; $dbType = 'enum'; } switch ($dbType) { - case 'inet': - $type[] = 'inet'; - break; - case 'bit': - case 'varbit': - $type[] = 'bit'; - break; + case 'inet': + $type[] = 'inet'; + break; + case 'bit': + case 'varbit': + $type[] = 'bit'; + break; case 'smallint': case 'int2': $type[] = 'integer'; $unsigned = false; $length = 2; - if ($length == '2') { + if ('2' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); @@ -515,13 +522,14 @@ public function getPortableDeclaration(array $field) case 'interval': case '_varchar': $fixed = false; + // no break case 'tsvector': case 'unknown': case 'char': case 'character': case 'bpchar': $type[] = 'string'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); @@ -529,14 +537,14 @@ public function getPortableDeclaration(array $field) } elseif (strstr($dbType, 'text')) { $type[] = 'clob'; } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } break; case 'enum': $type[] = 'enum'; - $length = $length ? $length :255; - if($default) { + $length = $length ? $length : 255; + if ($default) { $default = preg_replace('/\'(\w+)\'.*/', '${1}', $default); } break; @@ -596,21 +604,22 @@ public function getPortableDeclaration(array $field) break; default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - $ret = array('type' => $type, - 'length' => $length, - 'unsigned' => $unsigned, - 'fixed' => $fixed); + $ret = array('type' => $type, + 'length' => $length, + 'unsigned' => $unsigned, + 'fixed' => $fixed); // If this is postgresql enum type we will have non-null values here - if ($default !== null) { + if (null !== $default) { $ret['default'] = $default; } - if ($enumName !== null) { + if (null !== $enumName) { $ret['enumName'] = $enumName; } + return $ret; } @@ -618,10 +627,10 @@ public function getPortableDeclaration(array $field) * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param string $name name the field to be declared + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * unsigned * Boolean flag that indicates whether the field should be @@ -633,51 +642,53 @@ public function getPortableDeclaration(array $field) * notnull * Boolean flag that indicates whether this field is constrained * to not be set to null. + * * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * declare the specified field */ public function getIntegerDeclaration($name, $field) { /** - if ( ! empty($field['unsigned'])) { - $this->conn->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer"; - } - */ - - if ( ! empty($field['autoincrement'])) { + * if ( ! empty($field['unsigned'])) { + * $this->conn->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer"; + * }. + */ + if (!empty($field['autoincrement'])) { $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $this->getNativeDeclaration($field); + + return $name.' '.$this->getNativeDeclaration($field); } $default = ''; if (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : 0; } - $default = ' DEFAULT ' . (is_null($field['default']) + $default = ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'], $field['type'])); } /** - TODO: is this needed ? - elseif (empty($field['notnull'])) { - $default = ' DEFAULT NULL'; - } - */ - + * TODO: is this needed ? + * elseif (empty($field['notnull'])) { + * $default = ' DEFAULT NULL'; + * }. + */ $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $this->getNativeDeclaration($field) . $default . $notnull; + + return $name.' '.$this->getNativeDeclaration($field).$default.$notnull; } /** * parseBoolean * parses a literal boolean value and returns - * proper sql equivalent + * proper sql equivalent. + * + * @param string $value boolean value to be parsed * - * @param string $value boolean value to be parsed - * @return string parsed boolean value + * @return string parsed boolean value */ public function parseBoolean($value) { diff --git a/lib/Doctrine/DataDict/Sqlite.php b/lib/Doctrine/DataDict/Sqlite.php index 8bb7caeaa..1d525db68 100644 --- a/lib/Doctrine/DataDict/Sqlite.php +++ b/lib/Doctrine/DataDict/Sqlite.php @@ -20,13 +20,13 @@ */ /** - * @package Doctrine - * @subpackage DataDict * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict @@ -35,9 +35,9 @@ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict * Obtain DBMS specific SQL code portion needed to declare an text type * field to be used in statements like CREATE TABLE. * - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -50,18 +50,21 @@ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict * notnull * Boolean flag that indicates whether this field is constrained * to not be set to null. + * * @author Lukas Smith (PEAR MDB2 library) - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getNativeDeclaration(array $field) { - if ( ! isset($field['type'])) { + if (!isset($field['type'])) { throw new Doctrine_DataDict_Exception('Missing column type.'); } switch ($field['type']) { case 'enum': - $field['length'] = isset($field['length']) && $field['length'] ? $field['length']:255; + $field['length'] = isset($field['length']) && $field['length'] ? $field['length'] : 255; + // no break case 'text': case 'object': case 'array': @@ -71,33 +74,39 @@ public function getNativeDeclaration(array $field) case 'varchar': $length = (isset($field['length']) && $field['length']) ? $field['length'] : null; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || 'char' == $field['type']) ? true : false; return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$this->conn->varchar_max_length.')') : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); case 'clob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 255) { return 'TINYTEXT'; - } elseif ($length <= 65535) { + } + if ($length <= 65535) { return 'TEXT'; - } elseif ($length <= 16777215) { + } + if ($length <= 16777215) { return 'MEDIUMTEXT'; } } + return 'LONGTEXT'; case 'blob': - if ( ! empty($field['length'])) { + if (!empty($field['length'])) { $length = $field['length']; if ($length <= 255) { return 'TINYBLOB'; - } elseif ($length <= 65535) { + } + if ($length <= 65535) { return 'BLOB'; - } elseif ($length <= 16777215) { + } + if ($length <= 16777215) { return 'MEDIUMBLOB'; } } + return 'LONGBLOB'; case 'integer': case 'boolean': @@ -111,20 +120,23 @@ public function getNativeDeclaration(array $field) return 'DATETIME'; case 'float': case 'double': - return 'DOUBLE';//($this->conn->options['fixed_float'] ? '('. - //($this->conn->options['fixed_float']+2).','.$this->conn->options['fixed_float'].')' : ''); + return 'DOUBLE'; // ($this->conn->options['fixed_float'] ? '('. + // ($this->conn->options['fixed_float']+2).','.$this->conn->options['fixed_float'].')' : ''); case 'decimal': $length = !empty($field['length']) ? $field['length'] : 18; $scale = !empty($field['scale']) ? $field['scale'] : $this->conn->getAttribute(Doctrine_Core::ATTR_DECIMAL_PLACES); + return 'DECIMAL('.$length.','.$scale.')'; } - return $field['type'] . (isset($field['length']) ? '('.$field['length'].')':null); + + return $field['type'].(isset($field['length']) ? '('.$field['length'].')' : null); } /** - * Maps a native array description of a field to Doctrine datatype and length + * Maps a native array description of a field to Doctrine datatype and length. + * + * @param array $field native field description * - * @param array $field native field description * @return array containing the various possible types, length, sign, fixed */ public function getPortableDeclaration(array $field) @@ -138,7 +150,7 @@ public function getPortableDeclaration(array $field) $dbType = strtolower($field['type']); - if ( ! $dbType) { + if (!$dbType) { throw new Doctrine_DataDict_Exception('Missing "type" from field definition'); } @@ -147,7 +159,7 @@ public function getPortableDeclaration(array $field) $fixed = null; $type = array(); - if ( ! isset($field['name'])) { + if (!isset($field['name'])) { $field['name'] = ''; } @@ -199,9 +211,10 @@ public function getPortableDeclaration(array $field) case 'image': case 'nchar': $fixed = false; + // no break case 'char': $type[] = 'text'; - if ($length == '1') { + if ('1' == $length) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); @@ -209,7 +222,7 @@ public function getPortableDeclaration(array $field) } elseif (strstr($dbType, 'text')) { $type[] = 'clob'; } - if ($fixed !== false) { + if (false !== $fixed) { $fixed = true; } break; @@ -251,24 +264,24 @@ public function getPortableDeclaration(array $field) break; default: $type[] = $field['type']; - $length = isset($field['length']) ? $field['length']:null; + $length = isset($field['length']) ? $field['length'] : null; } - return array('type' => $type, - 'length' => $length, - 'unsigned' => $unsigned, - 'fixed' => $fixed); + return array('type' => $type, + 'length' => $length, + 'unsigned' => $unsigned, + 'fixed' => $fixed); } /** * Obtain DBMS specific SQL code portion needed to declare an integer type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. - * Currently, the types of supported field - * properties are as follows: + * @param string $name name the field to be declared + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. + * Currently, the types of supported field + * properties are as follows: * * unsigned * Boolean flag that indicates whether the field @@ -282,40 +295,40 @@ public function getPortableDeclaration(array $field) * notnull * Boolean flag that indicates whether this field is * constrained to not be set to null. - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. - * @access protected + * + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getIntegerDeclaration($name, array $field) { $default = $autoinc = ''; - $type = $this->getNativeDeclaration($field); + $type = $this->getNativeDeclaration($field); $autoincrement = isset($field['autoincrement']) && $field['autoincrement']; if ($autoincrement) { $autoinc = ' PRIMARY KEY AUTOINCREMENT'; - $type = 'INTEGER'; + $type = 'INTEGER'; } elseif (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : 0; } - $default = ' DEFAULT ' . (is_null($field['default']) + $default = ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'], $field['type'])); - }/** + } /** elseif (empty($field['notnull'])) { $default = ' DEFAULT NULL'; } - */ + */ + $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; + // sqlite does not support unsigned attribute for autoinremented fields + $unsigned = (isset($field['unsigned']) && $field['unsigned'] && !$autoincrement) ? ' UNSIGNED' : ''; - // sqlite does not support unsigned attribute for autoinremented fields - $unsigned = (isset($field['unsigned']) && $field['unsigned'] && !$autoincrement) ? ' UNSIGNED' : ''; + $name = $this->conn->quoteIdentifier($name, true); - $name = $this->conn->quoteIdentifier($name, true); - return $name . ' ' . $type . $unsigned . $default . $notnull . $autoinc; + return $name.' '.$type.$unsigned.$default.$notnull.$autoinc; + } } -} \ No newline at end of file diff --git a/lib/Doctrine/Event.php b/lib/Doctrine/Event.php index 408d8ba13..af5a32faa 100644 --- a/lib/Doctrine/Event.php +++ b/lib/Doctrine/Event.php @@ -20,122 +20,123 @@ */ /** - * Doctrine_Event + * Doctrine_Event. * * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Event - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Event { /** - * CONNECTION EVENT CODES + * CONNECTION EVENT CODES. */ - const CONN_QUERY = 1; - const CONN_EXEC = 2; - const CONN_PREPARE = 3; - const CONN_CONNECT = 4; - const CONN_CLOSE = 5; - const CONN_ERROR = 6; - - const STMT_EXECUTE = 10; - const STMT_FETCH = 11; - const STMT_FETCHALL = 12; - - const TX_BEGIN = 31; - const TX_COMMIT = 32; - const TX_ROLLBACK = 33; - const SAVEPOINT_CREATE = 34; - const SAVEPOINT_ROLLBACK = 35; - const SAVEPOINT_COMMIT = 36; - - const HYDRATE = 40; + public const CONN_QUERY = 1; + public const CONN_EXEC = 2; + public const CONN_PREPARE = 3; + public const CONN_CONNECT = 4; + public const CONN_CLOSE = 5; + public const CONN_ERROR = 6; + + public const STMT_EXECUTE = 10; + public const STMT_FETCH = 11; + public const STMT_FETCHALL = 12; + + public const TX_BEGIN = 31; + public const TX_COMMIT = 32; + public const TX_ROLLBACK = 33; + public const SAVEPOINT_CREATE = 34; + public const SAVEPOINT_ROLLBACK = 35; + public const SAVEPOINT_COMMIT = 36; + + public const HYDRATE = 40; /* * RECORD EVENT CODES */ - const RECORD_DELETE = 21; - const RECORD_SAVE = 22; - const RECORD_UPDATE = 23; - const RECORD_INSERT = 24; - const RECORD_SERIALIZE = 25; - const RECORD_UNSERIALIZE = 26; - const RECORD_DQL_DELETE = 27; - const RECORD_DQL_SELECT = 28; - const RECORD_DQL_UPDATE = 29; - const RECORD_VALIDATE = 30; + public const RECORD_DELETE = 21; + public const RECORD_SAVE = 22; + public const RECORD_UPDATE = 23; + public const RECORD_INSERT = 24; + public const RECORD_SERIALIZE = 25; + public const RECORD_UNSERIALIZE = 26; + public const RECORD_DQL_DELETE = 27; + public const RECORD_DQL_SELECT = 28; + public const RECORD_DQL_UPDATE = 29; + public const RECORD_VALIDATE = 30; /** - * @var mixed $_nextSequence the sequence of the next event that will be created + * @var mixed the sequence of the next event that will be created */ - static protected $_nextSequence = 0; + protected static $_nextSequence = 0; /** - * @var mixed $_sequence the sequence of this event + * @var mixed the sequence of this event */ protected $_sequence; /** - * @var mixed $_invoker the handler which invoked this event + * @var mixed the handler which invoked this event */ protected $_invoker; /** - * @var string $_query the sql query associated with this event (if any) + * @var string the sql query associated with this event (if any) */ protected $_query; /** - * @var string $_params the parameters associated with the query (if any) + * @var string the parameters associated with the query (if any) */ protected $_params; /** * @see Doctrine_Event constants - * @var integer $_code the event code + * + * @var int the event code */ protected $_code; /** - * @var integer $_startedMicrotime the time point in which this event was started + * @var int the time point in which this event was started */ protected $_startedMicrotime; /** - * @var integer $_endedMicrotime the time point in which this event was ended + * @var int the time point in which this event was ended */ protected $_endedMicrotime; /** - * @var array $_options an array of options + * @var array an array of options */ protected $_options = array(); /** - * constructor + * constructor. * * @param Doctrine_Connection|Doctrine_Connection_Statement| - Doctrine_Connection_UnitOfWork|Doctrine_Transaction $invoker the handler which invoked this event - * @param integer $code the event code - * @param string $query the sql query associated with this event (if any) + * Doctrine_Connection_UnitOfWork|Doctrine_Transaction $invoker the handler which invoked this event + * @param int $code the event code + * @param string $query the sql query associated with this event (if any) */ public function __construct($invoker, $code, $query = null, $params = array()) { $this->_sequence = self::$_nextSequence++; - $this->_invoker = $invoker; - $this->_code = $code; - $this->_query = $query; - $this->_params = $params; + $this->_invoker = $invoker; + $this->_code = $code; + $this->_query = $query; + $this->_params = $params; } /** - * getQuery + * getQuery. * - * @return Doctrine_Query returns the query associated with this event (if any) + * @return Doctrine_Query returns the query associated with this event (if any) */ public function getQuery() { @@ -144,9 +145,9 @@ public function getQuery() /** * getName - * returns the name of this event + * returns the name of this event. * - * @return string the name of this event + * @return string the name of this event */ public function getName() { @@ -209,9 +210,9 @@ public function getName() } /** - * getCode + * getCode. * - * @return integer returns the code associated with this event + * @return int returns the code associated with this event */ public function getCode() { @@ -220,14 +221,13 @@ public function getCode() /** * getOption - * returns the value of an option + * returns the value of an option. * - * @param string $option the name of the option - * @return mixed + * @param string $option the name of the option */ public function __get($option) { - if ( ! isset($this->_options[$option])) { + if (!isset($this->_options[$option])) { return null; } @@ -237,9 +237,9 @@ public function __get($option) /** * skipOperation * skips the next operation - * an alias for __set('skipOperation', true) + * an alias for __set('skipOperation', true). * - * @return Doctrine_Event this object + * @return Doctrine_Event this object */ public function skipOperation() { @@ -250,11 +250,12 @@ public function skipOperation() /** * setOption - * sets the value of an option + * sets the value of an option. * - * @param string $option the name of the option - * @param mixed $value the value of the given option - * @return Doctrine_Event this object + * @param string $option the name of the option + * @param mixed $value the value of the given option + * + * @return Doctrine_Event this object */ public function __set($option, $value) { @@ -265,24 +266,25 @@ public function __set($option, $value) /** * setOption - * sets the value of an option by reference + * sets the value of an option by reference. + * + * @param string $option the name of the option + * @param mixed $value the value of the given option * - * @param string $option the name of the option - * @param mixed $value the value of the given option - * @return Doctrine_Event this object + * @return Doctrine_Event this object */ public function set($option, &$value) { - $this->_options[$option] =& $value; + $this->_options[$option] = &$value; return $this; } /** * start - * starts the internal timer of this event + * starts the internal timer of this event. * - * @return Doctrine_Event this object + * @return Doctrine_Event this object */ public function start() { @@ -291,20 +293,20 @@ public function start() /** * hasEnded - * whether or not this event has ended + * whether or not this event has ended. * - * @return boolean + * @return bool */ public function hasEnded() { - return ($this->_endedMicrotime != null); + return null != $this->_endedMicrotime; } /** * end - * ends the internal timer of this event + * ends the internal timer of this event. * - * @return Doctrine_Event this object + * @return Doctrine_Event this object */ public function end() { @@ -315,9 +317,9 @@ public function end() /** * getSequence - * returns the sequence of this event + * returns the sequence of this event. * - * @return integer + * @return int */ public function getSequence() { @@ -326,7 +328,7 @@ public function getSequence() /** * getInvoker - * returns the handler that invoked this event + * returns the handler that invoked this event. * * @return Doctrine_Record|Doctrine_Connection|Doctrine_Connection_Statement| * Doctrine_Connection_UnitOfWork|Doctrine_Transaction the handler that invoked this event @@ -338,10 +340,7 @@ public function getInvoker() /** * setInvoker - * Defines new invoker (used in Hydrator) - * - * @param mixed $invoker - * @return void + * Defines new invoker (used in Hydrator). */ public function setInvoker($invoker) { @@ -350,9 +349,9 @@ public function setInvoker($invoker) /** * getParams - * returns the parameters of the query + * returns the parameters of the query. * - * @return array parameters of the query + * @return array parameters of the query */ public function getParams() { @@ -363,13 +362,14 @@ public function getParams() * Get the elapsed time (in microseconds) that the event ran. If the event has * not yet ended, return false. * - * @return integer + * @return int */ public function getElapsedSecs() { if (is_null($this->_endedMicrotime)) { return false; } - return ($this->_endedMicrotime - $this->_startedMicrotime); + + return $this->_endedMicrotime - $this->_startedMicrotime; } } diff --git a/lib/Doctrine/EventListener.php b/lib/Doctrine/EventListener.php index bffea6e3b..5b15e0c29 100644 --- a/lib/Doctrine/EventListener.php +++ b/lib/Doctrine/EventListener.php @@ -21,99 +21,147 @@ /** * Doctrine_EventListener all event listeners extend this base class - * the empty methods allow child classes to only implement the methods they need to implement + * the empty methods allow child classes to only implement the methods they need to implement. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage EventListener * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_EventListener implements Doctrine_EventListener_Interface { public function preClose(Doctrine_Event $event) - { } + { + } + public function postClose(Doctrine_Event $event) - { } + { + } public function onCollectionDelete(Doctrine_Collection $collection) - { } + { + } + public function onPreCollectionDelete(Doctrine_Collection $collection) - { } + { + } public function onOpen(Doctrine_Connection $connection) - { } + { + } public function preTransactionCommit(Doctrine_Event $event) - { } + { + } + public function postTransactionCommit(Doctrine_Event $event) - { } + { + } public function preTransactionRollback(Doctrine_Event $event) - { } + { + } + public function postTransactionRollback(Doctrine_Event $event) - { } + { + } public function preTransactionBegin(Doctrine_Event $event) - { } - public function postTransactionBegin(Doctrine_Event $event) - { } + { + } + public function postTransactionBegin(Doctrine_Event $event) + { + } public function preSavepointCommit(Doctrine_Event $event) - { } + { + } + public function postSavepointCommit(Doctrine_Event $event) - { } + { + } public function preSavepointRollback(Doctrine_Event $event) - { } + { + } + public function postSavepointRollback(Doctrine_Event $event) - { } + { + } public function preSavepointCreate(Doctrine_Event $event) - { } + { + } + public function postSavepointCreate(Doctrine_Event $event) - { } + { + } public function postConnect(Doctrine_Event $event) - { } + { + } + public function preConnect(Doctrine_Event $event) - { } + { + } public function preQuery(Doctrine_Event $event) - { } + { + } + public function postQuery(Doctrine_Event $event) - { } + { + } public function prePrepare(Doctrine_Event $event) - { } + { + } + public function postPrepare(Doctrine_Event $event) - { } + { + } public function preExec(Doctrine_Event $event) - { } + { + } + public function postExec(Doctrine_Event $event) - { } + { + } public function preError(Doctrine_Event $event) - { } + { + } + public function postError(Doctrine_Event $event) - { } + { + } public function preFetch(Doctrine_Event $event) - { } + { + } + public function postFetch(Doctrine_Event $event) - { } + { + } public function preFetchAll(Doctrine_Event $event) - { } + { + } + public function postFetchAll(Doctrine_Event $event) - { } + { + } public function preStmtExecute(Doctrine_Event $event) - { } + { + } + public function postStmtExecute(Doctrine_Event $event) - { } + { + } } diff --git a/lib/Doctrine/EventListener/Chain.php b/lib/Doctrine/EventListener/Chain.php index f7191c0a4..468b9796d 100644 --- a/lib/Doctrine/EventListener/Chain.php +++ b/lib/Doctrine/EventListener/Chain.php @@ -22,39 +22,37 @@ /** * Doctrine_EventListener_Chain * this class represents a chain of different listeners, - * useful for having multiple listeners listening the events at the same time + * useful for having multiple listeners listening the events at the same time. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage EventListener * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_EventListener_Interface { /** - * @var array $listeners an array containing all listeners + * @var array an array containing all listeners */ protected $_listeners = array(); /** * add - * adds a listener to the chain of listeners + * adds a listener to the chain of listeners. * * @param object $listener * @param string $name - * @return void */ public function add($listener, $name = null) { - if ( ! ($listener instanceof Doctrine_EventListener_Interface) && - ! ($listener instanceof Doctrine_Overloadable)) { - + if (!($listener instanceof Doctrine_EventListener_Interface) + && !($listener instanceof Doctrine_Overloadable)) { throw new Doctrine_EventListener_Exception("Couldn't add eventlistener. EventListeners should implement either Doctrine_EventListener_Interface or Doctrine_Overloadable"); } - if ($name === null) { + if (null === $name) { $this->_listeners[] = $listener; } else { $this->_listeners[$name] = $listener; @@ -63,25 +61,21 @@ public function add($listener, $name = null) /** * returns a Doctrine_EventListener on success - * and null on failure - * - * @param mixed $key - * @return mixed + * and null on failure. */ public function get($key) { - if ( ! isset($this->_listeners[$key])) { + if (!isset($this->_listeners[$key])) { return null; } + return $this->_listeners[$key]; } /** - * set + * set. * - * @param mixed $key * @param Doctrine_EventListener $listener - * @return void */ public function set($key, $listener) { @@ -90,10 +84,7 @@ public function set($key, $listener) /** * onLoad - * an event invoked when Doctrine_Record is being loaded from database - * - * @param Doctrine_Record $record - * @return void + * an event invoked when Doctrine_Record is being loaded from database. */ public function onLoad(Doctrine_Record $record) { @@ -105,10 +96,7 @@ public function onLoad(Doctrine_Record $record) /** * onPreLoad * an event invoked when Doctrine_Record is being loaded - * from database but not yet initialized - * - * @param Doctrine_Record $record - * @return void + * from database but not yet initialized. */ public function onPreLoad(Doctrine_Record $record) { @@ -119,10 +107,7 @@ public function onPreLoad(Doctrine_Record $record) /** * onSleep - * an event invoked when Doctrine_Record is serialized - * - * @param Doctrine_Record $record - * @return void + * an event invoked when Doctrine_Record is serialized. */ public function onSleep(Doctrine_Record $record) { @@ -133,10 +118,7 @@ public function onSleep(Doctrine_Record $record) /** * onWakeUp - * an event invoked when Doctrine_Record is unserialized - * - * @param Doctrine_Record $record - * @return void + * an event invoked when Doctrine_Record is unserialized. */ public function onWakeUp(Doctrine_Record $record) { @@ -147,10 +129,7 @@ public function onWakeUp(Doctrine_Record $record) /** * postClose - * an event invoked after Doctrine_Connection is closed - * - * @param Doctrine_Event $event - * @return void + * an event invoked after Doctrine_Connection is closed. */ public function postClose(Doctrine_Event $event) { @@ -161,10 +140,7 @@ public function postClose(Doctrine_Event $event) /** * preClose - * an event invoked before Doctrine_Connection is closed - * - * @param Doctrine_Event $event - * @return void + * an event invoked before Doctrine_Connection is closed. */ public function preClose(Doctrine_Event $event) { @@ -175,10 +151,7 @@ public function preClose(Doctrine_Event $event) /** * onOpen - * an event invoked after Doctrine_Connection is opened - * - * @param Doctrine_Connection $connection - * @return void + * an event invoked after Doctrine_Connection is opened. */ public function onOpen(Doctrine_Connection $connection) { @@ -189,10 +162,7 @@ public function onOpen(Doctrine_Connection $connection) /** * onTransactionCommit - * an event invoked after a Doctrine_Connection transaction is committed - * - * @param Doctrine_Event $event - * @return void + * an event invoked after a Doctrine_Connection transaction is committed. */ public function postTransactionCommit(Doctrine_Event $event) { @@ -203,10 +173,7 @@ public function postTransactionCommit(Doctrine_Event $event) /** * onPreTransactionCommit - * an event invoked before a Doctrine_Connection transaction is committed - * - * @param Doctrine_Event $event - * @return void + * an event invoked before a Doctrine_Connection transaction is committed. */ public function preTransactionCommit(Doctrine_Event $event) { @@ -217,10 +184,7 @@ public function preTransactionCommit(Doctrine_Event $event) /** * onTransactionRollback - * an event invoked after a Doctrine_Connection transaction is being rolled back - * - * @param Doctrine_Event $event - * @return void + * an event invoked after a Doctrine_Connection transaction is being rolled back. */ public function postTransactionRollback(Doctrine_Event $event) { @@ -231,10 +195,7 @@ public function postTransactionRollback(Doctrine_Event $event) /** * onPreTransactionRollback - * an event invoked before a Doctrine_Connection transaction is being rolled back - * - * @param Doctrine_Event $event - * @return void + * an event invoked before a Doctrine_Connection transaction is being rolled back. */ public function preTransactionRollback(Doctrine_Event $event) { @@ -245,10 +206,7 @@ public function preTransactionRollback(Doctrine_Event $event) /** * onTransactionBegin - * an event invoked after a Doctrine_Connection transaction has been started - * - * @param Doctrine_Event $event - * @return void + * an event invoked after a Doctrine_Connection transaction has been started. */ public function postTransactionBegin(Doctrine_Event $event) { @@ -259,10 +217,7 @@ public function postTransactionBegin(Doctrine_Event $event) /** * onTransactionBegin - * an event invoked before a Doctrine_Connection transaction is being started - * - * @param Doctrine_Event $event - * @return void + * an event invoked before a Doctrine_Connection transaction is being started. */ public function preTransactionBegin(Doctrine_Event $event) { @@ -274,10 +229,7 @@ public function preTransactionBegin(Doctrine_Event $event) /** * postSavepointCommit * an event invoked after a Doctrine_Connection transaction with savepoint - * is committed - * - * @param Doctrine_Event $event - * @return void + * is committed. */ public function postSavepointCommit(Doctrine_Event $event) { @@ -289,10 +241,7 @@ public function postSavepointCommit(Doctrine_Event $event) /** * preSavepointCommit * an event invoked before a Doctrine_Connection transaction with savepoint - * is committed - * - * @param Doctrine_Event $event - * @return void + * is committed. */ public function preSavepointCommit(Doctrine_Event $event) { @@ -304,10 +253,7 @@ public function preSavepointCommit(Doctrine_Event $event) /** * postSavepointRollback * an event invoked after a Doctrine_Connection transaction with savepoint - * is being rolled back - * - * @param Doctrine_Event $event - * @return void + * is being rolled back. */ public function postSavepointRollback(Doctrine_Event $event) { @@ -319,10 +265,7 @@ public function postSavepointRollback(Doctrine_Event $event) /** * preSavepointRollback * an event invoked before a Doctrine_Connection transaction with savepoint - * is being rolled back - * - * @param Doctrine_Event $event - * @return void + * is being rolled back. */ public function preSavepointRollback(Doctrine_Event $event) { @@ -334,10 +277,7 @@ public function preSavepointRollback(Doctrine_Event $event) /** * postSavepointCreate * an event invoked after a Doctrine_Connection transaction with savepoint - * has been started - * - * @param Doctrine_Event $event - * @return void + * has been started. */ public function postSavepointCreate(Doctrine_Event $event) { @@ -349,10 +289,7 @@ public function postSavepointCreate(Doctrine_Event $event) /** * preSavepointCreate * an event invoked before a Doctrine_Connection transaction with savepoint - * is being started - * - * @param Doctrine_Event $event - * @return void + * is being started. */ public function preSavepointCreate(Doctrine_Event $event) { @@ -364,10 +301,7 @@ public function preSavepointCreate(Doctrine_Event $event) /** * onCollectionDelete - * an event invoked after a Doctrine_Collection is being deleted - * - * @param Doctrine_Collection $collection - * @return void + * an event invoked after a Doctrine_Collection is being deleted. */ public function onCollectionDelete(Doctrine_Collection $collection) { @@ -378,10 +312,7 @@ public function onCollectionDelete(Doctrine_Collection $collection) /** * onCollectionDelete - * an event invoked after a Doctrine_Collection is being deleted - * - * @param Doctrine_Collection $collection - * @return void + * an event invoked after a Doctrine_Collection is being deleted. */ public function onPreCollectionDelete(Doctrine_Collection $collection) { @@ -405,7 +336,7 @@ public function preConnect(Doctrine_Event $event) } public function preQuery(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preQuery($event); } @@ -419,7 +350,7 @@ public function postQuery(Doctrine_Event $event) } public function prePrepare(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->prePrepare($event); } @@ -447,7 +378,7 @@ public function postExec(Doctrine_Event $event) } public function preError(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preError($event); } @@ -461,7 +392,7 @@ public function postError(Doctrine_Event $event) } public function preFetch(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preFetch($event); } @@ -475,7 +406,7 @@ public function postFetch(Doctrine_Event $event) } public function preFetchAll(Doctrine_Event $event) - { + { foreach ($this->_listeners as $listener) { $listener->preFetchAll($event); } @@ -501,4 +432,4 @@ public function postStmtExecute(Doctrine_Event $event) $listener->postStmtExecute($event); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/EventListener/Exception.php b/lib/Doctrine/EventListener/Exception.php index a0c10cb4a..4c463e852 100644 --- a/lib/Doctrine/EventListener/Exception.php +++ b/lib/Doctrine/EventListener/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_EventListener_Exception + * Doctrine_EventListener_Exception. * - * @package Doctrine - * @subpackage EventListener * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1344 $ + * * @author Konsta Vesterinen */ class Doctrine_EventListener_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/EventListener/Interface.php b/lib/Doctrine/EventListener/Interface.php index 6a3c12e87..bc8488f18 100644 --- a/lib/Doctrine/EventListener/Interface.php +++ b/lib/Doctrine/EventListener/Interface.php @@ -21,48 +21,59 @@ /** * Doctrine_EventListener all event listeners extend this base class - * the empty methods allow child classes to only implement the methods they need to implement + * the empty methods allow child classes to only implement the methods they need to implement. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage EventListener * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ interface Doctrine_EventListener_Interface { public function preTransactionCommit(Doctrine_Event $event); + public function postTransactionCommit(Doctrine_Event $event); public function preTransactionRollback(Doctrine_Event $event); + public function postTransactionRollback(Doctrine_Event $event); public function preTransactionBegin(Doctrine_Event $event); + public function postTransactionBegin(Doctrine_Event $event); public function postConnect(Doctrine_Event $event); + public function preConnect(Doctrine_Event $event); public function preQuery(Doctrine_Event $event); + public function postQuery(Doctrine_Event $event); public function prePrepare(Doctrine_Event $event); + public function postPrepare(Doctrine_Event $event); public function preExec(Doctrine_Event $event); + public function postExec(Doctrine_Event $event); public function preError(Doctrine_Event $event); + public function postError(Doctrine_Event $event); public function preFetch(Doctrine_Event $event); + public function postFetch(Doctrine_Event $event); public function preFetchAll(Doctrine_Event $event); + public function postFetchAll(Doctrine_Event $event); public function preStmtExecute(Doctrine_Event $event); + public function postStmtExecute(Doctrine_Event $event); } diff --git a/lib/Doctrine/Exception.php b/lib/Doctrine/Exception.php index 6db70250d..84c10f097 100644 --- a/lib/Doctrine/Exception.php +++ b/lib/Doctrine/Exception.php @@ -20,64 +20,66 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. * - * @package Doctrine - * @subpackage Exception * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Exception extends Exception -{ +{ /** - * @var array $_errorMessages an array of error messages + * @var array an array of error messages */ protected static $_errorMessages = array( - Doctrine_Core::ERR => 'unknown error', - Doctrine_Core::ERR_ALREADY_EXISTS => 'already exists', - Doctrine_Core::ERR_CANNOT_CREATE => 'can not create', - Doctrine_Core::ERR_CANNOT_ALTER => 'can not alter', - Doctrine_Core::ERR_CANNOT_REPLACE => 'can not replace', - Doctrine_Core::ERR_CANNOT_DELETE => 'can not delete', - Doctrine_Core::ERR_CANNOT_DROP => 'can not drop', - Doctrine_Core::ERR_CONSTRAINT => 'constraint violation', - Doctrine_Core::ERR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint', - Doctrine_Core::ERR_DIVZERO => 'division by zero', - Doctrine_Core::ERR_INVALID => 'invalid', - Doctrine_Core::ERR_INVALID_DATE => 'invalid date or time', - Doctrine_Core::ERR_INVALID_NUMBER => 'invalid number', - Doctrine_Core::ERR_MISMATCH => 'mismatch', - Doctrine_Core::ERR_NODBSELECTED => 'no database selected', - Doctrine_Core::ERR_NOSUCHFIELD => 'no such field', - Doctrine_Core::ERR_NOSUCHTABLE => 'no such table', - Doctrine_Core::ERR_NOT_CAPABLE => 'Doctrine backend not capable', - Doctrine_Core::ERR_NOT_FOUND => 'not found', - Doctrine_Core::ERR_NOT_LOCKED => 'not locked', - Doctrine_Core::ERR_SYNTAX => 'syntax error', - Doctrine_Core::ERR_UNSUPPORTED => 'not supported', - Doctrine_Core::ERR_VALUE_COUNT_ON_ROW => 'value count on row', - Doctrine_Core::ERR_INVALID_DSN => 'invalid DSN', - Doctrine_Core::ERR_CONNECT_FAILED => 'connect failed', - Doctrine_Core::ERR_NEED_MORE_DATA => 'insufficient data supplied', - Doctrine_Core::ERR_EXTENSION_NOT_FOUND=> 'extension not found', - Doctrine_Core::ERR_NOSUCHDB => 'no such database', - Doctrine_Core::ERR_ACCESS_VIOLATION => 'insufficient permissions', - Doctrine_Core::ERR_LOADMODULE => 'error while including on demand module', - Doctrine_Core::ERR_TRUNCATED => 'truncated', - Doctrine_Core::ERR_DEADLOCK => 'deadlock detected', - ); + Doctrine_Core::ERR => 'unknown error', + Doctrine_Core::ERR_ALREADY_EXISTS => 'already exists', + Doctrine_Core::ERR_CANNOT_CREATE => 'can not create', + Doctrine_Core::ERR_CANNOT_ALTER => 'can not alter', + Doctrine_Core::ERR_CANNOT_REPLACE => 'can not replace', + Doctrine_Core::ERR_CANNOT_DELETE => 'can not delete', + Doctrine_Core::ERR_CANNOT_DROP => 'can not drop', + Doctrine_Core::ERR_CONSTRAINT => 'constraint violation', + Doctrine_Core::ERR_CONSTRAINT_NOT_NULL => 'null value violates not-null constraint', + Doctrine_Core::ERR_DIVZERO => 'division by zero', + Doctrine_Core::ERR_INVALID => 'invalid', + Doctrine_Core::ERR_INVALID_DATE => 'invalid date or time', + Doctrine_Core::ERR_INVALID_NUMBER => 'invalid number', + Doctrine_Core::ERR_MISMATCH => 'mismatch', + Doctrine_Core::ERR_NODBSELECTED => 'no database selected', + Doctrine_Core::ERR_NOSUCHFIELD => 'no such field', + Doctrine_Core::ERR_NOSUCHTABLE => 'no such table', + Doctrine_Core::ERR_NOT_CAPABLE => 'Doctrine backend not capable', + Doctrine_Core::ERR_NOT_FOUND => 'not found', + Doctrine_Core::ERR_NOT_LOCKED => 'not locked', + Doctrine_Core::ERR_SYNTAX => 'syntax error', + Doctrine_Core::ERR_UNSUPPORTED => 'not supported', + Doctrine_Core::ERR_VALUE_COUNT_ON_ROW => 'value count on row', + Doctrine_Core::ERR_INVALID_DSN => 'invalid DSN', + Doctrine_Core::ERR_CONNECT_FAILED => 'connect failed', + Doctrine_Core::ERR_NEED_MORE_DATA => 'insufficient data supplied', + Doctrine_Core::ERR_EXTENSION_NOT_FOUND => 'extension not found', + Doctrine_Core::ERR_NOSUCHDB => 'no such database', + Doctrine_Core::ERR_ACCESS_VIOLATION => 'insufficient permissions', + Doctrine_Core::ERR_LOADMODULE => 'error while including on demand module', + Doctrine_Core::ERR_TRUNCATED => 'truncated', + Doctrine_Core::ERR_DEADLOCK => 'deadlock detected', + ); /** - * Return a textual error message for a Doctrine error code + * Return a textual error message for a Doctrine error code. * * @param int|array integer error code, * null to get the current error code-message map, * or an array with a new error code-message map + * @param mixed|null $value * - * @return string error message + * @return string error message */ public function errorMessage($value = null) { @@ -88,5 +90,4 @@ public function errorMessage($value = null) return isset(self::$_errorMessages[$value]) ? self::$_errorMessages[$value] : self::$_errorMessages[Doctrine_Core::ERR]; } - } diff --git a/lib/Doctrine/Export.php b/lib/Doctrine/Export.php index ab56d6620..68d6b591a 100644 --- a/lib/Doctrine/Export.php +++ b/lib/Doctrine/Export.php @@ -20,39 +20,36 @@ */ /** - * Doctrine_Export + * Doctrine_Export. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7653 $ */ class Doctrine_Export extends Doctrine_Connection_Module { protected $valid_default_values = array( - 'text' => '', - 'boolean' => true, - 'integer' => 0, - 'decimal' => 0.0, - 'float' => 0.0, + 'text' => '', + 'boolean' => true, + 'integer' => 0, + 'decimal' => 0.0, + 'float' => 0.0, 'timestamp' => '1970-01-01 00:00:00', - 'time' => '00:00:00', - 'date' => '1970-01-01', - 'clob' => '', - 'blob' => '', - 'string' => '' + 'time' => '00:00:00', + 'date' => '1970-01-01', + 'clob' => '', + 'blob' => '', + 'string' => '', ); /** * drop an existing database - * (this method is implemented by the drivers) - * - * @param string $name name of the database that should be dropped - * @return void + * (this method is implemented by the drivers). */ public function dropDatabase($database) { @@ -63,10 +60,7 @@ public function dropDatabase($database) /** * drop an existing database - * (this method is implemented by the drivers) - * - * @param string $name name of the database that should be dropped - * @return void + * (this method is implemented by the drivers). */ public function dropDatabaseSql($database) { @@ -75,22 +69,22 @@ public function dropDatabaseSql($database) /** * dropTableSql - * drop an existing table + * drop an existing table. + * + * @param string $table name of table that should be dropped from the database * - * @param string $table name of table that should be dropped from the database * @return string */ public function dropTableSql($table) { - return 'DROP TABLE ' . $this->conn->quoteIdentifier($table); + return 'DROP TABLE '.$this->conn->quoteIdentifier($table); } /** * dropTable - * drop an existing table + * drop an existing table. * - * @param string $table name of table that should be dropped from the database - * @return void + * @param string $table name of table that should be dropped from the database */ public function dropTable($table) { @@ -98,11 +92,10 @@ public function dropTable($table) } /** - * drop existing index + * drop existing index. * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the index to be dropped */ public function dropIndex($table, $name) { @@ -110,41 +103,40 @@ public function dropIndex($table, $name) } /** - * dropIndexSql + * dropIndexSql. + * + * @param string $table name of table that should be used in method + * @param string $name name of the index to be dropped * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return string SQL that is used for dropping an index + * @return string SQL that is used for dropping an index */ public function dropIndexSql($table, $name) { $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name)); - - return 'DROP INDEX ' . $name; + + return 'DROP INDEX '.$name; } /** - * drop existing constraint + * drop existing constraint. * - * @param string $table name of table that should be used in method - * @param string $name name of the constraint to be dropped - * @param string $primary hint if the constraint is primary - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the constraint to be dropped + * @param string $primary hint if the constraint is primary */ public function dropConstraint($table, $name, $primary = false) { $table = $this->conn->quoteIdentifier($table); - $name = $this->conn->quoteIdentifier($name); - - return $this->conn->exec('ALTER TABLE ' . $table . ' DROP CONSTRAINT ' . $name); + $name = $this->conn->quoteIdentifier($name); + + return $this->conn->exec('ALTER TABLE '.$table.' DROP CONSTRAINT '.$name); } /** - * drop existing foreign key + * drop existing foreign key. * - * @param string $table name of table that should be used in method - * @param string $name name of the foreign key to be dropped - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the foreign key to be dropped */ public function dropForeignKey($table, $name) { @@ -154,11 +146,11 @@ public function dropForeignKey($table, $name) /** * dropSequenceSql * drop existing sequence - * (this method is implemented by the drivers) + * (this method is implemented by the drivers). * - * @throws Doctrine_Connection_Exception if something fails at database level - * @param string $sequenceName name of the sequence to be dropped - * @return void + * @param string $sequenceName name of the sequence to be dropped + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function dropSequence($sequenceName) { @@ -167,11 +159,11 @@ public function dropSequence($sequenceName) /** * dropSequenceSql - * drop existing sequence + * drop existing sequence. * - * @throws Doctrine_Connection_Exception if something fails at database level * @param string $sequenceName name of the sequence to be dropped - * @return void + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function dropSequenceSql($sequenceName) { @@ -180,10 +172,7 @@ public function dropSequenceSql($sequenceName) /** * create a new database - * (this method is implemented by the drivers) - * - * @param string $name name of the database that should be created - * @return void + * (this method is implemented by the drivers). */ public function createDatabase($database) { @@ -192,9 +181,8 @@ public function createDatabase($database) /** * create a new database - * (this method is implemented by the drivers) + * (this method is implemented by the drivers). * - * @param string $name name of the database that should be created * @return string */ public function createDatabaseSql($database) @@ -203,67 +191,66 @@ public function createDatabaseSql($database) } /** - * create a new table - * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: + * create a new table. + * + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. + * array( + * 'id' => array( + * 'type' => 'integer', + * 'unsigned' => 1 + * 'notnull' => 1 + * 'default' => 0 + * ), + * 'name' => array( + * 'type' => 'text', + * 'length' => 12 + * ), + * 'password' => array( + * 'type' => 'text', + * 'length' => 12 + * ) + * ); + * @param array $options An associative array of table options: * * @return string */ public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } if (empty($fields)) { - throw new Doctrine_Export_Exception('no fields specified for table ' . $name); + throw new Doctrine_Export_Exception('no fields specified for table '.$name); } $queryFields = $this->getFieldDeclarationList($fields); - - if (isset($options['primary']) && ! empty($options['primary'])) { + if (isset($options['primary']) && !empty($options['primary'])) { $primaryKeys = array_map(array($this->conn, 'quoteIdentifier'), array_values($options['primary'])); - $queryFields .= ', PRIMARY KEY(' . implode(', ', $primaryKeys) . ')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $primaryKeys).')'; } - if (isset($options['indexes']) && ! empty($options['indexes'])) { - foreach($options['indexes'] as $index => $definition) { + if (isset($options['indexes']) && !empty($options['indexes'])) { + foreach ($options['indexes'] as $index => $definition) { $indexDeclaration = $this->getIndexDeclaration($index, $definition); // append only created index declarations - if ( ! is_null($indexDeclaration)) { + if (!is_null($indexDeclaration)) { $queryFields .= ', '.$indexDeclaration; - } + } } } - $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields; - + $query = 'CREATE TABLE '.$this->conn->quoteIdentifier($name, true).' ('.$queryFields; + $check = $this->getCheckDeclaration($fields); - if ( ! empty($check)) { - $query .= ', ' . $check; + if (!empty($check)) { + $query .= ', '.$check; } $query .= ')'; @@ -271,25 +258,24 @@ public function createTableSql($name, array $fields, array $options = array()) $sql[] = $query; if (isset($options['foreignKeys'])) { - foreach ((array) $options['foreignKeys'] as $k => $definition) { if (is_array($definition)) { $sql[] = $this->createForeignKeySql($name, $definition); } } } + return $sql; } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * @param array $options An associative array of table options: - * @see Doctrine_Export::createTableSql() + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * @param array $options An associative array of table options: * - * @return void + * @see Doctrine_Export::createTableSql() */ public function createTable($name, array $fields, array $options = array()) { @@ -298,10 +284,10 @@ public function createTable($name, array $fields, array $options = array()) $count = 0; foreach ($fields as $fieldName => $field) { if (isset($field['primary']) && $field['primary']) { - if ($count == 0) { + if (0 == $count) { $options['primary'] = array(); } - $count++; + ++$count; $options['primary'][] = $fieldName; } } @@ -314,18 +300,18 @@ public function createTable($name, array $fields, array $options = array()) } /** - * create sequence - * - * @throws Doctrine_Connection_Exception if something fails at database level - * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); - * @return void + * create sequence. + * + * @param string $seqName name of the sequence to be created + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function createSequence($seqName, $start = 1, array $options = array()) { @@ -334,18 +320,20 @@ public function createSequence($seqName, $start = 1, array $options = array()) /** * return RDBMS specific create sequence statement - * (this method is implemented by the drivers) - * - * @throws Doctrine_Connection_Exception if something fails at database level - * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); + * (this method is implemented by the drivers). + * + * @param string $seqName name of the sequence to be created + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); + * * @return string + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function createSequenceSql($seqName, $start = 1, array $options = array()) { @@ -353,16 +341,16 @@ public function createSequenceSql($seqName, $start = 1, array $options = array() } /** - * create a constraint on a table + * create a constraint on a table. * - * @param string $table name of the table on which the constraint is to be created - * @param string $name name of the constraint to be created - * @param array $definition associative array that defines properties of the constraint to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the constraint fields as array - * constraints. Each entry of this array is set to another type of associative - * array that specifies properties of the constraint that are specific to - * each field. + * @param string $table name of the table on which the constraint is to be created + * @param string $name name of the constraint to be created + * @param array $definition associative array that defines properties of the constraint to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the constraint fields as array + * constraints. Each entry of this array is set to another type of associative + * array that specifies properties of the constraint that are specific to + * each field. * * Example * array( @@ -371,26 +359,25 @@ public function createSequenceSql($seqName, $start = 1, array $options = array() * 'last_login' => array() * ) * ) - * @return void */ public function createConstraint($table, $name, $definition) { $sql = $this->createConstraintSql($table, $name, $definition); - + return $this->conn->exec($sql); } /** - * create a constraint on a table + * create a constraint on a table. * - * @param string $table name of the table on which the constraint is to be created - * @param string $name name of the constraint to be created - * @param array $definition associative array that defines properties of the constraint to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the constraint fields as array - * constraints. Each entry of this array is set to another type of associative - * array that specifies properties of the constraint that are specific to - * each field. + * @param string $table name of the table on which the constraint is to be created + * @param string $name name of the constraint to be created + * @param array $definition associative array that defines properties of the constraint to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the constraint fields as array + * constraints. Each entry of this array is set to another type of associative + * array that specifies properties of the constraint that are specific to + * each field. * * Example * array( @@ -399,13 +386,12 @@ public function createConstraint($table, $name, $definition) * 'last_login' => array() * ) * ) - * @return void */ public function createConstraintSql($table, $name, $definition) { $table = $this->conn->quoteIdentifier($table); - $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name)); - $query = 'ALTER TABLE ' . $table . ' ADD CONSTRAINT ' . $name; + $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name)); + $query = 'ALTER TABLE '.$table.' ADD CONSTRAINT '.$name; if (isset($definition['primary']) && $definition['primary']) { $query .= ' PRIMARY KEY'; @@ -417,22 +403,22 @@ public function createConstraintSql($table, $name, $definition) foreach (array_keys($definition['fields']) as $field) { $fields[] = $this->conn->quoteIdentifier($field, true); } - $query .= ' ('. implode(', ', $fields) . ')'; + $query .= ' ('.implode(', ', $fields).')'; return $query; } /** - * Get the stucture of a field into an array + * Get the stucture of a field into an array. * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the index fields as array + * indexes. Each entry of this array is set to another type of associative + * array that specifies properties of the index that are specific to + * each field. * * Currently, only the sorting property is supported. It should be used * to define the sorting direction of the index. It may be set to either @@ -451,7 +437,6 @@ public function createConstraintSql($table, $name, $definition) * 'last_login' => array() * ) * ) - * @return void */ public function createIndex($table, $name, array $definition) { @@ -459,79 +444,81 @@ public function createIndex($table, $name, array $definition) } /** - * Get the stucture of a field into an array + * Get the stucture of a field into an array. + * + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. * @see Doctrine_Export::createIndex() + * * @return string */ public function createIndexSql($table, $name, array $definition) { - $table = $this->conn->quoteIdentifier($table); - $name = $this->conn->quoteIdentifier($name); - $type = ''; - + $table = $this->conn->quoteIdentifier($table); + $name = $this->conn->quoteIdentifier($name); + $type = ''; + if (isset($definition['type'])) { switch (strtolower($definition['type'])) { case 'unique': - $type = strtoupper($definition['type']) . ' '; - break; + $type = strtoupper($definition['type']).' '; + break; default: - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name . ' in table ' . $table - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name.' in table '.$table); } } - $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table; + $query = 'CREATE '.$type.'INDEX '.$name.' ON '.$table; $fields = array(); foreach ($definition['fields'] as $field) { $fields[] = $this->conn->quoteIdentifier($field); } - $query .= ' (' . implode(', ', $fields) . ')'; + $query .= ' ('.implode(', ', $fields).')'; return $query; - } + } + /** - * createForeignKeySql + * createForeignKeySql. + * + * @param string $table name of the table on which the foreign key is to be created + * @param array $definition associative array that defines properties of the foreign key to be created * - * @param string $table name of the table on which the foreign key is to be created - * @param array $definition associative array that defines properties of the foreign key to be created. * @return string */ public function createForeignKeySql($table, array $definition) { $table = $this->conn->quoteIdentifier($table); - $query = 'ALTER TABLE ' . $table . ' ADD ' . $this->getForeignKeyDeclaration($definition); - return $query; + return 'ALTER TABLE '.$table.' ADD '.$this->getForeignKeyDeclaration($definition); } /** - * createForeignKey + * createForeignKey. + * + * @param string $table name of the table on which the foreign key is to be created + * @param array $definition associative array that defines properties of the foreign key to be created * - * @param string $table name of the table on which the foreign key is to be created - * @param array $definition associative array that defines properties of the foreign key to be created. * @return string */ public function createForeignKey($table, array $definition) { $sql = $this->createForeignKeySql($table, $definition); - + return $this->conn->execute($sql); } /** * alter an existing table - * (this method is implemented by the drivers) + * (this method is implemented by the drivers). * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -544,79 +531,14 @@ public function createForeignKey($table, array $definition) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the MDB2 parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the MDB2 parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @return void + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise */ public function alterTable($name, array $changes, $check = false) { $sql = $this->alterTableSql($name, $changes, $check); - + if (is_string($sql) && $sql) { $this->conn->execute($sql); } @@ -624,14 +546,16 @@ public function alterTable($name, array $changes, $check = false) /** * generates the sql for altering an existing table - * (this method is implemented by the drivers) + * (this method is implemented by the drivers). + * + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type * + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. * @see Doctrine_Export::alterTable() + * * @return string */ public function alterTableSql($name, array $changes, $check = false) @@ -640,13 +564,13 @@ public function alterTableSql($name, array $changes, $check = false) } /** - * Get declaration of a number of field in bulk + * Get declaration of a number of field in bulk. * - * @param array $fields a multidimensional associative array. - * The first dimension determines the field name, while the second - * dimension is keyed with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param array $fields a multidimensional associative array. + * The first dimension determines the field name, while the second + * dimension is keyed with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -675,6 +599,7 @@ public function getFieldDeclarationList(array $fields) $queryFields[] = $query; } + return implode(', ', $queryFields); } @@ -682,10 +607,10 @@ public function getFieldDeclarationList(array $fields) * Obtain DBMS specific SQL code portion needed to declare a generic type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param string $name name the field to be declared + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -711,43 +636,40 @@ public function getFieldDeclarationList(array $fields) * check * column check constraint * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getDeclaration($name, array $field) { + $default = $this->getDefaultFieldDeclaration($field); - $default = $this->getDefaultFieldDeclaration($field); - - $charset = (isset($field['charset']) && $field['charset']) ? - ' ' . $this->getCharsetFieldDeclaration($field['charset']) : ''; + $charset = (isset($field['charset']) && $field['charset']) ? + ' '.$this->getCharsetFieldDeclaration($field['charset']) : ''; $collation = (isset($field['collation']) && $field['collation']) ? - ' ' . $this->getCollationFieldDeclaration($field['collation']) : ''; + ' '.$this->getCollationFieldDeclaration($field['collation']) : ''; - $notnull = $this->getNotNullFieldDeclaration($field); + $notnull = $this->getNotNullFieldDeclaration($field); - $unique = (isset($field['unique']) && $field['unique']) ? - ' ' . $this->getUniqueFieldDeclaration() : ''; + $unique = (isset($field['unique']) && $field['unique']) ? + ' '.$this->getUniqueFieldDeclaration() : ''; - $check = (isset($field['check']) && $field['check']) ? - ' ' . $field['check'] : ''; + $check = (isset($field['check']) && $field['check']) ? + ' '.$field['check'] : ''; - $method = 'get' . $field['type'] . 'Declaration'; + $method = 'get'.$field['type'].'Declaration'; try { if (method_exists($this->conn->dataDict, $method)) { - return $this->conn->dataDict->$method($name, $field); - } else { - $dec = $this->conn->dataDict->getNativeDeclaration($field); + return $this->conn->dataDict->{$method}($name, $field); } + $dec = $this->conn->dataDict->getNativeDeclaration($field); return $this->conn->quoteIdentifier($name, true) - . ' ' . $dec . $charset . $default . $notnull . $unique . $check . $collation; + .' '.$dec.$charset.$default.$notnull.$unique.$check.$collation; } catch (Exception $e) { - throw new Doctrine_Exception('Around field ' . $name . ': ' . $e->getMessage()); + throw new Doctrine_Exception('Around field '.$name.': '.$e->getMessage()); } - } /** @@ -755,70 +677,69 @@ public function getDeclaration($name, array $field) * Obtain DBMS specific SQL code portion needed to set a default value * declaration to be used in statements like CREATE TABLE. * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @param array $field field definition array + * + * @return string DBMS specific SQL code portion needed to set a default value */ public function getDefaultFieldDeclaration($field) { $default = ''; if (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : $this->valid_default_values[$field['type']]; - if ($field['default'] === '' && - ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL)) { + if ('' === $field['default'] + && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL)) { $field['default'] = null; } } - if ($field['type'] === 'boolean') { + if ('boolean' === $field['type']) { $field['default'] = $this->conn->convertBooleans($field['default']); } - $default = ' DEFAULT ' . (is_null($field['default']) + $default = ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'], $field['type'])); } return $default; } - /** * getNotNullFieldDeclaration * Obtain DBMS specific SQL code portion needed to set a NOT NULL * declaration to be used in statements like CREATE TABLE. * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @return string DBMS specific SQL code portion needed to set a default value */ public function getNotNullFieldDeclaration(array $definition) { return (isset($definition['notnull']) && $definition['notnull']) ? ' NOT NULL' : ''; } - /** * Obtain DBMS specific SQL code portion needed to set a CHECK constraint * declaration to be used in statements like CREATE TABLE. * - * @param array $definition check definition - * @return string DBMS specific SQL code portion needed to set a CHECK constraint + * @param array $definition check definition + * + * @return string DBMS specific SQL code portion needed to set a CHECK constraint */ public function getCheckDeclaration(array $definition) { $constraints = array(); foreach ($definition as $field => $def) { if (is_string($def)) { - $constraints[] = 'CHECK (' . $def . ')'; + $constraints[] = 'CHECK ('.$def.')'; } else { if (isset($def['min'])) { - $constraints[] = 'CHECK (' . $field . ' >= ' . $def['min'] . ')'; + $constraints[] = 'CHECK ('.$field.' >= '.$def['min'].')'; } if (isset($def['max'])) { - $constraints[] = 'CHECK (' . $field . ' <= ' . $def['max'] . ')'; + $constraints[] = 'CHECK ('.$field.' <= '.$def['max'].')'; } } } @@ -830,32 +751,31 @@ public function getCheckDeclaration(array $definition) * Obtain DBMS specific SQL code portion needed to set an index * declaration to be used in statements like CREATE TABLE. * - * @param string $name name of the index - * @param array $definition index definition - * @return string DBMS specific SQL code portion needed to set an index + * @param string $name name of the index + * @param array $definition index definition + * + * @return string DBMS specific SQL code portion needed to set an index */ public function getIndexDeclaration($name, array $definition) { - $name = $this->conn->quoteIdentifier($name); - $type = ''; + $name = $this->conn->quoteIdentifier($name); + $type = ''; if (isset($definition['type'])) { - if (strtolower($definition['type']) == 'unique') { - $type = strtoupper($definition['type']) . ' '; + if ('unique' == strtolower($definition['type'])) { + $type = strtoupper($definition['type']).' '; } else { - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name); } } - if ( ! isset($definition['fields']) || ! is_array($definition['fields'])) { - throw new Doctrine_Export_Exception('No columns given for index ' . $name); + if (!isset($definition['fields']) || !is_array($definition['fields'])) { + throw new Doctrine_Export_Exception('No columns given for index '.$name); } - $query = $type . 'INDEX ' . $name; + $query = $type.'INDEX '.$name; - $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')'; + $query .= ' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; return $query; } @@ -877,6 +797,7 @@ public function getIndexFieldDeclarationList(array $fields) $ret[] = $this->conn->quoteIdentifier($definition); } } + return implode(', ', $ret); } @@ -891,8 +812,8 @@ public function getIndexFieldDeclarationList(array $fields) * SQL error for any database that does not support temporary tables, or that * requires a different SQL command from "CREATE TEMPORARY TABLE". * - * @return string The string required to be placed between "CREATE" and "TABLE" - * to generate a temporary table, if possible. + * @return string the string required to be placed between "CREATE" and "TABLE" + * to generate a temporary table, if possible */ public function getTemporaryTableQuery() { @@ -904,8 +825,8 @@ public function getTemporaryTableQuery() * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint * of a field declaration to be used in statements like CREATE TABLE. * - * @param array $definition an associative array with the following structure: - * name optional constraint name + * @param array $definition an associative array with the following structure: + * name optional constraint name * * local the local field(s) * @@ -938,12 +859,12 @@ public function getTemporaryTableQuery() * * SET DEFAULT * - * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint - * of a field declaration. + * @return string DBMS specific SQL code portion needed to set the FOREIGN KEY constraint + * of a field declaration */ public function getForeignKeyDeclaration(array $definition) { - $sql = $this->getForeignKeyBaseDeclaration($definition); + $sql = $this->getForeignKeyBaseDeclaration($definition); $sql .= $this->getAdvancedForeignKeyOptions($definition); return $sql; @@ -954,30 +875,33 @@ public function getForeignKeyDeclaration(array $definition) * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition foreign key definition + * @param array $definition foreign key definition + * * @return string */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; - if ( ! empty($definition['onUpdate'])) { - $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialAction($definition['onUpdate']); + if (!empty($definition['onUpdate'])) { + $query .= ' ON UPDATE '.$this->getForeignKeyReferentialAction($definition['onUpdate']); } - if ( ! empty($definition['onDelete'])) { - $query .= ' ON DELETE ' . $this->getForeignKeyReferentialAction($definition['onDelete']); + if (!empty($definition['onDelete'])) { + $query .= ' ON DELETE '.$this->getForeignKeyReferentialAction($definition['onDelete']); } + return $query; } /** - * getForeignKeyReferentialAction + * getForeignKeyReferentialAction. * * returns given referential action in uppercase if valid, otherwise throws * an exception * - * @throws Doctrine_Exception_Exception if unknown referential action given - * @param string $action foreign key referential action + * @param string $action foreign key referential action * @param string foreign key referential action in uppercase + * + * @throws Doctrine_Exception_Exception if unknown referential action given */ public function getForeignKeyReferentialAction($action) { @@ -989,9 +913,9 @@ public function getForeignKeyReferentialAction($action) case 'RESTRICT': case 'SET DEFAULT': return $upper; - break; + break; default: - throw new Doctrine_Export_Exception('Unknown foreign key referential action \'' . $upper . '\' given.'); + throw new Doctrine_Export_Exception('Unknown foreign key referential action \''.$upper.'\' given.'); } } @@ -1000,38 +924,37 @@ public function getForeignKeyReferentialAction($action) * Obtain DBMS specific SQL code portion needed to set the FOREIGN KEY constraint * of a field declaration to be used in statements like CREATE TABLE. * - * @param array $definition * @return string */ public function getForeignKeyBaseDeclaration(array $definition) { $sql = ''; if (isset($definition['name'])) { - $sql .= 'CONSTRAINT ' . $this->conn->quoteIdentifier($this->conn->formatter->getForeignKeyName($definition['name'])) . ' '; + $sql .= 'CONSTRAINT '.$this->conn->quoteIdentifier($this->conn->formatter->getForeignKeyName($definition['name'])).' '; } $sql .= 'FOREIGN KEY ('; - if ( ! isset($definition['local'])) { + if (!isset($definition['local'])) { throw new Doctrine_Export_Exception('Local reference field missing from definition.'); } - if ( ! isset($definition['foreign'])) { + if (!isset($definition['foreign'])) { throw new Doctrine_Export_Exception('Foreign reference field missing from definition.'); } - if ( ! isset($definition['foreignTable'])) { + if (!isset($definition['foreignTable'])) { throw new Doctrine_Export_Exception('Foreign reference table missing from definition.'); } - if ( ! is_array($definition['local'])) { + if (!is_array($definition['local'])) { $definition['local'] = array($definition['local']); } - if ( ! is_array($definition['foreign'])) { + if (!is_array($definition['foreign'])) { $definition['foreign'] = array($definition['foreign']); } $sql .= implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['local'])) - . ') REFERENCES ' - . $this->conn->quoteIdentifier($definition['foreignTable']) . '(' - . implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['foreign'])) . ')'; + .') REFERENCES ' + .$this->conn->quoteIdentifier($definition['foreignTable']).'(' + .implode(', ', array_map(array($this->conn, 'quoteIdentifier'), $definition['foreign'])).')'; return $sql; } @@ -1040,8 +963,8 @@ public function getForeignKeyBaseDeclaration(array $definition) * Obtain DBMS specific SQL code portion needed to set the UNIQUE constraint * of a field declaration to be used in statements like CREATE TABLE. * - * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint - * of a field declaration. + * @return string DBMS specific SQL code portion needed to set the UNIQUE constraint + * of a field declaration */ public function getUniqueFieldDeclaration() { @@ -1052,9 +975,10 @@ public function getUniqueFieldDeclaration() * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET * of a field declaration to be used in statements like CREATE TABLE. * - * @param string $charset name of the charset - * @return string DBMS specific SQL code portion needed to set the CHARACTER SET - * of a field declaration. + * @param string $charset name of the charset + * + * @return string DBMS specific SQL code portion needed to set the CHARACTER SET + * of a field declaration */ public function getCharsetFieldDeclaration($charset) { @@ -1065,9 +989,10 @@ public function getCharsetFieldDeclaration($charset) * Obtain DBMS specific SQL code portion needed to set the COLLATION * of a field declaration to be used in statements like CREATE TABLE. * - * @param string $collation name of the collation - * @return string DBMS specific SQL code portion needed to set the COLLATION - * of a field declaration. + * @param string $collation name of the collation + * + * @return string DBMS specific SQL code portion needed to set the COLLATION + * of a field declaration */ public function getCollationFieldDeclaration($collation) { @@ -1076,7 +1001,7 @@ public function getCollationFieldDeclaration($collation) /** * exportSchema - * method for exporting Doctrine_Record classes to a schema + * method for exporting Doctrine_Record classes to a schema. * * if the directory parameter is given this method first iterates * recursively trhough the given directory in order to find any model classes @@ -1084,14 +1009,14 @@ public function getCollationFieldDeclaration($collation) * Then it iterates through all declared classes and creates tables for the ones * that extend Doctrine_Record and are not abstract classes * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @param string $directory optional directory parameter - * @return void + * @param string $directory optional directory parameter + * + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function exportSchema($directory = null) { - if ($directory !== null) { + if (null !== $directory) { $models = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($directory)); } else { $models = Doctrine_Core::getLoadedModels(); @@ -1102,151 +1027,148 @@ public function exportSchema($directory = null) public function exportSortedClassesSql($classes, $groupByConnection = true) { - $connections = array(); - foreach ($classes as $class) { - $connection = Doctrine_Manager::getInstance()->getConnectionForComponent($class); - $connectionName = $connection->getName(); - - if ( ! isset($connections[$connectionName])) { - $connections[$connectionName] = array( - 'create_tables' => array(), - 'create_sequences' => array(), - 'create_indexes' => array(), - 'alters' => array(), - 'create_triggers' => array(), - ); - } - - $sql = $connection->export->exportClassesSql(array($class)); - - // Build array of all the creates - // We need these to happen first - foreach ($sql as $key => $query) { - // If create table statement - if (substr($query, 0, strlen('CREATE TABLE')) == 'CREATE TABLE') { - $connections[$connectionName]['create_tables'][] = $query; - - unset($sql[$key]); - continue; - } - - // If create sequence statement - if (substr($query, 0, strlen('CREATE SEQUENCE')) == 'CREATE SEQUENCE') { - $connections[$connectionName]['create_sequences'][] = $query; - - unset($sql[$key]); - continue; - } - - // If create index statement - if (preg_grep("/CREATE ([^ ]* )?INDEX/", array($query))) { - $connections[$connectionName]['create_indexes'][] = $query; - - unset($sql[$key]); - continue; - } - - // If alter table statement or oracle anonymous block enclosing alter - if (substr($query, 0, strlen('ALTER TABLE')) == 'ALTER TABLE' - || substr($query, 0, strlen('DECLARE')) == 'DECLARE') { - $connections[$connectionName]['alters'][] = $query; - - unset($sql[$key]); - continue; - } - - // If create trgger statement - if (substr($query, 0, strlen('CREATE TRIGGER')) == 'CREATE TRIGGER') { - $connections[$connectionName]['create_triggers'][] = $query; - - unset($sql[$key]); - continue; - } - - // If comment statement - if (substr($query, 0, strlen('COMMENT ON')) == 'COMMENT ON') { - $connections[$connectionName]['comments'][] = $query; - - unset($sql[$key]); - continue; - } - } - } - - // Loop over all the sql again to merge everything together so it is in the correct order - $build = array(); - foreach ($connections as $connectionName => $sql) { - $build[$connectionName] = array_unique(array_merge($sql['create_tables'], $sql['create_sequences'], $sql['create_indexes'], $sql['alters'], $sql['create_triggers'])); - } - - if ( ! $groupByConnection) { - $new = array(); - foreach($build as $connectionname => $sql) { - $new = array_unique(array_merge($new, $sql)); - } - $build = $new; - } - return $build; + $connections = array(); + foreach ($classes as $class) { + $connection = Doctrine_Manager::getInstance()->getConnectionForComponent($class); + $connectionName = $connection->getName(); + + if (!isset($connections[$connectionName])) { + $connections[$connectionName] = array( + 'create_tables' => array(), + 'create_sequences' => array(), + 'create_indexes' => array(), + 'alters' => array(), + 'create_triggers' => array(), + ); + } + + $sql = $connection->export->exportClassesSql(array($class)); + + // Build array of all the creates + // We need these to happen first + foreach ($sql as $key => $query) { + // If create table statement + if ('CREATE TABLE' == substr($query, 0, strlen('CREATE TABLE'))) { + $connections[$connectionName]['create_tables'][] = $query; + + unset($sql[$key]); + continue; + } + + // If create sequence statement + if ('CREATE SEQUENCE' == substr($query, 0, strlen('CREATE SEQUENCE'))) { + $connections[$connectionName]['create_sequences'][] = $query; + + unset($sql[$key]); + continue; + } + + // If create index statement + if (preg_grep('/CREATE ([^ ]* )?INDEX/', array($query))) { + $connections[$connectionName]['create_indexes'][] = $query; + + unset($sql[$key]); + continue; + } + + // If alter table statement or oracle anonymous block enclosing alter + if ('ALTER TABLE' == substr($query, 0, strlen('ALTER TABLE')) + || 'DECLARE' == substr($query, 0, strlen('DECLARE'))) { + $connections[$connectionName]['alters'][] = $query; + + unset($sql[$key]); + continue; + } + + // If create trgger statement + if ('CREATE TRIGGER' == substr($query, 0, strlen('CREATE TRIGGER'))) { + $connections[$connectionName]['create_triggers'][] = $query; + + unset($sql[$key]); + continue; + } + + // If comment statement + if ('COMMENT ON' == substr($query, 0, strlen('COMMENT ON'))) { + $connections[$connectionName]['comments'][] = $query; + + unset($sql[$key]); + continue; + } + } + } + + // Loop over all the sql again to merge everything together so it is in the correct order + $build = array(); + foreach ($connections as $connectionName => $sql) { + $build[$connectionName] = array_unique(array_merge($sql['create_tables'], $sql['create_sequences'], $sql['create_indexes'], $sql['alters'], $sql['create_triggers'])); + } + + if (!$groupByConnection) { + $new = array(); + foreach ($build as $connectionname => $sql) { + $new = array_unique(array_merge($new, $sql)); + } + $build = $new; + } + + return $build; } /** * exportClasses - * method for exporting Doctrine_Record classes to a schema + * method for exporting Doctrine_Record classes to a schema. * * FIXME: This function has ugly hacks in it to make sure sql is inserted in the correct order. * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @param array $classes - * @return void + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ - public function exportClasses(array $classes) - { - $queries = $this->exportSortedClassesSql($classes); - - foreach ($queries as $connectionName => $sql) { - $connection = Doctrine_Manager::getInstance()->getConnection($connectionName); - - $connection->beginTransaction(); - - foreach ($sql as $query) { - try { - $connection->exec($query); - } catch (Doctrine_Connection_Exception $e) { - // we only want to silence table already exists errors - if ($e->getPortableCode() !== Doctrine_Core::ERR_ALREADY_EXISTS) { - $connection->rollback(); - throw new Doctrine_Export_Exception($e->getMessage() . '. Failing Query: ' . $query); - } - } - } - - $connection->commit(); - } - } + public function exportClasses(array $classes) + { + $queries = $this->exportSortedClassesSql($classes); + + foreach ($queries as $connectionName => $sql) { + $connection = Doctrine_Manager::getInstance()->getConnection($connectionName); + + $connection->beginTransaction(); + + foreach ($sql as $query) { + try { + $connection->exec($query); + } catch (Doctrine_Connection_Exception $e) { + // we only want to silence table already exists errors + if (Doctrine_Core::ERR_ALREADY_EXISTS !== $e->getPortableCode()) { + $connection->rollback(); + throw new Doctrine_Export_Exception($e->getMessage().'. Failing Query: '.$query); + } + } + } + + $connection->commit(); + } + } /** * exportClassesSql - * method for exporting Doctrine_Record classes to a schema + * method for exporting Doctrine_Record classes to a schema. * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @param array $classes - * @return void + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function exportClassesSql(array $classes) { $models = Doctrine_Core::filterInvalidModels($classes); - + $sql = array(); - + foreach ($models as $name) { $record = new $name(); $table = $record->getTable(); $parents = $table->getOption('joinedParents'); foreach ($parents as $parent) { - $data = $table->getConnection()->getTable($parent)->getExportableFormat(); + $data = $table->getConnection()->getTable($parent)->getExportableFormat(); $query = $this->conn->export->createTableSql($data['tableName'], $data['columns'], $data['options']); @@ -1254,7 +1176,7 @@ public function exportClassesSql(array $classes) } // Don't export the tables with attribute EXPORT_NONE' - if ($table->getAttribute(Doctrine_Core::ATTR_EXPORT) === Doctrine_Core::EXPORT_NONE) { + if (Doctrine_Core::EXPORT_NONE === $table->getAttribute(Doctrine_Core::ATTR_EXPORT)) { continue; } @@ -1271,38 +1193,39 @@ public function exportClassesSql(array $classes) if ($table->getAttribute(Doctrine_Core::ATTR_EXPORT) & Doctrine_Core::EXPORT_PLUGINS) { $sql = array_merge($sql, $this->exportGeneratorsSql($table)); } - + // DC-474: Remove dummy $record from repository to not pollute it during export $table->getRepository()->evict($record->getOid()); unset($record); } - + $sql = array_unique($sql); - + rsort($sql); return $sql; } /** - * fetches all generators recursively for given table + * fetches all generators recursively for given table. * - * @param Doctrine_Table $table table object to retrieve the generators from - * @return array an array of Doctrine_Record_Generator objects + * @param Doctrine_Table $table table object to retrieve the generators from + * + * @return array an array of Doctrine_Record_Generator objects */ public function getAllGenerators(Doctrine_Table $table) { $generators = array(); foreach ($table->getGenerators() as $name => $generator) { - if ($generator === null) { - continue; + if (null === $generator) { + continue; } $generators[] = $generator; $generatorTable = $generator->getTable(); - + if ($generatorTable instanceof Doctrine_Table) { $generators = array_merge($generators, $this->getAllGenerators($generatorTable)); } @@ -1313,18 +1236,19 @@ public function getAllGenerators(Doctrine_Table $table) /** * exportGeneratorsSql - * exports plugin tables for given table + * exports plugin tables for given table. + * + * @param Doctrine_Table $table the table in which the generators belong to * - * @param Doctrine_Table $table the table in which the generators belong to - * @return array an array of sql strings + * @return array an array of sql strings */ public function exportGeneratorsSql(Doctrine_Table $table) { - $sql = array(); + $sql = array(); foreach ($this->getAllGenerators($table) as $name => $generator) { $table = $generator->getTable(); - + // Make sure plugin has a valid table if ($table instanceof Doctrine_Table) { $data = $table->getExportableFormat(); @@ -1340,7 +1264,7 @@ public function exportGeneratorsSql(Doctrine_Table $table) /** * exportSql - * returns the sql for exporting Doctrine_Record classes to a schema + * returns the sql for exporting Doctrine_Record classes to a schema. * * if the directory parameter is given this method first iterates * recursively trhough the given directory in order to find any model classes @@ -1348,30 +1272,31 @@ public function exportGeneratorsSql(Doctrine_Table $table) * Then it iterates through all declared classes and creates tables for the ones * that extend Doctrine_Record and are not abstract classes * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @param string $directory optional directory parameter - * @return void + * @param string $directory optional directory parameter + * + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function exportSql($directory = null) { - if ($directory !== null) { + if (null !== $directory) { $models = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($directory)); } else { $models = Doctrine_Core::getLoadedModels(); } - + return $this->exportSortedClassesSql($models, false); } /** * exportTable - * exports given table into database based on column and option definitions + * exports given table into database based on column and option definitions. + * + * @return bool whether or not the export operation was successful + * false if table already existed in the database * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @return boolean whether or not the export operation was successful - * false if table already existed in the database + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function exportTable(Doctrine_Table $table) { @@ -1379,9 +1304,9 @@ public function exportTable(Doctrine_Table $table) $data = $table->getExportableFormat(); $this->conn->export->createTable($data['tableName'], $data['columns'], $data['options']); - } catch(Doctrine_Connection_Exception $e) { + } catch (Doctrine_Connection_Exception $e) { // we only want to silence table already exists errors - if ($e->getPortableCode() !== Doctrine_Core::ERR_ALREADY_EXISTS) { + if (Doctrine_Core::ERR_ALREADY_EXISTS !== $e->getPortableCode()) { throw $e; } } diff --git a/lib/Doctrine/Export/Exception.php b/lib/Doctrine/Export/Exception.php index cb27a7595..7a3926ac7 100644 --- a/lib/Doctrine/Export/Exception.php +++ b/lib/Doctrine/Export/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Export_Exception + * Doctrine_Export_Exception. * - * @package Doctrine - * @subpackage Export * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Export_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Export/Mssql.php b/lib/Doctrine/Export/Mssql.php index 30db562fa..521813f18 100644 --- a/lib/Doctrine/Export/Mssql.php +++ b/lib/Doctrine/Export/Mssql.php @@ -20,77 +20,77 @@ */ /** - * Doctrine_Export_Mssql + * Doctrine_Export_Mssql. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @author Frank M. Kromann (PEAR MDB2 Mssql driver) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7660 $ */ class Doctrine_Export_Mssql extends Doctrine_Export { - /** - * create a new database + /** + * create a new database. * * @param string $name name of the database that should be created - * @return void */ public function createDatabase($name) { $name = $this->conn->quoteIdentifier($name, true); - $query = "CREATE DATABASE $name"; + $query = "CREATE DATABASE {$name}"; $options = $this->conn->getOptions(); if (isset($options['database_device']) && $options['database_device']) { - $query.= ' ON '.$this->conn->options['database_device']; - $query.= $this->conn->options['database_size'] ? '=' . + $query .= ' ON '.$this->conn->options['database_device']; + $query .= $this->conn->options['database_size'] ? '='. $this->conn->options['database_size'] : ''; } + return $this->conn->standaloneQuery($query, array(), true); } /** - * drop an existing database + * drop an existing database. * * @param string $name name of the database that should be dropped - * @return void */ public function dropDatabase($name) { $name = $this->conn->quoteIdentifier($name, true); - return $this->conn->standaloneQuery('DROP DATABASE ' . $name, array(), true); + + return $this->conn->standaloneQuery('DROP DATABASE '.$name, array(), true); } /** * Override the parent method. * - * @return string The string required to be placed between "CREATE" and "TABLE" - * to generate a temporary table, if possible. + * @return string the string required to be placed between "CREATE" and "TABLE" + * to generate a temporary table, if possible */ public function getTemporaryTableQuery() { return ''; - } + } public function dropIndexSql($table, $name) { $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name)); $table = $this->conn->quoteIdentifier($table); - return 'DROP INDEX ' . $name . ' ON ' . $table; + return 'DROP INDEX '.$name.' ON '.$table; } /** - * alter an existing table + * alter an existing table. * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -103,78 +103,13 @@ public function dropIndexSql($table, $name) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the Metabase parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the Metabase parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @return void + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise */ public function alterTable($name, array $changes, $check = false) { - if ( !$name ) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } @@ -187,7 +122,7 @@ public function alterTable($name, array $changes, $check = false) case 'change': break; default: - throw new Doctrine_Export_Exception('alterTable: change type "' . $changeName . '" not yet supported'); + throw new Doctrine_Export_Exception('alterTable: change type "'.$changeName.'" not yet supported'); } } @@ -195,11 +130,10 @@ public function alterTable($name, array $changes, $check = false) return true; } - $query = ''; - $postQueries = ''; //SQL Server uses a stored procedure to rename objects + $postQueries = ''; // SQL Server uses a stored procedure to rename objects - if ( ! empty($changes['name'])) { + if (!empty($changes['name'])) { $changeName = $this->conn->quoteIdentifier($changes['name'], true); $postQueries .= sprintf( @@ -209,47 +143,46 @@ public function alterTable($name, array $changes, $check = false) ); } - //ADD TABLE - if ( ! empty($changes['add']) && is_array($changes['add'])) { + // ADD TABLE + if (!empty($changes['add']) && is_array($changes['add'])) { foreach ($changes['add'] as $fieldName => $field) { if ($query) { $query .= ', '; } - $query .= 'ADD ' . $this->getDeclaration($fieldName, $field); + $query .= 'ADD '.$this->getDeclaration($fieldName, $field); } } - //REMOVE TABLE - if ( ! empty($changes['remove']) && is_array($changes['remove'])) { - if ($query) { - $query .= ', '; - } + // REMOVE TABLE + if (!empty($changes['remove']) && is_array($changes['remove'])) { + if ($query) { + $query .= ', '; + } $query .= 'DROP COLUMN '; $dropped = array(); foreach ($changes['remove'] as $fieldName => $field) { - $fieldName = $this->conn->quoteIdentifier($fieldName, true); $dropped[] = $fieldName; } - $query .= implode(', ', $dropped) . ' '; + $query .= implode(', ', $dropped).' '; } $rename = array(); - if ( ! empty($changes['rename']) && is_array($changes['rename'])) { + if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { $rename[$field['name']] = $fieldName; } } - //CHANGE (COLUMN DEFINITION) - if ( ! empty($changes['change']) && is_array($changes['change'])) { + // CHANGE (COLUMN DEFINITION) + if (!empty($changes['change']) && is_array($changes['change'])) { if ($query) { - $query.= ', '; + $query .= ', '; } - $query .= "ALTER COLUMN "; + $query .= 'ALTER COLUMN '; $altered = array(); foreach ($changes['change'] as $fieldName => $field) { @@ -267,9 +200,9 @@ public function alterTable($name, array $changes, $check = false) // Remove the default constraint declaration from the statement $altered[] = str_replace($matches[0], '', $declaration); - if (count($matches) === 6) { + if (6 === count($matches)) { // No constraint name provided. Try to make sure it's unique - $defaultName = 'DF__' . $name . '__' . $fieldName . '__' . mt_rand(); + $defaultName = 'DF__'.$name.'__'.$fieldName.'__'.mt_rand(); $defaultValue = $matches[5]; } else { $defaultName = $matches[2]; @@ -289,15 +222,14 @@ public function alterTable($name, array $changes, $check = false) } $query .= implode(sprintf( - "; ALTER TABLE %s ALTER COLUMN ", + '; ALTER TABLE %s ALTER COLUMN ', $this->conn->quoteIdentifier($name, true) - ), $altered) . ' '; + ), $altered).' '; } - //RENAME (COLUMN) - if ( ! empty($rename) && is_array($rename)) { + // RENAME (COLUMN) + if (!empty($rename) && is_array($rename)) { foreach ($rename as $renameName => $renamedField) { - $field = $changes['rename'][$renamedField]; $renamedField = $this->conn->quoteIdentifier($renamedField); @@ -310,7 +242,7 @@ public function alterTable($name, array $changes, $check = false) } } - if ( ! $query && ! $postQueries) { + if (!$query && !$postQueries) { return false; } @@ -318,7 +250,7 @@ public function alterTable($name, array $changes, $check = false) $finalQuery = ''; if ($query) { - $finalQuery .= 'ALTER TABLE ' . $name . ' ' . trim($query) . ';'; + $finalQuery .= 'ALTER TABLE '.$name.' '.trim($query).';'; } if ($postQueries) { @@ -329,93 +261,95 @@ public function alterTable($name, array $changes, $check = false) } /** - * create sequence + * create sequence. * * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); + * * @return string */ public function createSequence($seqName, $start = 1, array $options = array()) { $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($seqName), true); $seqcolName = $this->conn->quoteIdentifier($this->conn->options['seqcol_name'], true); - $query = 'CREATE TABLE ' . $sequenceName . ' (' . $seqcolName . - ' INT PRIMARY KEY CLUSTERED IDENTITY(' . $start . ', 1) NOT NULL)'; + $query = 'CREATE TABLE '.$sequenceName.' ('.$seqcolName. + ' INT PRIMARY KEY CLUSTERED IDENTITY('.$start.', 1) NOT NULL)'; $res = $this->conn->exec($query); - if ($start == 1) { + if (1 == $start) { return true; } try { - $query = 'SET IDENTITY_INSERT ' . $sequenceName . ' ON ' . - 'INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES ( ' . $start . ')'; + $query = 'SET IDENTITY_INSERT '.$sequenceName.' ON '. + 'INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES ( '.$start.')'; $res = $this->conn->exec($query); } catch (Exception $e) { - $result = $this->conn->exec('DROP TABLE ' . $sequenceName); + $result = $this->conn->exec('DROP TABLE '.$sequenceName); } + return true; } /** - * This function drops an existing sequence + * This function drops an existing sequence. * - * @param string $seqName name of the sequence to be dropped - * @return void + * @param string $seqName name of the sequence to be dropped */ public function dropSequenceSql($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->getSequenceName($seqName), true); - return 'DROP TABLE ' . $sequenceName; + + return 'DROP TABLE '.$sequenceName; } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. + * array( + * 'id' => array( + * 'type' => 'integer', + * 'unsigned' => 1 + * 'notnull' => 1 + * 'default' => 0 + * ), + * 'name' => array( + * 'type' => 'text', + * 'length' => 12 + * ), + * 'password' => array( + * 'type' => 'text', + * 'length' => 12 + * ) + * ); + * @param array $options An associative array of table options: * * @return string */ public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } if (empty($fields)) { - throw new Doctrine_Export_Exception('no fields specified for table ' . $name); + throw new Doctrine_Export_Exception('no fields specified for table '.$name); } // Use field declaration of primary if the primary option not set - if ( ! isset($options['primary'])) { + if (!isset($options['primary'])) { foreach ($fields as $fieldName => $fieldData) { if (isset($fieldData['primary']) && $fieldData['primary']) { $options['primary'][$fieldName] = $fieldName; @@ -426,38 +360,38 @@ public function createTableSql($name, array $fields, array $options = array()) if (isset($options['primary'])) { foreach ($options['primary'] as $fieldName) { if (isset($fields[$fieldName])) { - $fields[$fieldName]['notnull'] = true; //Silently forcing NOT NULL as MSSQL will kill a query that has a nullable PK + $fields[$fieldName]['notnull'] = true; // Silently forcing NOT NULL as MSSQL will kill a query that has a nullable PK } } } $queryFields = $this->getFieldDeclarationList($fields); - if (isset($options['primary']) && ! empty($options['primary'])) { + if (isset($options['primary']) && !empty($options['primary'])) { $primaryKeys = array_map(array($this->conn, 'quoteIdentifier'), array_values($options['primary'])); - $queryFields .= ', PRIMARY KEY(' . implode(', ', $primaryKeys) . ')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $primaryKeys).')'; } - $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields; - + $query = 'CREATE TABLE '.$this->conn->quoteIdentifier($name, true).' ('.$queryFields; + $check = $this->getCheckDeclaration($fields); - if ( ! empty($check)) { - $query .= ', ' . $check; + if (!empty($check)) { + $query .= ', '.$check; } $query .= ')'; $sql[] = $query; - - if (isset($options['indexes']) && ! empty($options['indexes'])) { - foreach($options['indexes'] as $index => $definition) { + + if (isset($options['indexes']) && !empty($options['indexes'])) { + foreach ($options['indexes'] as $index => $definition) { if (is_array($definition)) { - $sql[] = $this->createIndexSql($name,$index, $definition); + $sql[] = $this->createIndexSql($name, $index, $definition); } } } - + if (isset($options['foreignKeys'])) { foreach ((array) $options['foreignKeys'] as $k => $definition) { if (is_array($definition)) { @@ -474,51 +408,51 @@ public function createTableSql($name, array $fields, array $options = array()) * Obtain DBMS specific SQL code portion needed to set a NOT NULL * declaration to be used in statements like CREATE TABLE. * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @return string DBMS specific SQL code portion needed to set a default value */ public function getNotNullFieldDeclaration(array $definition) { return ( - (isset($definition['notnull']) && $definition['notnull']) || - (isset($definition['primary']) && $definition['primary']) + (isset($definition['notnull']) && $definition['notnull']) + || (isset($definition['primary']) && $definition['primary']) ) ? ' NOT NULL' : ' NULL'; } /** * @see Doctrine_Export::getDefaultFieldDeclaration * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @param array $field field definition array + * + * @return string DBMS specific SQL code portion needed to set a default value */ public function getDefaultFieldDeclaration($field) { $default = ''; if (array_key_exists('default', $field)) { - if ($field['default'] === '') { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : $this->valid_default_values[$field['type']]; - if ($field['default'] === '' && - ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL)) { + if ('' === $field['default'] + && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL)) { $field['default'] = null; } } - if ($field['type'] === 'boolean') { + if ('boolean' === $field['type']) { $field['default'] = $this->conn->convertBooleans($field['default']); } if (array_key_exists('defaultConstraintName', $field)) { - $default .= ' CONSTRAINT ' . $field['defaultConstraintName']; + $default .= ' CONSTRAINT '.$field['defaultConstraintName']; } - $default .= ' DEFAULT ' . (is_null($field['default']) + $default .= ' DEFAULT '.(is_null($field['default']) ? 'NULL' : $this->conn->quote($field['default'], $field['type'])); } - + return $default; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Export/Mysql.php b/lib/Doctrine/Export/Mysql.php index 097f68776..c7be961f8 100644 --- a/lib/Doctrine/Export/Mysql.php +++ b/lib/Doctrine/Export/Mysql.php @@ -20,104 +20,102 @@ */ /** - * Doctrine_Export_Mysql + * Doctrine_Export_Mysql. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7653 $ */ class Doctrine_Export_Mysql extends Doctrine_Export { /** - * drop existing constraint + * drop existing constraint. * - * @param string $table name of table that should be used in method - * @param string $name name of the constraint to be dropped - * @param string $primary hint if the constraint is primary - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the constraint to be dropped + * @param string $primary hint if the constraint is primary */ public function dropConstraint($table, $name, $primary = false) { $table = $this->conn->quoteIdentifier($table); - if ( ! $primary) { - $name = 'CONSTRAINT ' . $this->conn->quoteIdentifier($name); + if (!$primary) { + $name = 'CONSTRAINT '.$this->conn->quoteIdentifier($name); } else { $name = 'PRIMARY KEY'; } - return $this->conn->exec('ALTER TABLE ' . $table . ' DROP ' . $name); + return $this->conn->exec('ALTER TABLE '.$table.' DROP '.$name); } /** - * createDatabaseSql + * createDatabaseSql. * - * @param string $name - * @return void + * @param string $name */ public function createDatabaseSql($name) { - return 'CREATE DATABASE ' . $this->conn->quoteIdentifier($name, true); + return 'CREATE DATABASE '.$this->conn->quoteIdentifier($name, true); } /** - * drop an existing database + * drop an existing database. * * @param string $name name of the database that should be dropped + * * @return string */ public function dropDatabaseSql($name) { return array( 'SET FOREIGN_KEY_CHECKS = 0', - 'DROP DATABASE ' . $this->conn->quoteIdentifier($name), - 'SET FOREIGN_KEY_CHECKS = 1' + 'DROP DATABASE '.$this->conn->quoteIdentifier($name), + 'SET FOREIGN_KEY_CHECKS = 1', ); } /** - * create a new table - * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * 'type' => 'innodb', - * ); - * - * @return void + * create a new table. + * + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. + * array( + * 'id' => array( + * 'type' => 'integer', + * 'unsigned' => 1 + * 'notnull' => 1 + * 'default' => 0 + * ), + * 'name' => array( + * 'type' => 'text', + * 'length' => 12 + * ), + * 'password' => array( + * 'type' => 'text', + * 'length' => 12 + * ) + * ); + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * 'type' => 'innodb', + * ); */ - public function createTableSql($name, array $fields, array $options = array()) + public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); + } if (empty($fields)) { throw new Doctrine_Export_Exception('no fields specified for table "'.$name.'"'); @@ -132,34 +130,34 @@ public function createTableSql($name, array $fields, array $options = array()) if (isset($options['indexes'])) { foreach ($options['indexes'] as $definition) { if (is_string($definition['fields'])) { - // Check if index already exists on the column - $found = $found || ($local == $definition['fields']); - } else if (in_array($local, $definition['fields']) && count($definition['fields']) === 1) { + // Check if index already exists on the column + $found = $found || ($local == $definition['fields']); + } elseif (in_array($local, $definition['fields']) && 1 === count($definition['fields'])) { // Index already exists on the column $found = true; } } } - if (isset($options['primary']) && !empty($options['primary']) && - in_array($local, $options['primary'])) { + if (isset($options['primary']) && !empty($options['primary']) + && in_array($local, $options['primary'])) { // field is part of the PK and therefore already indexed $found = true; } - - if ( ! $found) { + + if (!$found) { if (is_array($local)) { - foreach($local as $localidx) { - $options['indexes'][$localidx] = array('fields' => array($localidx => array())); - } + foreach ($local as $localidx) { + $options['indexes'][$localidx] = array('fields' => array($localidx => array())); + } } else { - $options['indexes'][$local] = array('fields' => array($local => array())); + $options['indexes'][$local] = array('fields' => array($local => array())); } } } } // add all indexes - if (isset($options['indexes']) && ! empty($options['indexes'])) { + if (isset($options['indexes']) && !empty($options['indexes'])) { // Case Insensitive checking for duplicate indexes... $dupes = array(); foreach ($options['indexes'] as $key => $index) { @@ -171,30 +169,30 @@ public function createTableSql($name, array $fields, array $options = array()) } unset($dupes); - foreach($options['indexes'] as $index => $definition) { - $queryFields .= ', ' . $this->getIndexDeclaration($index, $definition); + foreach ($options['indexes'] as $index => $definition) { + $queryFields .= ', '.$this->getIndexDeclaration($index, $definition); } } // attach all primary keys - if (isset($options['primary']) && ! empty($options['primary'])) { + if (isset($options['primary']) && !empty($options['primary'])) { $keyColumns = array_values($options['primary']); $keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns); - $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $keyColumns).')'; } - $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields . ')'; + $query = 'CREATE TABLE '.$this->conn->quoteIdentifier($name, true).' ('.$queryFields.')'; $optionStrings = array(); if (isset($options['comment'])) { - $optionStrings['comment'] = 'COMMENT = ' . $this->conn->quote($options['comment'], 'text'); + $optionStrings['comment'] = 'COMMENT = '.$this->conn->quote($options['comment'], 'text'); } if (isset($options['charset'])) { - $optionStrings['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset']; + $optionStrings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; } if (isset($options['collate'])) { - $optionStrings['collate'] = 'COLLATE ' . $options['collate']; + $optionStrings['collate'] = 'COLLATE '.$options['collate']; } $type = false; @@ -207,22 +205,22 @@ public function createTableSql($name, array $fields, array $options = array()) } if ($type) { - $optionStrings[] = 'ENGINE = ' . $type; + $optionStrings[] = 'ENGINE = '.$type; } - if ( ! empty($optionStrings)) { - $query.= ' '.implode(' ', $optionStrings); + if (!empty($optionStrings)) { + $query .= ' '.implode(' ', $optionStrings); } $sql[] = $query; if (isset($options['foreignKeys'])) { - foreach ((array) $options['foreignKeys'] as $k => $definition) { if (is_array($definition)) { $sql[] = $this->createForeignKeySql($name, $definition); } } } + return $sql; } @@ -230,10 +228,10 @@ public function createTableSql($name, array $fields, array $options = array()) * Obtain DBMS specific SQL code portion needed to declare a generic type * field to be used in statements like CREATE TABLE. * - * @param string $name name the field to be declared. - * @param array $field associative array with the name of the properties - * of the field being declared as array indexes. Currently, the types - * of supported field properties are as follows: + * @param string $name name the field to be declared + * @param array $field associative array with the name of the properties + * of the field being declared as array indexes. Currently, the types + * of supported field properties are as follows: * * length * Integer value that determines the maximum length of the text @@ -255,54 +253,52 @@ public function createTableSql($name, array $fields, array $options = array()) * check * column check constraint * - * @return string DBMS specific SQL code portion that should be used to - * declare the specified field. + * @return string DBMS specific SQL code portion that should be used to + * declare the specified field */ public function getDeclaration($name, array $field) { + $default = $this->getDefaultFieldDeclaration($field); - $default = $this->getDefaultFieldDeclaration($field); - - $charset = (isset($field['charset']) && $field['charset']) ? - ' ' . $this->getCharsetFieldDeclaration($field['charset']) : ''; + $charset = (isset($field['charset']) && $field['charset']) ? + ' '.$this->getCharsetFieldDeclaration($field['charset']) : ''; $collation = (isset($field['collation']) && $field['collation']) ? - ' ' . $this->getCollationFieldDeclaration($field['collation']) : ''; + ' '.$this->getCollationFieldDeclaration($field['collation']) : ''; - $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; + $notnull = (isset($field['notnull']) && $field['notnull']) ? ' NOT NULL' : ''; - $unique = (isset($field['unique']) && $field['unique']) ? - ' ' . $this->getUniqueFieldDeclaration() : ''; + $unique = (isset($field['unique']) && $field['unique']) ? + ' '.$this->getUniqueFieldDeclaration() : ''; - $check = (isset($field['check']) && $field['check']) ? - ' ' . $field['check'] : ''; + $check = (isset($field['check']) && $field['check']) ? + ' '.$field['check'] : ''; - $comment = (isset($field['comment']) && $field['comment']) ? - " COMMENT " . $this->conn->quote($field['comment'], 'text') : ''; + $comment = (isset($field['comment']) && $field['comment']) ? + ' COMMENT '.$this->conn->quote($field['comment'], 'text') : ''; - $method = 'get' . $field['type'] . 'Declaration'; + $method = 'get'.$field['type'].'Declaration'; try { if (method_exists($this->conn->dataDict, $method)) { - return $this->conn->dataDict->$method($name, $field); - } else { - $dec = $this->conn->dataDict->getNativeDeclaration($field); + return $this->conn->dataDict->{$method}($name, $field); } - - return $this->conn->quoteIdentifier($name, true) - . ' ' . $dec . $charset . $default . $notnull . $comment . $unique . $check . $collation; + $dec = $this->conn->dataDict->getNativeDeclaration($field); + + return $this->conn->quoteIdentifier($name, true) + .' '.$dec.$charset.$default.$notnull.$comment.$unique.$check.$collation; } catch (Exception $e) { - throw new Doctrine_Exception('Around field ' . $name . ': ' . $e->getMessage() . "\n\n" . $e->getTraceAsString() . "\n\n"); + throw new Doctrine_Exception('Around field '.$name.': '.$e->getMessage()."\n\n".$e->getTraceAsString()."\n\n"); } } /** - * alter an existing table + * alter an existing table. * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -315,78 +311,15 @@ public function getDeclaration($name, array $field) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the Metabase parser. + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the Metabase parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @return boolean + * @return bool */ public function alterTableSql($name, array $changes, $check = false) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } foreach ($changes as $changeName => $change) { @@ -398,7 +331,7 @@ public function alterTableSql($name, array $changes, $check = false) case 'name': break; default: - throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported'); + throw new Doctrine_Export_Exception('change type "'.$changeName.'" not yet supported'); } } @@ -407,41 +340,41 @@ public function alterTableSql($name, array $changes, $check = false) } $query = ''; - if ( ! empty($changes['name'])) { + if (!empty($changes['name'])) { $change_name = $this->conn->quoteIdentifier($changes['name']); - $query .= 'RENAME TO ' . $change_name; + $query .= 'RENAME TO '.$change_name; } - if ( ! empty($changes['add']) && is_array($changes['add'])) { + if (!empty($changes['add']) && is_array($changes['add'])) { foreach ($changes['add'] as $fieldName => $field) { if ($query) { - $query.= ', '; + $query .= ', '; } - $query.= 'ADD ' . $this->getDeclaration($fieldName, $field); + $query .= 'ADD '.$this->getDeclaration($fieldName, $field); } } - if ( ! empty($changes['remove']) && is_array($changes['remove'])) { + if (!empty($changes['remove']) && is_array($changes['remove'])) { foreach ($changes['remove'] as $fieldName => $field) { if ($query) { $query .= ', '; } $fieldName = $this->conn->quoteIdentifier($fieldName); - $query .= 'DROP ' . $fieldName; + $query .= 'DROP '.$fieldName; } } $rename = array(); - if ( ! empty($changes['rename']) && is_array($changes['rename'])) { + if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { $rename[$field['name']] = $fieldName; } } - if ( ! empty($changes['change']) && is_array($changes['change'])) { + if (!empty($changes['change']) && is_array($changes['change'])) { foreach ($changes['change'] as $fieldName => $field) { if ($query) { - $query.= ', '; + $query .= ', '; } if (isset($rename[$fieldName])) { $oldFieldName = $rename[$fieldName]; @@ -450,62 +383,63 @@ public function alterTableSql($name, array $changes, $check = false) $oldFieldName = $fieldName; } $oldFieldName = $this->conn->quoteIdentifier($oldFieldName, true); - $query .= 'CHANGE ' . $oldFieldName . ' ' - . $this->getDeclaration($fieldName, $field['definition']); + $query .= 'CHANGE '.$oldFieldName.' ' + .$this->getDeclaration($fieldName, $field['definition']); } } - if ( ! empty($rename) && is_array($rename)) { + if (!empty($rename) && is_array($rename)) { foreach ($rename as $renameName => $renamedField) { if ($query) { - $query.= ', '; + $query .= ', '; } $field = $changes['rename'][$renamedField]; $renamedField = $this->conn->quoteIdentifier($renamedField, true); - $query .= 'CHANGE ' . $renamedField . ' ' - . $this->getDeclaration($field['name'], $field['definition']); + $query .= 'CHANGE '.$renamedField.' ' + .$this->getDeclaration($field['name'], $field['definition']); } } - if ( ! $query) { + if (!$query) { return false; } $name = $this->conn->quoteIdentifier($name, true); - - return 'ALTER TABLE ' . $name . ' ' . $query; + + return 'ALTER TABLE '.$name.' '.$query; } /** - * create sequence - * - * @param string $sequenceName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * 'type' => 'innodb', - * ); - * @return boolean + * create sequence. + * + * @param string $sequenceName name of the sequence to be created + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * 'type' => 'innodb', + * ); + * + * @return bool */ public function createSequence($sequenceName, $start = 1, array $options = array()) { - $sequenceName = $this->conn->quoteIdentifier($sequenceName, true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $sequenceName = $this->conn->quoteIdentifier($sequenceName, true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); $optionsStrings = array(); - if (isset($options['comment']) && ! empty($options['comment'])) { - $optionsStrings['comment'] = 'COMMENT = ' . $this->conn->quote($options['comment'], 'string'); + if (isset($options['comment']) && !empty($options['comment'])) { + $optionsStrings['comment'] = 'COMMENT = '.$this->conn->quote($options['comment'], 'string'); } - if (isset($options['charset']) && ! empty($options['charset'])) { - $optionsStrings['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset']; + if (isset($options['charset']) && !empty($options['charset'])) { + $optionsStrings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; if (isset($options['collate'])) { - $optionsStrings['charset'] .= ' COLLATE ' . $options['collate']; + $optionsStrings['charset'] .= ' COLLATE '.$options['collate']; } } @@ -517,53 +451,53 @@ public function createSequence($sequenceName, $start = 1, array $options = array $type = $this->conn->getAttribute(Doctrine_Core::ATTR_DEFAULT_TABLE_TYPE); } if ($type) { - $optionsStrings[] = 'ENGINE = ' . $type; + $optionsStrings[] = 'ENGINE = '.$type; } - try { - $query = 'CREATE TABLE ' . $sequenceName - . ' (' . $seqcolName . ' BIGINT NOT NULL AUTO_INCREMENT, PRIMARY KEY (' - . $seqcolName . ')) ' . implode(' ', $optionsStrings); + $query = 'CREATE TABLE '.$sequenceName + .' ('.$seqcolName.' BIGINT NOT NULL AUTO_INCREMENT, PRIMARY KEY (' + .$seqcolName.')) '.implode(' ', $optionsStrings); - $res = $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { + $res = $this->conn->exec($query); + } catch (Doctrine_Connection_Exception $e) { throw new Doctrine_Export_Exception('could not create sequence table'); } - if ($start == 1 && $res == 1) + if (1 == $start && 1 == $res) { return true; + } - $query = 'INSERT INTO ' . $sequenceName - . ' (' . $seqcolName . ') VALUES (' . ($start - 1) . ')'; + $query = 'INSERT INTO '.$sequenceName + .' ('.$seqcolName.') VALUES ('.($start - 1).')'; - $res = $this->conn->exec($query); + $res = $this->conn->exec($query); - if ($res == 1) + if (1 == $res) { return true; + } // Handle error try { - $result = $this->conn->exec('DROP TABLE ' . $sequenceName); - } catch(Doctrine_Connection_Exception $e) { + $result = $this->conn->exec('DROP TABLE '.$sequenceName); + } catch (Doctrine_Connection_Exception $e) { throw new Doctrine_Export_Exception('could not drop inconsistent sequence table'); } - - } /** - * Get the stucture of a field into an array + * Get the stucture of a field into an array. * * @author Leoncx - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. + * + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the index fields as array + * indexes. Each entry of this array is set to another type of associative + * array that specifies properties of the index that are specific to + * each field. * * Currently, only the sorting property is supported. It should be used * to define the sorting direction of the index. It may be set to either @@ -583,110 +517,107 @@ public function createSequence($sequenceName, $start = 1, array $options = array * 'last_login' => array() * ) * ) + * * @throws PDOException - * @return void */ public function createIndexSql($table, $name, array $definition) { - $table = $table; - $table = $this->conn->quoteIdentifier($table, true); + $table = $table; + $table = $this->conn->quoteIdentifier($table, true); - $name = $this->conn->formatter->getIndexName($name); - $name = $this->conn->quoteIdentifier($name); - $type = ''; + $name = $this->conn->formatter->getIndexName($name); + $name = $this->conn->quoteIdentifier($name); + $type = ''; if (isset($definition['type'])) { switch (strtolower($definition['type'])) { case 'fulltext': case 'unique': - $type = strtoupper($definition['type']) . ' '; - break; + $type = strtoupper($definition['type']).' '; + break; default: - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name . ' in table ' . $table - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name.' in table '.$table); } } - $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table; - $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')'; + $query = 'CREATE '.$type.'INDEX '.$name.' ON '.$table; + $query .= ' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; return $query; } - /** + /** * getDefaultDeclaration * Obtain DBMS specific SQL code portion needed to set a default value * declaration to be used in statements like CREATE TABLE. * - * @param array $field field definition array - * @return string DBMS specific SQL code portion needed to set a default value + * @param array $field field definition array + * + * @return string DBMS specific SQL code portion needed to set a default value */ public function getDefaultFieldDeclaration($field) { $default = ''; - if (isset($field['default']) && ( ! isset($field['length']) || $field['length'] <= 255)) { - if ($field['default'] === '') { + if (isset($field['default']) && (!isset($field['length']) || $field['length'] <= 255)) { + if ('' === $field['default']) { $field['default'] = empty($field['notnull']) ? null : $this->valid_default_values[$field['type']]; - if ($field['default'] === '' + if ('' === $field['default'] && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EMPTY_TO_NULL) ) { $field['default'] = ' '; } } - + // Proposed patch: - if ($field['type'] == 'enum' && $this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) { + if ('enum' == $field['type'] && $this->conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) { $fieldType = 'varchar'; } else { $fieldType = $field['type']; } - - $default = ' DEFAULT ' . (is_null($field['default']) - ? 'NULL' + + $default = ' DEFAULT '.(is_null($field['default']) + ? 'NULL' : $this->conn->quote($field['default'], $fieldType)); - //$default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']); + // $default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']); } - + return $default; } /** - * Obtain DBMS specific SQL code portion needed to set an index + * Obtain DBMS specific SQL code portion needed to set an index * declaration to be used in statements like CREATE TABLE. * - * @param string $charset name of the index - * @param array $definition index definition - * @return string DBMS specific SQL code portion needed to set an index + * @param array $definition index definition + * + * @return string DBMS specific SQL code portion needed to set an index */ public function getIndexDeclaration($name, array $definition) { - $name = $this->conn->formatter->getIndexName($name); - $type = ''; + $name = $this->conn->formatter->getIndexName($name); + $type = ''; if (isset($definition['type'])) { switch (strtolower($definition['type'])) { case 'fulltext': case 'unique': - $type = strtoupper($definition['type']) . ' '; - break; + $type = strtoupper($definition['type']).' '; + break; default: - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name); } } - - if ( ! isset($definition['fields'])) { - throw new Doctrine_Export_Exception('No columns given for index ' . $name); + + if (!isset($definition['fields'])) { + throw new Doctrine_Export_Exception('No columns given for index '.$name); } - if ( ! is_array($definition['fields'])) { + if (!is_array($definition['fields'])) { $definition['fields'] = array($definition['fields']); } - $query = $type . 'INDEX ' . $this->conn->quoteIdentifier($name); + $query = $type.'INDEX '.$this->conn->quoteIdentifier($name); + + $query .= ' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; - $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')'; - return $query; } @@ -706,7 +637,7 @@ public function getIndexFieldDeclarationList(array $fields) if (is_array($field)) { if (isset($field['length'])) { - $fieldString .= '(' . $field['length'] . ')'; + $fieldString .= '('.$field['length'].')'; } if (isset($field['sorting'])) { @@ -714,7 +645,7 @@ public function getIndexFieldDeclarationList(array $fields) switch ($sort) { case 'ASC': case 'DESC': - $fieldString .= ' ' . $sort; + $fieldString .= ' '.$sort; break; default: throw new Doctrine_Export_Exception('Unknown index sorting option given.'); @@ -725,6 +656,7 @@ public function getIndexFieldDeclarationList(array $fields) } $declFields[] = $fieldString; } + return implode(', ', $declFields); } @@ -757,63 +689,63 @@ public function getCollationFieldDeclaration($collation) * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition * @return string */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; - if ( ! empty($definition['match'])) { - $query .= ' MATCH ' . $definition['match']; + if (!empty($definition['match'])) { + $query .= ' MATCH '.$definition['match']; } - if ( ! empty($definition['onUpdate'])) { - $query .= ' ON UPDATE ' . $this->getForeignKeyReferentialAction($definition['onUpdate']); + if (!empty($definition['onUpdate'])) { + $query .= ' ON UPDATE '.$this->getForeignKeyReferentialAction($definition['onUpdate']); } - if ( ! empty($definition['onDelete'])) { - $query .= ' ON DELETE ' . $this->getForeignKeyReferentialAction($definition['onDelete']); + if (!empty($definition['onDelete'])) { + $query .= ' ON DELETE '.$this->getForeignKeyReferentialAction($definition['onDelete']); } + return $query; } /** - * drop existing index + * drop existing index. * - * @param string $table name of table that should be used in method - * @param string $name name of the index to be dropped - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the index to be dropped */ public function dropIndexSql($table, $name) { - $table = $this->conn->quoteIdentifier($table, true); - $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name), true); - return 'DROP INDEX ' . $name . ' ON ' . $table; + $table = $this->conn->quoteIdentifier($table, true); + $name = $this->conn->quoteIdentifier($this->conn->formatter->getIndexName($name), true); + + return 'DROP INDEX '.$name.' ON '.$table; } /** - * dropTable + * dropTable. + * + * @param string $table name of table that should be dropped from the database * - * @param string $table name of table that should be dropped from the database * @throws PDOException - * @return void */ public function dropTableSql($table) { - $table = $this->conn->quoteIdentifier($table, true); - return 'DROP TABLE ' . $table; + $table = $this->conn->quoteIdentifier($table, true); + + return 'DROP TABLE '.$table; } /** - * drop existing foreign key + * drop existing foreign key. * - * @param string $table name of table that should be used in method - * @param string $name name of the foreign key to be dropped - * @return void + * @param string $table name of table that should be used in method + * @param string $name name of the foreign key to be dropped */ public function dropForeignKey($table, $name) { $table = $this->conn->quoteIdentifier($table); - $name = $this->conn->quoteIdentifier($this->conn->formatter->getForeignKeyName($name)); + $name = $this->conn->quoteIdentifier($this->conn->formatter->getForeignKeyName($name)); - return $this->conn->exec('ALTER TABLE ' . $table . ' DROP FOREIGN KEY ' . $name); + return $this->conn->exec('ALTER TABLE '.$table.' DROP FOREIGN KEY '.$name); } } diff --git a/lib/Doctrine/Export/Oracle.php b/lib/Doctrine/Export/Oracle.php index 0fea53d35..53a8802e4 100644 --- a/lib/Doctrine/Export/Oracle.php +++ b/lib/Doctrine/Export/Oracle.php @@ -20,59 +20,59 @@ */ /** - * Doctrine_Export_Oracle + * Doctrine_Export_Oracle. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Export_Oracle extends Doctrine_Export { /** - * create a new database + * create a new database. * - * @param object $db database object that is extended by this class * @param string $name name of the database that should be created - * @return boolean success of operation + * + * @return bool success of operation */ public function createDatabase($name) { if ($this->conn->getAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE)) { - $username = $name; - $password = $this->conn->dsn['password'] ? $this->conn->dsn['password'] : $name; + $username = $name; + $password = $this->conn->dsn['password'] ? $this->conn->dsn['password'] : $name; $tablespace = $this->conn->options['default_tablespace'] ? ' DEFAULT TABLESPACE '.$this->conn->options['default_tablespace'] : ''; - $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password . $tablespace; + $query = 'CREATE USER '.$username.' IDENTIFIED BY '.$password.$tablespace; $result = $this->conn->exec($query); try { - $query = 'GRANT CREATE SESSION, CREATE TABLE, UNLIMITED TABLESPACE, CREATE SEQUENCE, CREATE TRIGGER TO ' . $username; + $query = 'GRANT CREATE SESSION, CREATE TABLE, UNLIMITED TABLESPACE, CREATE SEQUENCE, CREATE TRIGGER TO '.$username; $result = $this->conn->exec($query); } catch (Exception $e) { $this->dropDatabase($username); } } + return true; } /** - * drop an existing database + * drop an existing database. * - * @param object $this->conn database object that is extended by this class * @param string $name name of the database that should be dropped - * @return boolean success of operation - * @access public + * + * @return bool success of operation */ public function dropDatabase($name) { - $sql = <<conn->getAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE)) { $username = $name; - $this->conn->exec('DROP USER ' . $username . ' CASCADE'); + $this->conn->exec('DROP USER '.$username.' CASCADE'); } } /** - * add an autoincrement sequence + trigger + * add an autoincrement sequence + trigger. * * @param string $name name of the PK field * @param string $table name of the table * @param string $start start value for the sequence - * @return string Sql code - * @access private + * + * @return string Sql code */ public function _makeAutoincrement($name, $table, $start = 1) { - $sql = array(); + $sql = array(); - if ( ! $this->conn->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { - $table = strtoupper($table); + if (!$this->conn->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { + $table = strtoupper($table); } - $indexName = $table . '_AI_PK'; + $indexName = $table.'_AI_PK'; $definition = array( 'primary' => true, 'fields' => array($name => true), ); - + $sql[] = 'DECLARE constraints_Count NUMBER; BEGIN @@ -125,10 +125,10 @@ public function _makeAutoincrement($name, $table, $start = 1) IF constraints_Count = 0 THEN EXECUTE IMMEDIATE \''.$this->createConstraintSql($table, $indexName, $definition).'\'; END IF; -END;'; - +END;'; + if (is_null($start)) { - $query = 'SELECT MAX(' . $this->conn->quoteIdentifier($name, true) . ') FROM ' . $this->conn->quoteIdentifier($table, true); + $query = 'SELECT MAX('.$this->conn->quoteIdentifier($name, true).') FROM '.$this->conn->quoteIdentifier($table, true); $start = $this->conn->fetchOne($query); ++$start; @@ -137,50 +137,50 @@ public function _makeAutoincrement($name, $table, $start = 1) $sql[] = $this->createSequenceSql($table, $start); $sequenceName = $this->conn->formatter->getSequenceName($table); - $triggerName = $this->conn->quoteIdentifier($table . '_AI_PK', true); + $triggerName = $this->conn->quoteIdentifier($table.'_AI_PK', true); $table = $this->conn->quoteIdentifier($table, true); - $name = $this->conn->quoteIdentifier($name, true); - $sql[] = 'CREATE TRIGGER ' . $triggerName . ' + $name = $this->conn->quoteIdentifier($name, true); + $sql[] = 'CREATE TRIGGER '.$triggerName.' BEFORE INSERT - ON ' . $table . ' + ON '.$table.' FOR EACH ROW DECLARE last_Sequence NUMBER; last_InsertID NUMBER; BEGIN - IF (:NEW.' . $name . ' IS NULL OR :NEW.'.$name.' = 0) THEN - SELECT ' . $this->conn->quoteIdentifier($sequenceName) . '.NEXTVAL INTO :NEW.' . $name . ' FROM DUAL; + IF (:NEW.'.$name.' IS NULL OR :NEW.'.$name.' = 0) THEN + SELECT '.$this->conn->quoteIdentifier($sequenceName).'.NEXTVAL INTO :NEW.'.$name.' FROM DUAL; ELSE SELECT NVL(Last_Number, 0) INTO last_Sequence FROM User_Sequences - WHERE UPPER(Sequence_Name) = UPPER(\'' . $sequenceName . '\'); - SELECT :NEW.' . $name . ' INTO last_InsertID FROM DUAL; + WHERE UPPER(Sequence_Name) = UPPER(\''.$sequenceName.'\'); + SELECT :NEW.'.$name.' INTO last_InsertID FROM DUAL; WHILE (last_InsertID > last_Sequence) LOOP - SELECT ' . $this->conn->quoteIdentifier($sequenceName) . '.NEXTVAL INTO last_Sequence FROM DUAL; + SELECT '.$this->conn->quoteIdentifier($sequenceName).'.NEXTVAL INTO last_Sequence FROM DUAL; END LOOP; END IF; END;'; + return $sql; } /** - * drop an existing autoincrement sequence + trigger + * drop an existing autoincrement sequence + trigger. * * @param string $table name of the table - * @return void */ public function dropAutoincrement($table) { $table = strtoupper($table); - $triggerName = $table . '_AI_PK'; + $triggerName = $table.'_AI_PK'; $trigger_name_quoted = $this->conn->quote($triggerName); $query = 'SELECT trigger_name FROM user_triggers'; - $query.= ' WHERE trigger_name='.$trigger_name_quoted.' OR trigger_name='.strtoupper($trigger_name_quoted); + $query .= ' WHERE trigger_name='.$trigger_name_quoted.' OR trigger_name='.strtoupper($trigger_name_quoted); $trigger = $this->conn->fetchOne($query); if ($trigger) { - $trigger_name = $this->conn->quoteIdentifier($table . '_AI_PK', true); - $trigger_sql = 'DROP TRIGGER ' . $trigger_name; + $trigger_name = $this->conn->quoteIdentifier($table.'_AI_PK', true); + $trigger_sql = 'DROP TRIGGER '.$trigger_name; // if throws exception, trigger for autoincrement PK could not be dropped $this->conn->exec($trigger_sql); @@ -188,18 +188,19 @@ public function dropAutoincrement($table) // if throws exception, sequence for autoincrement PK could not be dropped $this->dropSequence($table); - $indexName = $table . '_AI_PK'; + $indexName = $table.'_AI_PK'; // if throws exception, primary key for autoincrement PK could not be dropped $this->dropConstraint($table, $indexName); } } - /** + + /** * A method to return the required SQL string that fits between CREATE ... TABLE * to create the table as a temporary table. * - * @return string The string required to be placed between "CREATE" and "TABLE" - * to generate a temporary table, if possible. + * @return string the string required to be placed between "CREATE" and "TABLE" + * to generate a temporary table, if possible */ public function getTemporaryTableQuery() { @@ -211,15 +212,15 @@ public function getTemporaryTableQuery() * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition foreign key definition + * @param array $definition foreign key definition + * * @return string - * @access protected */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; - if (isset($definition['onDelete']) && strtoupper(trim($definition['onDelete'])) != 'NO ACTION') { - $query .= ' ON DELETE ' . $definition['onDelete']; + if (isset($definition['onDelete']) && 'NO ACTION' != strtoupper(trim($definition['onDelete']))) { + $query .= ' ON DELETE '.$definition['onDelete']; } if (isset($definition['deferrable'])) { $query .= ' DEFERRABLE'; @@ -231,17 +232,18 @@ public function getAdvancedForeignKeyOptions(array $definition) } else { $query .= ' INITIALLY IMMEDIATE'; } + return $query; } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. * * Example * array( @@ -261,9 +263,7 @@ public function getAdvancedForeignKeyOptions(array $definition) * 'length' => 12 * ) * ); - * @param array $options An associative array of table options: - * - * @return void + * @param array $options An associative array of table options: */ public function createTable($name, array $fields, array $options = array()) { @@ -277,13 +277,13 @@ public function createTable($name, array $fields, array $options = array()) } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. * * Example * array( @@ -303,95 +303,92 @@ public function createTable($name, array $fields, array $options = array()) * 'length' => 12 * ) * ); - * @param array $options An associative array of table options: - * - * @return void + * @param array $options An associative array of table options: */ public function createTableSql($name, array $fields, array $options = array()) { $sql = parent::createTableSql($name, $fields, $options); - if (isset($options['comment']) && ! empty($options['comment'])) { - $sql[] = $this->_createTableCommentSql($name, $options['comment']); - } + if (isset($options['comment']) && !empty($options['comment'])) { + $sql[] = $this->_createTableCommentSql($name, $options['comment']); + } foreach ($fields as $fieldName => $field) { if (isset($field['sequence'])) { - $sql[] = $this->createSequenceSql($field['sequence'], 1); + $sql[] = $this->createSequenceSql($field['sequence'], 1); } - if (isset($field['autoincrement']) && $field['autoincrement'] || - (isset($field['autoinc']) && $fields['autoinc'])) { + if (isset($field['autoincrement']) && $field['autoincrement'] + || (isset($field['autoinc']) && $fields['autoinc'])) { $sql = array_merge($sql, $this->_makeAutoincrement($fieldName, $name)); } - if (isset($field['comment']) && ! empty($field['comment'])){ - $sql[] = $this->_createColumnCommentSql($name,$fieldName,$field['comment']); + if (isset($field['comment']) && !empty($field['comment'])) { + $sql[] = $this->_createColumnCommentSql($name, $fieldName, $field['comment']); } } - - if (isset($options['indexes']) && ! empty($options['indexes'])) { + + if (isset($options['indexes']) && !empty($options['indexes'])) { foreach ($options['indexes'] as $indexName => $definition) { // create nonunique indexes, as they are a part od CREATE TABLE DDL - if ( ! isset($definition['type']) || - (isset($definition['type']) && strtolower($definition['type']) != 'unique')) { + if (!isset($definition['type']) + || (isset($definition['type']) && 'unique' != strtolower($definition['type']))) { $sql[] = $this->createIndexSql($name, $indexName, $definition); } } } - + return $sql; } /** - * create a comment on a table + * create a comment on a table. * - * @param string $table Name of the table we are commenting - * @param string $comment The comment for the table + * @param string $table Name of the table we are commenting + * @param string $comment The comment for the table * * @return string */ - public function _createTableCommentSql($table,$comment) + public function _createTableCommentSql($table, $comment) { - return 'COMMENT ON TABLE '. $this->conn->quoteIdentifier($table, true). ' IS '.$this->conn->quote($comment, 'text').''; + return 'COMMENT ON TABLE '.$this->conn->quoteIdentifier($table, true).' IS '.$this->conn->quote($comment, 'text').''; } /** - * create a comment on a column + * create a comment on a column. * - * @param string $table Name of the table - * @param string $column Name of the column we are commenting - * @param string $comment The comment for the table + * @param string $table Name of the table + * @param string $column Name of the column we are commenting + * @param string $comment The comment for the table * * @return string */ - public function _createColumnCommentSql($table,$column, $comment) + public function _createColumnCommentSql($table, $column, $comment) { - return 'COMMENT ON COLUMN '. $this->conn->quoteIdentifier($table, true). '.'. $this->conn->quoteIdentifier($column, true). ' IS '.$this->conn->quote($comment, 'text').''; + return 'COMMENT ON COLUMN '.$this->conn->quoteIdentifier($table, true).'.'.$this->conn->quoteIdentifier($column, true).' IS '.$this->conn->quote($comment, 'text').''; } /** - * drop an existing table + * drop an existing table. * * @param string $name name of the table that should be dropped - * @return void */ public function dropTable($name) { - //$this->conn->beginNestedTransaction(); + // $this->conn->beginNestedTransaction(); $result = $this->dropAutoincrement($name); - $result = parent::dropTable($name); - //$this->conn->completeNestedTransaction(); - return $result; + + return parent::dropTable($name); + // $this->conn->completeNestedTransaction(); } /** - * alter an existing table + * alter an existing table. * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -404,78 +401,12 @@ public function dropTable($name) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the MDB2 parser. - * - * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the MDB2 parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. - * @return void + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise */ public function alterTable($name, array $changes, $check = false) { - foreach ($changes as $changeName => $change) { switch ($changeName) { case 'add': @@ -485,7 +416,7 @@ public function alterTable($name, array $changes, $check = false) case 'rename': break; default: - throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported'); + throw new Doctrine_Export_Exception('change type "'.$changeName.'" not yet supported'); } } @@ -495,112 +426,111 @@ public function alterTable($name, array $changes, $check = false) $name = $this->conn->quoteIdentifier($name, true); - if ( ! empty($changes['add']) && is_array($changes['add'])) { + if (!empty($changes['add']) && is_array($changes['add'])) { $fields = array(); foreach ($changes['add'] as $fieldName => $field) { - $fields[] = $this->getDeclaration($fieldName, $field); + $fields[] = $this->getDeclaration($fieldName, $field); } - $result = $this->conn->exec('ALTER TABLE ' . $name . ' ADD (' . implode(', ', $fields) . ')'); + $result = $this->conn->exec('ALTER TABLE '.$name.' ADD ('.implode(', ', $fields).')'); } - if ( ! empty($changes['change']) && is_array($changes['change'])) { + if (!empty($changes['change']) && is_array($changes['change'])) { $fields = array(); foreach ($changes['change'] as $fieldName => $field) { - $fields[] = $fieldName. ' ' . $this->getDeclaration('', $field['definition']); + $fields[] = $fieldName.' '.$this->getDeclaration('', $field['definition']); } - $result = $this->conn->exec('ALTER TABLE ' . $name . ' MODIFY (' . implode(', ', $fields) . ')'); + $result = $this->conn->exec('ALTER TABLE '.$name.' MODIFY ('.implode(', ', $fields).')'); } - if ( ! empty($changes['rename']) && is_array($changes['rename'])) { + if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { - $query = 'ALTER TABLE ' . $name . ' RENAME COLUMN ' . $this->conn->quoteIdentifier($fieldName, true) - . ' TO ' . $this->conn->quoteIdentifier($field['name']); + $query = 'ALTER TABLE '.$name.' RENAME COLUMN '.$this->conn->quoteIdentifier($fieldName, true) + .' TO '.$this->conn->quoteIdentifier($field['name']); $result = $this->conn->exec($query); } } - if ( ! empty($changes['remove']) && is_array($changes['remove'])) { + if (!empty($changes['remove']) && is_array($changes['remove'])) { $fields = array(); foreach ($changes['remove'] as $fieldName => $field) { $fields[] = $this->conn->quoteIdentifier($fieldName, true); } - $result = $this->conn->exec('ALTER TABLE ' . $name . ' DROP COLUMN ' . implode(', ', $fields)); + $result = $this->conn->exec('ALTER TABLE '.$name.' DROP COLUMN '.implode(', ', $fields)); } - if ( ! empty($changes['name'])) { + if (!empty($changes['name'])) { $changeName = $this->conn->quoteIdentifier($changes['name'], true); - $result = $this->conn->exec('ALTER TABLE ' . $name . ' RENAME TO ' . $changeName); + $result = $this->conn->exec('ALTER TABLE '.$name.' RENAME TO '.$changeName); } } /** - * create sequence + * create sequence. * * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); + * * @return string */ public function createSequenceSql($seqName, $start = 1, array $options = array()) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = 'CREATE SEQUENCE ' . $sequenceName . ' START WITH ' . $start . ' INCREMENT BY 1 NOCACHE'; - $query .= ($start < 1 ? ' MINVALUE ' . $start : ''); + $query = 'CREATE SEQUENCE '.$sequenceName.' START WITH '.$start.' INCREMENT BY 1 NOCACHE'; + $query .= ($start < 1 ? ' MINVALUE '.$start : ''); + return $query; } /** - * drop existing sequence + * drop existing sequence. * - * @param object $this->conn database object that is extended by this class * @param string $seqName name of the sequence to be dropped + * * @return string */ public function dropSequenceSql($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - return 'DROP SEQUENCE ' . $sequenceName; + + return 'DROP SEQUENCE '.$sequenceName; } /** * return Oracle's SQL code portion needed to set an index * declaration to be unsed in statements like CREATE TABLE. - * - * @param string $name name of the index - * @param array $definition index definition - * @return string Oracle's SQL code portion needed to set an index - */ + * + * @param string $name name of the index + * @param array $definition index definition + * + * @return string Oracle's SQL code portion needed to set an index + */ public function getIndexDeclaration($name, array $definition) { $name = $this->conn->quoteIdentifier($name); $type = ''; - - if ( isset($definition['type'])) - { - if (strtolower($definition['type']) == 'unique') { + + if (isset($definition['type'])) { + if ('unique' == strtolower($definition['type'])) { $type = strtoupper($definition['type']); } else { - throw new Doctrine_Export_Exception( - 'Unknown type '.$definition['type'] .' for index '.$name - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name); } } else { // only unique indexes should be defined in create table statement return null; } - - if ( !isset($definition['fields']) || !is_array($definition['fields'])) { + + if (!isset($definition['fields']) || !is_array($definition['fields'])) { throw new Doctrine_Export_Exception('No columns given for index '.$name); } - - $query = 'CONSTRAINT '.$name.' '.$type.' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; - - return $query; + + return 'CONSTRAINT '.$name.' '.$type.' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; } } diff --git a/lib/Doctrine/Export/Pgsql.php b/lib/Doctrine/Export/Pgsql.php index 6f1b106cf..6afbba5a5 100644 --- a/lib/Doctrine/Export/Pgsql.php +++ b/lib/Doctrine/Export/Pgsql.php @@ -20,15 +20,15 @@ */ /** - * Doctrine_Export_Pgsql + * Doctrine_Export_Pgsql. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7680 $ */ class Doctrine_Export_Pgsql extends Doctrine_Export @@ -36,30 +36,25 @@ class Doctrine_Export_Pgsql extends Doctrine_Export public $tmpConnectionDatabase = 'postgres'; /** - * createDatabaseSql + * createDatabaseSql. * - * @param string $name - * @return void + * @param string $name */ public function createDatabaseSql($name) { - $query = 'CREATE DATABASE ' . $this->conn->quoteIdentifier($name); - - return $query; + return 'CREATE DATABASE '.$this->conn->quoteIdentifier($name); } /** - * drop an existing database + * drop an existing database. * * @param string $name name of the database that should be dropped + * * @throws PDOException - * @access public */ public function dropDatabaseSql($name) { - $query = 'DROP DATABASE ' . $this->conn->quoteIdentifier($name); - - return $query; + return 'DROP DATABASE '.$this->conn->quoteIdentifier($name); } /** @@ -67,21 +62,21 @@ public function dropDatabaseSql($name) * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition foreign key definition + * @param array $definition foreign key definition + * * @return string - * @access protected */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; if (isset($definition['match'])) { - $query .= ' MATCH ' . $definition['match']; + $query .= ' MATCH '.$definition['match']; } if (isset($definition['onUpdate'])) { - $query .= ' ON UPDATE ' . $definition['onUpdate']; + $query .= ' ON UPDATE '.$definition['onUpdate']; } if (isset($definition['onDelete'])) { - $query .= ' ON DELETE ' . $definition['onDelete']; + $query .= ' ON DELETE '.$definition['onDelete']; } if (isset($definition['deferrable'])) { $query .= ' DEFERRABLE'; @@ -93,18 +88,21 @@ public function getAdvancedForeignKeyOptions(array $definition) } else { $query .= ' INITIALLY IMMEDIATE'; } + return $query; } /** - * generates the sql for altering an existing table on postgresql + * generates the sql for altering an existing table on postgresql. + * + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type * + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. * @see Doctrine_Export::alterTable() + * * @return array */ public function alterTableSql($name, array $changes, $check = false) @@ -118,28 +116,28 @@ public function alterTableSql($name, array $changes, $check = false) case 'rename': break; default: - throw new Doctrine_Export_Exception('change type "' . $changeName . '\" not yet supported'); + throw new Doctrine_Export_Exception('change type "'.$changeName.'\" not yet supported'); } } if ($check) { return true; } - + $sql = array(); if (isset($changes['add']) && is_array($changes['add'])) { foreach ($changes['add'] as $fieldName => $field) { - $query = 'ADD ' . $this->getDeclaration($fieldName, $field); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + $query = 'ADD '.$this->getDeclaration($fieldName, $field); + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } } if (isset($changes['remove']) && is_array($changes['remove'])) { foreach ($changes['remove'] as $fieldName => $field) { $fieldName = $this->conn->quoteIdentifier($fieldName, true); - $query = 'DROP ' . $fieldName; - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + $query = 'DROP '.$fieldName; + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } } @@ -152,16 +150,16 @@ public function alterTableSql($name, array $changes, $check = false) if (is_array($serverInfo) && $serverInfo['major'] < 8) { throw new Doctrine_Export_Exception('changing column type for "'.$field['type'].'\" requires PostgreSQL 8.0 or above'); } - $query = 'ALTER ' . $fieldName . ' TYPE ' . $this->conn->dataDict->getNativeDeclaration($field['definition']); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + $query = 'ALTER '.$fieldName.' TYPE '.$this->conn->dataDict->getNativeDeclaration($field['definition']); + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } if (array_key_exists('default', $field['definition'])) { - $query = 'ALTER ' . $fieldName . ' SET DEFAULT ' . $this->conn->quote($field['definition']['default'], $field['definition']['type']); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + $query = 'ALTER '.$fieldName.' SET DEFAULT '.$this->conn->quote($field['definition']['default'], $field['definition']['type']); + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } - if ( isset($field['definition']['notnull'])) { - $query = 'ALTER ' . $fieldName . ' ' . ($field['definition']['notnull'] ? 'SET' : 'DROP') . ' NOT NULL'; - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' ' . $query; + if (isset($field['definition']['notnull'])) { + $query = 'ALTER '.$fieldName.' '.($field['definition']['notnull'] ? 'SET' : 'DROP').' NOT NULL'; + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' '.$query; } } } @@ -169,26 +167,26 @@ public function alterTableSql($name, array $changes, $check = false) if (isset($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { $fieldName = $this->conn->quoteIdentifier($fieldName, true); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' RENAME COLUMN ' . $fieldName . ' TO ' . $this->conn->quoteIdentifier($field['name'], true); + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' RENAME COLUMN '.$fieldName.' TO '.$this->conn->quoteIdentifier($field['name'], true); } } $name = $this->conn->quoteIdentifier($name, true); if (isset($changes['name'])) { $changeName = $this->conn->quoteIdentifier($changes['name'], true); - $sql[] = 'ALTER TABLE ' . $this->conn->quoteIdentifier($name, true) . ' RENAME TO ' . $changeName; + $sql[] = 'ALTER TABLE '.$this->conn->quoteIdentifier($name, true).' RENAME TO '.$changeName; } - + return $sql; } - + /** - * alter an existing table + * alter an existing table. * - * @param string $name name of the table that is intended to be changed. - * @param array $changes associative array that contains the details of each type - * of change that is intended to be performed. The types of - * changes that are currently supported are defined as follows: + * @param string $name name of the table that is intended to be changed + * @param array $changes associative array that contains the details of each type + * of change that is intended to be performed. The types of + * changes that are currently supported are defined as follows: * * name * @@ -201,75 +199,13 @@ public function alterTableSql($name, array $changes, $check = false) * should be set to another associative array with the properties * of the fields to be added. The properties of the fields should * be the same as defined by the Metabase parser. + * @param bool $check indicates whether the function should just check if the DBMS driver + * can perform the requested table alterations if the value is true or + * actually perform them otherwise * + * @return bool * - * remove - * - * Associative array with the names of fields to be removed as indexes - * of the array. Currently the values assigned to each entry are ignored. - * An empty array should be used for future compatibility. - * - * rename - * - * Associative array with the names of fields to be renamed as indexes - * of the array. The value of each entry of the array should be set to - * another associative array with the entry named name with the new - * field name and the entry named Declaration that is expected to contain - * the portion of the field declaration already in DBMS specific SQL code - * as it is used in the CREATE TABLE statement. - * - * change - * - * Associative array with the names of the fields to be changed as indexes - * of the array. Keep in mind that if it is intended to change either the - * name of a field and any other properties, the change array entries - * should have the new names of the fields as array indexes. - * - * The value of each entry of the array should be set to another associative - * array with the properties of the fields to that are meant to be changed as - * array entries. These entries should be assigned to the new values of the - * respective properties. The properties of the fields should be the same - * as defined by the Metabase parser. - * - * Example - * array( - * 'name' => 'userlist', - * 'add' => array( - * 'quota' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * ) - * ), - * 'remove' => array( - * 'file_limit' => array(), - * 'time_limit' => array() - * ), - * 'change' => array( - * 'name' => array( - * 'length' => '20', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 20, - * ), - * ) - * ), - * 'rename' => array( - * 'sex' => array( - * 'name' => 'gender', - * 'definition' => array( - * 'type' => 'text', - * 'length' => 1, - * 'default' => 'M', - * ), - * ) - * ) - * ) - * - * @param boolean $check indicates whether the function should just check if the DBMS driver - * can perform the requested table alterations if the value is true or - * actually perform them otherwise. * @throws Doctrine_Connection_Exception - * @return boolean */ public function alterTable($name, array $changes, $check = false) { @@ -277,90 +213,91 @@ public function alterTable($name, array $changes, $check = false) foreach ($sql as $query) { $this->conn->exec($query); } - return true; + + return true; } /** - * return RDBMS specific create sequence statement + * return RDBMS specific create sequence statement. + * + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); * - * @throws Doctrine_Connection_Exception if something fails at database level - * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); * @return string + * + * @throws Doctrine_Connection_Exception if something fails at database level */ public function createSequenceSql($sequenceName, $start = 1, array $options = array()) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true); - return 'CREATE SEQUENCE ' . $sequenceName . ' INCREMENT 1' . - ($start < 1 ? ' MINVALUE ' . $start : '') . ' START ' . $start; + + return 'CREATE SEQUENCE '.$sequenceName.' INCREMENT 1'. + ($start < 1 ? ' MINVALUE '.$start : '').' START '.$start; } /** - * drop existing sequence + * drop existing sequence. * * @param string $sequenceName name of the sequence to be dropped */ public function dropSequenceSql($sequenceName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true); - return 'DROP SEQUENCE ' . $sequenceName; + + return 'DROP SEQUENCE '.$sequenceName; } /** * Creates a table. * * @param unknown_type $name - * @param array $fields - * @param array $options + * * @return unknown */ public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } - + if (empty($fields)) { - throw new Doctrine_Export_Exception('no fields specified for table ' . $name); + throw new Doctrine_Export_Exception('no fields specified for table '.$name); } $queryFields = $this->getFieldDeclarationList($fields); - - if (isset($options['primary']) && ! empty($options['primary'])) { + if (isset($options['primary']) && !empty($options['primary'])) { $keyColumns = array_values($options['primary']); $keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns); - $queryFields .= ', PRIMARY KEY(' . implode(', ', $keyColumns) . ')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $keyColumns).')'; } - $query = 'CREATE TABLE ' . $this->conn->quoteIdentifier($name, true) . ' (' . $queryFields; + $query = 'CREATE TABLE '.$this->conn->quoteIdentifier($name, true).' ('.$queryFields; if ($check = $this->getCheckDeclaration($fields)) { - $query .= ', ' . $check; + $query .= ', '.$check; } if (isset($options['checks']) && $check = $this->getCheckDeclaration($options['checks'])) { - $query .= ', ' . $check; + $query .= ', '.$check; } $query .= ')'; $sql[] = $query; - if (isset($options['indexes']) && ! empty($options['indexes'])) { - foreach($options['indexes'] as $index => $definition) { + if (isset($options['indexes']) && !empty($options['indexes'])) { + foreach ($options['indexes'] as $index => $definition) { $sql[] = $this->createIndexSql($name, $index, $definition); } } - - if (isset($options['foreignKeys'])) { + if (isset($options['foreignKeys'])) { foreach ((array) $options['foreignKeys'] as $k => $definition) { if (is_array($definition)) { $sql[] = $this->createForeignKeySql($name, $definition); @@ -370,24 +307,28 @@ public function createTableSql($name, array $fields, array $options = array()) if (isset($options['sequenceName'])) { $sql[] = $this->createSequenceSql($options['sequenceName']); } + return $sql; } - /** + /** * Get the stucture of a field into an array. - * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. + * + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created + * * @see Doctrine_Export::createIndex() + * * @return string */ public function createIndexSql($table, $name, array $definition) { - $query = parent::createIndexSql($table, $name, $definition); - if (isset($definition['where'])) { - return $query . ' WHERE ' . $definition['where']; - } + $query = parent::createIndexSql($table, $name, $definition); + if (isset($definition['where'])) { + return $query.' WHERE '.$definition['where']; + } + return $query; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Export/Reporter.php b/lib/Doctrine/Export/Reporter.php index 742f39fac..fc0b6c037 100644 --- a/lib/Doctrine/Export/Reporter.php +++ b/lib/Doctrine/Export/Reporter.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Export_Reporter + * Doctrine_Export_Reporter. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Export_Reporter implements IteratorAggregate @@ -44,9 +44,9 @@ public function pop() return array_pop($this->messages); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->messages); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Export/Schema.php b/lib/Doctrine/Export/Schema.php index 9e67bf437..17436b3fd 100644 --- a/lib/Doctrine/Export/Schema.php +++ b/lib/Doctrine/Export/Schema.php @@ -20,40 +20,40 @@ */ /** - * Doctrine_Export_Schema - * + * Doctrine_Export_Schema. + * * Used for exporting a schema to a yaml file * - * @package Doctrine - * @subpackage Export - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision: 1838 $ + * * @author Nicolas Bérard-Nault * @author Jonathan H. Wage */ class Doctrine_Export_Schema -{ +{ /** - * buildSchema - * + * buildSchema. + * * Build schema array that can be dumped to file * - * @param string $directory The directory of models to build the schema from - * @param array $models The array of model names to build the schema for - * @param integer $modelLoading The model loading strategy to use to load the models from the passed directory - * @return void + * @param string $directory The directory of models to build the schema from + * @param array $models The array of model names to build the schema for + * @param int $modelLoading The model loading strategy to use to load the models from the passed directory */ public function buildSchema($directory = null, $models = array(), $modelLoading = null) { - if ($directory !== null) { + if (null !== $directory) { $loadedModels = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($directory, $modelLoading)); } else { $loadedModels = Doctrine_Core::getLoadedModels(); } - + $array = array(); - + $parent = new ReflectionClass('Doctrine_Record'); $sql = array(); @@ -62,24 +62,24 @@ public function buildSchema($directory = null, $models = array(), $modelLoading // we iterate through the diff of previously declared classes // and currently declared classes foreach ($loadedModels as $className) { - if ( ! empty($models) && !in_array($className, $models)) { + if (!empty($models) && !in_array($className, $models)) { continue; } $recordTable = Doctrine_Core::getTable($className); - + $data = $recordTable->getExportableFormat(); - + $table = array(); $table['connection'] = $recordTable->getConnection()->getName(); $remove = array('ptype', 'ntype', 'alltypes'); // Fix explicit length in schema, concat it to type in this format: type(length) - foreach ($data['columns'] AS $name => $column) { + foreach ($data['columns'] as $name => $column) { if (isset($column['length']) && $column['length'] && isset($column['scale']) && $column['scale']) { - $data['columns'][$name]['type'] = $column['type'] . '(' . $column['length'] . ', ' . $column['scale'] . ')'; + $data['columns'][$name]['type'] = $column['type'].'('.$column['length'].', '.$column['scale'].')'; unset($data['columns'][$name]['length'], $data['columns'][$name]['scale']); } else { - $data['columns'][$name]['type'] = $column['type'] . '(' . $column['length'] . ')'; + $data['columns'][$name]['type'] = $column['type'].'('.$column['length'].')'; unset($data['columns'][$name]['length']); } // Strip out schema information which is not necessary to be dumped to the yaml schema file @@ -88,10 +88,10 @@ public function buildSchema($directory = null, $models = array(), $modelLoading unset($data['columns'][$name][$value]); } } - + // If type is the only property of the column then lets abbreviate the syntax // columns: { name: string(255) } - if (count($data['columns'][$name]) === 1 && isset($data['columns'][$name]['type'])) { + if (1 === count($data['columns'][$name]) && isset($data['columns'][$name]['type'])) { $type = $data['columns'][$name]['type']; unset($data['columns'][$name]); $data['columns'][$name] = $type; @@ -99,56 +99,54 @@ public function buildSchema($directory = null, $models = array(), $modelLoading } $table['tableName'] = $data['tableName']; $table['columns'] = $data['columns']; - + $relations = $recordTable->getRelations(); foreach ($relations as $key => $relation) { $relationData = $relation->toArray(); - + $relationKey = $relationData['alias']; - + if (isset($relationData['refTable']) && $relationData['refTable']) { $table['relations'][$relationKey]['refClass'] = $relationData['refTable']->getComponentName(); } - + if (isset($relationData['class']) && $relationData['class'] && $relation['class'] != $relationKey) { $table['relations'][$relationKey]['class'] = $relationData['class']; } - + $table['relations'][$relationKey]['local'] = $relationData['local']; $table['relations'][$relationKey]['foreign'] = $relationData['foreign']; - - if ($relationData['type'] === Doctrine_Relation::ONE) { + + if (Doctrine_Relation::ONE === $relationData['type']) { $table['relations'][$relationKey]['type'] = 'one'; - } else if ($relationData['type'] === Doctrine_Relation::MANY) { + } elseif (Doctrine_Relation::MANY === $relationData['type']) { $table['relations'][$relationKey]['type'] = 'many'; } else { $table['relations'][$relationKey]['type'] = 'one'; } } - + $array[$className] = $table; } - + return $array; } /** - * exportSchema + * exportSchema. * - * @param string $schema - * @param string $directory - * @param string $string of data in the specified format - * @param integer $modelLoading The model loading strategy to use to load the models from the passed directory - * @return void + * @param string $schema + * @param string $directory + * @param int $modelLoading The model loading strategy to use to load the models from the passed directory */ public function exportSchema($schema, $format = 'yml', $directory = null, $models = array(), $modelLoading = null) { $array = $this->buildSchema($directory, $models, $modelLoading); - + if (is_dir($schema)) { - $schema = $schema . DIRECTORY_SEPARATOR . 'schema.' . $format; + $schema = $schema.DIRECTORY_SEPARATOR.'schema.'.$format; } - + return Doctrine_Parser::dump($array, $format, $schema); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Export/Sqlite.php b/lib/Doctrine/Export/Sqlite.php index f9b50580e..acaf5b3a7 100644 --- a/lib/Doctrine/Export/Sqlite.php +++ b/lib/Doctrine/Export/Sqlite.php @@ -20,66 +20,65 @@ */ /** - * Doctrine_Export_Sqlite + * Doctrine_Export_Sqlite. * - * @package Doctrine - * @subpackage Export * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Export_Sqlite extends Doctrine_Export { /** - * dropDatabase + * dropDatabase. * * drop an existing database * - * @param string $databaseFile Path of the database that should be dropped - * @throws Doctrine_Export_Exception if the database file does not exist - * @throws Doctrine_Export_Exception if something failed during the removal of the database file - * @return void + * @param string $databaseFile Path of the database that should be dropped + * + * @throws Doctrine_Export_Exception if the database file does not exist + * @throws Doctrine_Export_Exception if something failed during the removal of the database file */ public function dropDatabase($databaseFile) { - if ( ! @file_exists($databaseFile)) { + if (!@file_exists($databaseFile)) { throw new Doctrine_Export_Exception('database does not exist'); } $result = @unlink($databaseFile); - if ( ! $result) { + if (!$result) { throw new Doctrine_Export_Exception('could not remove the database file'); } } /** - * createDatabase + * createDatabase. * * Create sqlite database file * - * @param string $databaseFile Path of the database that should be dropped - * @return void + * @param string $databaseFile Path of the database that should be dropped */ public function createDatabase($databaseFile) { - return new PDO('sqlite:' . $databaseFile); + return new PDO('sqlite:'.$databaseFile); } /** - * Get the stucture of a field into an array + * Get the stucture of a field into an array. * - * @param string $table name of the table on which the index is to be created - * @param string $name name of the index to be created - * @param array $definition associative array that defines properties of the index to be created. - * Currently, only one property named FIELDS is supported. This property - * is also an associative with the names of the index fields as array - * indexes. Each entry of this array is set to another type of associative - * array that specifies properties of the index that are specific to - * each field. + * @param string $table name of the table on which the index is to be created + * @param string $name name of the index to be created + * @param array $definition associative array that defines properties of the index to be created. + * Currently, only one property named FIELDS is supported. This property + * is also an associative with the names of the index fields as array + * indexes. Each entry of this array is set to another type of associative + * array that specifies properties of the index that are specific to + * each field. * * Currently, only the sorting property is supported. It should be used * to define the sorting direction of the index. It may be set to either @@ -97,29 +96,27 @@ public function createDatabase($databaseFile) * 'last_login' => array() * ) * ) + * * @throws PDOException - * @return void */ public function createIndexSql($table, $name, array $definition) { - $name = $this->conn->formatter->getIndexName($name); - $name = $this->conn->quoteIdentifier($name); - $type = ''; + $name = $this->conn->formatter->getIndexName($name); + $name = $this->conn->quoteIdentifier($name); + $type = ''; if (isset($definition['type'])) { switch (strtolower($definition['type'])) { case 'unique': - $type = strtoupper($definition['type']) . ' '; - break; + $type = strtoupper($definition['type']).' '; + break; default: - throw new Doctrine_Export_Exception( - 'Unknown type ' . $definition['type'] . ' for index ' . $name . ' in table ' . $table - ); + throw new Doctrine_Export_Exception('Unknown type '.$definition['type'].' for index '.$name.' in table '.$table); } } - $query = 'CREATE ' . $type . 'INDEX ' . $name . ' ON ' . $table; - $query .= ' (' . $this->getIndexFieldDeclarationList($definition['fields']) . ')'; + $query = 'CREATE '.$type.'INDEX '.$name.' ON '.$table; + $query .= ' ('.$this->getIndexFieldDeclarationList($definition['fields']).')'; return $query; } @@ -129,7 +126,7 @@ public function createIndexSql($table, $name, array $definition) * Obtain DBMS specific SQL code portion needed to set an index * declaration to be used in statements like CREATE TABLE. * - * @return string + * @return string */ public function getIndexFieldDeclarationList(array $fields) { @@ -144,7 +141,7 @@ public function getIndexFieldDeclarationList(array $fields) switch ($sort) { case 'ASC': case 'DESC': - $fieldString .= ' ' . $sort; + $fieldString .= ' '.$sort; break; default: throw new Doctrine_Export_Exception('Unknown index sorting option given.'); @@ -155,79 +152,78 @@ public function getIndexFieldDeclarationList(array $fields) } $declFields[] = $fieldString; } + return implode(', ', $declFields); } /** - * create a new table + * create a new table. * - * @param string $name Name of the database that should be created - * @param array $fields Associative array that contains the definition of each field of the new table - * The indexes of the array entries are the names of the fields of the table an - * the array entry values are associative arrays like those that are meant to be - * passed with the field definitions to get[Type]Declaration() functions. - * array( - * 'id' => array( - * 'type' => 'integer', - * 'unsigned' => 1 - * 'notnull' => 1 - * 'default' => 0 - * ), - * 'name' => array( - * 'type' => 'text', - * 'length' => 12 - * ), - * 'password' => array( - * 'type' => 'text', - * 'length' => 12 - * ) - * ); - * @param array $options An associative array of table options: - * - * @return void + * @param string $name Name of the database that should be created + * @param array $fields Associative array that contains the definition of each field of the new table + * The indexes of the array entries are the names of the fields of the table an + * the array entry values are associative arrays like those that are meant to be + * passed with the field definitions to get[Type]Declaration() functions. + * array( + * 'id' => array( + * 'type' => 'integer', + * 'unsigned' => 1 + * 'notnull' => 1 + * 'default' => 0 + * ), + * 'name' => array( + * 'type' => 'text', + * 'length' => 12 + * ), + * 'password' => array( + * 'type' => 'text', + * 'length' => 12 + * ) + * ); + * @param array $options An associative array of table options: */ public function createTableSql($name, array $fields, array $options = array()) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } - + if (empty($fields)) { throw new Doctrine_Export_Exception('no fields specified for table '.$name); } $queryFields = $this->getFieldDeclarationList($fields); - + $autoinc = false; - foreach($fields as $field) { - if (isset($field['autoincrement']) && $field['autoincrement'] || - (isset($field['autoinc']) && $field['autoinc'])) { + foreach ($fields as $field) { + if (isset($field['autoincrement']) && $field['autoincrement'] + || (isset($field['autoinc']) && $field['autoinc'])) { $autoinc = true; break; } } - if ( ! $autoinc && isset($options['primary']) && ! empty($options['primary'])) { + if (!$autoinc && isset($options['primary']) && !empty($options['primary'])) { $keyColumns = array_values($options['primary']); $keyColumns = array_map(array($this->conn, 'quoteIdentifier'), $keyColumns); - $queryFields.= ', PRIMARY KEY('.implode(', ', $keyColumns).')'; + $queryFields .= ', PRIMARY KEY('.implode(', ', $keyColumns).')'; } - $name = $this->conn->quoteIdentifier($name, true); - $sql = 'CREATE TABLE ' . $name . ' (' . $queryFields; + $name = $this->conn->quoteIdentifier($name, true); + $sql = 'CREATE TABLE '.$name.' ('.$queryFields; if ($check = $this->getCheckDeclaration($fields)) { - $sql .= ', ' . $check; + $sql .= ', '.$check; } if (isset($options['checks']) && $check = $this->getCheckDeclaration($options['checks'])) { - $sql .= ', ' . $check; + $sql .= ', '.$check; } $sql .= ')'; $query[] = $sql; - if (isset($options['indexes']) && ! empty($options['indexes'])) { + if (isset($options['indexes']) && !empty($options['indexes'])) { foreach ($options['indexes'] as $index => $definition) { $query[] = $this->createIndexSql($name, $index, $definition); } @@ -241,21 +237,21 @@ public function createTableSql($name, array $fields, array $options = array()) * Return the FOREIGN KEY query section dealing with non-standard options * as MATCH, INITIALLY DEFERRED, ON UPDATE, ... * - * @param array $definition foreign key definition + * @param array $definition foreign key definition + * * @return string - * @access protected */ public function getAdvancedForeignKeyOptions(array $definition) { $query = ''; if (isset($definition['match'])) { - $query .= ' MATCH ' . $definition['match']; + $query .= ' MATCH '.$definition['match']; } if (isset($definition['onUpdate'])) { - $query .= ' ON UPDATE ' . $definition['onUpdate']; + $query .= ' ON UPDATE '.$definition['onUpdate']; } if (isset($definition['onDelete'])) { - $query .= ' ON DELETE ' . $definition['onDelete']; + $query .= ' ON DELETE '.$definition['onDelete']; } if (isset($definition['deferrable'])) { $query .= ' DEFERRABLE'; @@ -267,43 +263,46 @@ public function getAdvancedForeignKeyOptions(array $definition) } else { $query .= ' INITIALLY IMMEDIATE'; } + return $query; } /** - * create sequence + * create sequence. + * + * @param string $seqName name of the sequence to be created + * @param string $start start value of the sequence; default is 1 + * @param array $options An associative array of table options: + * array( + * 'comment' => 'Foo', + * 'charset' => 'utf8', + * 'collate' => 'utf8_unicode_ci', + * ); * - * @param string $seqName name of the sequence to be created - * @param string $start start value of the sequence; default is 1 - * @param array $options An associative array of table options: - * array( - * 'comment' => 'Foo', - * 'charset' => 'utf8', - * 'collate' => 'utf8_unicode_ci', - * ); - * @return boolean + * @return bool */ public function createSequence($seqName, $start = 1, array $options = array()) { - $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'CREATE TABLE ' . $sequenceName . ' (' . $seqcolName . ' INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)'; + $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $query = 'CREATE TABLE '.$sequenceName.' ('.$seqcolName.' INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)'; $this->conn->exec($query); - if ($start == 1) { + if (1 == $start) { return true; } try { - $this->conn->exec('INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (' . ($start-1) . ')'); + $this->conn->exec('INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES ('.($start - 1).')'); + return true; - } catch(Doctrine_Connection_Exception $e) { - // Handle error + } catch (Doctrine_Connection_Exception $e) { + // Handle error try { - $result = $db->exec('DROP TABLE ' . $sequenceName); - } catch(Doctrine_Connection_Exception $e) { + $result = $db->exec('DROP TABLE '.$sequenceName); + } catch (Doctrine_Connection_Exception $e) { throw new Doctrine_Export_Exception('could not drop inconsistent sequence table'); } } @@ -311,21 +310,22 @@ public function createSequence($seqName, $start = 1, array $options = array()) } /** - * drop existing sequence + * drop existing sequence. + * + * @param string $sequenceName name of the sequence to be dropped * - * @param string $sequenceName name of the sequence to be dropped * @return string */ public function dropSequenceSql($sequenceName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName), true); - return 'DROP TABLE ' . $sequenceName; + return 'DROP TABLE '.$sequenceName; } - + public function alterTableSql($name, array $changes, $check = false) { - if ( ! $name) { + if (!$name) { throw new Doctrine_Export_Exception('no valid table name specified'); } foreach ($changes as $changeName => $change) { @@ -336,7 +336,7 @@ public function alterTableSql($name, array $changes, $check = false) case 'name': break; default: - throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported'); + throw new Doctrine_Export_Exception('change type "'.$changeName.'" not yet supported'); } } @@ -345,31 +345,31 @@ public function alterTableSql($name, array $changes, $check = false) } $query = ''; - if ( ! empty($changes['name'])) { + if (!empty($changes['name'])) { $change_name = $this->conn->quoteIdentifier($changes['name']); - $query .= 'RENAME TO ' . $change_name; + $query .= 'RENAME TO '.$change_name; } - if ( ! empty($changes['add']) && is_array($changes['add'])) { + if (!empty($changes['add']) && is_array($changes['add'])) { foreach ($changes['add'] as $fieldName => $field) { if ($query) { - $query.= ', '; + $query .= ', '; } - $query.= 'ADD ' . $this->getDeclaration($fieldName, $field); + $query .= 'ADD '.$this->getDeclaration($fieldName, $field); } } $rename = array(); - if ( ! empty($changes['rename']) && is_array($changes['rename'])) { + if (!empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $fieldName => $field) { $rename[$field['name']] = $fieldName; } } - if ( ! empty($changes['change']) && is_array($changes['change'])) { + if (!empty($changes['change']) && is_array($changes['change'])) { foreach ($changes['change'] as $fieldName => $field) { if ($query) { - $query.= ', '; + $query .= ', '; } if (isset($rename[$fieldName])) { $oldFieldName = $rename[$fieldName]; @@ -378,44 +378,45 @@ public function alterTableSql($name, array $changes, $check = false) $oldFieldName = $fieldName; } $oldFieldName = $this->conn->quoteIdentifier($oldFieldName, true); - $query .= 'CHANGE ' . $oldFieldName . ' ' - . $this->getDeclaration($fieldName, $field['definition']); + $query .= 'CHANGE '.$oldFieldName.' ' + .$this->getDeclaration($fieldName, $field['definition']); } } - if ( ! empty($rename) && is_array($rename)) { + if (!empty($rename) && is_array($rename)) { foreach ($rename as $renameName => $renamedField) { if ($query) { - $query.= ', '; + $query .= ', '; } $field = $changes['rename'][$renamedField]; $renamedField = $this->conn->quoteIdentifier($renamedField, true); - $query .= 'CHANGE ' . $renamedField . ' ' - . $this->getDeclaration($field['name'], $field['definition']); + $query .= 'CHANGE '.$renamedField.' ' + .$this->getDeclaration($field['name'], $field['definition']); } } - if ( ! $query) { + if (!$query) { return false; } $name = $this->conn->quoteIdentifier($name, true); - - return 'ALTER TABLE ' . $name . ' ' . $query; + + return 'ALTER TABLE '.$name.' '.$query; } /** - * createForeignKey + * createForeignKey. * * Sqlite does not support foreign keys so we are not even going to do anything if this function is called * to avoid any sql errors if a user tries to use this on sqlite * - * @param string $table name of the table on which the foreign key is to be created - * @param array $definition associative array that defines properties of the foreign key to be created. + * @param string $table name of the table on which the foreign key is to be created + * @param array $definition associative array that defines properties of the foreign key to be created + * * @return string */ public function createForeignKey($table, array $definition) { return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression.php b/lib/Doctrine/Expression.php index e2bdd2f39..8c54606ce 100644 --- a/lib/Doctrine/Expression.php +++ b/lib/Doctrine/Expression.php @@ -22,15 +22,16 @@ /** * Doctrine_Expression memorizes a dql expression that use a db function. * - * This class manages abstractions of dql expressions like query parts + * This class manages abstractions of dql expressions like query parts * that use CONCAT(), MIN(), SUM(). * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression @@ -42,18 +43,18 @@ class Doctrine_Expression /** * Creates an expression. * - * The constructor needs the dql fragment that contains one or more dbms + * The constructor needs the dql fragment that contains one or more dbms * functions. * * $e = new Doctrine_Expression("CONCAT('some', 'one')"); * - * - * @param string $expr sql fragment - * @param Doctrine_Connection $conn the connection (optional) + * + * @param string $expr sql fragment + * @param Doctrine_Connection $conn the connection (optional) */ public function __construct($expr, $conn = null) { - if ($conn !== null) { + if (null !== $conn) { $this->_conn = $conn; } $this->_tokenizer = new Doctrine_Query_Tokenizer(); @@ -62,13 +63,13 @@ public function __construct($expr, $conn = null) /** * Retrieves the connection associated to this expression at creation, - * or the current connection used if it was not specified. - * + * or the current connection used if it was not specified. + * * @return Doctrine_Connection The connection */ public function getConnection() { - if ( ! isset($this->_conn)) { + if (!isset($this->_conn)) { return Doctrine_Manager::connection(); } @@ -79,10 +80,9 @@ public function getConnection() * Sets the contained expression assuring that it is parsed. * * $e->setExpression("CONCAT('some', 'one')"); - * - * + * . + * * @param string $clause The expression to set - * @return void */ public function setExpression($clause) { @@ -90,38 +90,41 @@ public function setExpression($clause) } /** - * Parses a single expressions and substitutes dql abstract functions + * Parses a single expressions and substitutes dql abstract functions * with their concrete sql counterparts for the given connection. * * @param string $expr The expression to parse + * * @return string */ public function parseExpression($expr) { - $pos = strpos($expr, '('); - $quoted = (substr($expr, 0, 1) === "'" && substr($expr, -1) === "'"); - if ($pos === false || $quoted) { + $pos = strpos($expr, '('); + $quoted = ("'" === substr($expr, 0, 1) && "'" === substr($expr, -1)); + if (false === $pos || $quoted) { return $expr; } // get the name of the function - $name = substr($expr, 0, $pos); - $argStr = substr($expr, ($pos + 1), -1); + $name = substr($expr, 0, $pos); + $argStr = substr($expr, $pos + 1, -1); // parse args foreach ($this->_tokenizer->bracketExplode($argStr, ',') as $arg) { - $args[] = $this->parseClause($arg); + $args[] = $this->parseClause($arg); } return call_user_func_array(array($this->getConnection()->expression, $name), $args); } /** - * Parses a set of expressions at once. + * Parses a set of expressions at once. + * * @see parseExpression() - * - * @param string $clause The clause. Can be complex and parenthesised. - * @return string The parsed clause. + * + * @param string $clause The clause. Can be complex and parenthesised. + * + * @return string the parsed clause */ public function parseClause($clause) { @@ -130,13 +133,13 @@ public function parseClause($clause) foreach ($e as $k => $expr) { $e[$k] = $this->parseExpression($expr); } - + return implode(' ', $e); } /** * Gets the sql fragment represented. - * + * * @return string */ public function getSql() @@ -146,13 +149,13 @@ public function getSql() /** * Magic method. - * + * * Returns a string representation of this object. Proxies to @see getSql(). - * + * * @return string */ public function __toString() { return $this->getSql(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Driver.php b/lib/Doctrine/Expression/Driver.php index b97aef287..49d2b440e 100644 --- a/lib/Doctrine/Expression/Driver.php +++ b/lib/Doctrine/Expression/Driver.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Expression_Driver + * Doctrine_Expression_Driver. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Driver extends Doctrine_Connection_Module @@ -44,7 +45,7 @@ public function getIdentifiers($columns) /** * regexp - * returns the regular expression operator + * returns the regular expression operator. * * @return string */ @@ -54,66 +55,76 @@ public function regexp() } /** - * Returns the average value of a column + * Returns the average value of a column. + * + * @param string $column the column to use * - * @param string $column the column to use - * @return string generated sql including an AVG aggregate function + * @return string generated sql including an AVG aggregate function */ public function avg($column) { $column = $this->getIdentifier($column); - return 'AVG(' . $column . ')'; + + return 'AVG('.$column.')'; } /** - * Returns the number of rows (without a NULL value) of a column + * Returns the number of rows (without a NULL value) of a column. * * If a '*' is used instead of a column the number of selected rows * is returned. * - * @param string|integer $column the column to use - * @return string generated sql including a COUNT aggregate function + * @param string|int $column the column to use + * + * @return string generated sql including a COUNT aggregate function */ public function count($column) { $column = $this->getIdentifier($column); - return 'COUNT(' . $column . ')'; + + return 'COUNT('.$column.')'; } /** - * Returns the highest value of a column + * Returns the highest value of a column. * - * @param string $column the column to use - * @return string generated sql including a MAX aggregate function + * @param string $column the column to use + * + * @return string generated sql including a MAX aggregate function */ public function max($column) { $column = $this->getIdentifier($column); - return 'MAX(' . $column . ')'; + + return 'MAX('.$column.')'; } /** - * Returns the lowest value of a column + * Returns the lowest value of a column. * * @param string $column the column to use + * * @return string */ public function min($column) { $column = $this->getIdentifier($column); - return 'MIN(' . $column . ')'; + + return 'MIN('.$column.')'; } /** - * Returns the total sum of a column + * Returns the total sum of a column. * * @param string $column the column to use + * * @return string */ public function sum($column) { $column = $this->getIdentifier($column); - return 'SUM(' . $column . ')'; + + return 'SUM('.$column.')'; } // scalar functions @@ -128,34 +139,32 @@ public function sum($column) public function md5($column) { $column = $this->getIdentifier($column); - return 'MD5(' . $column . ')'; + + return 'MD5('.$column.')'; } /** * Returns the length of a text field. * - * @param string $expression1 - * @param string $expression2 * @return string */ public function length($column) { $column = $this->getIdentifier($column); - return 'LENGTH(' . $column . ')'; + + return 'LENGTH('.$column.')'; } /** * Rounds a numeric field to the number of decimals specified. * - * @param string $expression1 - * @param string $expression2 * @return string */ public function round($column, $decimals = 0) { $column = $this->getIdentifier($column); - return 'ROUND(' . $column . ', ' . $decimals . ')'; + return 'ROUND('.$column.', '.$decimals.')'; } /** @@ -164,49 +173,54 @@ public function round($column, $decimals = 0) * * @param string $expression1 * @param string $expression2 + * * @return string */ public function mod($expression1, $expression2) { $expression1 = $this->getIdentifier($expression1); $expression2 = $this->getIdentifier($expression2); - return 'MOD(' . $expression1 . ', ' . $expression2 . ')'; + + return 'MOD('.$expression1.', '.$expression2.')'; } /** * trim - * returns the string $str with leading and proceeding space characters removed + * returns the string $str with leading and proceeding space characters removed. + * + * @param string $str literal string or column name * - * @param string $str literal string or column name * @return string */ public function trim($str) { - return 'TRIM(' . $str . ')'; + return 'TRIM('.$str.')'; } /** * rtrim - * returns the string $str with proceeding space characters removed + * returns the string $str with proceeding space characters removed. + * + * @param string $str literal string or column name * - * @param string $str literal string or column name * @return string */ public function rtrim($str) { - return 'RTRIM(' . $str . ')'; + return 'RTRIM('.$str.')'; } /** * ltrim - * returns the string $str with leading space characters removed + * returns the string $str with leading space characters removed. + * + * @param string $str literal string or column name * - * @param string $str literal string or column name * @return string */ public function ltrim($str) { - return 'LTRIM(' . $str . ')'; + return 'LTRIM('.$str.')'; } /** @@ -214,12 +228,13 @@ public function ltrim($str) * Returns the string $str with all characters changed to * uppercase according to the current character set mapping. * - * @param string $str literal string or column name + * @param string $str literal string or column name + * * @return string */ public function upper($str) { - return 'UPPER(' . $str . ')'; + return 'UPPER('.$str.')'; } /** @@ -227,25 +242,27 @@ public function upper($str) * Returns the string $str with all characters changed to * lowercase according to the current character set mapping. * - * @param string $str literal string or column name + * @param string $str literal string or column name + * * @return string */ public function lower($str) { - return 'LOWER(' . $str . ')'; + return 'LOWER('.$str.')'; } /** * locate - * returns the position of the first occurrence of substring $substr in string $str + * returns the position of the first occurrence of substring $substr in string $str. * - * @param string $substr literal string to find - * @param string $str literal string - * @return integer + * @param string $substr literal string to find + * @param string $str literal string + * + * @return int */ public function locate($str, $substr) { - return 'LOCATE(' . $str . ', ' . $substr . ')'; + return 'LOCATE('.$str.', '.$substr.')'; } /** @@ -261,12 +278,13 @@ public function now() /** * soundex * Returns a string to call a function to compute the - * soundex encoding of a string + * soundex encoding of a string. * * The string "?000" is returned if the argument is NULL. * * @param string $value - * @return string SQL soundex function with given parameter + * + * @return string SQL soundex function with given parameter */ public function soundex($value) { @@ -274,41 +292,42 @@ public function soundex($value) } /** - * return string to call a function to get a substring inside an SQL statement + * return string to call a function to get a substring inside an SQL statement. * * Note: Not SQL92, but common functionality. * * SQLite only supports the 2 parameter variant of this function * - * @param string $value an sql string literal or column name/alias - * @param integer $position where to start the substring portion - * @param integer $length the substring portion length - * @return string SQL substring function with given parameters + * @param string $value an sql string literal or column name/alias + * @param mixed|null $len + * + * @return string SQL substring function with given parameters */ public function substring($value, $from, $len = null) { $value = $this->getIdentifier($value); - if ($len === null) - return 'SUBSTRING(' . $value . ' FROM ' . $from . ')'; - else { - $len = $this->getIdentifier($len); - return 'SUBSTRING(' . $value . ' FROM ' . $from . ' FOR ' . $len . ')'; + if (null === $len) { + return 'SUBSTRING('.$value.' FROM '.$from.')'; } + + $len = $this->getIdentifier($len); + + return 'SUBSTRING('.$value.' FROM '.$from.' FOR '.$len.')'; } /** - * Returns a series of strings concatinated + * Returns a series of strings concatinated. * * concat() accepts an arbitrary number of parameters. Each parameter * must contain an expression or an array with expressions. * - * @param string|array(string) strings that will be concatinated. + * @param string|array(string) strings that will be concatinated */ public function concat() { $args = func_get_args(); - return 'CONCAT(' . join(', ', (array) $args) . ')'; + return 'CONCAT('.join(', ', (array) $args).')'; } /** @@ -319,7 +338,8 @@ public function concat() public function not($expression) { $expression = $this->getIdentifier($expression); - return 'NOT(' . $expression . ')'; + + return 'NOT('.$expression.')'; } /** @@ -330,8 +350,9 @@ public function not($expression) * must contain a value or an expression or an array with values or * expressions. * - * @param string $type the type of operation, can be '+', '-', '*' or '/'. + * @param string $type the type of operation, can be '+', '-', '*' or '/' * @param string|array(string) + * * @return string an expression */ private function basicMath($type, array $args) @@ -340,11 +361,11 @@ private function basicMath($type, array $args) if (count($elements) < 1) { return ''; } - if (count($elements) == 1) { + if (1 == count($elements)) { return $elements[0]; - } else { - return '(' . implode(' ' . $type . ' ', $elements) . ')'; } + + return '('.implode(' '.$type.' ', $elements).')'; } /** @@ -355,6 +376,7 @@ private function basicMath($type, array $args) * expressions. * * @param string|array(string) + * * @return string an expression */ public function add(array $args) @@ -370,11 +392,12 @@ public function add(array $args) * expressions. * * @param string|array(string) + * * @return string an expression */ public function sub(array $args) { - return $this->basicMath('-', $args ); + return $this->basicMath('-', $args); } /** @@ -385,6 +408,7 @@ public function sub(array $args) * expressions. * * @param string|array(string) + * * @return string an expression */ public function mul(array $args) @@ -400,6 +424,7 @@ public function mul(array $args) * expressions. * * @param string|array(string) + * * @return string an expression */ public function div(array $args) @@ -412,13 +437,15 @@ public function div(array $args) * * @param string $value1 logical expression to compare * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function eq($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' = ' . $value2; + + return $value1.' = '.$value2; } /** @@ -426,13 +453,15 @@ public function eq($value1, $value2) * * @param string $value1 logical expression to compare * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function neq($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' <> ' . $value2; + + return $value1.' <> '.$value2; } /** @@ -440,13 +469,15 @@ public function neq($value1, $value2) * * @param string $value1 logical expression to compare * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function gt($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' > ' . $value2; + + return $value1.' > '.$value2; } /** @@ -455,42 +486,48 @@ public function gt($value1, $value2) * * @param string $value1 logical expression to compare * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function gte($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' >= ' . $value2; + + return $value1.' >= '.$value2; } /** * Returns the SQL to check if one value is less than another value. * - * @param string $value1 logical expression to compare - * @param string $value2 logical expression to compare with + * @param string $value1 logical expression to compare + * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function lt($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' < ' . $value2; + + return $value1.' < '.$value2; } /** * Returns the SQL to check if one value is less than or equal to * another value. * - * @param string $value1 logical expression to compare - * @param string $value2 logical expression to compare with + * @param string $value1 logical expression to compare + * @param string $value2 logical expression to compare with + * * @return string logical expression */ public function lte($value1, $value2) { $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $value1 . ' <= ' . $value2; + + return $value1.' <= '.$value2; } /** @@ -502,46 +539,52 @@ public function lte($value1, $value2) * must contain a logical expression or an array with logical expressions. * These expressions will be matched against the first parameter. * - * @param string $column the value that should be matched against + * @param string $column the value that should be matched against * @param string|array(string) values that will be matched against $column + * * @return string logical expression */ public function in($column, $values) { - if ( ! is_array($values)) { + if (!is_array($values)) { $values = array($values); } $values = $this->getIdentifiers($values); $column = $this->getIdentifier($column); - if (count($values) == 0) { + if (0 == count($values)) { throw new Doctrine_Expression_Exception('Values array for IN operator should not be empty.'); } - return $column . ' IN (' . implode(', ', $values) . ')'; + + return $column.' IN ('.implode(', ', $values).')'; } /** * Returns SQL that checks if a expression is null. * * @param string $expression the expression that should be compared to null + * * @return string logical expression */ public function isNull($expression) { $expression = $this->getIdentifier($expression); - return $expression . ' IS NULL'; + + return $expression.' IS NULL'; } /** * Returns SQL that checks if a expression is not null. * * @param string $expression the expression that should be compared to null + * * @return string logical expression */ public function isNotNull($expression) { $expression = $this->getIdentifier($expression); - return $expression . ' IS NOT NULL'; + + return $expression.' IS NOT NULL'; } /** @@ -555,8 +598,9 @@ public function isNotNull($expression) * independence you should avoid using between(). * * @param string $expression the value to compare to - * @param string $value1 the lower value to compare with - * @param string $value2 the higher value to compare with + * @param string $value1 the lower value to compare with + * @param string $value2 the higher value to compare with + * * @return string logical expression */ public function between($expression, $value1, $value2) @@ -564,11 +608,12 @@ public function between($expression, $value1, $value2) $expression = $this->getIdentifier($expression); $value1 = $this->getIdentifier($value1); $value2 = $this->getIdentifier($value2); - return $expression . ' BETWEEN ' .$value1 . ' AND ' . $value2; + + return $expression.' BETWEEN '.$value1.' AND '.$value2; } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -578,30 +623,27 @@ public function guid() } /** - * returns arcus cosine SQL string + * returns arcus cosine SQL string. * * @return string */ public function acos($value) { - return 'ACOS(' . $value . ')'; + return 'ACOS('.$value.')'; } /** - * sin + * sin. * - * @param string $value - * @return void + * @param string $value */ public function sin($value) { - return 'SIN(' . $value . ')'; + return 'SIN('.$value.')'; } /** - * pi - * - * @return void + * pi. */ public function pi() { @@ -609,18 +651,17 @@ public function pi() } /** - * cos + * cos. * - * @param string $value - * @return void + * @param string $value */ public function cos($value) { - return 'COS(' . $value . ')'; + return 'COS('.$value.')'; } /** - * coalesce + * coalesce. * * @return string */ @@ -628,20 +669,20 @@ public function coalesce() { $args = func_get_args(); - return 'COALESCE(' . join(', ', (array) $args) . ')'; + return 'COALESCE('.join(', ', (array) $args).')'; } /** - * __call + * __call. * * for all native RDBMS functions the function name itself is returned */ - public function __call($m, $a) + public function __call($m, $a) { if ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EXPR) { - throw new Doctrine_Expression_Exception('Unknown expression: ' . $m); + throw new Doctrine_Expression_Exception('Unknown expression: '.$m); } - return $m . '(' . implode(', ', $a) . ')'; + return $m.'('.implode(', ', $a).')'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Exception.php b/lib/Doctrine/Expression/Exception.php index 7815ddb5f..f5d432931 100644 --- a/lib/Doctrine/Expression/Exception.php +++ b/lib/Doctrine/Expression/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Expression_Exception + * Doctrine_Expression_Exception. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Expression/Mock.php b/lib/Doctrine/Expression/Mock.php index f792a45c9..9e995aee1 100644 --- a/lib/Doctrine/Expression/Mock.php +++ b/lib/Doctrine/Expression/Mock.php @@ -21,15 +21,17 @@ /** * Doctrine_Expression_Mock - * Mock driver that is used for testing purposes + * Mock driver that is used for testing purposes. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Mock extends Doctrine_Expression_Driver -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Expression/Mssql.php b/lib/Doctrine/Expression/Mssql.php index dc4f49437..b46e93e80 100644 --- a/lib/Doctrine/Expression/Mssql.php +++ b/lib/Doctrine/Expression/Mssql.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Expression_Mssql + * Doctrine_Expression_Mssql. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Mssql extends Doctrine_Expression_Driver @@ -37,10 +38,9 @@ class Doctrine_Expression_Mssql extends Doctrine_Expression_Driver * There are three special variables for current date and time: * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type) * - CURRENT_DATE (date, DATE type) - * - CURRENT_TIME (time, TIME type) + * - CURRENT_TIME (time, TIME type). * * @return string to call a variable with the current timestamp - * @access public */ public function now($type = 'timestamp') { @@ -54,34 +54,35 @@ public function now($type = 'timestamp') } /** - * return string to call a function to get a substring inside an SQL statement + * return string to call a function to get a substring inside an SQL statement. + * + * @param mixed|null $length * * @return string to call a function to get a substring */ public function substring($value, $position, $length = null) { - if ( ! is_null($length)) { - return 'SUBSTRING(' . $value . ', ' . $position . ', ' . $length . ')'; + if (!is_null($length)) { + return 'SUBSTRING('.$value.', '.$position.', '.$length.')'; } - return 'SUBSTRING(' . $value . ', ' . $position . ', LEN(' . $value . ') - ' . $position . ' + 1)'; + + return 'SUBSTRING('.$value.', '.$position.', LEN('.$value.') - '.$position.' + 1)'; } /** - * Returns string to concatenate two or more string parameters + * Returns string to concatenate two or more string parameters. * - * @param string $arg1 - * @param string $arg2 - * @param string $values... * @return string to concatenate two strings */ public function concat() { $args = func_get_args(); - return '(' . implode(' + ', $args) . ')'; + + return '('.implode(' + ', $args).')'; } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -91,7 +92,7 @@ public function guid() } /** - * Returns the length of a text field + * Returns the length of a text field. * * @param string $column * @@ -99,7 +100,7 @@ public function guid() */ public function length($column) { - return 'LEN (' . $column . ')'; + return 'LEN ('.$column.')'; } /** @@ -121,15 +122,12 @@ public function length($column) * minute mi, n * second ss, s * millisecond ms - * - * @param $datepart - * @param $date */ public function date_part($datepart, $date) { // remove ' and " from datepart for dblib $datepart = str_replace(array('\'', '"'), '', $datepart); - return 'DATEPART(' . $datepart . ', ' . $date . ')'; + return 'DATEPART('.$datepart.', '.$date.')'; } } diff --git a/lib/Doctrine/Expression/Mysql.php b/lib/Doctrine/Expression/Mysql.php index 165f558a5..8ed42e2ff 100644 --- a/lib/Doctrine/Expression/Mysql.php +++ b/lib/Doctrine/Expression/Mysql.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Expression_Mysql + * Doctrine_Expression_Mysql. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Mysql extends Doctrine_Expression_Driver { /** - * returns the regular expression operator + * returns the regular expression operator. * * @return string */ @@ -43,7 +44,7 @@ public function regexp() } /** - * return string to call a function to get random value inside an SQL statement + * return string to call a function to get random value inside an SQL statement. * * @return string to generate float between 0 and 1 */ @@ -53,26 +54,24 @@ public function random() } /** - * build a pattern matching string + * build a pattern matching string. * * EXPERIMENTAL * * WARNING: this function is experimental and may change signature at * any time until labelled as non-experimental * - * @access public - * - * @param array $pattern even keys are strings, odd are patterns (% and _) + * @param array $pattern even keys are strings, odd are patterns (% and _) * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future) - * @param string $field optional field name that is being matched against - * (might be required when emulating ILIKE) + * @param string $field optional field name that is being matched against + * (might be required when emulating ILIKE) * * @return string SQL pattern */ public function matchPattern($pattern, $operator = null, $field = null) { $match = ''; - if ( ! is_null($operator)) { + if (!is_null($operator)) { $field = is_null($field) ? '' : $field.' '; $operator = strtoupper($operator); switch ($operator) { @@ -80,15 +79,15 @@ public function matchPattern($pattern, $operator = null, $field = null) case 'ILIKE': $match = $field.'LIKE '; break; - // case sensitive + // case sensitive case 'LIKE': $match = $field.'LIKE BINARY '; break; default: - throw new Doctrine_Expression_Mysql_Exception('not a supported operator type:'. $operator); + throw new Doctrine_Expression_Mysql_Exception('not a supported operator type:'.$operator); } } - $match.= "'"; + $match .= "'"; foreach ($pattern as $key => $value) { if ($key % 2) { $match .= $value; @@ -96,13 +95,14 @@ public function matchPattern($pattern, $operator = null, $field = null) $match .= $this->conn->escapePattern($this->conn->escape($value)); } } - $match.= "'"; - $match.= $this->patternEscapeString(); + $match .= "'"; + $match .= $this->patternEscapeString(); + return $match; } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -112,49 +112,56 @@ public function guid() } /** - * Returns the year from dbms + * Returns the year from dbms. + * + * @param string $column * - * @param string $column * @return string to get year from dbms */ public function year($column) { $column = $this->getIdentifier($column); - return 'YEAR(' . $column . ')'; + + return 'YEAR('.$column.')'; } /** - * Returns the month from dbms + * Returns the month from dbms. + * + * @param string $column * - * @param string $column * @return string to get month from dbms */ public function month($column) { $column = $this->getIdentifier($column); - return 'MONTH(' . $column . ')'; + + return 'MONTH('.$column.')'; } /** - * Returns day from dbms + * Returns day from dbms. + * + * @param string $column * - * @param string $column * @return string to get day from dbms */ public function day($column) { $column = $this->getIdentifier($column); - return 'DAY(' . $column . ')'; + + return 'DAY('.$column.')'; } /** - * Returns soundex from dbms + * Returns soundex from dbms. * * @param string $column + * * @return string to get soundex from dbms */ public function soundex($column) { - return 'SOUNDEX(' . $column . ')'; + return 'SOUNDEX('.$column.')'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Oracle.php b/lib/Doctrine/Expression/Oracle.php index dd0a8387c..266181e57 100644 --- a/lib/Doctrine/Expression/Oracle.php +++ b/lib/Doctrine/Expression/Oracle.php @@ -20,50 +20,52 @@ */ /** - * Doctrine_Expression_Sqlite + * Doctrine_Expression_Sqlite. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Oracle extends Doctrine_Expression_Driver { /** - * Returns a series of strings concatinated + * Returns a series of strings concatinated. * * concat() accepts an arbitrary number of parameters. Each parameter * must contain an expression * - * @param string $arg1, $arg2 ... $argN strings that will be concatinated. * @return string */ public function concat() { $args = func_get_args(); - return join(' || ' , $args); + return join(' || ', $args); } /** - * return string to call a function to get a substring inside an SQL statement + * return string to call a function to get a substring inside an SQL statement. * * Note: Not SQL92, but common functionality. * - * @param string $value an sql string literal or column name/alias - * @param integer $position where to start the substring portion - * @param integer $length the substring portion length - * @return string SQL substring function with given parameters + * @param string $value an sql string literal or column name/alias + * @param int $position where to start the substring portion + * @param int $length the substring portion length + * + * @return string SQL substring function with given parameters */ public function substring($value, $position, $length = null) { - if ($length !== null) - return "SUBSTR($value, $position, $length)"; + if (null !== $length) { + return "SUBSTR({$value}, {$position}, {$length})"; + } - return "SUBSTR($value, $position)"; + return "SUBSTR({$value}, {$position})"; } /** @@ -71,7 +73,7 @@ public function substring($value, $position, $length = null) * There are three special variables for current date and time: * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type) * - CURRENT_DATE (date, DATE type) - * - CURRENT_TIME (time, TIME type) + * - CURRENT_TIME (time, TIME type). * * @return string to call a variable with the current timestamp */ @@ -87,9 +89,9 @@ public function now($type = 'timestamp') } /** - * random + * random. * - * @return string an oracle SQL string that generates a float between 0 and 1 + * @return string an oracle SQL string that generates a float between 0 and 1 */ public function random() { @@ -97,7 +99,7 @@ public function random() } /** - * Returns global unique identifier + * Returns global unique identifier. * * @return string to get global unique identifier */ @@ -105,4 +107,4 @@ public function guid() { return 'SYS_GUID()'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Pgsql.php b/lib/Doctrine/Expression/Pgsql.php index f447b1e10..e3c1a68fe 100644 --- a/lib/Doctrine/Expression/Pgsql.php +++ b/lib/Doctrine/Expression/Pgsql.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Expression_Pgsql + * Doctrine_Expression_Pgsql. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7685 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Pgsql extends Doctrine_Expression_Driver @@ -54,7 +55,7 @@ public function md5($column) { $column = $this->getIdentifier($column); - return 'MD5(' . $column . ')'; + return 'MD5('.$column.')'; } /** @@ -62,46 +63,52 @@ public function md5($column) * * Note: Not SQL92, but common functionality. * - * @param string $value the target $value the string or the string column. - * @param int $from extract from this characeter. - * @param int $len extract this amount of characters. - * @return string sql that extracts part of a string. + * @param string $value the target $value the string or the string column + * @param int $from extract from this characeter + * @param int $len extract this amount of characters + * + * @return string sql that extracts part of a string */ public function substring($value, $from, $len = null) { $value = $this->getIdentifier($value); - if ($len === null) { + if (null === $len) { $len = $this->getIdentifier($len); - return 'SUBSTR(' . $value . ', ' . $from . ')'; - } else { - return 'SUBSTR(' . $value . ', ' . $from . ', ' . $len . ')'; + + return 'SUBSTR('.$value.', '.$from.')'; } + + return 'SUBSTR('.$value.', '.$from.', '.$len.')'; } /** - * Returns a series of strings concatinated + * Returns a series of strings concatinated. * * concat() accepts an arbitrary number of parameters. Each parameter * must contain an expression or an array with expressions. * - * @param string|array(string) strings that will be concatinated. + * @param string|array(string) strings that will be concatinated + * @param mixed|null $timestamp2 + * * @return string */ - /** * PostgreSQLs AGE( [, ]) function. * * @param string $timestamp1 timestamp to subtract from NOW() * @param string $timestamp2 optional; if given: subtract arguments + * * @return string */ - public function age($timestamp1, $timestamp2 = null) { - if ( $timestamp2 == null ) { - return 'AGE(' . $timestamp1 . ')'; + public function age($timestamp1, $timestamp2 = null) + { + if (null == $timestamp2) { + return 'AGE('.$timestamp1.')'; } - return 'AGE(' . $timestamp1 . ', ' . $timestamp2 . ')'; + + return 'AGE('.$timestamp1.', '.$timestamp2.')'; } /** @@ -109,11 +116,12 @@ public function age($timestamp1, $timestamp2 = null) { * * @param string $text what to extract * @param string $time timestamp or interval to extract from + * * @return string */ public function date_part($text, $time) { - return 'DATE_PART(' . $text . ', ' . $time . ')'; + return 'DATE_PART('.$text.', '.$time.')'; } /** @@ -121,23 +129,26 @@ public function date_part($text, $time) * * @param string $time timestamp or interval * @param string $text how to the format the output + * * @return string */ - public function to_char($time, $text) { - return 'TO_CHAR(' . $time . ', ' . $text . ')'; + public function to_char($time, $text) + { + return 'TO_CHAR('.$time.', '.$text.')'; } /** - * PostgreSQLs CONCAT() function + * PostgreSQLs CONCAT() function. * * @param an array of values + * * @return string */ public function concat() { $args = func_get_args(); - return join(' || ' , $args); + return join(' || ', $args); } /** @@ -151,9 +162,9 @@ public function now() } /** - * regexp + * regexp. * - * @return string the regular expression operator + * @return string the regular expression operator */ public function regexp() { @@ -161,10 +172,9 @@ public function regexp() } /** - * return string to call a function to get random value inside an SQL statement + * return string to call a function to get random value inside an SQL statement. * * @return return string to generate float between 0 and 1 - * @access public */ public function random() { @@ -172,89 +182,89 @@ public function random() } /** - * build a pattern matching string + * build a pattern matching string. * * EXPERIMENTAL * * WARNING: this function is experimental and may change signature at * any time until labelled as non-experimental * - * @access public - * - * @param array $pattern even keys are strings, odd are patterns (% and _) + * @param array $pattern even keys are strings, odd are patterns (% and _) * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future) - * @param string $field optional field name that is being matched against - * (might be required when emulating ILIKE) + * @param string $field optional field name that is being matched against + * (might be required when emulating ILIKE) * * @return string SQL pattern */ public function matchPattern($pattern, $operator = null, $field = null) { $match = ''; - if ( ! is_null($operator)) { + if (!is_null($operator)) { $field = is_null($field) ? '' : $field.' '; $operator = strtoupper($operator); switch ($operator) { // case insensitive - case 'ILIKE': - $match = $field.'ILIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE '; - break; - default: - throw new Doctrine_Expression_Pgsql_Exception('not a supported operator type:'. $operator); + case 'ILIKE': + $match = $field.'ILIKE '; + break; + // case sensitive + case 'LIKE': + $match = $field.'LIKE '; + break; + default: + throw new Doctrine_Expression_Pgsql_Exception('not a supported operator type:'.$operator); } } - $match.= "'"; + $match .= "'"; foreach ($pattern as $key => $value) { if ($key % 2) { - $match.= $value; + $match .= $value; } else { - $match.= $this->conn->escapePattern($this->conn->escape($value)); + $match .= $this->conn->escapePattern($this->conn->escape($value)); } } - $match.= "'"; - $match.= $this->patternEscapeString(); + $match .= "'"; + $match .= $this->patternEscapeString(); + return $match; } /** - * return syntax for pgsql TRANSLATE() dbms function + * return syntax for pgsql TRANSLATE() dbms function. * * @return string $sql */ public function translate($string, $from, $to) { - $translate = 'TRANSLATE(' . $string . ', ' . $from . ', ' . $to . ')'; - return $translate; + return 'TRANSLATE('.$string.', '.$from.', '.$to.')'; } /** - * transform locate to position + * transform locate to position. * * @param string $substr string to find - * @param string $str to find where + * @param string $str to find where + * * @return string */ public function locate($substr, $str) { return $this->position($substr, $str); } - + /** - * position + * position. * * @param string $substr string to find - * @param string $str to find where + * @param string $str to find where + * * @return string */ public function position($substr, $str) { $substr = $this->getIdentifier($substr); $str = $this->getIdentifier($str); - + return sprintf('POSITION(%s IN %s)', $substr, $str); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Expression/Sqlite.php b/lib/Doctrine/Expression/Sqlite.php index d4ffcf3ed..35de55a36 100644 --- a/lib/Doctrine/Expression/Sqlite.php +++ b/lib/Doctrine/Expression/Sqlite.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Expression_Sqlite + * Doctrine_Expression_Sqlite. * - * @package Doctrine - * @subpackage Expression * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Expression_Sqlite extends Doctrine_Expression_Driver @@ -35,7 +36,6 @@ class Doctrine_Expression_Sqlite extends Doctrine_Expression_Driver /** * Returns the md5 sum of the data that SQLite's md5() function receives. * - * @param mixed $data * @return string */ public static function md5Impl($data) @@ -46,8 +46,9 @@ public static function md5Impl($data) /** * Returns the modules of the data that SQLite's mod() function receives. * - * @param integer $dividend - * @param integer $divisor + * @param int $dividend + * @param int $divisor + * * @return string */ public static function modImpl($dividend, $divisor) @@ -63,16 +64,18 @@ public static function modImpl($dividend, $divisor) public static function concatImpl() { $args = func_get_args(); + return join('', $args); } /** * locate * returns the position of the first occurrence of substring $substr in string $str that - * SQLite's locate() function receives + * SQLite's locate() function receives. + * + * @param string $substr literal string to find + * @param string $str literal string * - * @param string $substr literal string to find - * @param string $str literal string * @return string */ public static function locateImpl($substr, $str) @@ -99,13 +102,14 @@ public static function trimImpl($str) { return trim($str); } + public static function nowImpl() { return date('Y-m-d h:i:s'); } /** - * returns the regular expression operator + * returns the regular expression operator. * * @return string */ @@ -117,23 +121,24 @@ public function regexp() /** * soundex * Returns a string to call a function to compute the - * soundex encoding of a string + * soundex encoding of a string. * * The string "?000" is returned if the argument is NULL. * * @param string $value - * @return string SQL soundex function with given parameter + * + * @return string SQL soundex function with given parameter */ public function soundex($value) { - return 'SOUNDEX(' . $value . ')'; + return 'SOUNDEX('.$value.')'; } /** * Return string to call a variable with the current timestamp inside an SQL statement * There are three special variables for current date and time. * - * @return string sqlite function as string + * @return string sqlite function as string */ public function now($type = 'timestamp') { @@ -149,7 +154,7 @@ public function now($type = 'timestamp') } /** - * return string to call a function to get random value inside an SQL statement + * return string to call a function to get random value inside an SQL statement. * * @return string to generate float between 0 and 1 */ @@ -159,22 +164,24 @@ public function random() } /** - * return string to call a function to get a substring inside an SQL statement + * return string to call a function to get a substring inside an SQL statement. * * Note: Not SQL92, but common functionality. * * SQLite only supports the 2 parameter variant of this function * - * @param string $value an sql string literal or column name/alias - * @param integer $position where to start the substring portion - * @param integer $length the substring portion length - * @return string SQL substring function with given parameters + * @param string $value an sql string literal or column name/alias + * @param int $position where to start the substring portion + * @param int $length the substring portion length + * + * @return string SQL substring function with given parameters */ public function substring($value, $position, $length = null) { - if ($length !== null) { - return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')'; + if (null !== $length) { + return 'SUBSTR('.$value.', '.$position.', '.$length.')'; } - return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))'; + + return 'SUBSTR('.$value.', '.$position.', LENGTH('.$value.'))'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/File.php b/lib/Doctrine/File.php index 1d0cfe7ec..c9a6346c7 100644 --- a/lib/Doctrine/File.php +++ b/lib/Doctrine/File.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_File + * Doctrine_File. * - * @package Doctrine - * @subpackage File * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_File extends Doctrine_Record @@ -40,16 +40,17 @@ public function setTableDefinition() public function setUp() { $this->actAs('Searchable', array('className' => 'Doctrine_File_Index', - 'fields' => array('url', 'content'))); - + 'fields' => array('url', 'content'))); + $this->index('url', array('fields' => array('url'))); } public function get($name, $load = true) { - if ($name === 'content') { + if ('content' === $name) { return file_get_contents(parent::get('url')); } + return parent::get($name, $load); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/File/Index.php b/lib/Doctrine/File/Index.php index d97983696..07d49c660 100644 --- a/lib/Doctrine/File/Index.php +++ b/lib/Doctrine/File/Index.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_File_Index + * Doctrine_File_Index. * - * @package Doctrine - * @subpackage File * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_File_Index extends Doctrine_Record @@ -35,23 +35,23 @@ class Doctrine_File_Index extends Doctrine_Record public function setTableDefinition() { $this->hasColumn('keyword', 'string', 255, array('notnull' => true, - 'primary' => true)); - + 'primary' => true)); + $this->hasColumn('field', 'string', 50, array('notnull' => true, - 'primary' => true)); + 'primary' => true)); $this->hasColumn('position', 'string', 255, array('notnull' => true, - 'primary' => true)); - + 'primary' => true)); + $this->hasColumn('file_id', 'integer', 8, array('notnull' => true, - 'primary' => true)); + 'primary' => true)); } public function setUp() { $this->hasOne('Doctrine_File', array('local' => 'file_id', - 'foreign' => 'id', - 'onDelete' => 'CASCADE', - 'onUpdate' => 'CASCADE')); + 'foreign' => 'id', + 'onDelete' => 'CASCADE', + 'onUpdate' => 'CASCADE')); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Formatter.php b/lib/Doctrine/Formatter.php index d942b73b8..55b36f4db 100644 --- a/lib/Doctrine/Formatter.php +++ b/lib/Doctrine/Formatter.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Formatter + * Doctrine_Formatter. * - * @package Doctrine - * @subpackage Formatter * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Formatter extends Doctrine_Connection_Module { /** - * Quotes pattern (% and _) characters in a string) + * Quotes pattern (% and _) characters in a string). * * EXPERIMENTAL * @@ -42,34 +43,34 @@ class Doctrine_Formatter extends Doctrine_Connection_Module * * @param string the input string to quote * - * @return string quoted string + * @return string quoted string */ public function escapePattern($text) { - if ( ! $this->string_quoting['escape_pattern']) { + if (!$this->string_quoting['escape_pattern']) { return $text; } $tmp = $this->conn->string_quoting; - $text = str_replace($tmp['escape_pattern'], - $tmp['escape_pattern'] . + $text = str_replace($tmp['escape_pattern'], + $tmp['escape_pattern']. $tmp['escape_pattern'], $text); foreach ($this->wildcards as $wildcard) { - $text = str_replace($wildcard, $tmp['escape_pattern'] . $wildcard, $text); + $text = str_replace($wildcard, $tmp['escape_pattern'].$wildcard, $text); } + return $text; } /** * convertBooleans * some drivers need the boolean values to be converted into integers - * when using DQL API + * when using DQL API. * * This method takes care of that conversion * * @param array $item - * @return void */ public function convertBooleans($item) { @@ -84,11 +85,12 @@ public function convertBooleans($item) $item = (int) $item; } } + return $item; } /** - * Quote a string so it can be safely used as a table or column name + * Quote a string so it can be safely used as a table or column name. * * Delimiting style depends on which database driver is being used. * @@ -114,33 +116,32 @@ public function convertBooleans($item) * InterBase doesn't seem to be able to use delimited identifiers * via PHP 4. They work fine under PHP 5. * - * @param string $str identifier name to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param string $str identifier name to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteIdentifier($str, $checkOption = true) { - if ($checkOption && ! $this->conn->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { + if ($checkOption && !$this->conn->getAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER)) { return $str; } $tmp = $this->conn->identifier_quoting; $str = str_replace($tmp['end'], - $tmp['escape'] . + $tmp['escape']. $tmp['end'], $str); - return $tmp['start'] . $str . $tmp['end']; + return $tmp['start'].$str.$tmp['end']; } - - + /** * quoteMultipleIdentifier - * Quotes multiple identifier strings + * Quotes multiple identifier strings. * - * @param array $arr identifiers array to be quoted - * @param bool $checkOption check the 'quote_identifier' option + * @param array $arr identifiers array to be quoted + * @param bool $checkOption check the 'quote_identifier' option * - * @return string quoted identifier string + * @return string quoted identifier string */ public function quoteMultipleIdentifier($arr, $checkOption = true) { @@ -148,88 +149,95 @@ public function quoteMultipleIdentifier($arr, $checkOption = true) $arr[$k] = $this->quoteIdentifier($v, $checkOption); } - return $arr; + return $arr; } /** * quote - * quotes given input parameter + * quotes given input parameter. * - * @param mixed $input parameter to be quoted + * @param mixed $input parameter to be quoted * @param string $type + * * @return string */ public function quote($input, $type = null) { - if ($type == null) { + if (null == $type) { $type = gettype($input); } switch ($type) { - case 'integer': - case 'double': - case 'float': - case 'bool': - case 'decimal': - case 'int': - return $input; - case 'array': - case 'object': - $input = serialize($input); - case 'date': - case 'time': - case 'timestamp': - case 'string': - case 'char': - case 'varchar': - case 'text': - case 'gzip': - case 'blob': - case 'clob': - case 'enum': - case 'set': - case 'boolean': - return "'" . str_replace("'","''",$input) . "'"; + case 'integer': + case 'double': + case 'float': + case 'bool': + case 'decimal': + case 'int': + return $input; + case 'array': + case 'object': + $input = serialize($input); + // no break + case 'date': + case 'time': + case 'timestamp': + case 'string': + case 'char': + case 'varchar': + case 'text': + case 'gzip': + case 'blob': + case 'clob': + case 'enum': + case 'set': + case 'boolean': + return "'".str_replace("'", "''", $input)."'"; } } /** - * Removes any formatting in an sequence name using the 'seqname_format' option + * Removes any formatting in an sequence name using the 'seqname_format' option. * * @param string $sqn string that containts name of a potential sequence + * * @return string name of the sequence with possible formatting removed */ public function fixSequenceName($sqn) { - $seqPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->getAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT)).'$/i'; - $seqName = preg_replace($seqPattern, '\\1', $sqn); + $seqPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->getAttribute(Doctrine_Core::ATTR_SEQNAME_FORMAT)).'$/i'; + $seqName = preg_replace($seqPattern, '\\1', $sqn); - if ($seqName && ! strcasecmp($sqn, $this->getSequenceName($seqName))) { + if ($seqName && !strcasecmp($sqn, $this->getSequenceName($seqName))) { return $seqName; } + return $sqn; } /** - * Removes any formatting in an index name using the 'idxname_format' option + * Removes any formatting in an index name using the 'idxname_format' option. * * @param string $idx string that containts name of anl index + * * @return string name of the index with possible formatting removed */ public function fixIndexName($idx) { - $indexPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->getAttribute(Doctrine_Core::ATTR_IDXNAME_FORMAT)).'$/i'; - $indexName = preg_replace($indexPattern, '\\1', $idx); - if ($indexName && ! strcasecmp($idx, $this->getIndexName($indexName))) { + $indexPattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $this->conn->getAttribute(Doctrine_Core::ATTR_IDXNAME_FORMAT)).'$/i'; + $indexName = preg_replace($indexPattern, '\\1', $idx); + if ($indexName && !strcasecmp($idx, $this->getIndexName($indexName))) { return $indexName; } + return $idx; } /** - * adds sequence name formatting to a sequence name + * adds sequence name formatting to a sequence name. * * @param string name of the sequence - * @return string formatted sequence name + * + * @return string formatted sequence name */ public function getSequenceName($sqn) { @@ -238,22 +246,24 @@ public function getSequenceName($sqn) } /** - * adds index name formatting to a index name + * adds index name formatting to a index name. * * @param string name of the index - * @return string formatted index name + * + * @return string formatted index name */ public function getIndexName($idx) { return sprintf($this->conn->getAttribute(Doctrine_Core::ATTR_IDXNAME_FORMAT), preg_replace('/[^a-z0-9_\$]/i', '_', $idx)); } - + /** - * Formatting a foreign Key name + * Formatting a foreign Key name. * * @param string name of the foreign key - * @return string formatted foreign key name + * + * @return string formatted foreign key name */ public function getForeignKeyName($fkey) { @@ -262,14 +272,16 @@ public function getForeignKeyName($fkey) } /** - * adds table name formatting to a table name + * adds table name formatting to a table name. * * @param string name of the table - * @return string formatted table name + * + * @return string formatted table name */ public function getTableName($table) { $format = $this->conn->getAttribute(Doctrine_Core::ATTR_TBLNAME_FORMAT); + return sprintf($format, str_replace(sprintf($format, null), '', $table)); } } diff --git a/lib/Doctrine/Hook.php b/lib/Doctrine/Hook.php index 8d07492d7..3203c6bc7 100644 --- a/lib/Doctrine/Hook.php +++ b/lib/Doctrine/Hook.php @@ -20,61 +20,62 @@ */ /** - * Doctrine_Hook + * Doctrine_Hook. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Hook { /** - * @var Doctrine_Query $query the base query + * @var Doctrine_Query the base query */ protected $query; /** - * @var array $joins the optional joins of the base query + * @var array the optional joins of the base query */ protected $joins; /** - * @var array $hooks hooks array + * @var array hooks array */ - protected $hooks = array( - 'where', - 'orderby', - 'limit', - 'offset' - ); + protected $hooks = array( + 'where', + 'orderby', + 'limit', + 'offset', + ); /** - * @var array $fieldParsers custom field parsers array - * keys as field names in the format componentAlias.FieldName - * values as parser names / objects + * @var array custom field parsers array + * keys as field names in the format componentAlias.FieldName + * values as parser names / objects */ protected $fieldParsers = array(); /** - * @var array $typeParsers type parsers array - * keys as type names and values as parser names / objects + * @var array type parsers array + * keys as type names and values as parser names / objects */ - protected $typeParsers = array( - 'char' => 'Doctrine_Hook_WordLike', - 'string' => 'Doctrine_Hook_WordLike', - 'varchar' => 'Doctrine_Hook_WordLike', - 'integer' => 'Doctrine_Hook_Integer', - 'enum' => 'Doctrine_Hook_Integer', - 'time' => 'Doctrine_Hook_Time', - 'date' => 'Doctrine_Hook_Date', - ); + protected $typeParsers = array( + 'char' => 'Doctrine_Hook_WordLike', + 'string' => 'Doctrine_Hook_WordLike', + 'varchar' => 'Doctrine_Hook_WordLike', + 'integer' => 'Doctrine_Hook_Integer', + 'enum' => 'Doctrine_Hook_Integer', + 'time' => 'Doctrine_Hook_Time', + 'date' => 'Doctrine_Hook_Date', + ); /** - * @param Doctrine_Query $query the base query + * @param Doctrine_Query $query the base query */ public function __construct($query) { @@ -84,16 +85,16 @@ public function __construct($query) } elseif ($query instanceof Doctrine_Query) { $this->query = $query; } else { - throw new Doctrine_Exception('Constructor argument should be either Doctrine_Query object or valid DQL query'); + throw new Doctrine_Exception('Constructor argument should be either Doctrine_Query object or valid DQL query'); } - + $this->query->getSqlQuery(); } /** - * getQuery + * getQuery. * - * @return Doctrine_Query returns the query object associated with this hook + * @return Doctrine_Query returns the query object associated with this hook */ public function getQuery() { @@ -101,21 +102,21 @@ public function getQuery() } /** - * setTypeParser + * setTypeParser. * - * @param string $type type name - * @param string|object $parser parser name or custom parser object + * @param string $type type name + * @param string|object $parser parser name or custom parser object */ - public function setTypeParser($type, $parser) + public function setTypeParser($type, $parser) { $this->typeParsers[$type] = $parser; } /** - * setFieldParser + * setFieldParser. * - * @param string $field field name - * @param string|object $parser parser name or custom parser object + * @param string $field field name + * @param string|object $parser parser name or custom parser object */ public function setFieldParser($field, $parser) { @@ -124,39 +125,39 @@ public function setFieldParser($field, $parser) /** * hookWhere - * builds DQL query where part from given parameter array + * builds DQL query where part from given parameter array. + * + * @param array $params an associative array containing field + * names and their values * - * @param array $params an associative array containing field - * names and their values - * @return boolean whether or not the hooking was + * @return bool whether or not the hooking was */ public function hookWhere($params) { - if ( ! is_array($params)) { + if (!is_array($params)) { return false; } foreach ($params as $name => $value) { - if ($value === '' || $value === '-') { + if ('' === $value || '-' === $value) { continue; } $e = explode('.', $name); - if (count($e) == 2) { + if (2 == count($e)) { list($alias, $column) = $e; - $map = $this->query->getQueryComponent($alias); + $map = $this->query->getQueryComponent($alias); $table = $map['table']; - if ( ! $table) { - throw new Doctrine_Exception('Unknown alias ' . $alias); + if (!$table) { + throw new Doctrine_Exception('Unknown alias '.$alias); } if ($def = $table->getDefinitionOf($column)) { - - $def[0] = gettype($value); + $def[0] = gettype($value); if (isset($this->typeParsers[$def[0]])) { - $name = $this->typeParsers[$def[0]]; - $parser = new $name; + $name = $this->typeParsers[$def[0]]; + $parser = new $name(); } $parser->parse($alias, $column, $value); @@ -171,15 +172,16 @@ public function hookWhere($params) /** * hookOrderBy - * builds DQL query orderby part from given parameter array + * builds DQL query orderby part from given parameter array. + * + * @param array $params an array containing all fields which the built query + * should be ordered by * - * @param array $params an array containing all fields which the built query - * should be ordered by - * @return boolean whether or not the hooking was successful + * @return bool whether or not the hooking was successful */ public function hookOrderby($params) { - if ( ! is_array($params)) { + if (!is_array($params)) { return false; } foreach ($params as $name) { @@ -188,30 +190,30 @@ public function hookOrderby($params) $order = 'ASC'; if (count($e) > 1) { - $order = ($e[1] == 'DESC') ? 'DESC' : 'ASC'; + $order = ('DESC' == $e[1]) ? 'DESC' : 'ASC'; } $e = explode('.', $e[0]); - if (count($e) == 2) { + if (2 == count($e)) { list($alias, $column) = $e; - $map = $this->query->getQueryComponent($alias); + $map = $this->query->getQueryComponent($alias); $table = $map['table']; - if ($def = $table->getDefinitionOf($column)) { - $this->query->addOrderBy($alias . '.' . $column . ' ' . $order); + if ($def = $table->getDefinitionOf($column)) { + $this->query->addOrderBy($alias.'.'.$column.' '.$order); } } } + return true; } /** - * set the hook limit - * - * @param integer $limit - * @return void + * set the hook limit. + * + * @param int $limit */ public function hookLimit($limit) { @@ -219,9 +221,9 @@ public function hookLimit($limit) } /** - * set the hook offset + * set the hook offset. * - * @param integer $offset + * @param int $offset */ public function hookOffset($offset) { diff --git a/lib/Doctrine/Hook/Equal.php b/lib/Doctrine/Hook/Equal.php index 144f769ab..14da3f000 100644 --- a/lib/Doctrine/Hook/Equal.php +++ b/lib/Doctrine/Hook/Equal.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Hook_Equal + * Doctrine_Hook_Equal. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Hook_Equal extends Doctrine_Hook_Parser @@ -39,14 +40,13 @@ class Doctrine_Hook_Equal extends Doctrine_Hook_Parser * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parse($alias, $field, $value) { - $this->params = (array) $value; - $this->condition = $alias . '.' . $field . ' = ?'; + $this->params = (array) $value; + $this->condition = $alias.'.'.$field.' = ?'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hook/Integer.php b/lib/Doctrine/Hook/Integer.php index 20cf14dc2..06c58b463 100644 --- a/lib/Doctrine/Hook/Integer.php +++ b/lib/Doctrine/Hook/Integer.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Hook_Integer + * Doctrine_Hook_Integer. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Hook_Integer extends Doctrine_Hook_Parser_Complex @@ -39,37 +40,36 @@ class Doctrine_Hook_Integer extends Doctrine_Hook_Parser_Complex * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parseSingle($alias, $field, $value) { $e = explode(' ', $value); foreach ($e as $v) { - $v = trim($v); + $v = trim($v); - $e2 = explode('-', $v); + $e2 = explode('-', $v); - $name = $alias. '.' . $field; + $name = $alias.'.'.$field; - if (count($e2) == 1) { - // one '-' found + if (1 == count($e2)) { + // one '-' found - $a[] = $name . ' = ?'; + $a[] = $name.' = ?'; $this->params[] = $v; } else { // more than one '-' found - $a[] = '(' . $name . ' > ? AND ' . $name . ' < ?)'; + $a[] = '('.$name.' > ? AND '.$name.' < ?)'; $this->params += array($e2[0], $e2[1]); } - } + return implode(' OR ', $a); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hook/Parser.php b/lib/Doctrine/Hook/Parser.php index acb145780..f995ed365 100644 --- a/lib/Doctrine/Hook/Parser.php +++ b/lib/Doctrine/Hook/Parser.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Hook_Parser + * Doctrine_Hook_Parser. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Hook_Parser @@ -42,7 +43,7 @@ public function getCondition() /** * getParams - * returns the parameters associated with this parser + * returns the parameters associated with this parser. * * @return array */ @@ -58,10 +59,9 @@ public function getParams() * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ abstract public function parse($alias, $field, $value); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hook/Parser/Complex.php b/lib/Doctrine/Hook/Parser/Complex.php index 2e4671f09..774796696 100644 --- a/lib/Doctrine/Hook/Parser/Complex.php +++ b/lib/Doctrine/Hook/Parser/Complex.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Hook_Parser_Complex + * Doctrine_Hook_Parser_Complex. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Hook_Parser_Complex extends Doctrine_Hook_Parser { protected $_tokenizer; - + /** * Constructor. */ @@ -41,7 +42,7 @@ public function __construct() { $this->_tokenizer = new Doctrine_Query_Tokenizer(); } - + /** * parse * Parses given field and field value to DQL condition @@ -49,10 +50,9 @@ public function __construct() * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parse($alias, $field, $value) { @@ -60,12 +60,11 @@ public function parse($alias, $field, $value) } /** - * parseClause + * parseClause. * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parseClause($alias, $field, $value) { @@ -88,20 +87,19 @@ public function parseClause($alias, $field, $value) $r = implode(' OR ', $ret); } else { - $ret = $this->parseSingle($alias, $field, $parts[0]); - return $ret; + return $this->parseSingle($alias, $field, $parts[0]); } } - return '(' . $r . ')'; + + return '('.$r.')'; } /** - * parseSingle + * parseSingle. * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ abstract public function parseSingle($alias, $field, $value); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hook/WordLike.php b/lib/Doctrine/Hook/WordLike.php index ee1ff0680..2894e3470 100644 --- a/lib/Doctrine/Hook/WordLike.php +++ b/lib/Doctrine/Hook/WordLike.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Hook_WordLike + * Doctrine_Hook_WordLike. * - * @package Doctrine - * @subpackage Hook * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Hook_WordLike extends Doctrine_Hook_Parser_Complex @@ -39,28 +40,27 @@ class Doctrine_Hook_WordLike extends Doctrine_Hook_Parser_Complex * prepared statement conditions (conditions that use * placeholders instead of literal values). * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * @param string $alias component alias + * @param string $field the field name + * @param mixed $value the value of the field */ public function parseSingle($alias, $field, $value) { - if (strpos($value, "'") !== false) { + if (false !== strpos($value, "'")) { $value = $this->_tokenizer->bracketTrim($value, "'", "'"); - - $a[] = $alias . '.' . $field . ' LIKE ?'; - $this->params[] = '%' . $value . '%'; + $a[] = $alias.'.'.$field.' LIKE ?'; + $this->params[] = '%'.$value.'%'; } else { - $e2 = explode(' ',$value); - + $e2 = explode(' ', $value); + foreach ($e2 as $v) { $v = trim($v); - $a[] = $alias . '.' . $field . ' LIKE ?'; - $this->params[] = '%' . $v . '%'; + $a[] = $alias.'.'.$field.' LIKE ?'; + $this->params[] = '%'.$v.'%'; } } + return implode(' OR ', $a); } } diff --git a/lib/Doctrine/Hydrator.php b/lib/Doctrine/Hydrator.php index 129743e32..0595bd0bc 100644 --- a/lib/Doctrine/Hydrator.php +++ b/lib/Doctrine/Hydrator.php @@ -22,26 +22,24 @@ /** * Its purpose is to populate object graphs. * - * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3192 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Hydrator { - protected static - $_totalHydrationTime = 0; + protected static $_totalHydrationTime = 0; - protected - $_hydrators, - $_rootAlias = null, - $_hydrationMode = Doctrine_Core::HYDRATE_RECORD, - $_queryComponents = array(); + protected $_hydrators; + protected $_rootAlias; + protected $_hydrationMode = Doctrine_Core::HYDRATE_RECORD; + protected $_queryComponents = array(); public function __construct() { @@ -49,11 +47,11 @@ public function __construct() } /** - * Set the hydration mode + * Set the hydration mode. * - * @param mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants or - * a string representing the name of the hydration mode or - * or an instance of the hydration class + * @param mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants or + * a string representing the name of the hydration mode or + * or an instance of the hydration class */ public function setHydrationMode($hydrationMode) { @@ -61,7 +59,7 @@ public function setHydrationMode($hydrationMode) } /** - * Get the hydration mode + * Get the hydration mode. * * @return mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants */ @@ -71,9 +69,7 @@ public function getHydrationMode() } /** - * Set the array of query components - * - * @param array $queryComponents + * Set the array of query components. */ public function setQueryComponents(array $queryComponents) { @@ -81,7 +77,7 @@ public function setQueryComponents(array $queryComponents) } /** - * Get the array of query components + * Get the array of query components. * * @return array $queryComponents */ @@ -91,18 +87,19 @@ public function getQueryComponents() } /** - * Get the name of the driver class for the passed hydration mode + * Get the name of the driver class for the passed hydration mode. * * @param string $mode + * * @return string $className */ public function getHydratorDriverClassName($mode = null) { - if ($mode === null) { + if (null === $mode) { $mode = $this->_hydrationMode; } - if ( ! isset($this->_hydrators[$mode])) { + if (!isset($this->_hydrators[$mode])) { throw new Doctrine_Hydrator_Exception('Invalid hydration mode specified: '.$this->_hydrationMode); } @@ -110,17 +107,18 @@ public function getHydratorDriverClassName($mode = null) } /** - * Get an instance of the hydration driver for the passed hydration mode + * Get an instance of the hydration driver for the passed hydration mode. * * @param string $mode - * @param array $tableAliases + * @param array $tableAliases + * * @return Doctrine_Hydrator_Abstract */ public function getHydratorDriver($mode, $tableAliases) { $driverClass = $this->getHydratorDriverClassName($mode); if (is_object($driverClass)) { - if (!$driverClass instanceOf Doctrine_Hydrator_Abstract) { + if (!$driverClass instanceof Doctrine_Hydrator_Abstract) { throw new Doctrine_Hydrator_Exception('Invalid hydration class specified: '.get_class($driverClass)); } $driver = $driverClass; @@ -139,14 +137,14 @@ public function getHydratorDriver($mode, $tableAliases) * hydration drivers. * * @param object $stmt - * @param array $tableAliases + * @param array $tableAliases + * * @return mixed $result */ public function hydrateResultSet($stmt, $tableAliases) { $driver = $this->getHydratorDriver($this->_hydrationMode, $tableAliases); - $result = $driver->hydrateResultSet($stmt); - return $result; + return $driver->hydrateResultSet($stmt); } } diff --git a/lib/Doctrine/Hydrator/Abstract.php b/lib/Doctrine/Hydrator/Abstract.php index 3a4dc7dc4..af95fbf1c 100644 --- a/lib/Doctrine/Hydrator/Abstract.php +++ b/lib/Doctrine/Hydrator/Abstract.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Hydrator_Abstract + * Doctrine_Hydrator_Abstract. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3192 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Hydrator_Abstract extends Doctrine_Locator_Injectable { - protected - $_queryComponents = array(), - $_tableAliases = array(), - $_priorRow, - $_hydrationMode; + protected $_queryComponents = array(); + protected $_tableAliases = array(); + protected $_priorRow; + protected $_hydrationMode; public function __construct($queryComponents = null, $tableAliases = null, $hydrationMode = null) { @@ -46,10 +46,9 @@ public function __construct($queryComponents = null, $tableAliases = null, $hydr } /** - * Set the query components (structure and query instructions) + * Set the query components (structure and query instructions). * * @param array $queryComponents - * @return void */ public function setQueryComponents($queryComponents) { @@ -57,10 +56,9 @@ public function setQueryComponents($queryComponents) } /** - * Set the table aliases for this query + * Set the table aliases for this query. * * @param array $tableAliases - * @return void */ public function setTableAliases($tableAliases) { @@ -68,12 +66,11 @@ public function setTableAliases($tableAliases) } /** - * Set the hydration mode + * Set the hydration mode. * - * @param mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants or - * a string representing the name of the hydration mode or - * or an instance of the hydration class - * @return void + * @param mixed $hydrationMode One of the Doctrine_Core::HYDRATE_* constants or + * a string representing the name of the hydration mode or + * or an instance of the hydration class */ public function setHydrationMode($hydrationMode) { @@ -83,6 +80,7 @@ public function setHydrationMode($hydrationMode) public function getRootComponent() { $queryComponents = array_values($this->_queryComponents); + return $queryComponents[0]['table']; } @@ -97,24 +95,23 @@ public function onDemandReset() * (I.e. ORACLE limit/offset emulation adds doctrine_rownum to the result set). * * @param string $name + * * @return bool */ protected function _isIgnoredName($name) { - return $name === 'DOCTRINE_ROWNUM'; + return 'DOCTRINE_ROWNUM' === $name; } /** * hydrateResultSet - * parses the data returned by statement object + * parses the data returned by statement object. * * This is method defines the core of Doctrine object population algorithm * hence this method strives to be as fast as possible * * The key idea is the loop over the rowset only once doing all the needed operations * within this massive loop. - * - * @return mixed */ abstract public function hydrateResultSet($stmt); } diff --git a/lib/Doctrine/Hydrator/ArrayDriver.php b/lib/Doctrine/Hydrator/ArrayDriver.php index 0850ed0e2..cd878a9b6 100644 --- a/lib/Doctrine/Hydrator/ArrayDriver.php +++ b/lib/Doctrine/Hydrator/ArrayDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to the object graph using php arrays + * Builds result sets in to the object graph using php arrays. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Hydrator_ArrayDriver extends Doctrine_Hydrator_Graph @@ -44,49 +45,52 @@ public function getElement(array $data, $component) public function registerCollection($coll) { - } public function initRelated(&$record, $name, $keyColumn = null) { - if ( ! isset($record[$name])) { + if (!isset($record[$name])) { $record[$name] = array(); } + return true; } - public function getNullPointer() + public function getNullPointer() { - return null; + return null; } public function getLastKey(&$coll) { end($coll); + return key($coll); } public function setLastElement(&$prev, &$coll, $index, $dqlAlias, $oneToOne) { - if ($coll === null) { + if (null === $coll) { unset($prev[$dqlAlias]); // Ticket #1228 + return; } - if ($index !== false) { + if (false !== $index) { // Link element at $index to previous element for the component // identified by the DQL alias $alias - $prev[$dqlAlias] =& $coll[$index]; + $prev[$dqlAlias] = &$coll[$index]; + return; } - + if ($coll) { if ($oneToOne) { - $prev[$dqlAlias] =& $coll; + $prev[$dqlAlias] = &$coll; } else { end($coll); - $prev[$dqlAlias] =& $coll[key($coll)]; + $prev[$dqlAlias] = &$coll[key($coll)]; } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hydrator/ArrayHierarchyDriver.php b/lib/Doctrine/Hydrator/ArrayHierarchyDriver.php index 731ad0090..128ca7558 100644 --- a/lib/Doctrine/Hydrator/ArrayHierarchyDriver.php +++ b/lib/Doctrine/Hydrator/ArrayHierarchyDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to the hierarchy graph using php arrays + * Builds result sets in to the hierarchy graph using php arrays. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision$ + * * @author Guilherme Blanco */ class Doctrine_Hydrator_ArrayHierarchyDriver extends Doctrine_Hydrator_ArrayDriver @@ -41,7 +42,7 @@ public function hydrateResultSet($stmt) $table = $this->getRootComponent(); - if ( ! $table->isTree() || ! $table->hasColumn('level')) { + if (!$table->isTree() || !$table->hasColumn('level')) { throw new Doctrine_Exception('Cannot hydrate model that does not implements Tree behavior with `level` column'); } @@ -62,25 +63,26 @@ public function hydrateResultSet($stmt) $l = count($stack); // Check if we're dealing with different levels - while($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { + while ($l > 0 && $stack[$l - 1]['level'] >= $item['level']) { array_pop($stack); - $l--; + --$l; } // Stack is empty (we are inspecting the root) - if ($l == 0) { + if (0 == $l) { // Assigning the root child $i = count($trees); $trees[$i] = $item; - $stack[] = & $trees[$i]; + $stack[] = &$trees[$i]; } else { // Add child to parent $i = count($stack[$l - 1]['__children']); $stack[$l - 1]['__children'][$i] = $item; - $stack[] = & $stack[$l - 1]['__children'][$i]; + $stack[] = &$stack[$l - 1]['__children'][$i]; } } } + return $trees; } } diff --git a/lib/Doctrine/Hydrator/ArrayShallowDriver.php b/lib/Doctrine/Hydrator/ArrayShallowDriver.php index b595122b6..392b815cc 100644 --- a/lib/Doctrine/Hydrator/ArrayShallowDriver.php +++ b/lib/Doctrine/Hydrator/ArrayShallowDriver.php @@ -22,12 +22,14 @@ /** * Extended version of Doctrine_Hydrator_ScalarDriver, passes its _gatherRowData function a value of false for $aliasPrefix in order to cause it to generate the sorts of array keys one would see in a HYDRATE_ARRAY type return. * Note: This hydrator will have issues with fields in the return that have the same name (such as 2 fields each called id) -- the second field value will overwrite the first field. - * @package Doctrine - * @subpackage Hydrate + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2.3 + * * @version $Revision$ + * * @author Will Ferrer */ class Doctrine_Hydrator_ArrayShallowDriver extends Doctrine_Hydrator_ScalarDriver @@ -42,6 +44,7 @@ public function hydrateResultSet($stmt) while ($data = $stmt->fetch(Doctrine_Core::FETCH_ASSOC)) { $result[] = $this->_gatherRowData($data, $cache, false); } + return $result; } } diff --git a/lib/Doctrine/Hydrator/Exception.php b/lib/Doctrine/Hydrator/Exception.php index 571eba4af..7c5d1f441 100644 --- a/lib/Doctrine/Hydrator/Exception.php +++ b/lib/Doctrine/Hydrator/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Hydrator_Exception + * Doctrine_Hydrator_Exception. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Hydrator_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Hydrator/Graph.php b/lib/Doctrine/Hydrator/Graph.php index b227f3874..e80785d80 100644 --- a/lib/Doctrine/Hydrator/Graph.php +++ b/lib/Doctrine/Hydrator/Graph.php @@ -21,29 +21,29 @@ /** * Abstract base class for child drivers to hydrate the object graph in to - * various data types. For example Doctrine_Record instances or PHP arrays + * various data types. For example Doctrine_Record instances or PHP arrays. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Roman Borschel * @author Jonathan H. Wage */ abstract class Doctrine_Hydrator_Graph extends Doctrine_Hydrator_Abstract { - protected - $_tables = array(), - $_rootAlias = null; + protected $_tables = array(); + protected $_rootAlias; /** * Gets the custom field used for indexing for the specified component alias. * - * @return string The field name of the field used for indexing or NULL - * if the component does not use any custom field indices. + * @return string the field name of the field used for indexing or NULL + * if the component does not use any custom field indices */ protected function _getCustomIndexField($alias) { @@ -94,7 +94,7 @@ public function hydrateResultSet($stmt) if ($result instanceof Doctrine_Collection && $indexField = $this->_getCustomIndexField($rootAlias)) { $result->setKeyColumn($indexField); } - if ($stmt === false || $stmt === 0) { + if (false === $stmt || 0 === $stmt) { return $result; } @@ -103,21 +103,22 @@ public function hydrateResultSet($stmt) $event = new Doctrine_Event(null, Doctrine_Event::HYDRATE, null); - if ($this->_hydrationMode == Doctrine_Core::HYDRATE_ON_DEMAND) { - if ( ! is_null($this->_priorRow)) { + if (Doctrine_Core::HYDRATE_ON_DEMAND == $this->_hydrationMode) { + if (!is_null($this->_priorRow)) { $data = $this->_priorRow; $this->_priorRow = null; } else { $data = $stmt->fetch(Doctrine_Core::FETCH_ASSOC); - if ( ! $data) { + if (!$data) { return $result; } } $activeRootIdentifier = null; } else { $data = $stmt->fetch(Doctrine_Core::FETCH_ASSOC); - if ( ! $data) { + if (!$data) { $stmt->closeCursor(); + return $result; } } @@ -126,7 +127,7 @@ public function hydrateResultSet($stmt) $table = $this->_queryComponents[$rootAlias]['table']; if ($table->getConnection()->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_RTRIM) { - foreach($data as $key => $foo) { + foreach ($data as $key => $foo) { $data[$key] = (is_string($foo)) ? rtrim($foo) : $foo; } } @@ -135,13 +136,14 @@ public function hydrateResultSet($stmt) $nonemptyComponents = array(); $rowData = $this->_gatherRowData($data, $cache, $id, $nonemptyComponents); - if ($this->_hydrationMode == Doctrine_Core::HYDRATE_ON_DEMAND) { + if (Doctrine_Core::HYDRATE_ON_DEMAND == $this->_hydrationMode) { if (is_null($activeRootIdentifier)) { // first row for this record $activeRootIdentifier = $id[$rootAlias]; - } else if ($activeRootIdentifier != $id[$rootAlias]) { + } elseif ($activeRootIdentifier != $id[$rootAlias]) { // first row for the next record $this->_priorRow = $data; + return $result; } } @@ -159,7 +161,7 @@ public function hydrateResultSet($stmt) $index = false; // Check for an existing element - if ($isSimpleQuery || ! isset($identifierMap[$rootAlias][$id[$rootAlias]])) { + if ($isSimpleQuery || !isset($identifierMap[$rootAlias][$id[$rootAlias]])) { $element = $this->getElement($rowData[$rootAlias], $componentName); $event->set('data', $element); $listeners[$componentName]->postHydrate($event); @@ -167,10 +169,11 @@ public function hydrateResultSet($stmt) // do we need to index by a custom field? if ($field = $this->_getCustomIndexField($rootAlias)) { - if ( ! isset($element[$field])) { - throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key named '$field'."); - } else if (isset($result[$element[$field]])) { - throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping named '{$element[$field]}' for the field named '$field'."); + if (!isset($element[$field])) { + throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key named '{$field}'."); + } + if (isset($result[$element[$field]])) { + throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping named '{$element[$field]}' for the field named '{$field}'."); } $result[$element[$field]] = $element; } else { @@ -201,20 +204,17 @@ public function hydrateResultSet($stmt) $instances[$componentName]->preHydrate($event); // It would be nice if this could be moved to the query parser but I could not find a good place to implement it - if ( ! isset($map['parent'])) { - throw new Doctrine_Hydrator_Exception( - '"' . $componentName . '" with an alias of "' . $dqlAlias . '"' . - ' in your query does not reference the parent component it is related to.' - ); + if (!isset($map['parent'])) { + throw new Doctrine_Hydrator_Exception('"'.$componentName.'" with an alias of "'.$dqlAlias.'" in your query does not reference the parent component it is related to.'); } $parent = $map['parent']; $relation = $map['relation']; $relationAlias = $map['relation']->getAlias(); - $path = $parent . '.' . $dqlAlias; + $path = $parent.'.'.$dqlAlias; - if ( ! isset($prev[$parent])) { + if (!isset($prev[$parent])) { unset($prev[$dqlAlias]); // Ticket #1228 continue; } @@ -222,24 +222,25 @@ public function hydrateResultSet($stmt) $indexField = $this->_getCustomIndexField($dqlAlias); // check the type of the relation - if ( ! $relation->isOneToOne() && $this->initRelated($prev[$parent], $relationAlias, $indexField)) { + if (!$relation->isOneToOne() && $this->initRelated($prev[$parent], $relationAlias, $indexField)) { $oneToOne = false; // append element if (isset($nonemptyComponents[$dqlAlias])) { $indexExists = isset($identifierMap[$path][$id[$parent]][$id[$dqlAlias]]); $index = $indexExists ? $identifierMap[$path][$id[$parent]][$id[$dqlAlias]] : false; - $indexIsValid = $index !== false ? isset($prev[$parent][$relationAlias][$index]) : false; - if ( ! $indexExists || ! $indexIsValid) { + $indexIsValid = false !== $index ? isset($prev[$parent][$relationAlias][$index]) : false; + if (!$indexExists || !$indexIsValid) { $element = $this->getElement($data, $componentName); $event->set('data', $element); $listeners[$componentName]->postHydrate($event); $instances[$componentName]->postHydrate($event); if ($field = $this->_getCustomIndexField($dqlAlias)) { - if ( ! isset($element[$field])) { - throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key named '$field'."); - } else if (isset($prev[$parent][$relationAlias][$element[$field]])) { - throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping named '$field'."); + if (!isset($element[$field])) { + throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found a non-existent key named '{$field}'."); + } + if (isset($prev[$parent][$relationAlias][$element[$field]])) { + throw new Doctrine_Hydrator_Exception("Couldn't hydrate. Found non-unique key mapping named '{$field}'."); } $prev[$parent][$relationAlias][$element[$field]] = $element; } else { @@ -258,9 +259,9 @@ public function hydrateResultSet($stmt) } else { // 1-1 relation $oneToOne = true; - if ( ! isset($nonemptyComponents[$dqlAlias]) && ! isset($prev[$parent][$relationAlias])) { + if (!isset($nonemptyComponents[$dqlAlias]) && !isset($prev[$parent][$relationAlias])) { $prev[$parent][$relationAlias] = $this->getNullPointer(); - } else if ( ! isset($prev[$parent][$relationAlias])) { + } elseif (!isset($prev[$parent][$relationAlias])) { $element = $this->getElement($data, $componentName); // [FIX] Tickets #1205 and #1237 @@ -271,8 +272,8 @@ public function hydrateResultSet($stmt) $prev[$parent][$relationAlias] = $element; } } - if ($prev[$parent][$relationAlias] !== null && !$prev[$parent][$relationAlias] instanceof Doctrine_Null) { - $coll =& $prev[$parent][$relationAlias]; + if (null !== $prev[$parent][$relationAlias] && !$prev[$parent][$relationAlias] instanceof Doctrine_Null) { + $coll = &$prev[$parent][$relationAlias]; $this->setLastElement($prev, $coll, $index, $dqlAlias, $oneToOne); } } @@ -289,8 +290,8 @@ public function hydrateResultSet($stmt) * they belong to. The column names in the result set are mapped to their * field names during this procedure. * - * @return array An array with all the fields (name => value) of the data row, - * grouped by their component (alias). + * @return array an array with all the fields (name => value) of the data row, + * grouped by their component (alias) */ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) { @@ -298,7 +299,7 @@ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) foreach ($data as $key => $value) { // Parse each column name only once. Cache the results. - if ( ! isset($cache[$key])) { + if (!isset($cache[$key])) { // check ignored names. fastest solution for now. if we get more we'll start // to introduce a list. if ($this->_isIgnoredName($key)) { @@ -319,11 +320,11 @@ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) if ($table->isIdentifier($fieldName)) { $cache[$key]['isIdentifier'] = true; } else { - $cache[$key]['isIdentifier'] = false; + $cache[$key]['isIdentifier'] = false; } $type = $table->getTypeOfColumn($last); - if ($type == 'integer' || $type == 'string') { + if ('integer' == $type || 'string' == $type) { $cache[$key]['isSimpleType'] = true; } else { $cache[$key]['type'] = $type; @@ -342,7 +343,7 @@ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) } if ($cache[$key]['isIdentifier']) { - $id[$dqlAlias] .= '|' . $value; + $id[$dqlAlias] .= '|'.$value; } if ($cache[$key]['isSimpleType']) { @@ -363,7 +364,7 @@ protected function _gatherRowData(&$data, &$cache, &$id, &$nonemptyComponents) $rowData[$dqlAlias][$fieldName] = $preparedValue; } - if ( ! isset($nonemptyComponents[$dqlAlias]) && $value !== null) { + if (!isset($nonemptyComponents[$dqlAlias]) && null !== $value) { $nonemptyComponents[$dqlAlias] = true; } } @@ -387,11 +388,10 @@ abstract public function setLastElement(&$prev, &$coll, $index, $dqlAlias, $oneT public function flush() { - } /** - * Get the classname to return. Most often this is just the options['name'] + * Get the classname to return. Most often this is just the options['name']. * * Check the subclasses option and the inheritanceMap for each subclass to see * if all the maps in a subclass is met. If this is the case return that @@ -402,15 +402,14 @@ public function flush() * if the subclassing option is not set. * * @return string The name of the class to create - * */ protected function _getClassnameToReturn(array &$data, $component) { - if ( ! isset($this->_tables[$component])) { + if (!isset($this->_tables[$component])) { $this->_tables[$component] = Doctrine_Core::getTable($component); } - if ( ! ($subclasses = $this->_tables[$component]->getOption('subclasses'))) { + if (!($subclasses = $this->_tables[$component]->getOption('subclasses'))) { return $component; } @@ -426,7 +425,7 @@ protected function _getClassnameToReturn(array &$data, $component) --$needMatches; } } - if ($needMatches == 0) { + if (0 == $needMatches) { $matchedComponents[] = $table->getComponentName(); } } else { @@ -434,16 +433,15 @@ protected function _getClassnameToReturn(array &$data, $component) $key = $this->_tables[$component]->getFieldName($key); if (!isset($data[$key]) || $data[$key] != $value) { continue; - } else { - $matchedComponents[] = $table->getComponentName(); } + $matchedComponents[] = $table->getComponentName(); } } } - $matchedComponent = $matchedComponents[count($matchedComponents)-1]; + $matchedComponent = $matchedComponents[count($matchedComponents) - 1]; - if ( ! isset($this->_tables[$matchedComponent])) { + if (!isset($this->_tables[$matchedComponent])) { $this->_tables[$matchedComponent] = Doctrine_Core::getTable($matchedComponent); } diff --git a/lib/Doctrine/Hydrator/NoneDriver.php b/lib/Doctrine/Hydrator/NoneDriver.php index 6da15a6d6..924b7706b 100644 --- a/lib/Doctrine/Hydrator/NoneDriver.php +++ b/lib/Doctrine/Hydrator/NoneDriver.php @@ -20,22 +20,19 @@ */ /** - * Get results directly and skip hydration. Uses PDO::FETCH_NUM + * Get results directly and skip hydration. Uses PDO::FETCH_NUM. * - * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision: 3192 $ + * * @author Jonathan H. Wage */ class Doctrine_Hydrator_NoneDriver extends Doctrine_Hydrator_Abstract { - /** - * @return mixed - */ public function hydrateResultSet($stmt) { return $stmt->fetchAll(PDO::FETCH_NUM); diff --git a/lib/Doctrine/Hydrator/RecordDriver.php b/lib/Doctrine/Hydrator/RecordDriver.php index a028645d4..5b510c53f 100644 --- a/lib/Doctrine/Hydrator/RecordDriver.php +++ b/lib/Doctrine/Hydrator/RecordDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to the object graph using Doctrine_Record instances + * Builds result sets in to the object graph using Doctrine_Record instances. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Roman Borschel * @author Jonathan H. Wage @@ -44,68 +45,70 @@ public function getElementCollection($component) return $coll; } - + public function initRelated(&$record, $name, $keyColumn = null) { - if ( ! isset($this->_initializedRelations[$record->getOid()][$name])) { + if (!isset($this->_initializedRelations[$record->getOid()][$name])) { $relation = $record->getTable()->getRelation($name); $coll = Doctrine_Collection::create($relation->getTable()->getComponentName(), $keyColumn); $coll->setReference($record, $relation); $record[$name] = $coll; $this->_initializedRelations[$record->getOid()][$name] = true; } + return true; } - + public function registerCollection($coll) { $this->_collections[] = $coll; } - - public function getNullPointer() + + public function getNullPointer() { return self::$_null; } - + public function getElement(array $data, $component) { $component = $this->_getClassNameToReturn($data, $component); $this->_tables[$component]->setData($data); - $record = $this->_tables[$component]->getRecord(); - return $record; + return $this->_tables[$component]->getRecord(); } - public function getLastKey(&$coll) + public function getLastKey(&$coll) { $coll->end(); - + return $coll->key(); } /** * sets the last element of given data array / collection - * as previous element + * as previous element. + * + * @param bool|int $index * - * @param boolean|integer $index - * @return void * @todo Detailed documentation */ public function setLastElement(&$prev, &$coll, $index, $dqlAlias, $oneToOne) { if ($coll === self::$_null) { unset($prev[$dqlAlias]); // Ticket #1228 + return; } - if ($index !== false) { + if (false !== $index) { // Link element at $index to previous element for the component // identified by the DQL alias $alias $prev[$dqlAlias] = $coll[$index]; + return; } - + if (count($coll) > 0) { $prev[$dqlAlias] = $coll->getLast(); } @@ -121,4 +124,4 @@ public function flush() $this->_collections = array(); $this->_tables = null; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Hydrator/RecordHierarchyDriver.php b/lib/Doctrine/Hydrator/RecordHierarchyDriver.php index 28c54e20e..63266ea0d 100644 --- a/lib/Doctrine/Hydrator/RecordHierarchyDriver.php +++ b/lib/Doctrine/Hydrator/RecordHierarchyDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to the hierarchy graph using php arrays + * Builds result sets in to the hierarchy graph using php arrays. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.2 + * * @version $Revision$ + * * @author Guilherme Blanco */ class Doctrine_Hydrator_RecordHierarchyDriver extends Doctrine_Hydrator_RecordDriver diff --git a/lib/Doctrine/Hydrator/ScalarDriver.php b/lib/Doctrine/Hydrator/ScalarDriver.php index d3ce87e66..8a315e166 100644 --- a/lib/Doctrine/Hydrator/ScalarDriver.php +++ b/lib/Doctrine/Hydrator/ScalarDriver.php @@ -20,14 +20,15 @@ */ /** - * Builds result sets in to a scalar php array + * Builds result sets in to a scalar php array. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Hydrator_ScalarDriver extends Doctrine_Hydrator_Abstract @@ -52,8 +53,8 @@ protected function _gatherRowData($data, &$cache, $aliasPrefix = true) $rowData = array(); foreach ($data as $key => $value) { // Parse each column name only once. Cache the results. - if ( ! isset($cache[$key])) { - if ($key == 'DOCTRINE_ROWNUM') { + if (!isset($cache[$key])) { + if ('DOCTRINE_ROWNUM' == $key) { continue; } // cache general information like the column name <-> field name mapping @@ -74,7 +75,7 @@ protected function _gatherRowData($data, &$cache, $aliasPrefix = true) // cache type information $type = $table->getTypeOfColumn($columnName); - if ($type == 'integer' || $type == 'string') { + if ('integer' == $type || 'string' == $type) { $cache[$key]['isSimpleType'] = true; } else { $cache[$key]['type'] = $type; @@ -86,15 +87,16 @@ protected function _gatherRowData($data, &$cache, $aliasPrefix = true) $dqlAlias = $cache[$key]['dqlAlias']; $fieldName = $cache[$key]['fieldName']; - $rowDataKey = $aliasPrefix ? $dqlAlias . '_' . $fieldName:$fieldName; + $rowDataKey = $aliasPrefix ? $dqlAlias.'_'.$fieldName : $fieldName; if ($cache[$key]['isSimpleType'] || $cache[$key]['isAgg']) { $rowData[$rowDataKey] = $value; } else { $rowData[$rowDataKey] = $table->prepareValue( - $fieldName, $value, $cache[$key]['type']); + $fieldName, $value, $cache[$key]['type']); } } + return $rowData; } } diff --git a/lib/Doctrine/Hydrator/SingleScalarDriver.php b/lib/Doctrine/Hydrator/SingleScalarDriver.php index bf7589522..8b7fcd398 100644 --- a/lib/Doctrine/Hydrator/SingleScalarDriver.php +++ b/lib/Doctrine/Hydrator/SingleScalarDriver.php @@ -20,20 +20,20 @@ */ /** - * Returns the first row and first column single scalar value + * Returns the first row and first column single scalar value. * - * @package Doctrine - * @subpackage Hydrate * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Hydrator_SingleScalarDriver extends Doctrine_Hydrator_Abstract { /** - * @param mixed $stmt * @return array|mixed */ public function hydrateResultSet($stmt) @@ -42,10 +42,10 @@ public function hydrateResultSet($stmt) while (($val = $stmt->fetchColumn()) !== false) { $result[] = $val; } - if (count($result) === 1) { + if (1 === count($result)) { return $result[0]; - } else { - return $result; } + + return $result; } } diff --git a/lib/Doctrine/I18n.php b/lib/Doctrine/I18n.php index e520fe50d..ca6d4caba 100644 --- a/lib/Doctrine/I18n.php +++ b/lib/Doctrine/I18n.php @@ -20,39 +20,39 @@ */ /** - * Doctrine_I18n + * Doctrine_I18n. * - * @package Doctrine - * @subpackage I18n * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_I18n extends Doctrine_Record_Generator { protected $_options = array( - 'className' => '%CLASS%Translation', - 'tableName' => '%TABLE%_translation', - 'fields' => array(), - 'generateFiles' => false, - 'table' => false, - 'pluginTable' => false, - 'children' => array(), - 'i18nField' => 'lang', - 'type' => 'string', - 'length' => 2, - 'options' => array(), - 'cascadeDelete' => true, - 'appLevelDelete'=> false - ); + 'className' => '%CLASS%Translation', + 'tableName' => '%TABLE%_translation', + 'fields' => array(), + 'generateFiles' => false, + 'table' => false, + 'pluginTable' => false, + 'children' => array(), + 'i18nField' => 'lang', + 'type' => 'string', + 'length' => 2, + 'options' => array(), + 'cascadeDelete' => true, + 'appLevelDelete' => false, + ); /** - * __construct + * __construct. * - * @param string $options - * @return void + * @param string $options */ public function __construct($options) { @@ -66,16 +66,13 @@ public function buildRelation() } /** - * buildDefinition - * - * @param object $Doctrine_Table - * @return void + * buildDefinition. */ public function setTableDefinition() { - if (empty($this->_options['fields'])) { - throw new Doctrine_I18n_Exception('Fields not set.'); - } + if (empty($this->_options['fields'])) { + throw new Doctrine_I18n_Exception('Fields not set.'); + } $options = array('className' => $this->_options['className']); @@ -86,7 +83,7 @@ public function setTableDefinition() $fieldName = $this->_options['table']->getFieldName($column); if (in_array($fieldName, $this->_options['fields'])) { if ($column != $fieldName) { - $column .= ' as ' . $fieldName; + $column .= ' as '.$fieldName; } $columns[$column] = $definition; $this->_options['table']->removeColumn($fieldName); @@ -97,27 +94,27 @@ public function setTableDefinition() $defaultOptions = array( 'fixed' => true, - 'primary' => true + 'primary' => true, ); $options = array_merge($defaultOptions, $this->_options['options']); $this->hasColumn($this->_options['i18nField'], $this->_options['type'], $this->_options['length'], $options); $this->bindQueryParts(array('indexBy' => $this->_options['i18nField'])); - + // Rewrite any relations to our original table $originalName = $this->_options['table']->getClassnameToReturn(); $relations = $this->_options['table']->getRelationParser()->getPendingRelations(); - foreach($relations as $table => $relation) { - if ($table != $this->_table->getTableName() ) { + foreach ($relations as $table => $relation) { + if ($table != $this->_table->getTableName()) { // check that the localColumn is part of the moved col if (isset($relation['local']) && in_array($relation['local'], $this->_options['fields'])) { // found one, let's rewrite it $this->_options['table']->getRelationParser()->unsetPendingRelations($table); - + // and bind the rewritten one $this->_table->getRelationParser()->bind($table, $relation); - + // now try to get the reverse relation, to rewrite it $rp = Doctrine_Core::getTable($table)->getRelationParser(); $others = $rp->getPendingRelation($originalName); @@ -125,10 +122,10 @@ public function setTableDefinition() $others['class'] = $this->_table->getClassnameToReturn(); $others['alias'] = $this->_table->getClassnameToReturn(); $rp->unsetPendingRelations($originalName); - $rp->bind($this->_table->getClassnameToReturn() ,$others); + $rp->bind($this->_table->getClassnameToReturn(), $others); } } } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/I18n/Exception.php b/lib/Doctrine/I18n/Exception.php index cd1845a15..553f17515 100644 --- a/lib/Doctrine/I18n/Exception.php +++ b/lib/Doctrine/I18n/Exception.php @@ -18,17 +18,19 @@ * and is licensed under the LGPL. For more information, see * . */ - + /** - * Doctrine_I18n_Exception + * Doctrine_I18n_Exception. * - * @package Doctrine - * @subpackage I18n * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_I18n_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Import.php b/lib/Doctrine/Import.php index 928c1dd26..8dbe68c20 100644 --- a/lib/Doctrine/Import.php +++ b/lib/Doctrine/Import.php @@ -25,12 +25,14 @@ * reading to a reader object and passes the result to a builder object which * builds a Doctrine data model. * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jukka Hassinen */ @@ -39,74 +41,77 @@ class Doctrine_Import extends Doctrine_Connection_Module protected $sql = array(); /** - * lists all databases + * lists all databases. * * @return array */ public function listDatabases() { - if ( ! isset($this->sql['listDatabases'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listDatabases'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listDatabases']); } /** - * lists all availible database functions + * lists all availible database functions. * * @return array */ public function listFunctions() { - if ( ! isset($this->sql['listFunctions'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listFunctions'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listFunctions']); } /** - * lists all database triggers + * lists all database triggers. * * @param string|null $database + * * @return array */ public function listTriggers($database = null) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) { - if ( ! isset($this->sql['listSequences'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listSequences'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listSequences']); } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table relations + * lists table relations. * - * Expects an array of this format to be returned with all the relationships in it where the key is + * Expects an array of this format to be returned with all the relationships in it where the key is * the name of the foreign table, and the value is an array containing the local and foreign column * name * @@ -119,103 +124,111 @@ public function listTableConstraints($table) * ) * ) * - * @param string $table database table name + * @param string $table database table name + * * @return array */ public function listTableRelations($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists table views + * lists table views. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } /** - * lists database users + * lists database users. * * @return array */ public function listUsers() { - if ( ! isset($this->sql['listUsers'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listUsers'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listUsers']); } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) { - if ( ! isset($this->sql['listViews'])) { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + if (!isset($this->sql['listViews'])) { + throw new Doctrine_Import_Exception(__FUNCTION__.' not supported by this driver.'); } return $this->conn->fetchColumn($this->sql['listViews']); } /** - * checks if a database exists + * checks if a database exists. * * @param string $database - * @return boolean + * + * @return bool */ public function databaseExists($database) { @@ -223,10 +236,11 @@ public function databaseExists($database) } /** - * checks if a function exists + * checks if a function exists. * * @param string $function - * @return boolean + * + * @return bool */ public function functionExists($function) { @@ -234,11 +248,12 @@ public function functionExists($function) } /** - * checks if a trigger exists + * checks if a trigger exists. * - * @param string $trigger + * @param string $trigger * @param string|null $database - * @return boolean + * + * @return bool */ public function triggerExists($trigger, $database = null) { @@ -246,11 +261,12 @@ public function triggerExists($trigger, $database = null) } /** - * checks if a sequence exists + * checks if a sequence exists. * - * @param string $sequence + * @param string $sequence * @param string|null $database - * @return boolean + * + * @return bool */ public function sequenceExists($sequence, $database = null) { @@ -258,11 +274,12 @@ public function sequenceExists($sequence, $database = null) } /** - * checks if a table constraint exists + * checks if a table constraint exists. * * @param string $constraint - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableConstraintExists($constraint, $table) { @@ -270,11 +287,12 @@ public function tableConstraintExists($constraint, $table) } /** - * checks if a table column exists + * checks if a table column exists. * * @param string $column - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableColumnExists($column, $table) { @@ -282,11 +300,12 @@ public function tableColumnExists($column, $table) } /** - * checks if a table index exists + * checks if a table index exists. * * @param string $index - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableIndexExists($index, $table) { @@ -294,11 +313,12 @@ public function tableIndexExists($index, $table) } /** - * checks if a table exists + * checks if a table exists. * - * @param string $table + * @param string $table * @param string|null $database - * @return boolean + * + * @return bool */ public function tableExists($table, $database = null) { @@ -306,11 +326,12 @@ public function tableExists($table, $database = null) } /** - * checks if a table trigger exists + * checks if a table trigger exists. * * @param string $trigger - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableTriggerExists($trigger, $table) { @@ -318,11 +339,12 @@ public function tableTriggerExists($trigger, $table) } /** - * checks if a table view exists + * checks if a table view exists. * * @param string $view - * @param string $table database table name - * @return boolean + * @param string $table database table name + * + * @return bool */ public function tableViewExists($view, $table) { @@ -330,10 +352,11 @@ public function tableViewExists($view, $table) } /** - * checks if a user exists + * checks if a user exists. * * @param string $user - * @return boolean + * + * @return bool */ public function userExists($user) { @@ -341,25 +364,27 @@ public function userExists($user) } /** - * checks if a view exists + * checks if a view exists. * - * @param string $view + * @param string $view * @param string|null $database - * @return boolean + * + * @return bool */ public function viewExists($view, $database = null) { - return in_array($view, $this->listViews($database)); + return in_array($view, $this->listViews($database)); } /** - * importSchema + * importSchema. * * method for importing existing schema to Doctrine_Record classes * * @param string $directory - * @param array $connections Array of connection names to generate models for - * @return array the names of the imported classes + * @param array $connections Array of connection names to generate models for + * + * @return array the names of the imported classes */ public function importSchema($directory, array $connections = array(), array $options = array()) { @@ -367,79 +392,80 @@ public function importSchema($directory, array $connections = array(), array $op $manager = Doctrine_Manager::getInstance(); foreach ($manager as $name => $connection) { - // Limit the databases to the ones specified by $connections. - // Check only happens if array is not empty - if ( ! empty($connections) && ! in_array($name, $connections)) { - continue; - } - - $builder = new Doctrine_Import_Builder(); - $builder->setTargetPath($directory); - $builder->setOptions($options); - - $definitions = array(); - - foreach ($connection->import->listTables() as $table) { - $definition = array(); - $definition['tableName'] = $table; - $definition['className'] = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); - $definition['columns'] = $connection->import->listTableColumns($table); - $definition['connection'] = $connection->getName(); - $definition['connectionClassName'] = $definition['className']; - - try { - $definition['relations'] = array(); - $relations = $connection->import->listTableRelations($table); - $relClasses = array(); - foreach ($relations as $relation) { - $table = $relation['table']; - $class = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); - if (in_array($class, $relClasses)) { - $alias = $class . '_' . (count($relClasses) + 1); - } else { - $alias = $class; - } - $relClasses[] = $class; - $definition['relations'][$alias] = array( - 'alias' => $alias, - 'class' => $class, - 'local' => $relation['local'], - 'foreign' => $relation['foreign'] - ); - } - } catch (Exception $e) {} - - $definitions[strtolower($definition['className'])] = $definition; - $classes[] = $definition['className']; - } - - // Build opposite end of relationships - foreach ($definitions as $definition) { - $className = $definition['className']; - $relClasses = array(); - foreach ($definition['relations'] as $alias => $relation) { - if (in_array($relation['class'], $relClasses) || isset($definitions[$relation['class']]['relations'][$className])) { - $alias = $className . '_' . (count($relClasses) + 1); - } else { - $alias = $className; - } - $relClasses[] = $relation['class']; - $definitions[strtolower($relation['class'])]['relations'][$alias] = array( - 'type' => Doctrine_Relation::MANY, - 'alias' => $alias, - 'class' => $className, - 'local' => $relation['foreign'], - 'foreign' => $relation['local'] - ); - } - } - - // Build records - foreach ($definitions as $definition) { - $builder->buildRecord($definition); - } + // Limit the databases to the ones specified by $connections. + // Check only happens if array is not empty + if (!empty($connections) && !in_array($name, $connections)) { + continue; + } + + $builder = new Doctrine_Import_Builder(); + $builder->setTargetPath($directory); + $builder->setOptions($options); + + $definitions = array(); + + foreach ($connection->import->listTables() as $table) { + $definition = array(); + $definition['tableName'] = $table; + $definition['className'] = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); + $definition['columns'] = $connection->import->listTableColumns($table); + $definition['connection'] = $connection->getName(); + $definition['connectionClassName'] = $definition['className']; + + try { + $definition['relations'] = array(); + $relations = $connection->import->listTableRelations($table); + $relClasses = array(); + foreach ($relations as $relation) { + $table = $relation['table']; + $class = Doctrine_Inflector::classify(Doctrine_Inflector::tableize($table)); + if (in_array($class, $relClasses)) { + $alias = $class.'_'.(count($relClasses) + 1); + } else { + $alias = $class; + } + $relClasses[] = $class; + $definition['relations'][$alias] = array( + 'alias' => $alias, + 'class' => $class, + 'local' => $relation['local'], + 'foreign' => $relation['foreign'], + ); + } + } catch (Exception $e) { + } + + $definitions[strtolower($definition['className'])] = $definition; + $classes[] = $definition['className']; + } + + // Build opposite end of relationships + foreach ($definitions as $definition) { + $className = $definition['className']; + $relClasses = array(); + foreach ($definition['relations'] as $alias => $relation) { + if (in_array($relation['class'], $relClasses) || isset($definitions[$relation['class']]['relations'][$className])) { + $alias = $className.'_'.(count($relClasses) + 1); + } else { + $alias = $className; + } + $relClasses[] = $relation['class']; + $definitions[strtolower($relation['class'])]['relations'][$alias] = array( + 'type' => Doctrine_Relation::MANY, + 'alias' => $alias, + 'class' => $className, + 'local' => $relation['foreign'], + 'foreign' => $relation['local'], + ); + } + } + + // Build records + foreach ($definitions as $definition) { + $builder->buildRecord($definition); + } } return $classes; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Builder.php b/lib/Doctrine/Import/Builder.php index 7dc64d4ab..1267b9e4c 100644 --- a/lib/Doctrine/Import/Builder.php +++ b/lib/Doctrine/Import/Builder.php @@ -20,178 +20,176 @@ */ /** - * Doctrine_Import_Builder + * Doctrine_Import_Builder. * * Import builder is responsible of building Doctrine_Record classes * based on a database schema. * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen * @author Jukka Hassinen * @author Nicolas Bérard-Nault * @author Jonathan H. Wage */ -#[\AllowDynamicProperties] +#[AllowDynamicProperties] class Doctrine_Import_Builder extends Doctrine_Builder { /** - * Path where to generated files + * Path where to generated files. * - * @var string $_path + * @var string */ protected $_path = ''; /** - * Class prefix for generated packages + * Class prefix for generated packages. * * @var string */ protected $_packagesPrefix = 'Package'; /** - * Path to generate packages + * Path to generate packages. * * @var string */ protected $_packagesPath = ''; /** - * Name of folder to generate packages in + * Name of folder to generate packages in. * * @var string */ protected $_packagesFolderName = 'packages'; /** - * File suffix to use when writing class definitions + * File suffix to use when writing class definitions. * - * @var string $suffix + * @var string */ protected $_suffix = '.php'; /** - * Bool true/false for whether or not to generate base classes + * Bool true/false for whether or not to generate base classes. * - * @var boolean $generateBaseClasses + * @var bool */ protected $_generateBaseClasses = true; /** - * Bool true/false for whether or not to generate child table classes + * Bool true/false for whether or not to generate child table classes. * - * @var boolean $generateTableClasses + * @var bool */ protected $_generateTableClasses = false; /** - * Prefix to use for generated base classes + * Prefix to use for generated base classes. * * @var string */ protected $_baseClassPrefix = 'Base'; /** - * Directory to put the generate base classes in + * Directory to put the generate base classes in. * - * @var string $suffix + * @var string */ protected $_baseClassesDirectory = 'generated'; /** - * Base class name for generated classes + * Base class name for generated classes. * * @var string */ protected $_baseClassName = 'Doctrine_Record'; /** - * Base table class name for generated classes + * Base table class name for generated classes. * * @var string */ protected $_baseTableClassName = 'Doctrine_Table'; /** - * Format to use for generating the model table classes + * Format to use for generating the model table classes. * * @var string */ protected $_tableClassFormat = '%sTable'; /** - * Prefix to all generated classes + * Prefix to all generated classes. * * @var string */ - protected $_classPrefix = null; + protected $_classPrefix; /** - * Whether to use the class prefix for the filenames too + * Whether to use the class prefix for the filenames too. * - * @var boolean - **/ + * @var bool + */ protected $_classPrefixFiles = true; /** - * Whether or not to generate PEAR style directories and files + * Whether or not to generate PEAR style directories and files. * - * @var boolean + * @var bool */ protected $_pearStyle = false; /** - * Allows to force a line-ending style, by default PHP_EOL will be used + * Allows to force a line-ending style, by default PHP_EOL will be used. * * @var string */ - protected $_eolStyle = null; + protected $_eolStyle; /** - * The package name to use for the generated php docs + * The package name to use for the generated php docs. * * @var string */ protected $_phpDocPackage = '##PACKAGE##'; /** - * The subpackage name to use for the generated php docs + * The subpackage name to use for the generated php docs. * * @var string */ protected $_phpDocSubpackage = '##SUBPACKAGE##'; /** - * Full name of the author to use for the generated php docs + * Full name of the author to use for the generated php docs. * * @var string */ protected $_phpDocName = '##NAME##'; /** - * Email of the author to use for the generated php docs + * Email of the author to use for the generated php docs. * * @var string */ protected $_phpDocEmail = '##EMAIL##'; /** - * _tpl + * _tpl. * * Class template used for writing classes - * - * @var $_tpl */ protected static $_tpl; /** - * __construct - * - * @return void + * __construct. */ public function __construct() { @@ -209,16 +207,15 @@ public function __construct() } /** - * setTargetPath + * setTargetPath. * * @param string path the path where imported files are being generated - * @return */ public function setTargetPath($path) { if ($path) { - if ( ! $this->_packagesPath) { - $this->setOption('packagesPath', $path . DIRECTORY_SEPARATOR . $this->_packagesFolderName); + if (!$this->_packagesPath) { + $this->setOption('packagesPath', $path.DIRECTORY_SEPARATOR.$this->_packagesFolderName); } $this->_path = $path; @@ -226,16 +223,17 @@ public function setTargetPath($path) } /** - * generateBaseClasses + * generateBaseClasses. * * Specify whether or not to generate classes which extend from generated base classes * - * @param boolean $bool - * @return boolean $bool + * @param bool $bool + * + * @return bool $bool */ public function generateBaseClasses($bool = null) { - if ($bool !== null) { + if (null !== $bool) { $this->_generateBaseClasses = $bool; } @@ -243,16 +241,17 @@ public function generateBaseClasses($bool = null) } /** - * generateTableClasses + * generateTableClasses. * * Specify whether or not to generate children table classes * - * @param boolean $bool - * @return boolean $bool + * @param bool $bool + * + * @return bool $bool */ public function generateTableClasses($bool = null) { - if ($bool !== null) { + if (null !== $bool) { $this->_generateTableClasses = $bool; } @@ -260,9 +259,9 @@ public function generateTableClasses($bool = null) } /** - * getTargetPath + * getTargetPath. * - * @return string the path where imported files are being generated + * @return string the path where imported files are being generated */ public function getTargetPath() { @@ -270,14 +269,13 @@ public function getTargetPath() } /** - * setOptions + * setOptions. * * @param string $options - * @return void */ public function setOptions($options) { - if ( ! empty($options)) { + if (!empty($options)) { foreach ($options as $key => $value) { $this->setOption($key, $value); } @@ -285,30 +283,27 @@ public function setOptions($options) } /** - * setOption + * setOption. * * @param string $key * @param string $value - * @return void */ public function setOption($key, $value) { - $name = 'set' . Doctrine_Inflector::classify($key); + $name = 'set'.Doctrine_Inflector::classify($key); if (method_exists($this, $name)) { - $this->$name($value); + $this->{$name}($value); } else { - $key = '_' . $key; - $this->$key = $value; + $key = '_'.$key; + $this->{$key} = $value; } } /** - * loadTemplate + * loadTemplate. * * Loads the class template used for generating classes - * - * @return void */ public function loadTemplate() { @@ -317,13 +312,13 @@ public function loadTemplate() } self::$_tpl = '/**' - . '%s' . PHP_EOL - . ' */' . PHP_EOL - . '%sclass %s extends %s' . PHP_EOL - . '{' - . '%s' . PHP_EOL - . '%s' . PHP_EOL - . '}'; + .'%s'.PHP_EOL + .' */'.PHP_EOL + .'%sclass %s extends %s'.PHP_EOL + .'{' + .'%s'.PHP_EOL + .'%s'.PHP_EOL + .'}'; } /* @@ -334,7 +329,7 @@ public function loadTemplate() */ public function buildTableDefinition(array $definition) { - if (isset($definition['inheritance']['type']) && ($definition['inheritance']['type'] == 'simple' || $definition['inheritance']['type'] == 'column_aggregation')) { + if (isset($definition['inheritance']['type']) && ('simple' == $definition['inheritance']['type'] || 'column_aggregation' == $definition['inheritance']['type'])) { return; } @@ -342,63 +337,60 @@ public function buildTableDefinition(array $definition) $i = 0; - if (isset($definition['inheritance']['type']) && $definition['inheritance']['type'] == 'concrete') { - $ret[$i] = " parent::setTableDefinition();"; - $i++; + if (isset($definition['inheritance']['type']) && 'concrete' == $definition['inheritance']['type']) { + $ret[$i] = ' parent::setTableDefinition();'; + ++$i; } if (isset($definition['tableName']) && !empty($definition['tableName'])) { - $ret[$i] = " ".'$this->setTableName(\''. $definition['tableName'].'\');'; - $i++; + $ret[$i] = ' $this->setTableName(\''.$definition['tableName'].'\');'; + ++$i; } if (isset($definition['columns']) && is_array($definition['columns']) && !empty($definition['columns'])) { $ret[$i] = $this->buildColumns($definition['columns']); - $i++; + ++$i; } if (isset($definition['indexes']) && is_array($definition['indexes']) && !empty($definition['indexes'])) { $ret[$i] = $this->buildIndexes($definition['indexes']); - $i++; + ++$i; } if (isset($definition['attributes']) && is_array($definition['attributes']) && !empty($definition['attributes'])) { $ret[$i] = $this->buildAttributes($definition['attributes']); - $i++; + ++$i; } if (isset($definition['options']) && is_array($definition['options']) && !empty($definition['options'])) { $ret[$i] = $this->buildOptions($definition['options']); - $i++; + ++$i; } if (isset($definition['checks']) && is_array($definition['checks']) && !empty($definition['checks'])) { $ret[$i] = $this->buildChecks($definition['checks']); - $i++; + ++$i; } - if (isset($definition['inheritance']['subclasses']) && ! empty($definition['inheritance']['subclasses'])) { + if (isset($definition['inheritance']['subclasses']) && !empty($definition['inheritance']['subclasses'])) { $subClasses = array(); foreach ($definition['inheritance']['subclasses'] as $className => $def) { - $className = $this->_classPrefix . $className; + $className = $this->_classPrefix.$className; $subClasses[$className] = $def; } - $ret[$i] = " ".'$this->setSubClasses('. $this->varExport($subClasses).');'; - $i++; + $ret[$i] = ' $this->setSubClasses('.$this->varExport($subClasses).');'; + ++$i; } $code = implode(PHP_EOL, $ret); $code = trim($code); - return PHP_EOL . " public function setTableDefinition()" . PHP_EOL . ' {' . PHP_EOL . ' ' . $code . PHP_EOL . ' }'; + return PHP_EOL.' public function setTableDefinition()'.PHP_EOL.' {'.PHP_EOL.' '.$code.PHP_EOL.' }'; } /** - * buildSetUp + * buildSetUp. * - * @param array $options - * @param array $columns - * @param array $relations * @return string */ public function buildSetUp(array $definition) @@ -406,123 +398,122 @@ public function buildSetUp(array $definition) $ret = array(); $i = 0; - if (isset($definition['relations']) && is_array($definition['relations']) && ! empty($definition['relations'])) { + if (isset($definition['relations']) && is_array($definition['relations']) && !empty($definition['relations'])) { foreach ($definition['relations'] as $name => $relation) { - $class = isset($relation['class']) ? $relation['class']:$name; - $alias = (isset($relation['alias']) && $relation['alias'] !== $this->_classPrefix . $relation['class']) ? ' as ' . $relation['alias'] : ''; + $class = isset($relation['class']) ? $relation['class'] : $name; + $alias = (isset($relation['alias']) && $relation['alias'] !== $this->_classPrefix.$relation['class']) ? ' as '.$relation['alias'] : ''; - if ( ! isset($relation['type'])) { + if (!isset($relation['type'])) { $relation['type'] = Doctrine_Relation::ONE; } - if ($relation['type'] === Doctrine_Relation::ONE) { - $ret[$i] = " ".'$this->hasOne(\'' . $class . $alias . '\''; + if (Doctrine_Relation::ONE === $relation['type']) { + $ret[$i] = ' $this->hasOne(\''.$class.$alias.'\''; } else { - $ret[$i] = " ".'$this->hasMany(\'' . $class . $alias . '\''; + $ret[$i] = ' $this->hasMany(\''.$class.$alias.'\''; } $a = array(); if (isset($relation['refClass'])) { - $a[] = '\'refClass\' => ' . $this->varExport($relation['refClass']); + $a[] = '\'refClass\' => '.$this->varExport($relation['refClass']); } if (isset($relation['refClassRelationAlias'])) { - $a[] = '\'refClassRelationAlias\' => ' . $this->varExport($relation['refClassRelationAlias']); + $a[] = '\'refClassRelationAlias\' => '.$this->varExport($relation['refClassRelationAlias']); } if (isset($relation['deferred']) && $relation['deferred']) { - $a[] = '\'default\' => ' . $this->varExport($relation['deferred']); + $a[] = '\'default\' => '.$this->varExport($relation['deferred']); } if (isset($relation['local']) && $relation['local']) { - $a[] = '\'local\' => ' . $this->varExport($relation['local']); + $a[] = '\'local\' => '.$this->varExport($relation['local']); } if (isset($relation['foreign']) && $relation['foreign']) { - $a[] = '\'foreign\' => ' . $this->varExport($relation['foreign']); + $a[] = '\'foreign\' => '.$this->varExport($relation['foreign']); } if (isset($relation['onDelete']) && $relation['onDelete']) { - $a[] = '\'onDelete\' => ' . $this->varExport($relation['onDelete']); + $a[] = '\'onDelete\' => '.$this->varExport($relation['onDelete']); } if (isset($relation['onUpdate']) && $relation['onUpdate']) { - $a[] = '\'onUpdate\' => ' . $this->varExport($relation['onUpdate']); + $a[] = '\'onUpdate\' => '.$this->varExport($relation['onUpdate']); } if (isset($relation['cascade']) && $relation['cascade']) { - $a[] = '\'cascade\' => ' . $this->varExport($relation['cascade']); + $a[] = '\'cascade\' => '.$this->varExport($relation['cascade']); } if (isset($relation['equal']) && $relation['equal']) { - $a[] = '\'equal\' => ' . $this->varExport($relation['equal']); + $a[] = '\'equal\' => '.$this->varExport($relation['equal']); } if (isset($relation['owningSide']) && $relation['owningSide']) { - $a[] = '\'owningSide\' => ' . $this->varExport($relation['owningSide']); + $a[] = '\'owningSide\' => '.$this->varExport($relation['owningSide']); } if (isset($relation['foreignKeyName']) && $relation['foreignKeyName']) { - $a[] = '\'foreignKeyName\' => ' . $this->varExport($relation['foreignKeyName']); + $a[] = '\'foreignKeyName\' => '.$this->varExport($relation['foreignKeyName']); } if (isset($relation['orderBy']) && $relation['orderBy']) { - $a[] = '\'orderBy\' => ' . $this->varExport($relation['orderBy']); + $a[] = '\'orderBy\' => '.$this->varExport($relation['orderBy']); } - if ( ! empty($a)) { - $ret[$i] .= ', ' . 'array(' . PHP_EOL . str_repeat(' ', 13); + if (!empty($a)) { + $ret[$i] .= ', array('.PHP_EOL.str_repeat(' ', 13); $length = strlen($ret[$i]); - $ret[$i] .= implode(',' . PHP_EOL . str_repeat(' ', 13), $a) . ')'; + $ret[$i] .= implode(','.PHP_EOL.str_repeat(' ', 13), $a).')'; } $ret[$i] .= ');'.PHP_EOL; - $i++; + ++$i; } } if (isset($definition['actAs']) && is_array($definition['actAs']) && !empty($definition['actAs'])) { $ret[$i] = $this->buildActAs($definition['actAs']); - $i++; + ++$i; } if (isset($definition['listeners']) && is_array($definition['listeners']) && !empty($definition['listeners'])) { $ret[$i] = $this->buildListeners($definition['listeners']); - $i++; + ++$i; } $code = implode(PHP_EOL, $ret); $code = trim($code); - $code = "parent::setUp();" . PHP_EOL . ' ' . $code; + $code = 'parent::setUp();'.PHP_EOL.' '.$code; // If we have some code for the function then lets define it and return it if ($code) { - return ' public function setUp()' . PHP_EOL . ' {' . PHP_EOL . ' ' . $code . PHP_EOL . ' }'; + return ' public function setUp()'.PHP_EOL.' {'.PHP_EOL.' '.$code.PHP_EOL.' }'; } } /** - * Build php code for record checks + * Build php code for record checks. * * @param array $checks + * * @return string $build */ public function buildChecks($checks) { $build = ''; foreach ($checks as $check) { - $build .= " \$this->check('" . $check . "');" . PHP_EOL; + $build .= " \$this->check('".$check."');".PHP_EOL; } + return $build; } /** - * buildColumns - * - * @param string $array - * @return void + * buildColumns. */ public function buildColumns(array $columns) { @@ -533,34 +524,30 @@ public function buildColumns(array $columns) foreach ($columns as $name => $column) { // An alias cannot passed via column name and column alias definition if (isset($column['name']) && stripos($column['name'], ' as ') && isset($column['alias'])) { - throw new Doctrine_Import_Exception( - sprintf('When using a column alias you cannot pass it via column name and column alias definition (column: %s).', $column['name']) - ); + throw new Doctrine_Import_Exception(sprintf('When using a column alias you cannot pass it via column name and column alias definition (column: %s).', $column['name'])); } // Update column name if an alias is provided if (isset($column['alias']) && !isset($column['name'])) { - $column['name'] = $name . ' as ' . $column['alias']; + $column['name'] = $name.' as '.$column['alias']; } - $columnName = isset($column['name']) ? $column['name']:$name; + $columnName = isset($column['name']) ? $column['name'] : $name; if ($manager->getAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE)) { $e = explode(' as ', $columnName); $fieldName = isset($e[1]) ? $e[1] : $e[0]; $classified = Doctrine_Inflector::classify($fieldName); - $getter = 'get' . $classified; - $setter = 'set' . $classified; + $getter = 'get'.$classified; + $setter = 'set'.$classified; if ($refl->hasMethod($getter) || $refl->hasMethod($setter)) { - throw new Doctrine_Import_Exception( - sprintf('When using the attribute ATTR_AUTO_ACCESSOR_OVERRIDE you cannot use the field name "%s" because it is reserved by Doctrine. You must choose another field name.', $fieldName) - ); + throw new Doctrine_Import_Exception(sprintf('When using the attribute ATTR_AUTO_ACCESSOR_OVERRIDE you cannot use the field name "%s" because it is reserved by Doctrine. You must choose another field name.', $fieldName)); } } - $build .= " ".'$this->hasColumn(\'' . $columnName . '\', \'' . $column['type'] . '\''; + $build .= ' $this->hasColumn(\''.$columnName.'\', \''.$column['type'].'\''; if ($column['length']) { - $build .= ', ' . $column['length']; + $build .= ', '.$column['length']; } else { $build .= ', null'; } @@ -568,19 +555,17 @@ public function buildColumns(array $columns) $options = $column; // Remove name, alltypes, ntype. They are not needed in options array - unset($options['name']); - unset($options['alltypes']); - unset($options['ntype']); + unset($options['name'], $options['alltypes'], $options['ntype']); // Remove notnull => true if the column is primary // Primary columns are implied to be notnull in Doctrine - if (isset($options['primary']) && $options['primary'] == true && (isset($options['notnull']) && $options['notnull'] == true)) { + if (isset($options['primary']) && true == $options['primary'] && (isset($options['notnull']) && true == $options['notnull'])) { unset($options['notnull']); } // Remove default if the value is 0 and the column is a primary key // Doctrine defaults to 0 if it is a primary key - if (isset($options['primary']) && $options['primary'] == true && (isset($options['default']) && $options['default'] == 0)) { + if (isset($options['primary']) && true == $options['primary'] && (isset($options['default']) && 0 == $options['default'])) { unset($options['default']); } @@ -592,10 +577,10 @@ public function buildColumns(array $columns) } if (is_array($options) && !empty($options)) { - $build .= ', ' . $this->varExport($options); + $build .= ', '.$this->varExport($options); } - $build .= ');' . PHP_EOL; + $build .= ');'.PHP_EOL; } return $build; @@ -621,16 +606,16 @@ public function buildAccessors(array $definition) $ret = ''; foreach ($accessors as $name) { // getters - $ret .= PHP_EOL . ' public function get' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . "(\$load = true)" . PHP_EOL; - $ret .= " {" . PHP_EOL; - $ret .= " return \$this->get('{$name}', \$load);" . PHP_EOL; - $ret .= " }" . PHP_EOL; + $ret .= PHP_EOL.' public function get'.Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)).'($load = true)'.PHP_EOL; + $ret .= ' {'.PHP_EOL; + $ret .= " return \$this->get('{$name}', \$load);".PHP_EOL; + $ret .= ' }'.PHP_EOL; // setters - $ret .= PHP_EOL . ' public function set' . Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name)) . "(\${$name}, \$load = true)" . PHP_EOL; - $ret .= " {" . PHP_EOL; - $ret .= " return \$this->set('{$name}', \${$name}, \$load);" . PHP_EOL; - $ret .= " }" . PHP_EOL; + $ret .= PHP_EOL.' public function set'.Doctrine_Inflector::classify(Doctrine_Inflector::tableize($name))."(\${$name}, \$load = true)".PHP_EOL; + $ret .= ' {'.PHP_EOL; + $ret .= " return \$this->set('{$name}', \${$name}, \$load);".PHP_EOL; + $ret .= ' }'.PHP_EOL; } return $ret; @@ -650,127 +635,107 @@ public function buildPhpDocs(array $definition) $ret[] = ''; $properties = array(); - $getters = array(); - $setters = array(); + $getters = array(); + $setters = array(); - if ((isset($definition['is_base_class']) && $definition['is_base_class']) || ! $this->generateBaseClasses()) { + if ((isset($definition['is_base_class']) && $definition['is_base_class']) || !$this->generateBaseClasses()) { foreach ($definition['columns'] as $name => $column) { - $name = isset($column['name']) ? $column['name']:$name; + $name = isset($column['name']) ? $column['name'] : $name; // extract column name & field name - if (stripos($name, ' as ')) - { + if (stripos($name, ' as ')) { if (strpos($name, ' as')) { $parts = explode(' as ', $name); - } - else - { + } else { $parts = explode(' AS ', $name); } if (count($parts) > 1) { $fieldName = $parts[1]; - } - else - { + } else { $fieldName = $parts[0]; } $name = $parts[0]; - } - else - { + } else { $fieldName = $name; $name = $name; } $phpTypeMap = array( - "enum" => "string", - "datetime" => "string", - "timestamp" => "string", - "clob" => "string", - "date" => "string", - "time" => "string", - "varchar" => "string", - "char" => "string", - "decimal" => "float", - "blob" => "object", - "gzip" => "object", - "bit" => "binary", - "varbit" => "binary", - "inet" => "string", - "boolean" => "bool", - "integer" => "int", - "string" => "string" + 'enum' => 'string', + 'datetime' => 'string', + 'timestamp' => 'string', + 'clob' => 'string', + 'date' => 'string', + 'time' => 'string', + 'varchar' => 'string', + 'char' => 'string', + 'decimal' => 'float', + 'blob' => 'object', + 'gzip' => 'object', + 'bit' => 'binary', + 'varbit' => 'binary', + 'inet' => 'string', + 'boolean' => 'bool', + 'integer' => 'int', + 'string' => 'string', ); /** - * @var double $phpCommentMap; + * @var float $phpCommentMap; */ $phpCommentMap = array( - "time" => "Time in ISO-8601 format (HH:MI:SS)", - "date" => "Date in ISO-8601 format (YYYY-MM-DD)", - "datetime" => "Date and time in ISO-8601 format (YYYY-MM-DD HH:MI)", - "timestamp" => "Timestamp in ISO-8601 format (YYYY-MM-DD HH:MI:SS)", - "gzip" => "A gzipped object", - "object" => "A doctrine serialized object", - "enum" => "Possible values (%s)" + 'time' => 'Time in ISO-8601 format (HH:MI:SS)', + 'date' => 'Date in ISO-8601 format (YYYY-MM-DD)', + 'datetime' => 'Date and time in ISO-8601 format (YYYY-MM-DD HH:MI)', + 'timestamp' => 'Timestamp in ISO-8601 format (YYYY-MM-DD HH:MI:SS)', + 'gzip' => 'A gzipped object', + 'object' => 'A doctrine serialized object', + 'enum' => 'Possible values (%s)', ); - $phpType = $column["type"]; - if (isset($phpTypeMap[$column["type"]])) - { - $phpType = $phpTypeMap[$column["type"]]; + $phpType = $column['type']; + if (isset($phpTypeMap[$column['type']])) { + $phpType = $phpTypeMap[$column['type']]; } $commentOptions = array(); - if (isset($column["length"]) && $column["length"] != null) - { - if (isset($column["fixed"]) && $column["fixed"] == true) - { - $commentOptions[] = sprintf("Type: %s(%s) fixed-size", $column["type"], $column["length"]); - } - else - { - $commentOptions[] = sprintf("Type: %s(%s)", $column["type"], $column["length"]); + if (isset($column['length']) && null != $column['length']) { + if (isset($column['fixed']) && true == $column['fixed']) { + $commentOptions[] = sprintf('Type: %s(%s) fixed-size', $column['type'], $column['length']); + } else { + $commentOptions[] = sprintf('Type: %s(%s)', $column['type'], $column['length']); } - } - else - { - $commentOptions[] = sprintf("Type: %s", $column["type"]); + } else { + $commentOptions[] = sprintf('Type: %s', $column['type']); } - if (isset($column["unique"]) && $column["unique"] == true) - { - $commentOptions[] = sprintf("unique"); + if (isset($column['unique']) && true == $column['unique']) { + $commentOptions[] = sprintf('unique'); } - if (isset($column["primary"]) && $column["primary"] == true) - { - $commentOptions[] = sprintf("primary key"); + if (isset($column['primary']) && true == $column['primary']) { + $commentOptions[] = sprintf('primary key'); } - if (isset($column["notblank"]) && $column["notblank"] == true) - { - $commentOptions[] = "required"; + if (isset($column['notblank']) && true == $column['notblank']) { + $commentOptions[] = 'required'; } - if (isset($column["default"]) && $column["default"] != null) - { - $commentOptions[] = sprintf('default "%s"', $column["default"]); + if (isset($column['default']) && null != $column['default']) { + $commentOptions[] = sprintf('default "%s"', $column['default']); } - if (isset($phpCommentMap[$column["type"]])) { - $comment = $phpCommentMap[$column["type"]]; - if ($column['type'] == "enum") - { - $comment = sprintf($comment, strtoupper(join(", ",$column["values"]))); + if (isset($phpCommentMap[$column['type']])) { + $comment = $phpCommentMap[$column['type']]; + if ('enum' == $column['type']) { + $comment = sprintf($comment, strtoupper(join(', ', $column['values']))); } $commentOptions[] = $comment; } - - $comment = join(", ",$commentOptions); + $comment = join(', ', $commentOptions); $fieldName = trim($fieldName); @@ -779,149 +744,142 @@ public function buildPhpDocs(array $definition) $setters[] = array($definition['topLevelClassName'], Doctrine_Inflector::classify($fieldName), $phpType, $comment); } - - if (isset($definition['relations']) && ! empty($definition['relations'])) { + if (isset($definition['relations']) && !empty($definition['relations'])) { foreach ($definition['relations'] as $relation) { - $type = (isset($relation['type']) && $relation['type'] == Doctrine_Relation::MANY) ? 'Doctrine_Collection' : $this->_classPrefix . $relation['class']; + $type = (isset($relation['type']) && Doctrine_Relation::MANY == $relation['type']) ? 'Doctrine_Collection' : $this->_classPrefix.$relation['class']; if ((isset($relation['type']) ? $relation['type'] : null) == Doctrine_Relation::ONE) { - $properties[] = array($relation['class'], $relation['alias'], ""); - $getters[] = array($relation['class'], $relation['alias'], ""); - $setters[] = array($definition['topLevelClassName'], $relation['alias'], $relation['class'], ""); - } - else - { + $properties[] = array($relation['class'], $relation['alias'], ''); + $getters[] = array($relation['class'], $relation['alias'], ''); + $setters[] = array($definition['topLevelClassName'], $relation['alias'], $relation['class'], ''); + } else { // MANY - $properties[] = array($type . "|". $relation['class'] . "[]", $relation['alias'] , ""); - $getters[] = array($type . "|". $relation['class'] . "[]", $relation['alias'], ""); - $setters[] = array($definition['topLevelClassName'], $relation["alias"], $type, ""); + $properties[] = array($type.'|'.$relation['class'].'[]', $relation['alias'], ''); + $getters[] = array($type.'|'.$relation['class'].'[]', $relation['alias'], ''); + $setters[] = array($definition['topLevelClassName'], $relation['alias'], $type, ''); } } } - $maxTypeSize = 0; $maxNameSize = 0; - foreach ($properties as $propItem) - { + foreach ($properties as $propItem) { $maxTypeSize = max($maxTypeSize, strlen($propItem[0])); - $maxNameSize = max($maxNameSize, strlen($propItem[1])+1); + $maxNameSize = max($maxNameSize, strlen($propItem[1]) + 1); } - foreach ($getters as $getterItem) - { + foreach ($getters as $getterItem) { $maxTypeSize = max($maxTypeSize, strlen($getterItem[0])); - $maxNameSize = max($maxNameSize, strlen($getterItem[1])+5); + $maxNameSize = max($maxNameSize, strlen($getterItem[1]) + 5); } - foreach ($setters as $setterItem) - { + foreach ($setters as $setterItem) { $maxTypeSize = max($maxTypeSize, strlen($setterItem[0])); - $maxNameSize = max($maxNameSize, strlen($setterItem[1])+strlen($setterItem[2])+9); + $maxNameSize = max($maxNameSize, strlen($setterItem[1]) + strlen($setterItem[2]) + 9); } - $maxNameSize+=1; - $maxTypeSize+=1; + ++$maxNameSize; + ++$maxTypeSize; - - foreach ($properties as $propItem) - { - $ret[] = sprintf("@property %s $%s %s", str_pad($propItem[0], $maxTypeSize, " "), str_pad($propItem[1], $maxNameSize-1, " "), $propItem[2]); + foreach ($properties as $propItem) { + $ret[] = sprintf('@property %s $%s %s', str_pad($propItem[0], $maxTypeSize, ' '), str_pad($propItem[1], $maxNameSize - 1, ' '), $propItem[2]); } - $ret[] = " "; + $ret[] = ' '; - foreach ($getters as $getterItem) - { - $methodName = sprintf("get%s()",ucfirst($getterItem[1])); - $ret[] = sprintf("@method %s %s %s", str_pad($getterItem[0], $maxTypeSize+2, " "), str_pad(($methodName), $maxNameSize, " "), $getterItem[2]); + foreach ($getters as $getterItem) { + $methodName = sprintf('get%s()', ucfirst($getterItem[1])); + $ret[] = sprintf('@method %s %s %s', str_pad($getterItem[0], $maxTypeSize + 2, ' '), str_pad($methodName, $maxNameSize, ' '), $getterItem[2]); } - $ret[] = " "; + $ret[] = ' '; - foreach ($setters as $setterItem) - { - $methodName = sprintf('set%s(%s $val)',ucfirst($setterItem[1]), $setterItem[2]); - $ret[] = sprintf("@method %s %s %s", str_pad($setterItem[0], $maxTypeSize+2, " "), str_pad(($methodName), $maxNameSize, " "), $setterItem[3]); + foreach ($setters as $setterItem) { + $methodName = sprintf('set%s(%s $val)', ucfirst($setterItem[1]), $setterItem[2]); + $ret[] = sprintf('@method %s %s %s', str_pad($setterItem[0], $maxTypeSize + 2, ' '), str_pad($methodName, $maxNameSize, ' '), $setterItem[3]); } - //$ret = array_merge($ret, $getter, $setter); + // $ret = array_merge($ret, $getter, $setter); } - $ret[] = " "; + $ret[] = ' '; - $ret[] = '@package ' . $this->_phpDocPackage; - $ret[] = '@subpackage ' . $this->_phpDocSubpackage; - $ret[] = '@author ' . $this->_phpDocName . ' <' . $this->_phpDocEmail . '>'; + $ret[] = '@package '.$this->_phpDocPackage; + $ret[] = '@subpackage '.$this->_phpDocSubpackage; + $ret[] = '@author '.$this->_phpDocName.' <'.$this->_phpDocEmail.'>'; $ret[] = '@version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $'; - $ret = ' * ' . implode(PHP_EOL . ' * ', $ret); - $ret = ' ' . trim($ret); + $ret = ' * '.implode(PHP_EOL.' * ', $ret); - return $ret; + return ' '.trim($ret); } /** - * emit a behavior assign + * emit a behavior assign. * - * @param int $level + * @param int $level * @param string $name * @param string $option + * * @return string assignation code */ private function emitAssign($level, $name, $option) { // find class matching $name $classname = $name; - if (class_exists("Doctrine_Template_$name", true)) { - $classname = "Doctrine_Template_$name"; + if (class_exists("Doctrine_Template_{$name}", true)) { + $classname = "Doctrine_Template_{$name}"; } - return " \$" . strtolower($name) . "$level = new $classname($option);". PHP_EOL; + + return ' $'.strtolower($name)."{$level} = new {$classname}({$option});".PHP_EOL; } /** - * emit an addChild + * emit an addChild. * - * @param int $level + * @param int $level * @param string $name - * @param string $option + * * @return string addChild code */ private function emitAddChild($level, $parent, $name) { - return " \$" . strtolower($parent) . ($level - 1) . "->addChild(\$" . strtolower($name) . "$level);" . PHP_EOL; + return ' $'.strtolower($parent).($level - 1).'->addChild($'.strtolower($name)."{$level});".PHP_EOL; } /** - * emit an indented actAs + * emit an indented actAs. * - * @param int $level + * @param int $level * @param string $name - * @param string $option + * * @return string actAs code */ private function emitActAs($level, $name) { - return " \$this->actAs(\$" . strtolower($name) . "$level);" . PHP_EOL; + return ' $this->actAs($'.strtolower($name)."{$level});".PHP_EOL; } /** - * buildActAs: builds a complete actAs code. It supports hierarchy of plugins + * buildActAs: builds a complete actAs code. It supports hierarchy of plugins. + * * @param array $actAs array of plugin definitions and options */ public function buildActAs($actAs) { $emittedActAs = array(); $build = $this->innerBuildActAs($actAs, 0, null, $emittedActAs); - foreach($emittedActAs as $str) { + foreach ($emittedActAs as $str) { $build .= $str; } + return $build; } /** - * innerBuildActAs: build a complete actAs code that handles hierarchy of plugins + * innerBuildActAs: build a complete actAs code that handles hierarchy of plugins. * - * @param array $actAs array of plugin definitions and options - * @param int $level current indentation level - * @param string $parent name of the parent template/plugin + * @param array $actAs array of plugin definitions and options + * @param int $level current indentation level + * @param string $parent name of the parent template/plugin * @param array $emittedActAs contains on output an array of actAs command to be appended to output + * * @return string actAs full definition */ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emittedActAs = array()) @@ -931,7 +889,7 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi $tmp = array(); foreach ($actAs as $key => $value) { if (is_numeric($key)) { - $tmp[(string)$value] = null; + $tmp[(string) $value] = null; } else { $tmp[$key] = $value; } @@ -942,16 +900,16 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi $build = ''; $currentParent = $parent; if (is_array($actAs)) { - foreach($actAs as $template => $options) { - if ($template == 'actAs') { + foreach ($actAs as $template => $options) { + if ('actAs' == $template) { // found another actAs $build .= $this->innerBuildActAs($options, $level + 1, $parent, $emittedActAs); - } else if (is_array($options)) { + } elseif (is_array($options)) { // remove actAs from options $realOptions = array(); $leftActAs = array(); - foreach($options as $name => $value) { - if ($name != 'actAs') { + foreach ($options as $name => $value) { + if ('actAs' != $name) { $realOptions[$name] = $options[$name]; } else { $leftActAs[$name] = $options[$name]; @@ -960,7 +918,7 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi $optionPHP = $this->varExport($realOptions); $build .= $this->emitAssign($level, $template, $optionPHP); - if ($level == 0) { + if (0 == $level) { $emittedActAs[] = $this->emitActAs($level, $template); } else { $build .= $this->emitAddChild($level, $currentParent, $template); @@ -970,7 +928,7 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi $build .= $this->innerBuildActAs($leftActAs, $level, $template, $emittedActAs); } else { $build .= $this->emitAssign($level, $template, null); - if ($level == 0) { + if (0 == $level) { $emittedActAs[] = $this->emitActAs($level, $template); } else { $build .= $this->emitAddChild($level, $currentParent, $template); @@ -980,7 +938,7 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi } } else { $build .= $this->emitAssign($level, $actAs, null); - if ($level == 0) { + if (0 == $level) { $emittedActAs[] = $this->emitActAs($level, $actAs); } else { $build .= $this->emitAddChild($level, $currentParent, $actAs); @@ -991,97 +949,87 @@ private function innerBuildActAs($actAs, $level = 0, $parent = null, array &$emi } /** - * Build php code for adding record listeners + * Build php code for adding record listeners. * * @param string $listeners + * * @return string $build */ public function buildListeners($listeners) { $build = ''; - foreach($listeners as $name => $options) { - if ( ! is_array($options) && $options !== null) { + foreach ($listeners as $name => $options) { + if (!is_array($options) && null !== $options) { $name = $options; $options = null; } - $useOptions = ( ! empty($options) && isset($options['useOptions']) && $options['useOptions'] == true) + $useOptions = (!empty($options) && isset($options['useOptions']) && true == $options['useOptions']) ? '$this->getTable()->getOptions()' : 'array()'; - $class = ( ! empty($options) && isset($options['class'])) ? $options['class'] : $name; + $class = (!empty($options) && isset($options['class'])) ? $options['class'] : $name; - $build .= " \$this->addListener(new " . $class . "(" . $useOptions . "), '" . $name . "');" . PHP_EOL; + $build .= ' $this->addListener(new '.$class.'('.$useOptions."), '".$name."');".PHP_EOL; } return $build; } /** - * buildAttributes - * - * @param string $array - * @return void + * buildAttributes. */ public function buildAttributes(array $attributes) { $build = PHP_EOL; foreach ($attributes as $key => $value) { - $values = array(); - if (is_bool($value)) - { - $values[] = $value ? 'true':'false'; + if (is_bool($value)) { + $values[] = $value ? 'true' : 'false'; } else { - if ( ! is_array($value)) { + if (!is_array($value)) { $value = array($value); } foreach ($value as $attr) { - $const = "Doctrine_Core::" . strtoupper($key) . "_" . strtoupper($attr); + $const = 'Doctrine_Core::'.strtoupper($key).'_'.strtoupper($attr); if (defined($const)) { $values[] = $const; } else { - $values[] = "'" . $attr . "'"; + $values[] = "'".$attr."'"; } } } $string = implode(' ^ ', $values); - $build .= " \$this->setAttribute(Doctrine_Core::ATTR_" . strtoupper($key) . ", " . $string . ");" . PHP_EOL; + $build .= ' $this->setAttribute(Doctrine_Core::ATTR_'.strtoupper($key).', '.$string.');'.PHP_EOL; } return $build; } /** - * buildTableOptions - * - * @param string $array - * @return void + * buildTableOptions. */ public function buildOptions(array $options) { $build = ''; foreach ($options as $name => $value) { - $build .= " \$this->option('$name', " . $this->varExport($value) . ");" . PHP_EOL; + $build .= " \$this->option('{$name}', ".$this->varExport($value).');'.PHP_EOL; } return $build; } /** - * buildIndexes - * - * @param string $array - * @return void + * buildIndexes. */ public function buildIndexes(array $indexes) { $build = ''; foreach ($indexes as $indexName => $definitions) { - $build .= PHP_EOL . " \$this->index('" . $indexName . "'"; - $build .= ', ' . $this->varExport($definitions); + $build .= PHP_EOL." \$this->index('".$indexName."'"; + $build .= ', '.$this->varExport($definitions); $build .= ');'; } @@ -1089,40 +1037,39 @@ public function buildIndexes(array $indexes) } /** - * buildToString + * buildToString. * - * @param array $definition * @return string */ public function buildToString(array $definition) { - if ( empty($definition['toString'])) { + if (empty($definition['toString'])) { return ''; } - $ret = PHP_EOL . PHP_EOL . ' public function __toString()' . PHP_EOL; - $ret .= " {" . PHP_EOL; - $ret .= " return (string) \$this->".$definition['toString'].";" . PHP_EOL; - $ret .= " }"; + $ret = PHP_EOL.PHP_EOL.' public function __toString()'.PHP_EOL; + $ret .= ' {'.PHP_EOL; + $ret .= ' return (string) $this->'.$definition['toString'].';'.PHP_EOL; + $ret .= ' }'; + return $ret; } /** - * buildDefinition + * buildDefinition. * - * @param array $definition * @return string */ public function buildDefinition(array $definition) { - if ( ! isset($definition['className'])) { + if (!isset($definition['className'])) { throw new Doctrine_Import_Builder_Exception('Missing class name.'); } - $abstract = isset($definition['abstract']) && $definition['abstract'] === true ? 'abstract ':null; + $abstract = isset($definition['abstract']) && true === $definition['abstract'] ? 'abstract ' : null; $className = $definition['className']; - $extends = isset($definition['inheritance']['extends']) ? $definition['inheritance']['extends']:$this->_baseClassName; + $extends = isset($definition['inheritance']['extends']) ? $definition['inheritance']['extends'] : $this->_baseClassName; - if ( ! (isset($definition['no_definition']) && $definition['no_definition'] === true)) { + if (!(isset($definition['no_definition']) && true === $definition['no_definition'])) { $tableDefinitionCode = $this->buildTableDefinition($definition); $setUpCode = $this->buildSetUp($definition); } else { @@ -1131,50 +1078,41 @@ public function buildDefinition(array $definition) } if ($tableDefinitionCode && $setUpCode) { - $setUpCode = PHP_EOL . $setUpCode; + $setUpCode = PHP_EOL.$setUpCode; } - $setUpCode.= $this->buildToString($definition); + $setUpCode .= $this->buildToString($definition); - $docs = PHP_EOL . $this->buildPhpDocs($definition); + $docs = PHP_EOL.$this->buildPhpDocs($definition); - $content = sprintf(self::$_tpl, $docs, $abstract, + return sprintf(self::$_tpl, $docs, $abstract, $className, $extends, $tableDefinitionCode, $setUpCode); - - return $content; } /** - * buildRecord + * buildRecord. * - * @param array $options - * @param array $columns - * @param array $relations - * @param array $indexes - * @param array $attributes - * @param array $templates - * @param array $actAs * @return void= */ public function buildRecord(array $definition) { - if ( ! isset($definition['className'])) { + if (!isset($definition['className'])) { throw new Doctrine_Import_Builder_Exception('Missing class name.'); } $definition['topLevelClassName'] = $definition['className']; if ($this->generateBaseClasses()) { - $definition['is_package'] = (isset($definition['package']) && $definition['package']) ? true:false; + $definition['is_package'] = (isset($definition['package']) && $definition['package']) ? true : false; if ($definition['is_package']) { $e = explode('.', trim($definition['package'])); $definition['package_name'] = $e[0]; - $definition['package_path'] = ! empty($e) ? implode(DIRECTORY_SEPARATOR, $e):$definition['package_name']; + $definition['package_path'] = !empty($e) ? implode(DIRECTORY_SEPARATOR, $e) : $definition['package_name']; } // Top level definition that extends from all the others $topLevel = $definition; @@ -1182,7 +1120,7 @@ public function buildRecord(array $definition) // If we have a package then we need to make this extend the package definition and not the base definition // The package definition will then extends the base definition - $topLevel['inheritance']['extends'] = (isset($topLevel['package']) && $topLevel['package']) ? $this->_packagesPrefix . $topLevel['className']:$this->_baseClassPrefix . $topLevel['className']; + $topLevel['inheritance']['extends'] = (isset($topLevel['package']) && $topLevel['package']) ? $this->_packagesPrefix.$topLevel['className'] : $this->_baseClassPrefix.$topLevel['className']; $topLevel['no_definition'] = true; $topLevel['generate_once'] = true; $topLevel['is_main_class'] = true; @@ -1190,10 +1128,9 @@ public function buildRecord(array $definition) // Package level definition that extends from the base definition if (isset($definition['package'])) { - $packageLevel = $definition; $packageLevel['className'] = $topLevel['inheritance']['extends']; - $packageLevel['inheritance']['extends'] = $this->_baseClassPrefix . $topLevel['className']; + $packageLevel['inheritance']['extends'] = $this->_baseClassPrefix.$topLevel['className']; $packageLevel['no_definition'] = true; $packageLevel['abstract'] = true; $packageLevel['override_parent'] = true; @@ -1202,13 +1139,13 @@ public function buildRecord(array $definition) unset($packageLevel['connection']); $packageLevel['tableClassName'] = sprintf($this->_tableClassFormat, $packageLevel['className']); - $packageLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? sprintf($this->_tableClassFormat, $definition['inheritance']['extends']):$this->_baseTableClassName; + $packageLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? sprintf($this->_tableClassFormat, $definition['inheritance']['extends']) : $this->_baseTableClassName; $topLevel['tableClassName'] = sprintf($this->_tableClassFormat, $topLevel['topLevelClassName']); $topLevel['inheritance']['tableExtends'] = sprintf($this->_tableClassFormat, $packageLevel['className']); } else { $topLevel['tableClassName'] = sprintf($this->_tableClassFormat, $topLevel['className']); - $topLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? sprintf($this->_tableClassFormat, $definition['inheritance']['extends']):$this->_baseTableClassName; + $topLevel['inheritance']['tableExtends'] = isset($definition['inheritance']['extends']) ? sprintf($this->_tableClassFormat, $definition['inheritance']['extends']) : $this->_baseTableClassName; } $baseClass = $definition; @@ -1219,7 +1156,7 @@ public function buildRecord(array $definition) $this->writeDefinition($baseClass); - if ( ! empty($packageLevel)) { + if (!empty($packageLevel)) { $this->writeDefinition($packageLevel); } @@ -1231,14 +1168,14 @@ public function buildRecord(array $definition) protected function _getBaseClassName($className) { - return $this->_baseClassPrefix . $className; + return $this->_baseClassPrefix.$className; } public function buildTableClassDefinition($className, $definition, $options = array()) { - $extends = isset($options['extends']) ? $options['extends']:$this->_baseTableClassName; + $extends = isset($options['extends']) ? $options['extends'] : $this->_baseTableClassName; if ($extends !== $this->_baseTableClassName) { - $extends = $this->_classPrefix . $extends; + $extends = $this->_classPrefix.$extends; } $code = sprintf(" /** @@ -1255,9 +1192,9 @@ public static function getInstance() $docBlock[] = $className; $docBlock[] = ''; $docBlock[] = 'This class has been auto-generated by the Doctrine ORM Framework'; - $docBlock = PHP_EOL.' * ' . implode(PHP_EOL . ' * ', $docBlock); + $docBlock = PHP_EOL.' * '.implode(PHP_EOL.' * ', $docBlock); - $content = '_classPrefix) { - $className = $prefix . $definition['tableClassName']; + $className = $prefix.$definition['tableClassName']; if ($this->_classPrefixFiles) { - $fileName = $className . $this->_suffix; + $fileName = $className.$this->_suffix; } else { - $fileName = $definition['tableClassName'] . $this->_suffix; + $fileName = $definition['tableClassName'].$this->_suffix; } - $writePath = $path . DIRECTORY_SEPARATOR . $fileName; + $writePath = $path.DIRECTORY_SEPARATOR.$fileName; } else { $className = $definition['tableClassName']; - $fileName = $className . $this->_suffix; + $fileName = $className.$this->_suffix; } if ($this->_pearStyle) { - $writePath = $path . DIRECTORY_SEPARATOR . str_replace('_', '/', $fileName); + $writePath = $path.DIRECTORY_SEPARATOR.str_replace('_', '/', $fileName); } else { - $writePath = $path . DIRECTORY_SEPARATOR . $fileName; + $writePath = $path.DIRECTORY_SEPARATOR.$fileName; } $content = $this->buildTableClassDefinition($className, $definition, $options); @@ -1307,7 +1242,7 @@ public function writeTableClassDefinition(array $definition, $path, $options = a Doctrine_Core::loadModel($className, $writePath); - if ( ! file_exists($writePath)) { + if (!file_exists($writePath)) { file_put_contents($writePath, $content); } } @@ -1316,15 +1251,16 @@ public function writeTableClassDefinition(array $definition, $path, $options = a * Return the file name of the class to be generated. * * @param string $originalClassName - * @param array $definition + * @param array $definition + * * @return string */ protected function _getFileName($originalClassName, $definition) { if ($this->_classPrefixFiles) { - $fileName = $definition['className'] . $this->_suffix; + $fileName = $definition['className'].$this->_suffix; } else { - $fileName = $originalClassName . $this->_suffix; + $fileName = $originalClassName.$this->_suffix; } if ($this->_pearStyle) { @@ -1335,49 +1271,40 @@ protected function _getFileName($originalClassName, $definition) } /** - * writeDefinition - * - * @param array $options - * @param array $columns - * @param array $relations - * @param array $indexes - * @param array $attributes - * @param array $templates - * @param array $actAs - * @return void + * writeDefinition. */ public function writeDefinition(array $definition) { $originalClassName = $definition['className']; if ($prefix = $this->_classPrefix) { - $definition['className'] = $prefix . $definition['className']; + $definition['className'] = $prefix.$definition['className']; if (isset($definition['connectionClassName'])) { - $definition['connectionClassName'] = $prefix . $definition['connectionClassName']; + $definition['connectionClassName'] = $prefix.$definition['connectionClassName']; } - $definition['topLevelClassName'] = $prefix . $definition['topLevelClassName']; + $definition['topLevelClassName'] = $prefix.$definition['topLevelClassName']; if (isset($definition['inheritance']['extends'])) { - $definition['inheritance']['extends'] = $prefix . $definition['inheritance']['extends']; + $definition['inheritance']['extends'] = $prefix.$definition['inheritance']['extends']; } } $definitionCode = $this->buildDefinition($definition); if ($prefix) { - $definitionCode = str_replace("this->hasOne('", "this->hasOne('$prefix", $definitionCode); - $definitionCode = str_replace("this->hasMany('", "this->hasMany('$prefix", $definitionCode); - $definitionCode = str_replace("'refClass' => '", "'refClass' => '$prefix", $definitionCode); + $definitionCode = str_replace("this->hasOne('", "this->hasOne('{$prefix}", $definitionCode); + $definitionCode = str_replace("this->hasMany('", "this->hasMany('{$prefix}", $definitionCode); + $definitionCode = str_replace("'refClass' => '", "'refClass' => '{$prefix}", $definitionCode); } $fileName = $this->_getFileName($originalClassName, $definition); - $packagesPath = $this->_packagesPath ? $this->_packagesPath:$this->_path; + $packagesPath = $this->_packagesPath ? $this->_packagesPath : $this->_path; // If this is a main class that either extends from Base or Package class if (isset($definition['is_main_class']) && $definition['is_main_class']) { // If is package then we need to put it in a package subfolder if (isset($definition['is_package']) && $definition['is_package']) { - $writePath = $this->_path . DIRECTORY_SEPARATOR . $definition['package_name']; - // Otherwise lets just put it in the root of the path + $writePath = $this->_path.DIRECTORY_SEPARATOR.$definition['package_name']; + // Otherwise lets just put it in the root of the path } else { $writePath = $this->_path; } @@ -1387,11 +1314,11 @@ public function writeDefinition(array $definition) } } // If is the package class then we need to make the path to the complete package - else if (isset($definition['is_package_class']) && $definition['is_package_class']) { + elseif (isset($definition['is_package_class']) && $definition['is_package_class']) { if (isset($definition['package_custom_path'])) { $writePath = $definition['package_custom_path']; } else { - $writePath = $packagesPath . DIRECTORY_SEPARATOR . $definition['package_path']; + $writePath = $packagesPath.DIRECTORY_SEPARATOR.$definition['package_path']; } if ($this->generateTableClasses()) { @@ -1399,14 +1326,14 @@ public function writeDefinition(array $definition) } } // If it is the base class of the doctrine record definition - else if (isset($definition['is_base_class']) && $definition['is_base_class']) { + elseif (isset($definition['is_base_class']) && $definition['is_base_class']) { // If it is a part of a package then we need to put it in a package subfolder if (isset($definition['is_package']) && $definition['is_package']) { - $basePath = $this->_path . DIRECTORY_SEPARATOR . $definition['package_name']; - $writePath = $basePath . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory; - // Otherwise lets just put it in the root generated folder + $basePath = $this->_path.DIRECTORY_SEPARATOR.$definition['package_name']; + $writePath = $basePath.DIRECTORY_SEPARATOR.$this->_baseClassesDirectory; + // Otherwise lets just put it in the root generated folder } else { - $writePath = $this->_path . DIRECTORY_SEPARATOR . $this->_baseClassesDirectory; + $writePath = $this->_path.DIRECTORY_SEPARATOR.$this->_baseClassesDirectory; } } @@ -1414,22 +1341,22 @@ public function writeDefinition(array $definition) if (isset($writePath)) { Doctrine_Lib::makeDirectories($writePath); - $writePath .= DIRECTORY_SEPARATOR . $fileName; - // Otherwise none of the conditions were met and we aren't generating base classes + $writePath .= DIRECTORY_SEPARATOR.$fileName; + // Otherwise none of the conditions were met and we aren't generating base classes } else { Doctrine_Lib::makeDirectories($this->_path); - $writePath = $this->_path . DIRECTORY_SEPARATOR . $fileName; + $writePath = $this->_path.DIRECTORY_SEPARATOR.$fileName; } - $code = "bindComponent('" . $definition['connectionClassName'] . "', '" . $definition['connection'] . "');" . PHP_EOL; + $code .= '// Connection Component Binding'.PHP_EOL; + $code .= "Doctrine_Manager::getInstance()->bindComponent('".$definition['connectionClassName']."', '".$definition['connection']."');".PHP_EOL; } - $code .= PHP_EOL . $definitionCode; + $code .= PHP_EOL.$definitionCode; if ($this->_eolStyle) { $code = str_replace(PHP_EOL, $this->_eolStyle, $code); @@ -1437,16 +1364,16 @@ public function writeDefinition(array $definition) Doctrine_Lib::makeDirectories(dirname($writePath)); - if (isset($definition['generate_once']) && $definition['generate_once'] === true) { - if ( ! file_exists($writePath)) { + if (isset($definition['generate_once']) && true === $definition['generate_once']) { + if (!file_exists($writePath)) { $bytes = file_put_contents($writePath, $code); } } else { $bytes = file_put_contents($writePath, $code); } - if (isset($bytes) && $bytes === false) { - throw new Doctrine_Import_Builder_Exception("Couldn't write file " . $writePath); + if (isset($bytes) && false === $bytes) { + throw new Doctrine_Import_Builder_Exception("Couldn't write file ".$writePath); } Doctrine_Core::loadModel($definition['className'], $writePath); diff --git a/lib/Doctrine/Import/Builder/Exception.php b/lib/Doctrine/Import/Builder/Exception.php index b754732e4..23bffc5ae 100644 --- a/lib/Doctrine/Import/Builder/Exception.php +++ b/lib/Doctrine/Import/Builder/Exception.php @@ -20,15 +20,18 @@ */ /** - * Doctrine_Import_Builder_Exception + * Doctrine_Import_Builder_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Import_Builder_Exception extends Doctrine_Import_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Import/Exception.php b/lib/Doctrine/Import/Exception.php index 92640bbc2..13f697844 100644 --- a/lib/Doctrine/Import/Exception.php +++ b/lib/Doctrine/Import/Exception.php @@ -20,15 +20,18 @@ */ /** - * class Doctrine_Import_Exception + * class Doctrine_Import_Exception. + * + * @see www.doctrine-project.org * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Import_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Import/Mssql.php b/lib/Doctrine/Import/Mssql.php index 2e1c63de0..2b0776aa4 100644 --- a/lib/Doctrine/Import/Mssql.php +++ b/lib/Doctrine/Import/Mssql.php @@ -20,23 +20,24 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @author Frank M. Kromann (PEAR MDB2 Mssql driver) * @author David Coallier (PEAR MDB2 Mssql driver) + * * @version $Revision: 7675 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Mssql extends Doctrine_Import { /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) @@ -48,9 +49,9 @@ public function listSequences($database = null) } /** - * lists table relations + * lists table relations. * - * Expects an array of this format to be returned with all the relationships in it where the key is + * Expects an array of this format to be returned with all the relationships in it where the key is * the name of the foreign table, and the value is an array containing the local and foreign column * name * @@ -63,41 +64,41 @@ public function listSequences($database = null) * ) * ) * - * @param string $table database table name * @return array */ public function listTableRelations($tableName) { $relations = array(); - $sql = 'SELECT o1.name as table_name, c1.name as column_name, o2.name as referenced_table_name, c2.name as referenced_column_name, s.name as constraint_name FROM sysforeignkeys fk inner join sysobjects o1 on fk.fkeyid = o1.id inner join sysobjects o2 on fk.rkeyid = o2.id inner join syscolumns c1 on c1.id = o1.id and c1.colid = fk.fkey inner join syscolumns c2 on c2.id = o2.id and c2.colid = fk.rkey inner join sysobjects s on fk.constid = s.id AND o1.name = \'' . $tableName . '\''; + $sql = 'SELECT o1.name as table_name, c1.name as column_name, o2.name as referenced_table_name, c2.name as referenced_column_name, s.name as constraint_name FROM sysforeignkeys fk inner join sysobjects o1 on fk.fkeyid = o1.id inner join sysobjects o2 on fk.rkeyid = o2.id inner join syscolumns c1 on c1.id = o1.id and c1.colid = fk.fkey inner join syscolumns c2 on c2.id = o2.id and c2.colid = fk.rkey inner join sysobjects s on fk.constid = s.id AND o1.name = \''.$tableName.'\''; $results = $this->conn->fetchAssoc($sql); - foreach ($results as $result) - { + foreach ($results as $result) { $result = array_change_key_case($result, CASE_LOWER); - $relations[] = array('table' => $result['referenced_table_name'], - 'local' => $result['column_name'], - 'foreign' => $result['referenced_column_name']); + $relations[] = array('table' => $result['referenced_table_name'], + 'local' => $result['column_name'], + 'foreign' => $result['referenced_column_name']); } + return $relations; } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - $sql = 'EXEC sp_primary_keys_rowset @table_name = ' . $this->conn->quoteIdentifier($table, true); + $sql = 'EXEC sp_primary_keys_rowset @table_name = '.$this->conn->quoteIdentifier($table, true); $result = $this->conn->fetchAssoc($sql); $primary = array(); foreach ($result as $key => $val) { $primary[] = $val['COLUMN_NAME']; } - $sql = 'EXEC sp_columns @table_name = ' . $this->conn->quoteIdentifier($table, true); - $result = $this->conn->fetchAssoc($sql); + $sql = 'EXEC sp_columns @table_name = '.$this->conn->quoteIdentifier($table, true); + $result = $this->conn->fetchAssoc($sql); $columns = array(); foreach ($result as $key => $val) { @@ -110,29 +111,29 @@ public function listTableColumns($table) $identity = ''; } - if ($type == 'varchar') { - $type .= '(' . $val['length'] . ')'; + if ('varchar' == $type) { + $type .= '('.$val['length'].')'; } $val['type'] = $type; $val['identity'] = $identity; $decl = $this->conn->dataDict->getPortableDeclaration($val); - $isIdentity = (bool) (strtoupper(trim($identity)) == 'IDENTITY'); - $isNullable = (bool) (strtoupper(trim($val['is_nullable'])) == 'NO'); + $isIdentity = (bool) ('IDENTITY' == strtoupper(trim($identity))); + $isNullable = (bool) ('NO' == strtoupper(trim($val['is_nullable']))); $isPrimary = in_array($val['column_name'], $primary); - $description = array( - 'name' => $val['column_name'], - 'ntype' => $type, - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'length' => $decl['length'], - 'fixed' => (bool) $decl['fixed'], - 'unsigned' => (bool) $decl['unsigned'], - 'notnull' => $isIdentity ? true : $isNullable, - 'default' => $val['column_def'], - 'primary' => $isPrimary, + $description = array( + 'name' => $val['column_name'], + 'ntype' => $type, + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'length' => $decl['length'], + 'fixed' => (bool) $decl['fixed'], + 'unsigned' => (bool) $decl['unsigned'], + 'notnull' => $isIdentity ? true : $isNullable, + 'default' => $val['column_def'], + 'primary' => $isPrimary, 'autoincrement' => $isIdentity, ); @@ -143,20 +144,21 @@ public function listTableColumns($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) { - } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) @@ -167,7 +169,9 @@ public function listTables($database = null) } /** - * lists all triggers + * lists all triggers. + * + * @param mixed|null $database * * @return array */ @@ -175,31 +179,29 @@ public function listTriggers($database = null) { $query = "SELECT name FROM sysobjects WHERE xtype = 'TR'"; - $result = $this->conn->fetchColumn($query); - - return $result; + return $this->conn->fetchColumn($query); } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) { $table = $this->conn->quote($table, 'text'); - $query = "SELECT name FROM sysobjects WHERE xtype = 'TR' AND object_name(parent_obj) = " . $this->conn->quoteIdentifier($table, true); - - $result = $this->conn->fetchColumn($query); + $query = "SELECT name FROM sysobjects WHERE xtype = 'TR' AND object_name(parent_obj) = ".$this->conn->quoteIdentifier($table, true); - return $result; + return $this->conn->fetchColumn($query); } /** - * lists table views + * lists table views. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) @@ -207,25 +209,25 @@ public function listTableViews($table) $keyName = 'INDEX_NAME'; $pkName = 'PK_NAME'; if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) == CASE_LOWER) { + if (CASE_LOWER == $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE)) { $keyName = strtolower($keyName); - $pkName = strtolower($pkName); + $pkName = strtolower($pkName); } else { $keyName = strtoupper($keyName); - $pkName = strtoupper($pkName); + $pkName = strtoupper($pkName); } } $table = $this->conn->quote($table, 'text'); - $query = 'EXEC sp_statistics @table_name = ' . $this->conn->quoteIdentifier($table, true); + $query = 'EXEC sp_statistics @table_name = '.$this->conn->quoteIdentifier($table, true); $indexes = $this->conn->fetchColumn($query, $keyName); - $query = 'EXEC sp_pkeys @table_name = ' . $this->conn->quoteIdentifier($table, true); + $query = 'EXEC sp_pkeys @table_name = '.$this->conn->quoteIdentifier($table, true); $pkAll = $this->conn->fetchColumn($query, $pkName); $result = array(); foreach ($indexes as $index) { - if ( ! in_array($index, $pkAll) && $index != null) { + if (!in_array($index, $pkAll) && null != $index) { $result[] = $this->conn->formatter->fixIndexName($index); } } @@ -234,9 +236,10 @@ public function listTableViews($table) } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) @@ -245,4 +248,4 @@ public function listViews($database = null) return $this->conn->fetchColumn($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Mysql.php b/lib/Doctrine/Import/Mysql.php index da3244ebc..cfe2accde 100644 --- a/lib/Doctrine/Import/Mysql.php +++ b/lib/Doctrine/Import/Mysql.php @@ -20,37 +20,38 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7644 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Mysql extends Doctrine_Import { - protected $sql = array( - 'listDatabases' => 'SHOW DATABASES', - 'listTableFields' => 'DESCRIBE %s', - 'listSequences' => 'SHOW TABLES', - 'listTables' => 'SHOW TABLES', - 'listUsers' => 'SELECT DISTINCT USER FROM USER', - 'listViews' => "SHOW FULL TABLES %s WHERE Table_type = 'VIEW'", - ); + protected $sql = array( + 'listDatabases' => 'SHOW DATABASES', + 'listTableFields' => 'DESCRIBE %s', + 'listSequences' => 'SHOW TABLES', + 'listTables' => 'SHOW TABLES', + 'listUsers' => 'SELECT DISTINCT USER FROM USER', + 'listViews' => "SHOW FULL TABLES %s WHERE Table_type = 'VIEW'", + ); /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) { $query = 'SHOW TABLES'; - if ( ! is_null($database)) { - $query .= ' FROM ' . $database; + if (!is_null($database)) { + $query .= ' FROM '.$database; } $tableNames = $this->conn->fetchColumn($query); @@ -58,9 +59,10 @@ public function listSequences($database = null) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) @@ -68,7 +70,7 @@ public function listTableConstraints($table) $keyName = 'Key_name'; $nonUnique = 'Non_unique'; if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) == CASE_LOWER) { + if (CASE_LOWER == $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE)) { $keyName = strtolower($keyName); $nonUnique = strtolower($nonUnique); } else { @@ -78,29 +80,30 @@ public function listTableConstraints($table) } $table = $this->conn->quoteIdentifier($table, true); - $query = 'SHOW INDEX FROM ' . $table; + $query = 'SHOW INDEX FROM '.$table; $indexes = $this->conn->fetchAssoc($query); $result = array(); foreach ($indexes as $indexData) { - if ( ! $indexData[$nonUnique]) { - if ($indexData[$keyName] !== 'PRIMARY') { + if (!$indexData[$nonUnique]) { + if ('PRIMARY' !== $indexData[$keyName]) { $index = $this->conn->formatter->fixIndexName($indexData[$keyName]); } else { $index = 'PRIMARY'; } - if ( ! empty($index)) { + if (!empty($index)) { $result[] = $index; } } } + return $result; } /** - * lists table relations + * lists table relations. * - * Expects an array of this format to be returned with all the relationships in it where the key is + * Expects an array of this format to be returned with all the relationships in it where the key is * the name of the foreign table, and the value is an array containing the local and foreign column * name * @@ -113,60 +116,59 @@ public function listTableConstraints($table) * ) * ) * - * @param string $table database table name * @return array */ public function listTableRelations($tableName) { $relations = array(); - $sql = "SELECT column_name, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.key_column_usage WHERE table_name = '" . $tableName . "' AND table_schema = '" . $this->conn->getDatabaseName() . "' and REFERENCED_COLUMN_NAME is not NULL"; + $sql = "SELECT column_name, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM information_schema.key_column_usage WHERE table_name = '".$tableName."' AND table_schema = '".$this->conn->getDatabaseName()."' and REFERENCED_COLUMN_NAME is not NULL"; $results = $this->conn->fetchAssoc($sql); - foreach ($results as $result) - { + foreach ($results as $result) { $result = array_change_key_case($result, CASE_LOWER); - $relations[] = array('table' => $result['referenced_table_name'], - 'local' => $result['column_name'], - 'foreign' => $result['referenced_column_name']); + $relations[] = array('table' => $result['referenced_table_name'], + 'local' => $result['column_name'], + 'foreign' => $result['referenced_column_name']); } + return $relations; } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - $sql = 'DESCRIBE ' . $this->conn->quoteIdentifier($table, true); + $sql = 'DESCRIBE '.$this->conn->quoteIdentifier($table, true); $result = $this->conn->fetchAssoc($sql); $description = array(); $columns = array(); foreach ($result as $key => $val) { - $val = array_change_key_case($val, CASE_LOWER); $decl = $this->conn->dataDict->getPortableDeclaration($val); $values = isset($decl['values']) ? $decl['values'] : array(); - $val['default'] = $val['default'] == 'CURRENT_TIMESTAMP' ? null : $val['default']; + $val['default'] = 'CURRENT_TIMESTAMP' == $val['default'] ? null : $val['default']; $description = array( - 'name' => $val['field'], - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'ntype' => $val['type'], - 'length' => $decl['length'], - 'fixed' => (bool) $decl['fixed'], - 'unsigned' => (bool) $decl['unsigned'], - 'values' => $values, - 'primary' => (strtolower($val['key']) == 'pri'), - 'default' => $val['default'], - 'notnull' => (bool) ($val['null'] != 'YES'), - 'autoincrement' => (bool) (strpos($val['extra'], 'auto_increment') !== false), - ); + 'name' => $val['field'], + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'ntype' => $val['type'], + 'length' => $decl['length'], + 'fixed' => (bool) $decl['fixed'], + 'unsigned' => (bool) $decl['unsigned'], + 'values' => $values, + 'primary' => ('pri' == strtolower($val['key'])), + 'default' => $val['default'], + 'notnull' => (bool) ('YES' != $val['null']), + 'autoincrement' => (bool) (false !== strpos($val['extra'], 'auto_increment')), + ); if (isset($decl['scale'])) { $description['scale'] = $decl['scale']; } @@ -177,9 +179,10 @@ public function listTableColumns($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) @@ -187,7 +190,7 @@ public function listTableIndexes($table) $keyName = 'Key_name'; $nonUnique = 'Non_unique'; if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) == CASE_LOWER) { + if (CASE_LOWER == $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE)) { $keyName = strtolower($keyName); $nonUnique = strtolower($nonUnique); } else { @@ -197,23 +200,24 @@ public function listTableIndexes($table) } $table = $this->conn->quoteIdentifier($table, true); - $query = 'SHOW INDEX FROM ' . $table; + $query = 'SHOW INDEX FROM '.$table; $indexes = $this->conn->fetchAssoc($query); - $result = array(); foreach ($indexes as $indexData) { if ($indexData[$nonUnique] && ($index = $this->conn->formatter->fixIndexName($indexData[$keyName]))) { $result[] = $index; } } + return $result; } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) @@ -222,9 +226,10 @@ public function listTables($database = null) } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) @@ -232,9 +237,9 @@ public function listViews($database = null) if (is_null($database)) { $query = 'SELECT table_name FROM information_schema.VIEWS'; } else { - $query = sprintf($this->sql['listViews'], ' FROM ' . $database); + $query = sprintf($this->sql['listViews'], ' FROM '.$database); } return $this->conn->fetchColumn($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Oracle.php b/lib/Doctrine/Import/Oracle.php index 3800cc595..ce1aa2388 100644 --- a/lib/Doctrine/Import/Oracle.php +++ b/lib/Doctrine/Import/Oracle.php @@ -20,37 +20,36 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Oracle extends Doctrine_Import { /** - * lists all databases + * lists all databases. * * @return array */ public function listDatabases() { - if ( ! $this->conn->getAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE)) { + if (!$this->conn->getAttribute(Doctrine_Core::ATTR_EMULATE_DATABASE)) { throw new Doctrine_Import_Exception('database listing is only supported if the "emulate_database" option is enabled'); } - $query = 'SELECT username FROM sys.user_users'; + $query = 'SELECT username FROM sys.user_users'; $result2 = $this->conn->standaloneQuery($query); - $result = $result2->fetchColumn(); - return $result; + return $result2->fetchColumn(); } /** - * lists all availible database functions + * lists all availible database functions. * * @return array */ @@ -62,26 +61,29 @@ public function listFunctions() } /** - * lists all database triggers + * lists all database triggers. * * @param string|null $database + * * @return array */ public function listTriggers($database = null) { - $query = "SELECT trigger_name FROM sys.user_triggers"; + $query = 'SELECT trigger_name FROM sys.user_triggers'; + return $this->conn->fetchColumn($query); } /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) { - $query = "SELECT sequence_name FROM sys.user_sequences"; + $query = 'SELECT sequence_name FROM sys.user_sequences'; $tableNames = $this->conn->fetchColumn($query); @@ -89,9 +91,10 @@ public function listSequences($database = null) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) @@ -99,7 +102,7 @@ public function listTableConstraints($table) $table = $this->conn->quote($table, 'text'); $query = 'SELECT index_name name FROM user_constraints' - . ' WHERE table_name = ' . $table . ' OR table_name = ' . strtoupper($table); + .' WHERE table_name = '.$table.' OR table_name = '.strtoupper($table); $constraints = $this->conn->fetchColumn($query); @@ -107,14 +110,15 @@ public function listTableConstraints($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - $sql = <<conn->dataDict->getPortableDeclaration($val); $descr[$val['column_name']] = array( - 'name' => $val['column_name'], - 'notnull' => (bool) ($val['nullable'] === 'N'), - 'ntype' => $val['data_type'], - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'fixed' => (bool) $decl['fixed'], - 'unsigned' => (bool) $decl['unsigned'], - 'default' => $val['data_default'], - 'length' => $val['data_length'], - 'primary' => (bool) $val['primary'], - 'scale' => isset($val['scale']) ? $val['scale']:null, + 'name' => $val['column_name'], + 'notnull' => (bool) ('N' === $val['nullable']), + 'ntype' => $val['data_type'], + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'fixed' => (bool) $decl['fixed'], + 'unsigned' => (bool) $decl['unsigned'], + 'default' => $val['data_default'], + 'length' => $val['data_length'], + 'primary' => (bool) $val['primary'], + 'scale' => isset($val['scale']) ? $val['scale'] : null, ); } @@ -153,84 +157,88 @@ public function listTableColumns($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) { $table = $this->conn->quote($table, 'text'); $query = 'SELECT index_name name FROM user_indexes' - . ' WHERE table_name = ' . $table . ' OR table_name = ' . strtoupper($table) - . ' AND generated = ' . $this->conn->quote('N', 'text'); + .' WHERE table_name = '.$table.' OR table_name = '.strtoupper($table) + .' AND generated = '.$this->conn->quote('N', 'text'); $indexes = $this->conn->fetchColumn($query); return array_map(array($this->conn->formatter, 'fixIndexName'), $indexes); } - + /** - * list table relations + * list table relations. */ public function listTableRelations($table) { $relations = array(); $sql = 'SELECT ' - . 'rcc.table_name AS referenced_table_name, ' - . 'lcc.column_name AS local_column_name, ' - . 'rcc.column_name AS referenced_column_name ' - . 'FROM user_constraints ac ' - . 'JOIN user_cons_columns rcc ON ac.r_constraint_name = rcc.constraint_name ' - . 'JOIN user_cons_columns lcc ON ac.constraint_name = lcc.constraint_name ' - . "WHERE ac.constraint_type = 'R' AND ac.table_name = :tableName"; + .'rcc.table_name AS referenced_table_name, ' + .'lcc.column_name AS local_column_name, ' + .'rcc.column_name AS referenced_column_name ' + .'FROM user_constraints ac ' + .'JOIN user_cons_columns rcc ON ac.r_constraint_name = rcc.constraint_name ' + .'JOIN user_cons_columns lcc ON ac.constraint_name = lcc.constraint_name ' + ."WHERE ac.constraint_type = 'R' AND ac.table_name = :tableName"; $results = $this->conn->fetchAssoc($sql, array(':tableName' => $table)); foreach ($results as $result) { $result = array_change_key_case($result, CASE_LOWER); - $relations[] = array('table' => $result['referenced_table_name'], - 'local' => $result['local_column_name'], - 'foreign' => $result['referenced_column_name']); + $relations[] = array('table' => $result['referenced_table_name'], + 'local' => $result['local_column_name'], + 'foreign' => $result['referenced_column_name']); } + return $relations; } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) { $query = "SELECT * FROM user_objects WHERE object_type = 'TABLE' and object_name in (select table_name from user_tables)"; + return $this->conn->fetchColumn($query); } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) { - } /** - * lists table views + * lists table views. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) { - } /** - * lists database users + * lists database users. * * @return array */ @@ -242,14 +250,16 @@ public function listUsers() } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) { $query = 'SELECT view_name FROM sys.user_views'; + return $this->conn->fetchColumn($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Pgsql.php b/lib/Doctrine/Import/Pgsql.php index bdef1d00b..2eb2a1af3 100644 --- a/lib/Doctrine/Import/Pgsql.php +++ b/lib/Doctrine/Import/Pgsql.php @@ -20,22 +20,21 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Paul Cooper * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7689 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Pgsql extends Doctrine_Import { - protected $sql = array( - 'listDatabases' => 'SELECT datname FROM pg_database', - 'listFunctions' => "SELECT + 'listDatabases' => 'SELECT datname FROM pg_database', + 'listFunctions' => "SELECT proname FROM pg_proc pr, @@ -47,14 +46,14 @@ class Doctrine_Import_Pgsql extends Doctrine_Import AND pr.pronamespace IN (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema'", - 'listSequences' => "SELECT + 'listSequences' => "SELECT regexp_replace(relname, '_seq$', '') FROM pg_class WHERE relkind = 'S' AND relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')", - 'listTables' => "SELECT + 'listTables' => "SELECT c.relname AS table_name FROM pg_class c, pg_user u WHERE c.relowner = u.usesysid @@ -68,9 +67,9 @@ class Doctrine_Import_Pgsql extends Doctrine_Import AND NOT EXISTS (SELECT 1 FROM pg_views WHERE viewname = c.relname) AND NOT EXISTS (SELECT 1 FROM pg_user WHERE usesysid = c.relowner) AND c.relname !~ '^pg_'", - 'listViews' => 'SELECT viewname FROM pg_views', - 'listUsers' => 'SELECT usename FROM pg_user', - 'listTableConstraints' => "SELECT + 'listViews' => 'SELECT viewname FROM pg_views', + 'listUsers' => 'SELECT usename FROM pg_user', + 'listTableConstraints' => "SELECT relname FROM pg_class @@ -81,7 +80,7 @@ class Doctrine_Import_Pgsql extends Doctrine_Import AND pg_class.oid = pg_index.indrelid AND (indisunique = 't' OR indisprimary = 't') )", - 'listTableIndexes' => "SELECT + 'listTableIndexes' => "SELECT relname FROM pg_class @@ -93,7 +92,7 @@ class Doctrine_Import_Pgsql extends Doctrine_Import AND indisunique != 't' AND indisprimary != 't' )", - 'listTableColumns' => "SELECT + 'listTableColumns' => "SELECT ordinal_position as attnum, column_name as field, udt_name as type, @@ -112,7 +111,7 @@ class Doctrine_Import_Pgsql extends Doctrine_Import FROM information_schema.COLUMNS WHERE table_name = %s ORDER BY ordinal_position", - 'listTableRelations' => "SELECT pg_catalog.pg_get_constraintdef(oid, true) as condef + 'listTableRelations' => "SELECT pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_catalog.pg_constraint r WHERE r.conrelid = ( @@ -121,24 +120,25 @@ class Doctrine_Import_Pgsql extends Doctrine_Import LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relname ~ ? AND pg_catalog.pg_table_is_visible(c.oid) ) - AND r.contype = 'f'" - ); + AND r.contype = 'f'", + ); /** - * lists all database triggers + * lists all database triggers. * * @param string|null $database + * * @return array */ public function listTriggers($database = null) { - } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) @@ -150,9 +150,10 @@ public function listTableConstraints($table) } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) @@ -161,75 +162,76 @@ public function listTableColumns($table) $query = sprintf($this->sql['listTableColumns'], $table); $result = $this->conn->fetchAssoc($query); - $columns = array(); + $columns = array(); foreach ($result as $key => $val) { $val = array_change_key_case($val, CASE_LOWER); - if ($val['type'] == 'character varying') { + if ('character varying' == $val['type']) { // get length from varchar definition $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $val['complete_type']); $val['length'] = $length; - } else if (strpos($val['complete_type'], 'character varying') !== false) { + } elseif (false !== strpos($val['complete_type'], 'character varying')) { // get length from varchar definition $length = preg_replace('~.*\(([0-9]*)\).*~', '$1', $val['complete_type']); $val['length'] = $length; } - + $decl = $this->conn->dataDict->getPortableDeclaration($val); $description = array( - 'name' => $val['field'], - 'ntype' => $val['type'], - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'length' => $decl['length'], - 'fixed' => (bool) $decl['fixed'], - 'unsigned' => (bool) $decl['unsigned'], - 'notnull' => ($val['isnotnull'] == 'NO'), - 'default' => $val['default'], - 'primary' => ($val['pri'] == 't'), + 'name' => $val['field'], + 'ntype' => $val['type'], + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'length' => $decl['length'], + 'fixed' => (bool) $decl['fixed'], + 'unsigned' => (bool) $decl['unsigned'], + 'notnull' => ('NO' == $val['isnotnull']), + 'default' => $val['default'], + 'primary' => ('t' == $val['pri']), ); - // If postgres enum type - if ($val['type'] == 'e'){ + // If postgres enum type + if ('e' == $val['type']) { $description['default'] = isset($decl['default']) ? $decl['default'] : null; - $t_result = $this->conn->fetchAssoc(sprintf('select enum_range(null::%s) as range ', $decl['enum_name'])); - if (isset($t_result[0])){ - $range = $t_result[0]['range']; - $range = str_replace('{','',$range); - $range = str_replace('}','',$range); - $range = explode(',',$range); + $t_result = $this->conn->fetchAssoc(sprintf('select enum_range(null::%s) as range ', $decl['enum_name'])); + if (isset($t_result[0])) { + $range = $t_result[0]['range']; + $range = str_replace('{', '', $range); + $range = str_replace('}', '', $range); + $range = explode(',', $range); $description['values'] = $range; } } - $matches = array(); + $matches = array(); - if (preg_match("/^nextval\('(.*)'(::.*)?\)$/", $description['default'], $matches)) { - $description['sequence'] = $this->conn->formatter->fixSequenceName($matches[1]); - $description['default'] = null; - } else if (preg_match("/^'(.*)'::character varying$/", $description['default'], $matches)) { + if (preg_match("/^nextval\\('(.*)'(::.*)?\\)$/", $description['default'], $matches)) { + $description['sequence'] = $this->conn->formatter->fixSequenceName($matches[1]); + $description['default'] = null; + } elseif (preg_match("/^'(.*)'::character varying$/", $description['default'], $matches)) { $description['default'] = $matches[1]; - } else if (preg_match("/^(.*)::character varying$/", $description['default'], $matches)) { + } elseif (preg_match('/^(.*)::character varying$/', $description['default'], $matches)) { $description['default'] = $matches[1]; - } else if ($description['type'] == 'boolean') { - if ($description['default'] === 'true') { - $description['default'] = true; - } else if ($description['default'] === 'false') { - $description['default'] = false; + } elseif ('boolean' == $description['type']) { + if ('true' === $description['default']) { + $description['default'] = true; + } elseif ('false' === $description['default']) { + $description['default'] = false; } } $columns[$val['field']] = $description; } - + return $columns; } /** - * list all indexes in a table + * list all indexes in a table. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) @@ -241,9 +243,10 @@ public function listTableIndexes($table) } /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) @@ -252,9 +255,10 @@ public function listTables($database = null) } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) @@ -263,17 +267,19 @@ public function listTableTriggers($table) FROM pg_trigger trg, pg_class tbl WHERE trg.tgrelid = tbl.oid'; - if ($table !== null) { + if (null !== $table) { $table = $this->conn->quote(strtoupper($table), 'string'); - $query .= " AND tbl.relname = $table"; + $query .= " AND tbl.relname = {$table}"; } + return $this->conn->fetchColumn($query); } /** - * list the views in the database that reference a given table + * list the views in the database that reference a given table. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) @@ -284,21 +290,21 @@ public function listTableViews($table) public function listTableRelations($table) { $sql = $this->sql['listTableRelations']; - $param = array('^(' . $table . ')$'); + $param = array('^('.$table.')$'); $relations = array(); $results = $this->conn->fetchAssoc($sql, $param); foreach ($results as $result) { preg_match('/FOREIGN KEY \((.+)\) REFERENCES (.+)\((.+)\)/', $result['condef'], $values); - if ((strpos($values[1], ',') === false) && (strpos($values[3], ',') === false)) { + if ((false === strpos($values[1], ',')) && (false === strpos($values[3], ','))) { $tableName = trim($values[2], '"'); - $relations[] = array('table' => $tableName, - 'local' => $values[1], - 'foreign' => $values[3]); + $relations[] = array('table' => $tableName, + 'local' => $values[1], + 'foreign' => $values[3]); } } return $relations; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Schema.php b/lib/Doctrine/Import/Schema.php index 65ea075d5..c51904660 100644 --- a/lib/Doctrine/Import/Schema.php +++ b/lib/Doctrine/Import/Schema.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Import_Schema + * Doctrine_Import_Schema. * * Class for importing Doctrine_Record classes from a yaml schema definition * - * @package Doctrine - * @subpackage Import - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision: 1838 $ + * * @author Nicolas Bérard-Nault * @author Jonathan H. Wage */ @@ -51,7 +52,7 @@ class Doctrine_Import_Schema 'detect_relations'); /** - * _relations + * _relations. * * Array of all relationships parsed from all schema files * @@ -60,101 +61,101 @@ class Doctrine_Import_Schema protected $_relations = array(); /** - * _options + * _options. * * Array of options used to configure the model generation from the parsed schema files * This array is forwarded to Doctrine_Import_Builder * * @var array */ - protected $_options = array('packagesPrefix' => 'Package', - 'packagesPath' => '', - 'packagesFolderName' => 'packages', - 'suffix' => '.php', - 'generateBaseClasses' => true, - 'generateTableClasses' => false, - 'generateAccessors' => false, - 'baseClassPrefix' => 'Base', - 'baseClassesDirectory' => 'generated', - 'baseClassName' => 'Doctrine_Record'); + protected $_options = array('packagesPrefix' => 'Package', + 'packagesPath' => '', + 'packagesFolderName' => 'packages', + 'suffix' => '.php', + 'generateBaseClasses' => true, + 'generateTableClasses' => false, + 'generateAccessors' => false, + 'baseClassPrefix' => 'Base', + 'baseClassesDirectory' => 'generated', + 'baseClassName' => 'Doctrine_Record'); /** - * _validation + * _validation. * * Array used to validate schema element. * See: _validateSchemaElement * * @var array */ - protected $_validation = array('root' => array('abstract', - 'connection', - 'className', - 'tableName', - 'connection', - 'relations', - 'columns', - 'indexes', - 'attributes', - 'templates', - 'actAs', - 'options', - 'package', - 'package_custom_path', - 'inheritance', - 'detect_relations', - 'listeners', - 'checks', - 'comment'), - - 'column' => array('name', - 'format', - 'fixed', - 'primary', - 'autoincrement', - 'type', - 'length', - 'size', - 'default', - 'scale', - 'values', - 'comment', - 'sequence', - 'protected', - 'zerofill', - 'owner', - 'extra', - 'comment', - 'charset', - 'collation'), - - 'relation' => array('key', - 'class', - 'alias', - 'type', - 'refClass', - 'local', - 'foreign', - 'foreignClass', - 'foreignAlias', - 'foreignType', - 'autoComplete', - 'cascade', - 'onDelete', - 'onUpdate', - 'equal', - 'owningSide', - 'refClassRelationAlias', - 'foreignKeyName', - 'orderBy'), - - 'inheritance'=> array('type', - 'extends', - 'keyField', - 'keyValue')); + protected $_validation = array('root' => array('abstract', + 'connection', + 'className', + 'tableName', + 'connection', + 'relations', + 'columns', + 'indexes', + 'attributes', + 'templates', + 'actAs', + 'options', + 'package', + 'package_custom_path', + 'inheritance', + 'detect_relations', + 'listeners', + 'checks', + 'comment'), + + 'column' => array('name', + 'format', + 'fixed', + 'primary', + 'autoincrement', + 'type', + 'length', + 'size', + 'default', + 'scale', + 'values', + 'comment', + 'sequence', + 'protected', + 'zerofill', + 'owner', + 'extra', + 'comment', + 'charset', + 'collation'), + + 'relation' => array('key', + 'class', + 'alias', + 'type', + 'refClass', + 'local', + 'foreign', + 'foreignClass', + 'foreignAlias', + 'foreignType', + 'autoComplete', + 'cascade', + 'onDelete', + 'onUpdate', + 'equal', + 'owningSide', + 'refClassRelationAlias', + 'foreignKeyName', + 'orderBy'), + + 'inheritance' => array('type', + 'extends', + 'keyField', + 'keyValue')); /** * Returns an array of definition keys that can be applied at the global level. - * + * * @return array */ public static function getGlobalDefinitionKeys() @@ -163,22 +164,19 @@ public static function getGlobalDefinitionKeys() } /** - * getOption + * getOption. * - * @param string $name - * @return void + * @param string $name */ public function getOption($name) { - if (isset($this->_options[$name])) { + if (isset($this->_options[$name])) { return $this->_options[$name]; } } /** - * getOptions - * - * @return void + * getOptions. */ public function getOptions() { @@ -186,11 +184,10 @@ public function getOptions() } /** - * setOption + * setOption. * - * @param string $name - * @param string $value - * @return void + * @param string $name + * @param string $value */ public function setOption($name, $value) { @@ -198,42 +195,42 @@ public function setOption($name, $value) $this->_options[$name] = $value; } } - + /** - * setOptions + * setOptions. * - * @param string $options - * @return void + * @param string $options */ public function setOptions($options) { - if ( ! empty($options)) { - $this->_options = $options; + if (!empty($options)) { + $this->_options = $options; } } /** - * buildSchema + * buildSchema. * * Loop throug directories of schema files and parse them all in to one complete array of schema information * - * @param string $schema Array of schema files or single schema file. Array of directories with schema files or single directory - * @param string $format Format of the files we are parsing and building from - * @return array $array + * @param string $schema Array of schema files or single schema file. Array of directories with schema files or single directory + * @param string $format Format of the files we are parsing and building from + * + * @return array $array */ public function buildSchema($schema, $format) { $array = array(); - foreach ((array) $schema AS $s) { + foreach ((array) $schema as $s) { if (is_file($s)) { $e = explode('.', $s); if (end($e) === $format) { $array = array_merge($array, $this->parseSchema($s, $format)); - } - } else if (is_dir($s)) { + } + } elseif (is_dir($s)) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($s), - RecursiveIteratorIterator::LEAVES_ONLY); + RecursiveIteratorIterator::LEAVES_ONLY); foreach ($it as $file) { $e = explode('.', $file->getFileName()); @@ -242,27 +239,24 @@ public function buildSchema($schema, $format) } } } else { - $array = array_merge($array, $this->parseSchema($s, $format)); + $array = array_merge($array, $this->parseSchema($s, $format)); } } $array = $this->_buildRelationships($array); - $array = $this->_processInheritance($array); - return $array; + return $this->_processInheritance($array); } /** - * importSchema + * importSchema. * * A method to import a Schema and translate it into a Doctrine_Record object * - * @param string $schema The file containing the XML schema - * @param string $format Format of the schema file - * @param string $directory The directory where the Doctrine_Record class will be written - * @param array $models Optional array of models to import - * - * @return void + * @param string $schema The file containing the XML schema + * @param string $format Format of the schema file + * @param string $directory The directory where the Doctrine_Record class will be written + * @param array $models Optional array of models to import */ public function importSchema($schema, $format = 'yml', $directory = null, $models = array()) { @@ -270,50 +264,49 @@ public function importSchema($schema, $format = 'yml', $directory = null, $model $builder = new Doctrine_Import_Builder(); $builder->setTargetPath($directory); $builder->setOptions($this->getOptions()); - + $array = $this->buildSchema($schema, $format); - if (count($array) == 0) { - throw new Doctrine_Import_Exception( - sprintf('No ' . $format . ' schema found in ' . implode(", ", $schema)) - ); + if (0 == count($array)) { + throw new Doctrine_Import_Exception(sprintf('No '.$format.' schema found in '.implode(', ', $schema))); } foreach ($array as $name => $definition) { - if ( ! empty($models) && !in_array($definition['className'], $models)) { + if (!empty($models) && !in_array($definition['className'], $models)) { continue; } - + $builder->buildRecord($definition); } } /** - * parseSchema + * parseSchema. * * A method to parse a Schema and translate it into a property array. * The function returns that property array. * - * @param string $schema Path to the file containing the schema - * @param string $type Format type of the schema we are parsing - * @return array $build Built array of schema information + * @param string $schema Path to the file containing the schema + * @param string $type Format type of the schema we are parsing + * + * @return array $build Built array of schema information */ public function parseSchema($schema, $type) { - $defaults = array('abstract' => false, - 'className' => null, - 'tableName' => null, - 'connection' => null, - 'relations' => array(), - 'indexes' => array(), - 'attributes' => array(), - 'templates' => array(), - 'actAs' => array(), - 'options' => array(), - 'package' => null, - 'inheritance' => array(), - 'detect_relations' => false); - + $defaults = array('abstract' => false, + 'className' => null, + 'tableName' => null, + 'connection' => null, + 'relations' => array(), + 'indexes' => array(), + 'attributes' => array(), + 'templates' => array(), + 'actAs' => array(), + 'options' => array(), + 'package' => null, + 'inheritance' => array(), + 'detect_relations' => false); + $array = Doctrine_Parser::load($schema, $type); // Loop over and build up all the global values and remove them from the array @@ -338,7 +331,7 @@ public function parseSchema($schema, $type) $columns = array(); - $className = isset($table['className']) ? (string) $table['className']:(string) $className; + $className = isset($table['className']) ? (string) $table['className'] : (string) $className; if (isset($table['inheritance']['keyField']) || isset($table['inheritance']['keyValue'])) { $table['inheritance']['type'] = 'column_aggregation'; @@ -347,22 +340,21 @@ public function parseSchema($schema, $type) if (isset($table['tableName']) && $table['tableName']) { $tableName = $table['tableName']; } else { - if (isset($table['inheritance']['type']) && ($table['inheritance']['type'] == 'column_aggregation')) { + if (isset($table['inheritance']['type']) && ('column_aggregation' == $table['inheritance']['type'])) { $tableName = null; } else { $tableName = Doctrine_Inflector::tableize($className); } } - $connection = isset($table['connection']) ? $table['connection']:'current'; + $connection = isset($table['connection']) ? $table['connection'] : 'current'; - $columns = isset($table['columns']) ? $table['columns']:array(); + $columns = isset($table['columns']) ? $table['columns'] : array(); - if ( ! empty($columns)) { + if (!empty($columns)) { foreach ($columns as $columnName => $field) { - // Support short syntax: my_column: integer(4) - if ( ! is_array($field)) { + if (!is_array($field)) { $original = $field; $field = array(); $field['type'] = $original; @@ -375,11 +367,11 @@ public function parseSchema($schema, $type) $colDesc['name'] = $columnName; } - $this->_validateSchemaElement('column', array_keys($field), $className . '->columns->' . $colDesc['name']); + $this->_validateSchemaElement('column', array_keys($field), $className.'->columns->'.$colDesc['name']); // Support short type(length) syntax: my_column: { type: integer(4) } $e = explode('(', $field['type']); - if (isset($e[0]) && isset($e[1])) { + if (isset($e[0], $e[1])) { $colDesc['type'] = $e[0]; $value = substr($e[1], 0, strlen($e[1]) - 1); $e = explode(',', $value); @@ -388,15 +380,15 @@ public function parseSchema($schema, $type) $colDesc['scale'] = $e[1]; } } else { - $colDesc['type'] = isset($field['type']) ? (string) $field['type']:null; - $colDesc['length'] = isset($field['length']) ? (int) $field['length']:null; - $colDesc['length'] = isset($field['size']) ? (int) $field['size']:$colDesc['length']; + $colDesc['type'] = isset($field['type']) ? (string) $field['type'] : null; + $colDesc['length'] = isset($field['length']) ? (int) $field['length'] : null; + $colDesc['length'] = isset($field['size']) ? (int) $field['size'] : $colDesc['length']; } - $colDesc['fixed'] = isset($field['fixed']) ? (int) $field['fixed']:null; - $colDesc['primary'] = isset($field['primary']) ? (bool) (isset($field['primary']) && $field['primary']):null; - $colDesc['default'] = isset($field['default']) ? $field['default']:null; - $colDesc['autoincrement'] = isset($field['autoincrement']) ? (bool) (isset($field['autoincrement']) && $field['autoincrement']):null; + $colDesc['fixed'] = isset($field['fixed']) ? (int) $field['fixed'] : null; + $colDesc['primary'] = isset($field['primary']) ? (bool) (isset($field['primary']) && $field['primary']) : null; + $colDesc['default'] = isset($field['default']) ? $field['default'] : null; + $colDesc['autoincrement'] = isset($field['autoincrement']) ? (bool) (isset($field['autoincrement']) && $field['autoincrement']) : null; if (isset($field['sequence'])) { if (true === $field['sequence']) { @@ -408,7 +400,7 @@ public function parseSchema($schema, $type) $colDesc['sequence'] = null; } - $colDesc['values'] = isset($field['values']) ? (array) $field['values']:null; + $colDesc['values'] = isset($field['values']) ? (array) $field['values'] : null; // Include all the specified and valid validators in the colDesc $validators = Doctrine_Manager::getInstance()->getValidators(); @@ -425,20 +417,20 @@ public function parseSchema($schema, $type) // Apply the default values foreach ($defaults as $key => $defaultValue) { - if (isset($table[$key]) && ! isset($build[$className][$key])) { + if (isset($table[$key]) && !isset($build[$className][$key])) { $build[$className][$key] = $table[$key]; } else { - $build[$className][$key] = isset($build[$className][$key]) ? $build[$className][$key]:$defaultValue; + $build[$className][$key] = isset($build[$className][$key]) ? $build[$className][$key] : $defaultValue; } } - + $build[$className]['className'] = $className; $build[$className]['tableName'] = $tableName; $build[$className]['columns'] = $columns; - + // Make sure that anything else that is specified in the schema makes it to the final array $build[$className] = Doctrine_Lib::arrayDeepMerge($table, $build[$className]); - + // We need to keep track of the className for the connection $build[$className]['connectionClassName'] = $build[$className]['className']; } @@ -447,42 +439,41 @@ public function parseSchema($schema, $type) } /** - * _processInheritance - * + * _processInheritance. + * * Perform some processing on inheritance. * Sets the default type and sets some default values for certain types * - * @param string $array - * @return void + * @param string $array */ protected function _processInheritance($array) { // Apply default inheritance configuration foreach ($array as $className => $definition) { - if ( ! empty($array[$className]['inheritance'])) { - $this->_validateSchemaElement('inheritance', array_keys($definition['inheritance']), $className . '->inheritance'); + if (!empty($array[$className]['inheritance'])) { + $this->_validateSchemaElement('inheritance', array_keys($definition['inheritance']), $className.'->inheritance'); // Default inheritance to concrete inheritance - if ( ! isset($array[$className]['inheritance']['type'])) { + if (!isset($array[$className]['inheritance']['type'])) { $array[$className]['inheritance']['type'] = 'concrete'; } // Some magic for setting up the keyField and keyValue column aggregation options // Adds keyField to the parent class automatically - if ($array[$className]['inheritance']['type'] == 'column_aggregation') { + if ('column_aggregation' == $array[$className]['inheritance']['type']) { // Set the keyField to 'type' by default - if ( ! isset($array[$className]['inheritance']['keyField'])) { - $array[$className]['inheritance']['keyField'] = 'type'; + if (!isset($array[$className]['inheritance']['keyField'])) { + $array[$className]['inheritance']['keyField'] = 'type'; } - + // Set the keyValue to the name of the child class if it does not exist - if ( ! isset($array[$className]['inheritance']['keyValue'])) { + if (!isset($array[$className]['inheritance']['keyValue'])) { $array[$className]['inheritance']['keyValue'] = $className; } $parent = $this->_findBaseSuperClass($array, $definition['className']); // Add the keyType column to the parent if a definition does not already exist - if ( ! isset($array[$parent]['columns'][$array[$className]['inheritance']['keyField']])) { + if (!isset($array[$parent]['columns'][$array[$className]['inheritance']['keyField']])) { $array[$parent]['columns'][$array[$className]['inheritance']['keyField']] = array('name' => $array[$className]['inheritance']['keyField'], 'type' => 'string', 'length' => 255); } } @@ -492,40 +483,40 @@ protected function _processInheritance($array) // Array of the array keys to move to the parent, and the value to default the child definition to // after moving it. Will also populate the subclasses array for the inheritance parent $moves = array('columns' => array(), - 'indexes' => array(), - 'attributes' => array(), - 'options' => array(), - 'checks' => array()); + 'indexes' => array(), + 'attributes' => array(), + 'options' => array(), + 'checks' => array()); foreach ($array as $className => $definition) { // Move any definitions on the schema to the parent - if (isset($definition['inheritance']['extends']) && isset($definition['inheritance']['type']) && ($definition['inheritance']['type'] == 'simple' || $definition['inheritance']['type'] == 'column_aggregation')) { + if (isset($definition['inheritance']['extends'], $definition['inheritance']['type']) && ('simple' == $definition['inheritance']['type'] || 'column_aggregation' == $definition['inheritance']['type'])) { $parent = $this->_findBaseSuperClass($array, $definition['className']); foreach ($moves as $move => $resetValue) { - if (isset($array[$parent][$move]) && isset($definition[$move])) { + if (isset($array[$parent][$move], $definition[$move])) { $array[$parent][$move] = Doctrine_Lib::arrayDeepMerge($array[$parent][$move], $definition[$move]); $array[$definition['className']][$move] = $resetValue; } } // Populate the parents subclasses - if ($definition['inheritance']['type'] == 'column_aggregation') { - // Fix for 2015: loop through superclasses' inheritance to the base-superclass to - // make sure we collect all keyFields needed (and not only the first) - $inheritanceFields = array($definition['inheritance']['keyField'] => $definition['inheritance']['keyValue']); + if ('column_aggregation' == $definition['inheritance']['type']) { + // Fix for 2015: loop through superclasses' inheritance to the base-superclass to + // make sure we collect all keyFields needed (and not only the first) + $inheritanceFields = array($definition['inheritance']['keyField'] => $definition['inheritance']['keyValue']); - $superClass = $definition['inheritance']['extends']; - $multiInheritanceDef = $array[$superClass]; + $superClass = $definition['inheritance']['extends']; + $multiInheritanceDef = $array[$superClass]; - while (count($multiInheritanceDef['inheritance']) > 0 && array_key_exists('extends', $multiInheritanceDef['inheritance']) && $multiInheritanceDef['inheritance']['type'] == 'column_aggregation') { + while (count($multiInheritanceDef['inheritance']) > 0 && array_key_exists('extends', $multiInheritanceDef['inheritance']) && 'column_aggregation' == $multiInheritanceDef['inheritance']['type']) { $superClass = $multiInheritanceDef['inheritance']['extends']; - + // keep original keyField with it's keyValue - if ( ! isset($inheritanceFields[$multiInheritanceDef['inheritance']['keyField']])) { + if (!isset($inheritanceFields[$multiInheritanceDef['inheritance']['keyField']])) { $inheritanceFields[$multiInheritanceDef['inheritance']['keyField']] = $multiInheritanceDef['inheritance']['keyValue']; - } - $multiInheritanceDef = $array[$superClass]; - } + } + $multiInheritanceDef = $array[$superClass]; + } $array[$parent]['inheritance']['subclasses'][$definition['className']] = $inheritanceFields; } @@ -539,34 +530,34 @@ protected function _processInheritance($array) * Find the base super class for this inheritance child. We need to move all levels of children to the * top most parent. * - * @param array $array Array of schema information + * @param array $array Array of schema information + * * @return string $class Class to get find the parent for */ protected function _findBaseSuperClass($array, $class) { - if (isset($array[$class]['inheritance']['extends']) && isset($array[$class]['inheritance']['type']) && ($array[$class]['inheritance']['type'] == 'simple' || $array[$class]['inheritance']['type'] == 'column_aggregation')) { + if (isset($array[$class]['inheritance']['extends'], $array[$class]['inheritance']['type']) && ('simple' == $array[$class]['inheritance']['type'] || 'column_aggregation' == $array[$class]['inheritance']['type'])) { return $this->_findBaseSuperClass($array, $array[$class]['inheritance']['extends']); - } else { - return $class; } + + return $class; } /** - * buildRelationships + * buildRelationships. * * Loop through an array of schema information and build all the necessary relationship information - * Will attempt to auto complete relationships and simplify the amount of information required + * Will attempt to auto complete relationships and simplify the amount of information required * for defining a relationship * - * @param string $array - * @return void + * @param string $array */ protected function _buildRelationships($array) { // Handle auto detecting relations by the names of columns // User.contact_id will automatically create User hasOne Contact local => contact_id, foreign => id foreach ($array as $className => $properties) { - if (isset($properties['columns']) && ! empty($properties['columns']) && isset($properties['detect_relations']) && $properties['detect_relations']) { + if (isset($properties['columns']) && !empty($properties['columns']) && isset($properties['detect_relations']) && $properties['detect_relations']) { foreach ($properties['columns'] as $column) { // Check if the column we are inflecting has a _id on the end of it before trying to inflect it and find // the class name for the column @@ -577,8 +568,8 @@ protected function _buildRelationships($array) // Set the detected foreign key type and length to the same as the primary key // of the related table - $type = isset($array[$columnClassName]['columns']['id']['type']) ? $array[$columnClassName]['columns']['id']['type']:'integer'; - $length = isset($array[$columnClassName]['columns']['id']['length']) ? $array[$columnClassName]['columns']['id']['length']:8; + $type = isset($array[$columnClassName]['columns']['id']['type']) ? $array[$columnClassName]['columns']['id']['type'] : 'integer'; + $length = isset($array[$columnClassName]['columns']['id']['length']) ? $array[$columnClassName]['columns']['id']['length'] : 8; $array[$className]['columns'][$column['name']]['type'] = $type; $array[$className]['columns'][$column['name']]['length'] = $length; } @@ -588,55 +579,55 @@ protected function _buildRelationships($array) } foreach ($array as $name => $properties) { - if ( ! isset($properties['relations'])) { + if (!isset($properties['relations'])) { continue; } - + $className = $properties['className']; $relations = $properties['relations']; - + foreach ($relations as $alias => $relation) { - $class = isset($relation['class']) ? $relation['class']:$alias; - if ( ! isset($array[$class])) { + $class = isset($relation['class']) ? $relation['class'] : $alias; + if (!isset($array[$class])) { continue; } $relation['class'] = $class; $relation['alias'] = isset($relation['alias']) ? $relation['alias'] : $alias; - + // Attempt to guess the local and foreign if (isset($relation['refClass'])) { - $relation['local'] = isset($relation['local']) ? $relation['local']:Doctrine_Inflector::tableize($name) . '_id'; - $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign']:Doctrine_Inflector::tableize($class) . '_id'; + $relation['local'] = isset($relation['local']) ? $relation['local'] : Doctrine_Inflector::tableize($name).'_id'; + $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign'] : Doctrine_Inflector::tableize($class).'_id'; } else { - $relation['local'] = isset($relation['local']) ? $relation['local']:Doctrine_Inflector::tableize($relation['class']) . '_id'; - $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign']:'id'; + $relation['local'] = isset($relation['local']) ? $relation['local'] : Doctrine_Inflector::tableize($relation['class']).'_id'; + $relation['foreign'] = isset($relation['foreign']) ? $relation['foreign'] : 'id'; } - + if (isset($relation['refClass'])) { $relation['type'] = 'many'; } - + if (isset($relation['type']) && $relation['type']) { - $relation['type'] = $relation['type'] === 'one' ? Doctrine_Relation::ONE:Doctrine_Relation::MANY; + $relation['type'] = 'one' === $relation['type'] ? Doctrine_Relation::ONE : Doctrine_Relation::MANY; } else { $relation['type'] = Doctrine_Relation::ONE; } if (isset($relation['foreignType']) && $relation['foreignType']) { - $relation['foreignType'] = $relation['foreignType'] === 'one' ? Doctrine_Relation::ONE:Doctrine_Relation::MANY; + $relation['foreignType'] = 'one' === $relation['foreignType'] ? Doctrine_Relation::ONE : Doctrine_Relation::MANY; } - + $relation['key'] = $this->_buildUniqueRelationKey($relation); - - $this->_validateSchemaElement('relation', array_keys($relation), $className . '->relation->' . $relation['alias']); - + + $this->_validateSchemaElement('relation', array_keys($relation), $className.'->relation->'.$relation['alias']); + $this->_relations[$className][$alias] = $relation; } } - + // Now we auto-complete opposite ends of relationships $this->_autoCompleteOppositeRelations(); - + // Make sure we do not have any duplicate relations $this->_fixDuplicateRelations(); @@ -644,50 +635,48 @@ protected function _buildRelationships($array) foreach ($this->_relations as $className => $relations) { $array[$className]['relations'] = $relations; } - + return $array; } /** - * fixRelationships + * fixRelationships. * * Loop through all relationships building the opposite ends of each relationship * and make sure no duplicate relations exist - * - * @return void */ protected function _autoCompleteOppositeRelations() { - foreach($this->_relations as $className => $relations) { - foreach ($relations AS $alias => $relation) { - if ((isset($relation['equal']) && $relation['equal']) || (isset($relation['autoComplete']) && $relation['autoComplete'] === false)) { + foreach ($this->_relations as $className => $relations) { + foreach ($relations as $alias => $relation) { + if ((isset($relation['equal']) && $relation['equal']) || (isset($relation['autoComplete']) && false === $relation['autoComplete'])) { continue; } - + $newRelation = array(); $newRelation['foreign'] = $relation['local']; $newRelation['local'] = $relation['foreign']; - $newRelation['class'] = isset($relation['foreignClass']) ? $relation['foreignClass']:$className; - $newRelation['alias'] = isset($relation['foreignAlias']) ? $relation['foreignAlias']:$className; + $newRelation['class'] = isset($relation['foreignClass']) ? $relation['foreignClass'] : $className; + $newRelation['alias'] = isset($relation['foreignAlias']) ? $relation['foreignAlias'] : $className; $newRelation['foreignAlias'] = $alias; - + // this is so that we know that this relation was autogenerated and // that we do not need to include it if it is explicitly declared in the schema by the users. - $newRelation['autogenerated'] = true; - + $newRelation['autogenerated'] = true; + if (isset($relation['refClass'])) { $newRelation['refClass'] = $relation['refClass']; - $newRelation['type'] = isset($relation['foreignType']) ? $relation['foreignType']:$relation['type']; - } else { + $newRelation['type'] = isset($relation['foreignType']) ? $relation['foreignType'] : $relation['type']; + } else { if (isset($relation['foreignType'])) { $newRelation['type'] = $relation['foreignType']; } else { - $newRelation['type'] = $relation['type'] === Doctrine_Relation::ONE ? Doctrine_Relation::MANY:Doctrine_Relation::ONE; + $newRelation['type'] = Doctrine_Relation::ONE === $relation['type'] ? Doctrine_Relation::MANY : Doctrine_Relation::ONE; } } // Make sure it doesn't already exist - if ( ! isset($this->_relations[$relation['class']][$newRelation['alias']])) { + if (!isset($this->_relations[$relation['class']][$newRelation['alias']])) { $newRelation['key'] = $this->_buildUniqueRelationKey($newRelation); $this->_relations[$relation['class']][$newRelation['alias']] = $newRelation; } @@ -696,55 +685,50 @@ protected function _autoCompleteOppositeRelations() } /** - * _fixDuplicateRelations + * _fixDuplicateRelations. * * Ensure the relations for each class are unique and that no duplicated relations exist from the auto generated relations * and the user explicitely defining the opposite end - * - * @return void */ protected function _fixDuplicateRelations() { - foreach($this->_relations as $className => $relations) { + foreach ($this->_relations as $className => $relations) { // This is for checking for duplicates between alias-relations and a auto-generated relations to ensure the result set of unique relations $existingRelations = array(); $uniqueRelations = array(); foreach ($relations as $relation) { - if ( ! in_array($relation['key'], $existingRelations)) { + if (!in_array($relation['key'], $existingRelations)) { $existingRelations[] = $relation['key']; $uniqueRelations = array_merge($uniqueRelations, array($relation['alias'] => $relation)); } else { // check to see if this relationship is not autogenerated, if it's not, then the user must have explicitly declared it - if ( ! isset($relation['autogenerated']) || $relation['autogenerated'] != true) { + if (!isset($relation['autogenerated']) || true != $relation['autogenerated']) { $uniqueRelations = array_merge($uniqueRelations, array($relation['alias'] => $relation)); } } } - + $this->_relations[$className] = $uniqueRelations; } } /** - * _buildUniqueRelationKey + * _buildUniqueRelationKey. * * Build a unique key to identify a relationship by * Md5 hash of all the relationship parameters * - * @param string $relation - * @return void + * @param string $relation */ protected function _buildUniqueRelationKey($relation) { - return md5($relation['local'].$relation['foreign'].$relation['class'].(isset($relation['refClass']) ? $relation['refClass']:null)); + return md5($relation['local'].$relation['foreign'].$relation['class'].(isset($relation['refClass']) ? $relation['refClass'] : null)); } /** - * _validateSchemaElement + * _validateSchemaElement. * - * @param string $name - * @param string $value - * @return void + * @param string $name */ protected function _validateSchemaElement($name, $element, $path) { @@ -754,18 +738,16 @@ protected function _validateSchemaElement($name, $element, $path) // Validators are a part of the column validation // This should be fixed, made cleaner - if ($name == 'column') { + if ('column' == $name) { $validators = Doctrine_Manager::getInstance()->getValidators(); $validation = array_merge($validation, $validators); } $validation = array_flip($validation); foreach ($element as $key => $value) { - if ( ! isset($validation[$value])) { - throw new Doctrine_Import_Exception( - sprintf('Invalid schema element named "' . $value . '" at path "' . $path . '"') - ); + if (!isset($validation[$value])) { + throw new Doctrine_Import_Exception(sprintf('Invalid schema element named "'.$value.'" at path "'.$path.'"')); } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Import/Sqlite.php b/lib/Doctrine/Import/Sqlite.php index f6d686da6..6f854d6d3 100644 --- a/lib/Doctrine/Import/Sqlite.php +++ b/lib/Doctrine/Import/Sqlite.php @@ -20,57 +20,56 @@ */ /** - * @package Doctrine - * @subpackage Import * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) + * * @version $Revision: 7644 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Import_Sqlite extends Doctrine_Import { /** - * lists all databases + * lists all databases. * * @return array */ public function listDatabases() { - } /** - * lists all availible database functions + * lists all availible database functions. * * @return array */ public function listFunctions() { - } /** - * lists all database triggers + * lists all database triggers. * * @param string|null $database + * * @return array */ public function listTriggers($database = null) { - } /** - * lists all database sequences + * lists all database sequences. * * @param string|null $database + * * @return array */ public function listSequences($database = null) { - $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"; + $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name"; $tableNames = $this->conn->fetchColumn($query); $result = array(); @@ -80,15 +79,17 @@ public function listSequences($database = null) } } if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - $result = array_map(($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); + $result = array_map(CASE_LOWER == $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) ? 'strtolower' : 'strtoupper', $result); } + return $result; } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableConstraints($table) @@ -98,18 +99,18 @@ public function listTableConstraints($table) $query = "SELECT sql FROM sqlite_master WHERE type='index' AND "; if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { - $query .= 'LOWER(tbl_name) = ' . strtolower($table); + $query .= 'LOWER(tbl_name) = '.strtolower($table); } else { - $query .= 'tbl_name = ' . $table; + $query .= 'tbl_name = '.$table; } - $query .= ' AND sql NOT NULL ORDER BY name'; + $query .= ' AND sql NOT NULL ORDER BY name'; $indexes = $this->conn->fetchColumn($query); $result = array(); foreach ($indexes as $sql) { - if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) { + if (preg_match('/^create unique index ([^ ]+) on /i', $sql, $tmp)) { $index = $this->conn->formatter->fixIndexName($tmp[1]); - if ( ! empty($index)) { + if (!empty($index)) { $result[$index] = true; } } @@ -118,86 +119,94 @@ public function listTableConstraints($table) if ($this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE) && ($this->conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_FIX_CASE)) { $result = array_change_key_case($result, $this->conn->getAttribute(Doctrine_Core::ATTR_FIELD_CASE)); } + return array_keys($result); } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableColumns($table) { - $sql = 'PRAGMA table_info(' . $table . ')'; + $sql = 'PRAGMA table_info('.$table.')'; $result = $this->conn->fetchAll($sql); $description = array(); - $columns = array(); + $columns = array(); foreach ($result as $key => $val) { $val = array_change_key_case($val, CASE_LOWER); $decl = $this->conn->dataDict->getPortableDeclaration($val); $description = array( - 'name' => $val['name'], - 'ntype' => $val['type'], - 'type' => $decl['type'][0], - 'alltypes' => $decl['type'], - 'notnull' => (bool) $val['notnull'], - 'default' => $val['dflt_value'], - 'primary' => (bool) $val['pk'], - 'length' => null, - 'scale' => null, - 'precision' => null, - 'unsigned' => null, - 'autoincrement' => (bool) ($val['pk'] == 1 && $decl['type'][0] == 'integer'), - ); + 'name' => $val['name'], + 'ntype' => $val['type'], + 'type' => $decl['type'][0], + 'alltypes' => $decl['type'], + 'notnull' => (bool) $val['notnull'], + 'default' => $val['dflt_value'], + 'primary' => (bool) $val['pk'], + 'length' => null, + 'scale' => null, + 'precision' => null, + 'unsigned' => null, + 'autoincrement' => (bool) (1 == $val['pk'] && 'integer' == $decl['type'][0]), + ); $columns[$val['name']] = $description; } + return $columns; } /** - * lists table constraints + * lists table constraints. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableIndexes($table) { - $sql = 'PRAGMA index_list(' . $table . ')'; + $sql = 'PRAGMA index_list('.$table.')'; + return $this->conn->fetchColumn($sql); - } + } + /** - * lists tables + * lists tables. * * @param string|null $database + * * @return array */ public function listTables($database = null) { $sql = "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'sqlite_sequence' " - . "UNION ALL SELECT name FROM sqlite_temp_master " - . "WHERE type = 'table' ORDER BY name"; + .'UNION ALL SELECT name FROM sqlite_temp_master ' + ."WHERE type = 'table' ORDER BY name"; return $this->conn->fetchColumn($sql); } /** - * lists table triggers + * lists table triggers. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableTriggers($table) { - } /** - * lists table views + * lists table views. + * + * @param string $table database table name * - * @param string $table database table name * @return array */ public function listTableViews($table) @@ -207,29 +216,30 @@ public function listTableViews($table) $result = array(); foreach ($views as $row) { - if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) { - if ( ! empty($row['name'])) { + if (preg_match("/^create view .* \\bfrom\\b\\s+\\b{$table}\\b /i", $row['sql'])) { + if (!empty($row['name'])) { $result[$row['name']] = true; } } } + return $result; } /** - * lists database users + * lists database users. * * @return array */ public function listUsers() { - } /** - * lists database views + * lists database views. * * @param string|null $database + * * @return array */ public function listViews($database = null) @@ -238,4 +248,4 @@ public function listViews($database = null) return $this->conn->fetchColumn($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Inflector.php b/lib/Doctrine/Inflector.php index 25bb984e2..df86f3625 100644 --- a/lib/Doctrine/Inflector.php +++ b/lib/Doctrine/Inflector.php @@ -20,27 +20,29 @@ */ /** - * Doctrine inflector has static methods for inflecting text + * Doctrine inflector has static methods for inflecting text. * * The methods in these classes are from several different sources collected * across several different php projects and several different authors. The * original author names and emails are not known * - * @package Doctrine - * @subpackage Inflector * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3189 $ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Inflector { /** - * Convert word in to the format for a Doctrine table name. Converts 'ModelName' to 'model_name' + * Convert word in to the format for a Doctrine table name. Converts 'ModelName' to 'model_name'. + * + * @param string $word Word to tableize * - * @param string $word Word to tableize * @return string $word Tableized word */ public static function tableize($word) @@ -49,9 +51,10 @@ public static function tableize($word) } /** - * Convert a word in to the format for a Doctrine class name. Converts 'table_name' to 'TableName' + * Convert a word in to the format for a Doctrine class name. Converts 'table_name' to 'TableName'. + * + * @param string $word Word to classify * - * @param string $word Word to classify * @return string $word Classified word */ public static function classify($word) @@ -60,196 +63,217 @@ public static function classify($word) if (!isset($cache[$word])) { $word = preg_replace('/[$]/', '', $word); - $classify = preg_replace_callback('~(_?)([-_])([\w])~', array("Doctrine_Inflector", "classifyCallback"), ucfirst(strtolower($word))); + $classify = preg_replace_callback('~(_?)([-_])([\w])~', array('Doctrine_Inflector', 'classifyCallback'), ucfirst(strtolower($word))); $cache[$word] = $classify; } + return $cache[$word]; } /** * Callback function to classify a classname properly. * - * @param array $matches An array of matches from a pcre_replace call - * @return string $string A string with matches 1 and mathces 3 in upper case. + * @param array $matches An array of matches from a pcre_replace call + * + * @return string $string a string with matches 1 and mathces 3 in upper case */ public static function classifyCallback($matches) { - return $matches[1] . strtoupper($matches[3]); + return $matches[1].strtoupper($matches[3]); } /** - * Check if a string has utf7 characters in it + * Check if a string has utf7 characters in it. * * By bmorel at ssi dot fr * - * @param string $string - * @return boolean $bool + * @param string $string + * + * @return bool $bool */ public static function seemsUtf8($string) { - for ($i = 0; $i < strlen($string); $i++) { - if (ord($string[$i]) < 0x80) continue; # 0bbbbbbb - elseif ((ord($string[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb - elseif ((ord($string[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb - elseif ((ord($string[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb - elseif ((ord($string[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb - elseif ((ord($string[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b - else return false; # Does not match any model - for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ? - if ((++$i == strlen($string)) || ((ord($string[$i]) & 0xC0) != 0x80)) - return false; + for ($i = 0; $i < strlen($string); ++$i) { + if (ord($string[$i]) < 0x80) { + continue; + } // 0bbbbbbb + if ((ord($string[$i]) & 0xE0) == 0xC0) { + $n = 1; + } // 110bbbbb + elseif ((ord($string[$i]) & 0xF0) == 0xE0) { + $n = 2; + } // 1110bbbb + elseif ((ord($string[$i]) & 0xF8) == 0xF0) { + $n = 3; + } // 11110bbb + elseif ((ord($string[$i]) & 0xFC) == 0xF8) { + $n = 4; + } // 111110bb + elseif ((ord($string[$i]) & 0xFE) == 0xFC) { + $n = 5; + } // 1111110b + else { + return false; + } // Does not match any model + for ($j = 0; $j < $n; ++$j) { // n bytes matching 10bbbbbb follow ? + if ((++$i == strlen($string)) || ((ord($string[$i]) & 0xC0) != 0x80)) { + return false; + } + } } - } - return true; + + return true; } /** * Remove any illegal characters, accents, etc. * - * @param string $string String to unaccent + * @param string $string String to unaccent + * * @return string $string Unaccented string */ public static function unaccent($string) { - if ( ! preg_match('/[\x80-\xff]/', $string) ) { - return $string; - } + if (!preg_match('/[\x80-\xff]/', $string)) { + return $string; + } if (self::seemsUtf8($string)) { - $chars = array( - // Decompositions for Latin-1 Supplement - chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', - chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', - chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', - chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', - chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', - chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', - chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', - chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', - chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', - chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', - chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', - chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', - chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', - chr(195).chr(159) => 's', chr(195).chr(160) => 'a', - chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', - chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', - chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', - chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', - chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', - chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', - chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', - chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', - chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', - chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', - chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', - chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', - chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', - chr(195).chr(191) => 'y', - // Decompositions for Latin Extended-A - chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', - chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', - chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', - chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', - chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', - chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', - chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', - chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', - chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', - chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', - chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', - chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', - chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', - chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', - chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', - chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', - chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', - chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', - chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', - chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', - chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', - chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', - chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', - chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', - chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', - chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij', - chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', - chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', - chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', - chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', - chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', - chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', - chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', - chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', - chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', - chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', - chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', - chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', - chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', - chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', - chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', - chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe', - chr(197).chr(148) => 'R', chr(197).chr(149) => 'r', - chr(197).chr(150) => 'R', chr(197).chr(151) => 'r', - chr(197).chr(152) => 'R', chr(197).chr(153) => 'r', - chr(197).chr(154) => 'S', chr(197).chr(155) => 's', - chr(197).chr(156) => 'S', chr(197).chr(157) => 's', - chr(197).chr(158) => 'S', chr(197).chr(159) => 's', - chr(197).chr(160) => 'S', chr(197).chr(161) => 's', - chr(197).chr(162) => 'T', chr(197).chr(163) => 't', - chr(197).chr(164) => 'T', chr(197).chr(165) => 't', - chr(197).chr(166) => 'T', chr(197).chr(167) => 't', - chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', - chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', - chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', - chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', - chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', - chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', - chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', - chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', - chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', - chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', - chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', - chr(197).chr(190) => 'z', chr(197).chr(191) => 's', - // Euro Sign - chr(226).chr(130).chr(172) => 'E', - // GBP (Pound) Sign - chr(194).chr(163) => '', - 'Ä' => 'Ae', 'ä' => 'ae', 'Ü' => 'Ue', 'ü' => 'ue', - 'Ö' => 'Oe', 'ö' => 'oe', 'ß' => 'ss', - // Norwegian characters - 'Å'=>'Aa','Æ'=>'Ae','Ø'=>'O','æ'=>'a','ø'=>'o','å'=>'aa' - ); + $chars = array( + // Decompositions for Latin-1 Supplement + chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', + chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', + chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', + chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', + chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', + chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', + chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', + chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', + chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', + chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', + chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', + chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', + chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', + chr(195).chr(159) => 's', chr(195).chr(160) => 'a', + chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', + chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', + chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', + chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', + chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', + chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', + chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', + chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', + chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', + chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', + chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', + chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', + chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', + chr(195).chr(191) => 'y', + // Decompositions for Latin Extended-A + chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', + chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', + chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', + chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', + chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', + chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', + chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', + chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', + chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', + chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', + chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', + chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', + chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', + chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', + chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', + chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', + chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', + chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', + chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', + chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', + chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', + chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', + chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', + chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', + chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', + chr(196).chr(178) => 'IJ', chr(196).chr(179) => 'ij', + chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', + chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', + chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', + chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', + chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', + chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', + chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', + chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', + chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', + chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', + chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', + chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', + chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', + chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', + chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', + chr(197).chr(146) => 'OE', chr(197).chr(147) => 'oe', + chr(197).chr(148) => 'R', chr(197).chr(149) => 'r', + chr(197).chr(150) => 'R', chr(197).chr(151) => 'r', + chr(197).chr(152) => 'R', chr(197).chr(153) => 'r', + chr(197).chr(154) => 'S', chr(197).chr(155) => 's', + chr(197).chr(156) => 'S', chr(197).chr(157) => 's', + chr(197).chr(158) => 'S', chr(197).chr(159) => 's', + chr(197).chr(160) => 'S', chr(197).chr(161) => 's', + chr(197).chr(162) => 'T', chr(197).chr(163) => 't', + chr(197).chr(164) => 'T', chr(197).chr(165) => 't', + chr(197).chr(166) => 'T', chr(197).chr(167) => 't', + chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', + chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', + chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', + chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', + chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', + chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', + chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', + chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', + chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', + chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', + chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', + chr(197).chr(190) => 'z', chr(197).chr(191) => 's', + // Euro Sign + chr(226).chr(130).chr(172) => 'E', + // GBP (Pound) Sign + chr(194).chr(163) => '', + 'Ä' => 'Ae', 'ä' => 'ae', 'Ü' => 'Ue', 'ü' => 'ue', + 'Ö' => 'Oe', 'ö' => 'oe', 'ß' => 'ss', + // Norwegian characters + 'Å' => 'Aa', 'Æ' => 'Ae', 'Ø' => 'O', 'æ' => 'a', 'ø' => 'o', 'å' => 'aa', + ); - $string = strtr($string, $chars); + $string = strtr($string, $chars); } else { - // Assume ISO-8859-1 if not UTF-8 - $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158) - .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194) - .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202) - .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210) - .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218) - .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227) - .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235) - .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243) - .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251) - .chr(252).chr(253).chr(255); + // Assume ISO-8859-1 if not UTF-8 + $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158) + .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194) + .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202) + .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210) + .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218) + .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227) + .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235) + .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243) + .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251) + .chr(252).chr(253).chr(255); - $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy"; + $chars['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'; - $string = strtr($string, $chars['in'], $chars['out']); - $doubleChars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254)); - $doubleChars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); - $string = str_replace($doubleChars['in'], $doubleChars['out'], $string); + $string = strtr($string, $chars['in'], $chars['out']); + $doubleChars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254)); + $doubleChars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); + $string = str_replace($doubleChars['in'], $doubleChars['out'], $string); } return $string; } /** - * Convert any passed string to a url friendly string. Converts 'My first blog post' to 'my-first-blog-post' + * Convert any passed string to a url friendly string. Converts 'My first blog post' to 'my-first-blog-post'. + * + * @param string $text Text to urlize * - * @param string $text Text to urlize * @return string $text Urlized text */ public static function urlize($text) @@ -257,8 +281,7 @@ public static function urlize($text) // Remove all non url friendly characters with the unaccent function $text = self::unaccent($text); - if (function_exists('mb_strtolower')) - { + if (function_exists('mb_strtolower')) { $text = mb_strtolower($text); } else { $text = strtolower($text); @@ -269,10 +292,10 @@ public static function urlize($text) // More stripping. Replace spaces with dashes $text = strtolower(preg_replace('/[^A-Z^a-z^0-9^\/]+/', '-', - preg_replace('/([a-z\d])([A-Z])/', '\1_\2', - preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', - preg_replace('/::/', '/', $text))))); + preg_replace('/([a-z\d])([A-Z])/', '\1_\2', + preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', + preg_replace('/::/', '/', $text))))); return trim($text, '-'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/IntegrityMapper.php b/lib/Doctrine/IntegrityMapper.php index 9680b7eed..75b277032 100644 --- a/lib/Doctrine/IntegrityMapper.php +++ b/lib/Doctrine/IntegrityMapper.php @@ -20,75 +20,69 @@ */ /** - * Doctrine_IntegrityMapper + * Doctrine_IntegrityMapper. * - * @package Doctrine - * @subpackage IntegrityMapper * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ -class Doctrine_IntegrityMapper +class Doctrine_IntegrityMapper { /** - * processDeleteIntegrity - * - * @param Doctrine_Record $record - * @return void + * processDeleteIntegrity. */ public function processDeleteIntegrity(Doctrine_Record $record) { $coll = $this->buildIntegrityRelationQuery($record); - + $this->invokeIntegrityActions($record); } /** - * invokeIntegrityActions - * - * @param Doctrine_Record $record - * @return void + * invokeIntegrityActions. */ public function invokeIntegrityActions(Doctrine_Record $record) { $deleteActions = Doctrine_Manager::getInstance() - ->getDeleteActions($record->getTable()->getComponentName()); - + ->getDeleteActions($record->getTable()->getComponentName()) + ; + foreach ($record->getTable()->getRelations() as $relation) { $componentName = $relation->getTable()->getComponentName(); - - foreach($record->get($relation->getAlias()) as $coll) { - if ( ! ($coll instanceof Doctrine_Collection)) { + + foreach ($record->get($relation->getAlias()) as $coll) { + if (!($coll instanceof Doctrine_Collection)) { $coll = array($coll); } foreach ($coll as $record) { $this->invokeIntegrityActions($record); if (isset($deleteActions[$componentName])) { - if ($deleteActions[$componentName] === 'SET NULL') { + if ('SET NULL' === $deleteActions[$componentName]) { $record->set($relation->getForeign(), null); - } elseif ($deleteActions[$componentName] === 'CASCADE') { + } elseif ('CASCADE' === $deleteActions[$componentName]) { $this->conn->transaction->addDelete($record); } } - } } } } /** - * buildIntegrityRelationQuery - * - * @param Doctrine_Record $record + * buildIntegrityRelationQuery. + * * @return array The result */ public function buildIntegrityRelationQuery(Doctrine_Record $record) { $q = $record->getTable()->createQuery(); - + $aliases = array(); $indexes = array(); @@ -97,19 +91,19 @@ public function buildIntegrityRelationQuery(Doctrine_Record $record) $aliases[$rootAlias] = $root; foreach ((array) $record->getTable()->getIdentifier() as $id) { - $field = $rootAlias . '.' . $id; - $cond[] = $field . ' = ?'; + $field = $rootAlias.'.'.$id; + $cond[] = $field.' = ?'; $fields[] = $field; - $params = $record->get($id); + $params = $record->get($id); } $fields = implode(', ', $fields); $components[] = $root; $this->buildIntegrityRelations($record->getTable(), $aliases, $fields, $indexes, $components); - $q->select($fields)->from($root. ' ' . $rootAlias); + $q->select($fields)->from($root.' '.$rootAlias); foreach ($aliases as $alias => $name) { - $q->leftJoin($rootAlias . '.' . $name . ' ' . $alias); + $q->leftJoin($rootAlias.'.'.$name.' '.$alias); } $q->where(implode(' AND ', $cond)); @@ -117,19 +111,13 @@ public function buildIntegrityRelationQuery(Doctrine_Record $record) } /** - * buildIntegrityRelations - * - * @param Doctrine_Table $table - * @param mixed $aliases - * @param mixed $fields - * @param mixed $indexes - * @param mixed $components - * @return void + * buildIntegrityRelations. */ public function buildIntegrityRelations(Doctrine_Table $table, &$aliases, &$fields, &$indexes, &$components) { $deleteActions = Doctrine_Manager::getInstance() - ->getDeleteActions($table->getComponentName()); + ->getDeleteActions($table->getComponentName()) + ; foreach ($table->getRelations() as $relation) { $componentName = $relation->getTable()->getComponentName(); @@ -140,31 +128,31 @@ public function buildIntegrityRelations(Doctrine_Table $table, &$aliases, &$fiel $alias = strtolower(substr($relation->getAlias(), 0, 1)); - if ( ! isset($indexes[$alias])) { + if (!isset($indexes[$alias])) { $indexes[$alias] = 1; } if (isset($deleteActions[$componentName])) { if (isset($aliases[$alias])) { - $alias = $alias . ++$indexes[$alias]; + $alias = $alias.++$indexes[$alias]; } $aliases[$alias] = $relation->getAlias(); - if ($deleteActions[$componentName] === 'SET NULL') { + if ('SET NULL' === $deleteActions[$componentName]) { if ($relation instanceof Doctrine_Relation_ForeignKey) { foreach ((array) $relation->getForeign() as $foreign) { - $fields .= ', ' . $alias . '.' . $foreign; + $fields .= ', '.$alias.'.'.$foreign; } } elseif ($relation instanceof Doctrine_Relation_LocalKey) { foreach ((array) $relation->getLocal() as $foreign) { - $fields .= ', ' . $alias . '.' . $foreign; + $fields .= ', '.$alias.'.'.$foreign; } } } foreach ((array) $relation->getTable()->getIdentifier() as $id) { - $fields .= ', ' . $alias . '.' . $id; + $fields .= ', '.$alias.'.'.$id; } - if ($deleteActions[$componentName] === 'CASCADE') { + if ('CASCADE' === $deleteActions[$componentName]) { $this->buildIntegrityRelations($relation->getTable(), $aliases, $fields, $indexes, $components); } } diff --git a/lib/Doctrine/Lib.php b/lib/Doctrine/Lib.php index 97d740026..b979cebf1 100644 --- a/lib/Doctrine/Lib.php +++ b/lib/Doctrine/Lib.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Lib has not commonly used static functions, mostly for debugging purposes + * Doctrine_Lib has not commonly used static functions, mostly for debugging purposes. * - * @package Doctrine - * @subpackage Lib * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Lib @@ -37,28 +38,30 @@ class Doctrine_Lib * * This method translates a Doctrine_Record state (integer constant) * in an english string. + * * @see Doctrine_Record::STATE_* constants * - * @param integer $state the state of record - * @return string description of given state + * @param int $state the state of record + * + * @return string description of given state */ public static function getRecordStateAsString($state) { switch ($state) { case Doctrine_Record::STATE_PROXY: - return "proxy"; + return 'proxy'; break; case Doctrine_Record::STATE_CLEAN: - return "persistent clean"; + return 'persistent clean'; break; case Doctrine_Record::STATE_DIRTY: - return "persistent dirty"; + return 'persistent dirty'; break; case Doctrine_Record::STATE_TDIRTY: - return "transient dirty"; + return 'transient dirty'; break; case Doctrine_Record::STATE_TCLEAN: - return "transient clean"; + return 'transient clean'; break; } } @@ -69,21 +72,20 @@ public static function getRecordStateAsString($state) * This method returns an html representation of a given * record, containing keys, state and data. * - * @param Doctrine_Record $record * @return string */ public static function getRecordAsString(Doctrine_Record $record) { $r[] = '
';
-        $r[] = 'Component  : ' . $record->getTable()->getComponentName();
-        $r[] = 'ID         : ' . Doctrine_Core::dump($record->identifier());
-        $r[] = 'References : ' . count($record->getReferences());
-        $r[] = 'State      : ' . Doctrine_Lib::getRecordStateAsString($record->state());
-        $r[] = 'OID        : ' . $record->getOID();
-        $r[] = 'data       : ' . Doctrine_Core::dump($record->getData(), false);
+        $r[] = 'Component  : '.$record->getTable()->getComponentName();
+        $r[] = 'ID         : '.Doctrine_Core::dump($record->identifier());
+        $r[] = 'References : '.count($record->getReferences());
+        $r[] = 'State      : '.Doctrine_Lib::getRecordStateAsString($record->state());
+        $r[] = 'OID        : '.$record->getOID();
+        $r[] = 'data       : '.Doctrine_Core::dump($record->getData(), false);
         $r[] = '
'; - return implode("\n",$r)."
"; + return implode("\n", $r).'
'; } /** @@ -91,21 +93,24 @@ public static function getRecordAsString(Doctrine_Record $record) * * This method translates a Doctrine_Connection state (integer constant) * in a english description. + * * @see Doctrine_Transaction::STATE_* constants - * @param integer $state state of the connection as a string + * + * @param int $state state of the connection as a string + * * @return string */ public static function getConnectionStateAsString($state) { switch ($state) { case Doctrine_Transaction::STATE_SLEEP: - return "open"; + return 'open'; break; case Doctrine_Transaction::STATE_BUSY: - return "busy"; + return 'busy'; break; case Doctrine_Transaction::STATE_ACTIVE: - return "active"; + return 'active'; break; } } @@ -116,20 +121,19 @@ public static function getConnectionStateAsString($state) * This method returns an html dump of a connection, containing state, open * transactions and loaded tables. * - * @param Doctrine_Connection $connection * @return string */ public static function getConnectionAsString(Doctrine_Connection $connection) { $r[] = '
';
         $r[] = 'Doctrine_Connection object';
-        $r[] = 'State               : ' . Doctrine_Lib::getConnectionStateAsString($connection->transaction->getState());
-        $r[] = 'Open Transactions   : ' . $connection->transaction->getTransactionLevel();
-        $r[] = 'Table in memory     : ' . $connection->count();
-        $r[] = 'Driver name         : ' . $connection->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME);
-        $r[] = "
"; + $r[] = 'State : '.Doctrine_Lib::getConnectionStateAsString($connection->transaction->getState()); + $r[] = 'Open Transactions : '.$connection->transaction->getTransactionLevel(); + $r[] = 'Table in memory : '.$connection->count(); + $r[] = 'Driver name : '.$connection->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME); + $r[] = ''; - return implode("\n",$r)."
"; + return implode("\n", $r).'
'; } /** @@ -137,17 +141,17 @@ public static function getConnectionAsString(Doctrine_Connection $connection) * * This method returns an html dump of a table, containing component name * and table physical name. - * @param Doctrine_Table $table + * * @return string */ public static function getTableAsString(Doctrine_Table $table) { - $r[] = "
";
-        $r[] = "Component   : ".$table->getComponentName();
-        $r[] = "Table       : ".$table->getTableName();
-        $r[] = "
"; + $r[] = '
';
+        $r[] = 'Component   : '.$table->getComponentName();
+        $r[] = 'Table       : '.$table->getTableName();
+        $r[] = '
'; - return implode("\n",$r)."
"; + return implode("\n", $r).'
'; } /** @@ -157,29 +161,30 @@ public static function getTableAsString(Doctrine_Table $table) * for visual formatting. * * @todo: What about creating a config varialbe for the color? - * @param string $sql plain text query - * @return string the formatted sql code + * + * @param string $sql plain text query + * + * @return string the formatted sql code */ public static function formatSql($sql) { - $e = explode("\n",$sql); - $color = "367FAC"; + $e = explode("\n", $sql); + $color = '367FAC'; $l = $sql; - $l = str_replace("SELECT ", "SELECT
",$l); - $l = str_replace("FROM ", "FROM
",$l); - $l = str_replace(" LEFT JOIN ", "
LEFT JOIN ",$l); - $l = str_replace(" INNER JOIN ", "
INNER JOIN ",$l); - $l = str_replace(" WHERE ", "
WHERE ",$l); - $l = str_replace(" GROUP BY ", "
GROUP BY ",$l); - $l = str_replace(" HAVING ", "
HAVING ",$l); - $l = str_replace(" AS ", " AS
",$l); - $l = str_replace(" ON ", " ON ",$l); - $l = str_replace(" ORDER BY ", " ORDER BY
",$l); - $l = str_replace(" LIMIT ", " LIMIT
",$l); - $l = str_replace(" OFFSET ", " OFFSET
",$l); - $l = str_replace(" ", "
",$l); - - return $l; + $l = str_replace('SELECT ', "SELECT
", $l); + $l = str_replace('FROM ', "FROM
", $l); + $l = str_replace(' LEFT JOIN ', "
LEFT JOIN ", $l); + $l = str_replace(' INNER JOIN ', "
INNER JOIN ", $l); + $l = str_replace(' WHERE ', "
WHERE ", $l); + $l = str_replace(' GROUP BY ', "
GROUP BY ", $l); + $l = str_replace(' HAVING ', "
HAVING ", $l); + $l = str_replace(' AS ', " AS
", $l); + $l = str_replace(' ON ', " ON ", $l); + $l = str_replace(' ORDER BY ', " ORDER BY
", $l); + $l = str_replace(' LIMIT ', " LIMIT
", $l); + $l = str_replace(' OFFSET ', " OFFSET
", $l); + + return str_replace(' ', '
', $l); } /** @@ -188,18 +193,17 @@ public static function formatSql($sql) * This method returns an html dump of a collection of records, containing * all data. * - * @param Doctrine_Collection $collection * @return string */ public static function getCollectionAsString(Doctrine_Collection $collection) { - $r[] = "
";
+        $r[] = '
';
         $r[] = get_class($collection);
-        $r[] = 'data : ' . Doctrine_Core::dump($collection->getData(), false);
-        //$r[] = 'snapshot : ' . Doctrine_Core::dump($collection->getSnapshot());
-        $r[] = "
"; + $r[] = 'data : '.Doctrine_Core::dump($collection->getData(), false); + // $r[] = 'snapshot : ' . Doctrine_Core::dump($collection->getSnapshot()); + $r[] = '
'; - return implode("\n",$r); + return implode("\n", $r); } // Code from symfony sfToolkit class. See LICENSE @@ -224,52 +228,50 @@ public static function getCollectionAsString(Doctrine_Collection $collection) * Different from array_merge * If string keys have arrays for values, these arrays will merge recursively. */ - public static function arrayDeepMerge() - { - switch (func_num_args()) { - case 0: + public static function arrayDeepMerge() + { + switch (func_num_args()) { + case 0: return false; - case 1: + case 1: return func_get_arg(0); - case 2: + case 2: $args = func_get_args(); $args[2] = array(); - if (is_array($args[0]) && is_array($args[1])) - { - foreach (array_unique(array_merge(array_keys($args[0]),array_keys($args[1]))) as $key) - { + if (is_array($args[0]) && is_array($args[1])) { + foreach (array_unique(array_merge(array_keys($args[0]), array_keys($args[1]))) as $key) { $isKey0 = array_key_exists($key, $args[0]); $isKey1 = array_key_exists($key, $args[1]); - if ($isKey0 && $isKey1 && is_array($args[0][$key]) && is_array($args[1][$key])) - { + if ($isKey0 && $isKey1 && is_array($args[0][$key]) && is_array($args[1][$key])) { $args[2][$key] = self::arrayDeepMerge($args[0][$key], $args[1][$key]); - } else if ($isKey0 && $isKey1) { + } elseif ($isKey0 && $isKey1) { $args[2][$key] = $args[1][$key]; - } else if ( ! $isKey1) { + } elseif (!$isKey1) { $args[2][$key] = $args[0][$key]; - } else if ( ! $isKey0) { + } elseif (!$isKey0) { $args[2][$key] = $args[1][$key]; } } return $args[2]; - } else { - return $args[1]; } + + return $args[1]; + default: $args = func_get_args(); $args[1] = self::arrayDeepMerge($args[0], $args[1]); array_shift($args); return call_user_func_array(array('Doctrine_Lib', 'arrayDeepMerge'), $args); - break; + break; } } /** - * arrayDiffSimple + * arrayDiffSimple. * * array arrayDiffSimple ( array array1 , array array2 ) * @@ -285,19 +287,20 @@ public static function arrayDeepMerge() * * @param array $array1 * @param array $array2 + * * @static - * @access public + * * @return array */ public static function arrayDiffSimple($array1, $array2) { $diff = array(); - foreach($array1 as $key => $val) { - if(!isset($array2[$key])) { + foreach ($array1 as $key => $val) { + if (!isset($array2[$key])) { $diff[$key] = $val; } else { - if(is_array($array2[$key]) && !is_array($val)) { + if (is_array($array2[$key]) && !is_array($val)) { $diff[$key] = $val; } } @@ -313,18 +316,19 @@ public static function arrayDiffSimple($array1, $array2) * that do not exist yet. Equivalent to 'mkdir -p'. * * @param string $path - * @param integer $mode an integer (octal) chmod parameter for the - * created directories - * @return boolean true if succeeded + * @param int $mode an integer (octal) chmod parameter for the + * created directories + * + * @return bool true if succeeded */ public static function makeDirectories($path, $mode = 0777) { - if ( ! $path) { - return false; + if (!$path) { + return false; } if (is_dir($path) || is_file($path)) { - return true; + return true; } return mkdir(trim($path), $mode, true); @@ -337,30 +341,28 @@ public static function makeDirectories($path, $mode = 0777) * Equivalent to 'rm -rf'. * * @param string $folderPath - * @return boolean success of the operation + * + * @return bool success of the operation */ public static function removeDirectories($folderPath) { - if (is_dir($folderPath)) - { - foreach (scandir($folderPath) as $value) - { - if ($value != '.' && $value != '..') - { - $value = $folderPath . "/" . $value; + if (is_dir($folderPath)) { + foreach (scandir($folderPath) as $value) { + if ('.' != $value && '..' != $value) { + $value = $folderPath.'/'.$value; if (is_dir($value)) { self::removeDirectories($value); - } else if (is_file($value)) { + } elseif (is_file($value)) { unlink($value); } } } return rmdir($folderPath); - } else { - return false; } + + return false; } /** @@ -369,9 +371,8 @@ public static function removeDirectories($folderPath) * This method recursively copies all $source files and subdirs in $dest. * If $source is a file, only it will be copied in $dest. * - * @param string $source a directory path - * @param string $dest a directory path - * @return + * @param string $source a directory path + * @param string $dest a directory path */ public static function copyDirectory($source, $dest) { @@ -381,7 +382,7 @@ public static function copyDirectory($source, $dest) } // Make destination directory - if ( ! is_dir($dest)) { + if (!is_dir($dest)) { mkdir($dest); } @@ -389,13 +390,13 @@ public static function copyDirectory($source, $dest) $dir = dir($source); while (false !== $entry = $dir->read()) { // Skip pointers - if ($entry == '.' || $entry == '..') { + if ('.' == $entry || '..' == $entry) { continue; } // Deep copy directories - if ($dest !== "$source/$entry") { - self::copyDirectory("$source/$entry", "$dest/$entry"); + if ($dest !== "{$source}/{$entry}") { + self::copyDirectory("{$source}/{$entry}", "{$dest}/{$entry}"); } } @@ -412,8 +413,7 @@ public static function copyDirectory($source, $dest) * and for Doctrine coding standards. $className must use camel case naming * and underscores for directory separation. * - * @param string $classname - * @return boolean + * @return bool */ public static function isValidClassName($className) { diff --git a/lib/Doctrine/Locator.php b/lib/Doctrine/Locator.php index 8b4d2817f..79c31784a 100644 --- a/lib/Doctrine/Locator.php +++ b/lib/Doctrine/Locator.php @@ -1,6 +1,6 @@ * @author Konsta Vesterinen * @author Eevert Saukkokoski + * * @version $Revision$ + * * @since 1.0 */ class Doctrine_Locator implements Countable, IteratorAggregate { /** - * @var array $_resources an array of bound resources + * @var array an array of bound resources */ protected $_resources = array(); /** - * @var string $_classPrefix the default class prefix + * @var string the default class prefix */ protected $_classPrefix = 'Doctrine_'; /** - * @var array $_instances a pool of this object's instances + * @var array a pool of this object's instances */ protected static $_instances = array(); @@ -54,7 +57,6 @@ class Doctrine_Locator implements Countable, IteratorAggregate * Constructor. Provide an array of resources to set initial contents. * * @param array - * @return void */ public function __construct(array $defaults = null) { @@ -70,7 +72,7 @@ public function __construct(array $defaults = null) } /** - * instance + * instance. * * @return Sensei_Locator */ @@ -79,11 +81,12 @@ public static function instance() if (empty(self::$_instances)) { $obj = new Doctrine_Locator(); } + return current(self::$_instances); } /** - * setClassPrefix + * setClassPrefix. * * @param string $prefix */ @@ -93,7 +96,7 @@ public function setClassPrefix($prefix) } /** - * getClassPrefix + * getClassPrefix. * * @return string */ @@ -104,9 +107,9 @@ public function getClassPrefix() /** * contains - * checks if a resource exists under the given name + * checks if a resource exists under the given name. * - * @return boolean whether or not given resource name exists + * @return bool whether or not given resource name exists */ public function contains($name) { @@ -115,11 +118,12 @@ public function contains($name) /** * bind - * binds a resource to a name + * binds a resource to a name. + * + * @param string $name the name of the resource to bind + * @param mixed $value the value of the resource * - * @param string $name the name of the resource to bind - * @param mixed $value the value of the resource - * @return Sensei_Locator this object + * @return Sensei_Locator this object */ public function bind($name, $value) { @@ -130,55 +134,56 @@ public function bind($name, $value) /** * locate - * locates a resource by given name and returns it + * locates a resource by given name and returns it. + * + * @param string $name the name of the resource * - * @throws Doctrine_Locator_Exception if the resource could not be found - * @param string $name the name of the resource - * @return mixed the located resource + * @return mixed the located resource + * + * @throws Doctrine_Locator_Exception if the resource could not be found */ public function locate($name) { if (isset($this->_resources[$name])) { return $this->_resources[$name]; - } else { - $className = $name; - - if ( ! class_exists($className)) { - - $name = explode('.', $name); - foreach ($name as &$v) { - $v = ucfirst(strtolower($v)); - } - $name = implode('_', $name); - - $className = $this->_classPrefix . $name; + } + $className = $name; - if ( ! class_exists($className)) { - throw new Doctrine_Locator_Exception("Couldn't locate resource " . $className); - } + if (!class_exists($className)) { + $name = explode('.', $name); + foreach ($name as &$v) { + $v = ucfirst(strtolower($v)); } + $name = implode('_', $name); - $this->_resources[$name] = new $className(); + $className = $this->_classPrefix.$name; - if ($this->_resources[$name] instanceof Doctrine_Locator_Injectable) { - $this->_resources[$name]->setLocator($this); + if (!class_exists($className)) { + throw new Doctrine_Locator_Exception("Couldn't locate resource ".$className); } + } - return $this->_resources[$name]; + $this->_resources[$name] = new $className(); + + if ($this->_resources[$name] instanceof Doctrine_Locator_Injectable) { + $this->_resources[$name]->setLocator($this); } - throw new Doctrine_Locator_Exception("Couldn't locate resource " . $name); + return $this->_resources[$name]; + + throw new Doctrine_Locator_Exception("Couldn't locate resource ".$name); } /** * count * returns the number of bound resources associated with - * this object + * this object. * * @see Countable interface - * @return integer the number of resources + * + * @return int the number of resources */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_resources); @@ -187,12 +192,12 @@ public function count() /** * getIterator * returns an ArrayIterator that iterates through all - * bound resources + * bound resources. * - * @return ArrayIterator an iterator for iterating through - * all bound resources + * @return ArrayIterator an iterator for iterating through + * all bound resources */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->_resources); diff --git a/lib/Doctrine/Locator/Exception.php b/lib/Doctrine/Locator/Exception.php index 4a6386032..b3da90965 100644 --- a/lib/Doctrine/Locator/Exception.php +++ b/lib/Doctrine/Locator/Exception.php @@ -20,17 +20,21 @@ */ /** - * Doctrine_Locator_Exception + * Doctrine_Locator_Exception. * - * @package Doctrine - * @subpackage Doctrine_Locator * @category Locator + * * @license http://www.gnu.org/licenses/lgpl.txt LGPL - * @link http://www.doctrine-project.org + * + * @see http://www.doctrine-project.org + * * @author Janne Vanhala * @author Konsta Vesterinen + * * @version $Revision$ + * * @since 1.0 */ class Doctrine_Locator_Exception extends Doctrine_Exception -{ } +{ +} diff --git a/lib/Doctrine/Locator/Injectable.php b/lib/Doctrine/Locator/Injectable.php index b32ccf404..4c5aa0c9d 100644 --- a/lib/Doctrine/Locator/Injectable.php +++ b/lib/Doctrine/Locator/Injectable.php @@ -1,6 +1,6 @@ * @author Konsta Vesterinen * @author Eevert Saukkokoski + * * @version $Revision$ + * * @since 1.0 */ class Doctrine_Locator_Injectable { /** - * @var Doctrine_Locator the locator object + * @var Doctrine_Locator the locator object */ protected $_locator; /** - * @var array an array of bound resources + * @var array an array of bound resources */ protected $_resources = array(); /** - * @var Doctrine_Null $null Doctrine_Null object, used for extremely fast null value checking + * @var Doctrine_Null Doctrine_Null object, used for extremely fast null value checking */ protected static $_null; /** * setLocator - * this method can be used for setting the locator object locally + * this method can be used for setting the locator object locally. * * @param Doctrine_Locator the locator object - * @return Doctrine_Locator_Injectable this instance + * + * @return Doctrine_Locator_Injectable this instance */ public function setLocator(Doctrine_Locator $locator) { $this->_locator = $locator; + return $this; } /** * getLocator - * returns the locator associated with this object + * returns the locator associated with this object. * * if there are no locator locally associated then * this method tries to fetch the current global locator @@ -74,48 +79,51 @@ public function setLocator(Doctrine_Locator $locator) */ public function getLocator() { - if ( ! isset($this->_locator)) { + if (!isset($this->_locator)) { $this->_locator = Doctrine_Locator::instance(); - } + return $this->_locator; } /** * locate - * locates a resource by given name and returns it + * locates a resource by given name and returns it. * * if the resource cannot be found locally this method tries * to use the global locator for finding the resource * * @see Doctrine_Locator::locate() - * @throws Doctrine_Locator_Exception if the resource could not be found - * @param string $name the name of the resource - * @return mixed the located resource + * + * @param string $name the name of the resource + * + * @return mixed the located resource + * + * @throws Doctrine_Locator_Exception if the resource could not be found */ public function locate($name) { if (isset($this->_resources[$name])) { if (is_object($this->_resources[$name])) { return $this->_resources[$name]; - } else { - // get the name of the concrete implementation - $concreteImpl = $this->_resources[$name]; - - return $this->getLocator()->locate($concreteImpl); } - } else { - return $this->getLocator()->locate($name); + // get the name of the concrete implementation + $concreteImpl = $this->_resources[$name]; + + return $this->getLocator()->locate($concreteImpl); } + + return $this->getLocator()->locate($name); } /** * bind - * binds a resource to a name + * binds a resource to a name. * - * @param string $name the name of the resource to bind - * @param mixed $value the value of the resource - * @return static this object + * @param string $name the name of the resource to bind + * @param mixed $value the value of the resource + * + * @return static this object */ public function bind($name, $value) { @@ -126,10 +134,7 @@ public function bind($name, $value) /** * initNullObject - * initializes the null object - * - * @param Doctrine_Null $null - * @return void + * initializes the null object. */ public static function initNullObject(Doctrine_Null $null) { @@ -138,7 +143,7 @@ public static function initNullObject(Doctrine_Null $null) /** * getNullObject - * returns the null object associated with this object + * returns the null object associated with this object. * * @return Doctrine_Null */ diff --git a/lib/Doctrine/Locking/Exception.php b/lib/Doctrine/Locking/Exception.php index ec3bd6123..d3dc3cf9b 100644 --- a/lib/Doctrine/Locking/Exception.php +++ b/lib/Doctrine/Locking/Exception.php @@ -1,6 +1,6 @@ - */ class Doctrine_Locking_Exception extends Doctrine_Exception -{} \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Locking/Manager/Pessimistic.php b/lib/Doctrine/Locking/Manager/Pessimistic.php index 97c772b2e..2da813fa2 100644 --- a/lib/Doctrine/Locking/Manager/Pessimistic.php +++ b/lib/Doctrine/Locking/Manager/Pessimistic.php @@ -24,32 +24,33 @@ * a time-consuming task on a record or many records, which is spread over several * page requests can't be interfered by other users. * - * @package Doctrine - * @subpackage Locking - * @link www.doctrine-project.org + * @see www.doctrine-project.org + * * @author Roman Borschel * @author Pierre Minnieur * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Locking_Manager_Pessimistic { /** - * The conn that is used by the locking manager + * The conn that is used by the locking manager. * * @var Doctrine_Connection object */ private $conn; /** - * The database table name for the lock tracking + * The database table name for the lock tracking. */ private $_lockTable = 'doctrine_lock_tracking'; /** - * Constructs a new locking manager object + * Constructs a new locking manager object. * * When the CREATE_TABLES attribute of the connection on which the manager * is supposed to work on is set to true, the locking table is created. @@ -62,46 +63,47 @@ public function __construct(Doctrine_Connection $conn) if ($this->conn->getAttribute(Doctrine_Core::ATTR_EXPORT) & Doctrine_Core::EXPORT_TABLES) { $columns = array(); - $columns['object_type'] = array('type' => 'string', - 'length' => 50, - 'notnull' => true, - 'primary' => true); + $columns['object_type'] = array('type' => 'string', + 'length' => 50, + 'notnull' => true, + 'primary' => true); - $columns['object_key'] = array('type' => 'string', - 'length' => 250, - 'notnull' => true, - 'primary' => true); + $columns['object_key'] = array('type' => 'string', + 'length' => 250, + 'notnull' => true, + 'primary' => true); - $columns['user_ident'] = array('type' => 'string', - 'length' => 50, - 'notnull' => true); + $columns['user_ident'] = array('type' => 'string', + 'length' => 50, + 'notnull' => true); - $columns['timestamp_obtained'] = array('type' => 'integer', - 'length' => 10, - 'notnull' => true); + $columns['timestamp_obtained'] = array('type' => 'integer', + 'length' => 10, + 'notnull' => true); $options = array('primary' => array('object_type', 'object_key')); try { $this->conn->export->createTable($this->_lockTable, $columns, $options); - } catch(Exception $e) { - + } catch (Exception $e) { } } } /** - * Obtains a lock on a {@link Doctrine_Record} + * Obtains a lock on a {@link Doctrine_Record}. * - * @param Doctrine_Record $record The record that has to be locked - * @param mixed $userIdent A unique identifier of the locking user - * @return boolean TRUE if the locking was successful, FALSE if another user - * holds a lock on this record - * @throws Doctrine_Locking_Exception If the locking failed due to database errors + * @param Doctrine_Record $record The record that has to be locked + * @param mixed $userIdent A unique identifier of the locking user + * + * @return bool TRUE if the locking was successful, FALSE if another user + * holds a lock on this record + * + * @throws Doctrine_Locking_Exception If the locking failed due to database errors */ public function getLock(Doctrine_Record $record, $userIdent) { $objectType = $record->getTable()->getComponentName(); - $key = $record->getTable()->getIdentifier(); + $key = $record->getTable()->getIdentifier(); $gotLock = false; $time = time(); @@ -115,9 +117,9 @@ public function getLock(Doctrine_Record $record, $userIdent) $dbh = $this->conn->getDbh(); $this->conn->beginTransaction(); - $stmt = $dbh->prepare('INSERT INTO ' . $this->_lockTable - . ' (object_type, object_key, user_ident, timestamp_obtained)' - . ' VALUES (:object_type, :object_key, :user_ident, :ts_obtained)'); + $stmt = $dbh->prepare('INSERT INTO '.$this->_lockTable + .' (object_type, object_key, user_ident, timestamp_obtained)' + .' VALUES (:object_type, :object_key, :user_ident, :ts_obtained)'); $stmt->bindParam(':object_type', $objectType); $stmt->bindParam(':object_key', $key); @@ -128,21 +130,21 @@ public function getLock(Doctrine_Record $record, $userIdent) $stmt->execute(); $gotLock = true; - // we catch an Exception here instead of PDOException since we might also be catching Doctrine_Exception - } catch(Exception $pkviolation) { + // we catch an Exception here instead of PDOException since we might also be catching Doctrine_Exception + } catch (Exception $pkviolation) { // PK violation occured => existing lock! } - if ( ! $gotLock) { + if (!$gotLock) { $lockingUserIdent = $this->_getLockingUserIdent($objectType, $key); - if ($lockingUserIdent !== null && $lockingUserIdent == $userIdent) { + if (null !== $lockingUserIdent && $lockingUserIdent == $userIdent) { $gotLock = true; // The requesting user already has a lock // Update timestamp - $stmt = $dbh->prepare('UPDATE ' . $this->_lockTable - . ' SET timestamp_obtained = :ts' - . ' WHERE object_type = :object_type AND' - . ' object_key = :object_key AND' - . ' user_ident = :user_ident'); + $stmt = $dbh->prepare('UPDATE '.$this->_lockTable + .' SET timestamp_obtained = :ts' + .' WHERE object_type = :object_type AND' + .' object_key = :object_key AND' + .' user_ident = :user_ident'); $stmt->bindParam(':ts', $time); $stmt->bindParam(':object_type', $objectType); $stmt->bindParam(':object_key', $key); @@ -160,17 +162,19 @@ public function getLock(Doctrine_Record $record, $userIdent) } /** - * Releases a lock on a {@link Doctrine_Record} + * Releases a lock on a {@link Doctrine_Record}. + * + * @param Doctrine_Record $record The record for which the lock has to be released + * @param mixed $userIdent The unique identifier of the locking user + * + * @return bool TRUE if a lock was released, FALSE if no lock was released * - * @param Doctrine_Record $record The record for which the lock has to be released - * @param mixed $userIdent The unique identifier of the locking user - * @return boolean TRUE if a lock was released, FALSE if no lock was released * @throws Doctrine_Locking_Exception If the release procedure failed due to database errors */ public function releaseLock(Doctrine_Record $record, $userIdent) { $objectType = $record->getTable()->getComponentName(); - $key = $record->getTable()->getIdentifier(); + $key = $record->getTable()->getIdentifier(); if (is_array($key)) { // Composite key @@ -179,7 +183,7 @@ public function releaseLock(Doctrine_Record $record, $userIdent) try { $dbh = $this->conn->getDbh(); - $stmt = $dbh->prepare("DELETE FROM $this->_lockTable WHERE + $stmt = $dbh->prepare("DELETE FROM {$this->_lockTable} WHERE object_type = :object_type AND object_key = :object_key AND user_ident = :user_ident"); @@ -190,18 +194,20 @@ public function releaseLock(Doctrine_Record $record, $userIdent) $count = $stmt->rowCount(); - return ($count > 0); + return $count > 0; } catch (PDOException $pdoe) { throw new Doctrine_Locking_Exception($pdoe->getMessage()); } } /** - * Gets the unique user identifier of a lock + * Gets the unique user identifier of a lock. + * + * @param string $objectType The type of the object (component name) + * @param mixed $key The unique key of the object. Can be string or array + * + * @return string The unique user identifier for the specified lock * - * @param string $objectType The type of the object (component name) - * @param mixed $key The unique key of the object. Can be string or array - * @return string The unique user identifier for the specified lock * @throws Doctrine_Locking_Exception If the query failed due to database errors */ private function _getLockingUserIdent($objectType, $key) @@ -213,14 +219,14 @@ private function _getLockingUserIdent($objectType, $key) try { $dbh = $this->conn->getDbh(); - $stmt = $dbh->prepare('SELECT user_ident FROM ' . $this->_lockTable - . ' WHERE object_type = :object_type AND object_key = :object_key'); + $stmt = $dbh->prepare('SELECT user_ident FROM '.$this->_lockTable + .' WHERE object_type = :object_type AND object_key = :object_key'); $stmt->bindParam(':object_type', $objectType); $stmt->bindParam(':object_key', $key); $success = $stmt->execute(); - if ( ! $success) { - throw new Doctrine_Locking_Exception("Failed to determine locking user"); + if (!$success) { + throw new Doctrine_Locking_Exception('Failed to determine locking user'); } $userIdent = $stmt->fetchColumn(); @@ -235,25 +241,29 @@ private function _getLockingUserIdent($objectType, $key) * Gets the identifier that identifies the owner of the lock on the given * record. * - * @param Doctrine_Record $lockedRecord The record. - * @return mixed The unique user identifier that identifies the owner of the lock. + * @param Doctrine_Record $lockedRecord the record + * + * @return mixed the unique user identifier that identifies the owner of the lock */ public function getLockOwner($lockedRecord) { $objectType = $lockedRecord->getTable()->getComponentName(); - $key = $lockedRecord->getTable()->getIdentifier(); + $key = $lockedRecord->getTable()->getIdentifier(); + return $this->_getLockingUserIdent($objectType, $key); } /** - * Releases locks older than a defined amount of seconds + * Releases locks older than a defined amount of seconds. * * When called without parameters all locks older than 15 minutes are released. * - * @param integer $age The maximum valid age of locks in seconds - * @param string $objectType The type of the object (component name) - * @param mixed $userIdent The unique identifier of the locking user - * @return integer The number of locks that have been released + * @param int $age The maximum valid age of locks in seconds + * @param string $objectType The type of the object (component name) + * @param mixed $userIdent The unique identifier of the locking user + * + * @return int The number of locks that have been released + * * @throws Doctrine_Locking_Exception If the release process failed due to database errors */ public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = null) @@ -262,9 +272,9 @@ public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = nu try { $dbh = $this->conn->getDbh(); - $stmt = $dbh->prepare('DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age'); + $stmt = $dbh->prepare('DELETE FROM '.$this->_lockTable.' WHERE timestamp_obtained < :age'); $stmt->bindParam(':age', $age); - $query = 'DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age'; + $query = 'DELETE FROM '.$this->_lockTable.' WHERE timestamp_obtained < :age'; if ($objectType) { $query .= ' AND object_type = :object_type'; } @@ -281,9 +291,7 @@ public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = nu } $stmt->execute(); - $count = $stmt->rowCount(); - - return $count; + return $stmt->rowCount(); } catch (PDOException $pdoe) { throw new Doctrine_Locking_Exception($pdoe->getMessage()); } diff --git a/lib/Doctrine/Manager.php b/lib/Doctrine/Manager.php index a2b08944d..f0603c4fe 100644 --- a/lib/Doctrine/Manager.php +++ b/lib/Doctrine/Manager.php @@ -20,84 +20,84 @@ */ /** - * * Doctrine_Manager is the base component of all doctrine based projects. * It opens and keeps track of all connections (database connections). * - * @package Doctrine - * @subpackage Manager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Manager extends Doctrine_Configurable implements Countable, IteratorAggregate { /** - * @var array $connections an array containing all the opened connections + * @var array an array containing all the opened connections */ - protected $_connections = array(); + protected $_connections = array(); /** - * @var array $bound an array containing all components that have a bound connection + * @var array an array containing all components that have a bound connection */ - protected $_bound = array(); + protected $_bound = array(); /** - * @var integer $index the incremented index + * @var int the incremented index */ - protected $_index = 0; + protected $_index = 0; /** - * @var integer $currIndex the current connection index + * @var int the current connection index */ - protected $_currIndex = 0; + protected $_currIndex = 0; /** - * @var Doctrine_Query_Registry the query registry + * @var Doctrine_Query_Registry the query registry */ protected $_queryRegistry; /** - * @var array Array of registered validators + * @var array Array of registered validators */ protected $_validators = array(); /** - * @var array Array of registered hydrators + * @var array Array of registered hydrators */ protected $_hydrators = array( - Doctrine_Core::HYDRATE_ARRAY => 'Doctrine_Hydrator_ArrayDriver', - Doctrine_Core::HYDRATE_RECORD => 'Doctrine_Hydrator_RecordDriver', - Doctrine_Core::HYDRATE_NONE => 'Doctrine_Hydrator_NoneDriver', - Doctrine_Core::HYDRATE_SCALAR => 'Doctrine_Hydrator_ScalarDriver', - Doctrine_Core::HYDRATE_SINGLE_SCALAR => 'Doctrine_Hydrator_SingleScalarDriver', - Doctrine_Core::HYDRATE_ON_DEMAND => 'Doctrine_Hydrator_RecordDriver', - Doctrine_Core::HYDRATE_ARRAY_HIERARCHY => 'Doctrine_Hydrator_ArrayHierarchyDriver', + Doctrine_Core::HYDRATE_ARRAY => 'Doctrine_Hydrator_ArrayDriver', + Doctrine_Core::HYDRATE_RECORD => 'Doctrine_Hydrator_RecordDriver', + Doctrine_Core::HYDRATE_NONE => 'Doctrine_Hydrator_NoneDriver', + Doctrine_Core::HYDRATE_SCALAR => 'Doctrine_Hydrator_ScalarDriver', + Doctrine_Core::HYDRATE_SINGLE_SCALAR => 'Doctrine_Hydrator_SingleScalarDriver', + Doctrine_Core::HYDRATE_ON_DEMAND => 'Doctrine_Hydrator_RecordDriver', + Doctrine_Core::HYDRATE_ARRAY_HIERARCHY => 'Doctrine_Hydrator_ArrayHierarchyDriver', Doctrine_Core::HYDRATE_RECORD_HIERARCHY => 'Doctrine_Hydrator_RecordHierarchyDriver', - Doctrine_Core::HYDRATE_ARRAY_SHALLOW => 'Doctrine_Hydrator_ArrayShallowDriver', + Doctrine_Core::HYDRATE_ARRAY_SHALLOW => 'Doctrine_Hydrator_ArrayShallowDriver', ); protected $_connectionDrivers = array( - 'db2' => 'Doctrine_Connection_Db2', - 'mysql' => 'Doctrine_Connection_Mysql', - 'mysqli' => 'Doctrine_Connection_Mysql', - 'sqlite' => 'Doctrine_Connection_Sqlite', - 'pgsql' => 'Doctrine_Connection_Pgsql', - 'oci' => 'Doctrine_Connection_Oracle', - 'oci8' => 'Doctrine_Connection_Oracle', - 'oracle' => 'Doctrine_Connection_Oracle', - 'mssql' => 'Doctrine_Connection_Mssql', - 'dblib' => 'Doctrine_Connection_Mssql', - 'odbc' => 'Doctrine_Connection_Mssql', - 'mock' => 'Doctrine_Connection_Mock' + 'db2' => 'Doctrine_Connection_Db2', + 'mysql' => 'Doctrine_Connection_Mysql', + 'mysqli' => 'Doctrine_Connection_Mysql', + 'sqlite' => 'Doctrine_Connection_Sqlite', + 'pgsql' => 'Doctrine_Connection_Pgsql', + 'oci' => 'Doctrine_Connection_Oracle', + 'oci8' => 'Doctrine_Connection_Oracle', + 'oracle' => 'Doctrine_Connection_Oracle', + 'mssql' => 'Doctrine_Connection_Mssql', + 'dblib' => 'Doctrine_Connection_Mssql', + 'odbc' => 'Doctrine_Connection_Mssql', + 'mock' => 'Doctrine_Connection_Mock', ); protected $_extensions = array(); /** - * @var boolean Whether or not the default validators have been loaded + * @var bool Whether or not the default validators have been loaded */ protected $_loadedDefaultValidators = false; @@ -106,13 +106,13 @@ class Doctrine_Manager extends Doctrine_Configurable implements Countable, Itera private $_initialized = false; /** - * constructor + * constructor. * * this is private constructor (use getInstance to get an instance of this class) */ private function __construct() { - $null = new Doctrine_Null; + $null = new Doctrine_Null(); Doctrine_Locator_Injectable::initNullObject($null); Doctrine_Record_Iterator::initNullObject($null); } @@ -124,77 +124,78 @@ private function __construct() * instance. It is idempotent and can only be called one time. Subsequent * calls does not alter the attribute values. * - * @return boolean true if inizialization was executed + * @return bool true if inizialization was executed */ public function setDefaultAttributes() { - if ( ! $this->_initialized) { + if (!$this->_initialized) { $this->_initialized = true; $attributes = array( - Doctrine_Core::ATTR_CACHE => null, - Doctrine_Core::ATTR_RESULT_CACHE => null, - Doctrine_Core::ATTR_QUERY_CACHE => null, - Doctrine_Core::ATTR_TABLE_CACHE => null, - Doctrine_Core::ATTR_LOAD_REFERENCES => true, - Doctrine_Core::ATTR_LISTENER => new Doctrine_EventListener(), - Doctrine_Core::ATTR_RECORD_LISTENER => new Doctrine_Record_Listener(), - Doctrine_Core::ATTR_THROW_EXCEPTIONS => true, - Doctrine_Core::ATTR_VALIDATE => Doctrine_Core::VALIDATE_NONE, - Doctrine_Core::ATTR_QUERY_LIMIT => Doctrine_Core::LIMIT_RECORDS, - Doctrine_Core::ATTR_IDXNAME_FORMAT => "%s_idx", - Doctrine_Core::ATTR_SEQNAME_FORMAT => "%s_seq", - Doctrine_Core::ATTR_TBLNAME_FORMAT => "%s", - Doctrine_Core::ATTR_FKNAME_FORMAT => "%s", - Doctrine_Core::ATTR_QUOTE_IDENTIFIER => false, - Doctrine_Core::ATTR_SEQCOL_NAME => 'id', - Doctrine_Core::ATTR_PORTABILITY => Doctrine_Core::PORTABILITY_NONE, - Doctrine_Core::ATTR_EXPORT => Doctrine_Core::EXPORT_ALL, - Doctrine_Core::ATTR_DECIMAL_PLACES => 2, - Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE => 'doctrine', - Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES => false, - Doctrine_Core::ATTR_USE_DQL_CALLBACKS => false, - Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE => false, - Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS => false, - Doctrine_Core::ATTR_DEFAULT_IDENTIFIER_OPTIONS => array(), - Doctrine_Core::ATTR_DEFAULT_COLUMN_OPTIONS => array(), - Doctrine_Core::ATTR_HYDRATE_OVERWRITE => true, - Doctrine_Core::ATTR_QUERY_CLASS => 'Doctrine_Query', - Doctrine_Core::ATTR_COLLECTION_CLASS => 'Doctrine_Collection', - Doctrine_Core::ATTR_TABLE_CLASS => 'Doctrine_Table', - Doctrine_Core::ATTR_CASCADE_SAVES => true, - Doctrine_Core::ATTR_TABLE_CLASS_FORMAT => '%sTable', - Doctrine_Core::ATTR_USE_TABLE_REPOSITORY => true, - Doctrine_Core::ATTR_USE_TABLE_IDENTITY_MAP => true, - ); + Doctrine_Core::ATTR_CACHE => null, + Doctrine_Core::ATTR_RESULT_CACHE => null, + Doctrine_Core::ATTR_QUERY_CACHE => null, + Doctrine_Core::ATTR_TABLE_CACHE => null, + Doctrine_Core::ATTR_LOAD_REFERENCES => true, + Doctrine_Core::ATTR_LISTENER => new Doctrine_EventListener(), + Doctrine_Core::ATTR_RECORD_LISTENER => new Doctrine_Record_Listener(), + Doctrine_Core::ATTR_THROW_EXCEPTIONS => true, + Doctrine_Core::ATTR_VALIDATE => Doctrine_Core::VALIDATE_NONE, + Doctrine_Core::ATTR_QUERY_LIMIT => Doctrine_Core::LIMIT_RECORDS, + Doctrine_Core::ATTR_IDXNAME_FORMAT => '%s_idx', + Doctrine_Core::ATTR_SEQNAME_FORMAT => '%s_seq', + Doctrine_Core::ATTR_TBLNAME_FORMAT => '%s', + Doctrine_Core::ATTR_FKNAME_FORMAT => '%s', + Doctrine_Core::ATTR_QUOTE_IDENTIFIER => false, + Doctrine_Core::ATTR_SEQCOL_NAME => 'id', + Doctrine_Core::ATTR_PORTABILITY => Doctrine_Core::PORTABILITY_NONE, + Doctrine_Core::ATTR_EXPORT => Doctrine_Core::EXPORT_ALL, + Doctrine_Core::ATTR_DECIMAL_PLACES => 2, + Doctrine_Core::ATTR_DEFAULT_PARAM_NAMESPACE => 'doctrine', + Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES => false, + Doctrine_Core::ATTR_USE_DQL_CALLBACKS => false, + Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE => false, + Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS => false, + Doctrine_Core::ATTR_DEFAULT_IDENTIFIER_OPTIONS => array(), + Doctrine_Core::ATTR_DEFAULT_COLUMN_OPTIONS => array(), + Doctrine_Core::ATTR_HYDRATE_OVERWRITE => true, + Doctrine_Core::ATTR_QUERY_CLASS => 'Doctrine_Query', + Doctrine_Core::ATTR_COLLECTION_CLASS => 'Doctrine_Collection', + Doctrine_Core::ATTR_TABLE_CLASS => 'Doctrine_Table', + Doctrine_Core::ATTR_CASCADE_SAVES => true, + Doctrine_Core::ATTR_TABLE_CLASS_FORMAT => '%sTable', + Doctrine_Core::ATTR_USE_TABLE_REPOSITORY => true, + Doctrine_Core::ATTR_USE_TABLE_IDENTITY_MAP => true, + ); foreach ($attributes as $attribute => $value) { $old = $this->getAttribute($attribute); - if ($old === null) { - $this->setAttribute($attribute,$value); + if (null === $old) { + $this->setAttribute($attribute, $value); } } + return true; } + return false; } /** * Returns an instance of this class - * (this class uses the singleton pattern) + * (this class uses the singleton pattern). * * @return Doctrine_Manager */ public static function getInstance() { - if ( ! isset(self::$_instance)) { + if (!isset(self::$_instance)) { self::$_instance = new self(); } + return self::$_instance; } /** - * Reset the internal static instance - * - * @return void + * Reset the internal static instance. */ public static function resetInstance() { @@ -205,9 +206,7 @@ public static function resetInstance() } /** - * Reset this instance of the manager - * - * @return void + * Reset this instance of the manager. */ public function reset() { @@ -226,22 +225,23 @@ public function reset() } /** - * Lazy-initializes the query registry object and returns it + * Lazy-initializes the query registry object and returns it. * * @return Doctrine_Query_Registry */ public function getQueryRegistry() { - if ( ! isset($this->_queryRegistry)) { - $this->_queryRegistry = new Doctrine_Query_Registry(); - } + if (!isset($this->_queryRegistry)) { + $this->_queryRegistry = new Doctrine_Query_Registry(); + } + return $this->_queryRegistry; } /** - * Sets the query registry + * Sets the query registry. * - * @return Doctrine_Manager this object + * @return Doctrine_Manager this object */ public function setQueryRegistry(Doctrine_Query_Registry $registry) { @@ -252,56 +252,60 @@ public function setQueryRegistry(Doctrine_Query_Registry $registry) /** * Open a new connection. If the adapter parameter is set this method acts as - * a short cut for Doctrine_Manager::getInstance()->openConnection($adapter, $name); + * a short cut for Doctrine_Manager::getInstance()->openConnection($adapter, $name);. * * if the adapter paramater is not set this method acts as * a short cut for Doctrine_Manager::getInstance()->getCurrentConnection() * - * @param PDO|Doctrine_Adapter_Interface $adapter database driver - * @param string $name name of the connection, if empty numeric key is used - * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name + * @param PDO|Doctrine_Adapter_Interface $adapter database driver + * @param string $name name of the connection, if empty numeric key is used + * * @return Doctrine_Connection + * + * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name */ public static function connection($adapter = null, $name = null) { - if ($adapter == null) { + if (null == $adapter) { return Doctrine_Manager::getInstance()->getCurrentConnection(); - } else { - return Doctrine_Manager::getInstance()->openConnection($adapter, $name); } + + return Doctrine_Manager::getInstance()->openConnection($adapter, $name); } /** - * Opens a new connection and saves it to Doctrine_Manager->connections + * Opens a new connection and saves it to Doctrine_Manager->connections. + * + * @param PDO|Doctrine_Adapter_Interface $adapter database driver + * @param string $name name of the connection, if empty numeric key is used * - * @param PDO|Doctrine_Adapter_Interface $adapter database driver - * @param string $name name of the connection, if empty numeric key is used - * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name - * @throws Doctrine_Manager_Exception if trying to open connection for unknown driver * @return Doctrine_Connection + * + * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name + * @throws Doctrine_Manager_Exception if trying to open connection for unknown driver */ public function openConnection($adapter, $name = null, $setCurrent = true) { if (is_object($adapter)) { - if ( ! ($adapter instanceof PDO) && ! in_array('Doctrine_Adapter_Interface', class_implements($adapter))) { - throw new Doctrine_Manager_Exception("First argument should be an instance of PDO or implement Doctrine_Adapter_Interface"); + if (!($adapter instanceof PDO) && !in_array('Doctrine_Adapter_Interface', class_implements($adapter))) { + throw new Doctrine_Manager_Exception('First argument should be an instance of PDO or implement Doctrine_Adapter_Interface'); } $driverName = $adapter->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME); - } else if (is_array($adapter)) { - if ( ! isset($adapter[0])) { + } elseif (is_array($adapter)) { + if (!isset($adapter[0])) { throw new Doctrine_Manager_Exception('Empty data source name given.'); } $e = explode(':', $adapter[0]); - if ($e[0] == 'uri') { + if ('uri' == $e[0]) { $e[0] = 'odbc'; } - $parts['dsn'] = $adapter[0]; + $parts['dsn'] = $adapter[0]; $parts['scheme'] = $e[0]; - $parts['user'] = (isset($adapter[1])) ? $adapter[1] : null; - $parts['pass'] = (isset($adapter[2])) ? $adapter[2] : null; + $parts['user'] = (isset($adapter[1])) ? $adapter[1] : null; + $parts['pass'] = (isset($adapter[2])) ? $adapter[2] : null; $driverName = $e[0]; $adapter = $parts; } else { @@ -313,28 +317,29 @@ public function openConnection($adapter, $name = null, $setCurrent = true) // Decode adapter information if (is_array($adapter)) { foreach ($adapter as $key => $value) { - $adapter[$key] = $value ? urldecode($value):null; + $adapter[$key] = $value ? urldecode($value) : null; } } // initialize the default attributes $this->setDefaultAttributes(); - if ($name !== null) { + if (null !== $name) { $name = (string) $name; if (isset($this->_connections[$name])) { if ($setCurrent) { $this->_currIndex = $name; } + return $this->_connections[$name]; } } else { $name = $this->_index; - $this->_index++; + ++$this->_index; } - if ( ! isset($this->_connectionDrivers[$driverName])) { - throw new Doctrine_Manager_Exception('Unknown driver ' . $driverName); + if (!isset($this->_connectionDrivers[$driverName])) { + throw new Doctrine_Manager_Exception('Unknown driver '.$driverName); } $className = $this->_connectionDrivers[$driverName]; @@ -346,14 +351,17 @@ public function openConnection($adapter, $name = null, $setCurrent = true) if ($setCurrent) { $this->_currIndex = $name; } + return $this->_connections[$name]; } /** - * Parse a pdo style dsn in to an array of parts + * Parse a pdo style dsn in to an array of parts. * * @param array $dsn An array of dsn information + * * @return array The array parsed + * * @todo package:dbal */ public function parsePdoDsn($dsn) @@ -363,7 +371,7 @@ public function parsePdoDsn($dsn) $names = array('dsn', 'scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment', 'unix_socket'); foreach ($names as $name) { - if ( ! isset($parts[$name])) { + if (!isset($parts[$name])) { $parts[$name] = null; } } @@ -377,9 +385,8 @@ public function parsePdoDsn($dsn) if ($string) { $e2 = explode('=', $string); - if (isset($e2[0]) && isset($e2[1])) { - if (count($e2) > 2) - { + if (isset($e2[0], $e2[1])) { + if (count($e2) > 2) { $key = $e2[0]; unset($e2[0]); $value = implode('=', $e2); @@ -395,35 +402,37 @@ public function parsePdoDsn($dsn) } /** - * Build the blank dsn parts array used with parseDsn() + * Build the blank dsn parts array used with parseDsn(). * * @see parseDsn() + * * @param string $dsn + * * @return array $parts */ protected function _buildDsnPartsArray($dsn) { // fix sqlite dsn so that it will parse correctly - $dsn = str_replace("////", "/", $dsn); - $dsn = str_replace("\\", "/", $dsn); - $dsn = preg_replace("/\/\/\/(.*):\//", "//$1:/", $dsn); + $dsn = str_replace('////', '/', $dsn); + $dsn = str_replace('\\', '/', $dsn); + $dsn = preg_replace('/\\/\\/\\/(.*):\\//', '//$1:/', $dsn); // silence any warnings $parts = @parse_url($dsn); - if ($parts === false) { + if (false === $parts) { $parts = array(); } $names = array('dsn', 'scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment'); foreach ($names as $name) { - if ( ! isset($parts[$name])) { + if (!isset($parts[$name])) { $parts[$name] = null; } } - if (count($parts) == 0 || ! isset($parts['scheme'])) { + if (0 == count($parts) || !isset($parts['scheme'])) { throw new Doctrine_Manager_Exception('Could not parse dsn'); } @@ -431,10 +440,12 @@ protected function _buildDsnPartsArray($dsn) } /** - * Parse a Doctrine style dsn string in to an array of parts + * Parse a Doctrine style dsn string in to an array of parts. * * @param string $dsn + * * @return array Parsed contents of DSN + * * @todo package:dbal */ public function parseDsn($dsn) @@ -445,36 +456,36 @@ public function parseDsn($dsn) case 'sqlite': case 'sqlite2': case 'sqlite3': - if (isset($parts['host']) && $parts['host'] == ':memory') { + if (isset($parts['host']) && ':memory' == $parts['host']) { $parts['database'] = ':memory:'; - $parts['dsn'] = 'sqlite::memory:'; + $parts['dsn'] = 'sqlite::memory:'; } else { - //fix windows dsn we have to add host: to path and set host to null + // fix windows dsn we have to add host: to path and set host to null if (isset($parts['host'])) { - $parts['path'] = $parts['host'] . ":" . $parts["path"]; + $parts['path'] = $parts['host'].':'.$parts['path']; $parts['host'] = null; } $parts['database'] = $parts['path']; - $parts['dsn'] = $parts['scheme'] . ':' . $parts['path']; + $parts['dsn'] = $parts['scheme'].':'.$parts['path']; } break; case 'mssql': case 'dblib': - if ( ! isset($parts['path']) || $parts['path'] == '/') { + if (!isset($parts['path']) || '/' == $parts['path']) { throw new Doctrine_Manager_Exception('No database available in data source name'); } if (isset($parts['path'])) { $parts['database'] = substr($parts['path'], 1); } - if ( ! isset($parts['host'])) { + if (!isset($parts['host'])) { throw new Doctrine_Manager_Exception('No hostname set in data source name'); } - $parts['dsn'] = $parts['scheme'] . ':host=' - . $parts['host'] . (isset($parts['port']) ? ':' . $parts['port']:null) . ';dbname=' - . $parts['database']; + $parts['dsn'] = $parts['scheme'].':host=' + .$parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : null).';dbname=' + .$parts['database']; break; @@ -485,19 +496,19 @@ public function parseDsn($dsn) case 'odbc': case 'mock': case 'oracle': - if ( ! isset($parts['path']) || $parts['path'] == '/') { + if (!isset($parts['path']) || '/' == $parts['path']) { throw new Doctrine_Manager_Exception('No database available in data source name'); } if (isset($parts['path'])) { $parts['database'] = substr($parts['path'], 1); } - if ( ! isset($parts['host'])) { + if (!isset($parts['host'])) { throw new Doctrine_Manager_Exception('No hostname set in data source name'); } - $parts['dsn'] = $parts['scheme'] . ':host=' - . $parts['host'] . (isset($parts['port']) ? ';port=' . $parts['port']:null) . ';dbname=' - . $parts['database']; + $parts['dsn'] = $parts['scheme'].':host=' + .$parts['host'].(isset($parts['port']) ? ';port='.$parts['port'] : null).';dbname=' + .$parts['database']; break; default: @@ -508,26 +519,29 @@ public function parseDsn($dsn) } /** - * Get the connection instance for the passed name + * Get the connection instance for the passed name. + * + * @param string $name name of the connection, if empty numeric key is used * - * @param string $name name of the connection, if empty numeric key is used * @return Doctrine_Connection - * @throws Doctrine_Manager_Exception if trying to get a non-existent connection + * + * @throws Doctrine_Manager_Exception if trying to get a non-existent connection */ public function getConnection($name) { - if ( ! isset($this->_connections[$name])) { - throw new Doctrine_Manager_Exception('Unknown connection: ' . $name); + if (!isset($this->_connections[$name])) { + throw new Doctrine_Manager_Exception('Unknown connection: '.$name); } return $this->_connections[$name]; } /** - * Get the name of the passed connection instance + * Get the name of the passed connection instance. + * + * @param Doctrine_Connection $conn connection object to be searched for * - * @param Doctrine_Connection $conn connection object to be searched for - * @return string the name of the connection + * @return string the name of the connection */ public function getConnectionName(Doctrine_Connection $conn) { @@ -537,11 +551,12 @@ public function getConnectionName(Doctrine_Connection $conn) /** * Binds given component to given connection * this means that when ever the given component uses a connection - * it will be using the bound connection instead of the current connection + * it will be using the bound connection instead of the current connection. * * @param string $componentName * @param string $connectionName - * @return boolean + * + * @return bool */ public function bindComponent($componentName, $connectionName) { @@ -549,9 +564,10 @@ public function bindComponent($componentName, $connectionName) } /** - * Get the connection instance for the specified component + * Get the connection instance for the specified component. * * @param string $componentName + * * @return Doctrine_Connection */ public function getConnectionForComponent($componentName) @@ -566,10 +582,11 @@ public function getConnectionForComponent($componentName) } /** - * Check if a component is bound to a connection + * Check if a component is bound to a connection. * * @param string $componentName - * @return boolean + * + * @return bool */ public function hasConnectionForComponent($componentName = null) { @@ -577,10 +594,7 @@ public function hasConnectionForComponent($componentName = null) } /** - * Closes the specified connection - * - * @param Doctrine_Connection $connection - * @return void + * Closes the specified connection. */ public function closeConnection(Doctrine_Connection $connection) { @@ -588,12 +602,12 @@ public function closeConnection(Doctrine_Connection $connection) $key = array_search($connection, $this->_connections, true); - if ($key !== false) { + if (false !== $key) { unset($this->_connections[$key]); if ($key === $this->_currIndex) { $key = key($this->_connections); - $this->_currIndex = ($key !== null) ? $key : 0; + $this->_currIndex = (null !== $key) ? $key : 0; } } @@ -601,7 +615,7 @@ public function closeConnection(Doctrine_Connection $connection) } /** - * Returns all opened connections + * Returns all opened connections. * * @return array */ @@ -611,26 +625,27 @@ public function getConnections() } /** - * Sets the current connection to $key + * Sets the current connection to $key. + * + * @param mixed $key the connection key * - * @param mixed $key the connection key * @throws Doctrine_Manager_Exception - * @return void */ public function setCurrentConnection($key) { $key = (string) $key; - if ( ! isset($this->_connections[$key])) { - throw new Doctrine_Manager_Exception("Connection key '$key' does not exist."); + if (!isset($this->_connections[$key])) { + throw new Doctrine_Manager_Exception("Connection key '{$key}' does not exist."); } $this->_currIndex = $key; } /** - * Whether or not the manager contains specified connection + * Whether or not the manager contains specified connection. + * + * @param mixed $key the connection key * - * @param mixed $key the connection key - * @return boolean + * @return bool */ public function contains($key) { @@ -638,57 +653,59 @@ public function contains($key) } /** - * Returns the number of opened connections + * Returns the number of opened connections. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_connections); } /** - * Returns an ArrayIterator that iterates through all connections + * Returns an ArrayIterator that iterates through all connections. * * @return ArrayIterator */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->_connections); } /** - * Get the current connection instance + * Get the current connection instance. * - * @throws Doctrine_Connection_Exception if there are no open connections * @return Doctrine_Connection + * + * @throws Doctrine_Connection_Exception if there are no open connections */ public function getCurrentConnection() { $i = $this->_currIndex; - if ( ! isset($this->_connections[$i])) { + if (!isset($this->_connections[$i])) { throw new Doctrine_Connection_Exception('There is no open connection'); } + return $this->_connections[$i]; } /** - * Creates databases for all existing connections + * Creates databases for all existing connections. * * @param string $specifiedConnections Array of connections you wish to create the database for - * @return void + * * @todo package:dbal */ public function createDatabases($specifiedConnections = array()) { - if ( ! is_array($specifiedConnections)) { + if (!is_array($specifiedConnections)) { $specifiedConnections = (array) $specifiedConnections; } foreach ($this as $name => $connection) { - if ( ! empty($specifiedConnections) && ! in_array($name, $specifiedConnections)) { + if (!empty($specifiedConnections) && !in_array($name, $specifiedConnections)) { continue; } @@ -697,20 +714,20 @@ public function createDatabases($specifiedConnections = array()) } /** - * Drops databases for all existing connections + * Drops databases for all existing connections. * * @param string $specifiedConnections Array of connections you wish to drop the database for - * @return void + * * @todo package:dbal */ public function dropDatabases($specifiedConnections = array()) { - if ( ! is_array($specifiedConnections)) { + if (!is_array($specifiedConnections)) { $specifiedConnections = (array) $specifiedConnections; } foreach ($this as $name => $connection) { - if ( ! empty($specifiedConnections) && ! in_array($name, $specifiedConnections)) { + if (!empty($specifiedConnections) && !in_array($name, $specifiedConnections)) { continue; } @@ -719,27 +736,28 @@ public function dropDatabases($specifiedConnections = array()) } /** - * Returns a string representation of this object + * Returns a string representation of this object. * * @return string */ public function __toString() { - $r[] = "
";
-        $r[] = "Doctrine_Manager";
-        $r[] = "Connections : ".count($this->_connections);
-        $r[] = "
"; - return implode("\n",$r); + $r[] = '
';
+        $r[] = 'Doctrine_Manager';
+        $r[] = 'Connections : '.count($this->_connections);
+        $r[] = '
'; + + return implode("\n", $r); } /** - * Get available doctrine validators + * Get available doctrine validators. * * @return array $validators */ public function getValidators() { - if ( ! $this->_loadedDefaultValidators) { + if (!$this->_loadedDefaultValidators) { $this->_loadedDefaultValidators = true; $this->registerValidators(array( @@ -773,25 +791,22 @@ public function getValidators() } /** - * Register validators so that Doctrine is aware of them + * Register validators so that Doctrine is aware of them. * - * @param mixed $validators Name of validator or array of validators - * @return void + * @param mixed $validators Name of validator or array of validators */ public function registerValidators($validators) { $validators = (array) $validators; foreach ($validators as $validator) { - if ( ! in_array($validator, $this->_validators)) { + if (!in_array($validator, $this->_validators)) { $this->_validators[] = $validator; } } } /** - * Register a new driver for hydration - * - * @return void + * Register a new driver for hydration. */ public function registerHydrator($name, $class) { @@ -799,7 +814,7 @@ public function registerHydrator($name, $class) } /** - * Get all registered hydrators + * Get all registered hydrators. * * @return array $hydrators */ @@ -809,9 +824,7 @@ public function getHydrators() } /** - * Register a custom connection driver - * - * @return void + * Register a custom connection driver. */ public function registerConnectionDriver($name, $class) { @@ -819,7 +832,7 @@ public function registerConnectionDriver($name, $class) } /** - * Get all the available connection drivers + * Get all the available connection drivers. * * @return array $connectionDrivers */ @@ -829,22 +842,21 @@ public function getConnectionDrivers() } /** - * Register a Doctrine extension for extensionsAutoload() method + * Register a Doctrine extension for extensionsAutoload() method. * * @param string $name * @param string $path - * @return void */ public function registerExtension($name, $path = null) { if (is_null($path)) { - $path = Doctrine_Core::getExtensionsPath() . '/' . $name . '/lib'; + $path = Doctrine_Core::getExtensionsPath().'/'.$name.'/lib'; } $this->_extensions[$name] = $path; } /** - * Get all registered Doctrine extensions + * Get all registered Doctrine extensions. * * @return $extensions */ diff --git a/lib/Doctrine/Manager/Exception.php b/lib/Doctrine/Manager/Exception.php index 461598a2d..8ad0680f6 100644 --- a/lib/Doctrine/Manager/Exception.php +++ b/lib/Doctrine/Manager/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Manager_Exception + * Doctrine_Manager_Exception. * - * @package Doctrine - * @subpackage Manager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Manager_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Migration.php b/lib/Doctrine/Migration.php index 0208ce540..ebcbd51f3 100644 --- a/lib/Doctrine/Migration.php +++ b/lib/Doctrine/Migration.php @@ -20,39 +20,39 @@ */ /** - * Doctrine_Migration + * Doctrine_Migration. * * this class represents a database view * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Migration { - protected $_migrationTableName = 'migration_version', - $_migrationTableCreated = false, - $_connection, - $_migrationClassesDirectory = array(), - $_migrationClasses = array(), - $_reflectionClass, - $_errors = array(), - $_process; + protected $_migrationTableName = 'migration_version'; + protected $_migrationTableCreated = false; + protected $_connection; + protected $_migrationClassesDirectory = array(); + protected $_migrationClasses = array(); + protected $_reflectionClass; + protected $_errors = array(); + protected $_process; protected static $_migrationClassesForDirectories = array(); /** * Specify the path to the directory with the migration classes. * The classes will be loaded and the migration table will be created if it - * does not already exist + * does not already exist. * - * @param string $directory The path to your migrations directory - * @param mixed $connection The connection name or instance to use for this migration - * @return void + * @param string $directory The path to your migrations directory + * @param mixed $connection The connection name or instance to use for this migration */ public function __construct($directory = null, $connection = null) { @@ -63,7 +63,8 @@ public function __construct($directory = null, $connection = null) } else { if (is_string($connection)) { $this->_connection = Doctrine_Manager::getInstance() - ->getConnection($connection); + ->getConnection($connection) + ; } else { $this->_connection = $connection; } @@ -71,7 +72,7 @@ public function __construct($directory = null, $connection = null) $this->_process = new Doctrine_Migration_Process($this); - if ($directory != null) { + if (null != $directory) { $this->_migrationClassesDirectory = $directory; $this->loadMigrationClassesFromDirectory(); @@ -89,7 +90,7 @@ public function setConnection(Doctrine_Connection $conn) } /** - * Get the migration classes directory + * Get the migration classes directory. * * @return string $migrationClassesDirectory */ @@ -99,7 +100,7 @@ public function getMigrationClassesDirectory() } /** - * Get the table name for storing the version number for this migration instance + * Get the table name for storing the version number for this migration instance. * * @return string $migrationTableName */ @@ -109,27 +110,26 @@ public function getTableName() } /** - * Set the table name for storing the version number for this migration instance + * Set the table name for storing the version number for this migration instance. * * @param string $tableName - * @return void */ public function setTableName($tableName) { $this->_migrationTableName = $this->_connection - ->formatter->getTableName($tableName); + ->formatter->getTableName($tableName) + ; } /** * Load migration classes from the passed directory. Any file found with a .php - * extension will be passed to the loadMigrationClass() + * extension will be passed to the loadMigrationClass(). * - * @param string $directory Directory to load migration classes from - * @return void + * @param string $directory Directory to load migration classes from */ public function loadMigrationClassesFromDirectory($directory = null) { - $directory = $directory ? $directory:$this->_migrationClassesDirectory; + $directory = $directory ? $directory : $this->_migrationClassesDirectory; $classesToLoad = array(); $classes = get_declared_classes(); @@ -145,8 +145,8 @@ public function loadMigrationClassesFromDirectory($directory = null) foreach ($it as $file) { $info = pathinfo($file->getFileName()); - if (isset($info['extension']) && $info['extension'] == 'php') { - require_once($file->getPathName()); + if (isset($info['extension']) && 'php' == $info['extension']) { + require_once $file->getPathName(); $array = array_diff(get_declared_classes(), $classes); $className = end($array); @@ -171,22 +171,21 @@ public function loadMigrationClassesFromDirectory($directory = null) * migration classes to execute. It must be a child of Doctrine_Migration in order * to be loaded. * - * @param string $name - * @return void + * @param string $name + * @param mixed|null $path */ public function loadMigrationClass($name, $path = null) { $class = new ReflectionClass($name); while ($class->isSubclassOf($this->_reflectionClass)) { - $class = $class->getParentClass(); - if ($class === false) { + if (false === $class) { break; } } - if ($class === false) { + if (false === $class) { return false; } @@ -218,66 +217,65 @@ public function getMigrationClasses() } /** - * Set the current version of the database + * Set the current version of the database. * - * @param integer $number - * @return void + * @param int $number */ public function setCurrentVersion($number) { if ($this->hasMigrated()) { - $this->_connection->exec("UPDATE " . $this->_migrationTableName . " SET version = $number"); + $this->_connection->exec('UPDATE '.$this->_migrationTableName." SET version = {$number}"); } else { - $this->_connection->exec("INSERT INTO " . $this->_migrationTableName . " (version) VALUES ($number)"); + $this->_connection->exec('INSERT INTO '.$this->_migrationTableName." (version) VALUES ({$number})"); } } /** - * Get the current version of the database + * Get the current version of the database. * - * @return integer $version + * @return int $version */ public function getCurrentVersion() { $this->_createMigrationTable(); - $result = $this->_connection->fetchColumn("SELECT version FROM " . $this->_migrationTableName); + $result = $this->_connection->fetchColumn('SELECT version FROM '.$this->_migrationTableName); - return isset($result[0]) ? $result[0]:0; + return isset($result[0]) ? $result[0] : 0; } /** - * hReturns true/false for whether or not this database has been migrated in the past + * hReturns true/false for whether or not this database has been migrated in the past. * - * @return boolean $migrated + * @return bool $migrated */ public function hasMigrated() { $this->_createMigrationTable(); - $result = $this->_connection->fetchColumn("SELECT version FROM " . $this->_migrationTableName); + $result = $this->_connection->fetchColumn('SELECT version FROM '.$this->_migrationTableName); - return isset($result[0]) ? true:false; + return isset($result[0]) ? true : false; } /** - * Gets the latest possible version from the loaded migration classes + * Gets the latest possible version from the loaded migration classes. * - * @return integer $latestVersion + * @return int $latestVersion */ public function getLatestVersion() { $versions = array_keys($this->_migrationClasses); rsort($versions); - return isset($versions[0]) ? $versions[0]:0; + return isset($versions[0]) ? $versions[0] : 0; } /** * Get the next incremented version number based on the latest version number - * using getLatestVersion() + * using getLatestVersion(). * - * @return integer $nextVersion + * @return int $nextVersion */ public function getNextVersion() { @@ -285,19 +283,18 @@ public function getNextVersion() } /** - * Get the next incremented class version based on the loaded migration classes + * Get the next incremented class version based on the loaded migration classes. * - * @return integer $nextMigrationClassVersion + * @return int $nextMigrationClassVersion */ public function getNextMigrationClassVersion() { if (empty($this->_migrationClasses)) { return 1; - } else { - $nums = array_keys($this->_migrationClasses); - $num = end($nums) + 1; - return $num; } + $nums = array_keys($this->_migrationClasses); + + return end($nums) + 1; } /** @@ -305,9 +302,11 @@ public function getNextMigrationClassVersion() * migrate to. It will automatically know whether you are migrating up or down * based on the current version of the database. * - * @param integer $to Version to migrate to - * @param boolean $dryRun Whether or not to run the migrate process as a dry run - * @return integer $to Version number migrated to + * @param int $to Version to migrate to + * @param bool $dryRun Whether or not to run the migrate process as a dry run + * + * @return int $to Version number migrated to + * * @throws Doctrine_Exception */ public function migrate($to = null, $dryRun = false) @@ -321,7 +320,7 @@ public function migrate($to = null, $dryRun = false) try { // If nothing specified then lets assume we are migrating from // the current version to the latest version - if ($to === null) { + if (null === $to) { $to = $this->getLatestVersion(); } @@ -335,32 +334,33 @@ public function migrate($to = null, $dryRun = false) if ($dryRun) { return false; - } else { - $this->_throwErrorsException(); } + $this->_throwErrorsException(); } else { if ($dryRun) { $this->_connection->rollback(); if ($this->hasErrors()) { return false; - } else { - return $to; } - } else { - $this->_connection->commit(); - $this->setCurrentVersion($to); + return $to; } + $this->_connection->commit(); + $this->setCurrentVersion($to); + + return $to; } + return false; } /** * Run the migration process but rollback at the very end. Returns true or - * false for whether or not the migration can be ran + * false for whether or not the migration can be ran. * - * @param string $to - * @return boolean $success + * @param string $to + * + * @return bool $success */ public function migrateDryRun($to = null) { @@ -368,9 +368,9 @@ public function migrateDryRun($to = null) } /** - * Get the number of errors + * Get the number of errors. * - * @return integer $numErrors + * @return int $numErrors */ public function getNumErrors() { @@ -378,7 +378,7 @@ public function getNumErrors() } /** - * Get all the error exceptions + * Get all the error exceptions. * * @return array $errors */ @@ -388,9 +388,7 @@ public function getErrors() } /** - * Clears the error exceptions - * - * @return void + * Clears the error exceptions. */ public function clearErrors() { @@ -398,10 +396,7 @@ public function clearErrors() } /** - * Add an error to the stack. Excepts some type of Exception - * - * @param Exception $e - * @return void + * Add an error to the stack. Excepts some type of Exception. */ public function addError(Exception $e) { @@ -409,25 +404,27 @@ public function addError(Exception $e) } /** - * Whether or not the migration instance has errors + * Whether or not the migration instance has errors. * - * @return boolean + * @return bool */ public function hasErrors() { - return $this->getNumErrors() > 0 ? true:false; + return $this->getNumErrors() > 0 ? true : false; } /** - * Get instance of migration class for number/version specified + * Get instance of migration class for number/version specified. + * + * @param int $num * - * @param integer $num * @throws Doctrine_Migration_Exception $e */ public function getMigrationClass($num) { if (isset($this->_migrationClasses[$num])) { $className = $this->_migrationClasses[$num]; + return new $className(); } @@ -435,9 +432,8 @@ public function getMigrationClass($num) } /** - * Throw an exception with all the errors trigged during the migration + * Throw an exception with all the errors trigged during the migration. * - * @return void * @throws Doctrine_Migration_Exception $e */ protected function _throwErrorsException() @@ -445,23 +441,25 @@ protected function _throwErrorsException() $messages = array(); $num = 0; foreach ($this->getErrors() as $error) { - $num++; - $messages[] = ' Error #' . $num . ' - ' .$error->getMessage() . "\n" . $error->getTraceAsString() . "\n"; + ++$num; + $messages[] = ' Error #'.$num.' - '.$error->getMessage()."\n".$error->getTraceAsString()."\n"; } - $title = $this->getNumErrors() . ' error(s) encountered during migration'; - $message = $title . "\n"; - $message .= str_repeat('=', strlen($title)) . "\n"; + $title = $this->getNumErrors().' error(s) encountered during migration'; + $message = $title."\n"; + $message .= str_repeat('=', strlen($title))."\n"; $message .= implode("\n", $messages); throw new Doctrine_Migration_Exception($message); } /** - * Do the actual migration process + * Do the actual migration process. + * + * @param int $to + * + * @return int $to * - * @param integer $to - * @return integer $to * @throws Doctrine_Exception */ protected function _doMigrate($to) @@ -469,17 +467,17 @@ protected function _doMigrate($to) $from = $this->getCurrentVersion(); if ($from == $to) { - throw new Doctrine_Migration_Exception('Already at version # ' . $to); + throw new Doctrine_Migration_Exception('Already at version # '.$to); } - $direction = $from > $to ? 'down':'up'; + $direction = $from > $to ? 'down' : 'up'; - if ($direction === 'up') { - for ($i = $from + 1; $i <= $to; $i++) { + if ('up' === $direction) { + for ($i = $from + 1; $i <= $to; ++$i) { $this->_doMigrateStep($direction, $i); } } else { - for ($i = $from; $i > $to; $i--) { + for ($i = $from; $i > $to; --$i) { $this->_doMigrateStep($direction, $i); } } @@ -489,37 +487,36 @@ protected function _doMigrate($to) /** * Perform a single migration step. Executes a single migration class and - * processes the changes + * processes the changes. * * @param string $direction Direction to go, 'up' or 'down' - * @param integer $num - * @return void + * @param int $num */ protected function _doMigrateStep($direction, $num) { try { $migration = $this->getMigrationClass($num); - $method = 'pre' . $direction; - $migration->$method(); + $method = 'pre'.$direction; + $migration->{$method}(); if (method_exists($migration, $direction)) { - $migration->$direction(); - } else if (method_exists($migration, 'migrate')) { + $migration->{$direction}(); + } elseif (method_exists($migration, 'migrate')) { $migration->migrate($direction); } if ($migration->getNumChanges() > 0) { $changes = $migration->getChanges(); - if ($direction == 'down' && method_exists($migration, 'migrate')) { + if ('down' == $direction && method_exists($migration, 'migrate')) { $changes = array_reverse($changes); } foreach ($changes as $value) { list($type, $change) = $value; - $funcName = 'process' . Doctrine_Inflector::classify($type); + $funcName = 'process'.Doctrine_Inflector::classify($type); if (method_exists($this->_process, $funcName)) { try { - $this->_process->$funcName($change); + $this->_process->{$funcName}($change); } catch (Exception $e) { $this->addError($e); } @@ -529,8 +526,8 @@ protected function _doMigrateStep($direction, $num) } } - $method = 'post' . $direction; - $migration->$method(); + $method = 'post'.$direction; + $migration->{$method}(); } catch (Exception $e) { $this->addError($e); } @@ -538,10 +535,10 @@ protected function _doMigrateStep($direction, $num) /** * Create the migration table and return true. If it already exists it will - * silence the exception and return false + * silence the exception and return false. * - * @return boolean $created Whether or not the table was created. Exceptions - * are silenced when table already exists + * @return bool $created Whether or not the table was created. Exceptions + * are silenced when table already exists */ protected function _createMigrationTable() { @@ -555,8 +552,8 @@ protected function _createMigrationTable() $this->_connection->export->createTable($this->_migrationTableName, array('version' => array('type' => 'integer', 'size' => 11))); return true; - } catch(Exception $e) { + } catch (Exception $e) { return false; } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Migration/Base.php b/lib/Doctrine/Migration/Base.php index a2bcfb266..518fff28a 100644 --- a/lib/Doctrine/Migration/Base.php +++ b/lib/Doctrine/Migration/Base.php @@ -20,41 +20,42 @@ */ /** - * Base migration class. All migration classes must extend from this base class + * Base migration class. All migration classes must extend from this base class. * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.1 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ abstract class Doctrine_Migration_Base { /** - * The default options for tables created using Doctrine_Migration_Base::createTable() - * + * The default options for tables created using Doctrine_Migration_Base::createTable(). + * * @var array */ private static $defaultTableOptions = array(); protected $_changes = array(); - protected static $_opposites = array('created_table' => 'dropped_table', - 'dropped_table' => 'created_table', - 'created_constraint' => 'dropped_constraint', - 'dropped_constraint' => 'created_constraint', - 'created_foreign_key' => 'dropped_foreign_key', - 'dropped_foreign_key' => 'created_foreign_key', - 'created_column' => 'dropped_column', - 'dropped_column' => 'created_column', - 'created_index' => 'dropped_index', - 'dropped_index' => 'created_index', - ); + protected static $_opposites = array('created_table' => 'dropped_table', + 'dropped_table' => 'created_table', + 'created_constraint' => 'dropped_constraint', + 'dropped_constraint' => 'created_constraint', + 'created_foreign_key' => 'dropped_foreign_key', + 'dropped_foreign_key' => 'created_foreign_key', + 'created_column' => 'dropped_column', + 'dropped_column' => 'created_column', + 'created_index' => 'dropped_index', + 'dropped_index' => 'created_index', + ); /** - * Get the changes that have been added on this migration class instance + * Get the changes that have been added on this migration class instance. * * @return array $changes */ @@ -69,29 +70,28 @@ public function getNumChanges() } /** - * Add a change to the stack of changes to execute + * Add a change to the stack of changes to execute. * - * @param string $type The type of change - * @param array $change The array of information for the change - * @return void + * @param string $type The type of change + * @param array $change The array of information for the change */ protected function _addChange($type, array $change = array()) { - if (isset($change['upDown']) && $change['upDown'] !== null && isset(self::$_opposites[$type])) { + if (isset($change['upDown']) && null !== $change['upDown'] && isset(self::$_opposites[$type])) { $upDown = $change['upDown']; unset($change['upDown']); - if ($upDown == 'down') { + if ('down' == $upDown) { $opposite = self::$_opposites[$type]; + return $this->_changes[] = array($opposite, $change); } } + return $this->_changes[] = array($type, $change); } /** - * Sets the default options for tables created using Doctrine_Migration_Base::createTable() - * - * @param array $options + * Sets the default options for tables created using Doctrine_Migration_Base::createTable(). */ public static function setDefaultTableOptions(array $options) { @@ -99,8 +99,8 @@ public static function setDefaultTableOptions(array $options) } /** - * Returns the default options for tables created using Doctrine_Migration_Base::createTable() - * + * Returns the default options for tables created using Doctrine_Migration_Base::createTable(). + * * @return array */ public static function getDefaultTableOptions() @@ -111,11 +111,10 @@ public static function getDefaultTableOptions() /** * Add a create or drop table change. * - * @param string $upDown Whether to add the up(create) or down(drop) table change. - * @param string $tableName Name of the table - * @param array $fields Array of fields for table - * @param array $options Array of options for the table - * @return void + * @param string $upDown whether to add the up(create) or down(drop) table change + * @param string $tableName Name of the table + * @param array $fields Array of fields for table + * @param array $options Array of options for the table */ public function table($upDown, $tableName, array $fields = array(), array $options = array()) { @@ -127,10 +126,9 @@ public function table($upDown, $tableName, array $fields = array(), array $optio /** * Add a create table change. * - * @param string $tableName Name of the table - * @param array $fields Array of fields for table - * @param array $options Array of options for the table - * @return void + * @param string $tableName Name of the table + * @param array $fields Array of fields for table + * @param array $options Array of options for the table */ public function createTable($tableName, array $fields = array(), array $options = array()) { @@ -140,8 +138,7 @@ public function createTable($tableName, array $fields = array(), array $options /** * Add a drop table change. * - * @param string $tableName Name of the table - * @return void + * @param string $tableName Name of the table */ public function dropTable($tableName) { @@ -149,42 +146,38 @@ public function dropTable($tableName) } /** - * Add a rename table change + * Add a rename table change. * - * @param string $oldTableName Name of the table to change - * @param string $newTableName Name to change the table to - * @return void + * @param string $oldTableName Name of the table to change + * @param string $newTableName Name to change the table to */ public function renameTable($oldTableName, $newTableName) { $options = get_defined_vars(); - + $this->_addChange('renamed_table', $options); } /** * Add a create or drop constraint change. * - * @param string $upDown Whether to add the up(create) or down(drop) create change. - * @param string $tableName Name of the table. - * @param string $constraintName Name of the constraint. - * @param array $definition Array for the constraint definition. - * @return void + * @param string $upDown whether to add the up(create) or down(drop) create change + * @param string $tableName name of the table + * @param string $constraintName name of the constraint + * @param array $definition array for the constraint definition */ public function constraint($upDown, $tableName, $constraintName, array $definition) { $options = get_defined_vars(); - + $this->_addChange('created_constraint', $options); } /** * Add a create constraint change. * - * @param string $tableName Name of the table. - * @param string $constraintname Name of the constraint. - * @param array $definition Array for the constraint definition. - * @return void + * @param string $tableName name of the table + * @param array $definition array for the constraint definition */ public function createConstraint($tableName, $constraintName, array $definition) { @@ -194,9 +187,7 @@ public function createConstraint($tableName, $constraintName, array $definition) /** * Add a drop constraint change. * - * @param string $tableName Name of the table. - * @param string $constraintname Name of the constraint. - * @return void + * @param string $tableName name of the table */ public function dropConstraint($tableName, $constraintName, $primary = false) { @@ -206,14 +197,13 @@ public function dropConstraint($tableName, $constraintName, $primary = false) /** * Convenience method for creating or dropping primary keys. * - * @param string $direction - * @param string $tableName Name of the table - * @param string $columnNames Array of column names and column definitions - * @return void + * @param string $direction + * @param string $tableName Name of the table + * @param string $columnNames Array of column names and column definitions */ public function primaryKey($direction, $tableName, $columnNames) { - if ($direction == 'up') { + if ('up' == $direction) { $this->createPrimaryKey($tableName, $columnNames); } else { $this->dropPrimaryKey($tableName, $columnNames); @@ -221,7 +211,7 @@ public function primaryKey($direction, $tableName, $columnNames) } /** - * Convenience method for creating primary keys + * Convenience method for creating primary keys. * * [php] * $columns = array( @@ -237,10 +227,9 @@ public function primaryKey($direction, $tableName, $columnNames) * * Add new columns (addColumn()) * * Create primary constraint on columns (createConstraint()) * * Change autoincrement = true field to be autoincrement - * - * @param string $tableName Name of the table - * @param string $columnNames Array of column names and column definitions - * @return void + * + * @param string $tableName Name of the table + * @param string $columnNames Array of column names and column definitions */ public function createPrimaryKey($tableName, $columnNames) { @@ -270,7 +259,7 @@ public function createPrimaryKey($tableName, $columnNames) // Create the primary constraint for the columns $this->createConstraint($tableName, null, array( 'primary' => true, - 'fields' => $fields + 'fields' => $fields, )); // If auto increment change the column to be so @@ -297,9 +286,8 @@ public function createPrimaryKey($tableName, $columnNames) * * Remove primary constraint (dropConstraint()) * * Removing columns (removeColumn()) * - * @param string $tableName Name of the table - * @param string $columnNames Array of column names and column definitions - * @return void + * @param string $tableName Name of the table + * @param string $columnNames Array of column names and column definitions */ public function dropPrimaryKey($tableName, $columnNames) { @@ -324,11 +312,10 @@ public function dropPrimaryKey($tableName, $columnNames) /** * Add a create or drop foreign key change. * - * @param string $upDown Whether to add the up(create) or down(drop) foreign key change. - * @param string $tableName Name of the table. - * @param string $name Name of the foreign key. - * @param array $definition Array for the foreign key definition - * @return void + * @param string $upDown whether to add the up(create) or down(drop) foreign key change + * @param string $tableName name of the table + * @param string $name name of the foreign key + * @param array $definition Array for the foreign key definition */ public function foreignKey($upDown, $tableName, $name, array $definition = array()) { @@ -341,10 +328,9 @@ public function foreignKey($upDown, $tableName, $name, array $definition = array /** * Add a create foreign key change. * - * @param string $tableName Name of the table. - * @param string $name Name of the foreign key. - * @param array $definition Array for the foreign key definition - * @return void + * @param string $tableName name of the table + * @param string $name name of the foreign key + * @param array $definition Array for the foreign key definition */ public function createForeignKey($tableName, $name, array $definition) { @@ -354,9 +340,8 @@ public function createForeignKey($tableName, $name, array $definition) /** * Add a drop foreign key change. * - * @param string $tableName Name of the table. - * @param string $name Name of the foreign key. - * @return void + * @param string $tableName name of the table + * @param string $name name of the foreign key */ public function dropForeignKey($tableName, $name) { @@ -366,18 +351,17 @@ public function dropForeignKey($tableName, $name) /** * Add a add or remove column change. * - * @param string $upDown Whether to add the up(add) or down(remove) column change. - * @param string $tableName Name of the table - * @param string $columnName Name of the column - * @param string $type Type of the column - * @param string $length Length of the column - * @param array $options Array of options for the column - * @return void + * @param string $upDown whether to add the up(add) or down(remove) column change + * @param string $tableName Name of the table + * @param string $columnName Name of the column + * @param string $type Type of the column + * @param string $length Length of the column + * @param array $options Array of options for the column */ public function column($upDown, $tableName, $columnName, $type = null, $length = null, array $options = array()) { $options = get_defined_vars(); - if ( ! isset($options['options']['length'])) { + if (!isset($options['options']['length'])) { $options['options']['length'] = $length; } $options = array_merge($options, $options['options']); @@ -389,12 +373,11 @@ public function column($upDown, $tableName, $columnName, $type = null, $length = /** * Add a add column change. * - * @param string $tableName Name of the table - * @param string $columnName Name of the column - * @param string $type Type of the column - * @param string $length Length of the column - * @param array $options Array of options for the column - * @return void + * @param string $tableName Name of the table + * @param string $columnName Name of the column + * @param string $type Type of the column + * @param string $length Length of the column + * @param array $options Array of options for the column */ public function addColumn($tableName, $columnName, $type, $length = null, array $options = array()) { @@ -404,9 +387,8 @@ public function addColumn($tableName, $columnName, $type, $length = null, array /** * Add a remove column change. * - * @param string $tableName Name of the table - * @param string $columnName Name of the column - * @return void + * @param string $tableName Name of the table + * @param string $columnName Name of the column */ public function removeColumn($tableName, $columnName) { @@ -414,29 +396,27 @@ public function removeColumn($tableName, $columnName) } /** - * Add a rename column change + * Add a rename column change. * - * @param string $tableName Name of the table to rename the column on - * @param string $oldColumnName The old column name - * @param string $newColumnName The new column name - * @return void + * @param string $tableName Name of the table to rename the column on + * @param string $oldColumnName The old column name + * @param string $newColumnName The new column name */ public function renameColumn($tableName, $oldColumnName, $newColumnName) { $options = get_defined_vars(); - + $this->_addChange('renamed_column', $options); } /** - * Add a change column change + * Add a change column change. * - * @param string $tableName Name of the table to change the column on - * @param string $columnName Name of the column to change - * @param string $type New type of column - * @param string $length The length of the column - * @param array $options New options for the column - * @return void + * @param string $tableName Name of the table to change the column on + * @param string $columnName Name of the column to change + * @param string $type New type of column + * @param string $length The length of the column + * @param array $options New options for the column */ public function changeColumn($tableName, $columnName, $type = null, $length = null, array $options = array()) { @@ -449,26 +429,24 @@ public function changeColumn($tableName, $columnName, $type = null, $length = nu /** * Add a add or remove index change. * - * @param string $upDown Whether to add the up(add) or down(remove) index change. - * @param string $tableName Name of the table - * @param string $indexName Name of the index - * @param array $definition Array for the index definition - * @return void + * @param string $upDown whether to add the up(add) or down(remove) index change + * @param string $tableName Name of the table + * @param string $indexName Name of the index + * @param array $definition Array for the index definition */ public function index($upDown, $tableName, $indexName, array $definition = array()) { $options = get_defined_vars(); - + $this->_addChange('created_index', $options); } /** * Add a add index change. * - * @param string $tableName Name of the table - * @param string $indexName Name of the index - * @param array $definition Array for the index definition - * @return void + * @param string $tableName Name of the table + * @param string $indexName Name of the index + * @param array $definition Array for the index definition */ public function addIndex($tableName, $indexName, array $definition) { @@ -478,9 +456,8 @@ public function addIndex($tableName, $indexName, array $definition) /** * Add a remove index change. * - * @param string $tableName Name of the table - * @param string $indexName Name of the index - * @return void + * @param string $tableName Name of the table + * @param string $indexName Name of the index */ public function removeIndex($tableName, $indexName) { @@ -502,4 +479,4 @@ public function preDown() public function postDown() { } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Migration/Builder.php b/lib/Doctrine/Migration/Builder.php index e6ed9042a..544f9b70e 100644 --- a/lib/Doctrine/Migration/Builder.php +++ b/lib/Doctrine/Migration/Builder.php @@ -20,62 +20,60 @@ */ /** - * Doctrine_Migration_Builder + * Doctrine_Migration_Builder. * - * @package Doctrine - * @subpackage Migration * @author Konsta Vesterinen * @author Jonathan H. Wage * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2939 $ */ class Doctrine_Migration_Builder extends Doctrine_Builder { /** - * The path to your migration classes directory + * The path to your migration classes directory. * * @var string */ private $migrationsPath = ''; /** - * File suffix to use when writing class definitions + * File suffix to use when writing class definitions. * - * @var string $suffix + * @var string */ private $suffix = '.php'; /** - * Instance of the migration class for the migration classes directory + * Instance of the migration class for the migration classes directory. * - * @var Doctrine_Migration $migration + * @var Doctrine_Migration */ private $migration; /** - * Class template used for writing classes - * - * @var $tpl + * Class template used for writing classes. */ private static $tpl; /** - * Instantiate new instance of the Doctrine_Migration_Builder class + * Instantiate new instance of the Doctrine_Migration_Builder class. * * * $builder = new Doctrine_Migration_Builder('/path/to/migrations'); * * - * @return void + * @param mixed|null $migrationsPath */ public function __construct($migrationsPath = null) { if ($migrationsPath instanceof Doctrine_Migration) { $this->setMigrationsPath($migrationsPath->getMigrationClassesDirectory()); $this->migration = $migrationsPath; - } else if (is_dir((string) $migrationsPath)) { + } elseif (is_dir((string) $migrationsPath)) { $this->setMigrationsPath($migrationsPath); $this->migration = new Doctrine_Migration($migrationsPath); } @@ -84,10 +82,9 @@ public function __construct($migrationsPath = null) } /** - * Set the path to write the generated migration classes + * Set the path to write the generated migration classes. * * @param string path the path where migration classes are stored and being generated - * @return void */ public function setMigrationsPath($path) { @@ -97,9 +94,9 @@ public function setMigrationsPath($path) } /** - * Get the path where generated migration classes are written to + * Get the path where generated migration classes are written to. * - * @return string the path where migration classes are stored and being generated + * @return string the path where migration classes are stored and being generated */ public function getMigrationsPath() { @@ -107,9 +104,7 @@ public function getMigrationsPath() } /** - * Loads the class template used for generating classes - * - * @return void + * Loads the class template used for generating classes. */ protected function loadTemplate() { @@ -117,7 +112,7 @@ protected function loadTemplate() return; } - self::$tpl =<< $table) { $up[] = $this->buildDropTable($table); $down[] = $this->buildCreateTable($table); } } - if ( ! empty($changes['created_tables'])) { + if (!empty($changes['created_tables'])) { foreach ($changes['created_tables'] as $tableName => $table) { $up[] = $this->buildCreateTable($table); $down[] = $this->buildDropTable($table); } } - if ( ! empty($changes['dropped_columns'])) { + if (!empty($changes['dropped_columns'])) { foreach ($changes['dropped_columns'] as $tableName => $removedColumns) { foreach ($removedColumns as $name => $column) { $up[] = $this->buildRemoveColumn($tableName, $name, $column); @@ -172,7 +168,7 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['created_columns'])) { + if (!empty($changes['created_columns'])) { foreach ($changes['created_columns'] as $tableName => $addedColumns) { foreach ($addedColumns as $name => $column) { $up[] = $this->buildAddColumn($tableName, $name, $column); @@ -181,7 +177,7 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['changed_columns'])) { + if (!empty($changes['changed_columns'])) { foreach ($changes['changed_columns'] as $tableName => $changedColumns) { foreach ($changedColumns as $name => $column) { $up[] = $this->buildChangeColumn($tableName, $name, $column); @@ -189,19 +185,19 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($up) || ! empty($down)) { + if (!empty($up) || !empty($down)) { $up = implode("\n", $up); $down = implode("\n", $down); - $className = 'Version' . $this->migration->getNextMigrationClassVersion(); + $className = 'Version'.$this->migration->getNextMigrationClassVersion(); $this->generateMigrationClass($className, array(), $up, $down); } $up = array(); $down = array(); - if ( ! empty($changes['dropped_foreign_keys'])) { + if (!empty($changes['dropped_foreign_keys'])) { foreach ($changes['dropped_foreign_keys'] as $tableName => $droppedFks) { - if ( ! empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { - continue; + if (!empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { + continue; } foreach ($droppedFks as $name => $foreignKey) { @@ -211,10 +207,10 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['dropped_indexes'])) { + if (!empty($changes['dropped_indexes'])) { foreach ($changes['dropped_indexes'] as $tableName => $removedIndexes) { - if ( ! empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { - continue; + if (!empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { + continue; } foreach ($removedIndexes as $name => $index) { @@ -224,10 +220,10 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['created_foreign_keys'])) { + if (!empty($changes['created_foreign_keys'])) { foreach ($changes['created_foreign_keys'] as $tableName => $createdFks) { - if ( ! empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { - continue; + if (!empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { + continue; } foreach ($createdFks as $name => $foreignKey) { @@ -237,10 +233,10 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($changes['created_indexes'])) { + if (!empty($changes['created_indexes'])) { foreach ($changes['created_indexes'] as $tableName => $addedIndexes) { - if ( ! empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { - continue; + if (!empty($changes['dropped_tables']) && isset($changes['dropped_tables'][$tableName])) { + continue; } foreach ($addedIndexes as $name => $index) { @@ -253,23 +249,22 @@ public function generateMigrationsFromDiff(Doctrine_Migration_Diff $diff) } } - if ( ! empty($up) || ! empty($down)) { + if (!empty($up) || !empty($down)) { $up = implode("\n", $up); $down = implode("\n", $down); - $className = 'Version' . $this->migration->getNextMigrationClassVersion(); + $className = 'Version'.$this->migration->getNextMigrationClassVersion(); $this->generateMigrationClass($className, array(), $up, $down); } + return $changes; } /** - * Generate a set of migration classes from the existing databases - * - * @return void + * Generate a set of migration classes from the existing databases. */ public function generateMigrationsFromDb() { - $directory = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'tmp_doctrine_models'; + $directory = sys_get_temp_dir().DIRECTORY_SEPARATOR.'tmp_doctrine_models'; Doctrine_Core::generateModelsFromDb($directory); @@ -281,15 +276,16 @@ public function generateMigrationsFromDb() } /** - * Generate a set of migrations from a set of models + * Generate a set of migrations from a set of models. + * + * @param string $modelsPath Path to models + * @param string $modelLoading What type of model loading to use when loading the models * - * @param string $modelsPath Path to models - * @param string $modelLoading What type of model loading to use when loading the models - * @return boolean + * @return bool */ public function generateMigrationsFromModels($modelsPath = null, $modelLoading = null) { - if ($modelsPath !== null) { + if (null !== $modelsPath) { $models = Doctrine_Core::filterInvalidModels(Doctrine_Core::loadModels($modelsPath, $modelLoading)); } else { $models = Doctrine_Core::getLoadedModels(); @@ -309,18 +305,18 @@ public function generateMigrationsFromModels($modelsPath = null, $modelLoading = $up = $this->buildCreateTable($export); $down = $this->buildDropTable($export); - $className = 'Add' . Doctrine_Inflector::classify($export['tableName']); + $className = 'Add'.Doctrine_Inflector::classify($export['tableName']); $this->generateMigrationClass($className, array(), $up, $down); } } - if ( ! empty($foreignKeys)) { + if (!empty($foreignKeys)) { $className = 'AddFks'; $up = array(); $down = array(); - foreach ($foreignKeys as $tableName => $definitions) { + foreach ($foreignKeys as $tableName => $definitions) { $tableForeignKeyNames[$tableName] = array(); foreach ($definitions as $definition) { @@ -340,40 +336,43 @@ public function generateMigrationsFromModels($modelsPath = null, $modelLoading = } /** - * Build the code for creating foreign keys + * Build the code for creating foreign keys. + * + * @param string $tableName + * @param array $definition * - * @param string $tableName - * @param array $definition * @return string $code */ public function buildCreateForeignKey($tableName, $definition) { - return " \$this->createForeignKey('" . $tableName . "', '" . $definition['name'] . "', " . $this->varExport($definition, true) . ");"; + return " \$this->createForeignKey('".$tableName."', '".$definition['name']."', ".$this->varExport($definition, true).');'; } /** - * Build the code for dropping foreign keys + * Build the code for dropping foreign keys. + * + * @param string $tableName + * @param array $definition * - * @param string $tableName - * @param array $definition * @return string $code */ public function buildDropForeignKey($tableName, $definition) { - return " \$this->dropForeignKey('" . $tableName . "', '" . $definition['name'] . "');"; + return " \$this->dropForeignKey('".$tableName."', '".$definition['name']."');"; } /** - * Build the code for creating tables + * Build the code for creating tables. + * + * @param string $tableData * - * @param string $tableData * @return string $code */ public function buildCreateTable($tableData) { - $code = " \$this->createTable('" . $tableData['tableName'] . "', "; + $code = " \$this->createTable('".$tableData['tableName']."', "; - $code .= $this->varExport($tableData['columns'], true) . ", "; + $code .= $this->varExport($tableData['columns'], true).', '; $optionsWeNeed = array('type', 'indexes', 'primary', 'collate', 'charset'); @@ -386,28 +385,30 @@ public function buildCreateTable($tableData) $code .= $this->varExport($options, true); - $code .= ");"; + $code .= ');'; return $code; } /** - * Build the code for dropping tables + * Build the code for dropping tables. + * + * @param string $tableData * - * @param string $tableData * @return string $code */ public function buildDropTable($tableData) { - return " \$this->dropTable('" . $tableData['tableName'] . "');"; + return " \$this->dropTable('".$tableData['tableName']."');"; } /** - * Build the code for adding columns + * Build the code for adding columns. * * @param string $tableName * @param string $columnName * @param string $column + * * @return string $code */ public function buildAddColumn($tableName, $columnName, $column) @@ -415,28 +416,31 @@ public function buildAddColumn($tableName, $columnName, $column) $length = $column['length']; $type = $column['type']; unset($column['length'], $column['type']); - return " \$this->addColumn('" . $tableName . "', '" . $columnName. "', '" . $type . "', '" . $length . "', " . $this->varExport($column) . ");"; + + return " \$this->addColumn('".$tableName."', '".$columnName."', '".$type."', '".$length."', ".$this->varExport($column).');'; } /** - * Build the code for removing columns + * Build the code for removing columns. * * @param string $tableName * @param string $columnName * @param string $column + * * @return string $code */ public function buildRemoveColumn($tableName, $columnName, $column) { - return " \$this->removeColumn('" . $tableName . "', '" . $columnName. "');"; + return " \$this->removeColumn('".$tableName."', '".$columnName."');"; } /** - * Build the code for changing columns + * Build the code for changing columns. * * @param string $tableName * @param string $columnName * @param string $column + * * @return string $code */ public function buildChangeColumn($tableName, $columnName, $column) @@ -444,45 +448,47 @@ public function buildChangeColumn($tableName, $columnName, $column) $length = $column['length']; $type = $column['type']; unset($column['length'], $column['type']); - return " \$this->changeColumn('" . $tableName . "', '" . $columnName. "', '" . $type . "', '" . $length . "', " . $this->varExport($column) . ");"; + + return " \$this->changeColumn('".$tableName."', '".$columnName."', '".$type."', '".$length."', ".$this->varExport($column).');'; } /** - * Build the code for adding indexes + * Build the code for adding indexes. * * @param string $tableName * @param string $indexName * @param string $index + * * @return sgtring $code */ public function buildAddIndex($tableName, $indexName, $index) { - return " \$this->addIndex('$tableName', '$indexName', " . $this->varExport($index) . ");"; + return " \$this->addIndex('{$tableName}', '{$indexName}', ".$this->varExport($index).');'; } /** - * Build the code for removing indexes + * Build the code for removing indexes. * * @param string $tableName * @param string $indexName * @param string $index + * * @return string $code */ public function buildRemoveIndex($tableName, $indexName, $index) { - return " \$this->removeIndex('$tableName', '$indexName', " . $this->varExport($index) . ");"; + return " \$this->removeIndex('{$tableName}', '{$indexName}', ".$this->varExport($index).');'; } /** - * Generate a migration class - * - * @param string $className Class name to generate - * @param array $options Options for the migration class - * @param string $up The code for the up function - * @param string $down The code for the down function - * @param boolean $return Whether or not to return the code. - * If true return and false it writes the class to disk. - * @return mixed + * Generate a migration class. + * + * @param string $className Class name to generate + * @param array $options Options for the migration class + * @param string $up The code for the up function + * @param string $down The code for the down function + * @param bool $return Whether or not to return the code. + * If true return and false it writes the class to disk. */ public function generateMigrationClass($className, $options = array(), $up = null, $down = null, $return = false) { @@ -490,53 +496,54 @@ public function generateMigrationClass($className, $options = array(), $up = nul $className = str_replace('-', '_', $className); $className = Doctrine_Inflector::classify($className); - if ($return || ! $this->getMigrationsPath()) { + if ($return || !$this->getMigrationsPath()) { return $this->buildMigrationClass($className, null, $options, $up, $down); - } else { - if ( ! $this->getMigrationsPath()) { - throw new Doctrine_Migration_Exception('You must specify the path to your migrations.'); - } - - $next = time() + $this->migration->getNextMigrationClassVersion(); - $fileName = $next . '_' . Doctrine_Inflector::tableize($className) . $this->suffix; + } + if (!$this->getMigrationsPath()) { + throw new Doctrine_Migration_Exception('You must specify the path to your migrations.'); + } - $class = $this->buildMigrationClass($className, $fileName, $options, $up, $down); + $next = time() + $this->migration->getNextMigrationClassVersion(); + $fileName = $next.'_'.Doctrine_Inflector::tableize($className).$this->suffix; - $path = $this->getMigrationsPath() . DIRECTORY_SEPARATOR . $fileName; - if (class_exists($className) || file_exists($path)) { - $this->migration->loadMigrationClass($className); - return false; - } + $class = $this->buildMigrationClass($className, $fileName, $options, $up, $down); - file_put_contents($path, $class); - require_once($path); + $path = $this->getMigrationsPath().DIRECTORY_SEPARATOR.$fileName; + if (class_exists($className) || file_exists($path)) { $this->migration->loadMigrationClass($className); - return true; + return false; } + + file_put_contents($path, $class); + require_once $path; + $this->migration->loadMigrationClass($className); + + return true; } /** - * Build the code for a migration class + * Build the code for a migration class. + * + * @param string $className Class name to generate + * @param string $fileName File name to write the class to + * @param array $options Options for the migration class + * @param string $up The code for the up function + * @param string $down The code for the down function * - * @param string $className Class name to generate - * @param string $fileName File name to write the class to - * @param array $options Options for the migration class - * @param string $up The code for the up function - * @param string $down The code for the down function * @return string $content The code for the generated class */ public function buildMigrationClass($className, $fileName = null, $options = array(), $up = null, $down = null) { - $extends = isset($options['extends']) ? $options['extends']:'Doctrine_Migration_Base'; + $extends = isset($options['extends']) ? $options['extends'] : 'Doctrine_Migration_Base'; - $content = ' */ class Doctrine_Migration_Diff { - protected $_from, - $_to, - $_changes = array('created_tables' => array(), - 'dropped_tables' => array(), - 'created_foreign_keys'=> array(), - 'dropped_foreign_keys'=> array(), - 'created_columns' => array(), - 'dropped_columns' => array(), - 'changed_columns' => array(), - 'created_indexes' => array(), - 'dropped_indexes' => array()), - $_migration, - $_startingModelFiles = array(), - $_tmpPath; - - protected static $_toPrefix = 'ToPrfx', - $_fromPrefix = 'FromPrfx'; + protected $_from; + protected $_to; + protected $_changes = array('created_tables' => array(), + 'dropped_tables' => array(), + 'created_foreign_keys' => array(), + 'dropped_foreign_keys' => array(), + 'created_columns' => array(), + 'dropped_columns' => array(), + 'changed_columns' => array(), + 'created_indexes' => array(), + 'dropped_indexes' => array()); + protected $_migration; + protected $_startingModelFiles = array(); + protected $_tmpPath; + + protected static $_toPrefix = 'ToPrfx'; + protected static $_fromPrefix = 'FromPrfx'; /** - * Instantiate new Doctrine_Migration_Diff instance + * Instantiate new Doctrine_Migration_Diff instance. * * * $diff = new Doctrine_Migration_Diff('/path/to/old_models', '/path/to/new_models', '/path/to/migrations'); @@ -62,44 +63,42 @@ class Doctrine_Migration_Diff * @param string $from The from schema information source * @param string $to The to schema information source * @param mixed $migration Instance of Doctrine_Migration or path to migration classes - * @return void */ public function __construct($from, $to, $migration) { $this->_from = $from; $this->_to = $to; $this->_startingModelFiles = Doctrine_Core::getLoadedModelFiles(); - $this->setTmpPath(sys_get_temp_dir() . DIRECTORY_SEPARATOR . getmypid()); + $this->setTmpPath(sys_get_temp_dir().DIRECTORY_SEPARATOR.getmypid()); if ($migration instanceof Doctrine_Migration) { $this->_migration = $migration; - } else if (is_dir($migration)) { + } elseif (is_dir($migration)) { $this->_migration = new Doctrine_Migration($migration); } } /** - * Set the temporary path to store the generated models for generating diffs + * Set the temporary path to store the generated models for generating diffs. * * @param string $tmpPath - * @return void */ public function setTmpPath($tmpPath) { - if ( ! is_dir($tmpPath)) { + if (!is_dir($tmpPath)) { mkdir($tmpPath, 0777, true); } $this->_tmpPath = $tmpPath; } /** - * Get unique hash id for this migration instance + * Get unique hash id for this migration instance. * * @return string $uniqueId */ protected function getUniqueId() { - return md5($this->_from . $this->_to); + return md5($this->_from.$this->_to); } /** @@ -112,11 +111,11 @@ public function generateChanges() $this->_cleanup(); $from = $this->_generateModels( - Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) . self::$_fromPrefix, + Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX).self::$_fromPrefix, $this->_from ); $to = $this->_generateModels( - Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX) . self::$_toPrefix, + Doctrine_Manager::getInstance()->getAttribute(Doctrine_Core::ATTR_MODEL_CLASS_PREFIX).self::$_toPrefix, $this->_to ); @@ -124,7 +123,7 @@ public function generateChanges() } /** - * Generate a migration class for the changes in this diff instance + * Generate a migration class for the changes in this diff instance. * * @return array $changes */ @@ -139,13 +138,14 @@ public function generateMigrationClasses() * Initialize some Doctrine models at a given path. * * @param string $path + * * @return array $models */ protected function _initializeModels($path) { $manager = Doctrine_Manager::getInstance(); $modelLoading = $manager->getAttribute(Doctrine_Core::ATTR_MODEL_LOADING); - if ($modelLoading === Doctrine_Core::MODEL_LOADING_PEAR) { + if (Doctrine_Core::MODEL_LOADING_PEAR === $modelLoading) { $orig = Doctrine_Core::getModelsDirectory(); Doctrine_Core::setModelsDirectory($path); $models = Doctrine_Core::initializeModels(Doctrine_Core::loadModels($path)); @@ -153,15 +153,17 @@ protected function _initializeModels($path) } else { $models = Doctrine_Core::initializeModels(Doctrine_Core::loadModels($path)); } + return $models; } /** - * Generate a diff between the from and to schema information + * Generate a diff between the from and to schema information. + * + * @param string $from Path to set of models to migrate from + * @param string $to Path to set of models to migrate to * - * @param string $from Path to set of models to migrate from - * @param string $to Path to set of models to migrate to - * @return array $changes + * @return array $changes */ protected function _diff($from, $to) { @@ -182,10 +184,11 @@ protected function _diff($from, $to) } /** - * Build array of changes between the from and to array of schema information + * Build array of changes between the from and to array of schema information. + * + * @param array $from Array of schema information to generate changes from + * @param array $to Array of schema information to generate changes for * - * @param array $from Array of schema information to generate changes from - * @param array $to Array of schema information to generate changes for * @return array $changes */ protected function _buildChanges($from, $to) @@ -193,7 +196,7 @@ protected function _buildChanges($from, $to) // Loop over the to schema information and compare it to the from foreach ($to as $className => $info) { // If the from doesn't have this class then it is a new table - if ( ! isset($from[$className])) { + if (!isset($from[$className])) { $names = array('type', 'charset', 'collate', 'indexes', 'foreignKeys', 'primary'); $options = array(); foreach ($names as $name) { @@ -203,14 +206,14 @@ protected function _buildChanges($from, $to) } $table = array('tableName' => $info['tableName'], - 'columns' => $info['columns'], - 'options' => $options); + 'columns' => $info['columns'], + 'options' => $options); $this->_changes['created_tables'][$info['tableName']] = $table; } // Check for new and changed columns foreach ($info['columns'] as $name => $column) { // If column doesn't exist in the from schema information then it is a new column - if (isset($from[$className]) && ! isset($from[$className]['columns'][$name])) { + if (isset($from[$className]) && !isset($from[$className]['columns'][$name])) { $this->_changes['created_columns'][$info['tableName']][$name] = $column; } // If column exists in the from schema information but is not the same then it is a changed column @@ -222,12 +225,12 @@ protected function _buildChanges($from, $to) foreach ($info['options']['foreignKeys'] as $name => $foreignKey) { $foreignKey['name'] = $name; // If foreign key doesn't exist in the from schema information then we need to add a index and the new fk - if ( ! isset($from[$className]['options']['foreignKeys'][$name])) { + if (!isset($from[$className]['options']['foreignKeys'][$name])) { $this->_changes['created_foreign_keys'][$info['tableName']][$name] = $foreignKey; $indexName = Doctrine_Manager::connection()->generateUniqueIndexName($info['tableName'], $foreignKey['local']); $this->_changes['created_indexes'][$info['tableName']][$indexName] = array('fields' => array($foreignKey['local'])); // If foreign key does exist then lets see if anything has changed with it - } else if (isset($from[$className]['options']['foreignKeys'][$name])) { + } elseif (isset($from[$className]['options']['foreignKeys'][$name])) { $oldForeignKey = $from[$className]['options']['foreignKeys'][$name]; $oldForeignKey['name'] = $name; // If the foreign key has changed any then we need to drop the foreign key and readd it @@ -240,7 +243,7 @@ protected function _buildChanges($from, $to) // Check for new indexes foreach ($info['options']['indexes'] as $name => $index) { // If index doesn't exist in the from schema information - if ( ! isset($from[$className]['options']['indexes'][$name])) { + if (!isset($from[$className]['options']['indexes'][$name])) { $this->_changes['created_indexes'][$info['tableName']][$name] = $index; } } @@ -248,35 +251,35 @@ protected function _buildChanges($from, $to) // Loop over the from schema information and compare it to the to schema information foreach ($from as $className => $info) { // If the class exists in the from but not in the to then it is a dropped table - if ( ! isset($to[$className])) { + if (!isset($to[$className])) { $table = array('tableName' => $info['tableName'], - 'columns' => $info['columns'], - 'options' => array('type' => $info['options']['type'], - 'charset' => $info['options']['charset'], - 'collate' => $info['options']['collate'], - 'indexes' => $info['options']['indexes'], - 'foreignKeys' => $info['options']['foreignKeys'], - 'primary' => $info['options']['primary'])); + 'columns' => $info['columns'], + 'options' => array('type' => $info['options']['type'], + 'charset' => $info['options']['charset'], + 'collate' => $info['options']['collate'], + 'indexes' => $info['options']['indexes'], + 'foreignKeys' => $info['options']['foreignKeys'], + 'primary' => $info['options']['primary'])); $this->_changes['dropped_tables'][$info['tableName']] = $table; } // Check for removed columns foreach ($info['columns'] as $name => $column) { // If column exists in the from but not in the to then we need to remove it - if (isset($to[$className]) && ! isset($to[$className]['columns'][$name])) { + if (isset($to[$className]) && !isset($to[$className]['columns'][$name])) { $this->_changes['dropped_columns'][$info['tableName']][$name] = $column; } } // Check for dropped foreign keys foreach ($info['options']['foreignKeys'] as $name => $foreignKey) { // If the foreign key exists in the from but not in the to then we need to drop it - if ( ! isset($to[$className]['options']['foreignKeys'][$name])) { + if (!isset($to[$className]['options']['foreignKeys'][$name])) { $this->_changes['dropped_foreign_keys'][$info['tableName']][$name] = $foreignKey; } } // Check for removed indexes foreach ($info['options']['indexes'] as $name => $index) { // If the index exists in the from but not the to then we need to remove it - if ( ! isset($to[$className]['options']['indexes'][$name])) { + if (!isset($to[$className]['options']['indexes'][$name])) { $this->_changes['dropped_indexes'][$info['tableName']][$name] = $index; } } @@ -286,9 +289,10 @@ protected function _buildChanges($from, $to) } /** - * Build all the model schema information for the passed array of models + * Build all the model schema information for the passed array of models. + * + * @param array $models Array of models to build the schema information for * - * @param array $models Array of models to build the schema information for * @return array $info Array of schema information for all the passed models */ protected function _buildModelInformation(array $models) @@ -301,15 +305,14 @@ protected function _buildModelInformation(array $models) } } - $info = $this->_cleanModelInformation($info); - - return $info; + return $this->_cleanModelInformation($info); } /** - * Clean the produced model information of any potential prefix text + * Clean the produced model information of any potential prefix text. + * + * @param mixed $info Either array or string to clean of prefixes * - * @param mixed $info Either array or string to clean of prefixes * @return mixed $info Cleaned value which is either an array or string */ protected function _cleanModelInformation($info) @@ -320,18 +323,19 @@ protected function _cleanModelInformation($info) $key = $this->_cleanModelInformation($key); $info[$key] = $this->_cleanModelInformation($value); } + return $info; - } else { - $find = array( - self::$_toPrefix, - self::$_fromPrefix, - Doctrine_Inflector::tableize(self::$_toPrefix) . '_', - Doctrine_Inflector::tableize(self::$_fromPrefix) . '_', - Doctrine_Inflector::tableize(self::$_toPrefix), - Doctrine_Inflector::tableize(self::$_fromPrefix) - ); - return str_replace($find, '', (string) $info); } + $find = array( + self::$_toPrefix, + self::$_fromPrefix, + Doctrine_Inflector::tableize(self::$_toPrefix).'_', + Doctrine_Inflector::tableize(self::$_fromPrefix).'_', + Doctrine_Inflector::tableize(self::$_toPrefix), + Doctrine_Inflector::tableize(self::$_fromPrefix), + ); + + return str_replace($find, '', (string) $info); } /** @@ -339,12 +343,13 @@ protected function _cleanModelInformation($info) * Used to determine if a directory contains YAML or PHP files. * * @param string $item + * * @return string $extension */ protected function _getItemExtension($item) { if (is_dir($item)) { - $files = glob($item . DIRECTORY_SEPARATOR . '*'); + $files = glob($item.DIRECTORY_SEPARATOR.'*'); } else { $files = array($item); } @@ -358,53 +363,55 @@ protected function _getItemExtension($item) $extension = $pathInfo['extension']; } } + return $extension; } /** - * Generate a set of models for the schema information source + * Generate a set of models for the schema information source. + * + * @param string $prefix Prefix to generate the models with + * @param mixed $item The item to generate the models from * - * @param string $prefix Prefix to generate the models with - * @param mixed $item The item to generate the models from * @return string $path The path where the models were generated + * * @throws Doctrine_Migration_Exception $e */ protected function _generateModels($prefix, $item) { - $path = $this->_tmpPath . DIRECTORY_SEPARATOR . strtolower($prefix) . '_doctrine_tmp_dirs'; + $path = $this->_tmpPath.DIRECTORY_SEPARATOR.strtolower($prefix).'_doctrine_tmp_dirs'; $options = array( 'classPrefix' => $prefix, - 'generateBaseClasses' => false + 'generateBaseClasses' => false, ); if (is_string($item) && file_exists($item)) { $extension = $this->_getItemExtension($item); - if ($extension === 'yml') { + if ('yml' === $extension) { Doctrine_Core::generateModelsFromYaml($item, $path, $options); return $path; - } else if ($extension === 'php') { + } + if ('php' === $extension) { Doctrine_Lib::copyDirectory($item, $path); return $path; - } else { - throw new Doctrine_Migration_Exception('No php or yml files found at path: "' . $item . '"'); } + throw new Doctrine_Migration_Exception('No php or yml files found at path: "'.$item.'"'); } else { try { Doctrine_Core::generateModelsFromDb($path, (array) $item, $options); + return $path; } catch (Exception $e) { - throw new Doctrine_Migration_Exception('Could not generate models from connection: ' . $e->getMessage()); + throw new Doctrine_Migration_Exception('Could not generate models from connection: '.$e->getMessage()); } } } /** - * Cleanup temporary generated models after a diff is performed - * - * @return void + * Cleanup temporary generated models after a diff is performed. */ protected function _cleanup() { @@ -418,7 +425,7 @@ protected function _cleanup() } // clean up tmp directories - Doctrine_Lib::removeDirectories($this->_tmpPath . DIRECTORY_SEPARATOR . strtolower(self::$_fromPrefix) . '_doctrine_tmp_dirs'); - Doctrine_Lib::removeDirectories($this->_tmpPath . DIRECTORY_SEPARATOR . strtolower(self::$_toPrefix) . '_doctrine_tmp_dirs'); + Doctrine_Lib::removeDirectories($this->_tmpPath.DIRECTORY_SEPARATOR.strtolower(self::$_fromPrefix).'_doctrine_tmp_dirs'); + Doctrine_Lib::removeDirectories($this->_tmpPath.DIRECTORY_SEPARATOR.strtolower(self::$_toPrefix).'_doctrine_tmp_dirs'); } } diff --git a/lib/Doctrine/Migration/Exception.php b/lib/Doctrine/Migration/Exception.php index d8e5a43ce..4449cf02b 100644 --- a/lib/Doctrine/Migration/Exception.php +++ b/lib/Doctrine/Migration/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Migration_Exception + * Doctrine_Migration_Exception. * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Migration_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Migration/IrreversibleMigrationException.php b/lib/Doctrine/Migration/IrreversibleMigrationException.php index afee24ec5..fd6b3c672 100644 --- a/lib/Doctrine/Migration/IrreversibleMigrationException.php +++ b/lib/Doctrine/Migration/IrreversibleMigrationException.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Migration_IrreversibleMigration + * Doctrine_Migration_IrreversibleMigration. * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Migration_IrreversibleMigrationException extends Doctrine_Migration_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Migration/Process.php b/lib/Doctrine/Migration/Process.php index d2e53ef80..0e78bd6aa 100644 --- a/lib/Doctrine/Migration/Process.php +++ b/lib/Doctrine/Migration/Process.php @@ -20,20 +20,20 @@ */ /** - * Doctrine_Migration_Process + * Doctrine_Migration_Process. * - * @package Doctrine - * @subpackage Migration * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Migration_Process { - protected - $_migration; + protected $_migration; public function __construct(Doctrine_Migration $migration) { @@ -46,10 +46,9 @@ public function getConnection() } /** - * Process a created table change + * Process a created table change. * * @param string $table Table definition - * @return void */ public function processCreatedTable(array $table) { @@ -57,10 +56,9 @@ public function processCreatedTable(array $table) } /** - * Process a dropped table change + * Process a dropped table change. * * @param array $table Table definition - * @return void */ public function processDroppedTable(array $table) { @@ -68,10 +66,9 @@ public function processDroppedTable(array $table) } /** - * Process a renamed table change + * Process a renamed table change. * * @param array $table Renamed table definition - * @return void */ public function processRenamedTable(array $table) { @@ -79,10 +76,9 @@ public function processRenamedTable(array $table) } /** - * Process a created column change + * Process a created column change. * * @param array $column Column definition - * @return void */ public function processCreatedColumn(array $column) { @@ -90,10 +86,9 @@ public function processCreatedColumn(array $column) } /** - * Process a dropped column change + * Process a dropped column change. * * @param array $column Column definition - * @return void */ public function processDroppedColumn(array $column) { @@ -101,10 +96,9 @@ public function processDroppedColumn(array $column) } /** - * Process a renamed column change + * Process a renamed column change. * * @param array $column Column definition - * @return void */ public function processRenamedColumn(array $column) { @@ -115,25 +109,23 @@ public function processRenamedColumn(array $column) } /** - * Process a changed column change + * Process a changed column change. * * @param array $column Changed column definition - * @return void */ public function processChangedColumn(array $column) { $options = array(); $options = $column['options']; $options['type'] = $column['type']; - + $this->getConnection()->export->alterTable($column['tableName'], array('change' => array($column['columnName'] => array('definition' => $options)))); } /** - * Process a created index change + * Process a created index change. * * @param array $index Index definition - * @return void */ public function processCreatedIndex(array $index) { @@ -141,10 +133,9 @@ public function processCreatedIndex(array $index) } /** - * Process a dropped index change + * Process a dropped index change. * * @param array $index Index definition - * @return void */ public function processDroppedIndex(array $index) { @@ -152,10 +143,9 @@ public function processDroppedIndex(array $index) } /** - * Process a created constraint change + * Process a created constraint change. * * @param array $constraint Constraint definition - * @return void */ public function processCreatedConstraint(array $constraint) { @@ -163,10 +153,9 @@ public function processCreatedConstraint(array $constraint) } /** - * Process a dropped constraint change + * Process a dropped constraint change. * * @param array $constraint Constraint definition - * @return void */ public function processDroppedConstraint(array $constraint) { @@ -174,10 +163,9 @@ public function processDroppedConstraint(array $constraint) } /** - * Process a created foreign key change + * Process a created foreign key change. * * @param array $foreignKey Foreign key definition - * @return void */ public function processCreatedForeignKey(array $foreignKey) { @@ -185,13 +173,10 @@ public function processCreatedForeignKey(array $foreignKey) } /** - * Process a dropped foreign key change - * - * @param array $foreignKey - * @return void + * Process a dropped foreign key change. */ public function processDroppedForeignKey(array $foreignKey) { $this->getConnection()->export->dropForeignKey($foreignKey['tableName'], $foreignKey['definition']['name']); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Node.php b/lib/Doctrine/Node.php index 0d0e7c296..cacca98f5 100644 --- a/lib/Doctrine/Node.php +++ b/lib/Doctrine/Node.php @@ -20,35 +20,36 @@ */ /** - * Doctrine_Node + * Doctrine_Node. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node implements IteratorAggregate { /** - * @param object $record reference to associated Doctrine_Record instance + * @param object $record reference to associated Doctrine_Record instance */ protected $record; /** - * @param array $options + * @param array $options */ protected $options; /** - * @param string $iteratorType (Pre | Post | Level) + * @param string $iteratorType (Pre | Post | Level) */ protected $iteratorType; /** - * @param array $iteratorOptions + * @param array $iteratorOptions */ protected $iteratorOptions; @@ -60,16 +61,16 @@ class Doctrine_Node implements IteratorAggregate protected $_tree; /** - * contructor, creates node with reference to record and any options + * contructor, creates node with reference to record and any options. * - * @param object $record instance of Doctrine_Record - * @param array $options options + * @param object $record instance of Doctrine_Record + * @param array $options options */ public function __construct(Doctrine_Record $record, $options) { $this->record = $record; $this->options = $options; - + // Make sure that the tree object of the root class is used in the case // of column aggregation inheritance (single table inheritance). $class = $record->getTable()->getComponentName(); @@ -78,17 +79,14 @@ public function __construct(Doctrine_Record $record, $options) if ($thisTable->getOption('inheritanceMap')) { // Move up the hierarchy until we find the "subclasses" option. This option // MUST be set on the root class of the user's hierarchy that uses STI. - while ( ! $subclasses = $table->getOption('subclasses')) { + while (!$subclasses = $table->getOption('subclasses')) { $class = get_parent_class($class); $reflectionClass = new ReflectionClass($class); if ($reflectionClass->isAbstract()) { continue; } - if ($class == 'Doctrine_Record') { - throw new Doctrine_Node_Exception("No subclasses specified. You are " - . "using Single Table Inheritance with NestedSet but you have " - . "not specified the subclasses correctly. Make sure you use " - . "setSubclasses() in the root class of your hierarchy."); + if ('Doctrine_Record' == $class) { + throw new Doctrine_Node_Exception('No subclasses specified. You are using Single Table Inheritance with NestedSet but you have not specified the subclasses correctly. Make sure you use setSubclasses() in the root class of your hierarchy.'); } $table = $table->getConnection()->getTable($class); } @@ -106,27 +104,29 @@ public function __construct(Doctrine_Record $record, $options) * This is a factory method that returns node instance based upon chosen * implementation. * - * @param object $record instance of Doctrine_Record - * @param string $implName implementation (NestedSet, AdjacencyList, MaterializedPath) - * @param array $options options + * @param object $record instance of Doctrine_Record + * @param string $implName implementation (NestedSet, AdjacencyList, MaterializedPath) + * @param array $options options + * * @return Doctrine_Node - * @throws Doctrine_Node_Exception if $implName is not a valid class + * + * @throws Doctrine_Node_Exception if $implName is not a valid class */ public static function factory(Doctrine_Record $record, $implName, $options = array()) { - $class = 'Doctrine_Node_' . $implName; + $class = 'Doctrine_Node_'.$implName; - if ( ! class_exists($class)) { - throw new Doctrine_Node_Exception("The class $class must exist and extend Doctrine_Node"); + if (!class_exists($class)) { + throw new Doctrine_Node_Exception("The class {$class} must exist and extend Doctrine_Node"); } return new $class($record, $options); } /** - * setter for record attribute + * setter for record attribute. * - * @param object $record instance of Doctrine_Record + * @param object $record instance of Doctrine_Record */ public function setRecord(Doctrine_Record $record) { @@ -134,7 +134,7 @@ public function setRecord(Doctrine_Record $record) } /** - * getter for record attribute + * getter for record attribute. * * @return Doctrine_Record */ @@ -144,10 +144,10 @@ public function getRecord() } /** - * convenience function for getIterator + * convenience function for getIterator. * - * @param string $type type of iterator (Pre | Post | Level) - * @param array $options options + * @param string $type type of iterator (Pre | Post | Level) + * @param array $options options */ public function traverse($type = 'Pre', $options = array()) { @@ -155,30 +155,30 @@ public function traverse($type = 'Pre', $options = array()) } /** - * get iterator + * get iterator. * - * @param string $type type of iterator (Pre | Post | Level) - * @param array $options options + * @param string $type type of iterator (Pre | Post | Level) + * @param array $options options */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator($type = null, $options = null) { - if ($type === null) { + if (null === $type) { $type = (isset($this->iteratorType) ? $this->iteratorType : 'Pre'); } - if ($options === null) { + if (null === $options) { $options = (isset($this->iteratorOptions) ? $this->iteratorOptions : array()); } $implName = $this->record->getTable()->getOption('treeImpl'); - $iteratorClass = 'Doctrine_Node_' . $implName . '_' . ucfirst(strtolower($type)) . 'OrderIterator'; + $iteratorClass = 'Doctrine_Node_'.$implName.'_'.ucfirst(strtolower($type)).'OrderIterator'; return new $iteratorClass($this->record, $options); } /** - * sets node's iterator type + * sets node's iterator type. * * @param int */ @@ -188,7 +188,7 @@ public function setIteratorType($type) } /** - * sets node's iterator options + * sets node's iterator options. * * @param int */ diff --git a/lib/Doctrine/Node/AdjacencyList.php b/lib/Doctrine/Node/AdjacencyList.php index 2a48613aa..d31b0f9d9 100644 --- a/lib/Doctrine/Node/AdjacencyList.php +++ b/lib/Doctrine/Node/AdjacencyList.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_AdjacencyList + * Doctrine_Node_AdjacencyList. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_AdjacencyList extends Doctrine_Node implements Doctrine_Node_Interface -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/AdjacencyList/LevelOrderIterator.php b/lib/Doctrine/Node/AdjacencyList/LevelOrderIterator.php index 115e18987..f4763c6ba 100644 --- a/lib/Doctrine/Node/AdjacencyList/LevelOrderIterator.php +++ b/lib/Doctrine/Node/AdjacencyList/LevelOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_AdjacencyList_LevelOrderIterator + * Doctrine_Node_AdjacencyList_LevelOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_AdjacencyList_LevelOrderIterator implements Iterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/AdjacencyList/PostOrderIterator.php b/lib/Doctrine/Node/AdjacencyList/PostOrderIterator.php index 1c38fa3e7..7d65fa28c 100644 --- a/lib/Doctrine/Node/AdjacencyList/PostOrderIterator.php +++ b/lib/Doctrine/Node/AdjacencyList/PostOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_AdjacencyList_PostOrderIterator + * Doctrine_Node_AdjacencyList_PostOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_AdjacencyList_PostOrderIterator implements Iterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/AdjacencyList/PreOrderIterator.php b/lib/Doctrine/Node/AdjacencyList/PreOrderIterator.php index ab9322113..9eb0dfe03 100644 --- a/lib/Doctrine/Node/AdjacencyList/PreOrderIterator.php +++ b/lib/Doctrine/Node/AdjacencyList/PreOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_AdjacencyList_PreOrderIterator + * Doctrine_Node_AdjacencyList_PreOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_AdjacencyList_PreOrderIterator implements Iterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/Exception.php b/lib/Doctrine/Node/Exception.php index d13666eb5..0f9b75940 100644 --- a/lib/Doctrine/Node/Exception.php +++ b/lib/Doctrine/Node/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_Exception + * Doctrine_Node_Exception. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/Interface.php b/lib/Doctrine/Node/Interface.php index 95a717e46..c99fccc48 100644 --- a/lib/Doctrine/Node/Interface.php +++ b/lib/Doctrine/Node/Interface.php @@ -20,249 +20,245 @@ */ /** - * Doctrine_Node_Interface + * Doctrine_Node_Interface. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ -interface Doctrine_Node_Interface { - +interface Doctrine_Node_Interface +{ /** - * test if node has previous sibling + * test if node has previous sibling. * * @return bool */ public function hasPrevSibling(); /** - * test if node has next sibling + * test if node has next sibling. * * @return bool */ public function hasNextSibling(); /** - * test if node has children + * test if node has children. * * @return bool */ public function hasChildren(); /** - * test if node has parent + * test if node has parent. * * @return bool */ public function hasParent(); /** - * gets record of prev sibling or empty record + * gets record of prev sibling or empty record. * * @return Doctrine_Record */ public function getPrevSibling(); /** - * gets record of next sibling or empty record + * gets record of next sibling or empty record. * * @return Doctrine_Record */ public function getNextSibling(); /** - * gets siblings for node + * gets siblings for node. * - * @return array array of sibling Doctrine_Record objects + * @return array array of sibling Doctrine_Record objects */ public function getSiblings($includeNode = false); /** - * gets record of first child or empty record + * gets record of first child or empty record. * * @return Doctrine_Record */ public function getFirstChild(); /** - * gets record of last child or empty record + * gets record of last child or empty record. * * @return Doctrine_Record */ public function getLastChild(); /** - * gets children for node (direct descendants only) + * gets children for node (direct descendants only). * - * @return array array of sibling Doctrine_Record objects + * @return array array of sibling Doctrine_Record objects */ public function getChildren(); /** - * gets descendants for node (direct descendants only) + * gets descendants for node (direct descendants only). * - * @return Iterator iterator to traverse descendants from node + * @return Iterator iterator to traverse descendants from node */ public function getDescendants(); /** - * gets record of parent or empty record + * gets record of parent or empty record. * * @return Doctrine_Record */ public function getParent(); /** - * gets ancestors for node + * gets ancestors for node. * * @return Doctrine_Collection */ public function getAncestors(); /** - * gets path to node from root, uses record::toString() method to get node names + * gets path to node from root, uses record::toString() method to get node names. + * + * @param string $seperator path seperator + * @param bool $includeNode whether or not to include node at end of path * - * @param string $seperator path seperator - * @param bool $includeNode whether or not to include node at end of path - * @return string string representation of path + * @return string string representation of path */ public function getPath($seperator = ' > ', $includeNode = false); /** - * gets level (depth) of node in the tree + * gets level (depth) of node in the tree. * * @return int */ public function getLevel(); /** - * gets number of children (direct descendants) + * gets number of children (direct descendants). * * @return int */ public function getNumberChildren(); /** - * gets number of descendants (children and their children) + * gets number of descendants (children and their children). * * @return int */ public function getNumberDescendants(); /** - * inserts node as parent of dest record + * inserts node as parent of dest record. * * @return bool */ public function insertAsParentOf(Doctrine_Record $dest); /** - * inserts node as previous sibling of dest record + * inserts node as previous sibling of dest record. * * @return bool */ public function insertAsPrevSiblingOf(Doctrine_Record $dest); /** - * inserts node as next sibling of dest record + * inserts node as next sibling of dest record. * * @return bool */ public function insertAsNextSiblingOf(Doctrine_Record $dest); /** - * inserts node as first child of dest record + * inserts node as first child of dest record. * * @return bool */ public function insertAsFirstChildOf(Doctrine_Record $dest); /** - * inserts node as first child of dest record + * inserts node as first child of dest record. * * @return bool */ public function insertAsLastChildOf(Doctrine_Record $dest); /** - * moves node as prev sibling of dest record - * - */ + * moves node as prev sibling of dest record. + */ public function moveAsPrevSiblingOf(Doctrine_Record $dest); /** - * moves node as next sibling of dest record - * + * moves node as next sibling of dest record. */ public function moveAsNextSiblingOf(Doctrine_Record $dest); /** - * moves node as first child of dest record - * + * moves node as first child of dest record. */ public function moveAsFirstChildOf(Doctrine_Record $dest); /** - * moves node as last child of dest record - * + * moves node as last child of dest record. */ public function moveAsLastChildOf(Doctrine_Record $dest); /** - * adds node as last child of record - * + * adds node as last child of record. */ public function addChild(Doctrine_Record $record); /** - * determines if node is leaf + * determines if node is leaf. * * @return bool */ public function isLeaf(); /** - * determines if node is root + * determines if node is root. * * @return bool */ public function isRoot(); /** - * determines if node is equal to subject node + * determines if node is equal to subject node. * * @return bool */ public function isEqualTo(Doctrine_Record $subj); /** - * determines if node is child of subject node + * determines if node is child of subject node. * * @return bool */ public function isDescendantOf(Doctrine_Record $subj); /** - * determines if node is child of or sibling to subject node + * determines if node is child of or sibling to subject node. * * @return bool */ public function isDescendantOfOrEqualTo(Doctrine_Record $subj); /** - * determines if node is valid + * determines if node is valid. * * @return bool */ public function isValidNode(); /** - * deletes node and it's descendants - * + * deletes node and it's descendants. */ public function delete(); } diff --git a/lib/Doctrine/Node/MaterializedPath.php b/lib/Doctrine/Node/MaterializedPath.php index f997e6301..eb9762630 100644 --- a/lib/Doctrine/Node/MaterializedPath.php +++ b/lib/Doctrine/Node/MaterializedPath.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_MaterializedPath + * Doctrine_Node_MaterializedPath. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Node_MaterializedPath extends Doctrine_Node implements Doctrine_Node_Interface -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/MaterializedPath/LevelOrderIterator.php b/lib/Doctrine/Node/MaterializedPath/LevelOrderIterator.php index 6283563c3..4c0116732 100644 --- a/lib/Doctrine/Node/MaterializedPath/LevelOrderIterator.php +++ b/lib/Doctrine/Node/MaterializedPath/LevelOrderIterator.php @@ -20,21 +20,22 @@ */ /** - * Doctrine_Node_MaterializedPath_LevelOrderIterator + * Doctrine_Node_MaterializedPath_LevelOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_MaterializedPath_LevelOrderIterator implements Iterator { - private $topNode = null; + private $topNode; - private $curNode = null; + private $curNode; public function __construct($node, $opts) { @@ -65,4 +66,4 @@ public function next() { throw new Doctrine_Exception('Not yet implemented'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Node/MaterializedPath/PostOrderIterator.php b/lib/Doctrine/Node/MaterializedPath/PostOrderIterator.php index 1cc002f06..99606e898 100644 --- a/lib/Doctrine/Node/MaterializedPath/PostOrderIterator.php +++ b/lib/Doctrine/Node/MaterializedPath/PostOrderIterator.php @@ -20,21 +20,22 @@ */ /** - * Doctrine_Node_MaterializedPath_PostOrderIterator + * Doctrine_Node_MaterializedPath_PostOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_MaterializedPath_PostOrderIterator implements Iterator { - private $topNode = null; + private $topNode; - private $curNode = null; + private $curNode; public function __construct($node, $opts) { @@ -65,4 +66,4 @@ public function next() { throw new Doctrine_Exception('Not yet implemented'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Node/MaterializedPath/PreOrderIterator.php b/lib/Doctrine/Node/MaterializedPath/PreOrderIterator.php index 4ea31bd8c..704151855 100644 --- a/lib/Doctrine/Node/MaterializedPath/PreOrderIterator.php +++ b/lib/Doctrine/Node/MaterializedPath/PreOrderIterator.php @@ -20,21 +20,22 @@ */ /** - * Doctrine_Node_MaterializedPath_PreOrderIterator + * Doctrine_Node_MaterializedPath_PreOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_MaterializedPath_PreOrderIterator implements Iterator { - private $topNode = null; + private $topNode; - private $curNode = null; + private $curNode; public function __construct($node, $opts) { @@ -65,4 +66,4 @@ public function next() { throw new Doctrine_Exception('Not yet implemented'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Node/NestedSet.php b/lib/Doctrine/Node/NestedSet.php index ce754f471..5ac55d662 100644 --- a/lib/Doctrine/Node/NestedSet.php +++ b/lib/Doctrine/Node/NestedSet.php @@ -20,115 +20,116 @@ */ /** - * Doctrine_Node_NestedSet + * Doctrine_Node_NestedSet. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms - * @author Roman Borschel + * @author Roman Borschel */ class Doctrine_Node_NestedSet extends Doctrine_Node implements Doctrine_Node_Interface { /** - * test if node has previous sibling + * test if node has previous sibling. * - * @return bool + * @return bool */ public function hasPrevSibling() { - return $this->isValidNode($this->getPrevSibling()); + return $this->isValidNode($this->getPrevSibling()); } /** - * test if node has next sibling + * test if node has next sibling. * - * @return bool - */ + * @return bool + */ public function hasNextSibling() { - return $this->isValidNode($this->getNextSibling()); + return $this->isValidNode($this->getNextSibling()); } /** - * test if node has children + * test if node has children. * - * @return bool + * @return bool */ public function hasChildren() { - return (($this->getRightValue() - $this->getLeftValue()) > 1); + return ($this->getRightValue() - $this->getLeftValue()) > 1; } /** - * test if node has parent + * test if node has parent. * - * @return bool + * @return bool */ public function hasParent() { - return $this->isValidNode($this->getRecord()) && ! $this->isRoot(); + return $this->isValidNode($this->getRecord()) && !$this->isRoot(); } /** - * gets record of prev sibling or empty record + * gets record of prev sibling or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getPrevSibling() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q = $q->addWhere("$baseAlias.rgt = ?", $this->getLeftValue() - 1); + $q = $q->addWhere("{$baseAlias}.rgt = ?", $this->getLeftValue() - 1); $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $sibling = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $sibling = array_shift($result); } - + return $sibling; } /** - * gets record of next sibling or empty record + * gets record of next sibling or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getNextSibling() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q = $q->addWhere("$baseAlias.lft = ?", $this->getRightValue() + 1); + $q = $q->addWhere("{$baseAlias}.lft = ?", $this->getRightValue() + 1); $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $sibling = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $sibling = array_shift($result); } - + return $sibling; } /** - * gets siblings for node + * gets siblings for node. * - * @return array array of sibling Doctrine_Record objects + * @return array array of sibling Doctrine_Record objects */ public function getSiblings($includeNode = false) { @@ -140,94 +141,97 @@ public function getSiblings($includeNode = false) continue; } $siblings[] = $child; - } + } } + return $siblings; } /** - * gets record of first child or empty record + * gets record of first child or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getFirstChild() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q->addWhere("$baseAlias.lft = ?", $this->getLeftValue() + 1); + $q->addWhere("{$baseAlias}.lft = ?", $this->getLeftValue() + 1); $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $child = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $child = array_shift($result); } - - return $child; + + return $child; } /** - * gets record of last child or empty record + * gets record of last child or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getLastChild() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q->addWhere("$baseAlias.rgt = ?", $this->getRightValue() - 1); + $q->addWhere("{$baseAlias}.rgt = ?", $this->getRightValue() - 1); $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $child = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $child = array_shift($result); } - - return $child; + + return $child; } /** - * gets children for node (direct descendants only) + * gets children for node (direct descendants only). * - * @return mixed The children of the node or FALSE if the node has no children. + * @return mixed the children of the node or FALSE if the node has no children */ public function getChildren() - { + { return $this->getDescendants(1); } /** - * gets descendants for node (direct descendants only) + * gets descendants for node (direct descendants only). + * + * @param mixed|null $depth * - * @return mixed The descendants of the node or FALSE if the node has no descendants. + * @return mixed the descendants of the node or FALSE if the node has no descendants */ public function getDescendants($depth = null, $includeNode = false) { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); $params = array($this->record->get('lft'), $this->record->get('rgt')); - + if ($includeNode) { - $q->addWhere("$baseAlias.lft >= ? AND $baseAlias.rgt <= ?", $params)->addOrderBy("$baseAlias.lft asc"); + $q->addWhere("{$baseAlias}.lft >= ? AND {$baseAlias}.rgt <= ?", $params)->addOrderBy("{$baseAlias}.lft asc"); } else { - $q->addWhere("$baseAlias.lft > ? AND $baseAlias.rgt < ?", $params)->addOrderBy("$baseAlias.lft asc"); + $q->addWhere("{$baseAlias}.lft > ? AND {$baseAlias}.rgt < ?", $params)->addOrderBy("{$baseAlias}.lft asc"); } - - if ($depth !== null) { - $q->addWhere("$baseAlias.level <= ?", $this->record['level'] + $depth); + + if (null !== $depth) { + $q->addWhere("{$baseAlias}.level <= ?", $this->record['level'] + $depth); } - + $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); @@ -239,64 +243,68 @@ public function getDescendants($depth = null, $includeNode = false) } /** - * gets record of parent or empty record + * gets record of parent or empty record. * - * @return Doctrine_Record + * @return Doctrine_Record */ public function getParent() { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue())) - ->addWhere("$baseAlias.level >= ?", $this->record['level'] - 1) - ->addOrderBy("$baseAlias.rgt asc"); + $q->addWhere("{$baseAlias}.lft < ? AND {$baseAlias}.rgt > ?", array($this->getLeftValue(), $this->getRightValue())) + ->addWhere("{$baseAlias}.level >= ?", $this->record['level'] - 1) + ->addOrderBy("{$baseAlias}.rgt asc") + ; $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $result = $q->execute(); - + if (count($result) <= 0) { return false; } - + if ($result instanceof Doctrine_Collection) { $parent = $result->getFirst(); - } else if (is_array($result)) { + } elseif (is_array($result)) { $parent = array_shift($result); } - + return $parent; } /** - * gets ancestors for node + * gets ancestors for node. + * + * @param mixed|null $depth * - * @param integer $deth The depth 'upstairs'. - * @return mixed The ancestors of the node or FALSE if the node has no ancestors (this - * basically means it's a root node). + * @return mixed the ancestors of the node or FALSE if the node has no ancestors (this + * basically means it's a root node) */ public function getAncestors($depth = null) { $baseAlias = $this->_tree->getBaseAlias(); $q = $this->_tree->getBaseQuery(); - $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue())) - ->addOrderBy("$baseAlias.lft asc"); - if ($depth !== null) { - $q->addWhere("$baseAlias.level >= ?", $this->record['level'] - $depth); + $q->addWhere("{$baseAlias}.lft < ? AND {$baseAlias}.rgt > ?", array($this->getLeftValue(), $this->getRightValue())) + ->addOrderBy("{$baseAlias}.lft asc") + ; + if (null !== $depth) { + $q->addWhere("{$baseAlias}.level >= ?", $this->record['level'] - $depth); } $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); $ancestors = $q->execute(); if (count($ancestors) <= 0) { return false; } + return $ancestors; } /** - * gets path to node from root, uses record::toString() method to get node names + * gets path to node from root, uses record::toString() method to get node names. * - * @param string $seperator path seperator - * @param bool $includeNode whether or not to include node at end of path - * @return string string representation of path - */ + * @param string $seperator path seperator + * + * @return string string representation of path + */ public function getPath($seperator = ' > ', $includeRecord = false) { $path = array(); @@ -309,25 +317,26 @@ public function getPath($seperator = ' > ', $includeRecord = false) if ($includeRecord) { $path[] = $this->getRecord()->__toString(); } - + return implode($seperator, $path); } /** - * gets number of children (direct descendants) + * gets number of children (direct descendants). * - * @return int - */ + * @return int + */ public function getNumberChildren() { $children = $this->getChildren(); - return $children === false ? 0 : count($children); + + return false === $children ? 0 : count($children); } /** - * gets number of descendants (children and their children) + * gets number of descendants (children and their children). * - * @return int + * @return int */ public function getNumberDescendants() { @@ -335,10 +344,11 @@ public function getNumberDescendants() } /** - * inserts node as parent of dest record + * inserts node as parent of dest record. * * @return bool - * @todo Wrap in transaction + * + * @todo Wrap in transaction */ public function insertAsParentOf(Doctrine_Record $dest) { @@ -350,58 +360,60 @@ public function insertAsParentOf(Doctrine_Record $dest) if ($dest->getNode()->isRoot()) { return false; } - + // cannot insert as parent of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as parent of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as parent of itself'); return false; } - $newLeft = $dest->getNode()->getLeftValue(); + $newLeft = $dest->getNode()->getLeftValue(); $newRight = $dest->getNode()->getRightValue() + 2; - $newRoot = $dest->getNode()->getRootValue(); - $newLevel = $dest->getNode()->getLevel(); - - $conn = $this->record->getTable()->getConnection(); - try { - $conn->beginInternalTransaction(); - - // Make space for new node + $newRoot = $dest->getNode()->getRootValue(); + $newLevel = $dest->getNode()->getLevel(); + + $conn = $this->record->getTable()->getConnection(); + try { + $conn->beginInternalTransaction(); + + // Make space for new node $this->shiftRLValues($dest->getNode()->getRightValue() + 1, 2, $newRoot); // Slide child nodes over one and down one to allow new parent to wrap them - $componentName = $this->_tree->getBaseComponent(); + $componentName = $this->_tree->getBaseComponent(); $q = Doctrine_Core::getTable($componentName) ->createQuery() - ->update(); - $q->set("$componentName.lft", "$componentName.lft + 1"); - $q->set("$componentName.rgt", "$componentName.rgt + 1"); - $q->set("$componentName.level", "$componentName.level + 1"); - $q->where("$componentName.lft >= ? AND $componentName.rgt <= ?", array($newLeft, $newRight)); - $q = $this->_tree->returnQueryWithRootId($q, $newRoot); - $q->execute(); + ->update() + ; + $q->set("{$componentName}.lft", "{$componentName}.lft + 1"); + $q->set("{$componentName}.rgt", "{$componentName}.rgt + 1"); + $q->set("{$componentName}.level", "{$componentName}.level + 1"); + $q->where("{$componentName}.lft >= ? AND {$componentName}.rgt <= ?", array($newLeft, $newRight)); + $q = $this->_tree->returnQueryWithRootId($q, $newRoot); + $q->execute(); $this->record['level'] = $newLevel; - $this->insertNode($newLeft, $newRight, $newRoot); - - $conn->commit(); - } catch (Exception $e) { - $conn->rollback(); - throw $e; - } - + $this->insertNode($newLeft, $newRight, $newRoot); + + $conn->commit(); + } catch (Exception $e) { + $conn->rollback(); + throw $e; + } + return true; } /** - * inserts node as previous sibling of dest record + * inserts node as previous sibling of dest record. * * @return bool - * @todo Wrap in transaction + * + * @todo Wrap in transaction */ public function insertAsPrevSiblingOf(Doctrine_Record $dest) { @@ -411,10 +423,10 @@ public function insertAsPrevSiblingOf(Doctrine_Record $dest) } // cannot insert as sibling of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as previous sibling of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as previous sibling of itself'); return false; } @@ -422,33 +434,34 @@ public function insertAsPrevSiblingOf(Doctrine_Record $dest) $newLeft = $dest->getNode()->getLeftValue(); $newRight = $dest->getNode()->getLeftValue() + 1; $newRoot = $dest->getNode()->getRootValue(); - + $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + $this->shiftRLValues($newLeft, 2, $newRoot); $this->record['level'] = $dest['level']; $this->insertNode($newLeft, $newRight, $newRoot); // update destination left/right values to prevent a refresh // $dest->getNode()->setLeftValue($dest->getNode()->getLeftValue() + 2); // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } - + return true; } /** - * inserts node as next sibling of dest record + * inserts node as next sibling of dest record. * * @return bool - * @todo Wrap in transaction - */ + * + * @todo Wrap in transaction + */ public function insertAsNextSiblingOf(Doctrine_Record $dest) { // cannot insert a node that has already has a place within the tree @@ -457,10 +470,10 @@ public function insertAsNextSiblingOf(Doctrine_Record $dest) } // cannot insert as sibling of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as next sibling of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as next sibling of itself'); return false; } @@ -472,13 +485,13 @@ public function insertAsNextSiblingOf(Doctrine_Record $dest) $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + $this->shiftRLValues($newLeft, 2, $newRoot); $this->record['level'] = $dest['level']; $this->insertNode($newLeft, $newRight, $newRoot); // update destination left/right values to prevent a refresh // no need, node not affected - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); @@ -489,10 +502,11 @@ public function insertAsNextSiblingOf(Doctrine_Record $dest) } /** - * inserts node as first child of dest record + * inserts node as first child of dest record. * * @return bool - * @todo Wrap in transaction + * + * @todo Wrap in transaction */ public function insertAsFirstChildOf(Doctrine_Record $dest) { @@ -502,10 +516,10 @@ public function insertAsFirstChildOf(Doctrine_Record $dest) } // cannot insert as child of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as first child of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as first child of itself'); return false; } @@ -517,14 +531,14 @@ public function insertAsFirstChildOf(Doctrine_Record $dest) $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + $this->shiftRLValues($newLeft, 2, $newRoot); $this->record['level'] = $dest['level'] + 1; $this->insertNode($newLeft, $newRight, $newRoot); - + // update destination left/right values to prevent a refresh // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); @@ -535,10 +549,11 @@ public function insertAsFirstChildOf(Doctrine_Record $dest) } /** - * inserts node as last child of dest record + * inserts node as last child of dest record. * * @return bool - * @todo Wrap in transaction + * + * @todo Wrap in transaction */ public function insertAsLastChildOf(Doctrine_Record $dest) { @@ -548,10 +563,10 @@ public function insertAsLastChildOf(Doctrine_Record $dest) } // cannot insert as child of itself if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot insert node as last child of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot insert node as last child of itself'); return false; } @@ -563,20 +578,20 @@ public function insertAsLastChildOf(Doctrine_Record $dest) $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + $this->shiftRLValues($newLeft, 2, $newRoot); $this->record['level'] = $dest['level'] + 1; $this->insertNode($newLeft, $newRight, $newRoot); // update destination left/right values to prevent a refresh // $dest->getNode()->setRightValue($dest->getNode()->getRightValue() + 2); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } - + return true; } @@ -584,15 +599,15 @@ public function insertAsLastChildOf(Doctrine_Record $dest) * Accomplishes moving of nodes between different trees. * Used by the move* methods if the root values of the two nodes are different. * - * @param Doctrine_Record $dest * @param unknown_type $newLeftValue * @param unknown_type $moveType + * * @todo Better exception handling/wrapping */ private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveType) { $conn = $this->record->getTable()->getConnection(); - + try { $conn->beginInternalTransaction(); @@ -617,18 +632,18 @@ private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveTy switch ($moveType) { case 'moveAsPrevSiblingOf': $this->insertAsPrevSiblingOf($dest); - break; + break; case 'moveAsFirstChildOf': $this->insertAsFirstChildOf($dest); - break; + break; case 'moveAsNextSiblingOf': $this->insertAsNextSiblingOf($dest); - break; + break; case 'moveAsLastChildOf': $this->insertAsLastChildOf($dest); - break; + break; default: - throw new Doctrine_Node_Exception("Unknown move operation: $moveType."); + throw new Doctrine_Node_Exception("Unknown move operation: {$moveType}."); } $diff = $oldRgt - $oldLft; @@ -647,11 +662,12 @@ private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveTy $q = Doctrine_Core::getTable($componentName) ->createQuery() ->update() - ->set($componentName . '.lft', $componentName.'.lft + ?', $diff) - ->set($componentName . '.rgt', $componentName.'.rgt + ?', $diff) - ->set($componentName . '.level', $componentName.'.level + ?', $levelDiff) - ->set($componentName . '.' . $rootColName, '?', $newRoot) - ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?', array($oldLft, $oldRgt)); + ->set($componentName.'.lft', $componentName.'.lft + ?', $diff) + ->set($componentName.'.rgt', $componentName.'.rgt + ?', $diff) + ->set($componentName.'.level', $componentName.'.level + ?', $levelDiff) + ->set($componentName.'.'.$rootColName, '?', $newRoot) + ->where($componentName.'.lft > ? AND '.$componentName.'.rgt < ?', array($oldLft, $oldRgt)) + ; $q = $this->_tree->returnQueryWithRootId($q, $oldRoot); $q->execute(); @@ -661,125 +677,117 @@ private function _moveBetweenTrees(Doctrine_Record $dest, $newLeftValue, $moveTy $this->shiftRLValues($first, $delta, $oldRoot); $conn->commit(); - - return true; + + return true; } catch (Exception $e) { $conn->rollback(); throw $e; } - + return false; } /** - * moves node as prev sibling of dest record - * - */ + * moves node as prev sibling of dest record. + */ public function moveAsPrevSiblingOf(Doctrine_Record $dest) { if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot move node as previous sibling of itself"); + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot move node as previous sibling of itself'); - return false; - } + return false; + } if ($dest->getNode()->getRootValue() != $this->getRootValue()) { // Move between trees return $this->_moveBetweenTrees($dest, $dest->getNode()->getLeftValue(), __FUNCTION__); - } else { - // Move within the tree - $oldLevel = $this->record['level']; - $this->record['level'] = $dest['level']; - $this->updateNode($dest->getNode()->getLeftValue(), $this->record['level'] - $oldLevel); } - + // Move within the tree + $oldLevel = $this->record['level']; + $this->record['level'] = $dest['level']; + $this->updateNode($dest->getNode()->getLeftValue(), $this->record['level'] - $oldLevel); + return true; } /** - * moves node as next sibling of dest record - * + * moves node as next sibling of dest record. */ public function moveAsNextSiblingOf(Doctrine_Record $dest) { if ( - $dest === $this->record || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot move node as next sibling of itself"); - + $dest === $this->record + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot move node as next sibling of itself'); + return false; } if ($dest->getNode()->getRootValue() != $this->getRootValue()) { // Move between trees return $this->_moveBetweenTrees($dest, $dest->getNode()->getRightValue() + 1, __FUNCTION__); - } else { - // Move within tree - $oldLevel = $this->record['level']; - $this->record['level'] = $dest['level']; - $this->updateNode($dest->getNode()->getRightValue() + 1, $this->record['level'] - $oldLevel); } - + // Move within tree + $oldLevel = $this->record['level']; + $this->record['level'] = $dest['level']; + $this->updateNode($dest->getNode()->getRightValue() + 1, $this->record['level'] - $oldLevel); + return true; } /** - * moves node as first child of dest record - * + * moves node as first child of dest record. */ public function moveAsFirstChildOf(Doctrine_Record $dest) { if ( - $dest === $this->record || $this->isAncestorOf($dest) || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot move node as first child of itself or into a descendant"); + $dest === $this->record || $this->isAncestorOf($dest) + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot move node as first child of itself or into a descendant'); - return false; - } + return false; + } - if ($dest->getNode()->getRootValue() != $this->getRootValue()) { + if ($dest->getNode()->getRootValue() != $this->getRootValue()) { // Move between trees return $this->_moveBetweenTrees($dest, $dest->getNode()->getLeftValue() + 1, __FUNCTION__); - } else { - // Move within tree - $oldLevel = $this->record['level']; - $this->record['level'] = $dest['level'] + 1; - $this->updateNode($dest->getNode()->getLeftValue() + 1, $this->record['level'] - $oldLevel); } + // Move within tree + $oldLevel = $this->record['level']; + $this->record['level'] = $dest['level'] + 1; + $this->updateNode($dest->getNode()->getLeftValue() + 1, $this->record['level'] - $oldLevel); return true; } /** - * moves node as last child of dest record - * + * moves node as last child of dest record. */ public function moveAsLastChildOf(Doctrine_Record $dest) { if ( - $dest === $this->record || $this->isAncestorOf($dest) || - ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) - ) { - throw new Doctrine_Tree_Exception("Cannot move node as last child of itself or into a descendant"); + $dest === $this->record || $this->isAncestorOf($dest) + || ($dest->exists() && $this->record->exists() && $dest->identifier() === $this->record->identifier()) + ) { + throw new Doctrine_Tree_Exception('Cannot move node as last child of itself or into a descendant'); - return false; - } + return false; + } if ($dest->getNode()->getRootValue() != $this->getRootValue()) { // Move between trees return $this->_moveBetweenTrees($dest, $dest->getNode()->getRightValue(), __FUNCTION__); - } else { - // Move within tree - $oldLevel = $this->record['level']; - $this->record['level'] = $dest['level'] + 1; - $this->updateNode($dest->getNode()->getRightValue(), $this->record['level'] - $oldLevel); } - + // Move within tree + $oldLevel = $this->record['level']; + $this->record['level'] = $dest['level'] + 1; + $this->updateNode($dest->getNode()->getRightValue(), $this->record['level'] - $oldLevel); + return true; } @@ -791,19 +799,19 @@ public function moveAsLastChildOf(Doctrine_Record $dest) public function makeRoot($newRootId) { // TODO: throw exception instead? - if ($this->getLeftValue() == 1 || ! $this->_tree->getAttribute('hasManyRoots')) { + if (1 == $this->getLeftValue() || !$this->_tree->getAttribute('hasManyRoots')) { return false; } - + $oldRgt = $this->getRightValue(); $oldLft = $this->getLeftValue(); $oldRoot = $this->getRootValue(); $oldLevel = $this->record['level']; - + $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + // Update descendants lft/rgt/root/level values $diff = 1 - $oldLft; $newRoot = $newRootId; @@ -812,41 +820,41 @@ public function makeRoot($newRootId) $q = Doctrine_Core::getTable($componentName) ->createQuery() ->update() - ->set($componentName . '.lft', $componentName.'.lft + ?', array($diff)) - ->set($componentName . '.rgt', $componentName.'.rgt + ?', array($diff)) - ->set($componentName . '.level', $componentName.'.level - ?', array($oldLevel)) - ->set($componentName . '.' . $rootColName, '?', array($newRoot)) - ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?', array($oldLft, $oldRgt)); + ->set($componentName.'.lft', $componentName.'.lft + ?', array($diff)) + ->set($componentName.'.rgt', $componentName.'.rgt + ?', array($diff)) + ->set($componentName.'.level', $componentName.'.level - ?', array($oldLevel)) + ->set($componentName.'.'.$rootColName, '?', array($newRoot)) + ->where($componentName.'.lft > ? AND '.$componentName.'.rgt < ?', array($oldLft, $oldRgt)) + ; $q = $this->_tree->returnQueryWithRootId($q, $oldRoot); $q->execute(); - + // Detach from old tree (close gap in old tree) $first = $oldRgt + 1; $delta = $oldLft - $oldRgt - 1; $this->shiftRLValues($first, $delta, $this->getRootValue()); - + // Set new lft/rgt/root/level values for root node $this->setLeftValue(1); $this->setRightValue($oldRgt - $oldLft + 1); $this->setRootValue($newRootId); $this->record['level'] = 0; - + $this->record->save(); - + $conn->commit(); - + return true; } catch (Exception $e) { $conn->rollback(); throw $e; } - + return false; } /** - * adds node as last child of record - * + * adds node as last child of record. */ public function addChild(Doctrine_Record $record) { @@ -854,90 +862,92 @@ public function addChild(Doctrine_Record $record) } /** - * determines if node is leaf + * determines if node is leaf. * - * @return bool + * @return bool */ public function isLeaf() { - return (($this->getRightValue() - $this->getLeftValue()) == 1); + return ($this->getRightValue() - $this->getLeftValue()) == 1; } /** - * determines if node is root + * determines if node is root. * - * @return bool + * @return bool */ public function isRoot() { - return ($this->getLeftValue() == 1); + return 1 == $this->getLeftValue(); } /** - * determines if node is equal to subject node + * determines if node is equal to subject node. * - * @return bool - */ + * @return bool + */ public function isEqualTo(Doctrine_Record $subj) { - return (($this->getLeftValue() == $subj->getNode()->getLeftValue()) && - ($this->getRightValue() == $subj->getNode()->getRightValue()) && - ($this->getRootValue() == $subj->getNode()->getRootValue()) - ); + return ($this->getLeftValue() == $subj->getNode()->getLeftValue()) + && ($this->getRightValue() == $subj->getNode()->getRightValue()) + && ($this->getRootValue() == $subj->getNode()->getRootValue()); } /** - * determines if node is child of subject node + * determines if node is child of subject node. * * @return bool */ public function isDescendantOf(Doctrine_Record $subj) { - return (($this->getLeftValue() > $subj->getNode()->getLeftValue()) && - ($this->getRightValue() < $subj->getNode()->getRightValue()) && - ($this->getRootValue() == $subj->getNode()->getRootValue())); + return ($this->getLeftValue() > $subj->getNode()->getLeftValue()) + && ($this->getRightValue() < $subj->getNode()->getRightValue()) + && ($this->getRootValue() == $subj->getNode()->getRootValue()); } /** - * determines if node is child of or sibling to subject node + * determines if node is child of or sibling to subject node. * - * @return bool + * @return bool */ public function isDescendantOfOrEqualTo(Doctrine_Record $subj) { - return (($this->getLeftValue() >= $subj->getNode()->getLeftValue()) && - ($this->getRightValue() <= $subj->getNode()->getRightValue()) && - ($this->getRootValue() == $subj->getNode()->getRootValue())); + return ($this->getLeftValue() >= $subj->getNode()->getLeftValue()) + && ($this->getRightValue() <= $subj->getNode()->getRightValue()) + && ($this->getRootValue() == $subj->getNode()->getRootValue()); } /** - * determines if node is ancestor of subject node + * determines if node is ancestor of subject node. * - * @return bool + * @return bool */ public function isAncestorOf(Doctrine_Record $subj) { - return (($subj->getNode()->getLeftValue() > $this->getLeftValue()) && - ($subj->getNode()->getRightValue() < $this->getRightValue()) && - ($subj->getNode()->getRootValue() == $this->getRootValue())); + return ($subj->getNode()->getLeftValue() > $this->getLeftValue()) + && ($subj->getNode()->getRightValue() < $this->getRightValue()) + && ($subj->getNode()->getRootValue() == $this->getRootValue()); } /** - * determines if node is valid + * determines if node is valid. + * + * @param mixed|null $record * * @return bool */ public function isValidNode($record = null) { - if ($record === null) { - return ($this->getRightValue() > $this->getLeftValue()); - } else if ( $record instanceof Doctrine_Record ) { - return ($record->getNode()->getRightValue() > $record->getNode()->getLeftValue()); - } else { - return false; + if (null === $record) { + return $this->getRightValue() > $this->getLeftValue(); + } + if ($record instanceof Doctrine_Record) { + return $record->getNode()->getRightValue() > $record->getNode()->getLeftValue(); } + + return false; } - + /** * Detaches the node from the tree by invalidating it's lft & rgt values * (they're set to 0). @@ -949,15 +959,16 @@ public function detach() } /** - * deletes node and it's descendants - * @todo Delete more efficiently. Wrap in transaction if needed. + * deletes node and it's descendants. + * + * @todo Delete more efficiently. Wrap in transaction if needed. */ public function delete() { $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + // TODO: add the setting whether or not to delete descendants or relocate children $oldRoot = $this->getRootValue(); $q = $this->_tree->getBaseQuery(); @@ -965,7 +976,7 @@ public function delete() $baseAlias = $this->_tree->getBaseAlias(); $componentName = $this->_tree->getBaseComponent(); - $q = $q->addWhere("$baseAlias.lft >= ? AND $baseAlias.rgt <= ?", array($this->getLeftValue(), $this->getRightValue())); + $q = $q->addWhere("{$baseAlias}.lft >= ? AND {$baseAlias}.rgt <= ?", array($this->getLeftValue(), $this->getRightValue())); $q = $this->_tree->returnQueryWithRootId($q, $oldRoot); @@ -976,38 +987,39 @@ public function delete() $first = $this->getRightValue() + 1; $delta = $this->getLeftValue() - $this->getRightValue() - 1; $this->shiftRLValues($first, $delta, $oldRoot); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } - - return true; + + return true; } /** - * sets node's left and right values and save's it + * sets node's left and right values and save's it. * - * @param int $destLeft node left value - * @param int $destRight node right value - */ + * @param int $destLeft node left value + * @param int $destRight node right value + */ private function insertNode($destLeft = 0, $destRight = 0, $destRoot = 1) { $this->setLeftValue($destLeft); $this->setRightValue($destRight); $this->setRootValue($destRoot); - $this->record->save(); + $this->record->save(); } /** - * move node's and its children to location $destLeft and updates rest of tree + * move node's and its children to location $destLeft and updates rest of tree. + * + * @param int $destLeft destination left value * - * @param int $destLeft destination left value * @todo Wrap in transaction */ private function updateNode($destLeft, $levelDiff) - { + { $componentName = $this->_tree->getBaseComponent(); $left = $this->getLeftValue(); $right = $this->getRightValue(); @@ -1018,7 +1030,7 @@ private function updateNode($destLeft, $levelDiff) $conn = $this->record->getTable()->getConnection(); try { $conn->beginInternalTransaction(); - + // Make room in the new branch $this->shiftRLValues($destLeft, $treeSize, $rootId); @@ -1031,8 +1043,9 @@ private function updateNode($destLeft, $levelDiff) $q = Doctrine_Core::getTable($componentName) ->createQuery() ->update() - ->set($componentName . '.level', $componentName.'.level + ?', array($levelDiff)) - ->where($componentName . '.lft > ? AND ' . $componentName . '.rgt < ?', array($left, $right)); + ->set($componentName.'.level', $componentName.'.level + ?', array($levelDiff)) + ->where($componentName.'.lft > ? AND '.$componentName.'.rgt < ?', array($left, $right)) + ; $q = $this->_tree->returnQueryWithRootId($q, $rootId); $q->execute(); @@ -1044,13 +1057,13 @@ private function updateNode($destLeft, $levelDiff) $this->record->save(); $this->record->refresh(); - + $conn->commit(); } catch (Exception $e) { $conn->rollback(); throw $e; } - + return true; } @@ -1060,31 +1073,35 @@ private function updateNode($destLeft, $levelDiff) * Note: This method does wrap its database queries in a transaction. This should be done * by the invoking code. * - * @param int $first First node to be shifted - * @param int $delta Value to be shifted by, can be negative - */ + * @param int $first First node to be shifted + * @param int $delta Value to be shifted by, can be negative + */ private function shiftRlValues($first, $delta, $rootId = 1) { // shift left columns $componentName = $this->_tree->getBaseComponent(); - $qLeft = Doctrine_Core::getTable($componentName) + $qLeft = Doctrine_Core::getTable($componentName) ->createQuery() - ->update($componentName); + ->update($componentName) + ; $qRight = Doctrine_Core::getTable($componentName) ->createQuery() - ->update($componentName); + ->update($componentName) + ; - $qLeft = $qLeft->set($componentName . '.lft', $componentName.'.lft + ?', $delta) - ->where($componentName . '.lft >= ?', $first); + $qLeft = $qLeft->set($componentName.'.lft', $componentName.'.lft + ?', $delta) + ->where($componentName.'.lft >= ?', $first) + ; $qLeft = $this->_tree->returnQueryWithRootId($qLeft, $rootId); $resultLeft = $qLeft->execute(); // shift right columns - $qRight = $qRight->set($componentName . '.rgt', $componentName.'.rgt + ?', $delta) - ->where($componentName . '.rgt >= ?', $first); + $qRight = $qRight->set($componentName.'.rgt', $componentName.'.rgt + ?', $delta) + ->where($componentName.'.rgt >= ?', $first) + ; $qRight = $this->_tree->returnQueryWithRootId($qRight, $rootId); @@ -1092,39 +1109,43 @@ private function shiftRlValues($first, $delta, $rootId = 1) } /** - * adds '$delta' to all Left and Right values that are >= '$first' and <= '$last'. + * adds '$delta' to all Left and Right values that are >= '$first' and <= '$last'. * '$delta' can also be negative. * * Note: This method does wrap its database queries in a transaction. This should be done * by the invoking code. * - * @param int $first First node to be shifted (L value) - * @param int $last Last node to be shifted (L value) - * @param int $delta Value to be shifted by, can be negative - */ + * @param int $first First node to be shifted (L value) + * @param int $last Last node to be shifted (L value) + * @param int $delta Value to be shifted by, can be negative + */ private function shiftRlRange($first, $last, $delta, $rootId = 1) { $componentName = $this->_tree->getBaseComponent(); - $qLeft = Doctrine_Core::getTable($componentName) + $qLeft = Doctrine_Core::getTable($componentName) ->createQuery() - ->update(); + ->update() + ; $qRight = Doctrine_Core::getTable($componentName) ->createQuery() - ->update(); + ->update() + ; // shift left column values - $qLeft = $qLeft->set($componentName . '.lft', $componentName.'.lft + ?', $delta) - ->where($componentName . '.lft >= ? AND ' . $componentName . '.lft <= ?', array($first, $last)); - + $qLeft = $qLeft->set($componentName.'.lft', $componentName.'.lft + ?', $delta) + ->where($componentName.'.lft >= ? AND '.$componentName.'.lft <= ?', array($first, $last)) + ; + $qLeft = $this->_tree->returnQueryWithRootId($qLeft, $rootId); $resultLeft = $qLeft->execute(); - + // shift right column values - $qRight = $qRight->set($componentName . '.rgt', $componentName.'.rgt + ?', $delta) - ->where($componentName . '.rgt >= ? AND ' . $componentName . '.rgt <= ?', array($first, $last)); + $qRight = $qRight->set($componentName.'.rgt', $componentName.'.rgt + ?', $delta) + ->where($componentName.'.rgt >= ? AND '.$componentName.'.rgt <= ?', array($first, $last)) + ; $qRight = $this->_tree->returnQueryWithRootId($qRight, $rootId); @@ -1132,88 +1153,89 @@ private function shiftRlRange($first, $last, $delta, $rootId = 1) } /** - * gets record's left value + * gets record's left value. * - * @return int - */ + * @return int + */ public function getLeftValue() { return $this->record->get('lft'); } /** - * sets record's left value + * sets record's left value. * - * @param int - */ + * @param int + */ public function setLeftValue($lft) { - $this->record->set('lft', $lft); + $this->record->set('lft', $lft); } /** - * gets record's right value + * gets record's right value. * - * @return int - */ + * @return int + */ public function getRightValue() { - return $this->record->get('rgt'); + return $this->record->get('rgt'); } /** - * sets record's right value + * sets record's right value. * - * @param int - */ + * @param int + */ public function setRightValue($rgt) { - $this->record->set('rgt', $rgt); + $this->record->set('rgt', $rgt); } /** - * gets level (depth) of node in the tree + * gets level (depth) of node in the tree. * - * @return int - */ + * @return int + */ public function getLevel() { - if ( ! isset($this->record['level'])) { + if (!isset($this->record['level'])) { $baseAlias = $this->_tree->getBaseAlias(); $componentName = $this->_tree->getBaseComponent(); $q = $this->_tree->getBaseQuery(); - $q = $q->addWhere("$baseAlias.lft < ? AND $baseAlias.rgt > ?", array($this->getLeftValue(), $this->getRightValue())); + $q = $q->addWhere("{$baseAlias}.lft < ? AND {$baseAlias}.rgt > ?", array($this->getLeftValue(), $this->getRightValue())); $q = $this->_tree->returnQueryWithRootId($q, $this->getRootValue()); - + $coll = $q->execute(); $this->record['level'] = count($coll) ? count($coll) : 0; } + return $this->record['level']; } /** - * get records root id value - * - */ + * get records root id value. + */ public function getRootValue() { if ($this->_tree->getAttribute('hasManyRoots')) { return $this->record->get($this->_tree->getAttribute('rootColumnName')); } + return 1; } /** - * sets records root id value + * sets records root id value. * - * @param int + * @param int */ public function setRootValue($value) { if ($this->_tree->getAttribute('hasManyRoots')) { - $this->record->set($this->_tree->getAttribute('rootColumnName'), $value); - } + $this->record->set($this->_tree->getAttribute('rootColumnName'), $value); + } } } diff --git a/lib/Doctrine/Node/NestedSet/LevelOrderIterator.php b/lib/Doctrine/Node/NestedSet/LevelOrderIterator.php index c7dde8e86..09405ac40 100644 --- a/lib/Doctrine/Node/NestedSet/LevelOrderIterator.php +++ b/lib/Doctrine/Node/NestedSet/LevelOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_NestedSet_LevelOrderIterator + * Doctrine_Node_NestedSet_LevelOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_NestedSet_LevelOrderIterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/NestedSet/PostOrderIterator.php b/lib/Doctrine/Node/NestedSet/PostOrderIterator.php index 4e8689b3d..df66a366a 100644 --- a/lib/Doctrine/Node/NestedSet/PostOrderIterator.php +++ b/lib/Doctrine/Node/NestedSet/PostOrderIterator.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Node_NestedSet_PostOrderIterator + * Doctrine_Node_NestedSet_PostOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_NestedSet_PostOrderIterator -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Node/NestedSet/PreOrderIterator.php b/lib/Doctrine/Node/NestedSet/PreOrderIterator.php index a35a72223..ba27ac324 100644 --- a/lib/Doctrine/Node/NestedSet/PreOrderIterator.php +++ b/lib/Doctrine/Node/NestedSet/PreOrderIterator.php @@ -20,50 +20,48 @@ */ /** - * Doctrine_Node_NestedSet_PreOrderIterator + * Doctrine_Node_NestedSet_PreOrderIterator. * - * @package Doctrine - * @subpackage Node * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Node_NestedSet_PreOrderIterator implements Iterator { /** - * @var Doctrine_Collection $collection + * @var Doctrine_Collection */ protected $collection; /** - * @var array $keys + * @var array */ protected $keys; - /** - * @var mixed $key - */ protected $key; /** - * @var integer $index + * @var int */ protected $index; /** - * @var integer $index + * @var int */ protected $prevIndex; /** - * @var integer $index + * @var int */ protected $traverseLevel; /** - * @var integer $count + * @var int */ protected $count; @@ -75,30 +73,28 @@ public function __construct($record, $opts) $params = array($record->get('lft'), $record->get('rgt')); if (isset($opts['include_record']) && $opts['include_record']) { - $query = $q->where("$componentName.lft >= ? AND $componentName.rgt <= ?", $params)->orderBy("$componentName.lft asc"); + $query = $q->where("{$componentName}.lft >= ? AND {$componentName}.rgt <= ?", $params)->orderBy("{$componentName}.lft asc"); } else { - $query = $q->where("$componentName.lft > ? AND $componentName.rgt < ?", $params)->orderBy("$componentName.lft asc"); + $query = $q->where("{$componentName}.lft > ? AND {$componentName}.rgt < ?", $params)->orderBy("{$componentName}.lft asc"); } - + $query = $record->getTable()->getTree()->returnQueryWithRootId($query, $record->getNode()->getRootValue()); - $this->maxLevel = isset($opts['depth']) ? ($opts['depth'] + $record->getNode()->getLevel()) : 0; - $this->options = $opts; + $this->maxLevel = isset($opts['depth']) ? ($opts['depth'] + $record->getNode()->getLevel()) : 0; + $this->options = $opts; $this->collection = isset($opts['collection']) ? $opts['collection'] : $query->execute(); - $this->keys = $this->collection->getKeys(); - $this->count = $this->collection->count(); - $this->index = -1; - $this->level = $record->getNode()->getLevel(); - $this->prevLeft = $record->getNode()->getLeftValue(); + $this->keys = $this->collection->getKeys(); + $this->count = $this->collection->count(); + $this->index = -1; + $this->level = $record->getNode()->getLevel(); + $this->prevLeft = $record->getNode()->getLeftValue(); // clear the table identity cache $record->getTable()->clear(); } /** - * rewinds the iterator - * - * @return void + * rewinds the iterator. */ public function rewind() { @@ -107,9 +103,9 @@ public function rewind() } /** - * returns the current key + * returns the current key. * - * @return integer + * @return int */ public function key() { @@ -117,7 +113,7 @@ public function key() } /** - * returns the current record + * returns the current record. * * @return Doctrine_Record */ @@ -125,13 +121,12 @@ public function current() { $record = $this->collection->get($this->key); $record->getNode()->setLevel($this->level); + return $record; } /** - * advances the internal pointer - * - * @return void + * advances the internal pointer. */ public function next() { @@ -147,11 +142,11 @@ public function next() } /** - * @return boolean whether or not the iteration will continue + * @return bool whether or not the iteration will continue */ public function valid() { - return ($this->index < $this->count); + return $this->index < $this->count; } public function count() @@ -161,7 +156,7 @@ public function count() private function updateLevel() { - if ( ! (isset($this->options['include_record']) && $this->options['include_record'] && $this->index == 0)) { + if (!(isset($this->options['include_record']) && $this->options['include_record'] && 0 == $this->index)) { $left = $this->collection->get($this->key)->getNode()->getLeftValue(); $this->level += $this->prevLeft - $left + 2; $this->prevLeft = $left; @@ -170,14 +165,15 @@ private function updateLevel() private function advanceIndex() { - $this->index++; + ++$this->index; $i = $this->index; if (isset($this->keys[$i])) { - $this->key = $this->keys[$i]; + $this->key = $this->keys[$i]; $this->updateLevel(); + return $this->current(); } return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Null.php b/lib/Doctrine/Null.php index 4897de92d..2d3cf3dd8 100644 --- a/lib/Doctrine/Null.php +++ b/lib/Doctrine/Null.php @@ -20,28 +20,29 @@ */ /** - * Doctrine_Null + * Doctrine_Null. * * Simple empty class representing a null value * used for extra fast null value testing with isset() rather than array_key_exists() * - * @package Doctrine - * @subpackage Null * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ final class Doctrine_Null -{ +{ public function exists() { - return false; + return false; } public function __toString() { return ''; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Overloadable.php b/lib/Doctrine/Overloadable.php index b8e61eee3..ccc22ed7c 100644 --- a/lib/Doctrine/Overloadable.php +++ b/lib/Doctrine/Overloadable.php @@ -21,24 +21,27 @@ /** * Doctrine_Overloadable - * a very generic overloading interface + * a very generic overloading interface. * - * @package Doctrine - * @subpackage Overloadable * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ -interface Doctrine_Overloadable { +interface Doctrine_Overloadable +{ /** * __call - * method overloader + * method overloader. + * + * @param string $m the name of the method + * @param array $a method arguments * - * @param string $m the name of the method - * @param array $a method arguments - * @return mixed return value of the method + * @return mixed return value of the method */ public function __call($m, $a); } diff --git a/lib/Doctrine/Pager.php b/lib/Doctrine/Pager.php index 818f4e721..83cdf998d 100644 --- a/lib/Doctrine/Pager.php +++ b/lib/Doctrine/Pager.php @@ -20,68 +20,65 @@ */ /** - * Doctrine_Pager + * Doctrine_Pager. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager { /** - * @var Doctrine_Query $_query Doctrine_Query object related to the pager + * @var Doctrine_Query Doctrine_Query object related to the pager */ protected $_query; /** - * @var Doctrine_Query $_countQuery Doctrine_Query object related to the counter of pager + * @var Doctrine_Query Doctrine_Query object related to the counter of pager */ protected $_countQuery; /** - * @var array $_countQueryParams Hold the params to be used by Doctrine_Query counter object of pager + * @var array Hold the params to be used by Doctrine_Query counter object of pager */ protected $_countQueryParams; /** - * @var integer $_numResults Number of results found + * @var int Number of results found */ protected $_numResults; /** - * @var integer $_maxPerPage Maximum number of itens per page + * @var int Maximum number of itens per page */ protected $_maxPerPage; /** - * @var integer $page Current page + * @var int Current page */ protected $_page; /** - * @var integer $_lastPage Last page (total of pages) + * @var int Last page (total of pages) */ protected $_lastPage; /** - * @var boolean $_executed Pager was initialized (called "execute" at least once) + * @var bool Pager was initialized (called "execute" at least once) */ protected $_executed; - - /** - * __construct + * __construct. * - * @param mixed $query Accepts either a Doctrine_Query object or a string - * (which does the Doctrine_Query class creation). - * @param int $page Current page - * @param int $maxPerPage Maximum itens per page - * @return void + * @param mixed $query accepts either a Doctrine_Query object or a string + * (which does the Doctrine_Query class creation) + * @param int $page Current page + * @param int $maxPerPage Maximum itens per page */ public function __construct($query, $page, $maxPerPage = 0) { @@ -94,12 +91,11 @@ public function __construct($query, $page, $maxPerPage = 0) } /** - * _initialize + * _initialize. * * Initialize Pager object calculating number of results * - * @param $params Optional parameters to Doctrine_Query::execute - * @return void + * @param $params Optional parameters to Doctrine_Query::execute */ protected function _initialize($params = array()) { @@ -114,11 +110,9 @@ protected function _initialize($params = array()) } /** - * _adjustOffset + * _adjustOffset. * * Adjusts last page of Doctrine_Pager, offset and limit of Doctrine_Query associated - * - * @return void */ protected function _adjustOffset() { @@ -135,11 +129,11 @@ protected function _adjustOffset() } /** - * getExecuted + * getExecuted. * * Returns the check if Pager was already executed at least once * - * @return boolen Pager was executed + * @return boolen Pager was executed */ public function getExecuted() { @@ -147,12 +141,11 @@ public function getExecuted() } /** - * _setExecuted + * _setExecuted. * * Defines if Pager was already executed * - * @param $executed Pager was executed - * @return void + * @param $executed Pager was executed */ protected function _setExecuted($executed) { @@ -160,28 +153,29 @@ protected function _setExecuted($executed) } /** - * getRange + * getRange. * * Builds and return a Doctrine_Pager_Range_* based on arguments * * @param string $rangeStyle Pager Range style - * @param array $options Custom subclass implementation options. + * @param array $options Custom subclass implementation options. * Default is a blank array + * * @return Doctrine_Pager_Range Pager Range */ public function getRange($rangeStyle, $options = array()) { - $class = 'Doctrine_Pager_Range_' . ucfirst($rangeStyle); + $class = 'Doctrine_Pager_Range_'.ucfirst($rangeStyle); return new $class($options, $this); } /** - * getNumResults + * getNumResults. * * Returns the number of results found * - * @return int the number of results found + * @return int the number of results found */ public function getNumResults() { @@ -189,18 +183,15 @@ public function getNumResults() return $this->_numResults; } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the number of results of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the number of results of a not yet executed Pager query'); } /** - * _setNumResults + * _setNumResults. * * Defines the number of total results on initial query * - * @param $nb Number of results found on initial query fetch - * @return void + * @param $nb Number of results found on initial query fetch */ protected function _setNumResults($nb) { @@ -208,11 +199,11 @@ protected function _setNumResults($nb) } /** - * getFirstPage + * getFirstPage. * * Returns the first page * - * @return int first page + * @return int first page */ public function getFirstPage() { @@ -220,11 +211,11 @@ public function getFirstPage() } /** - * getLastPage + * getLastPage. * * Returns the last page (total of pages) * - * @return int last page (total of pages) + * @return int last page (total of pages) */ public function getLastPage() { @@ -232,18 +223,15 @@ public function getLastPage() return $this->_lastPage; } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the last page number of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the last page number of a not yet executed Pager query'); } /** - * _setLastPage + * _setLastPage. * * Defines the last page (total of pages) * - * @param $page last page (total of pages) - * @return void + * @param $page last page (total of pages) */ protected function _setLastPage($page) { @@ -255,11 +243,11 @@ protected function _setLastPage($page) } /** - * getLastPage + * getLastPage. * * Returns the current page * - * @return int current page + * @return int current page */ public function getPage() { @@ -267,11 +255,11 @@ public function getPage() } /** - * getNextPage + * getNextPage. * * Returns the next page * - * @return int next page + * @return int next page */ public function getNextPage() { @@ -279,17 +267,15 @@ public function getNextPage() return min($this->getPage() + 1, $this->getLastPage()); } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the last page number of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the last page number of a not yet executed Pager query'); } /** - * getPreviousPage + * getPreviousPage. * * Returns the previous page * - * @return int previous page + * @return int previous page */ public function getPreviousPage() { @@ -297,13 +283,11 @@ public function getPreviousPage() return max($this->getPage() - 1, $this->getFirstPage()); } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the previous page number of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the previous page number of a not yet executed Pager query'); } /** - * getFirstIndice + * getFirstIndice. * * Return the first indice number for the current page * @@ -315,7 +299,7 @@ public function getFirstIndice() } /** - * getLastIndice + * getLastIndice. * * Return the last indice number for the current page * @@ -323,15 +307,15 @@ public function getFirstIndice() */ public function getLastIndice() { - return min($this->getNumResults(), ($this->getPage() * $this->getMaxPerPage())); + return min($this->getNumResults(), $this->getPage() * $this->getMaxPerPage()); } /** - * haveToPaginate + * haveToPaginate. * * Return true if it's necessary to paginate or false if not * - * @return bool true if it is necessary to paginate, false otherwise + * @return bool true if it is necessary to paginate, false otherwise */ public function haveToPaginate() { @@ -339,18 +323,15 @@ public function haveToPaginate() return $this->getNumResults() > $this->getMaxPerPage(); } - throw new Doctrine_Pager_Exception( - 'Cannot know if it is necessary to paginate a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot know if it is necessary to paginate a not yet executed Pager query'); } /** - * setPage + * setPage. * * Defines the current page and automatically adjust offset and limits * - * @param $page current page - * @return void + * @param $page current page */ public function setPage($page) { @@ -359,12 +340,11 @@ public function setPage($page) } /** - * _setPage + * _setPage. * * Defines the current page * - * @param $page current page - * @return void + * @param $page current page */ protected function _setPage($page) { @@ -373,11 +353,11 @@ protected function _setPage($page) } /** - * getLastPage + * getLastPage. * * Returns the maximum number of itens per page * - * @return int maximum number of itens per page + * @return int maximum number of itens per page */ public function getMaxPerPage() { @@ -385,18 +365,17 @@ public function getMaxPerPage() } /** - * setMaxPerPage + * setMaxPerPage. * * Defines the maximum number of itens per page and automatically adjust offset and limits * - * @param $max maximum number of itens per page - * @return void + * @param $max maximum number of itens per page */ public function setMaxPerPage($max) { if ($max > 0) { $this->_maxPerPage = $max; - } else if ($max == 0) { + } elseif (0 == $max) { $this->_maxPerPage = 25; } else { $this->_maxPerPage = abs($max); @@ -406,11 +385,11 @@ public function setMaxPerPage($max) } /** - * getResultsInPage + * getResultsInPage. * * Returns the number of itens in current page * - * @return int Number of itens in current page + * @return int Number of itens in current page */ public function getResultsInPage() { @@ -426,11 +405,11 @@ public function getResultsInPage() } /** - * getQuery + * getQuery. * * Returns the Doctrine_Query collector object related to the pager * - * @return Doctrine_Query Doctrine_Query object related to the pager + * @return Doctrine_Query Doctrine_Query object related to the pager */ public function getQuery() { @@ -438,52 +417,53 @@ public function getQuery() } /** - * _setQuery + * _setQuery. * * Defines the collector query to be used by pager * - * @param Doctrine_Query Accepts either a Doctrine_Query object or a string - * (which does the Doctrine_Query class creation). - * @return void + * @param Doctrine_Query accepts either a Doctrine_Query object or a string + * (which does the Doctrine_Query class creation) */ protected function _setQuery($query) { if (is_string($query)) { $query = Doctrine_Query::create() - ->parseDqlQuery($query); + ->parseDqlQuery($query) + ; } $this->_query = $query; } /** - * getCountQuery + * getCountQuery. * * Returns the Doctrine_Query object that is used to make the count results to pager * - * @return Doctrine_Query Doctrine_Query object related to the pager + * @return Doctrine_Query Doctrine_Query object related to the pager */ public function getCountQuery() { - return ($this->_countQuery !== null) ? $this->_countQuery : $this->_query; + return (null !== $this->_countQuery) ? $this->_countQuery : $this->_query; } /** - * setCountQuery + * setCountQuery. * * Defines the counter query to be used by pager * - * @param Doctrine_Query Accepts either a Doctrine_Query object or a string - * (which does the Doctrine_Query class creation). - * @param array Optional params to be used by counter Doctrine_Query. + * @param Doctrine_Query accepts either a Doctrine_Query object or a string + * (which does the Doctrine_Query class creation) + * @param array Optional params to be used by counter Doctrine_Query. * If not defined, the params passed to execute method will be used. - * @return void + * @param mixed|null $params */ public function setCountQuery($query, $params = null) { if (is_string($query)) { $query = Doctrine_Query::create() - ->parseDqlQuery($query); + ->parseDqlQuery($query) + ; } $this->_countQuery = $query; @@ -494,33 +474,32 @@ public function setCountQuery($query, $params = null) } /** - * getCountQueryParams + * getCountQueryParams. * * Returns the params to be used by counter Doctrine_Query * - * @return array Doctrine_Query counter params + * @return array Doctrine_Query counter params */ public function getCountQueryParams($defaultParams = array()) { - return ($this->_countQueryParams !== null) ? $this->_countQueryParams : $defaultParams; + return (null !== $this->_countQueryParams) ? $this->_countQueryParams : $defaultParams; } /** - * setCountQueryParams + * setCountQueryParams. * * Defines the params to be used by counter Doctrine_Query * - * @param array Optional params to be used by counter Doctrine_Query. + * @param array Optional params to be used by counter Doctrine_Query. * If not defined, the params passed to execute method will be used. - * @param boolean Optional argument that append the query param instead of overriding the existent ones. - * @return void + * @param bool optional argument that append the query param instead of overriding the existent ones */ public function setCountQueryParams($params = array(), $append = false) { if ($append && is_array($this->_countQueryParams)) { $this->_countQueryParams = array_merge($this->_countQueryParams, $params); } else { - if ($params !== null && !is_array($params)) { + if (null !== $params && !is_array($params)) { $params = array($params); } @@ -531,20 +510,21 @@ public function setCountQueryParams($params = array(), $append = false) } /** - * execute + * execute. * * Executes the query, populates the collection and then return it * - * @param $params Optional parameters to Doctrine_Query::execute - * @param $hydrationMode Hydration Mode of Doctrine_Query::execute returned ResultSet. - * @return Doctrine_Collection The root collection + * @param $params Optional parameters to Doctrine_Query::execute + * @param $hydrationMode Hydration Mode of Doctrine_Query::execute returned ResultSet + * + * @return Doctrine_Collection The root collection */ public function execute($params = array(), $hydrationMode = null) { - if ( !$this->getExecuted()) { + if (!$this->getExecuted()) { $this->_initialize($params); } - + return $this->getQuery()->execute($params, $hydrationMode); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Pager/Exception.php b/lib/Doctrine/Pager/Exception.php index a8f0ecd48..5d8e6c231 100644 --- a/lib/Doctrine/Pager/Exception.php +++ b/lib/Doctrine/Pager/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Pager_Exception + * Doctrine_Pager_Exception. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Pager/Layout.php b/lib/Doctrine/Pager/Layout.php index bc831b934..843a736bc 100644 --- a/lib/Doctrine/Pager/Layout.php +++ b/lib/Doctrine/Pager/Layout.php @@ -20,63 +20,61 @@ */ /** - * Doctrine_Pager_Layout + * Doctrine_Pager_Layout. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager_Layout { /** - * @var Doctrine_Pager $_pager Doctrine_Pager object related to the pager layout + * @var Doctrine_Pager Doctrine_Pager object related to the pager layout */ private $_pager; /** - * @var Doctrine_Pager_Range $_pagerRange Doctrine_Pager_Range object related to the pager layout + * @var Doctrine_Pager_Range Doctrine_Pager_Range object related to the pager layout */ private $_pagerRange; /** - * @var string $_template Template to be applied for inactive pages - * (and also active is selected template is not defined) + * @var string Template to be applied for inactive pages + * (and also active is selected template is not defined) */ private $_template; /** - * @var string $_selectedTemplate Template to be applied for active page + * @var string Template to be applied for active page */ private $_selectedTemplate; /** - * @var string $_separatorTemplate Separator template, applied between each page + * @var string Separator template, applied between each page */ private $_separatorTemplate; /** - * @var string $_urlMask URL to be assigned for each page. Masks are used as: {%var_name} + * @var string URL to be assigned for each page. Masks are used as: {%var_name} */ private $_urlMask; - + /** - * @var array $_maskReplacements Stores references of masks and their correspondent - * (replaces defined masks with new masks or values) + * @var array Stores references of masks and their correspondent + * (replaces defined masks with new masks or values) */ private $_maskReplacements = array(); - /** - * __construct + * __construct. * - * @param Doctrine_Pager $pager Doctrine_Pager object related to the pager layout - * @param Doctrine_Pager_Range $pagerRange Doctrine_Pager_Range object related to the pager layout - * @param string $urlMask URL to be assigned for each page - * @return void + * @param Doctrine_Pager $pager Doctrine_Pager object related to the pager layout + * @param Doctrine_Pager_Range $pagerRange Doctrine_Pager_Range object related to the pager layout + * @param string $urlMask URL to be assigned for each page */ public function __construct($pager, $pagerRange, $urlMask) { @@ -90,11 +88,11 @@ public function __construct($pager, $pagerRange, $urlMask) } /** - * getPager + * getPager. * * Returns the Doctrine_Pager object related to the pager layout * - * @return Doctrine_Pager Doctrine_Pager object related to the pager range + * @return Doctrine_Pager Doctrine_Pager object related to the pager range */ public function getPager() { @@ -102,12 +100,11 @@ public function getPager() } /** - * _setPager + * _setPager. * * Defines the Doctrine_Pager object related to the pager layout * - * @param $pager Doctrine_Pager object related to the pager range - * @return void + * @param $pager Doctrine_Pager object related to the pager range */ protected function _setPager($pager) { @@ -115,13 +112,14 @@ protected function _setPager($pager) } /** - * execute + * execute. * * Handy method to execute the query without need to retrieve the Pager instance * - * @param $params Optional parameters to Doctrine_Query::execute - * @param $hydrationMode Hydration Mode of Doctrine_Query::execute returned ResultSet. - * @return Doctrine_Collection The root collection + * @param $params Optional parameters to Doctrine_Query::execute + * @param $hydrationMode Hydration Mode of Doctrine_Query::execute returned ResultSet + * + * @return Doctrine_Collection The root collection */ public function execute($params = array(), $hydrationMode = null) { @@ -129,11 +127,11 @@ public function execute($params = array(), $hydrationMode = null) } /** - * getPagerRange + * getPagerRange. * * Returns the Doctrine_Pager_Range subclass object related to the pager layout * - * @return Doctrine_Pager_Range Doctrine_Pager_Range subclass object related to the pager range + * @return Doctrine_Pager_Range Doctrine_Pager_Range subclass object related to the pager range */ public function getPagerRange() { @@ -141,12 +139,11 @@ public function getPagerRange() } /** - * _setPagerRange + * _setPagerRange. * * Defines the Doctrine_Pager_Range subclass object related to the pager layout * - * @param $pagerRange Doctrine_Pager_Range subclass object related to the pager range - * @return void + * @param $pagerRange Doctrine_Pager_Range subclass object related to the pager range */ protected function _setPagerRange($pagerRange) { @@ -155,11 +152,11 @@ protected function _setPagerRange($pagerRange) } /** - * getUrlMask + * getUrlMask. * * Returns the URL to be assigned for each page * - * @return string URL to be assigned for each page + * @return string URL to be assigned for each page */ public function getUrlMask() { @@ -167,25 +164,23 @@ public function getUrlMask() } /** - * _setUrlMask + * _setUrlMask. * * Defines the URL to be assigned for each page * - * @param $urlMask URL to be assigned for each page - * @return void + * @param $urlMask URL to be assigned for each page */ protected function _setUrlMask($urlMask) { $this->_urlMask = $urlMask; } - - /** - * getTemplate + /** + * getTemplate. * * Returns the Template to be applied for inactive pages * - * @return string Template to be applied for inactive pages + * @return string Template to be applied for inactive pages */ public function getTemplate() { @@ -193,13 +188,12 @@ public function getTemplate() } /** - * setTemplate + * setTemplate. * - * Defines the Template to be applied for inactive pages + * Defines the Template to be applied for inactive pages * (also active page if selected template not defined) * - * @param $template Template to be applied for inactive pages - * @return void + * @param $template Template to be applied for inactive pages */ public function setTemplate($template) { @@ -207,11 +201,11 @@ public function setTemplate($template) } /** - * getSelectedTemplate + * getSelectedTemplate. * * Returns the Template to be applied for active page * - * @return string Template to be applied for active page + * @return string Template to be applied for active page */ public function getSelectedTemplate() { @@ -219,12 +213,11 @@ public function getSelectedTemplate() } /** - * setSelectedTemplate + * setSelectedTemplate. * * Defines the Template to be applied for active page * - * @param $selectedTemplate Template to be applied for active page - * @return void + * @param $selectedTemplate Template to be applied for active page */ public function setSelectedTemplate($selectedTemplate) { @@ -232,11 +225,11 @@ public function setSelectedTemplate($selectedTemplate) } /** - * getSeparatorTemplate + * getSeparatorTemplate. * * Returns the Separator template, applied between each page * - * @return string Separator template, applied between each page + * @return string Separator template, applied between each page */ public function getSeparatorTemplate() { @@ -244,49 +237,46 @@ public function getSeparatorTemplate() } /** - * setSeparatorTemplate + * setSeparatorTemplate. * * Defines the Separator template, applied between each page * - * @param $separatorTemplate Separator template, applied between each page - * @return void - */ + * @param $separatorTemplate Separator template, applied between each page + */ public function setSeparatorTemplate($separatorTemplate) { $this->_separatorTemplate = $separatorTemplate; } /** - * addMaskReplacement + * addMaskReplacement. * * Defines a mask replacement. When parsing template, it converts replacement * masks into new ones (or values), allowing to change masks behavior on the fly * - * @param $oldMask Mask to be replaced - * @param $newMask Mask or Value that will be defined after replacement - * @param $asValue Optional value (default false) that if defined as true, - * changes the bahavior of replacement mask to replacement - * value - * @return void - */ + * @param $oldMask Mask to be replaced + * @param $newMask Mask or Value that will be defined after replacement + * @param $asValue Optional value (default false) that if defined as true, + * changes the bahavior of replacement mask to replacement + * value + */ public function addMaskReplacement($oldMask, $newMask, $asValue = false) { if (($oldMask = trim($oldMask)) != 'page_number') { $this->_maskReplacements[$oldMask] = array( 'newMask' => $newMask, - 'asValue' => ($asValue === false) ? false : true + 'asValue' => (false === $asValue) ? false : true, ); } } /** - * removeMaskReplacement + * removeMaskReplacement. * * Remove a mask replacement * - * @param $oldMask Replacement Mask to be removed - * @return void - */ + * @param $oldMask Replacement Mask to be removed + */ public function removeMaskReplacement($oldMask) { if (isset($this->_maskReplacements[$oldMask])) { @@ -294,15 +284,12 @@ public function removeMaskReplacement($oldMask) unset($this->_maskReplacements[$oldMask]); } } - - + /** - * cleanMaskReplacements + * cleanMaskReplacements. * * Remove all mask replacements - * - * @return void - */ + */ public function cleanMaskReplacements() { $this->_maskReplacements = null; @@ -310,16 +297,13 @@ public function cleanMaskReplacements() } /** - * display + * display. * * Displays the pager on screen based on templates and options defined * - * @param $options Optional parameters to be applied in template and url mask - * @param $return Optional parameter if you want to capture the output of this method call - * (Default value is false), instead of printing it - * @return void If you would like to capture the output of Doctrine_Pager_Layout::display(), - * use the $return parameter. If this parameter is set to TRUE, this method - * will return its output, instead of printing it (which it does by default) + * @param $options Optional parameters to be applied in template and url mask + * @param $return Optional parameter if you want to capture the output of this method call + * (Default value is false), instead of printing it */ public function display($options = array(), $return = false) { @@ -327,7 +311,7 @@ public function display($options = array(), $return = false) $str = ''; // For each page in range - for ($i = 0, $l = count($range); $i < $l; $i++) { + for ($i = 0, $l = count($range); $i < $l; ++$i) { // Define some optional mask values $options['page_number'] = $range[$i]; @@ -348,28 +332,26 @@ public function display($options = array(), $return = false) } /** - * processPage + * processPage. * * Parses the template and returns the string of a processed page * * @param array Optional parameters to be applied in template and url mask - * @return string Processed template for the given page + * + * @return string Processed template for the given page */ public function processPage($options = array()) { // Check if at least basic options are defined - if ( !isset($options['page_number'])) { - throw new Doctrine_Pager_Exception( - 'Cannot process template of the given page. ' . - 'Missing at least one of needed parameters: \'page\' or \'page_number\'' - ); + if (!isset($options['page_number'])) { + throw new Doctrine_Pager_Exception('Cannot process template of the given page. Missing at least one of needed parameters: \'page\' or \'page_number\''); // Should never reach here return ''; } // Assign "page" options index if not defined yet - if ( !isset($this->_maskReplacements['page']) && !isset($options['page'])) { + if (!isset($this->_maskReplacements['page']) && !isset($options['page'])) { $options['page'] = $options['page_number']; } @@ -381,16 +363,17 @@ public function processPage($options = array()) */ public function __toString() { - return $this->display(array(), true); + return $this->display(array(), true); } /** - * _parseTemplate + * _parseTemplate. * * Parse the template of a given page and return the processed template * * @param array Optional parameters to be applied in template and url mask - * @return string + * + * @return string */ protected function _parseTemplate($options = array()) { @@ -401,12 +384,13 @@ protected function _parseTemplate($options = array()) } /** - * _parseUrlTemplate + * _parseUrlTemplate. * * Parse the url mask to return the correct template depending of the options sent. * Already process the mask replacements assigned. * - * @param $options Optional parameters to be applied in template and url mask + * @param $options Optional parameters to be applied in template and url mask + * * @return string */ protected function _parseUrlTemplate($options = array()) @@ -419,7 +403,7 @@ protected function _parseUrlTemplate($options = array()) } // Possible attempt where Selected == Template - if ($str == '') { + if ('' == $str) { $str = $this->_parseMaskReplacements($this->getTemplate()); } @@ -427,11 +411,12 @@ protected function _parseUrlTemplate($options = array()) } /** - * _parseUrl + * _parseUrl. * * Parse the mask replacements of a given page * - * @param $options Optional parameters to be applied in template and url mask + * @param $options Optional parameters to be applied in template and url mask + * * @return string */ protected function _parseReplacementsTemplate($options = array()) @@ -449,11 +434,12 @@ protected function _parseReplacementsTemplate($options = array()) } /** - * _parseUrl + * _parseUrl. * * Parse the url mask of a given page and return the processed url * - * @param $options Optional parameters to be applied in template and url mask + * @param $options Optional parameters to be applied in template and url mask + * * @return string */ protected function _parseUrl($options = array()) @@ -470,21 +456,22 @@ protected function _parseUrl($options = array()) } /** - * _parseMaskReplacements + * _parseMaskReplacements. * * Parse the mask replacements, changing from to-be replaced mask with new masks/values * - * @param $str String to have masks replaced - * @return string + * @param $str String to have masks replaced + * + * @return string */ protected function _parseMaskReplacements($str) { $replacements = array(); foreach ($this->_maskReplacements as $k => $v) { - $replacements['{%'.$k.'}'] = ($v['asValue'] === true) ? $v['newMask'] : '{%'.$v['newMask'].'}'; + $replacements['{%'.$k.'}'] = (true === $v['asValue']) ? $v['newMask'] : '{%'.$v['newMask'].'}'; } return strtr($str, $replacements); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Pager/Range.php b/lib/Doctrine/Pager/Range.php index b512684c4..39a4dcf15 100644 --- a/lib/Doctrine/Pager/Range.php +++ b/lib/Doctrine/Pager/Range.php @@ -20,52 +20,50 @@ */ /** - * Doctrine_Pager_Range + * Doctrine_Pager_Range. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ abstract class Doctrine_Pager_Range { /** - * @var array $_options Custom Doctrine_Pager_Range implementation options + * @var array Custom Doctrine_Pager_Range implementation options */ protected $_options; /** - * @var Doctrine_Pager $pager Doctrine_Pager object related to the pager range + * @var Doctrine_Pager Doctrine_Pager object related to the pager range */ private $pager; - /** - * __construct + * __construct. * - * @param array $options Custom subclass implementation options. - * Default is a blank array - * @param Doctrine_Pager $pager Optional Doctrine_Pager object to be associated - * @return void + * @param array $options Custom subclass implementation options. + * Default is a blank array + * @param Doctrine_Pager $pager Optional Doctrine_Pager object to be associated */ final public function __construct($options = array(), $pager = null) { $this->_setOptions($options); - if ($pager !== null) { + if (null !== $pager) { $this->setPager($pager); } } /** - * getPager + * getPager. * * Returns the Doctrine_Pager object related to the pager range * - * @return Doctrine_Pager Doctrine_Pager object related to the pager range + * @return Doctrine_Pager Doctrine_Pager object related to the pager range */ public function getPager() { @@ -73,13 +71,12 @@ public function getPager() } /** - * setPager + * setPager. * * Defines the Doctrine_Pager object related to the pager range and * automatically (re-)initialize Doctrine_Pager_Range * - * @param $pager Doctrine_Pager object related to the pager range - * @return void + * @param $pager Doctrine_Pager object related to the pager range */ public function setPager($pager) { @@ -92,11 +89,11 @@ public function setPager($pager) } /** - * getOptions + * getOptions. * * Returns the custom Doctrine_Pager_Range implementation options * - * @return array Custom Doctrine_Pager_Range implementation options + * @return array Custom Doctrine_Pager_Range implementation options */ public function getOptions() { @@ -104,11 +101,11 @@ public function getOptions() } /** - * getOption + * getOption. * * Returns the custom Doctrine_Pager_Range implementation offset option * - * @return array Custom Doctrine_Pager_Range implementation options + * @return array Custom Doctrine_Pager_Range implementation options */ public function getOption($option) { @@ -116,18 +113,15 @@ public function getOption($option) return $this->_options[$option]; } - throw new Doctrine_Pager_Exception( - 'Cannot access unexistent option \'' . $option . '\' in Doctrine_Pager_Range class' - ); + throw new Doctrine_Pager_Exception('Cannot access unexistent option \''.$option.'\' in Doctrine_Pager_Range class'); } /** - * _setOptions + * _setOptions. * * Defines the subclass implementation options * - * @param $options Custom Doctrine_Pager_Range implementation options - * @return void + * @param $options Custom Doctrine_Pager_Range implementation options */ protected function _setOptions($options) { @@ -135,36 +129,32 @@ protected function _setOptions($options) } /** - * isInRange + * isInRange. * * Check if a given page is in the range * - * @param $page Page to be checked - * @return boolean + * @param $page Page to be checked + * + * @return bool */ public function isInRange($page) { - return (array_search($page, $this->rangeAroundPage()) !== false); + return false !== array_search($page, $this->rangeAroundPage()); } - - /** - * _initialize + * _initialize. * * Initialize Doctrine_Page_Range subclass which does custom class definitions - * - * @return void */ abstract protected function _initialize(); - /** - * rangeAroundPage + * rangeAroundPage. * * Calculate and returns an array representing the range around the current page * * @return array */ abstract public function rangeAroundPage(); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Pager/Range/Jumping.php b/lib/Doctrine/Pager/Range/Jumping.php index 137a4f6db..f2ecc2aa0 100644 --- a/lib/Doctrine/Pager/Range/Jumping.php +++ b/lib/Doctrine/Pager/Range/Jumping.php @@ -20,29 +20,27 @@ */ /** - * Doctrine_Pager_Range_Jumping + * Doctrine_Pager_Range_Jumping. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager_Range_Jumping extends Doctrine_Pager_Range { /** - * @var int $_chunkLength Chunk length to be returned + * @var int Chunk length to be returned */ private $_chunkLength; /** - * _initialize + * _initialize. * * Initialize Doctrine_Pager_Range_Jumping and does custom assignments - * - * @return void */ protected function _initialize() { @@ -54,11 +52,11 @@ protected function _initialize() } /** - * getChunkLength + * getChunkLength. * * Returns the size of the chunk defined * - * @return int Chunk length + * @return int Chunk length */ public function getChunkLength() { @@ -66,12 +64,11 @@ public function getChunkLength() } /** - * _setChunkLength + * _setChunkLength. * * Defines the size of the chunk * - * @param $chunkLength Chunk length - * @return void + * @param $chunkLength Chunk length */ protected function _setChunkLength($chunkLength) { @@ -79,7 +76,7 @@ protected function _setChunkLength($chunkLength) } /** - * rangeAroundPage + * rangeAroundPage. * * Calculate and returns an array representing the range around the current page * @@ -106,8 +103,6 @@ public function rangeAroundPage() return range($startPage, $endPage); } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the range around the page of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the range around the page of a not yet executed Pager query'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Pager/Range/Sliding.php b/lib/Doctrine/Pager/Range/Sliding.php index 93117b6cd..93f911e68 100644 --- a/lib/Doctrine/Pager/Range/Sliding.php +++ b/lib/Doctrine/Pager/Range/Sliding.php @@ -20,29 +20,27 @@ */ /** - * Doctrine_Pager_Range_Sliding + * Doctrine_Pager_Range_Sliding. * * @author Guilherme Blanco - * @package Doctrine - * @subpackage Pager * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 0.9 */ class Doctrine_Pager_Range_Sliding extends Doctrine_Pager_Range { /** - * @var int $_chunkLength Chunk length to be returned + * @var int Chunk length to be returned */ private $_chunkLength; /** - * _initialize + * _initialize. * * Initialize Doctrine_Pager_Range_Sliding and does custom assignments - * - * @return void */ protected function _initialize() { @@ -54,11 +52,11 @@ protected function _initialize() } /** - * getChunkLength + * getChunkLength. * * Returns the size of the chunk defined * - * @return int Chunk length + * @return int Chunk length */ public function getChunkLength() { @@ -66,17 +64,16 @@ public function getChunkLength() } /** - * _setChunkLength + * _setChunkLength. * * Defines the size of the chunk * - * @param $chunkLength Chunk length - * @return void + * @param $chunkLength Chunk length */ protected function _setChunkLength($chunkLength) { $chunkLength = (int) $chunkLength; - if ( !$chunkLength) { + if (!$chunkLength) { $chunkLength = 1; } else { $this->_chunkLength = $chunkLength; @@ -84,7 +81,7 @@ protected function _setChunkLength($chunkLength) } /** - * rangeAroundPage + * rangeAroundPage. * * Calculate and returns an array representing the range around the current page * @@ -95,7 +92,7 @@ public function rangeAroundPage() $pager = $this->getPager(); if ($pager->getExecuted()) { - $page = $pager->getPage(); + $page = $pager->getPage(); $pages = $pager->getLastPage(); $chunk = $this->getChunkLength(); @@ -104,8 +101,8 @@ public function rangeAroundPage() $chunk = $pages; } - $chunkStart = $page - (floor($chunk / 2)); - $chunkEnd = $page + (ceil($chunk / 2)-1); + $chunkStart = $page - floor($chunk / 2); + $chunkEnd = $page + (ceil($chunk / 2) - 1); if ($chunkStart < 1) { $adjust = 1 - $chunkStart; @@ -122,8 +119,6 @@ public function rangeAroundPage() return range($chunkStart, $chunkEnd); } - throw new Doctrine_Pager_Exception( - 'Cannot retrieve the range around the page of a not yet executed Pager query' - ); + throw new Doctrine_Pager_Exception('Cannot retrieve the range around the page of a not yet executed Pager query'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Parser.php b/lib/Doctrine/Parser.php index d9c8c124d..7313e8208 100644 --- a/lib/Doctrine/Parser.php +++ b/lib/Doctrine/Parser.php @@ -20,69 +20,70 @@ */ /** - * Doctrine_Parser + * Doctrine_Parser. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ abstract class Doctrine_Parser { /** - * loadData + * loadData. * * Override in the parser driver * * @param string $array - * @return void + * * @author Jonathan H. Wage */ abstract public function loadData($array, $charset = 'UTF-8'); /** - * dumpData + * dumpData. * * Override in the parser driver * * @param string $array * @param string $path * @param string $charset The charset of the data being dumped - * @return void + * * @author Jonathan H. Wage */ abstract public function dumpData($array, $path = null, $charset = null); /** - * getParser + * getParser. * * Get instance of the specified parser * * @param string $type - * @return void + * * @author Jonathan H. Wage */ - static public function getParser($type) + public static function getParser($type) { $class = 'Doctrine_Parser_'.ucfirst($type); - return new $class; + return new $class(); } /** - * load + * load. * * Interface for loading and parsing data from a file * * @param string $path * @param string $type - * @return void + * * @author Jonathan H. Wage */ - static public function load($path, $type = 'xml', $charset = 'UTF-8') + public static function load($path, $type = 'xml', $charset = 'UTF-8') { $parser = self::getParser($type); @@ -90,7 +91,7 @@ static public function load($path, $type = 'xml', $charset = 'UTF-8') } /** - * dump + * dump. * * Interface for pulling and dumping data to a file * @@ -98,10 +99,10 @@ static public function load($path, $type = 'xml', $charset = 'UTF-8') * @param string $path * @param string $type * @param string $charset The charset of the data being dumped - * @return void + * * @author Jonathan H. Wage */ - static public function dump($array, $type = 'xml', $path = null, $charset = null) + public static function dump($array, $type = 'xml', $path = null, $charset = null) { $parser = self::getParser($type); @@ -109,45 +110,43 @@ static public function dump($array, $type = 'xml', $path = null, $charset = null } /** - * doLoad + * doLoad. * * Get contents whether it is the path to a file file or a string of txt. * Either should allow php code in it. * * @param string $path - * @return void */ public function doLoad($path) { ob_start(); - if ( ! file_exists($path)) { + if (!file_exists($path)) { $contents = $path; - $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'dparser_' . microtime(); + $path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'dparser_'.microtime(); file_put_contents($path, $contents); } - include($path); + include $path; // Fix #1569. Need to check if it's still all valid - $contents = ob_get_clean(); //iconv("UTF-8", "UTF-8", ob_get_clean()); + $contents = ob_get_clean(); // iconv("UTF-8", "UTF-8", ob_get_clean()); return $contents; } /** - * doDump + * doDump. * * @param string $data * @param string $path - * @return void */ public function doDump($data, $path = null) { - if ($path !== null) { + if (null !== $path) { return file_put_contents($path, $data); - } else { - return $data; } + + return $data; } } diff --git a/lib/Doctrine/Parser/Exception.php b/lib/Doctrine/Parser/Exception.php index 6a6463834..c4cb3bf0b 100644 --- a/lib/Doctrine/Parser/Exception.php +++ b/lib/Doctrine/Parser/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Parser_Exception + * Doctrine_Parser_Exception. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Parser_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Parser/Json.php b/lib/Doctrine/Parser/Json.php index df4655de1..17adf27c6 100644 --- a/lib/Doctrine/Parser/Json.php +++ b/lib/Doctrine/Parser/Json.php @@ -20,28 +20,29 @@ */ /** - * Doctrine_Parser_Json + * Doctrine_Parser_Json. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Parser_Json extends Doctrine_Parser { /** - * dumpData + * dumpData. * * Dump an array of data to a specified path or return * - * @param string $array Array of data to dump to json - * @param string $path Path to dump json data to + * @param string $array Array of data to dump to json + * @param string $path Path to dump json data to * @param string $charset The charset of the data being dumped + * * @return string $json - * @return void */ public function dumpData($array, $path = null, $charset = null) { @@ -51,19 +52,18 @@ public function dumpData($array, $path = null, $charset = null) } /** - * loadData + * loadData. * * Load and unserialize data from a file or from passed data * - * @param string $path Path to dump data to - * @return array $json Array of json objects + * @param string $path Path to dump data to + * + * @return array $json Array of json objects */ public function loadData($path, $charset = 'UTF-8') { $contents = $this->doLoad($path); - $json = json_decode($contents); - - return $json; + return json_decode($contents); } } diff --git a/lib/Doctrine/Parser/Serialize.php b/lib/Doctrine/Parser/Serialize.php index e2eff7565..8fa2fa2f2 100644 --- a/lib/Doctrine/Parser/Serialize.php +++ b/lib/Doctrine/Parser/Serialize.php @@ -20,27 +20,27 @@ */ /** - * Doctrine_Parser_Serialize + * Doctrine_Parser_Serialize. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Parser_Serialize extends Doctrine_Parser { /** - * dumpData + * dumpData. * * Dump an array of data to a specified path or return * * @param string $array * @param string $path * @param string $charset The charset of the data being dumped - * @return void */ public function dumpData($array, $path = null, $charset = null) { @@ -50,12 +50,11 @@ public function dumpData($array, $path = null, $charset = null) } /** - * loadData + * loadData. * * Load and unserialize data from a file or from passed data * * @param string $path - * @return void */ public function loadData($path, $charset = 'UTF-8') { diff --git a/lib/Doctrine/Parser/Xml.php b/lib/Doctrine/Parser/Xml.php index 0f99699eb..a24ca2f93 100644 --- a/lib/Doctrine/Parser/Xml.php +++ b/lib/Doctrine/Parser/Xml.php @@ -20,28 +20,29 @@ */ /** - * Doctrine_Parser_Xml + * Doctrine_Parser_Xml. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage */ class Doctrine_Parser_Xml extends Doctrine_Parser { /** - * dumpData + * dumpData. * * Convert array to xml and dump to specified path or return the xml * - * @param string $array Array of data to convert to xml - * @param string $path Path to write xml data to + * @param string $array Array of data to convert to xml + * @param string $path Path to write xml data to * @param string $charset The charset of the data being dumped + * * @return string $xml - * @return void */ public function dumpData($array, $path = null, $charset = null) { @@ -51,24 +52,25 @@ public function dumpData($array, $path = null, $charset = null) } /** - * arrayToXml + * arrayToXml. + * + * @param string $array Array to convert to xml + * @param string $rootNodeName Name of the root node + * @param string $xml SimpleXmlElement + * @param mixed|null $charset * - * @param string $array Array to convert to xml - * @param string $rootNodeName Name of the root node - * @param string $xml SimpleXmlElement * @return string $asXml String of xml built from array */ public static function arrayToXml($array, $rootNodeName = 'data', $xml = null, $charset = null) { - if ($xml === null) { - $xml = new SimpleXmlElement("<$rootNodeName/>"); + if (null === $xml) { + $xml = new SimpleXMLElement("<{$rootNodeName}/>"); } - foreach($array as $key => $value) - { + foreach ($array as $key => $value) { $key = preg_replace('/[^a-z]/i', '', $key); - if (is_array($value) && ! empty($value)) { + if (is_array($value) && !empty($value)) { $node = $xml->addChild($key); foreach ($value as $k => $v) { @@ -79,11 +81,11 @@ public static function arrayToXml($array, $rootNodeName = 'data', $xml = null, $ } self::arrayToXml($value, $rootNodeName, $node, $charset); - } else if (is_int($key)) { + } elseif (is_int($key)) { $xml->addChild($value, 'true'); } else { $charset = $charset ? $charset : 'utf-8'; - if (strcasecmp($charset, 'utf-8') !== 0 && strcasecmp($charset, 'utf8') !== 0) { + if (0 !== strcasecmp($charset, 'utf-8') && 0 !== strcasecmp($charset, 'utf8')) { $value = iconv($charset, 'UTF-8', $value); } $value = htmlspecialchars((string) $value, ENT_COMPAT, 'UTF-8'); @@ -95,12 +97,13 @@ public static function arrayToXml($array, $rootNodeName = 'data', $xml = null, $ } /** - * loadData + * loadData. * * Load xml file and return array of data * - * @param string $path Path to load xml data from - * @return array $array Array of data converted from xml + * @param string $path Path to load xml data from + * + * @return array $array Array of data converted from xml */ public function loadData($path, $charset = 'UTF-8') { @@ -112,12 +115,13 @@ public function loadData($path, $charset = 'UTF-8') } /** - * prepareData + * prepareData. * * Prepare simple xml to array for return * - * @param string $simpleXml - * @return array $return + * @param string $simpleXml + * + * @return array $return */ public function prepareData($simpleXml) { @@ -133,10 +137,10 @@ public function prepareData($simpleXml) if (count($values) > 0) { $return[$element] = $this->prepareData($value); } else { - if ( ! isset($return[$element])) { + if (!isset($return[$element])) { $return[$element] = (string) $value; } else { - if ( ! is_array($return[$element])) { + if (!is_array($return[$element])) { $return[$element] = array($return[$element], (string) $value); } else { $return[$element][] = (string) $value; @@ -148,8 +152,8 @@ public function prepareData($simpleXml) if (is_array($return)) { return $return; - } else { - return array(); } + + return array(); } } diff --git a/lib/Doctrine/Parser/Yml.php b/lib/Doctrine/Parser/Yml.php index 9990be1db..c92ff43b8 100644 --- a/lib/Doctrine/Parser/Yml.php +++ b/lib/Doctrine/Parser/Yml.php @@ -20,72 +20,72 @@ */ /** - * Doctrine_Parser_Yml + * Doctrine_Parser_Yml. * - * @package Doctrine - * @subpackage Parser * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Jonathan H. Wage , Thomas Courbon */ class Doctrine_Parser_Yml extends Doctrine_Parser { /** - * dumpData + * dumpData. * * Dump an array of data to a specified path or return * - * @throws Doctrine_Parser_Exception dumping error - * @param string $array Array of data to dump to yaml - * @param string $path Path to dump the yaml to + * @param string $array Array of data to dump to yaml + * @param string $path Path to dump the yaml to + * @param mixed|null $charset + * * @return string $yaml - * @return void + * + * @throws Doctrine_Parser_Exception dumping error */ public function dumpData($array, $path = null, $charset = null) { - try { - $data = sfYaml::dump($array, 6); - - return $this->doDump($data, $path); + $data = sfYaml::dump($array, 6); - } catch(InvalidArgumentException $e) { - // rethrow the exceptions - $rethrowed_exception = new Doctrine_Parser_Exception($e->getMessage(), $e->getCode()); + return $this->doDump($data, $path); + } catch (InvalidArgumentException $e) { + // rethrow the exceptions + $rethrowed_exception = new Doctrine_Parser_Exception($e->getMessage(), $e->getCode()); - throw $rethrowed_exception; + throw $rethrowed_exception; } } /** - * loadData + * loadData. * * Load and parse data from a yml file * + * @param string $path Path to load yaml data from + * + * @return array $array Array of parsed yaml data + * * @throws Doctrine_Parser_Exception parsing error - * @param string $path Path to load yaml data from - * @return array $array Array of parsed yaml data */ public function loadData($path, $charset = 'UTF-8') { try { - /* - * I still use the doLoad method even if sfYaml can load yml from a file - * since this way Doctrine can handle file on it own. - */ - $contents = $this->doLoad($path); - - $array = sfYaml::load($contents, $charset); - - return $array; + /* + * I still use the doLoad method even if sfYaml can load yml from a file + * since this way Doctrine can handle file on it own. + */ + $contents = $this->doLoad($path); - } catch(InvalidArgumentException $e) { - // rethrow the exceptions - $rethrowed_exception = new Doctrine_Parser_Exception($e->getMessage(), $e->getCode()); + return sfYaml::load($contents, $charset); + } catch (InvalidArgumentException $e) { + // rethrow the exceptions + $rethrowed_exception = new Doctrine_Parser_Exception($e->getMessage(), $e->getCode()); - throw $rethrowed_exception; + throw $rethrowed_exception; } } } diff --git a/lib/Doctrine/Parser/sfYaml/sfYaml.php b/lib/Doctrine/Parser/sfYaml/sfYaml.php index 1d89ccc97..3d5adfc8a 100644 --- a/lib/Doctrine/Parser/sfYaml/sfYaml.php +++ b/lib/Doctrine/Parser/sfYaml/sfYaml.php @@ -11,117 +11,109 @@ /** * sfYaml offers convenience methods to load and dump YAML. * - * @package symfony - * @subpackage yaml * @author Fabien Potencier + * * @version SVN: $Id: sfYaml.class.php 8988 2008-05-15 20:24:26Z fabien $ */ class sfYaml { - static protected - $spec = '1.2'; - - /** - * Sets the YAML specification version to use. - * - * @param string $version The YAML specification version - */ - static public function setSpecVersion($version) - { - if (!in_array($version, array('1.1', '1.2'))) + protected static $spec = '1.2'; + + /** + * Sets the YAML specification version to use. + * + * @param string $version The YAML specification version + */ + public static function setSpecVersion($version) { - throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version)); + if (!in_array($version, array('1.1', '1.2'))) { + throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version)); + } + + self::$spec = $version; } - self::$spec = $version; - } - - /** - * Gets the YAML specification version to use. - * - * @return string The YAML specification version - */ - static public function getSpecVersion() - { - return self::$spec; - } - - /** - * Loads YAML into a PHP array. - * - * The load method, when supplied with a YAML stream (string or file), - * will do its best to convert YAML in a file into a PHP array. - * - * Usage: - * - * $array = sfYaml::load('config.yml'); - * print_r($array); - * - * - * @param string $input Path of YAML file or string containing YAML - * - * @return array The YAML converted to a PHP array - * - * @throws InvalidArgumentException If the YAML is not valid - */ - public static function load($input) - { - $file = ''; - - // if input is a file, process it - if (strpos($input, "\n") === false && is_file($input)) + /** + * Gets the YAML specification version to use. + * + * @return string The YAML specification version + */ + public static function getSpecVersion() { - $file = $input; - - ob_start(); - $retval = include($input); - $content = ob_get_clean(); - - // if an array is returned by the config file assume it's in plain php form else in YAML - $input = is_array($retval) ? $retval : $content; + return self::$spec; } - // if an array is returned by the config file assume it's in plain php form else in YAML - if (is_array($input)) + /** + * Loads YAML into a PHP array. + * + * The load method, when supplied with a YAML stream (string or file), + * will do its best to convert YAML in a file into a PHP array. + * + * Usage: + * + * $array = sfYaml::load('config.yml'); + * print_r($array); + * + * + * @param string $input Path of YAML file or string containing YAML + * + * @return array The YAML converted to a PHP array + * + * @throws InvalidArgumentException If the YAML is not valid + */ + public static function load($input) { - return $input; - } + $file = ''; - require_once dirname(__FILE__).'/sfYamlParser.php'; + // if input is a file, process it + if (false === strpos($input, "\n") && is_file($input)) { + $file = $input; - $yaml = new sfYamlParser(); + ob_start(); + $retval = include $input; + $content = ob_get_clean(); - try - { - $ret = $yaml->parse($input); + // if an array is returned by the config file assume it's in plain php form else in YAML + $input = is_array($retval) ? $retval : $content; + } + + // if an array is returned by the config file assume it's in plain php form else in YAML + if (is_array($input)) { + return $input; + } + + require_once dirname(__FILE__).'/sfYamlParser.php'; + + $yaml = new sfYamlParser(); + + try { + $ret = $yaml->parse($input); + } catch (Exception $e) { + throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); + } + + return $ret; } - catch (Exception $e) + + /** + * Dumps a PHP array to a YAML string. + * + * The dump method, when supplied with an array, will do its best + * to convert the array into friendly YAML. + * + * @param array $array PHP array + * @param int $inline The level where you switch to inline YAML + * + * @return string A YAML string representing the original PHP array + */ + public static function dump($array, $inline = 2) { - throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); - } + require_once dirname(__FILE__).'/sfYamlDumper.php'; + + $yaml = new sfYamlDumper(); - return $ret; - } - - /** - * Dumps a PHP array to a YAML string. - * - * The dump method, when supplied with an array, will do its best - * to convert the array into friendly YAML. - * - * @param array $array PHP array - * @param integer $inline The level where you switch to inline YAML - * - * @return string A YAML string representing the original PHP array - */ - public static function dump($array, $inline = 2) - { - require_once dirname(__FILE__).'/sfYamlDumper.php'; - - $yaml = new sfYamlDumper(); - - return $yaml->dump($array, $inline); - } + return $yaml->dump($array, $inline); + } } /** @@ -131,5 +123,5 @@ public static function dump($array, $inline = 2) */ function echoln($string) { - echo $string."\n"; + echo $string."\n"; } diff --git a/lib/Doctrine/Parser/sfYaml/sfYamlDumper.php b/lib/Doctrine/Parser/sfYaml/sfYamlDumper.php index 0ada2b37d..2eda33904 100644 --- a/lib/Doctrine/Parser/sfYaml/sfYamlDumper.php +++ b/lib/Doctrine/Parser/sfYaml/sfYamlDumper.php @@ -8,53 +8,48 @@ * file that was distributed with this source code. */ -require_once(dirname(__FILE__).'/sfYamlInline.php'); +require_once dirname(__FILE__).'/sfYamlInline.php'; /** * sfYamlDumper dumps PHP variables to YAML strings. * - * @package symfony - * @subpackage yaml * @author Fabien Potencier + * * @version SVN: $Id: sfYamlDumper.class.php 10575 2008-08-01 13:08:42Z nicolas $ */ class sfYamlDumper { - /** - * Dumps a PHP value to YAML. - * - * @param mixed $input The PHP value - * @param integer $inline The level where you switch to inline YAML - * @param integer $indent The level o indentation indentation (used internally) - * - * @return string The YAML representation of the PHP value - */ - public function dump($input, $inline = 0, $indent = 0) - { - $output = ''; - $prefix = $indent ? str_repeat(' ', $indent) : ''; - - if ($inline <= 0 || !is_array($input) || empty($input)) - { - $output .= $prefix.sfYamlInline::dump($input); - } - else + /** + * Dumps a PHP value to YAML. + * + * @param mixed $input The PHP value + * @param int $inline The level where you switch to inline YAML + * @param int $indent The level o indentation indentation (used internally) + * + * @return string The YAML representation of the PHP value + */ + public function dump($input, $inline = 0, $indent = 0) { - $isAHash = array_keys($input) !== range(0, count($input) - 1); + $output = ''; + $prefix = $indent ? str_repeat(' ', $indent) : ''; - foreach ($input as $key => $value) - { - $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); + if ($inline <= 0 || !is_array($input) || empty($input)) { + $output .= $prefix.sfYamlInline::dump($input); + } else { + $isAHash = array_keys($input) !== range(0, count($input) - 1); - $output .= sprintf('%s%s%s%s', - $prefix, - $isAHash ? sfYamlInline::dump($key).':' : '-', - $willBeInlined ? ' ' : "\n", - $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 2) - ).($willBeInlined ? "\n" : ''); - } - } + foreach ($input as $key => $value) { + $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); + + $output .= sprintf('%s%s%s%s', + $prefix, + $isAHash ? sfYamlInline::dump($key).':' : '-', + $willBeInlined ? ' ' : "\n", + $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 2) + ).($willBeInlined ? "\n" : ''); + } + } - return $output; - } + return $output; + } } diff --git a/lib/Doctrine/Parser/sfYaml/sfYamlInline.php b/lib/Doctrine/Parser/sfYaml/sfYamlInline.php index 77096e43f..8919f6d62 100644 --- a/lib/Doctrine/Parser/sfYaml/sfYamlInline.php +++ b/lib/Doctrine/Parser/sfYaml/sfYamlInline.php @@ -13,418 +13,377 @@ /** * sfYamlInline implements a YAML parser/dumper for the YAML inline syntax. * - * @package symfony - * @subpackage yaml * @author Fabien Potencier + * * @version SVN: $Id: sfYamlInline.class.php 16177 2009-03-11 08:32:48Z fabien $ */ class sfYamlInline { - const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')'; - - /** - * Convert a YAML string to a PHP array. - * - * @param string $value A YAML string - * - * @return array A PHP array representing the YAML string - */ - static public function load($value) - { - $value = trim($value); - - if (0 == strlen($value)) - { - return ''; - } - - if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) + public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')'; + + /** + * Convert a YAML string to a PHP array. + * + * @param string $value A YAML string + * + * @return array A PHP array representing the YAML string + */ + public static function load($value) { - $mbEncoding = mb_internal_encoding(); - mb_internal_encoding('ASCII'); - } + $value = trim($value); - switch ($value[0]) - { - case '[': - $result = self::parseSequence($value); - break; - case '{': - $result = self::parseMapping($value); - break; - default: - $result = self::parseScalar($value); - } + if (0 == strlen($value)) { + return ''; + } - if (isset($mbEncoding)) - { - mb_internal_encoding($mbEncoding); - } + if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { + $mbEncoding = mb_internal_encoding(); + mb_internal_encoding('ASCII'); + } - return $result; - } - - /** - * Dumps a given PHP variable to a YAML string. - * - * @param mixed $value The PHP variable to convert - * - * @return string The YAML string representing the PHP array - */ - static public function dump($value) - { - if ('1.1' === sfYaml::getSpecVersion()) - { - $trueValues = array('true', 'on', '+', 'yes', 'y'); - $falseValues = array('false', 'off', '-', 'no', 'n'); - } - else - { - $trueValues = array('true'); - $falseValues = array('false'); - } + switch ($value[0]) { + case '[': + $result = self::parseSequence($value); + break; + case '{': + $result = self::parseMapping($value); + break; + default: + $result = self::parseScalar($value); + } - switch (true) - { - case is_resource($value): - throw new InvalidArgumentException('Unable to dump PHP resources in a YAML file.'); - case is_object($value): - return '!!php/object:'.serialize($value); - case is_array($value): - return self::dumpArray($value); - case null === $value: - return 'null'; - case true === $value: - return 'true'; - case false === $value: - return 'false'; - case (is_string($value) && ctype_digit($value)): - return "'$value'"; - case is_numeric($value) && false === strpbrk($value, "\f\n\r\t\v"): - return is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'$value'" : $value); - case false !== strpos($value, "\n") || false !== strpos($value, "\r"): - return sprintf('"%s"', str_replace(array('"', "\n", "\r"), array('\\"', '\n', '\r'), $value)); - case preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ - ? | < > = ! % @ ` ]/x', $value): - return sprintf("'%s'", str_replace('\'', '\'\'', $value)); - case '' == $value: - return "''"; - case preg_match(self::getTimestampRegex(), $value): - return "'$value'"; - case in_array(strtolower($value), $trueValues): - return "'$value'"; - case in_array(strtolower($value), $falseValues): - return "'$value'"; - case in_array(strtolower($value), array('null', '~')): - return "'$value'"; - default: - return $value; - } - } - - /** - * Dumps a PHP array to a YAML string. - * - * @param array $value The PHP array to dump - * - * @return string The YAML string representing the PHP array - */ - static protected function dumpArray($value) - { - // array - $keys = array_keys($value); - if ( - (1 == count($keys) && '0' == $keys[0]) - || - (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int)($v + $w);}, 0) == count($keys) * (count($keys) - 1) / 2)) - { - $output = array(); - foreach ($value as $val) - { - $output[] = self::dump($val); - } + if (isset($mbEncoding)) { + mb_internal_encoding($mbEncoding); + } - return sprintf('[%s]', implode(', ', $output)); + return $result; } - // mapping - $output = array(); - foreach ($value as $key => $val) + /** + * Dumps a given PHP variable to a YAML string. + * + * @param mixed $value The PHP variable to convert + * + * @return string The YAML string representing the PHP array + */ + public static function dump($value) { - $output[] = sprintf('%s: %s', self::dump($key), self::dump($val)); - } + if ('1.1' === sfYaml::getSpecVersion()) { + $trueValues = array('true', 'on', '+', 'yes', 'y'); + $falseValues = array('false', 'off', '-', 'no', 'n'); + } else { + $trueValues = array('true'); + $falseValues = array('false'); + } - return sprintf('{ %s }', implode(', ', $output)); - } - - /** - * Parses a scalar to a YAML string. - * - * @param scalar $scalar - * @param string $delimiters - * @param array $stringDelimiter - * @param integer $i - * @param boolean $evaluate - * - * @return string A YAML string - */ - static public function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true) - { - if (in_array($scalar[$i], $stringDelimiters)) - { - // quoted scalar - $output = self::parseQuotedScalar($scalar, $i); - } - else - { - // "normal" string - if (!$delimiters) - { - $output = substr($scalar, $i); - $i += strlen($output); - - // remove comments - if (false !== $strpos = strpos($output, ' #')) - { - $output = rtrim(substr($output, 0, $strpos)); + switch (true) { + case is_resource($value): + throw new InvalidArgumentException('Unable to dump PHP resources in a YAML file.'); + case is_object($value): + return '!!php/object:'.serialize($value); + case is_array($value): + return self::dumpArray($value); + case null === $value: + return 'null'; + case true === $value: + return 'true'; + case false === $value: + return 'false'; + case is_string($value) && ctype_digit($value): + return "'{$value}'"; + case is_numeric($value) && false === strpbrk($value, "\f\n\r\t\v"): + return is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'{$value}'" : $value); + case false !== strpos($value, "\n") || false !== strpos($value, "\r"): + return sprintf('"%s"', str_replace(array('"', "\n", "\r"), array('\\"', '\n', '\r'), $value)); + case preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ - ? | < > = ! % @ ` ]/x', $value): + return sprintf("'%s'", str_replace('\'', '\'\'', $value)); + case '' == $value: + return "''"; + case preg_match(self::getTimestampRegex(), $value): + return "'{$value}'"; + case in_array(strtolower($value), $trueValues): + return "'{$value}'"; + case in_array(strtolower($value), $falseValues): + return "'{$value}'"; + case in_array(strtolower($value), array('null', '~')): + return "'{$value}'"; + default: + return $value; } - } - else if (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) - { - $output = $match[1]; - $i += strlen($output); - } - else - { - throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', $scalar)); - } - - $output = $evaluate ? self::evaluateScalar($output) : $output; } - return $output; - } - - /** - * Parses a quoted scalar to YAML. - * - * @param string $scalar - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseQuotedScalar($scalar, &$i) - { - if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) + /** + * Dumps a PHP array to a YAML string. + * + * @param array $value The PHP array to dump + * + * @return string The YAML string representing the PHP array + */ + protected static function dumpArray($value) { - throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i))); - } + // array + $keys = array_keys($value); + if ( + (1 == count($keys) && '0' == $keys[0]) + || (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int) ($v + $w); }, 0) == count($keys) * (count($keys) - 1) / 2)) { + $output = array(); + foreach ($value as $val) { + $output[] = self::dump($val); + } - $output = substr($match[0], 1, strlen($match[0]) - 2); + return sprintf('[%s]', implode(', ', $output)); + } - if ('"' == $scalar[$i]) - { - // evaluate the string - $output = str_replace(array('\\"', '\\n', '\\r'), array('"', "\n", "\r"), $output); - } - else - { - // unescape ' - $output = str_replace('\'\'', '\'', $output); + // mapping + $output = array(); + foreach ($value as $key => $val) { + $output[] = sprintf('%s: %s', self::dump($key), self::dump($val)); + } + + return sprintf('{ %s }', implode(', ', $output)); } - $i += strlen($match[0]); - - return $output; - } - - /** - * Parses a sequence to a YAML string. - * - * @param string $sequence - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseSequence($sequence, &$i = 0) - { - $output = array(); - $len = strlen($sequence); - $i += 1; - - // [foo, bar, ...] - while ($i < $len) + /** + * Parses a scalar to a YAML string. + * + * @param scalar $scalar + * @param string $delimiters + * @param int $i + * @param bool $evaluate + * + * @return string A YAML string + */ + public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true) { - switch ($sequence[$i]) - { - case '[': - // nested sequence - $output[] = self::parseSequence($sequence, $i); - break; - case '{': - // nested mapping - $output[] = self::parseMapping($sequence, $i); - break; - case ']': - return $output; - case ',': - case ' ': - break; - default: - $isQuoted = in_array($sequence[$i], array('"', "'")); - $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i); - - if (!$isQuoted && false !== strpos($value, ': ')) - { - // embedded mapping? - try - { - $value = self::parseMapping('{'.$value.'}'); + if (in_array($scalar[$i], $stringDelimiters)) { + // quoted scalar + $output = self::parseQuotedScalar($scalar, $i); + } else { + // "normal" string + if (!$delimiters) { + $output = substr($scalar, $i); + $i += strlen($output); + + // remove comments + if (false !== $strpos = strpos($output, ' #')) { + $output = rtrim(substr($output, 0, $strpos)); + } + } elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) { + $output = $match[1]; + $i += strlen($output); + } else { + throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', $scalar)); } - catch (InvalidArgumentException $e) - { - // no, it's not - } - } - - $output[] = $value; - --$i; - } + $output = $evaluate ? self::evaluateScalar($output) : $output; + } - ++$i; + return $output; } - throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $sequence)); - } - - /** - * Parses a mapping to a YAML string. - * - * @param string $mapping - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseMapping($mapping, &$i = 0) - { - $output = array(); - $len = strlen($mapping); - $i += 1; - - // {foo: bar, bar:foo, ...} - while ($i < $len) + /** + * Parses a quoted scalar to YAML. + * + * @param string $scalar + * @param int $i + * + * @return string A YAML string + */ + protected static function parseQuotedScalar($scalar, &$i) { - switch ($mapping[$i]) - { - case ' ': - case ',': - ++$i; - continue 2; - case '}': - return $output; - } - - // key - $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); - - // value - $done = false; - while ($i < $len) - { - switch ($mapping[$i]) - { - case '[': - // nested sequence - $output[$key] = self::parseSequence($mapping, $i); - $done = true; - break; - case '{': - // nested mapping - $output[$key] = self::parseMapping($mapping, $i); - $done = true; - break; - case ':': - case ' ': - break; - default: - $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i); - $done = true; - --$i; + if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { + throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i))); } - ++$i; + $output = substr($match[0], 1, strlen($match[0]) - 2); - if ($done) - { - continue 2; + if ('"' == $scalar[$i]) { + // evaluate the string + $output = str_replace(array('\\"', '\\n', '\\r'), array('"', "\n", "\r"), $output); + } else { + // unescape ' + $output = str_replace('\'\'', '\'', $output); } - } + + $i += strlen($match[0]); + + return $output; } - throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $mapping)); - } - - /** - * Evaluates scalars and replaces magic values. - * - * @param string $scalar - * - * @return string A YAML string - */ - static protected function evaluateScalar($scalar) - { - $scalar = trim($scalar); - - if ('1.1' === sfYaml::getSpecVersion()) + /** + * Parses a sequence to a YAML string. + * + * @param string $sequence + * @param int $i + * + * @return string A YAML string + */ + protected static function parseSequence($sequence, &$i = 0) { - $trueValues = array('true', 'on', '+', 'yes', 'y'); - $falseValues = array('false', 'off', '-', 'no', 'n'); + $output = array(); + $len = strlen($sequence); + ++$i; + + // [foo, bar, ...] + while ($i < $len) { + switch ($sequence[$i]) { + case '[': + // nested sequence + $output[] = self::parseSequence($sequence, $i); + break; + case '{': + // nested mapping + $output[] = self::parseMapping($sequence, $i); + break; + case ']': + return $output; + case ',': + case ' ': + break; + default: + $isQuoted = in_array($sequence[$i], array('"', "'")); + $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i); + + if (!$isQuoted && false !== strpos($value, ': ')) { + // embedded mapping? + try { + $value = self::parseMapping('{'.$value.'}'); + } catch (InvalidArgumentException $e) { + // no, it's not + } + } + + $output[] = $value; + + --$i; + } + + ++$i; + } + + throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $sequence)); } - else + + /** + * Parses a mapping to a YAML string. + * + * @param string $mapping + * @param int $i + * + * @return string A YAML string + */ + protected static function parseMapping($mapping, &$i = 0) { - $trueValues = array('true'); - $falseValues = array('false'); + $output = array(); + $len = strlen($mapping); + ++$i; + + // {foo: bar, bar:foo, ...} + while ($i < $len) { + switch ($mapping[$i]) { + case ' ': + case ',': + ++$i; + continue 2; + case '}': + return $output; + } + + // key + $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); + + // value + $done = false; + while ($i < $len) { + switch ($mapping[$i]) { + case '[': + // nested sequence + $output[$key] = self::parseSequence($mapping, $i); + $done = true; + break; + case '{': + // nested mapping + $output[$key] = self::parseMapping($mapping, $i); + $done = true; + break; + case ':': + case ' ': + break; + default: + $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i); + $done = true; + --$i; + } + + ++$i; + + if ($done) { + continue 2; + } + } + } + + throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $mapping)); } - switch (true) + /** + * Evaluates scalars and replaces magic values. + * + * @param string $scalar + * + * @return string A YAML string + */ + protected static function evaluateScalar($scalar) { - case 'null' == strtolower($scalar): - case '' == $scalar: - case '~' == $scalar: - return null; - case 0 === strpos($scalar, '!str'): - return (string) substr($scalar, 5); - case 0 === strpos($scalar, '! '): - return intval(self::parseScalar(substr($scalar, 2))); - case 0 === strpos($scalar, '!!php/object:'): - return unserialize(substr($scalar, 13)); - case ctype_digit($scalar): - $raw = $scalar; - $cast = intval($scalar); - return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); - case in_array(strtolower($scalar), $trueValues): - return true; - case in_array(strtolower($scalar), $falseValues): - return false; - case is_numeric($scalar): - return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar); - case 0 == strcasecmp($scalar, '.inf'): - case 0 == strcasecmp($scalar, '.NaN'): - return -log(0); - case 0 == strcasecmp($scalar, '-.inf'): - return log(0); - case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): - return floatval(str_replace(',', '', $scalar)); - case preg_match(self::getTimestampRegex(), $scalar): - return strtotime($scalar); - default: - return (string) $scalar; + $scalar = trim($scalar); + + if ('1.1' === sfYaml::getSpecVersion()) { + $trueValues = array('true', 'on', '+', 'yes', 'y'); + $falseValues = array('false', 'off', '-', 'no', 'n'); + } else { + $trueValues = array('true'); + $falseValues = array('false'); + } + + switch (true) { + case 'null' == strtolower($scalar): + case '' == $scalar: + case '~' == $scalar: + return null; + case 0 === strpos($scalar, '!str'): + return (string) substr($scalar, 5); + case 0 === strpos($scalar, '! '): + return intval(self::parseScalar(substr($scalar, 2))); + case 0 === strpos($scalar, '!!php/object:'): + return unserialize(substr($scalar, 13)); + case ctype_digit($scalar): + $raw = $scalar; + $cast = intval($scalar); + + return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); + case in_array(strtolower($scalar), $trueValues): + return true; + case in_array(strtolower($scalar), $falseValues): + return false; + case is_numeric($scalar): + return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar); + case 0 == strcasecmp($scalar, '.inf'): + case 0 == strcasecmp($scalar, '.NaN'): + return -log(0); + case 0 == strcasecmp($scalar, '-.inf'): + return log(0); + case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): + return floatval(str_replace(',', '', $scalar)); + case preg_match(self::getTimestampRegex(), $scalar): + return strtotime($scalar); + default: + return (string) $scalar; + } } - } - static protected function getTimestampRegex() - { - return <<[0-9][0-9][0-9][0-9]) -(?P[0-9][0-9]?) @@ -433,10 +392,10 @@ static protected function getTimestampRegex() (?P[0-9][0-9]?) :(?P[0-9][0-9]) :(?P[0-9][0-9]) - (?:\.(?P[0-9]*))? + (?:\\.(?P[0-9]*))? (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) (?::(?P[0-9][0-9]))?))?)? $~x EOF; - } + } } diff --git a/lib/Doctrine/Parser/sfYaml/sfYamlParser.php b/lib/Doctrine/Parser/sfYaml/sfYamlParser.php index 91da2dcb1..a05354fba 100644 --- a/lib/Doctrine/Parser/sfYaml/sfYamlParser.php +++ b/lib/Doctrine/Parser/sfYaml/sfYamlParser.php @@ -8,615 +8,522 @@ * file that was distributed with this source code. */ -require_once(dirname(__FILE__).'/sfYamlInline.php'); +require_once dirname(__FILE__).'/sfYamlInline.php'; -if (!defined('PREG_BAD_UTF8_OFFSET_ERROR')) -{ - define('PREG_BAD_UTF8_OFFSET_ERROR', 5); +if (!defined('PREG_BAD_UTF8_OFFSET_ERROR')) { + define('PREG_BAD_UTF8_OFFSET_ERROR', 5); } /** * sfYamlParser parses YAML strings to convert them to PHP arrays. * - * @package symfony - * @subpackage yaml * @author Fabien Potencier + * * @version SVN: $Id: sfYamlParser.class.php 10832 2008-08-13 07:46:08Z fabien $ */ class sfYamlParser { - protected - $offset = 0, - $lines = array(), - $currentLineNb = -1, - $currentLine = '', - $refs = array(); - - /** - * Constructor - * - * @param integer $offset The offset of YAML document (used for line numbers in error messages) - */ - public function __construct($offset = 0) - { - $this->offset = $offset; - } - - /** - * Parses a YAML string to a PHP value. - * - * @param string $value A YAML string - * - * @return mixed A PHP value - * - * @throws InvalidArgumentException If the YAML is not valid - */ - public function parse($value) - { - $this->currentLineNb = -1; - $this->currentLine = ''; - $this->lines = explode("\n", $this->cleanup($value)); - - if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) + protected $offset = 0; + protected $lines = array(); + protected $currentLineNb = -1; + protected $currentLine = ''; + protected $refs = array(); + + /** + * Constructor. + * + * @param int $offset The offset of YAML document (used for line numbers in error messages) + */ + public function __construct($offset = 0) { - $mbEncoding = mb_internal_encoding(); - mb_internal_encoding('UTF-8'); + $this->offset = $offset; } - $data = array(); - while ($this->moveToNextLine()) + /** + * Parses a YAML string to a PHP value. + * + * @param string $value A YAML string + * + * @return mixed A PHP value + * + * @throws InvalidArgumentException If the YAML is not valid + */ + public function parse($value) { - if ($this->isCurrentLineEmpty()) - { - continue; - } - - // tab? - if (preg_match('#^\t+#', $this->currentLine)) - { - throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - - $isRef = $isInPlace = $isProcessed = false; - if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#u', $this->currentLine, $values)) - { - if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) - { - $isRef = $matches['ref']; - $values['value'] = $matches['value']; - } + $this->currentLineNb = -1; + $this->currentLine = ''; + $this->lines = explode("\n", $this->cleanup($value)); - // array - if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) - { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $data[] = $parser->parse($this->getNextEmbedBlock()); + if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { + $mbEncoding = mb_internal_encoding(); + mb_internal_encoding('UTF-8'); } - else - { - if (isset($values['leadspaces']) - && ' ' == $values['leadspaces'] - && preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"\{].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches)) - { - // this is a compact notation element, add to next block and parse - $c = $this->getRealCurrentLineNb(); - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - - $block = $values['value']; - if (!$this->isNextLineIndented()) - { - $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); - } - $data[] = $parser->parse($block); - } - else - { - $data[] = $this->parseValue($values['value']); - } - } - } - else if (preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values)) - { - $key = sfYamlInline::parseScalar($values['key']); - - if ('<<' === $key) - { - if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) - { - $isInPlace = substr($values['value'], 1); - if (!array_key_exists($isInPlace, $this->refs)) - { - throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - } - else - { - if (isset($values['value']) && $values['value'] !== '') - { - $value = $values['value']; - } - else - { - $value = $this->getNextEmbedBlock(); + $data = array(); + while ($this->moveToNextLine()) { + if ($this->isCurrentLineEmpty()) { + continue; } - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $parsed = $parser->parse($value); - - $merged = array(); - if (!is_array($parsed)) - { - throw new InvalidArgumentException(sprintf("YAML merge keys used with a scalar value instead of an array at line %s (%s)", $this->getRealCurrentLineNb() + 1, $this->currentLine)); + + // tab? + if (preg_match('#^\t+#', $this->currentLine)) { + throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); } - else if (isset($parsed[0])) - { - // Numeric array, merge individual elements - foreach (array_reverse($parsed) as $parsedItem) - { - if (!is_array($parsedItem)) - { - throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem)); + + $isRef = $isInPlace = $isProcessed = false; + if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#u', $this->currentLine, $values)) { + if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { + $isRef = $matches['ref']; + $values['value'] = $matches['value']; } - $merged = array_merge($parsedItem, $merged); - } - } - else - { - // Associative array, merge - $merged = array_merge($merge, $parsed); - } - $isProcessed = $merged; - } - } - else if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) - { - $isRef = $matches['ref']; - $values['value'] = $matches['value']; - } + // array + if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { + $c = $this->getRealCurrentLineNb() + 1; + $parser = new sfYamlParser($c); + $parser->refs = &$this->refs; + $data[] = $parser->parse($this->getNextEmbedBlock()); + } else { + if (isset($values['leadspaces']) + && ' ' == $values['leadspaces'] + && preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"\{].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches)) { + // this is a compact notation element, add to next block and parse + $c = $this->getRealCurrentLineNb(); + $parser = new sfYamlParser($c); + $parser->refs = &$this->refs; + + $block = $values['value']; + if (!$this->isNextLineIndented()) { + $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); + } + + $data[] = $parser->parse($block); + } else { + $data[] = $this->parseValue($values['value']); + } + } + } elseif (preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values)) { + $key = sfYamlInline::parseScalar($values['key']); + + if ('<<' === $key) { + if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) { + $isInPlace = substr($values['value'], 1); + if (!array_key_exists($isInPlace, $this->refs)) { + throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } + } else { + if (isset($values['value']) && '' !== $values['value']) { + $value = $values['value']; + } else { + $value = $this->getNextEmbedBlock(); + } + $c = $this->getRealCurrentLineNb() + 1; + $parser = new sfYamlParser($c); + $parser->refs = &$this->refs; + $parsed = $parser->parse($value); + + $merged = array(); + if (!is_array($parsed)) { + throw new InvalidArgumentException(sprintf('YAML merge keys used with a scalar value instead of an array at line %s (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } + if (isset($parsed[0])) { + // Numeric array, merge individual elements + foreach (array_reverse($parsed) as $parsedItem) { + if (!is_array($parsedItem)) { + throw new InvalidArgumentException(sprintf('Merge items must be arrays at line %s (%s).', $this->getRealCurrentLineNb() + 1, $parsedItem)); + } + $merged = array_merge($parsedItem, $merged); + } + } else { + // Associative array, merge + $merged = array_merge($merge, $parsed); + } + + $isProcessed = $merged; + } + } elseif (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { + $isRef = $matches['ref']; + $values['value'] = $matches['value']; + } - if ($isProcessed) - { - // Merge keys - $data = $isProcessed; - } - // hash - else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) - { - // if next line is less indented or equal, then it means that the current value is null - if ($this->isNextLineIndented()) - { - $data[$key] = null; - } - else - { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $data[$key] = $parser->parse($this->getNextEmbedBlock()); - } - } - else - { - if ($isInPlace) - { - $data = $this->refs[$isInPlace]; - } - else - { - $data[$key] = $this->parseValue($values['value']); - } - } - } - else - { - // 1-liner followed by newline - if (2 == count($this->lines) && empty($this->lines[1])) - { - $value = sfYamlInline::load($this->lines[0]); - if (is_array($value)) - { - $first = reset($value); - if ('*' === substr($first, 0, 1)) - { - $data = array(); - foreach ($value as $alias) - { - $data[] = $this->refs[substr($alias, 1)]; - } - $value = $data; - } - } + if ($isProcessed) { + // Merge keys + $data = $isProcessed; + } + // hash + elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { + // if next line is less indented or equal, then it means that the current value is null + if ($this->isNextLineIndented()) { + $data[$key] = null; + } else { + $c = $this->getRealCurrentLineNb() + 1; + $parser = new sfYamlParser($c); + $parser->refs = &$this->refs; + $data[$key] = $parser->parse($this->getNextEmbedBlock()); + } + } else { + if ($isInPlace) { + $data = $this->refs[$isInPlace]; + } else { + $data[$key] = $this->parseValue($values['value']); + } + } + } else { + // 1-liner followed by newline + if (2 == count($this->lines) && empty($this->lines[1])) { + $value = sfYamlInline::load($this->lines[0]); + if (is_array($value)) { + $first = reset($value); + if ('*' === substr($first, 0, 1)) { + $data = array(); + foreach ($value as $alias) { + $data[] = $this->refs[substr($alias, 1)]; + } + $value = $data; + } + } + + if (isset($mbEncoding)) { + mb_internal_encoding($mbEncoding); + } + + return $value; + } - if (isset($mbEncoding)) - { - mb_internal_encoding($mbEncoding); - } + switch (preg_last_error()) { + case PREG_INTERNAL_ERROR: + $error = 'Internal PCRE error on line'; + break; + case PREG_BACKTRACK_LIMIT_ERROR: + $error = 'pcre.backtrack_limit reached on line'; + break; + case PREG_RECURSION_LIMIT_ERROR: + $error = 'pcre.recursion_limit reached on line'; + break; + case PREG_BAD_UTF8_ERROR: + $error = 'Malformed UTF-8 data on line'; + break; + case PREG_BAD_UTF8_OFFSET_ERROR: + $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line'; + break; + default: + $error = 'Unable to parse line'; + } - return $value; - } + throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } - switch (preg_last_error()) - { - case PREG_INTERNAL_ERROR: - $error = 'Internal PCRE error on line'; - break; - case PREG_BACKTRACK_LIMIT_ERROR: - $error = 'pcre.backtrack_limit reached on line'; - break; - case PREG_RECURSION_LIMIT_ERROR: - $error = 'pcre.recursion_limit reached on line'; - break; - case PREG_BAD_UTF8_ERROR: - $error = 'Malformed UTF-8 data on line'; - break; - case PREG_BAD_UTF8_OFFSET_ERROR: - $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line'; - break; - default: - $error = 'Unable to parse line'; + if ($isRef) { + $this->refs[$isRef] = end($data); + } } - throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } + if (isset($mbEncoding)) { + mb_internal_encoding($mbEncoding); + } - if ($isRef) - { - $this->refs[$isRef] = end($data); - } + return empty($data) ? null : $data; } - if (isset($mbEncoding)) + /** + * Returns the current line number (takes the offset into account). + * + * @return int The current line number + */ + protected function getRealCurrentLineNb() { - mb_internal_encoding($mbEncoding); + return $this->currentLineNb + $this->offset; } - return empty($data) ? null : $data; - } - - /** - * Returns the current line number (takes the offset into account). - * - * @return integer The current line number - */ - protected function getRealCurrentLineNb() - { - return $this->currentLineNb + $this->offset; - } - - /** - * Returns the current line indentation. - * - * @return integer The current line indentation - */ - protected function getCurrentLineIndentation() - { - return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); - } - - /** - * Returns the next embed block of YAML. - * - * @param integer $indentation The indent level at which the block is to be read, or null for default - * - * @return string A YAML string - */ - protected function getNextEmbedBlock($indentation = null) - { - $this->moveToNextLine(); - - if (null === $indentation) + /** + * Returns the current line indentation. + * + * @return int The current line indentation + */ + protected function getCurrentLineIndentation() { - $newIndent = $this->getCurrentLineIndentation(); - - if (!$this->isCurrentLineEmpty() && 0 == $newIndent) - { - throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } + return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); } - else + + /** + * Returns the next embed block of YAML. + * + * @param int $indentation The indent level at which the block is to be read, or null for default + * + * @return string A YAML string + */ + protected function getNextEmbedBlock($indentation = null) { - $newIndent = $indentation; - } + $this->moveToNextLine(); - $data = array(substr($this->currentLine, $newIndent)); + if (null === $indentation) { + $newIndent = $this->getCurrentLineIndentation(); - while ($this->moveToNextLine()) - { - if ($this->isCurrentLineEmpty()) - { - if ($this->isCurrentLineBlank()) - { - $data[] = substr($this->currentLine, $newIndent); + if (!$this->isCurrentLineEmpty() && 0 == $newIndent) { + throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } + } else { + $newIndent = $indentation; } - continue; - } - - $indent = $this->getCurrentLineIndentation(); - - if (preg_match('#^(?P *)$#', $this->currentLine, $match)) - { - // empty line - $data[] = $match['text']; - } - else if ($indent >= $newIndent) - { - $data[] = substr($this->currentLine, $newIndent); - } - else if (0 == $indent) - { - $this->moveToPreviousLine(); + $data = array(substr($this->currentLine, $newIndent)); - break; - } - else - { - throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - } + while ($this->moveToNextLine()) { + if ($this->isCurrentLineEmpty()) { + if ($this->isCurrentLineBlank()) { + $data[] = substr($this->currentLine, $newIndent); + } - return implode("\n", $data); - } + continue; + } - /** - * Moves the parser to the next line. - */ - protected function moveToNextLine() - { - if ($this->currentLineNb >= count($this->lines) - 1) - { - return false; - } + $indent = $this->getCurrentLineIndentation(); - $this->currentLine = $this->lines[++$this->currentLineNb]; - - return true; - } - - /** - * Moves the parser to the previous line. - */ - protected function moveToPreviousLine() - { - $this->currentLine = $this->lines[--$this->currentLineNb]; - } - - /** - * Parses a YAML value. - * - * @param string $value A YAML value - * - * @return mixed A PHP value - */ - protected function parseValue($value) - { - if ('*' === substr($value, 0, 1)) - { - if (false !== $pos = strpos($value, '#')) - { - $value = substr($value, 1, $pos - 2); - } - else - { - $value = substr($value, 1); - } - - if (!array_key_exists($value, $this->refs)) - { - throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine)); - } - return $this->refs[$value]; - } + if (preg_match('#^(?P *)$#', $this->currentLine, $match)) { + // empty line + $data[] = $match['text']; + } elseif ($indent >= $newIndent) { + $data[] = substr($this->currentLine, $newIndent); + } elseif (0 == $indent) { + $this->moveToPreviousLine(); - if (preg_match('/^(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?$/', $value, $matches)) - { - $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; + break; + } else { + throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); + } + } - return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); - } - else - { - return sfYamlInline::load($value); + return implode("\n", $data); } - } - - /** - * Parses a folded scalar. - * - * @param string $separator The separator that was used to begin this folded scalar (| or >) - * @param string $indicator The indicator that was used to begin this folded scalar (+ or -) - * @param integer $indentation The indentation that was used to begin this folded scalar - * - * @return string The text value - */ - protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0) - { - $separator = '|' == $separator ? "\n" : ' '; - $text = ''; - - $notEOF = $this->moveToNextLine(); - - while ($notEOF && $this->isCurrentLineBlank()) + + /** + * Moves the parser to the next line. + */ + protected function moveToNextLine() { - $text .= "\n"; + if ($this->currentLineNb >= count($this->lines) - 1) { + return false; + } - $notEOF = $this->moveToNextLine(); + $this->currentLine = $this->lines[++$this->currentLineNb]; + + return true; } - if (!$notEOF) + /** + * Moves the parser to the previous line. + */ + protected function moveToPreviousLine() { - return ''; + $this->currentLine = $this->lines[--$this->currentLineNb]; } - if (!preg_match('#^(?P'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P.*)$#u', $this->currentLine, $matches)) + /** + * Parses a YAML value. + * + * @param string $value A YAML value + * + * @return mixed A PHP value + */ + protected function parseValue($value) { - $this->moveToPreviousLine(); + if ('*' === substr($value, 0, 1)) { + if (false !== $pos = strpos($value, '#')) { + $value = substr($value, 1, $pos - 2); + } else { + $value = substr($value, 1); + } - return ''; - } + if (!array_key_exists($value, $this->refs)) { + throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine)); + } - $textIndent = $matches['indent']; - $previousIndent = 0; + return $this->refs[$value]; + } - $text .= $matches['text'].$separator; - while ($this->currentLineNb + 1 < count($this->lines)) - { - $this->moveToNextLine(); + if (preg_match('/^(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?$/', $value, $matches)) { + $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; - if (preg_match('#^(?P {'.strlen($textIndent).',})(?P.+)$#u', $this->currentLine, $matches)) - { - if (' ' == $separator && $previousIndent != $matches['indent']) - { - $text = substr($text, 0, -1)."\n"; + return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); } - $previousIndent = $matches['indent']; - - $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator); - } - else if (preg_match('#^(?P *)$#', $this->currentLine, $matches)) - { - $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n"; - } - else - { - $this->moveToPreviousLine(); - break; - } + return sfYamlInline::load($value); } - if (' ' == $separator) + /** + * Parses a folded scalar. + * + * @param string $separator The separator that was used to begin this folded scalar (| or >) + * @param string $indicator The indicator that was used to begin this folded scalar (+ or -) + * @param int $indentation The indentation that was used to begin this folded scalar + * + * @return string The text value + */ + protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0) { - // replace last separator by a newline - $text = preg_replace('/ (\n*)$/', "\n$1", $text); - } + $separator = '|' == $separator ? "\n" : ' '; + $text = ''; - switch ($indicator) - { - case '': - $text = preg_replace('#\n+$#s', "\n", $text); - break; - case '+': - break; - case '-': - $text = preg_replace('#\n+$#s', '', $text); - break; - } + $notEOF = $this->moveToNextLine(); - return $text; - } + while ($notEOF && $this->isCurrentLineBlank()) { + $text .= "\n"; - /** - * Returns true if the next line is indented. - * - * @return Boolean Returns true if the next line is indented, false otherwise - */ - protected function isNextLineIndented() - { - $currentIndentation = $this->getCurrentLineIndentation(); - $notEOF = $this->moveToNextLine(); + $notEOF = $this->moveToNextLine(); + } - while ($notEOF && $this->isCurrentLineEmpty()) - { - $notEOF = $this->moveToNextLine(); + if (!$notEOF) { + return ''; + } + + if (!preg_match('#^(?P'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P.*)$#u', $this->currentLine, $matches)) { + $this->moveToPreviousLine(); + + return ''; + } + + $textIndent = $matches['indent']; + $previousIndent = 0; + + $text .= $matches['text'].$separator; + while ($this->currentLineNb + 1 < count($this->lines)) { + $this->moveToNextLine(); + + if (preg_match('#^(?P {'.strlen($textIndent).',})(?P.+)$#u', $this->currentLine, $matches)) { + if (' ' == $separator && $previousIndent != $matches['indent']) { + $text = substr($text, 0, -1)."\n"; + } + $previousIndent = $matches['indent']; + + $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator); + } elseif (preg_match('#^(?P *)$#', $this->currentLine, $matches)) { + $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n"; + } else { + $this->moveToPreviousLine(); + + break; + } + } + + if (' ' == $separator) { + // replace last separator by a newline + $text = preg_replace('/ (\n*)$/', "\n$1", $text); + } + + switch ($indicator) { + case '': + $text = preg_replace('#\n+$#s', "\n", $text); + break; + case '+': + break; + case '-': + $text = preg_replace('#\n+$#s', '', $text); + break; + } + + return $text; } - if (false === $notEOF) + /** + * Returns true if the next line is indented. + * + * @return bool Returns true if the next line is indented, false otherwise + */ + protected function isNextLineIndented() { - return false; + $currentIndentation = $this->getCurrentLineIndentation(); + $notEOF = $this->moveToNextLine(); + + while ($notEOF && $this->isCurrentLineEmpty()) { + $notEOF = $this->moveToNextLine(); + } + + if (false === $notEOF) { + return false; + } + + $ret = false; + if ($this->getCurrentLineIndentation() <= $currentIndentation) { + $ret = true; + } + + $this->moveToPreviousLine(); + + return $ret; } - $ret = false; - if ($this->getCurrentLineIndentation() <= $currentIndentation) + /** + * Returns true if the current line is blank or if it is a comment line. + * + * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise + */ + protected function isCurrentLineEmpty() { - $ret = true; + return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); } - $this->moveToPreviousLine(); - - return $ret; - } - - /** - * Returns true if the current line is blank or if it is a comment line. - * - * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise - */ - protected function isCurrentLineEmpty() - { - return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); - } - - /** - * Returns true if the current line is blank. - * - * @return Boolean Returns true if the current line is blank, false otherwise - */ - protected function isCurrentLineBlank() - { - return '' == trim($this->currentLine, ' '); - } - - /** - * Returns true if the current line is a comment line. - * - * @return Boolean Returns true if the current line is a comment line, false otherwise - */ - protected function isCurrentLineComment() - { - //checking explicitly the first char of the trim is faster than loops or strpos - $ltrimmedLine = ltrim($this->currentLine, ' '); - return $ltrimmedLine[0] === '#'; - } - - /** - * Cleanups a YAML string to be parsed. - * - * @param string $value The input YAML string - * - * @return string A cleaned up YAML string - */ - protected function cleanup($value) - { - $value = str_replace(array("\r\n", "\r"), "\n", $value); - - if (!preg_match("#\n$#", $value)) + /** + * Returns true if the current line is blank. + * + * @return bool Returns true if the current line is blank, false otherwise + */ + protected function isCurrentLineBlank() { - $value .= "\n"; + return '' == trim($this->currentLine, ' '); } - // strip YAML header - $count = 0; - $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#su', '', $value, -1, $count); - $this->offset += $count; - - // remove leading comments - $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); - if ($count == 1) + /** + * Returns true if the current line is a comment line. + * + * @return bool Returns true if the current line is a comment line, false otherwise + */ + protected function isCurrentLineComment() { - // items have been removed, update the offset - $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); - $value = $trimmedValue; + // checking explicitly the first char of the trim is faster than loops or strpos + $ltrimmedLine = ltrim($this->currentLine, ' '); + + return '#' === $ltrimmedLine[0]; } - // remove start of the document marker (---) - $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); - if ($count == 1) + /** + * Cleanups a YAML string to be parsed. + * + * @param string $value The input YAML string + * + * @return string A cleaned up YAML string + */ + protected function cleanup($value) { - // items have been removed, update the offset - $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); - $value = $trimmedValue; + $value = str_replace(array("\r\n", "\r"), "\n", $value); - // remove end of the document marker (...) - $value = preg_replace('#\.\.\.\s*$#s', '', $value); - } + if (!preg_match("#\n$#", $value)) { + $value .= "\n"; + } - return $value; - } + // strip YAML header + $count = 0; + $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#su', '', $value, -1, $count); + $this->offset += $count; + + // remove leading comments + $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); + if (1 == $count) { + // items have been removed, update the offset + $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); + $value = $trimmedValue; + } + + // remove start of the document marker (---) + $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); + if (1 == $count) { + // items have been removed, update the offset + $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); + $value = $trimmedValue; + + // remove end of the document marker (...) + $value = preg_replace('#\.\.\.\s*$#s', '', $value); + } + + return $value; + } } diff --git a/lib/Doctrine/Query.php b/lib/Doctrine/Query.php index a4d0b40f8..274086455 100644 --- a/lib/Doctrine/Query.php +++ b/lib/Doctrine/Query.php @@ -25,13 +25,15 @@ * data in an object-oriented fashion. A DQL query understands relations and inheritance * and is dbms independant. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen + * * @todo Proposal: This class does far too much. It should have only 1 task: Collecting * the DQL query parts and the query parameters (the query state and caching options/methods * can remain here, too). @@ -59,58 +61,58 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable { /** - * @var array The DQL keywords. + * @var array the DQL keywords */ - protected static $_keywords = array('ALL', - 'AND', - 'ANY', - 'AS', - 'ASC', - 'AVG', - 'BETWEEN', - 'BIT_LENGTH', - 'BY', - 'CHARACTER_LENGTH', - 'CHAR_LENGTH', - 'CURRENT_DATE', - 'CURRENT_TIME', - 'CURRENT_TIMESTAMP', - 'DELETE', - 'DESC', - 'DISTINCT', - 'EMPTY', - 'EXISTS', - 'FALSE', - 'FETCH', - 'FROM', - 'GROUP', - 'HAVING', - 'IN', - 'INDEXBY', - 'INNER', - 'IS', - 'JOIN', - 'LEFT', - 'LIKE', - 'LOWER', - 'MEMBER', - 'MOD', - 'NEW', - 'NOT', - 'NULL', - 'OBJECT', - 'OF', - 'OR', - 'ORDER', - 'OUTER', - 'POSITION', - 'SELECT', - 'SOME', - 'TRIM', - 'TRUE', - 'UNKNOWN', - 'UPDATE', - 'WHERE'); + protected static $_keywords = array('ALL', + 'AND', + 'ANY', + 'AS', + 'ASC', + 'AVG', + 'BETWEEN', + 'BIT_LENGTH', + 'BY', + 'CHARACTER_LENGTH', + 'CHAR_LENGTH', + 'CURRENT_DATE', + 'CURRENT_TIME', + 'CURRENT_TIMESTAMP', + 'DELETE', + 'DESC', + 'DISTINCT', + 'EMPTY', + 'EXISTS', + 'FALSE', + 'FETCH', + 'FROM', + 'GROUP', + 'HAVING', + 'IN', + 'INDEXBY', + 'INNER', + 'IS', + 'JOIN', + 'LEFT', + 'LIKE', + 'LOWER', + 'MEMBER', + 'MOD', + 'NEW', + 'NOT', + 'NULL', + 'OBJECT', + 'OF', + 'OR', + 'ORDER', + 'OUTER', + 'POSITION', + 'SELECT', + 'SOME', + 'TRIM', + 'TRUE', + 'UNKNOWN', + 'UPDATE', + 'WHERE'); /** * @var array @@ -118,10 +120,10 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable protected $_subqueryAliases = array(); /** - * @var array $_aggregateAliasMap an array containing all aggregate aliases, keys as dql aliases - * and values as sql aliases + * @var array an array containing all aggregate aliases, keys as dql aliases + * and values as sql aliases */ - protected $_aggregateAliasMap = array(); + protected $_aggregateAliasMap = array(); /** * @var array @@ -129,34 +131,34 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable protected $_pendingAggregates = array(); /** - * @param boolean $needsSubquery + * @param bool $needsSubquery */ protected $_needsSubquery = false; /** - * @param boolean $isSubquery whether or not this query object is a subquery of another - * query object + * @param bool $isSubquery whether or not this query object is a subquery of another + * query object */ protected $_isSubquery; /** - * @var array $_neededTables an array containing the needed table aliases + * @var array an array containing the needed table aliases */ protected $_neededTables = array(); /** - * @var array $pendingSubqueries SELECT part subqueries, these are called pending subqueries since - * they cannot be parsed directly (some queries might be correlated) + * @var array SELECT part subqueries, these are called pending subqueries since + * they cannot be parsed directly (some queries might be correlated) */ protected $_pendingSubqueries = array(); /** - * @var array $_pendingFields an array of pending fields (fields waiting to be parsed) + * @var array an array of pending fields (fields waiting to be parsed) */ protected $_pendingFields = array(); /** - * @var array $_parsers an array of parser objects, each DQL query part has its own parser + * @var array an array of parser objects, each DQL query part has its own parser */ protected $_parsers = array(); @@ -166,24 +168,27 @@ class Doctrine_Query extends Doctrine_Query_Abstract implements Countable protected $_expressionMap = array(); /** - * @var string $_sql cached SQL query + * @var string cached SQL query */ protected $_sql; /** * create - * returns a new Doctrine_Query object + * returns a new Doctrine_Query object. * * @param Doctrine_Connection $conn optional connection parameter - * @param string $class Query class to instantiate + * @param string $class Query class to instantiate + * * @return Doctrine_Query */ public static function create($conn = null, $class = null) { - if ( ! $class) { + if (!$class) { $class = Doctrine_Manager::getInstance() - ->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS); + ->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS) + ; } + return new $class($conn); } @@ -216,14 +221,14 @@ public function reset() /** * createSubquery - * creates a subquery + * creates a subquery. * * @return Doctrine_Hydrate */ public function createSubquery() { $class = get_class($this); - $obj = new $class(); + $obj = new $class(); // copy the aliases to the subquery $obj->copySubqueryInfo($this); @@ -235,15 +240,16 @@ public function createSubquery() } /** - * addPendingJoinCondition + * addPendingJoinCondition. * - * @param string $componentAlias component alias - * @param string $joinCondition dql join condition - * @return Doctrine_Query this object + * @param string $componentAlias component alias + * @param string $joinCondition dql join condition + * + * @return Doctrine_Query this object */ public function addPendingJoinCondition($componentAlias, $joinCondition) { - if ( ! isset($this->_pendingJoinConditions[$componentAlias])) { + if (!isset($this->_pendingJoinConditions[$componentAlias])) { $this->_pendingJoinConditions[$componentAlias] = array(); } @@ -255,6 +261,7 @@ public function addPendingJoinCondition($componentAlias, $joinCondition) * Convenience method to execute using array fetching as hydration mode. * * @param string $params + * * @return array */ public function fetchArray($params = array()) @@ -280,13 +287,14 @@ public function fetchOne($params = array(), $hydrationMode = null) return $collection; } - if ($collection === null || count($collection) === 0) { + if (null === $collection || 0 === count($collection)) { return false; } if ($collection instanceof Doctrine_Collection) { return $collection->getFirst(); - } else if (is_array($collection)) { + } + if (is_array($collection)) { return array_shift($collection); } @@ -303,23 +311,26 @@ public function fetchOne($params = array(), $hydrationMode = null) * If null is given as the first parameter this method retrieves the current * value of Doctrine_Query::$isSubquery. * - * @param boolean $bool whether or not this query acts as a subquery + * @param bool $bool whether or not this query acts as a subquery + * * @return Doctrine_Query|bool */ public function isSubquery($bool = null) { - if ($bool === null) { + if (null === $bool) { return $this->_isSubquery; } $this->_isSubquery = (bool) $bool; + return $this; } /** - * getSqlAggregateAlias + * getSqlAggregateAlias. + * + * @param string $dqlAlias the dql alias of an aggregate value * - * @param string $dqlAlias the dql alias of an aggregate value * @return string */ public function getSqlAggregateAlias($dqlAlias) @@ -329,27 +340,30 @@ public function getSqlAggregateAlias($dqlAlias) $this->_expressionMap[$dqlAlias][1] = true; return $this->_aggregateAliasMap[$dqlAlias]; - } else if ( ! empty($this->_pendingAggregates)) { + } + if (!empty($this->_pendingAggregates)) { $this->processPendingAggregates(); return $this->getSqlAggregateAlias($dqlAlias); - } else if( ! ($this->_conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EXPR)){ + } + if (!($this->_conn->getAttribute(Doctrine_Core::ATTR_PORTABILITY) & Doctrine_Core::PORTABILITY_EXPR)) { return $dqlAlias; - } else { - throw new Doctrine_Query_Exception('Unknown aggregate alias: ' . $dqlAlias); } + throw new Doctrine_Query_Exception('Unknown aggregate alias: '.$dqlAlias); } /** - * Check if a dql alias has a sql aggregate alias + * Check if a dql alias has a sql aggregate alias. * * @param string $dqlAlias - * @return boolean + * + * @return bool */ public function hasSqlAggregateAlias($dqlAlias) { try { $this->getSqlAggregateAlias($dqlAlias); + return true; } catch (Exception $e) { return false; @@ -357,8 +371,7 @@ public function hasSqlAggregateAlias($dqlAlias) } /** - * Adjust the processed param index for "foo.bar IN ?" support - * + * Adjust the processed param index for "foo.bar IN ?" support. */ public function adjustProcessedParam($index) { @@ -384,40 +397,43 @@ public function adjustProcessedParam($index) * var_dump($q->getDqlPart('where')); * // array(2) { [0] => string(8) 'name = ?' [1] => string(8) 'date > ?' } * - * @param string $queryPart the name of the query part; can be: - * array from, containing strings; - * array select, containg string; - * boolean forUpdate; - * array set; - * array join; - * array where; - * array groupby; - * array having; - * array orderby, containing strings such as 'id ASC'; - * array limit, containing numerics; - * array offset, containing numerics; + * + * @param string $queryPart the name of the query part; can be: + * array from, containing strings; + * array select, containg string; + * boolean forUpdate; + * array set; + * array join; + * array where; + * array groupby; + * array having; + * array orderby, containing strings such as 'id ASC'; + * array limit, containing numerics; + * array offset, containing numerics; + * * @return array */ public function getDqlPart($queryPart) { - if ( ! isset($this->_dqlParts[$queryPart])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $queryPart); + if (!isset($this->_dqlParts[$queryPart])) { + throw new Doctrine_Query_Exception('Unknown query part '.$queryPart); } return $this->_dqlParts[$queryPart]; } /** - * contains + * contains. * * Method to check if a arbitrary piece of dql exists * * @param string $dql Arbitrary piece of dql to check for - * @return boolean + * + * @return bool */ public function contains($dql) { - return stripos($this->getDql(), $dql) === false ? false : true; + return false === stripos($this->getDql(), $dql) ? false : true; } /** @@ -427,9 +443,12 @@ public function contains($dql) * specific component is being parsed. For instance, the wildcard '*' * is expanded in the list of columns. * - * @throws Doctrine_Query_Exception if unknown component alias has been given - * @param string $componentAlias the alias of the component + * @param string $componentAlias the alias of the component + * * @return string SQL code + * + * @throws Doctrine_Query_Exception if unknown component alias has been given + * * @todo Description: What is a 'pending field' (and are there non-pending fields, too)? * What is 'processed'? (Meaning: What information is gathered & stored away) */ @@ -438,13 +457,13 @@ public function processPendingFields($componentAlias) $tableAlias = $this->getSqlTableAlias($componentAlias); $table = $this->_queryComponents[$componentAlias]['table']; - if ( ! isset($this->_pendingFields[$componentAlias])) { - if ($this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_NONE) { - if ( ! $this->_isSubquery && $componentAlias == $this->getRootAlias()) { - throw new Doctrine_Query_Exception("The root class of the query (alias $componentAlias) " - . " must have at least one field selected."); + if (!isset($this->_pendingFields[$componentAlias])) { + if (Doctrine_Core::HYDRATE_NONE != $this->_hydrator->getHydrationMode()) { + if (!$this->_isSubquery && $componentAlias == $this->getRootAlias()) { + throw new Doctrine_Query_Exception("The root class of the query (alias {$componentAlias}) ".' must have at least one field selected.'); } } + return; } @@ -452,15 +471,13 @@ public function processPendingFields($componentAlias) // the query (FROM xyz) or its a "fetch join"). // Check that the parent join (if there is one), is a "fetch join", too. - if ( ! $this->isSubquery() && isset($this->_queryComponents[$componentAlias]['parent'])) { + if (!$this->isSubquery() && isset($this->_queryComponents[$componentAlias]['parent'])) { $parentAlias = $this->_queryComponents[$componentAlias]['parent']; - if (is_string($parentAlias) && ! isset($this->_pendingFields[$parentAlias]) - && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_NONE - && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_SCALAR - && $this->_hydrator->getHydrationMode() != Doctrine_Core::HYDRATE_SINGLE_SCALAR) { - throw new Doctrine_Query_Exception("The left side of the join between " - . "the aliases '$parentAlias' and '$componentAlias' must have at least" - . " the primary key field(s) selected."); + if (is_string($parentAlias) && !isset($this->_pendingFields[$parentAlias]) + && Doctrine_Core::HYDRATE_NONE != $this->_hydrator->getHydrationMode() + && Doctrine_Core::HYDRATE_SCALAR != $this->_hydrator->getHydrationMode() + && Doctrine_Core::HYDRATE_SINGLE_SCALAR != $this->_hydrator->getHydrationMode()) { + throw new Doctrine_Query_Exception('The left side of the join between '."the aliases '{$parentAlias}' and '{$componentAlias}' must have at least".' the primary key field(s) selected.'); } } @@ -474,7 +491,7 @@ public function processPendingFields($componentAlias) // only auto-add the primary key fields if this query object is not // a subquery of another query object or we're using a child of the Object Graph // hydrator - if ( ! $this->_isSubquery && is_subclass_of($driverClassName, 'Doctrine_Hydrator_Graph')) { + if (!$this->_isSubquery && is_subclass_of($driverClassName, 'Doctrine_Hydrator_Graph')) { $fields = array_unique(array_merge((array) $table->getIdentifier(), $fields)); } } @@ -482,20 +499,19 @@ public function processPendingFields($componentAlias) $sql = array(); foreach ($fields as $fieldName) { $columnName = $table->getColumnName($fieldName); - if (($owner = $table->getColumnOwner($columnName)) !== null && - $owner !== $table->getComponentName()) { - + if (($owner = $table->getColumnOwner($columnName)) !== null + && $owner !== $table->getComponentName()) { $parent = $this->_conn->getTable($owner); $columnName = $parent->getColumnName($fieldName); - $parentAlias = $this->getSqlTableAlias($componentAlias . '.' . $parent->getComponentName()); - $sql[] = $this->_conn->quoteIdentifier($parentAlias) . '.' . $this->_conn->quoteIdentifier($columnName) - . ' AS ' - . $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName); + $parentAlias = $this->getSqlTableAlias($componentAlias.'.'.$parent->getComponentName()); + $sql[] = $this->_conn->quoteIdentifier($parentAlias).'.'.$this->_conn->quoteIdentifier($columnName) + .' AS ' + .$this->_conn->quoteIdentifier($tableAlias.'__'.$columnName); } else { $columnName = $table->getColumnName($fieldName); - $sql[] = $this->_conn->quoteIdentifier($tableAlias) . '.' . $this->_conn->quoteIdentifier($columnName) - . ' AS ' - . $this->_conn->quoteIdentifier($tableAlias . '__' . $columnName); + $sql[] = $this->_conn->quoteIdentifier($tableAlias).'.'.$this->_conn->quoteIdentifier($columnName) + .' AS ' + .$this->_conn->quoteIdentifier($tableAlias.'__'.$columnName); } } @@ -508,14 +524,16 @@ public function processPendingFields($componentAlias) * Parses a nested field * * $q->parseSelectField('u.Phonenumber.value'); - * + * . * * @param string $field - * @throws Doctrine_Query_Exception if unknown component alias has been given - * @return string SQL fragment + * + * @return string SQL fragment + * + * @throws Doctrine_Query_Exception if unknown component alias has been given + * * @todo Description: Explain what this method does. Is there a relation to parseSelect()? * This method is not used from any class or testcase in the Doctrine package. - * */ public function parseSelectField($field) { @@ -531,44 +549,44 @@ public function parseSelectField($field) } $tableAlias = $this->getSqlTableAlias($componentAlias); - $table = $this->_queryComponents[$componentAlias]['table']; - + $table = $this->_queryComponents[$componentAlias]['table']; // check for wildcards - if ($field === '*') { + if ('*' === $field) { $sql = array(); foreach ($table->getColumnNames() as $field) { - $sql[] = $this->parseSelectField($componentAlias . '.' . $field); + $sql[] = $this->parseSelectField($componentAlias.'.'.$field); } return implode(', ', $sql); - } else { - $name = $table->getColumnName($field); + } + $name = $table->getColumnName($field); - $this->_neededTables[] = $tableAlias; + $this->_neededTables[] = $tableAlias; - return $this->_conn->quoteIdentifier($tableAlias . '.' . $name) - . ' AS ' - . $this->_conn->quoteIdentifier($tableAlias . '__' . $name); - } + return $this->_conn->quoteIdentifier($tableAlias.'.'.$name) + .' AS ' + .$this->_conn->quoteIdentifier($tableAlias.'__'.$name); } /** * getExpressionOwner - * returns the component alias for owner of given expression + * returns the component alias for owner of given expression. + * + * @param string $expr expression from which to get to owner from + * + * @return string the component alias * - * @param string $expr expression from which to get to owner from - * @return string the component alias * @todo Description: What does it mean if a component is an 'owner' of an expression? * What kind of 'expression' are we talking about here? */ public function getExpressionOwner($expr) { - if (strtoupper(substr(trim($expr, '( '), 0, 6)) !== 'SELECT') { + if ('SELECT' !== strtoupper(substr(trim($expr, '( '), 0, 6))) { // Fix for http://www.doctrine-project.org/jira/browse/DC-754 $expr = preg_replace('/([\'\"])[^\1]*\1/', '', $expr); - preg_match_all("/[a-z_][a-z0-9_]*\.[a-z_][a-z0-9_]*[\.[a-z0-9]+]*/i", $expr, $matches); + preg_match_all('/[a-z_][a-z0-9_]*\\.[a-z_][a-z0-9_]*[\\.[a-z0-9]+]*/i', $expr, $matches); $match = current($matches); @@ -578,27 +596,28 @@ public function getExpressionOwner($expr) return $terms[0]; } } - return $this->getRootAlias(); + return $this->getRootAlias(); } /** * parseSelect * parses the query select part and - * adds selected fields to pendingFields array + * adds selected fields to pendingFields array. * * @param string $dql + * * @todo Description: What information is extracted (and then stored)? */ public function parseSelect($dql) { $refs = $this->_tokenizer->sqlExplode($dql, ','); - $pos = strpos(trim($refs[0]), ' '); + $pos = strpos(trim($refs[0]), ' '); $first = substr($refs[0], 0, $pos); // check for DISTINCT keyword - if ($first === 'DISTINCT') { + if ('DISTINCT' === $first) { $this->_sqlParts['distinct'] = true; $refs[0] = substr($refs[0], ++$pos); @@ -614,18 +633,18 @@ public function parseSelect($dql) } $terms = $this->_tokenizer->sqlExplode($reference, ' '); - $pos = strpos($terms[0], '('); + $pos = strpos($terms[0], '('); - if (count($terms) > 1 || $pos !== false) { + if (count($terms) > 1 || false !== $pos) { $expression = array_shift($terms); $alias = array_pop($terms); - if ( ! $alias) { + if (!$alias) { $alias = substr($expression, 0, $pos); } // Fix for http://www.doctrine-project.org/jira/browse/DC-706 - if ($pos !== false && substr($expression, 0, 1) !== "'" && substr($expression, 0, $pos) == '') { + if (false !== $pos && "'" !== substr($expression, 0, 1) && '' == substr($expression, 0, $pos)) { $_queryComponents = $this->_queryComponents; reset($_queryComponents); $componentAlias = key($_queryComponents); @@ -637,11 +656,11 @@ public function parseSelect($dql) $tableAlias = $this->getSqlTableAlias($componentAlias); - $index = count($this->_aggregateAliasMap); + $index = count($this->_aggregateAliasMap); - $sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index); + $sqlAlias = $this->_conn->quoteIdentifier($tableAlias.'__'.$index); - $this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias; + $this->_sqlParts['select'][] = $expression.' AS '.$sqlAlias; $this->_aggregateAliasMap[$alias] = $sqlAlias; $this->_expressionMap[$alias][0] = $expression; @@ -672,7 +691,7 @@ public function parseSelect($dql) /** * parseClause - * parses given DQL clause + * parses given DQL clause. * * this method handles five tasks: * @@ -682,7 +701,8 @@ public function parseSelect($dql) * 4. Quotes all identifiers * 5. Parses nested clauses and subqueries recursively * - * @return string SQL string + * @return string SQL string + * * @todo Description: What is a 'dql clause' (and what not)? * Refactor: Too long & nesting level */ @@ -691,7 +711,7 @@ public function parseClause($clause) $clause = $this->_conn->dataDict->parseBoolean(trim($clause)); if (is_numeric($clause)) { - return $clause; + return $clause; } $terms = $this->_tokenizer->clauseExplode($clause, array(' ', '+', '-', '*', '/', '<', '>', '=', '>=', '<=', '&', '|')); @@ -700,19 +720,19 @@ public function parseClause($clause) foreach ($terms as $term) { $pos = strpos($term[0], '('); - if ($pos !== false && substr($term[0], 0, 1) !== "'") { + if (false !== $pos && "'" !== substr($term[0], 0, 1)) { $name = substr($term[0], 0, $pos); $term[0] = $this->parseFunctionExpression($term[0]); } else { - if (substr($term[0], 0, 1) !== "'" && substr($term[0], -1) !== "'") { - if (strpos($term[0], '.') !== false) { - if ( ! is_numeric($term[0])) { + if ("'" !== substr($term[0], 0, 1) && "'" !== substr($term[0], -1)) { + if (false !== strpos($term[0], '.')) { + if (!is_numeric($term[0])) { $e = explode('.', $term[0]); $field = array_pop($e); - if ($this->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->getType()) { $componentAlias = implode('.', $e); if (empty($componentAlias)) { @@ -722,8 +742,8 @@ public function parseClause($clause) $this->load($componentAlias); // check the existence of the component alias - if ( ! isset($this->_queryComponents[$componentAlias])) { - throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias); + if (!isset($this->_queryComponents[$componentAlias])) { + throw new Doctrine_Query_Exception('Unknown component alias '.$componentAlias); } $table = $this->_queryComponents[$componentAlias]['table']; @@ -734,20 +754,20 @@ public function parseClause($clause) $field = $table->getColumnName($field); // check column existence - if ( ! $def) { - throw new Doctrine_Query_Exception('Unknown column ' . $field); + if (!$def) { + throw new Doctrine_Query_Exception('Unknown column '.$field); } if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->getSqlTableAlias($componentAlias); // build sql expression $term[0] = $this->_conn->quoteIdentifier($tableAlias) - . '.' - . $this->_conn->quoteIdentifier($field); + .'.' + .$this->_conn->quoteIdentifier($field); } else { // build sql expression $field = $this->getRoot()->getColumnName($field); @@ -755,14 +775,13 @@ public function parseClause($clause) } } } else { - if ( ! empty($term[0]) && ! in_array(strtoupper($term[0]), self::$_keywords) && - ! is_numeric($term[0]) && $term[0] !== '?' && substr($term[0], 0, 1) !== ':') { - + if (!empty($term[0]) && !in_array(strtoupper($term[0]), self::$_keywords) + && !is_numeric($term[0]) && '?' !== $term[0] && ':' !== substr($term[0], 0, 1)) { $componentAlias = $this->getRootAlias(); $found = false; - if ($componentAlias !== false && $componentAlias !== null) { + if (false !== $componentAlias && null !== $componentAlias) { $table = $this->_queryComponents[$componentAlias]['table']; // check column existence @@ -774,18 +793,17 @@ public function parseClause($clause) // get the actual column name from field name $term[0] = $table->getColumnName($term[0]); - if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->getSqlTableAlias($componentAlias); - if ($this->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->getType()) { // build sql expression $term[0] = $this->_conn->quoteIdentifier($tableAlias) - . '.' - . $this->_conn->quoteIdentifier($term[0]); + .'.' + .$this->_conn->quoteIdentifier($term[0]); } else { // build sql expression $term[0] = $this->_conn->quoteIdentifier($term[0]); @@ -795,7 +813,7 @@ public function parseClause($clause) } } - if ( ! $found) { + if (!$found) { $term[0] = $this->getSqlAggregateAlias($term[0]); } } @@ -803,14 +821,14 @@ public function parseClause($clause) } } - $str .= $term[0] . $term[1]; + $str .= $term[0].$term[1]; } + return $str; } public function parseIdentifierReference($expr) { - } public function parseFunctionExpression($expr, $parseCallback = null) @@ -818,40 +836,39 @@ public function parseFunctionExpression($expr, $parseCallback = null) $pos = strpos($expr, '('); $name = substr($expr, 0, $pos); - if ($name === '') { + if ('' === $name) { return $this->parseSubquery($expr); } - $argStr = substr($expr, ($pos + 1), -1); - $args = array(); + $argStr = substr($expr, $pos + 1, -1); + $args = array(); // parse args foreach ($this->_tokenizer->sqlExplode($argStr, ',') as $arg) { - $args[] = $parseCallback ? call_user_func_array($parseCallback, array($arg)) : $this->parseClause($arg); + $args[] = $parseCallback ? call_user_func_array($parseCallback, array($arg)) : $this->parseClause($arg); } // convert DQL function to its RDBMS specific equivalent try { $expr = call_user_func_array(array($this->_conn->expression, $name), $args); } catch (Doctrine_Expression_Exception $e) { - throw new Doctrine_Query_Exception('Unknown function ' . $name . '.'); + throw new Doctrine_Query_Exception('Unknown function '.$name.'.'); } return $expr; } - public function parseSubquery($subquery) { $trimmed = trim($this->_tokenizer->bracketTrim($subquery)); // check for possible subqueries - if (substr($trimmed, 0, 4) == 'FROM' || substr($trimmed, 0, 6) == 'SELECT') { + if ('FROM' == substr($trimmed, 0, 4) || 'SELECT' == substr($trimmed, 0, 6)) { // parse subquery $q = $this->createSubquery()->parseDqlQuery($trimmed); $trimmed = $q->getSqlQuery(); $q->free(); - } else if (substr($trimmed, 0, 4) == 'SQL:') { + } elseif ('SQL:' == substr($trimmed, 0, 4)) { $trimmed = substr($trimmed, 4); } else { $e = $this->_tokenizer->sqlExplode($trimmed, ','); @@ -866,18 +883,16 @@ public function parseSubquery($subquery) $trimmed = implode(', ', $value); } - return '(' . $trimmed . ')'; + return '('.$trimmed.')'; } - /** * processPendingSubqueries - * processes pending subqueries + * processes pending subqueries. * * subqueries can only be processed when the query is fully constructed * since some subqueries may be correlated * - * @return void * @todo Better description. i.e. What is a 'pending subquery'? What does 'processed' mean? * (parsed? sql is constructed? some information is gathered?) */ @@ -895,9 +910,9 @@ public function processPendingSubqueries() $componentAlias = key($this->_queryComponents); $tableAlias = $this->getSqlTableAlias($componentAlias); - $sqlAlias = $tableAlias . '__' . count($this->_aggregateAliasMap); + $sqlAlias = $tableAlias.'__'.count($this->_aggregateAliasMap); - $this->_sqlParts['select'][] = '(' . $sql . ') AS ' . $this->_conn->quoteIdentifier($sqlAlias); + $this->_sqlParts['select'][] = '('.$sql.') AS '.$this->_conn->quoteIdentifier($sqlAlias); $this->_aggregateAliasMap[$alias] = $sqlAlias; $this->_queryComponents[$componentAlias]['agg'][] = $alias; @@ -907,23 +922,21 @@ public function processPendingSubqueries() /** * processPendingAggregates - * processes pending aggregate values for given component alias + * processes pending aggregate values for given component alias. * - * @return void * @todo Better description. i.e. What is a 'pending aggregate'? What does 'processed' mean? */ public function processPendingAggregates() { // iterate trhough all aggregates foreach ($this->_pendingAggregates as $aggregate) { - list ($expression, $components, $alias) = $aggregate; + list($expression, $components, $alias) = $aggregate; $tableAliases = array(); // iterate through the component references within the aggregate function - if ( ! empty ($components)) { + if (!empty($components)) { foreach ($components as $component) { - if (is_numeric($component)) { continue; } @@ -934,8 +947,8 @@ public function processPendingAggregates() $componentAlias = implode('.', $e); // check the existence of the component alias - if ( ! isset($this->_queryComponents[$componentAlias])) { - throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias); + if (!isset($this->_queryComponents[$componentAlias])) { + throw new Doctrine_Query_Exception('Unknown component alias '.$componentAlias); } $table = $this->_queryComponents[$componentAlias]['table']; @@ -943,8 +956,8 @@ public function processPendingAggregates() $field = $table->getColumnName($field); // check column existence - if ( ! $table->hasColumn($field)) { - throw new Doctrine_Query_Exception('Unknown column ' . $field); + if (!$table->hasColumn($field)) { + throw new Doctrine_Query_Exception('Unknown column '.$field); } $sqlTableAlias = $this->getSqlTableAlias($componentAlias); @@ -953,20 +966,20 @@ public function processPendingAggregates() // build sql expression - $identifier = $this->_conn->quoteIdentifier($sqlTableAlias . '.' . $field); + $identifier = $this->_conn->quoteIdentifier($sqlTableAlias.'.'.$field); $expression = str_replace($component, $identifier, $expression); } } - if (count($tableAliases) !== 1) { + if (1 !== count($tableAliases)) { $componentAlias = reset($this->_tableAliasMap); $tableAlias = key($this->_tableAliasMap); } - $index = count($this->_aggregateAliasMap); - $sqlAlias = $this->_conn->quoteIdentifier($tableAlias . '__' . $index); + $index = count($this->_aggregateAliasMap); + $sqlAlias = $this->_conn->quoteIdentifier($tableAlias.'__'.$index); - $this->_sqlParts['select'][] = $expression . ' AS ' . $sqlAlias; + $this->_sqlParts['select'][] = $expression.' AS '.$sqlAlias; $this->_aggregateAliasMap[$alias] = $sqlAlias; $this->_expressionMap[$alias][0] = $expression; @@ -983,32 +996,33 @@ public function processPendingAggregates() * _buildSqlQueryBase * returns the base of the generated sql query * On mysql driver special strategy has to be used for DELETE statements - * (where is this special strategy??) + * (where is this special strategy??). * - * @return string the base of the generated sql query + * @return string the base of the generated sql query */ protected function _buildSqlQueryBase() { switch ($this->_type) { case self::DELETE: $q = 'DELETE FROM '; - break; + break; case self::UPDATE: $q = 'UPDATE '; - break; + break; case self::SELECT: $distinct = ($this->_sqlParts['distinct']) ? 'DISTINCT ' : ''; - $q = 'SELECT ' . $distinct . implode(', ', $this->_sqlParts['select']) . ' FROM '; - break; + $q = 'SELECT '.$distinct.implode(', ', $this->_sqlParts['select']).' FROM '; + break; } + return $q; } /** * _buildSqlFromPart - * builds the from part of the query and returns it + * builds the from part of the query and returns it. * - * @return string the query sql from part + * @return string the query sql from part */ protected function _buildSqlFromPart($ignorePending = false) { @@ -1017,8 +1031,8 @@ protected function _buildSqlFromPart($ignorePending = false) foreach ($this->_sqlParts['from'] as $k => $part) { $e = explode(' ', $part); - if ($k === 0) { - if ( ! $ignorePending && $this->_type == self::SELECT) { + if (0 === $k) { + if (!$ignorePending && self::SELECT == $this->_type) { // We may still have pending conditions $alias = count($e) > 1 ? $this->getComponentAlias($e[1]) @@ -1026,15 +1040,15 @@ protected function _buildSqlFromPart($ignorePending = false) $where = $this->_processPendingJoinConditions($alias); // apply inheritance to WHERE part - if ( ! empty($where)) { + if (!empty($where)) { if (count($this->_sqlParts['where']) > 0) { $this->_sqlParts['where'][] = 'AND'; } - if (substr($where, 0, 1) === '(' && substr($where, -1) === ')') { + if ('(' === substr($where, 0, 1) && ')' === substr($where, -1)) { $this->_sqlParts['where'][] = $where; } else { - $this->_sqlParts['where'][] = '(' . $where . ')'; + $this->_sqlParts['where'][] = '('.$where.')'; } } } @@ -1046,21 +1060,20 @@ protected function _buildSqlFromPart($ignorePending = false) // preserve LEFT JOINs only if needed // Check if it's JOIN, if not add a comma separator instead of space - if ( ! preg_match('/\bJOIN\b/i', $part) && ! isset($this->_pendingJoinConditions[$k])) { - $q .= ', ' . $part; + if (!preg_match('/\bJOIN\b/i', $part) && !isset($this->_pendingJoinConditions[$k])) { + $q .= ', '.$part; } else { - if (substr($part, 0, 9) === 'LEFT JOIN') { + if ('LEFT JOIN' === substr($part, 0, 9)) { $aliases = array_merge($this->_subqueryAliases, - array_keys($this->_neededTables)); + array_keys($this->_neededTables)); - if ( ! in_array($e[3], $aliases) && ! in_array($e[2], $aliases) && ! empty($this->_pendingFields)) { + if (!in_array($e[3], $aliases) && !in_array($e[2], $aliases) && !empty($this->_pendingFields)) { continue; } - } - if ( ! $ignorePending && isset($this->_pendingJoinConditions[$k])) { - if (strpos($part, ' ON ') !== false) { + if (!$ignorePending && isset($this->_pendingJoinConditions[$k])) { + if (false !== strpos($part, ' ON ')) { $part .= ' AND '; } else { $part .= ' ON '; @@ -1073,13 +1086,14 @@ protected function _buildSqlFromPart($ignorePending = false) $string = $this->getInheritanceCondition($componentAlias); if ($string) { - $part = $part . ' AND ' . $string; + $part = $part.' AND '.$string; } - $q .= ' ' . $part; + $q .= ' '.$part; } $this->_sqlParts['from'][$k] = $part; } + return $q; } @@ -1089,13 +1103,14 @@ protected function _buildSqlFromPart($ignorePending = false) * handling. * * @param string $alias Component Alias + * * @return Processed pending conditions */ protected function _processPendingJoinConditions($alias) { $parts = array(); - if ($alias !== null && isset($this->_pendingJoinConditions[$alias])) { + if (null !== $alias && isset($this->_pendingJoinConditions[$alias])) { $parser = new Doctrine_Query_JoinCondition($this, $this->_tokenizer); foreach ($this->_pendingJoinConditions[$alias] as $joinCondition) { @@ -1103,20 +1118,21 @@ protected function _processPendingJoinConditions($alias) } // FIX #1860 and #1876: Cannot unset them, otherwise query cannot be reused later - //unset($this->_pendingJoinConditions[$alias]); + // unset($this->_pendingJoinConditions[$alias]); } - return (count($parts) > 0 ? '(' . implode(') AND (', $parts) . ')' : ''); + return count($parts) > 0 ? '('.implode(') AND (', $parts).')' : ''; } /** * builds the sql query from the given parameters and applies things such as - * column aggregation inheritance and limit subqueries if needed + * column aggregation inheritance and limit subqueries if needed. * - * @param array $params an array of prepared statement params (needed only in mysql driver - * when limit subquery algorithm is used) - * @param bool $limitSubquery Whether or not to try and apply the limit subquery algorithm - * @return string the built sql query + * @param array $params an array of prepared statement params (needed only in mysql driver + * when limit subquery algorithm is used) + * @param bool $limitSubquery Whether or not to try and apply the limit subquery algorithm + * + * @return string the built sql query */ public function getSqlQuery($params = array(), $limitSubquery = true) { @@ -1126,25 +1142,27 @@ public function getSqlQuery($params = array(), $limitSubquery = true) // Initialize prepared parameters array $this->_execParams = $this->getFlattenedParams(); - if ($this->_state !== self::STATE_DIRTY) { + if (self::STATE_DIRTY !== $this->_state) { $this->fixArrayParameterValues($this->getInternalParams()); // Return compiled SQL return $this->_sql; } + return $this->buildSqlQuery($limitSubquery); } /** - * Build the SQL query from the DQL + * Build the SQL query from the DQL. * * @param bool $limitSubquery Whether or not to try and apply the limit subquery algorithm + * * @return string $sql The generated SQL string */ public function buildSqlQuery($limitSubquery = true) { // reset the state - if ( ! $this->isSubquery()) { + if (!$this->isSubquery()) { $this->_queryComponents = array(); $this->_pendingAggregates = array(); $this->_aggregateAliasMap = array(); @@ -1159,18 +1177,18 @@ public function buildSqlQuery($limitSubquery = true) // this will also populate the $_queryComponents. foreach ($this->_dqlParts as $queryPartName => $queryParts) { // If we are parsing FROM clause, we'll need to diff the queryComponents later - if ($queryPartName == 'from') { + if ('from' == $queryPartName) { // Pick queryComponents before processing $queryComponentsBefore = $this->getQueryComponents(); } // FIX #1667: _sqlParts are cleaned inside _processDqlQueryPart. - if ($queryPartName != 'forUpdate') { + if ('forUpdate' != $queryPartName) { $this->_processDqlQueryPart($queryPartName, $queryParts); } // We need to define the root alias - if ($queryPartName == 'from') { + if ('from' == $queryPartName) { // Pick queryComponents aftr processing $queryComponentsAfter = $this->getQueryComponents(); @@ -1192,24 +1210,24 @@ public function buildSqlQuery($limitSubquery = true) $table = $map['table']; $rootAlias = $this->getRootAlias(); - if ( ! empty($this->_sqlParts['limit']) && $this->_needsSubquery && - $table->getAttribute(Doctrine_Core::ATTR_QUERY_LIMIT) == Doctrine_Core::LIMIT_RECORDS) { + if (!empty($this->_sqlParts['limit']) && $this->_needsSubquery + && Doctrine_Core::LIMIT_RECORDS == $table->getAttribute(Doctrine_Core::ATTR_QUERY_LIMIT)) { // We do not need a limit-subquery if DISTINCT is used // and the selected fields are either from the root component or from a localKey relation (hasOne) // (i.e. DQL: SELECT DISTINCT u.id FROM User u LEFT JOIN u.phonenumbers LIMIT 5). - if(!$this->_sqlParts['distinct']) { + if (!$this->_sqlParts['distinct']) { $this->_isLimitSubqueryUsed = true; $needsSubQuery = true; } else { - foreach( array_keys($this->_pendingFields) as $alias){ - //no subquery for root fields - if($alias == $this->getRootAlias()){ + foreach (array_keys($this->_pendingFields) as $alias) { + // no subquery for root fields + if ($alias == $this->getRootAlias()) { continue; } - //no subquery for ONE relations - if(isset($this->_queryComponents[$alias]['relation']) && - $this->_queryComponents[$alias]['relation']->getType() == Doctrine_Relation::ONE){ + // no subquery for ONE relations + if (isset($this->_queryComponents[$alias]['relation']) + && Doctrine_Relation::ONE == $this->_queryComponents[$alias]['relation']->getType()) { continue; } @@ -1221,48 +1239,48 @@ public function buildSqlQuery($limitSubquery = true) $sql = array(); - if ( ! empty($this->_pendingFields)) { + if (!empty($this->_pendingFields)) { foreach ($this->_queryComponents as $alias => $map) { $fieldSql = $this->processPendingFields($alias); - if ( ! empty($fieldSql)) { + if (!empty($fieldSql)) { $sql[] = $fieldSql; } } } - if ( ! empty($sql)) { + if (!empty($sql)) { array_unshift($this->_sqlParts['select'], implode(', ', $sql)); } $this->_pendingFields = array(); // build the basic query - $q = $this->_buildSqlQueryBase(); + $q = $this->_buildSqlQueryBase(); $q .= $this->_buildSqlFromPart(); - if ( ! empty($this->_sqlParts['set'])) { - $q .= ' SET ' . implode(', ', $this->_sqlParts['set']); + if (!empty($this->_sqlParts['set'])) { + $q .= ' SET '.implode(', ', $this->_sqlParts['set']); } $string = $this->getInheritanceCondition($this->getRootAlias()); // apply inheritance to WHERE part - if ( ! empty($string)) { + if (!empty($string)) { if (count($this->_sqlParts['where']) > 0) { $this->_sqlParts['where'][] = 'AND'; } - if (substr($string, 0, 1) === '(' && substr($string, -1) === ')') { + if ('(' === substr($string, 0, 1) && ')' === substr($string, -1)) { $this->_sqlParts['where'][] = $string; } else { - $this->_sqlParts['where'][] = '(' . $string . ')'; + $this->_sqlParts['where'][] = '('.$string.')'; } } $modifyLimit = true; $limitSubquerySql = ''; - if ( ( ! empty($this->_sqlParts['limit']) || ! empty($this->_sqlParts['offset'])) && $needsSubQuery && $limitSubquery) { + if ((!empty($this->_sqlParts['limit']) || !empty($this->_sqlParts['offset'])) && $needsSubQuery && $limitSubquery) { $subquery = $this->getLimitSubquery(); // what about composite keys? @@ -1285,19 +1303,19 @@ public function buildSqlQuery($limitSubquery = true) $subqueryAlias = $this->_conn->quoteIdentifier('doctrine_subquery_alias'); // pgsql needs special nested LIMIT subquery - $subquery = 'SELECT ' . $subqueryAlias . '.' . $this->_conn->quoteIdentifier($idColumnName) - . ' FROM (' . $subquery . ') AS ' . $subqueryAlias; + $subquery = 'SELECT '.$subqueryAlias.'.'.$this->_conn->quoteIdentifier($idColumnName) + .' FROM ('.$subquery.') AS '.$subqueryAlias; break; } - $field = $this->getSqlTableAlias($rootAlias) . '.' . $idColumnName; + $field = $this->getSqlTableAlias($rootAlias).'.'.$idColumnName; // FIX #1868: If not ID under MySQL is found to be restricted, restrict pk column for null // (which will lead to a return of 0 items) $limitSubquerySql = $this->_conn->quoteIdentifier($field) - . (( ! empty($subquery)) ? ' IN (' . $subquery . ')' : ' IS NULL') - . ((count($this->_sqlParts['where']) > 0) ? ' AND ' : ''); + .((!empty($subquery)) ? ' IN ('.$subquery.')' : ' IS NULL') + .((count($this->_sqlParts['where']) > 0) ? ' AND ' : ''); $modifyLimit = false; } @@ -1305,12 +1323,12 @@ public function buildSqlQuery($limitSubquery = true) // FIX #DC-26: Include limitSubquerySql as major relevance in conditions $emptyWhere = empty($this->_sqlParts['where']); - if ( ! ($emptyWhere && $limitSubquerySql == '')) { + if (!($emptyWhere && '' == $limitSubquerySql)) { $where = implode(' ', $this->_sqlParts['where']); - $where = ($where == '' || (substr($where, 0, 1) === '(' && substr($where, -1) === ')')) - ? $where : '(' . $where . ')'; + $where = ('' == $where || ('(' === substr($where, 0, 1) && ')' === substr($where, -1))) + ? $where : '('.$where.')'; - $q .= ' WHERE ' . $limitSubquerySql . $where; + $q .= ' WHERE '.$limitSubquerySql.$where; // . (($limitSubquerySql == '' && count($this->_sqlParts['where']) == 1) ? substr($where, 1, -1) : $where); } @@ -1325,7 +1343,7 @@ public function buildSqlQuery($limitSubquery = true) // Add the default orderBy statements defined in the relationships and table classes // Only do this for SELECT queries - if ($this->_type === self::SELECT) { + if (self::SELECT === $this->_type) { foreach ($this->_queryComponents as $alias => $map) { $sqlAlias = $this->getSqlTableAlias($alias); if (isset($map['relation'])) { @@ -1345,7 +1363,7 @@ public function buildSqlQuery($limitSubquery = true) $e = explode(',', $orderBy); foreach ($e as $v) { $v = trim($v); - if ( ! in_array($v, $this->_sqlParts['orderby'])) { + if (!in_array($v, $this->_sqlParts['orderby'])) { $this->_sqlParts['orderby'][] = $v; } } @@ -1353,15 +1371,15 @@ public function buildSqlQuery($limitSubquery = true) } } - $q .= ( ! empty($this->_sqlParts['groupby'])) ? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : ''; - $q .= ( ! empty($this->_sqlParts['having'])) ? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']): ''; - $q .= ( ! empty($this->_sqlParts['orderby'])) ? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : ''; + $q .= (!empty($this->_sqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_sqlParts['groupby']) : ''; + $q .= (!empty($this->_sqlParts['having'])) ? ' HAVING '.implode(' AND ', $this->_sqlParts['having']) : ''; + $q .= (!empty($this->_sqlParts['orderby'])) ? ' ORDER BY '.implode(', ', $this->_sqlParts['orderby']) : ''; if ($modifyLimit) { $q = $this->_conn->modifyLimitQuery($q, $this->_sqlParts['limit'], $this->_sqlParts['offset'], false, false, $this); } - $q .= $this->_sqlParts['forUpdate'] === true ? ' FOR UPDATE ' : ''; + $q .= true === $this->_sqlParts['forUpdate'] ? ' FOR UPDATE ' : ''; $this->_sql = $q; @@ -1372,13 +1390,14 @@ public function buildSqlQuery($limitSubquery = true) /** * getLimitSubquery - * this is method is used by the record limit algorithm + * this is method is used by the record limit algorithm. * * when fetching one-to-many, many-to-many associated data with LIMIT clause * an additional subquery is needed for limiting the number of returned records instead * of limiting the number of sql result set rows * - * @return string the limit subquery + * @return string the limit subquery + * * @todo A little refactor to make the method easier to understand & maybe shorter? */ public function getLimitSubquery() @@ -1390,12 +1409,12 @@ public function getLimitSubquery() // get short alias $alias = $this->getSqlTableAlias($componentAlias); // what about composite keys? - $primaryKey = $alias . '.' . $table->getColumnName($table->getIdentifier()); + $primaryKey = $alias.'.'.$table->getColumnName($table->getIdentifier()); $driverName = $this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME); // initialize the base of the subquery - if (($driverName == 'oracle' || $driverName == 'oci' || $driverName == 'oci8') && $this->_isOrderedByJoinedColumn()) { + if (('oracle' == $driverName || 'oci' == $driverName || 'oci8' == $driverName) && $this->_isOrderedByJoinedColumn()) { $subquery = 'SELECT '; } else { $subquery = 'SELECT DISTINCT '; @@ -1403,12 +1422,12 @@ public function getLimitSubquery() $subquery .= $this->_conn->quoteIdentifier($primaryKey); // pgsql & oracle need the order by fields to be preserved in select clause - if ($driverName == 'pgsql' || $driverName == 'oracle' || $driverName == 'oci' || $driverName == 'oci8' || $driverName == 'mssql' || $driverName == 'odbc') { + if ('pgsql' == $driverName || 'oracle' == $driverName || 'oci' == $driverName || 'oci8' == $driverName || 'mssql' == $driverName || 'odbc' == $driverName) { foreach ($this->_sqlParts['orderby'] as $part) { // Remove identifier quoting if it exists $e = $this->_tokenizer->bracketExplode($part, ' '); foreach ($e as $f) { - if ($f == 0 || (int) $f % 2 == 0) { + if (0 == $f || 0 == (int) $f % 2) { $partOriginal = str_replace(',', '', trim($f)); $e = explode('.', $partOriginal); foreach ($e as &$v) { @@ -1416,18 +1435,18 @@ public function getLimitSubquery() } $part = trim(implode('.', $e)); - if (strpos($part, '.') === false) { + if (false === strpos($part, '.')) { continue; } // don't add functions - if (strpos($part, '(') !== false) { + if (false !== strpos($part, '(')) { continue; } // don't add primarykey column (its already in the select clause) if ($part !== $primaryKey) { - $subquery .= ', ' . $partOriginal; + $subquery .= ', '.$partOriginal; } } } @@ -1436,10 +1455,10 @@ public function getLimitSubquery() $orderby = $this->_sqlParts['orderby']; $having = $this->_sqlParts['having']; - if ($driverName == 'mysql' || $driverName == 'pgsql') { + if ('mysql' == $driverName || 'pgsql' == $driverName) { foreach ($this->_expressionMap as $dqlAlias => $expr) { if (isset($expr[1])) { - $subquery .= ', ' . $expr[0] . ' AS ' . $this->_aggregateAliasMap[$dqlAlias]; + $subquery .= ', '.$expr[0].' AS '.$this->_aggregateAliasMap[$dqlAlias]; } } } else { @@ -1461,14 +1480,14 @@ public function getLimitSubquery() // Add having fields that got stripped out of select preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', implode(' ', $having), $matches, PREG_PATTERN_ORDER); if (count($matches[0]) > 0) { - $subquery .= ', ' . implode(', ', array_unique($matches[0])); + $subquery .= ', '.implode(', ', array_unique($matches[0])); } $subquery .= ' FROM'; foreach ($this->_sqlParts['from'] as $part) { // preserve LEFT JOINs only if needed - if (substr($part, 0, 9) === 'LEFT JOIN') { + if ('LEFT JOIN' === substr($part, 0, 9)) { $e = explode(' ', $part); // Fix for http://www.doctrine-project.org/jira/browse/DC-706 // Fix for http://www.doctrine-project.org/jira/browse/DC-594 @@ -1477,26 +1496,26 @@ public function getLimitSubquery() } } - $subquery .= ' ' . $part; + $subquery .= ' '.$part; } // all conditions must be preserved in subquery - $subquery .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' ', $this->_sqlParts['where']) : ''; - $subquery .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : ''; - $subquery .= ( ! empty($having))? ' HAVING ' . implode(' AND ', $having) : ''; - $subquery .= ( ! empty($orderby))? ' ORDER BY ' . implode(', ', $orderby) : ''; + $subquery .= (!empty($this->_sqlParts['where'])) ? ' WHERE '.implode(' ', $this->_sqlParts['where']) : ''; + $subquery .= (!empty($this->_sqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_sqlParts['groupby']) : ''; + $subquery .= (!empty($having)) ? ' HAVING '.implode(' AND ', $having) : ''; + $subquery .= (!empty($orderby)) ? ' ORDER BY '.implode(', ', $orderby) : ''; - if (($driverName == 'oracle' || $driverName == 'oci' || $driverName == 'oci8') && $this->_isOrderedByJoinedColumn()) { + if (('oracle' == $driverName || 'oci' == $driverName || 'oci8' == $driverName) && $this->_isOrderedByJoinedColumn()) { // When using "ORDER BY x.foo" where x.foo is a column of a joined table, // we may get duplicate primary keys because all columns in ORDER BY must appear // in the SELECT list when using DISTINCT. Hence we need to filter out the // primary keys with an additional DISTINCT subquery. // #1038 $quotedIdentifierColumnName = $this->_conn->quoteIdentifier($table->getColumnName($table->getIdentifier())); - $subquery = 'SELECT doctrine_subquery_alias.' . $quotedIdentifierColumnName - . ' FROM (' . $subquery . ') doctrine_subquery_alias' - . ' GROUP BY doctrine_subquery_alias.' . $quotedIdentifierColumnName - . ' ORDER BY MIN(ROWNUM)'; + $subquery = 'SELECT doctrine_subquery_alias.'.$quotedIdentifierColumnName + .' FROM ('.$subquery.') doctrine_subquery_alias' + .' GROUP BY doctrine_subquery_alias.'.$quotedIdentifierColumnName + .' ORDER BY MIN(ROWNUM)'; } // add driver specific limit clause @@ -1505,11 +1524,11 @@ public function getLimitSubquery() $parts = $this->_tokenizer->quoteExplode($subquery, ' ', "'", "'"); foreach ($parts as $k => $part) { - if (strpos($part, ' ') !== false) { + if (false !== strpos($part, ' ')) { continue; } - $part = str_replace(array('"', "'", '`'), "", $part); + $part = str_replace(array('"', "'", '`'), '', $part); // Fix DC-645, Table aliases ending with ')' where not replaced properly preg_match('/^(\(?)(.*?)(\)?)$/', $part, $matches); @@ -1518,11 +1537,11 @@ public function getLimitSubquery() continue; } - if (strpos($part, '.') === false) { + if (false === strpos($part, '.')) { continue; } - preg_match_all("/[a-zA-Z0-9_]+\.[a-z0-9_]+/i", $part, $m); + preg_match_all('/[a-zA-Z0-9_]+\\.[a-z0-9_]+/i', $part, $m); foreach ($m[0] as $match) { $e = explode('.', $match); @@ -1530,7 +1549,7 @@ public function getLimitSubquery() // Rebuild the original part without the newly generate alias and with quoting reapplied $e2 = array(); foreach ($e as $k2 => $v2) { - $e2[$k2] = $this->_conn->quoteIdentifier($v2); + $e2[$k2] = $this->_conn->quoteIdentifier($v2); } $match = implode('.', $e2); @@ -1539,26 +1558,26 @@ public function getLimitSubquery() // Requote the part with the newly generated alias foreach ($e as $k2 => $v2) { - $e[$k2] = $this->_conn->quoteIdentifier($v2); + $e[$k2] = $this->_conn->quoteIdentifier($v2); } - $replace = implode('.' , $e); + $replace = implode('.', $e); // Replace the original part with the new part with new sql table alias $parts[$k] = str_replace($match, $replace, $parts[$k]); } } - if ($driverName == 'mysql' || $driverName == 'pgsql') { + if ('mysql' == $driverName || 'pgsql' == $driverName) { foreach ($parts as $k => $part) { - if (strpos($part, "'") !== false) { + if (false !== strpos($part, "'")) { continue; } - if (strpos($part, '__') == false) { + if (false == strpos($part, '__')) { continue; } - preg_match_all("/[a-zA-Z0-9_]+\_\_[a-z0-9_]+/i", $part, $m); + preg_match_all('/[a-zA-Z0-9_]+\\_\\_[a-z0-9_]+/i', $part, $m); foreach ($m[0] as $match) { $e = explode('__', $match); @@ -1570,6 +1589,7 @@ public function getLimitSubquery() } $subquery = implode(' ', $parts); + return $subquery; } @@ -1578,12 +1598,12 @@ public function getLimitSubquery() * This information is needed in special scenarios like the limit-offset when its * used with an Oracle database. * - * @return boolean TRUE if the query is ordered by a joined column, FALSE otherwise. + * @return bool TRUE if the query is ordered by a joined column, FALSE otherwise */ - private function _isOrderedByJoinedColumn() { - if ( ! $this->_queryComponents) { - throw new Doctrine_Query_Exception("The query is in an invalid state for this " - . "operation. It must have been fully parsed first."); + private function _isOrderedByJoinedColumn() + { + if (!$this->_queryComponents) { + throw new Doctrine_Query_Exception('The query is in an invalid state for this operation. It must have been fully parsed first.'); } $componentAlias = key($this->_queryComponents); $mainTableAlias = $this->getSqlTableAlias($componentAlias); @@ -1591,7 +1611,7 @@ private function _isOrderedByJoinedColumn() { $part = trim($part); $e = $this->_tokenizer->bracketExplode($part, ' '); $part = trim($e[0]); - if (strpos($part, '.') === false) { + if (false === strpos($part, '.')) { continue; } list($tableAlias, $columnName) = explode('.', $part); @@ -1599,6 +1619,7 @@ private function _isOrderedByJoinedColumn() { return true; } } + return false; } @@ -1606,12 +1627,14 @@ private function _isOrderedByJoinedColumn() { * DQL PARSER * parses a DQL query * first splits the query in parts and then uses individual - * parsers for each part + * parsers for each part. + * + * @param string $query DQL query + * @param bool $clear whether or not to clear the aliases * - * @param string $query DQL query - * @param boolean $clear whether or not to clear the aliases - * @throws Doctrine_Query_Exception if some generic parsing error occurs * @return Doctrine_Query + * + * @throws Doctrine_Query_Exception if some generic parsing error occurs */ public function parseDqlQuery($query, $clear = true) { @@ -1631,35 +1654,37 @@ public function parseDqlQuery($query, $clear = true) switch ($partName) { case 'create': $this->_type = self::CREATE; - break; + break; case 'insert': $this->_type = self::INSERT; - break; + break; case 'delete': $this->_type = self::DELETE; - break; + break; case 'select': $this->_type = self::SELECT; $this->_addDqlQueryPart($partName, $subParts); - break; + break; case 'update': $this->_type = self::UPDATE; $partName = 'from'; + // no break case 'from': $this->_addDqlQueryPart($partName, $subParts); - break; + break; case 'set': $this->_addDqlQueryPart($partName, $subParts, true); - break; + break; case 'group': case 'order': $partName .= 'by'; + // no break case 'where': case 'having': case 'limit': case 'offset': $this->_addDqlQueryPart($partName, $subParts); - break; + break; } } @@ -1668,8 +1693,9 @@ public function parseDqlQuery($query, $clear = true) /** * @todo Describe & refactor... too long and nested. - * @param string $path component alias - * @param boolean $loadFields + * + * @param string $path component alias + * @param bool $loadFields */ public function load($path, $loadFields = true) { @@ -1707,10 +1733,10 @@ public function load($path, $loadFields = true) $overrideJoin = false; } - $tmp = explode(' ', $path); + $tmp = explode(' ', $path); $componentAlias = $originalAlias = (count($tmp) > 1) ? end($tmp) : null; - $e = preg_split("/[.:]/", $tmp[0], -1); + $e = preg_split('/[.:]/', $tmp[0], -1); $fullPath = $tmp[0]; $prevPath = ''; @@ -1728,7 +1754,7 @@ public function load($path, $loadFields = true) $length = strlen($prevPath); // build the current component path - $prevPath = ($prevPath) ? $prevPath . '.' . $name : $name; + $prevPath = ($prevPath) ? $prevPath.'.'.$name : $name; $delimeter = substr($fullPath, $length, 1); @@ -1741,39 +1767,39 @@ public function load($path, $loadFields = true) // if the current alias already exists, skip it if (isset($this->_queryComponents[$componentAlias])) { - throw new Doctrine_Query_Exception("Duplicate alias '$componentAlias' in query."); + throw new Doctrine_Query_Exception("Duplicate alias '{$componentAlias}' in query."); } - if ( ! isset($table)) { + if (!isset($table)) { // process the root of the path $table = $this->loadRoot($name, $componentAlias); } else { - $join = ($delimeter == ':') ? 'INNER JOIN ' : 'LEFT JOIN '; + $join = (':' == $delimeter) ? 'INNER JOIN ' : 'LEFT JOIN '; $relation = $table->getRelation($name); $localTable = $table; $table = $relation->getTable(); $this->_queryComponents[$componentAlias] = array('table' => $table, - 'parent' => $parent, - 'relation' => $relation, - 'map' => null); + 'parent' => $parent, + 'relation' => $relation, + 'map' => null); // Fix for http://www.doctrine-project.org/jira/browse/DC-701 - if ( ! $relation->isOneToOne() && ! $this->disableLimitSubquery) { + if (!$relation->isOneToOne() && !$this->disableLimitSubquery) { $this->_needsSubquery = true; } - $localAlias = $this->getSqlTableAlias($parent, $localTable->getTableName()); + $localAlias = $this->getSqlTableAlias($parent, $localTable->getTableName()); $foreignAlias = $this->getSqlTableAlias($componentAlias, $relation->getTable()->getTableName()); - $foreignSql = $this->_conn->quoteIdentifier($relation->getTable()->getTableName()) - . ' ' - . $this->_conn->quoteIdentifier($foreignAlias); + $foreignSql = $this->_conn->quoteIdentifier($relation->getTable()->getTableName()) + .' ' + .$this->_conn->quoteIdentifier($foreignAlias); $map = $relation->getTable()->inheritanceMap; - if ( ! $loadFields || ! empty($map) || $joinCondition) { + if (!$loadFields || !empty($map) || $joinCondition) { $this->_subqueryAliases[] = $foreignAlias; } @@ -1782,11 +1808,11 @@ public function load($path, $loadFields = true) $assocTableName = $asf->getTableName(); - if ( ! $loadFields || ! empty($map) || $joinCondition) { + if (!$loadFields || !empty($map) || $joinCondition) { $this->_subqueryAliases[] = $assocTableName; } - $assocPath = $prevPath . '.' . $asf->getComponentName() . ' ' . $componentAlias; + $assocPath = $prevPath.'.'.$asf->getComponentName().' '.$componentAlias; $this->_queryComponents[$assocPath] = array( 'parent' => $prevPath, @@ -1797,33 +1823,33 @@ public function load($path, $loadFields = true) $assocAlias = $this->getSqlTableAlias($assocPath, $asf->getTableName()); $queryPart = $join - . $this->_conn->quoteIdentifier($assocTableName) - . ' ' - . $this->_conn->quoteIdentifier($assocAlias); + .$this->_conn->quoteIdentifier($assocTableName) + .' ' + .$this->_conn->quoteIdentifier($assocAlias); - $queryPart .= ' ON (' . $this->_conn->quoteIdentifier($localAlias - . '.' - . $localTable->getColumnName($localTable->getIdentifier())) // what about composite keys? - . ' = ' - . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getLocalRefColumnName()); + $queryPart .= ' ON ('.$this->_conn->quoteIdentifier($localAlias + .'.' + .$localTable->getColumnName($localTable->getIdentifier())) // what about composite keys? + .' = ' + .$this->_conn->quoteIdentifier($assocAlias.'.'.$relation->getLocalRefColumnName()); if ($relation->isEqual()) { // equal nest relation needs additional condition $queryPart .= ' OR ' - . $this->_conn->quoteIdentifier($localAlias - . '.' - . $table->getColumnName($table->getIdentifier())) - . ' = ' - . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getForeignRefColumnName()); + .$this->_conn->quoteIdentifier($localAlias + .'.' + .$table->getColumnName($table->getIdentifier())) + .' = ' + .$this->_conn->quoteIdentifier($assocAlias.'.'.$relation->getForeignRefColumnName()); } $queryPart .= ')'; $this->_sqlParts['from'][] = $queryPart; - $queryPart = $join . $foreignSql; + $queryPart = $join.$foreignSql; - if ( ! $overrideJoin) { + if (!$overrideJoin) { $queryPart .= $this->buildAssociativeRelationSql($relation, $assocAlias, $foreignAlias, $localAlias); } } else { @@ -1833,7 +1859,7 @@ public function load($path, $loadFields = true) $queryPart .= $this->buildInheritanceJoinSql($table->getComponentName(), $componentAlias); $this->_sqlParts['from'][$componentAlias] = $queryPart; - if ( ! empty($joinCondition)) { + if (!empty($joinCondition)) { $this->addPendingJoinCondition($componentAlias, $joinCondition); } } @@ -1857,15 +1883,15 @@ public function load($path, $loadFields = true) protected function buildSimpleRelationSql(Doctrine_Relation $relation, $foreignAlias, $localAlias, $overrideJoin, $join) { - $queryPart = $join . $this->_conn->quoteIdentifier($relation->getTable()->getTableName()) - . ' ' - . $this->_conn->quoteIdentifier($foreignAlias); + $queryPart = $join.$this->_conn->quoteIdentifier($relation->getTable()->getTableName()) + .' ' + .$this->_conn->quoteIdentifier($foreignAlias); - if ( ! $overrideJoin) { + if (!$overrideJoin) { $queryPart .= ' ON ' - . $this->_conn->quoteIdentifier($localAlias . '.' . $relation->getLocalColumnName()) - . ' = ' - . $this->_conn->quoteIdentifier($foreignAlias . '.' . $relation->getForeignColumnName()); + .$this->_conn->quoteIdentifier($localAlias.'.'.$relation->getLocalColumnName()) + .' = ' + .$this->_conn->quoteIdentifier($foreignAlias.'.'.$relation->getForeignColumnName()); } return $queryPart; @@ -1881,19 +1907,19 @@ protected function buildIndexBy($componentAlias, $mapWith = null) if (isset($mapWith)) { $terms = explode('.', $mapWith); - if (count($terms) == 1) { + if (1 == count($terms)) { $indexBy = $terms[0]; - } else if (count($terms) == 2) { + } elseif (2 == count($terms)) { $column = true; $indexBy = $terms[1]; } - } else if ($table->getBoundQueryPart('indexBy') !== null) { + } elseif (null !== $table->getBoundQueryPart('indexBy')) { $indexBy = $table->getBoundQueryPart('indexBy'); } - if ($indexBy !== null) { - if ( $column && ! $table->hasColumn($table->getColumnName($indexBy))) { - throw new Doctrine_Query_Exception("Couldn't use key mapping. Column " . $indexBy . " does not exist."); + if (null !== $indexBy) { + if ($column && !$table->hasColumn($table->getColumnName($indexBy))) { + throw new Doctrine_Query_Exception("Couldn't use key mapping. Column ".$indexBy.' does not exist.'); } $this->_queryComponents[$componentAlias]['map'] = $indexBy; @@ -1902,7 +1928,6 @@ protected function buildIndexBy($componentAlias, $mapWith = null) return $this->_queryComponents[$componentAlias]; } - protected function buildAssociativeRelationSql(Doctrine_Relation $relation, $assocAlias, $foreignAlias, $localAlias) { $table = $relation->getTable(); @@ -1915,30 +1940,32 @@ protected function buildAssociativeRelationSql(Doctrine_Relation $relation, $ass $localIdentifier = $table->getColumnName($table->getIdentifier()); - $queryPart .= $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier) - . ' = ' - . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getForeignRefColumnName()); + $queryPart .= $this->_conn->quoteIdentifier($foreignAlias.'.'.$localIdentifier) + .' = ' + .$this->_conn->quoteIdentifier($assocAlias.'.'.$relation->getForeignRefColumnName()); if ($relation->isEqual()) { $queryPart .= ' OR ' - . $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier) - . ' = ' - . $this->_conn->quoteIdentifier($assocAlias . '.' . $relation->getLocalRefColumnName()) - . ') AND ' - . $this->_conn->quoteIdentifier($foreignAlias . '.' . $localIdentifier) - . ' != ' - . $this->_conn->quoteIdentifier($localAlias . '.' . $localIdentifier); + .$this->_conn->quoteIdentifier($foreignAlias.'.'.$localIdentifier) + .' = ' + .$this->_conn->quoteIdentifier($assocAlias.'.'.$relation->getLocalRefColumnName()) + .') AND ' + .$this->_conn->quoteIdentifier($foreignAlias.'.'.$localIdentifier) + .' != ' + .$this->_conn->quoteIdentifier($localAlias.'.'.$localIdentifier); } return $queryPart; } /** - * loadRoot + * loadRoot. * * @param string $name * @param string $componentAlias + * * @return Doctrine_Table + * * @todo DESCRIBE ME! * @todo this method is called only in Doctrine_Query class. Shouldn't be private or protected? */ @@ -1946,7 +1973,7 @@ public function loadRoot($name, $componentAlias) { // get the connection for the component $manager = Doctrine_Manager::getInstance(); - if ( ! $this->_passedConn && $manager->hasConnectionForComponent($name)) { + if (!$this->_passedConn && $manager->hasConnectionForComponent($name)) { $this->_conn = $manager->getConnectionForComponent($name); } @@ -1958,8 +1985,8 @@ public function loadRoot($name, $componentAlias) // quote table name $queryPart = $this->_conn->quoteIdentifier($tableName); - if ($this->_type === self::SELECT) { - $queryPart .= ' ' . $this->_conn->quoteIdentifier($tableAlias); + if (self::SELECT === $this->_type) { + $queryPart .= ' '.$this->_conn->quoteIdentifier($tableAlias); } $this->_tableAliasMap[$tableAlias] = $componentAlias; @@ -1975,15 +2002,17 @@ public function loadRoot($name, $componentAlias) /** * @todo DESCRIBE ME! - * @param string $name component class name - * @param string $componentAlias alias of the component in the dql - * @return string query part + * + * @param string $name component class name + * @param string $componentAlias alias of the component in the dql + * + * @return string query part */ public function buildInheritanceJoinSql($name, $componentAlias) { // get the connection for the component $manager = Doctrine_Manager::getInstance(); - if ( ! $this->_passedConn && $manager->hasConnectionForComponent($name)) { + if (!$this->_passedConn && $manager->hasConnectionForComponent($name)) { $this->_conn = $manager->getConnectionForComponent($name); } @@ -1998,22 +2027,22 @@ public function buildInheritanceJoinSql($name, $componentAlias) foreach ($table->getOption('joinedParents') as $parent) { $parentTable = $this->_conn->getTable($parent); - $parentAlias = $componentAlias . '.' . $parent; + $parentAlias = $componentAlias.'.'.$parent; // get the short alias for the parent table $parentTableAlias = $this->getSqlTableAlias($parentAlias, $parentTable->getTableName()); - $queryPart .= ' LEFT JOIN ' . $this->_conn->quoteIdentifier($parentTable->getTableName()) - . ' ' . $this->_conn->quoteIdentifier($parentTableAlias) . ' ON '; + $queryPart .= ' LEFT JOIN '.$this->_conn->quoteIdentifier($parentTable->getTableName()) + .' '.$this->_conn->quoteIdentifier($parentTableAlias).' ON '; - //Doctrine_Core::dump($table->getIdentifier()); + // Doctrine_Core::dump($table->getIdentifier()); foreach ((array) $table->getIdentifier() as $identifier) { $column = $table->getColumnName($identifier); $queryPart .= $this->_conn->quoteIdentifier($tableAlias) - . '.' . $this->_conn->quoteIdentifier($column) - . ' = ' . $this->_conn->quoteIdentifier($parentTableAlias) - . '.' . $this->_conn->quoteIdentifier($column); + .'.'.$this->_conn->quoteIdentifier($column) + .' = '.$this->_conn->quoteIdentifier($parentTableAlias) + .'.'.$this->_conn->quoteIdentifier($column); } } @@ -2034,31 +2063,31 @@ public function getCountSqlQuery() $this->getSqlQuery(array(), false); // this is ugly // initialize temporary variables - $where = $this->_sqlParts['where']; - $having = $this->_sqlParts['having']; + $where = $this->_sqlParts['where']; + $having = $this->_sqlParts['having']; $groupby = $this->_sqlParts['groupby']; $rootAlias = $this->getRootAlias(); $tableAlias = $this->getSqlTableAlias($rootAlias); // Build the query base - $q = 'SELECT COUNT(*) AS ' . $this->_conn->quoteIdentifier('num_results') . ' FROM '; + $q = 'SELECT COUNT(*) AS '.$this->_conn->quoteIdentifier('num_results').' FROM '; // Build the from clause $from = $this->_buildSqlFromPart(true); // Build the where clause - $where = ( ! empty($where)) ? ' WHERE ' . implode(' ', $where) : ''; + $where = (!empty($where)) ? ' WHERE '.implode(' ', $where) : ''; // Build the group by clause - $groupby = ( ! empty($groupby)) ? ' GROUP BY ' . implode(', ', $groupby) : ''; + $groupby = (!empty($groupby)) ? ' GROUP BY '.implode(', ', $groupby) : ''; // Build the having clause - $having = ( ! empty($having)) ? ' HAVING ' . implode(' AND ', $having) : ''; + $having = (!empty($having)) ? ' HAVING '.implode(' AND ', $having) : ''; // Building the from clause and finishing query - if (count($this->_queryComponents) == 1 && empty($having)) { - $q .= $from . $where . $groupby . $having; + if (1 == count($this->_queryComponents) && empty($having)) { + $q .= $from.$where.$groupby.$having; } else { // Subselect fields will contain only the pk of root entity $ta = $this->_conn->quoteIdentifier($tableAlias); @@ -2066,34 +2095,34 @@ public function getCountSqlQuery() $map = $this->getRootDeclaration(); $idColumnNames = $map['table']->getIdentifierColumnNames(); - $pkFields = $ta . '.' . implode(', ' . $ta . '.', $this->_conn->quoteMultipleIdentifier($idColumnNames)); + $pkFields = $ta.'.'.implode(', '.$ta.'.', $this->_conn->quoteMultipleIdentifier($idColumnNames)); // We need to do some magic in select fields if the query contain anything in having clause $selectFields = $pkFields; - if ( ! empty($having)) { + if (!empty($having)) { // For each field defined in select clause foreach ($this->_sqlParts['select'] as $field) { // We only include aggregate expressions to count query // This is needed because HAVING clause will use field aliases - if (strpos($field, '(') !== false) { - $selectFields .= ', ' . $field; + if (false !== strpos($field, '(')) { + $selectFields .= ', '.$field; } } // Add having fields that got stripped out of select preg_match_all('/`[a-z0-9_]+`\.`[a-z0-9_]+`/i', $having, $matches, PREG_PATTERN_ORDER); if (count($matches[0]) > 0) { - $selectFields .= ', ' . implode(', ', array_unique($matches[0])); + $selectFields .= ', '.implode(', ', array_unique($matches[0])); } } // If we do not have a custom group by, apply the default one if (empty($groupby)) { - $groupby = ' GROUP BY ' . $pkFields; + $groupby = ' GROUP BY '.$pkFields; } - $q .= '(SELECT ' . $selectFields . ' FROM ' . $from . $where . $groupby . $having . ') ' - . $this->_conn->quoteIdentifier('dctrn_count_query'); + $q .= '(SELECT '.$selectFields.' FROM '.$from.$where.$groupby.$having.') ' + .$this->_conn->quoteIdentifier('dctrn_count_query'); } return $q; @@ -2116,10 +2145,11 @@ public function getCountSqlQuery() * LEFT JOIN u.Phonenumber p * WHERE p.phonenumber = '123 123' * - * @param array $params an array of prepared statement parameters - * @return integer the count of this query + * @param array $params an array of prepared statement parameters + * + * @return int the count of this query */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count($params = array()) { $q = $this->getCountSqlQuery(); @@ -2132,7 +2162,7 @@ public function count($params = array()) $hash = $this->getResultCacheHash($params).'_count'; $cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash); - if ($cached === false) { + if (false === $cached) { // cache miss $results = $this->getConnection()->fetchAll($q, $params); $cacheDriver->save($hash, serialize($results), $this->getResultCacheLifeSpan()); @@ -2162,38 +2192,35 @@ public function count($params = array()) * * This methods parses a Dql query and builds the query parts. * - * @param string $query Dql query - * @param array $params prepared statement parameters - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string $query Dql query + * @param array $params prepared statement parameters + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @see Doctrine_Core::FETCH_* constants - * @return mixed */ public function query($query, $params = array(), $hydrationMode = null) { $this->parseDqlQuery($query); + return $this->execute($params, $hydrationMode); } /** * Copies a Doctrine_Query object. * - * @return Doctrine_Query Copy of the Doctrine_Query instance. + * @return Doctrine_Query copy of the Doctrine_Query instance */ public function copy(Doctrine_Query $query = null) { - if ( ! $query) { + if (!$query) { $query = $this; } - $new = clone $query; - - return $new; + return clone $query; } /** * Magic method called after cloning process. - * - * @return void */ public function __clone() { @@ -2213,15 +2240,15 @@ public function __clone() /** * Kill the reference for the passed class property. * This method simply copies the value to a temporary variable and then unsets - * the reference and re-assigns the old value but not by reference + * the reference and re-assigns the old value but not by reference. * * @param string $key */ protected function _killReference($key) { - $tmp = $this->$key; - unset($this->$key); - $this->$key = $tmp; + $tmp = $this->{$key}; + unset($this->{$key}); + $this->{$key} = $tmp; } /** @@ -2231,7 +2258,7 @@ protected function _killReference($key) * This method can therefore be used to reduce memory usage when creating * a lot of query objects during a request. * - * @return Doctrine_Query this object + * @return Doctrine_Query this object */ public function free() { diff --git a/lib/Doctrine/Query/Abstract.php b/lib/Doctrine/Query/Abstract.php index 247886f1c..b8c8f2950 100644 --- a/lib/Doctrine/Query/Abstract.php +++ b/lib/Doctrine/Query/Abstract.php @@ -20,131 +20,133 @@ */ /** - * Doctrine_Query_Abstract + * Doctrine_Query_Abstract. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1393 $ + * * @author Konsta Vesterinen + * * @todo See {@link Doctrine_Query} */ abstract class Doctrine_Query_Abstract { /** - * QUERY TYPE CONSTANTS + * QUERY TYPE CONSTANTS. */ /** - * constant for SELECT queries + * constant for SELECT queries. */ - const SELECT = 0; + public const SELECT = 0; /** - * constant for DELETE queries + * constant for DELETE queries. */ - const DELETE = 1; + public const DELETE = 1; /** - * constant for UPDATE queries + * constant for UPDATE queries. */ - const UPDATE = 2; + public const UPDATE = 2; /** - * constant for INSERT queries + * constant for INSERT queries. */ - const INSERT = 3; + public const INSERT = 3; /** - * constant for CREATE queries + * constant for CREATE queries. */ - const CREATE = 4; + public const CREATE = 4; /** @todo document the query states (and the transitions between them). */ /** * A query object is in CLEAN state when it has NO unparsed/unprocessed DQL parts. */ - const STATE_CLEAN = 1; + public const STATE_CLEAN = 1; /** * A query object is in state DIRTY when it has DQL parts that have not yet been * parsed/processed. */ - const STATE_DIRTY = 2; + public const STATE_DIRTY = 2; /** * A query is in DIRECT state when ... ? */ - const STATE_DIRECT = 3; + public const STATE_DIRECT = 3; /** * A query object is on LOCKED state when ... ? */ - const STATE_LOCKED = 4; + public const STATE_LOCKED = 4; /** - * @var array Table alias map. Keys are SQL aliases and values DQL aliases. + * @var array Table alias map. Keys are SQL aliases and values DQL aliases. */ protected $_tableAliasMap = array(); /** - * @var Doctrine_View The view object used by this query, if any. + * @var Doctrine_View the view object used by this query, if any */ protected $_view; /** - * @var integer $_state The current state of this query. + * @var int the current state of this query */ protected $_state = self::STATE_CLEAN; /** - * @var array $_params The parameters of this query. + * @var array the parameters of this query */ protected $_params = array('exec' => array(), - 'join' => array(), - 'where' => array(), - 'set' => array(), - 'having' => array()); + 'join' => array(), + 'where' => array(), + 'set' => array(), + 'having' => array()); /** - * @var array $_execParams The parameters passed to connection statement + * @var array The parameters passed to connection statement */ protected $_execParams = array(); /* Caching properties */ /** - * @var Doctrine_Cache_Interface The cache driver used for caching result sets. + * @var Doctrine_Cache_Interface the cache driver used for caching result sets */ protected $_resultCache; /** - * @var string Key to use for result cache entry in the cache driver + * @var string Key to use for result cache entry in the cache driver */ protected $_resultCacheHash; /** - * @var boolean $_expireResultCache A boolean value that indicates whether or not - * expire the result cache. + * @var bool a boolean value that indicates whether or not + * expire the result cache */ protected $_expireResultCache = false; protected $_resultCacheTTL; /** - * @var Doctrine_Cache_Interface The cache driver used for caching queries. + * @var Doctrine_Cache_Interface the cache driver used for caching queries */ protected $_queryCache; protected $_expireQueryCache = false; protected $_queryCacheTTL; /** - * @var boolean $_autoFree A boolean value that indicates whether or not use auto free. + * @var bool a boolean value that indicates whether or not use auto free */ protected $_autoFree = false; /** - * @var Doctrine_Connection The connection used by this query object. + * @var Doctrine_Connection the connection used by this query object */ protected $_conn; @@ -154,45 +156,44 @@ abstract class Doctrine_Query_Abstract protected $_passedConn = false; /** - * @var array $_sqlParts The SQL query string parts. Filled during the DQL parsing process. + * @var array The SQL query string parts. Filled during the DQL parsing process. */ protected $_sqlParts = array( - 'select' => array(), - 'distinct' => false, - 'forUpdate' => false, - 'from' => array(), - 'set' => array(), - 'join' => array(), - 'where' => array(), - 'groupby' => array(), - 'having' => array(), - 'orderby' => array(), - 'limit' => false, - 'offset' => false, - ); + 'select' => array(), + 'distinct' => false, + 'forUpdate' => false, + 'from' => array(), + 'set' => array(), + 'join' => array(), + 'where' => array(), + 'groupby' => array(), + 'having' => array(), + 'orderby' => array(), + 'limit' => false, + 'offset' => false, + ); /** - * @var array $_dqlParts an array containing all DQL query parts; @see Doctrine_Query::getDqlPart() + * @var array an array containing all DQL query parts; @see Doctrine_Query::getDqlPart() */ protected $_dqlParts = array( - 'from' => array(), - 'select' => array(), - 'forUpdate' => false, - 'set' => array(), - 'join' => array(), - 'where' => array(), - 'groupby' => array(), - 'having' => array(), - 'orderby' => array(), - 'limit' => array(), - 'offset' => array(), - ); - + 'from' => array(), + 'select' => array(), + 'forUpdate' => false, + 'set' => array(), + 'join' => array(), + 'where' => array(), + 'groupby' => array(), + 'having' => array(), + 'orderby' => array(), + 'limit' => array(), + 'offset' => array(), + ); /** - * @var array $_queryComponents Two dimensional array containing the components of this query, - * informations about their relations and other related information. - * The components are constructed during query parsing. + * @var array Two dimensional array containing the components of this query, + * informations about their relations and other related information. + * The components are constructed during query parsing. * * Keys are component aliases and values the following: * @@ -219,51 +220,51 @@ abstract class Doctrine_Query_Abstract */ protected $_queryComponents = array(); - /** - * Stores the root DQL alias + /** + * Stores the root DQL alias. * * @var string */ protected $_rootAlias = ''; /** - * @var integer $type the query type + * @var int the query type * * @see Doctrine_Query::* constants */ protected $_type = self::SELECT; /** - * @var Doctrine_Hydrator The hydrator object used to hydrate query results. + * @var Doctrine_Hydrator the hydrator object used to hydrate query results */ protected $_hydrator; /** - * @var Doctrine_Query_Tokenizer The tokenizer that is used during the query parsing process. + * @var Doctrine_Query_Tokenizer the tokenizer that is used during the query parsing process */ protected $_tokenizer; /** - * @var Doctrine_Query_Parser The parser that is used for query parsing. + * @var Doctrine_Query_Parser the parser that is used for query parsing */ protected $_parser; /** - * @var array $_tableAliasSeeds A simple array keys representing table aliases and values - * table alias seeds. The seeds are used for generating short table - * aliases. + * @var array A simple array keys representing table aliases and values + * table alias seeds. The seeds are used for generating short table + * aliases. */ protected $_tableAliasSeeds = array(); /** - * @var array $_options an array of options + * @var array an array of options */ - protected $_options = array( - 'hydrationMode' => Doctrine_Core::HYDRATE_RECORD + protected $_options = array( + 'hydrationMode' => Doctrine_Core::HYDRATE_RECORD, ); /** - * @var boolean + * @var bool */ protected $_isLimitSubqueryUsed = false; @@ -278,34 +279,34 @@ abstract class Doctrine_Query_Abstract protected $_preQueried = false; /** - * @var array $_pendingJoinConditions an array containing pending joins + * @var array an array containing pending joins */ protected $_pendingJoinConditions = array(); /** - * Fix for http://www.doctrine-project.org/jira/browse/DC-701 + * Fix for http://www.doctrine-project.org/jira/browse/DC-701. * - * @var bool Boolean variable for whether the limitSubquery method of accessing tables via a many relationship should be used. + * @var bool boolean variable for whether the limitSubquery method of accessing tables via a many relationship should be used */ protected $disableLimitSubquery = false; /** * Constructor. * - * @param Doctrine_Connection $connection The connection object the query will use. - * @param Doctrine_Hydrator_Abstract $hydrator The hydrator that will be used for generating result sets. + * @param Doctrine_Connection $connection the connection object the query will use + * @param Doctrine_Hydrator_Abstract $hydrator the hydrator that will be used for generating result sets * * @throws Doctrine_Connection_Exception */ public function __construct(Doctrine_Connection $connection = null, - Doctrine_Hydrator_Abstract $hydrator = null) + Doctrine_Hydrator_Abstract $hydrator = null) { - if ($connection === null) { + if (null === $connection) { $connection = Doctrine_Manager::getInstance()->getCurrentConnection(); } else { $this->_passedConn = true; } - if ($hydrator === null) { + if (null === $hydrator) { $hydrator = new Doctrine_Hydrator(); } $this->_conn = $connection; @@ -317,10 +318,7 @@ public function __construct(Doctrine_Connection $connection = null, } /** - * Set the connection this query object should use - * - * @param Doctrine_Connection $connection - * @return void + * Set the connection this query object should use. */ public function setConnection(Doctrine_Connection $connection) { @@ -329,7 +327,7 @@ public function setConnection(Doctrine_Connection $connection) } /** - * setOption + * setOption. * * @param string $name option name * @param string $value option value @@ -338,45 +336,45 @@ public function setConnection(Doctrine_Connection $connection) */ public function setOption($name, $value) { - if ( ! isset($this->_options[$name])) { - throw new Doctrine_Query_Exception('Unknown option ' . $name); + if (!isset($this->_options[$name])) { + throw new Doctrine_Query_Exception('Unknown option '.$name); } $this->_options[$name] = $value; } /** * setAutoFree - * Sets auto free + * Sets auto free. * - * @param boolean $value True or false (true by default) + * @param bool $value True or false (true by default) * * @return $this */ public function setAutoFree($value = true) { - $this->_autoFree = (boolean) $value; + $this->_autoFree = (bool) $value; return $this; } /** * hasSqlTableAlias - * whether or not this object has given tableAlias + * whether or not this object has given tableAlias. * * @param string $sqlTableAlias the table alias to be checked * - * @return boolean true if this object has given alias, otherwise false + * @return bool true if this object has given alias, otherwise false */ public function hasSqlTableAlias($sqlTableAlias) { - return (isset($this->_tableAliasMap[$sqlTableAlias])); + return isset($this->_tableAliasMap[$sqlTableAlias]); } /** * getTableAliasMap - * returns all table aliases + * returns all table aliases. * - * @return array table aliases as an array + * @return array table aliases as an array */ public function getTableAliasMap() { @@ -389,66 +387,67 @@ public function getTableAliasMap() * * the query is built from $_dqlParts * - * @return string the DQL query + * @return string the DQL query */ public function getDql() { $q = ''; - if ($this->_type == self::SELECT) { - $q .= ( ! empty($this->_dqlParts['select'])) ? 'SELECT ' . implode(', ', $this->_dqlParts['select']) : ''; - $q .= ( ! empty($this->_dqlParts['from'])) ? ' FROM ' . implode(' ', $this->_dqlParts['from']) : ''; - } else if ($this->_type == self::DELETE) { + if (self::SELECT == $this->_type) { + $q .= (!empty($this->_dqlParts['select'])) ? 'SELECT '.implode(', ', $this->_dqlParts['select']) : ''; + $q .= (!empty($this->_dqlParts['from'])) ? ' FROM '.implode(' ', $this->_dqlParts['from']) : ''; + } elseif (self::DELETE == $this->_type) { $q .= 'DELETE'; - $q .= ( ! empty($this->_dqlParts['from'])) ? ' FROM ' . implode(' ', $this->_dqlParts['from']) : ''; - } else if ($this->_type == self::UPDATE) { + $q .= (!empty($this->_dqlParts['from'])) ? ' FROM '.implode(' ', $this->_dqlParts['from']) : ''; + } elseif (self::UPDATE == $this->_type) { $q .= 'UPDATE '; - $q .= ( ! empty($this->_dqlParts['from'])) ? implode(' ', $this->_dqlParts['from']) : ''; - $q .= ( ! empty($this->_dqlParts['set'])) ? ' SET ' . implode(' ', $this->_dqlParts['set']) : ''; + $q .= (!empty($this->_dqlParts['from'])) ? implode(' ', $this->_dqlParts['from']) : ''; + $q .= (!empty($this->_dqlParts['set'])) ? ' SET '.implode(' ', $this->_dqlParts['set']) : ''; } - $q .= ( ! empty($this->_dqlParts['where'])) ? ' WHERE ' . implode(' ', $this->_dqlParts['where']) : ''; - $q .= ( ! empty($this->_dqlParts['groupby'])) ? ' GROUP BY ' . implode(', ', $this->_dqlParts['groupby']) : ''; - $q .= ( ! empty($this->_dqlParts['having'])) ? ' HAVING ' . implode(' AND ', $this->_dqlParts['having']) : ''; - $q .= ( ! empty($this->_dqlParts['orderby'])) ? ' ORDER BY ' . implode(', ', $this->_dqlParts['orderby']) : ''; - $q .= ( ! empty($this->_dqlParts['limit'])) ? ' LIMIT ' . implode(' ', $this->_dqlParts['limit']) : ''; - $q .= ( ! empty($this->_dqlParts['offset'])) ? ' OFFSET ' . implode(' ', $this->_dqlParts['offset']) : ''; + $q .= (!empty($this->_dqlParts['where'])) ? ' WHERE '.implode(' ', $this->_dqlParts['where']) : ''; + $q .= (!empty($this->_dqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_dqlParts['groupby']) : ''; + $q .= (!empty($this->_dqlParts['having'])) ? ' HAVING '.implode(' AND ', $this->_dqlParts['having']) : ''; + $q .= (!empty($this->_dqlParts['orderby'])) ? ' ORDER BY '.implode(', ', $this->_dqlParts['orderby']) : ''; + $q .= (!empty($this->_dqlParts['limit'])) ? ' LIMIT '.implode(' ', $this->_dqlParts['limit']) : ''; + $q .= (!empty($this->_dqlParts['offset'])) ? ' OFFSET '.implode(' ', $this->_dqlParts['offset']) : ''; return $q; } /** * getSqlQueryPart - * gets an SQL query part from the SQL query part array + * gets an SQL query part from the SQL query part array. * * @param string $part the name of the query part to get * - * @return mixed * @throws Doctrine_Query_Exception if trying to get an unknown query part */ public function getSqlQueryPart($part) { - if ( ! isset($this->_sqlParts[$part])) { - throw new Doctrine_Query_Exception('Unknown SQL query part ' . $part); + if (!isset($this->_sqlParts[$part])) { + throw new Doctrine_Query_Exception('Unknown SQL query part '.$part); } + return $this->_sqlParts[$part]; } /** * setSqlQueryPart - * sets an SQL query part in the SQL query part array + * sets an SQL query part in the SQL query part array. * * @param string $name the name of the query part to be set * @param string $part query part string * * @return $this this object + * * @throws Doctrine_Query_Exception if trying to set unknown query part */ public function setSqlQueryPart($name, $part) { - if ( ! isset($this->_sqlParts[$name])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $name); + if (!isset($this->_sqlParts[$name])) { + throw new Doctrine_Query_Exception('Unknown query part '.$name); } - if ($name !== 'limit' && $name !== 'offset') { + if ('limit' !== $name && 'offset' !== $name) { if (is_array($part)) { $this->_sqlParts[$name] = $part; } else { @@ -463,43 +462,46 @@ public function setSqlQueryPart($name, $part) /** * addSqlQueryPart - * adds an SQL query part to the SQL query part array + * adds an SQL query part to the SQL query part array. * * @param string $name the name of the query part to be added * @param string $part query part string * * @return $this this object + * * @throws Doctrine_Query_Exception if trying to add unknown query part */ public function addSqlQueryPart($name, $part) { - if ( ! isset($this->_sqlParts[$name])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $name); + if (!isset($this->_sqlParts[$name])) { + throw new Doctrine_Query_Exception('Unknown query part '.$name); } if (is_array($part)) { $this->_sqlParts[$name] = array_merge($this->_sqlParts[$name], $part); } else { $this->_sqlParts[$name][] = $part; } + return $this; } /** * removeSqlQueryPart - * removes a query part from the query part array + * removes a query part from the query part array. * * @param string $name the name of the query part to be removed * * @return $this this object + * * @throws Doctrine_Query_Exception if trying to remove unknown query part */ public function removeSqlQueryPart($name) { - if ( ! isset($this->_sqlParts[$name])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $name); + if (!isset($this->_sqlParts[$name])) { + throw new Doctrine_Query_Exception('Unknown query part '.$name); } - if ($name == 'limit' || $name == 'offset' || $name == 'forUpdate') { + if ('limit' == $name || 'offset' == $name || 'forUpdate' == $name) { $this->_sqlParts[$name] = false; } else { $this->_sqlParts[$name] = array(); @@ -510,20 +512,21 @@ public function removeSqlQueryPart($name) /** * removeDqlQueryPart - * removes a dql query part from the dql query part array + * removes a dql query part from the dql query part array. * * @param string $name the name of the query part to be removed * * @return $this this object + * * @throws Doctrine_Query_Exception if trying to remove unknown query part */ public function removeDqlQueryPart($name) { - if ( ! isset($this->_dqlParts[$name])) { - throw new Doctrine_Query_Exception('Unknown query part ' . $name); + if (!isset($this->_dqlParts[$name])) { + throw new Doctrine_Query_Exception('Unknown query part '.$name); } - if ($name == 'limit' || $name == 'offset') { + if ('limit' == $name || 'offset' == $name) { $this->_dqlParts[$name] = false; } else { $this->_dqlParts[$name] = array(); @@ -560,7 +563,7 @@ public function getFlattenedParams($params = array()) } /** - * getInternalParams + * getInternalParams. * * @param array $params * @@ -572,9 +575,7 @@ public function getInternalParams($params = array()) } /** - * setParams - * - * @param array $params + * setParams. */ public function setParams(array $params = array()) { @@ -583,7 +584,7 @@ public function setParams(array $params = array()) /** * getCountQueryParams - * Retrieves the parameters for count query + * Retrieves the parameters for count query. * * @param array $params * @@ -591,7 +592,7 @@ public function setParams(array $params = array()) */ public function getCountQueryParams($params = array()) { - if ( ! is_array($params)) { + if (!is_array($params)) { $params = array($params); } @@ -619,7 +620,7 @@ public function fixArrayParameterValues($params = array()) $i += $c; } else { - $i++; + ++$i; } } @@ -629,10 +630,9 @@ public function fixArrayParameterValues($params = array()) /** * setView * sets a database view this query object uses - * this method should only be called internally by doctrine + * this method should only be called internally by doctrine. * - * @param Doctrine_View $view database view - * @return void + * @param Doctrine_View $view database view */ public function setView(Doctrine_View $view) { @@ -641,9 +641,9 @@ public function setView(Doctrine_View $view) /** * getView - * returns the view associated with this query object (if any) + * returns the view associated with this query object (if any). * - * @return Doctrine_View the view associated with this query object + * @return Doctrine_View the view associated with this query object */ public function getView() { @@ -651,9 +651,9 @@ public function getView() } /** - * limitSubqueryUsed + * limitSubqueryUsed. * - * @return boolean + * @return bool */ public function isLimitSubqueryUsed() { @@ -662,7 +662,7 @@ public function isLimitSubqueryUsed() /** * Returns the inheritance condition for the passed componentAlias - * If no component alias is specified it defaults to the root component + * If no component alias is specified it defaults to the root component. * * This function is used to append a SQL condition to models which have inheritance mapping * The condition is applied to the FROM component in the WHERE, but the condition is applied to @@ -671,6 +671,7 @@ public function isLimitSubqueryUsed() * @param string $componentAlias * * @return string|null $str SQL condition string + * * @throws Doctrine_Query_Exception */ public function getInheritanceCondition($componentAlias) @@ -684,7 +685,7 @@ public function getInheritanceCondition($componentAlias) $tableAlias = $this->getSqlTableAlias($componentAlias); - if ($this->_type !== Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT !== $this->_type) { $tableAlias = ''; } else { $tableAlias .= '.'; @@ -692,16 +693,16 @@ public function getInheritanceCondition($componentAlias) // Fix for 2015: loop through whole inheritanceMap to add all // keyFields for inheritance (and not only the first) - $retVal = ""; - $count = 0; + $retVal = ''; + $count = 0; foreach ($map as $field => $value) { if ($count++ > 0) { $retVal .= ' AND '; } - $identifier = $this->_conn->quoteIdentifier($tableAlias . $field); - $retVal .= $identifier . ' = ' . $this->_conn->quote($value); + $identifier = $this->_conn->quoteIdentifier($tableAlias.$field); + $retVal .= $identifier.' = '.$this->_conn->quote($value); } return $retVal; @@ -710,7 +711,7 @@ public function getInheritanceCondition($componentAlias) /** * getSqlTableAlias * some database such as Oracle need the identifier lengths to be < ~30 chars - * hence Doctrine creates as short identifier aliases as possible + * hence Doctrine creates as short identifier aliases as possible. * * this method is used for the creation of short table aliases, its also * smart enough to check if an alias already exists for given component (componentAlias) @@ -719,18 +720,19 @@ public function getInheritanceCondition($componentAlias) * @param string $tableName the table name from which the table alias is being created * * @return string the generated / fetched short alias + * * @throws Doctrine_Query_Exception */ public function getSqlTableAlias($componentAlias, $tableName = null) { $alias = array_search($componentAlias, $this->_tableAliasMap); - if ($alias !== false) { + if (false !== $alias) { return $alias; } - if ($tableName === null) { - throw new Doctrine_Query_Exception("Couldn't get short alias for " . $componentAlias); + if (null === $tableName) { + throw new Doctrine_Query_Exception("Couldn't get short alias for ".$componentAlias); } return $this->generateSqlTableAlias($componentAlias, $tableName); @@ -738,7 +740,7 @@ public function getSqlTableAlias($componentAlias, $tableName = null) /** * generateNewSqlTableAlias - * generates a new alias from given table alias + * generates a new alias from given table alias. * * @param string $oldAlias table alias from which to generate the new alias from * @@ -749,16 +751,16 @@ public function generateNewSqlTableAlias($oldAlias) if (isset($this->_tableAliasMap[$oldAlias])) { // generate a new alias $name = substr($oldAlias, 0, 1); - $i = ((int) substr($oldAlias, 1)); + $i = ((int) substr($oldAlias, 1)); // Fix #1530: It was reaching unexistent seeds index - if ( ! isset($this->_tableAliasSeeds[$name])) { + if (!isset($this->_tableAliasSeeds[$name])) { $this->_tableAliasSeeds[$name] = 1; } - $newIndex = ($this->_tableAliasSeeds[$name] + (($i == 0) ? 1 : $i)); + $newIndex = ($this->_tableAliasSeeds[$name] + ((0 == $i) ? 1 : $i)); - return $name . $newIndex; + return $name.$newIndex; } return $oldAlias; @@ -766,26 +768,28 @@ public function generateNewSqlTableAlias($oldAlias) /** * getSqlTableAliasSeed - * returns the alias seed for given table alias + * returns the alias seed for given table alias. * * @param string $sqlTableAlias table alias that identifies the alias seed * - * @return integer table alias seed + * @return int table alias seed */ public function getSqlTableAliasSeed($sqlTableAlias) { - if ( ! isset($this->_tableAliasSeeds[$sqlTableAlias])) { + if (!isset($this->_tableAliasSeeds[$sqlTableAlias])) { return 0; } + return $this->_tableAliasSeeds[$sqlTableAlias]; } /** * hasAliasDeclaration - * whether or not this object has a declaration for given component alias + * whether or not this object has a declaration for given component alias. + * + * @param string $componentAlias the component alias the retrieve the declaration from * - * @param string $componentAlias the component alias the retrieve the declaration from - * @return boolean + * @return bool */ public function hasAliasDeclaration($componentAlias) { @@ -794,17 +798,18 @@ public function hasAliasDeclaration($componentAlias) /** * getQueryComponent - * get the declaration for given component alias + * get the declaration for given component alias. * * @param string $componentAlias the component alias the retrieve the declaration from * * @return array the alias declaration + * * @throws Doctrine_Query_Exception */ public function getQueryComponent($componentAlias) { - if ( ! isset($this->_queryComponents[$componentAlias])) { - throw new Doctrine_Query_Exception('Unknown component alias ' . $componentAlias); + if (!isset($this->_queryComponents[$componentAlias])) { + throw new Doctrine_Query_Exception('Unknown component alias '.$componentAlias); } return $this->_queryComponents[$componentAlias]; @@ -812,7 +817,7 @@ public function getQueryComponent($componentAlias) /** * copySubqueryInfo - * copy aliases from another Hydrate object + * copy aliases from another Hydrate object. * * this method is needed by DQL subqueries which need the aliases * of the parent query @@ -824,22 +829,23 @@ public function getQueryComponent($componentAlias) */ public function copySubqueryInfo(Doctrine_Query_Abstract $query) { - $this->_params =& $query->_params; - $this->_tableAliasMap =& $query->_tableAliasMap; - $this->_queryComponents =& $query->_queryComponents; + $this->_params = &$query->_params; + $this->_tableAliasMap = &$query->_tableAliasMap; + $this->_queryComponents = &$query->_queryComponents; $this->_tableAliasSeeds = $query->_tableAliasSeeds; + return $this; } /** * getRootAlias - * returns the alias of the root component + * returns the alias of the root component. * * @return string */ public function getRootAlias() { - if ( ! $this->_queryComponents) { + if (!$this->_queryComponents) { $this->getSqlQuery(array(), false); } @@ -848,28 +854,28 @@ public function getRootAlias() /** * getRootDeclaration - * returns the root declaration + * returns the root declaration. * * @return array */ public function getRootDeclaration() { - $map = $this->_queryComponents[$this->_rootAlias]; - return $map; + return $this->_queryComponents[$this->_rootAlias]; } /** * getRoot - * returns the root component for this object + * returns the root component for this object. * * @return Doctrine_Table root components table + * * @throws Doctrine_Query_Exception */ public function getRoot() { $map = $this->_queryComponents[$this->_rootAlias]; - if ( ! isset($map['table'])) { + if (!isset($map['table'])) { throw new Doctrine_Query_Exception('Root component not initialized.'); } @@ -879,11 +885,12 @@ public function getRoot() /** * generateSqlTableAlias * generates a table alias from given table name and associates - * it with given component alias + * it with given component alias. * - * @param string $componentAlias the component alias to be associated with generated table alias - * @param string $tableName the table name from which to generate the table alias - * @return string the generated table alias + * @param string $componentAlias the component alias to be associated with generated table alias + * @param string $tableName the table name from which to generate the table alias + * + * @return string the generated table alias */ public function generateSqlTableAlias($componentAlias, $tableName) { @@ -892,15 +899,15 @@ public function generateSqlTableAlias($componentAlias, $tableName) $alias = $char; - if ( ! isset($this->_tableAliasSeeds[$alias])) { + if (!isset($this->_tableAliasSeeds[$alias])) { $this->_tableAliasSeeds[$alias] = 1; } while (isset($this->_tableAliasMap[$alias])) { - if ( ! isset($this->_tableAliasSeeds[$alias])) { + if (!isset($this->_tableAliasSeeds[$alias])) { $this->_tableAliasSeeds[$alias] = 1; } - $alias = $char . ++$this->_tableAliasSeeds[$alias]; + $alias = $char.++$this->_tableAliasSeeds[$alias]; } $this->_tableAliasMap[$alias] = $componentAlias; @@ -910,49 +917,52 @@ public function generateSqlTableAlias($componentAlias, $tableName) /** * getComponentAlias - * get component alias associated with given table alias + * get component alias associated with given table alias. * * @param string $sqlTableAlias the SQL table alias that identifies the component alias * * @return string component alias + * * @throws Doctrine_Query_Exception */ public function getComponentAlias($sqlTableAlias) { $sqlTableAlias = trim($sqlTableAlias, '[]`"'); - if ( ! isset($this->_tableAliasMap[$sqlTableAlias])) { - throw new Doctrine_Query_Exception('Unknown table alias ' . $sqlTableAlias); + if (!isset($this->_tableAliasMap[$sqlTableAlias])) { + throw new Doctrine_Query_Exception('Unknown table alias '.$sqlTableAlias); } + return $this->_tableAliasMap[$sqlTableAlias]; } /** * calculateQueryCacheHash - * calculate hash key for query cache + * calculate hash key for query cache. * - * @return string the hash + * @return string the hash */ public function calculateQueryCacheHash() { $dql = $this->getDql(); - $hash = md5($dql . var_export($this->_pendingJoinConditions, true) . 'DOCTRINE_QUERY_CACHE_SALT'); - return $hash; + + return md5($dql.var_export($this->_pendingJoinConditions, true).'DOCTRINE_QUERY_CACHE_SALT'); } /** * calculateResultCacheHash - * calculate hash key for result cache + * calculate hash key for result cache. * * @param array $params - * @return string the hash + * + * @return string the hash */ public function calculateResultCacheHash($params = array()) { $dql = $this->getDql(); $conn = $this->getConnection(); $params = $this->getFlattenedParams($params); - $hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $dql . var_export($this->_pendingJoinConditions, true) . var_export($params, true)); - return $hash; + + return md5($this->_hydrator->getHydrationMode().$conn->getName().$conn->getOption('dsn').$dql.var_export($this->_pendingJoinConditions, true).var_export($params, true)); } /** @@ -960,23 +970,25 @@ public function calculateResultCacheHash($params = array()) * or generates a unique key from the query automatically. * * @param array $params + * * @return string $hash */ public function getResultCacheHash($params = array()) { - if ($this->_resultCacheHash) { - return $this->_resultCacheHash; - } else { - return $this->calculateResultCacheHash($params); - } + if ($this->_resultCacheHash) { + return $this->_resultCacheHash; + } + + return $this->calculateResultCacheHash($params); } /** - * _execute + * _execute. * * @param array $params * * @return PDOStatement|int The executed PDOStatement or the number of affected rows + * * @throws Doctrine_Connection_Exception * @throws Doctrine_Exception */ @@ -992,8 +1004,8 @@ protected function _execute($params) $dqlParams = $this->getFlattenedParams($params); // Check if we're not using a Doctrine_View - if ( ! $this->_view) { - if ($this->_queryCache !== false && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) { + if (!$this->_view) { + if (false !== $this->_queryCache && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) { $queryCacheDriver = $this->getQueryCacheDriver(); $hash = $this->calculateQueryCacheHash(); $cached = $queryCacheDriver->fetch($hash); @@ -1017,7 +1029,7 @@ protected function _execute($params) // Check again because getSqlQuery() above could have flipped the _queryCache flag // if this query contains the limit sub query algorithm we don't need to cache it - if ($this->_queryCache !== false && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) { + if (false !== $this->_queryCache && ($this->_queryCache || $this->_conn->getAttribute(Doctrine_Core::ATTR_QUERY_CACHE))) { // Convert query into a serialized form $serializedQuery = $this->getCachedForm($query); @@ -1035,12 +1047,12 @@ protected function _execute($params) // Get prepared SQL params for execution $params = $this->getInternalParams(); - if ($this->isLimitSubqueryUsed() && - $this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME) !== 'mysql') { + if ($this->isLimitSubqueryUsed() + && 'mysql' !== $this->_conn->getAttribute(Doctrine_Core::ATTR_DRIVER_NAME)) { $params = array_merge((array) $params, (array) $params); } - if ($this->_type !== self::SELECT) { + if (self::SELECT !== $this->_type) { return $this->_conn->exec($query, $params); } @@ -1053,12 +1065,13 @@ protected function _execute($params) /** * execute - * executes the query and populates the data set + * executes the query and populates the data set. * * @param array $params - * @param null|int|string $hydrationMode one of the Doctrine_Core::HYDRATE_* constants or null + * @param int|string|null $hydrationMode one of the Doctrine_Core::HYDRATE_* constants or null * * @return Doctrine_Collection|array the root collection (the result type depends on the hydrator) + * * @throws Doctrine_Connection_Exception * @throws Doctrine_Hydrator_Exception * @throws Doctrine_Query_Exception @@ -1077,18 +1090,18 @@ public function execute($params = array(), $hydrationMode = null) $this->_preQuery($dqlParams); - if ($hydrationMode !== null) { + if (null !== $hydrationMode) { $this->_hydrator->setHydrationMode($hydrationMode); } $hydrationMode = $this->_hydrator->getHydrationMode(); - if ($this->_resultCache && $this->_type == self::SELECT) { + if ($this->_resultCache && self::SELECT == $this->_type) { $cacheDriver = $this->getResultCacheDriver(); $hash = $this->getResultCacheHash($params); $cached = ($this->_expireResultCache) ? false : $cacheDriver->fetch($hash); - if ($cached === false) { + if (false === $cached) { // cache miss $stmt = $this->_execute($params); $this->_hydrator->setQueryComponents($this->_queryComponents); @@ -1106,7 +1119,7 @@ public function execute($params = array(), $hydrationMode = null) $result = $stmt; } else { $this->_hydrator->setQueryComponents($this->_queryComponents); - if ($this->_type == self::SELECT && $hydrationMode == Doctrine_Core::HYDRATE_ON_DEMAND) { + if (self::SELECT == $this->_type && Doctrine_Core::HYDRATE_ON_DEMAND == $hydrationMode) { $hydrationDriver = $this->_hydrator->getHydratorDriver($hydrationMode, $this->_tableAliasMap); $result = new Doctrine_Collection_OnDemand($stmt, $hydrationDriver, $this->_tableAliasMap); } else { @@ -1122,40 +1135,40 @@ public function execute($params = array(), $hydrationMode = null) } /** - * Blank template method free(). Override to be used to free query object memory + * Blank template method free(). Override to be used to free query object memory. */ public function free() { } /** - * Get the dql call back for this query + * Get the dql call back for this query. * * @return array $callback */ protected function _getDqlCallback() { $callback = false; - if ( ! empty($this->_dqlParts['from'])) { + if (!empty($this->_dqlParts['from'])) { switch ($this->_type) { case self::DELETE: $callback = array( 'callback' => 'preDqlDelete', - 'const' => Doctrine_Event::RECORD_DQL_DELETE + 'const' => Doctrine_Event::RECORD_DQL_DELETE, ); - break; + break; case self::UPDATE: $callback = array( 'callback' => 'preDqlUpdate', - 'const' => Doctrine_Event::RECORD_DQL_UPDATE + 'const' => Doctrine_Event::RECORD_DQL_UPDATE, ); - break; + break; case self::SELECT: $callback = array( 'callback' => 'preDqlSelect', - 'const' => Doctrine_Event::RECORD_DQL_SELECT + 'const' => Doctrine_Event::RECORD_DQL_SELECT, ); - break; + break; } } @@ -1164,22 +1177,21 @@ protected function _getDqlCallback() /** * Pre query method which invokes the pre*Query() methods on the model instance or any attached - * record listeners + * record listeners. * * @param array $params * - * @return void * @throws Doctrine_Connection_Exception */ protected function _preQuery($params = array()) { - if ( ! $this->_preQueried && $this->getConnection()->getAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS)) { + if (!$this->_preQueried && $this->getConnection()->getAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS)) { $this->_preQueried = true; $callback = $this->_getDqlCallback(); // if there is no callback for the query type, then we can return early - if ( ! $callback) { + if (!$callback) { return; } @@ -1201,9 +1213,10 @@ protected function _preQuery($params = array()) } /** - * Returns an array of components to execute the query callbacks for + * Returns an array of components to execute the query callbacks for. + * + * @param array $params * - * @param array $params * @return array $components */ protected function _getDqlCallbackComponents($params = array()) @@ -1223,15 +1236,13 @@ protected function _getDqlCallbackComponents($params = array()) if ($componentsBefore !== $componentsAfter) { return Doctrine_Lib::arrayDiffSimple($componentsAfter, $componentsBefore); - } else { - return $componentsAfter; } + + return $componentsAfter; } /** - * Blank hook methods which can be implemented in Doctrine_Query child classes - * - * @return void + * Blank hook methods which can be implemented in Doctrine_Query child classes. */ public function preQuery() { @@ -1240,10 +1251,11 @@ public function preQuery() /** * Constructs the query from the cached form. * - * @param string The cached query, in a serialized form. - * @return array The custom component that was cached together with the essential - * query data. This can be either a result set (result caching) - * or an SQL query string (query caching). + * @param string the cached query, in a serialized form + * + * @return array The custom component that was cached together with the essential + * query data. This can be either a result set (result caching) + * or an SQL query string (query caching). */ protected function _constructQueryFromCache($cached) { @@ -1255,9 +1267,9 @@ protected function _constructQueryFromCache($cached) $cachedComponents = $cached[1]; foreach ($cachedComponents as $alias => $components) { $e = explode('.', $components['name']); - if (count($e) === 1) { + if (1 === count($e)) { $manager = Doctrine_Manager::getInstance(); - if ( ! $this->_passedConn && $manager->hasConnectionForComponent($e[0])) { + if (!$this->_passedConn && $manager->hasConnectionForComponent($e[0])) { $this->_conn = $manager->getConnectionForComponent($e[0]); } $queryComponents[$alias]['table'] = $this->_conn->getTable($e[0]); @@ -1283,9 +1295,9 @@ protected function _constructQueryFromCache($cached) /** * getCachedForm - * returns the cached form of this query for given resultSet + * returns the cached form of this query for given resultSet. * - * @param array|null|Doctrine_Collection $customComponent + * @param array|Doctrine_Collection|null $customComponent * * @return string serialized string representation of this query */ @@ -1294,10 +1306,10 @@ public function getCachedForm($customComponent = null) $componentInfo = array(); foreach ($this->getQueryComponents() as $alias => $components) { - if ( ! isset($components['parent'])) { + if (!isset($components['parent'])) { $componentInfo[$alias]['name'] = $components['table']->getComponentName(); } else { - $componentInfo[$alias]['name'] = $components['parent'] . '.' . $components['relation']->getAlias(); + $componentInfo[$alias]['name'] = $components['parent'].'.'.$components['relation']->getAlias(); } if (isset($components['agg'])) { $componentInfo[$alias]['agg'] = $components['agg']; @@ -1330,6 +1342,7 @@ public function getCachedForm($customComponent = null) * @param string $select Query SELECT part * * @return $this + * * @throws Doctrine_Query_Exception */ public function addSelect($select) @@ -1339,7 +1352,7 @@ public function addSelect($select) /** * addSqlTableAlias - * adds an SQL table alias and associates it a component alias + * adds an SQL table alias and associates it a component alias. * * @param string $componentAlias the alias for the query component associated with given tableAlias * @param string $sqlTableAlias the table alias to be added @@ -1349,16 +1362,18 @@ public function addSelect($select) public function addSqlTableAlias($sqlTableAlias, $componentAlias) { $this->_tableAliasMap[$sqlTableAlias] = $componentAlias; + return $this; } /** * addFrom - * adds fields to the FROM part of the query + * adds fields to the FROM part of the query. * * @param string $from Query FROM part * * @return $this + * * @throws Doctrine_Query_Exception */ public function addFrom($from) @@ -1370,6 +1385,7 @@ public function addFrom($from) * Alias for @see Doctrine_Query_Abstract::andWhere(). * * @return $this this object + * * @throws Doctrine_Query_Exception */ public function addWhere($where, $params = array()) @@ -1381,12 +1397,13 @@ public function addWhere($where, $params = array()) * Adds conditions to the WHERE part of the query. * * $q->andWhere('u.birthDate > ?', '1975-01-01'); - * + * . * * @param string $where Query WHERE part * @param mixed $params An array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function andWhere($where, $params = array()) @@ -1408,12 +1425,13 @@ public function andWhere($where, $params = array()) * Adds conditions to the WHERE part of the query * * $q->orWhere('u.role = ?', 'admin'); - * + * . * * @param string $where Query WHERE part * @param mixed $params An array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function orWhere($where, $params = array()) @@ -1434,11 +1452,12 @@ public function orWhere($where, $params = array()) /** * Adds IN condition to the query WHERE part. Alias to @see andWhereIn(). * - * @param string $expr the operand of the IN - * @param mixed $params an array of parameters or a simple scalar - * @param boolean $not whether or not to use NOT in front of IN + * @param string $expr the operand of the IN + * @param mixed $params an array of parameters or a simple scalar + * @param bool $not whether or not to use NOT in front of IN * * @return $this + * * @throws Doctrine_Query_Exception */ public function whereIn($expr, $params = array(), $not = false) @@ -1450,19 +1469,20 @@ public function whereIn($expr, $params = array(), $not = false) * Adds IN condition to the query WHERE part * * $q->whereIn('u.id', array(10, 23, 44)); - * + * . * - * @param string $expr The operand of the IN - * @param mixed $params An array of parameters or a simple scalar - * @param boolean $not Whether or not to use NOT in front of IN. Defaults to false (simple IN clause) + * @param string $expr The operand of the IN + * @param mixed $params An array of parameters or a simple scalar + * @param bool $not Whether or not to use NOT in front of IN. Defaults to false (simple IN clause) + * + * @return $this this object * - * @return $this this object. * @throws Doctrine_Query_Exception */ public function andWhereIn($expr, $params = array(), $not = false) { // if there's no params, return (else we'll get a WHERE IN (), invalid SQL) - if (isset($params) and is_array($params) and (count($params) == 0)) { + if (isset($params) and is_array($params) and (0 == count($params))) { return $this; } @@ -1479,19 +1499,20 @@ public function andWhereIn($expr, $params = array(), $not = false) * $q->orWhereIn('u.id', array(10, 23)) * ->orWhereIn('u.id', 44); * // will select all record with id equal to 10, 23 or 44 - * + * . * - * @param string $expr The operand of the IN - * @param mixed $params An array of parameters or a simple scalar - * @param boolean $not Whether or not to use NOT in front of IN + * @param string $expr The operand of the IN + * @param mixed $params An array of parameters or a simple scalar + * @param bool $not Whether or not to use NOT in front of IN * * @return $this + * * @throws Doctrine_Query_Exception */ public function orWhereIn($expr, $params = array(), $not = false) { // if there's no params, return (else we'll get a WHERE IN (), invalid SQL) - if (isset($params) and (count($params) == 0)) { + if (isset($params) and (0 == count($params))) { return $this; } @@ -1510,7 +1531,7 @@ protected function _processWhereIn($expr, $params = array(), $not = false) $params = (array) $params; // if there's no params, return (else we'll get a WHERE IN (), invalid SQL) - if (count($params) == 0) { + if (0 == count($params)) { throw new Doctrine_Query_Exception('You must pass at least one parameter when using an IN() condition.'); } @@ -1527,7 +1548,7 @@ protected function _processWhereIn($expr, $params = array(), $not = false) $this->_params['where'] = array_merge($this->_params['where'], $params); - return $expr . ($not === true ? ' NOT' : '') . ' IN (' . implode(', ', $a) . ')'; + return $expr.(true === $not ? ' NOT' : '').' IN ('.implode(', ', $a).')'; } /** @@ -1535,12 +1556,13 @@ protected function _processWhereIn($expr, $params = array(), $not = false) * * $q->whereNotIn('u.id', array(10, 20)); * // will exclude users with id 10 and 20 from the select - * + * . * * @param string $expr the operand of the NOT IN * @param mixed $params an array of parameters or a simple scalar * - * @return $this this object + * @return $this this object + * * @throws Doctrine_Query_Exception */ public function whereNotIn($expr, $params = array()) @@ -1556,6 +1578,7 @@ public function whereNotIn($expr, $params = array()) * @param mixed $params An array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function andWhereNotIn($expr, $params = array()) @@ -1564,12 +1587,13 @@ public function andWhereNotIn($expr, $params = array()) } /** - * Adds NOT IN condition to the query WHERE part + * Adds NOT IN condition to the query WHERE part. * * @param string $expr The operand of the NOT IN * @param mixed $params An array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function orWhereNotIn($expr, $params = array()) @@ -1581,11 +1605,12 @@ public function orWhereNotIn($expr, $params = array()) * Adds fields to the GROUP BY part of the query. * * $q->groupBy('u.id'); - * + * . * * @param string $groupby Query GROUP BY part * * @return $this + * * @throws Doctrine_Query_Exception */ public function addGroupBy($groupby) @@ -1606,6 +1631,7 @@ public function addGroupBy($groupby) * @param mixed $params an array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function addHaving($having, $params = array()) @@ -1615,16 +1641,18 @@ public function addHaving($having, $params = array()) } else { $this->_params['having'][] = $params; } + return $this->_addDqlQueryPart('having', $having, true); } /** * addOrderBy - * adds fields to the ORDER BY part of the query + * adds fields to the ORDER BY part of the query. * * @param string $orderby Query ORDER BY part * * @return $this + * * @throws Doctrine_Query_Exception */ public function addOrderBy($orderby) @@ -1634,11 +1662,12 @@ public function addOrderBy($orderby) /** * select - * sets the SELECT part of the query + * sets the SELECT part of the query. * * @param string $select Query SELECT part * * @return $this + * * @throws Doctrine_Query_Exception */ public function select($select = null) @@ -1646,9 +1675,9 @@ public function select($select = null) $this->_type = self::SELECT; if ($select) { return $this->_addDqlQueryPart('select', $select); - } else { - return $this; } + + return $this; } /** @@ -1656,15 +1685,16 @@ public function select($select = null) * Makes the query SELECT DISTINCT. * * $q->distinct(); - * + * . * - * @param bool $flag Whether or not the SELECT is DISTINCT (default true). + * @param bool $flag whether or not the SELECT is DISTINCT (default true) * * @return $this */ public function distinct($flag = true) { $this->_sqlParts['distinct'] = (bool) $flag; + return $this; } @@ -1672,55 +1702,60 @@ public function distinct($flag = true) * forUpdate * Makes the query SELECT FOR UPDATE. * - * @param bool $flag Whether or not the SELECT is FOR UPDATE (default true). + * @param bool $flag whether or not the SELECT is FOR UPDATE (default true) * * @return $this */ public function forUpdate($flag = true) { $this->_sqlParts['forUpdate'] = (bool) $flag; + return $this; } /** * delete - * sets the query type to DELETE + * sets the query type to DELETE. * - * @param null|string $from + * @param string|null $from * * @return $this + * * @throws Doctrine_Query_Exception */ public function delete($from = null) { $this->_type = self::DELETE; - if ($from != null) { + if (null != $from) { return $this->_addDqlQueryPart('from', $from); } + return $this; } /** * update - * sets the UPDATE part of the query + * sets the UPDATE part of the query. * * @param string|null $from Query UPDATE part * * @return $this + * * @throws Doctrine_Query_Exception */ public function update($from = null) { $this->_type = self::UPDATE; - if ($from != null) { + if (null != $from) { return $this->_addDqlQueryPart('from', $from); } + return $this; } /** * set - * sets the SET part of the query + * sets the SET part of the query. * * NOTE: best way is to use: $query->set(array('key' => 'value', ...)) * @@ -1732,6 +1767,7 @@ public function update($from = null) * '?', array(null)) or set(array('key' => null)) * * @return $this + * * @throws Doctrine_Query_Exception */ public function set($key, $value = null, $params = null) @@ -1740,18 +1776,18 @@ public function set($key, $value = null, $params = null) foreach ($key as $k => $v) { $this->set($k, '?', array($v)); } + return $this; - } else { - if ($params !== null) { - if (is_array($params)) { - $this->_params['set'] = array_merge($this->_params['set'], $params); - } else { - $this->_params['set'][] = $params; - } + } + if (null !== $params) { + if (is_array($params)) { + $this->_params['set'] = array_merge($this->_params['set'], $params); + } else { + $this->_params['set'][] = $params; } - - return $this->_addDqlQueryPart('set', $key . ' = ' . $value, true); } + + return $this->_addDqlQueryPart('set', $key.' = '.$value, true); } /** @@ -1759,11 +1795,12 @@ public function set($key, $value = null, $params = null) * sets the FROM part of the query * * $q->from('User u'); - * + * . * * @param string $from Query FROM part * * @return $this + * * @throws Doctrine_Query_Exception */ public function from($from) @@ -1773,11 +1810,12 @@ public function from($from) /** * innerJoin - * appends an INNER JOIN to the FROM part of the query + * appends an INNER JOIN to the FROM part of the query. * * @param string $join Query INNER JOIN * * @return $this + * * @throws Doctrine_Query_Exception */ public function innerJoin($join, $params = array()) @@ -1788,16 +1826,17 @@ public function innerJoin($join, $params = array()) $this->_params['join'][] = $params; } - return $this->_addDqlQueryPart('from', 'INNER JOIN ' . $join, true); + return $this->_addDqlQueryPart('from', 'INNER JOIN '.$join, true); } /** * leftJoin - * appends a LEFT JOIN to the FROM part of the query + * appends a LEFT JOIN to the FROM part of the query. * * @param string $join Query LEFT JOIN * * @return $this + * * @throws Doctrine_Query_Exception */ public function leftJoin($join, $params = array()) @@ -1808,16 +1847,17 @@ public function leftJoin($join, $params = array()) $this->_params['join'][] = $params; } - return $this->_addDqlQueryPart('from', 'LEFT JOIN ' . $join, true); + return $this->_addDqlQueryPart('from', 'LEFT JOIN '.$join, true); } /** * groupBy - * sets the GROUP BY part of the query + * sets the GROUP BY part of the query. * * @param string $groupby Query GROUP BY part * * @return $this + * * @throws Doctrine_Query_Exception */ public function groupBy($groupby) @@ -1827,12 +1867,13 @@ public function groupBy($groupby) /** * where - * sets the WHERE part of the query + * sets the WHERE part of the query. * * @param string $where Query WHERE part * @param mixed $params an array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function where($where, $params = array()) @@ -1850,12 +1891,13 @@ public function where($where, $params = array()) /** * having - * sets the HAVING part of the query + * sets the HAVING part of the query. * * @param string $having Query HAVING part * @param mixed $params an array of parameters or a simple scalar * * @return $this + * * @throws Doctrine_Query_Exception */ public function having($having, $params = array()) @@ -1875,11 +1917,12 @@ public function having($having, $params = array()) * * $q->orderBy('u.name'); * $query->orderBy('u.birthDate DESC'); - * + * . * * @param string $orderby Query ORDER BY part * * @return $this + * * @throws Doctrine_Query_Exception */ public function orderBy($orderby) @@ -1889,11 +1932,12 @@ public function orderBy($orderby) /** * limit - * sets the Query query limit + * sets the Query query limit. * - * @param integer $limit limit to be used for limiting the query results + * @param int $limit limit to be used for limiting the query results * * @return $this + * * @throws Doctrine_Query_Exception */ public function limit($limit) @@ -1903,11 +1947,12 @@ public function limit($limit) /** * offset - * sets the Query query offset + * sets the Query query offset. * - * @param integer $offset offset to be used for paginating the query + * @param int $offset offset to be used for paginating the query * * @return $this + * * @throws Doctrine_Query_Exception */ public function offset($offset) @@ -1917,30 +1962,29 @@ public function offset($offset) /** * Resets all the sql parts. - * - * @return void */ protected function clear() { $this->_sqlParts = array( - 'select' => array(), - 'distinct' => false, - 'forUpdate' => false, - 'from' => array(), - 'set' => array(), - 'join' => array(), - 'where' => array(), - 'groupby' => array(), - 'having' => array(), - 'orderby' => array(), - 'limit' => false, - 'offset' => false, - ); + 'select' => array(), + 'distinct' => false, + 'forUpdate' => false, + 'from' => array(), + 'set' => array(), + 'join' => array(), + 'where' => array(), + 'groupby' => array(), + 'having' => array(), + 'orderby' => array(), + 'limit' => false, + 'offset' => false, + ); } public function setHydrationMode($hydrationMode) { $this->_hydrator->setHydrationMode($hydrationMode); + return $this; } @@ -1963,7 +2007,7 @@ public function getSqlParts() } /** - * getType + * getType. * * returns the type of this query object * by default the type is Doctrine_Query_Abstract::SELECT but if update() or delete() @@ -1974,7 +2018,7 @@ public function getSqlParts() * @see Doctrine_Query_Abstract::UPDATE * @see Doctrine_Query_Abstract::DELETE * - * @return integer return the query type + * @return int return the query type */ public function getType() { @@ -1982,33 +2026,34 @@ public function getType() } /** - * useResultCache - * - * @throws Doctrine_Query_Exception + * useResultCache. * * @param bool|Doctrine_Cache_Interface|null $driver cache driver (true: use default driver | null: disable caching) - * @param integer $timeToLive (in sec) how long the cache entry is valid + * @param int $timeToLive (in sec) how long the cache entry is valid * @param string $resultCacheHash The key to use for storing the queries result cache entry * * @return $this this object + * + * @throws Doctrine_Query_Exception */ public function useResultCache($driver = true, $timeToLive = null, $resultCacheHash = null) { - if ($driver !== null && $driver !== true && ! ($driver instanceOf Doctrine_Cache_Interface)) { + if (null !== $driver && true !== $driver && !($driver instanceof Doctrine_Cache_Interface)) { $msg = 'First argument should be instance of Doctrine_Cache_Interface or null.'; throw new Doctrine_Query_Exception($msg); } $this->_resultCache = $driver; $this->_resultCacheHash = $resultCacheHash; - if ($timeToLive !== null) { + if (null !== $timeToLive) { $this->setResultCacheLifeSpan($timeToLive); } + return $this; } /** - * Set the result cache hash to be used for storing the results in the cache driver + * Set the result cache hash to be used for storing the results in the cache driver. * * @param string $resultCacheHash * @@ -2022,79 +2067,84 @@ public function setResultCacheHash($resultCacheHash) } /** - * Clear the result cache entry for this query + * Clear the result cache entry for this query. * * @return $this + * * @throws Doctrine_Exception */ public function clearResultCache() { $this->getResultCacheDriver() - ->delete($this->getResultCacheHash()); + ->delete($this->getResultCacheHash()) + ; return $this; } /** - * useQueryCache - * - * @throws Doctrine_Query_Exception + * useQueryCache. * * @param Doctrine_Cache_Interface|bool $driver cache driver - * @param integer $timeToLive how long the cache entry is valid + * @param int $timeToLive how long the cache entry is valid * * @return $this this object + * + * @throws Doctrine_Query_Exception */ public function useQueryCache($driver = true, $timeToLive = null) { - if ($driver !== null && $driver !== true && $driver !== false && ! ($driver instanceOf Doctrine_Cache_Interface)) { + if (null !== $driver && true !== $driver && false !== $driver && !($driver instanceof Doctrine_Cache_Interface)) { $msg = 'First argument should be instance of Doctrine_Cache_Interface or null.'; throw new Doctrine_Query_Exception($msg); } $this->_queryCache = $driver; - if ($timeToLive !== null) { + if (null !== $timeToLive) { $this->setQueryCacheLifeSpan($timeToLive); } + return $this; } /** - * expireCache + * expireCache. * - * @param boolean $expire whether or not to force cache expiration + * @param bool $expire whether or not to force cache expiration * * @return $this this object */ public function expireResultCache($expire = true) { $this->_expireResultCache = $expire; + return $this; } /** - * expireQueryCache + * expireQueryCache. * - * @param boolean $expire whether or not to force cache expiration + * @param bool $expire whether or not to force cache expiration * * @return $this this object */ public function expireQueryCache($expire = true) { $this->_expireQueryCache = $expire; + return $this; } /** - * setResultCacheLifeSpan + * setResultCacheLifeSpan. * - * @param integer $timeToLive how long the cache entry is valid (in seconds) + * @param int $timeToLive how long the cache entry is valid (in seconds) * * @return $this this object */ public function setResultCacheLifeSpan($timeToLive) { - if ($timeToLive !== null) { + if (null !== $timeToLive) { $timeToLive = (int) $timeToLive; } $this->_resultCacheTTL = $timeToLive; @@ -2105,7 +2155,7 @@ public function setResultCacheLifeSpan($timeToLive) /** * Gets the life span of the result cache in seconds. * - * @return integer + * @return int */ public function getResultCacheLifeSpan() { @@ -2113,15 +2163,15 @@ public function getResultCacheLifeSpan() } /** - * setQueryCacheLifeSpan + * setQueryCacheLifeSpan. * - * @param integer $timeToLive how long the cache entry is valid + * @param int $timeToLive how long the cache entry is valid * * @return $this this object */ public function setQueryCacheLifeSpan($timeToLive) { - if ($timeToLive !== null) { + if (null !== $timeToLive) { $timeToLive = (int) $timeToLive; } $this->_queryCacheTTL = $timeToLive; @@ -2132,7 +2182,7 @@ public function setQueryCacheLifeSpan($timeToLive) /** * Gets the life span of the query cache the Query object is using. * - * @return integer The life span in seconds. + * @return int the life span in seconds */ public function getQueryCacheLifeSpan() { @@ -2141,38 +2191,40 @@ public function getQueryCacheLifeSpan() /** * getResultCacheDriver - * returns the cache driver used for caching result sets + * returns the cache driver used for caching result sets. + * + * @return Doctrine_Cache_Interface|bool|null cache driver * - * @return Doctrine_Cache_Interface|boolean|null cache driver * @throws Doctrine_Exception */ public function getResultCacheDriver() { if ($this->_resultCache instanceof Doctrine_Cache_Interface) { return $this->_resultCache; - } else { - return $this->_conn->getResultCacheDriver(); } + + return $this->_conn->getResultCacheDriver(); } /** * getQueryCacheDriver - * returns the cache driver used for caching queries + * returns the cache driver used for caching queries. + * + * @return Doctrine_Cache_Interface|bool|null cache driver * - * @return Doctrine_Cache_Interface|boolean|null cache driver * @throws Doctrine_Exception */ public function getQueryCacheDriver() { if ($this->_queryCache instanceof Doctrine_Cache_Interface) { return $this->_queryCache; - } else { - return $this->_conn->getQueryCacheDriver(); } + + return $this->_conn->getQueryCacheDriver(); } /** - * getConnection + * getConnection. * * @return Doctrine_Connection */ @@ -2184,8 +2236,9 @@ public function getConnection() /** * Checks if there's at least one DQL part defined to the internal parts collection. * - * @param string $queryPartName The name of the query part. - * @return boolean + * @param string $queryPartName the name of the query part + * + * @return bool */ protected function _hasDqlQueryPart($queryPartName) { @@ -2201,20 +2254,21 @@ protected function _hasDqlQueryPart($queryPartName) * @see $_dqlParts; * @see Doctrine_Query::getDqlPart() * - * @param string $queryPartName The name of the query part. - * @param string $queryPart The actual query part to add. - * @param boolean $append Whether to append $queryPart to already existing - * parts under the same $queryPartName. Defaults to FALSE - * (previously added parts with the same name get overridden). + * @param string $queryPartName the name of the query part + * @param string $queryPart the actual query part to add + * @param bool $append Whether to append $queryPart to already existing + * parts under the same $queryPartName. Defaults to FALSE + * (previously added parts with the same name get overridden). * * @return $this + * * @throws Doctrine_Query_Exception */ protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false) { // We should prevent nullable query parts - if ($queryPart === null) { - throw new Doctrine_Query_Exception('Cannot define NULL as part of query when defining \'' . $queryPartName . '\'.'); + if (null === $queryPart) { + throw new Doctrine_Query_Exception('Cannot define NULL as part of query when defining \''.$queryPartName.'\'.'); } if ($append) { @@ -2224,30 +2278,32 @@ protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false) } $this->_state = Doctrine_Query::STATE_DIRTY; + return $this; } /** * _processDqlQueryPart - * parses given query part + * parses given query part. * * @param string $queryPartName the name of the query part * @param array $queryParts an array containing the query part data * * @todo Better description. "parses given query part" ??? Then wheres the difference * between process/parseQueryPart? I suppose this does something different. + * * @throws Doctrine_Query_Exception */ protected function _processDqlQueryPart($queryPartName, $queryParts) { $this->removeSqlQueryPart($queryPartName); - if (is_array($queryParts) && ! empty($queryParts)) { + if (is_array($queryParts) && !empty($queryParts)) { foreach ($queryParts as $queryPart) { $parser = $this->_getParser($queryPartName); $sql = $parser->parse($queryPart); if (isset($sql)) { - if ($queryPartName == 'limit' || $queryPartName == 'offset') { + if ('limit' == $queryPartName || 'offset' == $queryPartName) { $this->setSqlQueryPart($queryPartName, $sql); } else { $this->addSqlQueryPart($queryPartName, $sql); @@ -2259,21 +2315,23 @@ protected function _processDqlQueryPart($queryPartName, $queryParts) /** * _getParser - * parser lazy-loader + * parser lazy-loader. * - * @throws Doctrine_Query_Exception if unknown parser name given * @return Doctrine_Query_Part + * + * @throws Doctrine_Query_Exception if unknown parser name given + * * @todo Doc/Description: What is the parameter for? Which parsers are available? */ protected function _getParser($name) { - if ( ! isset($this->_parsers[$name])) { - $class = 'Doctrine_Query_' . ucwords(strtolower($name)); + if (!isset($this->_parsers[$name])) { + $class = 'Doctrine_Query_'.ucwords(strtolower($name)); Doctrine_Core::autoload($class); - if ( ! class_exists($class)) { - throw new Doctrine_Query_Exception('Unknown parser ' . $name); + if (!class_exists($class)) { + throw new Doctrine_Query_Exception('Unknown parser '.$name); } $this->_parsers[$name] = new $class($this, $this->_tokenizer); @@ -2295,9 +2353,10 @@ abstract public function getSqlQuery($params = array()); /** * parseDqlQuery - * parses a dql query + * parses a dql query. + * + * @param string $query query to be parsed * - * @param string $query query to be parsed * @return $this this object */ abstract public function parseDqlQuery($query); @@ -2305,7 +2364,7 @@ abstract public function parseDqlQuery($query); /** * toString magic call * this method is automatically called when Doctrine_Query object is trying to be used as a string - * So, it it converted into its DQL correspondant + * So, it it converted into its DQL correspondant. * * @return string DQL string */ @@ -2317,7 +2376,7 @@ public function __toString() /** * Gets the disableLimitSubquery property. * - * @return boolean + * @return bool */ public function getDisableLimitSubquery() { @@ -2328,7 +2387,7 @@ public function getDisableLimitSubquery() * Allows you to set the disableLimitSubquery property -- setting this to true will * restrict the query object from using the limit sub query method of tranversing many relationships. * - * @param boolean $disableLimitSubquery + * @param bool $disableLimitSubquery */ public function setDisableLimitSubquery($disableLimitSubquery) { diff --git a/lib/Doctrine/Query/Check.php b/lib/Doctrine/Query/Check.php index c730ce01c..7c87e3942 100644 --- a/lib/Doctrine/Query/Check.php +++ b/lib/Doctrine/Query/Check.php @@ -20,40 +20,42 @@ */ /** - * Doctrine_Query_Check + * Doctrine_Query_Check. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Check { /** - * @var Doctrine_Table $table Doctrine_Table object + * @var Doctrine_Table Doctrine_Table object */ protected $table; /** - * @var string $sql database specific sql CHECK constraint definition - * parsed from the given dql CHECK definition + * @var string database specific sql CHECK constraint definition + * parsed from the given dql CHECK definition */ protected $sql; - + protected $_tokenizer; /** - * @param Doctrine_Table|string $table Doctrine_Table object + * @param Doctrine_Table|string $table Doctrine_Table object */ public function __construct($table) { - if ( ! ($table instanceof Doctrine_Table)) { + if (!($table instanceof Doctrine_Table)) { $table = Doctrine_Manager::getInstance() - ->getCurrentConnection() - ->getTable($table); + ->getCurrentConnection() + ->getTable($table) + ; } $this->table = $table; $this->_tokenizer = new Doctrine_Query_Tokenizer(); @@ -61,7 +63,7 @@ public function __construct($table) /** * getTable - * returns the table object associated with this object + * returns the table object associated with this object. * * @return Doctrine_Connection */ @@ -71,9 +73,10 @@ public function getTable() } /** - * parse + * parse. + * + * @param string $dql DQL CHECK constraint definition * - * @param string $dql DQL CHECK constraint definition * @return string */ public function parse($dql) @@ -82,12 +85,7 @@ public function parse($dql) } /** - * parseClause - * - * @param string $alias component alias - * @param string $field the field name - * @param mixed $value the value of the field - * @return void + * parseClause. */ public function parseClause($dql) { @@ -110,17 +108,17 @@ public function parseClause($dql) $r = implode(' OR ', $ret); } else { - $ret = $this->parseSingle($dql); - return $ret; + return $this->parseSingle($dql); } } - return '(' . $r . ')'; + + return '('.$r.')'; } - + public function parseSingle($part) { $e = explode(' ', $part); - + $e[0] = $this->parseFunction($e[0]); switch ($e[1]) { @@ -129,34 +127,34 @@ public function parseSingle($part) case '=': case '!=': case '<>': - - break; + break; default: - throw new Doctrine_Query_Exception('Unknown operator ' . $e[1]); + throw new Doctrine_Query_Exception('Unknown operator '.$e[1]); } return implode(' ', $e); } - public function parseFunction($dql) + public function parseFunction($dql) { if (($pos = strpos($dql, '(')) !== false) { - $func = substr($dql, 0, $pos); - $value = substr($dql, ($pos + 1), -1); - - $expr = $this->table->getConnection()->expression; + $func = substr($dql, 0, $pos); + $value = substr($dql, $pos + 1, -1); - if ( ! method_exists($expr, $func)) { - throw new Doctrine_Query_Exception('Unknown function ' . $func); + $expr = $this->table->getConnection()->expression; + + if (!method_exists($expr, $func)) { + throw new Doctrine_Query_Exception('Unknown function '.$func); } - - $func = $expr->$func($value); + + $func = $expr->{$func}($value); } + return $func; } /** - * getSql + * getSql. * * returns database specific sql CHECK constraint definition * parsed from the given dql CHECK definition @@ -167,4 +165,4 @@ public function getSql() { return $this->sql; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Condition.php b/lib/Doctrine/Query/Condition.php index a4256b565..7de528c3f 100644 --- a/lib/Doctrine/Query/Condition.php +++ b/lib/Doctrine/Query/Condition.php @@ -20,31 +20,33 @@ */ /** - * Doctrine_Query_Condition + * Doctrine_Query_Condition. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Query_Condition extends Doctrine_Query_Part { /** * DQL CONDITION PARSER - * parses the join condition/where/having part of the query string + * parses the join condition/where/having part of the query string. * * @param string $str + * * @return string */ public function parse($str) { $tmp = trim($str); - + $parts = $this->_tokenizer->bracketExplode($str, array(' OR '), '(', ')'); - + if (count($parts) > 1) { $ret = array(); foreach ($parts as $part) { @@ -58,18 +60,18 @@ public function parse($str) // Ticket #1388: We need to make sure we're not splitting a BETWEEN ... AND ... clause $tmp = array(); - for ($i = 0, $l = count($parts); $i < $l; $i++) { + for ($i = 0, $l = count($parts); $i < $l; ++$i) { $test = $this->_tokenizer->sqlExplode($parts[$i]); - if (count($test) == 3 && strtoupper($test[1]) == 'BETWEEN') { - $tmp[] = $parts[$i] . ' AND ' . $parts[++$i]; - } else if (count($test) == 4 && strtoupper($test[1]) == 'NOT' && strtoupper($test[2]) == 'BETWEEN') { - $tmp[] = $parts[$i] . ' AND ' . $parts[++$i]; + if (3 == count($test) && 'BETWEEN' == strtoupper($test[1])) { + $tmp[] = $parts[$i].' AND '.$parts[++$i]; + } elseif (4 == count($test) && 'NOT' == strtoupper($test[1]) && 'BETWEEN' == strtoupper($test[2])) { + $tmp[] = $parts[$i].' AND '.$parts[++$i]; } else { $tmp[] = $parts[$i]; } } - + $parts = $tmp; unset($tmp); @@ -82,56 +84,56 @@ public function parse($str) $r = implode(' AND ', $ret); } else { // Fix for #710 - if (substr($parts[0],0,1) == '(' && substr($parts[0], -1) == ')') { + if ('(' == substr($parts[0], 0, 1) && ')' == substr($parts[0], -1)) { return $this->parse(substr($parts[0], 1, -1)); + } + // Processing NOT here + if ('NOT ' === strtoupper(substr($parts[0], 0, 4))) { + $r = 'NOT ('.$this->parse(substr($parts[0], 4)).')'; } else { - // Processing NOT here - if (strtoupper(substr($parts[0], 0, 4)) === 'NOT ') { - $r = 'NOT ('.$this->parse(substr($parts[0], 4)).')'; - } else { - return $this->load($parts[0]); - } + return $this->load($parts[0]); } } } - - return '(' . $r . ')'; + + return '('.$r.')'; } /** - * parses a literal value and returns the parsed value + * parses a literal value and returns the parsed value. * * boolean literals are parsed to integers * components are parsed to associated table aliases * - * @param string $value literal value to be parsed + * @param string $value literal value to be parsed + * * @return string */ public function parseLiteralValue($value) { // check that value isn't a string - if (strpos($value, '\'') === false) { + if (false === strpos($value, '\'')) { // parse booleans $value = $this->query->getConnection() - ->dataDict->parseBoolean($value); + ->dataDict->parseBoolean($value) + ; $a = explode('.', $value); if (count($a) > 1) { - // either a float or a component.. + // either a float or a component.. - if ( ! is_numeric($a[0])) { + if (!is_numeric($a[0])) { // a component found - $field = array_pop($a); - $reference = implode('.', $a); - $value = $this->query->getConnection()->quoteIdentifier( - $this->query->getSqlTableAlias($reference). '.' . $field + $field = array_pop($a); + $reference = implode('.', $a); + $value = $this->query->getConnection()->quoteIdentifier( + $this->query->getSqlTableAlias($reference).'.'.$field ); } } - } else { - // string literal found } + // string literal found return $value; } diff --git a/lib/Doctrine/Query/Exception.php b/lib/Doctrine/Query/Exception.php index 35630770d..d02e037a0 100644 --- a/lib/Doctrine/Query/Exception.php +++ b/lib/Doctrine/Query/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Query_Exception + * Doctrine_Query_Exception. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Query/Filter.php b/lib/Doctrine/Query/Filter.php index 5598fac2b..b831bba49 100644 --- a/lib/Doctrine/Query/Filter.php +++ b/lib/Doctrine/Query/Filter.php @@ -20,44 +20,38 @@ */ /** - * Doctrine_Query_Filter + * Doctrine_Query_Filter. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Query_Filter implements Doctrine_Query_Filter_Interface { /** - * preQuery + * preQuery. * * Method for listening the preQuery method of Doctrine_Query and * hooking into the query building procedure, doing any custom / specialized * query building procedures that are neccessary. - * - * @return void */ public function preQuery(Doctrine_Query $query) { - } /** - * postQuery + * postQuery. * * Method for listening the postQuery method of Doctrine_Query and * to hook into the query building procedure, doing any custom / specialized * post query procedures (for example logging) that are neccessary. - * - * @param Doctrine_Query $query - * @return void */ public function postQuery(Doctrine_Query $query) { - } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Filter/Chain.php b/lib/Doctrine/Query/Filter/Chain.php index 2262a8b18..3cdc4fafc 100644 --- a/lib/Doctrine/Query/Filter/Chain.php +++ b/lib/Doctrine/Query/Filter/Chain.php @@ -20,28 +20,26 @@ */ /** - * Doctrine_Query_Filter_Chain + * Doctrine_Query_Filter_Chain. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Query_Filter_Chain { /** - * @var array $_filters an array of Doctrine_Query_Filter objects + * @var array an array of Doctrine_Query_Filter objects */ protected $_filters = array(); /** - * add - * - * @param Doctrine_Query_Filter $filter - * @return void + * add. */ public function add(Doctrine_Query_Filter $filter) { @@ -50,25 +48,19 @@ public function add(Doctrine_Query_Filter $filter) /** * returns a Doctrine_Query_Filter on success - * and null on failure - * - * @param mixed $key - * @return mixed + * and null on failure. */ public function get($key) { - if ( ! isset($this->_filters[$key])) { - throw new Doctrine_Query_Exception('Unknown filter ' . $key); + if (!isset($this->_filters[$key])) { + throw new Doctrine_Query_Exception('Unknown filter '.$key); } + return $this->_filters[$key]; } /** - * set - * - * @param mixed $key - * @param Doctrine_Query_Filter $listener - * @return void + * set. */ public function set($key, Doctrine_Query_Filter $listener) { @@ -76,13 +68,11 @@ public function set($key, Doctrine_Query_Filter $listener) } /** - * preQuery + * preQuery. * * Method for listening the preQuery method of Doctrine_Query and * hooking into the query building procedure, doing any custom / specialized * query building procedures that are neccessary. - * - * @return void */ public function preQuery(Doctrine_Query $query) { @@ -92,13 +82,11 @@ public function preQuery(Doctrine_Query $query) } /** - * postQuery + * postQuery. * * Method for listening the postQuery method of Doctrine_Query and * to hook into the query building procedure, doing any custom / specialized * post query procedures (for example logging) that are neccessary. - * - * @return void */ public function postQuery(Doctrine_Query $query) { @@ -106,4 +94,4 @@ public function postQuery(Doctrine_Query $query) $filter->postQuery($query); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Filter/Interface.php b/lib/Doctrine/Query/Filter/Interface.php index 9ed69e786..9258d3a0c 100644 --- a/lib/Doctrine/Query/Filter/Interface.php +++ b/lib/Doctrine/Query/Filter/Interface.php @@ -20,38 +20,34 @@ */ /** - * Doctrine_Query_Filter_Interface + * Doctrine_Query_Filter_Interface. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ interface Doctrine_Query_Filter_Interface { - /** - * preQuery + * preQuery. * * Method for listening the preQuery method of Doctrine_Query and * hooking into the query building procedure, doing any custom / specialized * query building procedures that are neccessary. - * - * @return void */ public function preQuery(Doctrine_Query $query); /** - * postQuery + * postQuery. * * Method for listening the postQuery method of Doctrine_Query and * to hook into the query building procedure, doing any custom / specialized * post query procedures (for example logging) that are neccessary. - * - * @return void */ public function postQuery(Doctrine_Query $query); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Forupdate.php b/lib/Doctrine/Query/Forupdate.php index 6e5851812..d51c7fd53 100644 --- a/lib/Doctrine/Query/Forupdate.php +++ b/lib/Doctrine/Query/Forupdate.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Query_Forupdate + * Doctrine_Query_Forupdate. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1352 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Forupdate extends Doctrine_Query_Part { - public function parse($forUpdate) + public function parse($forUpdate) { return (bool) $forUpdate; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/From.php b/lib/Doctrine/Query/From.php index d9f9c86fa..df6c28037 100644 --- a/lib/Doctrine/Query/From.php +++ b/lib/Doctrine/Query/From.php @@ -20,25 +20,25 @@ */ /** - * Doctrine_Query_From + * Doctrine_Query_From. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_From extends Doctrine_Query_Part { /** * DQL FROM PARSER - * parses the FROM part of the query string + * parses the FROM part of the query string. * * @param string $str - * @param boolean $return if to return the parsed FROM and skip load() - * @return void + * @param bool $return if to return the parsed FROM and skip load() */ public function parse($str, $return = false) { @@ -52,9 +52,10 @@ public function parse($str, $return = false) switch (trim($parts[0])) { case 'INNER': $operator = ':'; + // no break case 'LEFT': array_shift($parts); - break; + break; } $last = ''; @@ -68,7 +69,7 @@ public function parse($str, $return = false) $e = explode(' ', $part); - if (end($e) == 'INNER' || end($e) == 'LEFT') { + if ('INNER' == end($e) || 'LEFT' == end($e)) { $last = array_pop($e); } $part = implode(' ', $e); @@ -79,7 +80,7 @@ public function parse($str, $return = false) $e2 = explode('.', $e[0]); if ($operator) { - $e[0] = array_shift($e2) . $operator . implode('.', $e2); + $e[0] = array_shift($e2).$operator.implode('.', $e2); } if ($return) { @@ -89,8 +90,9 @@ public function parse($str, $return = false) } } - $operator = ($last == 'INNER') ? ':' : '.'; + $operator = ('INNER' == $last) ? ':' : '.'; } + return $from; } } diff --git a/lib/Doctrine/Query/Groupby.php b/lib/Doctrine/Query/Groupby.php index e7293a605..82c05096a 100644 --- a/lib/Doctrine/Query/Groupby.php +++ b/lib/Doctrine/Query/Groupby.php @@ -20,24 +20,22 @@ */ /** - * Doctrine_Query_Groupby + * Doctrine_Query_Groupby. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Groupby extends Doctrine_Query_Part { /** * DQL GROUP BY PARSER - * parses the group by part of the query string - * - * @param string $str - * @return void + * parses the group by part of the query string. */ public function parse($clause, $append = false) { @@ -48,19 +46,18 @@ public function parse($clause, $append = false) $pos = strpos($term[0], '('); $hasComma = false; - if ($pos !== false) { + if (false !== $pos) { $name = substr($term[0], 0, $pos); $term[0] = $this->query->parseFunctionExpression($term[0]); } else { - if (substr($term[0], 0, 1) !== "'" && substr($term[0], -1) !== "'") { - - if (strpos($term[0], '.') !== false) { - if ( ! is_numeric($term[0])) { + if ("'" !== substr($term[0], 0, 1) && "'" !== substr($term[0], -1)) { + if (false !== strpos($term[0], '.')) { + if (!is_numeric($term[0])) { $e = explode('.', $term[0]); $field = array_pop($e); - + // Check if field name still has comma if (($pos = strpos($field, ',')) !== false) { $field = substr($field, 0, $pos); @@ -70,7 +67,7 @@ public function parse($clause, $append = false) // Grab query connection $conn = $this->query->getConnection(); - if ($this->query->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->query->getType()) { $componentAlias = implode('.', $e); if (empty($componentAlias)) { @@ -90,18 +87,18 @@ public function parse($clause, $append = false) $field = $table->getColumnName($field); // check column existence - if ( ! $def) { - throw new Doctrine_Query_Exception('Unknown column ' . $field); + if (!$def) { + throw new Doctrine_Query_Exception('Unknown column '.$field); } if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->query->getSqlTableAlias($componentAlias); // build sql expression - $term[0] = $conn->quoteIdentifier($tableAlias) . '.' . $conn->quoteIdentifier($field); + $term[0] = $conn->quoteIdentifier($tableAlias).'.'.$conn->quoteIdentifier($field); } else { // build sql expression $field = $this->query->getRoot()->getColumnName($field); @@ -109,22 +106,21 @@ public function parse($clause, $append = false) } } } else { - if ( ! empty($term[0]) && - ! is_numeric($term[0]) && - $term[0] !== '?' && substr($term[0], 0, 1) !== ':') { - + if (!empty($term[0]) + && !is_numeric($term[0]) + && '?' !== $term[0] && ':' !== substr($term[0], 0, 1)) { $componentAlias = $this->query->getRootAlias(); $found = false; - + // Check if field name still has comma if (($pos = strpos($term[0], ',')) !== false) { $term[0] = substr($term[0], 0, $pos); $hasComma = true; } - if ($componentAlias !== false && - $componentAlias !== null) { + if (false !== $componentAlias + && null !== $componentAlias) { $queryComponent = $this->query->getQueryComponent($componentAlias); $table = $queryComponent['table']; @@ -138,18 +134,17 @@ public function parse($clause, $append = false) // get the actual column name from field name $term[0] = $table->getColumnName($term[0]); - if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->query->getSqlTableAlias($componentAlias); $conn = $this->query->getConnection(); - if ($this->query->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->query->getType()) { // build sql expression $term[0] = $conn->quoteIdentifier($tableAlias) - . '.' . $conn->quoteIdentifier($term[0]); + .'.'.$conn->quoteIdentifier($term[0]); } else { // build sql expression $term[0] = $conn->quoteIdentifier($term[0]); @@ -159,7 +154,7 @@ public function parse($clause, $append = false) } } - if ( ! $found) { + if (!$found) { $term[0] = $this->query->getSqlAggregateAlias($term[0]); } } @@ -167,7 +162,7 @@ public function parse($clause, $append = false) } } - $str .= $term[0] . ($hasComma ? ',' : '') . $term[1]; + $str .= $term[0].($hasComma ? ',' : '').$term[1]; } return $str; diff --git a/lib/Doctrine/Query/Having.php b/lib/Doctrine/Query/Having.php index cb7308d74..c68f76775 100644 --- a/lib/Doctrine/Query/Having.php +++ b/lib/Doctrine/Query/Having.php @@ -20,75 +20,73 @@ */ /** - * Doctrine_Query_Having + * Doctrine_Query_Having. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7666 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Having extends Doctrine_Query_Condition { /** - * DQL Aggregate Function parser + * DQL Aggregate Function parser. * * @param string $func - * @return mixed */ private function parseAggregateFunction($func) { $pos = strpos($func, '('); // Check for subqueries - if ($pos === 0 && substr($func, 1, 6) == 'SELECT') { + if (0 === $pos && 'SELECT' == substr($func, 1, 6)) { // This code is taken from WHERE.php $sub = $this->_tokenizer->bracketTrim($func); $q = $this->query->createSubquery()->parseDqlQuery($sub, false); $sql = $q->getSqlQuery(); $q->free(); - return '(' . $sql . ')'; + + return '('.$sql.')'; } - if ($pos !== false) { - $funcs = array(); + if (false !== $pos) { + $funcs = array(); - $name = substr($func, 0, $pos); - $func = substr($func, ($pos + 1), -1); + $name = substr($func, 0, $pos); + $func = substr($func, $pos + 1, -1); $params = $this->_tokenizer->bracketExplode($func, ',', '(', ')'); foreach ($params as $k => $param) { $params[$k] = $this->parseAggregateFunction($param); } - $funcs = $name . '(' . implode(', ', $params) . ')'; - - return $funcs; - } else { - return $this->_parseAliases($func); + return $name.'('.implode(', ', $params).')'; } + + return $this->_parseAliases($func); } /** * _parseAliases - * Processes part of the query not being an aggregate function + * Processes part of the query not being an aggregate function. * - * @param mixed $value * @return string */ private function _parseAliases($value) { - if ( ! is_numeric($value)) { + if (!is_numeric($value)) { $a = explode('.', $value); if (count($a) > 1) { $field = array_pop($a); - $ref = implode('.', $a); - $map = $this->query->load($ref, false); + $ref = implode('.', $a); + $map = $this->query->load($ref, false); $field = $map['table']->getColumnName($field); - $value = $this->query->getConnection()->quoteIdentifier($this->query->getSqlTableAlias($ref) . '.' . $field); + $value = $this->query->getConnection()->quoteIdentifier($this->query->getSqlTableAlias($ref).'.'.$field); } else { $field = end($a); if ($this->query->hasSqlAggregateAlias($field)) { @@ -102,22 +100,23 @@ private function _parseAliases($value) /** * load - * returns the parsed query part + * returns the parsed query part. * * @param string $having + * * @return string */ final public function load($having) { $tokens = $this->_tokenizer->bracketExplode($having, ' ', '(', ')'); $part = $this->parseAggregateFunction(array_shift($tokens)); - $operator = array_shift($tokens); - $value = implode(' ', $tokens); + $operator = array_shift($tokens); + $value = implode(' ', $tokens); // check the RHS for aggregate functions $value = $this->parseAggregateFunction($value); - $part .= ' ' . $operator . ' ' . $value; + $part .= ' '.$operator.' '.$value; return $part; } diff --git a/lib/Doctrine/Query/JoinCondition.php b/lib/Doctrine/Query/JoinCondition.php index 9de41e3cb..66413bd79 100644 --- a/lib/Doctrine/Query/JoinCondition.php +++ b/lib/Doctrine/Query/JoinCondition.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Query_JoinCondition + * Doctrine_Query_JoinCondition. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_JoinCondition extends Doctrine_Query_Condition @@ -38,32 +39,32 @@ public function load($condition) $e = $this->_tokenizer->sqlExplode($condition); foreach ($e as $k => $v) { - if ( ! $v) { - unset($e[$k]); - } + if (!$v) { + unset($e[$k]); + } } $e = array_values($e); if (($l = count($e)) > 2) { $leftExpr = $this->query->parseClause($e[0]); - $operator = $e[1]; + $operator = $e[1]; - if ($l == 4) { + if (4 == $l) { // FIX: "field NOT IN (XXX)" issue // Related to ticket #1329 - $operator .= ' ' . $e[2]; // Glue "NOT" and "IN" + $operator .= ' '.$e[2]; // Glue "NOT" and "IN" $e[2] = $e[3]; // Move "(XXX)" to previous index unset($e[3]); // Remove unused index - } else if ($l >= 5) { + } elseif ($l >= 5) { // FIX: "field BETWEEN field2 AND field3" issue // Related to ticket #1488 - $e[2] .= ' ' . $e[3] . ' ' . $e[4]; + $e[2] .= ' '.$e[3].' '.$e[4]; unset($e[3], $e[4]); // Remove unused indexes } - if (substr(trim($e[2]), 0, 1) != '(') { + if ('(' != substr(trim($e[2]), 0, 1)) { $expr = new Doctrine_Expression($e[2], $this->query->getConnection()); $e[2] = $expr->getSql(); } @@ -75,20 +76,21 @@ public function load($condition) // Defining needed information $value = $e[2]; - if (substr($value, 0, 1) == '(') { + if ('(' == substr($value, 0, 1)) { // trim brackets - $trimmed = $this->_tokenizer->bracketTrim($value); + $trimmed = $this->_tokenizer->bracketTrim($value); $trimmed_upper = strtoupper($trimmed); - if (substr($trimmed_upper, 0, 4) == 'FROM' || substr($trimmed_upper, 0, 6) == 'SELECT') { + if ('FROM' == substr($trimmed_upper, 0, 4) || 'SELECT' == substr($trimmed_upper, 0, 6)) { // subquery found $q = $this->query->createSubquery() - ->parseDqlQuery($trimmed, false); - $value = '(' . $q->getSqlQuery() . ')'; + ->parseDqlQuery($trimmed, false) + ; + $value = '('.$q->getSqlQuery().')'; $q->free(); - } elseif (substr($trimmed_upper, 0, 4) == 'SQL:') { + } elseif ('SQL:' == substr($trimmed_upper, 0, 4)) { // Change due to bug "(" XXX ")" - //$value = '(' . substr($trimmed, 4) . ')'; + // $value = '(' . substr($trimmed, 4) . ')'; $value = substr($trimmed, 4); } else { // simple in expression found @@ -99,12 +101,12 @@ public function load($condition) $value[] = $this->parseLiteralValue($part); } - $value = '(' . implode(', ', $value) . ')'; + $value = '('.implode(', ', $value).')'; } - } elseif ( ! $hasRightAggExpression) { + } elseif (!$hasRightAggExpression) { // Possible expression found (field1 AND field2) // In relation to ticket #1488 - $e = $this->_tokenizer->bracketExplode($value, array(' AND ', ' \&\& '), '(', ')'); + $e = $this->_tokenizer->bracketExplode($value, array(' AND ', ' \&\& '), '(', ')'); $value = array(); foreach ($e as $part) { @@ -115,15 +117,13 @@ public function load($condition) } if ($hasRightAggExpression) { - $rightExpr = $rightMatches[1] . '(' . $value . ')' . $rightMatches[3]; + $rightExpr = $rightMatches[1].'('.$value.')'.$rightMatches[3]; $rightExpr = $this->query->parseClause($rightExpr); } else { $rightExpr = $value; } - $condition = $leftExpr . ' ' . $operator . ' ' . $rightExpr; - - return $condition; + return $leftExpr.' '.$operator.' '.$rightExpr; } $parser = new Doctrine_Query_Where($this->query, $this->_tokenizer); @@ -131,8 +131,7 @@ public function load($condition) return $parser->parse($condition); } - - protected function _processPossibleAggExpression(& $expr, & $matches = array()) + protected function _processPossibleAggExpression(&$expr, &$matches = array()) { $hasAggExpr = preg_match('/(.*[^\s\(\=])\(([^\)]*)\)(.*)/', $expr, $matches); @@ -140,18 +139,18 @@ protected function _processPossibleAggExpression(& $expr, & $matches = array()) $expr = $matches[2]; // We need to process possible comma separated items - if (substr(trim($matches[3]), 0, 1) == ',') { + if (',' == substr(trim($matches[3]), 0, 1)) { $xplod = $this->_tokenizer->sqlExplode(trim($matches[3], ' )'), ','); $matches[3] = array(); foreach ($xplod as $part) { - if ($part != '') { + if ('' != $part) { $matches[3][] = $this->parseLiteralValue($part); } } - $matches[3] = '), ' . implode(', ', $matches[3]); + $matches[3] = '), '.implode(', ', $matches[3]); } } diff --git a/lib/Doctrine/Query/Limit.php b/lib/Doctrine/Query/Limit.php index c6c97bfaa..f2094141e 100644 --- a/lib/Doctrine/Query/Limit.php +++ b/lib/Doctrine/Query/Limit.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Query_Limit + * Doctrine_Query_Limit. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1352 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Limit extends Doctrine_Query_Part { - public function parse($limit) + public function parse($limit) { return (int) $limit; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Offset.php b/lib/Doctrine/Query/Offset.php index 29deb7b91..c47dd6869 100644 --- a/lib/Doctrine/Query/Offset.php +++ b/lib/Doctrine/Query/Offset.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Query_Offset + * Doctrine_Query_Offset. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1352 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Offset extends Doctrine_Query_Part @@ -36,4 +37,4 @@ public function parse($offset) { return (int) $offset; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Orderby.php b/lib/Doctrine/Query/Orderby.php index 6853d9e9e..639c98193 100644 --- a/lib/Doctrine/Query/Orderby.php +++ b/lib/Doctrine/Query/Orderby.php @@ -20,24 +20,24 @@ */ /** - * Doctrine_Query_Orderby + * Doctrine_Query_Orderby. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Orderby extends Doctrine_Query_Part { /** * DQL ORDER BY PARSER - * parses the order by part of the query string + * parses the order by part of the query string. * * @param string $clause - * @return void */ public function parse($clause, $append = false) { @@ -48,19 +48,18 @@ public function parse($clause, $append = false) $pos = strpos($term[0], '('); $hasComma = false; - if ($pos !== false) { + if (false !== $pos) { $name = substr($term[0], 0, $pos); $term[0] = $this->query->parseFunctionExpression($term[0], array($this, 'parse')); } else { - if (substr($term[0], 0, 1) !== "'" && substr($term[0], -1) !== "'") { - - if (strpos($term[0], '.') !== false) { - if ( ! is_numeric($term[0])) { + if ("'" !== substr($term[0], 0, 1) && "'" !== substr($term[0], -1)) { + if (false !== strpos($term[0], '.')) { + if (!is_numeric($term[0])) { $e = explode('.', $term[0]); $field = array_pop($e); - + // Check if field name still has comma if (($pos = strpos($field, ',')) !== false) { $field = substr($field, 0, $pos); @@ -70,7 +69,7 @@ public function parse($clause, $append = false) // Grab query connection $conn = $this->query->getConnection(); - if ($this->query->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->query->getType()) { $componentAlias = implode('.', $e); if (empty($componentAlias)) { @@ -90,19 +89,19 @@ public function parse($clause, $append = false) $field = $table->getColumnName($field); // check column existence - if ( ! $def) { - throw new Doctrine_Query_Exception('Unknown column ' . $field); + if (!$def) { + throw new Doctrine_Query_Exception('Unknown column '.$field); } if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->query->getSqlTableAlias($componentAlias); // build sql expression - $term[0] = $conn->quoteIdentifier($tableAlias) . '.' . $conn->quoteIdentifier($field); - + $term[0] = $conn->quoteIdentifier($tableAlias).'.'.$conn->quoteIdentifier($field); + // driver specific modifications $term[0] = method_exists($conn, 'modifyOrderByColumn') ? $conn->modifyOrderByColumn($table, $field, $term[0]) : $term[0]; } else { @@ -112,22 +111,21 @@ public function parse($clause, $append = false) } } } else { - if ( ! empty($term[0]) && - ! is_numeric($term[0]) && - $term[0] !== '?' && substr($term[0], 0, 1) !== ':') { - + if (!empty($term[0]) + && !is_numeric($term[0]) + && '?' !== $term[0] && ':' !== substr($term[0], 0, 1)) { $componentAlias = $this->query->getRootAlias(); $found = false; - + // Check if field name still has comma if (($pos = strpos($term[0], ',')) !== false) { $term[0] = substr($term[0], 0, $pos); $hasComma = true; } - if ($componentAlias !== false && - $componentAlias !== null) { + if (false !== $componentAlias + && null !== $componentAlias) { $queryComponent = $this->query->getQueryComponent($componentAlias); $table = $queryComponent['table']; @@ -141,23 +139,22 @@ public function parse($clause, $append = false) // get the actual column name from field name $field = $table->getColumnName($term[0]); - if (isset($def['owner'])) { - $componentAlias = $componentAlias . '.' . $def['owner']; + $componentAlias = $componentAlias.'.'.$def['owner']; } $tableAlias = $this->query->getSqlTableAlias($componentAlias); $conn = $this->query->getConnection(); - if ($this->query->getType() === Doctrine_Query::SELECT) { + if (Doctrine_Query::SELECT === $this->query->getType()) { // build sql expression $term[0] = $conn->quoteIdentifier($tableAlias) - . '.' . $conn->quoteIdentifier($field); + .'.'.$conn->quoteIdentifier($field); } else { // build sql expression $term[0] = $conn->quoteIdentifier($field); } - + // driver specific modifications $term[0] = method_exists($conn, 'modifyOrderByColumn') ? $conn->modifyOrderByColumn($table, $field, $term[0]) : $term[0]; } else { @@ -165,10 +162,10 @@ public function parse($clause, $append = false) } } - if ( ! $found) { + if (!$found) { $tmp = strtoupper(trim($term[0], ', ')); - if ($tmp !== 'DESC' && $tmp !== 'ASC') { + if ('DESC' !== $tmp && 'ASC' !== $tmp) { $term[0] = $this->query->getSqlAggregateAlias($term[0]); } } @@ -177,7 +174,7 @@ public function parse($clause, $append = false) } } - $str .= $term[0] . ($hasComma ? ',' : '') . $term[1]; + $str .= $term[0].($hasComma ? ',' : '').$term[1]; } return $str; diff --git a/lib/Doctrine/Query/Parser.php b/lib/Doctrine/Query/Parser.php index 100bf299a..2d64bf707 100644 --- a/lib/Doctrine/Query/Parser.php +++ b/lib/Doctrine/Query/Parser.php @@ -20,16 +20,15 @@ */ /** - * Doctrine_Query_Parser + * Doctrine_Query_Parser. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ -class Doctrine_Query_Parser +class Doctrine_Query_Parser { - -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Part.php b/lib/Doctrine/Query/Part.php index 629ed2ad4..1d0293d78 100644 --- a/lib/Doctrine/Query/Part.php +++ b/lib/Doctrine/Query/Part.php @@ -20,33 +20,34 @@ */ /** - * Doctrine_Query_Part + * Doctrine_Query_Part. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Query_Part { /** - * @var Doctrine_Query $query the query object associated with this parser + * @var Doctrine_Query the query object associated with this parser */ protected $query; - + protected $_tokenizer; /** - * @param Doctrine_Query $query the query object associated with this parser + * @param Doctrine_Query $query the query object associated with this parser */ public function __construct($query, Doctrine_Query_Tokenizer $tokenizer = null) { $this->query = $query; - if ( ! $tokenizer) { + if (!$tokenizer) { $tokenizer = new Doctrine_Query_Tokenizer(); } $this->_tokenizer = $tokenizer; diff --git a/lib/Doctrine/Query/Registry.php b/lib/Doctrine/Query/Registry.php index 8a5245b4c..0d9f5d9f1 100644 --- a/lib/Doctrine/Query/Registry.php +++ b/lib/Doctrine/Query/Registry.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Query_Registry + * Doctrine_Query_Registry. * - * @package Doctrine - * @subpackage Query * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Query_Registry @@ -40,44 +40,44 @@ public function add($key, $query) $query = clone $query; } - if (strpos($key, '/') === false) { + if (false === strpos($key, '/')) { $this->_queries[$key] = $query; } else { // namespace found - + $e = explode('/', $key); $this->_queries[$e[0]][$e[1]] = $query; } } - + public function get($key, $namespace = null) { if (isset($namespace)) { - if ( ! isset($this->_queries[$namespace][$key])) { - throw new Doctrine_Query_Registry_Exception('A query with the name ' . $namespace . '/' . $key . ' does not exist.'); + if (!isset($this->_queries[$namespace][$key])) { + throw new Doctrine_Query_Registry_Exception('A query with the name '.$namespace.'/'.$key.' does not exist.'); } $query = $this->_queries[$namespace][$key]; } else { - if ( ! isset($this->_queries[$key])) { - throw new Doctrine_Query_Registry_Exception('A query with the name ' . $key . ' does not exist.'); + if (!isset($this->_queries[$key])) { + throw new Doctrine_Query_Registry_Exception('A query with the name '.$key.' does not exist.'); } $query = $this->_queries[$key]; } - - if ( ! ($query instanceof Doctrine_Query)) { + + if (!($query instanceof Doctrine_Query)) { $query = Doctrine_Query::create() - ->parseDqlQuery($query); + ->parseDqlQuery($query) + ; } - + return clone $query; } - - + public function has($key, $namespace = null) { - return isset($namespace) + return isset($namespace) ? isset($this->_queries[$namespace][$key]) : isset($this->_queries[$key]); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Registry/Exception.php b/lib/Doctrine/Query/Registry/Exception.php index 55042f7f7..354b2719d 100644 --- a/lib/Doctrine/Query/Registry/Exception.php +++ b/lib/Doctrine/Query/Registry/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Query_Exception + * Doctrine_Query_Exception. * - * @package Doctrine - * @subpackage Query * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Query_Registry_Exception extends Doctrine_Query_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Query/Select.php b/lib/Doctrine/Query/Select.php index 349c78400..8490feb61 100644 --- a/lib/Doctrine/Query/Select.php +++ b/lib/Doctrine/Query/Select.php @@ -20,19 +20,20 @@ */ /** - * Doctrine_Query_Select + * Doctrine_Query_Select. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Select extends Doctrine_Query_Part { - public function parse($dql) + public function parse($dql) { $this->query->parseSelect($dql); } diff --git a/lib/Doctrine/Query/Set.php b/lib/Doctrine/Query/Set.php index 5da9871ef..4e9d30344 100644 --- a/lib/Doctrine/Query/Set.php +++ b/lib/Doctrine/Query/Set.php @@ -20,87 +20,87 @@ */ /** - * Doctrine_Query + * Doctrine_Query. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Set extends Doctrine_Query_Part { public function parse($dql) { - $terms = $this->_tokenizer->sqlExplode($dql, ' '); + $terms = $this->_tokenizer->sqlExplode($dql, ' '); $termsTranslation = array(); - + foreach ($terms as $term) { - $termOriginal = $term; - - // We need to check for agg functions here + $termOriginal = $term; + + // We need to check for agg functions here $matches = array(); $hasAggExpression = $this->_processPossibleAggExpression($term, $matches); - $lftExpr = (($hasAggExpression) ? $matches[1] . '(' : ''); - $rgtExpr = (($hasAggExpression) ? $matches[3] . ')' : ''); - - preg_match_all("/^([a-zA-Z0-9_]+[\.[a-zA-Z0-9_]+]*)(\sAS\s[a-zA-Z0-9_]+)?/i", $term, $m, PREG_SET_ORDER); - + $lftExpr = (($hasAggExpression) ? $matches[1].'(' : ''); + $rgtExpr = (($hasAggExpression) ? $matches[3].')' : ''); + + preg_match_all('/^([a-zA-Z0-9_]+[\\.[a-zA-Z0-9_]+]*)(\\sAS\\s[a-zA-Z0-9_]+)?/i', $term, $m, PREG_SET_ORDER); + if (isset($m[0])) { $processed = array(); - + foreach ($m as $piece) { $part = $piece[1]; $e = explode('.', trim($part)); - $fieldName = array_pop($e); - $reference = (count($e) > 0) ? implode('.', $e) : $this->query->getRootAlias(); - $aliasMap = $this->query->getQueryComponent($reference); + $fieldName = array_pop($e); + $reference = (count($e) > 0) ? implode('.', $e) : $this->query->getRootAlias(); + $aliasMap = $this->query->getQueryComponent($reference); - if ($aliasMap['table']->hasField($fieldName)) { - $columnName = $aliasMap['table']->getColumnName($fieldName); + if ($aliasMap['table']->hasField($fieldName)) { + $columnName = $aliasMap['table']->getColumnName($fieldName); $columnName = $aliasMap['table']->getConnection()->quoteIdentifier($columnName); $part = $columnName; } - - $processed[] = $part . (isset($piece[2]) ? $piece[2] : ''); + + $processed[] = $part.(isset($piece[2]) ? $piece[2] : ''); } - - $termsTranslation[$termOriginal] = $lftExpr . implode(' ', $processed) . $rgtExpr; + + $termsTranslation[$termOriginal] = $lftExpr.implode(' ', $processed).$rgtExpr; } - } + } return strtr($dql, $termsTranslation); } - - protected function _processPossibleAggExpression(& $expr, & $matches = array()) + protected function _processPossibleAggExpression(&$expr, &$matches = array()) { $hasAggExpr = preg_match('/(.*[^\s\(\=])\(([^\)]*)\)(.*)/', $expr, $matches); - + if ($hasAggExpr) { $expr = $matches[2]; // We need to process possible comma separated items - if (substr(trim($matches[3]), 0, 1) == ',') { + if (',' == substr(trim($matches[3]), 0, 1)) { $xplod = $this->_tokenizer->sqlExplode(trim($matches[3], ' )'), ','); - + $matches[3] = array(); - + foreach ($xplod as $part) { - if ($part != '') { + if ('' != $part) { $matches[3][] = $this->parseLiteralValue($part); } } - $matches[3] = '), ' . implode(', ', $matches[3]); + $matches[3] = '), '.implode(', ', $matches[3]); } } - + return $hasAggExpr; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Query/Tokenizer.php b/lib/Doctrine/Query/Tokenizer.php index aed58797d..a72a9aa41 100644 --- a/lib/Doctrine/Query/Tokenizer.php +++ b/lib/Doctrine/Query/Tokenizer.php @@ -20,24 +20,24 @@ */ /** - * Doctrine_Query_Tokenizer + * Doctrine_Query_Tokenizer. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Guilherme Blanco * @author Stefan Klug */ class Doctrine_Query_Tokenizer { - /** * Splits the given dql query into an array where keys represent different - * query part names and values are arrays splitted using sqlExplode method + * query part names and values are arrays splitted using sqlExplode method. * * example: * @@ -50,11 +50,11 @@ class Doctrine_Query_Tokenizer * 'where' => array('u.name', 'LIKE', '?') * ); * - * @param string $query DQL query + * @param string $query DQL query * - * @throws Doctrine_Query_Exception If some generic parsing error occurs + * @return array An array containing the query string parts * - * @return array An array containing the query string parts + * @throws Doctrine_Query_Exception If some generic parsing error occurs */ public function tokenizeQuery($query) { @@ -75,35 +75,33 @@ public function tokenizeQuery($query) case 'offset': case 'having': $p = $token; - //$parts[$token] = array(); + // $parts[$token] = array(); $parts[$token] = ''; - break; + break; case 'order': case 'group': $i = ($index + 1); - if (isset($tokens[$i]) && strtolower($tokens[$i]) === 'by') { + if (isset($tokens[$i]) && 'by' === strtolower($tokens[$i])) { $p = $token; $parts[$token] = ''; - //$parts[$token] = array(); + // $parts[$token] = array(); } else { - $parts[$p] .= "$token "; - //$parts[$p][] = $token; + $parts[$p] .= "{$token} "; + // $parts[$p][] = $token; } - break; + break; case 'by': break; default: - if ( ! isset($p)) { - throw new Doctrine_Query_Tokenizer_Exception( - "Couldn't tokenize query. Encountered invalid token: '$token'." - ); + if (!isset($p)) { + throw new Doctrine_Query_Tokenizer_Exception("Couldn't tokenize query. Encountered invalid token: '{$token}'."); } - $parts[$p] .= "$token "; - //$parts[$p][] = $token; + $parts[$p] .= "{$token} "; + // $parts[$p][] = $token; } } @@ -111,7 +109,7 @@ public function tokenizeQuery($query) } /** - * Trims brackets from string + * Trims brackets from string. * * @param string $str String to remove the brackets * @param string $e1 First bracket, usually '(' @@ -123,9 +121,9 @@ public function bracketTrim($str, $e1 = '(', $e2 = ')') { if (substr($str, 0, 1) === $e1 && substr($str, -1) === $e2) { return substr($str, 1, -1); - } else { - return $str; } + + return $str; } /** @@ -156,7 +154,7 @@ public function bracketExplode($str, $d = ' ', $e1 = '(', $e2 = ')') } // Bracket explode has to be case insensitive - $regexp = $this->getSplitRegExpFromArray($d) . 'i'; + $regexp = $this->getSplitRegExpFromArray($d).'i'; $terms = $this->clauseExplodeRegExp($str, $regexp, $e1, $e2); $res = array(); @@ -170,7 +168,7 @@ public function bracketExplode($str, $d = ' ', $e1 = '(', $e2 = ')') } /** - * Explode quotes from string + * Explode quotes from string. * * Note: quoteExplode always trims the returned pieces * @@ -195,7 +193,7 @@ public function quoteExplode($str, $d = ' ') } // According to the testcases quoteExplode is case insensitive - $regexp = $this->getSplitRegExpFromArray($d) . 'i'; + $regexp = $this->getSplitRegExpFromArray($d).'i'; $terms = $this->clauseExplodeCountBrackets($str, $regexp); $res = array(); @@ -209,7 +207,7 @@ public function quoteExplode($str, $d = ' ') /** * Explodes a string into array using custom brackets and - * quote delimeters + * quote delimeters. * * Note: sqlExplode trims all returned parts * @@ -255,7 +253,7 @@ public function sqlExplode($str, $d = ' ', $e1 = '(', $e2 = ')') /** * Explodes a string into array using custom brackets and quote delimeters * Each array element is a array of length 2 where the first entry contains - * the term, and the second entry contains the corresponding delimiter + * the term, and the second entry contains the corresponding delimiter. * * example: * @@ -291,9 +289,7 @@ public function clauseExplode($str, array $d, $e1 = '(', $e2 = ')') /** * Builds regular expression for split from array. Return regular - * expression to be applied - * - * @param $d + * expression to be applied. * * @return string */ @@ -302,7 +298,7 @@ private function getSplitRegExpFromArray(array $d) foreach ($d as $key => $string) { $escapedString = preg_quote($string); if (preg_match('#^\w+$#', $string)) { - $escapedString = "\W$escapedString\W"; + $escapedString = "\\W{$escapedString}\\W"; } $d[$key] = $escapedString; } @@ -311,16 +307,11 @@ private function getSplitRegExpFromArray(array $d) $d[] = '\s'; } - return '#(' . implode('|', $d) . ')#'; + return '#('.implode('|', $d).')#'; } /** - * Same as clauseExplode, but you give a regexp, which splits the string - * - * @param $str - * @param $regexp - * @param $e1 - * @param $e2 + * Same as clauseExplode, but you give a regexp, which splits the string. * * @return array */ @@ -330,7 +321,7 @@ private function clauseExplodeRegExp($str, $regexp, $e1 = '(', $e2 = ')') $terms = $this->mergeBracketTerms($terms); // This is only here to comply with the old function signature - foreach ($terms as & $val) { + foreach ($terms as &$val) { unset($val[2]); } @@ -338,12 +329,7 @@ private function clauseExplodeRegExp($str, $regexp, $e1 = '(', $e2 = ')') } /** - * this function is like clauseExplode, but it doesn't merge bracket terms - * - * @param $str - * @param $d - * @param $e1 - * @param $e2 + * this function is like clauseExplode, but it doesn't merge bracket terms. * * @return unknown_type */ @@ -355,13 +341,13 @@ private function clauseExplodeCountBrackets($str, $regexp, $e1 = '(', $e2 = ')') foreach ($quoteTerms as $key => $val) { if ($key & 1) { // a quoted string - // If the last term had no ending delimiter, we append the string to the element, - // otherwise, we create a new element without delimiter - if ($terms[$i - 1][1] == '') { - $terms[$i - 1][0] .= $val; - } else { - $terms[$i++] = array($val, '', 0); - } + // If the last term had no ending delimiter, we append the string to the element, + // otherwise, we create a new element without delimiter + if ('' == $terms[$i - 1][1]) { + $terms[$i - 1][0] .= $val; + } else { + $terms[$i++] = array($val, '', 0); + } } else { // Not a quoted string // Do the clause explode $subterms = $this->clauseExplodeNonQuoted($val, $regexp); @@ -374,7 +360,7 @@ private function clauseExplodeCountBrackets($str, $regexp, $e1 = '(', $e2 = ')') } // If the previous term had no delimiter, merge them - if ($i > 0 && $terms[$i - 1][1] == '') { + if ($i > 0 && '' == $terms[$i - 1][1]) { $first = array_shift($subterms); $idx = $i - 1; @@ -399,7 +385,7 @@ private function clauseExplodeCountBrackets($str, $regexp, $e1 = '(', $e2 = ')') * [0] = the term itself * [1] = the delimiter splitting this term from the next * [2] = the sum of opening and closing brackets in this term - * (eg. -2 means 2 closing brackets (or 1 opening and 3 closing)) + * (eg. -2 means 2 closing brackets (or 1 opening and 3 closing)). * * example: * @@ -415,11 +401,6 @@ private function clauseExplodeCountBrackets($str, $regexp, $e1 = '(', $e2 = ')') * array("d))'", '', -2) * ); * - * @param $str - * @param $d - * @param $e1 - * @param $e2 - * * @return array */ private function clauseExplodeNonQuoted($str, $regexp) @@ -430,7 +411,7 @@ private function clauseExplodeNonQuoted($str, $regexp) foreach ($str as $key => $val) { // Every odd entry is a delimiter, so add it to the previous term entry - if ( ! ($key & 1)) { + if (!($key & 1)) { $term[$i] = array($val, ''); } else { $term[$i++][1] = $val; @@ -446,7 +427,7 @@ private function clauseExplodeNonQuoted($str, $regexp) * unbalanced bracket count. * Note that only the third parameter in each term is used to get the * bracket overhang. This is needed to be able to handle quoted strings - * wich contain brackets + * wich contain brackets. * * example: * @@ -475,26 +456,25 @@ private function mergeBracketTerms(array $terms) $i = 0; foreach ($terms as $val) { - if ( ! isset($res[$i])) { + if (!isset($res[$i])) { $res[$i] = array($val[0], $val[1], $val[2]); } else { - $res[$i][0] .= $res[$i][1] . $val[0]; + $res[$i][0] .= $res[$i][1].$val[0]; $res[$i][1] = $val[1]; $res[$i][2] += $val[2]; } // Bracket overhang - if ($res[$i][2] == 0) { - $i++; + if (0 == $res[$i][2]) { + ++$i; } } return $res; } - /** - * Explodes the given string by + * Explodes the given string by . * * example: * @@ -513,11 +493,11 @@ private function mergeBracketTerms(array $terms) public function quotedStringExplode($str) { // Split by all possible incarnations of a quote - $split = array("\\'","''","'", "\\\"", "\"\"", "\""); + $split = array("\\'", "''", "'", '\\"', '""', '"'); foreach ($split as &$v) { $v = preg_quote($v); } - $split = '#(' . implode('|', $split) . ')#'; + $split = '#('.implode('|', $split).')#'; $str = preg_split($split, $str, -1, PREG_SPLIT_DELIM_CAPTURE); $parts = array(); @@ -527,26 +507,26 @@ public function quotedStringExplode($str) foreach ($str as $key => $val) { // This is some kind of quote if ($key & 1) { - if ( ! $mode) { - if ($val == "'" || $val == "\"") { + if (!$mode) { + if ("'" == $val || '"' == $val) { $mode = $val; - $i++; + ++$i; } - } else if ($mode == $val) { - if ( ! isset($parts[$i])) { + } elseif ($mode == $val) { + if (!isset($parts[$i])) { $parts[$i] = $val; } else { $parts[$i] .= $val; } $mode = false; - $i++; + ++$i; continue; } } - if ( ! isset($parts[$i])) { + if (!isset($parts[$i])) { $parts[$i] = $val; } else { $parts[$i] .= $val; diff --git a/lib/Doctrine/Query/Tokenizer/Exception.php b/lib/Doctrine/Query/Tokenizer/Exception.php index a658ce061..b4e46d647 100644 --- a/lib/Doctrine/Query/Tokenizer/Exception.php +++ b/lib/Doctrine/Query/Tokenizer/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Query_Exception + * Doctrine_Query_Exception. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2702 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Tokenizer_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Query/Where.php b/lib/Doctrine/Query/Where.php index 554d6751f..bc6e20c60 100644 --- a/lib/Doctrine/Query/Where.php +++ b/lib/Doctrine/Query/Where.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Query_Where + * Doctrine_Query_Where. * - * @package Doctrine - * @subpackage Query * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7672 $ + * * @author Konsta Vesterinen */ class Doctrine_Query_Where extends Doctrine_Query_Condition @@ -37,19 +38,19 @@ public function load($where) // Handle operator ("AND" | "OR"), reducing overhead of this method processment $possibleOp = strtolower($where); - if ($possibleOp == 'and' || $possibleOp == 'or') - { + if ('and' == $possibleOp || 'or' == $possibleOp) { return $where; } $where = $this->_tokenizer->bracketTrim(trim($where)); - $conn = $this->query->getConnection(); + $conn = $this->query->getConnection(); $terms = $this->_tokenizer->sqlExplode($where); if (count($terms) > 1) { - if (substr($where, 0, 6) == 'EXISTS') { + if ('EXISTS' == substr($where, 0, 6)) { return $this->parseExists($where, true); - } elseif (preg_match('/^NOT\s+EXISTS\b/i', $where) !== 0) { + } + if (0 !== preg_match('/^NOT\s+EXISTS\b/i', $where)) { return $this->parseExists($where, false); } } @@ -63,7 +64,7 @@ public function load($where) $rightExpr = array_pop($terms); $operator = trim(substr($where, strlen($leftExpr), -strlen($rightExpr))); - if (strpos($leftExpr, "'") === false && strpos($leftExpr, '(') === false) { + if (false === strpos($leftExpr, "'") && false === strpos($leftExpr, '(')) { // normal field reference found $a = explode('.', $leftExpr); $fieldname = array_pop($a); // Discard the field name (not needed!) @@ -81,7 +82,7 @@ public function load($where) // @TODO apply database dependent parsing // list($leftExpr, $operator, $rightExpr) = $conn->modifyWhereCondition($leftExpr, $operator, $rightExpr); $driverName = strtolower($conn->getDriverName()); - if ($driverName == 'mssql' && !empty($reference)) { + if ('mssql' == $driverName && !empty($reference)) { $cmp = $this->query->getQueryComponent($reference); $table = $cmp['table']; @@ -89,20 +90,17 @@ public function load($where) $column = $table->getColumnName($fieldname); $columndef = $table->getColumnDefinition($column); - if ($columndef['type'] == 'string' && ($columndef['length'] == NULL || $columndef['length'] > $conn->varchar_max_length) && strtoupper($rightExpr) != 'NULL') { + if ('string' == $columndef['type'] && (null == $columndef['length'] || $columndef['length'] > $conn->varchar_max_length) && 'NULL' != strtoupper($rightExpr)) { $operator = 'LIKE'; } } } - $sql = $this->_buildSql($leftExpr, $operator, $rightExpr); - - return $sql; - } else { - return $where; + return $this->_buildSql($leftExpr, $operator, $rightExpr); } - } + return $where; + } protected function _buildSql($leftExpr, $operator, $rightExpr) { @@ -112,41 +110,37 @@ protected function _buildSql($leftExpr, $operator, $rightExpr) // BETWEEN operation if ('BETWEEN' == strtoupper(substr($operator, 0, 7))) { $midExpr = trim(substr($operator, 7, -3)); - $operator = 'BETWEEN ' . $this->query->parseClause($midExpr) . ' AND'; + $operator = 'BETWEEN '.$this->query->parseClause($midExpr).' AND'; } // NOT BETWEEN operation if ('NOT BETWEEN' == strtoupper(substr($operator, 0, 11))) { $midExpr = trim(substr($operator, 11, -3)); - $operator = 'NOT BETWEEN ' . $this->query->parseClause($midExpr) . ' AND'; + $operator = 'NOT BETWEEN '.$this->query->parseClause($midExpr).' AND'; } $op = strtolower($operator); - $isInX = ($op == 'in' || $op == 'not in'); + $isInX = ('in' == $op || 'not in' == $op); // Check if we are not dealing with "obj.field IN :named" - if (substr($rightExpr, 0 , 1) == ':' && $isInX) { - throw new Doctrine_Query_Exception( - 'Cannot use ' . $operator . ' with a named parameter in "' . - $leftExprOriginal . ' ' . $operator . ' ' . $rightExpr . '"' - ); + if (':' == substr($rightExpr, 0, 1) && $isInX) { + throw new Doctrine_Query_Exception('Cannot use '.$operator.' with a named parameter in "'.$leftExprOriginal.' '.$operator.' '.$rightExpr.'"'); } // Right Expression - $rightExpr = ($rightExpr == '?' && $isInX) + $rightExpr = ('?' == $rightExpr && $isInX) ? $this->_buildWhereInArraySqlPart($rightExpr) : $this->query->parseClause($rightExpr); - return $leftExpr . ' ' . $operator . ' ' . $rightExpr; + return $leftExpr.' '.$operator.' '.$rightExpr; } - protected function _buildWhereInArraySqlPart($rightExpr) { $params = $this->query->getInternalParams(); $value = array(); - for ($i = 0, $l = count($params); $i < $l; $i++) { + for ($i = 0, $l = count($params); $i < $l; ++$i) { if (is_array($params[$i])) { $value = array_fill(0, count($params[$i]), $rightExpr); $this->query->adjustProcessedParam($i); @@ -155,14 +149,15 @@ protected function _buildWhereInArraySqlPart($rightExpr) } } - return '(' . (count($value) > 0 ? implode(', ', $value) : $rightExpr) . ')'; + return '('.(count($value) > 0 ? implode(', ', $value) : $rightExpr).')'; } /** - * parses an EXISTS expression + * parses an EXISTS expression. + * + * @param string $where query where part to be parsed + * @param bool $negation whether or not to use the NOT keyword * - * @param string $where query where part to be parsed - * @param boolean $negation whether or not to use the NOT keyword * @return string */ public function parseExists($where, $negation) @@ -171,7 +166,7 @@ public function parseExists($where, $negation) $pos = strpos($where, '('); - if ($pos == false) { + if (false == $pos) { throw new Doctrine_Query_Exception('Unknown expression, expected a subquery with () -marks'); } @@ -181,6 +176,6 @@ public function parseExists($where, $negation) $sql = $q->getSqlQuery(); $q->free(); - return $operator . ' (' . $sql . ')'; + return $operator.' ('.$sql.')'; } } diff --git a/lib/Doctrine/RawSql.php b/lib/Doctrine/RawSql.php index 73220e2e9..8488201c4 100644 --- a/lib/Doctrine/RawSql.php +++ b/lib/Doctrine/RawSql.php @@ -20,7 +20,7 @@ */ /** - * Doctrine_RawSql + * Doctrine_RawSql. * * Doctrine_RawSql is an implementation of Doctrine_Query_Abstract that skips the entire * DQL parsing procedure. The "DQL" that is passed to a RawSql query object for execution @@ -28,28 +28,30 @@ * in a RawSql query is the SELECT part, which has a special syntax that provides Doctrine * with the necessary information to properly hydrate the query results. * - * @package Doctrine - * @subpackage RawSql * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_RawSql extends Doctrine_Query_Abstract { /** - * @var array $fields + * @var array */ private $fields = array(); /** * Constructor. * - * @param Doctrine_Connection The connection object the query will use. - * @param Doctrine_Hydrator_Abstract The hydrator that will be used for generating result sets. + * @param Doctrine_Connection the connection object the query will use + * @param Doctrine_Hydrator_Abstract the hydrator that will be used for generating result sets */ - function __construct(Doctrine_Connection $connection = null, Doctrine_Hydrator_Abstract $hydrator = null) { + public function __construct(Doctrine_Connection $connection = null, Doctrine_Hydrator_Abstract $hydrator = null) + { parent::__construct($connection, $hydrator); // Fix #1472. It's alid to disable QueryCache since there's no DQL for RawSql. @@ -71,31 +73,34 @@ protected function clear() * the user of the RawSql query is responsible for writing SQL that is portable between * different DBMS. * - * @param string $queryPartName the name of the query part - * @param string $queryPart query part to be parsed - * @param boolean $append whether or not to append the query part to its stack - * if false is given, this method will overwrite - * the given query part stack with $queryPart - * @return Doctrine_Query this object + * @param string $queryPartName the name of the query part + * @param string $queryPart query part to be parsed + * @param bool $append whether or not to append the query part to its stack + * if false is given, this method will overwrite + * the given query part stack with $queryPart + * + * @return Doctrine_Query this object */ - public function parseDqlQueryPart($queryPartName, $queryPart, $append = false) + public function parseDqlQueryPart($queryPartName, $queryPart, $append = false) { - if ($queryPartName == 'select') { - $this->_parseSelectFields($queryPart); - return $this; - } - if ( ! isset($this->_sqlParts[$queryPartName])) { - $this->_sqlParts[$queryPartName] = array(); - } - - if ( ! $append) { - $this->_sqlParts[$queryPartName] = array($queryPart); - } else { - $this->_sqlParts[$queryPartName][] = $queryPart; - } - return $this; + if ('select' == $queryPartName) { + $this->_parseSelectFields($queryPart); + + return $this; + } + if (!isset($this->_sqlParts[$queryPartName])) { + $this->_sqlParts[$queryPartName] = array(); + } + + if (!$append) { + $this->_sqlParts[$queryPartName] = array($queryPart); + } else { + $this->_sqlParts[$queryPartName][] = $queryPart; + } + + return $this; } - + /** * Adds a DQL query part. Overrides Doctrine_Query_Abstract::_addDqlQueryPart(). * This implementation for RawSql parses the new parts right away, generating the SQL. @@ -104,7 +109,7 @@ protected function _addDqlQueryPart($queryPartName, $queryPart, $append = false) { return $this->parseDqlQueryPart($queryPartName, $queryPart, $append); } - + /** * Add select parts to fields. * @@ -116,7 +121,7 @@ private function _parseSelectFields($queryPart) $this->fields = $m[1]; $this->_sqlParts['select'] = array(); } - + /** * parseDqlQuery * parses an sql query and adds the parts to internal array. @@ -124,8 +129,9 @@ private function _parseSelectFields($queryPart) * This implementation simply tokenizes the provided query string and uses them * as SQL parts right away. * - * @param string $query query to be parsed - * @return Doctrine_RawSql this object + * @param string $query query to be parsed + * + * @return Doctrine_RawSql this object */ public function parseDqlQuery($query) { @@ -145,30 +151,30 @@ public function parseDqlQuery($query) case 'offset': case 'having': $type = $partLowerCase; - if ( ! isset($parts[$partLowerCase])) { + if (!isset($parts[$partLowerCase])) { $parts[$partLowerCase] = array(); } break; case 'order': case 'group': $i = $key + 1; - if (isset($tokens[$i]) && strtolower($tokens[$i]) === 'by') { - $type = $partLowerCase . 'by'; + if (isset($tokens[$i]) && 'by' === strtolower($tokens[$i])) { + $type = $partLowerCase.'by'; $parts[$type] = array(); } else { - //not a keyword so we add it to the previous type + // not a keyword so we add it to the previous type $parts[$type][] = $part; } break; case 'by': break; default: - //not a keyword so we add it to the previous type. - if ( ! isset($parts[$type][0])) { + // not a keyword so we add it to the previous type. + if (!isset($parts[$type][0])) { $parts[$type][0] = $part; } else { // why does this add to index 0 and not append to the - // array. If it had done that one could have used + // array. If it had done that one could have used // parseQueryPart. $parts[$type][0] .= ' '.$part; } @@ -185,10 +191,10 @@ public function parseDqlQuery($query) * getSqlQuery * builds the sql query. * - * @return string the built sql query + * @return string the built sql query */ public function getSqlQuery($params = array()) - { + { // Assign building/execution specific params $this->_params['exec'] = $params; @@ -199,47 +205,47 @@ public function getSqlQuery($params = array()) $this->fixArrayParameterValues($this->_execParams); $select = array(); - + $formatter = $this->getConnection()->formatter; foreach ($this->fields as $field) { $e = explode('.', $field); - if ( ! isset($e[1])) { + if (!isset($e[1])) { throw new Doctrine_RawSql_Exception('All selected fields in Sql query must be in format tableAlias.fieldName'); } // try to auto-add component - if ( ! $this->hasSqlTableAlias($e[0])) { + if (!$this->hasSqlTableAlias($e[0])) { try { $this->addComponent($e[0], ucwords($e[0])); } catch (Doctrine_Exception $exception) { - throw new Doctrine_RawSql_Exception('The associated component for table alias ' . $e[0] . ' couldn\'t be found.'); + throw new Doctrine_RawSql_Exception('The associated component for table alias '.$e[0].' couldn\'t be found.'); } } $componentAlias = $this->getComponentAlias($e[0]); - - if ($e[1] == '*') { + + if ('*' == $e[1]) { foreach ($this->_queryComponents[$componentAlias]['table']->getColumnNames() as $name) { - $field = $formatter->quoteIdentifier($e[0]) . '.' . $formatter->quoteIdentifier($name); + $field = $formatter->quoteIdentifier($e[0]).'.'.$formatter->quoteIdentifier($name); - $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($e[0] . '__' . $name); + $select[$componentAlias][$field] = $field.' AS '.$formatter->quoteIdentifier($e[0].'__'.$name); } } else { - $field = $formatter->quoteIdentifier($e[0]) . '.' . $formatter->quoteIdentifier($e[1]); - $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($e[0] . '__' . $e[1]); + $field = $formatter->quoteIdentifier($e[0]).'.'.$formatter->quoteIdentifier($e[1]); + $select[$componentAlias][$field] = $field.' AS '.$formatter->quoteIdentifier($e[0].'__'.$e[1]); } } // force-add all primary key fields - if ( ! isset($this->_sqlParts['distinct']) || $this->_sqlParts['distinct'] != true) { + if (!isset($this->_sqlParts['distinct']) || true != $this->_sqlParts['distinct']) { foreach ($this->getTableAliasMap() as $tableAlias => $componentAlias) { $map = $this->_queryComponents[$componentAlias]; foreach ((array) $map['table']->getIdentifierColumnNames() as $key) { - $field = $formatter->quoteIdentifier($tableAlias) . '.' . $formatter->quoteIdentifier($key); + $field = $formatter->quoteIdentifier($tableAlias).'.'.$formatter->quoteIdentifier($key); - if ( ! isset($this->_sqlParts['select'][$field])) { - $select[$componentAlias][$field] = $field . ' AS ' . $formatter->quoteIdentifier($tableAlias . '__' . $key); + if (!isset($this->_sqlParts['select'][$field])) { + $select[$componentAlias][$field] = $field.' AS '.$formatter->quoteIdentifier($tableAlias.'__'.$key); } } } @@ -247,55 +253,56 @@ public function getSqlQuery($params = array()) $q = 'SELECT '; - if (isset($this->_sqlParts['distinct']) && $this->_sqlParts['distinct'] == true) { + if (isset($this->_sqlParts['distinct']) && true == $this->_sqlParts['distinct']) { $q .= 'DISTINCT '; } // first add the fields of the root component reset($this->_queryComponents); $componentAlias = key($this->_queryComponents); - + $this->_rootAlias = $componentAlias; $q .= implode(', ', $select[$componentAlias]); unset($select[$componentAlias]); foreach ($select as $component => $fields) { - if ( ! empty($fields)) { - $q .= ', ' . implode(', ', $fields); + if (!empty($fields)) { + $q .= ', '.implode(', ', $fields); } } $string = $this->getInheritanceCondition($this->getRootAlias()); - if ( ! empty($string)) { + if (!empty($string)) { $this->_sqlParts['where'][] = $string; } - $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : ''; - $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : ''; - $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : ''; - $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : ''; - $q .= ( ! empty($this->_sqlParts['orderby']))? ' ORDER BY ' . implode(', ', $this->_sqlParts['orderby']) : ''; - $q .= ( ! empty($this->_sqlParts['limit']))? ' LIMIT ' . implode(' ', $this->_sqlParts['limit']) : ''; - $q .= ( ! empty($this->_sqlParts['offset']))? ' OFFSET ' . implode(' ', $this->_sqlParts['offset']) : ''; + $q .= (!empty($this->_sqlParts['from'])) ? ' FROM '.implode(' ', $this->_sqlParts['from']) : ''; + $q .= (!empty($this->_sqlParts['where'])) ? ' WHERE '.implode(' AND ', $this->_sqlParts['where']) : ''; + $q .= (!empty($this->_sqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_sqlParts['groupby']) : ''; + $q .= (!empty($this->_sqlParts['having'])) ? ' HAVING '.implode(' AND ', $this->_sqlParts['having']) : ''; + $q .= (!empty($this->_sqlParts['orderby'])) ? ' ORDER BY '.implode(', ', $this->_sqlParts['orderby']) : ''; + $q .= (!empty($this->_sqlParts['limit'])) ? ' LIMIT '.implode(' ', $this->_sqlParts['limit']) : ''; + $q .= (!empty($this->_sqlParts['offset'])) ? ' OFFSET '.implode(' ', $this->_sqlParts['offset']) : ''; - if ( ! empty($string)) { + if (!empty($string)) { array_pop($this->_sqlParts['where']); } + return $q; } - /** + /** * getCountQuery * builds the count query. * - * @return string the built sql query + * @return string the built sql query */ - public function getCountSqlQuery($params = array()) + public function getCountSqlQuery($params = array()) { - //Doing COUNT( DISTINCT rootComponent.id ) - //This is not correct, if the result is not hydrated by doctrine, but it mimics the behaviour of Doctrine_Query::getCountQuery + // Doing COUNT( DISTINCT rootComponent.id ) + // This is not correct, if the result is not hydrated by doctrine, but it mimics the behaviour of Doctrine_Query::getCountQuery reset($this->_queryComponents); $componentAlias = key($this->_queryComponents); @@ -305,33 +312,33 @@ public function getCountSqlQuery($params = array()) $fields = array(); foreach ((array) $this->_queryComponents[$componentAlias]['table']->getIdentifierColumnNames() as $key) { - $fields[] = $tableAlias . '.' . $key; + $fields[] = $tableAlias.'.'.$key; } - $q = 'SELECT COUNT(*) as num_results FROM (SELECT DISTINCT '.implode(', ',$fields); + $q = 'SELECT COUNT(*) as num_results FROM (SELECT DISTINCT '.implode(', ', $fields); $string = $this->getInheritanceCondition($this->getRootAlias()); - if ( ! empty($string)) { + if (!empty($string)) { $this->_sqlParts['where'][] = $string; } - $q .= ( ! empty($this->_sqlParts['from']))? ' FROM ' . implode(' ', $this->_sqlParts['from']) : ''; - $q .= ( ! empty($this->_sqlParts['where']))? ' WHERE ' . implode(' AND ', $this->_sqlParts['where']) : ''; - $q .= ( ! empty($this->_sqlParts['groupby']))? ' GROUP BY ' . implode(', ', $this->_sqlParts['groupby']) : ''; - $q .= ( ! empty($this->_sqlParts['having']))? ' HAVING ' . implode(' AND ', $this->_sqlParts['having']) : ''; + $q .= (!empty($this->_sqlParts['from'])) ? ' FROM '.implode(' ', $this->_sqlParts['from']) : ''; + $q .= (!empty($this->_sqlParts['where'])) ? ' WHERE '.implode(' AND ', $this->_sqlParts['where']) : ''; + $q .= (!empty($this->_sqlParts['groupby'])) ? ' GROUP BY '.implode(', ', $this->_sqlParts['groupby']) : ''; + $q .= (!empty($this->_sqlParts['having'])) ? ' HAVING '.implode(' AND ', $this->_sqlParts['having']) : ''; $q .= ') as results'; - if ( ! empty($string)) { + if (!empty($string)) { array_pop($this->_sqlParts['where']); } return $q; } - /** + /** * count - * fetches the count of the query + * fetches the count of the query. * * This method executes the main query without all the * selected fields, ORDER BY part, LIMIT part and OFFSET part. @@ -339,8 +346,10 @@ public function getCountSqlQuery($params = array()) * This is an exact copy of the Dql Version * * @see Doctrine_Query::count() - * @param array $params an array of prepared statement parameters - * @return integer the count of this query + * + * @param array $params an array of prepared statement parameters + * + * @return int the count of this query */ public function count($params = array()) { @@ -364,9 +373,9 @@ public function count($params = array()) /** * getFields - * returns the fields associated with this parser + * returns the fields associated with this parser. * - * @return array all the fields associated with this parser + * @return array all the fields associated with this parser */ public function getFields() { @@ -374,15 +383,15 @@ public function getFields() } /** - * addComponent + * addComponent. * * @param string $tableAlias - * @param string $componentName + * * @return Doctrine_RawSql */ public function addComponent($tableAlias, $path) { - $tmp = explode(' ', $path); + $tmp = explode(' ', $path); $originalAlias = (count($tmp) > 1) ? end($tmp) : null; $e = explode('.', $tmp[0]); @@ -405,7 +414,7 @@ public function addComponent($tableAlias, $path) $length = strlen($currPath); // build the current component path - $currPath = ($currPath) ? $currPath . '.' . $component : $component; + $currPath = ($currPath) ? $currPath.'.'.$component : $component; $delimeter = substr($fullPath, $length, 1); @@ -415,18 +424,19 @@ public function addComponent($tableAlias, $path) } else { $componentAlias = $currPath; } - if ( ! isset($table)) { + if (!isset($table)) { $conn = Doctrine_Manager::getInstance() - ->getConnectionForComponent($component); - + ->getConnectionForComponent($component) + ; + $table = $conn->getTable($component); $this->_queryComponents[$componentAlias] = array('table' => $table); } else { $relation = $table->getRelation($component); - $this->_queryComponents[$componentAlias] = array('table' => $relation->getTable(), - 'parent' => $parent, - 'relation' => $relation); + $this->_queryComponents[$componentAlias] = array('table' => $relation->getTable(), + 'parent' => $parent, + 'relation' => $relation); } $this->addSqlTableAlias($tableAlias, $componentAlias); @@ -438,17 +448,18 @@ public function addComponent($tableAlias, $path) /** * calculateResultCacheHash - * calculate hash key for result cache + * calculate hash key for result cache. * * @param array $params - * @return string the hash + * + * @return string the hash */ public function calculateResultCacheHash($params = array()) { $sql = $this->getSqlQuery(); $conn = $this->getConnection(); $params = $this->getFlattenedParams($params); - $hash = md5($this->_hydrator->getHydrationMode() . $conn->getName() . $conn->getOption('dsn') . $sql . var_export($params, true)); - return $hash; + + return md5($this->_hydrator->getHydrationMode().$conn->getName().$conn->getOption('dsn').$sql.var_export($params, true)); } } diff --git a/lib/Doctrine/RawSql/Exception.php b/lib/Doctrine/RawSql/Exception.php index a53bd400b..82662d5c6 100644 --- a/lib/Doctrine/RawSql/Exception.php +++ b/lib/Doctrine/RawSql/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_RawSql_Exception + * Doctrine_RawSql_Exception. * - * @package Doctrine - * @subpackage RawSql * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_RawSql_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Record.php b/lib/Doctrine/Record.php index 2a2d92c06..89a3917b0 100644 --- a/lib/Doctrine/Record.php +++ b/lib/Doctrine/Record.php @@ -21,82 +21,81 @@ /** * Doctrine_Record - * All record classes should inherit this super class + * All record classes should inherit this super class. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7673 $ */ abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Countable, IteratorAggregate, Serializable { /** - * STATE CONSTANTS + * STATE CONSTANTS. */ /** * DIRTY STATE - * a Doctrine_Record is in dirty state when its properties are changed + * a Doctrine_Record is in dirty state when its properties are changed. */ - const STATE_DIRTY = 1; + public const STATE_DIRTY = 1; /** * TDIRTY STATE * a Doctrine_Record is in transient dirty state when it is created - * and some of its fields are modified but it is NOT yet persisted into database + * and some of its fields are modified but it is NOT yet persisted into database. */ - const STATE_TDIRTY = 2; + public const STATE_TDIRTY = 2; /** * CLEAN STATE * a Doctrine_Record is in clean state when all of its properties are loaded from the database - * and none of its properties are changed + * and none of its properties are changed. */ - const STATE_CLEAN = 3; + public const STATE_CLEAN = 3; /** * PROXY STATE - * a Doctrine_Record is in proxy state when its properties are not fully loaded + * a Doctrine_Record is in proxy state when its properties are not fully loaded. */ - const STATE_PROXY = 4; + public const STATE_PROXY = 4; /** * NEW TCLEAN - * a Doctrine_Record is in transient clean state when it is created and none of its fields are modified + * a Doctrine_Record is in transient clean state when it is created and none of its fields are modified. */ - const STATE_TCLEAN = 5; + public const STATE_TCLEAN = 5; /** * LOCKED STATE - * a Doctrine_Record is temporarily locked during deletes and saves + * a Doctrine_Record is temporarily locked during deletes and saves. * * This state is used internally to ensure that circular deletes * and saves will not cause infinite loops */ - const STATE_LOCKED = 6; - - /** - * TLOCKED STATE - * a Doctrine_Record is temporarily locked (and transient) during deletes and saves - * - * This state is used internally to ensure that circular deletes - * and saves will not cause infinite loops - */ - const STATE_TLOCKED = 7; + public const STATE_LOCKED = 6; + /** + * TLOCKED STATE + * a Doctrine_Record is temporarily locked (and transient) during deletes and saves. + * + * This state is used internally to ensure that circular deletes + * and saves will not cause infinite loops + */ + public const STATE_TLOCKED = 7; /** - * @var Doctrine_Node_ node object + * @var Doctrine_Node_ node object */ protected $_node; /** - * @var integer $_id the primary keys of this object + * @var int the primary keys of this object */ - protected $_id = array(); + protected $_id = array(); /** * each element is one of 3 following types: @@ -104,115 +103,117 @@ abstract class Doctrine_Record extends Doctrine_Record_Abstract implements Count * - null - field has NULL value in DB * - Doctrine_Null - field value is unknown, it wasn't loaded yet * - * @var array $_data the record data + * @var array the record data */ - protected $_data = array(); + protected $_data = array(); /** - * @var array $_values the values array, aggregate values and such are mapped into this array + * @var array the values array, aggregate values and such are mapped into this array */ - protected $_values = array(); + protected $_values = array(); /** - * @var integer $_state the state of this record + * @var int the state of this record + * * @see STATE_* constants */ protected $_state; /** - * @var array $_lastModified an array containing field names that were modified in the previous transaction + * @var array an array containing field names that were modified in the previous transaction */ protected $_lastModified = array(); /** - * @var array $_modified an array containing field names that have been modified + * @var array an array containing field names that have been modified + * * @todo Better name? $_modifiedFields? */ - protected $_modified = array(); + protected $_modified = array(); /** - * @var array $_oldValues an array of the old values from set properties + * @var array an array of the old values from set properties */ - protected $_oldValues = array(); + protected $_oldValues = array(); /** - * @var Doctrine_Validator_ErrorStack error stack object + * @var Doctrine_Validator_ErrorStack error stack object */ protected $_errorStack; /** - * @var array $_references an array containing all the references + * @var array an array containing all the references */ - protected $_references = array(); + protected $_references = array(); /** - * Doctrine_Collection of objects needing to be deleted on save + * Doctrine_Collection of objects needing to be deleted on save. * * @var string */ protected $_pendingDeletes = array(); /** - * Array of pending un links in format alias => keys to be executed after save + * Array of pending un links in format alias => keys to be executed after save. * - * @var array $_pendingUnlinks + * @var array */ protected $_pendingUnlinks = array(); /** - * Array of custom accessors for cache + * Array of custom accessors for cache. * * @var array */ protected static $_customAccessors = array(); /** - * Array of custom mutators for cache + * Array of custom mutators for cache. * * @var array */ protected static $_customMutators = array(); /** - * Whether or not to serialize references when a Doctrine_Record is serialized + * Whether or not to serialize references when a Doctrine_Record is serialized. * - * @var boolean + * @var bool */ protected $_serializeReferences = false; /** - * Array containing the save hooks and events that have been invoked + * Array containing the save hooks and events that have been invoked. * * @var array */ protected $_invokedSaveHooks = array(); /** - * @var integer $index this index is used for creating object identifiers + * @var int this index is used for creating object identifiers */ private static $_index = 1; /** - * @var integer $oid object identifier, each Record object has a unique object identifier + * @var int object identifier, each Record object has a unique object identifier */ private $_oid; /** - * constructor - * @param Doctrine_Table|null $table a Doctrine_Table object or null, - * if null the table object is retrieved from current connection + * constructor. * - * @param boolean $isNewEntry whether or not this record is transient + * @param Doctrine_Table|null $table a Doctrine_Table object or null, + * if null the table object is retrieved from current connection + * @param bool $isNewEntry whether or not this record is transient * - * @throws Doctrine_Connection_Exception if object is created using the new operator and there are no - * open connections - * @throws Doctrine_Record_Exception if the cleanData operation fails somehow + * @throws Doctrine_Connection_Exception if object is created using the new operator and there are no + * open connections + * @throws Doctrine_Record_Exception if the cleanData operation fails somehow */ public function __construct($table = null, $isNewEntry = false) { if (isset($table) && $table instanceof Doctrine_Table) { $this->_table = $table; - $exists = ( ! $isNewEntry); + $exists = (!$isNewEntry); } else { // get the table of this class $class = get_class($this); @@ -223,13 +224,13 @@ public function __construct($table = null, $isNewEntry = false) // Check if the current connection has the records table in its registry // If not this record is only used for creating table definition and setting up // relations. - if ( ! $this->_table->getConnection()->hasTable($this->_table->getComponentName())) { + if (!$this->_table->getConnection()->hasTable($this->_table->getComponentName())) { return; } $this->_oid = self::$_index; - self::$_index++; + ++self::$_index; // get the data array $this->_data = $this->_table->getData(); @@ -241,7 +242,7 @@ public function __construct($table = null, $isNewEntry = false) $this->prepareIdentifiers($exists); - if ( ! $exists) { + if (!$exists) { if ($count > count($this->_values)) { $this->_state = Doctrine_Record::STATE_TDIRTY; } else { @@ -254,7 +255,7 @@ public function __construct($table = null, $isNewEntry = false) $this->_state = Doctrine_Record::STATE_CLEAN; if ($this->isInProxyState()) { - $this->_state = Doctrine_Record::STATE_PROXY; + $this->_state = Doctrine_Record::STATE_PROXY; } } @@ -271,23 +272,25 @@ public function __construct($table = null, $isNewEntry = false) /** * Set whether or not to serialize references. * This is used by caching since we want to serialize references when caching - * but not when just normally serializing a instance + * but not when just normally serializing a instance. * - * @param boolean $bool - * @return boolean $bool + * @param bool $bool + * + * @return bool $bool */ public function serializeReferences($bool = null) { - if ( ! is_null($bool)) { + if (!is_null($bool)) { $this->_serializeReferences = $bool; } + return $this->_serializeReferences; } /** * the current instance counter used to generate unique ids for php objects. Contains the next identifier. * - * @return integer + * @return int */ public static function _index() { @@ -297,26 +300,25 @@ public static function _index() /** * setUp * this method is used for setting up relations and attributes - * it should be implemented by child classes - * - * @return void + * it should be implemented by child classes. */ public function setUp() - { } + { + } + /** * construct * Empty template method to provide concrete Record classes with the possibility - * to hook into the constructor procedure - * - * @return void + * to hook into the constructor procedure. */ public function construct() - { } + { + } /** * @see $_oid; * - * @return integer the object identifier + * @return int the object identifier */ public function getOid() { @@ -335,24 +337,25 @@ public function oid() * $this->invokeSaveHooks('pre', 'save'); * * - * @param string $when 'post' or 'pre' - * @param string $type serialize, unserialize, save, delete, update, insert, validate, dqlSelect, dqlDelete, hydrate - * @param Doctrine_Event $event event raised - * @return Doctrine_Event the event generated using the type, if not specified + * @param string $when 'post' or 'pre' + * @param string $type serialize, unserialize, save, delete, update, insert, validate, dqlSelect, dqlDelete, hydrate + * @param Doctrine_Event $event event raised + * + * @return Doctrine_Event the event generated using the type, if not specified */ public function invokeSaveHooks($when, $type, $event = null) { - $func = $when . ucfirst($type); + $func = $when.ucfirst($type); if (is_null($event)) { - $constant = constant('Doctrine_Event::RECORD_' . strtoupper($type)); - //echo $func . " - " . 'Doctrine_Event::RECORD_' . strtoupper($type) . "\n"; + $constant = constant('Doctrine_Event::RECORD_'.strtoupper($type)); + // echo $func . " - " . 'Doctrine_Event::RECORD_' . strtoupper($type) . "\n"; $event = new Doctrine_Event($this, $constant); } - if ( ! isset($this->_invokedSaveHooks[$func])) { - $this->$func($event); - $this->getTable()->getRecordListener()->$func($event); + if (!isset($this->_invokedSaveHooks[$func])) { + $this->{$func}($event); + $this->getTable()->getRecordListener()->{$func}($event); $this->_invokedSaveHooks[$func] = $event; } else { @@ -363,7 +366,7 @@ public function invokeSaveHooks($when, $type, $event = null) } /** - * makes all the already used save hooks available again + * makes all the already used save hooks available again. */ public function clearInvokedSaveHooks() { @@ -373,17 +376,18 @@ public function clearInvokedSaveHooks() /** * tests validity of the record using the current data. * - * @param boolean $deep run the validation process on the relations - * @param boolean $hooks invoke save hooks before start - * @return boolean whether or not this record is valid + * @param bool $deep run the validation process on the relations + * @param bool $hooks invoke save hooks before start + * + * @return bool whether or not this record is valid */ public function isValid($deep = false, $hooks = true) { - if ( ! $this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) { + if (!$this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) { return true; } - if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) { + if (self::STATE_LOCKED == $this->_state || self::STATE_TLOCKED == $this->_state) { return true; } @@ -400,12 +404,11 @@ public function isValid($deep = false, $hooks = true) $this->preValidate($event); $this->getTable()->getRecordListener()->preValidate($event); - if ( ! $event->skipOperation) { - + if (!$event->skipOperation) { $validator = new Doctrine_Validator(); $validator->validateRecord($this); $this->validate(); - if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) { + if (self::STATE_TDIRTY == $this->_state || self::STATE_TCLEAN == $this->_state) { $this->validateOnInsert(); } else { $this->validateOnUpdate(); @@ -415,19 +418,19 @@ public function isValid($deep = false, $hooks = true) $this->getTable()->getRecordListener()->postValidate($event); $this->postValidate($event); - $valid = $this->getErrorStack()->count() == 0 ? true : false; + $valid = 0 == $this->getErrorStack()->count() ? true : false; if ($valid && $deep) { $stateBeforeLock = $this->_state; $this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED; foreach ($this->_references as $reference) { if ($reference instanceof Doctrine_Record) { - if ( ! $valid = $reference->isValid($deep)) { + if (!$valid = $reference->isValid($deep)) { break; } - } else if ($reference instanceof Doctrine_Collection) { + } elseif ($reference instanceof Doctrine_Collection) { foreach ($reference as $record) { - if ( ! $valid = $record->isValid($deep)) { + if (!$valid = $record->isValid($deep)) { break; } } @@ -445,7 +448,8 @@ public function isValid($deep = false, $hooks = true) * validations that are neccessary. */ protected function validate() - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -453,7 +457,8 @@ protected function validate() * updated. */ protected function validateOnUpdate() - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -461,63 +466,72 @@ protected function validateOnUpdate() * inserted into the data store the first time. */ protected function validateOnInsert() - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the serializing procedure. */ public function preSerialize($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the serializing procedure. */ public function postSerialize($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the serializing procedure. */ public function preUnserialize($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the serializing procedure. */ public function postUnserialize($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the saving procedure. */ public function preSave($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the saving procedure. */ public function postSave($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the deletion procedure. */ public function preDelete($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility * to hook into the deletion procedure. */ public function postDelete($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -525,7 +539,8 @@ public function postDelete($event) * updated. */ public function preUpdate($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -533,7 +548,8 @@ public function preUpdate($event) * updated. */ public function postUpdate($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -541,7 +557,8 @@ public function postUpdate($event) * inserted into the data store the first time. */ public function preInsert($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -549,7 +566,8 @@ public function preInsert($event) * inserted into the data store the first time. */ public function postInsert($event) - { } + { + } /** * Empty template method to provide concrete Record classes with the possibility @@ -557,52 +575,60 @@ public function postInsert($event) * validating it. */ public function preValidate($event) - { } + { + } + /** * Empty template method to provide concrete Record classes with the possibility * to hook into the validation procedure. */ public function postValidate($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter DQL select - * queries at runtime + * queries at runtime. */ public function preDqlSelect($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter DQL update - * queries at runtime + * queries at runtime. */ public function preDqlUpdate($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter DQL delete - * queries at runtime + * queries at runtime. */ public function preDqlDelete($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter hydration - * before it runs + * before it runs. */ public function preHydrate($event) - { } + { + } /** * Empty template method to provide Record classes with the ability to alter hydration - * after it runs + * after it runs. */ public function postHydrate($event) - { } + { + } /** * Get the record error stack as a human readable string. - * Useful for outputting errors to user via web browser + * Useful for outputting errors to user via web browser. * * @return string $message */ @@ -613,24 +639,25 @@ public function getErrorStackAsString() if (count($errorStack)) { $message = sprintf("Validation failed in class %s\n\n", get_class($this)); - $message .= " " . count($errorStack) . " field" . (count($errorStack) > 1 ? 's' : null) . " had validation error" . (count($errorStack) > 1 ? 's' : null) . ":\n\n"; + $message .= ' '.count($errorStack).' field'.(count($errorStack) > 1 ? 's' : null).' had validation error'.(count($errorStack) > 1 ? 's' : null).":\n\n"; foreach ($errorStack as $field => $errors) { - $message .= " * " . count($errors) . " validator" . (count($errors) > 1 ? 's' : null) . " failed on $field (" . implode(", ", $errors) . ")\n"; + $message .= ' * '.count($errors).' validator'.(count($errors) > 1 ? 's' : null)." failed on {$field} (".implode(', ', $errors).")\n"; } + return $message; - } else { - return false; } + + return false; } /** * retrieves the ErrorStack. To be called after a failed validation attempt (@see isValid()). * - * @return Doctrine_Validator_ErrorStack returns the errorStack associated with this record + * @return Doctrine_Validator_ErrorStack returns the errorStack associated with this record */ public function getErrorStack() { - if ( ! $this->_errorStack) { + if (!$this->_errorStack) { $this->_errorStack = new Doctrine_Validator_ErrorStack(get_class($this)); } @@ -638,16 +665,18 @@ public function getErrorStack() } /** - * assigns the ErrorStack or returns it if called without parameters + * assigns the ErrorStack or returns it if called without parameters. * * @param Doctrine_Validator_ErrorStack errorStack to be assigned for this record - * @return void|Doctrine_Validator_ErrorStack returns the errorStack associated with this record + * @param mixed|null $stack + * + * @return void|Doctrine_Validator_ErrorStack returns the errorStack associated with this record */ public function errorStack($stack = null) { - if ($stack !== null) { - if ( ! ($stack instanceof Doctrine_Validator_ErrorStack)) { - throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.'); + if (null !== $stack) { + if (!($stack instanceof Doctrine_Validator_ErrorStack)) { + throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.'); } $this->_errorStack = $stack; } else { @@ -656,9 +685,7 @@ public function errorStack($stack = null) } /** - * Assign the inheritance column values - * - * @return void + * Assign the inheritance column values. */ public function assignInheritanceValues() { @@ -667,7 +694,7 @@ public function assignInheritanceValues() $k = $this->_table->getFieldName($k); $old = $this->get($k, false); - if (((string) $old !== (string) $v || $old === null) && !in_array($k, $this->_modified)) { + if (((string) $old !== (string) $v || null === $old) && !in_array($k, $this->_modified)) { $this->set($k, $v); } } @@ -675,26 +702,27 @@ public function assignInheritanceValues() /** * setDefaultValues - * sets the default values for records internal data + * sets the default values for records internal data. + * + * @param bool $overwrite whether or not to overwrite the already set values * - * @param boolean $overwrite whether or not to overwrite the already set values - * @return boolean + * @return bool */ public function assignDefaultValues($overwrite = false) { - if ( ! $this->_table->hasDefaultValues()) { + if (!$this->_table->hasDefaultValues()) { return false; } foreach ($this->_data as $column => $value) { $default = $this->_table->getDefaultValueOf($column); - if ($default === null) { + if (null === $default) { continue; } if ($value === self::$_null || $overwrite) { $this->_data[$column] = $default; - $this->_modified[] = $column; + $this->_modified[] = $column; $this->_state = Doctrine_Record::STATE_TDIRTY; } } @@ -706,8 +734,9 @@ public function assignDefaultValues($overwrite = false) * record and returns the values that were removed from $data. Also converts * any values of 'null' to objects of type Doctrine_Null. * - * @param array $data data array to be cleaned - * @return array values cleaned from data + * @param array $data data array to be cleaned + * + * @return array values cleaned from data */ public function cleanData(&$data) { @@ -717,9 +746,9 @@ public function cleanData(&$data) foreach ($this->getTable()->getFieldNames() as $fieldName) { if (isset($tmp[$fieldName])) { $data[$fieldName] = $tmp[$fieldName]; - } else if (array_key_exists($fieldName, $tmp)) { + } elseif (array_key_exists($fieldName, $tmp)) { $data[$fieldName] = null; - } else if ( !isset($this->_data[$fieldName])) { + } elseif (!isset($this->_data[$fieldName])) { $data[$fieldName] = self::$_null; } unset($tmp[$fieldName]); @@ -730,11 +759,9 @@ public function cleanData(&$data) /** * hydrate - * hydrates this object from given array + * hydrates this object from given array. * - * @param array $data - * @param boolean $overwriteLocalChanges whether to overwrite the unsaved (dirty) data - * @return void + * @param bool $overwriteLocalChanges whether to overwrite the unsaved (dirty) data */ public function hydrate(array $data, $overwriteLocalChanges = true) { @@ -755,10 +782,9 @@ public function hydrate(array $data, $overwriteLocalChanges = true) /** * prepareIdentifiers - * prepares identifiers for later use + * prepares identifiers for later use. * - * @param boolean $exists whether or not this record exists in persistent data store - * @return void + * @param bool $exists whether or not this record exists in persistent data store */ private function prepareIdentifiers($exists = true) { @@ -792,7 +818,7 @@ private function prepareIdentifiers($exists = true) /** * serialize - * this method is automatically called when an instance of Doctrine_Record is serialized + * this method is automatically called when an instance of Doctrine_Record is serialized. * * @return string */ @@ -804,11 +830,11 @@ public function serialize() } /** - * this method is automatically called everytime an instance is unserialized + * this method is automatically called everytime an instance is unserialized. * - * @param string $serialized Doctrine_Record as serialized string - * @throws Doctrine_Record_Exception if the cleanData operation fails somehow - * @return void + * @param string $serialized Doctrine_Record as serialized string + * + * @throws Doctrine_Record_Exception if the cleanData operation fails somehow */ public function unserialize($serialized) { @@ -818,12 +844,12 @@ public function unserialize($serialized) } /** - * Serializes the current instance for php 7.4+ + * Serializes the current instance for php 7.4+. * * @return array */ - public function __serialize() { - + public function __serialize() + { $event = new Doctrine_Event($this, Doctrine_Event::RECORD_SERIALIZE); $this->preSerialize($event); @@ -831,13 +857,10 @@ public function __serialize() { $vars = get_object_vars($this); - if ( ! $this->serializeReferences()) { + if (!$this->serializeReferences()) { unset($vars['_references']); } - unset($vars['_table']); - unset($vars['_errorStack']); - unset($vars['_filter']); - unset($vars['_node']); + unset($vars['_table'], $vars['_errorStack'], $vars['_filter'], $vars['_node']); $data = $this->_data; if ($this->exists()) { @@ -845,7 +868,7 @@ public function __serialize() { } foreach ($data as $k => $v) { - if ($v instanceof Doctrine_Record && $this->_table->getTypeOf($k) != 'object') { + if ($v instanceof Doctrine_Record && 'object' != $this->_table->getTypeOf($k)) { unset($vars['_data'][$k]); } elseif ($v === self::$_null) { unset($vars['_data'][$k]); @@ -872,15 +895,13 @@ public function __serialize() { } /** - * Unserializes a Doctrine_Record instance for php 7.4+ - * - * @param array $serialized + * Unserializes a Doctrine_Record instance for php 7.4+. */ public function __unserialize($data) { $event = new Doctrine_Event($this, Doctrine_Event::RECORD_UNSERIALIZE); - $manager = Doctrine_Manager::getInstance(); + $manager = Doctrine_Manager::getInstance(); $connection = $manager->getConnectionForComponent(get_class($this)); $this->_table = $connection->getTable(get_class($this)); @@ -888,8 +909,8 @@ public function __unserialize($data) $this->preUnserialize($event); $this->getTable()->getRecordListener()->preUnserialize($event); - foreach($data as $k => $v) { - $this->$k = $v; + foreach ($data as $k => $v) { + $this->{$k} = $v; } foreach ($this->_data as $k => $v) { @@ -904,7 +925,6 @@ public function __unserialize($data) case 'enum': $this->_data[$k] = $this->_table->enumValue($k, $this->_data[$k]); break; - } } @@ -918,7 +938,7 @@ public function __unserialize($data) // Add the unserialized record to repository and entity map. $this->_oid = self::$_index; - self::$_index++; + ++self::$_index; $this->_table->getRepository()->add($this); $this->_table->addRecord($this); @@ -931,17 +951,19 @@ public function __unserialize($data) } /** - * assigns the state of this record or returns it if called without parameters + * assigns the state of this record or returns it if called without parameters. + * + * @param int|string $state if set, this method tries to set the record state to $state * - * @param integer|string $state if set, this method tries to set the record state to $state * @see Doctrine_Record::STATE_* constants * - * @throws Doctrine_Record_State_Exception if trying to set an unknown state - * @return null|integer + * @return int|null + * + * @throws Doctrine_Record_State_Exception if trying to set an unknown state */ public function state($state = null) { - if ($state == null) { + if (null == $state) { return $this->_state; } @@ -952,10 +974,10 @@ public function state($state = null) } else { $err = true; } - } else if (is_string($state)) { + } elseif (is_string($state)) { $upper = strtoupper($state); - $const = 'Doctrine_Record::STATE_' . $upper; + $const = 'Doctrine_Record::STATE_'.$upper; if (defined($const)) { $this->_state = constant($const); } else { @@ -963,32 +985,32 @@ public function state($state = null) } } - if ($this->_state === Doctrine_Record::STATE_TCLEAN || - $this->_state === Doctrine_Record::STATE_CLEAN) { + if (Doctrine_Record::STATE_TCLEAN === $this->_state + || Doctrine_Record::STATE_CLEAN === $this->_state) { $this->_resetModified(); } if ($err) { - throw new Doctrine_Record_State_Exception('Unknown record state ' . $state); + throw new Doctrine_Record_State_Exception('Unknown record state '.$state); } } /** * refresh - * refresh internal data from the database - * - * @param bool $deep If true, fetch also current relations. Caution: this deletes - * any aggregated values you may have queried beforee + * refresh internal data from the database. * - * @throws Doctrine_Record_Exception When the refresh operation fails (when the database row - * this record represents does not exist anymore) + * @param bool $deep If true, fetch also current relations. Caution: this deletes + * any aggregated values you may have queried beforee * * @return false|Doctrine_Record false if the record is not saved yet + * + * @throws Doctrine_Record_Exception When the refresh operation fails (when the database row + * this record represents does not exist anymore) */ public function refresh($deep = false) { $id = $this->identifier(); - if ( ! is_array($id)) { + if (!is_array($id)) { $id = array($id); } if (empty($id)) { @@ -1002,9 +1024,9 @@ public function refresh($deep = false) if ($deep) { $query = $this->getTable()->createQuery(); foreach (array_keys($this->_references) as $name) { - $query->leftJoin(get_class($this) . '.' . $name); + $query->leftJoin(get_class($this).'.'.$name); } - $query->where(implode(' = ? AND ', (array)$this->getTable()->getIdentifier()) . ' = ?'); + $query->where(implode(' = ? AND ', (array) $this->getTable()->getIdentifier()).' = ?'); $this->clearRelated(); $record = $query->fetchOne($id); } else { @@ -1017,7 +1039,7 @@ public function refresh($deep = false) $this->getTable()->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, $overwrite); - if ($record === false) { + if (false === $record) { throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist.'); } @@ -1032,7 +1054,7 @@ public function refresh($deep = false) /** * refresh - * refresh data of related objects from the database + * refresh data of related objects from the database. * * @param string $name name of a related component. if set, this method only refreshes * the specified related component @@ -1046,7 +1068,7 @@ public function refreshRelated($name = null) $reference = $rel->fetchRelatedFor($this); if ($reference instanceof Doctrine_Collection) { $this->_references[$alias] = $reference; - } else if ($reference instanceof Doctrine_Record) { + } elseif ($reference instanceof Doctrine_Record) { if ($reference->exists()) { $this->_references[$alias] = $reference; } else { @@ -1060,7 +1082,7 @@ public function refreshRelated($name = null) $reference = $rel->fetchRelatedFor($this); if ($reference instanceof Doctrine_Collection) { $this->_references[$name] = $reference; - } else if ($reference instanceof Doctrine_Record) { + } elseif ($reference instanceof Doctrine_Record) { if ($reference->exists()) { $this->_references[$name] = $reference; } else { @@ -1071,10 +1093,9 @@ public function refreshRelated($name = null) } /** - * Clear a related reference or all references + * Clear a related reference or all references. * * @param string $name The relationship reference to clear - * @return void */ public function clearRelated($name = null) { @@ -1091,7 +1112,8 @@ public function clearRelated($name = null) * exist in the database, the related reference will be cleared immediately. * * @param string $name - * @return boolean Whether or not the related relationship exists + * + * @return bool Whether or not the related relationship exists */ public function relatedExists($name) { @@ -1099,14 +1121,11 @@ public function relatedExists($name) return true; } - $reference = $this->$name; + $reference = $this->{$name}; if ($reference instanceof Doctrine_Record) { $exists = $reference->exists(); } elseif ($reference instanceof Doctrine_Collection) { - throw new Doctrine_Record_Exception( - 'You can only call relatedExists() on a relationship that '. - 'returns an instance of Doctrine_Record' - ); + throw new Doctrine_Record_Exception('You can only call relatedExists() on a relationship that returns an instance of Doctrine_Record'); } else { $exists = false; } @@ -1121,7 +1140,7 @@ public function relatedExists($name) /** * returns the table object for this record. * - * @return Doctrine_Table a Doctrine_Table object + * @return Doctrine_Table a Doctrine_Table object */ public function getTable() { @@ -1129,9 +1148,9 @@ public function getTable() } /** - * return all the internal data (columns) + * return all the internal data (columns). * - * @return array an array containing all the properties + * @return array an array containing all the properties */ public function getData() { @@ -1142,14 +1161,12 @@ public function getData() * returns the value of a property (column). If the property is not yet loaded * this method does NOT load it. * - * @param $name name of the property - * @throws Doctrine_Record_Exception if trying to get an unknown property - * @return mixed + * @throws Doctrine_Record_Exception if trying to get an unknown property */ public function rawGet($fieldName) { - if ( ! array_key_exists($fieldName, $this->_data)) { - throw new Doctrine_Record_Exception('Unknown property '. $fieldName); + if (!array_key_exists($fieldName, $this->_data)) { + throw new Doctrine_Record_Exception('Unknown property '.$fieldName); } if ($this->_data[$fieldName] === self::$_null) { return null; @@ -1162,8 +1179,9 @@ public function rawGet($fieldName) * loads all the uninitialized properties from the database. * Used to move a record from PROXY to CLEAN/DIRTY state. * - * @param array $data overwriting data to load in the record. Instance is hydrated from the table if not specified. - * @return boolean + * @param array $data overwriting data to load in the record. Instance is hydrated from the table if not specified. + * + * @return bool */ public function load(array $data = array()) { @@ -1171,7 +1189,7 @@ public function load(array $data = array()) if ($this->exists() && $this->isInProxyState()) { $id = $this->identifier(); - if ( ! is_array($id)) { + if (!is_array($id)) { $id = array($id); } @@ -1184,15 +1202,15 @@ public function load(array $data = array()) if (is_array($data)) { foreach ($data as $field => $value) { - if ($table->hasField($field) && ( ! array_key_exists($field, $this->_data) || $this->_data[$field] === self::$_null)) { - $this->_data[$field] = $value; - } + if ($table->hasField($field) && (!array_key_exists($field, $this->_data) || $this->_data[$field] === self::$_null)) { + $this->_data[$field] = $value; + } } } if ($this->isModified()) { $this->_state = Doctrine_Record::STATE_DIRTY; - } else if (!$this->isInProxyState()) { + } elseif (!$this->isInProxyState()) { $this->_state = Doctrine_Record::STATE_CLEAN; } @@ -1203,21 +1221,22 @@ public function load(array $data = array()) } /** - * indicates whether record has any not loaded fields + * indicates whether record has any not loaded fields. * - * @return boolean + * @return bool */ public function isInProxyState() { $count = 0; foreach ($this->_data as $value) { if ($value !== self::$_null) { - $count++; + ++$count; } } if ($count < $this->_table->getColumnCount()) { return true; } + return false; } @@ -1227,7 +1246,8 @@ public function isInProxyState() * * @param string $fieldName * @param string $accessor - * @return boolean + * + * @return bool */ public function hasAccessor($fieldName, $accessor = null) { @@ -1235,15 +1255,14 @@ public function hasAccessor($fieldName, $accessor = null) if ($accessor) { self::$_customAccessors[$componentName][$fieldName] = $accessor; } else { - return (isset(self::$_customAccessors[$componentName][$fieldName]) && self::$_customAccessors[$componentName][$fieldName]); + return isset(self::$_customAccessors[$componentName][$fieldName]) && self::$_customAccessors[$componentName][$fieldName]; } } /** - * clears the accessor for a field name + * clears the accessor for a field name. * * @param string $fieldName - * @return void */ public function clearAccessor($fieldName) { @@ -1252,37 +1271,41 @@ public function clearAccessor($fieldName) } /** - * gets the custom accessor for a field name + * gets the custom accessor for a field name. * * @param string $fieldName + * * @return string $accessor */ public function getAccessor($fieldName) { if ($this->hasAccessor($fieldName)) { $componentName = $this->_table->getComponentName(); + return self::$_customAccessors[$componentName][$fieldName]; } } /** - * gets all accessors for this component instance + * gets all accessors for this component instance. * * @return array $accessors */ public function getAccessors() { $componentName = $this->_table->getComponentName(); + return isset(self::$_customAccessors[$componentName]) ? self::$_customAccessors[$componentName] : array(); } /** * sets a fieldname to have a custom mutator or check if a field has a custom - * mutator defined (when called without the $mutator parameter) + * mutator defined (when called without the $mutator parameter). * * @param string $fieldName * @param string $mutator - * @return boolean + * + * @return bool */ public function hasMutator($fieldName, $mutator = null) { @@ -1290,29 +1313,28 @@ public function hasMutator($fieldName, $mutator = null) if ($mutator) { self::$_customMutators[$componentName][$fieldName] = $mutator; } else { - return (isset(self::$_customMutators[$componentName][$fieldName]) && self::$_customMutators[$componentName][$fieldName]); + return isset(self::$_customMutators[$componentName][$fieldName]) && self::$_customMutators[$componentName][$fieldName]; } } /** - * gets the custom mutator for a field name + * gets the custom mutator for a field name. * - * @param string $fieldname * @return string */ public function getMutator($fieldName) { if ($this->hasMutator($fieldName)) { $componentName = $this->_table->getComponentName(); + return self::$_customMutators[$componentName][$fieldName]; } } /** - * clears the custom mutator for a field name + * clears the custom mutator for a field name. * * @param string $fieldName - * @return void */ public function clearMutator($fieldName) { @@ -1321,20 +1343,20 @@ public function clearMutator($fieldName) } /** - * gets all custom mutators for this component instance + * gets all custom mutators for this component instance. * * @return array $mutators */ public function getMutators() { $componentName = $this->_table->getComponentName(); + return self::$_customMutators[$componentName]; } /** - * Set a fieldname to have a custom accessor and mutator + * Set a fieldname to have a custom accessor and mutator. * - * @param string $fieldname * @param string $accessor * @param string $mutator */ @@ -1345,12 +1367,12 @@ public function hasAccessorMutator($fieldName, $accessor, $mutator) } /** - * returns a value of a property or a related component + * returns a value of a property or a related component. + * + * @param mixed $fieldName name of the property or related component + * @param bool $load whether or not to invoke the loading procedure * - * @param mixed $fieldName name of the property or related component - * @param boolean $load whether or not to invoke the loading procedure - * @throws Doctrine_Record_Exception if trying to get a value of unknown property / related component - * @return mixed + * @throws Doctrine_Record_Exception if trying to get a value of unknown property / related component */ public function get($fieldName, $load = true) { @@ -1359,13 +1381,15 @@ public function get($fieldName, $load = true) $accessor = $this->hasAccessor($fieldName) ? $this->getAccessor($fieldName) - : 'get' . Doctrine_Inflector::classify($fieldName); + : 'get'.Doctrine_Inflector::classify($fieldName); if ($this->hasAccessor($fieldName) || method_exists($this, $accessor)) { $this->hasAccessor($fieldName, $accessor); - return $this->$accessor($load, $fieldName); + + return $this->{$accessor}($load, $fieldName); } } + return $this->_get($fieldName, $load); } @@ -1393,7 +1417,7 @@ protected function _get($fieldName, $load = true) } try { - if ( ! isset($this->_references[$fieldName])) { + if (!isset($this->_references[$fieldName])) { if ($load) { $rel = $this->_table->getRelation($fieldName); $this->_references[$fieldName] = $rel->fetchRelatedFor($this); @@ -1413,13 +1437,13 @@ protected function _get($fieldName, $load = true) try { $value = $filter->filterGet($this, $fieldName); $success = true; - } catch (Doctrine_Exception $e) {} + } catch (Doctrine_Exception $e) { + } } if ($success) { return $value; - } else { - throw $e; } + throw $e; } } @@ -1427,9 +1451,8 @@ protected function _get($fieldName, $load = true) * sets a value that will be managed as if it were a field by magic accessor and mutators, @see get() and @see set(). * Normally used by Doctrine for the mapping of aggregate values. * - * @param string $name the name of the mapped value - * @param mixed $value mixed value to be mapped - * @return void + * @param string $name the name of the mapped value + * @param mixed $value mixed value to be mapped */ public function mapValue($name, $value = null) { @@ -1437,10 +1460,11 @@ public function mapValue($name, $value = null) } /** - * Tests whether a mapped value exists + * Tests whether a mapped value exists. + * + * @param string $name the name of the property * - * @param string $name the name of the property - * @return boolean + * @return bool */ public function hasMappedValue($name) { @@ -1450,28 +1474,29 @@ public function hasMappedValue($name) /** * alters mapped values, properties and related components. * - * @param mixed $name name of the property or reference - * @param mixed $value value of the property or reference - * @param boolean $load whether or not to refresh / load the uninitialized record data - * - * @throws Doctrine_Record_Exception if trying to set a value for unknown property / related component - * @throws Doctrine_Record_Exception if trying to set a value of wrong type for related component + * @param mixed $value value of the property or reference + * @param bool $load whether or not to refresh / load the uninitialized record data * * @return Doctrine_Record + * + * @throws Doctrine_Record_Exception if trying to set a value for unknown property / related component + * @throws Doctrine_Record_Exception if trying to set a value of wrong type for related component */ public function set($fieldName, $value, $load = true) { if ($this->_table->getAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE) || $this->hasMutator($fieldName)) { $componentName = $this->_table->getComponentName(); $mutator = $this->hasMutator($fieldName) - ? $this->getMutator($fieldName): - 'set' . Doctrine_Inflector::classify($fieldName); + ? $this->getMutator($fieldName) : + 'set'.Doctrine_Inflector::classify($fieldName); if ($this->hasMutator($fieldName) || method_exists($this, $mutator)) { $this->hasMutator($fieldName, $mutator); - return $this->$mutator($value, $load, $fieldName); + + return $this->{$mutator}($value, $load, $fieldName); } } + return $this->_set($fieldName, $value, $load); } @@ -1479,12 +1504,12 @@ protected function _set($fieldName, $value, $load = true) { if (array_key_exists($fieldName, $this->_values)) { $this->_values[$fieldName] = $value; - } else if (array_key_exists($fieldName, $this->_data)) { + } elseif (array_key_exists($fieldName, $this->_data)) { $type = $this->_table->getTypeOf($fieldName); if ($value instanceof Doctrine_Record) { $id = $value->getIncremented(); - if ($id !== null && $type !== 'object') { + if (null !== $id && 'object' !== $type) { $value = $id; } } @@ -1496,7 +1521,7 @@ protected function _set($fieldName, $value, $load = true) } if ($this->_isValueModified($type, $old, $value)) { - if ($value === null) { + if (null === $value) { $value = $this->_table->getDefaultValueOf($fieldName); } $this->_data[$fieldName] = $value; @@ -1522,13 +1547,13 @@ protected function _set($fieldName, $value, $load = true) try { $value = $filter->filterSet($this, $fieldName, $value); $success = true; - } catch (Doctrine_Exception $e) {} + } catch (Doctrine_Exception $e) { + } } if ($success) { return $value; - } else { - throw $e; } + throw $e; } } @@ -1537,7 +1562,7 @@ protected function _set($fieldName, $value, $load = true) /** * Check if a value has changed according to Doctrine - * Doctrine is loose with type checking in the same ways PHP is for consistancy of behavior + * Doctrine is loose with type checking in the same ways PHP is for consistancy of behavior. * * This function basically says if what is being set is of Doctrine type boolean and something * like current_value == 1 && new_value = true would not be considered modified @@ -1545,10 +1570,11 @@ protected function _set($fieldName, $value, $load = true) * Simply doing $old !== $new will return false for boolean columns would mark the field as modified * and change it in the database when it is not necessary * - * @param string $type Doctrine type of the column - * @param string $old Old value - * @param string $new New value - * @return boolean $modified Whether or not Doctrine considers the value modified + * @param string $type Doctrine type of the column + * @param string $old Old value + * @param string $new New value + * + * @return bool $modified Whether or not Doctrine considers the value modified */ protected function _isValueModified($type, $old, $new) { @@ -1556,23 +1582,26 @@ protected function _isValueModified($type, $old, $new) return true; } - if ($type == 'boolean' && (is_bool($old) || is_numeric($old)) && (is_bool($new) || is_numeric($new)) && $old == $new) { + if ('boolean' == $type && (is_bool($old) || is_numeric($old)) && (is_bool($new) || is_numeric($new)) && $old == $new) { return false; - } else if (in_array($type, array('decimal', 'float', 'double')) && is_numeric($old) && is_numeric($new)) { + } + if (in_array($type, array('decimal', 'float', 'double')) && is_numeric($old) && is_numeric($new)) { return $old * 100 != $new * 100; - } else if (in_array($type, array('integer', 'int')) && is_numeric($old) && is_numeric($new)) { + } + if (in_array($type, array('integer', 'int')) && is_numeric($old) && is_numeric($new)) { return $old != $new; - } else if ($type == 'timestamp' || $type == 'date') { + } + if ('timestamp' == $type || 'date' == $type) { $oldStrToTime = @strtotime((string) $old); $newStrToTime = @strtotime((string) $new); if ($oldStrToTime && $newStrToTime) { return $oldStrToTime !== $newStrToTime; - } else { - return $old !== $new; } - } else { + return $old !== $new; } + + return $old !== $new; } /** @@ -1581,23 +1610,24 @@ protected function _isValueModified($type, $old, $new) * This method inserts a related component instance in this record * relations, populating the foreign keys accordingly. * - * @param string $name related component alias in the relation - * @param Doctrine_Record|Doctrine_Collection $value object to be linked as a related component + * @param string $name related component alias in the relation + * @param Doctrine_Record|Doctrine_Collection $value object to be linked as a related component + * * @todo Refactor. What about composite keys? */ public function coreSetRelated($name, $value) { $rel = $this->_table->getRelation($name); - if ($value === null) { + if (null === $value) { $value = self::$_null; } // one-to-many or one-to-one relation if ($rel instanceof Doctrine_Relation_ForeignKey || $rel instanceof Doctrine_Relation_LocalKey) { - if ( ! $rel->isOneToOne()) { + if (!$rel->isOneToOne()) { // one-to-many relation found - if ( ! ($value instanceof Doctrine_Collection)) { + if (!($value instanceof Doctrine_Collection)) { throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references."); } @@ -1615,12 +1645,12 @@ public function coreSetRelated($name, $value) } // one-to-one relation found - if ( ! ($value instanceof Doctrine_Record) && ! ($value instanceof Doctrine_Null)) { + if (!($value instanceof Doctrine_Record) && !($value instanceof Doctrine_Null)) { throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Record or Doctrine_Null when setting one-to-one references."); } if ($rel instanceof Doctrine_Relation_LocalKey) { - if ($value !== self::$_null && ! empty($foreignFieldName) && $foreignFieldName != $value->getTable()->getIdentifier()) { + if ($value !== self::$_null && !empty($foreignFieldName) && $foreignFieldName != $value->getTable()->getIdentifier()) { $this->set($localFieldName, $value->rawGet($foreignFieldName), false); } else { // FIX: Ticket #1280 fits in this situation @@ -1631,9 +1661,9 @@ public function coreSetRelated($name, $value) $value->set($foreignFieldName, $this, false); } } - } else if ($rel instanceof Doctrine_Relation_Association) { + } elseif ($rel instanceof Doctrine_Relation_Association) { // join table relation found - if ( ! ($value instanceof Doctrine_Collection)) { + if (!($value instanceof Doctrine_Collection)) { throw new Doctrine_Record_Exception("Couldn't call Doctrine_Core::set(), second argument should be an instance of Doctrine_Collection when setting many-to-many references."); } } @@ -1642,10 +1672,11 @@ public function coreSetRelated($name, $value) } /** - * test whether a field (column, mapped value, related component, accessor) is accessible by @see get() + * test whether a field (column, mapped value, related component, accessor) is accessible by @see get(). * * @param string $fieldName - * @return boolean + * + * @return bool */ public function contains($fieldName) { @@ -1660,36 +1691,36 @@ public function contains($fieldName) if (isset($this->_values[$fieldName])) { return true; } - if (isset($this->_references[$fieldName]) && - $this->_references[$fieldName] !== self::$_null) { - + if (isset($this->_references[$fieldName]) + && $this->_references[$fieldName] !== self::$_null) { return true; } + return false; } /** * deletes a column or a related component. + * * @param string $name - * @return void */ public function __unset($name) { if (array_key_exists($name, $this->_data)) { $this->_data[$name] = array(); - } else if (isset($this->_references[$name])) { + } elseif (isset($this->_references[$name])) { if ($this->_references[$name] instanceof Doctrine_Record) { - $this->_pendingDeletes[] = $this->$name; + $this->_pendingDeletes[] = $this->{$name}; $this->_references[$name] = self::$_null; } elseif ($this->_references[$name] instanceof Doctrine_Collection) { - $this->_pendingDeletes[] = $this->$name; + $this->_pendingDeletes[] = $this->{$name}; $this->_references[$name]->setData(array()); } } } /** - * returns Doctrine_Record instances which need to be deleted on save + * returns Doctrine_Record instances which need to be deleted on save. * * @return array */ @@ -1699,7 +1730,7 @@ public function getPendingDeletes() } /** - * returns Doctrine_Record instances which need to be unlinked (deleting the relation) on save + * returns Doctrine_Record instances which need to be unlinked (deleting the relation) on save. * * @return array $pendingUnlinks */ @@ -1709,9 +1740,7 @@ public function getPendingUnlinks() } /** - * resets pending record unlinks - * - * @return void + * resets pending record unlinks. */ public function resetPendingUnlinks() { @@ -1721,17 +1750,17 @@ public function resetPendingUnlinks() /** * applies the changes made to this object into database * this method is smart enough to know if any changes are made - * and whether to use INSERT or UPDATE statement + * and whether to use INSERT or UPDATE statement. * * this method also saves the related components * - * @param Doctrine_Connection $conn optional connection parameter - * @throws Exception if record is not valid and validation is active - * @return void + * @param Doctrine_Connection $conn optional connection parameter + * + * @throws Exception if record is not valid and validation is active */ public function save(Doctrine_Connection $conn = null) { - if ($conn === null) { + if (null === $conn) { $conn = $this->_table->getConnection(); } $conn->unitOfWork->saveGraph($this); @@ -1743,12 +1772,15 @@ public function save(Doctrine_Connection $conn = null) * throw an exception when validation fails but returns TRUE on * success or FALSE on failure. * - * @param Doctrine_Connection $conn optional connection parameter - * @return TRUE if the record was saved sucessfully without errors, FALSE otherwise. + * @param Doctrine_Connection $conn optional connection parameter + * + * @return true if the record was saved sucessfully without errors, FALSE otherwise */ - public function trySave(Doctrine_Connection $conn = null) { + public function trySave(Doctrine_Connection $conn = null) + { try { $this->save($conn); + return true; } catch (Doctrine_Validator_Exception $ignored) { return false; @@ -1766,32 +1798,36 @@ public function trySave(Doctrine_Connection $conn = null) { * query isemulated through this method for other DBMS using standard types * of queries inside a transaction to assure the atomicity of the operation. * - * @param Doctrine_Connection $conn optional connection parameter - * @throws Doctrine_Connection_Exception if some of the key values was null - * @throws Doctrine_Connection_Exception if there were no key fields - * @throws Doctrine_Connection_Exception if something fails at database level - * @return integer number of rows affected + * @param Doctrine_Connection $conn optional connection parameter + * + * @return int number of rows affected + * + * @throws Doctrine_Connection_Exception if some of the key values was null + * @throws Doctrine_Connection_Exception if there were no key fields + * @throws Doctrine_Connection_Exception if something fails at database level */ public function replace(Doctrine_Connection $conn = null) { - if ($conn === null) { + if (null === $conn) { $conn = $this->_table->getConnection(); } + return $conn->unitOfWork->saveGraph($this, true); } /** * retrieves an array of modified fields and associated new values. * - * @param boolean $old pick the old values (instead of the new ones) - * @param boolean $last pick only lastModified values (@see getLastModified()) + * @param bool $old pick the old values (instead of the new ones) + * @param bool $last pick only lastModified values (@see getLastModified()) + * * @return array $a */ public function getModified($old = false, $last = false) { $a = array(); - $modified = $last ? $this->_lastModified:$this->_modified; + $modified = $last ? $this->_lastModified : $this->_modified; foreach ($modified as $fieldName) { if ($old) { $a[$fieldName] = isset($this->_oldValues[$fieldName]) @@ -1801,13 +1837,15 @@ public function getModified($old = false, $last = false) $a[$fieldName] = $this->_data[$fieldName]; } } + return $a; } /** * returns an array of the modified fields from the last transaction. * - * @param boolean $old pick the old values (instead of the new ones) + * @param bool $old pick the old values (instead of the new ones) + * * @return array */ public function getLastModified($old = false) @@ -1822,8 +1860,8 @@ public function getLastModified($old = false) * adds column aggregation inheritance and converts Records into primary * key values. * - * @param array $array * @return array + * * @todo What about a little bit more expressive name? getPreparedData? */ public function getPrepared(array $array = array()) @@ -1848,32 +1886,32 @@ public function getPrepared(array $array = array()) $a[$field] = serialize($this->_data[$field]); break; case 'gzip': - $a[$field] = gzcompress($this->_data[$field],5); + $a[$field] = gzcompress($this->_data[$field], 5); break; case 'boolean': $a[$field] = $this->getTable()->getConnection()->convertBooleans($this->_data[$field]); - break; + break; case 'set': if (is_array($this->_data[$field])) { $a[$field] = implode(',', $this->_data[$field]); } else { $a[$field] = $this->_data[$field]; } - break; + break; default: if ($this->_data[$field] instanceof Doctrine_Record) { $a[$field] = $this->_data[$field]->getIncremented(); - if ($a[$field] !== null) { + if (null !== $a[$field]) { $this->_data[$field] = $a[$field]; } } else { $a[$field] = $this->_data[$field]; } - /** TODO: - if ($this->_data[$v] === null) { - throw new Doctrine_Record_Exception('Unexpected null value.'); - } - */ + /* TODO: + * if ($this->_data[$v] === null) { + * throw new Doctrine_Record_Exception('Unexpected null value.'); + * } + */ } } @@ -1881,20 +1919,20 @@ public function getPrepared(array $array = array()) } /** - * implements Countable interface + * implements Countable interface. * - * @return integer the number of columns in this record + * @return int the number of columns in this record */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_data); } /** - * alias for @see count() + * alias for @see count(). * - * @return integer the number of columns in this record + * @return int the number of columns in this record */ public function columnCount() { @@ -1902,16 +1940,18 @@ public function columnCount() } /** - * returns the record representation as an array + * returns the record representation as an array. + * + * @see http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models + * + * @param bool $deep whether to include relations + * @param bool $prefixKey not used * - * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models - * @param boolean $deep whether to include relations - * @param boolean $prefixKey not used * @return array */ public function toArray($deep = true, $prefixKey = false) { - if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) { + if (self::STATE_LOCKED == $this->_state || self::STATE_TLOCKED == $this->_state) { return false; } @@ -1934,14 +1974,14 @@ public function toArray($deep = true, $prefixKey = false) } } - if ($this->_table->getIdentifierType() == Doctrine_Core::IDENTIFIER_AUTOINC) { - $i = $this->_table->getIdentifier(); - $a[$i] = $this->getIncremented(); + if (Doctrine_Core::IDENTIFIER_AUTOINC == $this->_table->getIdentifierType()) { + $i = $this->_table->getIdentifier(); + $a[$i] = $this->getIncremented(); } if ($deep) { foreach ($this->_references as $key => $relation) { - if ( ! $relation instanceof Doctrine_Null) { + if (!$relation instanceof Doctrine_Null) { $a[$key] = $relation->toArray($deep, $prefixKey); } } @@ -1960,19 +2000,18 @@ public function toArray($deep = true, $prefixKey = false) /** * merges this record with an array of values - * or with another existing instance of this object + * or with another existing instance of this object. * * @see fromArray() - * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models - * @param string $array array of data to merge, see link for documentation - * @param bool $deep whether or not to merge relations - * @return void + * @see http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models + * + * @param bool $deep whether or not to merge relations */ public function merge($data, $deep = true) { if ($data instanceof $this) { $array = $data->toArray($deep); - } else if (is_array($data)) { + } elseif (is_array($data)) { $array = $data; } @@ -1980,46 +2019,47 @@ public function merge($data, $deep = true) } /** - * imports data from a php array + * imports data from a php array. * - * @link http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models - * @param string $array array of data, see link for documentation - * @param bool $deep whether or not to act on relations - * @return void + * @see http://www.doctrine-project.org/documentation/manual/1_1/en/working-with-models + * + * @param string $array array of data, see link for documentation + * @param bool $deep whether or not to act on relations */ public function fromArray(array $array, $deep = true) { $refresh = false; foreach ($array as $key => $value) { - if ($key == '_identifier') { + if ('_identifier' == $key) { $refresh = true; $this->assignIdentifier($value); continue; } if ($deep && $this->getTable()->hasRelation($key)) { - if ( ! $this->$key) { + if (!$this->{$key}) { $this->refreshRelated($key); } if (is_array($value)) { - if (isset($value[0]) && ! is_array($value[0])) { + if (isset($value[0]) && !is_array($value[0])) { $this->unlink($key, array(), false); $this->link($key, $value, false); } else { - $this->$key->fromArray($value, $deep); + $this->{$key}->fromArray($value, $deep); } } - } else if ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { + } elseif ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { $this->set($key, $value); } else { - $method = 'set' . Doctrine_Inflector::classify($key); + $method = 'set'.Doctrine_Inflector::classify($key); try { if (is_callable(array($this, $method))) { - $this->$method($value); + $this->{$method}($value); } - } catch (Doctrine_Record_Exception $e) {} + } catch (Doctrine_Record_Exception $e) { + } } } @@ -2031,7 +2071,7 @@ public function fromArray(array $array, $deep = true) } /** - * synchronizes a Doctrine_Record instance and its relations with data from an array + * synchronizes a Doctrine_Record instance and its relations with data from an array. * * it expects an array representation of a Doctrine_Record similar to the return * value of the toArray() method. If the array contains relations it will create @@ -2040,43 +2080,43 @@ public function fromArray(array $array, $deep = true) * does not touch what it is not in $array) * * @param array $array representation of a Doctrine_Record - * @param bool $deep whether or not to act on relations + * @param bool $deep whether or not to act on relations */ public function synchronizeWithArray(array $array, $deep = true) { $refresh = false; foreach ($array as $key => $value) { - if ($key == '_identifier') { + if ('_identifier' == $key) { $refresh = true; $this->assignIdentifier($value); continue; } if ($deep && $this->getTable()->hasRelation($key)) { - if ( ! $this->$key) { + if (!$this->{$key}) { $this->refreshRelated($key); } if (is_array($value)) { - if (isset($value[0]) && ! is_array($value[0])) { + if (isset($value[0]) && !is_array($value[0])) { $this->unlink($key, array(), false); $this->link($key, $value, false); } else { - $this->$key->synchronizeWithArray($value); - $this->$key = $this->$key; + $this->{$key}->synchronizeWithArray($value); + $this->{$key} = $this->{$key}; } } - } else if ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { + } elseif ($this->getTable()->hasField($key) || array_key_exists($key, $this->_values)) { $this->set($key, $value); } } // Eliminate relationships missing in the $array foreach ($this->_references as $name => $relation) { - $rel = $this->getTable()->getRelation($name); + $rel = $this->getTable()->getRelation($name); - if ( ! $rel->isRefClass() && ! isset($array[$name]) && ( ! $rel->isOneToOne() || ! isset($array[$rel->getLocalFieldName()]))) { - unset($this->$name); + if (!$rel->isRefClass() && !isset($array[$name]) && (!$rel->isOneToOne() || !isset($array[$rel->getLocalFieldName()]))) { + unset($this->{$name}); } } @@ -2086,62 +2126,63 @@ public function synchronizeWithArray(array $array, $deep = true) } /** - * exports instance to a chosen format + * exports instance to a chosen format. + * + * @param string $type format type: array, xml, yml, json + * @param string $deep whether or not to export all relationships * - * @param string $type format type: array, xml, yml, json - * @param string $deep whether or not to export all relationships - * @return string representation as $type format. Array is $type is array + * @return string representation as $type format. Array is $type is array */ public function exportTo($type, $deep = true) { - if ($type == 'array') { + if ('array' == $type) { return $this->toArray($deep); - } else { - return Doctrine_Parser::dump($this->toArray($deep, true), $type); } + + return Doctrine_Parser::dump($this->toArray($deep, true), $type); } /** - * imports data from a chosen format in the current instance + * imports data from a chosen format in the current instance. * - * @param string $type Format type: xml, yml, json - * @param string $data Data to be parsed and imported - * @return void + * @param string $type Format type: xml, yml, json + * @param string $data Data to be parsed and imported */ public function importFrom($type, $data, $deep = true) { - if ($type == 'array') { + if ('array' == $type) { return $this->fromArray($data, $deep); - } else { - return $this->fromArray(Doctrine_Parser::load($data, $type), $deep); } + + return $this->fromArray(Doctrine_Parser::load($data, $type), $deep); } /** - * returns true if this record is saved in the database, otherwise false (it is transient) + * returns true if this record is saved in the database, otherwise false (it is transient). * - * @return boolean + * @return bool */ public function exists() { - return ($this->_state !== Doctrine_Record::STATE_TCLEAN && - $this->_state !== Doctrine_Record::STATE_TDIRTY && - $this->_state !== Doctrine_Record::STATE_TLOCKED && - $this->_state !== null); + return Doctrine_Record::STATE_TCLEAN !== $this->_state + && Doctrine_Record::STATE_TDIRTY !== $this->_state + && Doctrine_Record::STATE_TLOCKED !== $this->_state + && null !== $this->_state; } /** - * returns true if this record was modified, otherwise false + * returns true if this record was modified, otherwise false. + * + * @param bool $deep whether to process also the relations for changes * - * @param boolean $deep whether to process also the relations for changes - * @return boolean + * @return bool */ public function isModified($deep = false) { - $modified = ($this->_state === Doctrine_Record::STATE_DIRTY || - $this->_state === Doctrine_Record::STATE_TDIRTY); - if ( ! $modified && $deep) { - if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) { + $modified = (Doctrine_Record::STATE_DIRTY === $this->_state + || Doctrine_Record::STATE_TDIRTY === $this->_state); + if (!$modified && $deep) { + if (self::STATE_LOCKED == $this->_state || self::STATE_TLOCKED == $this->_state) { return false; } @@ -2153,7 +2194,7 @@ public function isModified($deep = false) if ($modified = $reference->isModified($deep)) { break; } - } else if ($reference instanceof Doctrine_Collection) { + } elseif ($reference instanceof Doctrine_Collection) { foreach ($reference as $record) { if ($modified = $record->isModified($deep)) { break 2; @@ -2163,27 +2204,32 @@ public function isModified($deep = false) } $this->_state = $stateBeforeLock; } + return $modified; } /** - * checks existence of properties and related components - * @param mixed $fieldName name of the property or reference - * @return boolean + * checks existence of properties and related components. + * + * @param mixed $fieldName name of the property or reference + * + * @return bool */ public function hasRelation($fieldName) { if (isset($this->_data[$fieldName]) || isset($this->_id[$fieldName])) { return true; } + return $this->_table->hasRelation($fieldName); } /** - * implements IteratorAggregate interface - * @return Doctrine_Record_Iterator iterator through data + * implements IteratorAggregate interface. + * + * @return Doctrine_Record_Iterator iterator through data */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new Doctrine_Record_Iterator($this); @@ -2191,31 +2237,33 @@ public function getIterator() /** * deletes this data access object and all the related composites - * this operation is isolated by a transaction + * this operation is isolated by a transaction. * * this event can be listened by the onPreDelete and onDelete listeners * - * @return boolean true if successful + * @return bool true if successful */ public function delete(Doctrine_Connection $conn = null) { - if ($conn == null) { + if (null == $conn) { $conn = $this->_table->getConnection(); } + return $conn->unitOfWork->delete($this); } /** * generates a copy of this object. Returns an instance of the same class of $this. * - * @param boolean $deep whether to duplicates the objects targeted by the relations + * @param bool $deep whether to duplicates the objects targeted by the relations + * * @return Doctrine_Record */ public function copy($deep = false) { $data = $this->_data; $idtype = $this->_table->getIdentifierType(); - if ($idtype === Doctrine_Core::IDENTIFIER_AUTOINC || $idtype === Doctrine_Core::IDENTIFIER_SEQUENCE) { + if (Doctrine_Core::IDENTIFIER_AUTOINC === $idtype || Doctrine_Core::IDENTIFIER_SEQUENCE === $idtype) { $id = $this->_table->getIdentifier(); unset($data[$id]); @@ -2225,7 +2273,7 @@ public function copy($deep = false) $modified = array(); foreach ($data as $key => $val) { - if ( ! ($val instanceof Doctrine_Null)) { + if (!($val instanceof Doctrine_Null)) { $ret->_modified[] = $key; } } @@ -2236,7 +2284,7 @@ public function copy($deep = false) foreach ($value as $valueKey => $record) { $ret->{$key}[$valueKey] = $record->copy($deep); } - } else if ($value instanceof Doctrine_Record) { + } elseif ($value instanceof Doctrine_Record) { $ret->set($key, $value->copy($deep)); } } @@ -2246,21 +2294,20 @@ public function copy($deep = false) } /** - * assigns an identifier to the instance, for database storage + * assigns an identifier to the instance, for database storage. * - * @param mixed $id a key value or an array of keys - * @return void + * @param mixed $id a key value or an array of keys */ public function assignIdentifier($id = false) { - if ($id === false) { - $this->_id = array(); - $this->_data = $this->cleanData($this->_data); - $this->_state = Doctrine_Record::STATE_TCLEAN; + if (false === $id) { + $this->_id = array(); + $this->_data = $this->cleanData($this->_data); + $this->_state = Doctrine_Record::STATE_TCLEAN; $this->_resetModified(); - } elseif ($id === true) { + } elseif (true === $id) { $this->prepareIdentifiers(true); - $this->_state = Doctrine_Record::STATE_CLEAN; + $this->_state = Doctrine_Record::STATE_CLEAN; $this->_resetModified(); } else { if (is_array($id)) { @@ -2279,7 +2326,7 @@ public function assignIdentifier($id = false) } /** - * returns the primary keys of this object + * returns the primary keys of this object. * * @return array */ @@ -2289,15 +2336,16 @@ public function identifier() } /** - * returns the value of autoincremented primary key of this object (if any) + * returns the value of autoincremented primary key of this object (if any). + * + * @return int * - * @return integer * @todo Better name? */ final public function getIncremented() { $id = current($this->_id); - if ($id === false) { + if (false === $id) { return null; } @@ -2308,7 +2356,7 @@ final public function getIncremented() * getLast * this method is used internally by Doctrine_Query * it is needed to provide compatibility between - * records and collections + * records and collections. * * @return Doctrine_Record */ @@ -2318,9 +2366,11 @@ public function getLast() } /** - * tests whether a relation is set - * @param string $name relation alias - * @return boolean + * tests whether a relation is set. + * + * @param string $name relation alias + * + * @return bool */ public function hasReference($name) { @@ -2328,9 +2378,10 @@ public function hasReference($name) } /** - * gets a related component + * gets a related component. * * @param string $name + * * @return Doctrine_Record|Doctrine_Collection */ public function reference($name) @@ -2341,22 +2392,24 @@ public function reference($name) } /** - * gets a related component and fails if it does not exist + * gets a related component and fails if it does not exist. * * @param string $name - * @throws Doctrine_Record_Exception if trying to get an unknown related component + * + * @throws Doctrine_Record_Exception if trying to get an unknown related component */ public function obtainReference($name) { if (isset($this->_references[$name])) { return $this->_references[$name]; } - throw new Doctrine_Record_Exception("Unknown reference $name"); + throw new Doctrine_Record_Exception("Unknown reference {$name}"); } /** - * get all related components - * @return array various Doctrine_Collection or Doctrine_Record instances + * get all related components. + * + * @return array various Doctrine_Collection or Doctrine_Record instances */ public function getReferences() { @@ -2364,10 +2417,9 @@ public function getReferences() } /** - * set a related component + * set a related component. * * @param string $alias - * @param Doctrine_Access $coll */ final public function setRelated($alias, Doctrine_Access $coll) { @@ -2376,11 +2428,11 @@ final public function setRelated($alias, Doctrine_Access $coll) /** * loadReference - * loads a related component + * loads a related component. + * + * @param string $name alias of the relation * - * @throws Doctrine_Table_Exception if trying to load an unknown related component - * @param string $name alias of the relation - * @return void + * @throws Doctrine_Table_Exception if trying to load an unknown related component */ public function loadReference($name) { @@ -2389,11 +2441,12 @@ public function loadReference($name) } /** - * call + * call. * - * @param string|array $callback valid callback - * @param string $column column name + * @param string|array $callback valid callback + * @param string $column column name * @param mixed arg1 ... argN optional callback arguments + * * @return Doctrine_Record provides a fluent interface */ public function call($callback, $column) @@ -2409,25 +2462,26 @@ public function call($callback, $column) $this->_data[$fieldName] = $newvalue; } + return $this; } /** - * getter for node associated with this record + * getter for node associated with this record. * - * @return Doctrine_Node false if component is not a Tree + * @return Doctrine_Node false if component is not a Tree */ public function getNode() { - if ( ! $this->_table->isTree()) { + if (!$this->_table->isTree()) { return false; } - if ( ! isset($this->_node)) { + if (!isset($this->_node)) { $this->_node = Doctrine_Node::factory($this, - $this->getTable()->getOption('treeImpl'), - $this->getTable()->getOption('treeOptions') - ); + $this->getTable()->getOption('treeImpl'), + $this->getTable()->getOption('treeOptions') + ); } return $this->_node; @@ -2441,19 +2495,20 @@ public function unshiftFilter(Doctrine_Record_Filter $filter) /** * unlink * removes links from this record to given records - * if no ids are given, it removes all links + * if no ids are given, it removes all links. * - * @param string $alias related component alias - * @param array $ids the identifiers of the related records - * @param boolean $now whether or not to execute now or set as pending unlinks - * @return Doctrine_Record this object (fluent interface) + * @param string $alias related component alias + * @param array $ids the identifiers of the related records + * @param bool $now whether or not to execute now or set as pending unlinks + * + * @return Doctrine_Record this object (fluent interface) */ public function unlink($alias, $ids = array(), $now = false) { $ids = (array) $ids; // fix for #1622 - if ( ! isset($this->_references[$alias]) && $this->hasRelation($alias)) { + if (!isset($this->_references[$alias]) && $this->hasRelation($alias)) { $this->loadReference($alias); } @@ -2474,24 +2529,27 @@ public function unlink($alias, $ids = array(), $now = false) } } - if ( ! $this->exists() || $now === false) { - if ( ! $ids) { + if (!$this->exists() || false === $now) { + if (!$ids) { $ids = $allIds; } foreach ($ids as $id) { $this->_pendingUnlinks[$alias][$id] = true; } + return $this; - } else { - return $this->unlinkInDb($alias, $ids); } + + return $this->unlinkInDb($alias, $ids); } /** - * unlink now the related components, querying the db - * @param string $alias related component alias - * @param array $ids the identifiers of the related records - * @return Doctrine_Record this object (fluent interface) + * unlink now the related components, querying the db. + * + * @param string $alias related component alias + * @param array $ids the identifiers of the related records + * + * @return Doctrine_Record this object (fluent interface) */ public function unlinkInDb($alias, $ids = array()) { @@ -2501,18 +2559,20 @@ public function unlinkInDb($alias, $ids = array()) $q = $rel->getAssociationTable() ->createQuery() ->delete() - ->where($rel->getLocal() . ' = ?', array_values($this->identifier())); + ->where($rel->getLocal().' = ?', array_values($this->identifier())) + ; if (count($ids) > 0) { $q->whereIn($rel->getForeign(), $ids); } $q->execute(); - } else if ($rel instanceof Doctrine_Relation_ForeignKey) { + } elseif ($rel instanceof Doctrine_Relation_ForeignKey) { $q = $rel->getTable()->createQuery() ->update() ->set($rel->getForeign(), '?', array(null)) - ->addWhere($rel->getForeign() . ' = ?', array_values($this->identifier())); + ->addWhere($rel->getForeign().' = ?', array_values($this->identifier())) + ; if (count($ids) > 0) { $q->whereIn($rel->getTable()->getIdentifier(), $ids); @@ -2520,33 +2580,36 @@ public function unlinkInDb($alias, $ids = array()) $q->execute(); } + return $this; } /** - * creates links from this record to given records + * creates links from this record to given records. + * + * @param string $alias related component alias + * @param array $ids the identifiers of the related records + * @param bool $now wether or not to execute now or set pending * - * @param string $alias related component alias - * @param array $ids the identifiers of the related records - * @param boolean $now wether or not to execute now or set pending - * @return Doctrine_Record this object (fluent interface) + * @return Doctrine_Record this object (fluent interface) */ public function link($alias, $ids, $now = false) { $ids = (array) $ids; - if ( ! count($ids)) { + if (!count($ids)) { return $this; } - if ( ! $this->exists() || $now === false) { + if (!$this->exists() || false === $now) { $relTable = $this->getTable()->getRelation($alias)->getTable(); $records = $relTable->createQuery() ->whereIn($relTable->getIdentifier(), $ids) - ->execute(); + ->execute() + ; foreach ($records as $record) { - if ($this->$alias instanceof Doctrine_Record) { + if ($this->{$alias} instanceof Doctrine_Record) { $this->set($alias, $record); } else { if ($c = $this->get($alias)) { @@ -2564,17 +2627,18 @@ public function link($alias, $ids, $now = false) } return $this; - } else { - return $this->linkInDb($alias, $ids); } + + return $this->linkInDb($alias, $ids); } /** - * creates links from this record to given records now, querying the db + * creates links from this record to given records now, querying the db. + * + * @param string $alias related component alias + * @param array $ids the identifiers of the related records * - * @param string $alias related component alias - * @param array $ids the identifiers of the related records - * @return Doctrine_Record this object (fluent interface) + * @return Doctrine_Record this object (fluent interface) */ public function linkInDb($alias, $ids) { @@ -2586,43 +2650,45 @@ public function linkInDb($alias, $ids) if ($rel instanceof Doctrine_Relation_Association) { $modelClassName = $rel->getAssociationTable()->getComponentName(); $localFieldName = $rel->getLocalFieldName(); - $localFieldDef = $rel->getAssociationTable()->getColumnDefinition($localFieldName); + $localFieldDef = $rel->getAssociationTable()->getColumnDefinition($localFieldName); - if ($localFieldDef['type'] == 'integer') { - $identifier = (integer) $identifier; + if ('integer' == $localFieldDef['type']) { + $identifier = (int) $identifier; } $foreignFieldName = $rel->getForeignFieldName(); - $foreignFieldDef = $rel->getAssociationTable()->getColumnDefinition($foreignFieldName); + $foreignFieldDef = $rel->getAssociationTable()->getColumnDefinition($foreignFieldName); - if ($foreignFieldDef['type'] == 'integer') { + if ('integer' == $foreignFieldDef['type']) { foreach ($ids as $i => $id) { - $ids[$i] = (integer) $id; + $ids[$i] = (int) $id; } } foreach ($ids as $id) { - $record = new $modelClassName; + $record = new $modelClassName(); $record[$localFieldName] = $identifier; $record[$foreignFieldName] = $id; $record->save(); } - } else if ($rel instanceof Doctrine_Relation_ForeignKey) { + } elseif ($rel instanceof Doctrine_Relation_ForeignKey) { $q = $rel->getTable() ->createQuery() ->update() - ->set($rel->getForeign(), '?', array_values($this->identifier())); + ->set($rel->getForeign(), '?', array_values($this->identifier())) + ; if (count($ids) > 0) { $q->whereIn($rel->getTable()->getIdentifier(), $ids); } $q->execute(); - } else if ($rel instanceof Doctrine_Relation_LocalKey) { + } elseif ($rel instanceof Doctrine_Relation_LocalKey) { $q = $this->getTable() ->createQuery() ->update() - ->set($rel->getLocalFieldName(), '?', $ids); + ->set($rel->getLocalFieldName(), '?', $ids) + ; if (count($ids) > 0) { $q->whereIn($rel->getTable()->getIdentifier(), array_values($this->identifier())); @@ -2638,19 +2704,17 @@ public function linkInDb($alias, $ids) * Reset the modified array and store the old array in lastModified so it * can be accessed by users after saving a record, since the modified array * is reset after the object is saved. - * - * @return void */ protected function _resetModified() { - if ( ! empty($this->_modified)) { + if (!empty($this->_modified)) { $this->_lastModified = $this->_modified; $this->_modified = array(); } } /** - * magic method used for method overloading + * magic method used for method overloading. * * the function of this method is to try to find a given method from the templates (behaviors) * the record is using, and if found, execute it. Note that already existing methods would not be @@ -2658,14 +2722,16 @@ protected function _resetModified() * * So, in sense, this method replicates the usage of mixins (as seen in some programming languages) * - * @param string $method name of the method - * @param array $args method arguments - * @return mixed the return value of the given method + * @param string $method name of the method + * @param array $args method arguments + * + * @return mixed the return value of the given method */ public function __call($method, $args) { if (($template = $this->_table->getMethodOwner($method)) !== false) { $template->setInvoker($this); + return call_user_func_array(array($template, $method), $args); } @@ -2682,8 +2748,7 @@ public function __call($method, $args) } /** - * used to delete node from tree - MUST BE USE TO DELETE RECORD IF TABLE ACTS AS TREE - * + * used to delete node from tree - MUST BE USE TO DELETE RECORD IF TABLE ACTS AS TREE. */ public function deleteNode() { @@ -2696,11 +2761,12 @@ public function deleteNode() * from the instance pool. * Note: The entity is no longer useable after free() has been called. Any operations * done with the entity afterwards can lead to unpredictable results. - * @param boolean $deep whether to free also the related components + * + * @param bool $deep whether to free also the related components */ public function free($deep = false) { - if ($this->_state != self::STATE_LOCKED && $this->_state != self::STATE_TLOCKED) { + if (self::STATE_LOCKED != $this->_state && self::STATE_TLOCKED != $this->_state) { $this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED; $this->_table->getRepository()->evict($this->_oid); @@ -2710,7 +2776,7 @@ public function free($deep = false) if ($deep) { foreach ($this->_references as $name => $reference) { - if ( ! ($reference instanceof Doctrine_Null)) { + if (!($reference instanceof Doctrine_Null)) { $reference->free($deep); } } @@ -2721,7 +2787,7 @@ public function free($deep = false) } /** - * __toString alias + * __toString alias. * * @return string */ @@ -2731,7 +2797,8 @@ public function toString() } /** - * magic method + * magic method. + * * @return string representation of this object */ public function __toString() diff --git a/lib/Doctrine/Record/Abstract.php b/lib/Doctrine/Record/Abstract.php index 709b72bbd..317076826 100644 --- a/lib/Doctrine/Record/Abstract.php +++ b/lib/Doctrine/Record/Abstract.php @@ -20,38 +20,36 @@ */ /** - * Doctrine_Record_Abstract + * Doctrine_Record_Abstract. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ abstract class Doctrine_Record_Abstract extends Doctrine_Access { /** - * @param Doctrine_Table $_table reference to associated Doctrine_Table instance + * @param Doctrine_Table $_table reference to associated Doctrine_Table instance */ protected $_table; public function setTableDefinition() { - } public function setUp() { - - } + } /** * getTable - * returns the associated table object + * returns the associated table object. * - * @return Doctrine_Table the associated table object + * @return Doctrine_Table the associated table object */ public function getTable() { @@ -59,9 +57,11 @@ public function getTable() } /** - * addListener + * addListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable|Doctrine_Record_Listener_Interface $listener + * @param mixed|null $name + * * @return Doctrine_Record */ public function addListener($listener, $name = null) @@ -72,7 +72,7 @@ public function addListener($listener, $name = null) } /** - * getListener + * getListener. * * @return Doctrine_EventListener_Interface|Doctrine_Overloadable|Doctrine_Record_Listener_Interface */ @@ -82,9 +82,10 @@ public function getListener() } /** - * setListener + * setListener. * * @param Doctrine_EventListener_Interface|Doctrine_Overloadable|Doctrine_Record_Listener_Interface $listener + * * @return Doctrine_Record */ public function setListener($listener) @@ -98,32 +99,30 @@ public function setListener($listener) * index * defines or retrieves an index * if the second parameter is set this method defines an index - * if not this method retrieves index named $name + * if not this method retrieves index named $name. * - * @param string $name the name of the index - * @param array $definition the definition array - * @return mixed + * @param string $name the name of the index + * @param array $definition the definition array */ public function index($name, array $definition = array()) { - if ( ! $definition) { + if (!$definition) { return $this->_table->getIndex($name); - } else { - return $this->_table->addIndex($name, $definition); } + + return $this->_table->addIndex($name, $definition); } /** - * Defines a n-uple of fields that must be unique for every record. + * Defines a n-uple of fields that must be unique for every record. * - * This method Will automatically add UNIQUE index definition + * This method Will automatically add UNIQUE index definition * and validate the values on save. The UNIQUE index is not created in the * database until you use @see export(). * - * @param array $fields values are fieldnames - * @param array $options array of options for unique validator - * @param bool $createUniqueIndex Whether or not to create a unique index in the database - * @return void + * @param array $fields values are fieldnames + * @param array $options array of options for unique validator + * @param bool $createUniqueIndex Whether or not to create a unique index in the database */ public function unique($fields, $options = array(), $createUniqueIndex = true) { @@ -150,21 +149,21 @@ public function setSubclasses($map) $class = get_class($this); // Set the inheritance map for subclasses if (isset($map[$class])) { - // fix for #1621 - $mapFieldNames = $map[$class]; - $mapColumnNames = array(); + // fix for #1621 + $mapFieldNames = $map[$class]; + $mapColumnNames = array(); - foreach ($mapFieldNames as $fieldName => $val) { - $mapColumnNames[$this->getTable()->getColumnName($fieldName)] = $val; + foreach ($mapFieldNames as $fieldName => $val) { + $mapColumnNames[$this->getTable()->getColumnName($fieldName)] = $val; } - + $this->_table->setOption('inheritanceMap', $mapColumnNames); + return; - } else { - // Put an index on the key column - $mapFieldName = array_keys(end($map)); - $this->index($this->getTable()->getTableName().'_'.$mapFieldName[0], array('fields' => array($mapFieldName[0]))); } + // Put an index on the key column + $mapFieldName = array_keys(end($map)); + $this->index($this->getTable()->getTableName().'_'.$mapFieldName[0], array('fields' => array($mapFieldName[0]))); // Set the subclasses array for the parent class $this->_table->setOption('subclasses', array_keys($map)); @@ -172,16 +171,13 @@ public function setSubclasses($map) /** * attribute - * sets or retrieves an option + * sets or retrieves an option. * * @see Doctrine_Core::ATTR_* constants availible attributes - * @param mixed $attr - * @param mixed $value - * @return mixed */ public function attribute($attr, $value) { - if ($value == null) { + if (null == $value) { if (is_array($attr)) { foreach ($attr as $k => $v) { $this->_table->setAttribute($k, $v); @@ -191,21 +187,21 @@ public function attribute($attr, $value) } } else { $this->_table->setAttribute($attr, $value); - } + } } /** * option - * sets or retrieves an option + * sets or retrieves an option. * * @see Doctrine_Table::$options availible options - * @param mixed $name the name of the option - * @param mixed $value options value - * @return mixed + * + * @param mixed $name the name of the option + * @param mixed $value options value */ public function option($name, $value = null) { - if ($value === null) { + if (null === $value) { if (is_array($name)) { foreach ($name as $k => $v) { $this->_table->setOption($k, $v); @@ -219,12 +215,11 @@ public function option($name, $value = null) } /** - * Binds One-to-One aggregate relation + * Binds One-to-One aggregate relation. * - * @param string $componentName the name of the related component - * @param string $options relation options * @see Doctrine_Relation::_$definition - * @return Doctrine_Record this object + * + * @return Doctrine_Record this object */ public function hasOne() { @@ -234,12 +229,11 @@ public function hasOne() } /** - * Binds One-to-Many / Many-to-Many aggregate relation + * Binds One-to-Many / Many-to-Many aggregate relation. * - * @param string $componentName the name of the related component - * @param string $options relation options * @see Doctrine_Relation::_$definition - * @return Doctrine_Record this object + * + * @return Doctrine_Record this object */ public function hasMany() { @@ -249,13 +243,11 @@ public function hasMany() } /** - * Sets a column definition + * Sets a column definition. * * @param string $name * @param string $type - * @param integer $length - * @param mixed $options - * @return void + * @param int $length */ public function hasColumn($name, $type = null, $length = null, $options = array()) { @@ -263,15 +255,12 @@ public function hasColumn($name, $type = null, $length = null, $options = array( } /** - * Set multiple column definitions at once - * - * @param array $definitions - * @return void + * Set multiple column definitions at once. */ public function hasColumns(array $definitions) { foreach ($definitions as $name => $options) { - $length = isset($options['length']) ? $options['length']:null; + $length = isset($options['length']) ? $options['length'] : null; $this->hasColumn($name, $options['type'], $length, $options); } } @@ -289,10 +278,6 @@ public function hasColumns(array $definitions) * 'unique' => true * )); * } - * - * @param string $columnName - * @param array $validators - * @return void */ public function setColumnOptions($name, array $options) { @@ -300,12 +285,11 @@ public function setColumnOptions($name, array $options) } /** - * Set an individual column option + * Set an individual column option. * - * @param string $columnName - * @param string $option - * @param string $value - * @return void + * @param string $columnName + * @param string $option + * @param string $value */ public function setColumnOption($columnName, $option, $value) { @@ -314,21 +298,22 @@ public function setColumnOption($columnName, $option, $value) /** * bindQueryParts - * binds query parts to given component + * binds query parts to given component. * - * @param array $queryParts an array of pre-bound query parts - * @return Doctrine_Record this object + * @param array $queryParts an array of pre-bound query parts + * + * @return Doctrine_Record this object */ public function bindQueryParts(array $queryParts) { - $this->_table->bindQueryParts($queryParts); + $this->_table->bindQueryParts($queryParts); return $this; } public function loadGenerator(Doctrine_Record_Generator $generator) { - $generator->initialize($this->_table); + $generator->initialize($this->_table); $this->_table->addGenerator($generator, get_class($generator)); } @@ -336,31 +321,33 @@ public function loadGenerator(Doctrine_Record_Generator $generator) /** * Loads the given plugin. * - * This method loads a behavior in the record. It will add the behavior + * This method loads a behavior in the record. It will add the behavior * also to the record table if it. * It is tipically called in @see setUp(). * - * @param mixed $tpl if an object, must be a subclass of Doctrine_Template. - * If a string, Doctrine will try to instantiate an object of the classes Doctrine_Template_$tpl and subsequently $tpl, using also autoloading capabilities if defined. - * @param array $options argument to pass to the template constructor if $tpl is a class name - * @throws Doctrine_Record_Exception if $tpl is neither an instance of Doctrine_Template subclass or a valid class name, that could be instantiated. - * @return Doctrine_Record this object; provides a fluent interface. + * @param mixed $tpl if an object, must be a subclass of Doctrine_Template. + * If a string, Doctrine will try to instantiate an object of the classes Doctrine_Template_$tpl and subsequently $tpl, using also autoloading capabilities if defined. + * @param array $options argument to pass to the template constructor if $tpl is a class name + * + * @return Doctrine_Record this object; provides a fluent interface + * + * @throws Doctrine_Record_Exception if $tpl is neither an instance of Doctrine_Template subclass or a valid class name, that could be instantiated */ public function actAs($tpl, array $options = array()) { - if ( ! is_object($tpl)) { - $className = 'Doctrine_Template_' . $tpl; + if (!is_object($tpl)) { + $className = 'Doctrine_Template_'.$tpl; if (class_exists($className, true)) { $tpl = new $className($options); - } else if (class_exists($tpl, true)) { + } elseif (class_exists($tpl, true)) { $tpl = new $tpl($options); } else { - throw new Doctrine_Record_Exception('Could not load behavior named: "' . $tpl . '"'); + throw new Doctrine_Record_Exception('Could not load behavior named: "'.$tpl.'"'); } } - if ( ! ($tpl instanceof Doctrine_Template)) { + if (!($tpl instanceof Doctrine_Template)) { throw new Doctrine_Record_Exception('Loaded behavior class is not an instance of Doctrine_Template.'); } @@ -381,9 +368,10 @@ public function actAs($tpl, array $options = array()) * * This method will add a CHECK constraint to the record table. * - * @param mixed $constraint either a SQL constraint portion or an array of CHECK constraints. If array, all values will be added as constraint - * @param string $name optional constraint name. Not used if $constraint is an array. - * @return Doctrine_Record this object + * @param mixed $constraint either a SQL constraint portion or an array of CHECK constraints. If array, all values will be added as constraint + * @param string $name optional constraint name. Not used if $constraint is an array. + * + * @return Doctrine_Record this object */ public function check($constraint, $name = null) { @@ -394,6 +382,7 @@ public function check($constraint, $name = null) } else { $this->_table->addCheckConstraint($constraint, $name); } + return $this; } } diff --git a/lib/Doctrine/Record/Exception.php b/lib/Doctrine/Record/Exception.php index ceec785cb..0d66e8f06 100644 --- a/lib/Doctrine/Record/Exception.php +++ b/lib/Doctrine/Record/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. * - * @package Doctrine - * @subpackage Record * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Record_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Record/Filter.php b/lib/Doctrine/Record/Filter.php index b122ff723..8cb824920 100644 --- a/lib/Doctrine/Record/Filter.php +++ b/lib/Doctrine/Record/Filter.php @@ -21,14 +21,14 @@ /** * Doctrine_Record_Filter - * Filters the record getters and setters + * Filters the record getters and setters. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1298 $ */ abstract class Doctrine_Record_Filter @@ -65,8 +65,6 @@ abstract public function filterSet(Doctrine_Record $record, $propertyOrRelation, * * @param string $propertyOrRelation * - * @return mixed - * * @thrown Doctrine_Exception when this way is not available */ abstract public function filterGet(Doctrine_Record $record, $propertyOrRelation); diff --git a/lib/Doctrine/Record/Filter/Compound.php b/lib/Doctrine/Record/Filter/Compound.php index 38e599aec..0a92b1b81 100644 --- a/lib/Doctrine/Record/Filter/Compound.php +++ b/lib/Doctrine/Record/Filter/Compound.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Record_Filter_Compound + * Doctrine_Record_Filter_Compound. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1298 $ */ class Doctrine_Record_Filter_Compound extends Doctrine_Record_Filter @@ -72,7 +72,7 @@ public function filterSet(Doctrine_Record $record, $propertyOrRelation, $value) // Related to PHP-7.0 compatibility so an explicit call to method get is required. $record[$alias]; - if ( ! $record->exists()) { + if (!$record->exists()) { if (isset($record[$alias][$propertyOrRelation])) { $record[$alias][$propertyOrRelation] = $value; @@ -94,8 +94,6 @@ public function filterSet(Doctrine_Record $record, $propertyOrRelation, $value) * * @param string $propertyOrRelation * - * @return mixed - * * @thrown Doctrine_Record_UnknownPropertyException when this way is not available */ public function filterGet(Doctrine_Record $record, $propertyOrRelation) @@ -105,7 +103,7 @@ public function filterGet(Doctrine_Record $record, $propertyOrRelation) // Related to PHP-7.0 compatibility so an explicit call to method get is required. $record[$alias]; - if ( ! $record->exists()) { + if (!$record->exists()) { if (isset($record[$alias][$propertyOrRelation])) { return $record[$alias][$propertyOrRelation]; } diff --git a/lib/Doctrine/Record/Filter/Standard.php b/lib/Doctrine/Record/Filter/Standard.php index f2a665358..42d0a0033 100644 --- a/lib/Doctrine/Record/Filter/Standard.php +++ b/lib/Doctrine/Record/Filter/Standard.php @@ -21,14 +21,14 @@ /** * Doctrine_Record_Filter_Standard - * Filters the record getters and setters + * Filters the record getters and setters. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1298 $ */ class Doctrine_Record_Filter_Standard extends Doctrine_Record_Filter diff --git a/lib/Doctrine/Record/Generator.php b/lib/Doctrine/Record/Generator.php index 728207ee0..e2a397a79 100644 --- a/lib/Doctrine/Record/Generator.php +++ b/lib/Doctrine/Record/Generator.php @@ -20,44 +20,44 @@ */ /** - * Doctrine_Record_Generator + * Doctrine_Record_Generator. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Plugin * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ abstract class Doctrine_Record_Generator extends Doctrine_Record_Abstract { /** - * _options + * _options. * - * @var array $_options an array of plugin specific options + * @var array an array of plugin specific options */ protected $_options = array( - 'generateFiles' => false, - 'generatePath' => false, + 'generateFiles' => false, + 'generatePath' => false, 'builderOptions' => array(), - 'identifier' => false, - 'table' => false, - 'pluginTable' => false, - 'children' => array(), - 'cascadeDelete' => true, - 'appLevelDelete' => false + 'identifier' => false, + 'table' => false, + 'pluginTable' => false, + 'children' => array(), + 'cascadeDelete' => true, + 'appLevelDelete' => false, ); /** - * Whether or not the generator has been initialized + * Whether or not the generator has been initialized. * - * @var bool $_initialized + * @var bool */ protected $_initialized = false; /** - * An alias for getOption + * An alias for getOption. * * @param string $option */ @@ -66,53 +66,52 @@ public function __get($option) if (isset($this->_options[$option])) { return $this->_options[$option]; } + return null; } /** - * __isset + * __isset. * * @param string $option */ - public function __isset($option) + public function __isset($option) { return isset($this->_options[$option]); } /** - * Returns the value of an option + * Returns the value of an option. * - * @param $option the name of the option to retrieve - * @return mixed the value of the option + * @return mixed the value of the option */ public function getOption($name) { - if ( ! isset($this->_options[$name])) { - throw new Doctrine_Exception('Unknown option ' . $name); + if (!isset($this->_options[$name])) { + throw new Doctrine_Exception('Unknown option '.$name); } - + return $this->_options[$name]; } /** - * Sets given value to an option + * Sets given value to an option. + * + * @param $value the value of the option * - * @param $option the name of the option to be changed - * @param $value the value of the option - * @return Doctrine_Plugin this object + * @return Doctrine_Plugin this object */ public function setOption($name, $value) { $this->_options[$name] = $value; - + return $this; } /** - * Add child record generator + * Add child record generator. * - * @param Doctrine_Record_Generator $generator - * @return void + * @param Doctrine_Record_Generator $generator */ public function addChild($generator) { @@ -120,9 +119,9 @@ public function addChild($generator) } /** - * Returns all options and their associated values + * Returns all options and their associated values. * - * @return array all options as an associative array + * @return array all options as an associative array */ public function getOptions() { @@ -130,18 +129,16 @@ public function getOptions() } /** - * Initialize the plugin. Call in Doctrine_Template setTableDefinition() in order to initiate a generator in a template + * Initialize the plugin. Call in Doctrine_Template setTableDefinition() in order to initiate a generator in a template. * * @see Doctrine_Template_I18n - * @param Doctrine_Table $table - * @return void */ public function initialize(Doctrine_Table $table) { - if ($this->_initialized) { - return false; - } - + if ($this->_initialized) { + return false; + } + $this->_initialized = true; $this->initOptions(); @@ -161,8 +158,9 @@ public function initialize(Doctrine_Table $table) } // check that class doesn't exist (otherwise we cannot create it) - if ($this->_options['generateFiles'] === false && class_exists($this->_options['className'])) { + if (false === $this->_options['generateFiles'] && class_exists($this->_options['className'])) { $this->_table = Doctrine_Core::getTable($this->_options['className']); + return false; } @@ -187,12 +185,10 @@ public function initialize(Doctrine_Table $table) /** * Create the new Doctrine_Table instance in $this->_table based on the owning * table. - * - * @return void */ public function buildTable() { - // Bind model + // Bind model $conn = $this->_options['table']->getConnection(); $bindConnName = $conn->getManager()->getConnectionForComponent($this->_options['table']->getComponentName())->getName(); if ($bindConnName) { @@ -203,7 +199,7 @@ public function buildTable() // Create table $tableClass = $conn->getAttribute(Doctrine_Core::ATTR_TABLE_CLASS); - $this->_table = new $tableClass($this->_options['className'], $conn); + $this->_table = new $tableClass($this->_options['className'], $conn); $this->_table->setGenerator($this); // If custom table name set then lets use it @@ -227,31 +223,26 @@ public function buildTable() $conn->addTable($this->_table); } - /** + /** * Empty template method for providing the concrete plugins the ability - * to initialize options before the actual definition is being built - * - * @return void + * to initialize options before the actual definition is being built. */ public function initOptions() { - } /** - * Build the child behavior definitions that are attached to this generator - * - * @return void + * Build the child behavior definitions that are attached to this generator. */ public function buildChildDefinitions() { - if ( ! isset($this->_options['children'])) { + if (!isset($this->_options['children'])) { throw new Doctrine_Record_Exception("Unknown option 'children'."); } foreach ($this->_options['children'] as $child) { if ($child instanceof Doctrine_Template) { - if ($child->getPlugin() !== null) { + if (null !== $child->getPlugin()) { $this->_table->addGenerator($child->getPlugin(), get_class($child->getPlugin())); } @@ -273,8 +264,9 @@ public function buildChildDefinitions() * These columns are automatically added to the generated model so we can * create foreign keys back to the table object that owns the plugin. * - * @param Doctrine_Table $table the table object that owns the plugin - * @return array an array of foreign key definitions + * @param Doctrine_Table $table the table object that owns the plugin + * + * @return array an array of foreign key definitions */ public function buildForeignKeys(Doctrine_Table $table) { @@ -283,53 +275,50 @@ public function buildForeignKeys(Doctrine_Table $table) foreach ((array) $table->getIdentifier() as $field) { $def = $table->getDefinitionOf($field); - unset($def['autoincrement']); - unset($def['sequence']); - unset($def['primary']); + unset($def['autoincrement'], $def['sequence'], $def['primary']); - $col = $table->hasColumn($field) ? $field : $table->getColumnName($field) . ' as ' . $field; + $col = $table->hasColumn($field) ? $field : $table->getColumnName($field).' as '.$field; $def['primary'] = true; $fk[$col] = $def; } + return $fk; } /** - * Build the local relationship on the generated model for this generator - * instance which points to the invoking table in $this->_options['table'] + * Build the local relationship on the generated model for this generator + * instance which points to the invoking table in $this->_options['table']. * * @param string $alias Alias of the foreign relation - * @return void */ public function buildLocalRelation($alias = null) { $options = array( - 'local' => $this->getRelationLocalKey(), - 'foreign' => $this->getRelationForeignKey(), - 'owningSide' => true + 'local' => $this->getRelationLocalKey(), + 'foreign' => $this->getRelationForeignKey(), + 'owningSide' => true, ); - if (isset($this->_options['cascadeDelete']) && $this->_options['cascadeDelete'] && ! $this->_options['appLevelDelete']) { + if (isset($this->_options['cascadeDelete']) && $this->_options['cascadeDelete'] && !$this->_options['appLevelDelete']) { $options['onDelete'] = 'CASCADE'; $options['onUpdate'] = 'CASCADE'; } $aliasStr = ''; - if ($alias !== null) { - $aliasStr = ' as ' . $alias; + if (null !== $alias) { + $aliasStr = ' as '.$alias; } - $this->hasOne($this->_options['table']->getComponentName() . $aliasStr, $options); + $this->hasOne($this->_options['table']->getComponentName().$aliasStr, $options); } /** - * Add a Doctrine_Relation::MANY relationship to the generator owner table + * Add a Doctrine_Relation::MANY relationship to the generator owner table. * - * @param string $name - * @param array $options - * @return void + * @param string $name + * @param array $options */ public function ownerHasMany($name, $options) { @@ -337,11 +326,10 @@ public function ownerHasMany($name, $options) } /** - * Add a Doctrine_Relation::ONE relationship to the generator owner table + * Add a Doctrine_Relation::ONE relationship to the generator owner table. * - * @param string $name - * @param array $options - * @return void + * @param string $name + * @param array $options */ public function ownerHasOne($name, $options) { @@ -353,14 +341,13 @@ public function ownerHasOne($name, $options) * which points back to the model generated in this generator instance. * * @param string $alias Alias of the foreign relation - * @return void */ public function buildForeignRelation($alias = null) { $options = array( - 'local' => $this->getRelationForeignKey(), - 'foreign' => $this->getRelationLocalKey(), - 'localKey' => false + 'local' => $this->getRelationForeignKey(), + 'foreign' => $this->getRelationLocalKey(), + 'localKey' => false, ); if (isset($this->_options['cascadeDelete']) && $this->_options['cascadeDelete'] && $this->_options['appLevelDelete']) { @@ -369,15 +356,15 @@ public function buildForeignRelation($alias = null) $aliasStr = ''; - if ($alias !== null) { - $aliasStr = ' as ' . $alias; + if (null !== $alias) { + $aliasStr = ' as '.$alias; } - $this->ownerHasMany($this->_table->getComponentName() . $aliasStr, $options); + $this->ownerHasMany($this->_table->getComponentName().$aliasStr, $options); } /** - * Get the local key of the generated relationship + * Get the local key of the generated relationship. * * @return string $local */ @@ -387,7 +374,7 @@ public function getRelationLocalKey() } /** - * Get the foreign key of the generated relationship + * Get the foreign key of the generated relationship. * * @return string $foreign */ @@ -402,16 +389,14 @@ public function getRelationForeignKey() return $column; } } - + return $identifier; } /** - * This method can be used for generating the relation from the plugin + * This method can be used for generating the relation from the plugin * table to the owner table. By default buildForeignRelation() and buildLocalRelation() are called - * Those methods can be overridden or this entire method can be overridden - * - * @return void + * Those methods can be overridden or this entire method can be overridden. */ public function buildRelation() { @@ -420,10 +405,7 @@ public function buildRelation() } /** - * Generate a Doctrine_Record from a populated Doctrine_Table instance - * - * @param Doctrine_Table $table - * @return void + * Generate a Doctrine_Record from a populated Doctrine_Table instance. */ public function generateClassFromTable(Doctrine_Table $table) { @@ -436,11 +418,10 @@ public function generateClassFromTable(Doctrine_Table $table) } /** - * Generates the class definition for plugin class + * Generates the class definition for plugin class. * - * @param array $definition Definition array defining columns, relations and options - * for the model - * @return void + * @param array $definition Definition array defining columns, relations and options + * for the model */ public function generateClass(array $definition = array()) { @@ -451,7 +432,7 @@ public function generateClass(array $definition = array()) } $builder = new Doctrine_Import_Builder(); - $builderOptions = isset($this->_options['builderOptions']) ? (array) $this->_options['builderOptions']:array(); + $builderOptions = isset($this->_options['builderOptions']) ? (array) $this->_options['builderOptions'] : array(); $builder->setOptions($builderOptions); if ($this->_options['generateFiles']) { @@ -467,4 +448,4 @@ public function generateClass(array $definition = array()) eval($def); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Record/Iterator.php b/lib/Doctrine/Record/Iterator.php index 6385c0131..a8ba4a863 100644 --- a/lib/Doctrine/Record/Iterator.php +++ b/lib/Doctrine/Record/Iterator.php @@ -20,32 +20,30 @@ */ /** - * Doctrine_Record_Iterator + * Doctrine_Record_Iterator. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Record_Iterator extends ArrayIterator { /** - * @var Doctrine_Record $record + * @var Doctrine_Record */ private $record; /** - * @var Doctrine_Null $null + * @var Doctrine_Null */ private static $null; /** - * constructor - * - * @param Doctrine_Record $record + * constructor. */ public function __construct(Doctrine_Record $record) { @@ -54,9 +52,7 @@ public function __construct(Doctrine_Record $record) } /** - * initNullObject - * - * @param Doctrine_Null $null + * initNullObject. */ public static function initNullObject(Doctrine_Null $null) { @@ -64,19 +60,17 @@ public static function initNullObject(Doctrine_Null $null) } /** - * current - * - * @return mixed + * current. */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function current() { $value = parent::current(); if ($value === self::$null) { return null; - } else { - return $value; } + + return $value; } } diff --git a/lib/Doctrine/Record/Listener.php b/lib/Doctrine/Record/Listener.php index 24e8858dd..355465f47 100644 --- a/lib/Doctrine/Record/Listener.php +++ b/lib/Doctrine/Record/Listener.php @@ -20,120 +20,140 @@ */ /** - * Doctrine_Record_Listener + * Doctrine_Record_Listener. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Record_Listener implements Doctrine_Record_Listener_Interface { /** - * @var array $_options an array containing options + * @var array an array containing options */ - protected $_options = array('disabled' => false); - - /** - * setOption - * sets an option in order to allow flexible listener - * - * @param mixed $name the name of the option to set - * @param mixed $value the value of the option - */ - public function setOption($name, $value = null) - { - if (is_array($name)) { - $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $name); - } else { - $this->_options[$name] = $value; + protected $_options = array('disabled' => false); + + /** + * setOption + * sets an option in order to allow flexible listener. + * + * @param mixed $name the name of the option to set + * @param mixed $value the value of the option + */ + public function setOption($name, $value = null) + { + if (is_array($name)) { + $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $name); + } else { + $this->_options[$name] = $value; } } - + /** * getOptions - * returns all options of this template and the associated values + * returns all options of this template and the associated values. * - * @return array all options and their values + * @return array all options and their values */ public function getOptions() { return $this->_options; } - /** - * getOption - * returns the value of given option - * - * @param string $name the name of the option - * @return mixed the value of given option - */ - public function getOption($name) - { - if (isset($this->_options[$name])) { - return $this->_options[$name]; - } + /** + * getOption + * returns the value of given option. + * + * @param string $name the name of the option + * + * @return mixed the value of given option + */ + public function getOption($name) + { + if (isset($this->_options[$name])) { + return $this->_options[$name]; + } - return null; + return null; } - + public function preSerialize(Doctrine_Event $event) - { } + { + } public function postSerialize(Doctrine_Event $event) - { } + { + } public function preUnserialize(Doctrine_Event $event) - { } + { + } public function postUnserialize(Doctrine_Event $event) - { } + { + } public function preDqlSelect(Doctrine_Event $event) - { } + { + } public function preSave(Doctrine_Event $event) - { } + { + } public function postSave(Doctrine_Event $event) - { } + { + } public function preDqlDelete(Doctrine_Event $event) - { } + { + } public function preDelete(Doctrine_Event $event) - { } + { + } public function postDelete(Doctrine_Event $event) - { } + { + } public function preDqlUpdate(Doctrine_Event $event) - { } + { + } public function preUpdate(Doctrine_Event $event) - { } + { + } public function postUpdate(Doctrine_Event $event) - { } + { + } public function preInsert(Doctrine_Event $event) - { } + { + } public function postInsert(Doctrine_Event $event) - { } + { + } public function preHydrate(Doctrine_Event $event) - { } + { + } public function postHydrate(Doctrine_Event $event) - { } + { + } public function preValidate(Doctrine_Event $event) - { } - + { + } + public function postValidate(Doctrine_Event $event) - { } -} \ No newline at end of file + { + } +} diff --git a/lib/Doctrine/Record/Listener/Chain.php b/lib/Doctrine/Record/Listener/Chain.php index 93a10937c..e7932b7cb 100644 --- a/lib/Doctrine/Record/Listener/Chain.php +++ b/lib/Doctrine/Record/Listener/Chain.php @@ -22,62 +22,63 @@ /** * Doctrine_Record_Listener_Chain * this class represents a chain of different listeners, - * useful for having multiple listeners listening the events at the same time + * useful for having multiple listeners listening the events at the same time. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Record_Listener_Chain extends Doctrine_Access implements Doctrine_Record_Listener_Interface { /** - * @var array $listeners an array containing all listeners + * @var array an array containing all listeners */ protected $_listeners = array(); /** - * @var array $_options an array containing chain options + * @var array an array containing chain options + */ + protected $_options = array('disabled' => false); + + /** + * setOption + * sets an option in order to allow flexible listener chaining. + * + * @param mixed $name the name of the option to set + * @param mixed $value the value of the option + */ + public function setOption($name, $value = null) + { + if (is_array($name)) { + $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $name); + } else { + $this->_options[$name] = $value; + } + } + + /** + * getOption + * returns the value of given option. + * + * @param string $name the name of the option + * + * @return mixed the value of given option */ - protected $_options = array('disabled' => false); - - /** - * setOption - * sets an option in order to allow flexible listener chaining - * - * @param mixed $name the name of the option to set - * @param mixed $value the value of the option - */ - public function setOption($name, $value = null) - { - if (is_array($name)) { - $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $name); - } else { - $this->_options[$name] = $value; + public function getOption($name) + { + if (isset($this->_options[$name])) { + return $this->_options[$name]; } - } - - /** - * getOption - * returns the value of given option - * - * @param string $name the name of the option - * @return mixed the value of given option - */ - public function getOption($name) - { - if (isset($this->_options[$name])) { - return $this->_options[$name]; - } - - return null; + + return null; } /** - * Get array of configured options + * Get array of configured options. * * @return array $options */ @@ -88,20 +89,18 @@ public function getOptions() /** * add - * adds a listener to the chain of listeners + * adds a listener to the chain of listeners. * * @param object $listener * @param string $name - * @return void */ public function add($listener, $name = null) { - if ( ! ($listener instanceof Doctrine_Record_Listener_Interface) && - ! ($listener instanceof Doctrine_Overloadable)) { - + if (!($listener instanceof Doctrine_Record_Listener_Interface) + && !($listener instanceof Doctrine_Overloadable)) { throw new Doctrine_EventListener_Exception("Couldn't add eventlistener. Record listeners should implement either Doctrine_Record_Listener_Interface or Doctrine_Overloadable"); } - if ($name === null) { + if (null === $name) { $this->_listeners[] = $listener; } else { $this->_listeners[$name] = $listener; @@ -110,25 +109,23 @@ public function add($listener, $name = null) /** * returns a Doctrine_Record_Listener on success - * and null on failure - * - * @param mixed $key - * @return mixed + * and null on failure. */ public function get($key) { - if ( ! isset($this->_listeners[$key])) { + if (!isset($this->_listeners[$key])) { return null; } + return $this->_listeners[$key]; } /** - * set + * set. * - * @param mixed $key - * @param Doctrine_Record_Listener $listener listener to be added - * @return Doctrine_Record_Listener_Chain this object + * @param Doctrine_Record_Listener $listener listener to be added + * + * @return Doctrine_Record_Listener_Chain this object */ public function set($key, $listener) { @@ -137,13 +134,13 @@ public function set($key, $listener) public function preSerialize(Doctrine_Event $event) { - $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preSerialize', $disabled))) { + $disabled = $this->getOption('disabled'); + + if (true !== $disabled && !(is_array($disabled) && in_array('preSerialize', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preSerialize', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preSerialize', $disabled))) { $listener->preSerialize($event); } } @@ -153,12 +150,12 @@ public function preSerialize(Doctrine_Event $event) public function postSerialize(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postSerialize', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postSerialize', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postSerialize', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postSerialize', $disabled))) { $listener->postSerialize($event); } } @@ -168,12 +165,12 @@ public function postSerialize(Doctrine_Event $event) public function preUnserialize(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preUnserialize', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preUnserialize', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preUnserialize', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preUnserialize', $disabled))) { $listener->preUnserialize($event); } } @@ -183,12 +180,12 @@ public function preUnserialize(Doctrine_Event $event) public function postUnserialize(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postUnserialize', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postUnserialize', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postUnserialize', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postUnserialize', $disabled))) { $listener->postUnserialize($event); } } @@ -198,12 +195,12 @@ public function postUnserialize(Doctrine_Event $event) public function preDqlSelect(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlSelect', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlSelect', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlSelect', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlSelect', $disabled))) { $listener->preDqlSelect($event); } } @@ -213,12 +210,12 @@ public function preDqlSelect(Doctrine_Event $event) public function preSave(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preSave', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preSave', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preSave', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preSave', $disabled))) { $listener->preSave($event); } } @@ -228,12 +225,12 @@ public function preSave(Doctrine_Event $event) public function postSave(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postSave', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postSave', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postSave', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postSave', $disabled))) { $listener->postSave($event); } } @@ -243,12 +240,12 @@ public function postSave(Doctrine_Event $event) public function preDqlDelete(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlDelete', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlDelete', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlDelete', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlDelete', $disabled))) { $listener->preDqlDelete($event); } } @@ -258,12 +255,12 @@ public function preDqlDelete(Doctrine_Event $event) public function preDelete(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preDelete', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preDelete', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preDelete', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preDelete', $disabled))) { $listener->preDelete($event); } } @@ -273,12 +270,12 @@ public function preDelete(Doctrine_Event $event) public function postDelete(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postDelete', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postDelete', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postDelete', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postDelete', $disabled))) { $listener->postDelete($event); } } @@ -288,12 +285,12 @@ public function postDelete(Doctrine_Event $event) public function preDqlUpdate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlUpdate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlUpdate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preDqlUpdate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preDqlUpdate', $disabled))) { $listener->preDqlUpdate($event); } } @@ -303,12 +300,12 @@ public function preDqlUpdate(Doctrine_Event $event) public function preUpdate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preUpdate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preUpdate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preUpdate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preUpdate', $disabled))) { $listener->preUpdate($event); } } @@ -318,12 +315,12 @@ public function preUpdate(Doctrine_Event $event) public function postUpdate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postUpdate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postUpdate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postUpdate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postUpdate', $disabled))) { $listener->postUpdate($event); } } @@ -333,12 +330,12 @@ public function postUpdate(Doctrine_Event $event) public function preInsert(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preInsert', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preInsert', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preInsert', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preInsert', $disabled))) { $listener->preInsert($event); } } @@ -348,12 +345,12 @@ public function preInsert(Doctrine_Event $event) public function postInsert(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postInsert', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postInsert', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postInsert', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postInsert', $disabled))) { $listener->postInsert($event); } } @@ -363,12 +360,12 @@ public function postInsert(Doctrine_Event $event) public function preHydrate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preHydrate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preHydrate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preHydrate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preHydrate', $disabled))) { $listener->preHydrate($event); } } @@ -378,45 +375,45 @@ public function preHydrate(Doctrine_Event $event) public function postHydrate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postHydrate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postHydrate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postHydrate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postHydrate', $disabled))) { $listener->postHydrate($event); } } } } - + public function preValidate(Doctrine_Event $event) - { + { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('preValidate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('preValidate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('preValidate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('preValidate', $disabled))) { $listener->preValidate($event); } } } } - + public function postValidate(Doctrine_Event $event) { $disabled = $this->getOption('disabled'); - - if ($disabled !== true && ! (is_array($disabled) && in_array('postValidate', $disabled))) { + + if (true !== $disabled && !(is_array($disabled) && in_array('postValidate', $disabled))) { foreach ($this->_listeners as $listener) { $disabled = $listener->getOption('disabled'); - if ($disabled !== true && ! (is_array($disabled) && in_array('postValidate', $disabled))) { + if (true !== $disabled && !(is_array($disabled) && in_array('postValidate', $disabled))) { $listener->postValidate($event); } } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Record/Listener/Interface.php b/lib/Doctrine/Record/Listener/Interface.php index bb2ce6ae2..c32b52138 100644 --- a/lib/Doctrine/Record/Listener/Interface.php +++ b/lib/Doctrine/Record/Listener/Interface.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Record_Listener + * Doctrine_Record_Listener. * - * @package Doctrine - * @subpackage Record * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ interface Doctrine_Record_Listener_Interface @@ -61,8 +61,8 @@ public function postUpdate(Doctrine_Event $event); public function preInsert(Doctrine_Event $event); public function postInsert(Doctrine_Event $event); - + public function preHydrate(Doctrine_Event $event); - + public function postHydrate(Doctrine_Event $event); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Record/State/Exception.php b/lib/Doctrine/Record/State/Exception.php index bbafb7006..0c5d320c2 100644 --- a/lib/Doctrine/Record/State/Exception.php +++ b/lib/Doctrine/Record/State/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Exception + * Doctrine_Exception. * - * @package Doctrine - * @subpackage Record * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Record_State_Exception extends Doctrine_Record_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Record/UnknownPropertyException.php b/lib/Doctrine/Record/UnknownPropertyException.php index 389004f89..9461e1d4c 100644 --- a/lib/Doctrine/Record/UnknownPropertyException.php +++ b/lib/Doctrine/Record/UnknownPropertyException.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Record_UnknownPropertyException + * Doctrine_Record_UnknownPropertyException. * - * @package Doctrine - * @subpackage Record * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 4252 $ + * * @author Konsta Vesterinen */ class Doctrine_Record_UnknownPropertyException extends Doctrine_Record_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Relation.php b/lib/Doctrine/Relation.php index cbdcb6ff2..2818e0167 100644 --- a/lib/Doctrine/Relation.php +++ b/lib/Doctrine/Relation.php @@ -21,66 +21,67 @@ /** * Doctrine_Relation - * This class represents a relation between components + * This class represents a relation between components. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ abstract class Doctrine_Relation implements ArrayAccess { /** - * RELATION CONSTANTS + * RELATION CONSTANTS. */ /** - * constant for ONE_TO_ONE and MANY_TO_ONE relationships + * constant for ONE_TO_ONE and MANY_TO_ONE relationships. */ - const ONE = 0; + public const ONE = 0; /** - * constant for MANY_TO_MANY and ONE_TO_MANY relationships + * constant for MANY_TO_MANY and ONE_TO_MANY relationships. */ - const MANY = 1; + public const MANY = 1; // TRUE => mandatory, everything else is just a default value. this should be refactored // since TRUE can bot be used as a default value this way. All values should be default values. /** - * @var array $definition @see __construct() + * @var array @see __construct() */ - protected $definition = array('alias' => true, - 'foreign' => true, - 'local' => true, - 'class' => true, - 'type' => true, - 'table' => true, - 'localTable' => true, - 'name' => null, - 'refTable' => null, - 'onDelete' => null, - 'onUpdate' => null, - 'deferred' => null, - 'deferrable' => null, - 'constraint' => null, - 'equal' => false, - 'cascade' => array(), // application-level cascades - 'owningSide' => false, // whether this is the owning side - 'refClassRelationAlias' => null, - 'foreignKeyName' => null, - 'orderBy' => null - ); - - protected $_isRefClass = null; + protected $definition = array('alias' => true, + 'foreign' => true, + 'local' => true, + 'class' => true, + 'type' => true, + 'table' => true, + 'localTable' => true, + 'name' => null, + 'refTable' => null, + 'onDelete' => null, + 'onUpdate' => null, + 'deferred' => null, + 'deferrable' => null, + 'constraint' => null, + 'equal' => false, + 'cascade' => array(), // application-level cascades + 'owningSide' => false, // whether this is the owning side + 'refClassRelationAlias' => null, + 'foreignKeyName' => null, + 'orderBy' => null, + ); + + protected $_isRefClass; /** - * constructor + * constructor. * - * @param array $definition an associative array with the following structure: - * name foreign key constraint name + * @param array $definition an associative array with the following structure: + * name foreign key constraint name * * local the local field(s) * @@ -129,8 +130,8 @@ public function __construct(array $definition) { $def = array(); foreach ($this->definition as $key => $val) { - if ( ! isset($definition[$key]) && $val) { - throw new Doctrine_Exception($key . ' is required!'); + if (!isset($definition[$key]) && $val) { + throw new Doctrine_Exception($key.' is required!'); } if (isset($definition[$key])) { $def[$key] = $definition[$key]; @@ -143,15 +144,15 @@ public function __construct(array $definition) /** * hasConstraint - * whether or not this relation has an explicit constraint + * whether or not this relation has an explicit constraint. * - * @return boolean + * @return bool */ public function hasConstraint() { - return ($this->definition['constraint'] || - ($this->definition['onUpdate']) || - ($this->definition['onDelete'])); + return $this->definition['constraint'] + || $this->definition['onUpdate'] + || $this->definition['onDelete']; } public function isDeferred() @@ -172,16 +173,13 @@ public function isEqual() /** * @return bool */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetExists($offset) { return isset($this->definition[$offset]); } - /** - * @return mixed - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetGet($offset) { if (isset($this->definition[$offset])) { @@ -191,10 +189,7 @@ public function offsetGet($offset) return null; } - /** - * @return void - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetSet($offset, $value) { if (isset($this->definition[$offset])) { @@ -202,17 +197,14 @@ public function offsetSet($offset, $value) } } - /** - * @return void - */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function offsetUnset($offset) { $this->definition[$offset] = false; } /** - * toArray + * toArray. * * @return array */ @@ -223,7 +215,7 @@ public function toArray() /** * getAlias - * returns the relation alias + * returns the relation alias. * * @return string */ @@ -234,10 +226,11 @@ final public function getAlias() /** * getType - * returns the relation type, either 0 or 1 + * returns the relation type, either 0 or 1. * * @see Doctrine_Relation MANY_* and ONE_* constants - * @return integer + * + * @return int */ final public function getType() { @@ -248,7 +241,7 @@ final public function getType() * Checks whether this relation cascades deletions to the related objects * on the application level. * - * @return boolean + * @return bool */ public function isCascadeDelete() { @@ -257,20 +250,21 @@ public function isCascadeDelete() /** * getTable - * returns the foreign table object + * returns the foreign table object. * * @return Doctrine_Table */ final public function getTable() { return Doctrine_Manager::getInstance() - ->getConnectionForComponent($this->definition['class']) - ->getTable($this->definition['class']); + ->getConnectionForComponent($this->definition['class']) + ->getTable($this->definition['class']) + ; } /** * getClass - * returns the name of the related class + * returns the name of the related class. * * @return string */ @@ -281,7 +275,7 @@ final public function getClass() /** * getLocal - * returns the name of the local column + * returns the name of the local column. * * @return string */ @@ -292,7 +286,7 @@ final public function getLocal() /** * getLocalFieldName - * returns the field name of the local column + * returns the field name of the local column. */ final public function getLocalFieldName() { @@ -301,7 +295,7 @@ final public function getLocalFieldName() /** * getLocalColumnName - * returns the column name of the local column + * returns the column name of the local column. * * @return string $columnName */ @@ -313,7 +307,7 @@ final public function getLocalColumnName() /** * getForeign * returns the name of the foreignkey column where - * the localkey column is pointing at + * the localkey column is pointing at. * * @return string */ @@ -324,7 +318,7 @@ final public function getForeign() /** * getLocalFieldName - * returns the field name of the foreign column + * returns the field name of the foreign column. */ final public function getForeignFieldName() { @@ -333,56 +327,54 @@ final public function getForeignFieldName() /** * getForeignColumnName - * returns the column name of the foreign column + * returns the column name of the foreign column. * * @return string $columnName */ final public function getForeignColumnName() { - return $this->definition['table']->getColumnName($this->definition['foreign']); + return $this->definition['table']->getColumnName($this->definition['foreign']); } /** * isOneToOne - * returns whether or not this relation is a one-to-one relation + * returns whether or not this relation is a one-to-one relation. * - * @return boolean + * @return bool */ final public function isOneToOne() { - return ($this->definition['type'] == Doctrine_Relation::ONE); + return Doctrine_Relation::ONE == $this->definition['type']; } /** - * getRelationDql + * getRelationDql. + * + * @param int $count * - * @param integer $count * @return string */ public function getRelationDql($count) { $component = $this->getTable()->getComponentName(); - $dql = 'FROM ' . $component - . ' WHERE ' . $component . '.' . $this->definition['foreign'] - . ' IN (' . substr(str_repeat('?, ', $count), 0, -2) . ')' - . $this->getOrderBy($component); - - return $dql; + return 'FROM '.$component + .' WHERE '.$component.'.'.$this->definition['foreign'] + .' IN ('.substr(str_repeat('?, ', $count), 0, -2).')' + .$this->getOrderBy($component); } /** - * fetchRelatedFor + * fetchRelatedFor. * * fetches a component related to given record * - * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ abstract public function fetchRelatedFor(Doctrine_Record $record); /** - * Get the name of the foreign key for this relationship + * Get the name of the foreign key for this relationship. * * @return string $foreignKeyName */ @@ -391,59 +383,62 @@ public function getForeignKeyName() if (isset($this->definition['foreignKeyName'])) { return $this->definition['foreignKeyName']; } + return $this['localTable']->getConnection()->generateUniqueRelationForeignKeyName($this); } /** - * Get the relationship orderby SQL/DQL + * Get the relationship orderby SQL/DQL. + * + * @param string $alias The alias to use + * @param bool $columnNames Whether or not to use column names instead of field names * - * @param string $alias The alias to use - * @param boolean $columnNames Whether or not to use column names instead of field names * @return string $orderBy */ public function getOrderBy($alias = null, $columnNames = false) { - if ( ! $alias) { - $alias = $this->getTable()->getComponentName(); + if (!$alias) { + $alias = $this->getTable()->getComponentName(); } if ($orderBy = $this->getOrderByStatement($alias, $columnNames)) { - return ' ORDER BY ' . $orderBy; + return ' ORDER BY '.$orderBy; } } /** - * Get the relationship orderby statement + * Get the relationship orderby statement. + * + * @param string $alias The alias to use + * @param bool $columnNames Whether or not to use column names instead of field names * - * @param string $alias The alias to use - * @param boolean $columnNames Whether or not to use column names instead of field names * @return string $orderByStatement */ public function getOrderByStatement($alias = null, $columnNames = false) { $table = $this->getTable(); - if ( ! $alias) { - $alias = $table->getComponentName(); + if (!$alias) { + $alias = $table->getComponentName(); } if (isset($this->definition['orderBy'])) { return $table->processOrderBy($alias, $this->definition['orderBy'], $columnNames); - } else { - return $table->getOrderByStatement($alias, $columnNames); } + + return $table->getOrderByStatement($alias, $columnNames); } public function isRefClass() { - if ($this->_isRefClass === null) { + if (null === $this->_isRefClass) { $this->_isRefClass = false; $table = $this->getTable(); foreach ($table->getRelations() as $name => $relation) { foreach ($relation['table']->getRelations() as $relation) { if (isset($relation['refTable']) && $relation['refTable'] === $table) { $this->_isRefClass = true; - break(2); + break 2; } } } @@ -453,20 +448,21 @@ public function isRefClass() } /** - * __toString + * __toString. * * @return string */ public function __toString() { - $r[] = "
";
+        $r[] = '
';
         foreach ($this->definition as $k => $v) {
             if (is_object($v)) {
-                $v = 'Object(' . get_class($v) . ')';
+                $v = 'Object('.get_class($v).')';
             }
-            $r[] = $k . ' : ' . $v;
+            $r[] = $k.' : '.$v;
         }
-        $r[] = "
"; + $r[] = '
'; + return implode("\n", $r); } } diff --git a/lib/Doctrine/Relation/Association.php b/lib/Doctrine/Relation/Association.php index 6d4c3ca7f..35543c312 100644 --- a/lib/Doctrine/Relation/Association.php +++ b/lib/Doctrine/Relation/Association.php @@ -22,15 +22,15 @@ /** * Doctrine_Relation_Association this class takes care of association mapping * (= many-to-many relationships, where the relationship is handled with an additional relational table - * which holds 2 foreign keys) + * which holds 2 foreign keys). * - * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Association extends Doctrine_Relation @@ -49,29 +49,30 @@ public function getAssociationTable() } /** - * getRelationDql + * getRelationDql. + * + * @param int $count * - * @param integer $count * @return string */ public function getRelationDql($count, $context = 'record') { $table = $this->definition['refTable']; $component = $this->definition['refTable']->getComponentName(); - + switch ($context) { - case "record": - $sub = substr(str_repeat("?, ", $count),0,-2); - $dql = 'FROM ' . $this->getTable()->getComponentName(); - $dql .= '.' . $component; - $dql .= ' WHERE ' . $this->getTable()->getComponentName() - . '.' . $component . '.' . $this->getLocalRefColumnName() . ' IN (' . $sub . ')'; + case 'record': + $sub = substr(str_repeat('?, ', $count), 0, -2); + $dql = 'FROM '.$this->getTable()->getComponentName(); + $dql .= '.'.$component; + $dql .= ' WHERE '.$this->getTable()->getComponentName() + .'.'.$component.'.'.$this->getLocalRefColumnName().' IN ('.$sub.')'; $dql .= $this->getOrderBy($this->getTable()->getComponentName(), false); break; - case "collection": - $sub = substr(str_repeat("?, ", $count),0,-2); - $dql = 'FROM ' . $component . '.' . $this->getTable()->getComponentName(); - $dql .= ' WHERE ' . $component . '.' . $this->getLocalRefColumnName() . ' IN (' . $sub . ')'; + case 'collection': + $sub = substr(str_repeat('?, ', $count), 0, -2); + $dql = 'FROM '.$component.'.'.$this->getTable()->getComponentName(); + $dql .= ' WHERE '.$component.'.'.$this->getLocalRefColumnName().' IN ('.$sub.')'; $dql .= $this->getOrderBy($component, false); break; } @@ -79,59 +80,59 @@ public function getRelationDql($count, $context = 'record') return $dql; } - /** + /** * getLocalRefColumnName - * returns the column name of the local reference column + * returns the column name of the local reference column. */ final public function getLocalRefColumnName() { - return $this->definition['refTable']->getColumnName($this->definition['local']); + return $this->definition['refTable']->getColumnName($this->definition['local']); } /** * getLocalRefFieldName - * returns the field name of the local reference column + * returns the field name of the local reference column. */ final public function getLocalRefFieldName() { - return $this->definition['refTable']->getFieldName($this->definition['local']); + return $this->definition['refTable']->getFieldName($this->definition['local']); } /** * getForeignRefColumnName - * returns the column name of the foreign reference column + * returns the column name of the foreign reference column. */ final public function getForeignRefColumnName() { - return $this->definition['refTable']->getColumnName($this->definition['foreign']); + return $this->definition['refTable']->getColumnName($this->definition['foreign']); } /** * getForeignRefFieldName - * returns the field name of the foreign reference column + * returns the field name of the foreign reference column. */ final public function getForeignRefFieldName() { - return $this->definition['refTable']->getFieldName($this->definition['foreign']); + return $this->definition['refTable']->getFieldName($this->definition['foreign']); } /** - * fetchRelatedFor + * fetchRelatedFor. * * fetches a component related to given record * - * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->getIncremented(); - if (empty($id) || ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { + if (empty($id) || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $coll = Doctrine_Collection::create($this->getTable()); } else { $coll = $this->getTable()->getConnection()->query($this->getRelationDql(1), array($id)); } $coll->setReference($record, $this); + return $coll; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Relation/Association/Self.php b/lib/Doctrine/Relation/Association/Self.php index 1f9487bed..5f53d25b7 100644 --- a/lib/Doctrine/Relation/Association/Self.php +++ b/lib/Doctrine/Relation/Association/Self.php @@ -20,22 +20,24 @@ */ /** - * Doctrine_Relation_Association_Self + * Doctrine_Relation_Association_Self. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Association_Self extends Doctrine_Relation_Association { /** - * getRelationDql + * getRelationDql. + * + * @param int $count * - * @param integer $count * @return string */ public function getRelationDql($count, $context = 'record') @@ -44,73 +46,74 @@ public function getRelationDql($count, $context = 'record') case 'record': $identifierColumnNames = $this->definition['table']->getIdentifierColumnNames(); $identifier = array_pop($identifierColumnNames); - $sub = 'SELECT '.$this->definition['foreign'] - . ' FROM '.$this->definition['refTable']->getTableName() - . ' WHERE '.$this->definition['local'] - . ' = ?'; + $sub = 'SELECT '.$this->definition['foreign'] + .' FROM '.$this->definition['refTable']->getTableName() + .' WHERE '.$this->definition['local'] + .' = ?'; - $sub2 = 'SELECT '.$this->definition['local'] - . ' FROM '.$this->definition['refTable']->getTableName() - . ' WHERE '.$this->definition['foreign'] - . ' = ?'; + $sub2 = 'SELECT '.$this->definition['local'] + .' FROM '.$this->definition['refTable']->getTableName() + .' WHERE '.$this->definition['foreign'] + .' = ?'; - $dql = 'FROM ' . $this->definition['table']->getComponentName() - . '.' . $this->definition['refTable']->getComponentName() - . ' WHERE ' . $this->definition['table']->getComponentName() - . '.' . $identifier - . ' IN (' . $sub . ')' - . ' || ' . $this->definition['table']->getComponentName() - . '.' . $identifier - . ' IN (' . $sub2 . ')'; + $dql = 'FROM '.$this->definition['table']->getComponentName() + .'.'.$this->definition['refTable']->getComponentName() + .' WHERE '.$this->definition['table']->getComponentName() + .'.'.$identifier + .' IN ('.$sub.')' + .' || '.$this->definition['table']->getComponentName() + .'.'.$identifier + .' IN ('.$sub2.')'; - $dql .= $this->getOrderBy($this->definition['table']->getComponentName(), false); + $dql .= $this->getOrderBy($this->definition['table']->getComponentName(), false); break; case 'collection': - $sub = substr(str_repeat('?, ', $count),0,-2); - $dql = 'FROM '.$this->definition['refTable']->getComponentName() - . '.' . $this->definition['table']->getComponentName() - . ' WHERE '.$this->definition['refTable']->getComponentName() - . '.' . $this->definition['local'] . ' IN (' . $sub . ')'; + $sub = substr(str_repeat('?, ', $count), 0, -2); + $dql = 'FROM '.$this->definition['refTable']->getComponentName() + .'.'.$this->definition['table']->getComponentName() + .' WHERE '.$this->definition['refTable']->getComponentName() + .'.'.$this->definition['local'].' IN ('.$sub.')'; $dql .= $this->getOrderBy($this->definition['refTable']->getComponentName(), false); - }; + } return $dql; } public function fetchRelatedFor(Doctrine_Record $record) { - $id = $record->getIncremented(); + $id = $record->getIncremented(); $q = new Doctrine_RawSql(); $assocTable = $this->getAssociationFactory()->getTableName(); - $tableName = $record->getTable()->getTableName(); + $tableName = $record->getTable()->getTableName(); $identifierColumnNames = $record->getTable()->getIdentifierColumnNames(); $identifier = array_pop($identifierColumnNames); - $sub = 'SELECT '.$this->getForeign(). + $sub = 'SELECT '.$this->getForeign(). ' FROM '.$assocTable. ' WHERE '.$this->getLocal(). ' = ?'; - $sub2 = 'SELECT '.$this->getLocal(). + $sub2 = 'SELECT '.$this->getLocal(). ' FROM '.$assocTable. ' WHERE '.$this->getForeign(). ' = ?'; $q->select('{'.$tableName.'.*}, {'.$assocTable.'.*}') - ->from($tableName . ' INNER JOIN '.$assocTable.' ON '. - $tableName . '.' . $identifier . ' = ' . $assocTable . '.' . $this->getLocal() . ' OR ' . - $tableName . '.' . $identifier . ' = ' . $assocTable . '.' . $this->getForeign() - ) - ->where($tableName.'.'.$identifier.' IN ('.$sub.') OR '. - $tableName.'.'.$identifier.' IN ('.$sub2.')' - ); - $q->addComponent($tableName, $record->getTable()->getComponentName()); - $q->addComponent($assocTable, $record->getTable()->getComponentName(). '.' . $this->getAssociationFactory()->getComponentName()); + ->from($tableName.' INNER JOIN '.$assocTable.' ON '. + $tableName.'.'.$identifier.' = '.$assocTable.'.'.$this->getLocal().' OR '. + $tableName.'.'.$identifier.' = '.$assocTable.'.'.$this->getForeign() + ) + ->where($tableName.'.'.$identifier.' IN ('.$sub.') OR '. + $tableName.'.'.$identifier.' IN ('.$sub2.')' + ) + ; + $q->addComponent($tableName, $record->getTable()->getComponentName()); + $q->addComponent($assocTable, $record->getTable()->getComponentName().'.'.$this->getAssociationFactory()->getComponentName()); $q->orderBy($this->getOrderByStatement($tableName, true)); return $q->execute(array($id, $id)); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Relation/Exception.php b/lib/Doctrine/Relation/Exception.php index 8937b9e2b..53e96f3cd 100644 --- a/lib/Doctrine/Relation/Exception.php +++ b/lib/Doctrine/Relation/Exception.php @@ -17,18 +17,20 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * . - */ + */ /** - * Doctrine_Relation_Exception + * Doctrine_Relation_Exception. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1344 $ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Relation/ForeignKey.php b/lib/Doctrine/Relation/ForeignKey.php index f07bbefbf..09f056faa 100644 --- a/lib/Doctrine/Relation/ForeignKey.php +++ b/lib/Doctrine/Relation/ForeignKey.php @@ -21,24 +21,23 @@ /** * Doctrine_Relation_ForeignKey - * This class represents a foreign key relation + * This class represents a foreign key relation. * - * @package Doctrine - * @subpackage Relation * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Relation_ForeignKey extends Doctrine_Relation { /** - * fetchRelatedFor + * fetchRelatedFor. * * fetches a component related to given record * - * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) @@ -46,55 +45,54 @@ public function fetchRelatedFor(Doctrine_Record $record) $id = array(); $localTable = $record->getTable(); foreach ((array) $this->definition['local'] as $local) { - $value = $record->get($localTable->getFieldName($local)); - if (isset($value)) { - $id[] = $value; - } + $value = $record->get($localTable->getFieldName($local)); + if (isset($value)) { + $id[] = $value; + } } if ($this->isOneToOne()) { - if ( ! $record->exists() || empty($id) || - ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { - + if (!$record->exists() || empty($id) + || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $related = $this->getTable()->create(); } else { - $dql = 'FROM ' . $this->getTable()->getComponentName() - . ' WHERE ' . $this->getCondition() . $this->getOrderBy(null, false); + $dql = 'FROM '.$this->getTable()->getComponentName() + .' WHERE '.$this->getCondition().$this->getOrderBy(null, false); $coll = $this->getTable()->getConnection()->query($dql, $id); $related = $coll[0]; } $related->set($related->getTable()->getFieldName($this->definition['foreign']), - $record, false); + $record, false); } else { - - if ( ! $record->exists() || empty($id) || - ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { - + if (!$record->exists() || empty($id) + || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $related = Doctrine_Collection::create($this->getTable()); } else { - $query = $this->getRelationDql(1); - $related = $this->getTable()->getConnection()->query($query, $id); + $query = $this->getRelationDql(1); + $related = $this->getTable()->getConnection()->query($query, $id); } $related->setReference($record, $this); } + return $related; } /** - * getCondition + * getCondition. * * @param string $alias */ public function getCondition($alias = null) { - if ( ! $alias) { - $alias = $this->getTable()->getComponentName(); + if (!$alias) { + $alias = $this->getTable()->getComponentName(); } $conditions = array(); foreach ((array) $this->definition['foreign'] as $foreign) { - $conditions[] = $alias . '.' . $foreign . ' = ?'; + $conditions[] = $alias.'.'.$foreign.' = ?'; } + return implode(' AND ', $conditions); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Relation/LocalKey.php b/lib/Doctrine/Relation/LocalKey.php index 1663b9681..4910b6f1f 100644 --- a/lib/Doctrine/Relation/LocalKey.php +++ b/lib/Doctrine/Relation/LocalKey.php @@ -21,24 +21,23 @@ /** * Doctrine_Relation_LocalKey - * This class represents a local key relation + * This class represents a local key relation. * - * @package Doctrine - * @subpackage Relation * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Relation_LocalKey extends Doctrine_Relation { /** - * fetchRelatedFor + * fetchRelatedFor. * * fetches a component related to given record * - * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) @@ -46,24 +45,25 @@ public function fetchRelatedFor(Doctrine_Record $record) $localFieldName = $record->getTable()->getFieldName($this->definition['local']); $id = $record->get($localFieldName); - if (is_null($id) || ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { + if (is_null($id) || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $related = $this->getTable()->create(); - // Ticket #1131 Patch. - if ( ! is_null($id)) { + // Ticket #1131 Patch. + if (!is_null($id)) { $related->assignIdentifier($id); $related->state(Doctrine_Record::STATE_PROXY); } } else { - $dql = 'FROM ' . $this->getTable()->getComponentName() - . ' WHERE ' . $this->getCondition() . $this->getOrderBy(null, false); + $dql = 'FROM '.$this->getTable()->getComponentName() + .' WHERE '.$this->getCondition().$this->getOrderBy(null, false); $related = $this->getTable() - ->getConnection() - ->query($dql, array($id)) - ->getFirst(); - - if ( ! $related || empty($related)) { + ->getConnection() + ->query($dql, array($id)) + ->getFirst() + ; + + if (!$related || empty($related)) { $related = $this->getTable()->create(); } } @@ -74,15 +74,16 @@ public function fetchRelatedFor(Doctrine_Record $record) } /** - * getCondition + * getCondition. * * @param string $alias */ public function getCondition($alias = null) { - if ( ! $alias) { - $alias = $this->getTable()->getComponentName(); + if (!$alias) { + $alias = $this->getTable()->getComponentName(); } - return $alias . '.' . $this->definition['foreign'] . ' = ?'; + + return $alias.'.'.$this->definition['foreign'].' = ?'; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Relation/Nest.php b/lib/Doctrine/Relation/Nest.php index 65b5f7325..cbedd7b04 100644 --- a/lib/Doctrine/Relation/Nest.php +++ b/lib/Doctrine/Relation/Nest.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Relation_Association_Self + * Doctrine_Relation_Association_Self. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1434 $ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Nest extends Doctrine_Relation_Association @@ -36,55 +37,53 @@ public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->getIncremented(); - if (empty($id) || ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { + if (empty($id) || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { return Doctrine_Collection::create($this->getTable()); - } else { - $q = new Doctrine_RawSql($this->getTable()->getConnection()); - $formatter = $q->getConnection()->formatter; - - $assocTable = $this->getAssociationFactory()->getTableName(); - $tableName = $record->getTable()->getTableName(); - $identifierColumnNames = $record->getTable()->getIdentifierColumnNames(); - $identifier = $formatter->quoteIdentifier(array_pop($identifierColumnNames)); + } + $q = new Doctrine_RawSql($this->getTable()->getConnection()); + $formatter = $q->getConnection()->formatter; - $sub = 'SELECT ' . $formatter->quoteIdentifier($this->getForeignRefColumnName()) - . ' FROM ' . $formatter->quoteIdentifier($assocTable) - . ' WHERE ' . $formatter->quoteIdentifier($this->getLocalRefColumnName()) - . ' = ?'; + $assocTable = $this->getAssociationFactory()->getTableName(); + $tableName = $record->getTable()->getTableName(); + $identifierColumnNames = $record->getTable()->getIdentifierColumnNames(); + $identifier = $formatter->quoteIdentifier(array_pop($identifierColumnNames)); - $condition[] = $formatter->quoteIdentifier($tableName) . '.' . $identifier . ' IN (' . $sub . ')'; - $joinCondition[] = $formatter->quoteIdentifier($tableName) . '.' . $identifier . ' = ' . $formatter->quoteIdentifier($assocTable) . '.' . $formatter->quoteIdentifier($this->getForeignRefColumnName()); + $sub = 'SELECT '.$formatter->quoteIdentifier($this->getForeignRefColumnName()) + .' FROM '.$formatter->quoteIdentifier($assocTable) + .' WHERE '.$formatter->quoteIdentifier($this->getLocalRefColumnName()) + .' = ?'; - if ($this->definition['equal']) { - $sub2 = 'SELECT ' . $formatter->quoteIdentifier($this->getLocalRefColumnName()) - . ' FROM ' . $formatter->quoteIdentifier($assocTable) - . ' WHERE ' . $formatter->quoteIdentifier($this->getForeignRefColumnName()) - . ' = ?'; + $condition[] = $formatter->quoteIdentifier($tableName).'.'.$identifier.' IN ('.$sub.')'; + $joinCondition[] = $formatter->quoteIdentifier($tableName).'.'.$identifier.' = '.$formatter->quoteIdentifier($assocTable).'.'.$formatter->quoteIdentifier($this->getForeignRefColumnName()); - $condition[] = $formatter->quoteIdentifier($tableName) . '.' . $identifier . ' IN (' . $sub2 . ')'; - $joinCondition[] = $formatter->quoteIdentifier($tableName) . '.' . $identifier . ' = ' . $formatter->quoteIdentifier($assocTable) . '.' . $formatter->quoteIdentifier($this->getLocalRefColumnName()); - } - $q->select('{'.$tableName.'.*}, {'.$assocTable.'.*}') - ->from($formatter->quoteIdentifier($tableName) . ' INNER JOIN ' . $formatter->quoteIdentifier($assocTable) . ' ON ' . implode(' OR ', $joinCondition)) - ->where(implode(' OR ', $condition)); - if ($orderBy = $this->getOrderByStatement($tableName, true)) { - $q->addOrderBy($orderBy); - } else { - $q->addOrderBy($formatter->quoteIdentifier($tableName) . '.' . $identifier . ' ASC'); - } - $q->addComponent($tableName, $this->getClass()); + if ($this->definition['equal']) { + $sub2 = 'SELECT '.$formatter->quoteIdentifier($this->getLocalRefColumnName()) + .' FROM '.$formatter->quoteIdentifier($assocTable) + .' WHERE '.$formatter->quoteIdentifier($this->getForeignRefColumnName()) + .' = ?'; - $path = $this->getClass(). '.' . $this->getAssociationFactory()->getComponentName(); - if ($this->definition['refClassRelationAlias']) { - $path = $this->getClass(). '.' . $this->definition['refClassRelationAlias']; - } - $q->addComponent($assocTable, $path); + $condition[] = $formatter->quoteIdentifier($tableName).'.'.$identifier.' IN ('.$sub2.')'; + $joinCondition[] = $formatter->quoteIdentifier($tableName).'.'.$identifier.' = '.$formatter->quoteIdentifier($assocTable).'.'.$formatter->quoteIdentifier($this->getLocalRefColumnName()); + } + $q->select('{'.$tableName.'.*}, {'.$assocTable.'.*}') + ->from($formatter->quoteIdentifier($tableName).' INNER JOIN '.$formatter->quoteIdentifier($assocTable).' ON '.implode(' OR ', $joinCondition)) + ->where(implode(' OR ', $condition)) + ; + if ($orderBy = $this->getOrderByStatement($tableName, true)) { + $q->addOrderBy($orderBy); + } else { + $q->addOrderBy($formatter->quoteIdentifier($tableName).'.'.$identifier.' ASC'); + } + $q->addComponent($tableName, $this->getClass()); - $params = ($this->definition['equal']) ? array($id, $id) : array($id); + $path = $this->getClass().'.'.$this->getAssociationFactory()->getComponentName(); + if ($this->definition['refClassRelationAlias']) { + $path = $this->getClass().'.'.$this->definition['refClassRelationAlias']; + } + $q->addComponent($assocTable, $path); - $res = $q->execute($params); + $params = ($this->definition['equal']) ? array($id, $id) : array($id); - return $res; - } + return $q->execute($params); } } diff --git a/lib/Doctrine/Relation/Parser.php b/lib/Doctrine/Relation/Parser.php index 45eda5bd5..214f92a1a 100644 --- a/lib/Doctrine/Relation/Parser.php +++ b/lib/Doctrine/Relation/Parser.php @@ -20,38 +20,39 @@ */ /** - * Doctrine_Relation_Parser + * Doctrine_Relation_Parser. * - * @package Doctrine - * @subpackage Relation * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @todo Composite key support? */ class Doctrine_Relation_Parser { /** - * @var Doctrine_Table $_table the table object this parser belongs to + * @var Doctrine_Table the table object this parser belongs to */ protected $_table; /** - * @var array $_relations an array containing all the Doctrine_Relation objects for this table + * @var array an array containing all the Doctrine_Relation objects for this table */ protected $_relations = array(); /** - * @var array $_pending relations waiting for parsing + * @var array relations waiting for parsing */ - protected $_pending = array(); + protected $_pending = array(); /** - * constructor + * constructor. * - * @param Doctrine_Table $table the table object this parser belongs to + * @param Doctrine_Table $table the table object this parser belongs to */ public function __construct(Doctrine_Table $table) { @@ -59,9 +60,9 @@ public function __construct(Doctrine_Table $table) } /** - * getTable + * getTable. * - * @return Doctrine_Table the table object this parser belongs to + * @return Doctrine_Table the table object this parser belongs to */ public function getTable() { @@ -69,23 +70,23 @@ public function getTable() } /** - * getPendingRelation + * getPendingRelation. * - * @return array an array defining a pending relation + * @return array an array defining a pending relation */ public function getPendingRelation($name) { - if ( ! isset($this->_pending[$name])) { - throw new Doctrine_Relation_Exception('Unknown pending relation ' . $name); + if (!isset($this->_pending[$name])) { + throw new Doctrine_Relation_Exception('Unknown pending relation '.$name); } return $this->_pending[$name]; } /** - * getPendingRelations + * getPendingRelations. * - * @return array an array containing all the pending relations + * @return array an array containing all the pending relations */ public function getPendingRelations() { @@ -94,24 +95,25 @@ public function getPendingRelations() /** * unsetPendingRelations - * Removes a relation. Warning: this only affects pending relations + * Removes a relation. Warning: this only affects pending relations. * * @param string relation to remove */ public function unsetPendingRelations($name) { - unset($this->_pending[$name]); + unset($this->_pending[$name]); } /** - * Check if a relation alias exists + * Check if a relation alias exists. * * @param string $name - * @return boolean $bool + * + * @return bool $bool */ public function hasRelation($name) { - if ( ! isset($this->_pending[$name]) && ! isset($this->_relations[$name])) { + if (!isset($this->_pending[$name]) && !isset($this->_relations[$name])) { return false; } @@ -119,11 +121,9 @@ public function hasRelation($name) } /** - * binds a relation + * binds a relation. * * @param string $name - * @param string $field - * @return void */ public function bind($name, $options = array()) { @@ -134,13 +134,12 @@ public function bind($name, $options = array()) $name = $e[0]; $alias = isset($e[1]) ? $e[1] : $name; - if ( ! isset($options['type'])) { + if (!isset($options['type'])) { throw new Doctrine_Relation_Exception('Relation type not set.'); } if ($this->hasRelation($alias)) { - unset($this->_relations[$alias]); - unset($this->_pending[$alias]); + unset($this->_relations[$alias], $this->_pending[$alias]); } $this->_pending[$alias] = array_merge($options, array('class' => $name, 'alias' => $alias)); @@ -149,9 +148,9 @@ public function bind($name, $options = array()) } /** - * getRelation + * getRelation. * - * @param string $alias relation alias + * @param string $alias relation alias */ public function getRelation($alias, $recursive = true) { @@ -172,30 +171,29 @@ public function getRelation($alias, $recursive = true) $backRefRelationName = isset($def['refClassRelationAlias']) ? $def['refClassRelationAlias'] : $def['refClass']; - if ( ! isset($this->_pending[$backRefRelationName]) && ! isset($this->_relations[$backRefRelationName])) { - + if (!isset($this->_pending[$backRefRelationName]) && !isset($this->_relations[$backRefRelationName])) { $parser = $def['refTable']->getRelationParser(); - if ( ! $parser->hasRelation($this->_table->getComponentName())) { + if (!$parser->hasRelation($this->_table->getComponentName())) { $parser->bind($this->_table->getComponentName(), - array('type' => Doctrine_Relation::ONE, - 'local' => $def['local'], - 'foreign' => $idColumnName, - 'localKey' => true, - )); + array('type' => Doctrine_Relation::ONE, + 'local' => $def['local'], + 'foreign' => $idColumnName, + 'localKey' => true, + )); } - if ( ! $this->hasRelation($backRefRelationName)) { + if (!$this->hasRelation($backRefRelationName)) { if (in_array($def['class'], $localClasses)) { - $this->bind($def['refClass'] . " as " . $backRefRelationName, array( - 'type' => Doctrine_Relation::MANY, - 'foreign' => $def['foreign'], - 'local' => $idColumnName)); + $this->bind($def['refClass'].' as '.$backRefRelationName, array( + 'type' => Doctrine_Relation::MANY, + 'foreign' => $def['foreign'], + 'local' => $idColumnName)); } else { - $this->bind($def['refClass'] . " as " . $backRefRelationName, array( - 'type' => Doctrine_Relation::MANY, - 'foreign' => $def['local'], - 'local' => $idColumnName)); + $this->bind($def['refClass'].' as '.$backRefRelationName, array( + 'type' => Doctrine_Relation::MANY, + 'foreign' => $def['local'], + 'local' => $idColumnName)); } } } @@ -216,7 +214,7 @@ public function getRelation($alias, $recursive = true) foreach ($foreign as $fk) { // Check if its already not indexed (primary key) - if ( ! $rel['table']->isIdentifier($rel['table']->getFieldName($fk))) { + if (!$rel['table']->isIdentifier($rel['table']->getFieldName($fk))) { $rel['table']->addIndex($fk, array('fields' => array($fk))); } } @@ -228,6 +226,7 @@ public function getRelation($alias, $recursive = true) // unset pending relation unset($this->_pending[$alias]); $this->_relations[$alias] = $rel; + return $rel; } } @@ -235,16 +234,15 @@ public function getRelation($alias, $recursive = true) $this->getRelations(); return $this->getRelation($alias, false); - } else { - throw new Doctrine_Table_Exception('Unknown relation alias ' . $alias); } + throw new Doctrine_Table_Exception('Unknown relation alias '.$alias); } /** * getRelations - * returns an array containing all relation objects + * returns an array containing all relation objects. * - * @return array an array of Doctrine_Relation objects + * @return array an array of Doctrine_Relation objects */ public function getRelations() { @@ -259,7 +257,7 @@ public function getRelations() * getImpl * returns the table class of the concrete implementation for given template * if the given template is not a template then this method just returns the - * table class for the given record + * table class for the given record. * * @param string $template */ @@ -270,8 +268,8 @@ public function getImpl($template) if (class_exists($template) && in_array('Doctrine_Template', class_parents($template))) { $impl = $this->_table->getImpl($template); - if ($impl === null) { - throw new Doctrine_Relation_Parser_Exception("Couldn't find concrete implementation for template " . $template); + if (null === $impl) { + throw new Doctrine_Relation_Parser_Exception("Couldn't find concrete implementation for template ".$template); } } else { $impl = $template; @@ -281,10 +279,11 @@ public function getImpl($template) } /** - * Completes the given association definition + * Completes the given association definition. * - * @param array $def definition array to be completed - * @return array completed definition array + * @param array $def definition array to be completed + * + * @return array completed definition array */ public function completeAssocDefinition($def) { @@ -297,20 +296,19 @@ public function completeAssocDefinition($def) $id = $def['refTable']->getIdentifierColumnNames(); if (count($id) > 1) { - if ( ! isset($def['foreign'])) { + if (!isset($def['foreign'])) { // foreign key not set // try to guess the foreign key $def['foreign'] = ($def['local'] === $id[0]) ? $id[1] : $id[0]; } - if ( ! isset($def['local'])) { + if (!isset($def['local'])) { // foreign key not set // try to guess the foreign key $def['local'] = ($def['foreign'] === $id[0]) ? $id[1] : $id[0]; } } else { - - if ( ! isset($def['foreign'])) { + if (!isset($def['foreign'])) { // foreign key not set // try to guess the foreign key @@ -318,7 +316,7 @@ public function completeAssocDefinition($def) $def['foreign'] = $columns; } - if ( ! isset($def['local'])) { + if (!isset($def['local'])) { // local key not set // try to guess the local key $columns = $this->getIdentifiers($this->_table); @@ -326,17 +324,18 @@ public function completeAssocDefinition($def) $def['local'] = $columns; } } + return $def; } /** * getIdentifiers - * gives a list of identifiers from given table + * gives a list of identifiers from given table. * * the identifiers are in format: * [componentName].[identifier] * - * @param Doctrine_Table $table table object to retrieve identifiers from + * @param Doctrine_Table $table table object to retrieve identifiers from */ public function getIdentifiers(Doctrine_Table $table) { @@ -344,22 +343,23 @@ public function getIdentifiers(Doctrine_Table $table) if (is_array($table->getIdentifier())) { $columns = array(); foreach ((array) $table->getIdentifierColumnNames() as $identColName) { - $columns[] = $componentNameToLower . '_' . $identColName; + $columns[] = $componentNameToLower.'_'.$identColName; } } else { - $columns = $componentNameToLower . '_' . $table->getColumnName( - $table->getIdentifier()); + $columns = $componentNameToLower.'_'.$table->getColumnName( + $table->getIdentifier()); } return $columns; } /** - * guessColumns + * guessColumns. + * + * @param array $classes an array of class names + * @param Doctrine_Table $foreignTable foreign table object * - * @param array $classes an array of class names - * @param Doctrine_Table $foreignTable foreign table object - * @return array an array of column names + * @return array an array of column names */ public function guessColumns(array $classes, Doctrine_Table $foreignTable) { @@ -367,15 +367,15 @@ public function guessColumns(array $classes, Doctrine_Table $foreignTable) foreach ($classes as $class) { try { - $table = $conn->getTable($class); + $table = $conn->getTable($class); } catch (Doctrine_Table_Exception $e) { continue; } $columns = $this->getIdentifiers($table); - $found = true; + $found = true; foreach ((array) $columns as $column) { - if ( ! $foreignTable->hasColumn($column)) { + if (!$foreignTable->hasColumn($column)) { $found = false; break; } @@ -385,7 +385,7 @@ public function guessColumns(array $classes, Doctrine_Table $foreignTable) } } - if ( ! $found) { + if (!$found) { throw new Doctrine_Relation_Exception("Couldn't find columns."); } @@ -393,10 +393,12 @@ public function guessColumns(array $classes, Doctrine_Table $foreignTable) } /** - * Completes the given definition + * Completes the given definition. + * + * @param array $def definition array to be completed + * + * @return array completed definition array * - * @param array $def definition array to be completed - * @return array completed definition array * @todo Description: What does it mean to complete a definition? What is done (not how)? * Refactor (too long & nesting level) */ @@ -408,7 +410,7 @@ public function completeDefinition($def) $def['class'] = $def['table']->getComponentName(); $foreignClasses = array_merge($def['table']->getOption('parents'), array($def['class'])); - $localClasses = array_merge($this->_table->getOption('parents'), array($this->_table->getComponentName())); + $localClasses = array_merge($this->_table->getOption('parents'), array($this->_table->getComponentName())); $localIdentifierColumnNames = $this->_table->getIdentifierColumnNames(); $localIdentifierCount = count($localIdentifierColumnNames); @@ -419,7 +421,7 @@ public function completeDefinition($def) if (isset($def['local'])) { $def['local'] = $def['localTable']->getColumnName($def['local']); - if ( ! isset($def['foreign'])) { + if (!isset($def['foreign'])) { // local key is set, but foreign key is not // try to guess the foreign key @@ -434,14 +436,14 @@ public function completeDefinition($def) } else { $def['foreign'] = $def['table']->getColumnName($def['foreign']); - if ($localIdentifierCount == 1) { + if (1 == $localIdentifierCount) { if ($def['local'] == $localIdColumnName && isset($def['owningSide']) - && $def['owningSide'] === true) { + && true === $def['owningSide']) { $def['localKey'] = true; - } else if (($def['local'] !== $localIdColumnName && $def['type'] == Doctrine_Relation::ONE)) { + } elseif ($def['local'] !== $localIdColumnName && Doctrine_Relation::ONE == $def['type']) { $def['localKey'] = true; } - } else if ($localIdentifierCount > 1 && ! isset($def['localKey'])) { + } elseif ($localIdentifierCount > 1 && !isset($def['localKey'])) { // It's a composite key and since 'foreign' can not point to a composite // key currently, we know that 'local' must be the foreign key. $def['localKey'] = true; @@ -475,31 +477,33 @@ public function completeDefinition($def) $identifierColumnNames = $table->getIdentifierColumnNames(); $idColumnName = array_pop($identifierColumnNames); $column = strtolower($table->getComponentName()) - . '_' . $idColumnName; + .'_'.$idColumnName; foreach ($foreignClasses as $class2) { $table2 = $conn->getTable($class2); if ($table2->hasColumn($column)) { $def['foreign'] = $column; $def['local'] = $idColumnName; + return $def; } } } foreach ($foreignClasses as $class) { - $table = $conn->getTable($class); + $table = $conn->getTable($class); $identifierColumnNames = $table->getIdentifierColumnNames(); $idColumnName = array_pop($identifierColumnNames); $column = strtolower($table->getComponentName()) - . '_' . $idColumnName; + .'_'.$idColumnName; foreach ($localClasses as $class2) { $table2 = $conn->getTable($class2); if ($table2->hasColumn($column)) { - $def['foreign'] = $idColumnName; - $def['local'] = $column; + $def['foreign'] = $idColumnName; + $def['local'] = $column; $def['localKey'] = true; + return $def; } } @@ -510,17 +514,13 @@ public function completeDefinition($def) foreach ((array) $this->_table->getIdentifierColumnNames() as $id) { // ?? should this not be $this->_table->getComponentName() ?? $column = strtolower($table->getComponentName()) - . '_' . $id; + .'_'.$id; $col = $this->_table->getColumnDefinition($id); $type = $col['type']; $length = $col['length']; - unset($col['type']); - unset($col['length']); - unset($col['autoincrement']); - unset($col['sequence']); - unset($col['primary']); + unset($col['type'], $col['length'], $col['autoincrement'], $col['sequence'], $col['primary']); $def['table']->setColumn($column, $type, $length, $col); @@ -534,6 +534,7 @@ public function completeDefinition($def) $def['local'] = $localIdColumnName; } } + return $def; } } diff --git a/lib/Doctrine/Relation/Parser/Exception.php b/lib/Doctrine/Relation/Parser/Exception.php index b8447bfbd..77a813983 100644 --- a/lib/Doctrine/Relation/Parser/Exception.php +++ b/lib/Doctrine/Relation/Parser/Exception.php @@ -17,18 +17,20 @@ * This software consists of voluntary contributions made by many individuals * and is licensed under the LGPL. For more information, see * . - */ + */ /** - * Doctrine_Relation_Parser_Exception + * Doctrine_Relation_Parser_Exception. * - * @package Doctrine - * @subpackage Relation * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Relation_Parser_Exception extends Doctrine_Relation_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Search.php b/lib/Doctrine/Search.php index f6449b3c4..ecf943df4 100644 --- a/lib/Doctrine/Search.php +++ b/lib/Doctrine/Search.php @@ -20,51 +20,49 @@ */ /** - * Doctrine_Search + * Doctrine_Search. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search extends Doctrine_Record_Generator { - const INDEX_FILES = 0; - - const INDEX_TABLES = 1; - - protected $_options = array('generateFiles' => false, - 'analyzer' => 'Doctrine_Search_Analyzer_Standard', - 'analyzer_options' => array(), - 'type' => self::INDEX_TABLES, - 'className' => '%CLASS%Index', - 'generatePath' => false, - 'table' => null, - 'batchUpdates' => false, - 'pluginTable' => false, - 'fields' => array(), - 'connection' => null, - 'children' => array(), - 'cascadeDelete' => true, - 'appLevelDelete' => false); + public const INDEX_FILES = 0; + + public const INDEX_TABLES = 1; + + protected $_options = array('generateFiles' => false, + 'analyzer' => 'Doctrine_Search_Analyzer_Standard', + 'analyzer_options' => array(), + 'type' => self::INDEX_TABLES, + 'className' => '%CLASS%Index', + 'generatePath' => false, + 'table' => null, + 'batchUpdates' => false, + 'pluginTable' => false, + 'fields' => array(), + 'connection' => null, + 'children' => array(), + 'cascadeDelete' => true, + 'appLevelDelete' => false); + /** - * __construct - * - * @param array $options - * @return void + * __construct. */ public function __construct(array $options) { $this->_options = Doctrine_Lib::arrayDeepMerge($this->_options, $options); - - if ( ! isset($this->_options['analyzer'])) { + + if (!isset($this->_options['analyzer'])) { $this->_options['analyzer'] = 'Doctrine_Search_Analyzer_Standard'; } - if ( ! isset($this->_options['analyzer_options'])) { + if (!isset($this->_options['analyzer_options'])) { $this->_options['analyzer_options'] = array(); } @@ -75,7 +73,7 @@ public function buildTable() { $result = parent::buildTable(); - if ( ! isset($this->_options['connection'])) { + if (!isset($this->_options['connection'])) { $manager = Doctrine_Manager::getInstance(); $this->_options['connection'] = $manager->getConnectionForComponent($this->_options['table']->getComponentName()); $manager->bindComponent($this->_options['className'], $this->_options['connection']->getName()); @@ -85,11 +83,12 @@ public function buildTable() } /** - * Searchable keyword search - * - * @param string $string Keyword string to search for - * @param Doctrine_Query $query Query object to alter. Adds where condition to limit the results using the search index - * @return array ids and relevancy + * Searchable keyword search. + * + * @param string $string Keyword string to search for + * @param Doctrine_Query $query Query object to alter. Adds where condition to limit the results using the search index + * + * @return array ids and relevancy */ public function search($string, $query = null) { @@ -101,24 +100,23 @@ public function search($string, $query = null) $newQuery = $query->copy(); $query->getSqlQuery(); $key = (array) $this->getOption('table')->getIdentifier(); - $newQuery->addWhere($query->getRootAlias() . '.'.current($key).' IN (SQL:' . $q->getSqlQuery() . ')', $q->getParams()); + $newQuery->addWhere($query->getRootAlias().'.'.current($key).' IN (SQL:'.$q->getSqlQuery().')', $q->getParams()); return $newQuery; - } else { - if ( ! isset($this->_options['connection'])) { - $this->_options['connection'] = $this->_table->getConnection(); - } - $q->query($string); - return $this->_options['connection']->fetchAll($q->getSqlQuery(), $q->getParams()); } + if (!isset($this->_options['connection'])) { + $this->_options['connection'] = $this->_table->getConnection(); + } + $q->query($string); + + return $this->_options['connection']->fetchAll($q->getSqlQuery(), $q->getParams()); } - + /** - * analyze a text in the encoding format - * - * @param string $text + * analyze a text in the encoding format. + * + * @param string $text * @param string $encoding - * @return void */ public function analyze($text, $encoding = null) { @@ -127,40 +125,41 @@ public function analyze($text, $encoding = null) /** * updateIndex - * updates the index + * updates the index. * - * @param Doctrine_Record $record - * @return integer + * @param mixed|null $encoding + * + * @return int */ public function updateIndex(array $data, $encoding = null) { $this->initialize($this->_options['table']); $fields = $this->getOption('fields'); - $class = $this->getOption('className'); - $name = $this->getOption('table')->getComponentName(); - $conn = $this->getOption('table')->getConnection(); + $class = $this->getOption('className'); + $name = $this->getOption('table')->getComponentName(); + $conn = $this->getOption('table')->getConnection(); $identifier = $this->_options['table']->getIdentifier(); $q = Doctrine_Core::getTable($class) ->createQuery() - ->delete(); + ->delete() + ; foreach ((array) $identifier as $id) { - $q->addWhere($id . ' = ?', array($data[$id])); + $q->addWhere($id.' = ?', array($data[$id])); } $q->execute(); - if ($this->_options['batchUpdates'] === true) { - $index = new $class(); + if (true === $this->_options['batchUpdates']) { + $index = new $class(); foreach ((array) $this->_options['table']->getIdentifier() as $id) { - $index->$id = $data[$id]; + $index->{$id} = $data[$id]; } $index->save(); } else { foreach ($fields as $field) { - $value = isset($data[$field]) ? $data[$field] : null; $terms = $this->analyze($value, $encoding); @@ -172,7 +171,7 @@ public function updateIndex(array $data, $encoding = null) $index->position = $pos; $index->field = $field; foreach ((array) $this->_options['table']->getIdentifier() as $id) { - $index->$id = $data[$id]; + $index->{$id} = $data[$id]; } $index->save(); @@ -183,28 +182,26 @@ public function updateIndex(array $data, $encoding = null) } /** - * readTableData - * - * @param mixed $limit - * @param mixed $offset + * readTableData. + * * @return Doctrine_Collection The collection of results */ public function readTableData($limit = null, $offset = null) { $this->initialize($this->_options['table']); - $conn = $this->_options['table']->getConnection(); + $conn = $this->_options['table']->getConnection(); $tableName = $this->_options['table']->getTableName(); - $id = current($this->_options['table']->getIdentifierColumnNames()); - $tableId = current($this->_table->getIdentifierColumnNames()); + $id = current($this->_options['table']->getIdentifierColumnNames()); + $tableId = current($this->_table->getIdentifierColumnNames()); - $query = 'SELECT * FROM ' . $conn->quoteIdentifier($tableName) - . ' WHERE ' . $conn->quoteIdentifier($id) - . ' IN (SELECT ' . $conn->quoteIdentifier($tableId) - . ' FROM ' . $conn->quoteIdentifier($this->_table->getTableName()) - . ' WHERE keyword = \'\') OR ' . $conn->quoteIdentifier($id) - . ' NOT IN (SELECT ' . $conn->quoteIdentifier($tableId) - . ' FROM ' . $conn->quoteIdentifier($this->_table->getTableName()) . ')'; + $query = 'SELECT * FROM '.$conn->quoteIdentifier($tableName) + .' WHERE '.$conn->quoteIdentifier($id) + .' IN (SELECT '.$conn->quoteIdentifier($tableId) + .' FROM '.$conn->quoteIdentifier($this->_table->getTableName()) + .' WHERE keyword = \'\') OR '.$conn->quoteIdentifier($id) + .' NOT IN (SELECT '.$conn->quoteIdentifier($tableId) + .' FROM '.$conn->quoteIdentifier($this->_table->getTableName()).')'; $query = $conn->modifyLimitQuery($query, $limit, $offset); @@ -212,11 +209,9 @@ public function readTableData($limit = null, $offset = null) } /** - * batchUpdateIndex - * - * @param mixed $limit - * @param mixed $offset - * @return void + * batchUpdateIndex. + * + * @param mixed|null $encoding */ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null) { @@ -224,12 +219,12 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null $this->initialize($table); - $id = $table->getIdentifierColumnNames(); - $class = $this->_options['className']; - $fields = $this->_options['fields']; - $conn = $this->_options['table']->getConnection(); - - for ($i = 0; $i < count($fields); $i++) { + $id = $table->getIdentifierColumnNames(); + $class = $this->_options['className']; + $fields = $this->_options['fields']; + $conn = $this->_options['table']->getConnection(); + + for ($i = 0; $i < count($fields); ++$i) { $fields[$i] = $table->getColumnName($fields[$i], $fields[$i]); } @@ -242,24 +237,23 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null } } - if (count($ids) > 0) - { - $sql = 'DELETE FROM ' . $conn->quoteIdentifier($this->_table->getTableName()); + if (count($ids) > 0) { + $sql = 'DELETE FROM '.$conn->quoteIdentifier($this->_table->getTableName()); - if (count($id) == 1) { + if (1 == count($id)) { $placeholders = str_repeat('?, ', count($ids)); $placeholders = substr($placeholders, 0, strlen($placeholders) - 2); - $sql .= ' WHERE ' . $conn->quoteIdentifier($table->getIdentifier()) . ' IN (' . substr($placeholders, 0) . ')'; + $sql .= ' WHERE '.$conn->quoteIdentifier($table->getIdentifier()).' IN ('.substr($placeholders, 0).')'; } else { // composite primary key $placeholders = ''; foreach ($table->getIdentifier() as $id) { - $placeholders .= $conn->quoteIdentifier($id) . ' = ? AND '; + $placeholders .= $conn->quoteIdentifier($id).' = ? AND '; } - $placeholders = '(' . substr($placeholders, 0, strlen($placeholders) - 5) . ') OR '; + $placeholders = '('.substr($placeholders, 0, strlen($placeholders) - 5).') OR '; $placeholders = str_repeat($placeholders, count($rows)); $placeholders = substr($placeholders, 0, strlen($placeholders) - 4); - $sql .= ' WHERE ' . $placeholders; + $sql .= ' WHERE '.$placeholders; } $conn->exec($sql, $ids); @@ -269,21 +263,21 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null $conn->beginTransaction(); try { foreach ($fields as $field) { - $data = $row[$field]; - + $data = $row[$field]; + $terms = $this->analyze($data, $encoding); - + foreach ($terms as $pos => $term) { $index = new $class(); - + $index->keyword = $term; $index->position = $pos; $index->field = $field; - + foreach ((array) $table->getIdentifier() as $identifier) { - $index->$identifier = $row[$table->getColumnName($identifier, $identifier)]; + $index->{$identifier} = $row[$table->getColumnName($identifier, $identifier)]; } - + $index->save(); $index->free(true); } @@ -297,21 +291,19 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null } /** - * buildDefinition - * - * @return void + * buildDefinition. */ public function setTableDefinition() { - if ( ! isset($this->_options['table'])) { - throw new Doctrine_Record_Exception("Unknown option 'table'."); - } + if (!isset($this->_options['table'])) { + throw new Doctrine_Record_Exception("Unknown option 'table'."); + } $componentName = $this->_options['table']->getComponentName(); $className = $this->getOption('className'); - $autoLoad = (bool) ($this->_options['generateFiles']); + $autoLoad = (bool) $this->_options['generateFiles']; if (class_exists($className, $autoLoad)) { return false; } @@ -324,17 +316,17 @@ public function setTableDefinition() $this->_table->removeColumn($name); } - $columns = array('keyword' => array('type' => 'string', - 'length' => 200, - 'primary' => true, - ), - 'field' => array('type' => 'string', - 'length' => 50, - 'primary' => true), - 'position' => array('type' => 'integer', - 'length' => 8, - 'primary' => true, - )); + $columns = array('keyword' => array('type' => 'string', + 'length' => 200, + 'primary' => true, + ), + 'field' => array('type' => 'string', + 'length' => 50, + 'primary' => true), + 'position' => array('type' => 'integer', + 'length' => 8, + 'primary' => true, + )); $this->hasColumns($columns); $this->hasColumns($previousIdentifier); diff --git a/lib/Doctrine/Search/Analyzer.php b/lib/Doctrine/Search/Analyzer.php index 75b1aed05..cbb7ef0e8 100644 --- a/lib/Doctrine/Search/Analyzer.php +++ b/lib/Doctrine/Search/Analyzer.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Search_Analyzer + * Doctrine_Search_Analyzer. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Analyzer implements Doctrine_Search_Analyzer_Interface @@ -43,4 +43,4 @@ public function analyze($text, $encoding = null) { return $text; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Analyzer/Exception.php b/lib/Doctrine/Search/Analyzer/Exception.php index 87fad8677..7052ae3ac 100644 --- a/lib/Doctrine/Search/Analyzer/Exception.php +++ b/lib/Doctrine/Search/Analyzer/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Search_Analyzer_Exception + * Doctrine_Search_Analyzer_Exception. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Analyzer_Exception extends Doctrine_Search_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Search/Analyzer/Interface.php b/lib/Doctrine/Search/Analyzer/Interface.php index 4722ce713..41c2cea1c 100644 --- a/lib/Doctrine/Search/Analyzer/Interface.php +++ b/lib/Doctrine/Search/Analyzer/Interface.php @@ -20,17 +20,17 @@ */ /** - * Doctrine_Search_Analyzer_Interface + * Doctrine_Search_Analyzer_Interface. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ interface Doctrine_Search_Analyzer_Interface { public function analyze($text); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Analyzer/Standard.php b/lib/Doctrine/Search/Analyzer/Standard.php index 0773eacb2..890dbd623 100644 --- a/lib/Doctrine/Search/Analyzer/Standard.php +++ b/lib/Doctrine/Search/Analyzer/Standard.php @@ -20,246 +20,246 @@ */ /** - * Doctrine_Search_Analyzer_Standard + * Doctrine_Search_Analyzer_Standard. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Analyzer_Standard extends Doctrine_Search_Analyzer implements Doctrine_Search_Analyzer_Interface { protected static $_stopwords = array( - // Ticket #1787. Fixed searchable behavior numeric evaluation - // Removed the numeric 0-9 from here - 'a', - 'about', - 'after', - 'all', - 'almost', - 'along', - 'also', - 'although', - 'amp', - 'an', - 'and', - 'another', - 'any', - 'are', - 'area', - 'arent', - 'around', - 'as', - 'at', - 'available', - 'back', - 'be', - 'because', - 'been', - 'before', - 'being', - 'best', - 'better', - 'big', - 'bit', - 'both', - 'but', - 'by', - 'c', - 'came', - 'can', - 'capable', - 'control', - 'could', - 'course', - 'd', - 'dan', - 'day', - 'decided', - 'did', - 'didn', - 'different', - 'div', - 'do', - 'doesn', - 'don', - 'down', - 'drive', - 'e', - 'each', - 'easily', - 'easy', - 'edition', - 'either', - 'end', - 'enough', - 'even', - 'every', - 'example', - 'few', - 'find', - 'first', - 'for', - 'found', - 'from', - 'get', - 'go', - 'going', - 'good', - 'got', - 'gt', - 'had', - 'hard', - 'has', - 'have', - 'he', - 'her', - 'here', - 'how', - 'i', - 'if', - 'in', - 'into', - 'is', - 'isn', - 'it', - 'just', - 'know', - 'last', - 'left', - 'li', - 'like', - 'little', - 'll', - 'long', - 'look', - 'lot', - 'lt', - 'm', - 'made', - 'make', - 'many', - 'mb', - 'me', - 'menu', - 'might', - 'mm', - 'more', - 'most', - 'much', - 'my', - 'name', - 'nbsp', - 'need', - 'new', - 'no', - 'not', - 'now', - 'number', - 'of', - 'off', - 'old', - 'on', - 'one', - 'only', - 'or', - 'original', - 'other', - 'our', - 'out', - 'over', - 'part', - 'place', - 'point', - 'pretty', - 'probably', - 'problem', - 'put', - 'quite', - 'quot', - 'r', - 're', - 'really', - 'results', - 'right', - 's', - 'same', - 'saw', - 'see', - 'set', - 'several', - 'she', - 'sherree', - 'should', - 'since', - 'size', - 'small', - 'so', - 'some', - 'something', - 'special', - 'still', - 'stuff', - 'such', - 'sure', - 'system', - 't', - 'take', - 'than', - 'that', - 'the', - 'their', - 'them', - 'then', - 'there', - 'these', - 'they', - 'thing', - 'things', - 'think', - 'this', - 'those', - 'though', - 'through', - 'time', - 'to', - 'today', - 'together', - 'too', - 'took', - 'two', - 'up', - 'us', - 'use', - 'used', - 'using', - 've', - 'very', - 'want', - 'was', - 'way', - 'we', - 'well', - 'went', - 'were', - 'what', - 'when', - 'where', - 'which', - 'while', - 'white', - 'who', - 'will', - 'with', - 'would', - 'yet', - 'you', - 'your', - 'yours' - ); + // Ticket #1787. Fixed searchable behavior numeric evaluation + // Removed the numeric 0-9 from here + 'a', + 'about', + 'after', + 'all', + 'almost', + 'along', + 'also', + 'although', + 'amp', + 'an', + 'and', + 'another', + 'any', + 'are', + 'area', + 'arent', + 'around', + 'as', + 'at', + 'available', + 'back', + 'be', + 'because', + 'been', + 'before', + 'being', + 'best', + 'better', + 'big', + 'bit', + 'both', + 'but', + 'by', + 'c', + 'came', + 'can', + 'capable', + 'control', + 'could', + 'course', + 'd', + 'dan', + 'day', + 'decided', + 'did', + 'didn', + 'different', + 'div', + 'do', + 'doesn', + 'don', + 'down', + 'drive', + 'e', + 'each', + 'easily', + 'easy', + 'edition', + 'either', + 'end', + 'enough', + 'even', + 'every', + 'example', + 'few', + 'find', + 'first', + 'for', + 'found', + 'from', + 'get', + 'go', + 'going', + 'good', + 'got', + 'gt', + 'had', + 'hard', + 'has', + 'have', + 'he', + 'her', + 'here', + 'how', + 'i', + 'if', + 'in', + 'into', + 'is', + 'isn', + 'it', + 'just', + 'know', + 'last', + 'left', + 'li', + 'like', + 'little', + 'll', + 'long', + 'look', + 'lot', + 'lt', + 'm', + 'made', + 'make', + 'many', + 'mb', + 'me', + 'menu', + 'might', + 'mm', + 'more', + 'most', + 'much', + 'my', + 'name', + 'nbsp', + 'need', + 'new', + 'no', + 'not', + 'now', + 'number', + 'of', + 'off', + 'old', + 'on', + 'one', + 'only', + 'or', + 'original', + 'other', + 'our', + 'out', + 'over', + 'part', + 'place', + 'point', + 'pretty', + 'probably', + 'problem', + 'put', + 'quite', + 'quot', + 'r', + 're', + 'really', + 'results', + 'right', + 's', + 'same', + 'saw', + 'see', + 'set', + 'several', + 'she', + 'sherree', + 'should', + 'since', + 'size', + 'small', + 'so', + 'some', + 'something', + 'special', + 'still', + 'stuff', + 'such', + 'sure', + 'system', + 't', + 'take', + 'than', + 'that', + 'the', + 'their', + 'them', + 'then', + 'there', + 'these', + 'they', + 'thing', + 'things', + 'think', + 'this', + 'those', + 'though', + 'through', + 'time', + 'to', + 'today', + 'together', + 'too', + 'took', + 'two', + 'up', + 'us', + 'use', + 'used', + 'using', + 've', + 'very', + 'want', + 'was', + 'way', + 'we', + 'well', + 'went', + 'were', + 'what', + 'when', + 'where', + 'which', + 'while', + 'white', + 'who', + 'will', + 'with', + 'would', + 'yet', + 'you', + 'your', + 'yours', + ); public function analyze($text, $encoding = null) { @@ -269,9 +269,9 @@ public function analyze($text, $encoding = null) $text = str_replace(' ', ' ', $text); $terms = explode(' ', $text); - + $ret = array(); - if ( ! empty($terms)) { + if (!empty($terms)) { foreach ($terms as $i => $term) { if (empty($term)) { continue; @@ -285,6 +285,7 @@ public function analyze($text, $encoding = null) $ret[$i] = $lower; } } + return $ret; } } diff --git a/lib/Doctrine/Search/Analyzer/Utf8.php b/lib/Doctrine/Search/Analyzer/Utf8.php index 88edd1216..d6f26634e 100644 --- a/lib/Doctrine/Search/Analyzer/Utf8.php +++ b/lib/Doctrine/Search/Analyzer/Utf8.php @@ -20,17 +20,17 @@ */ /** - * Doctrine_Search_Analyzer_Utf8 + * Doctrine_Search_Analyzer_Utf8. * - * This class is used to analyze (ie tokenize) an input $text in + * This class is used to analyze (ie tokenize) an input $text in * $encoding encoding, and return an array of words to be indexed. * - * @package Doctrine - * @subpackage Search * @author Brice Figureau * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Analyzer_Utf8 extends Doctrine_Search_Analyzer_Standard @@ -38,11 +38,11 @@ class Doctrine_Search_Analyzer_Utf8 extends Doctrine_Search_Analyzer_Standard public function analyze($text, $encoding = null) { if (is_null($encoding)) { - $encoding = isset($this->_options['encoding']) ? $this->_options['encoding']:'utf-8'; + $encoding = isset($this->_options['encoding']) ? $this->_options['encoding'] : 'utf-8'; } // check that $text encoding is utf-8, if not convert it - if (strcasecmp($encoding, 'utf-8') != 0 && strcasecmp($encoding, 'utf8') != 0) { + if (0 != strcasecmp($encoding, 'utf-8') && 0 != strcasecmp($encoding, 'utf8')) { $text = iconv($encoding, 'UTF-8', $text); } @@ -50,9 +50,9 @@ public function analyze($text, $encoding = null) $text = str_replace(' ', ' ', $text); $terms = explode(' ', $text); - + $ret = array(); - if ( ! empty($terms)) { + if (!empty($terms)) { foreach ($terms as $i => $term) { if (empty($term)) { continue; @@ -66,6 +66,7 @@ public function analyze($text, $encoding = null) $ret[$i] = $lower; } } + return $ret; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Exception.php b/lib/Doctrine/Search/Exception.php index 4018a960e..5ed34ae14 100644 --- a/lib/Doctrine/Search/Exception.php +++ b/lib/Doctrine/Search/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Search_Exception + * Doctrine_Search_Exception. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Search/File.php b/lib/Doctrine/Search/File.php index feff520f4..a86d3266e 100644 --- a/lib/Doctrine/Search/File.php +++ b/lib/Doctrine/Search/File.php @@ -20,28 +20,28 @@ */ /** - * Doctrine_Search + * Doctrine_Search. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_File extends Doctrine_Search { /** - * constructor + * constructor. * - * @param array $options an array of plugin options + * @param array $options an array of plugin options */ public function __construct(array $options = array()) { parent::__construct($options); - if ( ! isset($this->_options['resource'])) { + if (!isset($this->_options['resource'])) { $conn = Doctrine_Manager::connection(); $tableClass = $conn->getAttribute(Doctrine_Core::ATTR_TABLE_CLASS); $table = new $tableClass('File', $conn); @@ -58,22 +58,20 @@ public function __construct(array $options = array()) public function buildRelation() { - } /** - * indexes given directory + * indexes given directory. * - * @param string $dir the name of the directory to index - * @return void + * @param string $dir the name of the directory to index */ public function indexDirectory($dir) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), - RecursiveIteratorIterator::LEAVES_ONLY); - + RecursiveIteratorIterator::LEAVES_ONLY); + foreach ($it as $file) { - if (strpos($file, DIRECTORY_SEPARATOR . '.svn') !== false) { + if (false !== strpos($file, DIRECTORY_SEPARATOR.'.svn')) { continue; } @@ -82,7 +80,7 @@ public function indexDirectory($dir) } $this->updateIndex(array('url' => $file->getPathName(), - 'content' => file_get_contents($file))); + 'content' => file_get_contents($file))); } } } diff --git a/lib/Doctrine/Search/Indexer.php b/lib/Doctrine/Search/Indexer.php index 2fe82298d..52d300028 100644 --- a/lib/Doctrine/Search/Indexer.php +++ b/lib/Doctrine/Search/Indexer.php @@ -20,22 +20,22 @@ */ /** - * Doctrine_Search_Indexer + * Doctrine_Search_Indexer. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Indexer { public function indexDirectory($dir) { - if ( ! file_exists($dir)) { - throw new Doctrine_Search_Indexer_Exception('Unknown directory ' . $dir); + if (!file_exists($dir)) { + throw new Doctrine_Search_Indexer_Exception('Unknown directory '.$dir); } $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY); @@ -43,7 +43,7 @@ public function indexDirectory($dir) $files = array(); foreach ($it as $file) { $name = $file->getPathName(); - if (strpos($name, '.svn') === false) { + if (false === strpos($name, '.svn')) { $files[] = $name; } } @@ -51,21 +51,23 @@ public function indexDirectory($dir) $q = Doctrine_Core::getTable('Doctrine_File') ->createQuery('f') ->delete() - ->where('f.url LIKE ?', array($dir . '%')) - ->execute(); + ->where('f.url LIKE ?', array($dir.'%')) + ->execute() + ; // clear the index $q = Doctrine_Core::getTable('Doctrine_File_Index') ->createQuery('i') ->where('i.file_id = ?') - ->execute(); + ->execute() + ; $coll = Doctrine_Collection::create('Doctrine_File'); foreach ($files as $file) { $coll[]->url = $file; } - + $coll->save(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Indexer/Dir.php b/lib/Doctrine/Search/Indexer/Dir.php index 63df7d640..f52755b8e 100644 --- a/lib/Doctrine/Search/Indexer/Dir.php +++ b/lib/Doctrine/Search/Indexer/Dir.php @@ -20,28 +20,28 @@ */ /** - * Doctrine_Search_Indexer_Dir + * Doctrine_Search_Indexer_Dir. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Indexer_Dir { public function add($dir) { - if ( ! file_exists($dir)) { - throw new Doctrine_Search_Indexer_Exception('Unknown directory ' . $dir); + if (!file_exists($dir)) { + throw new Doctrine_Search_Indexer_Exception('Unknown directory '.$dir); } $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY); - + foreach ($it as $file) { $this->indexFile($file); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Indexer/Exception.php b/lib/Doctrine/Search/Indexer/Exception.php index f94d96657..4fb8f4f9c 100644 --- a/lib/Doctrine/Search/Indexer/Exception.php +++ b/lib/Doctrine/Search/Indexer/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_Search_Indexer + * Doctrine_Search_Indexer. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Indexer_Exception extends Doctrine_Search_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Search/Listener.php b/lib/Doctrine/Search/Listener.php index d0ee73d48..e5dfc3c69 100644 --- a/lib/Doctrine/Search/Listener.php +++ b/lib/Doctrine/Search/Listener.php @@ -20,17 +20,17 @@ */ /** - * Doctrine_Search_Listener + * Doctrine_Search_Listener. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ -class Doctrine_Search_Listener extends Doctrine_Record_Listener +class Doctrine_Search_Listener extends Doctrine_Record_Listener { protected $_search; @@ -45,15 +45,15 @@ public function preUpdate(Doctrine_Event $event) public function postUpdate(Doctrine_Event $event) { - $record = $event->getInvoker(); + $record = $event->getInvoker(); - $this->_search->updateIndex($record->toArray()); + $this->_search->updateIndex($record->toArray()); } public function postInsert(Doctrine_Event $event) { $record = $event->getInvoker(); - + $this->_search->updateIndex($record->toArray()); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Parser.php b/lib/Doctrine/Search/Parser.php index e9f39bd22..aa7fc9276 100644 --- a/lib/Doctrine/Search/Parser.php +++ b/lib/Doctrine/Search/Parser.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Search_Parser_Standard + * Doctrine_Search_Parser_Standard. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Parser @@ -35,7 +35,7 @@ class Doctrine_Search_Parser public function parse($file) { $contents = file_get_contents($file); - + return array('url' => $file, 'contents' => $contents); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Query.php b/lib/Doctrine/Search/Query.php index 81af580d8..eef9fbb6e 100644 --- a/lib/Doctrine/Search/Query.php +++ b/lib/Doctrine/Search/Query.php @@ -20,43 +20,39 @@ */ /** - * Doctrine_Search_Query + * Doctrine_Search_Query. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Query { - /** - * @var Doctrine_Table $_table the index table + * @var Doctrine_Table the index table */ protected $_table = array(); - + protected $_sql = ''; - + protected $_params = array(); - + protected $_words = array(); - + protected $_tokenizer; protected $_condition; - /** - * @param Doctrine_Table $_table the index table - */ public function __construct($table) { if (is_string($table)) { - $table = Doctrine_Core::getTable($table); + $table = Doctrine_Core::getTable($table); } else { - if ( ! $table instanceof Doctrine_Table) { + if (!$table instanceof Doctrine_Table) { throw new Doctrine_Search_Exception('Invalid argument type. Expected instance of Doctrine_Table.'); } } @@ -66,10 +62,9 @@ public function __construct($table) $foreignId = current(array_diff($this->_table->getColumnNames(), array('keyword', 'field', 'position'))); - $this->_condition = $foreignId . ' %s (SELECT ' . $foreignId . ' FROM ' . $this->_table->getTableName() . ' WHERE '; + $this->_condition = $foreignId.' %s (SELECT '.$foreignId.' FROM '.$this->_table->getTableName().' WHERE '; } - public function query($text, $includeRelevance = true) { $text = trim($text); @@ -77,40 +72,40 @@ public function query($text, $includeRelevance = true) $foreignId = current(array_diff($this->_table->getColumnNames(), array('keyword', 'field', 'position'))); $weighted = false; - if (strpos($text, '^') === false) { + if (false === strpos($text, '^')) { if ($includeRelevance) { - $select = 'SELECT COUNT(keyword) AS relevance, ' . $foreignId; + $select = 'SELECT COUNT(keyword) AS relevance, '.$foreignId; } else { - $select = 'SELECT ' . $foreignId; + $select = 'SELECT '.$foreignId; } } else { if ($includeRelevance) { - $select = 'SELECT SUM(sub_relevance) AS relevance, ' . $foreignId; + $select = 'SELECT SUM(sub_relevance) AS relevance, '.$foreignId; } else { - $select = 'SELECT ' . $foreignId; + $select = 'SELECT '.$foreignId; } } - - $from = 'FROM ' . $this->_table->getTableName(); + + $from = 'FROM '.$this->_table->getTableName(); $where = 'WHERE '; $where .= $this->parseClause($text); - $groupby = 'GROUP BY ' . $foreignId; + $groupby = 'GROUP BY '.$foreignId; if ($includeRelevance) { $orderBy = 'ORDER BY relevance DESC'; } else { $orderBy = null; } - $this->_sql = $select . ' ' . $from . ' ' . $where . ' ' . $groupby; - if (isset($orderBy) && $orderBy !== null) { - $this->_sql .= ' ' . $orderBy; + $this->_sql = $select.' '.$from.' '.$where.' '.$groupby; + if (isset($orderBy) && null !== $orderBy) { + $this->_sql .= ' '.$orderBy; } } public function parseClause($originalClause, $recursive = false) { $clause = $this->_tokenizer->bracketTrim($originalClause); - + $brackets = false; if ($clause !== $originalClause) { @@ -118,7 +113,7 @@ public function parseClause($originalClause, $recursive = false) } $foreignId = current(array_diff($this->_table->getColumnNames(), array('keyword', 'field', 'position'))); - + $terms = $this->_tokenizer->sqlExplode($clause, ' OR ', '(', ')'); $ret = array(); @@ -138,33 +133,33 @@ public function parseClause($originalClause, $recursive = false) $return = implode(' OR ', $ret); if ($leavesOnly && $recursive) { - $return = sprintf($this->_condition, 'IN') . $return . ')'; + $return = sprintf($this->_condition, 'IN').$return.')'; $brackets = false; } } else { $terms = $this->_tokenizer->sqlExplode($clause, ' ', '(', ')'); - - if (count($terms) === 1 && ! $recursive) { + + if (1 === count($terms) && !$recursive) { $return = $this->parseTerm($clause); } else { foreach ($terms as $k => $term) { $term = trim($term); - - if ($term === 'AND') { + + if ('AND' === $term) { continue; } - - if (substr($term, 0, 1) === '-') { + + if ('-' === substr($term, 0, 1)) { $operator = 'NOT IN'; $term = substr($term, 1); } else { $operator = 'IN'; } - + if ($this->isExpression($term)) { $ret[$k] = $this->parseClause($term, true); } else { - $ret[$k] = sprintf($this->_condition, $operator) . $this->parseTerm($term) . ')'; + $ret[$k] = sprintf($this->_condition, $operator).$this->parseTerm($term).')'; } } $return = implode(' AND ', $ret); @@ -172,28 +167,27 @@ public function parseClause($originalClause, $recursive = false) } if ($brackets) { - return '(' . $return . ')'; - } else { - return $return; + return '('.$return.')'; } + + return $return; } public function isExpression($term) { - if (strpos($term, '(') !== false) { + if (false !== strpos($term, '(')) { return true; - } else { - $terms = $this->_tokenizer->quoteExplode($term); - - return (count($terms) > 1); } + $terms = $this->_tokenizer->quoteExplode($term); + + return count($terms) > 1; } public function parseTerm($term) { $negation = false; - if (strpos($term, "'") === false) { + if (false === strpos($term, "'")) { $where = $this->parseWord($term); } else { $term = trim($term, "' "); @@ -202,12 +196,13 @@ public function parseTerm($term) $where = $this->parseWord($terms[0]); foreach ($terms as $k => $word) { - if ($k === 0) { + if (0 === $k) { continue; } - $where .= ' AND (position + ' . $k . ') IN (SELECT position FROM ' . $this->_table->getTableName() . ' WHERE ' . $this->parseWord($word) . ')'; + $where .= ' AND (position + '.$k.') IN (SELECT position FROM '.$this->_table->getTableName().' WHERE '.$this->parseWord($word).')'; } } + return $where; } @@ -215,9 +210,8 @@ public function parseWord($word) { $this->_words[] = str_replace('*', '', $word); - if (strpos($word, '?') !== false || - strpos($word, '*') !== false) { - + if (false !== strpos($word, '?') + || false !== strpos($word, '*')) { $word = str_replace('*', '%', $word); $where = 'keyword LIKE ?'; @@ -246,4 +240,4 @@ public function getSqlQuery() { return $this->_sql; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Search/Record.php b/lib/Doctrine/Search/Record.php index 3dc4f9b91..bf2913a67 100644 --- a/lib/Doctrine/Search/Record.php +++ b/lib/Doctrine/Search/Record.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Search_Record + * Doctrine_Search_Record. * - * @package Doctrine - * @subpackage Search * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Search_Record extends Doctrine_Template @@ -37,7 +37,7 @@ public function setTableDefinition() $this->hasColumn('keyword', 'string', 250, array('notnull' => true)); $this->hasColumn('field', 'string', 50, array('notnull' => true)); $this->hasColumn('position', 'integer', 8); - // depending on the identifiers of the owner record this record + // depending on the identifiers of the owner record this record // has also one to many foreign key columns } @@ -45,4 +45,4 @@ public function setUp() { $this->hasOne('[Component]', array('onDelete' => 'CASCADE')); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence.php b/lib/Doctrine/Sequence.php index 76ee236c6..0779b4552 100644 --- a/lib/Doctrine/Sequence.php +++ b/lib/Doctrine/Sequence.php @@ -23,23 +23,24 @@ * Doctrine_Sequence * The base class for sequence handling drivers. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence extends Doctrine_Connection_Module { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence + * * @throws Doctrine_Sequence_Exception */ public function nextId($seqName, $ondemand = true) @@ -49,10 +50,12 @@ public function nextId($seqName, $ondemand = true) /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted + * @param mixed|null $table + * @param mixed|null $field */ public function lastInsertId($table = null, $field = null) { @@ -60,16 +63,17 @@ public function lastInsertId($table = null, $field = null) } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $this->warnings[] = 'database does not support getting current sequence value, the sequence value was incremented'; + return $this->nextId($seqName); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Db2.php b/lib/Doctrine/Sequence/Db2.php index dc6bfe104..877ad5050 100644 --- a/lib/Doctrine/Sequence/Db2.php +++ b/lib/Doctrine/Sequence/Db2.php @@ -20,73 +20,76 @@ */ /** - * Doctrine_Sequence_Db2 + * Doctrine_Sequence_Db2. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Db2 extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence + * * @throws Doctrine_Sequence_Exception */ public function nextId($seqName, $ondemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = 'SELECT NEXTVAL FOR ' . $sequenceName . ' AS VAL FROM SYSIBM.SYSDUMMY1'; - + $query = 'SELECT NEXTVAL FOR '.$sequenceName.' AS VAL FROM SYSIBM.SYSDUMMY1'; + try { $result = $this->conn->fetchOne($query); - $result = ($result) ? $result['VAL'] : null; - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + $result = ($result) ? $result['VAL'] : null; + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { try { $result = $this->conn->export->createSequence($seqName); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } - + return $this->nextId($seqName, false); - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } + return $result; } - + /** * Return the most recent value from the specified sequence in the database. * This is supported only on RDBMS brands that support sequences * (e.g. Oracle, PostgreSQL, DB2). Other RDBMS brands return null. * * @param string $sequenceName - * @return integer + * + * @return int + * * @throws Doctrine_Adapter_Db2_Exception */ public function currId($sequenceName) { $sql = 'SELECT PREVVAL FOR ' - . $this->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName)) - . ' AS VAL FROM SYSIBM.SYSDUMMY1'; + .$this->quoteIdentifier($this->conn->formatter->getSequenceName($sequenceName)) + .' AS VAL FROM SYSIBM.SYSDUMMY1'; - $stmt = $this->query($sql); + $stmt = $this->query($sql); $result = $stmt->fetchAll(Doctrine_Core::FETCH_ASSOC); if ($result) { return $result[0]['VAL']; - } else { - return null; } + + return null; } /** @@ -102,21 +105,24 @@ public function currId($sequenceName) * The IDENTITY_VAL_LOCAL() function gives the last generated identity value * in the current process, even if it was for a GENERATED column. * - * @param string $tableName OPTIONAL + * @param string $tableName OPTIONAL * @param string $primaryKey OPTIONAL - * @return integer + * + * @return int + * * @throws Doctrine_Adapter_Db2_Exception */ public function lastInsertId($tableName = null, $primaryKey = null) { $this->_connect(); - if ($tableName !== null) { + if (null !== $tableName) { $sequenceName = $tableName; if ($primaryKey) { - $sequenceName .= "_$primaryKey"; + $sequenceName .= "_{$primaryKey}"; } $sequenceName .= '_seq'; + return $this->lastSequenceId($sequenceName); } @@ -125,8 +131,8 @@ public function lastInsertId($tableName = null, $primaryKey = null) $result = $stmt->fetchAll(Doctrine_Core::FETCH_ASSOC); if ($result) { return $result[0]['VAL']; - } else { - return null; } + + return null; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Exception.php b/lib/Doctrine/Sequence/Exception.php index 9476b1f81..1e088ebf9 100644 --- a/lib/Doctrine/Sequence/Exception.php +++ b/lib/Doctrine/Sequence/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Sequence_Exception + * Doctrine_Sequence_Exception. * - * @package Doctrine - * @subpackage Sequence * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Sequence_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Sequence/Mssql.php b/lib/Doctrine/Sequence/Mssql.php index fff760886..07663b1e7 100644 --- a/lib/Doctrine/Sequence/Mssql.php +++ b/lib/Doctrine/Sequence/Mssql.php @@ -20,14 +20,14 @@ */ /** - * Doctrine_Sequence_Mssql + * Doctrine_Sequence_Mssql. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Mssql extends Doctrine_Sequence @@ -35,40 +35,39 @@ class Doctrine_Sequence_Mssql extends Doctrine_Sequence protected $warnings; /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextId($seqName, $onDemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); if ($this->checkSequence($sequenceName)) { - $query = 'SET IDENTITY_INSERT ' . $sequenceName . ' OFF ' - . 'INSERT INTO ' . $sequenceName . ' DEFAULT VALUES'; + $query = 'SET IDENTITY_INSERT '.$sequenceName.' OFF ' + .'INSERT INTO '.$sequenceName.' DEFAULT VALUES'; } else { - $query = 'INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (0)'; + $query = 'INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES (0)'; } - + try { $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { // Since we are creating the sequence on demand // we know the first id = 1 so initialize the // sequence at 2 try { $result = $this->conn->export->createSequence($seqName, 2); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } - - /** + + /* * This could actually be a table that starts at 18.. oh well.. * we will keep the fallback to return 1 in case we skip this.. which * should really not happen.. otherwise the returned values is biased. @@ -76,68 +75,66 @@ public function nextId($seqName, $onDemand = true) if ($this->checkSequence($seqName)) { return $this->lastInsertId($seqName); } - + return 1; } - + throw $e; } - + $value = $this->lastInsertId($sequenceName); if (is_numeric($value)) { - $query = 'DELETE FROM ' . $sequenceName . ' WHERE ' . $seqcolName . ' < ' . $value; - + $query = 'DELETE FROM '.$sequenceName.' WHERE '.$seqcolName.' < '.$value; + try { $this->conn->exec($query); } catch (Doctrine_Connection_Exception $e) { - throw new Doctrine_Sequence_Exception( - 'Could not delete previous sequence from ' . - $sequenceName . ' at ' . __FILE__ . ' in ' . - __FUNCTION__ . ' with the message: ' . $e->getMessage() - ); + throw new Doctrine_Sequence_Exception('Could not delete previous sequence from '.$sequenceName.' at '.__FILE__.' in '.__FUNCTION__.' with the message: '.$e->getMessage()); } } + return $value; } /** * Checks if there's a sequence that exists. * - * @param string $seqName The sequence name to verify. - * @return bool $tableExists The value if the table exists or not - * @access private + * @param string $seqName the sequence name to verify + * + * @return bool $tableExists The value if the table exists or not */ public function checkSequence($seqName) { - $query = 'SELECT COUNT(1) FROM ' . $seqName; + $query = 'SELECT COUNT(1) FROM '.$seqName; try { $this->conn->execute($query); } catch (Doctrine_Connection_Exception $e) { - if ($e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + if (Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { return false; } } + return true; } /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted + * @param mixed|null $table + * @param mixed|null $field */ public function lastInsertId($table = null, $field = null) { $serverInfo = $this->conn->getServerVersion(); if (is_array($serverInfo) - && ! is_null($serverInfo['major']) + && !is_null($serverInfo['major']) && $serverInfo['major'] >= 8) { - - if (isset($table)) - { - $query = 'SELECT IDENT_CURRENT(\'' . $this->conn->quoteIdentifier($table) . '\')'; + if (isset($table)) { + $query = 'SELECT IDENT_CURRENT(\''.$this->conn->quoteIdentifier($table).'\')'; } else { $query = 'SELECT SCOPE_IDENTITY()'; } @@ -149,16 +146,17 @@ public function lastInsertId($table = null, $field = null) } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $this->warnings[] = 'database does not support getting current sequence value, the sequence value was incremented'; + return $this->nextId($seqName); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Mysql.php b/lib/Doctrine/Sequence/Mysql.php index 03b5f0a9f..320c50fe9 100644 --- a/lib/Doctrine/Sequence/Mysql.php +++ b/lib/Doctrine/Sequence/Mysql.php @@ -20,69 +20,71 @@ */ /** - * Doctrine_Sequence_Mysql + * Doctrine_Sequence_Mysql. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Mysql extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextId($seqName, $onDemand = true) { - $sequenceName = $this->conn->quoteIdentifier($seqName, true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (NULL)'; - + $sequenceName = $this->conn->quoteIdentifier($seqName, true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $query = 'INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES (NULL)'; + try { $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { // Since we are creating the sequence on demand // we know the first id = 1 so initialize the // sequence at 2 try { $result = $this->conn->export->createSequence($seqName, 2); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } // First ID of a newly created sequence is 1 return 1; - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } $value = $this->lastInsertId(); if (is_numeric($value)) { - $query = 'DELETE FROM ' . $sequenceName . ' WHERE ' . $seqcolName . ' < ' . $value; + $query = 'DELETE FROM '.$sequenceName.' WHERE '.$seqcolName.' < '.$value; $this->conn->exec($query); } - + return $value; } /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted - * @return integer|boolean + * @param mixed|null $table + * @param mixed|null $field + * + * @return int|bool */ public function lastInsertId($table = null, $field = null) { @@ -90,18 +92,18 @@ public function lastInsertId($table = null, $field = null) } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { - $sequenceName = $this->conn->quoteIdentifier($seqName, true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'SELECT MAX(' . $seqcolName . ') FROM ' . $sequenceName; + $sequenceName = $this->conn->quoteIdentifier($seqName, true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $query = 'SELECT MAX('.$seqcolName.') FROM '.$sequenceName; return (int) $this->conn->fetchOne($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Oracle.php b/lib/Doctrine/Sequence/Oracle.php index 6a8fa6452..76b571dec 100644 --- a/lib/Doctrine/Sequence/Oracle.php +++ b/lib/Doctrine/Sequence/Oracle.php @@ -20,45 +20,44 @@ */ /** - * Doctrine_Sequence_Oracle + * Doctrine_Sequence_Oracle. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Oracle extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool onDemand when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextID($seqName, $onDemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = 'SELECT ' . $sequenceName . '.nextval FROM DUAL'; + $query = 'SELECT '.$sequenceName.'.nextval FROM DUAL'; try { $result = $this->conn->fetchOne($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { try { $result = $this->conn->export->createSequence($seqName); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } return $this->nextId($seqName, false); - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } return $result; @@ -66,32 +65,34 @@ public function nextID($seqName, $onDemand = true) /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted + * @param mixed|null $table + * @param mixed|null $field */ public function lastInsertID($table = null, $field = null) { - $seqName = $table . (empty($field) ? '' : '_'.$field); - $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); + $seqName = $table.(empty($field) ? '' : '_'.$field); + $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - return $this->conn->fetchOne('SELECT ' . $sequenceName . '.currval FROM DUAL'); + return $this->conn->fetchOne('SELECT '.$sequenceName.'.currval FROM DUAL'); } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = 'SELECT (last_number-1) FROM user_sequences'; - $query .= ' WHERE sequence_name=' . $this->conn->quote($sequenceName, 'text'); - $query .= ' OR sequence_name=' . $this->conn->quote(strtoupper($sequenceName), 'text'); + $query = 'SELECT (last_number-1) FROM user_sequences'; + $query .= ' WHERE sequence_name='.$this->conn->quote($sequenceName, 'text'); + $query .= ' OR sequence_name='.$this->conn->quote(strtoupper($sequenceName), 'text'); return $this->conn->fetchOne($query); } diff --git a/lib/Doctrine/Sequence/Pgsql.php b/lib/Doctrine/Sequence/Pgsql.php index 2fbb5d586..ffd932c84 100644 --- a/lib/Doctrine/Sequence/Pgsql.php +++ b/lib/Doctrine/Sequence/Pgsql.php @@ -20,78 +20,81 @@ */ /** - * Doctrine_Sequence_Pgsql + * Doctrine_Sequence_Pgsql. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Pgsql extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * @param bool onDemand when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextId($seqName, $onDemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $query = "SELECT NEXTVAL('" . $sequenceName . "')"; + $query = "SELECT NEXTVAL('".$sequenceName."')"; try { $result = (int) $this->conn->fetchOne($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { try { $result = $this->conn->export->createSequence($seqName); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } return $this->nextId($seqName, false); - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } return $result; } /** - * lastInsertId + * lastInsertId. * * Returns the autoincrement ID if supported or $id or fetches the current * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted - * @return integer the autoincremented id + * @param mixed|null $table + * @param mixed|null $field + * + * @return int the autoincremented id */ public function lastInsertId($table = null, $field = null) { - $seqName = $table . (empty($field) ? '' : '_' . $field); + $seqName = $table.(empty($field) ? '' : '_'.$field); $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - return (int) $this->conn->fetchOne("SELECT CURRVAL('" . $sequenceName . "')"); + return (int) $this->conn->fetchOne("SELECT CURRVAL('".$sequenceName."')"); } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - return (int) $this->conn->fetchOne('SELECT last_value FROM ' . $sequenceName); + + return (int) $this->conn->fetchOne('SELECT last_value FROM '.$sequenceName); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Sequence/Sqlite.php b/lib/Doctrine/Sequence/Sqlite.php index 04c8cba0b..8800d37b9 100644 --- a/lib/Doctrine/Sequence/Sqlite.php +++ b/lib/Doctrine/Sequence/Sqlite.php @@ -20,68 +20,71 @@ */ /** - * Doctrine_Sequence_Sqlite + * Doctrine_Sequence_Sqlite. * - * @package Doctrine - * @subpackage Sequence * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Sequence_Sqlite extends Doctrine_Sequence { /** - * Returns the next free id of a sequence + * Returns the next free id of a sequence. * - * @param string $seqName name of the sequence - * @param bool $onDemand when true missing sequences are automatic created + * @param string $seqName name of the sequence + * @param bool $onDemand when true missing sequences are automatic created * - * @return integer next id in the given sequence + * @return int next id in the given sequence */ public function nextId($seqName, $onDemand = true) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'INSERT INTO ' . $sequenceName . ' (' . $seqcolName . ') VALUES (NULL)'; + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $query = 'INSERT INTO '.$sequenceName.' ('.$seqcolName.') VALUES (NULL)'; try { $this->conn->exec($query); - } catch(Doctrine_Connection_Exception $e) { - if ($onDemand && $e->getPortableCode() == Doctrine_Core::ERR_NOSUCHTABLE) { + } catch (Doctrine_Connection_Exception $e) { + if ($onDemand && Doctrine_Core::ERR_NOSUCHTABLE == $e->getPortableCode()) { // Since we are creating the sequence on demand // we know the first id = 1 so initialize the // sequence at 2 try { $result = $this->conn->export->createSequence($seqName, 2); - } catch(Doctrine_Exception $e) { - throw new Doctrine_Sequence_Exception('on demand sequence ' . $seqName . ' could not be created'); + } catch (Doctrine_Exception $e) { + throw new Doctrine_Sequence_Exception('on demand sequence '.$seqName.' could not be created'); } + // First ID of a newly created sequence is 1 return 1; - } else { - throw new Doctrine_Sequence_Exception('sequence ' .$seqName . ' does not exist'); } + throw new Doctrine_Sequence_Exception('sequence '.$seqName.' does not exist'); } $value = $this->conn->getDbh()->lastInsertId(); if (is_numeric($value)) { - $query = 'DELETE FROM ' . $sequenceName . ' WHERE ' . $seqcolName . ' < ' . $value; + $query = 'DELETE FROM '.$sequenceName.' WHERE '.$seqcolName.' < '.$value; $this->conn->exec($query); } - + return $value; } /** * Returns the autoincrement ID if supported or $id or fetches the current - * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field) + * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field). * * @param string name of the table into which a new row was inserted * @param string name of the field into which a new row was inserted - * @return integer|boolean + * @param mixed|null $table + * @param mixed|null $field + * + * @return int|bool */ public function lastInsertId($table = null, $field = null) { @@ -89,19 +92,19 @@ public function lastInsertId($table = null, $field = null) } /** - * Returns the current id of a sequence + * Returns the current id of a sequence. * - * @param string $seqName name of the sequence + * @param string $seqName name of the sequence * - * @return integer current id in the given sequence + * @return int current id in the given sequence */ public function currId($seqName) { $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true); - $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); + $seqcolName = $this->conn->quoteIdentifier($this->conn->getAttribute(Doctrine_Core::ATTR_SEQCOL_NAME), true); - $query = 'SELECT MAX(' . $seqcolName . ') FROM ' . $sequenceName; + $query = 'SELECT MAX('.$seqcolName.') FROM '.$sequenceName; return (int) $this->conn->fetchOne($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Table.php b/lib/Doctrine/Table.php index faac80574..251201f35 100644 --- a/lib/Doctrine/Table.php +++ b/lib/Doctrine/Table.php @@ -21,53 +21,53 @@ /** * Doctrine_Table represents a database table - * each Doctrine_Table holds the information of foreignKeys and associations - * + * each Doctrine_Table holds the information of foreignKeys and associations. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Table extends Doctrine_Configurable implements Countable, Serializable { /** - * @var array $data temporary data which is then loaded into Doctrine_Record::$_data + * @var array temporary data which is then loaded into Doctrine_Record::$_data */ - protected $_data = array(); + protected $_data = array(); /** - * @var mixed $identifier The field names of all fields that are part of the identifier/primary key + * @var mixed The field names of all fields that are part of the identifier/primary key */ protected $_identifier = array(); /** * @see Doctrine_Identifier constants - * @var integer $identifierType the type of identifier this table uses + * + * @var int the type of identifier this table uses */ protected $_identifierType; /** - * @var Doctrine_Connection $conn Doctrine_Connection object that created this table + * @var Doctrine_Connection Doctrine_Connection object that created this table */ protected $_conn; /** - * @var array $identityMap first level cache + * @var array first level cache */ - protected $_identityMap = array(); + protected $_identityMap = array(); /** - * @var Doctrine_Table_Repository $repository record repository + * @var Doctrine_Table_Repository record repository */ protected $_repository; /** - * @var array $columns an array of column definitions, - * keys are column names and values are column definitions + * @var array an array of column definitions, + * keys are column names and values are column definitions * * the definition array has atleast the following values: * @@ -80,45 +80,44 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable, Seriali * -- notblank notblank validator + notnull constraint * ... many more */ - protected $_columns = array(); + protected $_columns = array(); /** - * Array of unique sets of fields. These values are validated on save + * Array of unique sets of fields. These values are validated on save. * - * @var array $_uniques + * @var array */ protected $_uniques = array(); /** - * @var array $_fieldNames an array of field names, used to look up field names - * from column names. Keys are column - * names and values are field names. - * Alias for columns are here. + * @var array an array of field names, used to look up field names + * from column names. Keys are column + * names and values are field names. + * Alias for columns are here. */ - protected $_fieldNames = array(); + protected $_fieldNames = array(); /** - * - * @var array $_columnNames an array of column names - * keys are field names and values column names. - * used to look up column names from field names. - * this is the reverse lookup map of $_fieldNames. + * @var array an array of column names + * keys are field names and values column names. + * used to look up column names from field names. + * this is the reverse lookup map of $_fieldNames. */ protected $_columnNames = array(); /** - * @var integer $columnCount cached column count, Doctrine_Record uses this column count in when - * determining its state + * @var int cached column count, Doctrine_Record uses this column count in when + * determining its state */ protected $columnCount; /** - * @var boolean $hasDefaultValues whether or not this table has default values + * @var bool whether or not this table has default values */ protected $hasDefaultValues; /** - * @var array $options an array containing all options + * @var array an array containing all options * * -- name name of the component, for example component name of the GroupTable is 'Group' * @@ -160,83 +159,88 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable, Seriali * * -- versioning */ - protected $_options = array('name' => null, - 'tableName' => null, - 'sequenceName' => null, - 'inheritanceMap' => array(), - 'enumMap' => array(), - 'type' => null, - 'charset' => null, - 'collate' => null, - 'treeImpl' => null, - 'treeOptions' => array(), - 'indexes' => array(), - 'parents' => array(), - 'joinedParents' => array(), - 'queryParts' => array(), - 'versioning' => null, - 'subclasses' => array(), - 'orderBy' => null - ); - - /** - * @var Doctrine_Tree $tree tree object associated with this table + protected $_options = array('name' => null, + 'tableName' => null, + 'sequenceName' => null, + 'inheritanceMap' => array(), + 'enumMap' => array(), + 'type' => null, + 'charset' => null, + 'collate' => null, + 'treeImpl' => null, + 'treeOptions' => array(), + 'indexes' => array(), + 'parents' => array(), + 'joinedParents' => array(), + 'queryParts' => array(), + 'versioning' => null, + 'subclasses' => array(), + 'orderBy' => null, + ); + + /** + * @var Doctrine_Tree tree object associated with this table */ protected $_tree; /** - * @var Doctrine_Relation_Parser $_parser relation parser object + * @var Doctrine_Relation_Parser relation parser object */ protected $_parser; /** * @see Doctrine_Template - * @var array $_templates an array containing all templates attached to this table + * + * @var array an array containing all templates attached to this table */ - protected $_templates = array(); + protected $_templates = array(); /** * @see Doctrine_Record_Filter - * @var array $_filters an array containing all record filters attached to this table + * + * @var array an array containing all record filters attached to this table */ - protected $_filters = array(); + protected $_filters = array(); /** * @see Doctrine_Record_Generator - * @var array $_generators an array containing all generators attached to this table + * + * @var array an array containing all generators attached to this table */ - protected $_generators = array(); + protected $_generators = array(); /** - * Generator instance responsible for constructing this table + * Generator instance responsible for constructing this table. * * @see Doctrine_Record_Generator - * @var Doctrine_Record_Generator $generator + * + * @var Doctrine_Record_Generator */ protected $_generator; /** - * @var array $_invokedMethods method invoker cache + * @var array method invoker cache */ protected $_invokedMethods = array(); /** - * @var boolean $_useIdentityMap Use or not identyMap cache + * @var bool Use or not identyMap cache */ protected $_useIdentityMap = true; /** - * @var Doctrine_Record $record empty instance of the given model + * @var Doctrine_Record empty instance of the given model */ protected $record; /** - * the constructor + * the constructor. + * + * @param string $name the name of the component + * @param Doctrine_Connection $conn the connection associated with this table + * @param bool $initDefinition whether to init the in-memory schema * - * @throws Doctrine_Connection_Exception if there are no opened connections - * @param string $name the name of the component - * @param Doctrine_Connection $conn the connection associated with this table - * @param boolean $initDefinition whether to init the in-memory schema + * @throws Doctrine_Connection_Exception if there are no opened connections */ public function __construct($name, Doctrine_Connection $conn, $initDefinition = false) { @@ -267,12 +271,12 @@ public function __construct($name, Doctrine_Connection $conn, $initDefinition = $this->getTree()->setUp(); } } else { - if ( ! isset($this->_options['tableName'])) { + if (!isset($this->_options['tableName'])) { $this->setTableName(Doctrine_Inflector::tableize($this->_options['name'])); } } - $this->_filters[] = new Doctrine_Record_Filter_Standard(); + $this->_filters[] = new Doctrine_Record_Filter_Standard(); if ($this->getAttribute(Doctrine_Core::ATTR_USE_TABLE_REPOSITORY)) { $this->_repository = new Doctrine_Table_Repository($this); } else { @@ -290,22 +294,19 @@ public function __construct($name, Doctrine_Connection $conn, $initDefinition = * This method provides concrete Table classes with the possibility * to hook into the constructor procedure. It is called after the * Doctrine_Table construction process is finished. - * - * @return void */ public function construct() - { } + { + } /** * Initializes the in-memory table definition. - * - * @param string $name */ public function initDefinition() { $name = $this->_options['name']; - if ( ! class_exists($name) || empty($name)) { - throw new Doctrine_Exception("Couldn't find class " . $name); + if (!class_exists($name) || empty($name)) { + throw new Doctrine_Exception("Couldn't find class ".$name); } $record = new $name($this); @@ -316,7 +317,7 @@ public function initDefinition() // get parent classes do { - if ($class === 'Doctrine_Record') { + if ('Doctrine_Record' === $class) { break; } @@ -324,8 +325,8 @@ public function initDefinition() $names[] = $name; } while ($class = get_parent_class($class)); - if ($class === false) { - throw new Doctrine_Table_Exception('Class "' . $name . '" must be a child class of Doctrine_Record'); + if (false === $class) { + throw new Doctrine_Table_Exception('Class "'.$name.'" must be a child class of Doctrine_Record'); } // reverse names @@ -340,7 +341,6 @@ public function initDefinition() // get the declaring class of setTableDefinition method $method = new ReflectionMethod($this->_options['name'], 'setTableDefinition'); $class = $method->getDeclaringClass(); - } else { $class = new ReflectionClass($class); } @@ -348,13 +348,12 @@ public function initDefinition() $this->_options['joinedParents'] = array(); foreach (array_reverse($this->_options['parents']) as $parent) { - if ($parent === $class->getName()) { continue; } $ref = new ReflectionClass($parent); - if ($ref->isAbstract() || ! $class->isSubclassOf($parent)) { + if ($ref->isAbstract() || !$class->isSubclassOf($parent)) { continue; } $parentTable = $this->_conn->getTable($parent); @@ -363,17 +362,16 @@ public function initDefinition() $parentColumns = $parentTable->getColumns(); foreach ($parentColumns as $columnName => $definition) { - if ( ! isset($definition['primary']) || $definition['primary'] === false) { + if (!isset($definition['primary']) || false === $definition['primary']) { if (isset($this->_columns[$columnName])) { $found = true; break; - } else { - if ( ! isset($parentColumns[$columnName]['owner'])) { - $parentColumns[$columnName]['owner'] = $parentTable->getComponentName(); - } - - $this->_options['joinedParents'][] = $parentColumns[$columnName]['owner']; } + if (!isset($parentColumns[$columnName]['owner'])) { + $parentColumns[$columnName]['owner'] = $parentTable->getComponentName(); + } + + $this->_options['joinedParents'][] = $parentColumns[$columnName]['owner']; } else { unset($parentColumns[$columnName]); } @@ -384,7 +382,7 @@ public function initDefinition() } foreach ($parentColumns as $columnName => $definition) { - $fullName = $columnName . ' as ' . $parentTable->getFieldName($columnName); + $fullName = $columnName.' as '.$parentTable->getFieldName($columnName); $this->setColumn($fullName, $definition['type'], $definition['length'], $definition, true); } @@ -402,7 +400,7 @@ public function initDefinition() $this->columnCount = count($this->_columns); - if ( ! isset($this->_options['tableName'])) { + if (!isset($this->_options['tableName'])) { $this->setTableName(Doctrine_Inflector::tableize($class->getName())); } @@ -415,21 +413,19 @@ public function initDefinition() * Called in the construction process, builds the identifier definition * copying in the schema the list of the fields which constitutes * the primary key. - * - * @return void */ public function initIdentifier() { switch (count($this->_identifier)) { case 0: - if ( ! empty($this->_options['joinedParents'])) { + if (!empty($this->_options['joinedParents'])) { $root = current($this->_options['joinedParents']); $table = $this->_conn->getTable($root); $this->_identifier = $table->getIdentifier(); - $this->_identifierType = ($table->getIdentifierType() !== Doctrine_Core::IDENTIFIER_AUTOINC) + $this->_identifierType = (Doctrine_Core::IDENTIFIER_AUTOINC !== $table->getIdentifierType()) ? $table->getIdentifierType() : Doctrine_Core::IDENTIFIER_NATURAL; // add all inherited primary keys @@ -438,27 +434,26 @@ public function initIdentifier() // inherited primary keys shouldn't contain autoinc // and sequence definitions - unset($definition['autoincrement']); - unset($definition['sequence']); + unset($definition['autoincrement'], $definition['sequence']); // add the inherited primary key column - $fullName = $id . ' as ' . $table->getFieldName($id); + $fullName = $id.' as '.$table->getFieldName($id); $this->setColumn($fullName, $definition['type'], $definition['length'], - $definition, true); + $definition, true); } } else { $identifierOptions = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_IDENTIFIER_OPTIONS); - $name = (isset($identifierOptions['name']) && $identifierOptions['name']) ? $identifierOptions['name']:'id'; + $name = (isset($identifierOptions['name']) && $identifierOptions['name']) ? $identifierOptions['name'] : 'id'; $name = sprintf($name, $this->getTableName()); - $definition = array('type' => (isset($identifierOptions['type']) && $identifierOptions['type']) ? $identifierOptions['type']:'integer', - 'length' => (isset($identifierOptions['length']) && $identifierOptions['length']) ? $identifierOptions['length']:8, - 'autoincrement' => isset($identifierOptions['autoincrement']) ? $identifierOptions['autoincrement']:true, - 'primary' => isset($identifierOptions['primary']) ? $identifierOptions['primary']:true); + $definition = array('type' => (isset($identifierOptions['type']) && $identifierOptions['type']) ? $identifierOptions['type'] : 'integer', + 'length' => (isset($identifierOptions['length']) && $identifierOptions['length']) ? $identifierOptions['length'] : 8, + 'autoincrement' => isset($identifierOptions['autoincrement']) ? $identifierOptions['autoincrement'] : true, + 'primary' => isset($identifierOptions['primary']) ? $identifierOptions['primary'] : true); unset($identifierOptions['name'], $identifierOptions['type'], $identifierOptions['length']); foreach ($identifierOptions as $key => $value) { - if ( ! isset($definition[$key]) || ! $definition[$key]) { + if (!isset($definition[$key]) || !$definition[$key]) { $definition[$key] = $value; } } @@ -467,7 +462,7 @@ public function initIdentifier() $this->_identifier = $name; $this->_identifierType = Doctrine_Core::IDENTIFIER_AUTOINC; } - $this->columnCount++; + ++$this->columnCount; break; case 1: foreach ($this->_identifier as $pk) { @@ -485,7 +480,7 @@ public function initIdentifier() switch (strtolower($e2[0])) { case 'autoincrement': case 'autoinc': - if ($value !== false) { + if (false !== $value) { $this->_identifierType = Doctrine_Core::IDENTIFIER_AUTOINC; $found = true; } @@ -507,7 +502,7 @@ public function initIdentifier() break; } } - if ( ! isset($this->_identifierType)) { + if (!isset($this->_identifierType)) { $this->_identifierType = Doctrine_Core::IDENTIFIER_NATURAL; } } @@ -526,16 +521,17 @@ public function initIdentifier() * The owner of a column is the name of the component in a hierarchy that * defines the column. * - * @param string $columnName the column name - * @return string the name of the owning/defining component + * @param string $columnName the column name + * + * @return string the name of the owning/defining component */ public function getColumnOwner($columnName) { if (isset($this->_columns[$columnName]['owner'])) { return $this->_columns[$columnName]['owner']; - } else { - return $this->getComponentName(); } + + return $this->getComponentName(); } /** @@ -546,13 +542,14 @@ public function getColumnOwner($columnName) * but primarily it is first used to instantiate all the internal * in memory schema definition. * - * @return Doctrine_Record Empty instance of the record + * @return Doctrine_Record Empty instance of the record */ public function getRecordInstance() { - if ( ! $this->record) { - $this->record = new $this->_options['name']; + if (!$this->record) { + $this->record = new $this->_options['name'](); } + return $this->record; } @@ -560,11 +557,12 @@ public function getRecordInstance() * Checks whether a column is inherited from a component further up in the hierarchy. * * @param string $columnName The column name - * @return boolean TRUE if column is inherited, FALSE otherwise. + * + * @return bool TRUE if column is inherited, FALSE otherwise */ public function isInheritedColumn($columnName) { - return (isset($this->_columns[$columnName]['owner'])); + return isset($this->_columns[$columnName]['owner']); } /** @@ -573,13 +571,14 @@ public function isInheritedColumn($columnName) * Checks if $fieldName is part of the table identifier, which defines * the one-column or multi-column primary key. * - * @param string $fieldName The field name - * @return boolean TRUE if the field is part of the table identifier/primary key field(s), + * @param string $fieldName The field name + * + * @return bool TRUE if the field is part of the table identifier/primary key field(s), */ public function isIdentifier($fieldName) { - return ($fieldName === $this->getIdentifier() || - in_array($fieldName, (array) $this->getIdentifier())); + return $fieldName === $this->getIdentifier() + || in_array($fieldName, (array) $this->getIdentifier()); } /** @@ -588,30 +587,29 @@ public function isIdentifier($fieldName) * This method checks if the primary key is a AUTOINCREMENT column or * if the table uses a natural key. * - * @return boolean TRUE if the identifier is autoincrement - * FALSE otherwise + * @return bool TRUE if the identifier is autoincrement + * FALSE otherwise */ public function isIdentifierAutoincrement() { - return $this->getIdentifierType() === Doctrine_Core::IDENTIFIER_AUTOINC; + return Doctrine_Core::IDENTIFIER_AUTOINC === $this->getIdentifierType(); } /** * Checks whether a field identifier is a composite key. * - * @return boolean TRUE if the identifier is a composite key, - * FALSE otherwise + * @return bool TRUE if the identifier is a composite key, + * FALSE otherwise */ public function isIdentifierComposite() { - return $this->getIdentifierType() === Doctrine_Core::IDENTIFIER_COMPOSITE; + return Doctrine_Core::IDENTIFIER_COMPOSITE === $this->getIdentifierType(); } /** - * getMethodOwner + * getMethodOwner. * * @param string $method - * @return void */ public function getMethodOwner($method) { @@ -620,7 +618,7 @@ public function getMethodOwner($method) } /** - * setMethodOwner + * setMethodOwner. * * @param string $method * @param string $class @@ -636,10 +634,11 @@ public function setMethodOwner($method, $class) * This method create a physical table in the database, using the * definition that comes from the component Doctrine_Record instance. * - * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS - * occurred during the create table operation - * @return boolean whether or not the export operation was successful - * false if table already existed in the database + * @return bool whether or not the export operation was successful + * false if table already existed in the database + * + * @throws Doctrine_Connection_Exception if some error other than Doctrine_Core::ERR_ALREADY_EXISTS + * occurred during the create table operation */ public function export() { @@ -653,7 +652,8 @@ public function export() * keys are tableName, columns (@see $_columns) and options. * The options subarray contains 'primary' and 'foreignKeys'. * - * @param boolean $parseForeignKeys whether to include foreign keys definition in the options + * @param bool $parseForeignKeys whether to include foreign keys definition in the options + * * @return array */ public function getExportableFormat($parseForeignKeys = true) @@ -662,7 +662,6 @@ public function getExportableFormat($parseForeignKeys = true) $primary = array(); foreach ($this->getColumns() as $name => $definition) { - if (isset($definition['owner'])) { continue; } @@ -685,38 +684,37 @@ public function getExportableFormat($parseForeignKeys = true) $this->_options['foreignKeys'] : array(); if ($parseForeignKeys && $this->getAttribute(Doctrine_Core::ATTR_EXPORT) & Doctrine_Core::EXPORT_CONSTRAINTS) { - $constraints = array(); $emptyIntegrity = array('onUpdate' => null, - 'onDelete' => null); + 'onDelete' => null); foreach ($this->getRelations() as $name => $relation) { $fk = $relation->toArray(); $fk['foreignTable'] = $relation->getTable()->getTableName(); // do not touch tables that have EXPORT_NONE attribute - if ($relation->getTable()->getAttribute(Doctrine_Core::ATTR_EXPORT) === Doctrine_Core::EXPORT_NONE) { + if (Doctrine_Core::EXPORT_NONE === $relation->getTable()->getAttribute(Doctrine_Core::ATTR_EXPORT)) { continue; } if ($relation->getTable() === $this && in_array($relation->getLocal(), $primary)) { if ($relation->hasConstraint()) { - throw new Doctrine_Table_Exception("Badly constructed integrity constraints. Cannot define constraint of different fields in the same table."); + throw new Doctrine_Table_Exception('Badly constructed integrity constraints. Cannot define constraint of different fields in the same table.'); } continue; } $integrity = array('onUpdate' => $fk['onUpdate'], - 'onDelete' => $fk['onDelete']); + 'onDelete' => $fk['onDelete']); $fkName = $relation->getForeignKeyName(); if ($relation instanceof Doctrine_Relation_LocalKey) { - $def = array('name' => $fkName, - 'local' => $relation->getLocalColumnName(), - 'foreign' => $relation->getForeignColumnName(), - 'foreignTable' => $relation->getTable()->getTableName()); + $def = array('name' => $fkName, + 'local' => $relation->getLocalColumnName(), + 'foreign' => $relation->getForeignColumnName(), + 'foreignTable' => $relation->getTable()->getTableName()); if ($integrity !== $emptyIntegrity) { $def = array_merge($def, $integrity); @@ -734,17 +732,18 @@ public function getExportableFormat($parseForeignKeys = true) $options['primary'] = $primary; return array('tableName' => $this->getOption('tableName'), - 'columns' => $columns, - 'options' => array_merge($this->getOptions(), $options)); + 'columns' => $columns, + 'options' => array_merge($this->getOptions(), $options)); } /** * Check if a foreign definition already exists in the fks array for a - * foreign table, local and foreign key + * foreign table, local and foreign key. + * + * @param array $def Foreign key definition to check for + * @param array $foreignKeys Array of existing foreign key definitions to check in * - * @param array $def Foreign key definition to check for - * @param array $foreignKeys Array of existing foreign key definitions to check in - * @return boolean $result Whether or not the foreign key was found + * @return bool $result Whether or not the foreign key was found */ protected function _checkForeignKeyExists($def, $foreignKeys) { @@ -753,13 +752,14 @@ protected function _checkForeignKeyExists($def, $foreignKeys) return $key; } } + return false; } /** * Retrieves the relation parser associated with this table. * - * @return Doctrine_Relation_Parser relation parser object + * @return Doctrine_Relation_Parser relation parser object */ public function getRelationParser() { @@ -777,13 +777,13 @@ public function getRelationParser() * * * @param string $option - * @return mixed */ public function __get($option) { if (isset($this->_options[$option])) { return $this->_options[$option]; } + return null; } @@ -807,7 +807,7 @@ public function __isset($option) /** * Retrieves all options of this table and the associated values. * - * @return array all options and their values + * @return array all options and their values */ public function getOptions() { @@ -820,8 +820,7 @@ public function getOptions() * This method sets options of the table that are specified in the argument. * It has no effect on other options. * - * @param array $options keys are option names - * @return void + * @param array $options keys are option names */ public function setOptions($options) { @@ -836,8 +835,7 @@ public function setOptions($options) * This method adds a foreign key to the schema definition. * It does not add the key to the physical table in the db; @see export(). * - * @param array $definition definition of the foreign key - * @return void + * @param array $definition definition of the foreign key */ public function addForeignKey(array $definition) { @@ -851,10 +849,8 @@ public function addForeignKey(array $definition) * It does not add the constraint to the physical table in the * db; @see export(). * - * @param $definition - * @param mixed $name if string used as name for the constraint. - * Otherwise it is indexed numerically. - * @return void + * @param mixed $name if string used as name for the constraint. + * Otherwise it is indexed numerically. */ public function addCheckConstraint($definition, $name) { @@ -873,9 +869,8 @@ public function addCheckConstraint($definition, $name) * This method adds an INDEX to the schema definition. * It does not add the index to the physical table in the db; @see export(). * - * @param string $index index name - * @param array $definition keys are type, fields - * @return void + * @param string $index index name + * @param array $definition keys are type, fields */ public function addIndex($index, array $definition) { @@ -901,8 +896,9 @@ public function addIndex($index, array $definition) * * This method returns a given index definition: @see addIndex(). * - * @param string $index index name; @see addIndex() - * @return array|boolean array on success, FALSE on failure + * @param string $index index name; @see addIndex() + * + * @return array|bool array on success, FALSE on failure */ public function getIndex($index) { @@ -920,15 +916,13 @@ public function getIndex($index) * and validate the values on save. The UNIQUE index is not created in the * database until you use @see export(). * - * @param array $fields values are fieldnames - * @param array $options array of options for unique validator - * @param bool $createUniqueIndex Whether or not to create a unique index in the database - * @return void + * @param array $fields values are fieldnames + * @param array $options array of options for unique validator */ public function unique($fields, $options = array(), $createdUniqueIndex = true) { if ($createdUniqueIndex) { - $name = implode('_', $fields) . '_unqidx'; + $name = implode('_', $fields).'_unqidx'; $definition = array('type' => 'unique', 'fields' => $fields); $this->addIndex($name, $definition); } @@ -942,28 +936,27 @@ public function unique($fields, $options = array(), $createdUniqueIndex = true) * This method defines a relation on this table, that will be present on * every record belonging to this component. * - * @param array $args first value is a string, name of related component; - * second value is array, options for the relation. + * @param array $args first value is a string, name of related component; + * second value is array, options for the relation + * * @see Doctrine_Relation::_$definition - * @param integer $type Doctrine_Relation::ONE or Doctrine_Relation::MANY - * @return void + * + * @param int $type Doctrine_Relation::ONE or Doctrine_Relation::MANY + * * @todo Name proposal: addRelation */ public function bind($args, $type) { - $options = ( ! isset($args[1])) ? array() : $args[1]; + $options = (!isset($args[1])) ? array() : $args[1]; $options['type'] = $type; $this->_parser->bind($args[0], $options); } /** - * Binds One-to-One aggregate relation + * Binds One-to-One aggregate relation. * - * @param string $componentName the name of the related component - * @param string $options relation options * @see Doctrine_Relation::_$definition - * @return void */ public function hasOne() { @@ -971,12 +964,9 @@ public function hasOne() } /** - * Binds One-to-Many / Many-to-Many aggregate relation + * Binds One-to-Many / Many-to-Many aggregate relation. * - * @param string $componentName the name of the related component - * @param string $options relation options * @see Doctrine_Relation::_$definition - * @return void */ public function hasMany() { @@ -991,8 +981,9 @@ public function hasMany() * recognized as there's only one Doctrine_Relation object on the owning * side. * - * @param string $alias the relation alias to search for. - * @return bool true if the relation exists. Otherwise false. + * @param string $alias the relation alias to search for + * + * @return bool true if the relation exists. Otherwise false. */ public function hasRelation($alias) { @@ -1002,7 +993,8 @@ public function hasRelation($alias) /** * Retrieves a relation object for this component. * - * @param string $alias relation alias; @see hasRelation() + * @param string $alias relation alias; @see hasRelation() + * * @return Doctrine_Relation */ public function getRelation($alias, $recursive = true) @@ -1031,19 +1023,21 @@ public function getRelations() * ->where('myuser.Phonenumber = ?', '5551234'); * * - * @param string $alias name for component aliasing + * @param string $alias name for component aliasing + * * @return Doctrine_Query */ public function createQuery($alias = '') { - if ( ! empty($alias)) { - $alias = ' ' . trim($alias); + if (!empty($alias)) { + $alias = ' '.trim($alias); } $class = $this->getAttribute(Doctrine_Core::ATTR_QUERY_CLASS); return Doctrine_Query::create(null, $class) - ->from($this->getComponentName() . $alias); + ->from($this->getComponentName().$alias) + ; } /** @@ -1063,9 +1057,11 @@ public function getRepository() * allow flexible method chaining. * * @see Doctrine_Table::$_options for available options - * @param string $name the name of the option to set - * @param mixed $value the value of the option - * @return Doctrine_Table this object + * + * @param string $name the name of the option to set + * @param mixed $value the value of the option + * + * @return Doctrine_Table this object */ public function setOption($name, $value) { @@ -1077,8 +1073,8 @@ public function setOption($name, $value) case 'inheritanceMap': case 'index': case 'treeOptions': - if ( ! is_array($value)) { - throw new Doctrine_Table_Exception($name . ' should be an array.'); + if (!is_array($value)) { + throw new Doctrine_Table_Exception($name.' should be an array.'); } break; } @@ -1089,23 +1085,26 @@ public function setOption($name, $value) * Returns the value of a given option. * * @see Doctrine_Table::$_options for available options - * @param string $name the name of the option - * @return mixed the value of given option + * + * @param string $name the name of the option + * + * @return mixed the value of given option */ public function getOption($name) { if (isset($this->_options[$name])) { return $this->_options[$name]; } + return null; } - /** - * Get the table orderby statement + * Get the table orderby statement. + * + * @param string $alias The alias to use + * @param bool $columnNames Whether or not to use column names instead of field names * - * @param string $alias The alias to use - * @param boolean $columnNames Whether or not to use column names instead of field names * @return string $orderByStatement */ public function getOrderByStatement($alias = null, $columnNames = false) @@ -1119,15 +1118,16 @@ public function getOrderByStatement($alias = null, $columnNames = false) * Process an order by statement to be prefixed with the passed alias and * field names converted to column names if the 3rd argument is true. * - * @param string $alias The alias to prefix columns with - * @param string $orderBy The order by to process - * @param string $columnNames Whether or not to convert field names to column names + * @param string $alias The alias to prefix columns with + * @param string $orderBy The order by to process + * @param string $columnNames Whether or not to convert field names to column names + * * @return string $orderBy */ public function processOrderBy($alias, $orderBy, $columnNames = false) { - if ( ! $alias) { - $alias = $this->getComponentName(); + if (!$alias) { + $alias = $this->getComponentName(); } // Php8.1 require a string @@ -1135,7 +1135,7 @@ public function processOrderBy($alias, $orderBy, $columnNames = false) $orderBy = ''; } - if ( ! is_array($orderBy)) { + if (!is_array($orderBy)) { $e1 = explode(',', $orderBy); } else { $e1 = $orderBy; @@ -1148,12 +1148,12 @@ public function processOrderBy($alias, $orderBy, $columnNames = false) $e2[0] = $this->getColumnName($e2[0]); } if ($this->hasField($this->getFieldName($e2[0]))) { - $e1[$k] = $alias . '.' . $e2[0]; + $e1[$k] = $alias.'.'.$e2[0]; } else { $e1[$k] = $e2[0]; } if (isset($e2[1])) { - $e1[$k] .= ' ' . $e2[1]; + $e1[$k] .= ' '.$e2[1]; } } @@ -1166,14 +1166,13 @@ public function processOrderBy($alias, $orderBy, $columnNames = false) * If the actual name for the alias cannot be found * this method returns the given alias. * - * @param string $alias column alias - * @return string column name + * @return string column name */ public function getColumnName($fieldName) { // FIX ME: This is being used in places where an array is passed, but it should not be an array // For example in places where Doctrine should support composite foreign/primary keys - $fieldName = is_array($fieldName) ? $fieldName[0]:$fieldName; + $fieldName = is_array($fieldName) ? $fieldName[0] : $fieldName; if (isset($this->_columnNames[$fieldName])) { return $this->_columnNames[$fieldName]; @@ -1190,13 +1189,15 @@ public function getColumnName($fieldName) * Retrieves a column definition from this table schema. * * @param string $columnName - * @return array column definition; @see $_columns + * + * @return array column definition; @see $_columns */ public function getColumnDefinition($columnName) { - if ( ! isset($this->_columns[$columnName])) { + if (!isset($this->_columns[$columnName])) { return false; } + return $this->_columns[$columnName]; } @@ -1205,14 +1206,16 @@ public function getColumnDefinition($columnName) * * If no alias can be found the column name is returned. * - * @param string $columnName column name - * @return string column alias + * @param string $columnName column name + * + * @return string column alias */ public function getFieldName($columnName) { if (isset($this->_fieldNames[$columnName])) { return $this->_fieldNames[$columnName]; } + return $columnName; } @@ -1231,8 +1234,6 @@ public function getFieldName($columnName) * } * * @param string $columnName - * @param array $validators - * @return void */ public function setColumnOptions($columnName, array $options) { @@ -1248,23 +1249,22 @@ public function setColumnOptions($columnName, array $options) } /** - * Set an individual column option + * Set an individual column option. * * @param string $columnName * @param string $option * @param string $value - * @return void */ public function setColumnOption($columnName, $option, $value) { - if ($option == 'primary') { + if ('primary' == $option) { if (isset($this->_identifier)) { $this->_identifier = (array) $this->_identifier; } - if ($value && ! in_array($columnName, $this->_identifier)) { + if ($value && !in_array($columnName, $this->_identifier)) { $this->_identifier[] = $columnName; - } else if (!$value && in_array($columnName, $this->_identifier)) { + } elseif (!$value && in_array($columnName, $this->_identifier)) { $key = array_search($columnName, $this->_identifier); unset($this->_identifier[$key]); } @@ -1275,10 +1275,7 @@ public function setColumnOption($columnName, $option, $value) } /** - * Set multiple column definitions at once - * - * @param array $definitions - * @return void + * Set multiple column definitions at once. */ public function setColumns(array $definitions) { @@ -1293,14 +1290,14 @@ public function setColumns(array $definitions) * This method does not alter the database table; @see export(); * * @see $_columns; - * @param string $name column physical name - * @param string $type type of data - * @param integer $length maximum length - * @param mixed $options - * @param boolean $prepend Whether to prepend or append the new column to the column list. - * By default the column gets appended. - * @throws Doctrine_Table_Exception if trying use wrongly typed parameter - * @return void + * + * @param string $name column physical name + * @param string $type type of data + * @param int $length maximum length + * @param bool $prepend Whether to prepend or append the new column to the column list. + * By default the column gets appended. + * + * @throws Doctrine_Table_Exception if trying use wrongly typed parameter */ public function setColumn($name, $type = null, $length = null, $options = array(), $prepend = false) { @@ -1310,7 +1307,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( foreach ($options as $k => $option) { if (is_numeric($k)) { - if ( ! empty($option)) { + if (!empty($option)) { $options[$option] = true; } unset($options[$k]); @@ -1318,8 +1315,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( } // extract column name & field name - if (stripos($name, ' as ')) - { + if (stripos($name, ' as ')) { if (strpos($name, ' as ')) { $parts = explode(' as ', $name); } else { @@ -1351,18 +1347,18 @@ public function setColumn($name, $type = null, $length = null, $options = array( $defaultOptions = $this->getAttribute(Doctrine_Core::ATTR_DEFAULT_COLUMN_OPTIONS); - if (isset($defaultOptions['length']) && $defaultOptions['length'] && $length == null) { + if (isset($defaultOptions['length']) && $defaultOptions['length'] && null == $length) { $length = $defaultOptions['length']; } - if ($length == null) { + if (null == $length) { switch ($type) { case 'integer': $length = 8; - break; + break; case 'decimal': $length = 18; - break; + break; case 'string': case 'clob': case 'float': @@ -1371,20 +1367,23 @@ public function setColumn($name, $type = null, $length = null, $options = array( case 'object': case 'blob': case 'gzip': - //$length = 2147483647; + // $length = 2147483647; - //All the DataDict driver classes have work-arounds to deal - //with unset lengths. + // All the DataDict driver classes have work-arounds to deal + // with unset lengths. $length = null; - break; + break; case 'boolean': $length = 1; + // no break case 'date': // YYYY-MM-DD ISO 8601 $length = 10; + // no break case 'time': // HH:NN:SS+00:00 ISO 8601 $length = 14; + // no break case 'timestamp': // YYYY-MM-DDTHH:MM:SS+00:00 ISO 8601 $length = 25; @@ -1399,7 +1398,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( } foreach ($defaultOptions as $key => $value) { - if ( ! array_key_exists($key, $options) || is_null($options[$key])) { + if (!array_key_exists($key, $options) || is_null($options[$key])) { $options[$key] = $value; } } @@ -1414,7 +1413,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( if (isset($this->_identifier)) { $this->_identifier = (array) $this->_identifier; } - if ( ! in_array($fieldName, $this->_identifier)) { + if (!in_array($fieldName, $this->_identifier)) { $this->_identifier[] = $fieldName; } } @@ -1426,7 +1425,7 @@ public function setColumn($name, $type = null, $length = null, $options = array( /** * Finds out whether this table has default values for columns. * - * @return boolean + * @return bool */ public function hasDefaultValues() { @@ -1436,25 +1435,27 @@ public function hasDefaultValues() /** * Retrieves the default value (if any) for a given column. * - * @param string $fieldName column name - * @return mixed default value as set in definition + * @param string $fieldName column name + * + * @return mixed default value as set in definition */ public function getDefaultValueOf($fieldName) { $columnName = $this->getColumnName($fieldName); - if ( ! isset($this->_columns[$columnName])) { + if (!isset($this->_columns[$columnName])) { throw new Doctrine_Table_Exception("Couldn't get default value. Column ".$columnName." doesn't exist."); } if (isset($this->_columns[$columnName]['default'])) { return $this->_columns[$columnName]['default']; - } else { - return null; } + + return null; } /** * Returns the definition of the identifier key. - * @return string can be array if a multi-column primary key is used. + * + * @return string can be array if a multi-column primary key is used */ public function getIdentifier() { @@ -1465,8 +1466,10 @@ public function getIdentifier() * Retrieves the type of primary key. * * This method finds out if the primary key is multifield. + * * @see Doctrine_Identifier constants - * @return integer + * + * @return int */ public function getIdentifierType() { @@ -1475,8 +1478,10 @@ public function getIdentifierType() /** * Finds out whether the table definition contains a given column. + * * @param string $columnName - * @return boolean + * + * @return bool */ public function hasColumn($columnName) { @@ -1488,8 +1493,10 @@ public function hasColumn($columnName) * * This method returns true if @see hasColumn() returns true or if an alias * named $fieldName exists. + * * @param string $fieldName - * @return boolean + * + * @return bool */ public function hasField($fieldName) { @@ -1518,7 +1525,7 @@ public function setConnection(Doctrine_Connection $conn) /** * Returns the connection associated with this table (if any). * - * @return Doctrine_Connection|null the connection object + * @return Doctrine_Connection|null the connection object */ public function getConnection() { @@ -1536,6 +1543,7 @@ public function getConnection() * @param array $array an array where keys are field names and * values representing field values. Can contain * also related components; + * * @see Doctrine_Record::fromArray() * * @return Doctrine_Record the created record object @@ -1557,13 +1565,11 @@ public function create(array $array = array()) * * @param string $queryKey query key name to use for storage * @param string|Doctrine_Query $query DQL string or object - * - * @return void */ public function addNamedQuery($queryKey, $query) { $registry = Doctrine_Manager::getInstance()->getQueryRegistry(); - $registry->add($this->getComponentName() . '/' . $queryKey, $query); + $registry->add($this->getComponentName().'/'.$queryKey, $query); } /** @@ -1572,14 +1578,16 @@ public function addNamedQuery($queryKey, $query) * This method clones a new query object from a previously registered one. * * @see addNamedQuery() - * @param string $queryKey query key name + * + * @param string $queryKey query key name + * * @return Doctrine_Query */ public function createNamedQuery($queryKey) { $queryRegistry = Doctrine_Manager::getInstance()->getQueryRegistry(); - if (strpos($queryKey, '/') !== false) { + if (false !== strpos($queryKey, '/')) { $e = explode('/', $queryKey); return $queryRegistry->get($e[1], $e[0]); @@ -1597,13 +1605,6 @@ public function createNamedQuery($queryKey) * $table->find('namedQueryForYearArchive', array(2009), Doctrine_Core::HYDRATE_ARRAY); * * - * @param mixed $name Database Row ID or Query Name defined previously as a NamedQuery - * @param mixed $params This argument is the hydration mode (Doctrine_Core::HYDRATE_ARRAY or - * Doctrine_Core::HYDRATE_RECORD) if first param is a Database Row ID. - * Otherwise this argument expect an array of query params. - * @param int $hydrationMode Optional Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD if - * first argument is a NamedQuery - * * @return Doctrine_Collection|array|Doctrine_Record|false Doctrine_Collection, array, Doctrine_Record or false if no result */ public function find() @@ -1621,14 +1622,14 @@ public function find() $m = $name; // Check for possible cross-access - if ( ! is_array($name) && strpos($name, '/') !== false) { + if (!is_array($name) && false !== strpos($name, '/')) { list($ns, $m) = explode('/', $name); } // Define query to be used if ( - ! is_array($name) && - Doctrine_Manager::getInstance()->getQueryRegistry()->has($m, $ns) + !is_array($name) + && Doctrine_Manager::getInstance()->getQueryRegistry()->has($m, $ns) ) { // We're dealing with a named query $q = $this->createNamedQuery($name); @@ -1637,21 +1638,22 @@ public function find() $params = ($num_args >= 2) ? func_get_arg(1) : array(); // Hydration mode - $hydrationMode = ($num_args == 3) ? func_get_arg(2) : null; + $hydrationMode = (3 == $num_args) ? func_get_arg(2) : null; // Executing query $res = $q->execute($params, $hydrationMode); } else { // We're passing a single ID or an array of IDs $q = $this->createQuery('dctrn_find') - ->where('dctrn_find.' . implode(' = ? AND dctrn_find.', (array) $this->getIdentifier()) . ' = ?') - ->limit(1); + ->where('dctrn_find.'.implode(' = ? AND dctrn_find.', (array) $this->getIdentifier()).' = ?') + ->limit(1) + ; // Parameters construction $params = is_array($name) ? array_values($name) : array($name); // Hydration mode - $hydrationMode = ($num_args == 2) ? func_get_arg(1) : null; + $hydrationMode = (2 == $num_args) ? func_get_arg(1) : null; // Executing query $res = $q->fetchOne($params, $hydrationMode); @@ -1663,7 +1665,8 @@ public function find() /** * Retrieves all the records stored in this table. * - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array */ public function findAll($hydrationMode = null) @@ -1674,9 +1677,10 @@ public function findAll($hydrationMode = null) /** * Finds records in this table with a given SQL where clause. * - * @param string $dql DQL WHERE clause to use - * @param array $params query parameters (a la PDO) - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string $dql DQL WHERE clause to use + * @param array $params query parameters (a la PDO) + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array * * @todo This actually takes DQL, not SQL, but it requires column names @@ -1685,21 +1689,23 @@ public function findAll($hydrationMode = null) public function findBySql($dql, $params = array(), $hydrationMode = null) { return $this->createQuery('dctrn_find') - ->where($dql)->execute($params, $hydrationMode); + ->where($dql)->execute($params, $hydrationMode) + ; } /** * Finds records in this table with a given DQL where clause. * - * @param string $dql DQL WHERE clause - * @param array $params preparated statement parameters - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string $dql DQL WHERE clause + * @param array $params preparated statement parameters + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array */ public function findByDql($dql, $params = array(), $hydrationMode = null) { $parser = $this->createQuery(); - $query = 'FROM ' . $this->getComponentName() . ' dctrn_find WHERE ' . $dql; + $query = 'FROM '.$this->getComponentName().' dctrn_find WHERE '.$dql; return $parser->query($query, $params, $hydrationMode); } @@ -1707,24 +1713,25 @@ public function findByDql($dql, $params = array(), $hydrationMode = null) /** * Find records basing on a field. * - * @param string $column field for the WHERE clause - * @param string|array $value prepared statement parameter - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string|array $value prepared statement parameter + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array */ public function findBy($fieldName, $value, $hydrationMode = null) { return $this->createQuery('dctrn_find') ->where($this->buildFindByWhere($fieldName), (array) $value) - ->execute(array(), $hydrationMode); + ->execute(array(), $hydrationMode) + ; } /** * Finds the first record that satisfy the clause. * - * @param string $column field for the WHERE clause - * @param string|array $value prepared statement parameter - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * @param string|array $value prepared statement parameter + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Record */ public function findOneBy($fieldName, $value, $hydrationMode = null) @@ -1732,7 +1739,8 @@ public function findOneBy($fieldName, $value, $hydrationMode = null) return $this->createQuery('dctrn_find') ->where($this->buildFindByWhere($fieldName), (array) $value) ->limit(1) - ->fetchOne(array(), $hydrationMode); + ->fetchOne(array(), $hydrationMode) + ; } /** @@ -1742,10 +1750,12 @@ public function findOneBy($fieldName, $value, $hydrationMode = null) * query in the query registry. * * @param string $queryKey the query key - * @param array $params prepared statement params (if any) - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD - * @throws Doctrine_Query_Registry if no query for given queryKey is found + * @param array $params prepared statement params (if any) + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Collection|array + * + * @throws Doctrine_Query_Registry if no query for given queryKey is found */ public function execute($queryKey, $params = array(), $hydrationMode = Doctrine_Core::HYDRATE_RECORD) { @@ -1759,10 +1769,12 @@ public function execute($queryKey, $params = array(), $hydrationMode = Doctrine_ * the associated named query in the query registry. * * @param string $queryKey the query key - * @param array $params prepared statement params (if any) - * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD - * @throws Doctrine_Query_Registry if no query for given queryKey is found + * @param array $params prepared statement params (if any) + * @param int $hydrationMode Doctrine_Core::HYDRATE_ARRAY or Doctrine_Core::HYDRATE_RECORD + * * @return Doctrine_Record|array + * + * @throws Doctrine_Query_Registry if no query for given queryKey is found */ public function executeOne($queryKey, $params = array(), $hydrationMode = Doctrine_Core::HYDRATE_RECORD) { @@ -1774,7 +1786,6 @@ public function executeOne($queryKey, $params = array(), $hydrationMode = Doctri * * This method ensures that records are reloaded from the db. * - * @return void * @todo what about a more descriptive name? clearIdentityMap? */ public function clear() @@ -1788,8 +1799,10 @@ public function clear() * This method is used internally to cache records, ensuring that only one * object that represents a sql record exists in all scopes. * - * @param Doctrine_Record $record record to be added - * @return boolean true if record was not present in the map + * @param Doctrine_Record $record record to be added + * + * @return bool true if record was not present in the map + * * @todo Better name? registerRecord? */ public function addRecord(Doctrine_Record $record) @@ -1815,9 +1828,10 @@ public function addRecord(Doctrine_Record $record) * This method deletes from the cache the given record; can be used to * force reloading of an object from database. * - * @param Doctrine_Record $record record to remove from cache - * @return boolean true if the record was found and removed, - * false if the record wasn't found. + * @param Doctrine_Record $record record to remove from cache + * + * @return bool true if the record was found and removed, + * false if the record wasn't found */ public function removeRecord(Doctrine_Record $record) { @@ -1829,6 +1843,7 @@ public function removeRecord(Doctrine_Record $record) if (isset($this->_identityMap[$id])) { unset($this->_identityMap[$id]); + return true; } @@ -1845,16 +1860,16 @@ public function removeRecord(Doctrine_Record $record) */ public function getRecord() { - if ( ! empty($this->_data)) { + if (!empty($this->_data)) { $identifierFieldNames = $this->getIdentifier(); - if ( ! is_array($identifierFieldNames)) { + if (!is_array($identifierFieldNames)) { $identifierFieldNames = array($identifierFieldNames); } $found = false; foreach ($identifierFieldNames as $fieldName) { - if ( ! isset($this->_data[$fieldName])) { + if (!isset($this->_data[$fieldName])) { // primary key column not found return new record $found = true; break; @@ -1866,6 +1881,7 @@ public function getRecord() $recordName = $this->getComponentName(); $record = new $recordName($this, true); $this->_data = array(); + return $record; } @@ -1875,7 +1891,7 @@ public function getRecord() $record = $this->_identityMap[$id]; if ($record->getTable()->getAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE)) { $record->hydrate($this->_data); - if ($record->state() == Doctrine_Record::STATE_PROXY) { + if (Doctrine_Record::STATE_PROXY == $record->state()) { if (!$record->isInProxyState()) { $record->state(Doctrine_Record::STATE_CLEAN); } @@ -1912,11 +1928,12 @@ public function getRecord() * if the subclassing option is not set. * * @return string The name of the class to create + * * @deprecated */ public function getClassnameToReturn() { - if ( ! isset($this->_options['subclasses'])) { + if (!isset($this->_options['subclasses'])) { return $this->_options['name']; } foreach ($this->_options['subclasses'] as $subclass) { @@ -1924,56 +1941,63 @@ public function getClassnameToReturn() $inheritanceMap = $table->getOption('inheritanceMap'); $nomatch = false; foreach ($inheritanceMap as $key => $value) { - if ( ! isset($this->_data[$key]) || $this->_data[$key] != $value) { + if (!isset($this->_data[$key]) || $this->_data[$key] != $value) { $nomatch = true; break; } } - if ( ! $nomatch) { + if (!$nomatch) { return $table->getComponentName(); } } + return $this->_options['name']; } /** - * @param $id database row id - * @throws Doctrine_Find_Exception + * @param $id database row id + * * @return Doctrine_Record + * + * @throws Doctrine_Find_Exception */ final public function getProxy($id = null) { - if ($id !== null) { + if (null !== $id) { $identifierColumnNames = $this->getIdentifierColumnNames(); - $query = 'SELECT ' . implode(', ', (array) $identifierColumnNames) - . ' FROM ' . $this->getTableName() - . ' WHERE ' . implode(' = ? && ', (array) $identifierColumnNames) . ' = ?'; + $query = 'SELECT '.implode(', ', (array) $identifierColumnNames) + .' FROM '.$this->getTableName() + .' WHERE '.implode(' = ? && ', (array) $identifierColumnNames).' = ?'; $query = $this->applyInheritance($query); $params = array_merge(array($id), array_values($this->_options['inheritanceMap'])); $this->_data = $this->_conn->execute($query, $params)->fetch(PDO::FETCH_ASSOC); - if ($this->_data === false) + if (false === $this->_data) { return false; + } } + return $this->getRecord(); } /** - * applyInheritance - * @param $where query where part to be modified - * @return string query where part with column aggregation inheritance added + * applyInheritance. + * + * @param $where query where part to be modified + * + * @return string query where part with column aggregation inheritance added */ final public function applyInheritance($where) { - if ( ! empty($this->_options['inheritanceMap'])) { + if (!empty($this->_options['inheritanceMap'])) { $a = array(); foreach ($this->_options['inheritanceMap'] as $field => $value) { - $a[] = $this->getColumnName($field) . ' = ?'; + $a[] = $this->getColumnName($field).' = ?'; } $i = implode(' AND ', $a); - $where .= ' AND ' . $i; + $where .= ' AND '.$i; } return $where; @@ -1982,16 +2006,16 @@ final public function applyInheritance($where) /** * Implements Countable interface. * - * @return integer number of records in the table + * @return int number of records in the table */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return $this->createQuery()->count(); } /** - * @return Doctrine_Query a Doctrine_Query object + * @return Doctrine_Query a Doctrine_Query object */ public function getQueryObject() { @@ -2005,6 +2029,7 @@ public function getQueryObject() * Retrieves the enum values for a given field. * * @param string $fieldName + * * @return array */ public function getEnumValues($fieldName) @@ -2012,9 +2037,9 @@ public function getEnumValues($fieldName) $columnName = $this->getColumnName($fieldName); if (isset($this->_columns[$columnName]['values'])) { return $this->_columns[$columnName]['values']; - } else { - return array(); } + + return array(); } /** @@ -2024,8 +2049,7 @@ public function getEnumValues($fieldName) * on the connection, index and value are the same thing. * * @param string $fieldName - * @param integer $index numeric index of the enum - * @return mixed + * @param int $index numeric index of the enum */ public function enumValue($fieldName, $index) { @@ -2044,11 +2068,13 @@ public function enumValue($fieldName, $index) /** * Retrieves an enum index. + * * @see enumValue() * * @param string $fieldName - * @param mixed $value value of the enum considered - * @return integer can be string if native enums are used. + * @param mixed $value value of the enum considered + * + * @return int can be string if native enums are used */ public function enumIndex($fieldName, $value) { @@ -2057,16 +2083,19 @@ public function enumIndex($fieldName, $value) if ($this->_conn->getAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM)) { return $value; } + return array_search($value, $values); } /** * Validates a given field using table ATTR_VALIDATE rules. + * * @see Doctrine_Core::ATTR_VALIDATE * - * @param string $fieldName - * @param string $value - * @param Doctrine_Record $record record to consider; if it does not exists, it is created + * @param string $fieldName + * @param string $value + * @param Doctrine_Record $record record to consider; if it does not exists, it is created + * * @return Doctrine_Validator_ErrorStack $errorStack */ public function validateField($fieldName, $value, Doctrine_Record $record = null) @@ -2074,16 +2103,16 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null if ($record instanceof Doctrine_Record) { $errorStack = $record->getErrorStack(); } else { - $record = $this->create(); + $record = $this->create(); $errorStack = new Doctrine_Validator_ErrorStack($this->getOption('name')); } if ($value === self::$_null) { $value = null; - } else if ($value instanceof Doctrine_Record && $value->exists()) { + } elseif ($value instanceof Doctrine_Record && $value->exists()) { $value = $value->getIncremented(); - } else if ($value instanceof Doctrine_Record && ! $value->exists()) { - foreach($this->getRelations() as $relation) { + } elseif ($value instanceof Doctrine_Record && !$value->exists()) { + foreach ($this->getRelations() as $relation) { if ($fieldName == $relation->getLocalFieldName() && (get_class($value) == $relation->getClass() || is_subclass_of($value, $relation->getClass()))) { return $errorStack; } @@ -2094,16 +2123,16 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null // Validate field type, if type validation is enabled if ($this->getAttribute(Doctrine_Core::ATTR_VALIDATE) & Doctrine_Core::VALIDATE_TYPES) { - if ( ! Doctrine_Validator::isValidType($value, $dataType)) { + if (!Doctrine_Validator::isValidType($value, $dataType)) { $errorStack->add($fieldName, 'type'); } - if ($dataType == 'enum') { + if ('enum' == $dataType) { $enumIndex = $this->enumIndex($fieldName, $value); - if ($enumIndex === false && $value !== null) { + if (false === $enumIndex && null !== $value) { $errorStack->add($fieldName, 'enum'); } } - if ($dataType == 'set') { + if ('set' == $dataType) { $values = $this->_columns[$fieldName]['values']; // Convert string to array if (is_string($value)) { @@ -2115,7 +2144,7 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null } // Make sure each set value is valid foreach ($value as $k => $v) { - if ( ! in_array($v, $values)) { + if (!in_array($v, $values)) { $errorStack->add($fieldName, 'set'); } } @@ -2124,14 +2153,14 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null // Validate field length, if length validation is enabled if ($this->getAttribute(Doctrine_Core::ATTR_VALIDATE) & Doctrine_Core::VALIDATE_LENGTHS) { - if ( ! Doctrine_Validator::validateLength($value, $dataType, $this->getFieldLength($fieldName))) { + if (!Doctrine_Validator::validateLength($value, $dataType, $this->getFieldLength($fieldName))) { $errorStack->add($fieldName, 'length'); } } // Run all custom validators foreach ($this->getFieldValidators($fieldName) as $validatorName => $args) { - if ( ! is_string($validatorName)) { + if (!is_string($validatorName)) { $validatorName = $args; $args = array(); } @@ -2140,7 +2169,7 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null $validator->invoker = $record; $validator->field = $fieldName; $validator->args = $args; - if ( ! $validator->validate($value)) { + if (!$validator->validate($value)) { $errorStack->add($fieldName, $validator); } } @@ -2153,8 +2182,6 @@ public function validateField($fieldName, $value, Doctrine_Record $record = null * * This methods validates 'unique' sets of fields for the given Doctrine_Record instance. * Pushes error to the record error stack if they are generated. - * - * @param Doctrine_Record $record */ public function validateUniques(Doctrine_Record $record) { @@ -2162,16 +2189,15 @@ public function validateUniques(Doctrine_Record $record) $validator = Doctrine_Validator::getValidator('unique'); $validator->invoker = $record; - foreach ($this->_uniques as $unique) - { + foreach ($this->_uniques as $unique) { list($fields, $options) = $unique; $validator->args = $options; $validator->field = $fields; $values = array(); foreach ($fields as $field) { - $values[] = $record->$field; + $values[] = $record->{$field}; } - if ( ! $validator->validate($values)) { + if (!$validator->validate($values)) { foreach ($fields as $field) { $errorStack->add($field, $validator); } @@ -2180,7 +2206,7 @@ public function validateUniques(Doctrine_Record $record) } /** - * @return integer the number of columns in this table + * @return int the number of columns in this table */ public function getColumnCount() { @@ -2191,7 +2217,8 @@ public function getColumnCount() * Retrieves all columns of the table. * * @see $_columns; - * @return array keys are column names and values are definition + * + * @return array keys are column names and values are definition */ public function getColumns() { @@ -2202,18 +2229,20 @@ public function getColumns() * Removes a field name from the table schema information. * * @param string $fieldName - * @return boolean true if the field is found and removed. - * False otherwise. + * + * @return bool true if the field is found and removed. + * False otherwise. */ public function removeColumn($fieldName) { - if ( ! $this->hasField($fieldName)) { - return false; + if (!$this->hasField($fieldName)) { + return false; } $columnName = $this->getColumnName($fieldName); unset($this->_columnNames[$fieldName], $this->_fieldNames[$columnName], $this->_columns[$columnName]); $this->columnCount = count($this->_columns); + return true; } @@ -2224,15 +2253,15 @@ public function removeColumn($fieldName) */ public function getColumnNames(array $fieldNames = null) { - if ($fieldNames === null) { + if (null === $fieldNames) { return array_keys($this->_columns); - } else { - $columnNames = array(); - foreach ($fieldNames as $fieldName) { - $columnNames[] = $this->getColumnName($fieldName); - } - return $columnNames; } + $columnNames = array(); + foreach ($fieldNames as $fieldName) { + $columnNames[] = $this->getColumnName($fieldName); + } + + return $columnNames; } /** @@ -2247,6 +2276,7 @@ public function getIdentifierColumnNames() /** * Gets the array of unique fields sets. + * * @see $_uniques; * * @return array numeric array @@ -2273,11 +2303,13 @@ public function getFieldNames() * which can be a column name or a field name (alias). * * @param string $fieldName - * @return array false on failure + * + * @return array false on failure */ public function getDefinitionOf($fieldName) { $columnName = $this->getColumnName($fieldName); + return $this->getColumnDefinition($columnName); } @@ -2285,7 +2317,8 @@ public function getDefinitionOf($fieldName) * Retrieves the type of a field. * * @param string $fieldName - * @return string false on failure + * + * @return string false on failure */ public function getTypeOf($fieldName) { @@ -2296,7 +2329,8 @@ public function getTypeOf($fieldName) * Retrieves the type of a column. * * @param string $columnName - * @return string false if column is not found + * + * @return string false if column is not found */ public function getTypeOfColumn($columnName) { @@ -2307,9 +2341,7 @@ public function getTypeOfColumn($columnName) * Doctrine uses this function internally. * Users are strongly discouraged to use this function. * - * @access private - * @param array $data internal data - * @return void + * @param array $data internal data */ public function setData(array $data) { @@ -2346,57 +2378,61 @@ public function getData() * $table->prepareValue($field, $value); // Doctrine_Null * * - * @throws Doctrine_Table_Exception if unserialization of array/object typed column fails or - * @throws Doctrine_Table_Exception if uncompression of gzip typed column fails * - * @param string $field the name of the field - * @param string $value field value - * @param string $typeHint Type hint used to pass in the type of the value to prepare - * if it is already known. This enables the method to skip - * the type determination. Used i.e. during hydration. - * @return mixed prepared value + * @param string $value field value + * @param string $typeHint Type hint used to pass in the type of the value to prepare + * if it is already known. This enables the method to skip + * the type determination. Used i.e. during hydration. + * + * @return mixed prepared value + * + * @throws Doctrine_Table_Exception if unserialization of array/object typed column fails or + * @throws Doctrine_Table_Exception if uncompression of gzip typed column fails * */ public function prepareValue($fieldName, $value, $typeHint = null) { if ($value === self::$_null) { return self::$_null; - } else if ($value === null) { + } + if (null === $value) { return null; - } else { - $type = is_null($typeHint) ? $this->getTypeOf($fieldName) : $typeHint; + } + $type = is_null($typeHint) ? $this->getTypeOf($fieldName) : $typeHint; - switch ($type) { - case 'enum': - case 'integer': - case 'string'; - // don't do any casting here PHP INT_MAX is smaller than what the databases support + switch ($type) { + case 'enum': + case 'integer': + case 'string': + // don't do any casting here PHP INT_MAX is smaller than what the databases support break; - case 'set': - return explode(',', $value); + case 'set': + return explode(',', $value); break; - case 'boolean': - return (boolean) $value; + case 'boolean': + return (bool) $value; break; - case 'array': - case 'object': - if (is_string($value)) { - $value = empty($value) ? null:unserialize($value); + case 'array': + case 'object': + if (is_string($value)) { + $value = empty($value) ? null : unserialize($value); - if ($value === false) { - throw new Doctrine_Table_Exception('Unserialization of ' . $fieldName . ' failed.'); - } - return $value; + if (false === $value) { + throw new Doctrine_Table_Exception('Unserialization of '.$fieldName.' failed.'); } - break; - case 'gzip': - $value = gzuncompress($value); - if ($value === false) { - throw new Doctrine_Table_Exception('Uncompressing of ' . $fieldName . ' failed.'); - } return $value; + } + break; + case 'gzip': + $value = gzuncompress($value); + + if (false === $value) { + throw new Doctrine_Table_Exception('Uncompressing of '.$fieldName.' failed.'); + } + + return $value; break; - } } + return $value; } @@ -2410,15 +2446,17 @@ public function prepareValue($fieldName, $value, $typeHint = null) public function getTree() { if (isset($this->_options['treeImpl'])) { - if ( ! $this->_tree) { + if (!$this->_tree) { $options = isset($this->_options['treeOptions']) ? $this->_options['treeOptions'] : array(); $this->_tree = Doctrine_Tree::factory($this, $this->_options['treeImpl'], $options ); } + return $this->_tree; } + return false; } @@ -2446,7 +2484,6 @@ public function getTableName() * sets the table name in the schema definition. * * @param string $tableName - * @return void */ public function setTableName($tableName) { @@ -2456,17 +2493,17 @@ public function setTableName($tableName) /** * Determines if table acts as tree. * - * @return boolean if tree return true, otherwise returns false + * @return bool if tree return true, otherwise returns false */ public function isTree() { - return ( ! is_null($this->_options['treeImpl'])) ? true : false; + return (!is_null($this->_options['treeImpl'])) ? true : false; } /** * Retrieves all templates (behaviors) attached to this table. * - * @return array an array containing all templates + * @return array an array containing all templates */ public function getTemplates() { @@ -2479,38 +2516,43 @@ public function getTemplates() * This method retrieves a behavior/template object attached to the table. * For Doctrine_Template_* classes, the base name can be used. * - * @param string $template name of the behavior - * @throws Doctrine_Table_Exception if the given template is - * not set on this table + * @param string $template name of the behavior + * * @return Doctrine_Template + * + * @throws Doctrine_Table_Exception if the given template is + * not set on this table */ public function getTemplate($template) { - if (isset($this->_templates['Doctrine_Template_' . $template])) { - return $this->_templates['Doctrine_Template_' . $template]; - } else if (isset($this->_templates[$template])) { + if (isset($this->_templates['Doctrine_Template_'.$template])) { + return $this->_templates['Doctrine_Template_'.$template]; + } + if (isset($this->_templates[$template])) { return $this->_templates[$template]; } - throw new Doctrine_Table_Exception('Template ' . $template . ' not loaded'); + throw new Doctrine_Table_Exception('Template '.$template.' not loaded'); } /** * Checks if the table has a given template. * - * @param string $template name of template; @see getTemplate() - * @return boolean + * @param string $template name of template; @see getTemplate() + * + * @return bool */ public function hasTemplate($template) { - return isset($this->_templates[$template]) || isset($this->_templates['Doctrine_Template_' . $template]); + return isset($this->_templates[$template]) || isset($this->_templates['Doctrine_Template_'.$template]); } /** * Adds a template to this table. * - * @param string $template template name - * @param Doctrine_Template $impl behavior to attach + * @param string $template template name + * @param Doctrine_Template $impl behavior to attach + * * @return Doctrine_Table */ public function addTemplate($template, Doctrine_Template $impl) @@ -2534,12 +2576,13 @@ public function getGenerators() * Gets generator instance for a passed name. * * @param string $generator + * * @return Doctrine_Record_Generator $generator */ public function getGenerator($generator) { - if ( ! isset($this->_generators[$generator])) { - throw new Doctrine_Table_Exception('Generator ' . $generator . ' not loaded'); + if (!isset($this->_generators[$generator])) { + throw new Doctrine_Table_Exception('Generator '.$generator.' not loaded'); } return $this->_generators[$generator]; @@ -2549,7 +2592,6 @@ public function getGenerator($generator) * Checks if a generator name exists. * * @param string $generator - * @return void */ public function hasGenerator($generator) { @@ -2559,25 +2601,23 @@ public function hasGenerator($generator) /** * Adds a generate to the table instance. * - * @param Doctrine_Record_Generator $generator * @param string $name + * * @return Doctrine_Table */ public function addGenerator(Doctrine_Record_Generator $generator, $name = null) { - if ($name === null) { + if (null === $name) { $this->_generators[] = $generator; } else { $this->_generators[$name] = $generator; } + return $this; } /** - * Set the generator responsible for creating this table - * - * @param Doctrine_Record_Generator $generator - * @return void + * Set the generator responsible for creating this table. */ public function setGenerator(Doctrine_Record_Generator $generator) { @@ -2585,9 +2625,9 @@ public function setGenerator(Doctrine_Record_Generator $generator) } /** - * Check whether this table was created by a record generator or not + * Check whether this table was created by a record generator or not. * - * @return boolean + * @return bool */ public function isGenerator() { @@ -2595,7 +2635,7 @@ public function isGenerator() } /** - * Get the parent generator responsible for this table instance + * Get the parent generator responsible for this table instance. * * @return Doctrine_Record_Generator */ @@ -2606,10 +2646,12 @@ public function getParentGenerator() /** * Binds query parts to this component. + * * @see bindQueryPart() * - * @param array $queryParts an array of pre-bound query parts - * @return Doctrine_Table this object + * @param array $queryParts an array of pre-bound query parts + * + * @return Doctrine_Table this object */ public function bindQueryParts(array $queryParts) { @@ -2625,8 +2667,8 @@ public function bindQueryParts(array $queryParts) * Every query created by this table will have this part set by default. * * @param string $queryPart - * @param mixed $value - * @return Doctrine_Record this object + * + * @return Doctrine_Record this object */ public function bindQueryPart($queryPart, $value) { @@ -2639,7 +2681,8 @@ public function bindQueryPart($queryPart, $value) * Gets the names of all validators being applied on a field. * * @param string $fieldName - * @return array names of validators + * + * @return array names of validators */ public function getFieldValidators($fieldName) { @@ -2648,32 +2691,32 @@ public function getFieldValidators($fieldName) // this loop is a dirty workaround to get the validators filtered out of // the options, since everything is squeezed together currently foreach ($this->_columns[$columnName] as $name => $args) { - if (empty($name) - || $name == 'primary' - || $name == 'protected' - || $name == 'autoincrement' - || $name == 'default' - || $name == 'values' - || $name == 'sequence' - || $name == 'zerofill' - || $name == 'owner' - || $name == 'scale' - || $name == 'type' - || $name == 'length' - || $name == 'fixed' - || $name == 'comment' - || $name == 'alias' - || $name == 'charset' - || $name == 'collation' - || $name == 'extra') { + if (empty($name) + || 'primary' == $name + || 'protected' == $name + || 'autoincrement' == $name + || 'default' == $name + || 'values' == $name + || 'sequence' == $name + || 'zerofill' == $name + || 'owner' == $name + || 'scale' == $name + || 'type' == $name + || 'length' == $name + || 'fixed' == $name + || 'comment' == $name + || 'alias' == $name + || 'charset' == $name + || 'collation' == $name + || 'extra' == $name) { continue; } - if ($name == 'notnull' && isset($this->_columns[$columnName]['autoincrement']) - && $this->_columns[$columnName]['autoincrement'] === true) { + if ('notnull' == $name && isset($this->_columns[$columnName]['autoincrement']) + && true === $this->_columns[$columnName]['autoincrement']) { continue; } // skip it if it's explicitly set to FALSE (i.e. notnull => false) - if ($args === false) { + if (false === $args) { continue; } $validators[$name] = $args; @@ -2685,10 +2728,11 @@ public function getFieldValidators($fieldName) /** * Gets the maximum length of a field. * For integer fields, length is bytes occupied. - * For decimal fields, it is the total number of cyphers + * For decimal fields, it is the total number of cyphers. * * @param string $fieldName - * @return integer + * + * @return int */ public function getFieldLength($fieldName) { @@ -2697,14 +2741,16 @@ public function getFieldLength($fieldName) /** * Retrieves a bound query part. + * * @see bindQueryPart() * - * @param string $queryPart field interested - * @return string value of the bind + * @param string $queryPart field interested + * + * @return string value of the bind */ public function getBoundQueryPart($queryPart) { - if ( ! isset($this->_options['queryParts'][$queryPart])) { + if (!isset($this->_options['queryParts'][$queryPart])) { return null; } @@ -2712,10 +2758,9 @@ public function getBoundQueryPart($queryPart) } /** - * unshiftFilter + * unshiftFilter. * - * @param Doctrine_Record_Filter $filter - * @return Doctrine_Table this object (provides a fluent interface) + * @return Doctrine_Table this object (provides a fluent interface) */ public function unshiftFilter(Doctrine_Record_Filter $filter) { @@ -2729,7 +2774,7 @@ public function unshiftFilter(Doctrine_Record_Filter $filter) } /** - * getFilters + * getFilters. * * @return array $filters */ @@ -2752,14 +2797,17 @@ public function __toString() } /** - * Helper method for buildFindByWhere to decide if a string is greater than another + * Helper method for buildFindByWhere to decide if a string is greater than another. * * @param string $a * @param string $b */ private function isGreaterThan($a, $b) { - if (strlen($a) == strlen($b)) return 0; + if (strlen($a) == strlen($b)) { + return 0; + } + return (strlen($a) > strlen($b)) ? 1 : -1; } @@ -2784,7 +2832,7 @@ public function buildFindByWhere($fieldName) $fields = array_reverse(array_unique($fields)); // Identify fields and operators - preg_match_all('/(' . implode('|', $fields) . ')(Or|And)?/', $fieldName, $matches); + preg_match_all('/('.implode('|', $fields).')(Or|And)?/', $fieldName, $matches); $fieldsFound = $matches[1]; $operatorFound = $matches[2]; foreach ($operatorFound as &$v) { @@ -2792,9 +2840,9 @@ public function buildFindByWhere($fieldName) } // Check if $fieldName has unidentified parts left - if (strlen(implode('', $fieldsFound) . implode('', $operatorFound)) !== strlen($fieldName)) { - $expression = preg_replace('/(' . implode('|', $fields) . ')(Or|And)?/', '($1)$2', $fieldName); - throw new Doctrine_Table_Exception('Invalid expression found: ' . $expression); + if (strlen(implode('', $fieldsFound).implode('', $operatorFound)) !== strlen($fieldName)) { + $expression = preg_replace('/('.implode('|', $fields).')(Or|And)?/', '($1)$2', $fieldName); + throw new Doctrine_Table_Exception('Invalid expression found: '.$expression); } // Build result @@ -2803,22 +2851,22 @@ public function buildFindByWhere($fieldName) foreach ($fieldsFound as $index => $field) { $field = $this->_resolveFindByFieldName($field); if (!$field) { - throw new Doctrine_Table_Exception('Invalid field name to find by: ' . $field); + throw new Doctrine_Table_Exception('Invalid field name to find by: '.$field); } - if ($operatorFound[$index] == 'OR' && !$bracketOpen) { + if ('OR' == $operatorFound[$index] && !$bracketOpen) { $where .= '('; $bracketOpen = true; } - $where .= 'dctrn_find.' . $field . ' = ?'; + $where .= 'dctrn_find.'.$field.' = ?'; - if ($operatorFound[$index] != 'OR' && $lastOperator == 'OR') { + if ('OR' != $operatorFound[$index] && 'OR' == $lastOperator) { $where .= ')'; $bracketOpen = false; } - $where .= ' ' . strtoupper($operatorFound[$index]) . ' '; + $where .= ' '.strtoupper($operatorFound[$index]).' '; $lastOperator = $operatorFound[$index]; } @@ -2835,6 +2883,7 @@ public function buildFindByWhere($fieldName) * to get the column or field name. * * @param string $name + * * @return string $fieldName */ protected function _resolveFindByFieldName($name) @@ -2842,19 +2891,22 @@ protected function _resolveFindByFieldName($name) $fieldName = Doctrine_Inflector::tableize($name); if ($this->hasColumn($name) || $this->hasField($name)) { return $this->getFieldName($this->getColumnName($name)); - } else if ($this->hasColumn($fieldName) || $this->hasField($fieldName)) { + } + if ($this->hasColumn($fieldName) || $this->hasField($fieldName)) { return $this->getFieldName($this->getColumnName($fieldName)); - } else { - return false; } + + return false; } /** - * deletes table row(s) matching the specified identifier + * deletes table row(s) matching the specified identifier. + * + * @param mixed $identifier an associateve array containing identifier column-value pairs * - * @throws Doctrine_Connection_Exception if something went wrong at the database level - * @param mixed $identifier An associateve array containing identifier column-value pairs. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @return int the number of affected rows. Boolean false if empty value array was given, + * + * @throws Doctrine_Connection_Exception if something went wrong at the database level */ public function delete($identifier) { @@ -2864,9 +2916,10 @@ public function delete($identifier) /** * Inserts a table row with specified data. * - * @param array $fields An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param array $fields An associative array containing column-value pairs. + * Values can be strings or Doctrine_Expression instances. + * + * @return int the number of affected rows. Boolean false if empty value array was given, */ public function insert(array $fields) { @@ -2876,11 +2929,13 @@ public function insert(array $fields) /** * Updates table row(s) with specified data. * - * @throws Doctrine_Connection_Exception if something went wrong at the database level - * @param array $fields An associative array containing column-value pairs. - * Values can be strings or Doctrine_Expression instances. - * @param mixed $identifier An associateve array containing identifier column-value pairs. - * @return integer the number of affected rows. Boolean false if empty value array was given, + * @param array $fields An associative array containing column-value pairs. + * Values can be strings or Doctrine_Expression instances. + * @param mixed $identifier an associateve array containing identifier column-value pairs + * + * @return int the number of affected rows. Boolean false if empty value array was given, + * + * @throws Doctrine_Connection_Exception if something went wrong at the database level */ public function update(array $fields, $identifier) { @@ -2898,25 +2953,24 @@ public function update(array $fields, $identifier) * query isemulated through this method for other DBMS using standard types * of queries inside a transaction to assure the atomicity of the operation. * - * - * @param array $fields an associative array that describes the fields and the - * values that will be inserted or updated in the specified table. The - * indexes of the array are the names of all the fields of the table. + * @param array $fields an associative array that describes the fields and the + * values that will be inserted or updated in the specified table. The + * indexes of the array are the names of all the fields of the table. * * The values of the array are values to be assigned to the specified field. - * - * @param mixed $keys an array containing all key fields (primary key fields - * or unique index fields) for this table + * @param mixed $keys an array containing all key fields (primary key fields + * or unique index fields) for this table * * the uniqueness of a row will be determined according to * the provided key fields * * this method will fail if no key fields are specified * - * @throws Doctrine_Connection_Exception if this driver doesn't support replace - * @throws Doctrine_Connection_Exception if some of the key values was null - * @throws Doctrine_Connection_Exception if there were no key fields - * @throws PDOException if something fails at PDO level + * @throws Doctrine_Connection_Exception if this driver doesn't support replace + * @throws Doctrine_Connection_Exception if some of the key values was null + * @throws Doctrine_Connection_Exception if there were no key fields + * @throws PDOException if something fails at PDO level + * * @ return integer number of rows affected */ public function replace(array $fields, $keys) @@ -2937,54 +2991,55 @@ public function __call($method, $arguments) { $lcMethod = strtolower($method); - if (substr($lcMethod, 0, 6) == 'findby') { + if ('findby' == substr($lcMethod, 0, 6)) { $by = substr($method, 6, strlen($method)); $method = 'findBy'; - } else if (substr($lcMethod, 0, 9) == 'findoneby') { + } elseif ('findoneby' == substr($lcMethod, 0, 9)) { $by = substr($method, 9, strlen($method)); $method = 'findOneBy'; } if (isset($by)) { - if ( ! isset($arguments[0])) { - throw new Doctrine_Table_Exception('You must specify the value to ' . $method); + if (!isset($arguments[0])) { + throw new Doctrine_Table_Exception('You must specify the value to '.$method); } $fieldName = $this->_resolveFindByFieldName($by); $count = count(explode('Or', $by)) + (count(explode('And', $by)) - 1); - if (count($arguments) > $count) - { + if (count($arguments) > $count) { $hydrationMode = end($arguments); unset($arguments[count($arguments) - 1]); } else { $hydrationMode = null; } if ($this->hasField($fieldName)) { - return $this->$method($fieldName, $arguments[0], $hydrationMode); - } else if ($this->hasRelation($by)) { + return $this->{$method}($fieldName, $arguments[0], $hydrationMode); + } + if ($this->hasRelation($by)) { $relation = $this->getRelation($by); - if ($relation['type'] === Doctrine_Relation::MANY) { + if (Doctrine_Relation::MANY === $relation['type']) { throw new Doctrine_Table_Exception('Cannot findBy many relationship.'); } - return $this->$method($relation['local'], $arguments[0], $hydrationMode); - } else { - return $this->$method($by, $arguments, $hydrationMode); + return $this->{$method}($relation['local'], $arguments[0], $hydrationMode); } + + return $this->{$method}($by, $arguments, $hydrationMode); } // Forward the method on to the record instance and see if it has anything or one of its behaviors try { - return call_user_func_array(array($this->getRecordInstance(), $method . 'TableProxy'), $arguments); - } catch (Doctrine_Record_UnknownPropertyException $e) {} + return call_user_func_array(array($this->getRecordInstance(), $method.'TableProxy'), $arguments); + } catch (Doctrine_Record_UnknownPropertyException $e) { + } throw new Doctrine_Table_Exception(sprintf('Unknown method %s::%s', get_class($this), $method)); } /** * serialize - * this method is automatically called when an instance of Doctrine_Record is serialized + * this method is automatically called when an instance of Doctrine_Record is serialized. * * @return string */ @@ -2996,10 +3051,9 @@ public function serialize() } /** - * this method is automatically called everytime an instance is unserialized + * this method is automatically called everytime an instance is unserialized. * - * @param string $serialized Doctrine_Record as serialized string - * @return void + * @param string $serialized Doctrine_Record as serialized string */ public function unserialize($serialized) { @@ -3008,14 +3062,13 @@ public function unserialize($serialized) $this->__unserialize($data); } - /** - * Serializes the current instance for php 7.4+ + * Serializes the current instance for php 7.4+. * * @return array */ - public function __serialize() { - + public function __serialize() + { $options = $this->_options; unset($options['declaringClass']); @@ -3035,12 +3088,12 @@ public function __serialize() { } /** - * Unserializes a Doctrine_Record instance for php 7.4+ + * Unserializes a Doctrine_Record instance for php 7.4+. * * @param array $data */ - public function __unserialize($data) { - + public function __unserialize($data) + { $this->_identifier = $data[0]; $this->_identifierType = $data[1]; $this->_columns = $data[2]; @@ -3056,7 +3109,6 @@ public function __unserialize($data) { /** * Creates new instance and initialize it from cache. - * */ public function initializeFromCache(Doctrine_Connection $conn) { @@ -3066,8 +3118,8 @@ public function initializeFromCache(Doctrine_Connection $conn) $this->_parser = new Doctrine_Relation_Parser($this); $name = $this->_options['name']; - if ( ! class_exists($name) || empty($name)) { - throw new Doctrine_Exception("Couldn't find class " . $name); + if (!class_exists($name) || empty($name)) { + throw new Doctrine_Exception("Couldn't find class ".$name); } $record = new $name($this); @@ -3075,20 +3127,19 @@ public function initializeFromCache(Doctrine_Connection $conn) // get parent classes do { - if ($class === 'Doctrine_Record') { + if ('Doctrine_Record' === $class) { break; } } while ($class = get_parent_class($class)); - if ($class === false) { - throw new Doctrine_Table_Exception('Class "' . $name . '" must be a child class of Doctrine_Record'); + if (false === $class) { + throw new Doctrine_Table_Exception('Class "'.$name.'" must be a child class of Doctrine_Record'); } if (method_exists($record, 'setTableDefinition')) { // get the declaring class of setTableDefinition method $method = new ReflectionMethod($this->_options['name'], 'setTableDefinition'); $class = $method->getDeclaringClass(); - } else { $class = new ReflectionClass($class); } @@ -3104,7 +3155,7 @@ public function initializeFromCache(Doctrine_Connection $conn) $this->getTree()->setUp(); } - $this->_filters[] = new Doctrine_Record_Filter_Standard(); + $this->_filters[] = new Doctrine_Record_Filter_Standard(); if ($this->getAttribute(Doctrine_Core::ATTR_USE_TABLE_REPOSITORY)) { $this->_repository = new Doctrine_Table_Repository($this); } else { diff --git a/lib/Doctrine/Table/Exception.php b/lib/Doctrine/Table/Exception.php index a12d39226..812cbd5be 100644 --- a/lib/Doctrine/Table/Exception.php +++ b/lib/Doctrine/Table/Exception.php @@ -21,21 +21,23 @@ /** * thrown when user tries to initialize a new instance of Doctrine_Table, - * while there already exists an instance of that table + * while there already exists an instance of that table. * - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Table_Exception extends Doctrine_Exception { public function __construct($message = "Couldn't initialize table. One instance of this table already exists. Always use Doctrine_Session::getTable(\$name) - to get on instance of a Doctrine_Table.") { + to get on instance of a Doctrine_Table.") + { parent::__construct($message); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Table/Repository.php b/lib/Doctrine/Table/Repository.php index 715160434..7a22fbf99 100644 --- a/lib/Doctrine/Table/Repository.php +++ b/lib/Doctrine/Table/Repository.php @@ -22,34 +22,32 @@ /** * Doctrine_Repository * each record is added into Doctrine_Repository at the same time they are created, - * loaded from the database or retrieved from the cache + * loaded from the database or retrieved from the cache. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Table_Repository implements Countable, IteratorAggregate { /** - * @var object Doctrine_Table $table + * @var object Doctrine_Table */ private $table; /** - * @var array $registry - * an array of all records - * keys representing record object identifiers + * @var array + * an array of all records + * keys representing record object identifiers */ private $registry = array(); /** - * constructor - * - * @param Doctrine_Table $table + * constructor. */ public function __construct(Doctrine_Table $table) { @@ -57,7 +55,7 @@ public function __construct(Doctrine_Table $table) } /** - * getTable + * getTable. * * @return Doctrine_Table */ @@ -67,10 +65,11 @@ public function getTable() } /** - * add + * add. + * + * @param Doctrine_Record $record record to be added into registry * - * @param Doctrine_Record $record record to be added into registry - * @return boolean + * @return bool */ public function add(Doctrine_Record $record) { @@ -85,69 +84,78 @@ public function add(Doctrine_Record $record) } /** - * get - * @param integer $oid + * get. + * + * @param int $oid + * * @throws Doctrine_Table_Repository_Exception */ public function get($oid) { - if ( ! isset($this->registry[$oid])) { - throw new Doctrine_Table_Repository_Exception("Unknown object identifier"); + if (!isset($this->registry[$oid])) { + throw new Doctrine_Table_Repository_Exception('Unknown object identifier'); } + return $this->registry[$oid]; } /** * count - * Doctrine_Registry implements interface Countable - * @return integer the number of records this registry has + * Doctrine_Registry implements interface Countable. + * + * @return int the number of records this registry has */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->registry); } /** - * @param integer $oid object identifier - * @return boolean whether ot not the operation was successful + * @param int $oid object identifier + * + * @return bool whether ot not the operation was successful */ public function evict($oid) { - if ( ! isset($this->registry[$oid])) { + if (!isset($this->registry[$oid])) { return false; } unset($this->registry[$oid]); + return true; } /** - * @return integer number of records evicted + * @return int number of records evicted */ public function evictAll() { $evicted = 0; - foreach ($this->registry as $oid=>$record) { + foreach ($this->registry as $oid => $record) { if ($this->evict($oid)) { - $evicted++; + ++$evicted; } } + return $evicted; } /** - * getIterator + * getIterator. + * * @return ArrayIterator */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->registry); } /** - * contains - * @param integer $oid object identifier + * contains. + * + * @param int $oid object identifier */ public function contains($oid) { @@ -155,8 +163,7 @@ public function contains($oid) } /** - * loadAll - * @return void + * loadAll. */ public function loadAll() { diff --git a/lib/Doctrine/Table/Repository/Exception.php b/lib/Doctrine/Table/Repository/Exception.php index 8e433ff13..d18c58bed 100644 --- a/lib/Doctrine/Table/Repository/Exception.php +++ b/lib/Doctrine/Table/Repository/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Table_Repository_Exception + * Doctrine_Table_Repository_Exception. * - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Table_Repository_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Table/Repository/None.php b/lib/Doctrine/Table/Repository/None.php index fe651cae6..fc20cb80a 100644 --- a/lib/Doctrine/Table/Repository/None.php +++ b/lib/Doctrine/Table/Repository/None.php @@ -22,23 +22,24 @@ /** * Doctrine_Repository * each record is added into Doctrine_Repository at the same time they are created, - * loaded from the database or retrieved from the cache + * loaded from the database or retrieved from the cache. * * @author Jérôme Macias - * @package Doctrine - * @subpackage Table * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 115 $ */ class Doctrine_Table_Repository_None extends Doctrine_Table_Repository implements Countable, IteratorAggregate { /** - * add + * add. + * + * @param Doctrine_Record $record record to be added into registry * - * @param Doctrine_Record $record record to be added into registry - * @return boolean + * @return bool */ public function add(Doctrine_Record $record) { @@ -46,33 +47,35 @@ public function add(Doctrine_Record $record) } /** - * get + * get. + * + * @param int $oid * - * @param integer $oid * @throws Doctrine_Table_Repository_Exception */ public function get($oid) { - throw new Doctrine_Table_Repository_Exception("Unknown object identifier"); + throw new Doctrine_Table_Repository_Exception('Unknown object identifier'); } /** * count - * Doctrine_Registry implements interface Countable + * Doctrine_Registry implements interface Countable. * - * @return integer the number of records this registry has + * @return int the number of records this registry has */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return 0; } /** - * evict + * evict. + * + * @param int $oid object identifier * - * @param integer $oid object identifier - * @return boolean whether ot not the operation was successful + * @return bool whether ot not the operation was successful */ public function evict($oid) { @@ -80,9 +83,9 @@ public function evict($oid) } /** - * evictAll + * evictAll. * - * @return integer number of records evicted + * @return int number of records evicted */ public function evictAll() { diff --git a/lib/Doctrine/Task.php b/lib/Doctrine/Task.php index 3a9311c07..9d1c8f9b4 100644 --- a/lib/Doctrine/Task.php +++ b/lib/Doctrine/Task.php @@ -20,34 +20,36 @@ */ /** - * Doctrine_Task - * + * Doctrine_Task. + * * Abstract class used for writing Doctrine Tasks * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ abstract class Doctrine_Task { - public $dispatcher = null, - $taskName = null, /*Treat as protected*/ - $description = null, - $arguments = array(), - $requiredArguments = array(), - $optionalArguments = array(); + public $dispatcher; + public $taskName; + public /* Treat as protected */ + $description; + public $arguments = array(); + public $requiredArguments = array(); + public $optionalArguments = array(); /** - * __construct + * __construct. * * Since this is an abstract classes that extend this must follow a patter of Doctrine_Task_{TASK_NAME} * This is what determines the task name for executing it. * - * @return void + * @param mixed|null $dispatcher */ public function __construct($dispatcher = null) { @@ -55,7 +57,7 @@ public function __construct($dispatcher = null) $taskName = (string) $this->getTaskName(); - //Derive the task name only if it wasn't entered at design-time + // Derive the task name only if it wasn't entered at design-time if ('' === trim($taskName)) { $taskName = self::deriveTaskName(get_class($this)); } @@ -68,14 +70,15 @@ public function __construct($dispatcher = null) } /** - * Returns the name of the task the specified class _would_ implement - * + * Returns the name of the task the specified class _would_ implement. + * * N.B. This method does not check if the specified class is actually a Doctrine Task - * + * * This is public so we can easily test its reactions to fully-qualified class names, without having to add * PHP 5.3-specific test code - * + * * @param string $className + * * @return string|bool */ public static function deriveTaskName($className) @@ -83,8 +86,8 @@ public static function deriveTaskName($className) $nameParts = explode('\\', $className); foreach ($nameParts as &$namePart) { - $prefix = __CLASS__ . '_'; - $baseName = strpos($namePart, $prefix) === 0 ? substr($namePart, strlen($prefix)) : $namePart; + $prefix = __CLASS__.'_'; + $baseName = 0 === strpos($namePart, $prefix) ? substr($namePart, strlen($prefix)) : $namePart; $namePart = str_replace('_', '-', Doctrine_Inflector::tableize($baseName)); } @@ -92,52 +95,45 @@ public static function deriveTaskName($className) } /** - * notify + * notify. * - * @param string $notification - * @return void + * @param string $notification */ public function notify($notification = null) { if (is_object($this->dispatcher) && method_exists($this->dispatcher, 'notify')) { $args = func_get_args(); - + return call_user_func_array(array($this->dispatcher, 'notify'), $args); - } else if ( $notification !== null ) { + } + if (null !== $notification) { return $notification; - } else { - return false; } + + return false; } /** - * ask - * - * @return void + * ask. */ public function ask() { $args = func_get_args(); - + call_user_func_array(array($this, 'notify'), $args); - - $answer = strtolower(trim(fgets(STDIN))); - - return $answer; + + return strtolower(trim(fgets(STDIN))); } /** - * execute + * execute. * * Override with each task class - * - * @return void - * @abstract */ - abstract function execute(); + abstract public function execute(); /** - * validate + * validate. * * Validates that all required fields are present * @@ -146,22 +142,21 @@ abstract function execute(); public function validate() { $requiredArguments = $this->getRequiredArguments(); - + foreach ($requiredArguments as $arg) { - if ( ! isset($this->arguments[$arg])) { + if (!isset($this->arguments[$arg])) { return false; } } - + return true; } /** - * addArgument + * addArgument. * - * @param string $name - * @param string $value - * @return void + * @param string $name + * @param string $value */ public function addArgument($name, $value) { @@ -169,23 +164,22 @@ public function addArgument($name, $value) } /** - * getArgument + * getArgument. * - * @param string $name - * @param string $default - * @return mixed + * @param string $name + * @param string $default */ public function getArgument($name, $default = null) { - if (isset($this->arguments[$name]) && $this->arguments[$name] !== null) { + if (isset($this->arguments[$name]) && null !== $this->arguments[$name]) { return $this->arguments[$name]; - } else { - return $default; } + + return $default; } /** - * getArguments + * getArguments. * * @return array $arguments */ @@ -195,10 +189,7 @@ public function getArguments() } /** - * setArguments - * - * @param array $args - * @return void + * setArguments. */ public function setArguments(array $args) { @@ -206,9 +197,10 @@ public function setArguments(array $args) } /** - * Returns TRUE if the specified task name is valid, or FALSE otherwise - * + * Returns TRUE if the specified task name is valid, or FALSE otherwise. + * * @param string $taskName + * * @return bool */ protected static function validateTaskName($taskName) @@ -221,24 +213,23 @@ protected static function validateTaskName($taskName) } /** - * Sets the name of the task, the name that's used to invoke it through a CLI + * Sets the name of the task, the name that's used to invoke it through a CLI. * * @param string $taskName + * * @throws InvalidArgumentException If the task name is invalid */ protected function setTaskName($taskName) { - if (! self::validateTaskName($taskName)) { - throw new InvalidArgumentException( - sprintf('The task name "%s", in %s, is invalid', $taskName, get_class($this)) - ); + if (!self::validateTaskName($taskName)) { + throw new InvalidArgumentException(sprintf('The task name "%s", in %s, is invalid', $taskName, get_class($this))); } $this->taskName = $taskName; } /** - * getTaskName + * getTaskName. * * @return string $taskName */ @@ -248,7 +239,7 @@ public function getTaskName() } /** - * getDescription + * getDescription. * * @return string $description */ @@ -258,7 +249,7 @@ public function getDescription() } /** - * getRequiredArguments + * getRequiredArguments. * * @return array $requiredArguments */ @@ -268,7 +259,7 @@ public function getRequiredArguments() } /** - * getOptionalArguments + * getOptionalArguments. * * @return array $optionalArguments */ @@ -278,7 +269,7 @@ public function getOptionalArguments() } /** - * getRequiredArgumentsDescriptions + * getRequiredArgumentsDescriptions. * * @return array $requiredArgumentsDescriptions */ @@ -288,7 +279,7 @@ public function getRequiredArgumentsDescriptions() } /** - * getOptionalArgumentsDescriptions + * getOptionalArgumentsDescriptions. * * @return array $optionalArgumentsDescriptions */ @@ -296,4 +287,4 @@ public function getOptionalArgumentsDescriptions() { return $this->optionalArguments; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/BuildAll.php b/lib/Doctrine/Task/BuildAll.php index 07d07e216..1219c4596 100644 --- a/lib/Doctrine/Task/BuildAll.php +++ b/lib/Doctrine/Task/BuildAll.php @@ -20,47 +20,50 @@ */ /** - * Doctrine_Task_BuildAll + * Doctrine_Task_BuildAll. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_BuildAll extends Doctrine_Task { - public $description = 'Calls generate-models-from-yaml, create-db, and create-tables', - $requiredArguments = array(), - $optionalArguments = array(); - - protected $models, - $createDb, - $tables; - + public $description = 'Calls generate-models-from-yaml, create-db, and create-tables'; + public $requiredArguments = array(); + public $optionalArguments = array(); + + protected $models; + + protected $createDb; + + protected $tables; + public function __construct($dispatcher = null) { parent::__construct($dispatcher); - + $this->models = new Doctrine_Task_GenerateModelsYaml($this->dispatcher); $this->createDb = new Doctrine_Task_CreateDb($this->dispatcher); $this->tables = new Doctrine_Task_CreateTables($this->dispatcher); - + $this->requiredArguments = array_merge($this->requiredArguments, $this->models->requiredArguments, $this->createDb->requiredArguments, $this->tables->requiredArguments); $this->optionalArguments = array_merge($this->optionalArguments, $this->models->optionalArguments, $this->createDb->optionalArguments, $this->tables->optionalArguments); } - + public function execute() { $this->models->setArguments($this->getArguments()); $this->models->execute(); - + $this->createDb->setArguments($this->getArguments()); $this->createDb->execute(); - + $this->tables->setArguments($this->getArguments()); $this->tables->execute(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/BuildAllLoad.php b/lib/Doctrine/Task/BuildAllLoad.php index 90e685a01..b9c6c9c24 100644 --- a/lib/Doctrine/Task/BuildAllLoad.php +++ b/lib/Doctrine/Task/BuildAllLoad.php @@ -20,42 +20,43 @@ */ /** - * Doctrine_Task_BuildAllLoad + * Doctrine_Task_BuildAllLoad. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_BuildAllLoad extends Doctrine_Task { - public $description = 'Calls build-all, and load-data', - $requiredArguments = array(), - $optionalArguments = array(); + public $description = 'Calls build-all, and load-data'; + public $requiredArguments = array(); + public $optionalArguments = array(); + + protected $buildAll; + protected $loadData; - protected $buildAll, - $loadData; - public function __construct($dispatcher = null) { parent::__construct($dispatcher); $this->buildAll = new Doctrine_Task_BuildAll($this->dispatcher); $this->loadData = new Doctrine_Task_LoadData($this->dispatcher); - + $this->requiredArguments = array_merge($this->requiredArguments, $this->buildAll->requiredArguments, $this->loadData->requiredArguments); $this->optionalArguments = array_merge($this->optionalArguments, $this->buildAll->optionalArguments, $this->loadData->optionalArguments); } - + public function execute() { $this->buildAll->setArguments($this->getArguments()); $this->buildAll->execute(); - + $this->loadData->setArguments($this->getArguments()); $this->loadData->execute(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/BuildAllReload.php b/lib/Doctrine/Task/BuildAllReload.php index 1cd3c1aba..2a1c3b769 100644 --- a/lib/Doctrine/Task/BuildAllReload.php +++ b/lib/Doctrine/Task/BuildAllReload.php @@ -20,42 +20,43 @@ */ /** - * Doctrine_Task_BuildAllReload + * Doctrine_Task_BuildAllReload. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_BuildAllReload extends Doctrine_Task { - public $description = 'Calls rebuild-db and load-data', - $requiredArguments = array(), - $optionalArguments = array(); + public $description = 'Calls rebuild-db and load-data'; + public $requiredArguments = array(); + public $optionalArguments = array(); + + protected $rebuildDb; + protected $loadData; - protected $rebuildDb, - $loadData; - public function __construct($dispatcher = null) { parent::__construct($dispatcher); $this->rebuildDb = new Doctrine_Task_RebuildDb($this->dispatcher); $this->loadData = new Doctrine_Task_LoadData($this->dispatcher); - + $this->requiredArguments = array_merge($this->requiredArguments, $this->rebuildDb->requiredArguments, $this->loadData->requiredArguments); $this->optionalArguments = array_merge($this->optionalArguments, $this->rebuildDb->optionalArguments, $this->loadData->optionalArguments); } - + public function execute() { $this->rebuildDb->setArguments($this->getArguments()); $this->rebuildDb->execute(); - + $this->loadData->setArguments($this->getArguments()); $this->loadData->execute(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/Compile.php b/lib/Doctrine/Task/Compile.php index d958d9d7d..d75a56bff 100644 --- a/lib/Doctrine/Task/Compile.php +++ b/lib/Doctrine/Task/Compile.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Task_Compile + * Doctrine_Task_Compile. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_Compile extends Doctrine_Task { - public $description = 'Compile doctrine classes in to one single php file', - $requiredArguments = array(), - $optionalArguments = array('drivers' => 'Specify list of drivers you wish to compile. Ex: mysql|mssql|sqlite', - 'compiled_path' => 'The path where you want to write the compiled doctrine libs.'); - + public $description = 'Compile doctrine classes in to one single php file'; + public $requiredArguments = array(); + public $optionalArguments = array('drivers' => 'Specify list of drivers you wish to compile. Ex: mysql|mssql|sqlite', + 'compiled_path' => 'The path where you want to write the compiled doctrine libs.'); + public function execute() { $compiledPath = Doctrine_Core::compile($this->getArgument('compiled_path'), $this->getArgument('drivers', array())); - - $this->notify('Compiled Doctrine successfully to: ' . $compiledPath); + + $this->notify('Compiled Doctrine successfully to: '.$compiledPath); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/CreateDb.php b/lib/Doctrine/Task/CreateDb.php index 475f04051..9ec74ef32 100644 --- a/lib/Doctrine/Task/CreateDb.php +++ b/lib/Doctrine/Task/CreateDb.php @@ -20,31 +20,32 @@ */ /** - * Doctrine_Task_CreateDb + * Doctrine_Task_CreateDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_CreateDb extends Doctrine_Task { - public $description = 'Create all databases for your connections. If the database already exists, nothing happens.', - $optionalArguments = array(); - + public $description = 'Create all databases for your connections. If the database already exists, nothing happens.'; + public $optionalArguments = array(); + public function execute() { $manager = Doctrine_Manager::getInstance(); foreach ($manager as $name => $connection) { try { $connection->createDatabase(); - $this->notify("Successfully created database for connection named '" . $name . "'"); + $this->notify("Successfully created database for connection named '".$name."'"); } catch (Exception $e) { $this->notify($e->getMessage()); } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/CreateTables.php b/lib/Doctrine/Task/CreateTables.php index 649489c24..52adce9cf 100644 --- a/lib/Doctrine/Task/CreateTables.php +++ b/lib/Doctrine/Task/CreateTables.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_Task_CreateTables + * Doctrine_Task_CreateTables. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_CreateTables extends Doctrine_Task { - public $description = 'Create tables for all existing database connections. If table exists nothing happens.', - $requiredArguments = array('models_path' => 'Specify path to your models directory.'), - $optionalArguments = array(); - + public $description = 'Create tables for all existing database connections. If table exists nothing happens.'; + public $requiredArguments = array('models_path' => 'Specify path to your models directory.'); + public $optionalArguments = array(); + public function execute() { Doctrine_Core::createTablesFromModels($this->getArgument('models_path')); - + $this->notify('Created tables successfully'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/Dql.php b/lib/Doctrine/Task/Dql.php index b85c70df0..71e463521 100644 --- a/lib/Doctrine/Task/Dql.php +++ b/lib/Doctrine/Task/Dql.php @@ -20,22 +20,23 @@ */ /** - * Doctrine_Task_Dql + * Doctrine_Task_Dql. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_Dql extends Doctrine_Task { - public $description = 'Execute dql query and display the results', - $requiredArguments = array('models_path' => 'Specify path to your Doctrine_Record definitions.', - 'dql_query' => 'Specify the complete dql query to execute.'), - $optionalArguments = array('params' => 'Comma separated list of the params to replace the ? tokens in the dql'); + public $description = 'Execute dql query and display the results'; + public $requiredArguments = array('models_path' => 'Specify path to your Doctrine_Record definitions.', + 'dql_query' => 'Specify the complete dql query to execute.'); + public $optionalArguments = array('params' => 'Comma separated list of the params to replace the ? tokens in the dql'); public function execute() { @@ -46,9 +47,9 @@ public function execute() $query = Doctrine_Query::create(); $params = $this->getArgument('params'); - $params = $params ? explode(',', $params):array(); + $params = $params ? explode(',', $params) : array(); - $this->notify('executing: "' . $dql . '" (' . implode(', ', $params) . ')'); + $this->notify('executing: "'.$dql.'" ('.implode(', ', $params).')'); $results = $query->query($dql, $params, Doctrine_Core::HYDRATE_ARRAY); @@ -70,4 +71,4 @@ protected function _printResults($array) } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/DropDb.php b/lib/Doctrine/Task/DropDb.php index c2c07adc1..d9997d524 100644 --- a/lib/Doctrine/Task/DropDb.php +++ b/lib/Doctrine/Task/DropDb.php @@ -20,28 +20,29 @@ */ /** - * Doctrine_Task_DropDb + * Doctrine_Task_DropDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_DropDb extends Doctrine_Task { - public $description = 'Drop database for all existing connections', - $requiredArguments = array(), - $optionalArguments = array('force' => 'Whether or not to force the drop database task'); + public $description = 'Drop database for all existing connections'; + public $requiredArguments = array(); + public $optionalArguments = array('force' => 'Whether or not to force the drop database task'); public function execute() { - if ( ! $this->getArgument('force')) { + if (!$this->getArgument('force')) { $answer = $this->ask('Are you sure you wish to drop your databases? (y/n)'); - if ($answer != 'y') { + if ('y' != $answer) { $this->notify('Successfully cancelled'); return; @@ -52,10 +53,10 @@ public function execute() foreach ($manager as $name => $connection) { try { $connection->dropDatabase(); - $this->notify("Successfully dropped database for connection named '" . $name . "'"); + $this->notify("Successfully dropped database for connection named '".$name."'"); } catch (Exception $e) { $this->notify($e->getMessage()); } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/DumpData.php b/lib/Doctrine/Task/DumpData.php index 7b6add9f7..45fb11d66 100644 --- a/lib/Doctrine/Task/DumpData.php +++ b/lib/Doctrine/Task/DumpData.php @@ -20,29 +20,30 @@ */ /** - * Doctrine_Task_DumpData + * Doctrine_Task_DumpData. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_DumpData extends Doctrine_Task { - public $description = 'Dump data to a yaml data fixture file.', - $requiredArguments = array('data_fixtures_path' => 'Specify path to write the yaml data fixtures file to.', - 'models_path' => 'Specify path to your Doctrine_Record definitions.'), - $optionalArguments = array(); + public $description = 'Dump data to a yaml data fixture file.'; + public $requiredArguments = array('data_fixtures_path' => 'Specify path to write the yaml data fixtures file to.', + 'models_path' => 'Specify path to your Doctrine_Record definitions.'); + public $optionalArguments = array(); public function execute() { - $models = Doctrine_Core::loadModels($this->getArgument('models_path')); + $models = Doctrine_Core::loadModels($this->getArgument('models_path')); - if (empty($models)) { - throw new Doctrine_Task_Exception('No models were loaded'); + if (empty($models)) { + throw new Doctrine_Task_Exception('No models were loaded'); } $path = $this->getArgument('data_fixtures_path'); @@ -51,7 +52,7 @@ public function execute() $path = $path[0]; } - if ( ! empty($path)) { + if (!empty($path)) { Doctrine_Core::dumpData($path); $this->notify(sprintf('Dumped data successfully to: %s', $path)); @@ -59,4 +60,4 @@ public function execute() throw new Doctrine_Task_Exception('Unable to find data fixtures path.'); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/Exception.php b/lib/Doctrine/Task/Exception.php index a04890f85..cc315be4e 100644 --- a/lib/Doctrine/Task/Exception.php +++ b/lib/Doctrine/Task/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Task_Exception + * Doctrine_Task_Exception. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Task/GenerateMigration.php b/lib/Doctrine/Task/GenerateMigration.php index 40be329d6..c720d5f76 100644 --- a/lib/Doctrine/Task/GenerateMigration.php +++ b/lib/Doctrine/Task/GenerateMigration.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Task_GenerateMigration + * Doctrine_Task_GenerateMigration. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateMigration extends Doctrine_Task { - public $description = 'Generate new migration class definition', - $requiredArguments = array('class_name' => 'Name of the migration class to generate', - 'migrations_path' => 'Specify the complete path to your migration classes folder.'), - $optionalArguments = array(); - + public $description = 'Generate new migration class definition'; + public $requiredArguments = array('class_name' => 'Name of the migration class to generate', + 'migrations_path' => 'Specify the complete path to your migration classes folder.'); + public $optionalArguments = array(); + public function execute() { Doctrine_Core::generateMigrationClass($this->getArgument('class_name'), $this->getArgument('migrations_path')); - + $this->notify(sprintf('Generated migration class: %s successfully to %s', $this->getArgument('class_name'), $this->getArgument('migrations_path'))); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateMigrationsDb.php b/lib/Doctrine/Task/GenerateMigrationsDb.php index 98ca86173..982f78948 100644 --- a/lib/Doctrine/Task/GenerateMigrationsDb.php +++ b/lib/Doctrine/Task/GenerateMigrationsDb.php @@ -20,22 +20,23 @@ */ /** - * Doctrine_Task_GenerateMigrationsDb + * Doctrine_Task_GenerateMigrationsDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateMigrationsDb extends Doctrine_Task { - public $description = 'Generate migration classes for an existing database', - $requiredArguments = array('migrations_path' => 'Specify the complete path to your migration classes folder.'), - $optionalArguments = array(); - + public $description = 'Generate migration classes for an existing database'; + public $requiredArguments = array('migrations_path' => 'Specify the complete path to your migration classes folder.'); + public $optionalArguments = array(); + public function execute() { try { @@ -43,7 +44,7 @@ public function execute() $yamlSchemaPath = $this->getArgument('yaml_schema_path'); $migration = new Doctrine_Migration($migrationsPath); $result1 = false; - if ( ! count($migration->getMigrationClasses())) { + if (!count($migration->getMigrationClasses())) { $result1 = Doctrine_Core::generateMigrationsFromDb($migrationsPath); } $connections = array(); @@ -52,14 +53,13 @@ public function execute() } $changes = Doctrine_Core::generateMigrationsFromDiff($migrationsPath, $connections, $yamlSchemaPath); $numChanges = count($changes, true) - count($changes); - $result = ($result1 || $numChanges) ? true:false; + $result = ($result1 || $numChanges) ? true : false; } catch (Exception $e) { $result = false; } - if ( ! $result) { + if (!$result) { throw new Doctrine_Task_Exception('Could not generate migration classes from database'); - } else { - $this->notify('Generated migration classes successfully from database'); } + $this->notify('Generated migration classes successfully from database'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateMigrationsDiff.php b/lib/Doctrine/Task/GenerateMigrationsDiff.php index ac92aa685..083fe649e 100644 --- a/lib/Doctrine/Task/GenerateMigrationsDiff.php +++ b/lib/Doctrine/Task/GenerateMigrationsDiff.php @@ -20,25 +20,26 @@ */ /** - * Doctrine_Task_GenerateMigrationsDiff + * Doctrine_Task_GenerateMigrationsDiff. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateMigrationsDiff extends Doctrine_Task { - public $description = 'Generate migration classes from a generated difference between your models and yaml schema files', - $requiredArguments = array('migrations_path' => 'Specify the path to your migration classes folder.', - 'yaml_schema_path' => 'Specify the path to your yaml schema files folder.'), - $optionalArguments = array('models_path' => 'Specify the path to your doctrine models folder.'); + public $description = 'Generate migration classes from a generated difference between your models and yaml schema files'; + public $requiredArguments = array('migrations_path' => 'Specify the path to your migration classes folder.', + 'yaml_schema_path' => 'Specify the path to your yaml schema files folder.'); + public $optionalArguments = array('models_path' => 'Specify the path to your doctrine models folder.'); public function execute() - { + { $migrationsPath = $this->getArgument('migrations_path'); $modelsPath = $this->getArgument('models_path'); $yamlSchemaPath = $this->getArgument('yaml_schema_path'); @@ -49,10 +50,9 @@ public function execute() $numChanges = count($changes, true) - count($changes); - if ( ! $numChanges) { + if (!$numChanges) { throw new Doctrine_Task_Exception('Could not generate migration classes from difference'); - } else { - $this->notify('Generated migration classes successfully from difference'); } + $this->notify('Generated migration classes successfully from difference'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateMigrationsModels.php b/lib/Doctrine/Task/GenerateMigrationsModels.php index 7a462356c..8ff14cf05 100644 --- a/lib/Doctrine/Task/GenerateMigrationsModels.php +++ b/lib/Doctrine/Task/GenerateMigrationsModels.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Task_GenerateMigrationsModels + * Doctrine_Task_GenerateMigrationsModels. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateMigrationsModels extends Doctrine_Task { - public $description = 'Generate migration classes for an existing set of models', - $requiredArguments = array('migrations_path' => 'Specify the path to your migration classes folder.', - 'models_path' => 'Specify the path to your doctrine models folder.'), - $optionalArguments = array(); - + public $description = 'Generate migration classes for an existing set of models'; + public $requiredArguments = array('migrations_path' => 'Specify the path to your migration classes folder.', + 'models_path' => 'Specify the path to your doctrine models folder.'); + public $optionalArguments = array(); + public function execute() - { + { Doctrine_Core::generateMigrationsFromModels($this->getArgument('migrations_path'), $this->getArgument('models_path')); - + $this->notify('Generated migration classes successfully from models'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateModelsDb.php b/lib/Doctrine/Task/GenerateModelsDb.php index af59c4f35..eb545b019 100644 --- a/lib/Doctrine/Task/GenerateModelsDb.php +++ b/lib/Doctrine/Task/GenerateModelsDb.php @@ -20,22 +20,23 @@ */ /** - * Doctrine_Task_GenerateModelsDb + * Doctrine_Task_GenerateModelsDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateModelsDb extends Doctrine_Task { - public $description = 'Generates your Doctrine_Record definitions from your existing database connections.', - $requiredArguments = array('models_path' => 'Specify path to your Doctrine_Record definitions.'), - $optionalArguments = array('connection' => 'Optionally specify a single connection to generate the models for.'); - + public $description = 'Generates your Doctrine_Record definitions from your existing database connections.'; + public $requiredArguments = array('models_path' => 'Specify path to your Doctrine_Record definitions.'); + public $optionalArguments = array('connection' => 'Optionally specify a single connection to generate the models for.'); + public function execute() { $configs = $this->dispatcher->getConfig(); diff --git a/lib/Doctrine/Task/GenerateModelsYaml.php b/lib/Doctrine/Task/GenerateModelsYaml.php index 2bd82b1c1..7411c3f97 100644 --- a/lib/Doctrine/Task/GenerateModelsYaml.php +++ b/lib/Doctrine/Task/GenerateModelsYaml.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Task_GenerateModelsYaml + * Doctrine_Task_GenerateModelsYaml. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateModelsYaml extends Doctrine_Task { - public $description = 'Generates your Doctrine_Record definitions from a Yaml schema file', - $requiredArguments = array('yaml_schema_path' => 'Specify the complete directory path to your yaml schema files.', - 'models_path' => 'Specify complete path to your Doctrine_Record definitions.'), - $optionalArguments = array('generate_models_options' => 'Array of options for generating models'); - + public $description = 'Generates your Doctrine_Record definitions from a Yaml schema file'; + public $requiredArguments = array('yaml_schema_path' => 'Specify the complete directory path to your yaml schema files.', + 'models_path' => 'Specify complete path to your Doctrine_Record definitions.'); + public $optionalArguments = array('generate_models_options' => 'Array of options for generating models'); + public function execute() { Doctrine_Core::generateModelsFromYaml($this->getArgument('yaml_schema_path'), $this->getArgument('models_path'), $this->getArgument('generate_models_options', array())); - + $this->notify('Generated models successfully from YAML schema'); } } diff --git a/lib/Doctrine/Task/GenerateSql.php b/lib/Doctrine/Task/GenerateSql.php index be2a002d4..ce0068d77 100644 --- a/lib/Doctrine/Task/GenerateSql.php +++ b/lib/Doctrine/Task/GenerateSql.php @@ -20,37 +20,38 @@ */ /** - * Doctrine_Task_GenerateSql + * Doctrine_Task_GenerateSql. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateSql extends Doctrine_Task { - public $description = 'Generate sql for all existing database connections.', - $requiredArguments = array('models_path' => 'Specify complete path to your Doctrine_Record definitions.', - 'sql_path' => 'Path to write the generated sql.'), - $optionalArguments = array(); - + public $description = 'Generate sql for all existing database connections.'; + public $requiredArguments = array('models_path' => 'Specify complete path to your Doctrine_Record definitions.', + 'sql_path' => 'Path to write the generated sql.'); + public $optionalArguments = array(); + public function execute() { if (is_dir($this->getArgument('sql_path'))) { - $path = $this->getArgument('sql_path') . DIRECTORY_SEPARATOR . 'schema.sql'; - } else if (is_file($this->getArgument('sql_path'))) { + $path = $this->getArgument('sql_path').DIRECTORY_SEPARATOR.'schema.sql'; + } elseif (is_file($this->getArgument('sql_path'))) { $path = $this->getArgument('sql_path'); } else { throw new Doctrine_Task_Exception('Invalid sql path.'); } - + $sql = Doctrine_Core::generateSqlFromModels($this->getArgument('models_path')); - + file_put_contents($path, $sql); - + $this->notify('Generated SQL successfully for models'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateYamlDb.php b/lib/Doctrine/Task/GenerateYamlDb.php index 2da50293a..92248c85f 100644 --- a/lib/Doctrine/Task/GenerateYamlDb.php +++ b/lib/Doctrine/Task/GenerateYamlDb.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_Task_GenerateYamlDb + * Doctrine_Task_GenerateYamlDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateYamlDb extends Doctrine_Task { - public $description = 'Generates a Yaml schema file from an existing database', - $requiredArguments = array('yaml_schema_path' => 'Specify the path to your yaml schema files.'), - $optionalArguments = array(); - + public $description = 'Generates a Yaml schema file from an existing database'; + public $requiredArguments = array('yaml_schema_path' => 'Specify the path to your yaml schema files.'); + public $optionalArguments = array(); + public function execute() { Doctrine_Core::generateYamlFromDb($this->getArgument('yaml_schema_path')); - + $this->notify('Generate YAML schema successfully from database'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/GenerateYamlModels.php b/lib/Doctrine/Task/GenerateYamlModels.php index a25cfb14b..d287e641d 100644 --- a/lib/Doctrine/Task/GenerateYamlModels.php +++ b/lib/Doctrine/Task/GenerateYamlModels.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_Task_GenerateFromModels + * Doctrine_Task_GenerateFromModels. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_GenerateYamlModels extends Doctrine_Task { - public $description = 'Generates a Yaml schema file from existing Doctrine_Record definitions', - $requiredArguments = array('yaml_schema_path' => 'Specify the complete directory path to your yaml schema files.'), - $optionalArguments = array('models_path' => 'Specify complete path to your Doctrine_Record definitions.'); + public $description = 'Generates a Yaml schema file from existing Doctrine_Record definitions'; + public $requiredArguments = array('yaml_schema_path' => 'Specify the complete directory path to your yaml schema files.'); + public $optionalArguments = array('models_path' => 'Specify complete path to your Doctrine_Record definitions.'); public function execute() { Doctrine_Core::generateYamlFromModels($this->getArgument('yaml_schema_path'), $this->getArgument('models_path')); - + $this->notify('Generated YAML schema successfully from models'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/LoadData.php b/lib/Doctrine/Task/LoadData.php index 32e31efa1..7f2f5264a 100644 --- a/lib/Doctrine/Task/LoadData.php +++ b/lib/Doctrine/Task/LoadData.php @@ -20,23 +20,24 @@ */ /** - * Doctrine_Task_LoadData + * Doctrine_Task_LoadData. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_LoadData extends Doctrine_Task { - public $description = 'Load data from a yaml data fixture file.', - $requiredArguments = array('data_fixtures_path' => 'Specify the complete path to load the yaml data fixtures files from.', - 'models_path' => 'Specify path to your Doctrine_Record definitions.'), - $optionalArguments = array('append' => 'Whether or not to append the data', - 'charset' => 'Specify the charset to use for yaml laod'); + public $description = 'Load data from a yaml data fixture file.'; + public $requiredArguments = array('data_fixtures_path' => 'Specify the complete path to load the yaml data fixtures files from.', + 'models_path' => 'Specify path to your Doctrine_Record definitions.'); + public $optionalArguments = array('append' => 'Whether or not to append the data', + 'charset' => 'Specify the charset to use for yaml laod'); public function execute() { diff --git a/lib/Doctrine/Task/Migrate.php b/lib/Doctrine/Task/Migrate.php index 18aaa284e..c23e8773f 100644 --- a/lib/Doctrine/Task/Migrate.php +++ b/lib/Doctrine/Task/Migrate.php @@ -20,26 +20,27 @@ */ /** - * Doctrine_Task_Migrate + * Doctrine_Task_Migrate. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_Migrate extends Doctrine_Task { - public $description = 'Migrate database to latest version or the specified version', - $requiredArguments = array('migrations_path' => 'Specify path to your migrations directory.'), - $optionalArguments = array('version' => 'Version to migrate to. If you do not specify, the db will be migrated from the current version to the latest.'); - + public $description = 'Migrate database to latest version or the specified version'; + public $requiredArguments = array('migrations_path' => 'Specify path to your migrations directory.'); + public $optionalArguments = array('version' => 'Version to migrate to. If you do not specify, the db will be migrated from the current version to the latest.'); + public function execute() { $version = Doctrine_Core::migrate($this->getArgument('migrations_path'), $this->getArgument('version')); - - $this->notify('migrated successfully to version #' . $version); + + $this->notify('migrated successfully to version #'.$version); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Task/RebuildDb.php b/lib/Doctrine/Task/RebuildDb.php index ad9623f6d..085dd723d 100644 --- a/lib/Doctrine/Task/RebuildDb.php +++ b/lib/Doctrine/Task/RebuildDb.php @@ -20,30 +20,31 @@ */ /** - * Doctrine_Task_RebuildDb + * Doctrine_Task_RebuildDb. * - * @package Doctrine - * @subpackage Task * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 2761 $ + * * @author Jonathan H. Wage */ class Doctrine_Task_RebuildDb extends Doctrine_Task { - public $description = 'Drops and re-creates databases', - $requiredArguments = array(), - $optionalArguments = array(); + public $description = 'Drops and re-creates databases'; + public $requiredArguments = array(); + public $optionalArguments = array(); + + protected $dropDb; + protected $createDb; + protected $createTables; - protected $dropDb, - $createDb, - $createTables; - public function __construct($dispatcher = null) { parent::__construct($dispatcher); - + $this->dropDb = new Doctrine_Task_DropDb($this->dispatcher); $this->createDb = new Doctrine_Task_CreateDb($this->dispatcher); $this->createTables = new Doctrine_Task_CreateTables($this->dispatcher); @@ -63,4 +64,4 @@ public function execute() $this->createTables->setArguments($this->getArguments()); $this->createTables->execute(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template.php b/lib/Doctrine/Template.php index f42caf957..2b03d97fb 100644 --- a/lib/Doctrine/Template.php +++ b/lib/Doctrine/Template.php @@ -21,38 +21,36 @@ /** * Base abstract class for defining templates which are the base of all behaviors that can be attached - * to your Doctrine models + * to your Doctrine models. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ abstract class Doctrine_Template extends Doctrine_Record_Abstract { /** - * @var Doctrine_Record $_invoker the record that invoked the last delegated call + * @var Doctrine_Record the record that invoked the last delegated call */ protected $_invoker; /** - * @var Doctrine_Record_Generator $_plugin + * @var Doctrine_Record_Generator */ protected $_plugin; /** - * @var array $_options Template options + * @var array Template options */ protected $_options = array(); /** - * __construct - * - * @param string $array - * @return void + * __construct. */ public function __construct(array $options = array()) { @@ -60,9 +58,9 @@ public function __construct(array $options = array()) } /** - * Set the table object that this Template belongs to + * Set the table object that this Template belongs to. * - * @var Doctrine_Table $table the table object this Template belongs to + * @var Doctrine_Table the table object this Template belongs to */ public function setTable(Doctrine_Table $table) { @@ -70,9 +68,9 @@ public function setTable(Doctrine_Table $table) } /** - * returns the associated table object + * returns the associated table object. * - * @return Doctrine_Table the associated table object + * @return Doctrine_Table the associated table object */ public function getTable() { @@ -80,10 +78,11 @@ public function getTable() } /** - * sets the last used invoker + * sets the last used invoker. + * + * @param Doctrine_Record $invoker the record that invoked the last delegated call * - * @param Doctrine_Record $invoker the record that invoked the last delegated call - * @return Doctrine_Template this object + * @return Doctrine_Template this object */ public function setInvoker(Doctrine_Record_Abstract $invoker) { @@ -91,9 +90,9 @@ public function setInvoker(Doctrine_Record_Abstract $invoker) } /** - * returns the last used invoker + * returns the last used invoker. * - * @return Doctrine_Record the record that invoked the last delegated call + * @return Doctrine_Record the record that invoked the last delegated call */ public function getInvoker() { @@ -101,22 +100,19 @@ public function getInvoker() } /** - * Adds a plugin as a child to this plugin - * - * @param Doctrine_Template $template + * Adds a plugin as a child to this plugin. + * * @return Doctrine_Template. Chainable. */ public function addChild(Doctrine_Template $template) { $this->_plugin->addChild($template); - + return $this; } /** - * Get plugin instance - * - * @return void + * Get plugin instance. */ public function getPlugin() { @@ -124,9 +120,9 @@ public function getPlugin() } /** - * Check if this template has a generator plugin + * Check if this template has a generator plugin. * - * @return boolean + * @return bool */ public function hasPlugin() { @@ -135,9 +131,9 @@ public function hasPlugin() /** * getOptions - * returns all options of this template and the associated values + * returns all options of this template and the associated values. * - * @return array all options and their values + * @return array all options and their values */ public function getOptions() { @@ -146,37 +142,32 @@ public function getOptions() /** * getOption - * returns the value of given option + * returns the value of given option. + * + * @param string $name the name of the option + * @param mixed $default default value if option is not found * - * @param string $name the name of the option - * @param mixed $default default value if option is not found - * @return mixed the value of given option + * @return mixed the value of given option */ public function getOption($name, $default = null) { if (isset($this->_options[$name])) { return $this->_options[$name]; } + return $default; } /** - * get - * - * @param mixed $name - * @return void + * get. */ - public function get($name) + public function get($name) { throw new Doctrine_Exception("Templates doesn't support accessors."); } /** - * set - * - * @param mixed $name - * @param mixed $value - * @return void + * set. */ public function set($name, $value) { @@ -184,22 +175,16 @@ public function set($name, $value) } /** - * Blank method for template setup - * - * @return void + * Blank method for template setup. */ public function setUp() { - } /** - * Blank method for template table definition - * - * @return void + * Blank method for template table definition. */ public function setTableDefinition() { - } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Geographical.php b/lib/Doctrine/Template/Geographical.php index 9c99e817c..dc9429afa 100644 --- a/lib/Doctrine/Template/Geographical.php +++ b/lib/Doctrine/Template/Geographical.php @@ -20,38 +20,37 @@ */ /** - * Easily add longitude and latitude columns to your records and use inherited functionality for - * calculating distances + * Easily add longitude and latitude columns to your records and use inherited functionality for + * calculating distances. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Template_Geographical extends Doctrine_Template { /** - * Array of geographical options + * Array of geographical options. * * @var string */ - protected $_options = array('latitude' => array('name' => 'latitude', - 'type' => 'decimal', - 'size' => 10, - 'options' => array('scale' => 6)), - 'longitude' => array('name' => 'longitude', - 'type' => 'decimal', - 'size' => 10, - 'options' => array('scale' => 6))); + protected $_options = array('latitude' => array('name' => 'latitude', + 'type' => 'decimal', + 'size' => 10, + 'options' => array('scale' => 6)), + 'longitude' => array('name' => 'longitude', + 'type' => 'decimal', + 'size' => 10, + 'options' => array('scale' => 6))); /** - * Set table definition for Geographical behavior - * - * @return void + * Set table definition for Geographical behavior. */ public function setTableDefinition() { @@ -60,8 +59,8 @@ public function setTableDefinition() } /** - * Initiate and get a distance query with the select parts for the number of kilometers and miles - * between this record and other zipcode records in the database + * Initiate and get a distance query with the select parts for the number of kilometers and miles + * between this record and other zipcode records in the database. * * @return Doctrine_Query $query */ @@ -74,9 +73,9 @@ public function getDistanceQuery() $latName = $this->_options['latitude']['name']; $longName = $this->_options['longitude']['name']; - $query->addSelect($rootAlias . '.*'); + $query->addSelect($rootAlias.'.*'); - $sql = "((ACOS(SIN(%s * PI() / 180) * SIN(" . $rootAlias . "." . $latName . " * PI() / 180) + COS(%s * PI() / 180) * COS(" . $rootAlias . "." . $latName . " * PI() / 180) * COS((%s - " . $rootAlias . "." . $longName . ") * PI() / 180)) * 180 / PI()) * 60 * %s) as %s"; + $sql = '((ACOS(SIN(%s * PI() / 180) * SIN('.$rootAlias.'.'.$latName.' * PI() / 180) + COS(%s * PI() / 180) * COS('.$rootAlias.'.'.$latName.' * PI() / 180) * COS((%s - '.$rootAlias.'.'.$longName.') * PI() / 180)) * 180 / PI()) * 60 * %s) as %s'; $milesSql = sprintf($sql, $invoker->get($latName), $invoker->get($latName), $invoker->get($longName), '1.1515', 'miles'); $query->addSelect($milesSql); @@ -88,20 +87,20 @@ public function getDistanceQuery() } /** - * Get distance between this record and another + * Get distance between this record and another. * - * @param string $Doctrine_Record - * @param string $kilometers - * @return integer + * @param string $kilometers + * + * @return int */ public function getDistance(Doctrine_Record $record, $kilometers = false) { $query = $this->getDistanceQuery($kilometers); - + $conditions = array(); $values = array(); foreach ((array) $record->getTable()->getIdentifier() as $id) { - $conditions[] = $query->getRootAlias() . '.' . $id . ' = ?'; + $conditions[] = $query->getRootAlias().'.'.$id.' = ?'; $values[] = $record->get($id); } @@ -112,11 +111,11 @@ public function getDistance(Doctrine_Record $record, $kilometers = false) $query->limit(1); $result = $query->execute()->getFirst(); - + if (isset($result['kilometers']) && $result['miles']) { - return $kilometers ? $result->get('kilometers'):$result->get('miles'); - } else { - return 0; + return $kilometers ? $result->get('kilometers') : $result->get('miles'); } + + return 0; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/I18n.php b/lib/Doctrine/Template/I18n.php index 808b4016c..1bd0b2a3f 100644 --- a/lib/Doctrine/Template/I18n.php +++ b/lib/Doctrine/Template/I18n.php @@ -20,47 +20,41 @@ */ /** - * Add multilingual capabilities to your Doctrine models + * Add multilingual capabilities to your Doctrine models. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_I18n extends Doctrine_Template { /** - * __construct - * - * @param string $array - * @return void + * __construct. */ public function __construct(array $options = array()) { - parent::__construct($options); + parent::__construct($options); $this->_plugin = new Doctrine_I18n($this->_options); } /** - * Initialize the I18n plugin for the template - * - * @return void + * Initialize the I18n plugin for the template. */ public function setUp() { - $this->_plugin->initialize($this->_table); + $this->_plugin->initialize($this->_table); } /** - * Get the plugin instance for the I18n template - * - * @return void + * Get the plugin instance for the I18n template. */ public function getI18n() { return $this->_plugin; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Listener/Sluggable.php b/lib/Doctrine/Template/Listener/Sluggable.php index cc627a001..083da74f6 100644 --- a/lib/Doctrine/Template/Listener/Sluggable.php +++ b/lib/Doctrine/Template/Listener/Sluggable.php @@ -20,30 +20,28 @@ */ /** - * Easily create a slug for each record based on a specified set of fields + * Easily create a slug for each record based on a specified set of fields. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Listener_Sluggable extends Doctrine_Record_Listener { /** - * Array of sluggable options + * Array of sluggable options. * * @var string */ protected $_options = array(); /** - * __construct - * - * @param string $array - * @return void + * __construct. */ public function __construct(array $options) { @@ -51,27 +49,21 @@ public function __construct(array $options) } /** - * Set the slug value automatically when a record is inserted - * - * @param Doctrine_Event $event - * @return void + * Set the slug value automatically when a record is inserted. */ public function preInsert(Doctrine_Event $event) { $record = $event->getInvoker(); $name = $record->getTable()->getFieldName($this->_options['name']); - if ( ! $record->$name) { - $record->$name = $this->buildSlugFromFields($record); + if (!$record->{$name}) { + $record->{$name} = $this->buildSlugFromFields($record); } } /** * Set the slug value automatically when a record is updated if the options are configured - * to allow it - * - * @param Doctrine_Event $event - * @return void + * to allow it. */ public function preUpdate(Doctrine_Event $event) { @@ -79,32 +71,33 @@ public function preUpdate(Doctrine_Event $event) $record = $event->getInvoker(); $name = $record->getTable()->getFieldName($this->_options['name']); - if ( ! $record->$name || ( - false !== $this->_options['canUpdate'] && - ! array_key_exists($name, $record->getModified()) - )) { - $record->$name = $this->buildSlugFromFields($record); - } else if ( ! empty($record->$name) && - false !== $this->_options['canUpdate'] && - array_key_exists($name, $record->getModified() + if (!$record->{$name} || ( + false !== $this->_options['canUpdate'] + && !array_key_exists($name, $record->getModified()) )) { - $record->$name = $this->buildSlugFromSlugField($record); + $record->{$name} = $this->buildSlugFromFields($record); + } elseif (!empty($record->{$name}) + && false !== $this->_options['canUpdate'] + && array_key_exists($name, $record->getModified() + )) { + $record->{$name} = $this->buildSlugFromSlugField($record); } } } /** - * Generate the slug for a given Doctrine_Record based on the configured options + * Generate the slug for a given Doctrine_Record based on the configured options. * * @param Doctrine_Record $record + * * @return string $slug */ protected function buildSlugFromFields($record) { if (empty($this->_options['fields'])) { if (is_callable($this->_options['provider'])) { - $value = call_user_func($this->_options['provider'], $record); - } else if (method_exists($record, 'getUniqueSlug')) { + $value = call_user_func($this->_options['provider'], $record); + } elseif (method_exists($record, 'getUniqueSlug')) { $value = $record->getUniqueSlug($record); } else { $value = (string) $record; @@ -112,30 +105,31 @@ protected function buildSlugFromFields($record) } else { $value = ''; foreach ($this->_options['fields'] as $field) { - $value .= $record->$field . ' '; + $value .= $record->{$field}.' '; } $value = substr($value, 0, -1); } - if ($this->_options['unique'] === true) { - return $this->getUniqueSlug($record, $value); - } + if (true === $this->_options['unique']) { + return $this->getUniqueSlug($record, $value); + } return call_user_func_array($this->_options['builder'], array($value, $record)); } /** - * Generate the slug for a given Doctrine_Record slug field + * Generate the slug for a given Doctrine_Record slug field. * * @param Doctrine_Record $record + * * @return string $slug */ protected function buildSlugFromSlugField($record) { $name = $record->getTable()->getFieldName($this->_options['name']); - $value = $record->$name; + $value = $record->{$name}; - if ($this->_options['unique'] === true) { + if (true === $this->_options['unique']) { return $this->getUniqueSlug($record, $value); } @@ -144,52 +138,53 @@ protected function buildSlugFromSlugField($record) /** * Creates a unique slug for a given Doctrine_Record. This function enforces the uniqueness by - * incrementing the values with a postfix if the slug is not unique + * incrementing the values with a postfix if the slug is not unique. * * @param Doctrine_Record $record - * @param string $slugFromFields + * @param string $slugFromFields + * * @return string $slug */ public function getUniqueSlug($record, $slugFromFields) { /* fix for use with Column Aggregation Inheritance */ if ($record->getTable()->getOption('inheritanceMap')) { - $parentTable = $record->getTable()->getOption('parents'); - $i = 0; - // Be sure that you do not instanciate an abstract class; - $reflectionClass = new ReflectionClass($parentTable[$i]); - while ($reflectionClass->isAbstract()) { - $i++; + $parentTable = $record->getTable()->getOption('parents'); + $i = 0; + // Be sure that you do not instanciate an abstract class; $reflectionClass = new ReflectionClass($parentTable[$i]); - } - $table = Doctrine_Core::getTable($parentTable[$i]); + while ($reflectionClass->isAbstract()) { + ++$i; + $reflectionClass = new ReflectionClass($parentTable[$i]); + } + $table = Doctrine_Core::getTable($parentTable[$i]); } else { - $table = $record->getTable(); + $table = $record->getTable(); } $name = $table->getFieldName($this->_options['name']); - $proposal = call_user_func_array($this->_options['builder'], array($slugFromFields, $record)); + $proposal = call_user_func_array($this->_options['builder'], array($slugFromFields, $record)); $slug = $proposal; - $whereString = 'r.' . $name . ' LIKE ?'; + $whereString = 'r.'.$name.' LIKE ?'; $whereParams = array($proposal.'%'); if ($record->exists()) { $identifier = $record->identifier(); - $whereString .= ' AND r.' . implode(' != ? AND r.', $table->getIdentifierColumnNames()) . ' != ?'; + $whereString .= ' AND r.'.implode(' != ? AND r.', $table->getIdentifierColumnNames()).' != ?'; $whereParams = array_merge($whereParams, array_values($identifier)); } foreach ($this->_options['uniqueBy'] as $uniqueBy) { - if (is_null($record->$uniqueBy)) { + if (is_null($record->{$uniqueBy})) { $whereString .= ' AND r.'.$uniqueBy.' IS NULL'; } else { $whereString .= ' AND r.'.$uniqueBy.' = ?'; - $value = $record->$uniqueBy; + $value = $record->{$uniqueBy}; if ($value instanceof Doctrine_Record) { $value = current((array) $value->identifier()); } - $whereParams[] = $value; + $whereParams[] = $value; } } @@ -198,24 +193,25 @@ public function getUniqueSlug($record, $slugFromFields) $table->bindQueryPart('indexBy', null); $query = $table->createQuery('r') - ->select('r.' . $name) - ->where($whereString , $whereParams) - ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY); + ->select('r.'.$name) + ->where($whereString, $whereParams) + ->setHydrationMode(Doctrine_Core::HYDRATE_ARRAY) + ; // We need to introspect SoftDelete to check if we are not disabling unique records too if ($table->hasTemplate('Doctrine_Template_SoftDelete')) { - $softDelete = $table->getTemplate('Doctrine_Template_SoftDelete'); + $softDelete = $table->getTemplate('Doctrine_Template_SoftDelete'); - // we have to consider both situations here - if ($softDelete->getOption('type') == 'boolean') { + // we have to consider both situations here + if ('boolean' == $softDelete->getOption('type')) { $conn = $query->getConnection(); $query->addWhere( - '(r.' . $softDelete->getOption('name') . ' = ' . $conn->convertBooleans(true) . - ' OR r.' . $softDelete->getOption('name') . ' = ' . $conn->convertBooleans(false) . ')' + '(r.'.$softDelete->getOption('name').' = '.$conn->convertBooleans(true). + ' OR r.'.$softDelete->getOption('name').' = '.$conn->convertBooleans(false).')' ); } else { - $query->addWhere('(r.' . $softDelete->getOption('name') . ' IS NOT NULL OR r.' . $softDelete->getOption('name') . ' IS NULL)'); + $query->addWhere('(r.'.$softDelete->getOption('name').' IS NOT NULL OR r.'.$softDelete->getOption('name').' IS NULL)'); } } @@ -233,7 +229,7 @@ public function getUniqueSlug($record, $slugFromFields) $i = 1; while (in_array(strtolower($slug), $similarSlugs)) { $slug = call_user_func_array($this->_options['builder'], array($proposal.'-'.$i, $record)); - $i++; + ++$i; } // If slug is longer then the column length then we need to trim it @@ -244,6 +240,6 @@ public function getUniqueSlug($record, $slugFromFields) $slug = $this->getUniqueSlug($record, $slug); } - return $slug; + return $slug; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Listener/SoftDelete.php b/lib/Doctrine/Template/Listener/SoftDelete.php index fda661deb..93f666b52 100644 --- a/lib/Doctrine/Template/Listener/SoftDelete.php +++ b/lib/Doctrine/Template/Listener/SoftDelete.php @@ -24,29 +24,29 @@ * sets a delete flag instead of actually deleting the record and all queries automatically * include a check for the deleted flag to exclude deleted records. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Template_Listener_SoftDelete extends Doctrine_Record_Listener { /** - * Array of SoftDelete options + * Array of SoftDelete options. * * @var string */ protected $_options = array(); /** - * __construct + * __construct. * - * @param string $options - * @return void + * @param string $options */ public function __construct(array $options) { @@ -54,10 +54,9 @@ public function __construct(array $options) } /** - * Set the hard delete flag so that it is really deleted + * Set the hard delete flag so that it is really deleted. * - * @param boolean $bool - * @return void + * @param bool $bool */ public function hardDelete($bool) { @@ -65,91 +64,79 @@ public function hardDelete($bool) } /** - * Skip the normal delete options so we can override it with our own - * - * @param Doctrine_Event $event - * @return void + * Skip the normal delete options so we can override it with our own. */ public function preDelete(Doctrine_Event $event) { $name = $this->_options['name']; $invoker = $event->getInvoker(); - - if ($this->_options['type'] == 'timestamp') { - $invoker->$name = date('Y-m-d H:i:s', time()); - } else if ($this->_options['type'] == 'boolean') { - $invoker->$name = true; + + if ('timestamp' == $this->_options['type']) { + $invoker->{$name} = date('Y-m-d H:i:s', time()); + } elseif ('boolean' == $this->_options['type']) { + $invoker->{$name} = true; } - if ( ! $this->_options['hardDelete']) { + if (!$this->_options['hardDelete']) { $event->skipOperation(); } } /** - * Implement postDelete() hook and set the deleted flag to true - * - * @param Doctrine_Event $event - * @return void + * Implement postDelete() hook and set the deleted flag to true. */ public function postDelete(Doctrine_Event $event) { - if ( ! $this->_options['hardDelete']) { + if (!$this->_options['hardDelete']) { $event->getInvoker()->save(); } } /** * Implement preDqlDelete() hook and modify a dql delete query so it updates the deleted flag - * instead of deleting the record - * - * @param Doctrine_Event $event - * @return void + * instead of deleting the record. */ public function preDqlDelete(Doctrine_Event $event) { $params = $event->getParams(); - $field = $params['alias'] . '.' . $this->_options['name']; + $field = $params['alias'].'.'.$this->_options['name']; $query = $event->getQuery(); - if ( ! $query->contains($field)) { - $query->from('')->update($params['component']['table']->getOption('name') . ' ' . $params['alias']); - - if ($this->_options['type'] == 'timestamp') { + if (!$query->contains($field)) { + $query->from('')->update($params['component']['table']->getOption('name').' '.$params['alias']); + + if ('timestamp' == $this->_options['type']) { $query->set($field, '?', date('Y-m-d H:i:s', time())); - $query->addWhere($field . ' IS NULL'); - } else if ($this->_options['type'] == 'boolean') { + $query->addWhere($field.' IS NULL'); + } elseif ('boolean' == $this->_options['type']) { $query->set($field, $query->getConnection()->convertBooleans(true)); $query->addWhere( - $field . ' = ' . $query->getConnection()->convertBooleans(false) + $field.' = '.$query->getConnection()->convertBooleans(false) ); } } } /** - * Implement preDqlSelect() hook and add the deleted flag to all queries for which this model + * Implement preDqlSelect() hook and add the deleted flag to all queries for which this model * is being used in. - * - * @param Doctrine_Event $event - * @return void */ public function preDqlSelect(Doctrine_Event $event) { $params = $event->getParams(); - $field = $params['alias'] . '.' . $this->_options['name']; + $field = $params['alias'].'.'.$this->_options['name']; $query = $event->getQuery(); // We only need to add the restriction if: // 1 - We are in the root query // 2 - We are in the subquery and it defines the component with that alias - if (( ! $query->isSubquery() || ($query->isSubquery() && $query->contains(' ' . $params['alias'] . ' '))) && ! $query->contains($field)) { - if ($this->_options['type'] == 'timestamp') { - $query->addPendingJoinCondition($params['alias'], $field . ' IS NULL'); - } else if ($this->_options['type'] == 'boolean') { + if ((!$query->isSubquery() || ($query->isSubquery() && $query->contains(' '.$params['alias'].' '))) && !$query->contains($field)) { + if ('timestamp' == $this->_options['type']) { + $query->addPendingJoinCondition($params['alias'], $field.' IS NULL'); + } elseif ('boolean' == $this->_options['type']) { $query->addPendingJoinCondition( - $params['alias'], $field . ' = ' . $query->getConnection()->convertBooleans(false) + $params['alias'], $field.' = '.$query->getConnection()->convertBooleans(false) ); } } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Listener/Timestampable.php b/lib/Doctrine/Template/Listener/Timestampable.php index 5be06d106..685d772d3 100644 --- a/lib/Doctrine/Template/Listener/Timestampable.php +++ b/lib/Doctrine/Template/Listener/Timestampable.php @@ -23,27 +23,26 @@ * Listener for the Timestampable behavior which automatically sets the created * and updated columns when a record is inserted and updated. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Listener_Timestampable extends Doctrine_Record_Listener { /** - * Array of timestampable options + * Array of timestampable options. * * @var string */ protected $_options = array(); /** - * __construct - * - * @param array $options + * __construct. */ public function __construct(array $options) { @@ -51,69 +50,63 @@ public function __construct(array $options) } /** - * Set the created and updated Timestampable columns when a record is inserted - * - * @param Doctrine_Event $event + * Set the created and updated Timestampable columns when a record is inserted. */ public function preInsert(Doctrine_Event $event) { - if ( ! $this->_options['created']['disabled']) { + if (!$this->_options['created']['disabled']) { $createdName = $event->getInvoker()->getTable()->getFieldName($this->_options['created']['name']); $modified = $event->getInvoker()->getModified(); - if ( ! isset($modified[$createdName])) { - $event->getInvoker()->$createdName = $this->getTimestamp('created', $event->getInvoker()->getTable()->getConnection()); + if (!isset($modified[$createdName])) { + $event->getInvoker()->{$createdName} = $this->getTimestamp('created', $event->getInvoker()->getTable()->getConnection()); } } - if ( ! $this->_options['updated']['disabled'] && $this->_options['updated']['onInsert']) { + if (!$this->_options['updated']['disabled'] && $this->_options['updated']['onInsert']) { $updatedName = $event->getInvoker()->getTable()->getFieldName($this->_options['updated']['name']); $modified = $event->getInvoker()->getModified(); - if ( ! isset($modified[$updatedName])) { - $event->getInvoker()->$updatedName = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); + if (!isset($modified[$updatedName])) { + $event->getInvoker()->{$updatedName} = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); } } } /** - * Set updated Timestampable column when a record is updated - * - * @param Doctrine_Event $event + * Set updated Timestampable column when a record is updated. */ public function preUpdate(Doctrine_Event $event) { - if ( ! $this->_options['updated']['disabled']) { + if (!$this->_options['updated']['disabled']) { $updatedName = $event->getInvoker()->getTable()->getFieldName($this->_options['updated']['name']); $modified = $event->getInvoker()->getModified(); - if ( ! isset($modified[$updatedName])) { - $event->getInvoker()->$updatedName = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); + if (!isset($modified[$updatedName])) { + $event->getInvoker()->{$updatedName} = $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection()); } } } /** - * Set the updated field for dql update queries - * - * @param Doctrine_Event $event + * Set the updated field for dql update queries. */ public function preDqlUpdate(Doctrine_Event $event) { - if ( ! $this->_options['updated']['disabled']) { + if (!$this->_options['updated']['disabled']) { $params = $event->getParams(); $updatedName = $event->getInvoker()->getTable()->getFieldName($this->_options['updated']['name']); - $field = $params['alias'] . '.' . $updatedName; + $field = $params['alias'].'.'.$updatedName; $query = $event->getQuery(); - if ( ! $query->contains($field)) { + if (!$query->contains($field)) { $query->set($field, '?', $this->getTimestamp('updated', $event->getInvoker()->getTable()->getConnection())); } } } /** - * Gets the timestamp in the correct format based on the way the behavior is configured + * Gets the timestamp in the correct format based on the way the behavior is configured. * * @param string $type - * @param null|Doctrine_Connection $conn + * @param Doctrine_Connection|null $conn * * @return Doctrine_Expression|int|string */ @@ -121,16 +114,16 @@ public function getTimestamp($type, $conn = null) { $options = $this->_options[$type]; - if ($options['expression'] !== false && is_string($options['expression'])) { + if (false !== $options['expression'] && is_string($options['expression'])) { return new Doctrine_Expression($options['expression'], $conn); - } else { - if ($options['type'] == 'date') { - return date($options['format'], time()); - } else if ($options['type'] == 'timestamp') { - return date($options['format'], time()); - } else { - return time(); - } } + if ('date' == $options['type']) { + return date($options['format'], time()); + } + if ('timestamp' == $options['type']) { + return date($options['format'], time()); + } + + return time(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/NestedSet.php b/lib/Doctrine/Template/NestedSet.php index 41e7b92d8..fa22d0c15 100644 --- a/lib/Doctrine/Template/NestedSet.php +++ b/lib/Doctrine/Template/NestedSet.php @@ -20,22 +20,21 @@ */ /** - * Doctrine template which implements the custom NestedSet implementation + * Doctrine template which implements the custom NestedSet implementation. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Roman Borschel */ class Doctrine_Template_NestedSet extends Doctrine_Template { /** - * Set up NestedSet template - * - * @return void + * Set up NestedSet template. */ public function setUp() { @@ -44,12 +43,10 @@ public function setUp() } /** - * Call set table definition for the NestedSet behavior - * - * @return void + * Call set table definition for the NestedSet behavior. */ public function setTableDefinition() { $this->_table->getTree()->setTableDefinition(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Searchable.php b/lib/Doctrine/Template/Searchable.php index bfa33de3a..adc4e2c1d 100644 --- a/lib/Doctrine/Template/Searchable.php +++ b/lib/Doctrine/Template/Searchable.php @@ -20,34 +20,29 @@ */ /** - * Doctrine_Template_Searchable + * Doctrine_Template_Searchable. * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * * @version $Revision$ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 */ class Doctrine_Template_Searchable extends Doctrine_Template { /** - * __construct - * - * @param array $options - * @return void + * __construct. */ public function __construct(array $options = array()) { - parent::__construct($options); - $this->_plugin = new Doctrine_Search($this->_options); + parent::__construct($options); + $this->_plugin = new Doctrine_Search($this->_options); } /** - * Setup the Searchable template behavior - * - * @return void + * Setup the Searchable template behavior. */ public function setUp() { @@ -58,11 +53,11 @@ public function setUp() /** * Make the batchUpdateIndex() function available to the template so Doctrine_Record child classes - * with the behavior enabled can all the function + * with the behavior enabled can all the function. * - * @param integer $limit - * @param integer $offset - * @return void + * @param int $limit + * @param int $offset + * @param mixed|null $encoding */ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null) { @@ -70,11 +65,11 @@ public function batchUpdateIndex($limit = null, $offset = null, $encoding = null } /** - * Proxy method so the batch updating can be called from table classes + * Proxy method so the batch updating can be called from table classes. * - * @param integer $limit - * @param integer $offset - * @return void + * @param int $limit + * @param int $offset + * @param mixed|null $encoding */ public function batchUpdateIndexTableProxy($limit = null, $offset = null, $encoding = null) { @@ -82,11 +77,12 @@ public function batchUpdateIndexTableProxy($limit = null, $offset = null, $encod } /** - * Searchable keyword search proxy for Doctrine_Table - * - * @param string $string Keyword string to search for - * @param Doctrine_Query $query Query object to alter. Adds where condition to limit the results using the search index - * @return array ids and relevancy + * Searchable keyword search proxy for Doctrine_Table. + * + * @param string $string Keyword string to search for + * @param Doctrine_Query $query Query object to alter. Adds where condition to limit the results using the search index + * + * @return array ids and relevancy */ public function searchTableProxy($string, $query = null) { diff --git a/lib/Doctrine/Template/Sluggable.php b/lib/Doctrine/Template/Sluggable.php index 045019eb0..4a7fc0620 100644 --- a/lib/Doctrine/Template/Sluggable.php +++ b/lib/Doctrine/Template/Sluggable.php @@ -20,64 +20,63 @@ */ /** - * Doctrine_Template_Sluggable + * Doctrine_Template_Sluggable. * * Easily create a slug for each record based on a specified set of fields * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Sluggable extends Doctrine_Template { /** - * Array of Sluggable options + * Array of Sluggable options. * * @var string */ protected $_options = array( - 'name' => 'slug', - 'alias' => null, - 'type' => 'string', - 'length' => 255, - 'unique' => true, - 'options' => array(), - 'fields' => array(), - 'uniqueBy' => array(), - 'uniqueIndex' => true, - 'canUpdate' => false, - 'builder' => array('Doctrine_Inflector', 'urlize'), - 'provider' => null, - 'indexName' => null + 'name' => 'slug', + 'alias' => null, + 'type' => 'string', + 'length' => 255, + 'unique' => true, + 'options' => array(), + 'fields' => array(), + 'uniqueBy' => array(), + 'uniqueIndex' => true, + 'canUpdate' => false, + 'builder' => array('Doctrine_Inflector', 'urlize'), + 'provider' => null, + 'indexName' => null, ); /** - * Set table definition for Sluggable behavior - * - * @return void + * Set table definition for Sluggable behavior. */ public function setTableDefinition() { $name = $this->_options['name']; if ($this->_options['alias']) { - $name .= ' as ' . $this->_options['alias']; + $name .= ' as '.$this->_options['alias']; } - if ($this->_options['indexName'] === null) { + if (null === $this->_options['indexName']) { $this->_options['indexName'] = $this->getTable()->getTableName().'_sluggable'; } $this->hasColumn($name, $this->_options['type'], $this->_options['length'], $this->_options['options']); - - if ($this->_options['unique'] == true && $this->_options['uniqueIndex'] == true) { + + if (true == $this->_options['unique'] && true == $this->_options['uniqueIndex']) { $indexFields = array($this->_options['name']); $indexFields = array_merge($indexFields, $this->_options['uniqueBy']); $this->index($this->_options['indexName'], array('fields' => $indexFields, - 'type' => 'unique')); + 'type' => 'unique')); } $this->addListener(new Doctrine_Template_Listener_Sluggable($this->_options)); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/SoftDelete.php b/lib/Doctrine/Template/SoftDelete.php index 105a9355e..2b1de3b7e 100644 --- a/lib/Doctrine/Template/SoftDelete.php +++ b/lib/Doctrine/Template/SoftDelete.php @@ -20,49 +20,48 @@ */ /** - * Doctrine_Template_SoftDelete + * Doctrine_Template_SoftDelete. * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen * @author Jonathan H. Wage */ class Doctrine_Template_SoftDelete extends Doctrine_Template { /** - * Array of SoftDelete options + * Array of SoftDelete options. * * @var string */ protected $_options = array( - 'name' => 'deleted_at', - 'type' => 'timestamp', - 'length' => null, - 'options' => array( - 'notnull' => false + 'name' => 'deleted_at', + 'type' => 'timestamp', + 'length' => null, + 'options' => array( + 'notnull' => false, ), - 'hardDelete' => false + 'hardDelete' => false, ); protected $_listener; /** - * Set table definition for SoftDelete behavior - * - * @return void + * Set table definition for SoftDelete behavior. */ public function setTableDefinition() { // BC to 1.0.X of SoftDelete behavior - if ($this->_options['type'] == 'boolean') { + if ('boolean' == $this->_options['type']) { $this->_options['length'] = 1; $this->_options['options'] = array('default' => false, 'notnull' => true); } - + $this->hasColumn($this->_options['name'], $this->_options['type'], $this->_options['length'], $this->_options['options']); $this->_listener = new Doctrine_Template_Listener_SoftDelete($this->_options); @@ -70,19 +69,21 @@ public function setTableDefinition() } /** - * Add a hardDelete() method to any of the models who act as SoftDelete behavior + * Add a hardDelete() method to any of the models who act as SoftDelete behavior. * * @param Doctrine_Connection $conn - * @return integer $result Number of affected rows. + * + * @return int $result number of affected rows */ public function hardDelete($conn = null) { - if ($conn === null) { + if (null === $conn) { $conn = $this->_table->getConnection(); } $this->_listener->hardDelete(true); $result = $this->_invoker->delete(); $this->_listener->hardDelete(false); + return $result; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Timestampable.php b/lib/Doctrine/Template/Timestampable.php index 444bb84f3..2ce89d006 100644 --- a/lib/Doctrine/Template/Timestampable.php +++ b/lib/Doctrine/Template/Timestampable.php @@ -20,65 +20,64 @@ */ /** - * Doctrine_Template_Timestampable + * Doctrine_Template_Timestampable. * * Easily add created and updated at timestamps to your doctrine records that are automatically set * when records are saved * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Timestampable extends Doctrine_Template { /** - * Array of Timestampable options + * Array of Timestampable options. * * @var string */ - protected $_options = array('created' => array('name' => 'created_at', - 'alias' => null, - 'type' => 'timestamp', - 'format' => 'Y-m-d H:i:s', - 'disabled' => false, - 'expression' => false, - 'options' => array('notnull' => true)), - 'updated' => array('name' => 'updated_at', - 'alias' => null, - 'type' => 'timestamp', - 'format' => 'Y-m-d H:i:s', - 'disabled' => false, - 'expression' => false, - 'onInsert' => true, - 'options' => array('notnull' => true))); + protected $_options = array('created' => array('name' => 'created_at', + 'alias' => null, + 'type' => 'timestamp', + 'format' => 'Y-m-d H:i:s', + 'disabled' => false, + 'expression' => false, + 'options' => array('notnull' => true)), + 'updated' => array('name' => 'updated_at', + 'alias' => null, + 'type' => 'timestamp', + 'format' => 'Y-m-d H:i:s', + 'disabled' => false, + 'expression' => false, + 'onInsert' => true, + 'options' => array('notnull' => true))); /** - * Set table definition for Timestampable behavior - * - * @return void + * Set table definition for Timestampable behavior. */ public function setTableDefinition() { - if ( ! $this->_options['created']['disabled']) { + if (!$this->_options['created']['disabled']) { $name = $this->_options['created']['name']; if ($this->_options['created']['alias']) { - $name .= ' as ' . $this->_options['created']['alias']; + $name .= ' as '.$this->_options['created']['alias']; } $this->hasColumn($name, $this->_options['created']['type'], null, $this->_options['created']['options']); } - if ( ! $this->_options['updated']['disabled']) { + if (!$this->_options['updated']['disabled']) { $name = $this->_options['updated']['name']; if ($this->_options['updated']['alias']) { - $name .= ' as ' . $this->_options['updated']['alias']; + $name .= ' as '.$this->_options['updated']['alias']; } $this->hasColumn($name, $this->_options['updated']['type'], null, $this->_options['updated']['options']); } $this->addListener(new Doctrine_Template_Listener_Timestampable($this->_options)); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Template/Versionable.php b/lib/Doctrine/Template/Versionable.php index 7afba2b1a..8cf92d57c 100644 --- a/lib/Doctrine/Template/Versionable.php +++ b/lib/Doctrine/Template/Versionable.php @@ -20,53 +20,49 @@ */ /** - * Doctrine_Template_Versionable + * Doctrine_Template_Versionable. * * Add revisioning/audit log to your models * - * @package Doctrine - * @subpackage Template * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Template_Versionable extends Doctrine_Template { /** - * Array of AuditLog Options + * Array of AuditLog Options. * * @var array */ - protected $_options = array('version' => array('name' => 'version', - 'alias' => null, - 'type' => 'integer', - 'length' => 8, - 'options' => array()), - 'generateRelations' => true, - 'tableName' => false, - 'generateFiles' => false, - 'auditLog' => true, - 'deleteVersions' => true, - 'listener' => 'Doctrine_AuditLog_Listener'); + protected $_options = array('version' => array('name' => 'version', + 'alias' => null, + 'type' => 'integer', + 'length' => 8, + 'options' => array()), + 'generateRelations' => true, + 'tableName' => false, + 'generateFiles' => false, + 'auditLog' => true, + 'deleteVersions' => true, + 'listener' => 'Doctrine_AuditLog_Listener'); /** - * __construct - * - * @param array $options - * @return void + * __construct. */ public function __construct(array $options = array()) { - parent::__construct($options); + parent::__construct($options); $this->_plugin = new Doctrine_AuditLog($this->_options); } /** - * Setup the Versionable behavior for the template - * - * @return void + * Setup the Versionable behavior for the template. */ public function setUp() { @@ -75,7 +71,7 @@ public function setUp() } $version = $this->_options['version']; - $name = $version['name'] . (isset($version['alias']) ? ' as ' . $version['alias'] : ''); + $name = $version['name'].(isset($version['alias']) ? ' as '.$version['alias'] : ''); $this->hasColumn($name, $version['type'], $version['length'], $version['options']); $listener = $this->_options['listener']; @@ -83,41 +79,40 @@ public function setUp() } /** - * Get plugin for Versionable template - * - * @return void + * Get plugin for Versionable template. */ public function getAuditLog() { return $this->_plugin; } - /** + /** * revert * reverts this record to given version, this method only works if versioning plugin - * is enabled + * is enabled. + * + * @param int $version an integer > 1 * - * @throws Doctrine_Record_Exception if given version does not exist - * @param integer $version an integer > 1 - * @return Doctrine_Record this object + * @return Doctrine_Record this object + * + * @throws Doctrine_Record_Exception if given version does not exist */ public function revert($version) { $auditLog = $this->_plugin; - if ( ! $auditLog->getOption('auditLog')) { + if (!$auditLog->getOption('auditLog')) { throw new Doctrine_Record_Exception('Audit log is turned off, no version history is recorded.'); } $data = $auditLog->getVersion($this->getInvoker(), $version); - if ( ! isset($data[0])) { - throw new Doctrine_Record_Exception('Version ' . $version . ' does not exist!'); + if (!isset($data[0])) { + throw new Doctrine_Record_Exception('Version '.$version.' does not exist!'); } $this->getInvoker()->merge($data[0]); - return $this->getInvoker(); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction.php b/lib/Doctrine/Transaction.php index 23eeaa25f..086336561 100644 --- a/lib/Doctrine/Transaction.php +++ b/lib/Doctrine/Transaction.php @@ -21,77 +21,79 @@ /** * Doctrine_Transaction - * Handles transaction savepoint and isolation abstraction + * Handles transaction savepoint and isolation abstraction. * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7651 $ */ class Doctrine_Transaction extends Doctrine_Connection_Module { /** - * Doctrine_Transaction is in sleep state when it has no active transactions + * Doctrine_Transaction is in sleep state when it has no active transactions. */ - const STATE_SLEEP = 0; + public const STATE_SLEEP = 0; /** - * Doctrine_Transaction is in active state when it has one active transaction + * Doctrine_Transaction is in active state when it has one active transaction. */ - const STATE_ACTIVE = 1; + public const STATE_ACTIVE = 1; /** - * Doctrine_Transaction is in busy state when it has multiple active transactions + * Doctrine_Transaction is in busy state when it has multiple active transactions. */ - const STATE_BUSY = 2; + public const STATE_BUSY = 2; /** - * @var integer $_nestingLevel The current nesting level of this transaction. - * A nesting level of 0 means there is currently no active - * transaction. + * @var int The current nesting level of this transaction. + * A nesting level of 0 means there is currently no active + * transaction. */ protected $_nestingLevel = 0; - + /** - * @var integer $_internalNestingLevel The current internal nesting level of this transaction. - * "Internal" means transactions started by Doctrine itself. - * Therefore the internal nesting level is always - * lower or equal to the overall nesting level. - * A level of 0 means there is currently no active - * transaction that was initiated by Doctrine itself. + * @var int The current internal nesting level of this transaction. + * "Internal" means transactions started by Doctrine itself. + * Therefore the internal nesting level is always + * lower or equal to the overall nesting level. + * A level of 0 means there is currently no active + * transaction that was initiated by Doctrine itself. */ protected $_internalNestingLevel = 0; /** - * @var array $invalid an array containing all invalid records within this transaction + * @var array an array containing all invalid records within this transaction + * * @todo What about a more verbose name? $invalidRecords? */ - protected $invalid = array(); + protected $invalid = array(); /** - * @var array $savepoints an array containing all savepoints + * @var array an array containing all savepoints */ - protected $savePoints = array(); + protected $savePoints = array(); /** - * @var array $_collections an array of Doctrine_Collection objects that were affected during the Transaction + * @var array an array of Doctrine_Collection objects that were affected during the Transaction */ - protected $_collections = array(); + protected $_collections = array(); /** * addCollection - * adds a collection in the internal array of collections + * adds a collection in the internal array of collections. * * at the end of each commit this array is looped over and * of every collection Doctrine then takes a snapshot in order * to keep the collections up to date with the database * - * @param Doctrine_Collection $coll a collection to be added - * @return Doctrine_Transaction this object + * @param Doctrine_Collection $coll a collection to be added + * + * @return Doctrine_Transaction this object */ public function addCollection(Doctrine_Collection $coll) { @@ -105,7 +107,8 @@ public function addCollection(Doctrine_Collection $coll) * returns the state of this transaction module. * * @see Doctrine_Connection_Transaction::STATE_* constants - * @return integer the connection state + * + * @return int the connection state */ public function getState() { @@ -123,11 +126,10 @@ public function getState() /** * addInvalid - * adds record into invalid records list + * adds record into invalid records list. * - * @param Doctrine_Record $record - * @return boolean false if record already existed in invalid records list, - * otherwise true + * @return bool false if record already existed in invalid records list, + * otherwise true */ public function addInvalid(Doctrine_Record $record) { @@ -135,15 +137,15 @@ public function addInvalid(Doctrine_Record $record) return false; } $this->invalid[] = $record; + return true; } - - /** - * Return the invalid records - * - * @return array An array of invalid records - */ + /** + * Return the invalid records. + * + * @return array An array of invalid records + */ public function getInvalid() { return $this->invalid; @@ -151,15 +153,15 @@ public function getInvalid() /** * getTransactionLevel - * get the current transaction nesting level + * get the current transaction nesting level. * - * @return integer + * @return int */ public function getTransactionLevel() { return $this->_nestingLevel; } - + public function getInternalTransactionLevel() { return $this->_internalNestingLevel; @@ -177,35 +179,37 @@ public function getInternalTransactionLevel() * * Listeners: onPreTransactionBegin, onTransactionBegin * - * @param string $savepoint name of a savepoint to set - * @throws Doctrine_Transaction_Exception if the transaction fails at database level - * @return integer current transaction nesting level + * @param string $savepoint name of a savepoint to set + * + * @return int current transaction nesting level + * + * @throws Doctrine_Transaction_Exception if the transaction fails at database level */ public function beginTransaction($savepoint = null) { $this->conn->connect(); - + $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER); - if ( ! is_null($savepoint)) { + if (!is_null($savepoint)) { $this->savePoints[] = $savepoint; $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_CREATE); $listener->preSavepointCreate($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->createSavePoint($savepoint); } $listener->postSavepointCreate($event); } else { - if ($this->_nestingLevel == 0) { + if (0 == $this->_nestingLevel) { $event = new Doctrine_Event($this, Doctrine_Event::TX_BEGIN); $listener->preTransactionBegin($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { try { $this->_doBeginTransaction(); } catch (Exception $e) { @@ -216,9 +220,7 @@ public function beginTransaction($savepoint = null) } } - $level = ++$this->_nestingLevel; - - return $level; + return ++$this->_nestingLevel; } /** @@ -228,44 +230,45 @@ public function beginTransaction($savepoint = null) * * Listeners: preTransactionCommit, postTransactionCommit * - * @param string $savepoint name of a savepoint to release - * @throws Doctrine_Transaction_Exception if the transaction fails at database level - * @throws Doctrine_Validator_Exception if the transaction fails due to record validations - * @return boolean false if commit couldn't be performed, true otherwise + * @param string $savepoint name of a savepoint to release + * + * @return bool false if commit couldn't be performed, true otherwise + * + * @throws Doctrine_Transaction_Exception if the transaction fails at database level + * @throws Doctrine_Validator_Exception if the transaction fails due to record validations */ public function commit($savepoint = null) { - if ($this->_nestingLevel == 0) { - throw new Doctrine_Transaction_Exception("Commit failed. There is no active transaction."); + if (0 == $this->_nestingLevel) { + throw new Doctrine_Transaction_Exception('Commit failed. There is no active transaction.'); } - + $this->conn->connect(); $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER); - if ( ! is_null($savepoint)) { + if (!is_null($savepoint)) { $this->_nestingLevel -= $this->removeSavePoints($savepoint); $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_COMMIT); $listener->preSavepointCommit($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->releaseSavePoint($savepoint); } $listener->postSavepointCommit($event); } else { - - if ($this->_nestingLevel == 1 || $this->_internalNestingLevel == 1) { - if ( ! empty($this->invalid)) { - if ($this->_internalNestingLevel == 1) { + if (1 == $this->_nestingLevel || 1 == $this->_internalNestingLevel) { + if (!empty($this->invalid)) { + if (1 == $this->_internalNestingLevel) { $tmp = $this->invalid; $this->invalid = array(); throw new Doctrine_Validator_Exception($tmp); } } - if ($this->_nestingLevel == 1) { + if (1 == $this->_nestingLevel) { // take snapshots of all collections used within this transaction foreach ($this->_collections as $coll) { $coll->takeSnapshot(); @@ -275,19 +278,19 @@ public function commit($savepoint = null) $event = new Doctrine_Event($this, Doctrine_Event::TX_COMMIT); $listener->preTransactionCommit($event); - if ( ! $event->skipOperation) { + if (!$event->skipOperation) { $this->_doCommit(); } $listener->postTransactionCommit($event); } } - + if ($this->_nestingLevel > 0) { - $this->_nestingLevel--; - } + --$this->_nestingLevel; + } if ($this->_internalNestingLevel > 0) { - $this->_internalNestingLevel--; - } + --$this->_internalNestingLevel; + } } return true; @@ -303,9 +306,12 @@ public function commit($savepoint = null) * this method can be listened with onPreTransactionRollback and onTransactionRollback * eventlistener methods * - * @param string $savepoint name of a savepoint to rollback to - * @throws Doctrine_Transaction_Exception if the rollback operation fails at database level - * @return boolean false if rollback couldn't be performed, true otherwise + * @param string $savepoint name of a savepoint to rollback to + * + * @return bool false if rollback couldn't be performed, true otherwise + * + * @throws Doctrine_Transaction_Exception if the rollback operation fails at database level + * * @todo Shouldnt this method only commit a rollback if the transactionLevel is 1 * (STATE_ACTIVE)? Explanation: Otherwise a rollback that is triggered from inside doctrine * in an (emulated) nested transaction would lead to a complete database level @@ -315,41 +321,44 @@ public function commit($savepoint = null) */ public function rollback($savepoint = null) { - if ($this->_nestingLevel == 0) { - throw new Doctrine_Transaction_Exception("Rollback failed. There is no active transaction."); + if (0 == $this->_nestingLevel) { + throw new Doctrine_Transaction_Exception('Rollback failed. There is no active transaction.'); } - + $this->conn->connect(); if ($this->_internalNestingLevel >= 1 && $this->_nestingLevel > 1) { - $this->_internalNestingLevel--; - $this->_nestingLevel--; + --$this->_internalNestingLevel; + --$this->_nestingLevel; + return false; - } else if ($this->_nestingLevel > 1) { - $this->_nestingLevel--; + } + if ($this->_nestingLevel > 1) { + --$this->_nestingLevel; + return false; } $listener = $this->conn->getAttribute(Doctrine_Core::ATTR_LISTENER); - if ( ! is_null($savepoint)) { + if (!is_null($savepoint)) { $this->_nestingLevel -= $this->removeSavePoints($savepoint); $event = new Doctrine_Event($this, Doctrine_Event::SAVEPOINT_ROLLBACK); $listener->preSavepointRollback($event); - - if ( ! $event->skipOperation) { + + if (!$event->skipOperation) { $this->rollbackSavePoint($savepoint); } $listener->postSavepointRollback($event); } else { $event = new Doctrine_Event($this, Doctrine_Event::TX_ROLLBACK); - + $listener->preTransactionRollback($event); - - if ( ! $event->skipOperation) { + + if (!$event->skipOperation) { $this->_nestingLevel = 0; $this->_internalNestingLevel = 0; try { @@ -367,10 +376,9 @@ public function rollback($savepoint = null) /** * releaseSavePoint - * creates a new savepoint + * creates a new savepoint. * - * @param string $savepoint name of a savepoint to create - * @return void + * @param string $savepoint name of a savepoint to create */ protected function createSavePoint($savepoint) { @@ -379,10 +387,9 @@ protected function createSavePoint($savepoint) /** * releaseSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to release - * @return void + * @param string $savepoint name of a savepoint to release */ protected function releaseSavePoint($savepoint) { @@ -391,16 +398,15 @@ protected function releaseSavePoint($savepoint) /** * rollbackSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to rollback to - * @return void + * @param string $savepoint name of a savepoint to rollback to */ protected function rollbackSavePoint($savepoint) { throw new Doctrine_Transaction_Exception('Savepoints not supported by this driver.'); } - + /** * Performs the rollback. */ @@ -408,7 +414,7 @@ protected function _doRollback() { $this->conn->getDbh()->rollback(); } - + /** * Performs the commit. */ @@ -416,7 +422,7 @@ protected function _doCommit() { $this->conn->getDbh()->commit(); } - + /** * Begins a database transaction. */ @@ -428,10 +434,11 @@ protected function _doBeginTransaction() /** * removeSavePoints * removes a savepoint from the internal savePoints array of this transaction object - * and all its children savepoints + * and all its children savepoints. * - * @param sring $savepoint name of the savepoint to remove - * @return integer removed savepoints + * @param sring $savepoint name of the savepoint to remove + * + * @return int removed savepoints */ private function removeSavePoints($savepoint) { @@ -441,13 +448,13 @@ private function removeSavePoints($savepoint) $i = 0; foreach ($this->savePoints as $key => $sp) { - if ( ! $found) { + if (!$found) { if ($sp === $savepoint) { $found = true; } } if ($found) { - $i++; + ++$i; unset($this->savePoints[$key]); } } @@ -456,7 +463,7 @@ private function removeSavePoints($savepoint) } /** - * setIsolation + * setIsolation. * * Set the transacton isolation level. * (implemented by the connection drivers) @@ -473,9 +480,8 @@ private function removeSavePoints($savepoint) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) * - * @throws Doctrine_Transaction_Exception if the feature is not supported by the driver - * @throws PDOException if something fails at the PDO level - * @return void + * @throws Doctrine_Transaction_Exception if the feature is not supported by the driver + * @throws PDOException if something fails at the PDO level */ public function setIsolation($isolation) { @@ -483,32 +489,35 @@ public function setIsolation($isolation) } /** - * getTransactionIsolation + * getTransactionIsolation. * * fetches the current session transaction isolation level * * note: some drivers may support setting the transaction isolation level * but not fetching it * - * @throws Doctrine_Transaction_Exception if the feature is not supported by the driver - * @throws PDOException if something fails at the PDO level - * @return string returns the current session transaction isolation level + * @return string returns the current session transaction isolation level + * + * @throws Doctrine_Transaction_Exception if the feature is not supported by the driver + * @throws PDOException if something fails at the PDO level */ public function getIsolation() { throw new Doctrine_Transaction_Exception('Fetching transaction isolation level not supported by this driver.'); } - + /** * Initiates a transaction. * * This method must only be used by Doctrine itself to initiate transactions. * Userland-code must use {@link beginTransaction()}. + * + * @param mixed|null $savepoint */ public function beginInternalTransaction($savepoint = null) { - $this->_internalNestingLevel++; + ++$this->_internalNestingLevel; + return $this->beginTransaction($savepoint); } - } diff --git a/lib/Doctrine/Transaction/Exception.php b/lib/Doctrine/Transaction/Exception.php index aa0a64e5c..04a953071 100644 --- a/lib/Doctrine/Transaction/Exception.php +++ b/lib/Doctrine/Transaction/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Transaction_Exception + * Doctrine_Transaction_Exception. * - * @package Doctrine - * @subpackage Transaction * @license http://www.opensource.org/licenses/lgpl-license.php LGPL * @author Konsta Vesterinen + * * @since 1.0 + * * @version $Revision: 7490 $ - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org */ class Doctrine_Transaction_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Transaction/Mock.php b/lib/Doctrine/Transaction/Mock.php index aab70ad8b..5928016c9 100644 --- a/lib/Doctrine/Transaction/Mock.php +++ b/lib/Doctrine/Transaction/Mock.php @@ -21,16 +21,17 @@ /** * Doctrine_Transaction_Mock - * This class is used for testing purposes + * This class is used for testing purposes. * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ */ class Doctrine_Transaction_Mock extends Doctrine_Transaction -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Transaction/Mssql.php b/lib/Doctrine/Transaction/Mssql.php index a347b9c2f..a92b7105e 100644 --- a/lib/Doctrine/Transaction/Mssql.php +++ b/lib/Doctrine/Transaction/Mssql.php @@ -20,14 +20,13 @@ */ /** - * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Mssql extends Doctrine_Transaction @@ -44,12 +43,13 @@ class Doctrine_Transaction_Mssql extends Doctrine_Transaction * mssql specific modes: * SNAPSHOT * - * @link http://msdn2.microsoft.com/en-us/library/ms173763.aspx - * @throws PDOException if something fails at the PDO level - * @throws Doctrine_Transaction_Exception if using unknown isolation level or unknown wait option - * @return void + * @see http://msdn2.microsoft.com/en-us/library/ms173763.aspx + * + * @throws PDOException if something fails at the PDO level + * @throws Doctrine_Transaction_Exception if using unknown isolation level or unknown wait option */ - public function setIsolation($isolation, $options = array()) { + public function setIsolation($isolation, $options = array()) + { switch ($isolation) { case 'READ UNCOMMITTED': case 'READ COMMITTED': @@ -58,14 +58,14 @@ public function setIsolation($isolation, $options = array()) { case 'SNAPSHOT': break; default: - throw new Doctrine_Transaction_Exception('isolation level is not supported: ' . $isolation); + throw new Doctrine_Transaction_Exception('isolation level is not supported: '.$isolation); } - $query = 'SET TRANSACTION ISOLATION LEVEL ' . $isolation; + $query = 'SET TRANSACTION ISOLATION LEVEL '.$isolation; $this->conn->execute($query); } - + /** * Performs the rollback. */ @@ -73,7 +73,7 @@ protected function _doRollback() { $this->conn->getDbh()->exec('ROLLBACK TRANSACTION'); } - + /** * Performs the commit. */ @@ -81,7 +81,7 @@ protected function _doCommit() { $this->conn->getDbh()->exec('COMMIT TRANSACTION'); } - + /** * Begins a database transaction. */ @@ -89,4 +89,4 @@ protected function _doBeginTransaction() { $this->conn->getDbh()->exec('BEGIN TRANSACTION'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction/Mysql.php b/lib/Doctrine/Transaction/Mysql.php index 412e729a8..227d2c18b 100644 --- a/lib/Doctrine/Transaction/Mysql.php +++ b/lib/Doctrine/Transaction/Mysql.php @@ -20,56 +20,52 @@ */ /** - * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Mysql extends Doctrine_Transaction { /** * createSavepoint - * creates a new savepoint + * creates a new savepoint. * - * @param string $savepoint name of a savepoint to set - * @return void + * @param string $savepoint name of a savepoint to set */ protected function createSavePoint($savepoint) { - $query = 'SAVEPOINT ' . $savepoint; + $query = 'SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * releaseSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to release - * @return void + * @param string $savepoint name of a savepoint to release */ protected function releaseSavePoint($savepoint) { - $query = 'RELEASE SAVEPOINT ' . $savepoint; + $query = 'RELEASE SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * rollbackSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to rollback to - * @return void + * @param string $savepoint name of a savepoint to rollback to */ protected function rollbackSavePoint($savepoint) { - $query = 'ROLLBACK TO SAVEPOINT ' . $savepoint; + $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; return $this->conn->execute($query); } @@ -83,9 +79,8 @@ protected function rollbackSavePoint($savepoint) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) * - * @throws Doctrine_Transaction_Exception if using unknown isolation level - * @throws PDOException if something fails at the PDO level - * @return void + * @throws Doctrine_Transaction_Exception if using unknown isolation level + * @throws PDOException if something fails at the PDO level */ public function setIsolation($isolation) { @@ -96,21 +91,21 @@ public function setIsolation($isolation) case 'SERIALIZABLE': break; default: - throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . ' is not supported.'); + throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.' is not supported.'); } - $query = 'SET SESSION TRANSACTION ISOLATION LEVEL ' . $isolation; + $query = 'SET SESSION TRANSACTION ISOLATION LEVEL '.$isolation; return $this->conn->execute($query); } /** - * getTransactionIsolation + * getTransactionIsolation. * - * @return string returns the current session transaction isolation level + * @return string returns the current session transaction isolation level */ public function getIsolation() { return $this->conn->fetchOne('SELECT @@tx_isolation'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction/Oracle.php b/lib/Doctrine/Transaction/Oracle.php index 9098cd837..feb1a9d28 100644 --- a/lib/Doctrine/Transaction/Oracle.php +++ b/lib/Doctrine/Transaction/Oracle.php @@ -20,38 +20,35 @@ */ /** - * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Oracle extends Doctrine_Transaction { /** * createSavepoint - * creates a new savepoint + * creates a new savepoint. * - * @param string $savepoint name of a savepoint to set - * @return void + * @param string $savepoint name of a savepoint to set */ protected function createSavePoint($savepoint) { - $query = 'SAVEPOINT ' . $savepoint; + $query = 'SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * releaseSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to release - * @return void + * @param string $savepoint name of a savepoint to release */ protected function releaseSavePoint($savepoint) { @@ -61,14 +58,13 @@ protected function releaseSavePoint($savepoint) /** * rollbackSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to rollback to - * @return void + * @param string $savepoint name of a savepoint to rollback to */ protected function rollbackSavePoint($savepoint) { - $query = 'ROLLBACK TO SAVEPOINT ' . $savepoint; + $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; return $this->conn->execute($query); } @@ -81,9 +77,9 @@ protected function rollbackSavePoint($savepoint) * READ COMMITTED (prevents dirty reads) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) - * @throws PDOException if something fails at the PDO level - * @throws Doctrine_Transaction_Exception if using unknown isolation level - * @return void + * + * @throws PDOException if something fails at the PDO level + * @throws Doctrine_Transaction_Exception if using unknown isolation level */ public function setIsolation($isolation) { @@ -97,10 +93,11 @@ public function setIsolation($isolation) $isolation = 'SERIALIZABLE'; break; default: - throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . ' is not supported.'); + throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.' is not supported.'); } - $query = 'ALTER SESSION SET ISOLATION_LEVEL = ' . $isolation; + $query = 'ALTER SESSION SET ISOLATION_LEVEL = '.$isolation; + return $this->conn->execute($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction/Pgsql.php b/lib/Doctrine/Transaction/Pgsql.php index d4ba042d8..bbb900e1b 100644 --- a/lib/Doctrine/Transaction/Pgsql.php +++ b/lib/Doctrine/Transaction/Pgsql.php @@ -20,57 +20,53 @@ */ /** - * * @author Konsta Vesterinen * @author Paul Cooper (PEAR MDB2 Pgsql driver) * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Pgsql extends Doctrine_Transaction { /** * createSavepoint - * creates a new savepoint + * creates a new savepoint. * - * @param string $savepoint name of a savepoint to set - * @return void + * @param string $savepoint name of a savepoint to set */ protected function createSavePoint($savepoint) { - $query = 'SAVEPOINT ' . $savepoint; + $query = 'SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * releaseSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to release - * @return void + * @param string $savepoint name of a savepoint to release */ protected function releaseSavePoint($savepoint) { - $query = 'RELEASE SAVEPOINT ' . $savepoint; + $query = 'RELEASE SAVEPOINT '.$savepoint; return $this->conn->execute($query); } /** * rollbackSavePoint - * releases given savepoint + * releases given savepoint. * - * @param string $savepoint name of a savepoint to rollback to - * @return void + * @param string $savepoint name of a savepoint to rollback to */ protected function rollbackSavePoint($savepoint) { - $query = 'ROLLBACK TO SAVEPOINT ' . $savepoint; + $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; return $this->conn->execute($query); } @@ -83,9 +79,9 @@ protected function rollbackSavePoint($savepoint) * READ COMMITTED (prevents dirty reads) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) - * @throws PDOException if something fails at the PDO level - * @throws Doctrine_Transaction_Exception if using unknown isolation level or unknown wait option - * @return void + * + * @throws PDOException if something fails at the PDO level + * @throws Doctrine_Transaction_Exception if using unknown isolation level or unknown wait option */ public function setIsolation($isolation) { @@ -99,7 +95,8 @@ public function setIsolation($isolation) throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.' is not supported.'); } - $query = 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ' . $isolation; + $query = 'SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL '.$isolation; + return $this->conn->execute($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Transaction/Sqlite.php b/lib/Doctrine/Transaction/Sqlite.php index 7e343d1ef..3d312c33f 100644 --- a/lib/Doctrine/Transaction/Sqlite.php +++ b/lib/Doctrine/Transaction/Sqlite.php @@ -20,14 +20,13 @@ */ /** - * * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @subpackage Transaction - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Transaction_Sqlite extends Doctrine_Transaction @@ -40,9 +39,9 @@ class Doctrine_Transaction_Sqlite extends Doctrine_Transaction * READ COMMITTED (prevents dirty reads) * REPEATABLE READ (prevents nonrepeatable reads) * SERIALIZABLE (prevents phantom reads) - * @throws PDOException if something fails at the PDO level - * @throws Doctrine_Transaction_Exception if using unknown isolation level - * @return void + * + * @throws PDOException if something fails at the PDO level + * @throws Doctrine_Transaction_Exception if using unknown isolation level */ public function setIsolation($isolation) { @@ -56,11 +55,11 @@ public function setIsolation($isolation) $isolation = 1; break; default: - throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . 'is not supported.'); + throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.'is not supported.'); } - $query = 'PRAGMA read_uncommitted = ' . $isolation; + $query = 'PRAGMA read_uncommitted = '.$isolation; return $this->conn->execute($query); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Tree.php b/lib/Doctrine/Tree.php index ec1ed5955..4f53b64ba 100644 --- a/lib/Doctrine/Tree.php +++ b/lib/Doctrine/Tree.php @@ -18,22 +18,23 @@ * and is licensed under the LGPL. For more information, see * . */ - + /** - * Doctrine_Tree + * Doctrine_Tree. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ class Doctrine_Tree { /** - * @param object $table reference to associated Doctrine_Table instance + * @param object $table reference to associated Doctrine_Table instance */ protected $table; @@ -41,14 +42,14 @@ class Doctrine_Tree * @param array $options */ protected $options = array(); - + protected $_baseComponent; /** - * constructor, creates tree with reference to table and any options + * constructor, creates tree with reference to table and any options. * - * @param object $table instance of Doctrine_Table - * @param array $options options + * @param object $table instance of Doctrine_Table + * @param array $options options */ public function __construct(Doctrine_Table $table, $options) { @@ -63,13 +64,13 @@ public function __construct(Doctrine_Table $table, $options) } $this->_baseComponent = $class; } - //echo $this->_baseComponent; + // echo $this->_baseComponent; } /** - * Used to define table attributes required for the given implementation + * Used to define table attributes required for the given implementation. * - * @throws Doctrine_Tree_Exception if table attributes have not been defined + * @throws Doctrine_Tree_Exception if table attributes have not been defined */ public function setTableDefinition() { @@ -77,8 +78,7 @@ public function setTableDefinition() } /** - * this method is used for setting up relations and attributes and should be used by specific implementations - * + * this method is used for setting up relations and attributes and should be used by specific implementations. */ public function setUp() { @@ -87,41 +87,40 @@ public function setUp() /** * Factory method to create a Tree. * - * This is a factory method that returns a tree instance based upon + * This is a factory method that returns a tree instance based upon * chosen implementation. * - * @param object $table instance of Doctrine_Table - * @param string $impName implementation (NestedSet, AdjacencyList, MaterializedPath) - * @param array $options options + * @param object $table instance of Doctrine_Table + * @param array $options options + * * @return Doctrine_Tree - * @throws Doctrine_Exception if class $implName does not extend Doctrine_Tree + * + * @throws Doctrine_Exception if class $implName does not extend Doctrine_Tree */ public static function factory(Doctrine_Table $table, $implName, $options = array()) { - $class = 'Doctrine_Tree_' . $implName; - if ( ! class_exists($class)) { + $class = 'Doctrine_Tree_'.$implName; + if (!class_exists($class)) { throw new Doctrine_Exception('The chosen class must extend Doctrine_Tree'); } + return new $class($table, $options); } /** - * gets tree attribute value - * - */ + * gets tree attribute value. + */ public function getAttribute($name) { - return isset($this->options[$name]) ? $this->options[$name] : null; + return isset($this->options[$name]) ? $this->options[$name] : null; } /** - * sets tree attribute value - * - * @param mixed + * sets tree attribute value. */ public function setAttribute($name, $value) { - $this->options[$name] = $value; + $this->options[$name] = $value; } /** diff --git a/lib/Doctrine/Tree/AdjacencyList.php b/lib/Doctrine/Tree/AdjacencyList.php index 4430289c9..6c80e0459 100644 --- a/lib/Doctrine/Tree/AdjacencyList.php +++ b/lib/Doctrine/Tree/AdjacencyList.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Tree_AdjacencyList + * Doctrine_Tree_AdjacencyList. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Tree_AdjacencyList extends Doctrine_Tree implements Doctrine_Tree_Interface -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Tree/Exception.php b/lib/Doctrine/Tree/Exception.php index 0f3846155..6c76d2fc6 100644 --- a/lib/Doctrine/Tree/Exception.php +++ b/lib/Doctrine/Tree/Exception.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Tree_Exception + * Doctrine_Tree_Exception. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Tree_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Tree/Interface.php b/lib/Doctrine/Tree/Interface.php index 4a88116c4..f448850b4 100644 --- a/lib/Doctrine/Tree/Interface.php +++ b/lib/Doctrine/Tree/Interface.php @@ -20,48 +20,51 @@ */ /** - * Doctrine_Tree_Interface + * Doctrine_Tree_Interface. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ -interface Doctrine_Tree_Interface { - +interface Doctrine_Tree_Interface +{ /** - * creates root node from given record or from a new record + * creates root node from given record or from a new record. * - * @param Doctrine_Record $record instance of Doctrine_Record + * @param Doctrine_Record $record instance of Doctrine_Record */ public function createRoot(Doctrine_Record $record = null); /** - * returns root node + * returns root node. * * @return Doctrine_Record */ public function fetchRoot($root_id = 1); /** - * optimised method to returns iterator for traversal of the entire tree from root + * optimised method to returns iterator for traversal of the entire tree from root. + * + * @param array $options options + * @param mixed|null $hydrationMode * - * @param array $options options - * @param integer $fetchmode One of the Doctrine_Core::HYDRATE_* constants. - * @return Iterator instance of Doctrine_Node__PreOrderIterator + * @return Iterator instance of Doctrine_Node__PreOrderIterator */ public function fetchTree($options = array(), $hydrationMode = null); /** - * optimised method that returns iterator for traversal of the tree from the given record primary key + * optimised method that returns iterator for traversal of the tree from the given record primary key. + * + * @param mixed $pk primary key as used by table::find() to locate node to traverse tree from + * @param array $options options + * @param mixed|null $hydrationMode * - * @param mixed $pk primary key as used by table::find() to locate node to traverse tree from - * @param array $options options - * @param integer $fetchmode One of the Doctrine_Core::HYDRATE_* constants. - * @return iterator instance of Doctrine_Node__PreOrderIterator + * @return iterator instance of Doctrine_Node__PreOrderIterator */ public function fetchBranch($pk, $options = array(), $hydrationMode = null); -} \ No newline at end of file +} diff --git a/lib/Doctrine/Tree/MaterializedPath.php b/lib/Doctrine/Tree/MaterializedPath.php index 9fb5d436e..babaa0583 100644 --- a/lib/Doctrine/Tree/MaterializedPath.php +++ b/lib/Doctrine/Tree/MaterializedPath.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Tree_MaterializedPath + * Doctrine_Tree_MaterializedPath. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms */ abstract class Doctrine_Tree_MaterializedPath extends Doctrine_Tree implements Doctrine_Tree_Interface -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Tree/NestedSet.php b/lib/Doctrine/Tree/NestedSet.php index 53ba87269..9537de2e5 100644 --- a/lib/Doctrine/Tree/NestedSet.php +++ b/lib/Doctrine/Tree/NestedSet.php @@ -20,27 +20,28 @@ */ /** - * Doctrine_Tree_NestedSet + * Doctrine_Tree_NestedSet. * - * @package Doctrine - * @subpackage Tree * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Joe Simms * @author Roman Borschel */ class Doctrine_Tree_NestedSet extends Doctrine_Tree implements Doctrine_Tree_Interface { private $_baseQuery; - private $_baseAlias = "base"; + private $_baseAlias = 'base'; /** - * constructor, creates tree with reference to table and sets default root options + * constructor, creates tree with reference to table and sets default root options. * - * @param object $table instance of Doctrine_Table - * @param array $options options + * @param object $table instance of Doctrine_Table + * @param array $options options */ public function __construct(Doctrine_Table $table, $options) { @@ -55,8 +56,7 @@ public function __construct(Doctrine_Table $table, $options) /** * used to define table attributes required for the NestetSet implementation - * adds lft and rgt columns for corresponding left and right values - * + * adds lft and rgt columns for corresponding left and right values. */ public function setTableDefinition() { @@ -67,7 +67,7 @@ public function setTableDefinition() $this->table->setColumn('lft', 'integer', 4); $this->table->setColumn('rgt', 'integer', 4); if ($level = $this->getAttribute('levelColumnName')) { - $this->table->setColumn($level . ' AS level', 'integer', 2); + $this->table->setColumn($level.' AS level', 'integer', 2); } else { $this->table->setColumn('level', 'integer', 2); } @@ -82,27 +82,24 @@ public function setTableDefinition() * the records id will be assigned to the root id. You must use numeric columns for the id * and root id columns. * - * @param object $record instance of Doctrine_Record + * @param object $record instance of Doctrine_Record */ public function createRoot(Doctrine_Record $record = null) { if ($this->getAttribute('hasManyRoots')) { - if ( ! $record || ( ! $record->exists() && ! $record->getNode()->getRootValue()) + if (!$record || (!$record->exists() && !$record->getNode()->getRootValue()) || $record->getTable()->isIdentifierComposite()) { - throw new Doctrine_Tree_Exception("Node must have a root id set or must " - . " be persistent and have a single-valued numeric primary key in order to" - . " be created as a root node. Automatic assignment of a root id on" - . " transient/new records is no longer supported."); + throw new Doctrine_Tree_Exception('Node must have a root id set or must be persistent and have a single-valued numeric primary key in order to be created as a root node. Automatic assignment of a root id on transient/new records is no longer supported.'); } - - if ($record->exists() && ! $record->getNode()->getRootValue()) { + + if ($record->exists() && !$record->getNode()->getRootValue()) { // Default: root_id = id $identifier = $record->getTable()->getIdentifier(); $record->getNode()->setRootValue($record->get($identifier)); } } - - if ( ! $record) { + + if (!$record) { $record = $this->table->create(); } @@ -118,14 +115,15 @@ public function createRoot(Doctrine_Record $record = null) /** * Fetches a/the root node. * - * @param integer $rootId + * @param int $rootId + * * @todo Better $rootid = null and exception if $rootId == null && hasManyRoots? * Fetching with id = 1 is too magical and cant work reliably anyway. */ public function fetchRoot($rootId = 1) { $q = $this->getBaseQuery(); - $q = $q->addWhere($this->_baseAlias . '.lft = ?', 1); + $q = $q->addWhere($this->_baseAlias.'.lft = ?', 1); // if tree has many roots, then specify root id $q = $this->returnQueryWithRootId($q, $rootId); @@ -138,11 +136,11 @@ public function fetchRoot($rootId = 1) if ($data instanceof Doctrine_Collection) { $root = $data->getFirst(); $root['level'] = 0; - } else if (is_array($data)) { + } elseif (is_array($data)) { $root = array_shift($data); $root['level'] = 0; } else { - throw new Doctrine_Tree_Exception("Unexpected data structure returned."); + throw new Doctrine_Tree_Exception('Unexpected data structure returned.'); } return $root; @@ -151,9 +149,10 @@ public function fetchRoot($rootId = 1) /** * Fetches a tree. * - * @param array $options Options - * @param integer $fetchmode One of the Doctrine_Core::HYDRATE_* constants. - * @return mixed The tree or FALSE if the tree could not be found. + * @param array $options Options + * @param mixed|null $hydrationMode + * + * @return mixed the tree or FALSE if the tree could not be found */ public function fetchTree($options = array(), $hydrationMode = null) { @@ -162,19 +161,19 @@ public function fetchTree($options = array(), $hydrationMode = null) $depth = isset($options['depth']) ? $options['depth'] : null; - $q->addWhere($this->_baseAlias . ".lft >= ?", 1); + $q->addWhere($this->_baseAlias.'.lft >= ?', 1); // if tree has many roots, then specify root id $rootId = isset($options['root_id']) ? $options['root_id'] : '1'; if (is_array($rootId)) { - $q->addOrderBy($this->_baseAlias . "." . $this->getAttribute('rootColumnName') . - ", " . $this->_baseAlias . ".lft ASC"); + $q->addOrderBy($this->_baseAlias.'.'.$this->getAttribute('rootColumnName'). + ', '.$this->_baseAlias.'.lft ASC'); } else { - $q->addOrderBy($this->_baseAlias . ".lft ASC"); + $q->addOrderBy($this->_baseAlias.'.lft ASC'); } - if ( ! is_null($depth)) { - $q->addWhere($this->_baseAlias . ".level BETWEEN ? AND ?", array(0, $depth)); + if (!is_null($depth)) { + $q->addWhere($this->_baseAlias.'.level BETWEEN ? AND ?', array(0, $depth)); } $q = $this->returnQueryWithRootId($q, $rootId); @@ -191,16 +190,18 @@ public function fetchTree($options = array(), $hydrationMode = null) /** * Fetches a branch of a tree. * - * @param mixed $pk primary key as used by table::find() to locate node to traverse tree from - * @param array $options Options. - * @param integer $fetchmode One of the Doctrine_Core::HYDRATE_* constants. - * @return mixed The branch or FALSE if the branch could not be found. + * @param mixed $pk primary key as used by table::find() to locate node to traverse tree from + * @param array $options options + * @param mixed|null $hydrationMode + * + * @return mixed the branch or FALSE if the branch could not be found + * * @todo Only fetch the lft and rgt values of the initial record. more is not needed. */ public function fetchBranch($pk, $options = array(), $hydrationMode = null) { $record = $this->table->find($pk); - if ( ! ($record instanceof Doctrine_Record) || !$record->exists()) { + if (!($record instanceof Doctrine_Record) || !$record->exists()) { // TODO: if record doesn't exist, throw exception or similar? return false; } @@ -209,11 +210,12 @@ public function fetchBranch($pk, $options = array(), $hydrationMode = null) $q = $this->getBaseQuery(); $params = array($record->get('lft'), $record->get('rgt')); - $q->addWhere($this->_baseAlias . ".lft >= ? AND " . $this->_baseAlias . ".rgt <= ?", $params) - ->addOrderBy($this->_baseAlias . ".lft asc"); + $q->addWhere($this->_baseAlias.'.lft >= ? AND '.$this->_baseAlias.'.rgt <= ?', $params) + ->addOrderBy($this->_baseAlias.'.lft asc') + ; - if ( ! is_null($depth)) { - $q->addWhere($this->_baseAlias . ".level BETWEEN ? AND ?", array($record->get('level'), $record->get('level')+$depth)); + if (!is_null($depth)) { + $q->addWhere($this->_baseAlias.'.level BETWEEN ? AND ?', array($record->get('level'), $record->get('level') + $depth)); } $q = $this->returnQueryWithRootId($q, $record->getNode()->getRootValue()); @@ -225,30 +227,31 @@ public function fetchBranch($pk, $options = array(), $hydrationMode = null) * Fetches all root nodes. If the tree has only one root this is the same as * fetchRoot(). * - * @return mixed The root nodes. + * @return mixed the root nodes */ public function fetchRoots() { $q = $this->getBaseQuery(); - $q = $q->addWhere($this->_baseAlias . '.lft = ?', 1); + $q = $q->addWhere($this->_baseAlias.'.lft = ?', 1); + return $q->execute(); } /** - * returns parsed query with root id where clause added if applicable + * returns parsed query with root id where clause added if applicable. + * + * @param object $query Doctrine_Query * - * @param object $query Doctrine_Query - * @param integer $root_id id of destination root * @return Doctrine_Query */ public function returnQueryWithRootId($query, $rootId = 1) { if ($root = $this->getAttribute('rootColumnName')) { if (is_array($rootId)) { - $query->addWhere($root . ' IN (' . implode(',', array_fill(0, count($rootId), '?')) . ')', - $rootId); + $query->addWhere($root.' IN ('.implode(',', array_fill(0, count($rootId), '?')).')', + $rootId); } else { - $query->addWhere($root . ' = ?', $rootId); + $query->addWhere($root.' = ?', $rootId); } } @@ -258,20 +261,19 @@ public function returnQueryWithRootId($query, $rootId = 1) /** * Enter description here... * - * @param array $options * @return unknown */ public function getBaseQuery() { - if ( ! isset($this->_baseQuery)) { + if (!isset($this->_baseQuery)) { $this->_baseQuery = $this->_createBaseQuery(); } + return $this->_baseQuery->copy(); } /** * Enter description here... - * */ public function getBaseAlias() { @@ -280,35 +282,32 @@ public function getBaseAlias() /** * Enter description here... - * */ private function _createBaseQuery() { - $this->_baseAlias = "base"; - $q = Doctrine_Core::getTable($this->getBaseComponent()) + $this->_baseAlias = 'base'; + + return Doctrine_Core::getTable($this->getBaseComponent()) ->createQuery($this->_baseAlias) - ->select($this->_baseAlias . '.*'); - return $q; + ->select($this->_baseAlias.'.*') + ; } /** * Enter description here... - * - * @param Doctrine_Query $query */ public function setBaseQuery(Doctrine_Query $query) { $this->_baseAlias = $query->getRootAlias(); - $query->addSelect($this->_baseAlias . ".lft, " . $this->_baseAlias . ".rgt, ". $this->_baseAlias . ".level"); + $query->addSelect($this->_baseAlias.'.lft, '.$this->_baseAlias.'.rgt, '.$this->_baseAlias.'.level'); if ($this->getAttribute('rootColumnName')) { - $query->addSelect($this->_baseAlias . "." . $this->getAttribute('rootColumnName')); + $query->addSelect($this->_baseAlias.'.'.$this->getAttribute('rootColumnName')); } $this->_baseQuery = $query; } /** * Enter description here... - * */ public function resetBaseQuery() { diff --git a/lib/Doctrine/Util.php b/lib/Doctrine/Util.php index 2001bae29..d4ecd63c8 100644 --- a/lib/Doctrine/Util.php +++ b/lib/Doctrine/Util.php @@ -20,15 +20,17 @@ */ /** - * Doctrine_Util + * Doctrine_Util. * - * @package Doctrine - * @subpackage Util * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Konsta Vesterinen */ class Doctrine_Util extends Doctrine_Connection_Module -{ } \ No newline at end of file +{ +} diff --git a/lib/Doctrine/Validator.php b/lib/Doctrine/Validator.php index bab8fe82c..903ce771c 100644 --- a/lib/Doctrine/Validator.php +++ b/lib/Doctrine/Validator.php @@ -20,51 +20,50 @@ */ /** - * This class is responsible for performing all validations on record properties + * This class is responsible for performing all validations on record properties. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Roman Borschel * @author Konsta Vesterinen */ class Doctrine_Validator extends Doctrine_Locator_Injectable { /** - * @var array $validators an array of validator objects + * @var array an array of validator objects */ private static $validators = array(); /** - * Get a validator instance for the passed $name + * Get a validator instance for the passed $name. + * + * @param string $name Name of the validator or the validator class name * - * @param string $name Name of the validator or the validator class name * @return Doctrine_Validator_Interface $validator */ public static function getValidator($name) { - if ( ! isset(self::$validators[$name])) { - $class = 'Doctrine_Validator_' . ucwords(strtolower($name)); + if (!isset(self::$validators[$name])) { + $class = 'Doctrine_Validator_'.ucwords(strtolower($name)); if (class_exists($class)) { - self::$validators[$name] = new $class; - } else if (class_exists($name)) { - self::$validators[$name] = new $name; + self::$validators[$name] = new $class(); + } elseif (class_exists($name)) { + self::$validators[$name] = new $name(); } else { - throw new Doctrine_Exception("Validator named '$name' not available."); + throw new Doctrine_Exception("Validator named '{$name}' not available."); } - } + return self::$validators[$name]; } /** - * Validates a given record and saves possible errors in Doctrine_Validator::$stack - * - * @param Doctrine_Record $record - * @return void + * Validates a given record and saves possible errors in Doctrine_Validator::$stack. */ public function validateRecord(Doctrine_Record $record) { @@ -72,7 +71,7 @@ public function validateRecord(Doctrine_Record $record) // if record is transient all fields will be validated // if record is persistent only the modified fields will be validated - $fields = $record->exists() ? $record->getModified():$record->getData(); + $fields = $record->exists() ? $record->getModified() : $record->getData(); foreach ($fields as $fieldName => $value) { $table->validateField($fieldName, $value, $record); } @@ -82,21 +81,23 @@ public function validateRecord(Doctrine_Record $record) /** * Validates the length of a field. * - * @param string $value Value to validate - * @param string $type Type of field being validated - * @param string $maximumLength Maximum length allowed for the column - * @return boolean $success True/false for whether the value passed validation + * @param string $value Value to validate + * @param string $type Type of field being validated + * @param string $maximumLength Maximum length allowed for the column + * + * @return bool $success True/false for whether the value passed validation */ public static function validateLength($value, $type, $maximumLength) { - if ($maximumLength === null ) { + if (null === $maximumLength) { return true; } - if ($type == 'timestamp' || $type == 'integer' || $type == 'enum') { + if ('timestamp' == $type || 'integer' == $type || 'enum' == $type) { return true; - } else if ($type == 'array' || $type == 'object') { + } + if ('array' == $type || 'object' == $type) { $length = strlen(serialize($value)); - } else if ($type == 'decimal' || $type == 'float') { + } elseif ('decimal' == $type || 'float' == $type) { $value = abs($value); $localeInfo = localeconv(); @@ -108,7 +109,7 @@ public static function validateLength($value, $type, $maximumLength) if (isset($e[1])) { $length += strlen($e[1]); } - } else if ($type === 'blob') { + } elseif ('blob' === $type) { $length = strlen($value); } else { $length = self::getStringLength($value); @@ -118,36 +119,38 @@ public static function validateLength($value, $type, $maximumLength) } /** - * Get length of passed string. Will use multibyte character functions if they exist + * Get length of passed string. Will use multibyte character functions if they exist. * * @param string $string - * @return integer $length + * + * @return int $length */ public static function getStringLength($string) { if (function_exists('mb_strlen')) { return mb_strlen((string) $string, 'utf8'); - } else { - return strlen(utf8_decode((string) $string)); } + + return strlen(utf8_decode((string) $string)); } /** - * Whether or not errors exist on this validator + * Whether or not errors exist on this validator. * - * @return boolean True/false for whether or not this validate instance has error + * @return bool True/false for whether or not this validate instance has error */ public function hasErrors() { - return (count($this->stack) > 0); + return count($this->stack) > 0; } /** - * Validate the type of the passed variable + * Validate the type of the passed variable. * - * @param mixed $var Variable to validate - * @param string $type Type of the variable expected - * @return boolean + * @param mixed $var Variable to validate + * @param string $type Type of the variable expected + * + * @return bool */ public static function isValidType($var, $type) { @@ -155,16 +158,16 @@ public static function isValidType($var, $type) return true; } - if ($var === null) { + if (null === $var) { return true; } if (is_array($var)) { - return $type === 'array'; + return 'array' === $type; } if (is_object($var)) { - return $type === 'object'; + return 'object' === $type; } switch ($type) { @@ -173,7 +176,7 @@ public static function isValidType($var, $type) case 'decimal': return (string) $var == (string) (float) $var; case 'integer': - return (string) $var === (string)round((float) $var); + return (string) $var === (string) round((float) $var); case 'string': return is_string($var) || is_numeric($var); case 'blob': @@ -186,15 +189,18 @@ public static function isValidType($var, $type) case 'object': return is_object($var); case 'boolean': - return is_bool($var) || (is_numeric($var) && ($var == 0 || $var == 1)); + return is_bool($var) || (is_numeric($var) && (0 == $var || 1 == $var)); case 'timestamp': $validator = self::getValidator('timestamp'); + return $validator->validate($var); case 'time': $validator = self::getValidator('time'); + return $validator->validate($var); case 'date': $validator = self::getValidator('date'); + return $validator->validate($var); case 'enum': return is_string($var) || is_int($var); diff --git a/lib/Doctrine/Validator/Country.php b/lib/Doctrine/Validator/Country.php index 2029721a8..01146d536 100644 --- a/lib/Doctrine/Validator/Country.php +++ b/lib/Doctrine/Validator/Country.php @@ -20,265 +20,266 @@ */ /** - * Doctrine_Validator_Country + * Doctrine_Validator_Country. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Country extends Doctrine_Validator_Driver { private static $countries = array( - 'ad' => 'Andorra', - 'ae' => 'United Arab Emirates', - 'af' => 'Afghanistan', - 'ag' => 'Antigua and Barbuda', - 'ai' => 'Anguilla', - 'al' => 'Albania', - 'am' => 'Armenia', - 'an' => 'Netherlands Antilles', - 'ao' => 'Angola', - 'aq' => 'Antarctica', - 'ar' => 'Argentina', - 'as' => 'American Samoa', - 'at' => 'Austria', - 'au' => 'Australia', - 'aw' => 'Aruba', - 'az' => 'Azerbaijan', - 'ba' => 'Bosnia Hercegovina', - 'bb' => 'Barbados', - 'bd' => 'Bangladesh', - 'be' => 'Belgium', - 'bf' => 'Burkina Faso', - 'bg' => 'Bulgaria', - 'bh' => 'Bahrain', - 'bi' => 'Burundi', - 'bj' => 'Benin', - 'bm' => 'Bermuda', - 'bn' => 'Brunei Darussalam', - 'bo' => 'Bolivia', - 'br' => 'Brazil', - 'bs' => 'Bahamas', - 'bt' => 'Bhutan', - 'bv' => 'Bouvet Island', - 'bw' => 'Botswana', - 'by' => 'Belarus (Byelorussia)', - 'bz' => 'Belize', - 'ca' => 'Canada', - 'cc' => 'Cocos Islands', - 'cd' => 'Congo, The Democratic Republic of the', - 'cf' => 'Central African Republic', - 'cg' => 'Congo', - 'ch' => 'Switzerland', - 'ci' => 'Ivory Coast', - 'ck' => 'Cook Islands', - 'cl' => 'Chile', - 'cm' => 'Cameroon', - 'cn' => 'China', - 'co' => 'Colombia', - 'cr' => 'Costa Rica', - 'cs' => 'Czechoslovakia', - 'cu' => 'Cuba', - 'cv' => 'Cape Verde', - 'cx' => 'Christmas Island', - 'cy' => 'Cyprus', - 'cz' => 'Czech Republic', - 'de' => 'Germany', - 'dj' => 'Djibouti', - 'dk' => 'Denmark', - 'dm' => 'Dominica', - 'do' => 'Dominican Republic', - 'dz' => 'Algeria', - 'ec' => 'Ecuador', - 'ee' => 'Estonia', - 'eg' => 'Egypt', - 'eh' => 'Western Sahara', - 'er' => 'Eritrea', - 'es' => 'Spain', - 'et' => 'Ethiopia', - 'fi' => 'Finland', - 'fj' => 'Fiji', - 'fk' => 'Falkland Islands', - 'fm' => 'Micronesia', - 'fo' => 'Faroe Islands', - 'fr' => 'France', - 'fx' => 'France, Metropolitan FX', - 'ga' => 'Gabon', - 'gb' => 'United Kingdom (Great Britain)', - 'gd' => 'Grenada', - 'ge' => 'Georgia', - 'gf' => 'French Guiana', - 'gh' => 'Ghana', - 'gi' => 'Gibraltar', - 'gl' => 'Greenland', - 'gm' => 'Gambia', - 'gn' => 'Guinea', - 'gp' => 'Guadeloupe', - 'gq' => 'Equatorial Guinea', - 'gr' => 'Greece', - 'gs' => 'South Georgia and the South Sandwich Islands', - 'gt' => 'Guatemala', - 'gu' => 'Guam', - 'gw' => 'Guinea-bissau', - 'gy' => 'Guyana', - 'hk' => 'Hong Kong', - 'hm' => 'Heard and McDonald Islands', - 'hn' => 'Honduras', - 'hr' => 'Croatia', - 'ht' => 'Haiti', - 'hu' => 'Hungary', - 'id' => 'Indonesia', - 'ie' => 'Ireland', - 'il' => 'Israel', - 'in' => 'India', - 'io' => 'British Indian Ocean Territory', - 'iq' => 'Iraq', - 'ir' => 'Iran', - 'is' => 'Iceland', - 'it' => 'Italy', - 'jm' => 'Jamaica', - 'jo' => 'Jordan', - 'jp' => 'Japan', - 'ke' => 'Kenya', - 'kg' => 'Kyrgyzstan', - 'kh' => 'Cambodia', - 'ki' => 'Kiribati', - 'km' => 'Comoros', - 'kn' => 'Saint Kitts and Nevis', - 'kp' => 'North Korea', - 'kr' => 'South Korea', - 'kw' => 'Kuwait', - 'ky' => 'Cayman Islands', - 'kz' => 'Kazakhstan', - 'la' => 'Laos', - 'lb' => 'Lebanon', - 'lc' => 'Saint Lucia', - 'li' => 'Lichtenstein', - 'lk' => 'Sri Lanka', - 'lr' => 'Liberia', - 'ls' => 'Lesotho', - 'lt' => 'Lithuania', - 'lu' => 'Luxembourg', - 'lv' => 'Latvia', - 'ly' => 'Libya', - 'ma' => 'Morocco', - 'mc' => 'Monaco', - 'md' => 'Moldova Republic', - 'mg' => 'Madagascar', - 'mh' => 'Marshall Islands', - 'mk' => 'Macedonia, The Former Yugoslav Republic of', - 'ml' => 'Mali', - 'mm' => 'Myanmar', - 'mn' => 'Mongolia', - 'mo' => 'Macau', - 'mp' => 'Northern Mariana Islands', - 'mq' => 'Martinique', - 'mr' => 'Mauritania', - 'ms' => 'Montserrat', - 'mt' => 'Malta', - 'mu' => 'Mauritius', - 'mv' => 'Maldives', - 'mw' => 'Malawi', - 'mx' => 'Mexico', - 'my' => 'Malaysia', - 'mz' => 'Mozambique', - 'na' => 'Namibia', - 'nc' => 'New Caledonia', - 'ne' => 'Niger', - 'nf' => 'Norfolk Island', - 'ng' => 'Nigeria', - 'ni' => 'Nicaragua', - 'nl' => 'Netherlands', - 'no' => 'Norway', - 'np' => 'Nepal', - 'nr' => 'Nauru', - 'nt' => 'Neutral Zone', - 'nu' => 'Niue', - 'nz' => 'New Zealand', - 'om' => 'Oman', - 'pa' => 'Panama', - 'pe' => 'Peru', - 'pf' => 'French Polynesia', - 'pg' => 'Papua New Guinea', - 'ph' => 'Philippines', - 'pk' => 'Pakistan', - 'pl' => 'Poland', - 'pm' => 'St. Pierre and Miquelon', - 'pn' => 'Pitcairn', - 'pr' => 'Puerto Rico', - 'pt' => 'Portugal', - 'pw' => 'Palau', - 'py' => 'Paraguay', - 'qa' => 'Qatar', - 're' => 'Reunion', - 'ro' => 'Romania', - 'ru' => 'Russia', - 'rw' => 'Rwanda', - 'sa' => 'Saudi Arabia', - 'sb' => 'Solomon Islands', - 'sc' => 'Seychelles', - 'sd' => 'Sudan', - 'se' => 'Sweden', - 'sg' => 'Singapore', - 'sh' => 'St. Helena', - 'si' => 'Slovenia', - 'sj' => 'Svalbard and Jan Mayen Islands', - 'sk' => 'Slovakia (Slovak Republic)', - 'sl' => 'Sierra Leone', - 'sm' => 'San Marino', - 'sn' => 'Senegal', - 'so' => 'Somalia', - 'sr' => 'Suriname', - 'st' => 'Sao Tome and Principe', - 'sv' => 'El Salvador', - 'sy' => 'Syria', - 'sz' => 'Swaziland', - 'tc' => 'Turks and Caicos Islands', - 'td' => 'Chad', - 'tf' => 'French Southern Territories', - 'tg' => 'Togo', - 'th' => 'Thailand', - 'tj' => 'Tajikistan', - 'tk' => 'Tokelau', - 'tm' => 'Turkmenistan', - 'tn' => 'Tunisia', - 'to' => 'Tonga', - 'tp' => 'East Timor', - 'tr' => 'Turkey', - 'tt' => 'Trinidad, Tobago', - 'tv' => 'Tuvalu', - 'tw' => 'Taiwan', - 'tz' => 'Tanzania', - 'ua' => 'Ukraine', - 'ug' => 'Uganda', - 'uk' => 'United Kingdom', - 'um' => 'United States Minor Islands', - 'us' => 'United States of America', - 'uy' => 'Uruguay', - 'uz' => 'Uzbekistan', - 'va' => 'Vatican City', - 'vc' => 'Saint Vincent, Grenadines', - 've' => 'Venezuela', - 'vg' => 'Virgin Islands (British)', - 'vi' => 'Virgin Islands (USA)', - 'vn' => 'Viet Nam', - 'vu' => 'Vanuatu', - 'wf' => 'Wallis and Futuna Islands', - 'ws' => 'Samoa', - 'ye' => 'Yemen', - 'yt' => 'Mayotte', - 'yu' => 'Yugoslavia', - 'za' => 'South Africa', - 'zm' => 'Zambia', - 'zr' => 'Zaire', - 'zw' => 'Zimbabwe'); + 'ad' => 'Andorra', + 'ae' => 'United Arab Emirates', + 'af' => 'Afghanistan', + 'ag' => 'Antigua and Barbuda', + 'ai' => 'Anguilla', + 'al' => 'Albania', + 'am' => 'Armenia', + 'an' => 'Netherlands Antilles', + 'ao' => 'Angola', + 'aq' => 'Antarctica', + 'ar' => 'Argentina', + 'as' => 'American Samoa', + 'at' => 'Austria', + 'au' => 'Australia', + 'aw' => 'Aruba', + 'az' => 'Azerbaijan', + 'ba' => 'Bosnia Hercegovina', + 'bb' => 'Barbados', + 'bd' => 'Bangladesh', + 'be' => 'Belgium', + 'bf' => 'Burkina Faso', + 'bg' => 'Bulgaria', + 'bh' => 'Bahrain', + 'bi' => 'Burundi', + 'bj' => 'Benin', + 'bm' => 'Bermuda', + 'bn' => 'Brunei Darussalam', + 'bo' => 'Bolivia', + 'br' => 'Brazil', + 'bs' => 'Bahamas', + 'bt' => 'Bhutan', + 'bv' => 'Bouvet Island', + 'bw' => 'Botswana', + 'by' => 'Belarus (Byelorussia)', + 'bz' => 'Belize', + 'ca' => 'Canada', + 'cc' => 'Cocos Islands', + 'cd' => 'Congo, The Democratic Republic of the', + 'cf' => 'Central African Republic', + 'cg' => 'Congo', + 'ch' => 'Switzerland', + 'ci' => 'Ivory Coast', + 'ck' => 'Cook Islands', + 'cl' => 'Chile', + 'cm' => 'Cameroon', + 'cn' => 'China', + 'co' => 'Colombia', + 'cr' => 'Costa Rica', + 'cs' => 'Czechoslovakia', + 'cu' => 'Cuba', + 'cv' => 'Cape Verde', + 'cx' => 'Christmas Island', + 'cy' => 'Cyprus', + 'cz' => 'Czech Republic', + 'de' => 'Germany', + 'dj' => 'Djibouti', + 'dk' => 'Denmark', + 'dm' => 'Dominica', + 'do' => 'Dominican Republic', + 'dz' => 'Algeria', + 'ec' => 'Ecuador', + 'ee' => 'Estonia', + 'eg' => 'Egypt', + 'eh' => 'Western Sahara', + 'er' => 'Eritrea', + 'es' => 'Spain', + 'et' => 'Ethiopia', + 'fi' => 'Finland', + 'fj' => 'Fiji', + 'fk' => 'Falkland Islands', + 'fm' => 'Micronesia', + 'fo' => 'Faroe Islands', + 'fr' => 'France', + 'fx' => 'France, Metropolitan FX', + 'ga' => 'Gabon', + 'gb' => 'United Kingdom (Great Britain)', + 'gd' => 'Grenada', + 'ge' => 'Georgia', + 'gf' => 'French Guiana', + 'gh' => 'Ghana', + 'gi' => 'Gibraltar', + 'gl' => 'Greenland', + 'gm' => 'Gambia', + 'gn' => 'Guinea', + 'gp' => 'Guadeloupe', + 'gq' => 'Equatorial Guinea', + 'gr' => 'Greece', + 'gs' => 'South Georgia and the South Sandwich Islands', + 'gt' => 'Guatemala', + 'gu' => 'Guam', + 'gw' => 'Guinea-bissau', + 'gy' => 'Guyana', + 'hk' => 'Hong Kong', + 'hm' => 'Heard and McDonald Islands', + 'hn' => 'Honduras', + 'hr' => 'Croatia', + 'ht' => 'Haiti', + 'hu' => 'Hungary', + 'id' => 'Indonesia', + 'ie' => 'Ireland', + 'il' => 'Israel', + 'in' => 'India', + 'io' => 'British Indian Ocean Territory', + 'iq' => 'Iraq', + 'ir' => 'Iran', + 'is' => 'Iceland', + 'it' => 'Italy', + 'jm' => 'Jamaica', + 'jo' => 'Jordan', + 'jp' => 'Japan', + 'ke' => 'Kenya', + 'kg' => 'Kyrgyzstan', + 'kh' => 'Cambodia', + 'ki' => 'Kiribati', + 'km' => 'Comoros', + 'kn' => 'Saint Kitts and Nevis', + 'kp' => 'North Korea', + 'kr' => 'South Korea', + 'kw' => 'Kuwait', + 'ky' => 'Cayman Islands', + 'kz' => 'Kazakhstan', + 'la' => 'Laos', + 'lb' => 'Lebanon', + 'lc' => 'Saint Lucia', + 'li' => 'Lichtenstein', + 'lk' => 'Sri Lanka', + 'lr' => 'Liberia', + 'ls' => 'Lesotho', + 'lt' => 'Lithuania', + 'lu' => 'Luxembourg', + 'lv' => 'Latvia', + 'ly' => 'Libya', + 'ma' => 'Morocco', + 'mc' => 'Monaco', + 'md' => 'Moldova Republic', + 'mg' => 'Madagascar', + 'mh' => 'Marshall Islands', + 'mk' => 'Macedonia, The Former Yugoslav Republic of', + 'ml' => 'Mali', + 'mm' => 'Myanmar', + 'mn' => 'Mongolia', + 'mo' => 'Macau', + 'mp' => 'Northern Mariana Islands', + 'mq' => 'Martinique', + 'mr' => 'Mauritania', + 'ms' => 'Montserrat', + 'mt' => 'Malta', + 'mu' => 'Mauritius', + 'mv' => 'Maldives', + 'mw' => 'Malawi', + 'mx' => 'Mexico', + 'my' => 'Malaysia', + 'mz' => 'Mozambique', + 'na' => 'Namibia', + 'nc' => 'New Caledonia', + 'ne' => 'Niger', + 'nf' => 'Norfolk Island', + 'ng' => 'Nigeria', + 'ni' => 'Nicaragua', + 'nl' => 'Netherlands', + 'no' => 'Norway', + 'np' => 'Nepal', + 'nr' => 'Nauru', + 'nt' => 'Neutral Zone', + 'nu' => 'Niue', + 'nz' => 'New Zealand', + 'om' => 'Oman', + 'pa' => 'Panama', + 'pe' => 'Peru', + 'pf' => 'French Polynesia', + 'pg' => 'Papua New Guinea', + 'ph' => 'Philippines', + 'pk' => 'Pakistan', + 'pl' => 'Poland', + 'pm' => 'St. Pierre and Miquelon', + 'pn' => 'Pitcairn', + 'pr' => 'Puerto Rico', + 'pt' => 'Portugal', + 'pw' => 'Palau', + 'py' => 'Paraguay', + 'qa' => 'Qatar', + 're' => 'Reunion', + 'ro' => 'Romania', + 'ru' => 'Russia', + 'rw' => 'Rwanda', + 'sa' => 'Saudi Arabia', + 'sb' => 'Solomon Islands', + 'sc' => 'Seychelles', + 'sd' => 'Sudan', + 'se' => 'Sweden', + 'sg' => 'Singapore', + 'sh' => 'St. Helena', + 'si' => 'Slovenia', + 'sj' => 'Svalbard and Jan Mayen Islands', + 'sk' => 'Slovakia (Slovak Republic)', + 'sl' => 'Sierra Leone', + 'sm' => 'San Marino', + 'sn' => 'Senegal', + 'so' => 'Somalia', + 'sr' => 'Suriname', + 'st' => 'Sao Tome and Principe', + 'sv' => 'El Salvador', + 'sy' => 'Syria', + 'sz' => 'Swaziland', + 'tc' => 'Turks and Caicos Islands', + 'td' => 'Chad', + 'tf' => 'French Southern Territories', + 'tg' => 'Togo', + 'th' => 'Thailand', + 'tj' => 'Tajikistan', + 'tk' => 'Tokelau', + 'tm' => 'Turkmenistan', + 'tn' => 'Tunisia', + 'to' => 'Tonga', + 'tp' => 'East Timor', + 'tr' => 'Turkey', + 'tt' => 'Trinidad, Tobago', + 'tv' => 'Tuvalu', + 'tw' => 'Taiwan', + 'tz' => 'Tanzania', + 'ua' => 'Ukraine', + 'ug' => 'Uganda', + 'uk' => 'United Kingdom', + 'um' => 'United States Minor Islands', + 'us' => 'United States of America', + 'uy' => 'Uruguay', + 'uz' => 'Uzbekistan', + 'va' => 'Vatican City', + 'vc' => 'Saint Vincent, Grenadines', + 've' => 'Venezuela', + 'vg' => 'Virgin Islands (British)', + 'vi' => 'Virgin Islands (USA)', + 'vn' => 'Viet Nam', + 'vu' => 'Vanuatu', + 'wf' => 'Wallis and Futuna Islands', + 'ws' => 'Samoa', + 'ye' => 'Yemen', + 'yt' => 'Mayotte', + 'yu' => 'Yugoslavia', + 'za' => 'South Africa', + 'zm' => 'Zambia', + 'zr' => 'Zaire', + 'zw' => 'Zimbabwe'); /** - * returns all available country codes + * returns all available country codes. * * @return array */ @@ -288,10 +289,9 @@ public static function getCountries() } /** - * checks if given value is a valid country code + * checks if given value is a valid country code. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -302,4 +302,4 @@ public function validate($value) return isset(self::$countries[$value]); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Creditcard.php b/lib/Doctrine/Validator/Creditcard.php index 82d64c979..00c59813e 100644 --- a/lib/Doctrine/Validator/Creditcard.php +++ b/lib/Doctrine/Validator/Creditcard.php @@ -20,66 +20,67 @@ */ /** - * Doctrine_Validator_Creditcard + * Doctrine_Validator_Creditcard. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Creditcard extends Doctrine_Validator_Driver -{ +{ /** - * checks if given value is a valid credit card number + * checks if given value is a valid credit card number. * - * @link http://www.owasp.org/index.php/OWASP_Validation_Regex_Repository - * @param mixed $value - * @return boolean + * @see http://www.owasp.org/index.php/OWASP_Validation_Regex_Repository + * + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } - $cardType = ""; + $cardType = ''; $card_regexes = array( - "/^4\d{12}(\d\d\d){0,1}$/" => 'visa', - "/^5[12345]\d{14}$/" => 'mastercard', - "/^3[47]\d{13}$/" => 'amex', - "/^6011\d{12}$/" => 'discover', - "/^30[012345]\d{11}$/" => 'diners', - "/^3[68]\d{12}$/" => 'diners', + '/^4\\d{12}(\\d\\d\\d){0,1}$/' => 'visa', + '/^5[12345]\\d{14}$/' => 'mastercard', + '/^3[47]\\d{13}$/' => 'amex', + '/^6011\\d{12}$/' => 'discover', + '/^30[012345]\\d{11}$/' => 'diners', + '/^3[68]\\d{12}$/' => 'diners', ); foreach ($card_regexes as $regex => $type) { if (preg_match($regex, $value)) { - $cardType = $type; - break; + $cardType = $type; + break; } } - if ( ! $cardType) { + if (!$cardType) { return false; } /* mod 10 checksum algorithm */ $revcode = strrev($value); $checksum = 0; - for ($i = 0; $i < strlen($revcode); $i++) { + for ($i = 0; $i < strlen($revcode); ++$i) { $currentNum = intval($revcode[$i]); if ($i & 1) { /* Odd position */ - $currentNum *= 2; + $currentNum *= 2; } /* Split digits and add. */ $checksum += $currentNum % 10; if ($currentNum > 9) { - $checksum += 1; + ++$checksum; } } - if ($checksum % 10 == 0) { + if (0 == $checksum % 10) { return true; - } else { - return false; } + + return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Date.php b/lib/Doctrine/Validator/Date.php index 7173191e4..a2f653842 100644 --- a/lib/Doctrine/Validator/Date.php +++ b/lib/Doctrine/Validator/Date.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Validator_Date + * Doctrine_Validator_Date. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Date extends Doctrine_Validator_Driver { /** - * checks if given value is a valid date + * checks if given value is a valid date. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -45,11 +45,12 @@ public function validate($value) } $e = explode('-', $value); - if (count($e) !== 3) { + if (3 !== count($e)) { return false; } $e2 = explode(' ', $e[2]); $e[2] = $e2[0]; + return checkdate($e[1], $e[2], $e[0]); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Driver.php b/lib/Doctrine/Validator/Driver.php index 97a989828..34a28bf04 100644 --- a/lib/Doctrine/Validator/Driver.php +++ b/lib/Doctrine/Validator/Driver.php @@ -20,20 +20,21 @@ */ /** - * Doctrine_Validator_Driver + * Doctrine_Validator_Driver. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Driver { /** - * @var array $_args an array of plugin specific args + * @var array an array of plugin specific args */ public $args; public $invoker; @@ -41,7 +42,7 @@ class Doctrine_Validator_Driver /** * __get - * an alias for getOption + * an alias for getOption. * * @param string $arg */ @@ -50,11 +51,12 @@ public function __get($arg) if (isset($this->args[$arg])) { return $this->args[$arg]; } + return null; } /** - * __isset + * __isset. * * @param string $arg */ @@ -64,52 +66,55 @@ public function __isset($arg) } /** - * sets given value to an argument + * sets given value to an argument. + * + * @param $arg the name of the option to be changed + * @param $value the value of the option * - * @param $arg the name of the option to be changed - * @param $value the value of the option - * @return Doctrine_Validator_Driver this object + * @return Doctrine_Validator_Driver this object */ public function __set($arg, $value) { $this->args[$arg] = $value; - + return $this; } /** - * returns the value of an argument + * returns the value of an argument. * - * @param $arg the name of the option to retrieve - * @return mixed the value of the option + * @param $arg the name of the option to retrieve + * + * @return mixed the value of the option */ public function getArg($arg) { - if ( ! isset($this->args[$arg])) { - throw new Doctrine_Validator_Exception('Unknown option ' . $arg); + if (!isset($this->args[$arg])) { + throw new Doctrine_Validator_Exception('Unknown option '.$arg); } - + return $this->args[$arg]; } /** - * sets given value to an argument + * sets given value to an argument. + * + * @param $arg the name of the option to be changed + * @param $value the value of the option * - * @param $arg the name of the option to be changed - * @param $value the value of the option - * @return Doctrine_Validator_Driver this object + * @return Doctrine_Validator_Driver this object */ public function setArg($arg, $value) { $this->args[$arg] = $value; - + return $this; } /** - * returns all args and their associated values + * returns all args and their associated values. * - * @return array all args as an associative array + * @return array all args as an associative array */ public function getArgs() { @@ -119,10 +124,10 @@ public function getArgs() public function __toString() { $className = get_class($this); - if (strpos($className, 'Doctrine_Validator_') === 0) { + if (0 === strpos($className, 'Doctrine_Validator_')) { return strtolower(substr($className, 19)); - } else { - return $className; } + + return $className; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Email.php b/lib/Doctrine/Validator/Email.php index e15c21824..e35ba304d 100644 --- a/lib/Doctrine/Validator/Email.php +++ b/lib/Doctrine/Validator/Email.php @@ -20,24 +20,25 @@ */ /** - * Doctrine_Validator_Email + * Doctrine_Validator_Email. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Email extends Doctrine_Validator_Driver { /** - * checks if given value is a valid email address + * checks if given value is a valid email address. + * + * @see http://iamcal.com/publish/articles/php/parsing_email/pdf/ * - * @link http://iamcal.com/publish/articles/php/parsing_email/pdf/ - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -45,10 +46,10 @@ public function validate($value) return true; } - if (isset($this->args) && (! isset($this->args['check_mx']) || $this->args['check_mx'] == true)) { + if (isset($this->args) && (!isset($this->args['check_mx']) || true == $this->args['check_mx'])) { $parts = explode('@', $value); - if (isset($parts[1]) && $parts[1] && ! $this->_checkMX($parts[1])) { + if (isset($parts[1]) && $parts[1] && !$this->_checkMX($parts[1])) { return false; } } @@ -56,7 +57,7 @@ public function validate($value) $e = explode('.', $value); $tld = end($e); - if (preg_match("/[^a-zA-Z]/", $tld)) { + if (preg_match('/[^a-zA-Z]/', $tld)) { return false; } @@ -64,13 +65,13 @@ public function validate($value) $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; $quotedPair = '\\x5c[\\x00-\\x7f]'; - $domainLiteral = "\\x5b($dtext|$quotedPair)*\\x5d"; - $quotedString = "\\x22($qtext|$quotedPair)*\\x22"; + $domainLiteral = "\\x5b({$dtext}|{$quotedPair})*\\x5d"; + $quotedString = "\\x22({$qtext}|{$quotedPair})*\\x22"; $domainRef = $atom; - $subDomain = "($domainRef|$domainLiteral)"; - $word = "($atom|$quotedString)"; - $domain = "$subDomain(\\x2e$subDomain)+"; - + $subDomain = "({$domainRef}|{$domainLiteral})"; + $word = "({$atom}|{$quotedString})"; + $domain = "{$subDomain}(\\x2e{$subDomain})+"; + /* following pseudocode to allow strict checking - ask pookey about this if you're puzzled @@ -78,42 +79,44 @@ public function validate($value) $domain = "$sub_domain(\\x2e$sub_domain)*"; } */ - - $localPart = "$word(\\x2e$word)*"; - $addrSpec = "$localPart\\x40$domain"; - - return (bool) preg_match("!^$addrSpec$!D", $value); + + $localPart = "{$word}(\\x2e{$word})*"; + $addrSpec = "{$localPart}\\x40{$domain}"; + + return (bool) preg_match("!^{$addrSpec}$!D", $value); } - + /** - * Check DNS Records for MX type + * Check DNS Records for MX type. * * @param string $host Host name - * @return boolean + * + * @return bool */ private function _checkMX($host) { // We have different behavior here depending of OS and PHP version - if (strtolower(substr(PHP_OS, 0, 3)) == 'win' && version_compare(PHP_VERSION, '5.3.0', '<')) { + if ('win' == strtolower(substr(PHP_OS, 0, 3)) && version_compare(PHP_VERSION, '5.3.0', '<')) { $output = array(); - - @exec('nslookup -type=MX '.escapeshellcmd($host) . ' 2>&1', $output); - + + @exec('nslookup -type=MX '.escapeshellcmd($host).' 2>&1', $output); + if (empty($output)) { throw new Doctrine_Exception('Unable to execute DNS lookup. Are you sure PHP can call exec()?'); - } + } foreach ($output as $line) { - if (preg_match('/^'.$host.'/', $line)) { - return true; + if (preg_match('/^'.$host.'/', $line)) { + return true; } } - + return false; - } else if (function_exists('checkdnsrr')) { + } + if (function_exists('checkdnsrr')) { return checkdnsrr($host, 'MX'); } - + throw new Doctrine_Exception('Could not retrieve DNS record information. Remove check_mx = true to prevent this warning'); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/ErrorStack.php b/lib/Doctrine/Validator/ErrorStack.php index b3f5c41c1..662e5fdaa 100644 --- a/lib/Doctrine/Validator/ErrorStack.php +++ b/lib/Doctrine/Validator/ErrorStack.php @@ -20,15 +20,15 @@ */ /** - * Doctrine_Validator_ErrorStack + * Doctrine_Validator_ErrorStack. * - * @package Doctrine - * @subpackage Validator * @author Konsta Vesterinen * @author Roman Borschel * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Validator_ErrorStack extends Doctrine_Access implements Countable, IteratorAggregate @@ -41,22 +41,21 @@ class Doctrine_Validator_ErrorStack extends Doctrine_Access implements Countable protected $_errors = array(); /** - * Array of validators that failed + * Array of validators that failed. * * @var array */ protected $_validators = array(); /** - * Get model class name for the error stack + * Get model class name for the error stack. * * @var string */ protected $_className; /** - * Constructor - * + * Constructor. */ public function __construct($className) { @@ -68,12 +67,13 @@ public function __construct($className) * * @param string $invalidFieldName * @param string|Doctrine_Validator_Driver $errorCode + * * @throws Doctrine_Exception */ public function add($invalidFieldName, $errorCode = 'general') { if (is_object($errorCode)) { - if ( ! ($errorCode instanceof Doctrine_Validator_Driver)) { + if (!($errorCode instanceof Doctrine_Validator_Driver)) { throw new Doctrine_Exception('Validators must be an instance of Doctrine_Validator_Driver'); } $validator = $errorCode; @@ -100,10 +100,9 @@ public function remove($fieldName) } /** - * Get errors for field + * Get errors for field. * * @param string $fieldName - * @return mixed */ public function get($fieldName) { @@ -111,11 +110,10 @@ public function get($fieldName) } /** - * Alias for add() + * Alias for add(). * * @param string $fieldName * @param string $errorCode - * @return void */ public function set($fieldName, $errorCode) { @@ -123,10 +121,11 @@ public function set($fieldName, $errorCode) } /** - * Check if a field has an error + * Check if a field has an error. * * @param string $fieldName - * @return boolean + * + * @return bool */ public function contains($fieldName) { @@ -135,8 +134,6 @@ public function contains($fieldName) /** * Removes all errors from the stack. - * - * @return void */ public function clear() { @@ -149,7 +146,7 @@ public function clear() * * @return ArrayIterator unknown */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->_errors); @@ -161,18 +158,18 @@ public function toArray() } /** - * Count the number of errors + * Count the number of errors. * - * @return integer + * @return int */ - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->_errors); } /** - * Get the classname where the errors occured + * Get the classname where the errors occured. * * @return string */ @@ -182,7 +179,7 @@ public function getClassname() } /** - * Get array of failed validators + * Get array of failed validators. * * @return array */ @@ -190,4 +187,4 @@ public function getValidators() { return $this->_validators; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Exception.php b/lib/Doctrine/Validator/Exception.php index 98d3534fb..f6db1eb19 100644 --- a/lib/Doctrine/Validator/Exception.php +++ b/lib/Doctrine/Validator/Exception.php @@ -20,26 +20,23 @@ */ /** - * Doctrine_Validator_Exception + * Doctrine_Validator_Exception. * - * @package Doctrine - * @subpackage Validator * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_Validator_Exception extends Doctrine_Exception implements Countable, IteratorAggregate { /** - * @var array $invalid + * @var array */ private $invalid = array(); - /** - * @param Doctrine_Validator $validator - */ public function __construct(array $invalid) { $this->invalid = $invalid; @@ -51,20 +48,20 @@ public function getInvalidRecords() return $this->invalid; } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function getIterator() { return new ArrayIterator($this->invalid); } - #[\ReturnTypeWillChange] + #[ReturnTypeWillChange] public function count() { return count($this->invalid); } /** - * Generate a message with all classes that have exceptions + * Generate a message with all classes that have exceptions. */ private function generateMessage() { @@ -72,14 +69,15 @@ private function generateMessage() foreach ($this->invalid as $record) { $message .= $record->getErrorStackAsString(); } + return $message; } /** - * This method will apply the value of the $function variable as a user_func - * to tall errorstack objects in the exception + * This method will apply the value of the $function variable as a user_func + * to tall errorstack objects in the exception. * - * @param mixed Either string with function name or array with object, + * @param mixed Either string with function name or array with object, * functionname. See call_user_func in php manual for more inforamtion */ public function inspect($function) @@ -88,4 +86,4 @@ public function inspect($function) call_user_func($function, $record->getErrorStack()); } } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Future.php b/lib/Doctrine/Validator/Future.php index db5d7de79..39b7080d3 100644 --- a/lib/Doctrine/Validator/Future.php +++ b/lib/Doctrine/Validator/Future.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Validator_Future + * Doctrine_Validator_Future. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Roman Borschel */ class Doctrine_Validator_Future extends Doctrine_Validator_Driver @@ -35,8 +36,7 @@ class Doctrine_Validator_Future extends Doctrine_Validator_Driver /** * checks if the given value is a valid date in the future. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -45,14 +45,14 @@ public function validate($value) } $e = explode('-', $value); - if (count($e) !== 3) { + if (3 !== count($e)) { return false; } - + if (is_array($this->args) && isset($this->args['timezone'])) { switch (strtolower($this->args['timezone'])) { case 'gmt': - $now = gmdate("U") - date("Z"); + $now = gmdate('U') - date('Z'); break; default: $now = getdate(); @@ -61,19 +61,21 @@ public function validate($value) } else { $now = getdate(); } - + if ($now['year'] > $e[0]) { return false; - } else if ($now['year'] == $e[0]) { + } + if ($now['year'] == $e[0]) { if ($now['mon'] > $e[1]) { return false; - } else if ($now['mon'] == $e[1]) { + } + if ($now['mon'] == $e[1]) { return $now['mday'] < $e[2]; - } else { - return true; } - } else { + return true; } + + return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/HtmlColor.php b/lib/Doctrine/Validator/HtmlColor.php index a7249bfcb..ac4651669 100644 --- a/lib/Doctrine/Validator/HtmlColor.php +++ b/lib/Doctrine/Validator/HtmlColor.php @@ -20,32 +20,33 @@ */ /** - * Doctrine_Validator_HtmlColor + * Doctrine_Validator_HtmlColor. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_HtmlColor extends Doctrine_Validator_Driver { /** - * checks if given value is a valid html color code + * checks if given value is a valid html color code. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } - if ( ! preg_match("/^#{0,1}[0-9a-fA-F]{6}$/", $value)) { + if (!preg_match('/^#{0,1}[0-9a-fA-F]{6}$/', $value)) { return false; } + return true; } } diff --git a/lib/Doctrine/Validator/Ip.php b/lib/Doctrine/Validator/Ip.php index ab7ce928f..6198ce2a5 100644 --- a/lib/Doctrine/Validator/Ip.php +++ b/lib/Doctrine/Validator/Ip.php @@ -20,26 +20,26 @@ */ /** - * Doctrine_Validator_Ip + * Doctrine_Validator_Ip. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Ip extends Doctrine_Validator_Driver { /** - * checks if given value is valid ip address + * checks if given value is valid ip address. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { return is_null($value) ? true : (bool) filter_var($value, FILTER_VALIDATE_IP); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Minlength.php b/lib/Doctrine/Validator/Minlength.php index 34323fff1..e68c8ebb3 100644 --- a/lib/Doctrine/Validator/Minlength.php +++ b/lib/Doctrine/Validator/Minlength.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Validator_Regexp + * Doctrine_Validator_Regexp. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Gijs van Dulmen */ class Doctrine_Validator_Minlength extends Doctrine_Validator_Driver { /** - * checks if given value is more length than the minimum length required + * checks if given value is more length than the minimum length required. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -49,4 +49,4 @@ public function validate($value) return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Nospace.php b/lib/Doctrine/Validator/Nospace.php index b5585f671..c3032d1fa 100644 --- a/lib/Doctrine/Validator/Nospace.php +++ b/lib/Doctrine/Validator/Nospace.php @@ -20,29 +20,30 @@ */ /** - * Doctrine_Validator_Nospace + * Doctrine_Validator_Nospace. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Nospace extends Doctrine_Validator_Driver { /** - * checks that value doesn't contain any space chars + * checks that value doesn't contain any space chars. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } - return ($value === null || ! preg_match('/\s/', $value)); + + return null === $value || !preg_match('/\s/', $value); } } diff --git a/lib/Doctrine/Validator/Notblank.php b/lib/Doctrine/Validator/Notblank.php index fe6591105..ee9d37071 100644 --- a/lib/Doctrine/Validator/Notblank.php +++ b/lib/Doctrine/Validator/Notblank.php @@ -20,27 +20,27 @@ */ /** - * Doctrine_Validator_Notblank + * Doctrine_Validator_Notblank. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Notblank extends Doctrine_Validator_Driver { /** * checks that value isn't blank - * a value is blank when its either null or contains only space characters + * a value is blank when its either null or contains only space characters. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { - return (null !== $value && '' !== trim($value)); + return null !== $value && '' !== trim($value); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Notnull.php b/lib/Doctrine/Validator/Notnull.php index a0721c805..7a2804180 100644 --- a/lib/Doctrine/Validator/Notnull.php +++ b/lib/Doctrine/Validator/Notnull.php @@ -20,26 +20,26 @@ */ /** - * Doctrine_Validator_Notnull + * Doctrine_Validator_Notnull. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Notnull extends Doctrine_Validator_Driver { /** - * checks that given value isn't null + * checks that given value isn't null. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { - return ($value !== null); + return null !== $value; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Past.php b/lib/Doctrine/Validator/Past.php index f2e6be17f..a3798eb96 100644 --- a/lib/Doctrine/Validator/Past.php +++ b/lib/Doctrine/Validator/Past.php @@ -20,14 +20,15 @@ */ /** - * Doctrine_Validator_Past + * Doctrine_Validator_Past. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision$ + * * @author Roman Borschel */ class Doctrine_Validator_Past extends Doctrine_Validator_Driver @@ -35,8 +36,7 @@ class Doctrine_Validator_Past extends Doctrine_Validator_Driver /** * checks if the given value is a valid date in the past. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -45,14 +45,14 @@ public function validate($value) } $e = explode('-', $value); - if (count($e) !== 3) { + if (3 !== count($e)) { return false; } - + if (is_array($this->args) && isset($this->args['timezone'])) { switch (strtolower($this->args['timezone'])) { case 'gmt': - $now = gmdate("U") - date("Z"); + $now = gmdate('U') - date('Z'); break; default: $now = getdate(); @@ -61,19 +61,21 @@ public function validate($value) } else { $now = getdate(); } - + if ($now['year'] < $e[0]) { return false; - } else if ($now['year'] == $e[0]) { + } + if ($now['year'] == $e[0]) { if ($now['mon'] < $e[1]) { return false; - } else if ($now['mon'] == $e[1]) { + } + if ($now['mon'] == $e[1]) { return $now['mday'] > $e[2]; - } else { - return true; } - } else { + return true; } + + return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Range.php b/lib/Doctrine/Validator/Range.php index 4b160a720..79b229955 100644 --- a/lib/Doctrine/Validator/Range.php +++ b/lib/Doctrine/Validator/Range.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Validator_Range + * Doctrine_Validator_Range. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Range extends Doctrine_Validator_Driver { /** - * checks if value is within given range + * checks if value is within given range. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -49,6 +49,7 @@ public function validate($value) if (isset($this->args[1]) && $value > $this->args[1]) { return false; } + return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Readonly.php b/lib/Doctrine/Validator/Readonly.php index 115d08304..f0977407f 100755 --- a/lib/Doctrine/Validator/Readonly.php +++ b/lib/Doctrine/Validator/Readonly.php @@ -18,26 +18,25 @@ */ /** - * Doctrine_Validator_Readonly + * Doctrine_Validator_Readonly. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org + * * @author Adam Huttler */ class Doctrine_Validator_Readonly extends Doctrine_Validator_Driver { /** - * checks if value has been modified + * checks if value has been modified. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { $modified = $this->invoker->getModified(); - + return array_key_exists($this->field, $modified) ? false : true; } } diff --git a/lib/Doctrine/Validator/Regexp.php b/lib/Doctrine/Validator/Regexp.php index 036b76faf..3ccfe5094 100644 --- a/lib/Doctrine/Validator/Regexp.php +++ b/lib/Doctrine/Validator/Regexp.php @@ -20,46 +20,45 @@ */ /** - * Doctrine_Validator_Regexp + * Doctrine_Validator_Regexp. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Regexp extends Doctrine_Validator_Driver { /** - * checks if given value satisfies a regular expression + * checks if given value satisfies a regular expression. * - * @param mixed $value - * @param mixed $args - * @return boolean + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } - if ( ! isset($this->args)) { - return true; + if (!isset($this->args)) { + return true; } if (is_array($this->args)) { foreach ($this->args as $regexp) { - if ( ! preg_match($regexp, $value)) { + if (!preg_match($regexp, $value)) { return false; } } + + return true; + } + if (preg_match($this->args, $value)) { return true; - } else { - if (preg_match($this->args, $value)) { - return true; - } } return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Time.php b/lib/Doctrine/Validator/Time.php index cf5fed8fb..2bb100ae5 100644 --- a/lib/Doctrine/Validator/Time.php +++ b/lib/Doctrine/Validator/Time.php @@ -20,25 +20,25 @@ */ /** - * Doctrine_Validator_Time + * Doctrine_Validator_Time. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3884 $ + * * @author Mark Pearson */ class Doctrine_Validator_Time extends Doctrine_Validator_Driver { /** - * validate + * validate. * * checks if given value is a valid time * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -46,7 +46,7 @@ public function validate($value) return true; } - if ( ! preg_match('/^\s*(\d{2}):(\d{2})(:(\d{2}))?(\.(\d{1,6}))?([+-]\d{1,2}(:(\d{2}))?)?\s*$/', $value, $matches)) { + if (!preg_match('/^\s*(\d{2}):(\d{2})(:(\d{2}))?(\.(\d{1,6}))?([+-]\d{1,2}(:(\d{2}))?)?\s*$/', $value, $matches)) { return false; } @@ -57,10 +57,10 @@ public function validate($value) $tz_hh = (isset($matches[7])) ? intval($matches[7]) : 0; $tz_mm = (isset($matches[9])) ? intval($matches[9]) : 0; - return ($hh >= 0 && $hh <= 23) && - ($mm >= 0 && $mm <= 59) && - ($ss >= 0 && $ss <= 59) && - ($tz_hh >= -13 && $tz_hh <= 14) && - ($tz_mm >= 0 && $tz_mm <= 59) ; + return ($hh >= 0 && $hh <= 23) + && ($mm >= 0 && $mm <= 59) + && ($ss >= 0 && $ss <= 59) + && ($tz_hh >= -13 && $tz_hh <= 14) + && ($tz_mm >= 0 && $tz_mm <= 59); } } diff --git a/lib/Doctrine/Validator/Timestamp.php b/lib/Doctrine/Validator/Timestamp.php index 5070ac2e0..03c426ad9 100644 --- a/lib/Doctrine/Validator/Timestamp.php +++ b/lib/Doctrine/Validator/Timestamp.php @@ -20,24 +20,24 @@ */ /** - * Doctrine_Validator_Timestamp + * Doctrine_Validator_Timestamp. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 3884 $ + * * @author Mark Pearson */ class Doctrine_Validator_Timestamp extends Doctrine_Validator_Driver { /** * checks if given value is a valid timestamp - * ISO-8601 timestamp (YYYY-MM-DDTHH:MM:SS+00:00) or (YYYY-MM-DD HH:MM:SS) + * ISO-8601 timestamp (YYYY-MM-DDTHH:MM:SS+00:00) or (YYYY-MM-DD HH:MM:SS). * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -54,14 +54,14 @@ public function validate($value) $dateValidator = Doctrine_Validator::getValidator('date'); $timeValidator = Doctrine_Validator::getValidator('time'); - if ( ! $dateValidator->validate($date)) { + if (!$dateValidator->validate($date)) { return false; } - if ( ! $timeValidator->validate($time)) { + if (!$timeValidator->validate($time)) { return false; - } + } return true; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Unique.php b/lib/Doctrine/Validator/Unique.php index 672235b1d..33600aab1 100644 --- a/lib/Doctrine/Validator/Unique.php +++ b/lib/Doctrine/Validator/Unique.php @@ -20,23 +20,23 @@ */ /** - * Doctrine_Validator_Unique + * Doctrine_Validator_Unique. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Unique extends Doctrine_Validator_Driver { /** - * checks if given value is unique + * checks if given value is unique. * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { @@ -49,47 +49,47 @@ public function validate($value) $pks = $table->getIdentifierColumnNames(); if (is_array($pks)) { - for ($i = 0, $l = count($pks); $i < $l; $i++) { + for ($i = 0, $l = count($pks); $i < $l; ++$i) { $pks[$i] = $conn->quoteIdentifier($pks[$i]); } - + $pks = implode(', ', $pks); } - $sql = 'SELECT ' . $pks . ' FROM ' . $conn->quoteIdentifier($table->getTableName()) . ' WHERE '; - + $sql = 'SELECT '.$pks.' FROM '.$conn->quoteIdentifier($table->getTableName()).' WHERE '; + if (is_array($this->field)) { foreach ($this->field as $k => $v) { $this->field[$k] = $conn->quoteIdentifier($table->getColumnName($v)); } - - $sql .= implode(' = ? AND ', $this->field) . ' = ?'; + + $sql .= implode(' = ? AND ', $this->field).' = ?'; $values = $value; } else { - $sql .= $conn->quoteIdentifier($table->getColumnName($this->field)) . ' = ?'; + $sql .= $conn->quoteIdentifier($table->getColumnName($this->field)).' = ?'; $values = array(); $values[] = $value; } - - // If the record is not new we need to add primary key checks because its ok if the + + // If the record is not new we need to add primary key checks because its ok if the // unique value already exists in the database IF the record in the database is the same // as the one that is validated here. $state = $this->invoker->state(); - if ( ! ($state == Doctrine_Record::STATE_TDIRTY || $state == Doctrine_Record::STATE_TCLEAN)) { + if (!(Doctrine_Record::STATE_TDIRTY == $state || Doctrine_Record::STATE_TCLEAN == $state)) { foreach ((array) $table->getIdentifierColumnNames() as $pk) { - $sql .= ' AND ' . $conn->quoteIdentifier($pk) . ' != ?'; + $sql .= ' AND '.$conn->quoteIdentifier($pk).' != ?'; $pkFieldName = $table->getFieldName($pk); - $values[] = $this->invoker->$pkFieldName; + $values[] = $this->invoker->{$pkFieldName}; } } if (isset($this->args) && is_array($this->args) && isset($this->args['where'])) { - $sql .= ' AND ' . $this->args['where']; + $sql .= ' AND '.$this->args['where']; } - $stmt = $table->getConnection()->getDbh()->prepare($sql); + $stmt = $table->getConnection()->getDbh()->prepare($sql); $stmt->execute($values); - return ( ! is_array($stmt->fetch())); + return !is_array($stmt->fetch()); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Unsigned.php b/lib/Doctrine/Validator/Unsigned.php index 4ac099740..4f05af54c 100644 --- a/lib/Doctrine/Validator/Unsigned.php +++ b/lib/Doctrine/Validator/Unsigned.php @@ -20,41 +20,40 @@ */ /** - * Doctrine_Validator_Unsigned + * Doctrine_Validator_Unsigned. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 1080 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Unsigned extends Doctrine_Validator_Driver { /** - * checks if given value is a valid unsigned integer or float + * checks if given value is a valid unsigned integer or float. * * valid values: null, '', 5, '5', 5.9, '5.9' * invalid values: -5, '-5', 'five', -5.9, '-5.9', '5.5.5' * - * @param mixed $value - * @return boolean + * @return bool */ public function validate($value) { - if (is_null($value) || $value == '') { + if (is_null($value) || '' == $value) { return true; } if (preg_match('/[^0-9\-\.]/', $value)) { return false; } - if ((double) $value >= 0) - { + if ((float) $value >= 0) { return true; } return false; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/Validator/Usstate.php b/lib/Doctrine/Validator/Usstate.php index 41bc8c492..1a1ce4656 100644 --- a/lib/Doctrine/Validator/Usstate.php +++ b/lib/Doctrine/Validator/Usstate.php @@ -20,89 +20,91 @@ */ /** - * Doctrine_Validator_Usstate + * Doctrine_Validator_Usstate. * - * @package Doctrine - * @subpackage Validator * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ + * * @author Konsta Vesterinen */ class Doctrine_Validator_Usstate extends Doctrine_Validator_Driver { private static $states = array( - 'AK' => true, - 'AL' => true, - 'AR' => true, - 'AZ' => true, - 'CA' => true, - 'CO' => true, - 'CT' => true, - 'DC' => true, - 'DE' => true, - 'FL' => true, - 'GA' => true, - 'HI' => true, - 'IA' => true, - 'ID' => true, - 'IL' => true, - 'IN' => true, - 'KS' => true, - 'KY' => true, - 'LA' => true, - 'MA' => true, - 'MD' => true, - 'ME' => true, - 'MI' => true, - 'MN' => true, - 'MO' => true, - 'MS' => true, - 'MT' => true, - 'NC' => true, - 'ND' => true, - 'NE' => true, - 'NH' => true, - 'NJ' => true, - 'NM' => true, - 'NV' => true, - 'NY' => true, - 'OH' => true, - 'OK' => true, - 'OR' => true, - 'PA' => true, - 'PR' => true, - 'RI' => true, - 'SC' => true, - 'SD' => true, - 'TN' => true, - 'TX' => true, - 'UT' => true, - 'VA' => true, - 'VI' => true, - 'VT' => true, - 'WA' => true, - 'WI' => true, - 'WV' => true, - 'WY' => true - ); + 'AK' => true, + 'AL' => true, + 'AR' => true, + 'AZ' => true, + 'CA' => true, + 'CO' => true, + 'CT' => true, + 'DC' => true, + 'DE' => true, + 'FL' => true, + 'GA' => true, + 'HI' => true, + 'IA' => true, + 'ID' => true, + 'IL' => true, + 'IN' => true, + 'KS' => true, + 'KY' => true, + 'LA' => true, + 'MA' => true, + 'MD' => true, + 'ME' => true, + 'MI' => true, + 'MN' => true, + 'MO' => true, + 'MS' => true, + 'MT' => true, + 'NC' => true, + 'ND' => true, + 'NE' => true, + 'NH' => true, + 'NJ' => true, + 'NM' => true, + 'NV' => true, + 'NY' => true, + 'OH' => true, + 'OK' => true, + 'OR' => true, + 'PA' => true, + 'PR' => true, + 'RI' => true, + 'SC' => true, + 'SD' => true, + 'TN' => true, + 'TX' => true, + 'UT' => true, + 'VA' => true, + 'VI' => true, + 'VT' => true, + 'WA' => true, + 'WI' => true, + 'WV' => true, + 'WY' => true, + ); + public function getStates() { return self::$states; } /** - * checks if given value is a valid US state code + * checks if given value is a valid US state code. * - * @param string $args - * @return boolean + * @return bool */ public function validate($value) { if (is_null($value)) { return true; } + return isset(self::$states[$value]); } -} \ No newline at end of file +} diff --git a/lib/Doctrine/View.php b/lib/Doctrine/View.php index 1785f0cbb..a4655cef2 100644 --- a/lib/Doctrine/View.php +++ b/lib/Doctrine/View.php @@ -20,77 +20,75 @@ */ /** - * Doctrine_View + * Doctrine_View. * * this class represents a database view * * @author Konsta Vesterinen - * @package Doctrine - * @subpackage View * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_View { /** - * SQL DROP constant + * SQL DROP constant. */ - const DROP = 'DROP VIEW %s'; + public const DROP = 'DROP VIEW %s'; /** - * SQL CREATE constant + * SQL CREATE constant. */ - const CREATE = 'CREATE VIEW %s AS %s'; + public const CREATE = 'CREATE VIEW %s AS %s'; /** - * SQL SELECT constant + * SQL SELECT constant. */ - const SELECT = 'SELECT * FROM %s'; + public const SELECT = 'SELECT * FROM %s'; /** - * @var string $name the name of the view + * @var string the name of the view */ protected $_name; /** - * @var Doctrine_Query $query the DQL query object this view is hooked into + * @var Doctrine_Query the DQL query object this view is hooked into */ protected $_query; /** - * @var Doctrine_Connection $conn the connection object + * @var Doctrine_Connection the connection object */ protected $_conn; /** - * @var string $_dql The view dql string + * @var string The view dql string */ protected $_dql; /** - * @var string $_sql The view sql string + * @var string The view sql string */ protected $_sql; /** - * constructor - * - * @param Doctrine_Query $query + * constructor. */ public function __construct(Doctrine_Query $query, $viewName) { - $this->_name = $viewName; + $this->_name = $viewName; $this->_query = $query; $this->_query->setView($this); - $this->_conn = $query->getConnection(); + $this->_conn = $query->getConnection(); $this->_dql = $query->getDql(); $this->_sql = $query->getSqlQuery(); } /** - * returns the associated query object + * returns the associated query object. * * @return Doctrine_Query */ @@ -100,7 +98,7 @@ public function getQuery() } /** - * returns the name of this view + * returns the name of this view. * * @return string */ @@ -110,7 +108,7 @@ public function getName() } /** - * returns the connection object + * returns the connection object. * * @return Doctrine_Connection */ @@ -120,38 +118,36 @@ public function getConnection() } /** - * creates this view + * creates this view. * * @throws Doctrine_View_Exception - * @return void */ public function create() { $sql = sprintf(self::CREATE, $this->_name, $this->_query->getSqlQuery()); try { $this->_conn->execute($sql, $this->_query->getFlattenedParams()); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { throw new Doctrine_View_Exception($e->__toString()); } } /** - * drops this view from the database + * drops this view from the database. * * @throws Doctrine_View_Exception - * @return void */ public function drop() { try { $this->_conn->execute(sprintf(self::DROP, $this->_name)); - } catch(Doctrine_Exception $e) { + } catch (Doctrine_Exception $e) { throw new Doctrine_View_Exception($e->__toString()); } } /** - * returns a collection of Doctrine_Record objects + * returns a collection of Doctrine_Record objects. * * @return Doctrine_Collection */ @@ -161,7 +157,7 @@ public function execute() } /** - * returns the select sql for this view + * returns the select sql for this view. * * @return string */ @@ -171,7 +167,7 @@ public function getSelectSql() } /** - * Get the view sql string + * Get the view sql string. * * @return string $sql */ @@ -181,7 +177,7 @@ public function getViewSql() } /** - * Get the view dql string + * Get the view dql string. * * @return string $dql */ @@ -189,4 +185,4 @@ public function getViewDql() { return $this->_dql; } -} \ No newline at end of file +} diff --git a/lib/Doctrine/View/Exception.php b/lib/Doctrine/View/Exception.php index e32a62a9b..0dbd77364 100644 --- a/lib/Doctrine/View/Exception.php +++ b/lib/Doctrine/View/Exception.php @@ -20,15 +20,16 @@ */ /** - * Doctrine_View_Exception + * Doctrine_View_Exception. * - * @package Doctrine - * @subpackage View * @author Konsta Vesterinen * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.doctrine-project.org + * + * @see www.doctrine-project.org * @since 1.0 + * * @version $Revision: 7490 $ */ class Doctrine_View_Exception extends Doctrine_Exception -{ } \ No newline at end of file +{ +}