From 716bb65b8671310e473cbd7bd85a7f53d2e62649 Mon Sep 17 00:00:00 2001 From: lsmith Date: Fri, 29 Dec 2006 14:01:31 +0000 Subject: [PATCH] - first round of PEAR CS fixes --- lib/Doctrine.php | 900 ++--- lib/Doctrine/Access.php | 262 +- lib/Doctrine/Adapter.php | 6 +- lib/Doctrine/Adapter/Statement.php | 16 +- lib/Doctrine/Cache/Query/Sqlite.php | 12 +- lib/Doctrine/Collection.php | 233 +- lib/Doctrine/Collection/Batch.php | 91 +- lib/Doctrine/Collection/Exception.php | 16 +- lib/Doctrine/Collection/Immediate.php | 19 +- lib/Doctrine/Collection/Iterator.php | 29 +- .../Collection/Iterator/Expandable.php | 28 +- lib/Doctrine/Collection/Iterator/Normal.php | 19 +- lib/Doctrine/Collection/Iterator/Offset.php | 20 +- lib/Doctrine/Collection/Lazy.php | 21 +- lib/Doctrine/Collection/Offset.php | 17 +- lib/Doctrine/Compiler.php | 359 +- lib/Doctrine/Compiler/Exception.php | 16 +- lib/Doctrine/Configurable.php | 499 +-- lib/Doctrine/Connection.php | 145 +- lib/Doctrine/Connection/Common.php | 23 +- lib/Doctrine/Connection/Db2.php | 35 +- lib/Doctrine/Connection/Exception.php | 4 +- lib/Doctrine/Connection/Firebird.php | 5 +- .../Connection/Firebird/Exception.php | 22 +- lib/Doctrine/Connection/Informix.php | 18 +- .../Connection/Informix/Exception.php | 18 +- lib/Doctrine/Connection/Mock.php | 2 +- lib/Doctrine/Connection/Module.php | 12 +- lib/Doctrine/Connection/Mssql.php | 8 +- lib/Doctrine/Connection/Mssql/Exception.php | 8 +- lib/Doctrine/Connection/Mysql.php | 30 +- lib/Doctrine/Connection/Mysql/Exception.php | 8 +- lib/Doctrine/Connection/Oracle.php | 6 +- lib/Doctrine/Connection/Oracle/Exception.php | 8 +- lib/Doctrine/Connection/Pgsql.php | 24 +- lib/Doctrine/Connection/Pgsql/Exception.php | 8 +- lib/Doctrine/Connection/Sqlite.php | 7 +- lib/Doctrine/Connection/Sqlite/Exception.php | 10 +- lib/Doctrine/Connection/UnitOfWork.php | 157 +- lib/Doctrine/DataDict/Exception.php | 16 +- lib/Doctrine/DataDict/Firebird.php | 182 +- lib/Doctrine/DataDict/Informix.php | 85 +- lib/Doctrine/DataDict/Informix/Exception.php | 16 +- lib/Doctrine/DataDict/Mssql.php | 168 +- lib/Doctrine/DataDict/Mysql.php | 350 +- lib/Doctrine/DataDict/Mysql/Exception.php | 16 +- lib/Doctrine/DataDict/Oracle.php | 178 +- lib/Doctrine/DataDict/Oracle/Exception.php | 16 +- lib/Doctrine/DataDict/Pgsql.php | 280 +- lib/Doctrine/DataDict/Sqlite.php | 272 +- lib/Doctrine/Db.php | 136 +- lib/Doctrine/Db/Event.php | 8 +- lib/Doctrine/Db/EventListener/Chain.php | 67 +- lib/Doctrine/Db/Exception.php | 2 +- lib/Doctrine/Db/Mock.php | 23 +- lib/Doctrine/Db/Profiler.php | 28 +- lib/Doctrine/Db/Profiler/Query.php | 25 +- lib/Doctrine/Db/Statement.php | 148 +- lib/Doctrine/EventListener.php | 18 +- lib/Doctrine/EventListener/Chain.php | 131 +- lib/Doctrine/EventListener/Debugger.php | 42 +- lib/Doctrine/EventListener/Empty.php | 17 +- lib/Doctrine/EventListener/Interface.php | 8 +- lib/Doctrine/Exception.php | 64 +- lib/Doctrine/Export.php | 47 +- lib/Doctrine/Export/Exception.php | 18 +- lib/Doctrine/Export/Firebird.php | 12 +- lib/Doctrine/Export/Firebird/Exception.php | 2 +- lib/Doctrine/Export/Mssql.php | 1 - lib/Doctrine/Export/Mysql.php | 44 +- lib/Doctrine/Export/Mysql/Exception.php | 2 +- lib/Doctrine/Export/Oracle.php | 12 +- lib/Doctrine/Export/Pgsql.php | 6 +- lib/Doctrine/Export/Sqlite.php | 2 +- lib/Doctrine/Expression.php | 36 +- lib/Doctrine/Expression/Firebird.php | 2 +- lib/Doctrine/Expression/Mssql.php | 20 +- lib/Doctrine/Expression/Mysql.php | 4 +- lib/Doctrine/Expression/Oracle.php | 18 +- lib/Doctrine/Expression/Pgsql.php | 8 +- lib/Doctrine/Expression/Sqlite.php | 14 +- lib/Doctrine/Hook.php | 37 +- lib/Doctrine/Hook/Equal.php | 4 +- lib/Doctrine/Hook/Integer.php | 16 +- lib/Doctrine/Hook/Parser.php | 8 +- lib/Doctrine/Hook/Parser/Complex.php | 10 +- lib/Doctrine/Hook/WordLike.php | 6 +- lib/Doctrine/Hydrate.php | 244 +- lib/Doctrine/Hydrate/Alias.php | 22 +- lib/Doctrine/Identifier.php | 17 +- lib/Doctrine/Import.php | 354 +- lib/Doctrine/Import/Builder.php | 314 +- lib/Doctrine/Import/Firebird.php | 2 +- lib/Doctrine/Import/Mysql.php | 2 +- lib/Doctrine/Import/Reader.php | 120 +- lib/Doctrine/Import/Reader/Db.php | 207 +- lib/Doctrine/Import/Reader/Exception.php | 100 +- lib/Doctrine/Import/Reader/Propel.php | 132 +- lib/Doctrine/Import/Sqlite.php | 6 +- lib/Doctrine/Lib.php | 56 +- lib/Doctrine/Locking/Exception.php | 31 +- lib/Doctrine/Locking/Manager/Pessimistic.php | 565 ++-- lib/Doctrine/Manager.php | 703 ++-- lib/Doctrine/Manager/Exception.php | 18 +- lib/Doctrine/Null.php | 20 +- lib/Doctrine/Overloadable.php | 2 +- lib/Doctrine/Query/Condition.php | 14 +- lib/Doctrine/Query/Exception.php | 1 - lib/Doctrine/Query/From.php | 27 +- lib/Doctrine/Query/Groupby.php | 5 +- lib/Doctrine/Query/Having.php | 8 +- lib/Doctrine/Query/Orderby.php | 28 +- lib/Doctrine/Query/Part.php | 23 +- lib/Doctrine/Query/Set.php | 6 +- lib/Doctrine/Query/Where.php | 125 +- lib/Doctrine/RawSql.php | 127 +- lib/Doctrine/RawSql/Exception.php | 18 +- lib/Doctrine/Record.php | 2902 ++++++++--------- lib/Doctrine/Record/Exception.php | 20 +- lib/Doctrine/Record/Iterator.php | 6 +- lib/Doctrine/Record/State/Exception.php | 18 +- lib/Doctrine/Relation.php | 47 +- lib/Doctrine/Relation/Association.php | 69 +- lib/Doctrine/Relation/Association/Self.php | 64 +- lib/Doctrine/Relation/ForeignKey.php | 40 +- lib/Doctrine/Relation/LocalKey.php | 31 +- lib/Doctrine/Schema.php | 161 +- lib/Doctrine/Schema/Column.php | 147 +- lib/Doctrine/Schema/Database.php | 184 +- lib/Doctrine/Schema/Object.php | 190 +- lib/Doctrine/Schema/Relation.php | 245 +- lib/Doctrine/Schema/Table.php | 212 +- lib/Doctrine/Table.php | 396 ++- lib/Doctrine/Table/Exception.php | 19 +- lib/Doctrine/Table/Repository.php | 34 +- lib/Doctrine/Table/Repository/Exception.php | 18 +- lib/Doctrine/Transaction.php | 72 +- lib/Doctrine/Transaction/Exception.php | 2 +- lib/Doctrine/Transaction/Firebird.php | 12 +- lib/Doctrine/Transaction/Mssql.php | 2 +- lib/Doctrine/Transaction/Mysql.php | 8 +- lib/Doctrine/Transaction/Oracle.php | 22 +- lib/Doctrine/Transaction/Pgsql.php | 12 +- lib/Doctrine/Transaction/Sqlite.php | 2 +- lib/Doctrine/Validator.php | 547 ++-- lib/Doctrine/Validator/Country.php | 499 ++- lib/Doctrine/Validator/Creditcard.php | 1 - lib/Doctrine/Validator/Date.php | 9 +- lib/Doctrine/Validator/Email.php | 157 +- lib/Doctrine/Validator/Enum.php | 9 +- lib/Doctrine/Validator/ErrorStack.php | 254 +- lib/Doctrine/Validator/Exception.php | 21 +- lib/Doctrine/Validator/Htmlcolor.php | 3 +- lib/Doctrine/Validator/Interface.class.php | 1 - lib/Doctrine/Validator/Ip.php | 1 - lib/Doctrine/Validator/Nospace.php | 1 - lib/Doctrine/Validator/Notblank.php | 3 +- lib/Doctrine/Validator/Notnull.php | 5 +- lib/Doctrine/Validator/Protected.php | 1 - lib/Doctrine/Validator/Range.php | 9 +- lib/Doctrine/Validator/Regexp.php | 113 +- lib/Doctrine/Validator/Unique.php | 1 - lib/Doctrine/Validator/Usstate.php | 205 +- lib/Doctrine/ValueHolder.php | 27 +- lib/Doctrine/View.php | 2 - lib/Doctrine/View/Exception.php | 2 +- 166 files changed, 7871 insertions(+), 7978 deletions(-) diff --git a/lib/Doctrine.php b/lib/Doctrine.php index 8c5cf804f..89bb6a64a 100644 --- a/lib/Doctrine.php +++ b/lib/Doctrine.php @@ -1,450 +1,450 @@ -. - */ - -/** - * Doctrine - * the base class of Doctrine framework - * - * @package Doctrine - * @author Konsta Vesterinen - * @author Lukas Smith (PEAR MDB2 library) - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ -final class Doctrine { - /** - * 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; - /** - * class naming error - */ - const ERR_CLASS_NAME = -36; - - /** - * ATTRIBUTE CONSTANTS - */ - - /** - * event listener attribute - */ - const ATTR_LISTENER = 1; - /** - * portability attribute - */ - const ATTR_PORTABILITY = 9; - /** - * quote identifier attribute - */ - const ATTR_QUOTE_IDENTIFIER = 3; - /** - * field case attribute - */ - const ATTR_FIELD_CASE = 4; - /** - * index name format attribute - */ - const ATTR_IDXNAME_FORMAT = 5; - /** - * sequence name format attribute - */ - const ATTR_SEQNAME_FORMAT = 6; - /** - * sequence column name attribute - */ - const ATTR_SEQCOL_NAME = 7; - /** - * validation attribute - */ - const ATTR_VLD = 12; - /** - * collection key attribute - */ - const ATTR_COLL_KEY = 15; - /** - * query limit - */ - const ATTR_QUERY_LIMIT = 17; - /** - * automatic length validations attribute - */ - const ATTR_AUTO_LENGTH_VLD = 19; - /** - * automatic type validations attribute - */ - const ATTR_AUTO_TYPE_VLD = 20; - /** - * default table type attribute - */ - const ATTR_DEFAULT_TABLE_TYPE = 21; - const ATTR_DEF_TEXT_LENGTH = 30; - const ATTR_DEF_VARCHAR_LENGTH = 31; - const ATTR_DEF_TABLESPACE = 32; - const ATTR_EMULATE_DATABASE = 33; - const ATTR_DB_NAME_FORMAT = 34; - - /** TODO: REMOVE THE FOLLOWING CONSTANTS AND UPDATE THE DOCS ! */ - - /** - * fetchmode attribute - */ - const ATTR_FETCHMODE = 2; - /** - * batch size attribute - */ - const ATTR_BATCH_SIZE = 8; - /** - * locking attribute - */ - const ATTR_LOCKMODE = 11; - /** - * name prefix attribute - */ - const ATTR_NAME_PREFIX = 13; - /** - * create tables attribute - */ - const ATTR_CREATE_TABLES = 14; - /** - * collection limit attribute - */ - const ATTR_COLL_LIMIT = 16; - /** - * accessor invoking attribute - */ - const ATTR_ACCESSORS = 18; - /** - * accessor invoking prefix get - */ - const ATTR_ACCESSOR_PREFIX_GET = 22; - /** - * accessor invoking prefix set - */ - const ATTR_ACCESSOR_PREFIX_SET = 23; - - - - /** - * LIMIT CONSTANTS - */ - - /** - * constant for row limiting - */ - const LIMIT_ROWS = 1; - /** - * constant for record limiting - */ - const LIMIT_RECORDS = 2; - - /** - * FETCHMODE CONSTANTS - */ - - /** - * IMMEDIATE FETCHING - * mode for immediate fetching - */ - const FETCH_IMMEDIATE = 0; - /** - * BATCH FETCHING - * mode for batch fetching - */ - const FETCH_BATCH = 1; - /** - * LAZY FETCHING - * mode for lazy fetching - */ - const FETCH_LAZY = 2; - /** - * LAZY FETCHING - * mode for offset fetching - */ - const FETCH_OFFSET = 3; - /** - * LAZY OFFSET FETCHING - * mode for lazy offset fetching - */ - const FETCH_LAZY_OFFSET = 4; - - /** - * FETCH CONSTANTS - */ - - - /** - * FETCH VALUEHOLDER - */ - const FETCH_VHOLDER = 1; - /** - * FETCH RECORD - * - * Specifies that the fetch method shall return Doctrine_Record - * objects as the elements of the result set. - * - * This is the default fetchmode. - */ - const FETCH_RECORD = 2; - /** - * FETCH ARRAY - */ - - const FETCH_ARRAY = 3; - - - /** - * ACCESSOR CONSTANTS - */ - - /** - * constant for no accessors - */ - const ACCESSOR_NONE = 0; - /** - * constant for get accessors - */ - const ACCESSOR_GET = 1; - /** - * constant for set accessors - */ - const ACCESSOR_SET = 2; - /** - * constant for both accessors get and set - */ - const ACCESSOR_BOTH = 3; - - /** - * PORTABILITY CONSTANTS - */ - - - /** - * Portability: turn off all portability features. - * @see Doctrine::ATTR_PORTABILITY - */ - 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 Doctrine::ATTR_PORTABILITY - */ - const PORTABILITY_FIX_CASE = 1; - - /** - * Portability: right trim the data output by query*() and fetch*(). - * @see Doctrine::ATTR_PORTABILITY - */ - const PORTABILITY_RTRIM = 2; - - /** - * Portability: force reporting the number of rows deleted. - * @see Doctrine::ATTR_PORTABILITY - */ - const PORTABILITY_DELETE_COUNT = 4; - /** - * Portability: convert empty values to null strings in data output by - * query*() and fetch*(). - * @see Doctrine::ATTR_PORTABILITY - */ - const PORTABILITY_EMPTY_TO_NULL = 8; - /** - * Portability: removes database/table qualifiers from associative indexes - * @see Doctrine::ATTR_PORTABILITY - */ - const PORTABILITY_FIX_ASSOC_FIELD_NAMES = 16; - - /** - * Portability: turn on all portability features. - * @see Doctrine::ATTR_PORTABILITY - */ - const PORTABILITY_ALL = 17; - - /** - * LOCKMODE CONSTANTS - */ - - /** - * mode for optimistic locking - */ - const LOCK_OPTIMISTIC = 0; - /** - * mode for pessimistic locking - */ - const LOCK_PESSIMISTIC = 1; - /** - * constructor - */ - public function __construct() { - throw new Doctrine_Exception('Doctrine is static class. No instances can be created.'); - } - /** - * @var string $path doctrine root directory - */ - private static $path; - /** - * getPath - * returns the doctrine root - * - * @return string - */ - public static function getPath() { - if(! self::$path) - self::$path = dirname(__FILE__); - - return self::$path; - } - /** - * loadAll - * loads all runtime classes - * - * @return void - */ - public static function loadAll() { - $classes = Doctrine_Compiler::getRuntimeClasses(); - - foreach($classes as $class) { - Doctrine::autoload($class); - } - } - /** - * import - * method for importing existing schema to Doctrine_Record classes - * - * @param string $directory - */ - public static function import($directory) { - Doctrine_Import::import(); - } - /** - * export - * method for exporting Doctrine_Record classes to a schema - * - * @param string $directory - */ - public static function export($directory) { - Doctrine_Export::export(); - } - /** - * compile - * 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 - * - * @throws Doctrine_Exception - * @return void - */ - public static function compile() { - Doctrine_Compiler::compile(); - } - /** - * simple autoload function - * returns true if the class was loaded, otherwise false - * - * @param string $classname - * @return boolean - */ - public static function autoload($classname) { - if(class_exists($classname)) - return false; - - if(! self::$path) - self::$path = dirname(__FILE__); - - $class = self::$path.DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR,$classname) . '.php'; - - if( ! file_exists($class)) - return false; - - - require_once($class); - - return true; - } - /** - * returns table name from class name - * - * @param string $classname - * @return string - */ - public static function tableize($classname) { - return strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $classname)); - } - /** - * returns class name from table name - * - * @param string $tablename - * @return string - */ - public static function classify($tablename) { - return preg_replace('~(_?)(_)([\w])~e', '"$1".strtoupper("$3")', ucfirst($tablename)); - } - /** - * checks for valid class name (uses camel case and underscores) - * - * @param string $classname - * @return boolean - */ - public static function isValidClassname($classname) { - if(preg_match('~(^[a-z])|(_[a-z])|([\W])|(_{2})~', $classname)) - return false; - - return true; - } -} -?> +. + */ + +/** + * Doctrine + * the base class of Doctrine framework + * + * @package Doctrine + * @author Konsta Vesterinen + * @author Lukas Smith (PEAR MDB2 library) + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ +final class Doctrine { + /** + * 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; + /** + * class naming error + */ + const ERR_CLASS_NAME = -36; + + /** + * ATTRIBUTE CONSTANTS + */ + + /** + * event listener attribute + */ + const ATTR_LISTENER = 1; + /** + * portability attribute + */ + const ATTR_PORTABILITY = 9; + /** + * quote identifier attribute + */ + const ATTR_QUOTE_IDENTIFIER = 3; + /** + * field case attribute + */ + const ATTR_FIELD_CASE = 4; + /** + * index name format attribute + */ + const ATTR_IDXNAME_FORMAT = 5; + /** + * sequence name format attribute + */ + const ATTR_SEQNAME_FORMAT = 6; + /** + * sequence column name attribute + */ + const ATTR_SEQCOL_NAME = 7; + /** + * validation attribute + */ + const ATTR_VLD = 12; + /** + * collection key attribute + */ + const ATTR_COLL_KEY = 15; + /** + * query limit + */ + const ATTR_QUERY_LIMIT = 17; + /** + * automatic length validations attribute + */ + const ATTR_AUTO_LENGTH_VLD = 19; + /** + * automatic type validations attribute + */ + const ATTR_AUTO_TYPE_VLD = 20; + /** + * default table type attribute + */ + const ATTR_DEFAULT_TABLE_TYPE = 21; + const ATTR_DEF_TEXT_LENGTH = 30; + const ATTR_DEF_VARCHAR_LENGTH = 31; + const ATTR_DEF_TABLESPACE = 32; + const ATTR_EMULATE_DATABASE = 33; + const ATTR_DB_NAME_FORMAT = 34; + + /** TODO: REMOVE THE FOLLOWING CONSTANTS AND UPDATE THE DOCS ! */ + + /** + * fetchmode attribute + */ + const ATTR_FETCHMODE = 2; + /** + * batch size attribute + */ + const ATTR_BATCH_SIZE = 8; + /** + * locking attribute + */ + const ATTR_LOCKMODE = 11; + /** + * name prefix attribute + */ + const ATTR_NAME_PREFIX = 13; + /** + * create tables attribute + */ + const ATTR_CREATE_TABLES = 14; + /** + * collection limit attribute + */ + const ATTR_COLL_LIMIT = 16; + /** + * accessor invoking attribute + */ + const ATTR_ACCESSORS = 18; + /** + * accessor invoking prefix get + */ + const ATTR_ACCESSOR_PREFIX_GET = 22; + /** + * accessor invoking prefix set + */ + const ATTR_ACCESSOR_PREFIX_SET = 23; + + + + /** + * LIMIT CONSTANTS + */ + + /** + * constant for row limiting + */ + const LIMIT_ROWS = 1; + /** + * constant for record limiting + */ + const LIMIT_RECORDS = 2; + + /** + * FETCHMODE CONSTANTS + */ + + /** + * IMMEDIATE FETCHING + * mode for immediate fetching + */ + const FETCH_IMMEDIATE = 0; + /** + * BATCH FETCHING + * mode for batch fetching + */ + const FETCH_BATCH = 1; + /** + * LAZY FETCHING + * mode for lazy fetching + */ + const FETCH_LAZY = 2; + /** + * LAZY FETCHING + * mode for offset fetching + */ + const FETCH_OFFSET = 3; + /** + * LAZY OFFSET FETCHING + * mode for lazy offset fetching + */ + const FETCH_LAZY_OFFSET = 4; + + /** + * FETCH CONSTANTS + */ + + + /** + * FETCH VALUEHOLDER + */ + const FETCH_VHOLDER = 1; + /** + * FETCH RECORD + * + * Specifies that the fetch method shall return Doctrine_Record + * objects as the elements of the result set. + * + * This is the default fetchmode. + */ + const FETCH_RECORD = 2; + /** + * FETCH ARRAY + */ + + const FETCH_ARRAY = 3; + + + /** + * ACCESSOR CONSTANTS + */ + + /** + * constant for no accessors + */ + const ACCESSOR_NONE = 0; + /** + * constant for get accessors + */ + const ACCESSOR_GET = 1; + /** + * constant for set accessors + */ + const ACCESSOR_SET = 2; + /** + * constant for both accessors get and set + */ + const ACCESSOR_BOTH = 3; + + /** + * PORTABILITY CONSTANTS + */ + + + /** + * Portability: turn off all portability features. + * @see Doctrine::ATTR_PORTABILITY + */ + 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 Doctrine::ATTR_PORTABILITY + */ + const PORTABILITY_FIX_CASE = 1; + + /** + * Portability: right trim the data output by query*() and fetch*(). + * @see Doctrine::ATTR_PORTABILITY + */ + const PORTABILITY_RTRIM = 2; + + /** + * Portability: force reporting the number of rows deleted. + * @see Doctrine::ATTR_PORTABILITY + */ + const PORTABILITY_DELETE_COUNT = 4; + /** + * Portability: convert empty values to null strings in data output by + * query*() and fetch*(). + * @see Doctrine::ATTR_PORTABILITY + */ + const PORTABILITY_EMPTY_TO_NULL = 8; + /** + * Portability: removes database/table qualifiers from associative indexes + * @see Doctrine::ATTR_PORTABILITY + */ + const PORTABILITY_FIX_ASSOC_FIELD_NAMES = 16; + + /** + * Portability: turn on all portability features. + * @see Doctrine::ATTR_PORTABILITY + */ + const PORTABILITY_ALL = 17; + + /** + * LOCKMODE CONSTANTS + */ + + /** + * mode for optimistic locking + */ + const LOCK_OPTIMISTIC = 0; + /** + * mode for pessimistic locking + */ + const LOCK_PESSIMISTIC = 1; + /** + * constructor + */ + public function __construct() { + throw new Doctrine_Exception('Doctrine is static class. No instances can be created.'); + } + /** + * @var string $path doctrine root directory + */ + private static $path; + /** + * getPath + * returns the doctrine root + * + * @return string + */ + public static function getPath() { + if (! self::$path) { + self::$path = dirname(__FILE__); + } + return self::$path; + } + /** + * loadAll + * loads all runtime classes + * + * @return void + */ + public static function loadAll() { + $classes = Doctrine_Compiler::getRuntimeClasses(); + + foreach ($classes as $class) { + Doctrine::autoload($class); + } + } + /** + * import + * method for importing existing schema to Doctrine_Record classes + * + * @param string $directory + */ + public static function import($directory) { + Doctrine_Import::import(); + } + /** + * export + * method for exporting Doctrine_Record classes to a schema + * + * @param string $directory + */ + public static function export($directory) { + Doctrine_Export::export(); + } + /** + * compile + * 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 + * + * @throws Doctrine_Exception + * @return void + */ + public static function compile() { + Doctrine_Compiler::compile(); + } + /** + * simple autoload function + * returns true if the class was loaded, otherwise false + * + * @param string $classname + * @return boolean + */ + public static function autoload($classname) { + if (class_exists($classname)) { + return false; + } + if (! self::$path) { + self::$path = dirname(__FILE__); + } + $class = self::$path.DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR,$classname) . '.php'; + + if ( ! file_exists($class)) { + return false; + } + + require_once($class); + + return true; + } + /** + * returns table name from class name + * + * @param string $classname + * @return string + */ + public static function tableize($classname) { + return strtolower(preg_replace('~(?<=\\w)([A-Z])~', '_$1', $classname)); + } + /** + * returns class name from table name + * + * @param string $tablename + * @return string + */ + public static function classify($tablename) { + return preg_replace('~(_?)(_)([\w])~e', '"$1".strtoupper("$3")', ucfirst($tablename)); + } + /** + * checks for valid class name (uses camel case and underscores) + * + * @param string $classname + * @return boolean + */ + public static function isValidClassname($classname) { + if (preg_match('~(^[a-z])|(_[a-z])|([\W])|(_{2})~', $classname)) + return false; + + return true; + } +} +?> diff --git a/lib/Doctrine/Access.php b/lib/Doctrine/Access.php index aa22b64df..575a925e2 100644 --- a/lib/Doctrine/Access.php +++ b/lib/Doctrine/Access.php @@ -1,131 +1,131 @@ -. - */ -/** - * Doctrine_Access - * - * the purpose of Doctrine_Access is to provice array access - * and property overload interface for subclasses - * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -abstract class Doctrine_Access implements ArrayAccess { - /** - * setArray - * - * @param array $array an array of key => value pairs - * @since 1.0 - * @return Doctrine_Access - */ - public function setArray(array $array) { - foreach($array as $k=>$v): - $this->set($k,$v); - endforeach; - - return $this; - } - /** - * __set an alias of set() - * - * @see set, offsetSet - * @param $name - * @param $value - * @since 1.0 - * @return void - */ - public function __set($name,$value) { - $this->set($name,$value); - } - /** - * __get -- an alias of get() - * - * @see get, offsetGet - * @param mixed $name - * @since 1.0 - * @return mixed - */ - public function __get($name) { - return $this->get($name); - } - /** - * __isset() - * - * @param string $name - * @since 1.0 - * @return boolean whether or not this object contains $name - */ - public function __isset($name) { - return $this->contains($name); - } - /** - * __unset() - * - * @param string $name - * @since 1.0 - * @return void - */ - public function __unset($name) { - return $this->remove($name); - } - /** - * @param mixed $offset - * @return boolean whether or not this object contains $offset - */ - public function offsetExists($offset) { - return $this->contains($offset); - } - /** - * offsetGet an alias of get() - * @see get, __get - * @param mixed $offset - * @return mixed - */ - public function offsetGet($offset) { - return $this->get($offset); - } - /** - * sets $offset to $value - * @see set, __set - * @param mixed $offset - * @param mixed $value - * @return void - */ - public function offsetSet($offset, $value) { - if( ! isset($offset)) { - $this->add($value); - } else - $this->set($offset,$value); - } - /** - * unset a given offset - * @see set, offsetSet, __set - * @param mixed $offset - */ - public function offsetUnset($offset) { - return $this->remove($offset); - } -} - +. + */ +/** + * Doctrine_Access + * + * the purpose of Doctrine_Access is to provice array access + * and property overload interface for subclasses + * + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +abstract class Doctrine_Access implements ArrayAccess { + /** + * setArray + * + * @param array $array an array of key => value pairs + * @since 1.0 + * @return Doctrine_Access + */ + public function setArray(array $array) { + foreach ($array as $k=>$v) { + $this->set($k,$v); + }; + + return $this; + } + /** + * __set an alias of set() + * + * @see set, offsetSet + * @param $name + * @param $value + * @since 1.0 + * @return void + */ + public function __set($name,$value) { + $this->set($name,$value); + } + /** + * __get -- an alias of get() + * + * @see get, offsetGet + * @param mixed $name + * @since 1.0 + * @return mixed + */ + public function __get($name) { + return $this->get($name); + } + /** + * __isset() + * + * @param string $name + * @since 1.0 + * @return boolean whether or not this object contains $name + */ + public function __isset($name) { + return $this->contains($name); + } + /** + * __unset() + * + * @param string $name + * @since 1.0 + * @return void + */ + public function __unset($name) { + return $this->remove($name); + } + /** + * @param mixed $offset + * @return boolean whether or not this object contains $offset + */ + public function offsetExists($offset) { + return $this->contains($offset); + } + /** + * offsetGet an alias of get() + * @see get, __get + * @param mixed $offset + * @return mixed + */ + public function offsetGet($offset) { + return $this->get($offset); + } + /** + * sets $offset to $value + * @see set, __set + * @param mixed $offset + * @param mixed $value + * @return void + */ + public function offsetSet($offset, $value) { + if ( ! isset($offset)) { + $this->add($value); + } else { + $this->set($offset,$value); + } + } + /** + * unset a given offset + * @see set, offsetSet, __set + * @param mixed $offset + */ + public function offsetUnset($offset) { + return $this->remove($offset); + } +} diff --git a/lib/Doctrine/Adapter.php b/lib/Doctrine/Adapter.php index eaf37e510..964989804 100644 --- a/lib/Doctrine/Adapter.php +++ b/lib/Doctrine/Adapter.php @@ -1,5 +1,5 @@ . */ /** - * + * * Doctrine_Adapter * * @package Doctrine @@ -92,7 +92,7 @@ class Doctrine_Adapter { const FETCH_UNIQUE = 196608; const NULL_EMPTY_STRING = 1; const NULL_NATURAL = 0; - const NULL_TO_STRING = NULL; + const NULL_TO_STRING = NULL; const PARAM_BOOL = 5; const PARAM_INPUT_OUTPUT = -2147483648; const PARAM_INT = 1; diff --git a/lib/Doctrine/Adapter/Statement.php b/lib/Doctrine/Adapter/Statement.php index d4fd374fc..684634006 100644 --- a/lib/Doctrine/Adapter/Statement.php +++ b/lib/Doctrine/Adapter/Statement.php @@ -21,14 +21,14 @@ /** * Doctrine_Adapter_Statement * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ abstract class Doctrine_Adapter_Statement { public function bindValue($no, $value) { } diff --git a/lib/Doctrine/Cache/Query/Sqlite.php b/lib/Doctrine/Cache/Query/Sqlite.php index 207a0c3db..371653f32 100644 --- a/lib/Doctrine/Cache/Query/Sqlite.php +++ b/lib/Doctrine/Cache/Query/Sqlite.php @@ -1,5 +1,5 @@ getCurrentConnection(); - + } $this->session = $connection; $dir = 'cache'; $this->path = $dir.DIRECTORY_SEPARATOR; $this->dbh = new PDO("sqlite::memory:"); - try { - if($this->session->getAttribute(Doctrine::ATTR_CREATE_TABLES) === true) - { + if ($this->session->getAttribute(Doctrine::ATTR_CREATE_TABLES) === true) { $columns = array(); $columns['query_md5'] = array('string', 32, 'notnull'); $columns['query_result'] = array('array', 100000, 'notnull'); @@ -127,7 +125,7 @@ class Doctrine_Cache_Query_Sqlite implements Countable { } /** * delete - * returns whether or not the given + * returns whether or not the given * query was succesfully deleted * * @param string $md5 diff --git a/lib/Doctrine/Collection.php b/lib/Doctrine/Collection.php index 385577e5b..f09fbc1df 100644 --- a/lib/Doctrine/Collection.php +++ b/lib/Doctrine/Collection.php @@ -68,8 +68,7 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator * @var Doctrine_Null $null used for extremely fast null value testing */ protected static $null; - - + protected $aggregateValues = array(); /** @@ -78,15 +77,15 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator * @param Doctrine_Table|string $table */ public function __construct($table) { - if( ! ($table instanceof Doctrine_Table)) + if ( ! ($table instanceof Doctrine_Table)) { $table = Doctrine_Manager::getInstance() ->getCurrentConnection() ->getTable($table); - + } $this->table = $table; $name = $table->getAttribute(Doctrine::ATTR_COLL_KEY); - if($name !== null) { + if ($name !== null) { $this->keyColumn = $name; } } @@ -158,7 +157,7 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $array = unserialize($serialized); - foreach($array as $name => $values) { + foreach ($array as $name => $values) { $this->$name = $values; } @@ -168,7 +167,7 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $this->expandable = true; $name = $this->table->getAttribute(Doctrine::ATTR_COLL_KEY); - if($name !== null) { + if ($name !== null) { $this->keyColumn = $name; } } @@ -250,21 +249,22 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $this->reference = $record; $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->reference_field = $relation->getForeign(); $value = $record->get($relation->getLocal()); - foreach($this->getNormalIterator() as $record) { - if($value !== null) { + foreach ($this->getNormalIterator() as $record) { + if ($value !== null) { $record->set($this->reference_field, $value, false); } else { $record->set($this->reference_field, $this->reference, false); } } - } elseif($relation instanceof Doctrine_Relation_Association) { + } elseif ($relation instanceof Doctrine_Relation_Association) { } } @@ -288,48 +288,49 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $limit = null; $offset = null; - switch(get_class($this)): - case "Doctrine_Collection_Offset": - $limit = $this->getLimit(); - $offset = (floor($key / $limit) * $limit); + switch (get_class($this)) { + case "Doctrine_Collection_Offset": + $limit = $this->getLimit(); + $offset = (floor($key / $limit) * $limit); - if( ! $this->expandable && isset($this->expanded[$offset])) - return false; - - $fields = implode(", ",$this->table->getColumnNames()); + if ( ! $this->expandable && isset($this->expanded[$offset])) { + return false; + } + $fields = implode(", ",$this->table->getColumnNames()); break; + default: + if ( ! $this->expandable) { + return false; + } + + if ( ! isset($this->reference)) { + return false; + } + + $id = $this->reference->obtainIdentifier(); + + if (empty($id)) { + return false; + } + + switch (get_class($this)) { + case "Doctrine_Collection_Immediate": + $fields = implode(", ",$this->table->getColumnNames()); + break; default: - if( ! $this->expandable) - return false; + $fields = implode(", ",$this->table->getPrimaryKeys()); + }; + }; - if( ! isset($this->reference)) - return false; - - $id = $this->reference->obtainIdentifier(); - - if(empty($id)) - return false; - - switch(get_class($this)): - case "Doctrine_Collection_Immediate": - $fields = implode(", ",$this->table->getColumnNames()); - break; - default: - $fields = implode(", ",$this->table->getPrimaryKeys()); - endswitch; - - - endswitch; - - if(isset($this->relation)) { - if($this->relation instanceof Doctrine_Relation_ForeignKey) { + if (isset($this->relation)) { + if ($this->relation instanceof Doctrine_Relation_ForeignKey) { $params[] = $this->reference->getIncremented(); $where[] = $this->reference_field." = ?"; - if( ! isset($offset)) { + if ( ! isset($offset)) { $ids = $this->getPrimaryKeys(); - if( ! empty($ids)) { + if ( ! empty($ids)) { $where[] = $this->table->getIdentifier()." NOT IN (".substr(str_repeat("?, ",count($ids)),0,-2).")"; $params = array_merge($params,$ids); } @@ -337,8 +338,7 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $this->expandable = false; } - - } elseif($this->relation instanceof Doctrine_Relation_Association) { + } elseif ($this->relation instanceof Doctrine_Relation_Association) { $asf = $this->relation->getAssociationFactory(); $query = 'SELECT '.$foreign." FROM ".$asf->getTableName()." WHERE ".$local."=".$this->getIncremented(); @@ -354,32 +354,32 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $query = "SELECT ".$fields." FROM ".$this->table->getTableName(); // apply column aggregation inheritance - foreach($this->table->getInheritanceMap() as $k => $v) { + foreach ($this->table->getInheritanceMap() as $k => $v) { $where[] = $k." = ?"; $params[] = $v; } - if( ! empty($where)) { + if ( ! empty($where)) { $query .= " WHERE ".implode(" AND ",$where); } $coll = $this->table->execute($query, $params, $limit, $offset); - if( ! isset($offset)) { - foreach($coll as $record) { - if(isset($this->reference_field)) + if ( ! isset($offset)) { + foreach ($coll as $record) { + if (isset($this->reference_field)) { $record->set($this->reference_field,$this->reference, false); - + } $this->reference->addReference($record, $this->relation); } } else { $i = $offset; - foreach($coll as $record) { - if(isset($this->reference)) { + foreach ($coll as $record) { + if (isset($this->reference)) { $this->reference->addReference($record, $this->relation, $i); - } else + } else { $this->data[$i] = $record; - + } $i++; } @@ -388,7 +388,7 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator // check if the fetched collection's record count is smaller // than the query limit, if so this collection has been expanded to its max size - if(count($coll) < $limit) { + if (count($coll) < $limit) { $this->expandable = false; } } @@ -403,7 +403,7 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator * @return boolean */ public function remove($key) { - if( ! isset($this->data[$key])) { + if ( ! isset($this->data[$key])) { $this->expand($key); throw new InvalidKeyException(); } @@ -428,16 +428,16 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator * @return object Doctrine_Record return a specified record */ public function get($key) { - if( ! isset($this->data[$key])) { + if ( ! isset($this->data[$key])) { $this->expand($key); - if( ! isset($this->data[$key])) + if ( ! isset($this->data[$key])) { $this->data[$key] = $this->table->create(); - - if(isset($this->reference_field)) { + } + if (isset($this->reference_field)) { $value = $this->reference->get($this->relation->getLocal()); - if($value !== null) { + if ($value !== null) { $this->data[$key]->set($this->reference_field, $value, false); } else { @@ -456,13 +456,13 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $list = array(); $name = $this->table->getIdentifier(); - foreach($this->data as $record): - if(is_array($record) && isset($record[$name])) { + foreach ($this->data as $record) { + if (is_array($record) && isset($record[$name])) { $list[] = $record[$name]; } else { $list[] = $record->getIncremented(); } - endforeach; + }; return $list; } /** @@ -489,9 +489,9 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator * @return void */ public function set($key, Doctrine_Record $record) { - if(isset($this->reference_field)) + if (isset($this->reference_field)) { $record->set($this->reference_field, $this->reference, false); - + } $this->data[$key] = $record; } /** @@ -501,36 +501,37 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator * @return boolean */ public function add(Doctrine_Record $record,$key = null) { - if(isset($this->reference_field)) + if (isset($this->reference_field)) { $record->set($this->reference_field, $this->reference, false); - + } /** * for some weird reason in_array cannot be used here (php bug ?) - * + * * if used it results in fatal error : [ nesting level too deep ] */ - foreach($this->data as $val) { - if($val === $record) + foreach ($this->data as $val) { + if ($val === $record) { return false; + } } - if(isset($key)) { - if(isset($this->data[$key])) + if (isset($key)) { + if (isset($this->data[$key])) { return false; - + } $this->data[$key] = $record; return true; } - if(isset($this->keyColumn)) { + if (isset($this->keyColumn)) { $value = $record->get($this->keyColumn); - if($value === null) + if ($value === null) { throw new Doctrine_Collection_Exception("Couldn't create collection index. Record field '".$this->keyColumn."' was null."); - + } $this->data[$value] = $record; - } else + } else { $this->data[] = $record; - + } return true; } /** @@ -542,12 +543,13 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator public function loadRelated($name = null) { $query = new Doctrine_Query($this->table->getConnection()); - if( ! isset($name)) { - foreach($this->data as $record): + if ( ! isset($name)) { + foreach ($this->data as $record) { $value = $record->getIncremented(); - if($value !== null) + if ($value !== null) { $list[] = $value; - endforeach; + } + }; $query->from($this->table->getComponentName()."(".implode(", ",$this->table->getPrimaryKeys()).")"); $query->where($this->table->getComponentName().".id IN (".substr(str_repeat("?, ", count($list)),0,-2).")"); @@ -560,16 +562,17 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $local = $rel->getLocal(); $list = array(); - if($rel instanceof Doctrine_Relation_LocalKey || $rel instanceof Doctrine_Relation_ForeignKey) { - foreach($this->data as $record): + if ($rel instanceof Doctrine_Relation_LocalKey || $rel instanceof Doctrine_Relation_ForeignKey) { + foreach ($this->data as $record) { $list[] = $record[$local]; - endforeach; + }; } else { - foreach($this->data as $record): + foreach ($this->data as $record) { $value = $record->getIncremented(); - if($value !== null) + if ($value !== null) { $list[] = $value; - endforeach; + } + }; } $this->table->getRelation($name); $dql = $rel->getRelationDql(count($list), 'collection'); @@ -591,24 +594,25 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $foreign = $rel->getForeign(); $local = $rel->getLocal(); - if($rel instanceof Doctrine_Relation_LocalKey) { - foreach($this->data as $key => $record) { - foreach($coll as $k => $related) { - if($related[$foreign] == $record[$local]) { + if ($rel instanceof Doctrine_Relation_LocalKey) { + foreach ($this->data as $key => $record) { + foreach ($coll as $k => $related) { + if ($related[$foreign] == $record[$local]) { $this->data[$key]->setRelated($name, $related); } } } - } elseif($rel instanceof Doctrine_Relation_ForeignKey) { - foreach($this->data as $key => $record) { - if($record->getState() == Doctrine_Record::STATE_TCLEAN || - $record->getState() == Doctrine_Record::STATE_TDIRTY) + } elseif ($rel instanceof Doctrine_Relation_ForeignKey) { + foreach ($this->data as $key => $record) { + if ($record->getState() == Doctrine_Record::STATE_TCLEAN + || $record->getState() == Doctrine_Record::STATE_TDIRTY + ) { continue; - + } $sub = new Doctrine_Collection($table); - foreach($coll as $k => $related) { - if($related[$foreign] == $record[$local]) { + foreach ($coll as $k => $related) { + if ($related[$foreign] == $record[$local]) { $sub->add($related); $coll->remove($k); } @@ -616,20 +620,20 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $this->data[$key]->setRelated($name, $sub); } - } elseif($rel instanceof Doctrine_Relation_Association) { + } elseif ($rel instanceof Doctrine_Relation_Association) { $identifier = $this->table->getIdentifier(); $asf = $rel->getAssociationFactory(); $name = $table->getComponentName(); - foreach($this->data as $key => $record) { - if($record->getState() == Doctrine_Record::STATE_TCLEAN || - $record->getState() == Doctrine_Record::STATE_TDIRTY) + foreach ($this->data as $key => $record) { + if ($record->getState() == Doctrine_Record::STATE_TCLEAN + || $record->getState() == Doctrine_Record::STATE_TDIRTY + ) { continue; - + } $sub = new Doctrine_Collection($table); - foreach($coll as $k => $related) { - if($related->get($local) == $record[$identifier]) { - + foreach ($coll as $k => $related) { + if ($related->get($local) == $record[$identifier]) { $sub->add($related->get($name)); } } @@ -659,9 +663,9 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator } $conn->beginTransaction(); - foreach($this as $key => $record): + foreach ($this as $key => $record) { $record->save(); - endforeach; + }; $conn->commit(); } @@ -679,7 +683,7 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator $conn->beginTransaction(); - foreach($this as $key => $record) { + foreach ($this as $key => $record) { $record->delete(); } @@ -702,4 +706,3 @@ class Doctrine_Collection extends Doctrine_Access implements Countable, Iterator return Doctrine_Lib::getCollectionAsString($this); } } - diff --git a/lib/Doctrine/Collection/Batch.php b/lib/Doctrine/Collection/Batch.php index 4edb47fca..6b7cd1ca7 100644 --- a/lib/Doctrine/Collection/Batch.php +++ b/lib/Doctrine/Collection/Batch.php @@ -24,14 +24,14 @@ Doctrine::autoload('Doctrine_Collection'); * with batch load strategy * * - * @author Konsta Vesterinen - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @version $Revision$ - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - */ + * @author Konsta Vesterinen + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @version $Revision$ + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + */ class Doctrine_Collection_Batch extends Doctrine_Collection { /** * @var integer $batchSize batch size @@ -41,7 +41,7 @@ class Doctrine_Collection_Batch extends Doctrine_Collection { * @var array $loaded an array containing the loaded batches, keys representing the batch indexes */ private $loaded = array(); - + public function __construct(Doctrine_Table $table) { parent::__construct($table); $this->batchSize = $this->getTable()->getAttribute(Doctrine::ATTR_BATCH_SIZE); @@ -53,9 +53,9 @@ class Doctrine_Collection_Batch extends Doctrine_Collection { */ public function setBatchSize($batchSize) { $batchSize = (int) $batchSize; - if($batchSize <= 0) + if ($batchSize <= 0) { return false; - + } $this->batchSize = $batchSize; return true; } @@ -68,47 +68,46 @@ class Doctrine_Collection_Batch extends Doctrine_Collection { return $this->batchSize; } /** - * load + * load * loads a specified element, by loading the batch the element is part of * * @param Doctrine_Record $record record to be loaded * @return boolean whether or not the load operation was successful */ public function load(Doctrine_Record $record) { - if(empty($this->data)) + if (empty($this->data)) { return false; - + } $id = $record->obtainIdentifier(); $identifier = $this->table->getIdentifier(); - foreach($this->data as $key => $v) { - if(is_object($v)) { - if($v->obtainIdentifier() == $id) + foreach ($this->data as $key => $v) { + if (is_object($v)) { + if ($v->obtainIdentifier() == $id) { break; - - } elseif(is_array($v[$identifier])) { - if($v[$identifier] == $id) + } + } elseif (is_array($v[$identifier])) { + if ($v[$identifier] == $id) { break; + } } } $x = floor($key / $this->batchSize); - if( ! isset($this->loaded[$x])) { - + if ( ! isset($this->loaded[$x])) { $e = $x * $this->batchSize; $e2 = ($x + 1)* $this->batchSize; $a = array(); $proxies = array(); - for($i = $e; $i < $e2 && $i < $this->count(); $i++): - if($this->data[$i] instanceof Doctrine_Record) + for ($i = $e; $i < $e2 && $i < $this->count(); $i++) { + if ($this->data[$i] instanceof Doctrine_Record) { $id = $this->data[$i]->getIncremented(); - elseif(is_array($this->data[$i])) + } elseif (is_array($this->data[$i])) { $id = $this->data[$i][$identifier]; - - + } $a[$i] = $id; - endfor; + }; $c = count($a); @@ -120,14 +119,14 @@ class Doctrine_Collection_Batch extends Doctrine_Collection { $stmt = $this->table->getConnection()->execute($query,array_values($a)); - foreach($a as $k => $id) { + foreach ($a as $k => $id) { $row = $stmt->fetch(PDO::FETCH_ASSOC); - if($row === false) + if ($row === false) { break; - + } $this->table->setData($row); - if(is_object($this->data[$k])) { + if (is_object($this->data[$k])) { $this->data[$k]->factoryRefresh($this->table); } else { $this->data[$k] = $this->table->getRecord(); @@ -148,30 +147,27 @@ class Doctrine_Collection_Batch extends Doctrine_Collection { * @return object Doctrine_Record record */ public function get($key) { - if(isset($this->data[$key])) { - switch(gettype($this->data[$key])): - case "array": - // Doctrine_Record didn't exist in cache - $this->table->setData($this->data[$key]); - $this->data[$key] = $this->table->getProxy(); + if (isset($this->data[$key])) { + switch (gettype($this->data[$key])) { + case "array": + // Doctrine_Record didn't exist in cache + $this->table->setData($this->data[$key]); + $this->data[$key] = $this->table->getProxy(); - $this->data[$key]->addCollection($this); + $this->data[$key]->addCollection($this); break; - endswitch; + }; } else { - $this->expand($key); - if( ! isset($this->data[$key])) + if ( ! isset($this->data[$key])) { $this->data[$key] = $this->table->create(); - + } } - - if(isset($this->reference_field)) + if (isset($this->reference_field)) { $this->data[$key]->set($this->reference_field, $this->reference, false); - - + } return $this->data[$key]; } /** @@ -181,4 +177,3 @@ class Doctrine_Collection_Batch extends Doctrine_Collection { return new Doctrine_Collection_Iterator_Expandable($this); } } - diff --git a/lib/Doctrine/Collection/Exception.php b/lib/Doctrine/Collection/Exception.php index e3c63b0fd..7ef151ef4 100644 --- a/lib/Doctrine/Collection/Exception.php +++ b/lib/Doctrine/Collection/Exception.php @@ -21,12 +21,12 @@ /** * Doctrine_Collection_Exception * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Collection_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/Collection/Immediate.php b/lib/Doctrine/Collection/Immediate.php index fb07bfbfd..4007759b2 100644 --- a/lib/Doctrine/Collection/Immediate.php +++ b/lib/Doctrine/Collection/Immediate.php @@ -1,21 +1,20 @@ - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @version $Revision$ - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - */ + * @author Konsta Vesterinen + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @version $Revision$ + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + */ class Doctrine_Collection_Immediate extends Doctrine_Collection { /** * @param Doctrine_DQL_Parser $graph - * @param integer $key + * @param integer $key */ public function __construct(Doctrine_Table $table) { parent::__construct($table); } } - diff --git a/lib/Doctrine/Collection/Iterator.php b/lib/Doctrine/Collection/Iterator.php index 73110fd62..cff66ed6c 100644 --- a/lib/Doctrine/Collection/Iterator.php +++ b/lib/Doctrine/Collection/Iterator.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ abstract class Doctrine_Collection_Iterator implements Iterator { /** - * @var Doctrine_Collection $collection + * @var Doctrine_Collection $collection */ protected $collection; /** @@ -69,8 +69,9 @@ abstract class Doctrine_Collection_Iterator implements Iterator { public function rewind() { $this->index = 0; $i = $this->index; - if(isset($this->keys[$i])) + if (isset($this->keys[$i])) { $this->key = $this->keys[$i]; + } } /** @@ -97,10 +98,8 @@ abstract class Doctrine_Collection_Iterator implements Iterator { public function next() { $this->index++; $i = $this->index; - if(isset($this->keys[$i])) + if (isset($this->keys[$i])) { $this->key = $this->keys[$i]; + } } } - - - diff --git a/lib/Doctrine/Collection/Iterator/Expandable.php b/lib/Doctrine/Collection/Iterator/Expandable.php index ac1fd27ed..2a848ba5c 100644 --- a/lib/Doctrine/Collection/Iterator/Expandable.php +++ b/lib/Doctrine/Collection/Iterator/Expandable.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Collection_Iterator_Expandable extends Doctrine_Collection_Iterator { public function valid() { - if($this->index < $this->count) + if ($this->index < $this->count) { return true; - elseif($this->index == $this->count) { - + } elseif ($this->index == $this->count) { $coll = $this->collection->expand($this->index); - if($coll instanceof Doctrine_Collection) { + if ($coll instanceof Doctrine_Collection) { $count = count($coll); - if($count > 0) { + if ($count > 0) { $this->keys = array_merge($this->keys, $coll->getKeys()); $this->count += $count; return true; @@ -51,4 +50,3 @@ class Doctrine_Collection_Iterator_Expandable extends Doctrine_Collection_Iterat } } } - diff --git a/lib/Doctrine/Collection/Iterator/Normal.php b/lib/Doctrine/Collection/Iterator/Normal.php index 0fa23d114..7a7819620 100644 --- a/lib/Doctrine/Collection/Iterator/Normal.php +++ b/lib/Doctrine/Collection/Iterator/Normal.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Collection_Iterator_Normal extends Doctrine_Collection_Iterator { /** * @return boolean whether or not the iteration will continue @@ -38,4 +38,3 @@ class Doctrine_Collection_Iterator_Normal extends Doctrine_Collection_Iterator { return ($this->index < $this->count); } } - diff --git a/lib/Doctrine/Collection/Iterator/Offset.php b/lib/Doctrine/Collection/Iterator/Offset.php index ffe33ef03..a58dada46 100644 --- a/lib/Doctrine/Collection/Iterator/Offset.php +++ b/lib/Doctrine/Collection/Iterator/Offset.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Collection_Iterator_Offset extends Doctrine_Collection_Iterator { public function valid() { } } - - diff --git a/lib/Doctrine/Collection/Lazy.php b/lib/Doctrine/Collection/Lazy.php index 2f8963c59..bcd74db05 100644 --- a/lib/Doctrine/Collection/Lazy.php +++ b/lib/Doctrine/Collection/Lazy.php @@ -1,20 +1,20 @@ - */ + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Collection_Lazy extends Doctrine_Collection_Batch { /** * constructor - * @param Doctrine_DQL_Parser $graph + * @param Doctrine_DQL_Parser $graph * @param string $key */ public function __construct(Doctrine_Table $table) { @@ -22,4 +22,3 @@ class Doctrine_Collection_Lazy extends Doctrine_Collection_Batch { parent::setBatchSize(1); } } - diff --git a/lib/Doctrine/Collection/Offset.php b/lib/Doctrine/Collection/Offset.php index 5237b0659..d7348860b 100644 --- a/lib/Doctrine/Collection/Offset.php +++ b/lib/Doctrine/Collection/Offset.php @@ -23,14 +23,14 @@ Doctrine::autoload('Doctrine_Collection_Offset'); * Doctrine_Collection_Offset * Collection of Doctrine_Record objects. * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Collection_Offset extends Doctrine_Collection { /** * @var integer $limit @@ -56,4 +56,3 @@ class Doctrine_Collection_Offset extends Doctrine_Collection { return new Doctrine_Collection_Iterator_Expandable($this); } } - diff --git a/lib/Doctrine/Compiler.php b/lib/Doctrine/Compiler.php index 372b4f170..deebec974 100644 --- a/lib/Doctrine/Compiler.php +++ b/lib/Doctrine/Compiler.php @@ -1,179 +1,180 @@ -. - */ -/** - * Doctrine_Compiler - * This class can be used for compiling the entire Doctrine framework into a single file - * - * @package Doctrine - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ -class Doctrine_Compiler { - /** - * @var array $classes an array containing all runtime classes of Doctrine framework - */ - private static $classes = array( - 'Access', - 'Adapter_Interface', - 'Doctrine', - 'Configurable', - 'Collection', - 'Collection_Immediate', - 'Connection', - 'Connection_Exception', - 'Connection_UnitOfWork', - 'Db', - 'Db_Exception', - 'Db_EventListener', - 'Db_Event', - 'Db_EventListener_Chain', - 'Db_EventListener_Interface', - 'Db_Profiler', - 'Db_Statement', - 'Exception', - 'EventListener_Interface', - 'EventListener', - 'EventListener_Empty', - 'EventListener_Chain', - 'Hydrate', - 'Identifier', - 'Locking_Exception', - 'Manager', - 'Null', - 'Overloadable', - 'Query', - 'Query_Part', - 'Query_From', - 'Query_Orderby', - 'Query_Groupby', - 'Query_Condition', - 'Query_Where', - 'Query_Having', - 'Query_Exception', - 'Query_Set', - 'RawSql', - 'RawSql_Exception', - 'Record', - 'Record_Exception', - 'Record_Iterator', - 'Relation', - 'Relation_ForeignKey', - 'Relation_LocalKey', - 'Relation_Association', - 'Relation_Association_Self', - 'Table', - 'Table_Exception', - 'Validator', - 'Validator_Exception', - 'Validator_Notnull', - 'Validator_Nospace', - 'Validator_Range', - 'Validator_Regexp', - 'Validator_Country', - 'Validator_Notblank', - 'Validator_Creditcard', - 'Validator_Date', - 'Validator_Ip', - 'Validator_Unique', - 'Validator_Usstate', - 'Validator_Htmlcolor', - 'Validator_Email', - 'View', - 'View_Exception'); - - /** - * getRuntimeClasses - * returns an array containing all runtime classes of Doctrine framework - * - * @return array - */ - public static function getRuntimeClasses() { - return self::$classes; - } - /** - * 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 - * - * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation - * @return void - */ - public static function compile($target = null) { - $path = Doctrine::getPath(); - - $classes = self::$classes; - - $ret = array(); - - foreach($classes as $class) { - if($class !== 'Doctrine') - $class = 'Doctrine_'.$class; - - $file = $path.DIRECTORY_SEPARATOR.str_replace("_",DIRECTORY_SEPARATOR,$class).".php"; - - echo "Adding $file" . PHP_EOL; - - if( ! file_exists($file)) - throw new Doctrine_Compiler_Exception("Couldn't compile $file. File $file does not exists."); - - Doctrine::autoload($class); - $refl = new ReflectionClass ( $class ); - $lines = file( $file ); - - $start = $refl -> getStartLine() - 1; - $end = $refl -> getEndLine(); - - $ret = array_merge($ret, - array_slice($lines, - $start, - ($end - $start))); - - } - - if ($target == null) { - $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"); - - fwrite($fp, ". + */ +/** + * Doctrine_Compiler + * This class can be used for compiling the entire Doctrine framework into a single file + * + * @package Doctrine + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ +class Doctrine_Compiler { + /** + * @var array $classes an array containing all runtime classes of Doctrine framework + */ + private static $classes = array( + 'Access', + 'Adapter_Interface', + 'Doctrine', + 'Configurable', + 'Collection', + 'Collection_Immediate', + 'Connection', + 'Connection_Exception', + 'Connection_UnitOfWork', + 'Db', + 'Db_Exception', + 'Db_EventListener', + 'Db_Event', + 'Db_EventListener_Chain', + 'Db_EventListener_Interface', + 'Db_Profiler', + 'Db_Statement', + 'Exception', + 'EventListener_Interface', + 'EventListener', + 'EventListener_Empty', + 'EventListener_Chain', + 'Hydrate', + 'Identifier', + 'Locking_Exception', + 'Manager', + 'Null', + 'Overloadable', + 'Query', + 'Query_Part', + 'Query_From', + 'Query_Orderby', + 'Query_Groupby', + 'Query_Condition', + 'Query_Where', + 'Query_Having', + 'Query_Exception', + 'Query_Set', + 'RawSql', + 'RawSql_Exception', + 'Record', + 'Record_Exception', + 'Record_Iterator', + 'Relation', + 'Relation_ForeignKey', + 'Relation_LocalKey', + 'Relation_Association', + 'Relation_Association_Self', + 'Table', + 'Table_Exception', + 'Validator', + 'Validator_Exception', + 'Validator_Notnull', + 'Validator_Nospace', + 'Validator_Range', + 'Validator_Regexp', + 'Validator_Country', + 'Validator_Notblank', + 'Validator_Creditcard', + 'Validator_Date', + 'Validator_Ip', + 'Validator_Unique', + 'Validator_Usstate', + 'Validator_Htmlcolor', + 'Validator_Email', + 'View', + 'View_Exception'); + + /** + * getRuntimeClasses + * returns an array containing all runtime classes of Doctrine framework + * + * @return array + */ + public static function getRuntimeClasses() { + return self::$classes; + } + /** + * 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 + * + * @throws Doctrine_Compiler_Exception if something went wrong during the compile operation + * @return void + */ + public static function compile($target = null) { + $path = Doctrine::getPath(); + + $classes = self::$classes; + + $ret = array(); + + foreach ($classes as $class) { + if ($class !== 'Doctrine') + $class = 'Doctrine_'.$class; + + $file = $path.DIRECTORY_SEPARATOR.str_replace("_",DIRECTORY_SEPARATOR,$class).".php"; + + echo "Adding $file" . PHP_EOL; + + if ( ! file_exists($file)) { + throw new Doctrine_Compiler_Exception("Couldn't compile $file. File $file does not exists."); + } + Doctrine::autoload($class); + $refl = new ReflectionClass ( $class ); + $lines = file( $file ); + + $start = $refl -> getStartLine() - 1; + $end = $refl -> getEndLine(); + + $ret = array_merge($ret, + array_slice($lines, + $start, + ($end - $start))); + + } + + if ($target == null) { + $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"); + } + fwrite($fp, " - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @package Doctrine + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Compiler_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/Configurable.php b/lib/Doctrine/Configurable.php index 61d568e75..08422a37f 100644 --- a/lib/Doctrine/Configurable.php +++ b/lib/Doctrine/Configurable.php @@ -1,248 +1,251 @@ -. - */ -/** - * Doctrine_Configurable - * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection - * - * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -abstract class Doctrine_Configurable { - - /** - * @var array $attributes an array of containing all attributes - */ - private $attributes = array(); - /** - * @var $parent the parents of this component - */ - private $parent; - /** - * setAttribute - * sets a given attribute - * - * - * $manager->setAttribute(Doctrine::ATTR_PORTABILITY, Doctrine::PORTABILITY_ALL); - * - * // or - * - * $manager->setAttribute('portability', Doctrine::PORTABILITY_ALL); - * - * - * @param mixed $attribute either a Doctrine::ATTR_* integer constant or a string - * corresponding to a constant - * @param mixed $value the value of the attribute - * @see Doctrine::ATTR_* constants - * @throws Doctrine_Exception if the value is invalid - * @return void - */ - public function setAttribute($attribute,$value) { - switch($attribute): - case Doctrine::ATTR_BATCH_SIZE: - if($value < 0) - throw new Doctrine_Exception("Batch size should be greater than or equal to zero"); - break; - - case Doctrine::ATTR_FETCHMODE: - if($value < 0) - throw new Doctrine_Exception("Unknown fetchmode. See Doctrine::FETCH_* constants."); - break; - case Doctrine::ATTR_LISTENER: - $this->setEventListener($value); - break; - case Doctrine::ATTR_LOCKMODE: - if($this instanceof Doctrine_Connection) { - if($this->transaction->getState() != Doctrine_Transaction::STATE_SLEEP) - throw new Doctrine_Exception("Couldn't set lockmode. There are transactions open."); - - } elseif($this instanceof Doctrine_Manager) { - foreach($this as $connection) { - if($connection->transaction->getState() != Doctrine_Transaction::STATE_SLEEP) - throw new Doctrine_Exception("Couldn't set lockmode. There are transactions open."); - } - } else { - throw new Doctrine_Exception("Lockmode attribute can only be set at the global or connection level."); - } - break; - case Doctrine::ATTR_CREATE_TABLES: - $value = (bool) $value; - break; - case Doctrine::ATTR_ACCESSORS: - $accessors = array('none','get','set','both'); - - // if( ! in_array($value,$accessors)) - // throw new Doctrine_Exception(); - - break; - case Doctrine::ATTR_COLL_LIMIT: - if($value < 1) { - throw new Doctrine_Exception("Collection limit should be a value greater than or equal to 1."); - } - break; - case Doctrine::ATTR_COLL_KEY: - if( ! ($this instanceof Doctrine_Table)) - throw new Doctrine_Exception("This attribute can only be set at table level."); - - if( ! $this->hasColumn($value)) - throw new Doctrine_Exception("Couldn't set collection key attribute. No such column '$value'"); - - - break; - case Doctrine::ATTR_VLD: - case Doctrine::ATTR_AUTO_LENGTH_VLD: - case Doctrine::ATTR_AUTO_TYPE_VLD: - case Doctrine::ATTR_QUERY_LIMIT: - case Doctrine::ATTR_QUOTE_IDENTIFIER: - case Doctrine::ATTR_PORTABILITY: - case Doctrine::ATTR_DEFAULT_TABLE_TYPE: - case Doctrine::ATTR_ACCESSOR_PREFIX_GET: - case Doctrine::ATTR_ACCESSOR_PREFIX_SET: - - break; - case Doctrine::ATTR_SEQCOL_NAME: - if( ! is_string($value)) - throw new Doctrine_Exception('Sequence column name attribute only accepts string values'); - - break; - case Doctrine::ATTR_FIELD_CASE: - if($value != 0 && $value != CASE_LOWER && $value != CASE_UPPER) - throw new Doctrine_Exception('Field case attribute should be either 0, CASE_LOWER or CASE_UPPER constant.'); - break; - case Doctrine::ATTR_SEQNAME_FORMAT: - case Doctrine::ATTR_IDXNAME_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).'); - } - break; - default: - throw new Doctrine_Exception("Unknown attribute."); - endswitch; - - $this->attributes[$attribute] = $value; - - } - /** - * @param Doctrine_EventListener $listener - * @return void - */ - public function setEventListener($listener) { - return $this->setListener($listener); - } - /** - * addListener - * - * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Db - */ - public function addListener($listener, $name = null) { - if( ! ($this->attributes[Doctrine::ATTR_LISTENER] instanceof Doctrine_EventListener_Chain)) - $this->attributes[Doctrine::ATTR_LISTENER] = new Doctrine_EventListener_Chain(); - - $this->attributes[Doctrine::ATTR_LISTENER]->add($listener, $name); - - return $this; - } - /** - * getListener - * - * @return Doctrine_Db_EventListener_Interface|Doctrine_Overloadable - */ - public function getListener() { - if( ! isset($this->attributes[Doctrine::ATTR_LISTENER])) { - if(isset($this->parent)) - return $this->parent->getListener(); - - return null; - } - return $this->attributes[Doctrine::ATTR_LISTENER]; - } - /** - * setListener - * - * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Db - */ - public function setListener($listener) { - if( ! ($listener instanceof Doctrine_EventListener_Interface) && - ! ($listener instanceof Doctrine_Overloadable)) - throw new Doctrine_Exception("Couldn't set eventlistener. EventListeners should implement either Doctrine_EventListener_Interface or Doctrine_Overloadable"); - - $this->attributes[Doctrine::ATTR_LISTENER] = $listener; - - return $this; - } - /** - * returns the value of an attribute - * - * @param integer $attribute - * @return mixed - */ - public function getAttribute($attribute) { - $attribute = (int) $attribute; - - if($attribute < 1 || $attribute > 23) - throw new Doctrine_Exception('Unknown attribute.'); - - if( ! isset($this->attributes[$attribute])) { - if(isset($this->parent)) - return $this->parent->getAttribute($attribute); - - return null; - } - return $this->attributes[$attribute]; - } - /** - * getAttributes - * returns all attributes as an array - * - * @return array - */ - public function getAttributes() { - return $this->attributes; - } - /** - * sets a parent for this configurable component - * the parent must be configurable component itself - * - * @param Doctrine_Configurable $component - * @return void - */ - public function setParent(Doctrine_Configurable $component) { - $this->parent = $component; - } - /** - * getParent - * returns the parent of this component - * - * @return Doctrine_Configurable - */ - public function getParent() { - return $this->parent; - } -} - +. + */ +/** + * Doctrine_Configurable + * the base for Doctrine_Table, Doctrine_Manager and Doctrine_Connection + * + * + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +abstract class Doctrine_Configurable { + + /** + * @var array $attributes an array of containing all attributes + */ + private $attributes = array(); + /** + * @var $parent the parents of this component + */ + private $parent; + /** + * setAttribute + * sets a given attribute + * + * + * $manager->setAttribute(Doctrine::ATTR_PORTABILITY, Doctrine::PORTABILITY_ALL); + * + * // or + * + * $manager->setAttribute('portability', Doctrine::PORTABILITY_ALL); + * + * + * @param mixed $attribute either a Doctrine::ATTR_* integer constant or a string + * corresponding to a constant + * @param mixed $value the value of the attribute + * @see Doctrine::ATTR_* constants + * @throws Doctrine_Exception if the value is invalid + * @return void + */ + public function setAttribute($attribute,$value) { + switch ($attribute) { + case Doctrine::ATTR_BATCH_SIZE: + if ($value < 0) { + throw new Doctrine_Exception("Batch size should be greater than or equal to zero"); + } + break; + + case Doctrine::ATTR_FETCHMODE: + if ($value < 0) { + throw new Doctrine_Exception("Unknown fetchmode. See Doctrine::FETCH_* constants."); + } + break; + case Doctrine::ATTR_LISTENER: + $this->setEventListener($value); + break; + case Doctrine::ATTR_LOCKMODE: + if ($this instanceof Doctrine_Connection) { + if ($this->transaction->getState() != Doctrine_Transaction::STATE_SLEEP) { + throw new Doctrine_Exception("Couldn't set lockmode. There are transactions open."); + } + } elseif ($this instanceof Doctrine_Manager) { + foreach ($this as $connection) { + if ($connection->transaction->getState() != Doctrine_Transaction::STATE_SLEEP) { + throw new Doctrine_Exception("Couldn't set lockmode. There are transactions open."); + } + } + } else { + throw new Doctrine_Exception("Lockmode attribute can only be set at the global or connection level."); + } + break; + case Doctrine::ATTR_CREATE_TABLES: + $value = (bool) $value; + break; + case Doctrine::ATTR_ACCESSORS: + $accessors = array('none','get','set','both'); + + // if ( ! in_array($value,$accessors)) { + // throw new Doctrine_Exception(); + // } + + break; + case Doctrine::ATTR_COLL_LIMIT: + if ($value < 1) { + throw new Doctrine_Exception("Collection limit should be a value greater than or equal to 1."); + } + break; + case Doctrine::ATTR_COLL_KEY: + if ( ! ($this instanceof Doctrine_Table)) { + throw new Doctrine_Exception("This attribute can only be set at table level."); + } + if ( ! $this->hasColumn($value)) { + throw new Doctrine_Exception("Couldn't set collection key attribute. No such column '$value'"); + } + break; + case Doctrine::ATTR_VLD: + case Doctrine::ATTR_AUTO_LENGTH_VLD: + case Doctrine::ATTR_AUTO_TYPE_VLD: + case Doctrine::ATTR_QUERY_LIMIT: + case Doctrine::ATTR_QUOTE_IDENTIFIER: + case Doctrine::ATTR_PORTABILITY: + case Doctrine::ATTR_DEFAULT_TABLE_TYPE: + case Doctrine::ATTR_ACCESSOR_PREFIX_GET: + case Doctrine::ATTR_ACCESSOR_PREFIX_SET: + + break; + case Doctrine::ATTR_SEQCOL_NAME: + if ( ! is_string($value)) { + throw new Doctrine_Exception('Sequence column name attribute only accepts string values'); + } + break; + case Doctrine::ATTR_FIELD_CASE: + if ($value != 0 && $value != CASE_LOWER && $value != CASE_UPPER) + throw new Doctrine_Exception('Field case attribute should be either 0, CASE_LOWER or CASE_UPPER constant.'); + break; + case Doctrine::ATTR_SEQNAME_FORMAT: + case Doctrine::ATTR_IDXNAME_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).'); + } + break; + default: + throw new Doctrine_Exception("Unknown attribute."); + }; + + $this->attributes[$attribute] = $value; + + } + /** + * @param Doctrine_EventListener $listener + * @return void + */ + public function setEventListener($listener) { + return $this->setListener($listener); + } + /** + * addListener + * + * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener + * @return Doctrine_Db + */ + public function addListener($listener, $name = null) { + if ( ! ($this->attributes[Doctrine::ATTR_LISTENER] instanceof Doctrine_EventListener_Chain)) { + $this->attributes[Doctrine::ATTR_LISTENER] = new Doctrine_EventListener_Chain(); + } + $this->attributes[Doctrine::ATTR_LISTENER]->add($listener, $name); + + return $this; + } + /** + * getListener + * + * @return Doctrine_Db_EventListener_Interface|Doctrine_Overloadable + */ + public function getListener() { + if ( ! isset($this->attributes[Doctrine::ATTR_LISTENER])) { + if (isset($this->parent)) { + return $this->parent->getListener(); + } + return null; + } + return $this->attributes[Doctrine::ATTR_LISTENER]; + } + /** + * setListener + * + * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener + * @return Doctrine_Db + */ + public function setListener($listener) { + if ( ! ($listener instanceof Doctrine_EventListener_Interface) + && ! ($listener instanceof Doctrine_Overloadable) + ) { + throw new Doctrine_Exception("Couldn't set eventlistener. EventListeners should implement either Doctrine_EventListener_Interface or Doctrine_Overloadable"); + } + $this->attributes[Doctrine::ATTR_LISTENER] = $listener; + + return $this; + } + /** + * returns the value of an attribute + * + * @param integer $attribute + * @return mixed + */ + public function getAttribute($attribute) { + $attribute = (int) $attribute; + + if ($attribute < 1 || $attribute > 23) + throw new Doctrine_Exception('Unknown attribute.'); + + if ( ! isset($this->attributes[$attribute])) { + if (isset($this->parent)) { + return $this->parent->getAttribute($attribute); + } + return null; + } + return $this->attributes[$attribute]; + } + /** + * getAttributes + * returns all attributes as an array + * + * @return array + */ + public function getAttributes() { + return $this->attributes; + } + /** + * sets a parent for this configurable component + * the parent must be configurable component itself + * + * @param Doctrine_Configurable $component + * @return void + */ + public function setParent(Doctrine_Configurable $component) { + $this->parent = $component; + } + /** + * getParent + * returns the parent of this component + * + * @return Doctrine_Configurable + */ + public function getParent() { + return $this->parent; + } +} diff --git a/lib/Doctrine/Connection.php b/lib/Doctrine/Connection.php index c2543501d..faeb4a0b6 100644 --- a/lib/Doctrine/Connection.php +++ b/lib/Doctrine/Connection.php @@ -110,9 +110,9 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @param PDO|Doctrine_Adapter_Interface $adapter database driver */ public function __construct(Doctrine_Manager $manager, $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->modules['transaction'] = new Doctrine_Connection_Transaction($this); @@ -148,20 +148,20 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return Doctrine_Connection_Module connection module */ public function __get($name) { - if(isset($this->properties[$name])) + if (isset($this->properties[$name])) return $this->properties[$name]; - if( ! isset($this->modules[$name])) + if ( ! isset($this->modules[$name])) { throw new Doctrine_Connection_Exception('Unknown module / property ' . $name); - - if($this->modules[$name] === false) { - switch($name) { - case 'unitOfWork': - $this->modules[$name] = new Doctrine_Connection_UnitOfWork($this); + } + if ($this->modules[$name] === false) { + switch ($name) { + case 'unitOfWork': + $this->modules[$name] = new Doctrine_Connection_UnitOfWork($this); break; - default: - $class = 'Doctrine_' . ucwords($name) . '_' . $this->getName(); - $this->modules[$name] = new $class($this); + default: + $class = 'Doctrine_' . ucwords($name) . '_' . $this->getName(); + $this->modules[$name] = new $class($this); } } @@ -261,9 +261,11 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return boolean 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]) + && ($this->supported[$feature] === 'emulated' + || $this->supported[$feature] + ) + ); } /** * quote @@ -274,25 +276,25 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return mixed */ public function quote($input, $type = null) { - if($type == null) { + if ($type == null) { $type = gettype($input); } - switch($type) { - case 'integer': - case 'enum': - case 'boolean': - return $input; - case 'array': - case 'object': - $input = serialize($input); - case 'string': - case 'char': - case 'varchar': - case 'text': - case 'gzip': - case 'blob': - case 'clob': - return $this->dbh->quote($input); + switch ($type) { + case 'integer': + case 'enum': + case 'boolean': + return $input; + case 'array': + case 'object': + $input = serialize($input); + case 'string': + case 'char': + case 'varchar': + case 'text': + case 'gzip': + case 'blob': + case 'clob': + return $this->dbh->quote($input); } } /** @@ -380,20 +382,19 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return integer number of rows affected */ public function replace($table, array $fields, array $keys) { - //if( ! $this->supports('replace')) + //if ( ! $this->supports('replace')) // throw new Doctrine_Connection_Exception('replace query is not supported'); - - if(empty($keys)) + if (empty($keys)) { throw new Doctrine_Connection_Exception('Not specified which fields are keys'); - + } $condition = $values = array(); - foreach($fields as $name => $value) { + foreach ($fields as $name => $value) { $values[$name] = $value; - if(in_array($name, $keys)) { - if($value === null) + if (in_array($name, $keys)) { + if ($value === null) throw new Doctrine_Connection_Exception('key value '.$name.' may not be null'); $condition[] = $name . ' = ?'; @@ -419,9 +420,9 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return boolean */ public function insert($table, array $values = array()) { - if(empty($values)) + if (empty($values)) { return false; - + } // column names are specified as array keys $cols = array_keys($values); @@ -505,9 +506,9 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun public function fetchColumn($statement, array $params = array()) { $result = $this->query($statement, $params)->fetchAll(PDO::FETCH_COLUMN); - if($this->options['portability'] & Doctrine::PORTABILITY_FIX_CASE) + if ($this->options['portability'] & Doctrine::PORTABILITY_FIX_CASE) { $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result); - + } return $result; } /** @@ -530,8 +531,6 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun public function fetchBoth($statement, array $params = array()) { return $this->query($statement, $params)->fetchAll(PDO::FETCH_BOTH); } - - /** * query * queries the database using Doctrine Query Language @@ -576,9 +575,9 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun $parser = new Doctrine_Query($this); $coll = $parser->query($query, $params); - if( ! $coll->contains(0)) + if ( ! $coll->contains(0)) { return false; - + } return $coll[0]; } /** @@ -591,9 +590,9 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return PDOStatement */ public function select($query,$limit = 0,$offset = 0) { - if($limit > 0 || $offset > 0) + if ($limit > 0 || $offset > 0) { $query = $this->modifyLimitQuery($query, $limit, $offset); - + } return $this->dbh->query($query); } /** @@ -605,7 +604,7 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun */ public function execute($query, array $params = array()) { try { - if( ! empty($params)) { + if ( ! empty($params)) { $stmt = $this->dbh->prepare($query); $stmt->execute($params); return $stmt; @@ -626,7 +625,7 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun */ public function exec($query, array $params = array()) { try { - if( ! empty($params)) { + if ( ! empty($params)) { $stmt = $this->dbh->prepare($query); $stmt->execute($params); return $stmt; @@ -647,9 +646,9 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun $name = 'Doctrine_Connection_' . $this->driverName . '_Exception'; $exc = new $name($e->getMessage(), (int) $e->getCode()); - if( ! is_array($e->errorInfo)) + if ( ! is_array($e->errorInfo)) { $e->errorInfo = array(null, null, null, null); - + } $exc->processErrorInfo($e->errorInfo); throw $exc; @@ -671,15 +670,14 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return object Doctrine_Table */ public function getTable($name) { - if(isset($this->tables[$name])) + if (isset($this->tables[$name])) { return $this->tables[$name]; - + } $class = $name."Table"; - if(class_exists($class) && in_array("Doctrine_Table", class_parents($class))) { + if (class_exists($class) && in_array("Doctrine_Table", class_parents($class))) { return new $class($name, $this); } else { - return new Doctrine_Table($name, $this); } } @@ -696,7 +694,7 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * initialized table objects * * - * foreach($conn as $index => $table) { + * foreach ($conn as $index => $table) { * print $table; // get a string representation of each table object * } * @@ -724,9 +722,9 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun public function addTable(Doctrine_Table $objTable) { $name = $objTable->getComponentName(); - if(isset($this->tables[$name])) + if (isset($this->tables[$name])) { return false; - + } $this->tables[$name] = $objTable; return true; } @@ -761,7 +759,7 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return void */ public function clear() { - foreach($this->tables as $k => $table) { + foreach ($this->tables as $k => $table) { $table->getRepository()->evictAll(); $table->clear(); } @@ -839,20 +837,19 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun public function save(Doctrine_Record $record) { $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreSave($record); - - switch($record->getState()): - case Doctrine_Record::STATE_TDIRTY: - $this->unitOfWork->insert($record); + switch ($record->getState()) { + case Doctrine_Record::STATE_TDIRTY: + $this->unitOfWork->insert($record); break; - case Doctrine_Record::STATE_DIRTY: - case Doctrine_Record::STATE_PROXY: - $this->unitOfWork->update($record); + case Doctrine_Record::STATE_DIRTY: + case Doctrine_Record::STATE_PROXY: + $this->unitOfWork->update($record); break; - case Doctrine_Record::STATE_CLEAN: - case Doctrine_Record::STATE_TCLEAN: - // do nothing + case Doctrine_Record::STATE_CLEAN: + case Doctrine_Record::STATE_TCLEAN: + // do nothing break; - endswitch; + }; $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onSave($record); } @@ -865,9 +862,9 @@ abstract class Doctrine_Connection extends Doctrine_Configurable implements Coun * @return boolean true on success, false on failure */ public function delete(Doctrine_Record $record) { - if( ! $record->exists()) + if ( ! $record->exists()) { return false; - + } $this->beginTransaction(); $record->getTable()->getListener()->onPreDelete($record); diff --git a/lib/Doctrine/Connection/Common.php b/lib/Doctrine/Connection/Common.php index 9365406f6..50bb54994 100644 --- a/lib/Doctrine/Connection/Common.php +++ b/lib/Doctrine/Connection/Common.php @@ -2,14 +2,14 @@ Doctrine::autoload('Doctrine_Connection'); /** * standard connection, the parent of pgsql, mysql and sqlite - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Connection_Common extends Doctrine_Connection { /** * Adds an driver-specific LIMIT clause to the query @@ -19,15 +19,14 @@ class Doctrine_Connection_Common extends Doctrine_Connection { * @param mixed $offset */ public function modifyLimitQuery($query,$limit = false,$offset = false,$isManip=false) { - if($limit && $offset) { + if ($limit && $offset) { $query .= " LIMIT ".$limit." OFFSET ".$offset; - } elseif($limit && ! $offset) { + } elseif ($limit && ! $offset) { $query .= " LIMIT ".$limit; - } elseif( ! $limit && $offset) { + } 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 dc2cfa638..0cf0c57b1 100644 --- a/lib/Doctrine/Connection/Db2.php +++ b/lib/Doctrine/Connection/Db2.php @@ -1,5 +1,5 @@ */ -class Doctrine_Connection_Exception extends Doctrine_Exception { +class Doctrine_Connection_Exception extends Doctrine_Exception { /** * @var array $errorMessages an array containing messages for portable error codes */ diff --git a/lib/Doctrine/Connection/Firebird.php b/lib/Doctrine/Connection/Firebird.php index 69aa63d77..4473cb8f0 100644 --- a/lib/Doctrine/Connection/Firebird.php +++ b/lib/Doctrine/Connection/Firebird.php @@ -1,5 +1,5 @@ 0) { + if ($limit > 0) { $query = preg_replace('/^([\s(])*SELECT(?!\s*FIRST\s*\d+)/i', "SELECT FIRST $limit SKIP $offset", $query); } @@ -112,4 +112,3 @@ class Doctrine_Connection_Firebird extends Doctrine_Connection { return $data[0]; } } - diff --git a/lib/Doctrine/Connection/Firebird/Exception.php b/lib/Doctrine/Connection/Firebird/Exception.php index f00dfde80..e5bd880f6 100644 --- a/lib/Doctrine/Connection/Firebird/Exception.php +++ b/lib/Doctrine/Connection/Firebird/Exception.php @@ -1,5 +1,5 @@ (PEAR MDB2 Interbase driver) * @author Lukas Smith (PEAR MDB2 library) */ -class Doctrine_Connection_Firebird_Exception extends Doctrine_Connection_Exception { +class Doctrine_Connection_Firebird_Exception extends Doctrine_Connection_Exception { /** * @var array $errorCodeMap an array that is used for determining portable * error code from a native database error code @@ -68,16 +68,16 @@ class Doctrine_Connection_Firebird_Exception extends Doctrine_Connection_Excepti -924 => Doctrine::ERR_CONNECT_FAILED ); /** - * @var array $errorRegexps an array that is used for determining portable + * @var array $errorRegexps an array that is used for determining portable * error code from a native database error message */ protected static $errorRegexps = array( '/generator .* is not defined/' => Doctrine::ERR_SYNTAX, // for compat. w ibase_errcode() '/table.*(not exist|not found|unknown)/i' - => Doctrine::ERR_NOSUCHTABLE, + => Doctrine::ERR_NOSUCHTABLE, '/table .* already exists/i' - => Doctrine::ERR_ALREADY_EXISTS, + => Doctrine::ERR_ALREADY_EXISTS, '/unsuccessful metadata update .* failed attempt to store duplicate value/i' => Doctrine::ERR_ALREADY_EXISTS, '/unsuccessful metadata update .* not found/i' @@ -92,12 +92,12 @@ class Doctrine_Connection_Firebird_Exception extends Doctrine_Connection_Excepti => Doctrine::ERR_ACCESS_VIOLATION, '/arithmetic exception, numeric overflow, or string truncation/i' => Doctrine::ERR_INVALID, - '/table unknown/i' + '/table unknown/i' => Doctrine::ERR_NOSUCHTABLE, ); /** - * This method checks if native error code/message can be - * converted into a portable code and then adds this + * This method checks if native error code/message can be + * converted into a portable code and then adds this * portable error code to errorInfo array and returns the modified array * * the portable error code is added at the end of array @@ -118,15 +118,15 @@ class Doctrine_Connection_Firebird_Exception extends Doctrine_Connection_Excepti } */ - foreach(self::$errorRegexps as $regexp => $code) { + foreach (self::$errorRegexps as $regexp => $code) { if (preg_match($regexp, $errorInfo[2])) { $errorInfo[3] = $code; break; } } - if(isset(self::$errorCodeMap[$errorInfo[1]])) + if (isset(self::$errorCodeMap[$errorInfo[1]])) { $errorInfo[3] = self::$errorCodeMap[$errorInfo[1]]; - + } return $errorInfo; } } diff --git a/lib/Doctrine/Connection/Informix.php b/lib/Doctrine/Connection/Informix.php index 0f3d4027c..c8f5bd7a9 100644 --- a/lib/Doctrine/Connection/Informix.php +++ b/lib/Doctrine/Connection/Informix.php @@ -22,15 +22,15 @@ Doctrine::autoload('Doctrine_Connection'); /** * Doctrine_Connection_Mysql * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Connection_Informix extends Doctrine_Connection { + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Connection_Informix extends Doctrine_Connection { /** * @var string $driverName the name of this connection driver */ diff --git a/lib/Doctrine/Connection/Informix/Exception.php b/lib/Doctrine/Connection/Informix/Exception.php index 27be9baba..49be2f956 100644 --- a/lib/Doctrine/Connection/Informix/Exception.php +++ b/lib/Doctrine/Connection/Informix/Exception.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Connection_Informix_Exception extends Doctrine_Connection_Exception { } diff --git a/lib/Doctrine/Connection/Mock.php b/lib/Doctrine/Connection/Mock.php index 6d02f482e..0d116441d 100644 --- a/lib/Doctrine/Connection/Mock.php +++ b/lib/Doctrine/Connection/Mock.php @@ -1,5 +1,5 @@ getCurrentConnection(); - + } $this->conn = $conn; - + $e = explode('_', get_class($this)); $this->moduleName = $e[1]; @@ -69,6 +69,6 @@ class Doctrine_Connection_Module { * @return string the name of this module */ public function getModuleName() { - return $this->moduleName; + return $this->moduleName; } } diff --git a/lib/Doctrine/Connection/Mssql.php b/lib/Doctrine/Connection/Mssql.php index ade9a16c9..e8f824fbc 100644 --- a/lib/Doctrine/Connection/Mssql.php +++ b/lib/Doctrine/Connection/Mssql.php @@ -104,13 +104,12 @@ class Doctrine_Connection_Mssql extends Doctrine_Connection { * @return string */ public function modifyLimitQuery($query, $limit, $offset, $isManip = false) { - if($limit > 0) { - + if ($limit > 0) { // we need the starting SELECT clause for later $select = 'SELECT '; - if (preg_match('/^[[:space:]*SELECT[[:space:]]*DISTINCT/i', $query, $matches) == 1) + if (preg_match('/^[[:space:]*SELECT[[:space:]]*DISTINCT/i', $query, $matches) == 1) { $select .= 'DISTINCT '; - + } $length = strlen($select); // is there an offset? @@ -168,4 +167,3 @@ class Doctrine_Connection_Mssql extends Doctrine_Connection { return $this->queryOne($query); } } - diff --git a/lib/Doctrine/Connection/Mssql/Exception.php b/lib/Doctrine/Connection/Mssql/Exception.php index a1a9834a9..c53b9b6d8 100644 --- a/lib/Doctrine/Connection/Mssql/Exception.php +++ b/lib/Doctrine/Connection/Mssql/Exception.php @@ -1,5 +1,5 @@ portableCode = self::$errorCodeMap[$code]; return true; } diff --git a/lib/Doctrine/Connection/Mysql.php b/lib/Doctrine/Connection/Mysql.php index 492f1005b..2d550d286 100644 --- a/lib/Doctrine/Connection/Mysql.php +++ b/lib/Doctrine/Connection/Mysql.php @@ -1,5 +1,5 @@ true, 'pattern_escaping' => true ); - - $this->properties['string_quoting'] = array('start' => "'", - 'end' => "'", + + $this->properties['string_quoting'] = array('start' => "'", + 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\'); $this->properties['identifier_quoting'] = array('start' => '`', - 'end' => '`', + 'end' => '`', 'escape' => '`'); $this->properties['sql_comments'] = array( @@ -85,7 +85,6 @@ class Doctrine_Connection_Mysql extends Doctrine_Connection_Common { $this->properties['varchar_max_length'] = 255; - parent::__construct($manager, $adapter); } /** @@ -118,7 +117,7 @@ class Doctrine_Connection_Mysql extends Doctrine_Connection_Common { $value = $this->dbh->lastInsertId(); - if(is_numeric($value)) { + if (is_numeric($value)) { $query = 'DELETE FROM ' . $sequenceName . ' WHERE ' . $seqcolName . ' < ' . $value; $result = $this->dbh->query($query); } @@ -205,17 +204,17 @@ class Doctrine_Connection_Mysql extends Doctrine_Connection_Common { $query = $values = ''; $keys = $colnum = 0; - for(reset($fields); $colnum < $count; next($fields), $colnum++) { + for (reset($fields); $colnum < $count; next($fields), $colnum++) { $name = key($fields); - if($colnum > 0) { + if ($colnum > 0) { $query .= ','; $values.= ','; } $query .= $name; - if(isset($fields[$name]['null']) && $fields[$name]['null']) { + if (isset($fields[$name]['null']) && $fields[$name]['null']) { $value = 'NULL'; } else { $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null; @@ -224,18 +223,17 @@ class Doctrine_Connection_Mysql extends Doctrine_Connection_Common { $values .= $value; - if(isset($fields[$name]['key']) && $fields[$name]['key']) { - if($value === 'NULL') + if (isset($fields[$name]['key']) && $fields[$name]['key']) { + if ($value === 'NULL') { throw new Doctrine_Connection_Mysql_Exception('key value '.$name.' may not be NULL'); - + } $keys++; } } - if($keys == 0) + if ($keys == 0) { throw new Doctrine_Connection_Mysql_Exception('not specified which fields are keys'); - - + } $query = 'REPLACE INTO ' . $table . ' (' . $query . ') VALUES (' . $values . ')'; return $this->dbh->exec($query); diff --git a/lib/Doctrine/Connection/Mysql/Exception.php b/lib/Doctrine/Connection/Mysql/Exception.php index 4704bda34..f7f427953 100644 --- a/lib/Doctrine/Connection/Mysql/Exception.php +++ b/lib/Doctrine/Connection/Mysql/Exception.php @@ -1,5 +1,5 @@ portableCode = self::$errorCodeMap[$code]; return true; } diff --git a/lib/Doctrine/Connection/Oracle.php b/lib/Doctrine/Connection/Oracle.php index e4383dd4e..4155181f8 100644 --- a/lib/Doctrine/Connection/Oracle.php +++ b/lib/Doctrine/Connection/Oracle.php @@ -1,5 +1,5 @@ supported = array( 'sequences' => true, @@ -127,4 +126,3 @@ class Doctrine_Connection_Oracle extends Doctrine_Connection { return $data[0]; } } - diff --git a/lib/Doctrine/Connection/Oracle/Exception.php b/lib/Doctrine/Connection/Oracle/Exception.php index 22f8c4ec7..24fb01a2a 100644 --- a/lib/Doctrine/Connection/Oracle/Exception.php +++ b/lib/Doctrine/Connection/Oracle/Exception.php @@ -1,5 +1,5 @@ portableCode = self::$errorCodeMap[$code]; return true; } diff --git a/lib/Doctrine/Connection/Pgsql.php b/lib/Doctrine/Connection/Pgsql.php index 191f0af26..b4b0f8b55 100644 --- a/lib/Doctrine/Connection/Pgsql.php +++ b/lib/Doctrine/Connection/Pgsql.php @@ -1,5 +1,5 @@ true, ); - $this->properties['string_quoting'] = array('start' => "'", - 'end' => "'", + $this->properties['string_quoting'] = array('start' => "'", + 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\'); @@ -119,23 +119,23 @@ class Doctrine_Connection_Pgsql extends Doctrine_Connection_Common { public function modifyLimitQuery($query, $limit = false, $offset = false, $isManip = false) { if ($limit > 0) { $query = rtrim($query); - + if (substr($query, -1) == ';') { $query = substr($query, 0, -1); } - + if ($isManip) { $manip = preg_replace('/^(DELETE FROM|UPDATE).*$/', '\\1', $query); $from = $match[2]; $where = $match[3]; - $query = $manip . ' ' . $from . ' WHERE ctid=(SELECT ctid FROM ' + $query = $manip . ' ' . $from . ' WHERE ctid=(SELECT ctid FROM ' . $from . ' ' . $where . ' LIMIT ' . $limit . ')'; } else { - if($limit !== false) { + if ($limit !== false) { $query .= ' LIMIT ' . $limit; } - if($offset !== false) { + if ($offset !== false) { $query .= ' OFFSET ' . $offset; } } @@ -153,12 +153,12 @@ class Doctrine_Connection_Pgsql extends Doctrine_Connection_Common { $serverInfo = $this->fetchOne($query); - if( ! $native) { + if ( ! $native) { $tmp = explode('.', $server_info, 3); - - if(empty($tmp[2]) && isset($tmp[1]) - && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)) { + if (empty($tmp[2]) && isset($tmp[1]) + && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2) + ) { $serverInfo = array( 'major' => $tmp[0], 'minor' => $tmp2[1], diff --git a/lib/Doctrine/Connection/Pgsql/Exception.php b/lib/Doctrine/Connection/Pgsql/Exception.php index d1da1c101..1c51b86b9 100644 --- a/lib/Doctrine/Connection/Pgsql/Exception.php +++ b/lib/Doctrine/Connection/Pgsql/Exception.php @@ -1,5 +1,5 @@ supported = array( 'sequences' => 'emulated', 'indexes' => true, @@ -96,4 +96,3 @@ class Doctrine_Connection_Sqlite extends Doctrine_Connection_Common { return $data[0]; } } - diff --git a/lib/Doctrine/Connection/Sqlite/Exception.php b/lib/Doctrine/Connection/Sqlite/Exception.php index a199b3e58..62477fd91 100644 --- a/lib/Doctrine/Connection/Sqlite/Exception.php +++ b/lib/Doctrine/Connection/Sqlite/Exception.php @@ -1,5 +1,5 @@ $code) { - if(preg_match($regexp, $errorInfo[2])) { + foreach (self::$errorRegexps as $regexp => $code) { + if (preg_match($regexp, $errorInfo[2])) { $this->portableCode = $code; return true; diff --git a/lib/Doctrine/Connection/UnitOfWork.php b/lib/Doctrine/Connection/UnitOfWork.php index acdc02c98..0a2c434b5 100644 --- a/lib/Doctrine/Connection/UnitOfWork.php +++ b/lib/Doctrine/Connection/UnitOfWork.php @@ -1,5 +1,5 @@ $table) { + foreach ($tables as $k => $table) { $k = $k.$table; - if( ! ($table instanceof Doctrine_Table)) + if ( ! ($table instanceof Doctrine_Table)) { $table = $this->conn->getTable($table); - + } $nm = $table->getComponentName(); $index = array_search($nm,$tree); - if($index === false) { + if ($index === false) { $tree[] = $nm; $index = max(array_keys($tree)); } $rels = $table->getRelations(); - + // group relations - - foreach($rels as $key => $rel) { - if($rel instanceof Doctrine_Relation_ForeignKey) { + + foreach ($rels as $key => $rel) { + if ($rel instanceof Doctrine_Relation_ForeignKey) { unset($rels[$key]); array_unshift($rels, $rel); } } - foreach($rels as $rel) { + foreach ($rels as $rel) { $name = $rel->getTable()->getComponentName(); $index2 = array_search($name,$tree); $type = $rel->getType(); // skip self-referenced relations - if($name === $nm) + if ($name === $nm) continue; - if($rel instanceof Doctrine_Relation_ForeignKey) { - if($index2 !== false) { - if($index2 >= $index) + if ($rel instanceof Doctrine_Relation_ForeignKey) { + if ($index2 !== false) { + if ($index2 >= $index) continue; unset($tree[$index]); @@ -90,9 +90,9 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen $tree[] = $name; } - } elseif($rel instanceof Doctrine_Relation_LocalKey) { - if($index2 !== false) { - if($index2 <= $index) + } elseif ($rel instanceof Doctrine_Relation_LocalKey) { + if ($index2 !== false) { + if ($index2 <= $index) continue; unset($tree[$index2]); @@ -101,20 +101,20 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen array_unshift($tree,$name); $index++; } - } elseif($rel instanceof Doctrine_Relation_Association) { + } elseif ($rel instanceof Doctrine_Relation_Association) { $t = $rel->getAssociationFactory(); $n = $t->getComponentName(); - - if($index2 !== false) + + if ($index2 !== false) unset($tree[$index2]); - + array_splice($tree,$index, 0,$name); $index++; $index3 = array_search($n,$tree); - if($index3 !== false) { - if($index3 >= $index) + if ($index3 !== false) { + if ($index3 >= $index) continue; unset($tree[$index]); @@ -137,29 +137,30 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen */ public function saveRelated(Doctrine_Record $record) { $saveLater = array(); - foreach($record->getReferences() as $k=>$v) { + foreach ($record->getReferences() as $k=>$v) { $fk = $record->getTable()->getRelation($k); - if($fk instanceof Doctrine_Relation_ForeignKey || + if ($fk instanceof Doctrine_Relation_ForeignKey || $fk instanceof Doctrine_Relation_LocalKey) { - if($fk->isComposite()) { + if ($fk->isComposite()) { $local = $fk->getLocal(); $foreign = $fk->getForeign(); - if($record->getTable()->hasPrimaryKey($fk->getLocal())) { - if( ! $record->exists()) + if ($record->getTable()->hasPrimaryKey($fk->getLocal())) { + if ( ! $record->exists()) { $saveLater[$k] = $fk; - else + } else { $v->save(); + } } else { // ONE-TO-ONE relationship $obj = $record->get($fk->getTable()->getComponentName()); - if($obj->getState() != Doctrine_Record::STATE_TCLEAN) + if ($obj->getState() != Doctrine_Record::STATE_TCLEAN) { $obj->save(); - + } } } - } elseif($fk instanceof Doctrine_Relation_Association) { + } elseif ($fk instanceof Doctrine_Relation_Association) { $v->save(); } } @@ -167,8 +168,8 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen } /** * saveAssociations - * - * this method takes a diff of one-to-many / many-to-many original and + * + * this method takes a diff of one-to-many / many-to-many original and * current collections and applies the changes * * for example if original many-to-many related collection has records with @@ -181,7 +182,7 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen * @return void */ public function saveAssociations(Doctrine_Record $record) { - foreach($record->getTable()->getRelations() as $rel) { + foreach ($record->getTable()->getRelations() as $rel) { $table = $rel->getTable(); $alias = $rel->getAlias(); @@ -196,18 +197,18 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen * @return void */ public function deleteComposites(Doctrine_Record $record) { - foreach($record->getTable()->getRelations() as $fk) { - switch($fk->getType()): - case Doctrine_Relation::ONE_COMPOSITE: - case Doctrine_Relation::MANY_COMPOSITE: - $obj = $record->get($fk->getAlias()); - $obj->delete(); + foreach ($record->getTable()->getRelations() as $fk) { + switch ($fk->getType()) { + case Doctrine_Relation::ONE_COMPOSITE: + case Doctrine_Relation::MANY_COMPOSITE: + $obj = $record->get($fk->getAlias()); + $obj->delete(); break; - endswitch; + }; } } /** - * saveAll + * saveAll * persists all the pending records from all tables * * @throws PDOException if something went wrong at database level @@ -218,19 +219,19 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen $tree = $this->buildFlushTree($this->conn->getTables()); // save all records - foreach($tree as $name) { + foreach ($tree as $name) { $table = $this->conn->getTable($name); - foreach($table->getRepository() as $record) { + foreach ($table->getRepository() as $record) { $this->conn->save($record); } } - + // save all associations - foreach($tree as $name) { + foreach ($tree as $name) { $table = $this->conn->getTable($name); - foreach($table->getRepository() as $record) { + foreach ($table->getRepository() as $record) { $this->saveAssociations($record); } } @@ -246,39 +247,37 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen $array = $record->getPrepared(); - if(empty($array)) + if (empty($array)) { return false; - + } $set = array(); - foreach($array as $name => $value): + foreach ($array as $name => $value) { $set[] = $name." = ?"; - if($value instanceof Doctrine_Record) { - switch($value->getState()): - case Doctrine_Record::STATE_TCLEAN: - case Doctrine_Record::STATE_TDIRTY: - $record->save(); - default: - $array[$name] = $value->getIncremented(); - $record->set($name, $value->getIncremented()); - endswitch; + if ($value instanceof Doctrine_Record) { + switch ($value->getState()) { + case Doctrine_Record::STATE_TCLEAN: + case Doctrine_Record::STATE_TDIRTY: + $record->save(); + default: + $array[$name] = $value->getIncremented(); + $record->set($name, $value->getIncremented()); + }; } - endforeach; + }; $params = array_values($array); $id = $record->obtainIdentifier(); - - if( ! is_array($id)) + if ( ! is_array($id)) { $id = array($id); - + } $id = array_values($id); $params = array_merge($params, $id); - - $sql = 'UPDATE ' . $record->getTable()->getTableName() - . ' SET ' . implode(', ', $set) - . ' WHERE ' . implode(' = ? AND ', $record->getTable()->getPrimaryKeys()) + $sql = 'UPDATE ' . $record->getTable()->getTableName() + . ' SET ' . implode(', ', $set) + . ' WHERE ' . implode(' = ? AND ', $record->getTable()->getPrimaryKeys()) . ' = ?'; $stmt = $this->conn->getDBH()->prepare($sql); @@ -299,19 +298,18 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen public function insert(Doctrine_Record $record) { // listen the onPreInsert event $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreInsert($record); - + $array = $record->getPrepared(); - if(empty($array)) + if (empty($array)) { return false; - + } $table = $record->getTable(); $keys = $table->getPrimaryKeys(); - $seq = $record->getTable()->getSequenceName(); - if( ! empty($seq)) { + if ( ! empty($seq)) { $id = $this->nextId($seq); $name = $record->getTable()->getIdentifier(); $array[$name] = $id; @@ -319,15 +317,16 @@ class Doctrine_Connection_UnitOfWork extends Doctrine_Connection_Module implemen $this->conn->insert($table->getTableName(), $array); - if(count($keys) == 1 && $keys[0] == $table->getIdentifier()) { + if (count($keys) == 1 && $keys[0] == $table->getIdentifier()) { $id = $this->conn->getDBH()->lastInsertID(); - if( ! $id) + if ( ! $id) $id = $table->getMaxIdentifier(); - + $record->assignIdentifier($id); - } else + } else { $record->assignIdentifier(true); + } // listen the onInsert event $table->getAttribute(Doctrine::ATTR_LISTENER)->onInsert($record); diff --git a/lib/Doctrine/DataDict/Exception.php b/lib/Doctrine/DataDict/Exception.php index 3c11e6a6b..cf6e02afa 100644 --- a/lib/Doctrine/DataDict/Exception.php +++ b/lib/Doctrine/DataDict/Exception.php @@ -22,12 +22,12 @@ Doctrine::autoload('Doctrine_Exception'); /** * Doctrine_DataDict_Exception * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_DataDict_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/DataDict/Firebird.php b/lib/Doctrine/DataDict/Firebird.php index ebb362c1f..35dbcba29 100644 --- a/lib/Doctrine/DataDict/Firebird.php +++ b/lib/Doctrine/DataDict/Firebird.php @@ -54,39 +54,39 @@ class Doctrine_DataDict_Firebird extends Doctrine_DataDict { * declare the specified field. */ public function getNativeDeclaration($field) { - switch($field['type']) { - case 'varchar': - case 'string': - case 'array': - case 'object': - case 'char': - case 'text': - $length = !empty($field['length']) - ? $field['length'] : 16777215; // TODO: $db->options['default_text_field_length']; + switch ($field['type']) { + case 'varchar': + case 'string': + case 'array': + case 'object': + case 'char': + case 'text': + $length = !empty($field['length']) + ? $field['length'] : 16777215; // TODO: $db->options['default_text_field_length']; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; - return $fixed ? 'CHAR('.$length.')' : 'VARCHAR('.$length.')'; - case 'clob': - return 'BLOB SUB_TYPE 1'; - case 'blob': - return 'BLOB SUB_TYPE 0'; - case 'integer': - case 'enum': - return 'INT'; - case 'boolean': - return 'SMALLINT'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME'; - case 'timestamp': - return 'TIMESTAMP'; - case 'float': - return 'DOUBLE PRECISION'; - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - return 'DECIMAL('.$length.','.$db->options['decimal_places'].')'; + return $fixed ? 'CHAR('.$length.')' : 'VARCHAR('.$length.')'; + case 'clob': + return 'BLOB SUB_TYPE 1'; + case 'blob': + return 'BLOB SUB_TYPE 0'; + case 'integer': + case 'enum': + return 'INT'; + case 'boolean': + return 'SMALLINT'; + case 'date': + return 'DATE'; + case 'time': + return 'TIME'; + case 'timestamp': + return 'TIMESTAMP'; + case 'float': + return 'DOUBLE PRECISION'; + case 'decimal': + $length = !empty($field['length']) ? $field['length'] : 18; + return 'DECIMAL('.$length.','.$db->options['decimal_places'].')'; } return ''; } @@ -99,7 +99,7 @@ class Doctrine_DataDict_Firebird extends Doctrine_DataDict { public function getPortableDeclaration($field) { $length = $field['length']; - if((int) $length <= 0) + if ((int) $length <= 0) $length = null; $type = array(); @@ -108,67 +108,67 @@ class Doctrine_DataDict_Firebird extends Doctrine_DataDict { $field['field_sub_type'] = !empty($field['field_sub_type']) ? strtolower($field['field_sub_type']) : null; switch ($db_type) { - case 'smallint': - case 'integer': - case 'int64': - //these may be 'numeric' or 'decimal' - if (isset($field['field_sub_type'])) { - $field['type'] = $field['field_sub_type']; - return $this->mapNativeDatatype($field); + case 'smallint': + case 'integer': + case 'int64': + //these may be 'numeric' or 'decimal' + if (isset($field['field_sub_type'])) { + $field['type'] = $field['field_sub_type']; + return $this->mapNativeDatatype($field); + } + case 'bigint': + case 'quad': + $type[] = 'integer'; + if ($length == '1') { + $type[] = 'boolean'; + if (preg_match('/^(is|has)/', $field['name'])) { + $type = array_reverse($type); } - case 'bigint': - case 'quad': - $type[] = 'integer'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } + } + break; + case 'varchar': + $fixed = false; + case 'char': + case 'cstring': + $type[] = 'text'; + if ($length == '1') { + $type[] = 'boolean'; + if (preg_match('/^(is|has)/', $field['name'])) { + $type = array_reverse($type); } - break; - case 'varchar': - $fixed = false; - case 'char': - case 'cstring': - $type[] = 'text'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } - if ($fixed !== false) { - $fixed = true; - } - break; - case 'date': - $type[] = 'date'; - $length = null; - break; - case 'timestamp': - $type[] = 'timestamp'; - $length = null; - break; - case 'time': - $type[] = 'time'; - $length = null; - break; - case 'float': - case 'double': - case 'double precision': - case 'd_float': - $type[] = 'float'; - break; - case 'decimal': - case 'numeric': - $type[] = 'decimal'; - break; - case 'blob': - $type[] = ($field['field_sub_type'] == 'text') ? 'clob' : 'blob'; - $length = null; - break; - default: - throw new Doctrine_DataDict_Firebird_Exception('unknown database attribute type: '.$db_type); + } + if ($fixed !== false) { + $fixed = true; + } + break; + case 'date': + $type[] = 'date'; + $length = null; + break; + case 'timestamp': + $type[] = 'timestamp'; + $length = null; + break; + case 'time': + $type[] = 'time'; + $length = null; + break; + case 'float': + case 'double': + case 'double precision': + case 'd_float': + $type[] = 'float'; + break; + case 'decimal': + case 'numeric': + $type[] = 'decimal'; + break; + case 'blob': + $type[] = ($field['field_sub_type'] == 'text') ? 'clob' : 'blob'; + $length = null; + break; + default: + throw new Doctrine_DataDict_Firebird_Exception('unknown database attribute type: '.$db_type); } return array($type, $length, $unsigned, $fixed); diff --git a/lib/Doctrine/DataDict/Informix.php b/lib/Doctrine/DataDict/Informix.php index a19652d3a..1cf8e9ecb 100644 --- a/lib/Doctrine/DataDict/Informix.php +++ b/lib/Doctrine/DataDict/Informix.php @@ -55,52 +55,51 @@ class Doctrine_DataDict_Informix extends Doctrine_DataDict { */ public function getNativeDeclaration($field) { switch ($field['type']) { - case 'char': - case 'varchar': - case 'array': - case 'object': - case 'string': - if (empty($field['length']) && array_key_exists('default', $field)) { - $field['length'] = $this->conn->varchar_max_length; - } - - $length = (! empty($field['length'])) ? $field['length'] : false; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + case 'char': + case 'varchar': + case 'array': + case 'object': + case 'string': + if (empty($field['length']) && array_key_exists('default', $field)) { + $field['length'] = $this->conn->varchar_max_length; + } + + $length = (! empty($field['length'])) ? $field['length'] : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)') - : ($length ? 'VARCHAR('.$length.')' : 'NVARCHAR'); - case 'clob': - return 'TEXT'; - case 'blob': - return 'BLOB'; - case 'integer': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 1) { - return 'SMALLINT'; - } elseif ($length == 2) { - return 'SMALLINT'; - } elseif ($length == 3 || $length == 4) { - return 'INTEGER'; - } elseif ($length > 4) { - return 'DECIMAL(20)'; - } + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)') + : ($length ? 'VARCHAR('.$length.')' : 'NVARCHAR'); + case 'clob': + return 'TEXT'; + case 'blob': + return 'BLOB'; + case 'integer': + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 1) { + return 'SMALLINT'; + } elseif ($length == 2) { + return 'SMALLINT'; + } elseif ($length == 3 || $length == 4) { + return 'INTEGER'; + } elseif ($length > 4) { + return 'DECIMAL(20)'; } - return 'INT'; - case 'boolean': - return 'SMALLINT'; - case 'date': - return 'DATE'; - case 'time': - return 'DATETIME YEAR TO SECOND'; - case 'timestamp': - return 'DATETIME'; - case 'float': - return 'FLOAT'; - case 'decimal': - return 'DECIMAL'; + } + return 'INT'; + case 'boolean': + return 'SMALLINT'; + case 'date': + return 'DATE'; + case 'time': + return 'DATETIME YEAR TO SECOND'; + case 'timestamp': + return 'DATETIME'; + case 'float': + return 'FLOAT'; + case 'decimal': + return 'DECIMAL'; } return ''; } - } diff --git a/lib/Doctrine/DataDict/Informix/Exception.php b/lib/Doctrine/DataDict/Informix/Exception.php index a754fe812..001816298 100644 --- a/lib/Doctrine/DataDict/Informix/Exception.php +++ b/lib/Doctrine/DataDict/Informix/Exception.php @@ -22,12 +22,12 @@ Doctrine::autoload('Doctrine_DataDict_Informix_Exception'); /** * Doctrine_DataDict_Sqlite_Exception * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_DataDict_Informix_Exception extends Doctrine_DataDict_Exception { } diff --git a/lib/Doctrine/DataDict/Mssql.php b/lib/Doctrine/DataDict/Mssql.php index 1f33ef6d4..e79156351 100644 --- a/lib/Doctrine/DataDict/Mssql.php +++ b/lib/Doctrine/DataDict/Mssql.php @@ -57,51 +57,51 @@ class Doctrine_DataDict_Mssql extends Doctrine_DataDict { */ public function getNativeDeclaration($field) { switch ($field['type']) { - case 'array': - case 'object': - case 'text': - case 'char': - case 'varchar': - case 'string': - $length = !empty($field['length']) - ? $field['length'] : false; - - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + case 'array': + case 'object': + case 'text': + case 'char': + case 'varchar': + case 'string': + $length = !empty($field['length']) + ? $field['length'] : false; + + $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')') - : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); - case 'clob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 8000) { - return 'VARCHAR('.$length.')'; - } - } - return 'TEXT'; - case 'blob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 8000) { - return "VARBINARY($length)"; - } + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')') + : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); + case 'clob': + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 8000) { + return 'VARCHAR('.$length.')'; } - return 'IMAGE'; - case 'integer': - case 'enum': - return 'INT'; - case 'boolean': - return 'BIT'; - case 'date': - return 'CHAR(' . strlen('YYYY-MM-DD') . ')'; - case 'time': - return 'CHAR(' . strlen('HH:MM:SS') . ')'; - case 'timestamp': - return 'CHAR(' . strlen('YYYY-MM-DD HH:MM:SS') . ')'; - case 'float': - return 'FLOAT'; - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - return 'DECIMAL('.$length.','.$db->options['decimal_places'].')'; + } + return 'TEXT'; + case 'blob': + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 8000) { + return "VARBINARY($length)"; + } + } + return 'IMAGE'; + case 'integer': + case 'enum': + return 'INT'; + case 'boolean': + return 'BIT'; + case 'date': + return 'CHAR(' . strlen('YYYY-MM-DD') . ')'; + case 'time': + return 'CHAR(' . strlen('HH:MM:SS') . ')'; + case 'timestamp': + return 'CHAR(' . strlen('YYYY-MM-DD HH:MM:SS') . ')'; + case 'float': + return 'FLOAT'; + case 'decimal': + $length = !empty($field['length']) ? $field['length'] : 18; + return 'DECIMAL('.$length.','.$db->options['decimal_places'].')'; } return ''; } @@ -121,48 +121,48 @@ class Doctrine_DataDict_Mssql extends Doctrine_DataDict { // todo: unsigned handling seems to be missing $unsigned = $fixed = null; switch ($db_type) { - case 'bit': - $type[0] = 'boolean'; - break; - case 'int': - $type[0] = 'integer'; - break; - case 'datetime': - $type[0] = 'timestamp'; - break; - case 'float': - case 'real': - case 'numeric': - $type[0] = 'float'; - break; - case 'decimal': - case 'money': - $type[0] = 'decimal'; - break; - case 'text': - case 'varchar': - $fixed = false; - case 'char': - $type[0] = 'text'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^[is|has]/', $field['name'])) { - $type = array_reverse($type); - } - } elseif (strstr($db_type, 'text')) { - $type[] = 'clob'; + case 'bit': + $type[0] = 'boolean'; + break; + case 'int': + $type[0] = 'integer'; + break; + case 'datetime': + $type[0] = 'timestamp'; + break; + case 'float': + case 'real': + case 'numeric': + $type[0] = 'float'; + break; + case 'decimal': + case 'money': + $type[0] = 'decimal'; + break; + case 'text': + case 'varchar': + $fixed = false; + case 'char': + $type[0] = 'text'; + if ($length == '1') { + $type[] = 'boolean'; + if (preg_match('/^[is|has]/', $field['name'])) { + $type = array_reverse($type); } - if ($fixed !== false) { - $fixed = true; - } - break; - case 'image': - case 'varbinary': - $type[] = 'blob'; - $length = null; - break; - default: - throw new Doctrine_DataDict_Mssql_Exception('unknown database attribute type: '.$db_type); + } elseif (strstr($db_type, 'text')) { + $type[] = 'clob'; + } + if ($fixed !== false) { + $fixed = true; + } + break; + case 'image': + case 'varbinary': + $type[] = 'blob'; + $length = null; + break; + default: + throw new Doctrine_DataDict_Mssql_Exception('unknown database attribute type: '.$db_type); } return array($type, $length, $unsigned, $fixed); diff --git a/lib/Doctrine/DataDict/Mysql.php b/lib/Doctrine/DataDict/Mysql.php index 6fde93e2b..fa188ee48 100644 --- a/lib/Doctrine/DataDict/Mysql.php +++ b/lib/Doctrine/DataDict/Mysql.php @@ -133,82 +133,82 @@ class Doctrine_DataDict_Mysql extends Doctrine_DataDict { public function getNativeDeclaration($field) { switch ($field['type']) { - case 'char': - $length = (! empty($field['length'])) ? $field['length'] : false; + case 'char': + $length = (! empty($field['length'])) ? $field['length'] : false; - return $length ? 'CHAR('.$length.')' : 'CHAR(255)'; - case 'varchar': - case 'array': - case 'object': - case 'string': + return $length ? 'CHAR('.$length.')' : 'CHAR(255)'; + case 'varchar': + case 'array': + case 'object': + case 'string': - if ( ! isset($field['length'])) { - if(array_key_exists('default', $field)) { - $field['length'] = $this->conn->varchar_max_length; - } else { - $field['length'] = false; - } + if ( ! isset($field['length'])) { + if (array_key_exists('default', $field)) { + $field['length'] = $this->conn->varchar_max_length; + } else { + $field['length'] = false; } + } - $length = ($field['length'] < $this->conn->varchar_max_length) ? $field['length'] : false; - $fixed = (isset($field['fixed'])) ? $field['fixed'] : false; + $length = ($field['length'] < $this->conn->varchar_max_length) ? $field['length'] : false; + $fixed = (isset($field['fixed'])) ? $field['fixed'] : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)') - : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT'); - case 'clob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYTEXT'; - } elseif ($length <= 65532) { - return 'TEXT'; - } elseif ($length <= 16777215) { - return 'MEDIUMTEXT'; - } + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)') + : ($length ? 'VARCHAR(' . $length . ')' : 'TEXT'); + case 'clob': + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 255) { + return 'TINYTEXT'; + } elseif ($length <= 65532) { + return 'TEXT'; + } elseif ($length <= 16777215) { + return 'MEDIUMTEXT'; } - return 'LONGTEXT'; - case 'blob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYBLOB'; - } elseif ($length <= 65532) { - return 'BLOB'; - } elseif ($length <= 16777215) { - return 'MEDIUMBLOB'; - } + } + return 'LONGTEXT'; + case 'blob': + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 255) { + return 'TINYBLOB'; + } elseif ($length <= 65532) { + return 'BLOB'; + } elseif ($length <= 16777215) { + return 'MEDIUMBLOB'; } - return 'LONGBLOB'; - case 'integer': - case 'enum': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 1) { - return 'TINYINT'; - } elseif ($length == 2) { - return 'SMALLINT'; - } elseif ($length == 3) { - return 'MEDIUMINT'; - } elseif ($length == 4) { - return 'INT'; - } elseif ($length > 4) { - return 'BIGINT'; - } + } + return 'LONGBLOB'; + case 'integer': + case 'enum': + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 1) { + return 'TINYINT'; + } elseif ($length == 2) { + return 'SMALLINT'; + } elseif ($length == 3) { + return 'MEDIUMINT'; + } elseif ($length == 4) { + return 'INT'; + } elseif ($length > 4) { + return 'BIGINT'; } - return 'INT'; - case 'boolean': - return 'TINYINT(1)'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME'; - case 'timestamp': - return 'DATETIME'; - case 'float': - return 'DOUBLE'; - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - return 'DECIMAL(' . $length . ',' . 0 . ')'; //$this->dbh->options['decimal_places'] . ')'; + } + return 'INT'; + case 'boolean': + return 'TINYINT(1)'; + case 'date': + return 'DATE'; + case 'time': + return 'TIME'; + case 'timestamp': + return 'DATETIME'; + case 'float': + return 'DOUBLE'; + case 'decimal': + $length = !empty($field['length']) ? $field['length'] : 18; + return 'DECIMAL(' . $length . ',' . 0 . ')'; //$this->dbh->options['decimal_places'] . ')'; } return ''; } @@ -234,122 +234,122 @@ class Doctrine_DataDict_Mysql extends Doctrine_DataDict { $type = array(); $unsigned = $fixed = null; switch ($dbType) { - case 'tinyint': - $type[] = 'integer'; + case 'tinyint': + $type[] = 'integer'; + $type[] = 'boolean'; + if (preg_match('/^(is|has)/', $field['name'])) { + $type = array_reverse($type); + } + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 1; + break; + case 'smallint': + $type[] = 'integer'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 2; + break; + case 'mediumint': + $type[] = 'integer'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 3; + break; + case 'int': + case 'integer': + $type[] = 'integer'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 4; + break; + case 'bigint': + $type[] = 'integer'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 8; + break; + case 'tinytext': + case 'mediumtext': + case 'longtext': + case 'text': + case 'text': + case 'varchar': + $fixed = false; + case 'string': + case 'char': + $type[] = 'text'; + if ($length == '1') { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); } - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 1; - break; - case 'smallint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 2; - break; - case 'mediumint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 3; - break; - case 'int': - case 'integer': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 4; - break; - case 'bigint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 8; - break; - case 'tinytext': - case 'mediumtext': - case 'longtext': - case 'text': - case 'text': - case 'varchar': - $fixed = false; - case 'string': - case 'char': - $type[] = 'text'; - if ($length == '1') { + } elseif (strstr($dbType, 'text')) { + $type[] = 'clob'; + if ($decimal == 'binary') { + $type[] = 'blob'; + } + } + if ($fixed !== false) { + $fixed = true; + } + break; + case 'enum': + $type[] = 'text'; + preg_match_all('/\'.+\'/U', $field['type'], $matches); + $length = 0; + $fixed = false; + if (is_array($matches)) { + foreach ($matches[0] as $value) { + $length = max($length, strlen($value)-2); + } + if ($length == '1' && count($matches[0]) == 2) { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); } - } elseif (strstr($dbType, 'text')) { - $type[] = 'clob'; - if ($decimal == 'binary') { - $type[] = 'blob'; - } } - if ($fixed !== false) { - $fixed = true; - } - break; - case 'enum': - $type[] = 'text'; - preg_match_all('/\'.+\'/U', $field['type'], $matches); - $length = 0; - $fixed = false; - if (is_array($matches)) { - foreach ($matches[0] as $value) { - $length = max($length, strlen($value)-2); - } - if ($length == '1' && count($matches[0]) == 2) { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } - } - $type[] = 'integer'; - case 'set': - $fixed = false; - $type[] = 'text'; - $type[] = 'integer'; - break; - case 'date': - $type[] = 'date'; - $length = null; - break; - case 'datetime': - case 'timestamp': - $type[] = 'timestamp'; - $length = null; - break; - case 'time': - $type[] = 'time'; - $length = null; - break; - case 'float': - case 'double': - case 'real': - $type[] = 'float'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - break; - case 'unknown': - case 'decimal': - case 'numeric': - $type[] = 'decimal'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - break; - case 'tinyblob': - case 'mediumblob': - case 'longblob': - case 'blob': - $type[] = 'blob'; - $length = null; - break; - case 'year': - $type[] = 'integer'; - $type[] = 'date'; - $length = null; - break; - default: - throw new Doctrine_DataDict_Mysql_Exception('unknown database attribute type: '.$dbType); + } + $type[] = 'integer'; + case 'set': + $fixed = false; + $type[] = 'text'; + $type[] = 'integer'; + break; + case 'date': + $type[] = 'date'; + $length = null; + break; + case 'datetime': + case 'timestamp': + $type[] = 'timestamp'; + $length = null; + break; + case 'time': + $type[] = 'time'; + $length = null; + break; + case 'float': + case 'double': + case 'real': + $type[] = 'float'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + break; + case 'unknown': + case 'decimal': + case 'numeric': + $type[] = 'decimal'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + break; + case 'tinyblob': + case 'mediumblob': + case 'longblob': + case 'blob': + $type[] = 'blob'; + $length = null; + break; + case 'year': + $type[] = 'integer'; + $type[] = 'date'; + $length = null; + break; + default: + throw new Doctrine_DataDict_Mysql_Exception('unknown database attribute type: '.$dbType); } return array($type, $length, $unsigned, $fixed); diff --git a/lib/Doctrine/DataDict/Mysql/Exception.php b/lib/Doctrine/DataDict/Mysql/Exception.php index 4640dead4..31c97358b 100644 --- a/lib/Doctrine/DataDict/Mysql/Exception.php +++ b/lib/Doctrine/DataDict/Mysql/Exception.php @@ -22,12 +22,12 @@ Doctrine::autoload('Doctrine_DataDict_Exception'); /** * Doctrine_DataDict_Mysql_Exception * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_DataDict_Mysql_Exception extends Doctrine_DataDict_Exception { } diff --git a/lib/Doctrine/DataDict/Oracle.php b/lib/Doctrine/DataDict/Oracle.php index 073194940..5ed9f63ef 100644 --- a/lib/Doctrine/DataDict/Oracle.php +++ b/lib/Doctrine/DataDict/Oracle.php @@ -52,38 +52,38 @@ class Doctrine_DataDict_Oracle extends Doctrine_DataDict { */ public function getNativeDeclaration(array $field) { switch ($field['type']) { - case 'string': - case 'array': - case 'object': - case 'gzip': - case 'char': - case 'varchar': - $length = !empty($field['length']) - ? $field['length'] : 16777215; // TODO: $db->options['default_text_field_length']; + case 'string': + case 'array': + case 'object': + case 'gzip': + case 'char': + case 'varchar': + $length = !empty($field['length']) + ? $field['length'] : 16777215; // TODO: $db->options['default_text_field_length']; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; - - return $fixed ? 'CHAR('.$length.')' : 'VARCHAR2('.$length.')'; - case 'clob': - return 'CLOB'; - case 'blob': - return 'BLOB'; - case 'integer': - case 'enum': - if (!empty($field['length'])) { - return 'NUMBER('.$field['length'].')'; - } - return 'INT'; - case 'boolean': - return 'NUMBER(1)'; - case 'date': - case 'time': - case 'timestamp': - return 'DATE'; - case 'float': - return 'NUMBER'; - case 'decimal': - return 'NUMBER(*,'.$db->options['decimal_places'].')'; + $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + + return $fixed ? 'CHAR('.$length.')' : 'VARCHAR2('.$length.')'; + case 'clob': + return 'CLOB'; + case 'blob': + return 'BLOB'; + case 'integer': + case 'enum': + if (!empty($field['length'])) { + return 'NUMBER('.$field['length'].')'; + } + return 'INT'; + case 'boolean': + return 'NUMBER(1)'; + case 'date': + case 'time': + case 'timestamp': + return 'DATE'; + case 'float': + return 'NUMBER'; + case 'decimal': + return 'NUMBER(*,'.$db->options['decimal_places'].')'; } } /** @@ -101,9 +101,46 @@ class Doctrine_DataDict_Oracle extends Doctrine_DataDict { $length = $field['length']; } switch ($db_type) { - case 'integer': - case 'pls_integer': - case 'binary_integer': + case 'integer': + case 'pls_integer': + case 'binary_integer': + $type[] = 'integer'; + if ($length == '1') { + $type[] = 'boolean'; + if (preg_match('/^(is|has)/', $field['name'])) { + $type = array_reverse($type); + } + } + break; + case 'varchar': + case 'varchar2': + case 'nvarchar2': + $fixed = false; + case 'char': + case 'nchar': + $type[] = 'text'; + if ($length == '1') { + $type[] = 'boolean'; + if (preg_match('/^(is|has)/', $field['name'])) { + $type = array_reverse($type); + } + } + if ($fixed !== false) { + $fixed = true; + } + break; + case 'date': + case 'timestamp': + $type[] = 'timestamp'; + $length = null; + break; + case 'float': + $type[] = 'float'; + break; + case 'number': + if (!empty($field['scale'])) { + $type[] = 'decimal'; + } else { $type[] = 'integer'; if ($length == '1') { $type[] = 'boolean'; @@ -111,62 +148,25 @@ class Doctrine_DataDict_Oracle extends Doctrine_DataDict { $type = array_reverse($type); } } - break; - case 'varchar': - case 'varchar2': - case 'nvarchar2': - $fixed = false; - case 'char': - case 'nchar': - $type[] = 'text'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } - if ($fixed !== false) { - $fixed = true; - } - break; - case 'date': - case 'timestamp': - $type[] = 'timestamp'; - $length = null; - break; - case 'float': - $type[] = 'float'; - break; - case 'number': - if (!empty($field['scale'])) { - $type[] = 'decimal'; - } else { - $type[] = 'integer'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } - } - break; - case 'long': - $type[] = 'text'; - case 'clob': - case 'nclob': - $type[] = 'clob'; - break; - case 'blob': - case 'raw': - case 'long raw': - case 'bfile': - $type[] = 'blob'; - $length = null; + } break; - case 'rowid': - case 'urowid': - default: - throw new Doctrine_DataDict_Oracle_Exception('unknown database attribute type: '.$db_type); + case 'long': + $type[] = 'text'; + case 'clob': + case 'nclob': + $type[] = 'clob'; + break; + case 'blob': + case 'raw': + case 'long raw': + case 'bfile': + $type[] = 'blob'; + $length = null; + break; + case 'rowid': + case 'urowid': + default: + throw new Doctrine_DataDict_Oracle_Exception('unknown database attribute type: '.$db_type); } return array($type, $length, $unsigned, $fixed); diff --git a/lib/Doctrine/DataDict/Oracle/Exception.php b/lib/Doctrine/DataDict/Oracle/Exception.php index 551efac52..563ed5158 100644 --- a/lib/Doctrine/DataDict/Oracle/Exception.php +++ b/lib/Doctrine/DataDict/Oracle/Exception.php @@ -22,12 +22,12 @@ Doctrine::autoload('Doctrine_DataDict_Exception'); /** * Doctrine_DataDict_Oracle_Exception * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_DataDict_Oracle_Exception extends Doctrine_DataDict_Exception { } diff --git a/lib/Doctrine/DataDict/Pgsql.php b/lib/Doctrine/DataDict/Pgsql.php index 7fba0b180..c927c703b 100644 --- a/lib/Doctrine/DataDict/Pgsql.php +++ b/lib/Doctrine/DataDict/Pgsql.php @@ -357,60 +357,60 @@ class Doctrine_DataDict_Pgsql extends Doctrine_DataDict { */ public function getNativeDeclaration(array $field) { switch ($field['type']) { - case 'char': - case 'string': - case 'array': - case 'object': - case 'varchar': - $length = (isset($field['length']) && $field['length']) ? $field['length'] : null; - // TODO: $db->options['default_text_field_length']; + case 'char': + case 'string': + case 'array': + case 'object': + case 'varchar': + $length = (isset($field['length']) && $field['length']) ? $field['length'] : null; + // TODO: $db->options['default_text_field_length']; - $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; + $fixed = ((isset($field['fixed']) && $field['fixed']) || $field['type'] == 'char') ? true : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')') - : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')') + : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); - case 'clob': - return 'TEXT'; - case 'blob': - return 'BYTEA'; - case 'enum': - case 'integer': - if (!empty($field['autoincrement'])) { - if (!empty($field['length'])) { - $length = $field['length']; - if ($length > 4) { - return 'BIGSERIAL PRIMARY KEY'; - } - } - return 'SERIAL PRIMARY KEY'; - } + case 'clob': + return 'TEXT'; + case 'blob': + return 'BYTEA'; + case 'enum': + case 'integer': + if (!empty($field['autoincrement'])) { if (!empty($field['length'])) { $length = $field['length']; - if ($length <= 2) { - return 'SMALLINT'; - } elseif ($length == 3 || $length == 4) { - return 'INT'; - } elseif ($length > 4) { - return 'BIGINT'; + if ($length > 4) { + return 'BIGSERIAL PRIMARY KEY'; } } - return 'INT'; - case 'boolean': - return 'BOOLEAN'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME without time zone'; - case 'timestamp': - return 'TIMESTAMP without time zone'; - case 'float': - return 'FLOAT8'; - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - return 'NUMERIC(' . $length . ',' . $this->conn->getAttribute(Doctrine::ATTR_DECIMAL_PLACES) . ')'; - default: - throw new Doctrine_DataDict_Pgsql_Exception('Unknown field type '. $field['type']); + return 'SERIAL PRIMARY KEY'; + } + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 2) { + return 'SMALLINT'; + } elseif ($length == 3 || $length == 4) { + return 'INT'; + } elseif ($length > 4) { + return 'BIGINT'; + } + } + return 'INT'; + case 'boolean': + return 'BOOLEAN'; + case 'date': + return 'DATE'; + case 'time': + return 'TIME without time zone'; + case 'timestamp': + return 'TIMESTAMP without time zone'; + case 'float': + return 'FLOAT8'; + case 'decimal': + $length = !empty($field['length']) ? $field['length'] : 18; + return 'NUMERIC(' . $length . ',' . $this->conn->getAttribute(Doctrine::ATTR_DECIMAL_PLACES) . ')'; + default: + throw new Doctrine_DataDict_Pgsql_Exception('Unknown field type '. $field['type']); } } /** @@ -432,102 +432,102 @@ class Doctrine_DataDict_Pgsql extends Doctrine_DataDict { $type = array(); $unsigned = $fixed = null; switch (strtolower($field['type'])) { - case 'smallint': - case 'int2': - $type[] = 'integer'; - $unsigned = false; - $length = 2; - if ($length == '2') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } - break; - case 'int': - case 'int4': - case 'integer': - case 'serial': - case 'serial4': - $type[] = 'integer'; - $unsigned = false; - $length = 4; - break; - case 'bigint': - case 'int8': - case 'bigserial': - case 'serial8': - $type[] = 'integer'; - $unsigned = false; - $length = 8; - break; - case 'bool': - case 'boolean': + case 'smallint': + case 'int2': + $type[] = 'integer'; + $unsigned = false; + $length = 2; + if ($length == '2') { $type[] = 'boolean'; - $length = 1; - break; - case 'text': - case 'varchar': - $fixed = false; - case 'unknown': - case 'char': - case 'bpchar': - $type[] = 'text'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } elseif (strstr($db_type, 'text')) { - $type[] = 'clob'; + if (preg_match('/^(is|has)/', $field['name'])) { + $type = array_reverse($type); } - if ($fixed !== false) { - $fixed = true; + } + break; + case 'int': + case 'int4': + case 'integer': + case 'serial': + case 'serial4': + $type[] = 'integer'; + $unsigned = false; + $length = 4; + break; + case 'bigint': + case 'int8': + case 'bigserial': + case 'serial8': + $type[] = 'integer'; + $unsigned = false; + $length = 8; + break; + case 'bool': + case 'boolean': + $type[] = 'boolean'; + $length = 1; + break; + case 'text': + case 'varchar': + $fixed = false; + case 'unknown': + case 'char': + case 'bpchar': + $type[] = 'text'; + if ($length == '1') { + $type[] = 'boolean'; + if (preg_match('/^(is|has)/', $field['name'])) { + $type = array_reverse($type); } - break; - case 'date': - $type[] = 'date'; - $length = null; - break; - case 'datetime': - case 'timestamp': - $type[] = 'timestamp'; - $length = null; - break; - case 'time': - $type[] = 'time'; - $length = null; - break; - case 'float': - case 'double': - case 'real': - $type[] = 'float'; - break; - case 'decimal': - case 'money': - case 'numeric': - $type[] = 'decimal'; - break; - case 'tinyblob': - case 'mediumblob': - case 'longblob': - case 'blob': - case 'bytea': - $type[] = 'blob'; - $length = null; - break; - case 'oid': - $type[] = 'blob'; + } elseif (strstr($db_type, 'text')) { $type[] = 'clob'; - $length = null; - break; - case 'year': - $type[] = 'integer'; - $type[] = 'date'; - $length = null; - break; - default: - throw new Doctrine_DataDict_Pgsql_Exception('unknown database attribute type: '.$db_type); + } + if ($fixed !== false) { + $fixed = true; + } + break; + case 'date': + $type[] = 'date'; + $length = null; + break; + case 'datetime': + case 'timestamp': + $type[] = 'timestamp'; + $length = null; + break; + case 'time': + $type[] = 'time'; + $length = null; + break; + case 'float': + case 'double': + case 'real': + $type[] = 'float'; + break; + case 'decimal': + case 'money': + case 'numeric': + $type[] = 'decimal'; + break; + case 'tinyblob': + case 'mediumblob': + case 'longblob': + case 'blob': + case 'bytea': + $type[] = 'blob'; + $length = null; + break; + case 'oid': + $type[] = 'blob'; + $type[] = 'clob'; + $length = null; + break; + case 'year': + $type[] = 'integer'; + $type[] = 'date'; + $length = null; + break; + default: + throw new Doctrine_DataDict_Pgsql_Exception('unknown database attribute type: '.$db_type); } return array($type, $length, $unsigned, $fixed); @@ -561,7 +561,7 @@ class Doctrine_DataDict_Pgsql extends Doctrine_DataDict { } */ - if( ! empty($field['autoincrement'])) { + if ( ! empty($field['autoincrement'])) { $name = $this->conn->quoteIdentifier($name, true); return $name.' '.$this->getNativeDeclaration($field); } diff --git a/lib/Doctrine/DataDict/Sqlite.php b/lib/Doctrine/DataDict/Sqlite.php index 1380379db..068983f64 100644 --- a/lib/Doctrine/DataDict/Sqlite.php +++ b/lib/Doctrine/DataDict/Sqlite.php @@ -55,60 +55,60 @@ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict { */ public function getNativeDeclaration(array $field) { switch ($field['type']) { - case 'text': - case 'object': - case 'array': - case 'string': - case 'char': - case 'gzip': - case 'varchar': - $length = (isset($field['length']) && $field['length']) ? $field['length'] : null; + case 'text': + case 'object': + case 'array': + case 'string': + case 'char': + case 'gzip': + 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']) || $field['type'] == 'char') ? true : false; - return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$this->conn->getAttribute(Doctrine::ATTR_DEFAULT_TEXTFLD_LENGTH).')') - : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); - case 'clob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYTEXT'; - } elseif ($length <= 65535) { - return 'TEXT'; - } elseif ($length <= 16777215) { - return 'MEDIUMTEXT'; - } + return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$this->conn->getAttribute(Doctrine::ATTR_DEFAULT_TEXTFLD_LENGTH).')') + : ($length ? 'VARCHAR('.$length.')' : 'TEXT'); + case 'clob': + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 255) { + return 'TINYTEXT'; + } elseif ($length <= 65535) { + return 'TEXT'; + } elseif ($length <= 16777215) { + return 'MEDIUMTEXT'; } - return 'LONGTEXT'; - case 'blob': - if (!empty($field['length'])) { - $length = $field['length']; - if ($length <= 255) { - return 'TINYBLOB'; - } elseif ($length <= 65535) { - return 'BLOB'; - } elseif ($length <= 16777215) { - return 'MEDIUMBLOB'; - } + } + return 'LONGTEXT'; + case 'blob': + if (!empty($field['length'])) { + $length = $field['length']; + if ($length <= 255) { + return 'TINYBLOB'; + } elseif ($length <= 65535) { + return 'BLOB'; + } elseif ($length <= 16777215) { + return 'MEDIUMBLOB'; } - return 'LONGBLOB'; - case 'enum': - case 'integer': - case 'boolean': - return 'INTEGER'; - case 'date': - return 'DATE'; - case 'time': - return 'TIME'; - case 'timestamp': - return 'DATETIME'; - case 'float': - case 'double': - return 'DOUBLE';//($db->options['fixed_float'] ? '('. - //($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : ''); - case 'decimal': - $length = !empty($field['length']) ? $field['length'] : 18; - return 'DECIMAL('.$length.','.$db->options['decimal_places'].')'; + } + return 'LONGBLOB'; + case 'enum': + case 'integer': + case 'boolean': + return 'INTEGER'; + case 'date': + return 'DATE'; + case 'time': + return 'TIME'; + case 'timestamp': + return 'DATETIME'; + case 'float': + case 'double': + return 'DOUBLE';//($db->options['fixed_float'] ? '('. + //($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : ''); + case 'decimal': + $length = !empty($field['length']) ? $field['length'] : 18; + return 'DECIMAL('.$length.','.$db->options['decimal_places'].')'; } throw new Doctrine_DataDict_Sqlite_Exception('Unknown datatype ' . $field['type']); } @@ -125,101 +125,101 @@ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict { $fixed = null; $type = array(); switch ($dbType) { - case 'boolean': - $type[] = 'boolean'; - break; - case 'tinyint': - $type[] = 'integer'; + case 'boolean': + $type[] = 'boolean'; + break; + case 'tinyint': + $type[] = 'integer'; + $type[] = 'boolean'; + if (preg_match('/^(is|has)/', $field['name'])) { + $type = array_reverse($type); + } + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 1; + break; + case 'smallint': + $type[] = 'integer'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 2; + break; + case 'mediumint': + $type[] = 'integer'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 3; + break; + case 'int': + case 'integer': + case 'serial': + $type[] = 'integer'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 4; + break; + case 'bigint': + case 'bigserial': + $type[] = 'integer'; + $unsigned = preg_match('/ unsigned/i', $field['type']); + $length = 8; + break; + case 'clob': + case 'tinytext': + case 'mediumtext': + case 'longtext': + case 'text': + case 'varchar': + case 'varchar2': + $fixed = false; + case 'char': + $type[] = 'text'; + if ($length == '1') { $type[] = 'boolean'; if (preg_match('/^(is|has)/', $field['name'])) { $type = array_reverse($type); } - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 1; - break; - case 'smallint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 2; - break; - case 'mediumint': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 3; - break; - case 'int': - case 'integer': - case 'serial': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 4; - break; - case 'bigint': - case 'bigserial': - $type[] = 'integer'; - $unsigned = preg_match('/ unsigned/i', $field['type']); - $length = 8; - break; - case 'clob': - case 'tinytext': - case 'mediumtext': - case 'longtext': - case 'text': - case 'varchar': - case 'varchar2': - $fixed = false; - case 'char': - $type[] = 'text'; - if ($length == '1') { - $type[] = 'boolean'; - if (preg_match('/^(is|has)/', $field['name'])) { - $type = array_reverse($type); - } - } elseif (strstr($dbType, 'text')) { - $type[] = 'clob'; - } - if ($fixed !== false) { - $fixed = true; - } + } elseif (strstr($dbType, 'text')) { + $type[] = 'clob'; + } + if ($fixed !== false) { + $fixed = true; + } break; - case 'date': - $type[] = 'date'; - $length = null; + case 'date': + $type[] = 'date'; + $length = null; break; - case 'datetime': - case 'timestamp': - $type[] = 'timestamp'; - $length = null; + case 'datetime': + case 'timestamp': + $type[] = 'timestamp'; + $length = null; break; - case 'time': - $type[] = 'time'; - $length = null; + case 'time': + $type[] = 'time'; + $length = null; break; - case 'float': - case 'double': - case 'real': - $type[] = 'float'; - $length = null; + case 'float': + case 'double': + case 'real': + $type[] = 'float'; + $length = null; break; - case 'decimal': - case 'numeric': - $type[] = 'decimal'; - $length = null; + case 'decimal': + case 'numeric': + $type[] = 'decimal'; + $length = null; break; - case 'tinyblob': - case 'mediumblob': - case 'longblob': - case 'blob': - $type[] = 'blob'; - $length = null; + case 'tinyblob': + case 'mediumblob': + case 'longblob': + case 'blob': + $type[] = 'blob'; + $length = null; break; - case 'year': - $type[] = 'integer'; - $type[] = 'date'; - $length = null; - break; - default: - throw new Doctrine_DataDict_Sqlite_Exception('unknown database attribute type: '.$dbType); + case 'year': + $type[] = 'integer'; + $type[] = 'date'; + $length = null; + break; + default: + throw new Doctrine_DataDict_Sqlite_Exception('unknown database attribute type: '.$dbType); } return array($type, $length, $unsigned, $fixed); @@ -254,10 +254,10 @@ class Doctrine_DataDict_Sqlite extends Doctrine_DataDict { $default = $autoinc = ''; $type = $this->getNativeDeclaration($field); - if(isset($field['autoincrement']) && $field['autoincrement']) { + if (isset($field['autoincrement']) && $field['autoincrement']) { $autoinc = ' PRIMARY KEY AUTOINCREMENT'; $type = 'INTEGER'; - } elseif(array_key_exists('default', $field)) { + } elseif (array_key_exists('default', $field)) { if ($field['default'] === '') { $field['default'] = empty($field['notnull']) ? null : 0; } diff --git a/lib/Doctrine/Db.php b/lib/Doctrine/Db.php index 14d4cb106..ce59b0171 100644 --- a/lib/Doctrine/Db.php +++ b/lib/Doctrine/Db.php @@ -69,7 +69,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte 'password' => null, ); /** - * @var Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener + * @var Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener * listener for listening events */ protected $listener; @@ -84,7 +84,6 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte 'sqlite2' => 'sqlite', 'sqlite3' => 'sqlite'); - /** * constructor * @@ -93,7 +92,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte * @param string $pass database password */ public function __construct($dsn, $user, $pass) { - if( ! isset($user)) { + if ( ! isset($user)) { $a = self::parseDSN($dsn); extract($a); @@ -104,7 +103,6 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte $this->listener = new Doctrine_Db_EventListener(); } - public function nextQuerySequence() { return ++$this->querySequence; } @@ -121,9 +119,9 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte return $this->dbh; } public function getOption($name) { - if( ! array_key_exists($name, $this->options)) + if ( ! array_key_exists($name, $this->options)) { throw new Doctrine_Db_Exception('Unknown option ' . $name); - + } return $this->options[$name]; } /** @@ -133,16 +131,16 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte * @return Doctrine_Db */ public function addListener($listener, $name = null) { - if( ! ($this->listener instanceof Doctrine_Db_EventListener_Chain)) + if ( ! ($this->listener instanceof Doctrine_Db_EventListener_Chain)) { $this->listener = new Doctrine_Db_EventListener_Chain(); - + } $this->listener->add($listener, $name); - + return $this; } /** * getListener - * + * * @return Doctrine_Db_EventListener_Interface|Doctrine_Overloadable */ public function getListener() { @@ -155,10 +153,11 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte * @return Doctrine_Db */ public function setListener($listener) { - if( ! ($listener instanceof Doctrine_Db_EventListener_Interface) && - ! ($listener instanceof Doctrine_Overloadable)) + if ( ! ($listener instanceof Doctrine_Db_EventListener_Interface) + && ! ($listener instanceof Doctrine_Overloadable) + ) { throw new Doctrine_Db_Exception("Couldn't set eventlistener for database handler. EventListeners should implement either Doctrine_Db_EventListener_Interface or Doctrine_Overloadable"); - + } $this->listener = $listener; return $this; @@ -171,7 +170,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte * @return boolean */ public function connect() { - if($this->isConnected) + if ($this->isConnected) return false; $this->dbh = new PDO($this->options['dsn'], $this->options['username'], $this->options['password']); @@ -194,77 +193,78 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte } /** * driverName - * converts a driver name like (oracle) to appropriate PDO + * converts a driver name like (oracle) to appropriate PDO * driver name (oci8 in the case of oracle) * * @param string $name * @return string */ public static function driverName($name) { - if(isset(self::$driverMap[$name])) + if (isset(self::$driverMap[$name])) { return self::$driverMap[$name]; - + } return $name; } /** * parseDSN * - * @param string $dsn - * @return array Parsed contents of DSN + * @param string $dsn + * @return array Parsed contents of DSN */ function parseDSN($dsn) { // silence any warnings - $parts = @parse_url($dsn); - + $parts = @parse_url($dsn); + $names = array('scheme', 'host', 'port', 'user', 'pass', 'path', 'query', 'fragment'); - - foreach($names as $name) { - if( ! isset($parts[$name])) + + foreach ($names as $name) { + if ( ! isset($parts[$name])) { $parts[$name] = null; + } } - if(count($parts) == 0 || ! isset($parts['scheme'])) - throw new Doctrine_Db_Exception('Empty data source name'); - + if (count($parts) == 0 || ! isset($parts['scheme'])) { + throw new Doctrine_Db_Exception('Empty data source name'); + } $drivers = self::getAvailableDrivers(); $parts['scheme'] = self::driverName($parts['scheme']); - if( ! in_array($parts['scheme'], $drivers)) + if ( ! in_array($parts['scheme'], $drivers)) { throw new Doctrine_Db_Exception('Driver '.$parts['scheme'].' not availible or extension not loaded'); - - switch($parts['scheme']) { - case 'sqlite': - if(isset($parts['host']) && $parts['host'] == ':memory') { - $parts['database'] = ':memory:'; - $parts['dsn'] = 'sqlite::memory:'; - } + } + switch ($parts['scheme']) { + case 'sqlite': + if (isset($parts['host']) && $parts['host'] == ':memory') { + $parts['database'] = ':memory:'; + $parts['dsn'] = 'sqlite::memory:'; + } break; - case 'mysql': - case 'informix': - case 'oci8': - case 'mssql': - case 'firebird': - case 'pgsql': - case 'odbc': - if( ! isset($parts['path']) || $parts['path'] == '/') - throw new Doctrine_Db_Exception('No database availible in data source name'); - - if(isset($parts['path'])) - $parts['database'] = substr($parts['path'], 1); - - if( ! isset($parts['host'])) - throw new Doctrine_Db_Exception('No hostname set in data source name'); - - $parts['dsn'] = $parts["scheme"].":host=".$parts["host"].";dbname=".$parts["database"]; + case 'mysql': + case 'informix': + case 'oci8': + case 'mssql': + case 'firebird': + case 'pgsql': + case 'odbc': + if ( ! isset($parts['path']) || $parts['path'] == '/') { + throw new Doctrine_Db_Exception('No database availible in data source name'); + } + if (isset($parts['path'])) { + $parts['database'] = substr($parts['path'], 1); + } + if ( ! isset($parts['host'])) { + throw new Doctrine_Db_Exception('No hostname set in data source name'); + } + $parts['dsn'] = $parts["scheme"].":host=".$parts["host"].";dbname=".$parts["database"]; break; - default: - throw new Doctrine_Db_Exception('Unknown driver '.$parts['scheme']); - } + default: + throw new Doctrine_Db_Exception('Unknown driver '.$parts['scheme']); + } - return $parts; - } + return $parts; + } /** * clear * clears all instances from the memory @@ -322,16 +322,16 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte */ public function query($statement, array $params = array()) { $this->connect(); - + $event = new Doctrine_Db_Event($this, Doctrine_Db_Event::QUERY, $statement); $this->listener->onPreQuery($event); - if( ! empty($params)) + if ( ! empty($params)) { $stmt = $this->dbh->query($statement)->execute($params); - else + } else { $stmt = $this->dbh->query($statement); - + } $this->listener->onQuery($event); $this->querySequence++; @@ -361,7 +361,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte $this->connect(); $args = func_get_args(); - + $event = new Doctrine_Db_Event($this, Doctrine_Db_Event::EXEC, $statement); $this->listener->onPreExec($event); @@ -396,7 +396,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte $return = $this->dbh->beginTransaction(); $this->listener->onBeginTransaction($event); - + return $return; } /** @@ -428,7 +428,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte $this->listener->onPreRollback($event); $this->dbh->rollBack(); - + $this->listener->onRollback($event); } /** @@ -440,7 +440,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte */ public function getAttribute($attribute) { $this->connect(); - + return $this->dbh->getAttribute($attribute); } /** @@ -459,7 +459,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte */ public function setAttribute($attribute, $value) { $this->connect(); - + $this->dbh->setAttribute($attribute, $value); } /** @@ -468,7 +468,7 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte * @return ArrayIterator */ public function getIterator() { - if($this->listener instanceof Doctrine_Db_Profiler) + if ($this->listener instanceof Doctrine_Db_Profiler) return $this->listener; } /** @@ -479,5 +479,5 @@ class Doctrine_Db implements Countable, IteratorAggregate, Doctrine_Adapter_Inte */ public function count() { return $this->querySequence; - } + } } diff --git a/lib/Doctrine/Db/Event.php b/lib/Doctrine/Db/Event.php index d331f1b07..3f615b0bb 100644 --- a/lib/Doctrine/Db/Event.php +++ b/lib/Doctrine/Db/Event.php @@ -40,7 +40,7 @@ class Doctrine_Db_Event { protected $invoker; protected $query; - + protected $type; protected $startedMicrotime; @@ -56,7 +56,7 @@ class Doctrine_Db_Event { return $this->query; } public function getType() { - return $this->type; + return $this->type; } public function start() { @@ -78,9 +78,9 @@ class Doctrine_Db_Event { * @return mixed */ public function getElapsedSecs() { - if (is_null($this->endedMicrotime)) + if (is_null($this->endedMicrotime)) { return false; - + } return ($this->endedMicrotime - $this->startedMicrotime); } diff --git a/lib/Doctrine/Db/EventListener/Chain.php b/lib/Doctrine/Db/EventListener/Chain.php index 466fb4297..c0fea9d44 100644 --- a/lib/Doctrine/Db/EventListener/Chain.php +++ b/lib/Doctrine/Db/EventListener/Chain.php @@ -23,116 +23,119 @@ Doctrine::autoload('Doctrine_Access'); /** * Doctrine_Db_EventListener * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Db_EventListener_Chain extends Doctrine_Access implements Doctrine_Db_EventListener_Interface { private $listeners = array(); public function add($listener, $name = null) { - if( ! ($listener instanceof Doctrine_Db_EventListener_Interface) && - ! ($listener instanceof Doctrine_Overloadable)) + if ( ! ($listener instanceof Doctrine_Db_EventListener_Interface) + && ! ($listener instanceof Doctrine_Overloadable) + ) { throw new Doctrine_Db_Exception("Couldn't add eventlistener. EventListeners should implement either Doctrine_Db_EventListener_Interface or Doctrine_Overloadable"); - - if($name === null) + } + if ($name === null) { $this->listeners[] = $listener; - else + } else { $this->listeners[$name] = $listener; + } } public function get($name) { - if( ! isset($this->listeners[$name])) + if ( ! isset($this->listeners[$name])) { throw new Doctrine_Db_Exception("Unknown listener $name"); - + } return $this->listeners[$name]; } public function set($name, $listener) { - if( ! ($listener instanceof Doctrine_Db_EventListener_Interface) && - ! ($listener instanceof Doctrine_Overloadable)) + if ( ! ($listener instanceof Doctrine_Db_EventListener_Interface) + && ! ($listener instanceof Doctrine_Overloadable) + ) { throw new Doctrine_Db_Exception("Couldn't set eventlistener. EventListeners should implement either Doctrine_Db_EventListener_Interface or Doctrine_Overloadable"); - + } $this->listeners[$name] = $listener; } public function onQuery(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onQuery($event); } } public function onPreQuery(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPreQuery($event); } } public function onPreExec(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPreExec($event); } } public function onExec(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onExec($event); } } public function onPrePrepare(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPrePrepare($event); } } public function onPrepare(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPrepare($event); } } public function onPreCommit(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPreCommit($event); } } public function onCommit(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onCommit($event); } } public function onPreRollBack(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPreRollBack($event); } } public function onRollBack(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onRollBack($event); } } public function onPreBeginTransaction(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPreBeginTransaction($event); } } public function onBeginTransaction(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onBeginTransaction($event); } } public function onPreExecute(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPreExecute($event); } } public function onExecute(Doctrine_Db_Event $event) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onExecute($event); } } diff --git a/lib/Doctrine/Db/Exception.php b/lib/Doctrine/Db/Exception.php index ffa352c08..e7f84bfd4 100644 --- a/lib/Doctrine/Db/Exception.php +++ b/lib/Doctrine/Db/Exception.php @@ -30,6 +30,6 @@ * @since 1.0 * @version $Revision$ */ -class Doctrine_Db_Exception extends Doctrine_Exception { +class Doctrine_Db_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/Db/Mock.php b/lib/Doctrine/Db/Mock.php index 7213a19e2..6a0b499bc 100644 --- a/lib/Doctrine/Db/Mock.php +++ b/lib/Doctrine/Db/Mock.php @@ -20,15 +20,15 @@ */ Doctrine::autoload('Doctrine_Db'); /** - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Konsta Vesterinen + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Konsta Vesterinen * @author Lukas Smith (PEAR MDB2 library) - * @version $Revision$ - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - */ + * @version $Revision$ + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + */ class Doctrine_Db_Mock extends Doctrine_Db { protected static $errorCodeMap = array( 1004 => Doctrine::ERR_CANNOT_CREATE, @@ -59,10 +59,11 @@ class Doctrine_Db_Mock extends Doctrine_Db { { return true; } - + public function getAttribute($attribute) { - if($attribute == PDO::ATTR_DRIVER_NAME) - return 'mock'; + if ($attribute == PDO::ATTR_DRIVER_NAME) { + return 'mock'; + } } } diff --git a/lib/Doctrine/Db/Profiler.php b/lib/Doctrine/Db/Profiler.php index 69a5c95b9..d81a68224 100644 --- a/lib/Doctrine/Db/Profiler.php +++ b/lib/Doctrine/Db/Profiler.php @@ -22,14 +22,14 @@ Doctrine::autoload('Doctrine_Overloadable'); /** * Doctrine_Db_Profiler * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Db_Profiler implements Doctrine_Overloadable { /** * @param array $listeners an array containing all availible listeners @@ -58,25 +58,25 @@ class Doctrine_Db_Profiler implements Doctrine_Overloadable { */ public function __call($m, $a) { // first argument should be an instance of Doctrine_Db_Event - if( ! ($a[0] instanceof Doctrine_Db_Event)) + if ( ! ($a[0] instanceof Doctrine_Db_Event)) { throw new Doctrine_Db_Profiler_Exception("Couldn't listen event. Event should be an instance of Doctrine_Db_Event."); + } // event methods should start with 'on' - if(substr($m, 0, 2) !== 'on') + if (substr($m, 0, 2) !== 'on') { throw new Doctrine_Db_Profiler_Exception("Couldn't invoke listener $m."); - - if(substr($m, 2, 3) === 'Pre' && in_array(strtolower(substr($m, 3)), $this->listeners)) { + } + if (substr($m, 2, 3) === 'Pre' && in_array(strtolower(substr($m, 3)), $this->listeners)) { // pre-event listener found $a[0]->start(); } else { // after-event listener found $a[0]->end(); } - + $this->events[] = $a[0]; } - /** * Get the Doctrine_Db_Event object for the last query that was run, regardless if it has * ended or not. If the event has not ended, it's end time will be Null. diff --git a/lib/Doctrine/Db/Profiler/Query.php b/lib/Doctrine/Db/Profiler/Query.php index 2c3be4d88..52ac469b9 100644 --- a/lib/Doctrine/Db/Profiler/Query.php +++ b/lib/Doctrine/Db/Profiler/Query.php @@ -21,14 +21,14 @@ /** * Doctrine_Db_Profiler_Query * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Db_Profiler_Query { /** * @var string SQL query string or user comment, set by $query argument in constructor. @@ -39,7 +39,6 @@ class Doctrine_Db_Profiler_Query { */ protected $queryType = 0; - protected $prepareTime; /** @@ -54,7 +53,6 @@ class Doctrine_Db_Profiler_Query { */ protected $endedMicrotime; - /** * Class constructor. A query is about to be started, save the query text ($query) and its * type (one of the Zend_Db_Profiler::* constants). @@ -64,14 +62,14 @@ class Doctrine_Db_Profiler_Query { */ public function __construct($query, $prepareTime = null) { $this->query = $query; - if($prepareTime !== null) { + if ($prepareTime !== null) { $this->prepareTime = $prepareTime; } else { $this->startedMicrotime = microtime(true); } } public function start() { - $this->startedMicrotime = microtime(true); + $this->startedMicrotime = microtime(true); } /** * The query has ended. Record the time so that the elapsed time can be determined later. @@ -96,7 +94,6 @@ class Doctrine_Db_Profiler_Query { return ($this->endedMicrotime != null); } - /** * Get the original SQL text of the query. * @@ -106,7 +103,6 @@ class Doctrine_Db_Profiler_Query { return $this->query; } - /** * Get the type of this query (one of the Zend_Db_Profiler::* constants) * @@ -129,4 +125,3 @@ class Doctrine_Db_Profiler_Query { return ($this->prepareTime + ($this->endedMicrotime - $this->startedMicrotime)); } } - diff --git a/lib/Doctrine/Db/Statement.php b/lib/Doctrine/Db/Statement.php index fe8311854..3e11b000b 100644 --- a/lib/Doctrine/Db/Statement.php +++ b/lib/Doctrine/Db/Statement.php @@ -1,75 +1,73 @@ -. - */ -/** - * Doctrine_Db_Statement - * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ -class Doctrine_Db_Statement extends PDOStatement { - protected $dbh; - - protected $querySequence; - - protected $baseSequence; - - protected $executed = false; - - protected function __construct($dbh) { - $this->dbh = $dbh; - $this->baseSequence = $this->querySequence = $this->dbh->getQuerySequence(); - } - - public function getQuerySequence() { - return $this->querySequence; - } - public function getBaseSequence() { - return $this->baseSequence; - } - public function getQuery() { - return $this->queryString; - } - public function isExecuted($executed = null) { - if($executed === null) - return $this->executed; - - $this->executed = (bool) $executed; - } - - public function execute(array $params = null) { - $event = new Doctrine_Db_Event($this, Doctrine_Db_Event::EXECUTE, $this->queryString); - - $this->dbh->getListener()->onPreExecute($event); - - $ret = parent::execute($params); - - $this->dbh->getListener()->onExecute($event); - - - - return $this; - } -} +. + */ +/** + * Doctrine_Db_Statement + * + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ +class Doctrine_Db_Statement extends PDOStatement { + protected $dbh; + + protected $querySequence; + + protected $baseSequence; + + protected $executed = false; + + protected function __construct($dbh) { + $this->dbh = $dbh; + $this->baseSequence = $this->querySequence = $this->dbh->getQuerySequence(); + } + + public function getQuerySequence() { + return $this->querySequence; + } + public function getBaseSequence() { + return $this->baseSequence; + } + public function getQuery() { + return $this->queryString; + } + public function isExecuted($executed = null) { + if ($executed === null) + return $this->executed; + + $this->executed = (bool) $executed; + } + + public function execute(array $params = null) { + $event = new Doctrine_Db_Event($this, Doctrine_Db_Event::EXECUTE, $this->queryString); + + $this->dbh->getListener()->onPreExecute($event); + + $ret = parent::execute($params); + + $this->dbh->getListener()->onExecute($event); + + return $this; + } +} diff --git a/lib/Doctrine/EventListener.php b/lib/Doctrine/EventListener.php index a3de65d06..d0afbc47b 100644 --- a/lib/Doctrine/EventListener.php +++ b/lib/Doctrine/EventListener.php @@ -24,14 +24,14 @@ Doctrine::autoload('Doctrine_EventListener_Interface'); * the empty methods allow child classes to only implement the methods they need to implement * * - * @author Konsta Vesterinen - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_EventListener implements Doctrine_EventListener_Interface { public function onLoad(Doctrine_Record $record) { } @@ -79,7 +79,7 @@ class Doctrine_EventListener implements Doctrine_EventListener_Interface { public function onTransactionBegin(Doctrine_Connection $connection) { } public function onPreTransactionBegin(Doctrine_Connection $connection) { } - + public function onCollectionDelete(Doctrine_Collection $collection) { } public function onPreCollectionDelete(Doctrine_Collection $collection) { } } diff --git a/lib/Doctrine/EventListener/Chain.php b/lib/Doctrine/EventListener/Chain.php index beb4fabbb..1888d7202 100644 --- a/lib/Doctrine/EventListener/Chain.php +++ b/lib/Doctrine/EventListener/Chain.php @@ -22,17 +22,17 @@ Doctrine::autoload('Doctrine_Access'); /** * Doctrine_EventListener_Chain - * this class represents a chain of different listeners, + * this class represents a chain of different listeners, * useful for having multiple listeners listening the events at the same time * - * @author Konsta Vesterinen - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_EventListener_Interface { /** * @var array $listeners an array containing all listeners @@ -55,14 +55,14 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @return mixed */ public function get($key) { - if( ! isset($this->listeners[$key])) + if ( ! isset($this->listeners[$key])) { return null; - + } return $this->listeners[$key]; } /** * set - * + * * @param mixed $key * @param Doctrine_EventListener $listener * @return void @@ -77,8 +77,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onLoad(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onLoad(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onLoad($record); } } @@ -90,8 +90,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onPreLoad(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onPreLoad(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onPreLoad($record); } } @@ -102,8 +102,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onSleep(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onSleep(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onSleep($record); } } @@ -114,8 +114,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onWakeUp(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onWakeUp(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onWakeUp($record); } } @@ -126,8 +126,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onUpdate(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onUpdate(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onUpdate($record); } } @@ -138,8 +138,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onPreUpdate(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onPreUpdate(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onPreUpdate($record); } } @@ -150,8 +150,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onCreate(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onCreate(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onCreate($record); } } @@ -163,8 +163,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onPreCreate(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onPreCreate(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onPreCreate($record); } } @@ -175,8 +175,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onSave(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onSave(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onSave($record); } } @@ -187,8 +187,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onPreSave(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onPreSave(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onPreSave($record); } } @@ -202,7 +202,7 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @return mixed */ public function onGetProperty(Doctrine_Record $record, $property, $value) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $value = $listener->onGetProperty($record, $property, $value); } return $value; @@ -217,7 +217,7 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @return mixed */ public function onSetProperty(Doctrine_Record $record, $property, $value) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $value = $listener->onSetProperty($record, $property, $value); } return $value; @@ -229,8 +229,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onInsert(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onInsert(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onInsert($record); } } @@ -242,7 +242,7 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @return void */ public function onPreInsert(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onPreInsert($record); } } @@ -253,8 +253,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onDelete(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onDelete(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onDelete($record); } } @@ -265,8 +265,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onPreDelete(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onPreDelete(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onPreDelete($record); } } @@ -277,8 +277,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onEvict(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onEvict(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onEvict($record); } } @@ -289,8 +289,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Record $record * @return void */ - public function onPreEvict(Doctrine_Record $record) { - foreach($this->listeners as $listener) { + public function onPreEvict(Doctrine_Record $record) { + foreach ($this->listeners as $listener) { $listener->onPreEvict($record); } } @@ -302,7 +302,7 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @return void */ public function onClose(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onClose($connection); } } @@ -313,8 +313,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Connection $connection * @return void */ - public function onPreClose(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + public function onPreClose(Doctrine_Connection $connection) { + foreach ($this->listeners as $listener) { $listener->onPreClose($connection); } } @@ -325,8 +325,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Connection $connection * @return void */ - public function onOpen(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + public function onOpen(Doctrine_Connection $connection) { + foreach ($this->listeners as $listener) { $listener->onOpen($connection); } } @@ -337,8 +337,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Connection $connection * @return void */ - public function onTransactionCommit(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + public function onTransactionCommit(Doctrine_Connection $connection) { + foreach ($this->listeners as $listener) { $listener->onTransactionCommit($connection); } } @@ -349,8 +349,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Connection $connection * @return void */ - public function onPreTransactionCommit(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + public function onPreTransactionCommit(Doctrine_Connection $connection) { + foreach ($this->listeners as $listener) { $listener->onPreTransactionCommit($connection); } } @@ -361,8 +361,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Connection $connection * @return void */ - public function onTransactionRollback(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + public function onTransactionRollback(Doctrine_Connection $connection) { + foreach ($this->listeners as $listener) { $listener->onTransactionRollback($connection); } } @@ -373,8 +373,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Connection $connection * @return void */ - public function onPreTransactionRollback(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + public function onPreTransactionRollback(Doctrine_Connection $connection) { + foreach ($this->listeners as $listener) { $listener->onPreTransactionRollback($connection); } } @@ -386,7 +386,7 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @return void */ public function onTransactionBegin(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + foreach ($this->listeners as $listener) { $listener->onTransactionBegin($connection); } } @@ -397,8 +397,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Connection $connection * @return void */ - public function onPreTransactionBegin(Doctrine_Connection $connection) { - foreach($this->listeners as $listener) { + public function onPreTransactionBegin(Doctrine_Connection $connection) { + foreach ($this->listeners as $listener) { $listener->onPreTransactionBegin($connection); } } @@ -409,8 +409,8 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Collection $collection * @return void */ - public function onCollectionDelete(Doctrine_Collection $collection) { - foreach($this->listeners as $listener) { + public function onCollectionDelete(Doctrine_Collection $collection) { + foreach ($this->listeners as $listener) { $listener->onCollectionDelete($record); } } @@ -421,10 +421,9 @@ class Doctrine_EventListener_Chain extends Doctrine_Access implements Doctrine_E * @param Doctrine_Collection $collection * @return void */ - public function onPreCollectionDelete(Doctrine_Collection $collection) { - foreach($this->listeners as $listener) { + public function onPreCollectionDelete(Doctrine_Collection $collection) { + foreach ($this->listeners as $listener) { $listener->onPreCollectionDelete($collection); } } } - diff --git a/lib/Doctrine/EventListener/Debugger.php b/lib/Doctrine/EventListener/Debugger.php index 6ebe82011..522622291 100644 --- a/lib/Doctrine/EventListener/Debugger.php +++ b/lib/Doctrine/EventListener/Debugger.php @@ -47,11 +47,10 @@ class Doctrine_EventListener_Debugger extends Doctrine_EventListener { const EVENT_COLLDELETE = 26; const EVENT_PRECOLLDELETE = 27; private $debug; - - public function getMessages() { - return $this->debug; - } + public function getMessages() { + return $this->debug; + } public function onLoad(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_LOAD); @@ -60,18 +59,18 @@ class Doctrine_EventListener_Debugger extends Doctrine_EventListener { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PRELOAD); } - public function onSleep(Doctrine_Record $record) { + public function onSleep(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_SLEEP); } - public function onWakeUp(Doctrine_Record $record) { + public function onWakeUp(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_WAKEUP); } - public function onUpdate(Doctrine_Record $record) { + public function onUpdate(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_UPDATE); } - public function onPreUpdate(Doctrine_Record $record) { + public function onPreUpdate(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PREUPDATE); } @@ -89,42 +88,42 @@ class Doctrine_EventListener_Debugger extends Doctrine_EventListener { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PRESAVE); } - public function onInsert(Doctrine_Record $record) { + public function onInsert(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_INSERT); } - public function onPreInsert(Doctrine_Record $record) { + public function onPreInsert(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PREINSERT); } - public function onDelete(Doctrine_Record $record) { + public function onDelete(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_DELETE); } - public function onPreDelete(Doctrine_Record $record) { + public function onPreDelete(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PREDELETE); } - public function onEvict(Doctrine_Record $record) { + public function onEvict(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_EVICT); } - public function onPreEvict(Doctrine_Record $record) { + public function onPreEvict(Doctrine_Record $record) { $this->debug[] = new Doctrine_DebugMessage($record,self::EVENT_PREEVICT); } - public function onClose(Doctrine_Connection $connection) { + public function onClose(Doctrine_Connection $connection) { $this->debug[] = new Doctrine_DebugMessage($connection,self::EVENT_CLOSE); } - public function onPreClose(Doctrine_Connection $connection) { + public function onPreClose(Doctrine_Connection $connection) { $this->debug[] = new Doctrine_DebugMessage($connection,self::EVENT_PRECLOSE); } - public function onOpen(Doctrine_Connection $connection) { + public function onOpen(Doctrine_Connection $connection) { $this->debug[] = new Doctrine_DebugMessage($connection,self::EVENT_OPEN); } - public function onTransactionCommit(Doctrine_Connection $connection) { + public function onTransactionCommit(Doctrine_Connection $connection) { $this->debug[] = new Doctrine_DebugMessage($connection,self::EVENT_COMMIT); } - public function onPreTransactionCommit(Doctrine_Connection $connection) { + public function onPreTransactionCommit(Doctrine_Connection $connection) { $this->debug[] = new Doctrine_DebugMessage($connection,self::EVENT_PRECOMMIT); } @@ -141,12 +140,11 @@ class Doctrine_EventListener_Debugger extends Doctrine_EventListener { public function onPreTransactionBegin(Doctrine_Connection $connection) { $this->debug[] = new Doctrine_DebugMessage($connection,self::EVENT_PREBEGIN); } - - public function onCollectionDelete(Doctrine_Collection $collection) { + + public function onCollectionDelete(Doctrine_Collection $collection) { $this->debug[] = new Doctrine_DebugMessage($collection,self::EVENT_COLLDELETE); } public function onPreCollectionDelete(Doctrine_Collection $collection) { $this->debug[] = new Doctrine_DebugMessage($collection,self::EVENT_PRECOLLDELETE); } } - diff --git a/lib/Doctrine/EventListener/Empty.php b/lib/Doctrine/EventListener/Empty.php index 704de150b..626822666 100644 --- a/lib/Doctrine/EventListener/Empty.php +++ b/lib/Doctrine/EventListener/Empty.php @@ -1,13 +1,12 @@ - */ + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_EventListener_Empty extends Doctrine_EventListener { } - diff --git a/lib/Doctrine/EventListener/Interface.php b/lib/Doctrine/EventListener/Interface.php index b9920bae3..abc99ebae 100644 --- a/lib/Doctrine/EventListener/Interface.php +++ b/lib/Doctrine/EventListener/Interface.php @@ -56,12 +56,12 @@ interface Doctrine_EventListener_Interface { public function onPreEvict(Doctrine_Record $record); public function onSleep(Doctrine_Record $record); - + public function onWakeUp(Doctrine_Record $record); - + public function onClose(Doctrine_Connection $connection); public function onPreClose(Doctrine_Connection $connection); - + public function onOpen(Doctrine_Connection $connection); public function onTransactionCommit(Doctrine_Connection $connection); @@ -72,7 +72,7 @@ interface Doctrine_EventListener_Interface { public function onTransactionBegin(Doctrine_Connection $connection); public function onPreTransactionBegin(Doctrine_Connection $connection); - + public function onCollectionDelete(Doctrine_Collection $collection); public function onPreCollectionDelete(Doctrine_Collection $collection); } diff --git a/lib/Doctrine/Exception.php b/lib/Doctrine/Exception.php index 273434007..342f8ecc1 100644 --- a/lib/Doctrine/Exception.php +++ b/lib/Doctrine/Exception.php @@ -1,32 +1,32 @@ -. - */ -/** - * Doctrine_Exception - * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Exception extends Exception { } +. + */ +/** + * Doctrine_Exception + * + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Exception extends Exception { } diff --git a/lib/Doctrine/Export.php b/lib/Doctrine/Export.php index 9c235f99f..0d62ad75b 100644 --- a/lib/Doctrine/Export.php +++ b/lib/Doctrine/Export.php @@ -130,9 +130,9 @@ class Doctrine_Export extends Doctrine_Connection_Module { if ( ! $name) throw new Doctrine_Export_Exception('no valid table name specified'); - if (empty($fields)) + if (empty($fields)) { throw new Doctrine_Export_Exception('no fields specified for table '.$name); - + } $queryFields = $this->getFieldDeclarationList($fields); if (!empty($options['primary'])) { @@ -522,8 +522,8 @@ class Doctrine_Export extends Doctrine_Connection_Module { public function getDeclaration($name, array $field) { $default = ''; - if(isset($field['default'])) { - if($field['default'] === '') { + if (isset($field['default'])) { + if ($field['default'] === '') { $field['default'] = empty($field['notnull']) ? null : $this->valid_default_values[$field['type']]; if ($field['default'] === '' @@ -536,27 +536,27 @@ class Doctrine_Export extends Doctrine_Connection_Module { $default = ' DEFAULT ' . $this->conn->quote($field['default'], $field['type']); } /** - TODO: is this really needed for portability? - elseif(empty($field['notnull'])) { + TODO: is this really needed for portability? + elseif (empty($field['notnull'])) { $default = ' DEFAULT NULL'; } */ $charset = empty($field['charset']) ? '' : ' '.$this->getCharsetFieldDeclaration($field['charset']); - + $collation = empty($field['collation']) ? '' : ' '.$this->getCollationFieldDeclaration($field['collation']); - + $notnull = empty($field['notnull']) ? '' : ' NOT NULL'; $method = 'get' . $field['type'] . 'Declaration'; - if(method_exists($this->conn->dataDict, $method)) + if (method_exists($this->conn->dataDict, $method)) { return $this->conn->dataDict->$method($name, $field); - else + } else { $dec = $this->conn->dataDict->getNativeDeclaration($field); - + } return $this->conn->quoteIdentifier($name, true) . ' ' . $dec . $charset . $default . $notnull . $collation; } /** @@ -593,40 +593,41 @@ class Doctrine_Export extends Doctrine_Connection_Module { $old = $conn->getAttribute(Doctrine::ATTR_CREATE_TABLES); $conn->setAttribute(Doctrine::ATTR_CREATE_TABLES, true); - - foreach(get_declared_classes() as $name) { + + foreach (get_declared_classes() as $name) { $class = new ReflectionClass($name); - if($class->isSubclassOf($parent) && ! $class->isAbstract()) + if ($class->isSubclassOf($parent) && ! $class->isAbstract()) { $obj = new $class(); + } } $conn->setAttribute(Doctrine::ATTR_CREATE_TABLES, $old); } public function export($record) { - if( ! $record instanceof Doctrine_Record) + if ( ! $record instanceof Doctrine_Record) $record = new $record(); $table = $record->getTable(); - + $reporter = new Doctrine_Reporter(); - if( ! Doctrine::isValidClassname($table->getComponentName())) { + if ( ! Doctrine::isValidClassname($table->getComponentName())) { $reporter->add(E_WARNING, 'Badly named class.'); } - + try { $columns = array(); - foreach($table->getColumns() as $name => $column) { + foreach ($table->getColumns() as $name => $column) { $definition = $column[2]; $definition['type'] = $column[0]; $definition['length'] = $column[1]; - if($definition['type'] == 'enum' && isset($definition['default'])) + if ($definition['type'] == 'enum' && isset($definition['default'])) { $definition['default'] = $table->enumIndex($name, $definition['default']); - - if($definition['type'] == 'boolean' && isset($definition['default'])) + } + if ($definition['type'] == 'boolean' && isset($definition['default'])) { $definition['default'] = (int) $definition['default']; - + } $columns[$name] = $definition; } diff --git a/lib/Doctrine/Export/Exception.php b/lib/Doctrine/Export/Exception.php index 827f54f3f..f4a76e777 100644 --- a/lib/Doctrine/Export/Exception.php +++ b/lib/Doctrine/Export/Exception.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Export_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/Export/Firebird.php b/lib/Doctrine/Export/Firebird.php index ca2c19d2f..f20bf3f82 100644 --- a/lib/Doctrine/Export/Firebird.php +++ b/lib/Doctrine/Export/Firebird.php @@ -81,7 +81,7 @@ class Doctrine_Export_Firebird extends Doctrine_Export { $table = $this->conn->quoteIdentifier($table, true); $name = $this->conn->quoteIdentifier($name, true); - + $triggerSql = 'CREATE TRIGGER ' . $trigger_name . ' FOR ' . $table . ' ACTIVE BEFORE INSERT POSITION 0 AS @@ -104,7 +104,7 @@ class Doctrine_Export_Firebird extends Doctrine_Export { public function _dropAutoincrement($table) { $result = $this->dropSequence($table); - + /** if (PEAR::isError($result)) { return $db->raiseError(null, null, null, @@ -115,7 +115,7 @@ class Doctrine_Export_Firebird extends Doctrine_Export { $table = $this->conn->getDbh()->quote(strtoupper($table)); $trigger_name = $this->conn->getDbh()->quote(strtoupper($table) . '_AUTOINCREMENT_PK'); $result = $this->conn->exec("DELETE FROM RDB\$TRIGGERS WHERE UPPER(RDB\$RELATION_NAME)=$table AND UPPER(RDB\$TRIGGER_NAME)=$trigger_name"); - + /** if (PEAR::isError($result)) { return $db->raiseError(null, null, null, @@ -158,8 +158,8 @@ class Doctrine_Export_Firebird extends Doctrine_Export { parent::createTable($name, $fields, $options); // TODO ? $this->_silentCommit(); - foreach($fields as $field_name => $field) { - if( ! empty($field['autoincrement'])) { + foreach ($fields as $field_name => $field) { + if ( ! empty($field['autoincrement'])) { //create PK constraint $pk_definition = array( 'fields' => array($field_name => array()), @@ -218,7 +218,7 @@ class Doctrine_Export_Firebird extends Doctrine_Export { $result = parent::dropTable($name); //$this->_silentCommit(); - + return $result; } /** diff --git a/lib/Doctrine/Export/Firebird/Exception.php b/lib/Doctrine/Export/Firebird/Exception.php index 33c5e041c..e98d3fa52 100644 --- a/lib/Doctrine/Export/Firebird/Exception.php +++ b/lib/Doctrine/Export/Firebird/Exception.php @@ -1,5 +1,5 @@ exec($query); diff --git a/lib/Doctrine/Export/Mysql.php b/lib/Doctrine/Export/Mysql.php index 6b60f6a4b..24abaec20 100644 --- a/lib/Doctrine/Export/Mysql.php +++ b/lib/Doctrine/Export/Mysql.php @@ -90,29 +90,28 @@ class Doctrine_Export_Mysql extends Doctrine_Export { * @return void */ public function createTable($name, array $fields, array $options = array()) { - if( ! $name) + if ( ! $name) throw new Doctrine_Export_Mysql_Exception('no valid table name specified'); - if(empty($fields)) + if (empty($fields)) { throw new Doctrine_Export_Mysql_Exception('no fields specified for table "'.$name.'"'); - + } $query_fields = $this->getFieldDeclarationList($fields); - if( ! empty($options['primary'])) + if ( ! empty($options['primary'])) { $query_fields.= ', PRIMARY KEY(' . implode(', ', array_values($options['primary'])) . ')'; - + } $name = $this->conn->quoteIdentifier($name, true); $query = 'CREATE TABLE ' . $name . ' (' . $query_fields . ')'; $optionStrings = array(); - if(isset($options['comment'])) + if (isset($options['comment'])) { $optionStrings['comment'] = 'COMMENT = '.$this->dbh->quote($options['comment'], 'text'); - - - if(isset($options['charset'])) { + } + if (isset($options['charset'])) { $optionsSting['charset'] = 'DEFAULT CHARACTER SET '.$options['charset']; - if(isset($options['collate'])) { + if (isset($options['collate'])) { $optionStrings['charset'].= ' COLLATE '.$options['collate']; } } @@ -124,7 +123,7 @@ class Doctrine_Export_Mysql extends Doctrine_Export { } else { $type = $this->conn->getAttribute(Doctrine::ATTR_DEFAULT_TABLE_TYPE); } - + if ($type) { $optionStrings[] = 'ENGINE = ' . $type; } @@ -223,7 +222,7 @@ class Doctrine_Export_Mysql extends Doctrine_Export { * @return boolean */ public function alterTable($name, array $changes, $check) { - if( ! $name) + if ( ! $name) throw new Doctrine_Export_Mysql_Exception('no valid table name specified'); foreach ($changes as $changeName => $change) { @@ -239,17 +238,17 @@ class Doctrine_Export_Mysql extends Doctrine_Export { } } - if($check) { + if ($check) { return true; } $query = ''; - if( ! empty($changes['name'])) { + if ( ! empty($changes['name'])) { $change_name = $this->conn->quoteIdentifier($changes['name'], true); $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 $field_name => $field) { if ($query) { $query.= ', '; @@ -258,7 +257,7 @@ class Doctrine_Export_Mysql extends Doctrine_Export { } } - if( ! empty($changes['remove']) && is_array($changes['remove'])) { + if ( ! empty($changes['remove']) && is_array($changes['remove'])) { foreach ($changes['remove'] as $field_name => $field) { if ($query) { $query.= ', '; @@ -269,13 +268,13 @@ class Doctrine_Export_Mysql extends Doctrine_Export { } $rename = array(); - if( ! empty($changes['rename']) && is_array($changes['rename'])) { + if ( ! empty($changes['rename']) && is_array($changes['rename'])) { foreach ($changes['rename'] as $field_name => $field) { $rename[$field['name']] = $field_name; } } - if( ! empty($changes['change']) && is_array($changes['change'])) { + if ( ! empty($changes['change']) && is_array($changes['change'])) { foreach ($changes['change'] as $field_name => $field) { if ($query) { $query.= ', '; @@ -291,7 +290,7 @@ class Doctrine_Export_Mysql extends Doctrine_Export { } } - if( ! empty($rename) && is_array($rename)) { + if ( ! empty($rename) && is_array($rename)) { foreach ($rename as $rename_name => $renamed_field) { if ($query) { $query.= ', '; @@ -302,7 +301,7 @@ class Doctrine_Export_Mysql extends Doctrine_Export { } } - if( ! $query) { + if ( ! $query) { return MDB2_OK; } @@ -321,7 +320,7 @@ class Doctrine_Export_Mysql extends Doctrine_Export { $query = 'CREATE TABLE ' . $sequenceName . ' (' . $seqcol_name . ' INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (' . $seqcol_name . '))' - . strlen($this->dbh->options['default_table_type']) ? ' TYPE = ' + . strlen($this->dbh->options['default_table_type']) ? ' TYPE = ' . $this->dbh->options['default_table_type'] : ''; $res = $this->dbh->query($query); @@ -329,7 +328,6 @@ class Doctrine_Export_Mysql extends Doctrine_Export { if ($start == 1) return true; - $query = 'INSERT INTO ' . $sequenceName . ' (' . $seqcol_name . ') VALUES (' . ($start-1) . ')'; @@ -418,4 +416,4 @@ class Doctrine_Export_Mysql extends Doctrine_Export { $this->conn->exec('DROP TABLE ' . $table); } } -?> + diff --git a/lib/Doctrine/Export/Mysql/Exception.php b/lib/Doctrine/Export/Mysql/Exception.php index ffdea672c..ec76c2143 100644 --- a/lib/Doctrine/Export/Mysql/Exception.php +++ b/lib/Doctrine/Export/Mysql/Exception.php @@ -1,5 +1,5 @@ conn->getAttribute(Doctrine::ATTR_EMULATE_DATABASE)) throw new Doctrine_Export_Oracle_Exception('database creation is only supported if the "emulate_database" attribute is enabled'); - $username = sprintf($this->conn->getAttribute(Doctrine::ATTR_DB_NAME_FORMAT), $name); $password = $this->conn->dsn['password'] ? $this->conn->dsn['password'] : $name; @@ -78,10 +77,9 @@ class Doctrine_Export_Oracle extends Doctrine_Export { public function dropDatabase($name) { if ( ! $this->conn->getAttribute(Doctrine::ATTR_EMULATE_DATABASE)) - throw new Doctrine_Export_Oracle_Exception('database dropping is only supported if the + throw new Doctrine_Export_Oracle_Exception('database dropping is only supported if the "emulate_database" option is enabled'); - $username = sprintf($this->conn->getAttribute(Doctrine::ATTR_DB_NAME_FORMAT), $name); return $this->conn->query('DROP USER ' . $username . ' CASCADE'); @@ -174,10 +172,10 @@ END; $query.= ' WHERE trigger_name='.$trigger_name_quoted.' OR trigger_name='.strtoupper($trigger_name_quoted); $trigger = $this->conn->fetchOne($query); - if($trigger) { + if ($trigger) { $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); @@ -227,8 +225,8 @@ END; $result = parent::createTable($name, $fields, $options); - foreach($fields as $field_name => $field) { - if(isset($field['autoincrement']) && $field['autoincrement']) { + foreach ($fields as $field_name => $field) { + if (isset($field['autoincrement']) && $field['autoincrement']) { $result = $this->_makeAutoincrement($field_name, $name); } } diff --git a/lib/Doctrine/Export/Pgsql.php b/lib/Doctrine/Export/Pgsql.php index af889c697..ac90333a4 100644 --- a/lib/Doctrine/Export/Pgsql.php +++ b/lib/Doctrine/Export/Pgsql.php @@ -182,9 +182,9 @@ class Doctrine_Export_Pgsql extends Doctrine_Export { if (!empty($field['type'])) { $server_info = $db->getServerVersion(); - if (is_array($server_info) && $server_info['major'] < 8) + if (is_array($server_info) && $server_info['major'] < 8) { throw new Doctrine_Export_Pgsql_Exception('changing column type for "'.$change_name.'\" requires PostgreSQL 8.0 or above'); - + } $query = "ALTER $field_name TYPE ".$db->datatype->getTypeDeclaration($field['definition']); $this->dbh->query("ALTER TABLE $name $query"); } @@ -214,4 +214,4 @@ class Doctrine_Export_Pgsql extends Doctrine_Export { } } } -?> + diff --git a/lib/Doctrine/Export/Sqlite.php b/lib/Doctrine/Export/Sqlite.php index 89a717796..616e13ff5 100644 --- a/lib/Doctrine/Export/Sqlite.php +++ b/lib/Doctrine/Export/Sqlite.php @@ -71,7 +71,7 @@ class Doctrine_Export_Sqlite extends Doctrine_Export { $fields = array(); foreach ($definition['fields'] as $fieldName => $field) { $fieldString = $fieldName; - if(isset($field['sorting'])) { + if (isset($field['sorting'])) { switch ($field['sorting']) { case 'ascending': $fieldString .= ' ASC'; diff --git a/lib/Doctrine/Expression.php b/lib/Doctrine/Expression.php index 97a4414df..8d31dca80 100644 --- a/lib/Doctrine/Expression.php +++ b/lib/Doctrine/Expression.php @@ -1,5 +1,5 @@ getIdentifiers($args); - if (count($elements) < 1) + if (count($elements) < 1) { return ''; - + } if (count($elements) == 1) { return $elements[0]; } else { @@ -303,7 +303,7 @@ class Doctrine_Expression extends Doctrine_Connection_Module { * Example: * * $q = new Doctrine_Query(); - * $e = $q->expr; + * $e = $q->expr; * * $q->select('u.*') * ->from('User u') @@ -327,7 +327,7 @@ class Doctrine_Expression extends Doctrine_Connection_Module { * Example: * * $q = new Doctrine_Query(); - * $e = $q->expr; + * $e = $q->expr; * * $q->select('u.*') * ->from('User u') @@ -351,7 +351,7 @@ class Doctrine_Expression extends Doctrine_Connection_Module { * Example: * * $q = new Doctrine_Query(); - * $e = $q->expr; + * $e = $q->expr; * * $q->select('u.*') * ->from('User u') @@ -375,7 +375,7 @@ class Doctrine_Expression extends Doctrine_Connection_Module { * Example: * * $q = new Doctrine_Query(); - * $e = $q->expr; + * $e = $q->expr; * * $q->select('u.*') * ->from('User u') @@ -539,15 +539,15 @@ class Doctrine_Expression extends Doctrine_Connection_Module { * @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 (count($values) == 0) { throw new Doctrine_Expression_Exception('Values array for IN operator should not be empty.'); - + } return $column . ' IN (' . implode(', ', $values) . ')'; } /** diff --git a/lib/Doctrine/Expression/Firebird.php b/lib/Doctrine/Expression/Firebird.php index 904cc360e..5bba1dcaa 100644 --- a/lib/Doctrine/Expression/Firebird.php +++ b/lib/Doctrine/Expression/Firebird.php @@ -44,7 +44,7 @@ class Doctrine_Expression_Firebird extends Doctrine_Expression { } /** * build string to define escape pattern string - * + * * @return string define escape pattern */ function patternEscapeString() { diff --git a/lib/Doctrine/Expression/Mssql.php b/lib/Doctrine/Expression/Mssql.php index a3c5be983..cdb029b2c 100644 --- a/lib/Doctrine/Expression/Mssql.php +++ b/lib/Doctrine/Expression/Mssql.php @@ -22,14 +22,14 @@ Doctrine::autoload('Doctrine_Expression'); /** * Doctrine_Expression_Mssql * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Expression_Mssql extends Doctrine_Expression { /** * Return string to call a variable with the current timestamp inside an SQL statement @@ -56,9 +56,9 @@ class Doctrine_Expression_Mssql extends Doctrine_Expression { * @return string to call a function to get a substring */ public function substring($value, $position, $length = null) { - if (!is_null($length)) + if (!is_null($length)) { return "SUBSTRING($value, $position, $length)"; - + } return "SUBSTRING($value, $position, LEN($value) - $position + 1)"; } /** diff --git a/lib/Doctrine/Expression/Mysql.php b/lib/Doctrine/Expression/Mysql.php index 88bcc7320..83dd3a7f2 100644 --- a/lib/Doctrine/Expression/Mysql.php +++ b/lib/Doctrine/Expression/Mysql.php @@ -32,13 +32,13 @@ Doctrine::autoload('Doctrine_Expression'); */ class Doctrine_Expression_Mysql extends Doctrine_Expression { /** - * returns the regular expression operator + * returns the regular expression operator * * @return string */ public function regexp() { return 'RLIKE'; - } + } /** * build a pattern matching string * diff --git a/lib/Doctrine/Expression/Oracle.php b/lib/Doctrine/Expression/Oracle.php index d79dfee98..988d12a0d 100644 --- a/lib/Doctrine/Expression/Oracle.php +++ b/lib/Doctrine/Expression/Oracle.php @@ -22,14 +22,14 @@ Doctrine::autoload('Doctrine_Expression'); /** * Doctrine_Expression_Sqlite * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Expression_Oracle extends Doctrine_Expression { /** * Returns a series of strings concatinated @@ -57,7 +57,7 @@ class Doctrine_Expression_Oracle extends Doctrine_Expression { * @return string SQL substring function with given parameters */ public function substring($value, $position, $length = null) { - if($length !== null) + if ($length !== null) return "SUBSTR($value, $position, $length)"; return "SUBSTR($value, $position)"; diff --git a/lib/Doctrine/Expression/Pgsql.php b/lib/Doctrine/Expression/Pgsql.php index bac74ada8..76aad4949 100644 --- a/lib/Doctrine/Expression/Pgsql.php +++ b/lib/Doctrine/Expression/Pgsql.php @@ -52,10 +52,11 @@ class Doctrine_Expression_Pgsql extends Doctrine_Expression { public function md5($column) { $column = $this->getIdentifier($column); - if ($this->version > 7) + if ($this->version > 7) { return 'MD5(' . $column . ')'; - else + } else { return 'encode(digest(' . $column .', md5), hex)'; + } } /** @@ -74,8 +75,9 @@ class Doctrine_Expression_Pgsql extends Doctrine_Expression { if ($len === null) { $len = $this->getIdentifier($len); return 'SUBSTR(' . $value . ', ' . $from . ')'; - } else + } else { return 'SUBSTR(' . $value . ', ' . $from . ', ' . $len . ')'; + } } /** diff --git a/lib/Doctrine/Expression/Sqlite.php b/lib/Doctrine/Expression/Sqlite.php index 3f168771f..1a8b48345 100644 --- a/lib/Doctrine/Expression/Sqlite.php +++ b/lib/Doctrine/Expression/Sqlite.php @@ -73,7 +73,7 @@ class Doctrine_Expression_Sqlite extends Doctrine_Expression { return strpos($str, $substr); } public static function sha1Impl($str) { - return sha1($str); + return sha1($str); } public static function ltrimImpl($str) { return ltrim($str); @@ -85,7 +85,7 @@ class Doctrine_Expression_Sqlite extends Doctrine_Expression { return trim($str); } /** - * returns the regular expression operator + * returns the regular expression operator * * @return string */ @@ -94,7 +94,7 @@ class Doctrine_Expression_Sqlite extends Doctrine_Expression { } /** * soundex - * Returns a string to call a function to compute the + * Returns a string to call a function to compute the * soundex encoding of a string * * The string "?000" is returned if the argument is NULL. @@ -133,8 +133,8 @@ class Doctrine_Expression_Sqlite extends Doctrine_Expression { /** * return string to call a function to get a substring inside an SQL statement * - * Note: Not SQL92, but common functionality. - * + * 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 @@ -143,9 +143,9 @@ class Doctrine_Expression_Sqlite extends Doctrine_Expression { * @return string SQL substring function with given parameters */ public function substring($value, $position, $length = null) { - if($length !== null) + if ($length !== null) { return 'SUBSTR(' . $value . ', ' . $position . ', ' . $length . ')'; - + } return 'SUBSTR(' . $value . ', ' . $position . ', LENGTH(' . $value . '))'; } } diff --git a/lib/Doctrine/Hook.php b/lib/Doctrine/Hook.php index bdc479410..194112b87 100644 --- a/lib/Doctrine/Hook.php +++ b/lib/Doctrine/Hook.php @@ -30,7 +30,7 @@ * @version $Revision$ * @author Konsta Vesterinen */ -class Doctrine_Hook { +class Doctrine_Hook { /** * @var Doctrine_Query $query the base query */ @@ -70,10 +70,10 @@ class Doctrine_Hook { * @param Doctrine_Query $query the base query */ public function __construct($query) { - if(is_string($query)) { + if (is_string($query)) { $this->query = new Doctrine_Query(); $this->query->parseQuery($query); - } elseif($query instanceof Doctrine_Query) { + } elseif ($query instanceof Doctrine_Query) { $this->query = $query; } } @@ -84,32 +84,31 @@ class Doctrine_Hook { } public function innerJoin($dql) { - + } /** * hookWhere * builds DQL query where part from given parameter array * - * @param array $params an associative array containing field + * @param array $params an associative array containing field * names and their values * @return boolean 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) { + } + foreach ($params as $name => $value) { $e = explode('.', $name); - if(count($e) == 2) { + if (count($e) == 2) { list($alias, $column) = $e; $tableAlias = $this->query->getTableAlias($alias); $table = $this->query->getTable($tableAlias); - if($def = $table->getDefinitionOf($column)) { - - if(isset($this->typeParsers[$def[0]])) { + if ($def = $table->getDefinitionOf($column)) { + if (isset($this->typeParsers[$def[0]])) { $name = $this->typeParsers[$def[0]]; $parser = new $name; } @@ -122,7 +121,7 @@ class Doctrine_Hook { } } $this->params += $params; - + return true; } /** @@ -134,27 +133,27 @@ class Doctrine_Hook { * @return boolean whether or not the hooking was */ public function hookOrderby($params) { - if( ! is_array($params)) + if ( ! is_array($params)) { return false; - - foreach($params as $name) { + } + foreach ($params as $name) { $e = explode(' ', $name); $order = 'ASC'; - if(count($e) > 1) { + if (count($e) > 1) { $order = ($e[1] == 'DESC') ? 'DESC' : 'ASC'; } $e = explode('.', $e[0]); - if(count($e) == 2) { + if (count($e) == 2) { list($alias, $column) = $e; $tableAlias = $this->query->getTableAlias($alias); $table = $this->query->getTable($tableAlias); - if($def = $table->getDefinitionOf($column)) { + if ($def = $table->getDefinitionOf($column)) { $this->query->addOrderBy($alias . '.' . $column . ' ' . $order); } } diff --git a/lib/Doctrine/Hook/Equal.php b/lib/Doctrine/Hook/Equal.php index 9bd263120..8b4feaf8a 100644 --- a/lib/Doctrine/Hook/Equal.php +++ b/lib/Doctrine/Hook/Equal.php @@ -34,8 +34,8 @@ class Doctrine_Hook_Equal extends Doctrine_Hook_Parser { /** * parse * Parses given field and field value to DQL condition - * and parameters. This method should always return - * prepared statement conditions (conditions that use + * and parameters. This method should always return + * prepared statement conditions (conditions that use * placeholders instead of literal values). * * @param string $alias component alias diff --git a/lib/Doctrine/Hook/Integer.php b/lib/Doctrine/Hook/Integer.php index b36a6fbd0..f7f920998 100644 --- a/lib/Doctrine/Hook/Integer.php +++ b/lib/Doctrine/Hook/Integer.php @@ -34,8 +34,8 @@ class Doctrine_Hook_Integer extends Doctrine_Hook_Parser_Complex { /** * parse * Parses given field and field value to DQL condition - * and parameters. This method should always return - * prepared statement conditions (conditions that use + * and parameters. This method should always return + * prepared statement conditions (conditions that use * placeholders instead of literal values). * * @param string $alias component alias @@ -46,15 +46,15 @@ class Doctrine_Hook_Integer extends Doctrine_Hook_Parser_Complex { public function parseSingle($alias, $field, $value) { $e = explode(' ', $value); - foreach($e as $v) { - $v = trim($v); + foreach ($e as $v) { + $v = trim($v); - $e2 = explode('-', $v); + $e2 = explode('-', $v); $name = $alias. '.' . $field; - if(count($e2) == 1) { - // one '-' found + if (count($e2) == 1) { + // one '-' found $a[] = $name . ' = ?'; @@ -63,7 +63,7 @@ class Doctrine_Hook_Integer extends Doctrine_Hook_Parser_Complex { // more than one '-' found $a[] = '(' . $name . ' > ? AND ' . $name . ' < ?)'; - + $this->params += array($e2[0], $e2[1]); } diff --git a/lib/Doctrine/Hook/Parser.php b/lib/Doctrine/Hook/Parser.php index cdba2ca88..0151f0a4f 100644 --- a/lib/Doctrine/Hook/Parser.php +++ b/lib/Doctrine/Hook/Parser.php @@ -33,19 +33,19 @@ abstract class Doctrine_Hook_Parser { protected $condition; protected $params = array(); - + public function getCondition() { return $this->condition; } - + public function getParams() { return $this->params; } /** * parse * Parses given field and field value to DQL condition - * and parameters. This method should always return - * prepared statement conditions (conditions that use + * and parameters. This method should always return + * prepared statement conditions (conditions that use * placeholders instead of literal values). * * @param string $alias component alias diff --git a/lib/Doctrine/Hook/Parser/Complex.php b/lib/Doctrine/Hook/Parser/Complex.php index 3a2d88df2..4b520e95f 100644 --- a/lib/Doctrine/Hook/Parser/Complex.php +++ b/lib/Doctrine/Hook/Parser/Complex.php @@ -57,9 +57,9 @@ abstract class Doctrine_Hook_Parser_Complex extends Doctrine_Hook_Parser { public function parseClause($alias, $field, $value) { $parts = Doctrine_Query::bracketExplode($value, ' AND ', '(', ')'); - if(count($parts) > 1) { + if (count($parts) > 1) { $ret = array(); - foreach($parts as $part) { + foreach ($parts as $part) { $part = Doctrine_Query::bracketTrim($part, '(', ')'); $ret[] = $this->parseSingle($alias, $field, $part); } @@ -67,16 +67,16 @@ abstract class Doctrine_Hook_Parser_Complex extends Doctrine_Hook_Parser { $r = implode(' AND ', $ret); } else { $parts = Doctrine_Query::bracketExplode($value, ' OR ', '(', ')'); - if(count($parts) > 1) { + if (count($parts) > 1) { $ret = array(); - foreach($parts as $part) { + foreach ($parts as $part) { $part = Doctrine_Query::bracketTrim($part, '(', ')'); $ret[] = $this->parseClause($alias, $field, $part); } $r = implode(' OR ', $ret); } else { - if(substr($parts[0],0,1) == '(' && substr($parts[0],-1) == ')') { + if (substr($parts[0],0,1) == '(' && substr($parts[0],-1) == ')') { return $this->parseClause(substr($parts[0],1,-1)); } else { $ret = $this->parseSingle($alias, $field, $parts[0]); diff --git a/lib/Doctrine/Hook/WordLike.php b/lib/Doctrine/Hook/WordLike.php index b3ddc5713..b681babaf 100644 --- a/lib/Doctrine/Hook/WordLike.php +++ b/lib/Doctrine/Hook/WordLike.php @@ -35,7 +35,7 @@ class Doctrine_Hook_WordLike extends Doctrine_Hook_Parser_Complex { * parse * Parses given field and field value to DQL condition * and parameters. This method should always return - * prepared statement conditions (conditions that use + * prepared statement conditions (conditions that use * placeholders instead of literal values). * * @param string $alias component alias @@ -46,8 +46,8 @@ class Doctrine_Hook_WordLike extends Doctrine_Hook_Parser_Complex { public function parseSingle($alias, $field, $value) { $e2 = explode(' ',$value); - foreach($e2 as $v) { - $v = trim($v); + foreach ($e2 as $v) { + $v = trim($v); $a[] = $alias. '.' . $field . ' LIKE ?'; $this->params[] = $v . '%'; } diff --git a/lib/Doctrine/Hydrate.php b/lib/Doctrine/Hydrate.php index 2af6b8e6e..08a460ec6 100644 --- a/lib/Doctrine/Hydrate.php +++ b/lib/Doctrine/Hydrate.php @@ -1,5 +1,5 @@ getCurrentConnection(); - + } $this->conn = $connection; $this->aliasHandler = new Doctrine_Hydrate_Alias(); } @@ -158,26 +158,26 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { $this->compAliases = $query->getComponentAliases(); $this->tableAliases = $query->getTableAliases(); $this->tableIndexes = $query->getTableIndexes(); - + return $this; } - + public function getPathAlias($path) { $s = array_search($path, $this->compAliases); - if($s === false) + if ($s === false) return $path; return $s; } /** * createSubquery - * + * * @return Doctrine_Hydrate */ public function createSubquery() { $class = get_class($this); $obj = new $class(); - + // copy the aliases to the subquery $obj->copyAliases($this); @@ -203,19 +203,20 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { * * @param $name */ - public function remove($name) { - if(isset($this->parts[$name])) { - if($name == "limit" || $name == "offset") - $this->parts[$name] = false; - else - $this->parts[$name] = array(); - } - return $this; - } + public function remove($name) { + if (isset($this->parts[$name])) { + if ($name == "limit" || $name == "offset") { + $this->parts[$name] = false; + } else { + $this->parts[$name] = array(); + } + } + return $this; + } /** * clear * resets all the variables - * + * * @return void */ protected function clear() { @@ -284,12 +285,12 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { * @return string */ final public function getTableAlias($path) { - if(isset($this->compAliases[$path])) + if (isset($this->compAliases[$path])) { $path = $this->compAliases[$path]; - - if( ! isset($this->tableAliases[$path])) + } + if ( ! isset($this->tableAliases[$path])) { return false; - + } return $this->tableAliases[$path]; } /** @@ -300,28 +301,28 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { */ private function getCollection($name) { $table = $this->tables[$name]; - if( ! isset($this->fetchModes[$name])) + if ( ! isset($this->fetchModes[$name])) { return new Doctrine_Collection($table); - - switch($this->fetchModes[$name]): - case Doctrine::FETCH_BATCH: - $coll = new Doctrine_Collection_Batch($table); + } + switch ($this->fetchModes[$name]) { + case Doctrine::FETCH_BATCH: + $coll = new Doctrine_Collection_Batch($table); break; - case Doctrine::FETCH_LAZY: - $coll = new Doctrine_Collection_Lazy($table); + case Doctrine::FETCH_LAZY: + $coll = new Doctrine_Collection_Lazy($table); break; - case Doctrine::FETCH_OFFSET: - $coll = new Doctrine_Collection_Offset($table); + case Doctrine::FETCH_OFFSET: + $coll = new Doctrine_Collection_Offset($table); break; - case Doctrine::FETCH_IMMEDIATE: - $coll = new Doctrine_Collection_Immediate($table); + case Doctrine::FETCH_IMMEDIATE: + $coll = new Doctrine_Collection_Immediate($table); break; - case Doctrine::FETCH_LAZY_OFFSET: - $coll = new Doctrine_Collection_LazyOffset($table); + case Doctrine::FETCH_LAZY_OFFSET: + $coll = new Doctrine_Collection_LazyOffset($table); break; - default: - throw new Doctrine_Exception("Unknown fetchmode"); - endswitch; + default: + throw new Doctrine_Exception("Unknown fetchmode"); + }; return $coll; } @@ -333,8 +334,9 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { * @return void */ public static function convertBoolean(&$item) { - if(is_bool($item)) + if (is_bool($item)) { $item = (int) $item; + } } /** * setParams @@ -353,28 +355,30 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { */ public function execute($params = array(), $return = Doctrine::FETCH_RECORD) { $this->collections = array(); - + $params = array_merge($this->params, $params); - + array_walk($params, array(__CLASS__, 'convertBoolean')); - - if( ! $this->view) + + if ( ! $this->view) { $query = $this->getQuery($params); - else + } else { $query = $this->view->getSelectSql(); + } - if($this->isLimitSubqueryUsed() && - $this->conn->getDBH()->getAttribute(PDO::ATTR_DRIVER_NAME) !== 'mysql') + if ($this->isLimitSubqueryUsed() + && $this->conn->getDBH()->getAttribute(PDO::ATTR_DRIVER_NAME) !== 'mysql' + ) { $params = array_merge($params, $params); - + } $stmt = $this->conn->execute($query, $params); - if($this->aggregate) + if ($this->aggregate) return $stmt->fetchAll(PDO::FETCH_ASSOC); - if(count($this->tables) == 0) + if (count($this->tables) == 0) { throw new Doctrine_Query_Exception("No components selected"); - + } $keys = array_keys($this->tables); $root = $keys[0]; @@ -383,50 +387,48 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { $coll = $this->getCollection($root); $prev[$root] = $coll; - - if($this->aggregate) + if ($this->aggregate) $return = Doctrine::FETCH_ARRAY; $array = $this->parseData($stmt); - - if($return == Doctrine::FETCH_ARRAY) + if ($return == Doctrine::FETCH_ARRAY) return $array; - - foreach($array as $data) { + foreach ($array as $data) { /** * remove duplicated data rows and map data into objects */ - foreach($data as $key => $row) { - if(empty($row)) + foreach ($data as $key => $row) { + if (empty($row)) { continue; - + } //$key = array_search($key, $this->shortAliases); - foreach($this->tables as $k => $t) { - if ( ! strcasecmp($key, $k)) + foreach ($this->tables as $k => $t) { + if ( ! strcasecmp($key, $k)) { $key = $k; + } } - - if ( !isset($this->tables[$key]) ) - throw new Doctrine_Exception('No table named ' . $key . ' found.'); + if ( !isset($this->tables[$key]) ) { + throw new Doctrine_Exception('No table named ' . $key . ' found.'); + } $ids = $this->tables[$key]->getIdentifier(); $name = $key; - if($this->isIdentifiable($row, $ids)) { - if($name !== $root) { + if ($this->isIdentifiable($row, $ids)) { + if ($name !== $root) { $prev = $this->initRelated($prev, $name); } // aggregate values have numeric keys - if(isset($row[0])) { + if (isset($row[0])) { $component = $this->tables[$name]->getComponentName(); - + // if the collection already has objects, get the last object // otherwise create a new one where the aggregate values are being mapped - if($prev[$name]->count() > 0) { + if ($prev[$name]->count() > 0) { $record = $prev[$name]->getLast(); } else { $record = new $component(); @@ -437,10 +439,10 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { $alias = $this->getPathAlias($path); // map each aggregate value - foreach($row as $index => $value) { + foreach ($row as $index => $value) { $agg = false; - if(isset($this->pendingAggregates[$alias][$index])) { + if (isset($this->pendingAggregates[$alias][$index])) { $agg = $this->pendingAggregates[$alias][$index][3]; } @@ -452,11 +454,10 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { } - - if( ! isset($previd[$name])) - $previd[$name] = array(); - - if($previd[$name] !== $row) { + if ( ! isset($previd[$name])) { + $previd[$name] = array(); + } + if ($previd[$name] !== $row) { // set internal data $this->tables[$name]->setData($row); @@ -465,23 +466,22 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { $record = $this->tables[$name]->getRecord(); // aggregate values have numeric keys - if(isset($row[0])) { + if (isset($row[0])) { $path = array_search($name, $this->tableAliases); $alias = $this->getPathAlias($path); // map each aggregate value - foreach($row as $index => $value) { + foreach ($row as $index => $value) { $agg = false; - if(isset($this->pendingAggregates[$alias][$index])) + if (isset($this->pendingAggregates[$alias][$index])) { $agg = $this->pendingAggregates[$alias][$index][3]; - + } $record->mapValue($agg, $value); } } - if($name == $root) { - + if ($name == $root) { // add record into root collection $coll->add($record); unset($previd); @@ -490,12 +490,12 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { $prev = $this->addRelated($prev, $name, $record); } - + // following statement is needed to ensure that mappings // are being done properly when the result set doesn't // contain the rows in 'right order' - - if($prev[$name] !== $record) + + if ($prev[$name] !== $record) $prev[$name] = $record; } @@ -505,7 +505,7 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { return $coll; } - /** + /** * initRelation * * @param array $prev @@ -518,18 +518,19 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { $tmp = explode('.', $path); $alias = end($tmp); - if( ! isset($prev[$pointer]) ) + if ( ! isset($prev[$pointer]) ) { return $prev; - + } $fk = $this->tables[$pointer]->getRelation($alias); - if( ! $fk->isOneToOne()) { - if($prev[$pointer]->getLast() instanceof Doctrine_Record) { - if( ! $prev[$pointer]->getLast()->hasReference($alias)) { + if ( ! $fk->isOneToOne()) { + if ($prev[$pointer]->getLast() instanceof Doctrine_Record) { + if ( ! $prev[$pointer]->getLast()->hasReference($alias)) { $prev[$name] = $this->getCollection($name); $prev[$pointer]->getLast()->initReference($prev[$name],$fk); - } else + } else { $prev[$name] = $prev[$pointer]->getLast()->get($alias); + } } } @@ -551,14 +552,14 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { $fk = $this->tables[$pointer]->getRelation($alias); - if($fk->isOneToOne()) { + if ($fk->isOneToOne()) { $prev[$pointer]->getLast()->set($fk->getAlias(), $record); $prev[$name] = $record; } else { // one-to-many relation or many-to-many relation - if( ! $prev[$pointer]->getLast()->hasReference($alias)) { + if ( ! $prev[$pointer]->getLast()->hasReference($alias)) { $prev[$name] = $this->getCollection($name); $prev[$pointer]->getLast()->initReference($prev[$name], $fk); @@ -573,7 +574,7 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { } /** * isIdentifiable - * returns whether or not a given data row is identifiable (it contains + * returns whether or not a given data row is identifiable (it contains * all id fields specified in the second argument) * * @param array $row @@ -581,14 +582,15 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { * @return boolean */ public function isIdentifiable(array $row, $ids) { - if(is_array($ids)) { - foreach($ids as $id) { - if($row[$id] == null) + if (is_array($ids)) { + foreach ($ids as $id) { + if ($row[$id] == null) return true; } } else { - if( ! isset($row[$ids])) + if ( ! isset($row[$ids])) { return true; + } } return false; } @@ -602,34 +604,35 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { // get the inheritance maps $array = array(); - foreach($this->tables as $alias => $table): + foreach ($this->tables as $alias => $table) { $array[$alias][] = $table->getInheritanceMap(); - endforeach; + }; // apply inheritance maps $str = ""; $c = array(); $index = 0; - foreach($array as $tableAlias => $maps) { - + foreach ($array as $tableAlias => $maps) { $a = array(); - foreach($maps as $map) { + foreach ($maps as $map) { $b = array(); - foreach($map as $field => $value) { - if($index > 0) + foreach ($map as $field => $value) { + if ($index > 0) { $b[] = '(' . $tableAlias . '.' . $field . ' = ' . $value . ' OR ' . $tableAlias . '.' . $field . ' IS NULL)'; - else + } else { $b[] = $tableAlias . '.' . $field . ' = ' . $value; + } } - - if( ! empty($b)) + + if ( ! empty($b)) { $a[] = implode(' AND ', $b); + } } - if( ! empty($a)) + if ( ! empty($a)) { $c[] = implode(' AND ', $a); - + } $index++; } @@ -646,12 +649,12 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { */ public function parseData(PDOStatement $stmt) { $array = array(); - - while($data = $stmt->fetch(PDO::FETCH_ASSOC)): + + while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { /** * parse the data into two-dimensional array */ - foreach($data as $key => $value): + foreach ($data as $key => $value) { $e = explode('__', $key); $field = strtolower(array_pop($e)); @@ -660,9 +663,9 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { $data[$component][$field] = $value; unset($data[$key]); - endforeach; + }; $array[] = $data; - endwhile; + }; $stmt->closeCursor(); return $array; @@ -674,9 +677,9 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { * @return Doctrine_Table|boolean */ public function getTable($name) { - if(isset($this->tables[$name])) + if (isset($this->tables[$name])) { return $this->tables[$name]; - + } return false; } /** @@ -686,4 +689,3 @@ abstract class Doctrine_Hydrate extends Doctrine_Access { return Doctrine_Lib::formatSql($this->getQuery()); } } - diff --git a/lib/Doctrine/Hydrate/Alias.php b/lib/Doctrine/Hydrate/Alias.php index 3e36ef5a6..ecca99887 100644 --- a/lib/Doctrine/Hydrate/Alias.php +++ b/lib/Doctrine/Hydrate/Alias.php @@ -31,9 +31,9 @@ * @author Konsta Vesterinen */ class Doctrine_Hydrate_Alias { - + protected $shortAliases = array(); - + protected $shortAliasIndexes = array(); public function clear() { @@ -42,12 +42,12 @@ class Doctrine_Hydrate_Alias { } public function generateNewAlias($alias) { - if(isset($this->shortAliases[$alias])) { + if (isset($this->shortAliases[$alias])) { // generate a new alias $name = substr($alias, 0, 1); $i = ((int) substr($alias, 1)); - if($i == 0) + if ($i == 0) $i = 1; $newIndex = ($this->shortAliasIndexes[$name] + $i); @@ -62,9 +62,9 @@ class Doctrine_Hydrate_Alias { return (isset($this->shortAliases[$tableName])); } public function getShortAliasIndex($alias) { - if( ! isset($this->shortAliasIndexes[$alias])) + if ( ! isset($this->shortAliasIndexes[$alias])) { return 0; - + } return $this->shortAliasIndexes[$alias]; } public function generateShortAlias($tableName) { @@ -72,10 +72,10 @@ class Doctrine_Hydrate_Alias { $alias = $char; - if( ! isset($this->shortAliasIndexes[$alias])) + if ( ! isset($this->shortAliasIndexes[$alias])) { $this->shortAliasIndexes[$alias] = 1; - - while(isset($this->shortAliases[$alias])) { + } + while (isset($this->shortAliases[$alias])) { $alias = $char . ++$this->shortAliasIndexes[$alias]; } $this->shortAliases[$alias] = $tableName; @@ -86,9 +86,9 @@ class Doctrine_Hydrate_Alias { public function getShortAlias($tableName) { $alias = array_search($tableName, $this->shortAliases); - if($alias !== false) + if ($alias !== false) { return $alias; - + } return $this->generateShortAlias($tableName); } } diff --git a/lib/Doctrine/Identifier.php b/lib/Doctrine/Identifier.php index 0d8d65615..520513654 100644 --- a/lib/Doctrine/Identifier.php +++ b/lib/Doctrine/Identifier.php @@ -21,14 +21,14 @@ /** * Doctrine_Identifier * - * @author Konsta Vesterinen - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Identifier { /** * constant for auto_increment identifier @@ -47,4 +47,3 @@ class Doctrine_Identifier { */ const COMPOSITE = 4; } - diff --git a/lib/Doctrine/Import.php b/lib/Doctrine/Import.php index eacf2120d..e6f4004b0 100644 --- a/lib/Doctrine/Import.php +++ b/lib/Doctrine/Import.php @@ -1,177 +1,177 @@ -. - */ -Doctrine::autoload('Doctrine_Connection_Module'); -/** - * class Doctrine_Import - * Main responsible of performing import operation. Delegates database schema - * reading to a reader object and passes the result to a builder object which - * builds a Doctrine data model. - * - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - * @author Jukka Hassinen - */ -class Doctrine_Import extends Doctrine_Connection_Module -{ - protected $sql = array(); - /** - * lists all databases - * - * @return array - */ - public function listDatabases() - { - 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 - * - * @return array - */ - public function listFunctions() - { - 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 - * - * @param string|null $database - * @return array - */ - public function listTriggers($database = null) - { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); - } - /** - * 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.'); - } - - return $this->conn->fetchColumn($this->sql['listSequences']); - } - /** - * lists table constraints - * - * @param string $table database table name - * @return array - */ - public function listTableConstraints($table) - { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); - } - /** - * lists table constraints - * - * @param string $table database table name - * @return array - */ - public function listTableColumns($table) - { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); - } - /** - * lists table constraints - * - * @param string $table database table name - * @return array - */ - public function listTableIndexes($table) - { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); - } - /** - * lists tables - * - * @param string|null $database - * @return array - */ - public function listTables($database = null) - { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); - } - /** - * lists table triggers - * - * @param string $table database table name - * @return array - */ - public function listTableTriggers($table) - { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); - } - /** - * lists table views - * - * @param string $table database table name - * @return array - */ - public function listTableViews($table) - { - throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); - } - /** - * lists database users - * - * @return array - */ - public function listUsers() - { - 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 - * - * @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.'); - } - - return $this->conn->fetchColumn($this->sql['listViews']); - } -} +. + */ +Doctrine::autoload('Doctrine_Connection_Module'); +/** + * class Doctrine_Import + * Main responsible of performing import operation. Delegates database schema + * reading to a reader object and passes the result to a builder object which + * builds a Doctrine data model. + * + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + * @author Jukka Hassinen + */ +class Doctrine_Import extends Doctrine_Connection_Module +{ + protected $sql = array(); + /** + * lists all databases + * + * @return array + */ + public function listDatabases() + { + 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 + * + * @return array + */ + public function listFunctions() + { + 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 + * + * @param string|null $database + * @return array + */ + public function listTriggers($database = null) + { + throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + } + /** + * 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.'); + } + + return $this->conn->fetchColumn($this->sql['listSequences']); + } + /** + * lists table constraints + * + * @param string $table database table name + * @return array + */ + public function listTableConstraints($table) + { + throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + } + /** + * lists table constraints + * + * @param string $table database table name + * @return array + */ + public function listTableColumns($table) + { + throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + } + /** + * lists table constraints + * + * @param string $table database table name + * @return array + */ + public function listTableIndexes($table) + { + throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + } + /** + * lists tables + * + * @param string|null $database + * @return array + */ + public function listTables($database = null) + { + throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + } + /** + * lists table triggers + * + * @param string $table database table name + * @return array + */ + public function listTableTriggers($table) + { + throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + } + /** + * lists table views + * + * @param string $table database table name + * @return array + */ + public function listTableViews($table) + { + throw new Doctrine_Import_Exception(__FUNCTION__ . ' not supported by this driver.'); + } + /** + * lists database users + * + * @return array + */ + public function listUsers() + { + 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 + * + * @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.'); + } + + return $this->conn->fetchColumn($this->sql['listViews']); + } +} diff --git a/lib/Doctrine/Import/Builder.php b/lib/Doctrine/Import/Builder.php index b33fbec13..5f0724871 100644 --- a/lib/Doctrine/Import/Builder.php +++ b/lib/Doctrine/Import/Builder.php @@ -1,157 +1,157 @@ -. - */ - -/** - * Doctrine_Import_Builder - * Import builder is responsible of building Doctrine ActiveRecord classes - * based on a database schema. - * - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - * @author Jukka Hassinen - */ -class Doctrine_Import_Builder { - - private $path = ''; - - private $suffix = '.php'; - - private static $tpl; - - public function __construct() { - if( ! isset(self::$tpl)) - self::$tpl = file_get_contents(Doctrine::getPath() - . DIRECTORY_SEPARATOR . 'Doctrine' - . DIRECTORY_SEPARATOR . 'Import' - . DIRECTORY_SEPARATOR . 'Builder' - . DIRECTORY_SEPARATOR . 'Record.tpl'); - } - - /** - * - * @param string path - * @return - * @access public - */ - public function setTargetPath($path) { - if( ! file_exists($path)) { - mkdir($path, 0777); - } - - $this->path = $path; - } - public function getTargetPath() { - return $this->path; - } - /** - * - * @param string path - * @return - * @access public - */ - public function setFileSuffix($suffix) { - $this->suffix = $suffix; - } - public function getFileSuffix() { - return $this->suffix; - } - - - public function buildRecord(Doctrine_Schema_Table $table) { - if (empty($this->path)) - throw new Doctrine_Import_Builder_Exception('No build target directory set.'); - - if (is_writable($this->path) === false) - throw new Doctrine_Import_Builder_Exception('Build target directory ' . $this->path . ' is not writable.'); - - $created = date('l dS \of F Y h:i:s A'); - $className = Doctrine::classify($table->get('name')); - $fileName = $this->path . DIRECTORY_SEPARATOR . $className . $this->suffix; - $columns = array(); - - $i = 0; - - foreach($table as $name => $column) { - - $columns[$i] = ' $this->hasColumn(\'' . $column['name'] . '\', \'' . $column['type'] . '\''; - if($column['length']) - $columns[$i] .= ', ' . $column['length']; - else - $columns[$i] .= ', null'; - - $a = array(); - - if($column['default']) { - $a[] = '\'default\' => ' . var_export($column['default'], true); - } - if($column['notnull']) { - $a[] = '\'notnull\' => true'; - } - if($column['primary']) { - $a[] = '\'primary\' => true'; - } - if($column['autoinc']) { - $a[] = '\'autoincrement\' => true'; - } - if($column['unique']) { - $a[] = '\'unique\' => true'; - } - - if( ! empty($a)) - $columns[$i] .= ', ' . 'array(' . implode(', -', $a) . ')'; - - $columns[$i] .= ');'; - - if($i < (count($table) - 1)) - $columns[$i] .= ' -'; - $i++; - } - - $content = sprintf(self::$tpl, $created, $className, implode('', $columns)); - - $bytes = file_put_contents($fileName, $content); - - - if($bytes === false) - throw new Doctrine_Import_Builder_Exception("Couldn't write file " . $fileName); - } - /** - * - * @param Doctrine_Schema_Object $schema - * @throws Doctrine_Import_Exception - * @return void - */ - public function build(Doctrine_Schema_Object $schema) { - foreach($schema->getDatabases() as $database){ - foreach($database->getTables() as $table){ - $this->buildRecord($table); - } - } - } - -} +. + */ + +/** + * Doctrine_Import_Builder + * Import builder is responsible of building Doctrine ActiveRecord classes + * based on a database schema. + * + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + * @author Jukka Hassinen + */ +class Doctrine_Import_Builder { + + private $path = ''; + + private $suffix = '.php'; + + private static $tpl; + + public function __construct() { + if ( ! isset(self::$tpl)) { + self::$tpl = file_get_contents(Doctrine::getPath() + . DIRECTORY_SEPARATOR . 'Doctrine' + . DIRECTORY_SEPARATOR . 'Import' + . DIRECTORY_SEPARATOR . 'Builder' + . DIRECTORY_SEPARATOR . 'Record.tpl'); + } + } + + /** + * + * @param string path + * @return + * @access public + */ + public function setTargetPath($path) { + if ( ! file_exists($path)) { + mkdir($path, 0777); + } + + $this->path = $path; + } + public function getTargetPath() { + return $this->path; + } + /** + * + * @param string path + * @return + * @access public + */ + public function setFileSuffix($suffix) { + $this->suffix = $suffix; + } + public function getFileSuffix() { + return $this->suffix; + } + + public function buildRecord(Doctrine_Schema_Table $table) { + if (empty($this->path)) { + throw new Doctrine_Import_Builder_Exception('No build target directory set.'); + } + if (is_writable($this->path) === false) { + throw new Doctrine_Import_Builder_Exception('Build target directory ' . $this->path . ' is not writable.'); + } + $created = date('l dS \of F Y h:i:s A'); + $className = Doctrine::classify($table->get('name')); + $fileName = $this->path . DIRECTORY_SEPARATOR . $className . $this->suffix; + $columns = array(); + + $i = 0; + + foreach ($table as $name => $column) { + $columns[$i] = ' $this->hasColumn(\'' . $column['name'] . '\', \'' . $column['type'] . '\''; + if ($column['length']) { + $columns[$i] .= ', ' . $column['length']; + } else { + $columns[$i] .= ', null'; + } + + $a = array(); + + if ($column['default']) { + $a[] = '\'default\' => ' . var_export($column['default'], true); + } + if ($column['notnull']) { + $a[] = '\'notnull\' => true'; + } + if ($column['primary']) { + $a[] = '\'primary\' => true'; + } + if ($column['autoinc']) { + $a[] = '\'autoincrement\' => true'; + } + if ($column['unique']) { + $a[] = '\'unique\' => true'; + } + + if ( ! empty($a)) { + $columns[$i] .= ', ' . 'array(' . implode(', +', $a) . ')'; + } + $columns[$i] .= ');'; + + if ($i < (count($table) - 1)) { + $columns[$i] .= ' +'; + } + $i++; + } + + $content = sprintf(self::$tpl, $created, $className, implode('', $columns)); + + $bytes = file_put_contents($fileName, $content); + + if ($bytes === false) + throw new Doctrine_Import_Builder_Exception("Couldn't write file " . $fileName); + } + /** + * + * @param Doctrine_Schema_Object $schema + * @throws Doctrine_Import_Exception + * @return void + */ + public function build(Doctrine_Schema_Object $schema) { + foreach ($schema->getDatabases() as $database){ + foreach ($database->getTables() as $table){ + $this->buildRecord($table); + } + } + } + +} diff --git a/lib/Doctrine/Import/Firebird.php b/lib/Doctrine/Import/Firebird.php index b547c7855..9d8dff710 100644 --- a/lib/Doctrine/Import/Firebird.php +++ b/lib/Doctrine/Import/Firebird.php @@ -109,7 +109,7 @@ class Doctrine_Import_Firebird extends Doctrine_Import { WHERE RDB$SYSTEM_FLAG IS NULL OR RDB$SYSTEM_FLAG = 0'; - if( ! is_null($table)) { + if ( ! is_null($table)) { $table = $db->quote(strtoupper($table), 'text'); $query .= 'WHERE UPPER(RDB$RELATION_NAME) = ' . $table; } diff --git a/lib/Doctrine/Import/Mysql.php b/lib/Doctrine/Import/Mysql.php index 86f5150b4..769fbb593 100644 --- a/lib/Doctrine/Import/Mysql.php +++ b/lib/Doctrine/Import/Mysql.php @@ -143,7 +143,7 @@ class Doctrine_Import_Mysql extends Doctrine_Import { $description = array(); foreach ($result as $key => $val2) { $val = array(); - foreach(array_keys($val2) as $valKey){ // lowercase the key names + foreach (array_keys($val2) as $valKey){ // lowercase the key names $val[strtolower($valKey)] = $val2[$valKey]; } $description = array( diff --git a/lib/Doctrine/Import/Reader.php b/lib/Doctrine/Import/Reader.php index 6c9a529e6..aadb25c92 100644 --- a/lib/Doctrine/Import/Reader.php +++ b/lib/Doctrine/Import/Reader.php @@ -1,63 +1,57 @@ -. - */ - -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ -/** - * class Doctrine_Import_Reader - * Is responsible of reading a database definitions from a source and costructing a - * database schema - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -abstract class Doctrine_Import_Reader -{ - - /** Aggregations: */ - - /** Compositions: */ - - /*** Attributes: ***/ - - - /** - * - * @return Doctrine_Schema - * @abstract - * @access public - */ - abstract public function read( ); - - - - - -} // end of Doctrine_Import_Reader - +. + */ + +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ +/** + * class Doctrine_Import_Reader + * Is responsible of reading a database definitions from a source and costructing a + * database schema + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +abstract class Doctrine_Import_Reader +{ + + /** Aggregations: */ + + /** Compositions: */ + + /*** Attributes: ***/ + + /** + * + * @return Doctrine_Schema + * @abstract + * @access public + */ + abstract public function read( ); + +} // end of Doctrine_Import_Reader diff --git a/lib/Doctrine/Import/Reader/Db.php b/lib/Doctrine/Import/Reader/Db.php index 0845f5d77..86ec03bb5 100644 --- a/lib/Doctrine/Import/Reader/Db.php +++ b/lib/Doctrine/Import/Reader/Db.php @@ -1,106 +1,101 @@ -. - */ -Doctrine::autoload('Doctrine_Import_Reader'); -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ - */ -/** - * class Doctrine_Import_Reader_Db - * Reads a database using the given PDO connection and constructs a database - * schema - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Import_Reader_Db extends Doctrine_Import_Reader -{ - - /** Aggregations: */ - - /** Compositions: */ - - /*** Attributes: ***/ - - /** - * @access private - */ - private $pdo; - - - /** - * - * @param object pdo * @return - * @access public - */ - public function setPdo( $pdo ) { - - } // end of member function setPdo - - - /** - * - * @return Doctrine_Schema - * @access public - */ - public function read( ) - { - $dataDict = Doctrine_Manager::getInstance()->getCurrentConnection()->getDataDict(); - - $schema = new Doctrine_Schema(); /* @todo FIXME i am incomplete*/ - $db = new Doctrine_Schema_Database(); - $schema->addDatabase($db); - - $dbName = 'XXtest'; // @todo FIXME where should we get - - $db->set("name",$dbName); - $tableNames = $dataDict->listTables(); - foreach($tableNames as $tableName){ - $table = new Doctrine_Schema_Table(); - $table->set("name",$tableName); - $tableColumns = $dataDict->listTableColumns($tableName); - foreach($tableColumns as $tableColumn){ - $table->addColumn($tableColumn); - } - $db->addTable($table); - if ($fks = $dataDict->listTableConstraints($tableName)){ - foreach($fks as $fk){ - $relation = new Doctrine_Schema_Relation(); - $relation->setRelationBetween($fk['referencingColumn'],$fk['referencedTable'],$fk['referencedColumn']); - $table->setRelation($relation); - } - } - } - - return $schema; - } - - - -} // end of Doctrine_Import_Reader_Db - +. + */ +Doctrine::autoload('Doctrine_Import_Reader'); +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ + */ +/** + * class Doctrine_Import_Reader_Db + * Reads a database using the given PDO connection and constructs a database + * schema + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Import_Reader_Db extends Doctrine_Import_Reader +{ + + /** Aggregations: */ + + /** Compositions: */ + + /*** Attributes: ***/ + + /** + * @access private + */ + private $pdo; + + /** + * + * @param object pdo * @return + * @access public + */ + public function setPdo( $pdo ) { + + } // end of member function setPdo + + /** + * + * @return Doctrine_Schema + * @access public + */ + public function read( ) + { + $dataDict = Doctrine_Manager::getInstance()->getCurrentConnection()->getDataDict(); + + $schema = new Doctrine_Schema(); /* @todo FIXME i am incomplete*/ + $db = new Doctrine_Schema_Database(); + $schema->addDatabase($db); + + $dbName = 'XXtest'; // @todo FIXME where should we get + + $db->set("name",$dbName); + $tableNames = $dataDict->listTables(); + foreach ($tableNames as $tableName){ + $table = new Doctrine_Schema_Table(); + $table->set("name",$tableName); + $tableColumns = $dataDict->listTableColumns($tableName); + foreach ($tableColumns as $tableColumn){ + $table->addColumn($tableColumn); + } + $db->addTable($table); + if ($fks = $dataDict->listTableConstraints($tableName)){ + foreach ($fks as $fk){ + $relation = new Doctrine_Schema_Relation(); + $relation->setRelationBetween($fk['referencingColumn'],$fk['referencedTable'],$fk['referencedColumn']); + $table->setRelation($relation); + } + } + } + + return $schema; + } + +} // end of Doctrine_Import_Reader_Db diff --git a/lib/Doctrine/Import/Reader/Exception.php b/lib/Doctrine/Import/Reader/Exception.php index b9987aa78..9623f6f31 100644 --- a/lib/Doctrine/Import/Reader/Exception.php +++ b/lib/Doctrine/Import/Reader/Exception.php @@ -1,53 +1,47 @@ -. - */ - -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ -/** - * class Doctrine_Import_Reader_Exception - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Import_Reader_Exception -{ - - /** Aggregations: */ - - /** Compositions: */ - - /*** Attributes: ***/ - - - - - - -} // end of Doctrine_Import_Reader_Exception - +. + */ + +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ +/** + * class Doctrine_Import_Reader_Exception + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Import_Reader_Exception +{ + + /** Aggregations: */ + + /** Compositions: */ + + /*** Attributes: ***/ + +} // end of Doctrine_Import_Reader_Exception diff --git a/lib/Doctrine/Import/Reader/Propel.php b/lib/Doctrine/Import/Reader/Propel.php index 4c7739b6a..dc3cc532f 100644 --- a/lib/Doctrine/Import/Reader/Propel.php +++ b/lib/Doctrine/Import/Reader/Propel.php @@ -1,68 +1,64 @@ -. - */ -Doctrine::autoload('Doctrine_Import_Reader'); -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ - */ -/** - * class Doctrine_Import_Reader_Xml_Propel - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Import_Reader_Xml_Propel extends Doctrine_Import_Reader -{ - - /** Aggregations: */ - - /** Compositions: */ - - /*** Attributes: ***/ - - /** - * @access private - */ - private $xml; - - - /** - * - * @param string xml * @return - * @access public - */ - public function setXml( $xml ) { - - } // end of member function setXml - - public function read() { } - - - -} // end of Doctrine_Import_Reader_Xml_Propel - +. + */ +Doctrine::autoload('Doctrine_Import_Reader'); +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ + */ +/** + * class Doctrine_Import_Reader_Xml_Propel + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Import_Reader_Xml_Propel extends Doctrine_Import_Reader +{ + + /** Aggregations: */ + + /** Compositions: */ + + /*** Attributes: ***/ + + /** + * @access private + */ + private $xml; + + /** + * + * @param string xml * @return + * @access public + */ + public function setXml( $xml ) { + + } // end of member function setXml + + public function read() { } + +} // end of Doctrine_Import_Reader_Xml_Propel diff --git a/lib/Doctrine/Import/Sqlite.php b/lib/Doctrine/Import/Sqlite.php index bdd1b3e4f..5f3aa67d5 100644 --- a/lib/Doctrine/Import/Sqlite.php +++ b/lib/Doctrine/Import/Sqlite.php @@ -136,7 +136,7 @@ class Doctrine_Import_Sqlite extends Doctrine_Import { $description = array(); $columns = array(); - foreach($result as $key => $val) { + foreach ($result as $key => $val) { $description = array( 'name' => $val['name'], 'type' => $val['type'], @@ -159,7 +159,7 @@ class Doctrine_Import_Sqlite extends Doctrine_Import { $result = $this->dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC); $indexes = array(); - foreach($result as $key => $val) { + foreach ($result as $key => $val) { } } @@ -179,7 +179,7 @@ class Doctrine_Import_Sqlite extends Doctrine_Import { $data = $stmt->fetchAll(PDO::FETCH_COLUMN); - foreach($data as $table) { + foreach ($data as $table) { $tables[] = new Doctrine_Schema_Table(array('name' => $table)); } return $tables; diff --git a/lib/Doctrine/Lib.php b/lib/Doctrine/Lib.php index a49362199..7696a5167 100644 --- a/lib/Doctrine/Lib.php +++ b/lib/Doctrine/Lib.php @@ -1,5 +1,5 @@ count(); $queries = false; - if($connection->getDBH() instanceof Doctrine_Db) { + if ($connection->getDBH() instanceof Doctrine_Db) { $handler = "Doctrine Database Handler"; $queries = count($connection->getDBH()->getQueries()); $sum = array_sum($connection->getDBH()->getExecTimes()); - } elseif($connection->getDBH() instanceof PDO) { + } elseif ($connection->getDBH() instanceof PDO) { $handler = "PHP Native PDO Driver"; - } else + } else { $handler = "Unknown Database Handler"; + } $r[] = "DB Handler : ".$handler; - if($queries) { + if ($queries) { $r[] = "Executed Queries : ".$queries; $r[] = "Sum of Exec Times : ".$sum; } @@ -150,7 +151,7 @@ class Doctrine_Lib { $l = str_replace(" LIMIT ", " LIMIT
",$l); $l = str_replace(" OFFSET ", " OFFSET
",$l); $l = str_replace(" ", "
",$l); - + return $l; } /** @@ -162,11 +163,10 @@ class Doctrine_Lib { $r[] = "
";
         $r[] = get_class($collection);
 
-        foreach($collection as $key => $record) {
+        foreach ($collection as $key => $record) {
             $r[] = "Key : ".$key." ID : ".$record->obtainIdentifier();
         }
         $r[] = "
"; return implode("\n",$r); } } - diff --git a/lib/Doctrine/Locking/Exception.php b/lib/Doctrine/Locking/Exception.php index 948284c12..228210bd9 100644 --- a/lib/Doctrine/Locking/Exception.php +++ b/lib/Doctrine/Locking/Exception.php @@ -1,16 +1,15 @@ - - */ -class Doctrine_Locking_Exception extends Doctrine_Exception {} - + + */ +class Doctrine_Locking_Exception extends Doctrine_Exception {} diff --git a/lib/Doctrine/Locking/Manager/Pessimistic.php b/lib/Doctrine/Locking/Manager/Pessimistic.php index ce0b570e2..f8366e356 100644 --- a/lib/Doctrine/Locking/Manager/Pessimistic.php +++ b/lib/Doctrine/Locking/Manager/Pessimistic.php @@ -1,284 +1,281 @@ -. - */ -/** - * Offline locking of records comes in handy where you need to make sure that - * a time-consuming task on a record or many records, which is spread over several - * page requests can't be interfered by other users. - * - * @link www.phpdoctrine.com - * @author Roman Borschel - * @author Pierre Minnieur - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @package Doctrine - * @category Object Relational Mapping - * @version $Revision$ - */ -class Doctrine_Locking_Manager_Pessimistic { - /** - * The conn that is used by the locking manager - * - * @var Doctrine_Connection object - */ - private $conn; - /** - * The database table name for the lock tracking - */ - private $_lockTable = 'doctrine_lock_tracking'; - - /** - * 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. - * - * @param Doctrine_Connection $conn The database connection to use - */ - public function __construct(Doctrine_Connection $conn) { - $this->conn = $conn; - - if ($this->conn->getAttribute(Doctrine::ATTR_CREATE_TABLES) === true) { - $columns = array(); - $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['user_ident'] = array('type' => 'string', - 'length' => 50, - '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) { - - } - } - } - - /** - * 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 - */ - public function getLock(Doctrine_Record $record, $userIdent) { - $objectType = $record->getTable()->getComponentName(); - $key = $record->obtainIdentifier(); - - $gotLock = false; - - if (is_array($key)) { - // Composite key - $key = implode('|', $key); - } - - try { - $dbh = $this->conn->getDBH(); - $dbh->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->bindParam(':object_type', $objectType); - $stmt->bindParam(':object_key', $key); - $stmt->bindParam(':user_ident', $userIdent); - $stmt->bindParam(':ts_obtained', time()); - - try { - $stmt->execute(); - $gotLock = true; - - // 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) { - $lockingUserIdent = $this->_getLockingUserIdent($objectType, $key); - if ($lockingUserIdent !== null && $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->bindParam(':ts', time()); - $stmt->bindParam(':object_type', $objectType); - $stmt->bindParam(':object_key', $key); - $stmt->bindParam(':user_ident', $lockingUserIdent); - $stmt->execute(); - } - } - $dbh->commit(); - } catch (Exception $pdoe) { - $dbh->rollback(); - throw new Doctrine_Locking_Exception($pdoe->getMessage()); - } - - return $gotLock; - } - - /** - * 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 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->obtainIdentifier(); - - if (is_array($key)) { - // Composite key - $key = implode('|', $key); - } - - try { - $dbh = $this->conn->getDbh(); - $stmt = $dbh->prepare("DELETE FROM $this->_lockTable WHERE - object_type = :object_type AND - object_key = :object_key AND - user_ident = :user_ident"); - $stmt->bindParam(':object_type', $objectType); - $stmt->bindParam(':object_key', $key); - $stmt->bindParam(':user_ident', $userIdent); - $stmt->execute(); - - $count = $stmt->rowCount(); - - return ($count > 0); - } catch (PDOException $pdoe) { - throw new Doctrine_Locking_Exception($pdoe->getMessage()); - } - } - - /** - * 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 - * @return mixed 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) { - if (is_array($key)) { - // Composite key - $key = implode('|', $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->bindParam(':object_type', $objectType); - $stmt->bindParam(':object_key', $key); - $success = $stmt->execute(); - - if (!$success) { - throw new Doctrine_Locking_Exception("Failed to determine locking user"); - } - - $userIdent = $stmt->fetchColumn(); - } catch (PDOException $pdoe) { - throw new Doctrine_Locking_Exception($pdoe->getMessage()); - } - - return $userIdent; - } - - /** - * 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. - */ - public function getLockOwner($lockedRecord) { - $objectType = $lockedRecord->getTable()->getComponentName(); - $key = $lockedRecord->obtainIdentifier(); - return $this->_getLockingUserIdent($objectType, $key); - } - - /** - * 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 - * @throws Doctrine_Locking_Exception If the release process failed due to database errors - */ - public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = null) { - $age = time() - $age; - - try { - $dbh = $this->conn->getDbh(); - $stmt = $dbh->prepare('DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age'); - $stmt->bindParam(':age', $age); - $query = 'DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age'; - if ($objectType) { - $query .= ' AND object_type = :object_type'; - } - if ($userIdent) { - $query .= ' AND user_ident = :user_ident'; - } - $stmt = $dbh->prepare($query); - $stmt->bindParam(':age', $age); - if ($objectType) { - $stmt->bindParam(':object_type', $objectType); - } - if ($userIdent) { - $stmt->bindParam(':user_ident', $userIdent); - } - $stmt->execute(); - - $count = $stmt->rowCount(); - - return $count; - } catch (PDOException $pdoe) { - throw new Doctrine_Locking_Exception($pdoe->getMessage()); - } - } - -} - - - +. + */ +/** + * Offline locking of records comes in handy where you need to make sure that + * a time-consuming task on a record or many records, which is spread over several + * page requests can't be interfered by other users. + * + * @link www.phpdoctrine.com + * @author Roman Borschel + * @author Pierre Minnieur + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @package Doctrine + * @category Object Relational Mapping + * @version $Revision$ + */ +class Doctrine_Locking_Manager_Pessimistic { + /** + * The conn that is used by the locking manager + * + * @var Doctrine_Connection object + */ + private $conn; + /** + * The database table name for the lock tracking + */ + private $_lockTable = 'doctrine_lock_tracking'; + + /** + * 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. + * + * @param Doctrine_Connection $conn The database connection to use + */ + public function __construct(Doctrine_Connection $conn) { + $this->conn = $conn; + + if ($this->conn->getAttribute(Doctrine::ATTR_CREATE_TABLES) === true) { + $columns = array(); + $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['user_ident'] = array('type' => 'string', + 'length' => 50, + '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) { + + } + } + } + + /** + * 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 + */ + public function getLock(Doctrine_Record $record, $userIdent) { + $objectType = $record->getTable()->getComponentName(); + $key = $record->obtainIdentifier(); + + $gotLock = false; + + if (is_array($key)) { + // Composite key + $key = implode('|', $key); + } + + try { + $dbh = $this->conn->getDBH(); + $dbh->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->bindParam(':object_type', $objectType); + $stmt->bindParam(':object_key', $key); + $stmt->bindParam(':user_ident', $userIdent); + $stmt->bindParam(':ts_obtained', time()); + + try { + $stmt->execute(); + $gotLock = true; + + // 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) { + $lockingUserIdent = $this->_getLockingUserIdent($objectType, $key); + if ($lockingUserIdent !== null && $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->bindParam(':ts', time()); + $stmt->bindParam(':object_type', $objectType); + $stmt->bindParam(':object_key', $key); + $stmt->bindParam(':user_ident', $lockingUserIdent); + $stmt->execute(); + } + } + $dbh->commit(); + } catch (Exception $pdoe) { + $dbh->rollback(); + throw new Doctrine_Locking_Exception($pdoe->getMessage()); + } + + return $gotLock; + } + + /** + * 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 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->obtainIdentifier(); + + if (is_array($key)) { + // Composite key + $key = implode('|', $key); + } + + try { + $dbh = $this->conn->getDbh(); + $stmt = $dbh->prepare("DELETE FROM $this->_lockTable WHERE + object_type = :object_type AND + object_key = :object_key AND + user_ident = :user_ident"); + $stmt->bindParam(':object_type', $objectType); + $stmt->bindParam(':object_key', $key); + $stmt->bindParam(':user_ident', $userIdent); + $stmt->execute(); + + $count = $stmt->rowCount(); + + return ($count > 0); + } catch (PDOException $pdoe) { + throw new Doctrine_Locking_Exception($pdoe->getMessage()); + } + } + + /** + * 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 + * @return mixed 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) { + if (is_array($key)) { + // Composite key + $key = implode('|', $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->bindParam(':object_type', $objectType); + $stmt->bindParam(':object_key', $key); + $success = $stmt->execute(); + + if (!$success) { + throw new Doctrine_Locking_Exception("Failed to determine locking user"); + } + + $userIdent = $stmt->fetchColumn(); + } catch (PDOException $pdoe) { + throw new Doctrine_Locking_Exception($pdoe->getMessage()); + } + + return $userIdent; + } + + /** + * 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. + */ + public function getLockOwner($lockedRecord) { + $objectType = $lockedRecord->getTable()->getComponentName(); + $key = $lockedRecord->obtainIdentifier(); + return $this->_getLockingUserIdent($objectType, $key); + } + + /** + * 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 + * @throws Doctrine_Locking_Exception If the release process failed due to database errors + */ + public function releaseAgedLocks($age = 900, $objectType = null, $userIdent = null) { + $age = time() - $age; + + try { + $dbh = $this->conn->getDbh(); + $stmt = $dbh->prepare('DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age'); + $stmt->bindParam(':age', $age); + $query = 'DELETE FROM ' . $this->_lockTable . ' WHERE timestamp_obtained < :age'; + if ($objectType) { + $query .= ' AND object_type = :object_type'; + } + if ($userIdent) { + $query .= ' AND user_ident = :user_ident'; + } + $stmt = $dbh->prepare($query); + $stmt->bindParam(':age', $age); + if ($objectType) { + $stmt->bindParam(':object_type', $objectType); + } + if ($userIdent) { + $stmt->bindParam(':user_ident', $userIdent); + } + $stmt->execute(); + + $count = $stmt->rowCount(); + + return $count; + } catch (PDOException $pdoe) { + throw new Doctrine_Locking_Exception($pdoe->getMessage()); + } + } + +} diff --git a/lib/Doctrine/Manager.php b/lib/Doctrine/Manager.php index 66eb104e6..2b6c59624 100644 --- a/lib/Doctrine/Manager.php +++ b/lib/Doctrine/Manager.php @@ -1,352 +1,351 @@ -. - */ -/** - * - * Doctrine_Manager is the base component of all doctrine based projects. - * It opens and keeps track of all connections (database connections). - * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @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 - */ - private $connections = array(); - /** - * @var array $bound an array containing all components that have a bound connection - */ - private $bound = array(); - /** - * @var integer $index the incremented index - */ - private $index = 0; - /** - * @var integer $currIndex the current connection index - */ - private $currIndex = 0; - /** - * @var string $root root directory - */ - private $root; - /** - * @var Doctrine_Null $null Doctrine_Null object, used for extremely fast null value checking - */ - private $null; - - /** - * constructor - * - * this is private constructor (use getInstance to get an instance of this class) - */ - private function __construct() { - $this->root = dirname(__FILE__); - $this->null = new Doctrine_Null; - - Doctrine_Record::initNullObject($this->null); - Doctrine_Collection::initNullObject($this->null); - Doctrine_Record_Iterator::initNullObject($this->null); - Doctrine_Validator::initNullObject($this->null); - } - /** - * @return Doctrine_Null - */ - final public function getNullObject() { - return $this->null; - } - /** - * setDefaultAttributes - * sets default attributes - * - * @return boolean - */ - final public function setDefaultAttributes() { - static $init = false; - if( ! $init) { - $init = true; - $attributes = array( - Doctrine::ATTR_FETCHMODE => Doctrine::FETCH_IMMEDIATE, - Doctrine::ATTR_BATCH_SIZE => 5, - Doctrine::ATTR_COLL_LIMIT => 5, - Doctrine::ATTR_LISTENER => new Doctrine_EventListener(), - Doctrine::ATTR_LOCKMODE => 1, - Doctrine::ATTR_VLD => false, - Doctrine::ATTR_AUTO_LENGTH_VLD => true, - Doctrine::ATTR_AUTO_TYPE_VLD => true, - Doctrine::ATTR_CREATE_TABLES => true, - Doctrine::ATTR_QUERY_LIMIT => Doctrine::LIMIT_RECORDS, - Doctrine::ATTR_IDXNAME_FORMAT => "%s_idx", - Doctrine::ATTR_SEQNAME_FORMAT => "%s_seq", - Doctrine::ATTR_QUOTE_IDENTIFIER => false, - Doctrine::ATTR_SEQCOL_NAME => 'id', - Doctrine::ATTR_PORTABILITY => Doctrine::PORTABILITY_ALL, - ); - foreach($attributes as $attribute => $value) { - $old = $this->getAttribute($attribute); - if($old === null) - $this->setAttribute($attribute,$value); - } - return true; - } - return false; - } - /** - * returns the root directory of Doctrine - * - * @return string - */ - final public function getRoot() { - return $this->root; - } - /** - * getInstance - * returns an instance of this class - * (this class uses the singleton pattern) - * - * @return Doctrine_Manager - */ - public static function getInstance() { - static $instance; - if( ! isset($instance)) - $instance = new self(); - - return $instance; - } - /** - * connection - * - * if the adapter parameter is set this method acts as - * 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 - * @return Doctrine_Connection - */ - public static function connection($adapter = null, $name = null) { - if($adapter == null) { - return Doctrine_Manager::getInstance()->getCurrentConnection(); - } else { - return Doctrine_Manager::getInstance()->openConnection($adapter, $name); - } - } - /** - * openConnection - * 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 - * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name - * @return Doctrine_Connection - */ - public function openConnection($adapter, $name = null) { - 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"); - - - // initialize the default attributes - $this->setDefaultAttributes(); - - if($name !== null) { - $name = (string) $name; - if(isset($this->connections[$name])) - throw new Doctrine_Manager_Exception("Connection with $name already exists!"); - - } else { - $name = $this->index; - $this->index++; - } - switch($adapter->getAttribute(PDO::ATTR_DRIVER_NAME)): - case 'mysql': - $this->connections[$name] = new Doctrine_Connection_Mysql($this, $adapter); - break; - case 'sqlite': - $this->connections[$name] = new Doctrine_Connection_Sqlite($this, $adapter); - break; - case 'pgsql': - $this->connections[$name] = new Doctrine_Connection_Pgsql($this, $adapter); - break; - case 'oci': - case 'oracle': - $this->connections[$name] = new Doctrine_Connection_Oracle($this, $adapter); - break; - case 'mssql': - $this->connections[$name] = new Doctrine_Connection_Mssql($this, $adapter); - break; - case 'firebird': - $this->connections[$name] = new Doctrine_Connection_Firebird($this, $adapter); - break; - case 'informix': - $this->connections[$name] = new Doctrine_Connection_Informix($this, $adapter); - break; - case 'mock': - $this->connections[$name] = new Doctrine_Connection_Mock($this, $adapter); - break; - default: - throw new Doctrine_Manager_Exception('Unknown connection driver '. $adapter->getAttribute(PDO::ATTR_DRIVER_NAME)); - endswitch; - - - $this->currIndex = $name; - return $this->connections[$name]; - } - public function openSession(PDO $pdo, $name = null) { - return $this->openConnection($pdo, $name); - } - /** - * getConnection - * @param integer $index - * @return object Doctrine_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); - - $this->currIndex = $name; - return $this->connections[$name]; - } - /** - * bindComponent - * 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 - * - * @param string $componentName - * @param string $connectionName - * @return boolean - */ - public function bindComponent($componentName, $connectionName) { - $this->bound[$componentName] = $connectionName; - } - /** - * getConnectionForComponent - * - * @param string $componentName - * @return Doctrine_Connection - */ - public function getConnectionForComponent($componentName = null) { - if(isset($this->bound[$componentName])) - return $this->getConnection($this->bound[$componentName]); - - return $this->getCurrentConnection(); - } - /** - * getTable - * this is the same as Doctrine_Connection::getTable() except - * that it works seamlessly in multi-server/connection environment - * - * @see Doctrine_Connection::getTable() - * @param string $componentName - * @return Doctrine_Table - */ - public function getTable($componentName) { - return $this->getConnectionForComponent($componentName)->getTable($componentName); - } - /** - * closes the connection - * - * @param Doctrine_Connection $connection - * @return void - */ - public function closeConnection(Doctrine_Connection $connection) { - $connection->close(); - unset($connection); - } - /** - * getConnections - * returns all opened connections - * - * @return array - */ - public function getConnections() { - return $this->connections; - } - /** - * setCurrentConnection - * sets the current connection to $key - * - * @param mixed $key the connection key - * @throws InvalidKeyException - * @return void - */ - public function setCurrentConnection($key) { - $key = (string) $key; - if( ! isset($this->connections[$key])) - throw new InvalidKeyException(); - - $this->currIndex = $key; - } - /** - * count - * returns the number of opened connections - * - * @return integer - */ - public function count() { - return count($this->connections); - } - /** - * getIterator - * returns an ArrayIterator that iterates through all connections - * - * @return ArrayIterator - */ - public function getIterator() { - return new ArrayIterator($this->connections); - } - /** - * getCurrentConnection - * returns the current connection - * - * @throws Doctrine_Connection_Exception if there are no open connections - * @return Doctrine_Connection - */ - public function getCurrentConnection() { - $i = $this->currIndex; - if( ! isset($this->connections[$i])) - throw new Doctrine_Connection_Exception(); - - return $this->connections[$i]; - } - /** - * __toString - * 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); - } -} - +. + */ +/** + * + * Doctrine_Manager is the base component of all doctrine based projects. + * It opens and keeps track of all connections (database connections). + * + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @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 + */ + private $connections = array(); + /** + * @var array $bound an array containing all components that have a bound connection + */ + private $bound = array(); + /** + * @var integer $index the incremented index + */ + private $index = 0; + /** + * @var integer $currIndex the current connection index + */ + private $currIndex = 0; + /** + * @var string $root root directory + */ + private $root; + /** + * @var Doctrine_Null $null Doctrine_Null object, used for extremely fast null value checking + */ + private $null; + + /** + * constructor + * + * this is private constructor (use getInstance to get an instance of this class) + */ + private function __construct() { + $this->root = dirname(__FILE__); + $this->null = new Doctrine_Null; + + Doctrine_Record::initNullObject($this->null); + Doctrine_Collection::initNullObject($this->null); + Doctrine_Record_Iterator::initNullObject($this->null); + Doctrine_Validator::initNullObject($this->null); + } + /** + * @return Doctrine_Null + */ + final public function getNullObject() { + return $this->null; + } + /** + * setDefaultAttributes + * sets default attributes + * + * @return boolean + */ + final public function setDefaultAttributes() { + static $init = false; + if ( ! $init) { + $init = true; + $attributes = array( + Doctrine::ATTR_FETCHMODE => Doctrine::FETCH_IMMEDIATE, + Doctrine::ATTR_BATCH_SIZE => 5, + Doctrine::ATTR_COLL_LIMIT => 5, + Doctrine::ATTR_LISTENER => new Doctrine_EventListener(), + Doctrine::ATTR_LOCKMODE => 1, + Doctrine::ATTR_VLD => false, + Doctrine::ATTR_AUTO_LENGTH_VLD => true, + Doctrine::ATTR_AUTO_TYPE_VLD => true, + Doctrine::ATTR_CREATE_TABLES => true, + Doctrine::ATTR_QUERY_LIMIT => Doctrine::LIMIT_RECORDS, + Doctrine::ATTR_IDXNAME_FORMAT => "%s_idx", + Doctrine::ATTR_SEQNAME_FORMAT => "%s_seq", + Doctrine::ATTR_QUOTE_IDENTIFIER => false, + Doctrine::ATTR_SEQCOL_NAME => 'id', + Doctrine::ATTR_PORTABILITY => Doctrine::PORTABILITY_ALL, + ); + foreach ($attributes as $attribute => $value) { + $old = $this->getAttribute($attribute); + if ($old === null) { + $this->setAttribute($attribute,$value); + } + } + return true; + } + return false; + } + /** + * returns the root directory of Doctrine + * + * @return string + */ + final public function getRoot() { + return $this->root; + } + /** + * getInstance + * returns an instance of this class + * (this class uses the singleton pattern) + * + * @return Doctrine_Manager + */ + public static function getInstance() { + static $instance; + if ( ! isset($instance)) { + $instance = new self(); + } + return $instance; + } + /** + * connection + * + * if the adapter parameter is set this method acts as + * 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 + * @return Doctrine_Connection + */ + public static function connection($adapter = null, $name = null) { + if ($adapter == null) { + return Doctrine_Manager::getInstance()->getCurrentConnection(); + } else { + return Doctrine_Manager::getInstance()->openConnection($adapter, $name); + } + } + /** + * openConnection + * 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 + * @throws Doctrine_Manager_Exception if trying to bind a connection with an existing name + * @return Doctrine_Connection + */ + public function openConnection($adapter, $name = null) { + 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"); + } + + // initialize the default attributes + $this->setDefaultAttributes(); + + if ($name !== null) { + $name = (string) $name; + if (isset($this->connections[$name])) { + throw new Doctrine_Manager_Exception("Connection with $name already exists!"); + } + } else { + $name = $this->index; + $this->index++; + } + switch ($adapter->getAttribute(PDO::ATTR_DRIVER_NAME)) { + case 'mysql': + $this->connections[$name] = new Doctrine_Connection_Mysql($this, $adapter); + break; + case 'sqlite': + $this->connections[$name] = new Doctrine_Connection_Sqlite($this, $adapter); + break; + case 'pgsql': + $this->connections[$name] = new Doctrine_Connection_Pgsql($this, $adapter); + break; + case 'oci': + case 'oracle': + $this->connections[$name] = new Doctrine_Connection_Oracle($this, $adapter); + break; + case 'mssql': + $this->connections[$name] = new Doctrine_Connection_Mssql($this, $adapter); + break; + case 'firebird': + $this->connections[$name] = new Doctrine_Connection_Firebird($this, $adapter); + break; + case 'informix': + $this->connections[$name] = new Doctrine_Connection_Informix($this, $adapter); + break; + case 'mock': + $this->connections[$name] = new Doctrine_Connection_Mock($this, $adapter); + break; + default: + throw new Doctrine_Manager_Exception('Unknown connection driver '. $adapter->getAttribute(PDO::ATTR_DRIVER_NAME)); + }; + + $this->currIndex = $name; + return $this->connections[$name]; + } + public function openSession(PDO $pdo, $name = null) { + return $this->openConnection($pdo, $name); + } + /** + * getConnection + * @param integer $index + * @return object Doctrine_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); + } + $this->currIndex = $name; + return $this->connections[$name]; + } + /** + * bindComponent + * 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 + * + * @param string $componentName + * @param string $connectionName + * @return boolean + */ + public function bindComponent($componentName, $connectionName) { + $this->bound[$componentName] = $connectionName; + } + /** + * getConnectionForComponent + * + * @param string $componentName + * @return Doctrine_Connection + */ + public function getConnectionForComponent($componentName = null) { + if (isset($this->bound[$componentName])) { + return $this->getConnection($this->bound[$componentName]); + } + return $this->getCurrentConnection(); + } + /** + * getTable + * this is the same as Doctrine_Connection::getTable() except + * that it works seamlessly in multi-server/connection environment + * + * @see Doctrine_Connection::getTable() + * @param string $componentName + * @return Doctrine_Table + */ + public function getTable($componentName) { + return $this->getConnectionForComponent($componentName)->getTable($componentName); + } + /** + * closes the connection + * + * @param Doctrine_Connection $connection + * @return void + */ + public function closeConnection(Doctrine_Connection $connection) { + $connection->close(); + unset($connection); + } + /** + * getConnections + * returns all opened connections + * + * @return array + */ + public function getConnections() { + return $this->connections; + } + /** + * setCurrentConnection + * sets the current connection to $key + * + * @param mixed $key the connection key + * @throws InvalidKeyException + * @return void + */ + public function setCurrentConnection($key) { + $key = (string) $key; + if ( ! isset($this->connections[$key])) { + throw new InvalidKeyException(); + } + $this->currIndex = $key; + } + /** + * count + * returns the number of opened connections + * + * @return integer + */ + public function count() { + return count($this->connections); + } + /** + * getIterator + * returns an ArrayIterator that iterates through all connections + * + * @return ArrayIterator + */ + public function getIterator() { + return new ArrayIterator($this->connections); + } + /** + * getCurrentConnection + * returns the current connection + * + * @throws Doctrine_Connection_Exception if there are no open connections + * @return Doctrine_Connection + */ + public function getCurrentConnection() { + $i = $this->currIndex; + if ( ! isset($this->connections[$i])) { + throw new Doctrine_Connection_Exception(); + } + return $this->connections[$i]; + } + /** + * __toString + * 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); + } +} diff --git a/lib/Doctrine/Manager/Exception.php b/lib/Doctrine/Manager/Exception.php index f54f9db63..5b87ef65c 100644 --- a/lib/Doctrine/Manager/Exception.php +++ b/lib/Doctrine/Manager/Exception.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Manager_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/Null.php b/lib/Doctrine/Null.php index 71320e658..47742a327 100644 --- a/lib/Doctrine/Null.php +++ b/lib/Doctrine/Null.php @@ -1,5 +1,5 @@ - */ + * + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ final class Doctrine_Null { } diff --git a/lib/Doctrine/Overloadable.php b/lib/Doctrine/Overloadable.php index 1c7f072e9..53bfff61f 100644 --- a/lib/Doctrine/Overloadable.php +++ b/lib/Doctrine/Overloadable.php @@ -1,5 +1,5 @@ 1) { + if (count($parts) > 1) { $ret = array(); - foreach($parts as $part) { + foreach ($parts as $part) { $part = Doctrine_Query::bracketTrim($part, '(', ')'); $ret[] = $this->parse($part); } @@ -25,22 +25,22 @@ abstract class Doctrine_Query_Condition extends Doctrine_Query_Part { } else { $parts = Doctrine_Query::bracketExplode($str, array(' \|\| ', ' OR '), '(', ')'); - if(count($parts) > 1) { + if (count($parts) > 1) { $ret = array(); - foreach($parts as $part) { + foreach ($parts as $part) { $part = Doctrine_Query::bracketTrim($part, '(', ')'); $ret[] = $this->parse($part); } $r = implode(' OR ',$ret); } else { - 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)); - else + } else { return $this->load($parts[0]); + } } } return '(' . $r . ')'; } } - diff --git a/lib/Doctrine/Query/Exception.php b/lib/Doctrine/Query/Exception.php index 390e0f49f..d1e799299 100644 --- a/lib/Doctrine/Query/Exception.php +++ b/lib/Doctrine/Query/Exception.php @@ -2,4 +2,3 @@ require_once(Doctrine::getPath().DIRECTORY_SEPARATOR."Doctrine".DIRECTORY_SEPARATOR."Exception.php"); class Doctrine_Query_Exception extends Doctrine_Exception { } - diff --git a/lib/Doctrine/Query/From.php b/lib/Doctrine/Query/From.php index b94d711e7..150f4a30a 100644 --- a/lib/Doctrine/Query/From.php +++ b/lib/Doctrine/Query/From.php @@ -45,39 +45,39 @@ class Doctrine_Query_From extends Doctrine_Query_Part { $operator = false; - switch(trim($parts[0])) { - case 'INNER': - $operator = ':'; - case 'LEFT': - array_shift($parts); + switch (trim($parts[0])) { + case 'INNER': + $operator = ':'; + case 'LEFT': + array_shift($parts); } $last = ''; - foreach($parts as $k => $part) { + foreach ($parts as $k => $part) { $part = trim($part); - if(empty($part)) { + if (empty($part)) { continue; } $e = explode(' ', $part); - if(end($e) == 'INNER' || end($e) == 'LEFT') + if (end($e) == 'INNER' || end($e) == 'LEFT') { $last = array_pop($e); - + } $part = implode(' ', $e); - foreach(Doctrine_Query::bracketExplode($part, ',') as $reference) { + foreach (Doctrine_Query::bracketExplode($part, ',') as $reference) { $reference = trim($reference); $e = explode('.', $reference); - if($operator) { + if ($operator) { $reference = array_shift($e) . $operator . implode('.', $e); } $table = $this->query->load($reference); - } - + } + $operator = ($last == 'INNER') ? ':' : '.'; } } @@ -86,4 +86,3 @@ class Doctrine_Query_From extends Doctrine_Query_Part { return ( ! empty($this->parts))?implode(", ", $this->parts):''; } } - diff --git a/lib/Doctrine/Query/Groupby.php b/lib/Doctrine/Query/Groupby.php index e77bfad92..d8ce741d3 100644 --- a/lib/Doctrine/Query/Groupby.php +++ b/lib/Doctrine/Query/Groupby.php @@ -1,4 +1,4 @@ -parts))?implode(", ", $this->parts):''; } } - diff --git a/lib/Doctrine/Query/Having.php b/lib/Doctrine/Query/Having.php index 989d0cbbd..ed6ab858d 100644 --- a/lib/Doctrine/Query/Having.php +++ b/lib/Doctrine/Query/Having.php @@ -11,15 +11,14 @@ class Doctrine_Query_Having extends Doctrine_Query_Condition { private function parseAggregateFunction($func) { $pos = strpos($func,"("); - if($pos !== false) { - + if ($pos !== false) { $funcs = array(); $name = substr($func, 0, $pos); $func = substr($func, ($pos + 1), -1); $params = Doctrine_Query::bracketExplode($func, ",", "(", ")"); - foreach($params as $k => $param) { + foreach ($params as $k => $param) { $params[$k] = $this->parseAggregateFunction($param); } @@ -28,7 +27,7 @@ class Doctrine_Query_Having extends Doctrine_Query_Condition { return $funcs; } else { - if( ! is_numeric($func)) { + if ( ! is_numeric($func)) { $a = explode(".",$func); $field = array_pop($a); $reference = implode(".",$a); @@ -71,4 +70,3 @@ class Doctrine_Query_Having extends Doctrine_Query_Condition { return ( ! empty($this->parts))?implode(' AND ', $this->parts):''; } } - diff --git a/lib/Doctrine/Query/Orderby.php b/lib/Doctrine/Query/Orderby.php index b310baa59..0ee106db9 100644 --- a/lib/Doctrine/Query/Orderby.php +++ b/lib/Doctrine/Query/Orderby.php @@ -22,14 +22,14 @@ Doctrine::autoload('Doctrine_Query_Part'); /** * Doctrine_Query_Orderby * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Query_Orderby extends Doctrine_Query_Part { /** * DQL ORDER BY PARSER @@ -41,27 +41,26 @@ class Doctrine_Query_Orderby extends Doctrine_Query_Part { public function parse($str) { $ret = array(); - foreach(explode(',', trim($str)) as $r) { + foreach (explode(',', trim($str)) as $r) { $r = trim($r); $e = explode(' ', $r); $a = explode('.', $e[0]); - - if(count($a) > 1) { + + if (count($a) > 1) { $field = array_pop($a); $reference = implode('.', $a); $name = end($a); - $this->query->load($reference, false); $alias = $this->query->getTableAlias($reference); - $tname = $this->query->getTable($alias)->getTableName(); $r = $alias . '.' . $field; - if(isset($e[1])) + if (isset($e[1])) { $r .= ' '.$e[1]; + } } $ret[] = $r; } @@ -72,4 +71,3 @@ class Doctrine_Query_Orderby extends Doctrine_Query_Part { return ( ! empty($this->parts))?implode(', ', $this->parts):''; } } - diff --git a/lib/Doctrine/Query/Part.php b/lib/Doctrine/Query/Part.php index 0bb1988b7..02c519c64 100644 --- a/lib/Doctrine/Query/Part.php +++ b/lib/Doctrine/Query/Part.php @@ -22,14 +22,14 @@ Doctrine::autoload("Doctrine_Access"); /** * Doctrine_Query_Part * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ abstract class Doctrine_Query_Part extends Doctrine_Access { /** * @var Doctrine_Query $query the query object associated with this parser @@ -61,9 +61,9 @@ abstract class Doctrine_Query_Part extends Doctrine_Access { public function getQuery() { return $this->query; } - /** + /** * add - * + * * @param string $value * @return void */ @@ -75,6 +75,3 @@ abstract class Doctrine_Query_Part extends Doctrine_Access { public function get($name) { } public function set($name, $value) { } } - - - diff --git a/lib/Doctrine/Query/Set.php b/lib/Doctrine/Query/Set.php index 7c7164e43..5b9fd6242 100644 --- a/lib/Doctrine/Query/Set.php +++ b/lib/Doctrine/Query/Set.php @@ -34,7 +34,7 @@ class Doctrine_Query_Set extends Doctrine_Query_Part { $parts = Doctrine_Query::sqlExplode($dql, ','); $result = array(); - foreach($parts as $part) { + foreach ($parts as $part) { $set = Doctrine_Query::sqlExplode($part, '='); $e = explode('.', trim($set[0])); @@ -43,11 +43,11 @@ class Doctrine_Query_Set extends Doctrine_Query_Part { $reference = implode('.', $e); $alias = $this->query->getTableAlias($reference); - + $result[] = $alias . '.' . $field . ' = ' . $set[1]; } return implode(', ', $result); } } -?> + diff --git a/lib/Doctrine/Query/Where.php b/lib/Doctrine/Query/Where.php index 05579dc61..bb0ff04f7 100644 --- a/lib/Doctrine/Query/Where.php +++ b/lib/Doctrine/Query/Where.php @@ -14,23 +14,24 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { $e = Doctrine_Query::sqlExplode($where); - if(count($e) > 1) { + if (count($e) > 1) { $tmp = $e[0].' '.$e[1]; - if(substr($tmp, 0, 6) == 'EXISTS') + if (substr($tmp, 0, 6) == 'EXISTS') { return $this->parseExists($where, true); - elseif(substr($where, 0, 10) == 'NOT EXISTS') + } elseif (substr($where, 0, 10) == 'NOT EXISTS') { return $this->parseExists($where, false); + } } - if(count($e) < 3) { + if (count($e) < 3) { $e = Doctrine_Query::sqlExplode($where, array('=', '<', '>', '!=')); } $r = array_shift($e); $a = explode('.', $r); - if(count($a) > 1) { + if (count($a) > 1) { $field = array_pop($a); $count = count($e); $slice = array_slice($e, -1, 1); @@ -40,11 +41,9 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { $reference = implode('.', $a); $count = count($a); - - $pos = strpos($field, '('); - if($pos !== false) { + if ($pos !== false) { $func = substr($field, 0, $pos); $value = trim(substr($field, ($pos + 1), -1)); @@ -59,28 +58,28 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { $stack = $this->query->getRelationStack(); $relation = end($stack); - + $stack = $this->query->getTableStack(); - switch($func) { - case 'contains': - case 'regexp': - case 'like': - $operator = $this->getOperator($func); + switch ($func) { + case 'contains': + case 'regexp': + case 'like': + $operator = $this->getOperator($func); - if(empty($relation)) - throw new Doctrine_Query_Exception('DQL functions contains/regexp/like can only be used for fields of related components'); - - $where = array(); - foreach($values as $value) { - $where[] = $alias.'.'.$relation->getLocal(). - ' IN (SELECT '.$relation->getForeign(). - ' FROM '.$relation->getTable()->getTableName().' WHERE '.$field.$operator.$value.')'; - } - $where = implode(' AND ', $where); + if (empty($relation)) { + throw new Doctrine_Query_Exception('DQL functions contains/regexp/like can only be used for fields of related components'); + } + $where = array(); + foreach ($values as $value) { + $where[] = $alias.'.'.$relation->getLocal(). + ' IN (SELECT '.$relation->getForeign(). + ' FROM '.$relation->getTable()->getTableName().' WHERE '.$field.$operator.$value.')'; + } + $where = implode(' AND ', $where); break; - default: - throw new Doctrine_Query_Exception('Unknown DQL function: '.$func); + default: + throw new Doctrine_Query_Exception('Unknown DQL function: '.$func); } } else { $table = $this->query->load($reference, false); @@ -89,47 +88,49 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { // check if value is enumerated value $enumIndex = $table->enumIndex($field, trim($value, "'")); - if(substr($value, 0, 1) == '(') { + if (substr($value, 0, 1) == '(') { // trim brackets $trimmed = Doctrine_Query::bracketTrim($value); - if(substr($trimmed, 0, 4) == 'FROM' || substr($trimmed, 0, 6) == 'SELECT') { + if (substr($trimmed, 0, 4) == 'FROM' || substr($trimmed, 0, 6) == 'SELECT') { // subquery found $q = new Doctrine_Query(); $value = '(' . $q->parseQuery($trimmed)->getQuery() . ')'; - } elseif(substr($trimmed, 0, 4) == 'SQL:') { + } elseif (substr($trimmed, 0, 4) == 'SQL:') { $value = '(' . substr($trimmed, 4) . ')'; } else { // simple in expression found $e = Doctrine_Query::sqlExplode($trimmed, ','); - + $value = array(); - foreach($e as $part) { + foreach ($e as $part) { $index = $table->enumIndex($field, trim($part, "'")); - if($index !== false) + if ($index !== false) { $value[] = $index; - else + } else { $value[] = $this->parseLiteralValue($part); + } } $value = '(' . implode(', ', $value) . ')'; } } else { - if($enumIndex !== false) + if ($enumIndex !== false) { $value = $enumIndex; - else + } else { $value = $this->parseLiteralValue($value); + } } - - switch($operator) { - case '<': - case '>': - case '=': - case '!=': - if($enumIndex !== false) - $value = $enumIndex; - default: - $where = $alias.'.'.$field.' '.$operator.' '.$value; + switch ($operator) { + case '<': + case '>': + case '=': + case '!=': + if ($enumIndex !== false) { + $value = $enumIndex; + } + default: + $where = $alias.'.'.$field.' '.$operator.' '.$value; } } } @@ -137,7 +138,7 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { } /** * parses a literal value and returns the parsed value - * + * * boolean literals are parsed to integers * components are parsed to associated table aliases * @@ -146,20 +147,19 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { */ public function parseLiteralValue($value) { // check that value isn't a string - if(strpos($value, '\'') === false) { - + if (strpos($value, '\'') === false) { // parse booleans - if($value == 'true') + if ($value == 'true') $value = 1; - elseif($value == 'false') + elseif ($value == 'false') $value = 0; $a = explode('.', $value); - if(count($a) > 1) { + if (count($a) > 1) { // either a float or a component.. - - if( ! is_numeric($a[0])) { + + if ( ! is_numeric($a[0])) { // a component found $value = $this->query->getTableAlias($a[0]). '.' . $a[1]; } @@ -181,8 +181,8 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { $operator = ($negation) ? 'EXISTS' : 'NOT EXISTS'; $pos = strpos($where, '('); - - if($pos == false) + + if ($pos == false) throw new Doctrine_Query_Exception("Unknown expression, expected '('"); $sub = Doctrine_Query::bracketTrim(substr($where, $pos)); @@ -196,15 +196,15 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { * @return string */ public function getOperator($func) { - switch($func) { - case 'contains': - $operator = ' = '; + switch ($func) { + case 'contains': + $operator = ' = '; break; - case 'regexp': - $operator = $this->query->getConnection()->getRegexpOperator(); + case 'regexp': + $operator = $this->query->getConnection()->getRegexpOperator(); break; - case 'like': - $operator = ' LIKE '; + case 'like': + $operator = ' LIKE '; break; } return $operator; @@ -219,4 +219,3 @@ class Doctrine_Query_Where extends Doctrine_Query_Condition { return ( ! empty($this->parts))?implode(' AND ', $this->parts):''; } } - diff --git a/lib/Doctrine/RawSql.php b/lib/Doctrine/RawSql.php index e9ec3d9a8..8d083829b 100644 --- a/lib/Doctrine/RawSql.php +++ b/lib/Doctrine/RawSql.php @@ -1,5 +1,5 @@ parts[$name])) + if ( ! isset($this->parts[$name])) { throw new Doctrine_RawSql_Exception("Unknown overload method $name. Availible overload methods are ".implode(" ",array_keys($this->parts))); - - if($name == 'select') { + } + if ($name == 'select') { preg_match_all('/{([^}{]*)}/U', $args[0], $m); $this->fields = $m[1]; $this->parts["select"] = array(); - } else + } else { $this->parts[$name][] = $args[0]; - + } return $this; } /** * get */ public function get($name) { - if( ! isset($this->parts[$name])) + if ( ! isset($this->parts[$name])) { throw new Doctrine_RawSql_Exception('Unknown query part '.$name); - + } return $this->parts[$name]; } /** @@ -80,44 +80,46 @@ class Doctrine_RawSql extends Doctrine_Hydrate { $e = Doctrine_Query::sqlExplode($query,' '); - foreach($e as $k => $part): + foreach ($e as $k => $part) { $low = strtolower($part); - switch(strtolower($part)): - case "select": - case "from": - case "where": - case "limit": - case "offset": - case "having": + switch (strtolower($part)) { + case "select": + case "from": + case "where": + case "limit": + case "offset": + case "having": + $p = $low; + if ( ! isset($parts[$low])) { + $parts[$low] = array(); + } + break; + case "order": + case "group": + $i = ($k + 1); + if (isset($e[$i]) && strtolower($e[$i]) === "by") { $p = $low; - if( ! isset($parts[$low])) - $parts[$low] = array(); + $p .= "by"; + $parts[$low."by"] = array(); + } else { + $parts[$p][] = $part; + } break; - case "order": - case "group": - $i = ($k + 1); - if(isset($e[$i]) && strtolower($e[$i]) === "by") { - $p = $low; - $p .= "by"; - $parts[$low."by"] = array(); - - } else - $parts[$p][] = $part; - break; - case "by": - continue; - default: - if( ! isset($parts[$p][0])) - $parts[$p][0] = $part; - else - $parts[$p][0] .= ' '.$part; - endswitch; - endforeach; + case "by": + continue; + default: + if ( ! isset($parts[$p][0])) { + $parts[$p][0] = $part; + } else { + $parts[$p][0] .= ' '.$part; + } + }; + }; $this->parts = $parts; $this->parts["select"] = array(); - + return $this; } /** @@ -127,12 +129,12 @@ class Doctrine_RawSql extends Doctrine_Hydrate { * @return string */ public function getQuery() { - foreach($this->fields as $field) { + 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"); - - if( ! isset($this->tables[$e[0]])) { + } + if ( ! isset($this->tables[$e[0]])) { try { $this->addComponent($e[0], ucwords($e[0])); } catch(Doctrine_Exception $exception) { @@ -140,8 +142,8 @@ class Doctrine_RawSql extends Doctrine_Hydrate { } } - if($e[1] == '*') { - foreach($this->tables[$e[0]]->getColumnNames() as $name) { + if ($e[1] == '*') { + foreach ($this->tables[$e[0]]->getColumnNames() as $name) { $field = $e[0].".".$name; $this->parts["select"][$field] = $field." AS ".$e[0]."__".$name; } @@ -153,20 +155,21 @@ class Doctrine_RawSql extends Doctrine_Hydrate { // force-add all primary key fields - foreach($this->tableAliases as $alias) { - foreach($this->tables[$alias]->getPrimaryKeys() as $key) { + foreach ($this->tableAliases as $alias) { + foreach ($this->tables[$alias]->getPrimaryKeys() as $key) { $field = $alias . '.' . $key; - if( ! isset($this->parts["select"][$field])) + if ( ! isset($this->parts["select"][$field])) { $this->parts["select"][$field] = $field." AS ".$alias."__".$key; + } } } $q = 'SELECT '.implode(', ', $this->parts['select']); $string = $this->applyInheritance(); - if( ! empty($string)) + if ( ! empty($string)) { $this->parts['where'][] = $string; - + } $copy = $this->parts; unset($copy['select']); @@ -178,9 +181,9 @@ class Doctrine_RawSql extends Doctrine_Hydrate { $q .= ( ! empty($this->parts['limit']))? ' LIMIT ' . implode(' ', $this->parts['limit']) : ''; $q .= ( ! empty($this->parts['offset']))? ' OFFSET ' . implode(' ', $this->parts['offset']) : ''; - if( ! empty($string)) + if ( ! empty($string)) { array_pop($this->parts['where']); - + } return $q; } /** @@ -204,20 +207,19 @@ class Doctrine_RawSql extends Doctrine_Hydrate { $currPath = ''; $table = null; - foreach($e as $k => $component) { + foreach ($e as $k => $component) { $currPath .= '.' . $component; - if($k == 0) + if ($k == 0) $currPath = substr($currPath,1); - if(isset($this->tableAliases[$currPath])) + if (isset($this->tableAliases[$currPath])) { $alias = $this->tableAliases[$currPath]; - else + } else { $alias = $tableAlias; + } - if($table) { - + if ($table) { $tableName = $table->getAliasName($component); - $table = $this->conn->getTable($tableName); } else { @@ -227,15 +229,14 @@ class Doctrine_RawSql extends Doctrine_Hydrate { $this->fetchModes[$alias] = Doctrine::FETCH_IMMEDIATE; $this->tableAliases[$currPath] = $alias; - if($k !== 0) + if ($k !== 0) { $this->joins[$alias] = $prevAlias; - + } $prevAlias = $alias; $prevPath = $currPath; } - + return $this; } } - diff --git a/lib/Doctrine/RawSql/Exception.php b/lib/Doctrine/RawSql/Exception.php index 264b8c010..32d581ab3 100644 --- a/lib/Doctrine/RawSql/Exception.php +++ b/lib/Doctrine/RawSql/Exception.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_RawSql_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/Record.php b/lib/Doctrine/Record.php index 9d86c9ee8..09e3bb9c2 100644 --- a/lib/Doctrine/Record.php +++ b/lib/Doctrine/Record.php @@ -1,1453 +1,1449 @@ -. - */ -Doctrine::autoload('Doctrine_Access'); -/** - * Doctrine_Record - * All record classes should inherit this super class - * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ -abstract class Doctrine_Record extends Doctrine_Access implements Countable, IteratorAggregate, Serializable { - /** - * STATE CONSTANTS - */ - - /** - * DIRTY STATE - * a Doctrine_Record is in dirty state when its properties are changed - */ - 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 - */ - 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 - */ - const STATE_CLEAN = 3; - /** - * PROXY STATE - * a Doctrine_Record is in proxy state when its properties are not fully loaded - */ - 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 - */ - const STATE_TCLEAN = 5; - /** - * DELETED STATE - * a Doctrine_Record turns into deleted state when it is deleted - */ - const STATE_DELETED = 6; - /** - * the following protected variables use '_' prefixes, the reason for this is to allow child - * classes call for example $this->id, $this->state for getting the values of columns named 'id' and 'state' - * rather than the values of these protected variables - */ - /** - * @var object Doctrine_Table $_table the factory that created this data access object - */ - protected $_table; - /** - * @var integer $_id the primary keys of this object - */ - protected $_id = array(); - /** - * @var array $_data the record data - */ - protected $_data = array(); - /** - * @var array $_values the values array, aggregate values and such are mapped into this array - */ - protected $_values = array(); - /** - * @var integer $_state the state of this record - * @see STATE_* constants - */ - protected $_state; - /** - * @var array $_modified an array containing properties that have been modified - */ - protected $_modified = array(); - /** - * @var Doctrine_Validator_ErrorStack error stack object - */ - protected $_errorStack; - /** - * @var array $references an array containing all the references - */ - private $references = array(); - /** - * @var array $originals an array containing all the original references - */ - private $originals = array(); - /** - * @var integer $index this index is used for creating object identifiers - */ - private static $index = 1; - /** - * @var Doctrine_Null $null a Doctrine_Null object used for extremely fast - * null value testing - */ - private static $null; - /** - * @var integer $oid 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 - * - * @param boolean $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 - */ - public function __construct($table = null, $isNewEntry = false) { - if(isset($table) && $table instanceof Doctrine_Table) { - $this->_table = $table; - $exists = ( ! $isNewEntry); - } else { - $class = get_class($this); - // get the table of this class - $this->_table = Doctrine_Manager::getInstance()->getConnectionForComponent($class)->getTable(get_class($this)); - $exists = 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())) { - - $this->oid = self::$index; - - self::$index++; - - $keys = $this->_table->getPrimaryKeys(); - - if( ! $exists) { - // listen the onPreCreate event - $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onPreCreate($this); - } else { - - // listen the onPreLoad event - $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onPreLoad($this); - } - // get the data array - $this->_data = $this->_table->getData(); - - - // get the column count - $count = count($this->_data); - - // clean data array - $this->cleanData(); - - $this->prepareIdentifiers($exists); - - if( ! $exists) { - - if($count > 0) - $this->_state = Doctrine_Record::STATE_TDIRTY; - else - $this->_state = Doctrine_Record::STATE_TCLEAN; - - // set the default values for this record - $this->setDefaultValues(); - - // listen the onCreate event - $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onCreate($this); - - } else { - $this->_state = Doctrine_Record::STATE_CLEAN; - - if($count < $this->_table->getColumnCount()) { - $this->_state = Doctrine_Record::STATE_PROXY; - } - - // listen the onLoad event - $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this); - } - - $this->_errorStack = new Doctrine_Validator_ErrorStack(); - - $repository = $this->_table->getRepository(); - $repository->add($this); - } - $this->construct(); - } - /** - * initNullObject - * - * @param Doctrine_Null $null - * @return void - */ - public static function initNullObject(Doctrine_Null $null) { - self::$null = $null; - } - /** - * @return Doctrine_Null - */ - public static function getNullObject() { - return self::$null; - } - /** - * setUp - * this method is used for setting up relations and attributes - * it should be implemented by child classes - * - * @return void - */ - public function setUp() { } - /** - * construct - * Empty tempalte method to provide concrete Record classes with the possibility - * to hook into the constructor procedure - * - * @return void - */ - public function construct() { } - /** - * getOID - * returns the object identifier - * - * @return integer - */ - public function getOID() { - return $this->oid; - } - /** - * isValid - * - * @return boolean whether or not this record passes all column validations - */ - public function isValid() { - if( ! $this->_table->getAttribute(Doctrine::ATTR_VLD)) - return true; - - // Clear the stack from any previous errors. - $this->_errorStack->clear(); - - // Run validation process - $validator = new Doctrine_Validator(); - $validator->validateRecord($this); - $this->validate(); - if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) { - $this->validateOnInsert(); - } else { - $this->validateOnUpdate(); - } - - return $this->_errorStack->count() == 0 ? true : false; - } - /** - * Emtpy template method to provide concrete Record classes with the possibility - * to hook into the validation procedure, doing any custom / specialized - * validations that are neccessary. - */ - protected function validate() {} - /** - * Empty tempalte method to provide concrete Record classes with the possibility - * to hook into the validation procedure only when the record is going to be - * updated. - */ - protected function validateOnUpdate() {} - /** - * Empty tempalte method to provide concrete Record classes with the possibility - * to hook into the validation procedure only when the record is going to be - * inserted into the data store the first time. - */ - protected function validateOnInsert() {} - /** - * getErrorStack - * - * @return Doctrine_Validator_ErrorStack returns the errorStack associated with this record - */ - public function getErrorStack() { - return $this->_errorStack; - } - /** - * setDefaultValues - * sets the default values for records internal data - * - * @param boolean $overwrite whether or not to overwrite the already set values - * @return boolean - */ - public function setDefaultValues($overwrite = false) { - if( ! $this->_table->hasDefaultValues()) - return false; - - foreach($this->_data as $column => $value) { - $default = $this->_table->getDefaultValueOf($column); - - if($default === null) - $default = self::$null; - - if($value === self::$null || $overwrite) { - $this->_data[$column] = $default; - $this->_modified[] = $column; - $this->_state = Doctrine_Record::STATE_TDIRTY; - } - } - } - /** - * cleanData - * this method does several things to records internal data - * - * 1. It unserializes array and object typed columns - * 2. Uncompresses gzip typed columns - * 3. Gets the appropriate enum values for enum typed columns - * 4. Initializes special null object pointer for null values (for fast column existence checking purposes) - * - * - * example: - * - * $data = array("name"=>"John","lastname"=> null, "id" => 1,"unknown" => "unknown"); - * $names = array("name", "lastname", "id"); - * $data after operation: - * $data = array("name"=>"John","lastname" => Object(Doctrine_Null)); - * - * here column 'id' is removed since its auto-incremented primary key (read-only) - * - * @throws Doctrine_Record_Exception if unserialization of array/object typed column fails or - * if uncompression of gzip typed column fails - * - * @return integer - */ - private function cleanData($debug = false) { - $tmp = $this->_data; - - $this->_data = array(); - - $count = 0; - - foreach($this->_table->getColumnNames() as $name) { - $type = $this->_table->getTypeOf($name); - - if( ! isset($tmp[$name])) { - $this->_data[$name] = self::$null; - } else { - switch($type): - case "array": - case "object": - - if($tmp[$name] !== self::$null) { - if(is_string($tmp[$name])) { - $value = unserialize($tmp[$name]); - - if($value === false) - throw new Doctrine_Record_Exception("Unserialization of $name failed."); - } else - $value = $tmp[$name]; - - $this->_data[$name] = $value; - } - break; - case "gzip": - - if($tmp[$name] !== self::$null) { - $value = gzuncompress($tmp[$name]); - - - if($value === false) - throw new Doctrine_Record_Exception("Uncompressing of $name failed."); - - $this->_data[$name] = $value; - } - break; - case "enum": - $this->_data[$name] = $this->_table->enumValue($name, $tmp[$name]); - break; - default: - $this->_data[$name] = $tmp[$name]; - endswitch; - $count++; - } - } - - - return $count; - } - /** - * prepareIdentifiers - * prepares identifiers for later use - * - * @param boolean $exists whether or not this record exists in persistent data store - * @return void - */ - private function prepareIdentifiers($exists = true) { - switch($this->_table->getIdentifierType()): - case Doctrine_Identifier::AUTO_INCREMENT: - case Doctrine_Identifier::SEQUENCE: - $name = $this->_table->getIdentifier(); - - if($exists) { - if(isset($this->_data[$name]) && $this->_data[$name] !== self::$null) - $this->_id[$name] = $this->_data[$name]; - } - - unset($this->_data[$name]); - - break; - case Doctrine_Identifier::NORMAL: - $this->_id = array(); - $name = $this->_table->getIdentifier(); - - if(isset($this->_data[$name]) && $this->_data[$name] !== self::$null) - $this->_id[$name] = $this->_data[$name]; - break; - case Doctrine_Identifier::COMPOSITE: - $names = $this->_table->getIdentifier(); - - - foreach($names as $name) { - if($this->_data[$name] === self::$null) - $this->_id[$name] = null; - else - $this->_id[$name] = $this->_data[$name]; - } - break; - endswitch; - } - /** - * serialize - * this method is automatically called when this Doctrine_Record is serialized - * - * @return array - */ - public function serialize() { - $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onSleep($this); - - $vars = get_object_vars($this); - - unset($vars['references']); - unset($vars['originals']); - unset($vars['_table']); - - $name = $this->_table->getIdentifier(); - $this->_data = array_merge($this->_data, $this->_id); - - foreach($this->_data as $k => $v) { - if($v instanceof Doctrine_Record) - unset($vars['_data'][$k]); - elseif($v === self::$null) { - unset($vars['_data'][$k]); - } else { - switch($this->_table->getTypeOf($k)): - case "array": - case "object": - $vars['_data'][$k] = serialize($vars['_data'][$k]); - break; - endswitch; - } - } - - return serialize($vars); - } - /** - * unseralize - * this method is automatically called everytime a Doctrine_Record object is unserialized - * - * @param string $serialized Doctrine_Record as serialized string - * @throws Doctrine_Record_Exception if the cleanData operation fails somehow - * @return void - */ - public function unserialize($serialized) { - $manager = Doctrine_Manager::getInstance(); - $connection = $manager->getCurrentConnection(); - - $this->oid = self::$index; - self::$index++; - - $this->_table = $connection->getTable(get_class($this)); - - - $array = unserialize($serialized); - - foreach($array as $name => $values) { - $this->$name = $values; - } - - $this->_table->getRepository()->add($this); - - $this->cleanData(); - - $this->prepareIdentifiers($this->exists()); - - $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onWakeUp($this); - } - /** - * getState - * returns the current state of the object - * - * @see Doctrine_Record::STATE_* constants - * @return integer - */ - public function getState() { - return $this->_state; - } - /** - * state - * returns / assigns the state of this record - * - * @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 - */ - public function state($state = null) { - if($state == null) { - return $this->_state; - } - $err = false; - if(is_integer($state)) { - - if($state >= 1 && $state <= 6) - $this->_state = $state; - else - $err = true; - - } elseif(is_string($state)) { - $upper = strtoupper($state); - switch($upper) { - case 'DIRTY': - case 'CLEAN': - case 'TDIRTY': - case 'TCLEAN': - case 'PROXY': - case 'DELETED': - $this->_state = constant('Doctrine_Record::STATE_' . $upper); - break; - default: - $err = true; - } - } - - if($err) - throw new Doctrine_Record_State_Exception('Unknown record state ' . $state); - } - /** - * refresh - * 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) - * @return boolean - */ - final public function refresh() { - $id = $this->obtainIdentifier(); - if( ! is_array($id)) - $id = array($id); - - if(empty($id)) - return false; - - $id = array_values($id); - - $query = $this->_table->getQuery()." WHERE ".implode(" = ? AND ",$this->_table->getPrimaryKeys())." = ?"; - $stmt = $this->_table->getConnection()->execute($query,$id); - - $this->_data = $stmt->fetch(PDO::FETCH_ASSOC); - - - if( ! $this->_data) - throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist anymore'); - - $this->_data = array_change_key_case($this->_data, CASE_LOWER); - - $this->_modified = array(); - $this->cleanData(true); - - $this->prepareIdentifiers(); - - $this->_state = Doctrine_Record::STATE_CLEAN; - - $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this); - - return true; - } - /** - * factoryRefresh - * refreshes the data from outer source (Doctrine_Table) - * - * @throws Doctrine_Record_Exception When the primary key of this record doesn't match the primary key fetched from a collection - * @return void - */ - final public function factoryRefresh() { - $this->_data = $this->_table->getData(); - $old = $this->_id; - - $this->cleanData(); - - $this->prepareIdentifiers(); - - if($this->_id != $old) - throw new Doctrine_Record_Exception("The refreshed primary key doesn't match the one in the record memory.", Doctrine::ERR_REFRESH); - - $this->_state = Doctrine_Record::STATE_CLEAN; - $this->_modified = array(); - - $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this); - } - /** - * getTable - * returns the table object for this record - * - * @return object Doctrine_Table a Doctrine_Table object - */ - final public function getTable() { - return $this->_table; - } - /** - * getData - * return all the internal data - * - * @return array an array containing all the properties - */ - final public function getData() { - return $this->_data; - } - /** - * rawGet - * returns the value of a property, 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 - */ - - public function rawGet($name) { - if( ! isset($this->_data[$name])) - throw new Doctrine_Record_Exception('Unknown property '. $name); - - if($this->_data[$name] === self::$null) - return null; - - return $this->_data[$name]; - } - - /** - * load - * loads all the unitialized properties from the database - * - * @return boolean - */ - public function load() { - // only load the data from database if the Doctrine_Record is in proxy state - if($this->_state == Doctrine_Record::STATE_PROXY) { - $this->refresh(); - - $this->_state = Doctrine_Record::STATE_CLEAN; - - return true; - } - return false; - } - /** - * get - * returns a value of a property or a related component - * - * @param mixed $name name of the property or related component - * @param boolean $invoke whether or not to invoke the onGetProperty listener - * @throws Doctrine_Record_Exception if trying to get a value of unknown property / related component - * @return mixed - */ - public function get($name, $invoke = true) { - - $listener = $this->_table->getAttribute(Doctrine::ATTR_LISTENER); - $value = self::$null; - $lower = strtolower($name); - - if(isset($this->_data[$lower])) { - - // check if the property is null (= it is the Doctrine_Null object located in self::$null) - if($this->_data[$lower] === self::$null) - $this->load(); - - - if($this->_data[$lower] === self::$null) - $value = null; - else - $value = $this->_data[$lower]; - - } - - - if($value !== self::$null) { - - $value = $this->_table->invokeGet($this, $name, $value); - - if($invoke && $name !== $this->_table->getIdentifier()) - return $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onGetProperty($this, $name, $value); - else - return $value; - - return $value; - } - - - if(isset($this->_id[$lower])) - return $this->_id[$lower]; - - if($name === $this->_table->getIdentifier()) - return null; - - if(isset($this->_values[$lower])) - return $this->_values[$lower]; - - $rel = $this->_table->getRelation($name); - - try { - if( ! isset($this->references[$name])) - $this->loadReference($name); - } catch(Doctrine_Table_Exception $e) { - throw new Doctrine_Record_Exception("Unknown property / related component '$name'."); - } - - return $this->references[$name]; - } - /** - * mapValue - * This simple method is used for mapping values to $values property. - * Usually this method is used internally 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 - */ - public function mapValue($name, $value) { - $name = strtolower($name); - $this->_values[$name] = $value; - } - /** - * set - * method for altering properties and Doctrine_Record references - * if the load parameter is set to false this method will not try to load uninitialized record data - * - * @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 - * - * @return Doctrine_Record - */ - public function set($name, $value, $load = true) { - $lower = strtolower($name); - - if(isset($this->_data[$lower])) { - - if($value instanceof Doctrine_Record) { - $id = $value->getIncremented(); - - if($id !== null) - $value = $id; - } - - if($load) - $old = $this->get($lower, false); - else - $old = $this->_data[$lower]; - - if($old !== $value) { - - $value = $this->_table->invokeSet($this, $name, $value); - - $value = $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onSetProperty($this, $name, $value); - - if($value === null) - $value = self::$null; - - $this->_data[$lower] = $value; - $this->_modified[] = $lower; - switch($this->_state): - case Doctrine_Record::STATE_CLEAN: - $this->_state = Doctrine_Record::STATE_DIRTY; - break; - case Doctrine_Record::STATE_TCLEAN: - $this->_state = Doctrine_Record::STATE_TDIRTY; - break; - endswitch; - } - } else { - try { - $this->coreSetRelated($name, $value); - } catch(Doctrine_Table_Exception $e) { - throw new Doctrine_Record_Exception("Unknown property / related component '$name'."); - } - } - } - - public function coreSetRelated($name, $value) { - $rel = $this->_table->getRelation($name); - - // one-to-many or one-to-one relation - if($rel instanceof Doctrine_Relation_ForeignKey || - $rel instanceof Doctrine_Relation_LocalKey) { - if( ! $rel->isOneToOne()) { - // one-to-many relation found - if( ! ($value instanceof Doctrine_Collection)) - throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references."); - - $value->setReference($this,$rel); - } else { - // one-to-one relation found - if( ! ($value instanceof Doctrine_Record)) - throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Record when setting one-to-one references."); - - if($rel instanceof Doctrine_Relation_LocalKey) { - $this->set($rel->getLocal(), $value, false); - } else { - $value->set($rel->getForeign(), $this, false); - } - } - - } elseif($rel instanceof Doctrine_Relation_Association) { - // join table relation found - if( ! ($value instanceof Doctrine_Collection)) - throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting many-to-many references."); - - } - - $this->references[$name] = $value; - } - /** - * contains - * - * @param string $name - * @return boolean - */ - public function contains($name) { - $lower = strtolower($name); - - if(isset($this->_data[$lower])) - return true; - - if(isset($this->_id[$lower])) - return true; - - if(isset($this->references[$name])) - return true; - - return false; - } - /** - * @param string $name - * @return void - */ - public function __unset($name) { - if(isset($this->_data[$name])) - $this->_data[$name] = array(); - - // todo: what to do with references ? - } - /** - * 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 - * - * this method also saves the related components - * - * @param Doctrine_Connection $conn optional connection parameter - * @return void - */ - public function save(Doctrine_Connection $conn = null) { - if ($conn === null) { - $conn = $this->_table->getConnection(); - } - $conn->beginTransaction(); - - - $saveLater = $conn->unitOfWork->saveRelated($this); - - if ($this->isValid()) { - $conn->save($this); - } else { - $conn->transaction->addInvalid($this); - } - - foreach($saveLater as $fk) { - $table = $fk->getTable(); - $alias = $this->_table->getAlias($table->getComponentName()); - - if(isset($this->references[$alias])) { - $obj = $this->references[$alias]; - $obj->save(); - } - } - - // save the MANY-TO-MANY associations - - $conn->unitOfWork->saveAssociations($this); - //$this->saveAssociations(); - - $conn->commit(); - } - /** - * replace - * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT - * query, except that if there is already a row in the table with the same - * key field values, the REPLACE query just updates its values instead of - * inserting a new row. - * - * The REPLACE type of query does not make part of the SQL standards. Since - * practically only MySQL and SQLIte implement it natively, this type of - * 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 PDOException if something fails at PDO level - * @return integer number of rows affected - */ - public function replace(Doctrine_Connection $conn = null) { - if ($conn === null) { - $conn = $this->_table->getConnection(); - } - - return $conn->replace($this->_table->getTableName(), $this->getPrepared(), $this->id); - } - /** - * returns an array of modified fields and associated values - * @return array - */ - public function getModified() { - $a = array(); - - foreach($this->_modified as $k => $v) { - $a[$v] = $this->_data[$v]; - } - return $a; - } - /** - * getPrepared - * - * returns an array of modified fields and values with data preparation - * adds column aggregation inheritance and converts Records into primary key values - * - * @param array $array - * @return array - */ - public function getPrepared(array $array = array()) { - $a = array(); - - if(empty($array)) - $array = $this->_modified; - - foreach($array as $k => $v) { - $type = $this->_table->getTypeOf($v); - - if($this->_data[$v] === self::$null) { - $a[$v] = null; - continue; - } - - switch($type) { - case 'array': - case 'object': - $a[$v] = serialize($this->_data[$v]); - break; - case 'gzip': - $a[$v] = gzcompress($this->_data[$v],5); - break; - case 'boolean': - $a[$v] = (int) $this->_data[$v]; - break; - case 'enum': - $a[$v] = $this->_table->enumIndex($v,$this->_data[$v]); - break; - default: - if($this->_data[$v] instanceof Doctrine_Record) - $this->_data[$v] = $this->_data[$v]->getIncremented(); - - $a[$v] = $this->_data[$v]; - } - } - - foreach($this->_table->getInheritanceMap() as $k => $v) { - $old = $this->get($k, false); - - if((string) $old !== (string) $v || $old === null) { - $a[$k] = $v; - $this->_data[$k] = $v; - } - } - - return $a; - } - /** - * count - * this class implements countable interface - * - * @return integer the number of columns in this record - */ - public function count() { - return count($this->_data); - } - /** - * alias for count() - * - * @return integer the number of columns in this record - */ - public function columnCount() { - return $this->count(); - } - /** - * toArray - * returns the record as an array - * - * @return array - */ - public function toArray() { - $a = array(); - - foreach($this as $column => $value) { - $a[$column] = $value; - } - if($this->_table->getIdentifierType() == Doctrine_Identifier::AUTO_INCREMENT) { - $i = $this->_table->getIdentifier(); - $a[$i] = $this->getIncremented(); - } - return $a; - } - /** - * exists - * returns true if this record is persistent, otherwise false - * - * @return boolean - */ - public function exists() { - return ($this->_state !== Doctrine_Record::STATE_TCLEAN && - $this->_state !== Doctrine_Record::STATE_TDIRTY); - } - /** - * method for checking existence of properties and Doctrine_Record references - * @param mixed $name name of the property or reference - * @return boolean - */ - public function hasRelation($name) { - if(isset($this->_data[$name]) || isset($this->_id[$name])) - return true; - return $this->_table->hasRelation($name); - } - /** - * getIterator - * @return Doctrine_Record_Iterator a Doctrine_Record_Iterator that iterates through the data - */ - public function getIterator() { - return new Doctrine_Record_Iterator($this); - } - /** - * getOriginals - * returns an original collection of related component - * - * @return Doctrine_Collection|false - */ - public function obtainOriginals($name) { - if(isset($this->originals[$name])) - return $this->originals[$name]; - - return false; - } - /** - * deletes this data access object and all the related composites - * this operation is isolated by a transaction - * - * this event can be listened by the onPreDelete and onDelete listeners - * - * @return boolean true on success, false on failure - */ - public function delete(Doctrine_Connection $conn = null) { - if ($conn == null) { - $conn = $this->_table->getConnection(); - } - return $conn->delete($this); - } - /** - * copy - * returns a copy of this object - * - * @return Doctrine_Record - */ - public function copy() { - $ret = $this->_table->create($this->_data); - $modified = array(); - foreach($this->_data as $key => $val) - if (!($val instanceof Doctrine_Null)) - $ret->_modified[] = $key; - return $ret; - } - /** - * assignIdentifier - * - * @param integer $id - * @return void - */ - final public function assignIdentifier($id = false) { - if($id === false) { - $this->_id = array(); - $this->cleanData(); - $this->_state = Doctrine_Record::STATE_TCLEAN; - $this->_modified = array(); - } elseif($id === true) { - $this->prepareIdentifiers(false); - $this->_state = Doctrine_Record::STATE_CLEAN; - $this->_modified = array(); - } else { - $name = $this->_table->getIdentifier(); - - $this->_id[$name] = $id; - $this->_state = Doctrine_Record::STATE_CLEAN; - $this->_modified = array(); - } - } - /** - * assignOriginals - * - * @param string $alias - * @param Doctrine_Collection $coll - * @return void - */ - public function assignOriginals($alias, Doctrine_Collection $coll) { - $this->originals[$alias] = $coll; - } - /** - * returns the primary keys of this object - * - * @return array - */ - final public function obtainIdentifier() { - return $this->_id; - } - /** - * returns the value of autoincremented primary key of this object (if any) - * - * @return integer - */ - final public function getIncremented() { - $id = current($this->_id); - if($id === false) - return null; - - return $id; - } - /** - * getLast - * this method is used internally be Doctrine_Query - * it is needed to provide compatibility between - * records and collections - * - * @return Doctrine_Record - */ - public function getLast() { - return $this; - } - /** - * hasRefence - * @param string $name - * @return boolean - */ - public function hasReference($name) { - return isset($this->references[$name]); - } - /** - * obtainReference - * - * @param string $name - * @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"); - } - /** - * initalizes a one-to-many / many-to-many relation - * - * @param Doctrine_Collection $coll - * @param Doctrine_Relation $connector - * @return boolean - */ - public function initReference(Doctrine_Collection $coll, Doctrine_Relation $connector) { - $alias = $connector->getAlias(); - - if(isset($this->references[$alias])) - return false; - - if( ! $connector->isOneToOne()) { - if( ! ($connector instanceof Doctrine_Relation_Association)) - $coll->setReference($this, $connector); - - $this->references[$alias] = $coll; - $this->originals[$alias] = clone $coll; - - return true; - } - return false; - } - - public function lazyInitRelated(Doctrine_Collection $coll, Doctrine_Relation $connector) { - - } - /** - * addReference - * @param Doctrine_Record $record - * @param mixed $key - * @return void - */ - public function addReference(Doctrine_Record $record, Doctrine_Relation $connector, $key = null) { - $alias = $connector->getAlias(); - - $this->references[$alias]->add($record, $key); - $this->originals[$alias]->add($record, $key); - } - /** - * getReferences - * @return array all references - */ - public function getReferences() { - return $this->references; - } - /** - * setRelated - * - * @param string $alias - * @param Doctrine_Access $coll - */ - final public function setRelated($alias, Doctrine_Access $coll) { - $this->references[$alias] = $coll; - $this->originals[$alias] = $coll; - } - /** - * loadReference - * loads a related component - * - * @throws Doctrine_Table_Exception if trying to load an unknown related component - * @param string $name - * @return void - */ - final public function loadReference($name) { - $fk = $this->_table->getRelation($name); - - if($fk->isOneToOne()) { - $this->references[$name] = $fk->fetchRelatedFor($this); - } else { - $coll = $fk->fetchRelatedFor($this); - - $this->references[$name] = $coll; - $this->originals[$name] = clone $coll; - } - } - /** - * binds One-to-One composite relation - * - * @param string $objTableName - * @param string $fkField - * @return void - */ - final public function ownsOne($componentName, $foreignKey, $localKey = null) { - $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::ONE_COMPOSITE, $localKey); - } - /** - * binds One-to-Many composite relation - * - * @param string $objTableName - * @param string $fkField - * @return void - */ - final public function ownsMany($componentName,$foreignKey, $localKey = null) { - $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::MANY_COMPOSITE, $localKey); - } - /** - * binds One-to-One aggregate relation - * - * @param string $objTableName - * @param string $fkField - * @return void - */ - final public function hasOne($componentName,$foreignKey, $localKey = null) { - $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::ONE_AGGREGATE, $localKey); - } - /** - * binds One-to-Many aggregate relation - * - * @param string $objTableName - * @param string $fkField - * @return void - */ - final public function hasMany($componentName,$foreignKey, $localKey = null) { - $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::MANY_AGGREGATE, $localKey); - } - /** - * setPrimaryKey - * @param mixed $key - */ - final public function setPrimaryKey($key) { - $this->_table->setPrimaryKey($key); - } - /** - * hasColumn - * sets a column definition - * - * @param string $name - * @param string $type - * @param integer $length - * @param mixed $options - * @return void - */ - final public function hasColumn($name, $type, $length = 2147483647, $options = "") { - $this->_table->setColumn($name, $type, $length, $options); - } - /** - * countRelated - * - * @param string $name the name of the related component - * @return integer - */ - public function countRelated($name) { - $rel = $this->_table->getRelation($name); - $componentName = $rel->getTable()->getComponentName(); - $alias = $rel->getTable()->getAlias(get_class($this)); - $query = new Doctrine_Query(); - $query->from($componentName. '(' . 'COUNT(1)' . ')')->where($componentName. '.' .$alias. '.' . $this->getTable()->getIdentifier(). ' = ?'); - $array = $query->execute(array($this->getIncremented())); - return $array[0]['COUNT(1)']; - } - /** - * merge - * merges this record with an array of values - * - * @param array $values - * @return void - */ - public function merge(array $values) { - foreach($this->_table->getColumnNames() as $value) { - try { - if(isset($values[$value])) - $this->set($value, $values[$value]); - } catch(Exception $e) { - // silence all exceptions - } - } - } - public function setAttribute($attr, $value) { - $this->_table->setAttribute($attr, $value); - } - public function setTableName($tableName) { - $this->_table->setTableName($tableName); - } - public function setInheritanceMap($map) { - $this->_table->setOption('inheritanceMap', $map); - } - public function setEnumValues($column, $values) { - $this->_table->setEnumValues($column, $values); - } - public function option($name, $value = null) { - if($value == null) - $this->_table->getOption($name); - else - $this->_table->setOption($name, $value); - } - public function hasIndex($name ) { - - } - public function actsAsTree($treeImplName, $args) { - - } - /** - * addListener - * - * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Db - */ - public function addListener($listener, $name = null) { - $this->_table->addListener($listener, $name = null); - return $this; - } - /** - * getListener - * - * @return Doctrine_Db_EventListener_Interface|Doctrine_Overloadable - */ - public function getListener() { - return $this->_table->getListener(); - } - /** - * setListener - * - * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener - * @return Doctrine_Db - */ - public function setListener($listener) { - $this->_table->setListener($listener); - return $this; - } - /** - * call - * - * @param string|array $callback valid callback - * @param string $column column name - * @param mixed arg1 ... argN optional callback arguments - * @return Doctrine_Record - */ - public function call($callback, $column) { - $args = func_get_args(); - array_shift($args); - - if(isset($args[0])) { - $column = $args[0]; - $args[0] = $this->get($column); - - $newvalue = call_user_func_array($callback, $args); - - $this->_data[$column] = $newvalue; - } - return $this; - } - /** - * returns a string representation of this object - */ - public function __toString() { - return Doctrine_Lib::getRecordAsString($this); - } -} - +. + */ +Doctrine::autoload('Doctrine_Access'); +/** + * Doctrine_Record + * All record classes should inherit this super class + * + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ +abstract class Doctrine_Record extends Doctrine_Access implements Countable, IteratorAggregate, Serializable { + /** + * STATE CONSTANTS + */ + + /** + * DIRTY STATE + * a Doctrine_Record is in dirty state when its properties are changed + */ + 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 + */ + 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 + */ + const STATE_CLEAN = 3; + /** + * PROXY STATE + * a Doctrine_Record is in proxy state when its properties are not fully loaded + */ + 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 + */ + const STATE_TCLEAN = 5; + /** + * DELETED STATE + * a Doctrine_Record turns into deleted state when it is deleted + */ + const STATE_DELETED = 6; + /** + * the following protected variables use '_' prefixes, the reason for this is to allow child + * classes call for example $this->id, $this->state for getting the values of columns named 'id' and 'state' + * rather than the values of these protected variables + */ + /** + * @var object Doctrine_Table $_table the factory that created this data access object + */ + protected $_table; + /** + * @var integer $_id the primary keys of this object + */ + protected $_id = array(); + /** + * @var array $_data the record data + */ + protected $_data = array(); + /** + * @var array $_values the values array, aggregate values and such are mapped into this array + */ + protected $_values = array(); + /** + * @var integer $_state the state of this record + * @see STATE_* constants + */ + protected $_state; + /** + * @var array $_modified an array containing properties that have been modified + */ + protected $_modified = array(); + /** + * @var Doctrine_Validator_ErrorStack error stack object + */ + protected $_errorStack; + /** + * @var array $references an array containing all the references + */ + private $references = array(); + /** + * @var array $originals an array containing all the original references + */ + private $originals = array(); + /** + * @var integer $index this index is used for creating object identifiers + */ + private static $index = 1; + /** + * @var Doctrine_Null $null a Doctrine_Null object used for extremely fast + * null value testing + */ + private static $null; + /** + * @var integer $oid 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 + * + * @param boolean $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 + */ + public function __construct($table = null, $isNewEntry = false) { + if (isset($table) && $table instanceof Doctrine_Table) { + $this->_table = $table; + $exists = ( ! $isNewEntry); + } else { + $class = get_class($this); + // get the table of this class + $this->_table = Doctrine_Manager::getInstance()->getConnectionForComponent($class)->getTable(get_class($this)); + $exists = 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())) { + $this->oid = self::$index; + + self::$index++; + + $keys = $this->_table->getPrimaryKeys(); + + if ( ! $exists) { + // listen the onPreCreate event + $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onPreCreate($this); + } else { + + // listen the onPreLoad event + $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onPreLoad($this); + } + // get the data array + $this->_data = $this->_table->getData(); + + // get the column count + $count = count($this->_data); + + // clean data array + $this->cleanData(); + + $this->prepareIdentifiers($exists); + + if ( ! $exists) { + if ($count > 0) { + $this->_state = Doctrine_Record::STATE_TDIRTY; + } else { + $this->_state = Doctrine_Record::STATE_TCLEAN; + } + + // set the default values for this record + $this->setDefaultValues(); + + // listen the onCreate event + $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onCreate($this); + + } else { + $this->_state = Doctrine_Record::STATE_CLEAN; + + if ($count < $this->_table->getColumnCount()) { + $this->_state = Doctrine_Record::STATE_PROXY; + } + + // listen the onLoad event + $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this); + } + + $this->_errorStack = new Doctrine_Validator_ErrorStack(); + + $repository = $this->_table->getRepository(); + $repository->add($this); + } + $this->construct(); + } + /** + * initNullObject + * + * @param Doctrine_Null $null + * @return void + */ + public static function initNullObject(Doctrine_Null $null) { + self::$null = $null; + } + /** + * @return Doctrine_Null + */ + public static function getNullObject() { + return self::$null; + } + /** + * setUp + * this method is used for setting up relations and attributes + * it should be implemented by child classes + * + * @return void + */ + public function setUp() { } + /** + * construct + * Empty tempalte method to provide concrete Record classes with the possibility + * to hook into the constructor procedure + * + * @return void + */ + public function construct() { } + /** + * getOID + * returns the object identifier + * + * @return integer + */ + public function getOID() { + return $this->oid; + } + /** + * isValid + * + * @return boolean whether or not this record passes all column validations + */ + public function isValid() { + if ( ! $this->_table->getAttribute(Doctrine::ATTR_VLD)) { + return true; + } + // Clear the stack from any previous errors. + $this->_errorStack->clear(); + + // Run validation process + $validator = new Doctrine_Validator(); + $validator->validateRecord($this); + $this->validate(); + if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) { + $this->validateOnInsert(); + } else { + $this->validateOnUpdate(); + } + + return $this->_errorStack->count() == 0 ? true : false; + } + /** + * Emtpy template method to provide concrete Record classes with the possibility + * to hook into the validation procedure, doing any custom / specialized + * validations that are neccessary. + */ + protected function validate() {} + /** + * Empty tempalte method to provide concrete Record classes with the possibility + * to hook into the validation procedure only when the record is going to be + * updated. + */ + protected function validateOnUpdate() {} + /** + * Empty tempalte method to provide concrete Record classes with the possibility + * to hook into the validation procedure only when the record is going to be + * inserted into the data store the first time. + */ + protected function validateOnInsert() {} + /** + * getErrorStack + * + * @return Doctrine_Validator_ErrorStack returns the errorStack associated with this record + */ + public function getErrorStack() { + return $this->_errorStack; + } + /** + * setDefaultValues + * sets the default values for records internal data + * + * @param boolean $overwrite whether or not to overwrite the already set values + * @return boolean + */ + public function setDefaultValues($overwrite = false) { + if ( ! $this->_table->hasDefaultValues()) { + return false; + } + foreach ($this->_data as $column => $value) { + $default = $this->_table->getDefaultValueOf($column); + + if ($default === null) + $default = self::$null; + + if ($value === self::$null || $overwrite) { + $this->_data[$column] = $default; + $this->_modified[] = $column; + $this->_state = Doctrine_Record::STATE_TDIRTY; + } + } + } + /** + * cleanData + * this method does several things to records internal data + * + * 1. It unserializes array and object typed columns + * 2. Uncompresses gzip typed columns + * 3. Gets the appropriate enum values for enum typed columns + * 4. Initializes special null object pointer for null values (for fast column existence checking purposes) + * + * + * example: + * + * $data = array("name"=>"John","lastname"=> null, "id" => 1,"unknown" => "unknown"); + * $names = array("name", "lastname", "id"); + * $data after operation: + * $data = array("name"=>"John","lastname" => Object(Doctrine_Null)); + * + * here column 'id' is removed since its auto-incremented primary key (read-only) + * + * @throws Doctrine_Record_Exception if unserialization of array/object typed column fails or + * if uncompression of gzip typed column fails + * + * @return integer + */ + private function cleanData($debug = false) { + $tmp = $this->_data; + + $this->_data = array(); + + $count = 0; + + foreach ($this->_table->getColumnNames() as $name) { + $type = $this->_table->getTypeOf($name); + + if ( ! isset($tmp[$name])) { + $this->_data[$name] = self::$null; + } else { + switch ($type) { + case "array": + case "object": + + if ($tmp[$name] !== self::$null) { + if (is_string($tmp[$name])) { + $value = unserialize($tmp[$name]); + + if ($value === false) + throw new Doctrine_Record_Exception("Unserialization of $name failed."); + } else { + $value = $tmp[$name]; + } + $this->_data[$name] = $value; + } + break; + case "gzip": + + if ($tmp[$name] !== self::$null) { + $value = gzuncompress($tmp[$name]); + + if ($value === false) + throw new Doctrine_Record_Exception("Uncompressing of $name failed."); + + $this->_data[$name] = $value; + } + break; + case "enum": + $this->_data[$name] = $this->_table->enumValue($name, $tmp[$name]); + break; + default: + $this->_data[$name] = $tmp[$name]; + }; + $count++; + } + } + + return $count; + } + /** + * prepareIdentifiers + * prepares identifiers for later use + * + * @param boolean $exists whether or not this record exists in persistent data store + * @return void + */ + private function prepareIdentifiers($exists = true) { + switch ($this->_table->getIdentifierType()) { + case Doctrine_Identifier::AUTO_INCREMENT: + case Doctrine_Identifier::SEQUENCE: + $name = $this->_table->getIdentifier(); + + if ($exists) { + if (isset($this->_data[$name]) && $this->_data[$name] !== self::$null) { + $this->_id[$name] = $this->_data[$name]; + } + } + + unset($this->_data[$name]); + + break; + case Doctrine_Identifier::NORMAL: + $this->_id = array(); + $name = $this->_table->getIdentifier(); + + if (isset($this->_data[$name]) && $this->_data[$name] !== self::$null) { + $this->_id[$name] = $this->_data[$name]; + } + break; + case Doctrine_Identifier::COMPOSITE: + $names = $this->_table->getIdentifier(); + + foreach ($names as $name) { + if ($this->_data[$name] === self::$null) { + $this->_id[$name] = null; + } else { + $this->_id[$name] = $this->_data[$name]; + } + } + break; + }; + } + /** + * serialize + * this method is automatically called when this Doctrine_Record is serialized + * + * @return array + */ + public function serialize() { + $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onSleep($this); + + $vars = get_object_vars($this); + + unset($vars['references']); + unset($vars['originals']); + unset($vars['_table']); + + $name = $this->_table->getIdentifier(); + $this->_data = array_merge($this->_data, $this->_id); + + foreach ($this->_data as $k => $v) { + if ($v instanceof Doctrine_Record) + unset($vars['_data'][$k]); + elseif ($v === self::$null) { + unset($vars['_data'][$k]); + } else { + switch ($this->_table->getTypeOf($k)) { + case "array": + case "object": + $vars['_data'][$k] = serialize($vars['_data'][$k]); + break; + }; + } + } + + return serialize($vars); + } + /** + * unseralize + * this method is automatically called everytime a Doctrine_Record object is unserialized + * + * @param string $serialized Doctrine_Record as serialized string + * @throws Doctrine_Record_Exception if the cleanData operation fails somehow + * @return void + */ + public function unserialize($serialized) { + $manager = Doctrine_Manager::getInstance(); + $connection = $manager->getCurrentConnection(); + + $this->oid = self::$index; + self::$index++; + + $this->_table = $connection->getTable(get_class($this)); + + $array = unserialize($serialized); + + foreach ($array as $name => $values) { + $this->$name = $values; + } + + $this->_table->getRepository()->add($this); + + $this->cleanData(); + + $this->prepareIdentifiers($this->exists()); + + $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onWakeUp($this); + } + /** + * getState + * returns the current state of the object + * + * @see Doctrine_Record::STATE_* constants + * @return integer + */ + public function getState() { + return $this->_state; + } + /** + * state + * returns / assigns the state of this record + * + * @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 + */ + public function state($state = null) { + if ($state == null) { + return $this->_state; + } + $err = false; + if (is_integer($state)) { + + if ($state >= 1 && $state <= 6) { + $this->_state = $state; + } else { + $err = true; + } + } elseif (is_string($state)) { + $upper = strtoupper($state); + switch ($upper) { + case 'DIRTY': + case 'CLEAN': + case 'TDIRTY': + case 'TCLEAN': + case 'PROXY': + case 'DELETED': + $this->_state = constant('Doctrine_Record::STATE_' . $upper); + break; + default: + $err = true; + } + } + + if ($err) + throw new Doctrine_Record_State_Exception('Unknown record state ' . $state); + } + /** + * refresh + * 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) + * @return boolean + */ + final public function refresh() { + $id = $this->obtainIdentifier(); + if ( ! is_array($id)) { + $id = array($id); + } + if (empty($id)) { + return false; + } + $id = array_values($id); + + $query = $this->_table->getQuery()." WHERE ".implode(" = ? AND ",$this->_table->getPrimaryKeys())." = ?"; + $stmt = $this->_table->getConnection()->execute($query,$id); + + $this->_data = $stmt->fetch(PDO::FETCH_ASSOC); + + if ( ! $this->_data) + throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist anymore'); + + $this->_data = array_change_key_case($this->_data, CASE_LOWER); + + $this->_modified = array(); + $this->cleanData(true); + + $this->prepareIdentifiers(); + + $this->_state = Doctrine_Record::STATE_CLEAN; + + $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this); + + return true; + } + /** + * factoryRefresh + * refreshes the data from outer source (Doctrine_Table) + * + * @throws Doctrine_Record_Exception When the primary key of this record doesn't match the primary key fetched from a collection + * @return void + */ + final public function factoryRefresh() { + $this->_data = $this->_table->getData(); + $old = $this->_id; + + $this->cleanData(); + + $this->prepareIdentifiers(); + + if ($this->_id != $old) + throw new Doctrine_Record_Exception("The refreshed primary key doesn't match the one in the record memory.", Doctrine::ERR_REFRESH); + + $this->_state = Doctrine_Record::STATE_CLEAN; + $this->_modified = array(); + + $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this); + } + /** + * getTable + * returns the table object for this record + * + * @return object Doctrine_Table a Doctrine_Table object + */ + final public function getTable() { + return $this->_table; + } + /** + * getData + * return all the internal data + * + * @return array an array containing all the properties + */ + final public function getData() { + return $this->_data; + } + /** + * rawGet + * returns the value of a property, 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 + */ + + public function rawGet($name) { + if ( ! isset($this->_data[$name])) { + throw new Doctrine_Record_Exception('Unknown property '. $name); + } + if ($this->_data[$name] === self::$null) + return null; + + return $this->_data[$name]; + } + + /** + * load + * loads all the unitialized properties from the database + * + * @return boolean + */ + public function load() { + // only load the data from database if the Doctrine_Record is in proxy state + if ($this->_state == Doctrine_Record::STATE_PROXY) { + $this->refresh(); + + $this->_state = Doctrine_Record::STATE_CLEAN; + + return true; + } + return false; + } + /** + * get + * returns a value of a property or a related component + * + * @param mixed $name name of the property or related component + * @param boolean $invoke whether or not to invoke the onGetProperty listener + * @throws Doctrine_Record_Exception if trying to get a value of unknown property / related component + * @return mixed + */ + public function get($name, $invoke = true) { + + $listener = $this->_table->getAttribute(Doctrine::ATTR_LISTENER); + $value = self::$null; + $lower = strtolower($name); + + if (isset($this->_data[$lower])) { + // check if the property is null (= it is the Doctrine_Null object located in self::$null) + if ($this->_data[$lower] === self::$null) { + $this->load(); + } + + if ($this->_data[$lower] === self::$null) { + $value = null; + } else { + $value = $this->_data[$lower]; + } + + } + + if ($value !== self::$null) { + $value = $this->_table->invokeGet($this, $name, $value); + + if ($invoke && $name !== $this->_table->getIdentifier()) { + return $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onGetProperty($this, $name, $value); + } else { + return $value; + } + return $value; + } + + if (isset($this->_id[$lower])) { + return $this->_id[$lower]; + } + if ($name === $this->_table->getIdentifier()) { + return null; + } + if (isset($this->_values[$lower])) { + return $this->_values[$lower]; + } + $rel = $this->_table->getRelation($name); + + try { + if ( ! isset($this->references[$name])) { + $this->loadReference($name); + } + } catch(Doctrine_Table_Exception $e) { + throw new Doctrine_Record_Exception("Unknown property / related component '$name'."); + } + + return $this->references[$name]; + } + /** + * mapValue + * This simple method is used for mapping values to $values property. + * Usually this method is used internally 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 + */ + public function mapValue($name, $value) { + $name = strtolower($name); + $this->_values[$name] = $value; + } + /** + * set + * method for altering properties and Doctrine_Record references + * if the load parameter is set to false this method will not try to load uninitialized record data + * + * @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 + * + * @return Doctrine_Record + */ + public function set($name, $value, $load = true) { + $lower = strtolower($name); + + if (isset($this->_data[$lower])) { + if ($value instanceof Doctrine_Record) { + $id = $value->getIncremented(); + + if ($id !== null) + $value = $id; + } + + if ($load) { + $old = $this->get($lower, false); + } else { + $old = $this->_data[$lower]; + } + + if ($old !== $value) { + $value = $this->_table->invokeSet($this, $name, $value); + + $value = $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onSetProperty($this, $name, $value); + + if ($value === null) + $value = self::$null; + + $this->_data[$lower] = $value; + $this->_modified[] = $lower; + switch ($this->_state) { + case Doctrine_Record::STATE_CLEAN: + $this->_state = Doctrine_Record::STATE_DIRTY; + break; + case Doctrine_Record::STATE_TCLEAN: + $this->_state = Doctrine_Record::STATE_TDIRTY; + break; + }; + } + } else { + try { + $this->coreSetRelated($name, $value); + } catch(Doctrine_Table_Exception $e) { + throw new Doctrine_Record_Exception("Unknown property / related component '$name'."); + } + } + } + + public function coreSetRelated($name, $value) { + $rel = $this->_table->getRelation($name); + + // one-to-many or one-to-one relation + if ($rel instanceof Doctrine_Relation_ForeignKey || + $rel instanceof Doctrine_Relation_LocalKey) { + if ( ! $rel->isOneToOne()) { + // one-to-many relation found + if ( ! ($value instanceof Doctrine_Collection)) { + throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references."); + } + $value->setReference($this,$rel); + } else { + // one-to-one relation found + if ( ! ($value instanceof Doctrine_Record)) { + throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Record when setting one-to-one references."); + } + if ($rel instanceof Doctrine_Relation_LocalKey) { + $this->set($rel->getLocal(), $value, false); + } else { + $value->set($rel->getForeign(), $this, false); + } + } + + } elseif ($rel instanceof Doctrine_Relation_Association) { + // join table relation found + if ( ! ($value instanceof Doctrine_Collection)) { + throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting many-to-many references."); + } + } + + $this->references[$name] = $value; + } + /** + * contains + * + * @param string $name + * @return boolean + */ + public function contains($name) { + $lower = strtolower($name); + + if (isset($this->_data[$lower])) { + return true; + } + if (isset($this->_id[$lower])) { + return true; + } + if (isset($this->references[$name])) { + return true; + } + return false; + } + /** + * @param string $name + * @return void + */ + public function __unset($name) { + if (isset($this->_data[$name])) { + $this->_data[$name] = array(); + } + // todo: what to do with references ? + } + /** + * 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 + * + * this method also saves the related components + * + * @param Doctrine_Connection $conn optional connection parameter + * @return void + */ + public function save(Doctrine_Connection $conn = null) { + if ($conn === null) { + $conn = $this->_table->getConnection(); + } + $conn->beginTransaction(); + + $saveLater = $conn->unitOfWork->saveRelated($this); + + if ($this->isValid()) { + $conn->save($this); + } else { + $conn->transaction->addInvalid($this); + } + + foreach ($saveLater as $fk) { + $table = $fk->getTable(); + $alias = $this->_table->getAlias($table->getComponentName()); + + if (isset($this->references[$alias])) { + $obj = $this->references[$alias]; + $obj->save(); + } + } + + // save the MANY-TO-MANY associations + + $conn->unitOfWork->saveAssociations($this); + //$this->saveAssociations(); + + $conn->commit(); + } + /** + * replace + * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT + * query, except that if there is already a row in the table with the same + * key field values, the REPLACE query just updates its values instead of + * inserting a new row. + * + * The REPLACE type of query does not make part of the SQL standards. Since + * practically only MySQL and SQLIte implement it natively, this type of + * 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 PDOException if something fails at PDO level + * @return integer number of rows affected + */ + public function replace(Doctrine_Connection $conn = null) { + if ($conn === null) { + $conn = $this->_table->getConnection(); + } + + return $conn->replace($this->_table->getTableName(), $this->getPrepared(), $this->id); + } + /** + * returns an array of modified fields and associated values + * @return array + */ + public function getModified() { + $a = array(); + + foreach ($this->_modified as $k => $v) { + $a[$v] = $this->_data[$v]; + } + return $a; + } + /** + * getPrepared + * + * returns an array of modified fields and values with data preparation + * adds column aggregation inheritance and converts Records into primary key values + * + * @param array $array + * @return array + */ + public function getPrepared(array $array = array()) { + $a = array(); + + if (empty($array)) { + $array = $this->_modified; + } + foreach ($array as $k => $v) { + $type = $this->_table->getTypeOf($v); + + if ($this->_data[$v] === self::$null) { + $a[$v] = null; + continue; + } + + switch ($type) { + case 'array': + case 'object': + $a[$v] = serialize($this->_data[$v]); + break; + case 'gzip': + $a[$v] = gzcompress($this->_data[$v],5); + break; + case 'boolean': + $a[$v] = (int) $this->_data[$v]; + break; + case 'enum': + $a[$v] = $this->_table->enumIndex($v,$this->_data[$v]); + break; + default: + if ($this->_data[$v] instanceof Doctrine_Record) + $this->_data[$v] = $this->_data[$v]->getIncremented(); + + $a[$v] = $this->_data[$v]; + } + } + + foreach ($this->_table->getInheritanceMap() as $k => $v) { + $old = $this->get($k, false); + + if ((string) $old !== (string) $v || $old === null) { + $a[$k] = $v; + $this->_data[$k] = $v; + } + } + + return $a; + } + /** + * count + * this class implements countable interface + * + * @return integer the number of columns in this record + */ + public function count() { + return count($this->_data); + } + /** + * alias for count() + * + * @return integer the number of columns in this record + */ + public function columnCount() { + return $this->count(); + } + /** + * toArray + * returns the record as an array + * + * @return array + */ + public function toArray() { + $a = array(); + + foreach ($this as $column => $value) { + $a[$column] = $value; + } + if ($this->_table->getIdentifierType() == Doctrine_Identifier::AUTO_INCREMENT) { + $i = $this->_table->getIdentifier(); + $a[$i] = $this->getIncremented(); + } + return $a; + } + /** + * exists + * returns true if this record is persistent, otherwise false + * + * @return boolean + */ + public function exists() { + return ($this->_state !== Doctrine_Record::STATE_TCLEAN && + $this->_state !== Doctrine_Record::STATE_TDIRTY); + } + /** + * method for checking existence of properties and Doctrine_Record references + * @param mixed $name name of the property or reference + * @return boolean + */ + public function hasRelation($name) { + if (isset($this->_data[$name]) || isset($this->_id[$name])) { + return true; + } + return $this->_table->hasRelation($name); + } + /** + * getIterator + * @return Doctrine_Record_Iterator a Doctrine_Record_Iterator that iterates through the data + */ + public function getIterator() { + return new Doctrine_Record_Iterator($this); + } + /** + * getOriginals + * returns an original collection of related component + * + * @return Doctrine_Collection|false + */ + public function obtainOriginals($name) { + if (isset($this->originals[$name])) { + return $this->originals[$name]; + } + return false; + } + /** + * deletes this data access object and all the related composites + * this operation is isolated by a transaction + * + * this event can be listened by the onPreDelete and onDelete listeners + * + * @return boolean true on success, false on failure + */ + public function delete(Doctrine_Connection $conn = null) { + if ($conn == null) { + $conn = $this->_table->getConnection(); + } + return $conn->delete($this); + } + /** + * copy + * returns a copy of this object + * + * @return Doctrine_Record + */ + public function copy() { + $ret = $this->_table->create($this->_data); + $modified = array(); + foreach ($this->_data as $key => $val) { + if (!($val instanceof Doctrine_Null)) { + $ret->_modified[] = $key; + } + } + return $ret; + } + /** + * assignIdentifier + * + * @param integer $id + * @return void + */ + final public function assignIdentifier($id = false) { + if ($id === false) { + $this->_id = array(); + $this->cleanData(); + $this->_state = Doctrine_Record::STATE_TCLEAN; + $this->_modified = array(); + } elseif ($id === true) { + $this->prepareIdentifiers(false); + $this->_state = Doctrine_Record::STATE_CLEAN; + $this->_modified = array(); + } else { + $name = $this->_table->getIdentifier(); + + $this->_id[$name] = $id; + $this->_state = Doctrine_Record::STATE_CLEAN; + $this->_modified = array(); + } + } + /** + * assignOriginals + * + * @param string $alias + * @param Doctrine_Collection $coll + * @return void + */ + public function assignOriginals($alias, Doctrine_Collection $coll) { + $this->originals[$alias] = $coll; + } + /** + * returns the primary keys of this object + * + * @return array + */ + final public function obtainIdentifier() { + return $this->_id; + } + /** + * returns the value of autoincremented primary key of this object (if any) + * + * @return integer + */ + final public function getIncremented() { + $id = current($this->_id); + if ($id === false) + return null; + + return $id; + } + /** + * getLast + * this method is used internally be Doctrine_Query + * it is needed to provide compatibility between + * records and collections + * + * @return Doctrine_Record + */ + public function getLast() { + return $this; + } + /** + * hasRefence + * @param string $name + * @return boolean + */ + public function hasReference($name) { + return isset($this->references[$name]); + } + /** + * obtainReference + * + * @param string $name + * @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"); + } + /** + * initalizes a one-to-many / many-to-many relation + * + * @param Doctrine_Collection $coll + * @param Doctrine_Relation $connector + * @return boolean + */ + public function initReference(Doctrine_Collection $coll, Doctrine_Relation $connector) { + $alias = $connector->getAlias(); + + if (isset($this->references[$alias])) { + return false; + } + if ( ! $connector->isOneToOne()) { + if ( ! ($connector instanceof Doctrine_Relation_Association)) { + $coll->setReference($this, $connector); + } + $this->references[$alias] = $coll; + $this->originals[$alias] = clone $coll; + + return true; + } + return false; + } + + public function lazyInitRelated(Doctrine_Collection $coll, Doctrine_Relation $connector) { + + } + /** + * addReference + * @param Doctrine_Record $record + * @param mixed $key + * @return void + */ + public function addReference(Doctrine_Record $record, Doctrine_Relation $connector, $key = null) { + $alias = $connector->getAlias(); + + $this->references[$alias]->add($record, $key); + $this->originals[$alias]->add($record, $key); + } + /** + * getReferences + * @return array all references + */ + public function getReferences() { + return $this->references; + } + /** + * setRelated + * + * @param string $alias + * @param Doctrine_Access $coll + */ + final public function setRelated($alias, Doctrine_Access $coll) { + $this->references[$alias] = $coll; + $this->originals[$alias] = $coll; + } + /** + * loadReference + * loads a related component + * + * @throws Doctrine_Table_Exception if trying to load an unknown related component + * @param string $name + * @return void + */ + final public function loadReference($name) { + $fk = $this->_table->getRelation($name); + + if ($fk->isOneToOne()) { + $this->references[$name] = $fk->fetchRelatedFor($this); + } else { + $coll = $fk->fetchRelatedFor($this); + + $this->references[$name] = $coll; + $this->originals[$name] = clone $coll; + } + } + /** + * binds One-to-One composite relation + * + * @param string $objTableName + * @param string $fkField + * @return void + */ + final public function ownsOne($componentName, $foreignKey, $localKey = null) { + $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::ONE_COMPOSITE, $localKey); + } + /** + * binds One-to-Many composite relation + * + * @param string $objTableName + * @param string $fkField + * @return void + */ + final public function ownsMany($componentName,$foreignKey, $localKey = null) { + $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::MANY_COMPOSITE, $localKey); + } + /** + * binds One-to-One aggregate relation + * + * @param string $objTableName + * @param string $fkField + * @return void + */ + final public function hasOne($componentName,$foreignKey, $localKey = null) { + $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::ONE_AGGREGATE, $localKey); + } + /** + * binds One-to-Many aggregate relation + * + * @param string $objTableName + * @param string $fkField + * @return void + */ + final public function hasMany($componentName,$foreignKey, $localKey = null) { + $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::MANY_AGGREGATE, $localKey); + } + /** + * setPrimaryKey + * @param mixed $key + */ + final public function setPrimaryKey($key) { + $this->_table->setPrimaryKey($key); + } + /** + * hasColumn + * sets a column definition + * + * @param string $name + * @param string $type + * @param integer $length + * @param mixed $options + * @return void + */ + final public function hasColumn($name, $type, $length = 2147483647, $options = "") { + $this->_table->setColumn($name, $type, $length, $options); + } + /** + * countRelated + * + * @param string $name the name of the related component + * @return integer + */ + public function countRelated($name) { + $rel = $this->_table->getRelation($name); + $componentName = $rel->getTable()->getComponentName(); + $alias = $rel->getTable()->getAlias(get_class($this)); + $query = new Doctrine_Query(); + $query->from($componentName. '(' . 'COUNT(1)' . ')')->where($componentName. '.' .$alias. '.' . $this->getTable()->getIdentifier(). ' = ?'); + $array = $query->execute(array($this->getIncremented())); + return $array[0]['COUNT(1)']; + } + /** + * merge + * merges this record with an array of values + * + * @param array $values + * @return void + */ + public function merge(array $values) { + foreach ($this->_table->getColumnNames() as $value) { + try { + if (isset($values[$value])) { + $this->set($value, $values[$value]); + } + } catch(Exception $e) { + // silence all exceptions + } + } + } + public function setAttribute($attr, $value) { + $this->_table->setAttribute($attr, $value); + } + public function setTableName($tableName) { + $this->_table->setTableName($tableName); + } + public function setInheritanceMap($map) { + $this->_table->setOption('inheritanceMap', $map); + } + public function setEnumValues($column, $values) { + $this->_table->setEnumValues($column, $values); + } + public function option($name, $value = null) { + if ($value == null) { + $this->_table->getOption($name); + } else { + $this->_table->setOption($name, $value); + } + } + public function hasIndex($name ) { + + } + public function actsAsTree($treeImplName, $args) { + + } + /** + * addListener + * + * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener + * @return Doctrine_Db + */ + public function addListener($listener, $name = null) { + $this->_table->addListener($listener, $name = null); + return $this; + } + /** + * getListener + * + * @return Doctrine_Db_EventListener_Interface|Doctrine_Overloadable + */ + public function getListener() { + return $this->_table->getListener(); + } + /** + * setListener + * + * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener + * @return Doctrine_Db + */ + public function setListener($listener) { + $this->_table->setListener($listener); + return $this; + } + /** + * call + * + * @param string|array $callback valid callback + * @param string $column column name + * @param mixed arg1 ... argN optional callback arguments + * @return Doctrine_Record + */ + public function call($callback, $column) { + $args = func_get_args(); + array_shift($args); + + if (isset($args[0])) { + $column = $args[0]; + $args[0] = $this->get($column); + + $newvalue = call_user_func_array($callback, $args); + + $this->_data[$column] = $newvalue; + } + return $this; + } + /** + * returns a string representation of this object + */ + public function __toString() { + return Doctrine_Lib::getRecordAsString($this); + } +} diff --git a/lib/Doctrine/Record/Exception.php b/lib/Doctrine/Record/Exception.php index 43218dbb7..6cac7e944 100644 --- a/lib/Doctrine/Record/Exception.php +++ b/lib/Doctrine/Record/Exception.php @@ -1,5 +1,5 @@ - */ -class Doctrine_Record_Exception extends Doctrine_Exception { } + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Record_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/Record/Iterator.php b/lib/Doctrine/Record/Iterator.php index 72b325b44..596c3c76a 100644 --- a/lib/Doctrine/Record/Iterator.php +++ b/lib/Doctrine/Record/Iterator.php @@ -33,10 +33,10 @@ class Doctrine_Record_Iterator extends ArrayIterator { public function current() { $value = parent::current(); - if($value === self::$null) + if ($value === self::$null) { return null; - else + } else { return $value; + } } } - diff --git a/lib/Doctrine/Record/State/Exception.php b/lib/Doctrine/Record/State/Exception.php index 9eb247913..6d2968260 100644 --- a/lib/Doctrine/Record/State/Exception.php +++ b/lib/Doctrine/Record/State/Exception.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Record_State_Exception extends Doctrine_Record_Exception { } diff --git a/lib/Doctrine/Relation.php b/lib/Doctrine/Relation.php index b8c337f38..9d2469e89 100644 --- a/lib/Doctrine/Relation.php +++ b/lib/Doctrine/Relation.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ abstract class Doctrine_Relation { /** * RELATION CONSTANTS @@ -51,7 +51,6 @@ abstract class Doctrine_Relation { * constant for MANY_TO_MANY and ONE_TO_MANY composite relationships */ const MANY_COMPOSITE = 3; - /** * @var Doctrine_Table $table foreign factory @@ -155,7 +154,7 @@ abstract class Doctrine_Relation { return ($this->type == Doctrine_Relation::ONE_AGGREGATE || $this->type == Doctrine_Relation::ONE_COMPOSITE); } - /** + /** * getRelationDql * * @param integer $count @@ -165,7 +164,7 @@ abstract class Doctrine_Relation { $dql = "FROM ".$this->table->getComponentName(). " WHERE ".$this->table->getComponentName(). '.' . $this->foreign. " IN (".substr(str_repeat("?, ", $count),0,-2).")"; - + return $dql; } /** @@ -188,21 +187,21 @@ abstract class Doctrine_Relation { public static function getDeleteOperations(Doctrine_Collection $old, Doctrine_Collection $new) { $r = array(); - foreach($old as $k => $record) { + foreach ($old as $k => $record) { $id = $record->getIncremented(); - if(empty($id)) + if (empty($id)) { continue; - + } $found = false; - foreach($new as $k2 => $record2) { - if($record2->getIncremented() === $record->getIncremented()) { + foreach ($new as $k2 => $record2) { + if ($record2->getIncremented() === $record->getIncremented()) { $found = true; break; } } - if( ! $found) { + if ( ! $found) { $r[] = $record; unset($old[$k]); } @@ -230,19 +229,19 @@ abstract class Doctrine_Relation { public static function getInsertOperations(Doctrine_Collection $old, Doctrine_Collection $new) { $r = array(); - foreach($new as $k => $record) { + foreach ($new as $k => $record) { $found = false; $id = $record->getIncremented(); - if( ! empty($id)) { - foreach($old as $k2 => $record2) { - if($record2->getIncremented() === $record->getIncremented()) { + if ( ! empty($id)) { + foreach ($old as $k2 => $record2) { + if ($record2->getIncremented() === $record->getIncremented()) { $found = true; break; } } } - if( ! $found) { + if ( ! $found) { $old[] = $record; $r[] = $record; } @@ -276,5 +275,3 @@ abstract class Doctrine_Relation { return implode("\n", $r); } } - - diff --git a/lib/Doctrine/Relation/Association.php b/lib/Doctrine/Relation/Association.php index 84e380923..16e2663c7 100644 --- a/lib/Doctrine/Relation/Association.php +++ b/lib/Doctrine/Relation/Association.php @@ -25,14 +25,14 @@ Doctrine::autoload('Doctrine_Relation'); * which holds 2 foreign keys) * * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Relation_Association extends Doctrine_Relation { /** * @var Doctrine_Table $associationTable @@ -66,17 +66,15 @@ class Doctrine_Relation_Association extends Doctrine_Relation { $asf = $this->getAssociationFactory(); $alias = $this->getAlias(); - if($record->hasReference($alias)) { - + if ($record->hasReference($alias)) { $new = $record->obtainReference($alias); - if( ! $record->obtainOriginals($alias)) + if ( ! $record->obtainOriginals($alias)) { $record->loadReference($alias); - - + } $operations = Doctrine_Relation::getDeleteOperations($record->obtainOriginals($alias), $new); - foreach($operations as $r) { + foreach ($operations as $r) { $query = 'DELETE FROM ' . $asf->getTableName() . ' WHERE ' . $this->getForeign() . ' = ?' . ' AND ' . $this->getLocal() . ' = ?'; @@ -85,8 +83,8 @@ class Doctrine_Relation_Association extends Doctrine_Relation { } $operations = Doctrine_Relation::getInsertOperations($record->obtainOriginals($alias),$new); - - foreach($operations as $r) { + + foreach ($operations as $r) { $reldao = $asf->create(); $reldao->set($this->getForeign(), $r); $reldao->set($this->getLocal(), $record); @@ -102,24 +100,24 @@ class Doctrine_Relation_Association extends Doctrine_Relation { * @param integer $count * @return string */ - public function getRelationDql($count, $context = 'record') { - switch($context): - case "record": - $sub = 'SQL:SELECT ' . $this->foreign. - ' FROM ' . $this->associationTable->getTableName(). - ' WHERE ' . $this->local. - ' IN (' . substr(str_repeat("?, ", $count),0,-2) . - ')'; + public function getRelationDql($count, $context = 'record') { + switch ($context) { + case "record": + $sub = 'SQL:SELECT ' . $this->foreign. + ' FROM ' . $this->associationTable->getTableName(). + ' WHERE ' . $this->local. + ' IN (' . substr(str_repeat("?, ", $count),0,-2) . + ')'; - $dql = "FROM ".$this->table->getComponentName(); - $dql .= ".".$this->associationTable->getComponentName(); - $dql .= " WHERE ".$this->table->getComponentName().".".$this->table->getIdentifier()." IN ($sub)"; + $dql = "FROM ".$this->table->getComponentName(); + $dql .= ".".$this->associationTable->getComponentName(); + $dql .= " WHERE ".$this->table->getComponentName().".".$this->table->getIdentifier()." IN ($sub)"; break; - case "collection": - $sub = substr(str_repeat("?, ", $count),0,-2); - $dql = "FROM ".$this->associationTable->getComponentName().".".$this->table->getComponentName(); - $dql .= " WHERE ".$this->associationTable->getComponentName().".".$this->local." IN ($sub)"; - endswitch; + case "collection": + $sub = substr(str_repeat("?, ", $count),0,-2); + $dql = "FROM ".$this->associationTable->getComponentName().".".$this->table->getComponentName(); + $dql .= " WHERE ".$this->associationTable->getComponentName().".".$this->local." IN ($sub)"; + }; return $dql; } @@ -133,12 +131,11 @@ class Doctrine_Relation_Association extends Doctrine_Relation { */ public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->getIncremented(); - if(empty($id)) + if (empty($id)) { $coll = new Doctrine_Collection($this->table); - else + } else { $coll = Doctrine_Query::create()->parseQuery($this->getRelationDql(1))->execute(array($id)); - + } return $coll; } } - diff --git a/lib/Doctrine/Relation/Association/Self.php b/lib/Doctrine/Relation/Association/Self.php index 477729d1e..1dd315458 100644 --- a/lib/Doctrine/Relation/Association/Self.php +++ b/lib/Doctrine/Relation/Association/Self.php @@ -1,4 +1,4 @@ - - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Relation_Association_Self extends Doctrine_Relation_Association { /** * getRelationDql @@ -37,33 +37,31 @@ class Doctrine_Relation_Association_Self extends Doctrine_Relation_Association { * @param integer $count * @return string */ - public function getRelationDql($count, $context = 'record') { - switch($context): - case 'record': - $sub = 'SELECT '.$this->foreign. - ' FROM '.$this->associationTable->getTableName(). - ' WHERE '.$this->local. - ' = ?'; - $sub2 = 'SELECT '.$this->local. - ' FROM '.$this->associationTable->getTableName(). - ' WHERE '.$this->foreign. - ' = ?'; + public function getRelationDql($count, $context = 'record') { + switch ($context) { + case 'record': + $sub = 'SELECT '.$this->foreign. + ' FROM '.$this->associationTable->getTableName(). + ' WHERE '.$this->local. + ' = ?'; + $sub2 = 'SELECT '.$this->local. + ' FROM '.$this->associationTable->getTableName(). + ' WHERE '.$this->foreign. + ' = ?'; - - $dql = 'FROM '.$this->table->getComponentName(); - $dql .= '.'.$this->associationTable->getComponentName(); - $dql .= ' WHERE '.$this->table->getComponentName().'.'.$this->table->getIdentifier().' IN ('.$sub.')'; - $dql .= ' || '.$this->table->getComponentName().'.'.$this->table->getIdentifier().' IN ('.$sub2.')'; + $dql = 'FROM '.$this->table->getComponentName(); + $dql .= '.'.$this->associationTable->getComponentName(); + $dql .= ' WHERE '.$this->table->getComponentName().'.'.$this->table->getIdentifier().' IN ('.$sub.')'; + $dql .= ' || '.$this->table->getComponentName().'.'.$this->table->getIdentifier().' IN ('.$sub2.')'; break; - case 'collection': - $sub = substr(str_repeat('?, ', $count),0,-2); - $dql = 'FROM '.$this->associationTable->getComponentName().'.'.$this->table->getComponentName(); - $dql .= ' WHERE '.$this->associationTable->getComponentName().'.'.$this->local.' IN ('.$sub.')'; - endswitch; + case 'collection': + $sub = substr(str_repeat('?, ', $count),0,-2); + $dql = 'FROM '.$this->associationTable->getComponentName().'.'.$this->table->getComponentName(); + $dql .= ' WHERE '.$this->associationTable->getComponentName().'.'.$this->local.' IN ('.$sub.')'; + }; return $dql; } - public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->getIncremented(); @@ -94,8 +92,8 @@ class Doctrine_Relation_Association_Self extends Doctrine_Relation_Association { ); $q->addComponent($tableName, $record->getTable()->getComponentName()); $q->addComponent($assocTable, $record->getTable()->getComponentName(). '.' . $this->getAssociationFactory()->getComponentName()); - + return $q->execute(array($id, $id)); } } -?> + diff --git a/lib/Doctrine/Relation/ForeignKey.php b/lib/Doctrine/Relation/ForeignKey.php index 2ca13ca15..8469b4ae7 100644 --- a/lib/Doctrine/Relation/ForeignKey.php +++ b/lib/Doctrine/Relation/ForeignKey.php @@ -23,14 +23,14 @@ Doctrine::autoload('Doctrine_Relation'); * Doctrine_Relation_ForeignKey * This class represents a foreign key relation * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Relation_ForeignKey extends Doctrine_Relation { /** * processDiff @@ -39,21 +39,23 @@ class Doctrine_Relation_ForeignKey extends Doctrine_Relation { */ public function processDiff(Doctrine_Record $record) { $alias = $this->getAlias(); - - if($this->isOneToOne()) { - if($record->obtainOriginals($alias) && - $record->obtainOriginals($alias)->obtainIdentifier() != $this->obtainReference($alias)->obtainIdentifier()) + + if ($this->isOneToOne()) { + if ($record->obtainOriginals($alias) + && $record->obtainOriginals($alias)->obtainIdentifier() != $this->obtainReference($alias)->obtainIdentifier() + ) { $record->obtainOriginals($alias)->delete(); + } } else { - if($record->hasReference($alias)) { + if ($record->hasReference($alias)) { $new = $record->obtainReference($alias); - if( ! $record->obtainOriginals($alias)) + if ( ! $record->obtainOriginals($alias)) { $record->loadReference($alias); - + } $operations = Doctrine_Relation::getDeleteOperations($record->obtainOriginals($alias), $new); - foreach($operations as $r) { + foreach ($operations as $r) { $r->delete(); } @@ -72,8 +74,8 @@ class Doctrine_Relation_ForeignKey extends Doctrine_Relation { public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->get($this->local); - if($this->isOneToOne()) { - if(empty($id)) { + if ($this->isOneToOne()) { + if (empty($id)) { $related = $this->table->create(); } else { $dql = "FROM ".$this->table->getComponentName()." WHERE ".$this->table->getComponentName().".".$this->foreign." = ?"; @@ -84,7 +86,7 @@ class Doctrine_Relation_ForeignKey extends Doctrine_Relation { $related->set($this->foreign, $record, false); } else { - if(empty($id)) { + if (empty($id)) { $related = new Doctrine_Collection($this->table); } else { $query = $this->getRelationDql(1); diff --git a/lib/Doctrine/Relation/LocalKey.php b/lib/Doctrine/Relation/LocalKey.php index 840cf5789..88c39808d 100644 --- a/lib/Doctrine/Relation/LocalKey.php +++ b/lib/Doctrine/Relation/LocalKey.php @@ -23,14 +23,14 @@ Doctrine::autoload('Doctrine_Relation'); * Doctrine_Relation_LocalKey * This class represents a local key relation * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Relation_LocalKey extends Doctrine_Relation { /** * processDiff @@ -40,9 +40,11 @@ class Doctrine_Relation_LocalKey extends Doctrine_Relation { public function processDiff(Doctrine_Record $record) { $alias = $this->getAlias(); - if($record->obtainOriginals($alias) && - $record->obtainOriginals($alias)->obtainIdentifier() != $this->references[$alias]->obtainIdentifier()) + if ($record->obtainOriginals($alias) + && $record->obtainOriginals($alias)->obtainIdentifier() != $this->references[$alias]->obtainIdentifier() + ) { $record->obtainOriginals($alias)->delete(); + } } /** * fetchRelatedFor @@ -55,15 +57,16 @@ class Doctrine_Relation_LocalKey extends Doctrine_Relation { public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->get($this->local); - if(empty($id)) + if (empty($id)) { $related = $this->table->create(); - else { - if( ! ($related = $this->table->find($id))) + } else { + if ( ! ($related = $this->table->find($id))) { $related = $this->table->create(); + } } $record->set($this->local, $related, false); - + return $related; } } diff --git a/lib/Doctrine/Schema.php b/lib/Doctrine/Schema.php index e818ebf35..2f3847af3 100644 --- a/lib/Doctrine/Schema.php +++ b/lib/Doctrine/Schema.php @@ -1,81 +1,80 @@ -. - */ - -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ -/** - * class Doctrine_Schema - * Holds information on one to many databases - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Schema extends Doctrine_Schema_Object implements Countable, IteratorAggregate { - /** - * Holds any number of databases contained in the schema - * @access private - */ - private $childs; - - - /** - * - * @param Doctrine_Schema_Database database * @return - * @access public - */ - public function addDatabase( Doctrine_Schema_Database $database ) { - $this->childs[] = $database; - } - - /** - * Return the childs for this schema - * - * @return array of Doctrine_Schema_Database - * - */ - public function getDatabases(){ - return $this->childs; - } - /** - * - * @return - * @access public - */ - public function __toString( ) { - - } - /** - * - * @return bool - * @access public - */ - public function isValid( ) { - - } -} +. + */ + +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ +/** + * class Doctrine_Schema + * Holds information on one to many databases + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Schema extends Doctrine_Schema_Object implements Countable, IteratorAggregate { + /** + * Holds any number of databases contained in the schema + * @access private + */ + private $childs; + + /** + * + * @param Doctrine_Schema_Database database * @return + * @access public + */ + public function addDatabase( Doctrine_Schema_Database $database ) { + $this->childs[] = $database; + } + + /** + * Return the childs for this schema + * + * @return array of Doctrine_Schema_Database + * + */ + public function getDatabases(){ + return $this->childs; + } + /** + * + * @return + * @access public + */ + public function __toString( ) { + + } + /** + * + * @return bool + * @access public + */ + public function isValid( ) { + + } +} diff --git a/lib/Doctrine/Schema/Column.php b/lib/Doctrine/Schema/Column.php index dde458475..72347c2e0 100644 --- a/lib/Doctrine/Schema/Column.php +++ b/lib/Doctrine/Schema/Column.php @@ -1,74 +1,73 @@ -. - */ -Doctrine::autoload('Doctrine_Schema_Object'); -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ - */ -/** - * class Doctrine_Schema_Column - * Holds information on a database table field - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Schema_Column extends Doctrine_Schema_Object implements IteratorAggregate { - /** - * column definitions - * @var array $definition - */ - protected $definition = array('name' => '', - 'type' => '', - 'length' => null, - 'unique' => false, - 'primary' => false, - 'notnull' => false, - 'default' => false, - 'autoinc' => false - ); - - - public function getName() { - return $this->definition['name']; - } - public function getType() { - return $this->definition['type']; - } - public function isUnique() { - return $this->definition['unique']; - } - public function isPrimaryKey() { - return $this->definition['primary']; - } - public function defaultValue() { - return $this->definition['default']; - } - public function isNotNull() { - return $this->definition['notnull']; - } -} +. + */ +Doctrine::autoload('Doctrine_Schema_Object'); +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ + */ +/** + * class Doctrine_Schema_Column + * Holds information on a database table field + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Schema_Column extends Doctrine_Schema_Object implements IteratorAggregate { + /** + * column definitions + * @var array $definition + */ + protected $definition = array('name' => '', + 'type' => '', + 'length' => null, + 'unique' => false, + 'primary' => false, + 'notnull' => false, + 'default' => false, + 'autoinc' => false + ); + + public function getName() { + return $this->definition['name']; + } + public function getType() { + return $this->definition['type']; + } + public function isUnique() { + return $this->definition['unique']; + } + public function isPrimaryKey() { + return $this->definition['primary']; + } + public function defaultValue() { + return $this->definition['default']; + } + public function isNotNull() { + return $this->definition['notnull']; + } +} diff --git a/lib/Doctrine/Schema/Database.php b/lib/Doctrine/Schema/Database.php index 8e2cc333c..e17154e6f 100644 --- a/lib/Doctrine/Schema/Database.php +++ b/lib/Doctrine/Schema/Database.php @@ -1,92 +1,92 @@ -. - */ -Doctrine::autoload('Doctrine_Schema_Object'); -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ - */ -/** - * class Doctrine_Schema_Database - * Holds information on a database - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Schema_Database extends Doctrine_Schema_Object { - - protected $definition = array('name' => null, - 'type' => null, - 'charset' => null, - 'description' => null, - 'version' => null, - 'engine' => null); - - private $childs = array(); - - /** - * - * @return - * @access public - */ - public function __clone( ) { - - } - /** - * - * @return - * @access public - */ - public function __toString( ) { - - } - /** - * - * @return bool - * @access public - */ - public function isValid( ) { - - } - /** - * - * @param Doctrine_Schema_Table table * @return Doctrine_Schema_Table - * @access public - */ - public function addTable( $table = null ) { - $this->childs[] = $table; - } - - /** - * - * @return array of Doctrine_Schema_Table - * - */ - public function getTables() { - return $this->childs; - } -} +. + */ +Doctrine::autoload('Doctrine_Schema_Object'); +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ + */ +/** + * class Doctrine_Schema_Database + * Holds information on a database + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Schema_Database extends Doctrine_Schema_Object { + + protected $definition = array('name' => null, + 'type' => null, + 'charset' => null, + 'description' => null, + 'version' => null, + 'engine' => null); + + private $childs = array(); + + /** + * + * @return + * @access public + */ + public function __clone( ) { + + } + /** + * + * @return + * @access public + */ + public function __toString( ) { + + } + /** + * + * @return bool + * @access public + */ + public function isValid( ) { + + } + /** + * + * @param Doctrine_Schema_Table table * @return Doctrine_Schema_Table + * @access public + */ + public function addTable( $table = null ) { + $this->childs[] = $table; + } + + /** + * + * @return array of Doctrine_Schema_Table + * + */ + public function getTables() { + return $this->childs; + } +} diff --git a/lib/Doctrine/Schema/Object.php b/lib/Doctrine/Schema/Object.php index 72155407a..388e45918 100644 --- a/lib/Doctrine/Schema/Object.php +++ b/lib/Doctrine/Schema/Object.php @@ -1,95 +1,95 @@ -. - */ -Doctrine::autoload('Doctrine_Access'); -/** - * class Doctrine_Schema_Object - * Catches any non-property call from child classes and throws an exception. - * - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - * @author Jukka Hassinen - */ -abstract class Doctrine_Schema_Object extends Doctrine_Access implements IteratorAggregate, Countable { - - protected $children = array(); - - protected $definition = array('name' => ''); - - public function __construct(array $definition = array()) { - foreach($this->definition as $key => $val) { - if(isset($definition[$key])) - $this->definition[$key] = $definition[$key]; - } - } - - public function get($name) { - if( ! array_key_exists($name, $this->definition)) - throw new Doctrine_Schema_Exception('Unknown definition '. $name); - - return $this->definition[$name]; - - } - - public function set($name, $value) { - if( ! array_key_exists($name, $this->definition)) - throw new Doctrine_Schema_Exception('Unknown definition '. $name); - - $this->definition[$name] = $value; - } - - public function contains($name) { - return array_key_exists($name, $this->definition); - } - - public function toArray() { - return $this->definition; - } - /** - * - * @return int - * @access public - */ - public function count() { - if( ! empty($this->children)) - return count($this->children); - - return count($this->definition); - } - - /** - * getIterator - * - * @return ArrayIterator - * @access public - */ - public function getIterator() { - if( ! empty($this->children)) - return new ArrayIterator($this->children); - - return new ArrayIterator($this->definition); - } -} - +. + */ +Doctrine::autoload('Doctrine_Access'); +/** + * class Doctrine_Schema_Object + * Catches any non-property call from child classes and throws an exception. + * + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + * @author Jukka Hassinen + */ +abstract class Doctrine_Schema_Object extends Doctrine_Access implements IteratorAggregate, Countable { + + protected $children = array(); + + protected $definition = array('name' => ''); + + public function __construct(array $definition = array()) { + foreach ($this->definition as $key => $val) { + if (isset($definition[$key])) { + $this->definition[$key] = $definition[$key]; + } + } + } + + public function get($name) { + if ( ! array_key_exists($name, $this->definition)) { + throw new Doctrine_Schema_Exception('Unknown definition '. $name); + } + return $this->definition[$name]; + + } + + public function set($name, $value) { + if ( ! array_key_exists($name, $this->definition)) { + throw new Doctrine_Schema_Exception('Unknown definition '. $name); + } + $this->definition[$name] = $value; + } + + public function contains($name) { + return array_key_exists($name, $this->definition); + } + + public function toArray() { + return $this->definition; + } + /** + * + * @return int + * @access public + */ + public function count() { + if ( ! empty($this->children)) { + return count($this->children); + } + return count($this->definition); + } + + /** + * getIterator + * + * @return ArrayIterator + * @access public + */ + public function getIterator() { + if ( ! empty($this->children)) { + return new ArrayIterator($this->children); + } + return new ArrayIterator($this->definition); + } +} diff --git a/lib/Doctrine/Schema/Relation.php b/lib/Doctrine/Schema/Relation.php index d6c503eb3..347178329 100644 --- a/lib/Doctrine/Schema/Relation.php +++ b/lib/Doctrine/Schema/Relation.php @@ -1,123 +1,122 @@ -. - */ -Doctrine::autoload('Doctrine_Schema_Object'); -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ - */ -/** - * class Doctrine_Schema_Relation - * Holds information on a foreign key relation. - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Schema_Relation extends Doctrine_Schema_Object { - - /** - * Column that refers to another table - * @access public - */ - public $referencingColumn; - - /** - * Column that is referred from another table - * @access public - */ - public $referencedColumn; - - /** - * Table where the referred column lives - * @access public - * - */ - public $referencedTable; - - /** - * ON UPDATE or ON DELETE action - * @static - * @access public - */ - public static $ACTION_RESTRICT = 1; - - /** - * ON UPDATE or ON DELETE action - * @static - * @access public - */ - public static $ACTION_SET_NULL = 2; - - /** - * ON UPDATE or ON DELETE action - * @static - * @access public - */ - public static $ACTION_CASCADE = 3; - - /** - * ON UPDATE or ON DELETE action - * @static - * @access public - */ - public static $ACTION_NO_ACTION = 4; - - /** - * ON UPDATE or ON DELETE action - * @static - * @access public - */ - public static $ACTION_SET_DEFAULT = 5; - - - /** - * - * @param Doctrine_Schema_Column referencing - * @param Doctrine_Schema_Table referencedtable - * @param Doctrine_Schema_Column referencedColumn - * @return - * @access public - */ - public function setRelationBetween( $referencingColumn, $referencedTable, $referencedColumn ) { - $this->referencingColumn = $referencingColumn; - $this->referencedTable = $referencedTable; - $this->referencedColumn = $referencedColumn; - } - /** - * @return string - */ - public function __toString( ) { - return "Relation between '".$this->referencingColumn."' and '".$this->referencedTable."'.'".$this->referencingColumn."'"; - } - /** - * - * @return bool - */ - public function isValid( ) { - - } -} +. + */ +Doctrine::autoload('Doctrine_Schema_Object'); +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ + */ +/** + * class Doctrine_Schema_Relation + * Holds information on a foreign key relation. + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Schema_Relation extends Doctrine_Schema_Object { + + /** + * Column that refers to another table + * @access public + */ + public $referencingColumn; + + /** + * Column that is referred from another table + * @access public + */ + public $referencedColumn; + + /** + * Table where the referred column lives + * @access public + * + */ + public $referencedTable; + + /** + * ON UPDATE or ON DELETE action + * @static + * @access public + */ + public static $ACTION_RESTRICT = 1; + + /** + * ON UPDATE or ON DELETE action + * @static + * @access public + */ + public static $ACTION_SET_NULL = 2; + + /** + * ON UPDATE or ON DELETE action + * @static + * @access public + */ + public static $ACTION_CASCADE = 3; + + /** + * ON UPDATE or ON DELETE action + * @static + * @access public + */ + public static $ACTION_NO_ACTION = 4; + + /** + * ON UPDATE or ON DELETE action + * @static + * @access public + */ + public static $ACTION_SET_DEFAULT = 5; + + /** + * + * @param Doctrine_Schema_Column referencing + * @param Doctrine_Schema_Table referencedtable + * @param Doctrine_Schema_Column referencedColumn + * @return + * @access public + */ + public function setRelationBetween( $referencingColumn, $referencedTable, $referencedColumn ) { + $this->referencingColumn = $referencingColumn; + $this->referencedTable = $referencedTable; + $this->referencedColumn = $referencedColumn; + } + /** + * @return string + */ + public function __toString( ) { + return "Relation between '".$this->referencingColumn."' and '".$this->referencedTable."'.'".$this->referencingColumn."'"; + } + /** + * + * @return bool + */ + public function isValid( ) { + + } +} diff --git a/lib/Doctrine/Schema/Table.php b/lib/Doctrine/Schema/Table.php index 6dbe92096..ec2f0cc92 100644 --- a/lib/Doctrine/Schema/Table.php +++ b/lib/Doctrine/Schema/Table.php @@ -1,106 +1,106 @@ -. - */ -Doctrine::autoload('Doctrine_Schema_Object'); -/** - * @package Doctrine - * @url http://www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @author Jukka Hassinen - * @version $Id$ - */ -/** - * class Doctrine_Schema_Table - * Holds information on a database table - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Schema_Table extends Doctrine_Schema_Object implements Countable, IteratorAggregate { - - protected $definition = array('name' => '', - 'check' => '', - 'charset' => '', - 'description' => ''); - /** - * Relations this table has with others. An array of Doctrine_Schema_Relation - */ - private $relations = array(); - /** - * - * @return bool - * @access public - */ - public function isValid( ) { - - } - /** - * returns an array of Doctrine_Schema_Column objects - * - * @return array - */ - public function getColumns() { - return $this->children; - } - /** - * @return Doctrine_Schema_Column|false - */ - public function getColumn($name) { - if( ! isset($this->children[$name])) - return false; - - return $this->children[$name]; - } - /** - * - * @param Doctrine_Schema_Column column - * @return Doctrine_Schema_Table - * @access public - */ - public function addColumn(Doctrine_Schema_Column $column) { - $name = $column->get('name'); - $this->children[$name] = $column; - - return $this; - } - - /** - * Adds a relation between a local column and a 2nd table / column - * - * @param Doctrine_Schema_Relation Relation - * - */ - public function setRelation(Doctrine_Schema_Relation $relation){ - $this->relations[] = $relation; - } - /** - * Return all the relations this table has with others - * - * @return array Array of Doctrine_Schema_Relation - */ - public function getRelations(){ - return $this->relations; - } - -} +. + */ +Doctrine::autoload('Doctrine_Schema_Object'); +/** + * @package Doctrine + * @url http://www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @author Jukka Hassinen + * @version $Id$ + */ +/** + * class Doctrine_Schema_Table + * Holds information on a database table + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Schema_Table extends Doctrine_Schema_Object implements Countable, IteratorAggregate { + + protected $definition = array('name' => '', + 'check' => '', + 'charset' => '', + 'description' => ''); + /** + * Relations this table has with others. An array of Doctrine_Schema_Relation + */ + private $relations = array(); + /** + * + * @return bool + * @access public + */ + public function isValid( ) { + + } + /** + * returns an array of Doctrine_Schema_Column objects + * + * @return array + */ + public function getColumns() { + return $this->children; + } + /** + * @return Doctrine_Schema_Column|false + */ + public function getColumn($name) { + if ( ! isset($this->children[$name])) { + return false; + } + return $this->children[$name]; + } + /** + * + * @param Doctrine_Schema_Column column + * @return Doctrine_Schema_Table + * @access public + */ + public function addColumn(Doctrine_Schema_Column $column) { + $name = $column->get('name'); + $this->children[$name] = $column; + + return $this; + } + + /** + * Adds a relation between a local column and a 2nd table / column + * + * @param Doctrine_Schema_Relation Relation + * + */ + public function setRelation(Doctrine_Schema_Relation $relation){ + $this->relations[] = $relation; + } + /** + * Return all the relations this table has with others + * + * @return array Array of Doctrine_Schema_Relation + */ + public function getRelations(){ + return $this->relations; + } + +} diff --git a/lib/Doctrine/Table.php b/lib/Doctrine/Table.php index 152dcc4d0..7582b508d 100644 --- a/lib/Doctrine/Table.php +++ b/lib/Doctrine/Table.php @@ -76,9 +76,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { /** * @var array $columns an array of column definitions, * keys as column names and values as column definitions - * + * * the value array has three values: - * + * * the column type, eg. 'integer' * the column length, eg. 11 * the column options/constraints/validators. eg array('notnull' => true) @@ -135,9 +135,6 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { 'enumMap' => array(), ); - - - /** * the constructor * @throws Doctrine_Connection_Exception if there are no opened connections @@ -151,9 +148,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { $this->options['name'] = $name; - if( ! class_exists($name) || empty($name)) + if ( ! class_exists($name) || empty($name)) { throw new Doctrine_Exception("Couldn't find class $name"); - + } $record = new $name($this); $names = array(); @@ -163,98 +160,97 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { // get parent classes do { - if($class == "Doctrine_Record") + if ($class == "Doctrine_Record") break; - $name = $class; + $name = $class; $names[] = $name; - } while($class = get_parent_class($class)); + } while ($class = get_parent_class($class)); // reverse names $names = array_reverse($names); // create database table - if(method_exists($record, 'setTableDefinition')) { + if (method_exists($record, 'setTableDefinition')) { $record->setTableDefinition(); $this->columnCount = count($this->columns); - if(isset($this->columns)) { - + if (isset($this->columns)) { // get the declaring class of setTableDefinition method $method = new ReflectionMethod($this->options['name'], 'setTableDefinition'); $class = $method->getDeclaringClass(); - if( ! isset($this->options['tableName'])) + if ( ! isset($this->options['tableName'])) { $this->options['tableName'] = Doctrine::tableize($class->getName()); + } + switch (count($this->primaryKeys)) { + case 0: + $this->columns = array_merge(array('id' => + array('integer', + 20, + array('autoincrement' => true, + 'primary' => true + ) + ) + ), $this->columns); - switch(count($this->primaryKeys)): - case 0: - $this->columns = array_merge(array('id' => - array('integer', - 20, - array('autoincrement' => true, - 'primary' => true - ) - ) - ), $this->columns); - - $this->primaryKeys[] = 'id'; - $this->identifier = 'id'; - $this->identifierType = Doctrine_Identifier::AUTO_INCREMENT; - $this->columnCount++; + $this->primaryKeys[] = 'id'; + $this->identifier = 'id'; + $this->identifierType = Doctrine_Identifier::AUTO_INCREMENT; + $this->columnCount++; break; - default: - if(count($this->primaryKeys) > 1) { - $this->identifier = $this->primaryKeys; - $this->identifierType = Doctrine_Identifier::COMPOSITE; + default: + if (count($this->primaryKeys) > 1) { + $this->identifier = $this->primaryKeys; + $this->identifierType = Doctrine_Identifier::COMPOSITE; - } else { - foreach($this->primaryKeys as $pk) { - $e = $this->columns[$pk][2]; + } else { + foreach ($this->primaryKeys as $pk) { + $e = $this->columns[$pk][2]; - $found = false; + $found = false; - foreach($e as $option => $value) { - if($found) - break; + foreach ($e as $option => $value) { + if ($found) + break; - $e2 = explode(":",$option); + $e2 = explode(":",$option); - switch(strtolower($e2[0])): - case "autoincrement": - $this->identifierType = Doctrine_Identifier::AUTO_INCREMENT; - $found = true; - break; - case "seq": - $this->identifierType = Doctrine_Identifier::SEQUENCE; - $found = true; - break; - endswitch; - } - if( ! isset($this->identifierType)) - $this->identifierType = Doctrine_Identifier::NORMAL; - - $this->identifier = $pk; + switch (strtolower($e2[0])) { + case "autoincrement": + $this->identifierType = Doctrine_Identifier::AUTO_INCREMENT; + $found = true; + break; + case "seq": + $this->identifierType = Doctrine_Identifier::SEQUENCE; + $found = true; + break; + }; } + if ( ! isset($this->identifierType)) { + $this->identifierType = Doctrine_Identifier::NORMAL; + } + $this->identifier = $pk; } - endswitch; - - if($this->getAttribute(Doctrine::ATTR_CREATE_TABLES)) { - if(Doctrine::isValidClassname($class->getName())) { + } + }; + + if ($this->getAttribute(Doctrine::ATTR_CREATE_TABLES)) { + if (Doctrine::isValidClassname($class->getName())) { try { $columns = array(); - foreach($this->columns as $name => $column) { + foreach ($this->columns as $name => $column) { $definition = $column[2]; $definition['type'] = $column[0]; $definition['length'] = $column[1]; - if($definition['type'] == 'enum' && isset($definition['default'])) + if ($definition['type'] == 'enum' && isset($definition['default'])) { $definition['default'] = $this->enumIndex($name, $definition['default']); - - if($definition['type'] == 'boolean' && isset($definition['default'])) + } + if ($definition['type'] == 'boolean' && isset($definition['default'])) { $definition['default'] = (int) $definition['default']; - + } $columns[$name] = $definition; } @@ -265,13 +261,11 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { } } - } } else { throw new Doctrine_Table_Exception("Class '$name' has no table definition."); } - $record->setUp(); // save parents @@ -281,16 +275,16 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { $this->query = "SELECT ".implode(", ",array_keys($this->columns))." FROM ".$this->getTableName(); // check if an instance of this table is already initialized - if( ! $this->conn->addTable($this)) + if ( ! $this->conn->addTable($this)) { throw new Doctrine_Table_Exception(); - + } $this->repository = new Doctrine_Table_Repository($this); } /** * createQuery * creates a new Doctrine_Query object and adds the component name * of this table as the query 'from' part - * + * * @return Doctrine_Query */ public function createQuery() { @@ -304,28 +298,29 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { public function getRepository() { return $this->repository; } - + public function setOption($name, $value) { - switch($name) { - case 'name': - case 'tableName': + switch ($name) { + case 'name': + case 'tableName': break; - case 'enumMap': - case 'inheritanceMap': - if( ! is_array($value)) - throw new Doctrine_Table_Exception($name.' should be an array.'); + case 'enumMap': + case 'inheritanceMap': + if ( ! is_array($value)) { + throw new Doctrine_Table_Exception($name.' should be an array.'); + } break; } $this->options[$name] = $value; } - + public function usesInheritanceMap() { return ( ! empty($this->options['inheritanceMap'])); } public function getOption($name) { - if(isset($this->options[$name])) + if (isset($this->options[$name])) { return $this->options[$name]; - + } return null; } /** @@ -337,28 +332,28 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return void */ final public function setColumn($name, $type, $length = null, $options = array()) { - if(is_string($options)) + if (is_string($options)) { $options = explode('|', $options); - - foreach($options as $k => $option) { - if(is_numeric($k)) { - if( ! empty($option)) + } + foreach ($options as $k => $option) { + if (is_numeric($k)) { + if ( ! empty($option)) { $options[$option] = true; - + } unset($options[$k]); } } $name = strtolower($name); - - if($length == null) + + if ($length == null) $length = 2147483647; $this->columns[$name] = array($type, $length, $options); - if(isset($options['primary'])) { + if (isset($options['primary'])) { $this->primaryKeys[] = $name; } - if(isset($options['default'])) { + if (isset($options['default'])) { $this->hasDefaultValues = true; } } @@ -380,14 +375,14 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { */ public function getDefaultValueOf($column) { $column = strtolower($column); - if( ! isset($this->columns[$column])) + if ( ! isset($this->columns[$column])) { throw new Doctrine_Table_Exception("Couldn't get default value. Column ".$column." doesn't exist."); - - if(isset($this->columns[$column][2]['default'])) { - + } + if (isset($this->columns[$column][2]['default'])) { return $this->columns[$column][2]['default']; - } else + } else { return null; + } } /** * @return mixed @@ -413,14 +408,14 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return void */ final public function setPrimaryKey($key) { - switch(gettype($key)): - case "array": - $this->primaryKeys = array_values($key); + switch (gettype($key)) { + case "array": + $this->primaryKeys = array_values($key); break; - case "string": - $this->primaryKeys[] = $key; + case "string": + $this->primaryKeys[] = $key; break; - endswitch; + }; } /** * returns all primary keys @@ -473,22 +468,22 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { final public function getCompositePaths() { $array = array(); $name = $this->getComponentName(); - foreach($this->bound as $k=>$a) { + foreach ($this->bound as $k=>$a) { try { $fk = $this->getRelation($k); - switch($fk->getType()): - case Doctrine_Relation::ONE_COMPOSITE: - case Doctrine_Relation::MANY_COMPOSITE: - $n = $fk->getTable()->getComponentName(); - $array[] = $name.".".$n; - $e = $fk->getTable()->getCompositePaths(); - if( ! empty($e)) { - foreach($e as $name) { - $array[] = $name.".".$n.".".$name; - } + switch ($fk->getType()) { + case Doctrine_Relation::ONE_COMPOSITE: + case Doctrine_Relation::MANY_COMPOSITE: + $n = $fk->getTable()->getComponentName(); + $array[] = $name.".".$n; + $e = $fk->getTable()->getCompositePaths(); + if ( ! empty($e)) { + foreach ($e as $name) { + $array[] = $name.".".$n.".".$name; } + } break; - endswitch; + }; } catch(Doctrine_Table_Exception $e) { } @@ -510,9 +505,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return array */ public function getBound($name) { - if( ! isset($this->bound[$name])) + if ( ! isset($this->bound[$name])) { throw new Doctrine_Table_Exception('Unknown bound '.$name); - + } return $this->bound[$name]; } /** @@ -523,10 +518,10 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { */ public function getBoundForName($name, $component) { - foreach($this->bound as $k => $bound) { + foreach ($this->bound as $k => $bound) { $e = explode('.', $bound[0]); - if($bound[3] == $name && $e[0] == $component) { + if ($bound[3] == $name && $e[0] == $component) { return $this->bound[$k]; } } @@ -539,9 +534,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return string */ public function getAlias($name) { - if(isset($this->boundAliases[$name])) + if (isset($this->boundAliases[$name])) { return $this->boundAliases[$name]; - + } return $name; } /** @@ -551,9 +546,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return string */ public function getAliasName($alias) { - if($name = array_search($alias, $this->boundAliases)) + if ($name = array_search($alias, $this->boundAliases)) { return $name; - + } return $alias; } /** @@ -574,17 +569,17 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return boolean */ public function unbind($name) { - if( ! isset($this->bound[$name])) + if ( ! isset($this->bound[$name])) { return false; - + } unset($this->bound[$name]); - if(isset($this->relations[$name])) + if (isset($this->relations[$name])) { unset($this->relations[$name]); - - if(isset($this->boundAliases[$name])) + } + if (isset($this->boundAliases[$name])) { unset($this->boundAliases[$name]); - + } return true; } /** @@ -595,18 +590,18 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return void */ public function bind($name, $field, $type, $localKey) { - if(isset($this->relations[$name])) + if (isset($this->relations[$name])) { unset($this->relations[$name]); - + } $e = explode(" as ",$name); $name = $e[0]; - if(isset($e[1])) { + if (isset($e[1])) { $alias = $e[1]; $this->boundAliases[$name] = $alias; - } else + } else { $alias = $name; - + } $this->bound[$alias] = array($field, $type, $localKey, $name); } @@ -635,13 +630,13 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return boolean */ final public function hasRelation($name) { - if(isset($this->bound[$name])) + if (isset($this->bound[$name])) { return true; - - foreach($this->bound as $k=>$v) - { - if($this->hasRelatedComponent($k, $name)) + } + foreach ($this->bound as $k=>$v) { + if ($this->hasRelatedComponent($k, $name)) { return true; + } } return false; } @@ -654,10 +649,10 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { final public function getRelation($name, $recursive = true) { $original = $name; - if(isset($this->relations[$name])) - return $this->relations[$name]; - - if(isset($this->bound[$name])) { + if (isset($this->relations[$name])) { + return $this->relations[$name]; + } + if (isset($this->bound[$name])) { $type = $this->bound[$name][1]; $local = $this->bound[$name][2]; list($component, $foreign) = explode(".",$this->bound[$name][0]); @@ -666,25 +661,24 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { $table = $this->conn->getTable($name); - if($component == $this->options['name'] || in_array($component, $this->parents)) { - + if ($component == $this->options['name'] || in_array($component, $this->parents)) { // ONE-TO-ONE - if($type == Doctrine_Relation::ONE_COMPOSITE || + if ($type == Doctrine_Relation::ONE_COMPOSITE || $type == Doctrine_Relation::ONE_AGGREGATE) { - if( ! isset($local)) + if ( ! isset($local)) { $local = $table->getIdentifier(); - + } $relation = new Doctrine_Relation_LocalKey($table, $foreign, $local, $type, $alias); - } else + } else { $relation = new Doctrine_Relation_ForeignKey($table, $foreign, $local, $type, $alias); + } - - } elseif($component == $name || + } elseif ($component == $name || ($component == $alias)) { // && ($name == $this->options['name'] || in_array($name,$this->parents)) - if( ! isset($local)) + if ( ! isset($local)) { $local = $this->identifier; - + } // ONE-TO-MANY or ONE-TO-ONE $relation = new Doctrine_Relation_ForeignKey($table, $local, $foreign, $type, $alias); @@ -692,34 +686,33 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { // MANY-TO-MANY // only aggregate relations allowed - if($type != Doctrine_Relation::MANY_AGGREGATE) + if ($type != Doctrine_Relation::MANY_AGGREGATE) throw new Doctrine_Table_Exception("Only aggregate relations are allowed for many-to-many relations"); $classes = array_merge($this->parents, array($this->options['name'])); - foreach(array_reverse($classes) as $class) { + foreach (array_reverse($classes) as $class) { try { $bound = $table->getBoundForName($class, $component); break; } catch(Doctrine_Table_Exception $exc) { } } - if( ! isset($bound)) + if ( ! isset($bound)) { throw new Doctrine_Table_Exception("Couldn't map many-to-many relation for " . $this->options['name'] . " and $name. Components use different join tables."); - - - if( ! isset($local)) + } + if ( ! isset($local)) { $local = $this->identifier; - + } $e2 = explode('.', $bound[0]); $fields = explode('-', $e2[1]); - if($e2[0] != $component) + if ($e2[0] != $component) throw new Doctrine_Table_Exception($e2[0] . ' doesn\'t match ' . $component); $associationTable = $this->conn->getTable($e2[0]); - if(count($fields) > 1) { + if (count($fields) > 1) { // SELF-REFERENCING THROUGH JOIN TABLE $this->relations[$e2[0]] = new Doctrine_Relation_ForeignKey($associationTable, $local, $fields[0],Doctrine_Relation::MANY_COMPOSITE, $e2[0]); @@ -744,11 +737,11 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { // load all relations $this->getRelations(); - - if($recursive) { + + if ($recursive) { return $this->getRelation($original, false); } else { - throw new Doctrine_Table_Exception($this->options['name'] . " doesn't have a relation to " . $original); + throw new Doctrine_Table_Exception($this->options['name'] . " doesn't have a relation to " . $original); } } /** @@ -758,7 +751,7 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { */ final public function getRelations() { $a = array(); - foreach($this->bound as $k=>$v) { + foreach ($this->bound as $k=>$v) { $this->getRelation($k); } @@ -802,25 +795,25 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return Doctrine_Record|false a record for given database identifier */ public function find($id) { - if($id !== null) { - if( ! is_array($id)) + if ($id !== null) { + if ( ! is_array($id)) { $id = array($id); - else + } else { $id = array_values($id); + } $query = $this->query." WHERE ".implode(" = ? AND ",$this->primaryKeys)." = ?"; $query = $this->applyInheritance($query); - $params = array_merge($id, array_values($this->options['inheritanceMap'])); $stmt = $this->conn->execute($query,$params); $this->data = $stmt->fetch(PDO::FETCH_ASSOC); - if($this->data === false) + if ($this->data === false) return false; - + return $this->getRecord(); } return false; @@ -831,9 +824,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @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) { + foreach ($this->options['inheritanceMap'] as $field => $value) { $a[] = $field." = ?"; } $i = implode(" AND ",$a); @@ -891,21 +884,21 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { $key = $this->getIdentifier(); - if( ! is_array($key)) + if ( ! is_array($key)) { $key = array($key); - - foreach($key as $k) { - if( ! isset($this->data[$k])) + } + foreach ($key as $k) { + if ( ! isset($this->data[$k])) { throw new Doctrine_Exception("Primary key value for $k wasn't found"); - + } $id[] = $this->data[$k]; } $id = implode(' ', $id); - if(isset($this->identityMap[$id])) + if (isset($this->identityMap[$id])) { $record = $this->identityMap[$id]; - else { + } else { $record = new $this->options['name']($this); $this->identityMap[$id] = $record; } @@ -918,7 +911,7 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @throws Doctrine_Find_Exception */ final public function getProxy($id = null) { - if($id !== null) { + if ($id !== null) { $query = "SELECT ".implode(", ",$this->primaryKeys)." FROM ".$this->getTableName()." WHERE ".implode(" = ? && ",$this->primaryKeys)." = ?"; $query = $this->applyInheritance($query); @@ -926,7 +919,7 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { $this->data = $this->conn->execute($query,$params)->fetch(PDO::FETCH_ASSOC); - if($this->data === false) + if ($this->data === false) return false; } return $this->getRecord(); @@ -958,7 +951,7 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { public function execute($query, array $array = array(), $limit = null, $offset = null) { $coll = new Doctrine_Collection($this); $query = $this->conn->modifyLimitQuery($query,$limit,$offset); - if( ! empty($array)) { + if ( ! empty($array)) { $stmt = $this->conn->getDBH()->prepare($query); $stmt->execute($array); } else { @@ -967,7 +960,7 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { $data = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->closeCursor(); - foreach($data as $row) { + foreach ($data as $row) { $this->data = $row; $record = $this->getRecord(); $coll->add($record); @@ -989,10 +982,11 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return array */ final public function getEnumValues($field) { - if(isset($this->options['enumMap'][$field])) + if (isset($this->options['enumMap'][$field])) { return $this->options['enumMap'][$field]; - else + } else { return array(); + } } /** * enumValue @@ -1013,16 +1007,16 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @param mixed $value */ public function invokeSet(Doctrine_Record $record, $name, $value) { - if( ! ($this->getAttribute(Doctrine::ATTR_ACCESSORS) & Doctrine::ACCESSOR_SET)) + if ( ! ($this->getAttribute(Doctrine::ATTR_ACCESSORS) & Doctrine::ACCESSOR_SET)) { return $value; - + } $prefix = $this->getAttribute(Doctrine::ATTR_ACCESSOR_PREFIX_SET); if (!$prefix) $prefix = 'set'; $method = $prefix . $name; - if(method_exists($record, $method)) { + if (method_exists($record, $method)) { return $record->$method($value); } @@ -1034,16 +1028,16 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @param mixed $value */ public function invokeGet(Doctrine_Record $record, $name, $value) { - if( ! ($this->getAttribute(Doctrine::ATTR_ACCESSORS) & Doctrine::ACCESSOR_GET)) + if ( ! ($this->getAttribute(Doctrine::ATTR_ACCESSORS) & Doctrine::ACCESSOR_GET)) { return $value; - + } $prefix = $this->getAttribute(Doctrine::ATTR_ACCESSOR_PREFIX_GET); if (!$prefix) $prefix = 'get'; $method = $prefix . $name; - if(method_exists($record, $method)) { + if (method_exists($record, $method)) { return $record->$method($value); } @@ -1057,10 +1051,11 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return mixed */ final public function enumIndex($field, $value) { - if( ! isset($this->options['enumMap'][$field])) + if ( ! isset($this->options['enumMap'][$field])) { $values = array(); - else + } else { $values = $this->options['enumMap'][$field]; + } return array_search($value, $values); } @@ -1070,9 +1065,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return string ValueWrapper class name on success, false on failure */ public function getValueWrapperOf($column) { - if(isset($this->columns[$column][2]['wrapper'])) + if (isset($this->columns[$column][2]['wrapper'])) { return $this->columns[$column][2]['wrapper']; - + } return false; } /** @@ -1107,9 +1102,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return mixed array on success, false on failure */ public function getDefinitionOf($column) { - if(isset($this->columns[$column])) + if (isset($this->columns[$column])) { return $this->columns[$column]; - + } return false; } /** @@ -1118,9 +1113,9 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { * @return mixed string on success, false on failure */ public function getTypeOf($column) { - if(isset($this->columns[$column])) + if (isset($this->columns[$column])) { return $this->columns[$column][0]; - + } return false; } /** @@ -1171,4 +1166,3 @@ class Doctrine_Table extends Doctrine_Configurable implements Countable { return Doctrine_Lib::getTableAsString($this); } } - diff --git a/lib/Doctrine/Table/Exception.php b/lib/Doctrine/Table/Exception.php index 1a997c984..c733c75ee 100644 --- a/lib/Doctrine/Table/Exception.php +++ b/lib/Doctrine/Table/Exception.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @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) @@ -38,4 +38,3 @@ class Doctrine_Table_Exception extends Doctrine_Exception { parent::__construct($message); } } - diff --git a/lib/Doctrine/Table/Repository.php b/lib/Doctrine/Table/Repository.php index 5d399728d..c3737c4f3 100644 --- a/lib/Doctrine/Table/Repository.php +++ b/lib/Doctrine/Table/Repository.php @@ -23,14 +23,14 @@ * each record is added into Doctrine_Repository at the same time they are created, * loaded from the database or retrieved from the cache * - * @author Konsta Vesterinen - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Table_Repository implements Countable, IteratorAggregate { /** * @var object Doctrine_Table $table @@ -67,9 +67,9 @@ class Doctrine_Table_Repository implements Countable, IteratorAggregate { public function add(Doctrine_Record $record) { $oid = $record->getOID(); - if(isset($this->registry[$oid])) + if (isset($this->registry[$oid])) { return false; - + } $this->registry[$oid] = $record; return true; @@ -80,9 +80,9 @@ class Doctrine_Table_Repository implements Countable, IteratorAggregate { * @throws Doctrine_Table_Repository_Exception */ public function get($oid) { - if( ! isset($this->registry[$oid])) + if ( ! isset($this->registry[$oid])) { throw new Doctrine_Table_Repository_Exception("Unknown object identifier"); - + } return $this->registry[$oid]; } /** @@ -98,9 +98,9 @@ class Doctrine_Table_Repository implements Countable, IteratorAggregate { * @return boolean 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; } @@ -109,9 +109,10 @@ class Doctrine_Table_Repository implements Countable, IteratorAggregate { */ public function evictAll() { $evicted = 0; - foreach($this->registry as $oid=>$record) { - if($this->evict($oid)) + foreach ($this->registry as $oid=>$record) { + if ($this->evict($oid)) { $evicted++; + } } return $evicted; } @@ -137,4 +138,3 @@ class Doctrine_Table_Repository implements Countable, IteratorAggregate { $this->table->findAll(); } } - diff --git a/lib/Doctrine/Table/Repository/Exception.php b/lib/Doctrine/Table/Repository/Exception.php index 44113e515..4268a7aee 100644 --- a/lib/Doctrine/Table/Repository/Exception.php +++ b/lib/Doctrine/Table/Repository/Exception.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_Table_Repository_Exception extends Doctrine_Exception { } diff --git a/lib/Doctrine/Transaction.php b/lib/Doctrine/Transaction.php index 7cb160668..b4afb1d94 100644 --- a/lib/Doctrine/Transaction.php +++ b/lib/Doctrine/Transaction.php @@ -68,15 +68,15 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { * @return integer the connection state */ public function getState() { - switch($this->transactionLevel) { - case 0: - return Doctrine_Transaction::STATE_SLEEP; + switch ($this->transactionLevel) { + case 0: + return Doctrine_Transaction::STATE_SLEEP; break; - case 1: - return Doctrine_Transaction::STATE_ACTIVE; + case 1: + return Doctrine_Transaction::STATE_ACTIVE; break; - default: - return Doctrine_Transaction::STATE_BUSY; + default: + return Doctrine_Transaction::STATE_BUSY; } } /** @@ -86,19 +86,19 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { public function addDelete(Doctrine_Record $record) { $name = $record->getTable()->getComponentName(); $this->delete[$name][] = $record; - } + } /** * addInvalid * adds record into invalid records list * * @param Doctrine_Record $record - * @return boolean false if record already existed in invalid records list, + * @return boolean false if record already existed in invalid records list, * otherwise true */ public function addInvalid(Doctrine_Record $record) { - if(in_array($record, $this->invalid)) + if (in_array($record, $this->invalid)) { return false; - + } $this->invalid[] = $record; return true; } @@ -118,19 +118,19 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { * @return void */ public function bulkDelete() { - foreach($this->delete as $name => $deletes) { + foreach ($this->delete as $name => $deletes) { $record = false; $ids = array(); - foreach($deletes as $k => $record) { + foreach ($deletes as $k => $record) { $ids[] = $record->getIncremented(); $record->assignIdentifier(false); } - if($record instanceof Doctrine_Record) { + if ($record instanceof Doctrine_Record) { $params = substr(str_repeat("?, ",count($ids)),0,-2); - + $query = 'DELETE FROM ' - . $record->getTable()->getTableName() - . ' WHERE ' + . $record->getTable()->getTableName() + . ' WHERE ' . $record->getTable()->getIdentifier() . ' IN(' . $params . ')'; @@ -153,7 +153,7 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { * beginTransaction * Start a transaction or set a savepoint. * - * if trying to set a savepoint and there is no active transaction + * if trying to set a savepoint and there is no active transaction * a new transaction is being started * * Listeners: onPreTransactionBegin, onTransactionBegin @@ -162,15 +162,14 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { * @return integer current transaction nesting level */ public function beginTransaction($savepoint = null) { - if( ! is_null($savepoint)) { + if ( ! is_null($savepoint)) { $this->beginTransaction(); $this->savePoints[] = $savepoint; - $this->createSavePoint($savepoint); } else { - if($this->transactionLevel == 0) { + if ($this->transactionLevel == 0) { $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionBegin($this->conn); $this->conn->getDbh()->beginTransaction(); @@ -181,14 +180,13 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { $level = ++$this->transactionLevel; - return $level; } /** * commit * Commit the database changes done during a transaction that is in * progress or release a savepoint. This function may only be called when - * auto-committing is disabled, otherwise it will fail. + * auto-committing is disabled, otherwise it will fail. * * Listeners: onPreTransactionCommit, onTransactionCommit * @@ -198,17 +196,16 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { * @return boolean false if commit couldn't be performed, true otherwise */ public function commit($savepoint = null) { - if($this->transactionLevel == 0) + if ($this->transactionLevel == 0) return false; if ( ! is_null($savepoint)) { $this->transactionLevel = $this->removeSavePoints($savepoint); $this->releaseSavePoint($savepoint); - } else { - if($this->transactionLevel == 1) { + } else { + if ($this->transactionLevel == 1) { $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionCommit($this->conn); - try { $this->bulkDelete(); @@ -218,9 +215,9 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { throw new Doctrine_Connection_Transaction_Exception($e->__toString()); } - if( ! empty($this->invalid)) { + if ( ! empty($this->invalid)) { $this->rollback(); - + $tmp = $this->invalid; $this->invalid = array(); @@ -228,13 +225,13 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { } $this->conn->getDbh()->commit(); - + //$this->conn->unitOfWork->reset(); - + $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionCommit($this->conn); } } - + $this->transactionLevel--; return true; @@ -253,13 +250,12 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { * @return boolean false if rollback couldn't be performed, true otherwise */ public function rollback($savepoint = null) { - if($this->transactionLevel == 0) + if ($this->transactionLevel == 0) return false; $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionRollback($this->conn); - if( ! is_null($savepoint)) { - + if ( ! is_null($savepoint)) { $this->transactionLevel = $this->removeSavePoints($savepoint); $this->rollbackSavePoint($savepoint); @@ -272,7 +268,7 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { $this->conn->getDbh()->rollback(); } $this->conn->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionRollback($this->conn); - + return true; } /** @@ -318,7 +314,7 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { $c = count($this->savePoints); - for($x = $i; $x < count($this->savePoints); $x++) { + for ($x = $i; $x < count($this->savePoints); $x++) { unset($this->savePoints[$x]); } return ($c - $i); @@ -354,7 +350,7 @@ class Doctrine_Transaction extends Doctrine_Connection_Module { * * fetches the current session transaction isolation level * - * note: some drivers may support setting the 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 diff --git a/lib/Doctrine/Transaction/Exception.php b/lib/Doctrine/Transaction/Exception.php index 65b83ec99..540d27fd3 100644 --- a/lib/Doctrine/Transaction/Exception.php +++ b/lib/Doctrine/Transaction/Exception.php @@ -1,5 +1,5 @@ conn->getDbh()->query($query); } /** @@ -52,7 +52,7 @@ class Doctrine_Transaction_Firebird extends Doctrine_Transaction { */ protected function releaseSavePoint($savepoint) { $query = 'RELEASE SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -64,7 +64,7 @@ class Doctrine_Transaction_Firebird extends Doctrine_Transaction { */ protected function rollbackSavePoint($savepoint) { $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -101,10 +101,10 @@ class Doctrine_Transaction_Firebird extends Doctrine_Transaction { default: throw new Doctrine_Transaction_Exception('isolation level is not supported: ' . $isolation); } - + $rw = $wait = ''; - if(isset($options['wait'])) { + if (isset($options['wait'])) { switch ($options['wait']) { case 'WAIT': case 'NO WAIT': @@ -115,7 +115,7 @@ class Doctrine_Transaction_Firebird extends Doctrine_Transaction { } } - if(isset($options['rw'])) { + if (isset($options['rw'])) { switch ($options['rw']) { case 'READ ONLY': case 'READ WRITE': diff --git a/lib/Doctrine/Transaction/Mssql.php b/lib/Doctrine/Transaction/Mssql.php index a58a29227..aadc6119f 100644 --- a/lib/Doctrine/Transaction/Mssql.php +++ b/lib/Doctrine/Transaction/Mssql.php @@ -30,7 +30,7 @@ Doctrine::autoload('Doctrine_Transaction'); * @since 1.0 * @version $Revision$ */ -class Doctrine_Transaction_Mssql extends Doctrine_Transaction { +class Doctrine_Transaction_Mssql extends Doctrine_Transaction { /** * Set the transacton isolation level. * diff --git a/lib/Doctrine/Transaction/Mysql.php b/lib/Doctrine/Transaction/Mysql.php index 28e713624..cd342ddc6 100644 --- a/lib/Doctrine/Transaction/Mysql.php +++ b/lib/Doctrine/Transaction/Mysql.php @@ -40,7 +40,7 @@ class Doctrine_Transaction_Mysql extends Doctrine_Transaction { */ protected function createSavePoint($savepoint) { $query = 'SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -64,7 +64,7 @@ class Doctrine_Transaction_Mysql extends Doctrine_Transaction { */ protected function rollbackSavePoint($savepoint) { $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -86,7 +86,7 @@ class Doctrine_Transaction_Mysql extends Doctrine_Transaction { case 'READ COMMITTED': case 'REPEATABLE READ': case 'SERIALIZABLE': - + break; default: throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . ' is not supported.'); @@ -98,7 +98,7 @@ class Doctrine_Transaction_Mysql extends Doctrine_Transaction { } /** * getTransactionIsolation - * + * * @return string returns the current session transaction isolation level */ public function getIsolation() { diff --git a/lib/Doctrine/Transaction/Oracle.php b/lib/Doctrine/Transaction/Oracle.php index 504312ef7..d433207f1 100644 --- a/lib/Doctrine/Transaction/Oracle.php +++ b/lib/Doctrine/Transaction/Oracle.php @@ -40,7 +40,7 @@ class Doctrine_Transaction_Oracle extends Doctrine_Transaction { */ protected function createSavePoint($savepoint) { $query = 'SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -63,7 +63,7 @@ class Doctrine_Transaction_Oracle extends Doctrine_Transaction { */ protected function rollbackSavePoint($savepoint) { $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -79,17 +79,17 @@ class Doctrine_Transaction_Oracle extends Doctrine_Transaction { * @return void */ public function setIsolation($isolation) { - switch($isolation) { - case 'READ UNCOMMITTED': - $isolation = 'READ COMMITTED'; + switch ($isolation) { + case 'READ UNCOMMITTED': + $isolation = 'READ COMMITTED'; break; - case 'READ COMMITTED': - case 'REPEATABLE READ': - case 'SERIALIZABLE': - $isolation = 'SERIALIZABLE'; + case 'READ COMMITTED': + case 'REPEATABLE READ': + case 'SERIALIZABLE': + $isolation = 'SERIALIZABLE'; break; - default: - throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . ' is not supported.'); + default: + throw new Doctrine_Transaction_Exception('Isolation level ' . $isolation . ' is not supported.'); } $query = 'ALTER SESSION ISOLATION LEVEL ' . $isolation; diff --git a/lib/Doctrine/Transaction/Pgsql.php b/lib/Doctrine/Transaction/Pgsql.php index 913d5a4e7..d683631f3 100644 --- a/lib/Doctrine/Transaction/Pgsql.php +++ b/lib/Doctrine/Transaction/Pgsql.php @@ -31,7 +31,7 @@ Doctrine::autoload('Doctrine_Transaction'); * @since 1.0 * @version $Revision$ */ -class Doctrine_Transaction_Pgsql extends Doctrine_Transaction { +class Doctrine_Transaction_Pgsql extends Doctrine_Transaction { /** * createSavepoint * creates a new savepoint @@ -41,7 +41,7 @@ class Doctrine_Transaction_Pgsql extends Doctrine_Transaction { */ protected function createSavePoint($savepoint) { $query = 'SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -53,7 +53,7 @@ class Doctrine_Transaction_Pgsql extends Doctrine_Transaction { */ protected function releaseSavePoint($savepoint) { $query = 'RELEASE SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -65,7 +65,7 @@ class Doctrine_Transaction_Pgsql extends Doctrine_Transaction { */ protected function rollbackSavePoint($savepoint) { $query = 'ROLLBACK TO SAVEPOINT '.$savepoint; - + return $this->conn->getDbh()->query($query); } /** @@ -86,8 +86,8 @@ class Doctrine_Transaction_Pgsql extends Doctrine_Transaction { case 'READ COMMITTED': case 'REPEATABLE READ': case 'SERIALIZABLE': - - break; + + break; default: throw new Doctrine_Transaction_Exception('Isolation level '.$isolation.' is not supported.'); } diff --git a/lib/Doctrine/Transaction/Sqlite.php b/lib/Doctrine/Transaction/Sqlite.php index 97bf76f42..9eb62499e 100644 --- a/lib/Doctrine/Transaction/Sqlite.php +++ b/lib/Doctrine/Transaction/Sqlite.php @@ -30,7 +30,7 @@ Doctrine::autoload('Doctrine_Transaction'); * @since 1.0 * @version $Revision$ */ -class Doctrine_Transaction_Sqlite extends Doctrine_Transaction { +class Doctrine_Transaction_Sqlite extends Doctrine_Transaction { /** * Set the transacton isolation level. * diff --git a/lib/Doctrine/Validator.php b/lib/Doctrine/Validator.php index 68a3ebe83..74cc57e29 100644 --- a/lib/Doctrine/Validator.php +++ b/lib/Doctrine/Validator.php @@ -1,273 +1,274 @@ -. - */ -/** - * Doctrine_Validator - * Doctrine_Validator performs validations in record properties - * - * @package Doctrine - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Validator { - /** - * @var array $validators an array of validator objects - */ - private static $validators = array(); - /** - * @var Doctrine_Null $null a Doctrine_Null object used for extremely fast - * null value testing - */ - private static $null; - /** - * initNullObject - * - * @param Doctrine_Null $null - * @return void - */ - public static function initNullObject(Doctrine_Null $null) { - self::$null = $null; - } - /** - * returns a validator object - * - * @param string $name - * @return Doctrine_Validator_Interface - */ - public static function getValidator($name) { - if( ! isset(self::$validators[$name])) { - $class = "Doctrine_Validator_".ucwords(strtolower($name)); - if(class_exists($class)) { - self::$validators[$name] = new $class; - } else { - throw new Doctrine_Exception("Validator named '$name' not availible."); - } - - } - return self::$validators[$name]; - } - /** - * validates a given record and saves possible errors - * in Doctrine_Validator::$stack - * - * @param Doctrine_Record $record - * @return void - */ - public function validateRecord(Doctrine_Record $record) { - $columns = $record->getTable()->getColumns(); - $component = $record->getTable()->getComponentName(); - - $errorStack = $record->getErrorStack(); - - - // if record is transient all fields will be validated - // if record is persistent only the modified fields will be validated - $data = ($record->exists()) ? $record->getModified() : $record->getData(); - - $err = array(); - foreach($data as $key => $value) { - if($value === self::$null) - $value = null; - elseif($value instanceof Doctrine_Record) - $value = $value->getIncremented(); - - $column = $columns[$key]; - - if($column[0] == "enum") { - $value = $record->getTable()->enumIndex($key, $value); - - if($value === false) { - $errorStack->add($key, 'enum'); - continue; - } - } - - if($record->getTable()->getAttribute(Doctrine::ATTR_AUTO_LENGTH_VLD)) { - if(!$this->validateLength($column, $key, $value)) { - $errorStack->add($key, 'length'); - continue; - } - } - - if( ! is_array($column[2])) - $e = explode("|",$column[2]); - else - $e = $column[2]; - - - foreach($e as $k => $arg) { - if(is_string($k)) { - $name = $k; - $args = $arg; - } else { - $args = explode(":",$arg); - $name = array_shift($args); - if( ! isset($args[0])) - $args[0] = ''; - } - - if(empty($name) || $name == 'primary' || - $name == 'protected' || - $name == 'autoincrement' || - $name == 'default') - continue; - - if(strtolower($name) == 'length') { - if(!$record->getTable()->getAttribute(Doctrine::ATTR_AUTO_LENGTH_VLD)) { - if(!$this->validateLength($column, $key, $value)) { - $errorStack->add($key, 'length'); - } - } - continue; - } - - if(strtolower($name) == 'type') { - if(!$record->getTable()->getAttribute(Doctrine::ATTR_AUTO_TYPE_VLD)) { - if( ! self::isValidType($value, $column[0])) { - $errorStack->add($key, 'type'); - } - } - continue; - } - - $validator = self::getValidator($name); - if( ! $validator->validate($record, $key, $value, $args)) { - - - $errorStack->add($key, $name); - - //$err[$key] = 'not valid'; - - // errors found quit validation looping for this column - //break; - } - } - - if($record->getTable()->getAttribute(Doctrine::ATTR_AUTO_TYPE_VLD)) { - if( ! self::isValidType($value, $column[0])) { - $errorStack->add($key, 'type'); - continue; - } - } - } - } - /** - * Enter description here... - * - */ - private function validateLength($column, $key, $value) { - if($column[0] == "array" || $column[0] == "object") - $length = strlen(serialize($value)); - else - $length = strlen($value); - - if($length > $column[1]) { - return false; - } - return true; - } - /** - * whether or not this validator has errors - * - * @return boolean - */ - public function hasErrors() { - return (count($this->stack) > 0); - } - /** - * converts a doctrine type to native php type - * - * @param $doctrineType - * @return string - */ - public static function phpType($doctrineType) { - switch($doctrineType) { - case 'enum': - return 'integer'; - case 'blob': - case 'clob': - case 'mbstring': - case 'timestamp': - case 'date': - case 'gzip': - return 'string'; - break; - default: - return $doctrineType; - } - } - /** - * returns whether or not the given variable is - * valid type - * - * @param mixed $var - * @param string $type - * @return boolean - */ - public static function isValidType($var, $type) { - if($type == 'boolean') - return true; - - $looseType = self::gettype($var); - $type = self::phpType($type); - - switch($looseType): - case 'float': - case 'double': - case 'integer': - if($type == 'string' || $type == 'float') - return true; - case 'string': - case 'array': - case 'object': - return ($type === $looseType); - break; - case 'NULL': - return true; - break; - endswitch; - } - /** - * returns the type of loosely typed variable - * - * @param mixed $var - * @return string - */ - public static function gettype($var) { - $type = gettype($var); - switch($type): - case 'string': - if(preg_match("/^[0-9]+$/",$var)) - return 'integer'; - elseif(is_numeric($var)) - return 'float'; - else - return $type; - break; - default: - return $type; - endswitch; - } -} - +. + */ +/** + * Doctrine_Validator + * Doctrine_Validator performs validations in record properties + * + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Validator { + /** + * @var array $validators an array of validator objects + */ + private static $validators = array(); + /** + * @var Doctrine_Null $null a Doctrine_Null object used for extremely fast + * null value testing + */ + private static $null; + /** + * initNullObject + * + * @param Doctrine_Null $null + * @return void + */ + public static function initNullObject(Doctrine_Null $null) { + self::$null = $null; + } + /** + * returns a validator object + * + * @param string $name + * @return Doctrine_Validator_Interface + */ + public static function getValidator($name) { + if ( ! isset(self::$validators[$name])) { + $class = "Doctrine_Validator_".ucwords(strtolower($name)); + if (class_exists($class)) { + self::$validators[$name] = new $class; + } else { + throw new Doctrine_Exception("Validator named '$name' not availible."); + } + + } + return self::$validators[$name]; + } + /** + * validates a given record and saves possible errors + * in Doctrine_Validator::$stack + * + * @param Doctrine_Record $record + * @return void + */ + public function validateRecord(Doctrine_Record $record) { + $columns = $record->getTable()->getColumns(); + $component = $record->getTable()->getComponentName(); + + $errorStack = $record->getErrorStack(); + + // if record is transient all fields will be validated + // if record is persistent only the modified fields will be validated + $data = ($record->exists()) ? $record->getModified() : $record->getData(); + + $err = array(); + foreach ($data as $key => $value) { + if ($value === self::$null) + $value = null; + elseif ($value instanceof Doctrine_Record) + $value = $value->getIncremented(); + + $column = $columns[$key]; + + if ($column[0] == "enum") { + $value = $record->getTable()->enumIndex($key, $value); + + if ($value === false) { + $errorStack->add($key, 'enum'); + continue; + } + } + + if ($record->getTable()->getAttribute(Doctrine::ATTR_AUTO_LENGTH_VLD)) { + if (!$this->validateLength($column, $key, $value)) { + $errorStack->add($key, 'length'); + continue; + } + } + + if ( ! is_array($column[2])) { + $e = explode("|",$column[2]); + } else { + $e = $column[2]; + } + + foreach ($e as $k => $arg) { + if (is_string($k)) { + $name = $k; + $args = $arg; + } else { + $args = explode(":",$arg); + $name = array_shift($args); + if ( ! isset($args[0])) { + $args[0] = ''; + } + } + + if (empty($name) + || $name == 'primary' + || $name == 'protected' + || $name == 'autoincrement' + || $name == 'default' + ) { + continue; + } + if (strtolower($name) == 'length') { + if (!$record->getTable()->getAttribute(Doctrine::ATTR_AUTO_LENGTH_VLD)) { + if (!$this->validateLength($column, $key, $value)) { + $errorStack->add($key, 'length'); + } + } + continue; + } + + if (strtolower($name) == 'type') { + if (!$record->getTable()->getAttribute(Doctrine::ATTR_AUTO_TYPE_VLD)) { + if ( ! self::isValidType($value, $column[0])) { + $errorStack->add($key, 'type'); + } + } + continue; + } + + $validator = self::getValidator($name); + if ( ! $validator->validate($record, $key, $value, $args)) { + $errorStack->add($key, $name); + + //$err[$key] = 'not valid'; + + // errors found quit validation looping for this column + //break; + } + } + + if ($record->getTable()->getAttribute(Doctrine::ATTR_AUTO_TYPE_VLD)) { + if ( ! self::isValidType($value, $column[0])) { + $errorStack->add($key, 'type'); + continue; + } + } + } + } + /** + * Enter description here... + * + */ + private function validateLength($column, $key, $value) { + if ($column[0] == "array" || $column[0] == "object") { + $length = strlen(serialize($value)); + } else { + $length = strlen($value); + } + + if ($length > $column[1]) { + return false; + } + return true; + } + /** + * whether or not this validator has errors + * + * @return boolean + */ + public function hasErrors() { + return (count($this->stack) > 0); + } + /** + * converts a doctrine type to native php type + * + * @param $doctrineType + * @return string + */ + public static function phpType($doctrineType) { + switch ($doctrineType) { + case 'enum': + return 'integer'; + case 'blob': + case 'clob': + case 'mbstring': + case 'timestamp': + case 'date': + case 'gzip': + return 'string'; + break; + default: + return $doctrineType; + } + } + /** + * returns whether or not the given variable is + * valid type + * + * @param mixed $var + * @param string $type + * @return boolean + */ + public static function isValidType($var, $type) { + if ($type == 'boolean') + return true; + + $looseType = self::gettype($var); + $type = self::phpType($type); + + switch ($looseType) { + case 'float': + case 'double': + case 'integer': + if ($type == 'string' || $type == 'float') + return true; + case 'string': + case 'array': + case 'object': + return ($type === $looseType); + break; + case 'NULL': + return true; + break; + }; + } + /** + * returns the type of loosely typed variable + * + * @param mixed $var + * @return string + */ + public static function gettype($var) { + $type = gettype($var); + switch ($type) { + case 'string': + if (preg_match("/^[0-9]+$/",$var)) { + return 'integer'; + } elseif (is_numeric($var)) { + return 'float'; + } else { + return $type; + } + break; + default: + return $type; + }; + } +} diff --git a/lib/Doctrine/Validator/Country.php b/lib/Doctrine/Validator/Country.php index d55e54eb7..c17ae4bb9 100644 --- a/lib/Doctrine/Validator/Country.php +++ b/lib/Doctrine/Validator/Country.php @@ -32,255 +32,255 @@ */ class Doctrine_Validator_Country { 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"); - /** - * @return array - */ - public static function getCountries() { + "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"); + /** + * @return array + */ + public static function getCountries() { return self::$countries; - } + } /** * @param Doctrine_Record $record * @param string $key @@ -291,7 +291,6 @@ class Doctrine_Validator_Country { public function validate(Doctrine_Record $record, $key, $value, $args) { $value = strtolower($value); return isset(self::$countries[$value]); - } + } } - diff --git a/lib/Doctrine/Validator/Creditcard.php b/lib/Doctrine/Validator/Creditcard.php index e46e5e13c..77ec54127 100644 --- a/lib/Doctrine/Validator/Creditcard.php +++ b/lib/Doctrine/Validator/Creditcard.php @@ -45,4 +45,3 @@ class Doctrine_Validator_Creditcard { } } - diff --git a/lib/Doctrine/Validator/Date.php b/lib/Doctrine/Validator/Date.php index 1fe43b140..1160a7ab2 100644 --- a/lib/Doctrine/Validator/Date.php +++ b/lib/Doctrine/Validator/Date.php @@ -39,14 +39,13 @@ class Doctrine_Validator_Date { * @return boolean */ public function validate(Doctrine_Record $record, $key, $value, $args) { - if(empty($value)) + if (empty($value)) { return true; - + } $e = explode("-", $value); - if(count($e) !== 3) + if (count($e) !== 3) { return false; - + } return checkdate($e[1], $e[0], $e[2]); } } - diff --git a/lib/Doctrine/Validator/Email.php b/lib/Doctrine/Validator/Email.php index 6c3e5c0a5..a9e250834 100644 --- a/lib/Doctrine/Validator/Email.php +++ b/lib/Doctrine/Validator/Email.php @@ -1,78 +1,79 @@ -. - */ - -/** - * Doctrine_Validator_Email - * - * @package Doctrine - * @category Object Relational Mapping - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Validator_Email { - - /** - * @link http://iamcal.com/publish/articles/php/parsing_email/pdf/ - * @param Doctrine_Record $record - * @param string $key - * @param mixed $value - * @param string $args - * @return boolean - */ - public function validate(Doctrine_Record $record, $key, $value, $args) { - if(empty($value)) - return true; - - if(isset($args[0])) { - $parts = explode("@", $value); - if(isset($parts[1]) && function_exists("checkdnsrr")) { - if( ! checkdnsrr($parts[1], "MX")) - return false; - } - } - - $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; - $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; - $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; - $quoted_pair = '\\x5c[\\x00-\\x7f]'; - $domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d"; - $quoted_string = "\\x22($qtext|$quoted_pair)*\\x22"; - $domain_ref = $atom; - $sub_domain = "($domain_ref|$domain_literal)"; - $word = "($atom|$quoted_string)"; - $domain = "$sub_domain(\\x2e$sub_domain)+"; - /* - following psudocode to allow strict checking - ask pookey about this if you're puzzled - - if ($this->getValidationOption('strict_checking') == true) - $domain = "$sub_domain(\\x2e$sub_domain)*"; - */ - $local_part = "$word(\\x2e$word)*"; - $addr_spec = "$local_part\\x40$domain"; - - return (bool)preg_match("!^$addr_spec$!", $value); - } - -} - +. + */ + +/** + * Doctrine_Validator_Email + * + * @package Doctrine + * @category Object Relational Mapping + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Validator_Email { + + /** + * @link http://iamcal.com/publish/articles/php/parsing_email/pdf/ + * @param Doctrine_Record $record + * @param string $key + * @param mixed $value + * @param string $args + * @return boolean + */ + public function validate(Doctrine_Record $record, $key, $value, $args) { + if (empty($value)) { + return true; + } + if (isset($args[0])) { + $parts = explode("@", $value); + if (isset($parts[1]) && function_exists("checkdnsrr")) { + if ( ! checkdnsrr($parts[1], "MX")) { + return false; + } + } + } + + $qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'; + $dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'; + $atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'; + $quoted_pair = '\\x5c[\\x00-\\x7f]'; + $domain_literal = "\\x5b($dtext|$quoted_pair)*\\x5d"; + $quoted_string = "\\x22($qtext|$quoted_pair)*\\x22"; + $domain_ref = $atom; + $sub_domain = "($domain_ref|$domain_literal)"; + $word = "($atom|$quoted_string)"; + $domain = "$sub_domain(\\x2e$sub_domain)+"; + /* + following psudocode to allow strict checking - ask pookey about this if you're puzzled + + if ($this->getValidationOption('strict_checking') == true) { + $domain = "$sub_domain(\\x2e$sub_domain)*"; + } + */ + $local_part = "$word(\\x2e$word)*"; + $addr_spec = "$local_part\\x40$domain"; + + return (bool)preg_match("!^$addr_spec$!", $value); + } + +} diff --git a/lib/Doctrine/Validator/Enum.php b/lib/Doctrine/Validator/Enum.php index 909f2d66d..d7ed4a45c 100644 --- a/lib/Doctrine/Validator/Enum.php +++ b/lib/Doctrine/Validator/Enum.php @@ -42,13 +42,12 @@ class Doctrine_Validator_Enum { $max = substr_count($args, '-'); $int = (int) $value; - if($int != $value) + if ($int != $value) { return false; - - if($int < 0 || $int > $max) + } + if ($int < 0 || $int > $max) { return false; - + } return true; } } - diff --git a/lib/Doctrine/Validator/ErrorStack.php b/lib/Doctrine/Validator/ErrorStack.php index db69cb60a..b268e2693 100644 --- a/lib/Doctrine/Validator/ErrorStack.php +++ b/lib/Doctrine/Validator/ErrorStack.php @@ -1,128 +1,126 @@ -. - */ -/** - * Doctrine_Validator_ErrorStack - * - * @author Konsta Vesterinen - * @author Roman Borschel - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ -class Doctrine_Validator_ErrorStack extends Doctrine_Access implements Countable, IteratorAggregate { - - /** - * The errors of the error stack. - * - * @var array - */ - protected $errors = array(); - - /** - * Constructor - * - */ - public function __construct() - {} - - /** - * Adds an error to the stack. - * - * @param string $invalidFieldName - * @param string $errorType - */ - public function add($invalidFieldName, $errorCode = 'general') { - $this->errors[$invalidFieldName][] = $errorCode; - } - - /** - * Removes all existing errors for the specified field from the stack. - * - * @param string $fieldName - */ - public function remove($fieldName) { - if (isset($this->errors[$fieldName])) { - unset($this->errors[$fieldName]); - } - } - - /** - * Enter description here... - * - * @param unknown_type $name - * @return unknown - */ - public function get($fieldName) { - return isset($this->errors[$fieldName]) ? $this->errors[$fieldName] : null; - } - - /** - * Enter description here... - * - * @param unknown_type $name - */ - public function set($fieldName, $errorCode) { - $this->add($fieldName, $errorCode); - } - - /** - * Enter description here... - * - * @return unknown - */ - public function contains($fieldName) { - return array_key_exists($fieldName, $this->errors); - } - - /** - * Removes all errors from the stack. - */ - public function clear() { - $this->errors = array(); - } - - - /** IteratorAggregate implementation */ - - /** - * Enter description here... - * - * @return unknown - */ - public function getIterator() { - return new ArrayIterator($this->errors); - } - - - /** Countable implementation */ - - /** - * Enter description here... - * - * @return unknown - */ - public function count() { - return count($this->errors); - } -} +. + */ +/** + * Doctrine_Validator_ErrorStack + * + * @author Konsta Vesterinen + * @author Roman Borschel + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ +class Doctrine_Validator_ErrorStack extends Doctrine_Access implements Countable, IteratorAggregate { + + /** + * The errors of the error stack. + * + * @var array + */ + protected $errors = array(); + + /** + * Constructor + * + */ + public function __construct() + {} + + /** + * Adds an error to the stack. + * + * @param string $invalidFieldName + * @param string $errorType + */ + public function add($invalidFieldName, $errorCode = 'general') { + $this->errors[$invalidFieldName][] = $errorCode; + } + + /** + * Removes all existing errors for the specified field from the stack. + * + * @param string $fieldName + */ + public function remove($fieldName) { + if (isset($this->errors[$fieldName])) { + unset($this->errors[$fieldName]); + } + } + + /** + * Enter description here... + * + * @param unknown_type $name + * @return unknown + */ + public function get($fieldName) { + return isset($this->errors[$fieldName]) ? $this->errors[$fieldName] : null; + } + + /** + * Enter description here... + * + * @param unknown_type $name + */ + public function set($fieldName, $errorCode) { + $this->add($fieldName, $errorCode); + } + + /** + * Enter description here... + * + * @return unknown + */ + public function contains($fieldName) { + return array_key_exists($fieldName, $this->errors); + } + + /** + * Removes all errors from the stack. + */ + public function clear() { + $this->errors = array(); + } + + /** IteratorAggregate implementation */ + + /** + * Enter description here... + * + * @return unknown + */ + public function getIterator() { + return new ArrayIterator($this->errors); + } + + /** Countable implementation */ + + /** + * Enter description here... + * + * @return unknown + */ + public function count() { + return count($this->errors); + } +} diff --git a/lib/Doctrine/Validator/Exception.php b/lib/Doctrine/Validator/Exception.php index fed3cb246..9cd7b8787 100644 --- a/lib/Doctrine/Validator/Exception.php +++ b/lib/Doctrine/Validator/Exception.php @@ -22,14 +22,14 @@ Doctrine::autoload('Doctrine_Exception'); /** * Doctrine_Validator_Exception * - * @author Konsta Vesterinen - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @package Doctrine - * @category Object Relational Mapping - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - */ + * @author Konsta Vesterinen + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @package Doctrine + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + */ class Doctrine_Validator_Exception extends Doctrine_Exception implements Countable, IteratorAggregate { /** * @var array $invalid @@ -41,7 +41,7 @@ class Doctrine_Validator_Exception extends Doctrine_Exception implements Countab public function __construct(array $invalid) { $this->invalid = $invalid; } - + public function getInvalidRecords() { return $this->invalid; } @@ -49,7 +49,7 @@ class Doctrine_Validator_Exception extends Doctrine_Exception implements Countab public function getIterator() { return new ArrayIterator($this->invalid); } - + public function count() { return count($this->invalid); } @@ -63,4 +63,3 @@ class Doctrine_Validator_Exception extends Doctrine_Exception implements Countab return parent::__toString(); } } - diff --git a/lib/Doctrine/Validator/Htmlcolor.php b/lib/Doctrine/Validator/Htmlcolor.php index acd4969a4..1cd7c3de0 100644 --- a/lib/Doctrine/Validator/Htmlcolor.php +++ b/lib/Doctrine/Validator/Htmlcolor.php @@ -39,10 +39,9 @@ class Doctrine_Validator_HtmlColor { * @return boolean */ public function validate(Doctrine_Record $record, $key, $value, $args) { - if( ! preg_match("/^#{0,1}[0-9]{6}$/",$color)) { + if ( ! preg_match("/^#{0,1}[0-9]{6}$/",$color)) { return false; } return true; } } - diff --git a/lib/Doctrine/Validator/Interface.class.php b/lib/Doctrine/Validator/Interface.class.php index 50470c9f7..ec5521561 100644 --- a/lib/Doctrine/Validator/Interface.class.php +++ b/lib/Doctrine/Validator/Interface.class.php @@ -2,4 +2,3 @@ interface Doctrine_Validator_Interface { public function validate(); } - diff --git a/lib/Doctrine/Validator/Ip.php b/lib/Doctrine/Validator/Ip.php index 46b5f7f30..694d65ec6 100644 --- a/lib/Doctrine/Validator/Ip.php +++ b/lib/Doctrine/Validator/Ip.php @@ -42,4 +42,3 @@ class Doctrine_Validator_Ip { return (bool) ip2long(str_replace("\0", '', $value)); } } - diff --git a/lib/Doctrine/Validator/Nospace.php b/lib/Doctrine/Validator/Nospace.php index 1980a8ab4..60d03df56 100644 --- a/lib/Doctrine/Validator/Nospace.php +++ b/lib/Doctrine/Validator/Nospace.php @@ -42,4 +42,3 @@ class Doctrine_Validator_Nospace { return ($value === null || ! preg_match('/\s\t\r\n/',$value)); } } - diff --git a/lib/Doctrine/Validator/Notblank.php b/lib/Doctrine/Validator/Notblank.php index d9cddf8c6..daebd5781 100644 --- a/lib/Doctrine/Validator/Notblank.php +++ b/lib/Doctrine/Validator/Notblank.php @@ -39,7 +39,6 @@ class Doctrine_Validator_Notblank { * @return boolean */ public function validate(Doctrine_Record $record, $key, $value, $args) { - return (trim($value) != ""); + return (trim($value) != ""); } } - diff --git a/lib/Doctrine/Validator/Notnull.php b/lib/Doctrine/Validator/Notnull.php index 2c31e3284..62f2a0f2f 100644 --- a/lib/Doctrine/Validator/Notnull.php +++ b/lib/Doctrine/Validator/Notnull.php @@ -38,10 +38,9 @@ class Doctrine_Validator_Notnull { * @return boolean */ public function validate(Doctrine_Record $record, $key, $value) { - if ($value === null || $value === '') + if ($value === null || $value === '') { return false; - + } return true; } } - diff --git a/lib/Doctrine/Validator/Protected.php b/lib/Doctrine/Validator/Protected.php index ab4fa67a0..6fd199e66 100644 --- a/lib/Doctrine/Validator/Protected.php +++ b/lib/Doctrine/Validator/Protected.php @@ -1,2 +1 @@ $args[1]) + } + if (isset($args[1]) && $value > $args[1]) { return false; - + } return true; } } - diff --git a/lib/Doctrine/Validator/Regexp.php b/lib/Doctrine/Validator/Regexp.php index fff4d86d5..8464dfc68 100644 --- a/lib/Doctrine/Validator/Regexp.php +++ b/lib/Doctrine/Validator/Regexp.php @@ -1,56 +1,57 @@ -. - */ - -/** - * Doctrine_Validator_Regexp - * - * @package Doctrine - * @category Object Relational Mapping - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Validator_Regexp { - /** - * @param Doctrine_Record $record - * @param string $key - * @param mixed $value - * @param string $args - * @return boolean - */ - public function validate(Doctrine_Record $record, $key, $value, $args) { - if(is_array($args)) { - foreach($args as $regexp) { - if( ! preg_match($args, $value)) - return false; - } - return true; - } else { - if(preg_match($args, $value)) - return true; - } - - return false; - } -} - +. + */ + +/** + * Doctrine_Validator_Regexp + * + * @package Doctrine + * @category Object Relational Mapping + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Validator_Regexp { + /** + * @param Doctrine_Record $record + * @param string $key + * @param mixed $value + * @param string $args + * @return boolean + */ + public function validate(Doctrine_Record $record, $key, $value, $args) { + if (is_array($args)) { + foreach ($args as $regexp) { + if ( ! preg_match($args, $value)) { + return false; + } + } + return true; + } else { + if (preg_match($args, $value)) { + return true; + } + } + + return false; + } +} diff --git a/lib/Doctrine/Validator/Unique.php b/lib/Doctrine/Validator/Unique.php index d7c2ad407..967b3c578 100644 --- a/lib/Doctrine/Validator/Unique.php +++ b/lib/Doctrine/Validator/Unique.php @@ -47,4 +47,3 @@ class Doctrine_Validator_Unique { return ( ! is_array($stmt->fetch())); } } - diff --git a/lib/Doctrine/Validator/Usstate.php b/lib/Doctrine/Validator/Usstate.php index fd417c7e2..48175ad87 100644 --- a/lib/Doctrine/Validator/Usstate.php +++ b/lib/Doctrine/Validator/Usstate.php @@ -1,103 +1,102 @@ -. - */ - -/** - * Doctrine_Validator_Usstate - * - * @package Doctrine - * @category Object Relational Mapping - * @license http://www.opensource.org/licenses/lgpl-license.php LGPL - * @link www.phpdoctrine.com - * @since 1.0 - * @version $Revision$ - * @author Konsta Vesterinen - */ -class Doctrine_Validator_Usstate { - 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 - ); - public function getStates() { - return self::$states; - } - /** - * @param Doctrine_Record $record - * @param string $key - * @param mixed $value - * @param string $args - * @return boolean - */ - public function validate(Doctrine_Record $record, $key, $value, $args) { - return isset(self::$states[$value]); - } -} - +. + */ + +/** + * Doctrine_Validator_Usstate + * + * @package Doctrine + * @category Object Relational Mapping + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Validator_Usstate { + 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 + ); + public function getStates() { + return self::$states; + } + /** + * @param Doctrine_Record $record + * @param string $key + * @param mixed $value + * @param string $args + * @return boolean + */ + public function validate(Doctrine_Record $record, $key, $value, $args) { + return isset(self::$states[$value]); + } +} diff --git a/lib/Doctrine/ValueHolder.php b/lib/Doctrine/ValueHolder.php index 7c2cf04fe..5051212e0 100644 --- a/lib/Doctrine/ValueHolder.php +++ b/lib/Doctrine/ValueHolder.php @@ -1,5 +1,5 @@ - */ + * @package Doctrine + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @category Object Relational Mapping + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ class Doctrine_ValueHolder extends Doctrine_Access implements Countable { - + public $data = array(); private $table; @@ -42,15 +42,15 @@ class Doctrine_ValueHolder extends Doctrine_Access implements Countable { public function __construct(Doctrine_Table $table) { $this->table = $table; } - + public function set($name, $value) { $this->data[$name] = $value; } public function get($name) { - if( ! isset($this->data[$name])) + if ( ! isset($this->data[$name])) { throw new Doctrine_Exception("Unknown property $name."); - + } return $this->data[$name]; } public function count() { @@ -65,4 +65,3 @@ class Doctrine_ValueHolder extends Doctrine_Access implements Countable { throw new Doctrine_Exception("Method 'save' not availible on Doctrine_ValueHolder."); } } - diff --git a/lib/Doctrine/View.php b/lib/Doctrine/View.php index d0160660b..ad65e5eb4 100644 --- a/lib/Doctrine/View.php +++ b/lib/Doctrine/View.php @@ -45,7 +45,6 @@ class Doctrine_View { */ const SELECT = 'SELECT * FROM %s'; - /** * @var string $name the name of the view */ @@ -146,4 +145,3 @@ class Doctrine_View { return sprintf(self::SELECT, $this->name); } } - diff --git a/lib/Doctrine/View/Exception.php b/lib/Doctrine/View/Exception.php index 187fcdf68..67f1a6262 100644 --- a/lib/Doctrine/View/Exception.php +++ b/lib/Doctrine/View/Exception.php @@ -30,4 +30,4 @@ Doctrine::autoload('Doctrine_View_Exception'); * @since 1.0 * @version $Revision$ */ -class Doctrine_View_Exception extends Doctrine_Exception { } +class Doctrine_View_Exception extends Doctrine_Exception { }